feat(ivy): bridge component styles into the component renderer (#25255)

PR Close #25255
This commit is contained in:
Matias Niemelä 2018-07-31 11:14:06 -07:00
parent a59d4da304
commit a37bcc3bfe
26 changed files with 3557 additions and 24 deletions

View File

@ -15,7 +15,7 @@ import {filterToMembersWithDecorator, reflectObjectLiteral, staticallyResolve} f
import {AnalysisOutput, CompileResult, DecoratorHandler} from '../../transform'; import {AnalysisOutput, CompileResult, DecoratorHandler} from '../../transform';
import {ResourceLoader} from './api'; import {ResourceLoader} from './api';
import {extractDirectiveMetadata, extractQueriesFromDecorator, queriesFromFields} from './directive'; import {extractDirectiveMetadata, extractQueriesFromDecorator, parseFieldArrayValue, queriesFromFields} from './directive';
import {SelectorScopeRegistry} from './selector_scope'; import {SelectorScopeRegistry} from './selector_scope';
import {isAngularCore, unwrapExpression} from './util'; import {isAngularCore, unwrapExpression} from './util';
@ -135,11 +135,24 @@ export class ComponentDecoratorHandler implements DecoratorHandler<R3ComponentMe
viewQueries.push(...queriesFromDecorator.view); viewQueries.push(...queriesFromDecorator.view);
} }
let styles: string[]|null = null;
if (component.has('styles')) {
styles = parseFieldArrayValue(component, 'styles', this.reflector, this.checker);
}
let encapsulation: number = 0;
if (component.has('encapsulation')) {
encapsulation = parseInt(staticallyResolve(
component.get('encapsulation') !, this.reflector, this.checker) as string);
}
return { return {
analysis: { analysis: {
...metadata, ...metadata,
template, template,
viewQueries, viewQueries,
encapsulation,
styles: styles || [],
// These will be replaced during the compilation step, after all `NgModule`s have been // These will be replaced during the compilation step, after all `NgModule`s have been
// analyzed and the full compilation scope for the component can be realized. // analyzed and the full compilation scope for the component can be realized.

View File

@ -261,6 +261,22 @@ function isStringArrayOrDie(value: any, name: string): value is string[] {
return true; return true;
} }
export function parseFieldArrayValue(
directive: Map<string, ts.Expression>, field: string, reflector: ReflectionHost,
checker: ts.TypeChecker): null|string[] {
if (!directive.has(field)) {
return null;
}
// Resolve the field of interest from the directive metadata to a string[].
const value = staticallyResolve(directive.get(field) !, reflector, checker);
if (!isStringArrayOrDie(value, field)) {
throw new Error(`Failed to resolve @Directive.${field}`);
}
return value;
}
/** /**
* Interpret property mapping fields on the decorator (e.g. inputs or outputs) and return the * Interpret property mapping fields on the decorator (e.g. inputs or outputs) and return the
* correctly shaped metadata object. * correctly shaped metadata object.
@ -268,16 +284,11 @@ function isStringArrayOrDie(value: any, name: string): value is string[] {
function parseFieldToPropertyMapping( function parseFieldToPropertyMapping(
directive: Map<string, ts.Expression>, field: string, reflector: ReflectionHost, directive: Map<string, ts.Expression>, field: string, reflector: ReflectionHost,
checker: ts.TypeChecker): {[field: string]: string} { checker: ts.TypeChecker): {[field: string]: string} {
if (!directive.has(field)) { const metaValues = parseFieldArrayValue(directive, field, reflector, checker);
if (!metaValues) {
return EMPTY_OBJECT; return EMPTY_OBJECT;
} }
// Resolve the field of interest from the directive metadata to a string[].
const metaValues = staticallyResolve(directive.get(field) !, reflector, checker);
if (!isStringArrayOrDie(metaValues, field)) {
throw new Error(`Failed to resolve @Directive.${field}`);
}
return metaValues.reduce( return metaValues.reduce(
(results, value) => { (results, value) => {
// Either the value is 'field' or 'field: property'. In the first case, `property` will // Either the value is 'field' or 'field: property'. In the first case, `property` will

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {InitialStylingFlags} from '@angular/compiler/src/core'; import {InitialStylingFlags, ViewEncapsulation} from '@angular/compiler/src/core';
import {MockDirectory, setup} from '@angular/compiler/test/aot/test_util'; import {MockDirectory, setup} from '@angular/compiler/test/aot/test_util';
import {compile, expectEmit} from './mock_compile'; import {compile, expectEmit} from './mock_compile';
@ -18,6 +18,89 @@ describe('compiler compliance: styling', () => {
compileAnimations: false, compileAnimations: false,
}); });
describe('@Component.styles', () => {
it('should pass in the component metadata styles into the component definition and shim them using style encapsulation',
() => {
const files = {
app: {
'spec.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
selector: "my-component",
styles: ["div.foo { color: red; }", ":host p:nth-child(even) { --webkit-transition: 1s linear all; }"],
template: "..."
})
export class MyComponent {
}
@NgModule({declarations: [MyComponent]})
export class MyModule {}
`
}
};
const template =
'styles: ["div.foo[_ngcontent-%COMP%] { color: red; }", "[_nghost-%COMP%] p[_ngcontent-%COMP%]:nth-child(even) { --webkit-transition: 1s linear all; }"]';
const result = compile(files, angularFiles);
expectEmit(result.source, template, 'Incorrect template');
});
it('should pass in styles, but skip shimming the styles if the view encapsulation signals not to',
() => {
const files = {
app: {
'spec.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
selector: "my-component",
encapsulation: ${ViewEncapsulation.None},
styles: ["div.tall { height: 123px; }", ":host.small p { height:5px; }"],
template: "..."
})
export class MyComponent {
}
@NgModule({declarations: [MyComponent]})
export class MyModule {}
`
}
};
const template = 'div.tall { height: 123px; }", ":host.small p { height:5px; }';
const result = compile(files, angularFiles);
expectEmit(result.source, template, 'Incorrect template');
});
it('should pass in the component metadata styles into the component definition but skip shimming when style encapsulation is set to native',
() => {
const files = {
app: {
'spec.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
encapsulation: ${ViewEncapsulation.Native},
selector: "my-component",
styles: ["div.cool { color: blue; }", ":host.nice p { color: gold; }"],
template: "..."
})
export class MyComponent {
}
@NgModule({declarations: [MyComponent]})
export class MyModule {}
`
}
};
const template = 'div.cool { color: blue; }", ":host.nice p { color: gold; }';
const result = compile(files, angularFiles);
expectEmit(result.source, template, 'Incorrect template');
});
});
describe('[style] and [style.prop]', () => { describe('[style] and [style.prop]', () => {
it('should create style instructions on the element', () => { it('should create style instructions on the element', () => {
const files = { const files = {

View File

@ -188,6 +188,7 @@ export class CompileStylesheetMetadata {
export interface CompileTemplateSummary { export interface CompileTemplateSummary {
ngContentSelectors: string[]; ngContentSelectors: string[];
encapsulation: ViewEncapsulation|null; encapsulation: ViewEncapsulation|null;
styles: string[];
} }
/** /**
@ -243,6 +244,7 @@ export class CompileTemplateMetadata {
return { return {
ngContentSelectors: this.ngContentSelectors, ngContentSelectors: this.ngContentSelectors,
encapsulation: this.encapsulation, encapsulation: this.encapsulation,
styles: this.styles
}; };
} }
} }

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ViewEncapsulation} from '../../core';
import * as o from '../../output/output_ast'; import * as o from '../../output/output_ast';
import {ParseSourceSpan} from '../../parse_util'; import {ParseSourceSpan} from '../../parse_util';
import * as t from '../r3_ast'; import * as t from '../r3_ast';
@ -151,6 +152,22 @@ export interface R3ComponentMetadata extends R3DirectiveMetadata {
* This is done when the directives contain forward references. * This is done when the directives contain forward references.
*/ */
wrapDirectivesInClosure: boolean; wrapDirectivesInClosure: boolean;
/**
* A collection of styling data that will be applied and scoped to the component.
*/
styles: string[];
/**
* An encapsulation policy for the template and CSS styles. One of:
* - `ViewEncapsulation.Native`: Use shadow roots. This works only if natively available on the
* platform (note that this is marked the as the "deprecated shadow DOM" as of Angular v6.1.
* - `ViewEncapsulation.Emulated`: Use shimmed CSS that emulates the native behavior.
* - `ViewEncapsulation.None`: Use global CSS without any encapsulation.
* - `ViewEncapsulation.ShadowDom`: Use the latest ShadowDOM API to natively encapsulate styles
* into a shadow root.
*/
encapsulation: ViewEncapsulation;
} }
/** /**

View File

@ -16,6 +16,8 @@ import {LifecycleHooks} from '../../lifecycle_reflector';
import * as o from '../../output/output_ast'; import * as o from '../../output/output_ast';
import {typeSourceSpan} from '../../parse_util'; import {typeSourceSpan} from '../../parse_util';
import {CssSelector, SelectorMatcher} from '../../selector'; import {CssSelector, SelectorMatcher} from '../../selector';
import {ShadowCss} from '../../shadow_css';
import {CONTENT_ATTR, HOST_ATTR} from '../../style_compiler';
import {BindingParser} from '../../template_parser/binding_parser'; import {BindingParser} from '../../template_parser/binding_parser';
import {OutputContext, error} from '../../util'; import {OutputContext, error} from '../../util';
import {compileFactoryFunction, dependenciesFromGlobalMetadata} from '../r3_factory'; import {compileFactoryFunction, dependenciesFromGlobalMetadata} from '../r3_factory';
@ -27,6 +29,8 @@ import {R3ComponentDef, R3ComponentMetadata, R3DirectiveDef, R3DirectiveMetadata
import {BindingScope, TemplateDefinitionBuilder, renderFlagCheckIfStmt} from './template'; import {BindingScope, TemplateDefinitionBuilder, renderFlagCheckIfStmt} from './template';
import {CONTEXT_NAME, DefinitionMap, RENDER_FLAGS, TEMPORARY_NAME, asLiteral, conditionallyCreateMapObjectLiteral, getQueryPredicate, temporaryAllocator} from './util'; import {CONTEXT_NAME, DefinitionMap, RENDER_FLAGS, TEMPORARY_NAME, asLiteral, conditionallyCreateMapObjectLiteral, getQueryPredicate, temporaryAllocator} from './util';
const EMPTY_ARRAY: any[] = [];
function baseDirectiveFields( function baseDirectiveFields(
meta: R3DirectiveMetadata, constantPool: ConstantPool, meta: R3DirectiveMetadata, constantPool: ConstantPool,
bindingParser: BindingParser): {definitionMap: DefinitionMap, statements: o.Statement[]} { bindingParser: BindingParser): {definitionMap: DefinitionMap, statements: o.Statement[]} {
@ -218,6 +222,15 @@ export function compileComponentFromMetadata(
definitionMap.set('pipes', o.literalArr(Array.from(pipesUsed))); definitionMap.set('pipes', o.literalArr(Array.from(pipesUsed)));
} }
// e.g. `styles: [str1, str2]`
if (meta.styles && meta.styles.length) {
const styleValues = meta.encapsulation == core.ViewEncapsulation.Emulated ?
compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
meta.styles;
const strings = styleValues.map(str => o.literal(str));
definitionMap.set('styles', o.literalArr(strings));
}
// On the type side, remove newlines from the selector as it will need to fit into a TypeScript // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
// string literal, which must be on one line. // string literal, which must be on one line.
const selectorForType = (meta.selector || '').replace(/\n/g, ''); const selectorForType = (meta.selector || '').replace(/\n/g, '');
@ -287,6 +300,9 @@ export function compileComponentFromRender2(
pipes: typeMapToExpressionMap(pipeTypeByName, outputCtx), pipes: typeMapToExpressionMap(pipeTypeByName, outputCtx),
viewQueries: queriesFromGlobalMetadata(component.viewQueries, outputCtx), viewQueries: queriesFromGlobalMetadata(component.viewQueries, outputCtx),
wrapDirectivesInClosure: false, wrapDirectivesInClosure: false,
styles: (summary.template && summary.template.styles) || EMPTY_ARRAY,
encapsulation:
(summary.template && summary.template.encapsulation) || core.ViewEncapsulation.Emulated
}; };
const res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser); const res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser);
@ -624,3 +640,8 @@ export function parseHostBindings(host: {[key: string]: string}): {
return {attributes, listeners, properties, animations}; return {attributes, listeners, properties, animations};
} }
function compileStyles(styles: string[], selector: string, hostSelector: string): string[] {
const shadowCss = new ShadowCss();
return styles.map(style => { return shadowCss !.shimCssText(style, selector, hostSelector); });
}

View File

@ -14,8 +14,8 @@ import {UrlResolver} from './url_resolver';
import {OutputContext} from './util'; import {OutputContext} from './util';
const COMPONENT_VARIABLE = '%COMP%'; const COMPONENT_VARIABLE = '%COMP%';
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`; export const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`; export const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
export class StylesCompileDependency { export class StylesCompileDependency {
constructor( constructor(

View File

@ -9,8 +9,9 @@
import './ng_dev_mode'; import './ng_dev_mode';
import {ChangeDetectionStrategy} from '../change_detection/constants'; import {ChangeDetectionStrategy} from '../change_detection/constants';
import {Provider, ViewEncapsulation} from '../core'; import {Provider} from '../di/provider';
import {NgModuleDef, NgModuleDefInternal} from '../metadata/ng_module'; import {NgModuleDef, NgModuleDefInternal} from '../metadata/ng_module';
import {ViewEncapsulation} from '../metadata/view';
import {Type} from '../type'; import {Type} from '../type';
import {BaseDef, ComponentDefFeature, ComponentDefInternal, ComponentQuery, ComponentTemplate, ComponentType, DirectiveDefFeature, DirectiveDefInternal, DirectiveType, DirectiveTypesOrFactory, PipeDefInternal, PipeType, PipeTypesOrFactory} from './interfaces/definition'; import {BaseDef, ComponentDefFeature, ComponentDefInternal, ComponentQuery, ComponentTemplate, ComponentType, DirectiveDefFeature, DirectiveDefInternal, DirectiveType, DirectiveTypesOrFactory, PipeDefInternal, PipeType, PipeTypesOrFactory} from './interfaces/definition';
@ -266,7 +267,8 @@ export function defineComponent<T>(componentDefinition: {
const pipeTypes = componentDefinition.pipes !; const pipeTypes = componentDefinition.pipes !;
const directiveTypes = componentDefinition.directives !; const directiveTypes = componentDefinition.directives !;
const declaredInputs: {[key: string]: string} = {} as any; const declaredInputs: {[key: string]: string} = {} as any;
const encapsulation = componentDefinition.encapsulation; const encapsulation = componentDefinition.encapsulation || ViewEncapsulation.Emulated;
const styles: string[] = componentDefinition.styles || EMPTY_ARRAY;
const def: ComponentDefInternal<any> = { const def: ComponentDefInternal<any> = {
type: type, type: type,
diPublic: null, diPublic: null,
@ -304,9 +306,10 @@ export function defineComponent<T>(componentDefinition: {
data: componentDefinition.data || EMPTY, data: componentDefinition.data || EMPTY,
// TODO(misko): convert ViewEncapsulation into const enum so that it can be used directly in the // TODO(misko): convert ViewEncapsulation into const enum so that it can be used directly in the
// next line. Also `None` should be 0 not 2. // next line. Also `None` should be 0 not 2.
encapsulation: encapsulation == null ? 2 /* ViewEncapsulation.None */ : encapsulation, encapsulation,
id: `c${_renderCompCount++}`, providers: EMPTY_ARRAY,
styles: EMPTY_ARRAY, viewProviders: EMPTY_ARRAY,
id: `c${_renderCompCount++}`, styles,
}; };
const feature = componentDefinition.features; const feature = componentDefinition.features;
feature && feature.forEach((fn) => fn(def)); feature && feature.forEach((fn) => fn(def));

View File

@ -255,13 +255,13 @@ export interface ComponentDef<T, Selector extends string> extends DirectiveDef<T
* Defines the set of injectable providers that are visible to a Directive and its content DOM * Defines the set of injectable providers that are visible to a Directive and its content DOM
* children. * children.
*/ */
readonly providers?: Provider[]; readonly providers: Provider[]|null;
/** /**
* Defines the set of injectable providers that are visible to a Directive and its view DOM * Defines the set of injectable providers that are visible to a Directive and its view DOM
* children only. * children only.
*/ */
readonly viewProviders?: Provider[]; readonly viewProviders: Provider[]|null;
/** /**
* Registry of directives and components that may be found in this view. * Registry of directives and components that may be found in this view.

View File

@ -10,6 +10,7 @@ import {ConstantPool, R3DirectiveMetadata, WrappedNodeExpr, compileComponentFrom
import {Component, Directive, HostBinding, HostListener, Input, Output} from '../../metadata/directives'; import {Component, Directive, HostBinding, HostListener, Input, Output} from '../../metadata/directives';
import {componentNeedsResolution, maybeQueueResolutionOfComponentResources} from '../../metadata/resource_loading'; import {componentNeedsResolution, maybeQueueResolutionOfComponentResources} from '../../metadata/resource_loading';
import {ViewEncapsulation} from '../../metadata/view';
import {Type} from '../../type'; import {Type} from '../../type';
import {stringify} from '../../util'; import {stringify} from '../../util';
@ -73,6 +74,8 @@ export function compileComponent(type: Type<any>, metadata: Component): void {
pipes: new Map(), pipes: new Map(),
viewQueries: [], viewQueries: [],
wrapDirectivesInClosure: false, wrapDirectivesInClosure: false,
styles: metadata.styles || [],
encapsulation: metadata.encapsulation || ViewEncapsulation.Emulated
}, },
constantPool, makeBindingParser()); constantPool, makeBindingParser());
const preStatements = [...constantPool.statements, ...res.statements]; const preStatements = [...constantPool.statements, ...res.statements];

View File

@ -27,7 +27,7 @@
"name": "EMPTY$1" "name": "EMPTY$1"
}, },
{ {
"name": "EMPTY_ARRAY" "name": "EMPTY_ARRAY$1"
}, },
{ {
"name": "FLAGS" "name": "FLAGS"
@ -83,6 +83,9 @@
{ {
"name": "VIEWS" "name": "VIEWS"
}, },
{
"name": "ViewEncapsulation$1"
},
{ {
"name": "_CLEAN_PROMISE" "name": "_CLEAN_PROMISE"
}, },

View File

@ -573,10 +573,10 @@
"name": "EMPTY" "name": "EMPTY"
}, },
{ {
"name": "EMPTY_ARRAY$3" "name": "EMPTY_ARRAY$4"
}, },
{ {
"name": "EMPTY_ARRAY$4" "name": "EMPTY_ARRAY$5"
}, },
{ {
"name": "EMPTY_CONTEXT" "name": "EMPTY_CONTEXT"

View File

@ -6,7 +6,7 @@
"name": "CIRCULAR$2" "name": "CIRCULAR$2"
}, },
{ {
"name": "EMPTY_ARRAY$1" "name": "EMPTY_ARRAY$2"
}, },
{ {
"name": "GET_PROPERTY_NAME" "name": "GET_PROPERTY_NAME"

View File

@ -45,7 +45,7 @@
"name": "EMPTY$1" "name": "EMPTY$1"
}, },
{ {
"name": "EMPTY_ARRAY" "name": "EMPTY_ARRAY$1"
}, },
{ {
"name": "ElementRef" "name": "ElementRef"
@ -188,6 +188,9 @@
{ {
"name": "ViewContainerRef$1" "name": "ViewContainerRef$1"
}, },
{
"name": "ViewEncapsulation$1"
},
{ {
"name": "ViewRef" "name": "ViewRef"
}, },

View File

@ -9,7 +9,7 @@
import '@angular/core/test/bundling/util/src/reflect_metadata'; import '@angular/core/test/bundling/util/src/reflect_metadata';
import {CommonModule} from '@angular/common'; import {CommonModule} from '@angular/common';
import {Component, Injectable, NgModule, ɵrenderComponent as renderComponent} from '@angular/core'; import {Component, Injectable, NgModule, ViewEncapsulation, ɵrenderComponent as renderComponent} from '@angular/core';
class Todo { class Todo {
editing: boolean; editing: boolean;
@ -59,6 +59,7 @@ class TodoStore {
@Component({ @Component({
selector: 'todo-app', selector: 'todo-app',
// TODO(misko): make this work with `[(ngModel)]` // TODO(misko): make this work with `[(ngModel)]`
encapsulation: ViewEncapsulation.None,
template: ` template: `
<section class="todoapp"> <section class="todoapp">
<header class="header"> <header class="header">

View File

@ -0,0 +1,116 @@
package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "ng_module", "ts_library")
load("//tools/http-server:http_server.bzl", "http_server")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
load("//packages/bazel/src:ng_rollup_bundle.bzl", "ng_rollup_bundle")
load("@build_bazel_rules_nodejs//:defs.bzl", "jasmine_node_test")
load("@build_bazel_rules_typescript//:defs.bzl", "ts_devserver")
ng_module(
name = "todo",
srcs = ["index.ts"],
tags = ["ivy-only"],
deps = [
"//packages/common",
"//packages/core",
"//packages/core/test/bundling/util:reflect_metadata",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
],
)
ng_rollup_bundle(
name = "bundle",
# TODO(alexeagle): This is inconsistent.
# We try to teach users to always have their workspace at the start of a
# path, to disambiguate from other workspaces.
# Here, the rule implementation is looking in an execroot where the layout
# has an "external" directory for external dependencies.
# This should probably start with "angular/" and let the rule deal with it.
entry_point = "packages/core/test/bundling/todo_r2/index.js",
tags = ["ivy-only"],
deps = [
":todo",
"//packages/common",
"//packages/core",
"//packages/core/test/bundling/util:reflect_metadata",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
],
)
ts_library(
name = "test_lib",
testonly = 1,
srcs = glob(["*_spec.ts"]),
deps = [
"//packages:types",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/private/testing",
],
)
jasmine_node_test(
name = "test",
data = [
":bundle",
":bundle.js",
":bundle.min.js",
":bundle.min_debug.js",
],
tags = [
"ivy-jit",
"ivy-local",
"ivy-only",
],
deps = [":test_lib"],
)
js_expected_symbol_test(
name = "symbol_test",
src = ":bundle.min_debug.js",
golden = ":bundle.golden_symbols.json",
tags = [
"ivy-local",
"ivy-only",
],
)
genrule(
name = "tslib",
srcs = [
"@angular_deps//:node_modules/tslib/tslib.js",
],
outs = [
"tslib.js",
],
cmd = "cp $< $@",
)
ts_devserver(
name = "devserver",
entry_module = "angular/packages/core/test/bundling/todo_r2/index",
serving_path = "/bundle.min.js",
static_files = [
"index.html",
":tslib",
"todo.css",
"base.css",
],
deps = [":todo"],
)
http_server(
name = "prodserver",
data = [
"base.css",
"index.html",
"todo.css",
":bundle.min.js.br",
":bundle.min_debug.js",
],
)

View File

@ -0,0 +1,141 @@
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #c5c5c5;
border-bottom: 1px dashed #f7f7f7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
#issue-count {
display: none;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
padding-left: 300px;
}
.learn-bar > .learn {
left: 8px;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
<!doctype html>
<html>
<head>
<title>Angular Todo Example</title>
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="todo.css">
<style>
.done {
text-decoration: line-through;
}
</style>
</head>
<body>
<!-- The Angular application will be bootstrapped into this element. -->
<todo-app></todo-app>
<!--
Script tag which bootstraps the application. Use `?debug` in URL to select
the debug version of the script.
There are two scripts sources: `bundle.min.js` and `bundle.min_debug.js` You can
switch between which bundle the browser loads to experiment with the application.
- `bundle.min.js`: Is what the site would serve to their users. It has gone
through rollup, build-optimizer, and uglify with tree shaking.
- In `devserver` mode `bundle.min.js` is a bit misnamed since it is concatenated
individual files which are not minified.
- `bundle.min_debug.js`: Is what the developer would like to see when debugging
the application. It has also gone through full pipeline of rollup, build-optimizer,
and uglify, however special flags were passed to uglify to prevent inlining and
property renaming.
-->
<script>
document.write('<script src="' +
(document.location.search.endsWith('debug') ? '/bundle.min_debug.js' : '/bundle.min.js.br') +
'"></' + 'script>');
</script>
<script>
if (typeof define === "function" && define.amd) {
// If `define` is defined that we are in devserver mode. Dev server concatenates all of the
// source files and than loads them using `require`. There is an issue with the way
// `@angular/core` imports are generated which results in both `@angular/core` as well as `@angular/core/index`
// This hack makes both of the exports available to the application.
define("@angular/core", ["require", "exports", "tslib", "@angular/core/index"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib = require("tslib");
tslib.__exportStar(require("@angular/core/index"), exports);
});
}
</script>
</body>
</html>

View File

@ -0,0 +1,165 @@
/**
* @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 '@angular/core/test/bundling/util/src/reflect_metadata';
import {CommonModule} from '@angular/common';
import {Component, Injectable, NgModule, ɵNgModuleFactory as NgModuleFactory} from '@angular/core';
import {BrowserModule, platformBrowser} from '@angular/platform-browser';
class Todo {
editing: boolean;
// TODO(issue/24571): remove '!'.
private _title !: string;
get title() { return this._title; }
set title(value: string) { this._title = value.trim(); }
constructor(title: string, public completed: boolean = false) {
this.editing = false;
this.title = title;
}
}
@Injectable({providedIn: 'root'})
class TodoStore {
todos: Array<Todo> = [
new Todo('Demonstrate Components'),
new Todo('Demonstrate Structural Directives', true),
new Todo('Demonstrate NgModules'),
new Todo('Demonstrate zoneless change detection'),
new Todo('Demonstrate internationalization'),
];
private getWithCompleted(completed: boolean) {
return this.todos.filter((todo: Todo) => todo.completed === completed);
}
allCompleted() { return this.todos.length === this.getCompleted().length; }
setAllTo(completed: boolean) { this.todos.forEach((t: Todo) => t.completed = completed); }
removeCompleted() { this.todos = this.getWithCompleted(false); }
getRemaining() { return this.getWithCompleted(false); }
getCompleted() { return this.getWithCompleted(true); }
toggleCompletion(todo: Todo) { todo.completed = !todo.completed; }
remove(todo: Todo) { this.todos.splice(this.todos.indexOf(todo), 1); }
add(title: string) { this.todos.push(new Todo(title)); }
}
@Component({
selector: 'todo-app',
// TODO(misko): make this work with `[(ngModel)]`
styles: [`
.todo-list li.completed label {
color: #d9d9d9;
text-decoration: line-through;
font-weight:bold;
}
`],
template: `
<section class="todoapp">
<header class="header">
<h1>todos</h1>
<input class="new-todo" placeholder="What needs to be done?" autofocus=""
[value]="newTodoText"
(keyup)="$event.code == 'Enter' ? addTodo() : newTodoText = $event.target.value">
</header>
<section *ngIf="todoStore.todos.length > 0" class="main">
<input *ngIf="todoStore.todos.length"
#toggleall class="toggle-all" type="checkbox"
[checked]="todoStore.allCompleted()"
(click)="todoStore.setAllTo(toggleall.checked)">
<ul class="todo-list">
<li *ngFor="let todo of todoStore.todos"
[class.completed]="todo.completed"
[class.editing]="todo.editing">
<div class="view">
<input class="toggle" type="checkbox"
(click)="toggleCompletion(todo)"
[checked]="todo.completed">
<label (dblclick)="editTodo(todo)">{{todo.title}}</label>
<button class="destroy" (click)="remove(todo)"></button>
</div>
<input *ngIf="todo.editing"
class="edit" #editedtodo
[value]="todo.title"
(blur)="stopEditing(todo, editedtodo.value)"
(keyup)="todo.title = $event.target.value"
(keyup)="$event.code == 'Enter' && updateEditingTodo(todo, editedtodo.value)"
(keyup)="$event.code == 'Escape' && cancelEditingTodo(todo)">
</li>
</ul>
</section>
<footer *ngIf="todoStore.todos.length > 0" class="footer">
<span class="todo-count">
<strong>{{todoStore.getRemaining().length}}</strong>
{{todoStore.getRemaining().length == 1 ? 'item' : 'items'}} left
</span>
<button *ngIf="todoStore.getCompleted().length > 0"
class="clear-completed"
(click)="removeCompleted()">
Clear completed
</button>
</footer>
</section>
`,
// TODO(misko): switch over to OnPush
// changeDetection: ChangeDetectionStrategy.OnPush
})
class ToDoAppComponent {
newTodoText = '';
constructor(public todoStore: TodoStore) { (window as any).toDoAppComponent = this; }
stopEditing(todo: Todo, editedTitle: string) {
todo.title = editedTitle;
todo.editing = false;
}
cancelEditingTodo(todo: Todo) { todo.editing = false; }
updateEditingTodo(todo: Todo, editedTitle: string) {
editedTitle = editedTitle.trim();
todo.editing = false;
if (editedTitle.length === 0) {
return this.todoStore.remove(todo);
}
todo.title = editedTitle;
}
editTodo(todo: Todo) { todo.editing = true; }
removeCompleted() { this.todoStore.removeCompleted(); }
toggleCompletion(todo: Todo) { this.todoStore.toggleCompletion(todo); }
remove(todo: Todo) { this.todoStore.remove(todo); }
addTodo() {
if (this.newTodoText.trim().length) {
this.todoStore.add(this.newTodoText);
this.newTodoText = '';
}
}
}
@NgModule({declarations: [ToDoAppComponent], imports: [CommonModule, BrowserModule]})
class ToDoAppModule {
ngDoBootstrap(app: any) { app.bootstrap(ToDoAppComponent); }
}
(window as any).waitForApp =
platformBrowser().bootstrapModuleFactory(new NgModuleFactory(ToDoAppModule), {ngZone: 'noop'});

View File

@ -0,0 +1,372 @@
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
font-smoothing: antialiased;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #4d4d4d;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
font-smoothing: antialiased;
font-weight: 300;
}
button,
input[type="checkbox"] {
outline: none;
}
.hidden {
display: none;
}
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp h1 {
position: absolute;
top: -155px;
width: 100%;
font-size: 100px;
font-weight: 100;
text-align: center;
color: rgba(175, 47, 47, 0.15);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
border: 0;
outline: none;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
font-smoothing: antialiased;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
label[for='toggle-all'] {
display: none;
}
.toggle-all {
position: absolute;
top: -55px;
left: -12px;
width: 60px;
height: 34px;
text-align: center;
border: none; /* Mobile Safari */
}
.toggle-all:before {
content: '';
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
.toggle-all:checked:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle:after {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#ededed" stroke-width="3"/></svg>');
}
.todo-list li .toggle:checked:after {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#bddad5" stroke-width="3"/><path fill="#5dc2af" d="M72 25L42 71 27 56l-4 4 20 20 34-52z"/></svg>');
}
.todo-list li label {
white-space: pre-line;
word-break: break-all;
padding: 15px 60px 15px 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
transition: color 0.4s;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover {
color: #af5b5e;
}
.todo-list li .destroy:after {
content: '×';
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
color: #777;
padding: 10px 15px;
height: 20px;
text-align: center;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2),
0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a.selected,
.filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
.filters li a.selected {
border-color: rgba(175, 47, 47, 0.2);
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
cursor: pointer;
}
.clear-completed:hover {
text-decoration: underline;
}
.info {
margin: 65px auto 0;
color: #bfbfbf;
font-size: 10px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
.toggle-all {
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}

View File

@ -0,0 +1,51 @@
/**
* @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 {ɵwhenRendered as whenRendered} from '@angular/core';
import {withBody} from '@angular/private/testing';
import * as fs from 'fs';
import * as path from 'path';
const UTF8 = {
encoding: 'utf-8'
};
const PACKAGE = 'angular/packages/core/test/bundling/todo_r2';
const BUNDLES = ['bundle.js', 'bundle.min_debug.js', 'bundle.min.js'];
describe('functional test for todo', () => {
BUNDLES.forEach(bundle => {
describe(bundle, () => {
it('should place styles on the elements within the component',
withBody('<todo-app></todo-app>', async() => {
require(path.join(PACKAGE, bundle));
await(window as any).waitForApp;
const toDoAppComponent = (window as any).toDoAppComponent;
await whenRendered(toDoAppComponent);
const styleContent = findStyleTextForSelector('.todo-list\\\[_ngcontent-\\\w+\\\]');
expect(styleContent).toMatch(/font-weight:\s*bold;/);
expect(styleContent).toMatch(/color:\s*#d9d9d9;/);
}));
});
});
});
function findStyleTextForSelector(selector: string): string {
const styles = document.querySelectorAll('head style');
const matchExp = new RegExp(`${selector}.+?\\\{([\\s\\S]+)\\\}`, 'm');
for (let i = 0; i < styles.length; i++) {
const styleElement = styles[i];
const content = styleElement.textContent || '';
const result = matchExp.exec(content);
if (result && result.length > 1) {
return result[1];
}
}
throw new Error(`The CSS Style Rule ${selector} was not found`);
}

View File

@ -26,6 +26,7 @@ describe('component', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: CounterComponent, type: CounterComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['counter']], selectors: [['counter']],
consts: 1, consts: 1,
vars: 1, vars: 1,
@ -72,6 +73,7 @@ describe('component', () => {
constructor(public myService: MyService) {} constructor(public myService: MyService) {}
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: MyComponent, type: MyComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['my-component']], selectors: [['my-component']],
factory: () => new MyComponent(directiveInject(MyService)), factory: () => new MyComponent(directiveInject(MyService)),
consts: 1, consts: 1,
@ -139,6 +141,7 @@ describe('component with a container', () => {
items !: string[]; items !: string[];
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: WrapperComponent, type: WrapperComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['wrapper']], selectors: [['wrapper']],
consts: 1, consts: 1,
vars: 0, vars: 0,
@ -188,6 +191,7 @@ describe('encapsulation', () => {
class WrapperComponent { class WrapperComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: WrapperComponent, type: WrapperComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['wrapper']], selectors: [['wrapper']],
consts: 1, consts: 1,
vars: 0, vars: 0,
@ -224,6 +228,7 @@ describe('encapsulation', () => {
class LeafComponent { class LeafComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: LeafComponent, type: LeafComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['leaf']], selectors: [['leaf']],
consts: 2, consts: 2,
vars: 0, vars: 0,
@ -334,6 +339,7 @@ describe('recursive components', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: TreeComponent, type: TreeComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['tree-comp']], selectors: [['tree-comp']],
factory: () => new TreeComponent(), factory: () => new TreeComponent(),
consts: 3, consts: 3,
@ -395,6 +401,7 @@ describe('recursive components', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: NgIfTree, type: NgIfTree,
encapsulation: ViewEncapsulation.None,
selectors: [['ng-if-tree']], selectors: [['ng-if-tree']],
factory: () => new NgIfTree(), factory: () => new NgIfTree(),
consts: 3, consts: 3,
@ -534,6 +541,7 @@ describe('recursive components', () => {
minifiedName !: string; minifiedName !: string;
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: TestInputsComponent, type: TestInputsComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['test-inputs']], selectors: [['test-inputs']],
inputs: {minifiedName: 'unminifiedName'}, inputs: {minifiedName: 'unminifiedName'},
consts: 0, consts: 0,

View File

@ -9,10 +9,12 @@
import {ElementRef, TemplateRef, ViewContainerRef} from '@angular/core'; import {ElementRef, TemplateRef, ViewContainerRef} from '@angular/core';
import {RenderFlags} from '@angular/core/src/render3'; import {RenderFlags} from '@angular/core/src/render3';
import {RendererType2} from '../../src/render/api';
import {getOrCreateNodeInjectorForNode, getOrCreateTemplateRef} from '../../src/render3/di'; import {getOrCreateNodeInjectorForNode, getOrCreateTemplateRef} from '../../src/render3/di';
import {AttributeMarker, defineComponent, defineDirective, injectElementRef, injectTemplateRef, injectViewContainerRef} from '../../src/render3/index'; import {AttributeMarker, defineComponent, defineDirective, injectElementRef, injectTemplateRef, injectViewContainerRef} from '../../src/render3/index';
import {NO_CHANGE, bind, container, containerRefreshEnd, containerRefreshStart, element, elementAttribute, elementClassProp, elementContainerEnd, elementContainerStart, elementEnd, elementProperty, elementStart, elementStyleProp, elementStyling, elementStylingApply, embeddedViewEnd, embeddedViewStart, interpolation1, interpolation2, interpolation3, interpolation4, interpolation5, interpolation6, interpolation7, interpolation8, interpolationV, listener, load, loadDirective, projection, projectionDef, text, textBinding, template} from '../../src/render3/instructions'; import {NO_CHANGE, bind, container, containerRefreshEnd, containerRefreshStart, element, elementAttribute, elementClassProp, elementContainerEnd, elementContainerStart, elementEnd, elementProperty, elementStart, elementStyleProp, elementStyling, elementStylingApply, embeddedViewEnd, embeddedViewStart, interpolation1, interpolation2, interpolation3, interpolation4, interpolation5, interpolation6, interpolation7, interpolation8, interpolationV, listener, load, loadDirective, projection, projectionDef, text, textBinding, template} from '../../src/render3/instructions';
import {InitialStylingFlags} from '../../src/render3/interfaces/definition'; import {InitialStylingFlags} from '../../src/render3/interfaces/definition';
import {RElement, Renderer3, RendererFactory3, domRendererFactory3} from '../../src/render3/interfaces/renderer';
import {HEADER_OFFSET} from '../../src/render3/interfaces/view'; import {HEADER_OFFSET} from '../../src/render3/interfaces/view';
import {sanitizeUrl} from '../../src/sanitization/sanitization'; import {sanitizeUrl} from '../../src/sanitization/sanitization';
import {Sanitizer, SecurityContext} from '../../src/sanitization/security'; import {Sanitizer, SecurityContext} from '../../src/sanitization/security';
@ -1384,6 +1386,32 @@ describe('render3 integration test', () => {
}); });
describe('component styles', () => {
it('should pass in the component styles directly into the underlying renderer', () => {
class StyledComp {
static ngComponentDef = defineComponent({
type: StyledComp,
styles: ['div { color: red; }'],
consts: 1,
vars: 0,
encapsulation: 100,
selectors: [['foo']],
factory: () => new StyledComp(),
template: (rf: RenderFlags, ctx: StyledComp) => {
if (rf & RenderFlags.Create) {
element(0, 'div');
}
}
});
}
const rendererFactory = new MockRendererFactory();
new ComponentFixture(StyledComp, {rendererFactory});
expect(rendererFactory.lastCapturedType !.styles).toEqual(['div { color: red; }']);
expect(rendererFactory.lastCapturedType !.encapsulation).toEqual(100);
});
});
describe('sanitization', () => { describe('sanitization', () => {
it('should sanitize data using the provided sanitization interface', () => { it('should sanitize data using the provided sanitization interface', () => {
class SanitizationComp { class SanitizationComp {
@ -1447,3 +1475,12 @@ class LocalSanitizer implements Sanitizer {
bypassSecurityTrustUrl(value: string) { return new LocalSanitizedValue(value); } bypassSecurityTrustUrl(value: string) { return new LocalSanitizedValue(value); }
} }
class MockRendererFactory implements RendererFactory3 {
lastCapturedType: RendererType2|null = null;
createRenderer(hostElement: RElement|null, rendererType: RendererType2|null): Renderer3 {
this.lastCapturedType = rendererType;
return domRendererFactory3.createRenderer(hostElement, rendererType);
}
}

View File

@ -32,6 +32,7 @@ describe('renderer factory lifecycle', () => {
class SomeComponent { class SomeComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: SomeComponent, type: SomeComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['some-component']], selectors: [['some-component']],
consts: 1, consts: 1,
vars: 0, vars: 0,
@ -48,6 +49,7 @@ describe('renderer factory lifecycle', () => {
class SomeComponentWhichThrows { class SomeComponentWhichThrows {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: SomeComponentWhichThrows, type: SomeComponentWhichThrows,
encapsulation: ViewEncapsulation.None,
selectors: [['some-component-with-Error']], selectors: [['some-component-with-Error']],
consts: 0, consts: 0,
vars: 0, vars: 0,
@ -128,6 +130,7 @@ describe('animation renderer factory', () => {
class SomeComponent { class SomeComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: SomeComponent, type: SomeComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['some-component']], selectors: [['some-component']],
consts: 1, consts: 1,
vars: 0, vars: 0,
@ -258,6 +261,7 @@ describe('Renderer2 destruction hooks', () => {
class SimpleComponent { class SimpleComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: SimpleComponent, type: SimpleComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['simple']], selectors: [['simple']],
consts: 1, consts: 1,
vars: 0, vars: 0,

View File

@ -7,8 +7,10 @@
*/ */
import {Component, ComponentFactoryResolver, ElementRef, EmbeddedViewRef, NgModuleRef, Pipe, PipeTransform, RendererFactory2, TemplateRef, ViewContainerRef, createInjector, defineInjector, ɵAPP_ROOT as APP_ROOT, ɵNgModuleDef as NgModuleDef} from '../../src/core'; import {Component, ComponentFactoryResolver, ElementRef, EmbeddedViewRef, NgModuleRef, Pipe, PipeTransform, RendererFactory2, TemplateRef, ViewContainerRef, createInjector, defineInjector, ɵAPP_ROOT as APP_ROOT, ɵNgModuleDef as NgModuleDef} from '../../src/core';
import {ViewEncapsulation} from '../../src/metadata';
import {templateRefExtractor} from '../../src/render3/di'; import {templateRefExtractor} from '../../src/render3/di';
import {AttributeMarker, NgOnChangesFeature, defineComponent, defineDirective, definePipe, injectComponentFactoryResolver, injectTemplateRef, injectViewContainerRef} from '../../src/render3/index'; import {AttributeMarker, NgOnChangesFeature, defineComponent, defineDirective, definePipe, injectComponentFactoryResolver, injectTemplateRef, injectViewContainerRef} from '../../src/render3/index';
import {bind, container, containerRefreshEnd, containerRefreshStart, element, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, interpolation1, interpolation3, loadDirective, nextContext, projection, projectionDef, reference, template, text, textBinding} from '../../src/render3/instructions'; import {bind, container, containerRefreshEnd, containerRefreshStart, element, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, interpolation1, interpolation3, loadDirective, nextContext, projection, projectionDef, reference, template, text, textBinding} from '../../src/render3/instructions';
import {RenderFlags} from '../../src/render3/interfaces/definition'; import {RenderFlags} from '../../src/render3/interfaces/definition';
import {NgModuleFactory} from '../../src/render3/ng_module_ref'; import {NgModuleFactory} from '../../src/render3/ng_module_ref';
@ -261,6 +263,7 @@ describe('ViewContainerRef', () => {
testDir !: TestDirective; testDir !: TestDirective;
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: TestComponent, type: TestComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['test-cmp']], selectors: [['test-cmp']],
factory: () => new TestComponent(), factory: () => new TestComponent(),
consts: 4, consts: 4,
@ -332,6 +335,7 @@ describe('ViewContainerRef', () => {
testDir !: TestDirective; testDir !: TestDirective;
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: TestComponent, type: TestComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['test-cmp']], selectors: [['test-cmp']],
consts: 4, consts: 4,
vars: 0, vars: 0,
@ -393,6 +397,7 @@ describe('ViewContainerRef', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Child, type: Child,
encapsulation: ViewEncapsulation.None,
selectors: [['child']], selectors: [['child']],
factory: () => new Child(), factory: () => new Child(),
consts: 1, consts: 1,
@ -442,6 +447,7 @@ describe('ViewContainerRef', () => {
class SomeComponent { class SomeComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: SomeComponent, type: SomeComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['some-comp']], selectors: [['some-comp']],
factory: () => new SomeComponent(), factory: () => new SomeComponent(),
consts: 6, consts: 6,
@ -509,6 +515,7 @@ describe('ViewContainerRef', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Child, type: Child,
encapsulation: ViewEncapsulation.None,
selectors: [['child']], selectors: [['child']],
factory: () => child = new Child(), factory: () => child = new Child(),
consts: 2, consts: 2,
@ -593,6 +600,7 @@ describe('ViewContainerRef', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: LoopComp, type: LoopComp,
encapsulation: ViewEncapsulation.None,
selectors: [['loop-comp']], selectors: [['loop-comp']],
factory: () => new LoopComp(), factory: () => new LoopComp(),
consts: 1, consts: 1,
@ -906,6 +914,7 @@ describe('ViewContainerRef', () => {
class EmbeddedComponent { class EmbeddedComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: EmbeddedComponent, type: EmbeddedComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['embedded-cmp']], selectors: [['embedded-cmp']],
factory: () => new EmbeddedComponent(), factory: () => new EmbeddedComponent(),
consts: 1, consts: 1,
@ -991,6 +1000,7 @@ describe('ViewContainerRef', () => {
class EmbeddedComponentWithNgContent { class EmbeddedComponentWithNgContent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: EmbeddedComponentWithNgContent, type: EmbeddedComponentWithNgContent,
encapsulation: ViewEncapsulation.None,
selectors: [['embedded-cmp-with-ngcontent']], selectors: [['embedded-cmp-with-ngcontent']],
factory: () => new EmbeddedComponentWithNgContent(), factory: () => new EmbeddedComponentWithNgContent(),
consts: 3, consts: 3,
@ -1030,6 +1040,7 @@ describe('ViewContainerRef', () => {
class Reprojector { class Reprojector {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Reprojector, type: Reprojector,
encapsulation: ViewEncapsulation.None,
selectors: [['reprojector']], selectors: [['reprojector']],
factory: () => new Reprojector(), factory: () => new Reprojector(),
consts: 2, consts: 2,
@ -1150,6 +1161,7 @@ describe('ViewContainerRef', () => {
class Child { class Child {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Child, type: Child,
encapsulation: ViewEncapsulation.None,
selectors: [['child']], selectors: [['child']],
factory: () => new Child(), factory: () => new Child(),
consts: 2, consts: 2,
@ -1177,6 +1189,7 @@ describe('ViewContainerRef', () => {
name: string = 'bar'; name: string = 'bar';
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Parent, type: Parent,
encapsulation: ViewEncapsulation.None,
selectors: [['parent']], selectors: [['parent']],
factory: () => new Parent(), factory: () => new Parent(),
consts: 5, consts: 5,
@ -1227,6 +1240,7 @@ describe('ViewContainerRef', () => {
show: boolean = true; show: boolean = true;
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: ChildWithView, type: ChildWithView,
encapsulation: ViewEncapsulation.None,
selectors: [['child-with-view']], selectors: [['child-with-view']],
factory: () => new ChildWithView(), factory: () => new ChildWithView(),
consts: 3, consts: 3,
@ -1269,6 +1283,7 @@ describe('ViewContainerRef', () => {
name: string = 'bar'; name: string = 'bar';
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Parent, type: Parent,
encapsulation: ViewEncapsulation.None,
selectors: [['parent']], selectors: [['parent']],
factory: () => new Parent(), factory: () => new Parent(),
consts: 7, consts: 7,
@ -1317,6 +1332,7 @@ describe('ViewContainerRef', () => {
class ChildWithSelector { class ChildWithSelector {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: ChildWithSelector, type: ChildWithSelector,
encapsulation: ViewEncapsulation.None,
selectors: [['child-with-selector']], selectors: [['child-with-selector']],
factory: () => new ChildWithSelector(), factory: () => new ChildWithSelector(),
consts: 4, consts: 4,
@ -1350,6 +1366,7 @@ describe('ViewContainerRef', () => {
name: string = 'bar'; name: string = 'bar';
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Parent, type: Parent,
encapsulation: ViewEncapsulation.None,
selectors: [['parent']], selectors: [['parent']],
factory: () => new Parent(), factory: () => new Parent(),
consts: 5, consts: 5,
@ -1402,6 +1419,7 @@ describe('ViewContainerRef', () => {
name: string = 'bar'; name: string = 'bar';
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: Parent, type: Parent,
encapsulation: ViewEncapsulation.None,
selectors: [['parent']], selectors: [['parent']],
factory: () => new Parent(), factory: () => new Parent(),
consts: 5, consts: 5,
@ -1468,6 +1486,7 @@ describe('ViewContainerRef', () => {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: ComponentWithHooks, type: ComponentWithHooks,
encapsulation: ViewEncapsulation.None,
selectors: [['hooks']], selectors: [['hooks']],
factory: () => new ComponentWithHooks(), factory: () => new ComponentWithHooks(),
consts: 1, consts: 1,
@ -1602,6 +1621,7 @@ describe('ViewContainerRef', () => {
class SomeComponent { class SomeComponent {
static ngComponentDef = defineComponent({ static ngComponentDef = defineComponent({
type: SomeComponent, type: SomeComponent,
encapsulation: ViewEncapsulation.None,
selectors: [['some-comp']], selectors: [['some-comp']],
factory: () => new SomeComponent(), factory: () => new SomeComponent(),
consts: 2, consts: 2,