forked from angular/angular
/
styling.ts
592 lines (536 loc) · 23.6 KB
/
styling.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/**
* @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 {SafeValue} from '../../sanitization/bypass';
import {StyleSanitizeFn} from '../../sanitization/style_sanitizer';
import {throwErrorIfNoChangesMode} from '../errors';
import {setInputsForProperty} from '../instructions/shared';
import {AttributeMarker, TAttributes, TNode, TNodeFlags, TNodeType} from '../interfaces/node';
import {RElement} from '../interfaces/renderer';
import {StylingMapArray, StylingMapArrayIndex, TStylingConfig, TStylingContext} from '../interfaces/styling';
import {isDirectiveHost} from '../interfaces/type_checks';
import {BINDING_INDEX, LView, RENDERER} from '../interfaces/view';
import {getActiveDirectiveId, getCheckNoChangesMode, getCurrentStyleSanitizer, getLView, getSelectedIndex, resetCurrentStyleSanitizer, setCurrentStyleSanitizer, setElementExitFn} from '../state';
import {applyStylingMapDirectly, applyStylingValueDirectly, flushStyling, setClass, setStyle, updateClassViaContext, updateStyleViaContext} from '../styling/bindings';
import {activateStylingMapFeature} from '../styling/map_based_bindings';
import {attachStylingDebugObject} from '../styling/styling_debug';
import {NO_CHANGE} from '../tokens';
import {renderStringify} from '../util/misc_utils';
import {addItemToStylingMap, allocStylingMapArray, allocTStylingContext, allowDirectStyling, concatString, forceClassesAsString, forceStylesAsString, getInitialStylingValue, getStylingMapArray, getValue, hasClassInput, hasStyleInput, hasValueChanged, isContextLocked, isHostStylingActive, isStylingContext, normalizeIntoStylingMap, patchConfig, selectClassBasedInputName, setValue, stylingMapToString} from '../util/styling_utils';
import {getNativeByTNode, getTNode} from '../util/view_utils';
/**
* --------
*
* This file contains the core logic for how styling instructions are processed in Angular.
*
* To learn more about the algorithm see `TStylingContext`.
*
* --------
*/
/**
* Sets the current style sanitizer function which will then be used
* within all follow-up prop and map-based style binding instructions
* for the given element.
*
* Note that once styling has been applied to the element (i.e. once
* `advance(n)` is executed or the hostBindings/template function exits)
* then the active `sanitizerFn` will be set to `null`. This means that
* once styling is applied to another element then a another call to
* `styleSanitizer` will need to be made.
*
* @param sanitizerFn The sanitization function that will be used to
* process style prop/value entries.
*
* @codeGenApi
*/
export function ɵɵstyleSanitizer(sanitizer: StyleSanitizeFn | null): void {
setCurrentStyleSanitizer(sanitizer);
}
/**
* Update a style binding on an element with the provided value.
*
* If the style value is falsy then it will be removed from the element
* (or assigned a different value depending if there are any styles placed
* on the element with `styleMap` or any static styles that are
* present from when the element was created with `styling`).
*
* Note that the styling element is updated as part of `stylingApply`.
*
* @param prop A valid CSS property.
* @param value New value to write (`null` or an empty string to remove).
* @param suffix Optional suffix. Used with scalar values to add unit such as `px`.
* Note that when a suffix is provided then the underlying sanitizer will
* be ignored.
*
* Note that this will apply the provided style value to the host element if this function is called
* within a host binding function.
*
* @codeGenApi
*/
export function ɵɵstyleProp(
prop: string, value: string | number | SafeValue | null, suffix?: string | null): void {
stylePropInternal(getSelectedIndex(), prop, value, suffix);
}
/**
* Internal function for applying a single style to an element.
*
* The reason why this function has been separated from `ɵɵstyleProp` is because
* it is also called from `ɵɵstylePropInterpolate`.
*/
export function stylePropInternal(
elementIndex: number, prop: string, value: string | number | SafeValue | null,
suffix?: string | null | undefined): void {
const lView = getLView();
// if a value is interpolated then it may render a `NO_CHANGE` value.
// in this case we do not need to do anything, but the binding index
// still needs to be incremented because all styling binding values
// are stored inside of the lView.
const bindingIndex = getAndIncrementBindingIndex(lView, false);
const updated =
stylingProp(elementIndex, bindingIndex, prop, resolveStylePropValue(value, suffix), false);
if (ngDevMode) {
ngDevMode.styleProp++;
if (updated) {
ngDevMode.stylePropCacheMiss++;
}
}
}
/**
* Update a class binding on an element with the provided value.
*
* This instruction is meant to handle the `[class.foo]="exp"` case and,
* therefore, the class binding itself must already be allocated using
* `styling` within the creation block.
*
* @param prop A valid CSS class (only one).
* @param value A true/false value which will turn the class on or off.
*
* Note that this will apply the provided class value to the host element if this function
* is called within a host binding function.
*
* @codeGenApi
*/
export function ɵɵclassProp(className: string, value: boolean | null): void {
const lView = getLView();
// if a value is interpolated then it may render a `NO_CHANGE` value.
// in this case we do not need to do anything, but the binding index
// still needs to be incremented because all styling binding values
// are stored inside of the lView.
const bindingIndex = getAndIncrementBindingIndex(lView, false);
const updated = stylingProp(getSelectedIndex(), bindingIndex, className, value, true);
if (ngDevMode) {
ngDevMode.classProp++;
if (updated) {
ngDevMode.classPropCacheMiss++;
}
}
}
/**
* Shared function used to update a prop-based styling binding for an element.
*
* Depending on the state of the `tNode.styles` styles context, the style/prop
* value may be applied directly to the element instead of being processed
* through the context. The reason why this occurs is for performance and fully
* depends on the state of the context (i.e. whether or not there are duplicate
* bindings or whether or not there are map-based bindings and property bindings
* present together).
*/
function stylingProp(
elementIndex: number, bindingIndex: number, prop: string,
value: boolean | number | SafeValue | string | null | undefined | NO_CHANGE,
isClassBased: boolean): boolean {
let updated = false;
const lView = getLView();
const tNode = getTNode(elementIndex, lView);
const native = getNativeByTNode(tNode, lView) as RElement;
const hostBindingsMode = isHostStyling();
const context = isClassBased ? getClassesContext(tNode) : getStylesContext(tNode);
const sanitizer = isClassBased ? null : getCurrentStyleSanitizer();
// we check for this in the instruction code so that the context can be notified
// about prop or map bindings so that the direct apply check can decide earlier
// if it allows for context resolution to be bypassed.
if (!isContextLocked(context, hostBindingsMode)) {
patchConfig(context, TStylingConfig.HasPropBindings);
}
// [style.prop] and [class.name] bindings do not use `bind()` and will
// therefore manage accessing and updating the new value in the lView directly.
// For this reason, the checkNoChanges situation must also be handled here
// as well.
if (ngDevMode && getCheckNoChangesMode()) {
const oldValue = getValue(lView, bindingIndex);
if (hasValueChanged(oldValue, value)) {
throwErrorIfNoChangesMode(false, oldValue, value);
}
}
// Direct Apply Case: bypass context resolution and apply the
// style/class value directly to the element
if (allowDirectStyling(context, hostBindingsMode)) {
const sanitizerToUse = isClassBased ? null : sanitizer;
const renderer = getRenderer(tNode, lView);
updated = applyStylingValueDirectly(
renderer, context, native, lView, bindingIndex, prop, value, isClassBased, sanitizerToUse);
if (sanitizerToUse) {
// it's important we remove the current style sanitizer once the
// element exits, otherwise it will be used by the next styling
// instructions for the next element.
setElementExitFn(stylingApply);
}
} else {
// Context Resolution (or first update) Case: save the value
// and defer to the context to flush and apply the style/class binding
// value to the element.
const directiveIndex = getActiveDirectiveId();
if (isClassBased) {
updated = updateClassViaContext(
context, lView, native, directiveIndex, prop, bindingIndex,
value as string | boolean | null);
} else {
updated = updateStyleViaContext(
context, lView, native, directiveIndex, prop, bindingIndex,
value as string | SafeValue | null, sanitizer);
}
setElementExitFn(stylingApply);
}
return updated;
}
/**
* Update style bindings using an object literal on an element.
*
* This instruction is meant to apply styling via the `[style]="exp"` template bindings.
* When styles are applied to the element they will then be updated with respect to
* any styles/classes set via `styleProp`. If any styles are set to falsy
* then they will be removed from the element.
*
* Note that the styling instruction will not be applied until `stylingApply` is called.
*
* @param styles A key/value style map of the styles that will be applied to the given element.
* Any missing styles (that have already been applied to the element beforehand) will be
* removed (unset) from the element's styling.
*
* Note that this will apply the provided styleMap value to the host element if this function
* is called within a host binding.
*
* @codeGenApi
*/
export function ɵɵstyleMap(styles: {[styleName: string]: any} | NO_CHANGE | null): void {
const index = getSelectedIndex();
const lView = getLView();
const tNode = getTNode(index, lView);
const context = getStylesContext(tNode);
const hasDirectiveInput = hasStyleInput(tNode);
// if a value is interpolated then it may render a `NO_CHANGE` value.
// in this case we do not need to do anything, but the binding index
// still needs to be incremented because all styling binding values
// are stored inside of the lView.
const bindingIndex = getAndIncrementBindingIndex(lView, true);
// inputs are only evaluated from a template binding into a directive, therefore,
// there should not be a situation where a directive host bindings function
// evaluates the inputs (this should only happen in the template function)
if (!isHostStyling() && hasDirectiveInput && styles !== NO_CHANGE) {
updateDirectiveInputValue(context, lView, tNode, bindingIndex, styles, false);
styles = NO_CHANGE;
}
stylingMap(context, tNode, lView, bindingIndex, styles, false, hasDirectiveInput);
}
/**
* Update class bindings using an object literal or class-string on an element.
*
* This instruction is meant to apply styling via the `[class]="exp"` template bindings.
* When classes are applied to the element they will then be updated with
* respect to any styles/classes set via `classProp`. If any
* classes are set to falsy then they will be removed from the element.
*
* Note that the styling instruction will not be applied until `stylingApply` is called.
* Note that this will the provided classMap value to the host element if this function is called
* within a host binding.
*
* @param classes A key/value map or string of CSS classes that will be added to the
* given element. Any missing classes (that have already been applied to the element
* beforehand) will be removed (unset) from the element's list of CSS classes.
*
* @codeGenApi
*/
export function ɵɵclassMap(classes: {[className: string]: any} | NO_CHANGE | string | null): void {
classMapInternal(getSelectedIndex(), classes);
}
/**
* Internal function for applying a class string or key/value map of classes to an element.
*
* The reason why this function has been separated from `ɵɵclassMap` is because
* it is also called from `ɵɵclassMapInterpolate`.
*/
export function classMapInternal(
elementIndex: number, classes: {[className: string]: any} | NO_CHANGE | string | null): void {
const lView = getLView();
const tNode = getTNode(elementIndex, lView);
const context = getClassesContext(tNode);
const hasDirectiveInput = hasClassInput(tNode);
// if a value is interpolated then it may render a `NO_CHANGE` value.
// in this case we do not need to do anything, but the binding index
// still needs to be incremented because all styling binding values
// are stored inside of the lView.
const bindingIndex = getAndIncrementBindingIndex(lView, true);
// inputs are only evaluated from a template binding into a directive, therefore,
// there should not be a situation where a directive host bindings function
// evaluates the inputs (this should only happen in the template function)
if (!isHostStyling() && hasDirectiveInput && classes !== NO_CHANGE) {
updateDirectiveInputValue(context, lView, tNode, bindingIndex, classes, true);
classes = NO_CHANGE;
}
stylingMap(context, tNode, lView, bindingIndex, classes, true, hasDirectiveInput);
}
/**
* Shared function used to update a map-based styling binding for an element.
*
* When this function is called it will activate support for `[style]` and
* `[class]` bindings in Angular.
*/
function stylingMap(
context: TStylingContext, tNode: TNode, lView: LView, bindingIndex: number,
value: {[key: string]: any} | string | null, isClassBased: boolean,
hasDirectiveInput: boolean): void {
const directiveIndex = getActiveDirectiveId();
const native = getNativeByTNode(tNode, lView) as RElement;
const oldValue = getValue(lView, bindingIndex);
const hostBindingsMode = isHostStyling();
const sanitizer = getCurrentStyleSanitizer();
const valueHasChanged = hasValueChanged(oldValue, value);
// [style] and [class] bindings do not use `bind()` and will therefore
// manage accessing and updating the new value in the lView directly.
// For this reason, the checkNoChanges situation must also be handled here
// as well.
if (ngDevMode && valueHasChanged && getCheckNoChangesMode()) {
throwErrorIfNoChangesMode(false, oldValue, value);
}
// we check for this in the instruction code so that the context can be notified
// about prop or map bindings so that the direct apply check can decide earlier
// if it allows for context resolution to be bypassed.
if (!isContextLocked(context, hostBindingsMode)) {
patchConfig(context, TStylingConfig.HasMapBindings);
}
// Direct Apply Case: bypass context resolution and apply the
// style/class map values directly to the element
if (allowDirectStyling(context, hostBindingsMode)) {
const sanitizerToUse = isClassBased ? null : sanitizer;
const renderer = getRenderer(tNode, lView);
applyStylingMapDirectly(
renderer, context, native, lView, bindingIndex, value, isClassBased, sanitizerToUse,
valueHasChanged, hasDirectiveInput);
if (sanitizerToUse) {
// it's important we remove the current style sanitizer once the
// element exits, otherwise it will be used by the next styling
// instructions for the next element.
setElementExitFn(stylingApply);
}
} else {
const stylingMapArr =
value === NO_CHANGE ? NO_CHANGE : normalizeIntoStylingMap(oldValue, value, !isClassBased);
activateStylingMapFeature();
// Context Resolution (or first update) Case: save the map value
// and defer to the context to flush and apply the style/class binding
// value to the element.
if (isClassBased) {
updateClassViaContext(
context, lView, native, directiveIndex, null, bindingIndex, stylingMapArr,
valueHasChanged);
} else {
updateStyleViaContext(
context, lView, native, directiveIndex, null, bindingIndex, stylingMapArr, sanitizer,
valueHasChanged);
}
setElementExitFn(stylingApply);
}
if (ngDevMode) {
isClassBased ? ngDevMode.classMap : ngDevMode.styleMap++;
if (valueHasChanged) {
isClassBased ? ngDevMode.classMapCacheMiss : ngDevMode.styleMapCacheMiss++;
}
}
}
/**
* Writes a value to a directive's `style` or `class` input binding (if it has changed).
*
* If a directive has a `@Input` binding that is set on `style` or `class` then that value
* will take priority over the underlying style/class styling bindings. This value will
* be updated for the binding each time during change detection.
*
* When this occurs this function will attempt to write the value to the input binding
* depending on the following situations:
*
* - If `oldValue !== newValue`
* - If `newValue` is `null` (but this is skipped if it is during the first update pass--
* which is when the context is not locked yet)
*/
function updateDirectiveInputValue(
context: TStylingContext, lView: LView, tNode: TNode, bindingIndex: number, newValue: any,
isClassBased: boolean): void {
const oldValue = lView[bindingIndex];
if (oldValue !== newValue) {
// even if the value has changed we may not want to emit it to the
// directive input(s) in the event that it is falsy during the
// first update pass.
if (newValue || isContextLocked(context, false)) {
const inputName: string = isClassBased ? selectClassBasedInputName(tNode.inputs !) : 'style';
const inputs = tNode.inputs ![inputName] !;
const initialValue = getInitialStylingValue(context);
const value = normalizeStylingDirectiveInputValue(initialValue, newValue, isClassBased);
setInputsForProperty(lView, inputs, value);
setElementExitFn(stylingApply);
}
setValue(lView, bindingIndex, newValue);
}
}
/**
* Returns the appropriate directive input value for `style` or `class`.
*
* Earlier versions of Angular expect a binding value to be passed into directive code
* exactly as it is unless there is a static value present (in which case both values
* will be stringified and concatenated).
*/
function normalizeStylingDirectiveInputValue(
initialValue: string, bindingValue: string | {[key: string]: any} | null,
isClassBased: boolean) {
let value = bindingValue;
// we only concat values if there is an initial value, otherwise we return the value as is.
// Note that this is to satisfy backwards-compatibility in Angular.
if (initialValue.length) {
if (isClassBased) {
value = concatString(initialValue, forceClassesAsString(bindingValue));
} else {
value = concatString(initialValue, forceStylesAsString(bindingValue, true), ';');
}
}
return value;
}
/**
* Flushes all styling code to the element.
*
* This function is designed to be scheduled from any of the four styling instructions
* in this file. When called it will flush all style and class bindings to the element
* via the context resolution algorithm.
*/
function stylingApply(): void {
const lView = getLView();
const elementIndex = getSelectedIndex();
const tNode = getTNode(elementIndex, lView);
const native = getNativeByTNode(tNode, lView) as RElement;
const directiveIndex = getActiveDirectiveId();
const renderer = getRenderer(tNode, lView);
const sanitizer = getCurrentStyleSanitizer();
const classesContext = isStylingContext(tNode.classes) ? tNode.classes as TStylingContext : null;
const stylesContext = isStylingContext(tNode.styles) ? tNode.styles as TStylingContext : null;
flushStyling(renderer, lView, classesContext, stylesContext, native, directiveIndex, sanitizer);
resetCurrentStyleSanitizer();
}
function getRenderer(tNode: TNode, lView: LView) {
return tNode.type === TNodeType.Element ? lView[RENDERER] : null;
}
/**
* Searches and assigns provided all static style/class entries (found in the `attrs` value)
* and registers them in their respective styling contexts.
*/
export function registerInitialStylingOnTNode(
tNode: TNode, attrs: TAttributes, startIndex: number): boolean {
let hasAdditionalInitialStyling = false;
let styles = getStylingMapArray(tNode.styles);
let classes = getStylingMapArray(tNode.classes);
let mode = -1;
for (let i = startIndex; i < attrs.length; i++) {
const attr = attrs[i] as string;
if (typeof attr == 'number') {
mode = attr;
} else if (mode == AttributeMarker.Classes) {
classes = classes || allocStylingMapArray(null);
addItemToStylingMap(classes, attr, true);
hasAdditionalInitialStyling = true;
} else if (mode == AttributeMarker.Styles) {
const value = attrs[++i] as string | null;
styles = styles || allocStylingMapArray(null);
addItemToStylingMap(styles, attr, value);
hasAdditionalInitialStyling = true;
}
}
if (classes && classes.length > StylingMapArrayIndex.ValuesStartPosition) {
if (!tNode.classes) {
tNode.classes = classes;
}
updateRawValueOnContext(tNode.classes, stylingMapToString(classes, true));
}
if (styles && styles.length > StylingMapArrayIndex.ValuesStartPosition) {
if (!tNode.styles) {
tNode.styles = styles;
}
updateRawValueOnContext(tNode.styles, stylingMapToString(styles, false));
}
if (hasAdditionalInitialStyling) {
tNode.flags |= TNodeFlags.hasInitialStyling;
}
return hasAdditionalInitialStyling;
}
function updateRawValueOnContext(context: TStylingContext | StylingMapArray, value: string) {
const stylingMapArr = getStylingMapArray(context) !;
stylingMapArr[StylingMapArrayIndex.RawValuePosition] = value;
}
function getStylesContext(tNode: TNode): TStylingContext {
return getContext(tNode, false);
}
function getClassesContext(tNode: TNode): TStylingContext {
return getContext(tNode, true);
}
/**
* Returns/instantiates a styling context from/to a `tNode` instance.
*/
function getContext(tNode: TNode, isClassBased: boolean): TStylingContext {
let context = isClassBased ? tNode.classes : tNode.styles;
if (!isStylingContext(context)) {
const hasDirectives = isDirectiveHost(tNode);
context = allocTStylingContext(context as StylingMapArray | null, hasDirectives);
if (ngDevMode) {
attachStylingDebugObject(context as TStylingContext, isClassBased);
}
if (isClassBased) {
tNode.classes = context;
} else {
tNode.styles = context;
}
}
return context as TStylingContext;
}
function resolveStylePropValue(
value: string | number | SafeValue | null | NO_CHANGE,
suffix: string | null | undefined): string|SafeValue|null|undefined|NO_CHANGE {
if (value === NO_CHANGE) return value;
let resolvedValue: string|null = null;
if (value !== null) {
if (suffix) {
// when a suffix is applied then it will bypass
// sanitization entirely (b/c a new string is created)
resolvedValue = renderStringify(value) + suffix;
} else {
// sanitization happens by dealing with a string value
// this means that the string value will be passed through
// into the style rendering later (which is where the value
// will be sanitized before it is applied)
resolvedValue = value as any as string;
}
}
return resolvedValue;
}
/**
* Whether or not the style/class binding being applied was executed within a host bindings
* function.
*/
function isHostStyling(): boolean {
return isHostStylingActive(getActiveDirectiveId());
}
function getAndIncrementBindingIndex(lView: LView, isMapBased: boolean): number {
// map-based bindings use two slots because the previously constructed
// className / style value must be compared against.
const index = lView[BINDING_INDEX];
lView[BINDING_INDEX] += isMapBased ? 2 : 1;
return index;
}