refactor(dart): Format Dart code

Use the dart formatter to clean up all pure Dart code.

Closes #4832
This commit is contained in:
Tim Blasi
2015-10-20 09:38:14 -07:00
committed by Timothy Blasi
parent 6be95ae88a
commit fd0ba37734
44 changed files with 326 additions and 258 deletions

View File

@ -5,8 +5,10 @@ library angular2;
* *
* This library does not include `bootstrap`. Import `bootstrap.dart` instead. * This library does not include `bootstrap`. Import `bootstrap.dart` instead.
*/ */
export 'package:angular2/core.dart' hide forwardRef, resolveForwardRef, ForwardRefFn; export 'package:angular2/core.dart'
hide forwardRef, resolveForwardRef, ForwardRefFn;
export 'package:angular2/profile.dart'; export 'package:angular2/profile.dart';
export 'package:angular2/lifecycle_hooks.dart'; export 'package:angular2/lifecycle_hooks.dart';
export 'package:angular2/src/core/application_tokens.dart' hide APP_COMPONENT_REF_PROMISE, APP_ID_RANDOM_PROVIDER; export 'package:angular2/src/core/application_tokens.dart'
hide APP_COMPONENT_REF_PROMISE, APP_ID_RANDOM_PROVIDER;
export 'package:angular2/src/core/render/dom/dom_tokens.dart'; export 'package:angular2/src/core/render/dom/dom_tokens.dart';

View File

@ -8,7 +8,8 @@ export 'package:angular2/src/core/pipes.dart';
export 'package:angular2/src/core/facade.dart'; export 'package:angular2/src/core/facade.dart';
// Do not export application for dart. Must import from angular2/bootstrap // Do not export application for dart. Must import from angular2/bootstrap
//export 'package:angular2/src/core/application.dart'; //export 'package:angular2/src/core/application.dart';
export 'package:angular2/src/core/application_ref.dart' hide ApplicationRef_, PlatformRef_; export 'package:angular2/src/core/application_ref.dart'
hide ApplicationRef_, PlatformRef_;
export 'package:angular2/src/core/services.dart'; export 'package:angular2/src/core/services.dart';
export 'package:angular2/src/core/linker.dart'; export 'package:angular2/src/core/linker.dart';
export 'package:angular2/src/core/lifecycle.dart'; export 'package:angular2/src/core/lifecycle.dart';

View File

@ -9,7 +9,8 @@ import 'application_common.dart';
import 'package:angular2/src/core/compiler/compiler.dart'; import 'package:angular2/src/core/compiler/compiler.dart';
import 'package:angular2/src/core/linker/dynamic_component_loader.dart'; import 'package:angular2/src/core/linker/dynamic_component_loader.dart';
export 'package:angular2/src/core/linker/dynamic_component_loader.dart' show ComponentRef; export 'package:angular2/src/core/linker/dynamic_component_loader.dart'
show ComponentRef;
/// Starts an application from a root component. This implementation uses /// Starts an application from a root component. This implementation uses
/// mirrors. Angular 2 transformer automatically replaces this method with a /// mirrors. Angular 2 transformer automatically replaces this method with a

View File

@ -2,7 +2,8 @@ library angular2.src.core.application_static;
import 'dart:async'; import 'dart:async';
import 'application_common.dart'; import 'application_common.dart';
import 'package:angular2/src/core/linker/dynamic_component_loader.dart' show ComponentRef; import 'package:angular2/src/core/linker/dynamic_component_loader.dart'
show ComponentRef;
/// Starts an application from a root component. /// Starts an application from a root component.
/// ///

View File

@ -8,7 +8,8 @@ library change_detection.change_detection_jit_generator;
/// `src/transform/template_compiler/change_detector_codegen.dart` for details. /// `src/transform/template_compiler/change_detector_codegen.dart` for details.
class ChangeDetectorJITGenerator { class ChangeDetectorJITGenerator {
String typeName; String typeName;
ChangeDetectorJITGenerator(definition, changeDetectionUtilVarName, abstractChangeDetectorVarName) {} ChangeDetectorJITGenerator(
definition, changeDetectionUtilVarName, abstractChangeDetectorVarName) {}
generate() { generate() {
throw "Jit Change Detection is not supported in Dart"; throw "Jit Change Detection is not supported in Dart";

View File

@ -216,7 +216,8 @@ class BrowserDomAdapter extends GenericBrowserDomAdapter {
String nodeName(Node el) => el.nodeName; String nodeName(Node el) => el.nodeName;
String nodeValue(Node el) => el.nodeValue; String nodeValue(Node el) => el.nodeValue;
String type(InputElement el) => el.type; String type(InputElement el) => el.type;
Node content(TemplateElement el) => _supportsTemplateElement ? el.content : el; Node content(TemplateElement el) =>
_supportsTemplateElement ? el.content : el;
Node firstChild(el) => el.firstChild; Node firstChild(el) => el.firstChild;
Node nextSibling(Node el) => el.nextNode; Node nextSibling(Node el) => el.nextNode;
Element parentElement(Node el) => el.parent; Element parentElement(Node el) => el.parent;

View File

@ -18,8 +18,7 @@ List<EmulatedCssRule> parseAndEmulateCssRules(String css) {
/// Converts `csslib` [rules] to their emulated counterparts. /// Converts `csslib` [rules] to their emulated counterparts.
List<EmulatedCssRule> emulateRules(Iterable<cssv.TreeNode> rules) { List<EmulatedCssRule> emulateRules(Iterable<cssv.TreeNode> rules) {
return rules return rules.map((cssv.TreeNode node) {
.map((cssv.TreeNode node) {
if (node is cssv.RuleSet) { if (node is cssv.RuleSet) {
if (node.declarationGroup.span.text.isEmpty) { if (node.declarationGroup.span.text.isEmpty) {
// Skip CSS matchers with no bodies // Skip CSS matchers with no bodies
@ -31,9 +30,7 @@ List<EmulatedCssRule> emulateRules(Iterable<cssv.TreeNode> rules) {
} else if (node is cssv.ImportDirective) { } else if (node is cssv.ImportDirective) {
return new EmulatedCssImportRule(node); return new EmulatedCssImportRule(node);
} }
}) }).where((r) => r != null).toList();
.where((r) => r != null)
.toList();
} }
/// Emulates [CSSRule](https://developer.mozilla.org/en-US/docs/Web/API/CSSRule) /// Emulates [CSSRule](https://developer.mozilla.org/en-US/docs/Web/API/CSSRule)
@ -98,8 +95,8 @@ class EmulatedMediaList {
String mediaText; String mediaText;
EmulatedMediaList(cssv.MediaDirective directive) { EmulatedMediaList(cssv.MediaDirective directive) {
this.mediaText = directive.mediaQueries this.mediaText =
.map((q) => q.span.text).join(' and '); directive.mediaQueries.map((q) => q.span.text).join(' and ');
} }
} }

View File

@ -211,7 +211,6 @@ class ListWrapper {
return end < 0 ? max(len + end, 0) : min(end, len); return end < 0 ? max(len + end, 0) : min(end, len);
} }
static maximum(List l, fn(item)) { static maximum(List l, fn(item)) {
if (l.length == 0) { if (l.length == 0) {
return null; return null;

View File

@ -20,11 +20,18 @@ class WrappedException extends Error {
final originalStack; final originalStack;
WrappedException( WrappedException(
[this.wrapperMessage, this.originalException, this.originalStack, this.context]); [this.wrapperMessage,
this.originalException,
this.originalStack,
this.context]);
get message { return ExceptionHandler.exceptionToString(this); } get message {
return ExceptionHandler.exceptionToString(this);
}
String toString() { return this.message; } String toString() {
return this.message;
}
} }
Error makeTypeError([String message = ""]) { Error makeTypeError([String message = ""]) {

View File

@ -6,8 +6,7 @@ import 'package:angular2/src/core/facade/async.dart';
/** /**
* See query_list.ts * See query_list.ts
*/ */
class QueryList<T> extends Object class QueryList<T> extends Object with IterableMixin<T> {
with IterableMixin<T> {
List<T> _results = []; List<T> _results = [];
EventEmitter _emitter = new EventEmitter(); EventEmitter _emitter = new EventEmitter();

View File

@ -14,13 +14,17 @@ export './metadata/view.dart' hide VIEW_ENCAPSULATION_VALUES;
* See: [DirectiveMetadata] for docs. * See: [DirectiveMetadata] for docs.
*/ */
class Directive extends DirectiveMetadata { class Directive extends DirectiveMetadata {
const Directive({String selector, List<String> inputs, const Directive(
{String selector,
List<String> inputs,
List<String> outputs, List<String> outputs,
@deprecated List<String> properties, @deprecated List<String> properties,
@deprecated List<String> events, @deprecated List<String> events,
Map<String, String> host, Map<String, String> host,
@deprecated List bindings, @deprecated List bindings,
List providers, String exportAs, String moduleId, List providers,
String exportAs,
String moduleId,
Map<String, dynamic> queries}) Map<String, dynamic> queries})
: super( : super(
selector: selector, selector: selector,
@ -40,19 +44,28 @@ class Directive extends DirectiveMetadata {
* See: [ComponentMetadata] for docs. * See: [ComponentMetadata] for docs.
*/ */
class Component extends ComponentMetadata { class Component extends ComponentMetadata {
const Component({String selector, List<String> inputs, const Component(
{String selector,
List<String> inputs,
List<String> outputs, List<String> outputs,
@deprecated List<String> properties, @deprecated List<String> properties,
@deprecated List<String> events, @deprecated List<String> events,
Map<String, String> host, Map<String, String> host,
@deprecated List bindings, List providers, String exportAs, String moduleId, @deprecated List bindings,
List providers,
String exportAs,
String moduleId,
Map<String, dynamic> queries, Map<String, dynamic> queries,
@deprecated List viewBindings, @deprecated List viewBindings,
List viewProviders, ChangeDetectionStrategy changeDetection, List viewProviders,
String templateUrl, String template, dynamic directives, ChangeDetectionStrategy changeDetection,
dynamic pipes, ViewEncapsulation encapsulation, List<String> styles, String templateUrl,
List<String> styleUrls String template,
}) dynamic directives,
dynamic pipes,
ViewEncapsulation encapsulation,
List<String> styles,
List<String> styleUrls})
: super( : super(
selector: selector, selector: selector,
inputs: inputs, inputs: inputs,
@ -74,16 +87,20 @@ class Component extends ComponentMetadata {
pipes: pipes, pipes: pipes,
encapsulation: encapsulation, encapsulation: encapsulation,
styles: styles, styles: styles,
styleUrls: styleUrls styleUrls: styleUrls);
);
} }
/** /**
* See: [ViewMetadata] for docs. * See: [ViewMetadata] for docs.
*/ */
class View extends ViewMetadata { class View extends ViewMetadata {
const View({String templateUrl, String template, dynamic directives, const View(
dynamic pipes, ViewEncapsulation encapsulation, List<String> styles, {String templateUrl,
String template,
dynamic directives,
dynamic pipes,
ViewEncapsulation encapsulation,
List<String> styles,
List<String> styleUrls}) List<String> styleUrls})
: super( : super(
templateUrl: templateUrl, templateUrl: templateUrl,
@ -121,7 +138,8 @@ class Query extends QueryMetadata {
* See: [ContentChildrenMetadata] for docs. * See: [ContentChildrenMetadata] for docs.
*/ */
class ContentChildren extends ContentChildrenMetadata { class ContentChildren extends ContentChildrenMetadata {
const ContentChildren(dynamic /*Type | string*/ selector, {bool descendants: false}) const ContentChildren(dynamic /*Type | string*/ selector,
{bool descendants: false})
: super(selector, descendants: descendants); : super(selector, descendants: descendants);
} }
@ -129,8 +147,7 @@ class ContentChildren extends ContentChildrenMetadata {
* See: [ContentChildMetadata] for docs. * See: [ContentChildMetadata] for docs.
*/ */
class ContentChild extends ContentChildMetadata { class ContentChild extends ContentChildMetadata {
const ContentChild(dynamic /*Type | string*/ selector) const ContentChild(dynamic /*Type | string*/ selector) : super(selector);
: super(selector);
} }
/** /**
@ -145,40 +162,35 @@ class ViewQuery extends ViewQueryMetadata {
* See: [ViewChildrenMetadata] for docs. * See: [ViewChildrenMetadata] for docs.
*/ */
class ViewChildren extends ViewChildrenMetadata { class ViewChildren extends ViewChildrenMetadata {
const ViewChildren(dynamic /*Type | string*/ selector) const ViewChildren(dynamic /*Type | string*/ selector) : super(selector);
: super(selector);
} }
/** /**
* See: [ViewChildMetadata] for docs. * See: [ViewChildMetadata] for docs.
*/ */
class ViewChild extends ViewChildMetadata { class ViewChild extends ViewChildMetadata {
const ViewChild(dynamic /*Type | string*/ selector) const ViewChild(dynamic /*Type | string*/ selector) : super(selector);
: super(selector);
} }
/** /**
* See: [InputMetadata] for docs. * See: [InputMetadata] for docs.
*/ */
class Input extends InputMetadata { class Input extends InputMetadata {
const Input([String bindingPropertyName]) const Input([String bindingPropertyName]) : super(bindingPropertyName);
: super(bindingPropertyName);
} }
/** /**
* See: [OutputMetadata] for docs. * See: [OutputMetadata] for docs.
*/ */
class Output extends OutputMetadata { class Output extends OutputMetadata {
const Output([String bindingPropertyName]) const Output([String bindingPropertyName]) : super(bindingPropertyName);
: super(bindingPropertyName);
} }
/** /**
* See: [HostBindingMetadata] for docs. * See: [HostBindingMetadata] for docs.
*/ */
class HostBinding extends HostBindingMetadata { class HostBinding extends HostBindingMetadata {
const HostBinding([String hostPropertyName]) const HostBinding([String hostPropertyName]) : super(hostPropertyName);
: super(hostPropertyName);
} }
/** /**

View File

@ -1,12 +1,12 @@
library angular2.src.core.platform_bindings; library angular2.src.core.platform_bindings;
import 'package:angular2/core.dart'; import 'package:angular2/core.dart';
import 'package:angular2/src/core/facade/exceptions.dart'; import 'package:angular2/src/core/facade/exceptions.dart';
import 'package:angular2/src/core/dom/dom_adapter.dart'; import 'package:angular2/src/core/dom/dom_adapter.dart';
exceptionFactory() => new ExceptionHandler(DOM, true); exceptionFactory() => new ExceptionHandler(DOM, true);
const EXCEPTION_PROVIDER = const Binding(ExceptionHandler, toFactory: exceptionFactory, deps: const []); const EXCEPTION_PROVIDER = const Binding(ExceptionHandler,
toFactory: exceptionFactory, deps: const []);
const EXCEPTION_BINDING = EXCEPTION_PROVIDER; const EXCEPTION_BINDING = EXCEPTION_PROVIDER;

View File

@ -277,7 +277,8 @@ class ReflectionCapabilities implements PlatformReflectionCapabilities {
List _interfacesFromMirror(classMirror) { List _interfacesFromMirror(classMirror) {
return classMirror.superinterfaces.map((si) => si.reflectedType).toList() return classMirror.superinterfaces.map((si) => si.reflectedType).toList()
..addAll(classMirror.superclass == null ? [] ..addAll(classMirror.superclass == null
? []
: _interfacesFromMirror(classMirror.superclass)); : _interfacesFromMirror(classMirror.superclass));
} }

View File

@ -10,8 +10,17 @@ import 'dart:js' as js;
// Proxies a Dart function that accepts up to 10 parameters. // Proxies a Dart function that accepts up to 10 parameters.
js.JsFunction _jsFunction(Function fn) { js.JsFunction _jsFunction(Function fn) {
const Object X = __varargSentinel; const Object X = __varargSentinel;
return new js.JsFunction.withThis((thisArg, [o1 = X, o2 = X, o3 = X, o4 = X, return new js.JsFunction.withThis((thisArg,
o5 = X, o6 = X, o7 = X, o8 = X, o9 = X, o10 = X]) { [o1 = X,
o2 = X,
o3 = X,
o4 = X,
o5 = X,
o6 = X,
o7 = X,
o8 = X,
o9 = X,
o10 = X]) {
return __invokeFn(fn, o1, o2, o3, o4, o5, o6, o7, o8, o9, o10); return __invokeFn(fn, o1, o2, o3, o4, o5, o6, o7, o8, o9, o10);
}); });
} }
@ -96,12 +105,12 @@ class BrowserGetTestability implements GetTestability {
var jsRegistry = js.context['ngTestabilityRegistries']; var jsRegistry = js.context['ngTestabilityRegistries'];
if (jsRegistry == null) { if (jsRegistry == null) {
js.context['ngTestabilityRegistries'] = jsRegistry = new js.JsArray(); js.context['ngTestabilityRegistries'] = jsRegistry = new js.JsArray();
js.context['getAngularTestability'] = _jsify((Element elem, js.context['getAngularTestability'] =
[bool findInAncestors = true]) { _jsify((Element elem, [bool findInAncestors = true]) {
var registry = js.context['ngTestabilityRegistries']; var registry = js.context['ngTestabilityRegistries'];
for (int i = 0; i < registry.length; i++) { for (int i = 0; i < registry.length; i++) {
var result = registry[i].callMethod( var result = registry[i]
'getAngularTestability', [elem, findInAncestors]); .callMethod('getAngularTestability', [elem, findInAncestors]);
if (result != null) return result; if (result != null) return result;
} }
throw 'Could not find testability for element.'; throw 'Could not find testability for element.';
@ -122,8 +131,8 @@ class BrowserGetTestability implements GetTestability {
js.JsObject _createRegistry(TestabilityRegistry registry) { js.JsObject _createRegistry(TestabilityRegistry registry) {
var object = new js.JsObject(js.context['Object']); var object = new js.JsObject(js.context['Object']);
object['getAngularTestability'] = _jsify((Element elem, object['getAngularTestability'] =
bool findInAncestors) { _jsify((Element elem, bool findInAncestors) {
var testability = registry.findTestabilityInTree(elem, findInAncestors); var testability = registry.findTestabilityInTree(elem, findInAncestors);
return testability == null return testability == null
? null ? null

View File

@ -214,7 +214,6 @@ class NgZone {
try { try {
_inVmTurnDone = true; _inVmTurnDone = true;
parent.run(_innerZone, _onTurnDone); parent.run(_innerZone, _onTurnDone);
} finally { } finally {
_inVmTurnDone = false; _inVmTurnDone = false;
_hasExecutedCodeInInnerZone = false; _hasExecutedCodeInInnerZone = false;

View File

@ -9,6 +9,7 @@ RouteDefinition normalizeRouteConfig(RouteDefinition config) {
void assertComponentExists(Type component, String path) { void assertComponentExists(Type component, String path) {
if (component == null) { if (component == null) {
throw new BaseException('Component for route "${path}" is not defined, or is not a class.'); throw new BaseException(
'Component for route "${path}" is not defined, or is not a class.');
} }
} }

View File

@ -67,7 +67,6 @@ void testSetup() {
}, priority: 1); }, priority: 1);
} }
/** /**
* Allows overriding default bindings defined in test_injector.js. * Allows overriding default bindings defined in test_injector.js.
* *
@ -93,14 +92,16 @@ void beforeEachBindings(Function fn) {
} }
void beforeEach(fn) { void beforeEach(fn) {
if (fn is! FunctionWithParamTokens) fn = new FunctionWithParamTokens([], fn, false); if (fn is! FunctionWithParamTokens) fn =
new FunctionWithParamTokens([], fn, false);
gns.beforeEach(() { gns.beforeEach(() {
fn.execute(_injector); fn.execute(_injector);
}); });
} }
void _it(gnsFn, name, fn) { void _it(gnsFn, name, fn) {
if (fn is! FunctionWithParamTokens) fn = new FunctionWithParamTokens([], fn, false); if (fn is! FunctionWithParamTokens) fn =
new FunctionWithParamTokens([], fn, false);
gnsFn(name, () { gnsFn(name, () {
_inIt = true; _inIt = true;
fn.execute(_injector); fn.execute(_injector);
@ -139,7 +140,9 @@ class SpyObject extends gns.SpyObject {
_spyFuncs.putIfAbsent(funcName, () => new SpyFunction(funcName)); _spyFuncs.putIfAbsent(funcName, () => new SpyFunction(funcName));
void prop(String funcName, value) { void prop(String funcName, value) {
_spyFuncs.putIfAbsent("get:${funcName}", () => new SpyFunction(funcName)).andReturn(value); _spyFuncs
.putIfAbsent("get:${funcName}", () => new SpyFunction(funcName))
.andReturn(value);
} }
static stub([object = null, config = null, overrides = null]) { static stub([object = null, config = null, overrides = null]) {

View File

@ -1,7 +1,8 @@
library angular2.src.tools.tools; library angular2.src.tools.tools;
import 'dart:js'; import 'dart:js';
import 'package:angular2/src/core/linker/dynamic_component_loader.dart' show ComponentRef; import 'package:angular2/src/core/linker/dynamic_component_loader.dart'
show ComponentRef;
import 'common_tools.dart' show AngularTools; import 'common_tools.dart' show AngularTools;
/** /**

View File

@ -5,7 +5,8 @@ import "package:angular2/src/web_workers/worker/application_common.dart"
show bootstrapWebWorkerCommon; show bootstrapWebWorkerCommon;
import "package:angular2/src/core/facade/async.dart" show Future; import "package:angular2/src/core/facade/async.dart" show Future;
import "package:angular2/src/core/facade/lang.dart" show Type, BaseException; import "package:angular2/src/core/facade/lang.dart" show Type, BaseException;
import "package:angular2/src/core/linker/dynamic_component_loader.dart" show ComponentRef; import "package:angular2/src/core/linker/dynamic_component_loader.dart"
show ComponentRef;
import "dart:isolate"; import "dart:isolate";
import "dart:async"; import "dart:async";
import 'dart:core'; import 'dart:core';
@ -22,8 +23,7 @@ import 'package:angular2/src/core/dom/webworker_adapter.dart';
* bootstrap() in a regular Angular application * bootstrap() in a regular Angular application
* See the bootstrap() docs for more details. * See the bootstrap() docs for more details.
*/ */
Future<ComponentRef> bootstrapWebWorker( Future<ComponentRef> bootstrapWebWorker(SendPort replyTo, Type appComponentType,
SendPort replyTo, Type appComponentType,
[List<dynamic> componentInjectableBindings = null]) { [List<dynamic> componentInjectableBindings = null]) {
WebWorkerDomAdapter.makeCurrent(); WebWorkerDomAdapter.makeCurrent();
ReceivePort rPort = new ReceivePort(); ReceivePort rPort = new ReceivePort();

View File

@ -24,7 +24,9 @@ main(List args, SendPort replyPort) {
var timeStamp = new DateTime.now().millisecondsSinceEpoch; var timeStamp = new DateTime.now().millisecondsSinceEpoch;
dynamic callModule(dynamic data) { return data.map( (a) => a+1); } dynamic callModule(dynamic data) {
return data.map((a) => a + 1);
}
evalModule(String moduleSource, List<List<String>> imports, List args) { evalModule(String moduleSource, List<List<String>> imports, List args) {
String source = createIsolateSource(moduleSource, imports); String source = createIsolateSource(moduleSource, imports);
@ -39,7 +41,10 @@ evalModule(String moduleSource, List<List<String>> imports, List args) {
// With this, spawning multiple isolates gets faster as Darts does not // With this, spawning multiple isolates gets faster as Darts does not
// reload the files from the server. // reload the files from the server.
var packageRoot = Uri.parse('/packages_${timeStamp}'); var packageRoot = Uri.parse('/packages_${timeStamp}');
return Isolate.spawnUri(toDartDataUri(source), args, receivePort.sendPort, packageRoot: packageRoot).then( (isolate) { return Isolate
.spawnUri(toDartDataUri(source), args, receivePort.sendPort,
packageRoot: packageRoot)
.then((isolate) {
RawReceivePort errorPort; RawReceivePort errorPort;
errorPort = new RawReceivePort((message) { errorPort = new RawReceivePort((message) {
completer.completeError(message); completer.completeError(message);

View File

@ -2,7 +2,8 @@ library angular2.test.directives.observable_list_iterable_diff_spec;
import 'package:angular2/testing_internal.dart'; import 'package:angular2/testing_internal.dart';
import 'package:observe/observe.dart' show ObservableList; import 'package:observe/observe.dart' show ObservableList;
import 'package:angular2/core.dart' show ObservableListDiffFactory, ChangeDetectorRef; import 'package:angular2/core.dart'
show ObservableListDiffFactory, ChangeDetectorRef;
@proxy @proxy
class SpyChangeDetectorRef extends SpyObject implements ChangeDetectorRef { class SpyChangeDetectorRef extends SpyObject implements ChangeDetectorRef {

View File

@ -7,96 +7,106 @@ import 'package:angular2/src/core/linker/interfaces.dart';
main() { main() {
describe('Create DirectiveMetadata', () { describe('Create DirectiveMetadata', () {
describe('lifecycle', () { describe('lifecycle', () {
describe("onChanges", () { describe("onChanges", () {
it("should be true when the directive has the onChanges method", () { it("should be true when the directive has the onChanges method", () {
expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveImplementingOnChanges)) expect(hasLifecycleHook(
LifecycleHooks.OnChanges, DirectiveImplementingOnChanges))
.toBe(true); .toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveNoHooks)).toBe(false); expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveNoHooks))
.toBe(false);
}); });
}); });
describe("onDestroy", () { describe("onDestroy", () {
it("should be true when the directive has the onDestroy method", () { it("should be true when the directive has the onDestroy method", () {
expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveImplementingOnDestroy)) expect(hasLifecycleHook(
LifecycleHooks.OnDestroy, DirectiveImplementingOnDestroy))
.toBe(true); .toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveNoHooks)).toBe(false); expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveNoHooks))
.toBe(false);
}); });
}); });
describe("onInit", () { describe("onInit", () {
it("should be true when the directive has the onInit method", () { it("should be true when the directive has the onInit method", () {
expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveImplementingOnInit)) expect(hasLifecycleHook(
.toBe(true); LifecycleHooks.OnInit, DirectiveImplementingOnInit)).toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveNoHooks)).toBe(false); expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveNoHooks))
.toBe(false);
}); });
}); });
describe("doCheck", () { describe("doCheck", () {
it("should be true when the directive has the doCheck method", () { it("should be true when the directive has the doCheck method", () {
expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveImplementingOnCheck)) expect(hasLifecycleHook(
.toBe(true); LifecycleHooks.DoCheck, DirectiveImplementingOnCheck)).toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveNoHooks)).toBe(false); expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveNoHooks))
.toBe(false);
}); });
}); });
describe("afterContentInit", () { describe("afterContentInit", () {
it("should be true when the directive has the afterContentInit method", () { it("should be true when the directive has the afterContentInit method",
expect(hasLifecycleHook(LifecycleHooks.AfterContentInit, DirectiveImplementingAfterContentInit)) () {
.toBe(true); expect(hasLifecycleHook(LifecycleHooks.AfterContentInit,
DirectiveImplementingAfterContentInit)).toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.AfterContentInit, DirectiveNoHooks)) expect(hasLifecycleHook(
.toBe(false); LifecycleHooks.AfterContentInit, DirectiveNoHooks)).toBe(false);
}); });
}); });
describe("afterContentChecked", () { describe("afterContentChecked", () {
it("should be true when the directive has the afterContentChecked method", () { it("should be true when the directive has the afterContentChecked method",
expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked, DirectiveImplementingAfterContentChecked)) () {
.toBe(true); expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked,
DirectiveImplementingAfterContentChecked)).toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked, DirectiveNoHooks)) expect(hasLifecycleHook(
LifecycleHooks.AfterContentChecked, DirectiveNoHooks))
.toBe(false); .toBe(false);
}); });
}); });
describe("afterViewInit", () { describe("afterViewInit", () {
it("should be true when the directive has the afterViewInit method", () { it("should be true when the directive has the afterViewInit method",
expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, DirectiveImplementingAfterViewInit)) () {
.toBe(true); expect(hasLifecycleHook(LifecycleHooks.AfterViewInit,
DirectiveImplementingAfterViewInit)).toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, DirectiveNoHooks)).toBe(false); expect(hasLifecycleHook(
LifecycleHooks.AfterViewInit, DirectiveNoHooks)).toBe(false);
}); });
}); });
describe("afterViewChecked", () { describe("afterViewChecked", () {
it("should be true when the directive has the afterViewChecked method", () { it("should be true when the directive has the afterViewChecked method",
expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked, DirectiveImplementingAfterViewChecked)) () {
.toBe(true); expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked,
DirectiveImplementingAfterViewChecked)).toBe(true);
}); });
it("should be false otherwise", () { it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked, DirectiveNoHooks)) expect(hasLifecycleHook(
.toBe(false); LifecycleHooks.AfterViewChecked, DirectiveNoHooks)).toBe(false);
}); });
}); });
}); });

View File

@ -149,7 +149,8 @@ main() {
.createAsync(Dummy) .createAsync(Dummy)
.then((tc) { .then((tc) {
tc.detectChanges(); tc.detectChanges();
var cmp = tc.debugElement.componentViewChildren[0].inject(OnChangeComponent); var cmp = tc.debugElement.componentViewChildren[0]
.inject(OnChangeComponent);
expect(cmp.prop).toEqual('hello'); expect(cmp.prop).toEqual('hello');
expect(cmp.changes.containsKey('prop')).toEqual(true); expect(cmp.changes.containsKey('prop')).toEqual(true);
async.done(); async.done();
@ -171,12 +172,14 @@ main() {
directives: [ComponentWithObservableList])) directives: [ComponentWithObservableList]))
.createAsync(Dummy) .createAsync(Dummy)
.then((tc) { .then((tc) {
tc.debugElement.componentInstance.value = new ObservableList.from([1, 2]); tc.debugElement.componentInstance.value =
new ObservableList.from([1, 2]);
tc.detectChanges(); tc.detectChanges();
expect(log.result()).toEqual("check"); expect(log.result()).toEqual("check");
expect(asNativeElements(tc.debugElement.componentViewChildren)).toHaveText('12'); expect(asNativeElements(tc.debugElement.componentViewChildren))
.toHaveText('12');
tc.detectChanges(); tc.detectChanges();
@ -195,7 +198,8 @@ main() {
.toHaveText('123'); .toHaveText('123');
// we replaced the list => a check // we replaced the list => a check
tc.debugElement.componentInstance.value = new ObservableList.from([5, 6, 7]); tc.debugElement.componentInstance.value =
new ObservableList.from([5, 6, 7]);
tc.detectChanges(); tc.detectChanges();
@ -264,9 +268,7 @@ class NoPropertyAccess {
final model = new PropModel(); final model = new PropModel();
} }
@Component( @Component(selector: 'on-change', inputs: const ['prop'])
selector: 'on-change',
inputs: const ['prop'])
@View(template: '') @View(template: '')
class OnChangeComponent implements OnChanges { class OnChangeComponent implements OnChanges {
Map changes; Map changes;
@ -297,8 +299,7 @@ class ComponentWithObservableList {
Iterable list; Iterable list;
} }
@Directive( @Directive(selector: 'directive-logging-checks')
selector: 'directive-logging-checks')
class DirectiveLoggingChecks implements DoCheck { class DirectiveLoggingChecks implements DoCheck {
Log log; Log log;

View File

@ -83,7 +83,8 @@ class SpyProtoViewFactory extends SpyObject implements ProtoViewFactory {
} }
@proxy @proxy
class SpyProtoElementInjector extends SpyObject implements ProtoElementInjector { class SpyProtoElementInjector extends SpyObject
implements ProtoElementInjector {
noSuchMethod(m) => super.noSuchMethod(m); noSuchMethod(m) => super.noSuchMethod(m);
} }
@ -108,7 +109,8 @@ class SpyXHR extends SpyObject implements XHR {
} }
@proxy @proxy
class SpyRenderEventDispatcher extends SpyObject implements RenderEventDispatcher { class SpyRenderEventDispatcher extends SpyObject
implements RenderEventDispatcher {
noSuchMethod(m) => super.noSuchMethod(m); noSuchMethod(m) => super.noSuchMethod(m);
} }

View File

@ -89,8 +89,8 @@ class LibraryInfo {
} }
} }
Iterable<Symbol> _getUsedSymbols(DeclarationMirror decl, seenDecls, path, onlyType) { Iterable<Symbol> _getUsedSymbols(
DeclarationMirror decl, seenDecls, path, onlyType) {
if (seenDecls.containsKey(decl.qualifiedName)) return []; if (seenDecls.containsKey(decl.qualifiedName)) return [];
seenDecls[decl.qualifiedName] = true; seenDecls[decl.qualifiedName] = true;
@ -111,13 +111,11 @@ Iterable<Symbol> _getUsedSymbols(DeclarationMirror decl, seenDecls, path, onlyTy
used.addAll(_getUsedSymbols(p.type, seenDecls, path, onlyType)); used.addAll(_getUsedSymbols(p.type, seenDecls, path, onlyType));
}); });
used.addAll(_getUsedSymbols(ftdecl.returnType, seenDecls, path, onlyType)); used.addAll(_getUsedSymbols(ftdecl.returnType, seenDecls, path, onlyType));
} } else if (decl is TypeMirror) {
else if (decl is TypeMirror) {
var tdecl = decl; var tdecl = decl;
used.add(tdecl.qualifiedName); used.add(tdecl.qualifiedName);
} }
if (!onlyType) { if (!onlyType) {
if (decl is ClassMirror) { if (decl is ClassMirror) {
ClassMirror cdecl = decl; ClassMirror cdecl = decl;
@ -128,13 +126,11 @@ Iterable<Symbol> _getUsedSymbols(DeclarationMirror decl, seenDecls, path, onlyTy
print("Got error [$e] when visiting $d\n$s"); print("Got error [$e] when visiting $d\n$s");
} }
}); });
} }
if (decl is MethodMirror) { if (decl is MethodMirror) {
MethodMirror mdecl = decl; MethodMirror mdecl = decl;
if (mdecl.parameters != null) if (mdecl.parameters != null) mdecl.parameters.forEach((p) {
mdecl.parameters.forEach((p) {
used.addAll(_getUsedSymbols(p.type, seenDecls, path, true)); used.addAll(_getUsedSymbols(p.type, seenDecls, path, true));
}); });
used.addAll(_getUsedSymbols(mdecl.returnType, seenDecls, path, true)); used.addAll(_getUsedSymbols(mdecl.returnType, seenDecls, path, true));
@ -209,6 +205,5 @@ LibraryInfo extractSymbols(LibraryMirror lib, [String printPrefix = ""]) {
return new LibraryInfo(exportedSymbols, used); return new LibraryInfo(exportedSymbols, used);
} }
var _SYMBOL_NAME = new RegExp('"(.*)"'); var _SYMBOL_NAME = new RegExp('"(.*)"');
unwrapSymbol(sym) => _SYMBOL_NAME.firstMatch(sym.toString()).group(1); unwrapSymbol(sym) => _SYMBOL_NAME.firstMatch(sym.toString()).group(1);

View File

@ -18,6 +18,7 @@ void expectSinkSendsEncodedJson(SpyObject socket, MessageBusSink sink,
} }
void expectMessageEquality(String message, Map expectedData, String channel) { void expectMessageEquality(String message, Map expectedData, String channel) {
expect(JSON.decode(message)) expect(JSON.decode(message)).toEqual([
.toEqual([{'channel': channel, 'message': expectedData}]); {'channel': channel, 'message': expectedData}
]);
} }

View File

@ -79,8 +79,9 @@ main() {
var random = new Random(); var random = new Random();
for (var i = 0; i < numMessages; i++) { for (var i = 0; i < numMessages; i++) {
var message = {'value': random.nextInt(MAX)}; var message = {'value': random.nextInt(MAX)};
messageHistory messageHistory.add(JSON.encode([
.add(JSON.encode([{'channel': CHANNEL, 'message': message}])); {'channel': CHANNEL, 'message': message}
]));
} }
// copy the message history to ensure the test fails if the wrapper modifies the list // copy the message history to ensure the test fails if the wrapper modifies the list
return new List.from(messageHistory); return new List.from(messageHistory);
@ -189,8 +190,7 @@ main() {
messageHistory, resultMarkers, result.socket); messageHistory, resultMarkers, result.socket);
socket.setPrimary(true); socket.setPrimary(true);
var source = var source = new MultiClientServerMessageBusSource();
new MultiClientServerMessageBusSource();
source.onResult.listen((result) => async.done()); source.onResult.listen((result) => async.done());
source.initChannel(CHANNEL, false); source.initChannel(CHANNEL, false);
source.addConnection(socket); source.addConnection(socket);

View File

@ -94,8 +94,9 @@ main() {
async.done(); async.done();
}); });
controller controller.add(JSON.encode([
.add(JSON.encode([{'channel': CHANNEL, 'message': MESSAGE}])); {'channel': CHANNEL, 'message': MESSAGE}
]));
})); }));
}); });
} }

View File

@ -50,8 +50,9 @@ main() {
}); });
var event = new SpyMessageEvent(); var event = new SpyMessageEvent();
event.spy("get:data").andCallFake( event.spy("get:data").andCallFake(() => JSON.encode([
() => JSON.encode([{'channel': CHANNEL, 'message': MESSAGE}])); {'channel': CHANNEL, 'message': MESSAGE}
]));
controller.add(event); controller.add(event);
})); }));
}); });

View File

@ -10,7 +10,8 @@ class MockEventEmitter extends EventEmitter {
@override @override
StreamSubscription listen(void onData(dynamic line), StreamSubscription listen(void onData(dynamic line),
{void onError(Error error), void onDone(), bool cancelOnError}) { {void onError(Error error), void onDone(), bool cancelOnError}) {
return controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); return controller.stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
} }
@override @override

View File

@ -7,5 +7,3 @@ import 'package:angular2/testing_internal.dart';
class SpyMessageBroker extends SpyObject implements ClientMessageBroker { class SpyMessageBroker extends SpyObject implements ClientMessageBroker {
noSuchMethod(m) => super.noSuchMethod(m); noSuchMethod(m) => super.noSuchMethod(m);
} }

View File

@ -209,7 +209,8 @@ class _DirectiveMetadataVisitor extends Object
'Found unexpected "$node".', 'Found unexpected "$node".',
'$node' /* source */); '$node' /* source */);
} }
_viewTemplate = new _CompileTemplateMetadataVisitor().visitAnnotation(node); _viewTemplate =
new _CompileTemplateMetadataVisitor().visitAnnotation(node);
} }
// Annotation we do not recognize - no need to visit. // Annotation we do not recognize - no need to visit.

View File

@ -47,7 +47,8 @@ const _ON_AFTER_CONTENT_INIT_INTERFACES = const [
'AfterContentInit', 'package:angular2/src/core/linker/interfaces.dart') 'AfterContentInit', 'package:angular2/src/core/linker/interfaces.dart')
]; ];
const _ON_AFTER_CONTENT_CHECKED_INTERFACES = const [ const _ON_AFTER_CONTENT_CHECKED_INTERFACES = const [
const ClassDescriptor('AfterContentChecked', 'package:angular2/angular2.dart'), const ClassDescriptor(
'AfterContentChecked', 'package:angular2/angular2.dart'),
const ClassDescriptor( const ClassDescriptor(
'AfterContentChecked', 'package:angular2/lifecycle_hooks.dart'), 'AfterContentChecked', 'package:angular2/lifecycle_hooks.dart'),
const ClassDescriptor( const ClassDescriptor(
@ -112,12 +113,13 @@ class InterfaceMatcher extends ClassMatcherBase {
firstMatch(typeName, assetId), _ON_AFTER_CONTENT_INIT_INTERFACES); firstMatch(typeName, assetId), _ON_AFTER_CONTENT_INIT_INTERFACES);
/// Checks if an [Identifier] implements [AfterContentChecked]. /// Checks if an [Identifier] implements [AfterContentChecked].
bool isAfterContentChecked(Identifier typeName, AssetId assetId) => implements( bool isAfterContentChecked(Identifier typeName, AssetId assetId) =>
implements(
firstMatch(typeName, assetId), _ON_AFTER_CONTENT_CHECKED_INTERFACES); firstMatch(typeName, assetId), _ON_AFTER_CONTENT_CHECKED_INTERFACES);
/// Checks if an [Identifier] implements [AfterViewInit]. /// Checks if an [Identifier] implements [AfterViewInit].
bool isAfterViewInit(Identifier typeName, AssetId assetId) => implements( bool isAfterViewInit(Identifier typeName, AssetId assetId) =>
firstMatch(typeName, assetId), _ON_AFTER_VIEW_INIT_INTERFACES); implements(firstMatch(typeName, assetId), _ON_AFTER_VIEW_INIT_INTERFACES);
/// Checks if an [Identifier] implements [AfterViewChecked]. /// Checks if an [Identifier] implements [AfterViewChecked].
bool isAfterViewChecked(Identifier typeName, AssetId assetId) => implements( bool isAfterViewChecked(Identifier typeName, AssetId assetId) => implements(

View File

@ -40,8 +40,14 @@ class RegisteredType {
factory RegisteredType.fromMethodInvocation(MethodInvocation registerMethod) { factory RegisteredType.fromMethodInvocation(MethodInvocation registerMethod) {
var visitor = new _ParseRegisterTypeVisitor(); var visitor = new _ParseRegisterTypeVisitor();
registerMethod.accept(visitor); registerMethod.accept(visitor);
return new RegisteredType._(visitor.typeName, registerMethod, visitor.info, return new RegisteredType._(
visitor.factoryFn, visitor.parameters, visitor.annotations, visitor.propMetadata); visitor.typeName,
registerMethod,
visitor.info,
visitor.factoryFn,
visitor.parameters,
visitor.annotations,
visitor.propMetadata);
} }
} }

View File

@ -45,8 +45,8 @@ Uri toAssetScheme(Uri absoluteUri) {
if (absoluteUri == null) throw new ArgumentError.notNull('absoluteUri'); if (absoluteUri == null) throw new ArgumentError.notNull('absoluteUri');
if (!absoluteUri.isAbsolute) { if (!absoluteUri.isAbsolute) {
throw new ArgumentError.value( throw new ArgumentError.value(absoluteUri.toString(), 'absoluteUri',
absoluteUri.toString(), 'absoluteUri', 'Value passed must be an absolute uri'); 'Value passed must be an absolute uri');
} }
if (absoluteUri.scheme == 'asset') { if (absoluteUri.scheme == 'asset') {
if (absoluteUri.pathSegments.length < 3) { if (absoluteUri.pathSegments.length < 3) {

View File

@ -10,8 +10,12 @@ void initReflector(reflector) {
reflector reflector
..registerType( ..registerType(
ToolTip, ToolTip,
new ReflectionInfo(const [ new ReflectionInfo(
const Directive( const [const Directive(selector: '[tool-tip]')],
selector: '[tool-tip]') const [],
], const [], () => new ToolTip(), null, const {'queryField': const [const ContentChild('child')]})); () => new ToolTip(),
null,
const {
'queryField': const [const ContentChild('child')]
}));
} }

View File

@ -10,9 +10,13 @@ void initReflector(reflector) {
reflector reflector
..registerType( ..registerType(
ToolTip, ToolTip,
new ReflectionInfo(const [ new ReflectionInfo(
const Directive( const [const Directive(selector: '[tool-tip]')],
selector: '[tool-tip]') const [],
], const [], () => new ToolTip(), null, const {'queryField': const [const ContentChild('child')]})) () => new ToolTip(),
null,
const {
'queryField': const [const ContentChild('child')]
}))
..registerSetters({'queryField': (o, v) => o.queryField = v}); ..registerSetters({'queryField': (o, v) => o.queryField = v});
} }