diff --git a/gulpfile.js b/gulpfile.js index eaa8b2eec7..9863586bab 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -43,19 +43,21 @@ if (cliArgs.projects) { // --projects=angular2 => {angular2: true} var allProjects = 'angular1_router,angular2,benchmarks,benchmarks_external,benchpress,playground,payload_tests,bundle_deps'; -var cliArgsProjects = (cliArgs.projects || allProjects).split(',').reduce((map, projectName) => { - map[projectName] = true; - return map; -}, {}); +var cliArgsProjects = (cliArgs.projects || allProjects) + .split(',') + .reduce((map, projectName) => { + map[projectName] = true; + return map; + }, {}); var generateEs6 = !cliArgs.projects; function printModulesWarning() { if (!cliArgs.projects && !process.env.CI) { // if users didn't specify projects to build, tell them why and how they should console.warn( - 'Pro Tip: Did you know that you can speed up your build by specifying project name(s)?'); - console.warn(' It\'s like pressing the turbo button in the old days, but better!'); - console.warn(' Examples: --project=angular2 or --project=angular2'); + "Pro Tip: Did you know that you can speed up your build by specifying project name(s)?"); + console.warn(" It's like pressing the turbo button in the old days, but better!"); + console.warn(" Examples: --project=angular2 or --project=angular2"); } } @@ -103,19 +105,18 @@ function runJasmineTests(globs, done) { var fork = require('child_process').fork; var args = ['--'].concat(globs); - fork('./tools/cjs-jasmine', args, { - stdio: 'inherit' - }).on('close', function jasmineCloseHandler(exitCode) { - if (exitCode && treatTestErrorsAsFatal) { - var err = new Error('Jasmine tests failed'); - // Mark the error for gulp similar to how gulp-utils.PluginError does it. - // The stack is not useful in this context. - err.showStack = false; - done(err); - } else { - done(); - } - }); + fork('./tools/cjs-jasmine', args, {stdio: 'inherit'}) + .on('close', function jasmineCloseHandler(exitCode) { + if (exitCode && treatTestErrorsAsFatal) { + var err = new Error('Jasmine tests failed'); + // Mark the error for gulp similar to how gulp-utils.PluginError does it. + // The stack is not useful in this context. + err.showStack = false; + done(err); + } else { + done(); + } + }); } // Note: when DART_SDK is not found, all gulp tasks ending with `.dart` will be skipped. @@ -142,14 +143,18 @@ var CONFIG = { }; var ANGULAR2_BUNDLE_CONFIG = [ - 'angular2/common', 'angular2/core', 'angular2/compiler', 'angular2/instrumentation', - 'angular2/platform/browser', 'angular2/platform/common_dom' + 'angular2/common', + 'angular2/core', + 'angular2/compiler', + 'angular2/instrumentation', + 'angular2/platform/browser', + 'angular2/platform/common_dom' ]; var NG2_BUNDLE_CONTENT = ANGULAR2_BUNDLE_CONFIG.join(' + ') + ' - rxjs/*'; var HTTP_BUNDLE_CONTENT = 'angular2/http - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); var ROUTER_BUNDLE_CONTENT = 'angular2/router + angular2/router/router_link_dsl - rxjs/* - ' + - ANGULAR2_BUNDLE_CONFIG.join(' - '); + ANGULAR2_BUNDLE_CONFIG.join(' - '); var TESTING_BUNDLE_CONTENT = 'angular2/testing + angular2/http/testing + angular2/router/testing + angular2/platform/testing/browser - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); @@ -169,8 +174,8 @@ var PAYLOAD_TESTS_CONFIG = { bundleName: 'app-bundle-deps.min.js', cases: ['hello_world'], dist: function(caseName, packaging) { - return path.join( - __dirname, CONFIG.dest.js.prod.es5, 'payload_tests', caseName, 'ts/' + packaging); + return path.join(__dirname, CONFIG.dest.js.prod.es5, 'payload_tests', caseName, + 'ts/' + packaging); }, systemjs: {sizeLimits: {'uncompressed': 870 * 1024, 'gzip level=9': 165 * 1024}}, webpack: {sizeLimits: {'uncompressed': 550 * 1024, 'gzip level=9': 120 * 1024}} @@ -192,19 +197,18 @@ gulp.task('build/clean.docs_angular_io', (done) => fse.remove(CONFIG.dest.docs_a gulp.task('build/clean.bundles', (done) => fse.remove(CONFIG.dest.bundles.all, done)); -gulp.task( - 'build/clean.bundles.benchpress', (done) => fse.remove(CONFIG.dest.bundles.benchpress, done)); +gulp.task('build/clean.bundles.benchpress', + (done) => fse.remove(CONFIG.dest.bundles.benchpress, done)); // ------------ // transpile -gulp.task('build/tree.dart', ['build/clean.dart', 'build.tools'], function(done) { - runSequence('!build/tree.dart', sequenceComplete(done)); -}); +gulp.task('build/tree.dart', ['build/clean.dart', 'build.tools'], + function(done) { runSequence('!build/tree.dart', sequenceComplete(done)); }); -gulp.task( - '!build/tree.dart', function() { return angularBuilder.rebuildDartTree(cliArgsProjects); }); +gulp.task('!build/tree.dart', + function() { return angularBuilder.rebuildDartTree(cliArgsProjects); }); // ------------ @@ -214,15 +218,13 @@ gulp.task( gulp.task('pubget.dart', pubget.dir(gulp, gulpPlugins, {dir: '.', command: DART_SDK.PUB})); // Run `pub get` only on the angular2 dir of CONFIG.dest.dart -gulp.task( - '!build/pubget.angular2.dart', - pubget.dir( - gulp, gulpPlugins, {dir: path.join(CONFIG.dest.dart, 'angular2'), command: DART_SDK.PUB})); +gulp.task('!build/pubget.angular2.dart', + pubget.dir(gulp, gulpPlugins, + {dir: path.join(CONFIG.dest.dart, 'angular2'), command: DART_SDK.PUB})); // Run `pub get` over CONFIG.dest.dart -gulp.task( - 'build/pubspec.dart', - pubget.subDir(gulp, gulpPlugins, {dir: CONFIG.dest.dart, command: DART_SDK.PUB})); +gulp.task('build/pubspec.dart', + pubget.subDir(gulp, gulpPlugins, {dir: CONFIG.dest.dart, command: DART_SDK.PUB})); // This is a hacky way to work around dart's pub that creates `packages` symlink in every directory @@ -243,15 +245,14 @@ gulp.task('!build/remove-pub-symlinks', function(done) { return; } - exec( - 'find dist/dart/angular2/test/ -name packages | xargs rm -r', - function(error, stdout, stderr) { - if (error) { - done(stderr); - return; - } - done(); - }); + exec('find dist/dart/angular2/test/ -name packages | xargs rm -r', + function(error, stdout, stderr) { + if (error) { + done(stderr); + return; + } + done(); + }); }); // ------------ @@ -268,17 +269,16 @@ gulp.task('build/analyze.dart', () => { gulp.task('build/analyze.ddc.dart', () => { var dartanalyzer = require('./tools/build/dartanalyzer'); - return dartanalyzer( - gulp, gulpPlugins, {dest: CONFIG.dest.dart, command: DART_SDK.ANALYZER, use_ddc: true}); + return dartanalyzer(gulp, gulpPlugins, + {dest: CONFIG.dest.dart, command: DART_SDK.ANALYZER, use_ddc: true}); }); gulp.task('build/check.apidocs.dart', () => { var dartapidocs = require('./tools/build/dartapidocs'); - return dartapidocs( - gulp, gulpPlugins, - {dest: CONFIG.dest.dart, output: os.tmpdir(), command: DART_SDK.DARTDOCGEN}); + return dartapidocs(gulp, gulpPlugins, + {dest: CONFIG.dest.dart, output: os.tmpdir(), command: DART_SDK.DARTDOCGEN}); }); @@ -288,9 +288,8 @@ gulp.task('build/check.apidocs.dart', () => { gulp.task( 'build/pubbuild.dart', - pubbuild.subdirs( - gulp, gulpPlugins, - {src: CONFIG.dest.dart, dest: CONFIG.dest.js.dart2js, command: DART_SDK.PUB})); + pubbuild.subdirs(gulp, gulpPlugins, + {src: CONFIG.dest.dart, dest: CONFIG.dest.js.dart2js, command: DART_SDK.PUB})); // ------------ // formatting @@ -305,14 +304,14 @@ function doCheckFormat() { gulp.task('check-format', function() { return doCheckFormat().on('warning', function(e) { - console.log('NOTE: this will be promoted to an ERROR in the continuous build'); + console.log("NOTE: this will be promoted to an ERROR in the continuous build"); }); }); gulp.task('enforce-format', function() { return doCheckFormat().on('warning', function(e) { - console.log('ERROR: You forgot to run clang-format on your change.'); - console.log('See https://github.com/angular/angular/blob/master/DEVELOPER.md#clang-format'); + console.log("ERROR: You forgot to run clang-format on your change."); + console.log("See https://github.com/angular/angular/blob/master/DEVELOPER.md#clang-format"); process.exit(1); }); }); @@ -322,14 +321,14 @@ gulp.task('lint', ['build.tools'], function() { // Built-in rules are at // https://github.com/palantir/tslint#supported-rules var tslintConfig = { - 'rules': { - 'requireInternalWithUnderscore': true, - 'requireParameterType': true, - 'requireReturnType': true, - 'semicolon': true, + "rules": { + "requireInternalWithUnderscore": true, + "requireParameterType": true, + "requireReturnType": true, + "semicolon": true, // TODO: find a way to just screen for reserved names - 'variable-name': false + "variable-name": false } }; return gulp.src(['modules/angular2/src/**/*.ts', '!modules/angular2/src/testing/**']) @@ -349,7 +348,7 @@ gulp.task('build/checkCircularDependencies', function(done) { var dependencyObject = madge([CONFIG.dest.js.dev.es5], { format: 'cjs', extensions: ['.js'], - onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, '//'); } + onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, "//"); } }); var circularDependencies = dependencyObject.circular().getArray(); if (circularDependencies.length > 0) { @@ -420,29 +419,26 @@ gulp.task('!proxyServeDart', proxyServeDart); gulp.task('serve.dart', function(done) { runSequence( [ - '!proxyServeDart', 'serve/playground.dart', 'serve/benchmarks.dart', + '!proxyServeDart', + 'serve/playground.dart', + 'serve/benchmarks.dart', 'serve/benchmarks_external.dart' ], done); }); -gulp.task( - 'serve/playground.dart', - pubserve( - gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/playground', port: 8004})); +gulp.task('serve/playground.dart', + pubserve(gulp, gulpPlugins, + {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/playground', port: 8004})); -gulp.task( - 'serve/benchmarks.dart', - pubserve( - gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks', port: 8006})); +gulp.task('serve/benchmarks.dart', + pubserve(gulp, gulpPlugins, + {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks', port: 8006})); gulp.task( 'serve/benchmarks_external.dart', - pubserve( - gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks_external', port: 8008})); + pubserve(gulp, gulpPlugins, + {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks_external', port: 8008})); gulp.task('serve.e2e.dart', ['build.js.cjs'], function(neverDone) { var watch = require('./tools/build/watch'); @@ -470,14 +466,13 @@ function runKarma(configFile, done) { } gulp.task('test.js', function(done) { - runSequence( - 'test.unit.tools/ci', 'test.transpiler.unittest', 'test.unit.js/ci', 'test.unit.cjs/ci', - 'test.typings', 'check-public-api', sequenceComplete(done)); + runSequence('test.unit.tools/ci', 'test.transpiler.unittest', 'test.unit.js/ci', + 'test.unit.cjs/ci', 'test.typings', 'check-public-api', sequenceComplete(done)); }); gulp.task('test.dart', function(done) { - runSequence( - 'versions.dart', 'test.transpiler.unittest', 'test.unit.dart/ci', sequenceComplete(done)); + runSequence('versions.dart', 'test.transpiler.unittest', 'test.unit.dart/ci', + sequenceComplete(done)); }); gulp.task('versions.dart', function() { dartSdk.logVersion(DART_SDK); }); @@ -500,26 +495,24 @@ function getBrowsersFromCLI(provider, isDart) { var input = inputList[i]; var karmaChromeLauncher = require('karma-chrome-launcher'); if (browserProvidersConf.customLaunchers.hasOwnProperty(input) || - karmaChromeLauncher.hasOwnProperty('launcher:' + input)) { + karmaChromeLauncher.hasOwnProperty("launcher:" + input)) { // In case of non-sauce browsers, or browsers defined in karma-chrome-launcher (Chrome, // ChromeCanary and Dartium): // overrides everything, ignoring other options outputList = [input]; isProvider = false; break; - } else if ( - provider && - browserProvidersConf.customLaunchers.hasOwnProperty(provider + '_' + input.toUpperCase())) { + } else if (provider && + browserProvidersConf.customLaunchers.hasOwnProperty(provider + "_" + + input.toUpperCase())) { isProvider = true; - outputList.push(provider + '_' + input.toUpperCase()); - } else if ( - provider && provider == 'SL' && - browserProvidersConf.sauceAliases.hasOwnProperty(input.toUpperCase())) { + outputList.push(provider + "_" + input.toUpperCase()); + } else if (provider && provider == 'SL' && + browserProvidersConf.sauceAliases.hasOwnProperty(input.toUpperCase())) { outputList = outputList.concat(browserProvidersConf.sauceAliases[input.toUpperCase()]); isProvider = true; - } else if ( - provider && provider == 'BS' && - browserProvidersConf.browserstackAliases.hasOwnProperty(input.toUpperCase())) { + } else if (provider && provider == 'BS' && + browserProvidersConf.browserstackAliases.hasOwnProperty(input.toUpperCase())) { outputList = outputList.concat(browserProvidersConf.browserstackAliases[input.toUpperCase()]); isProvider = true; } else { @@ -573,20 +566,19 @@ gulp.task('test.unit.js.browserstack', ['build.js.dev'], function(done) { function launchKarmaWithExternalBrowsers(reporters, browsers, done) { var karma = require('karma'); - new karma - .Server( - { - configFile: __dirname + '/karma-js.conf.js', - singleRun: true, - browserNoActivityTimeout: 240000, - captureTimeout: 120000, - reporters: reporters, - browsers: browsers - }, - function(err) { - done(); - process.exit(err ? 1 : 0); - }) + new karma.Server( + { + configFile: __dirname + '/karma-js.conf.js', + singleRun: true, + browserNoActivityTimeout: 240000, + captureTimeout: 120000, + reporters: reporters, + browsers: browsers + }, + function(err) { + done(); + process.exit(err ? 1 : 0); + }) .start(); } @@ -630,14 +622,13 @@ gulp.task('!test.unit.router/karma-server', function() { gulp.task('!test.unit.router/karma-run', function(done) { var karma = require('karma'); - karma.runner.run( - {configFile: __dirname + '/modules/angular1_router/karma-router.conf.js'}, - function(exitCode) { - // ignore exitCode, we don't want to fail the build in the interactive (non-ci) - // mode - // karma will print all test failures - done(); - }); + karma.runner.run({configFile: __dirname + '/modules/angular1_router/karma-router.conf.js'}, + function(exitCode) { + // ignore exitCode, we don't want to fail the build in the interactive (non-ci) + // mode + // karma will print all test failures + done(); + }); }); gulp.task('buildRouter.dev', function() { @@ -648,21 +639,21 @@ gulp.task('buildRouter.dev', function() { gulp.task('test.unit.dart', function(done) { printModulesWarning(); - runSequence( - 'build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { - var watch = require('./tools/build/watch'); + runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', + '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { + var watch = require('./tools/build/watch'); - // if initial build failed (likely due to build or formatting step) then exit - // otherwise karma server doesn't start and we can't continue running properly - if (error) { - done(error); - return; - } - // treatTestErrorsAsFatal = false; + // if initial build failed (likely due to build or formatting step) then exit + // otherwise karma server doesn't start and we can't continue running properly + if (error) { + done(error); + return; + } + // treatTestErrorsAsFatal = false; - watch(['modules/angular2/**'], ['!build/tree.dart', '!test.unit.dart/run/angular2']); - }); + watch(['modules/angular2/**'], + ['!build/tree.dart', '!test.unit.dart/run/angular2']); + }); }); // Dart Payload Size Test @@ -671,26 +662,22 @@ gulp.task('test.unit.dart', function(done) { // Measure in bytes. var _DART_PAYLOAD_SIZE_LIMITS = {'uncompressed': 320 * 1024, 'gzip level=9': 90 * 1024}; gulp.task('test.payload.dart/ci', function(done) { - runSequence( - 'build/packages.dart', '!pubget.payload.dart', '!pubbuild.payload.dart', - '!checkAndReport.payload.dart', done); + runSequence('build/packages.dart', '!pubget.payload.dart', '!pubbuild.payload.dart', + '!checkAndReport.payload.dart', done); }); -gulp.task( - '!pubget.payload.dart', - pubget.dir( - gulp, gulpPlugins, {dir: 'modules_dart/payload/hello_world', command: DART_SDK.PUB})); +gulp.task('!pubget.payload.dart', + pubget.dir(gulp, gulpPlugins, + {dir: 'modules_dart/payload/hello_world', command: DART_SDK.PUB})); -gulp.task( - '!pubbuild.payload.dart', - pubbuild.single( - gulp, gulpPlugins, {command: DART_SDK.PUB, src: 'modules_dart/payload/hello_world'})); +gulp.task('!pubbuild.payload.dart', + pubbuild.single(gulp, gulpPlugins, + {command: DART_SDK.PUB, src: 'modules_dart/payload/hello_world'})); gulp.task('!checkAndReport.payload.dart', function() { var reportSize = require('./tools/analytics/reportsize'); - return reportSize( - 'modules_dart/payload/hello_world/build/web/*.dart.js', - {failConditions: _DART_PAYLOAD_SIZE_LIMITS, prefix: 'hello_world'}); + return reportSize('modules_dart/payload/hello_world/build/web/*.dart.js', + {failConditions: _DART_PAYLOAD_SIZE_LIMITS, prefix: 'hello_world'}); }); // JS payload size tracking @@ -714,7 +701,7 @@ gulp.task('!build.payload.js.webpack', function() { return webpack({ // bundle app + framework entry: CASE_PATH + '/index.js', - output: {path: CASE_PATH, filename: 'app-bundle.js'}, + output: {path: CASE_PATH, filename: "app-bundle.js"}, resolve: { extensions: ['', '.js'], packageAlias: '', // option added to ignore "broken" package.json in our dist folder @@ -726,7 +713,8 @@ gulp.task('!build.payload.js.webpack', function() { gulp.src([ 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', - 'node_modules/reflect-metadata/Reflect.js', CASE_PATH + '/app-bundle.js' + 'node_modules/reflect-metadata/Reflect.js', + CASE_PATH + '/app-bundle.js' ]) .pipe(gulpPlugins.concat(PAYLOAD_TESTS_CONFIG.ts.bundleName)) .pipe(gulpPlugins.uglify()) @@ -756,8 +744,10 @@ gulp.task('!build.payload.js.systemjs', function() { gulp.src([ 'node_modules/systemjs/dist/system.src.js', 'dist/js/prod/es5/bundle/angular2-polyfills.js', - 'dist/js/prod/es5/bundle/angular2.js', 'dist/js/prod/es5//rxjs/bundles/Rx.js', - CASE_PATH + '/index.register.js', 'tools/build/systemjs/payload_tests_import.js' + 'dist/js/prod/es5/bundle/angular2.js', + 'dist/js/prod/es5//rxjs/bundles/Rx.js', + CASE_PATH + '/index.register.js', + 'tools/build/systemjs/payload_tests_import.js' ]) .pipe(gulpPlugins.concat(PAYLOAD_TESTS_CONFIG.ts.bundleName)) .pipe(gulpPlugins.uglify()) @@ -773,13 +763,12 @@ gulp.task('!checkAndReport.payload.js', function() { var reportSize = require('./tools/analytics/reportsize'); function caseSizeStream(caseName, packaging) { - return reportSize( - PAYLOAD_TESTS_CONFIG.ts.dist(caseName, packaging) + '/' + - PAYLOAD_TESTS_CONFIG.ts.bundleName, - { - failConditions: PAYLOAD_TESTS_CONFIG.ts[packaging].sizeLimits, - prefix: caseName + '_' + packaging - }); + return reportSize(PAYLOAD_TESTS_CONFIG.ts.dist(caseName, packaging) + '/' + + PAYLOAD_TESTS_CONFIG.ts.bundleName, + { + failConditions: PAYLOAD_TESTS_CONFIG.ts[packaging].sizeLimits, + prefix: caseName + '_' + packaging + }) } return PAYLOAD_TESTS_CONFIG.ts.cases.reduce(function(sizeReportingStreams, caseName) { @@ -789,35 +778,33 @@ gulp.task('!checkAndReport.payload.js', function() { }); gulp.task('watch.dart.dev', function(done) { - runSequence( - 'build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { - var watch = require('./tools/build/watch'); + runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', + '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { + var watch = require('./tools/build/watch'); - // if initial build failed (likely due to build or formatting step) then exit - // otherwise karma server doesn't start and we can't continue running properly - if (error) { - done(error); - return; - } + // if initial build failed (likely due to build or formatting step) then exit + // otherwise karma server doesn't start and we can't continue running properly + if (error) { + done(error); + return; + } - watch(['modules/angular2/**'], {ignoreInitial: true}, ['!build/tree.dart']); - }); + watch(['modules/angular2/**'], {ignoreInitial: true}, ['!build/tree.dart']); + }); }); gulp.task('test.unit.router/ci', function(done) { var karma = require('karma'); var browserConf = getBrowsersFromCLI(); - new karma - .Server( - { - configFile: __dirname + '/modules/angular1_router/karma-router.conf.js', - singleRun: true, - reporters: ['dots'], - browsers: browserConf.browsersToRun - }, - done) + new karma.Server( + { + configFile: __dirname + '/modules/angular1_router/karma-router.conf.js', + singleRun: true, + reporters: ['dots'], + browsers: browserConf.browsersToRun + }, + done) .start(); }); @@ -825,15 +812,14 @@ gulp.task('test.unit.js/ci', function(done) { var karma = require('karma'); var browserConf = getBrowsersFromCLI(); - new karma - .Server( - { - configFile: __dirname + '/karma-js.conf.js', - singleRun: true, - reporters: ['dots'], - browsers: browserConf.browsersToRun - }, - function(err) { done(); }) + new karma.Server( + { + configFile: __dirname + '/karma-js.conf.js', + singleRun: true, + reporters: ['dots'], + browsers: browserConf.browsersToRun + }, + function(err) { done(); }) .start(); }); @@ -854,10 +840,9 @@ gulp.task('test.unit.js.browserstack/ci', function(done) { }); gulp.task('test.unit.dart/ci', function(done) { - runSequence( - 'test.dart.dartium_symlink', '!test.unit.dart/run/angular2', - '!test.unit.dart/run/angular2_testing', '!test.unit.dart/run/benchpress', - sequenceComplete(done)); + runSequence('test.dart.dartium_symlink', '!test.unit.dart/run/angular2', + '!test.unit.dart/run/angular2_testing', '!test.unit.dart/run/benchpress', + sequenceComplete(done)); }); // At the moment, dart test requires dartium to be an executable on the path. @@ -910,9 +895,8 @@ gulp.task('test.unit.cjs/ci', function(done) { runJasmineTests(['dist/js/cjs/{angular2,benchpress}/test/**/*_spec.js'], done); }); -gulp.task('check-public-api', function(done) { - runJasmineTests(['dist/tools/public_api_guard/**/*_spec.js'], done); -}); +gulp.task('check-public-api', + function(done) { runJasmineTests(['dist/tools/public_api_guard/**/*_spec.js'], done); }); gulp.task('test.unit.cjs', ['build/clean.js', 'build.tools'], function(neverDone) { var watch = require('./tools/build/watch'); @@ -933,21 +917,19 @@ gulp.task('test.unit.dartvm', function(neverDone) { // Watch for changes made in the TS and Dart code under "modules" and // run ts2dart and test change detector generator prior to rerunning the // tests. - watch( - 'modules/angular2/**', {ignoreInitial: true}, - ['!build/tree.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); + watch('modules/angular2/**', {ignoreInitial: true}, + ['!build/tree.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); // Watch for changes made in Dart code under "modules_dart", then copy it // to dist and run test change detector generator prior to retunning the // tests. - watch( - 'modules_dart/**', {ignoreInitial: true}, - ['build/pure-packages.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); + watch('modules_dart/**', {ignoreInitial: true}, + ['build/pure-packages.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); }); }); -gulp.task( - '!test.unit.dartvm/run', runServerDartTests(gulp, gulpPlugins, {dir: 'dist/dart/angular2'})); +gulp.task('!test.unit.dartvm/run', + runServerDartTests(gulp, gulpPlugins, {dir: 'dist/dart/angular2'})); gulp.task('test.unit.tools/ci', function(done) { @@ -971,9 +953,8 @@ gulp.task('test.server.dart', runServerDartTests(gulp, gulpPlugins, {dest: 'dist // ----------------- // test builders -gulp.task('test.transpiler.unittest', function(done) { - runJasmineTests(['tools/transpiler/unittest/**/*.js'], done); -}); +gulp.task('test.transpiler.unittest', + function(done) { runJasmineTests(['tools/transpiler/unittest/**/*.js'], done); }); // ----------------- // Pre-test checks @@ -1008,14 +989,13 @@ gulp.task('!pre.test.typings.layoutNodeModule', ['build.js.cjs'], function() { }); gulp.task('!pre.test.typings.copyDeps', function() { - return gulp - .src( - [ - 'modules/angular2/typings/angular-protractor/*.ts', - 'modules/angular2/typings/jasmine/*.ts', - 'modules/angular2/typings/selenium-webdriver/*.ts', - ], - {base: 'modules/angular2/typings'}) + return gulp.src( + [ + 'modules/angular2/typings/angular-protractor/*.ts', + 'modules/angular2/typings/jasmine/*.ts', + 'modules/angular2/typings/selenium-webdriver/*.ts', + ], + {base: 'modules/angular2/typings'}) .pipe(gulp.dest(tmpdir)); }); @@ -1023,24 +1003,25 @@ gulp.task('!pre.test.typings.copyTypingsSpec', function() { return gulp.src(['modules/angular2/examples/**/*.ts']).pipe(gulp.dest(tmpdir)); }); -gulp.task( - 'test.typings', - [ - '!pre.test.typings.layoutNodeModule', '!pre.test.typings.copyTypingsSpec', - '!pre.test.typings.copyDeps' - ], - function() { - var tsc = require('gulp-typescript'); +gulp.task('test.typings', + [ + '!pre.test.typings.layoutNodeModule', + '!pre.test.typings.copyTypingsSpec', + '!pre.test.typings.copyDeps' + ], + function() { + var tsc = require('gulp-typescript'); - return gulp.src([tmpdir + '/**/*.ts', '!' + tmpdir + '/node_modules/**/*']).pipe(tsc({ - target: 'ES6', - module: 'commonjs', - experimentalDecorators: true, - noImplicitAny: true, - moduleResolution: 'node', - typescript: require('typescript') - })); - }); + return gulp.src([tmpdir + '/**/*.ts', '!' + tmpdir + '/node_modules/**/*']) + .pipe(tsc({ + target: 'ES6', + module: 'commonjs', + experimentalDecorators: true, + noImplicitAny: true, + moduleResolution: 'node', + typescript: require('typescript') + })); + }); // ----------------- // orchestrated targets @@ -1051,22 +1032,20 @@ gulp.task( // // This task is expected to be run after build/tree.dart gulp.task('build/pure-packages.dart', function(done) { - runSequence( - 'build/pure-packages.dart/standalone', 'build/pure-packages.dart/license', - 'build/pure-packages.dart/angular2', sequenceComplete(done)); + runSequence('build/pure-packages.dart/standalone', 'build/pure-packages.dart/license', + 'build/pure-packages.dart/angular2', sequenceComplete(done)); }); gulp.task('build/pure-packages.dart/standalone', function() { - return gulp - .src([ - 'modules_dart/**/*', - '!modules_dart/**/*.proto', - '!modules_dart/**/packages{,/**}', - '!modules_dart/**/.packages', - '!modules_dart/payload{,/**}', - '!modules_dart/transform{,/**}', - ]) + return gulp.src([ + 'modules_dart/**/*', + '!modules_dart/**/*.proto', + '!modules_dart/**/packages{,/**}', + '!modules_dart/**/.packages', + '!modules_dart/payload{,/**}', + '!modules_dart/transform{,/**}', + ]) .pipe(gulp.dest(CONFIG.dest.dart)); }); @@ -1076,36 +1055,32 @@ gulp.task('build/pure-packages.dart/license', function() { gulp.task('build/pure-packages.dart/angular2', function() { - return gulp - .src([ - 'modules_dart/transform/**/*', - '!modules_dart/transform/**/*.proto', - '!modules_dart/transform/pubspec.yaml', - '!modules_dart/transform/**/packages{,/**}', - ]) + return gulp.src([ + 'modules_dart/transform/**/*', + '!modules_dart/transform/**/*.proto', + '!modules_dart/transform/pubspec.yaml', + '!modules_dart/transform/**/packages{,/**}', + ]) .pipe(gulp.dest(path.join(CONFIG.dest.dart, 'angular2'))); }); // Builds all Dart packages, but does not compile them gulp.task('build/packages.dart', function(done) { - runSequence( - 'lint_protos.dart', 'build/tree.dart', 'build/pure-packages.dart', - // Run after 'build/tree.dart' because broccoli clears the dist/dart folder - '!build/pubget.angular2.dart', '!build/change_detect.dart', sequenceComplete(done)); + runSequence('lint_protos.dart', 'build/tree.dart', 'build/pure-packages.dart', + // Run after 'build/tree.dart' because broccoli clears the dist/dart folder + '!build/pubget.angular2.dart', '!build/change_detect.dart', sequenceComplete(done)); }); // Builds and compiles all Dart packages gulp.task('build.dart', function(done) { - runSequence( - 'build/packages.dart', 'build/pubspec.dart', 'build/analyze.dart', 'build/check.apidocs.dart', - sequenceComplete(done)); + runSequence('build/packages.dart', 'build/pubspec.dart', 'build/analyze.dart', + 'build/check.apidocs.dart', sequenceComplete(done)); }); // public task to build tools -gulp.task('build.tools', ['build/clean.tools'], function(done) { - runSequence('!build.tools', sequenceComplete(done)); -}); +gulp.task('build.tools', ['build/clean.tools'], + function(done) { runSequence('!build.tools', sequenceComplete(done)); }); // private task to build tools @@ -1113,14 +1088,16 @@ gulp.task('!build.tools', function() { var sourcemaps = require('gulp-sourcemaps'); var tsc = require('gulp-typescript'); - var stream = gulp.src(['tools/**/*.ts']).pipe(sourcemaps.init()).pipe(tsc({ - target: 'ES5', - module: 'commonjs', - declaration: true, - // Don't use the version of typescript that gulp-typescript depends on - // see https://github.com/ivogabe/gulp-typescript#typescript-version - typescript: require('typescript') - })); + var stream = gulp.src(['tools/**/*.ts']) + .pipe(sourcemaps.init()) + .pipe(tsc({ + target: 'ES5', + module: 'commonjs', + declaration: true, + // Don't use the version of typescript that gulp-typescript depends on + // see https://github.com/ivogabe/gulp-typescript#typescript-version + typescript: require('typescript') + })); stream = merge2([stream.js.pipe(gulp.dest('dist/tools')), stream.dts.pipe(gulp.dest('dist/tools'))]) .on('error', @@ -1140,9 +1117,8 @@ gulp.task('!build.tools', function() { return stream; }); -gulp.task('broccoli.js.dev', ['build.tools'], function(done) { - runSequence('!broccoli.js.dev', sequenceComplete(done)); -}); +gulp.task('broccoli.js.dev', ['build.tools'], + function(done) { runSequence('!broccoli.js.dev', sequenceComplete(done)); }); gulp.task('!broccoli.js.dev', () => angularBuilder.rebuildBrowserDevTree({ generateEs6: generateEs6, @@ -1158,21 +1134,18 @@ gulp.task('!broccoli.js.prod', () => angularBuilder.rebuildBrowserProdTree({ useBundles: cliArgs.useBundles })); -gulp.task('build.js.dev', ['build/clean.js'], function(done) { - runSequence('broccoli.js.dev', sequenceComplete(done)); -}); +gulp.task('build.js.dev', ['build/clean.js'], + function(done) { runSequence('broccoli.js.dev', sequenceComplete(done)); }); -gulp.task('build.js.prod', ['build.tools'], function(done) { - runSequence('!broccoli.js.prod', sequenceComplete(done)); -}); +gulp.task('build.js.prod', ['build.tools'], + function(done) { runSequence('!broccoli.js.prod', sequenceComplete(done)); }); /** * public task */ -gulp.task('build.js.cjs', ['build.tools'], function(done) { - runSequence('!build.js.cjs', sequenceComplete(done)); -}); +gulp.task('build.js.cjs', ['build.tools'], + function(done) { runSequence('!build.js.cjs', sequenceComplete(done)); }); var firstBuildJsCjs = true; @@ -1181,13 +1154,12 @@ var firstBuildJsCjs = true; * private task */ gulp.task('!build.js.cjs', function() { - return angularBuilder - .rebuildNodeTree({ - generateEs6: generateEs6, - projects: cliArgsProjects, - noTypeChecks: cliArgs.noTypeChecks, - useBundles: cliArgs.useBundles - }) + return angularBuilder.rebuildNodeTree({ + generateEs6: generateEs6, + projects: cliArgsProjects, + noTypeChecks: cliArgs.noTypeChecks, + useBundles: cliArgs.useBundles + }) .then(function() { if (firstBuildJsCjs) { firstBuildJsCjs = false; @@ -1200,7 +1172,7 @@ gulp.task('!build.js.cjs', function() { var bundleConfig = { - paths: {'*': 'dist/js/prod/es5/*.js'}, + paths: {"*": "dist/js/prod/es5/*.js"}, // Files that end up empty after transpilation confuse system-builder // and need to be explitily listed here. // TODO: upgrade system builder and find a way to declare all input as cjs. @@ -1220,10 +1192,10 @@ gulp.task('!bundle.js.prod', ['build.js.prod'], function() { .then(function() { return Promise.all([ bundler.bundle(bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.js', bundlerConfig), - bundler.bundle( - bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.js', bundlerConfig), - bundler.bundle( - bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.js', bundlerConfig) + bundler.bundle(bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.js', + bundlerConfig), + bundler.bundle(bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.js', + bundlerConfig) ]); }); }); @@ -1234,16 +1206,16 @@ gulp.task('!bundle.js.min', ['build.js.prod'], function() { var bundlerConfig = {sourceMaps: true, minify: true, mangle: false, uglify: {compress: {keep_fnames: true}}}; - return bundler - .bundle(bundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.min.js', bundlerConfig) + return bundler.bundle(bundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.min.js', + bundlerConfig) .then(function() { return Promise.all([ - bundler.bundle( - bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.min.js', bundlerConfig), - bundler.bundle( - bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.min.js', bundlerConfig), - bundler.bundle( - bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.min.js', bundlerConfig) + bundler.bundle(bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.min.js', + bundlerConfig), + bundler.bundle(bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.min.js', + bundlerConfig), + bundler.bundle(bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.min.js', + bundlerConfig) ]); }); }); @@ -1254,37 +1226,34 @@ gulp.task('!bundle.js.dev', ['build.js.dev'], function() { var bundlerConfig = {sourceMaps: true}; var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {'*': 'dist/js/dev/es5/*.js'}); + devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - return bundler - .bundle(devBundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.dev.js', bundlerConfig) + return bundler.bundle(devBundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.dev.js', + bundlerConfig) .then(function() { return Promise.all([ - bundler.bundle( - devBundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.dev.js', bundlerConfig), - bundler.bundle( - devBundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.dev.js', bundlerConfig), - bundler.bundle( - devBundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.dev.js', bundlerConfig) + bundler.bundle(devBundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.dev.js', + bundlerConfig), + bundler.bundle(devBundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.dev.js', + bundlerConfig), + bundler.bundle(devBundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.dev.js', + bundlerConfig) ]); }); }); // WebWorker build -gulp.task('!bundle.web_worker.js.dev', ['build.js.dev'], function() { +gulp.task("!bundle.web_worker.js.dev", ["build.js.dev"], function() { var bundler = require('./tools/build/bundle'); var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {'*': 'dist/js/dev/es5/*.js'}); + devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - return bundler - .bundle( - devBundleConfig, 'angular2/web_worker/ui', './dist/build/web_worker/ui.dev.js', - {sourceMaps: true}) + return bundler.bundle(devBundleConfig, 'angular2/web_worker/ui', + './dist/build/web_worker/ui.dev.js', {sourceMaps: true}) .then(function() { - return bundler.bundle( - devBundleConfig, 'angular2/web_worker/worker', './dist/build/web_worker/worker.dev.js', - {sourceMaps: true}); + return bundler.bundle(devBundleConfig, 'angular2/web_worker/worker', + './dist/build/web_worker/worker.dev.js', {sourceMaps: true}); }); }); @@ -1292,11 +1261,10 @@ gulp.task('!bundle.testing', ['build.js.dev'], function() { var bundler = require('./tools/build/bundle'); var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {'*': 'dist/js/dev/es5/*.js'}); + devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - return bundler.bundle( - devBundleConfig, TESTING_BUNDLE_CONTENT, './dist/js/bundle/testing.dev.js', - {sourceMaps: true}); + return bundler.bundle(devBundleConfig, TESTING_BUNDLE_CONTENT, './dist/js/bundle/testing.dev.js', + {sourceMaps: true}); }); gulp.task('!bundles.js.docs', ['clean'], function() { @@ -1362,13 +1330,12 @@ gulp.task('!bundles.js.umd', ['build.js.dev'], function() { } return q.all([ - webpack(webPackConf( - [__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', 'dev')), - webpack(webPackConf( - [__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', 'prod')), - webpack(webPackConf( - [__dirname + '/tools/build/webpack/angular2-all-testing.umd.js'], 'angular2-all-testing', - 'dev')) + webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', + 'dev')), + webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', + 'prod')), + webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all-testing.umd.js'], + 'angular2-all-testing', 'dev')) ]); }); @@ -1386,11 +1353,10 @@ gulp.task('bundles.js.umd.min', ['!bundles.js.umd', '!bundle.ng.polyfills'], fun gulp.task('!bundle.js.prod.deps', ['!bundle.js.prod'], function() { var bundler = require('./tools/build/bundle'); - return merge2( - bundler.modify(['dist/build/angular2.js'], 'angular2.js'), - bundler.modify(['dist/build/http.js'], 'http.js'), - bundler.modify(['dist/build/router.js'], 'router.js'), - bundler.modify(['dist/build/upgrade.js'], 'upgrade.js')) + return merge2(bundler.modify(['dist/build/angular2.js'], 'angular2.js'), + bundler.modify(['dist/build/http.js'], 'http.js'), + bundler.modify(['dist/build/router.js'], 'router.js'), + bundler.modify(['dist/build/upgrade.js'], 'upgrade.js')) .pipe(gulp.dest('dist/js/bundle')); }); @@ -1398,21 +1364,20 @@ gulp.task('!bundle.js.min.deps', ['!bundle.js.min'], function() { var bundler = require('./tools/build/bundle'); var uglify = require('gulp-uglify'); - return merge2( - bundler.modify(['dist/build/angular2.min.js'], 'angular2.min.js'), - bundler.modify(['dist/build/http.min.js'], 'http.min.js'), - bundler.modify(['dist/build/router.min.js'], 'router.min.js'), - bundler.modify(['dist/build/upgrade.min.js'], 'upgrade.min.js')) + return merge2(bundler.modify(['dist/build/angular2.min.js'], 'angular2.min.js'), + bundler.modify(['dist/build/http.min.js'], 'http.min.js'), + bundler.modify(['dist/build/router.min.js'], 'router.min.js'), + bundler.modify(['dist/build/upgrade.min.js'], 'upgrade.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist/js/bundle')); }); -gulp.task('!bundle.ng.polyfills', ['clean'], function() { - return addDevDependencies('angular2-polyfills.js'); -}); +gulp.task('!bundle.ng.polyfills', ['clean'], + function() { return addDevDependencies('angular2-polyfills.js'); }); var JS_DEV_DEPS = [ - licenseWrap('node_modules/zone.js/LICENSE', true), 'node_modules/zone.js/dist/zone.js', + licenseWrap('node_modules/zone.js/LICENSE', true), + 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', licenseWrap('node_modules/reflect-metadata/LICENSE', true), 'node_modules/reflect-metadata/Reflect.js' @@ -1430,26 +1395,23 @@ function addDevDependencies(outputFile) { gulp.task('!bundle.js.dev.deps', ['!bundle.js.dev'], function() { var bundler = require('./tools/build/bundle'); - return merge2( - bundler.modify(['dist/build/angular2.dev.js'], 'angular2.dev.js'), - bundler.modify(['dist/build/http.dev.js'], 'http.dev.js'), - bundler.modify(['dist/build/router.dev.js'], 'router.dev.js'), - bundler.modify(['dist/build/upgrade.dev.js'], 'upgrade.dev.js')) + return merge2(bundler.modify(['dist/build/angular2.dev.js'], 'angular2.dev.js'), + bundler.modify(['dist/build/http.dev.js'], 'http.dev.js'), + bundler.modify(['dist/build/router.dev.js'], 'router.dev.js'), + bundler.modify(['dist/build/upgrade.dev.js'], 'upgrade.dev.js')) .pipe(gulp.dest('dist/js/bundle')); }); gulp.task('!bundle.web_worker.js.dev.deps', ['!bundle.web_worker.js.dev'], function() { var bundler = require('./tools/build/bundle'); - return merge2( - bundler.modify(['dist/build/web_worker/ui.dev.js'], 'web_worker/ui.dev.js'), - bundler.modify(['dist/build/web_worker/worker.dev.js'], 'web_worker/worker.dev.js')) + return merge2(bundler.modify(['dist/build/web_worker/ui.dev.js'], "web_worker/ui.dev.js"), + bundler.modify(['dist/build/web_worker/worker.dev.js'], "web_worker/worker.dev.js")) .pipe(gulp.dest('dist/js/bundle')); }); gulp.task('!bundle.copy', function() { - return merge2( - gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/prod/es5/bundle')), - gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/dev/es5/bundle'))); + return merge2(gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/prod/es5/bundle')), + gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/dev/es5/bundle'))); }); gulp.task('!bundles.js.checksize', function(done) { @@ -1457,21 +1419,27 @@ gulp.task('!bundles.js.checksize', function(done) { return reportSize('dist/js/bundle/**/*.js', {printToConsole: ['gzip level=2']}); }); -gulp.task( - 'bundles.js', - [ - '!bundle.js.prod.deps', '!bundle.js.dev.deps', '!bundle.js.min.deps', - '!bundle.web_worker.js.dev.deps', 'bundles.js.umd.min', '!bundle.testing', - '!bundle.ng.polyfills', '!bundles.js.docs' - ], - function(done) { runSequence('!bundle.copy', '!bundles.js.checksize', done); }); +gulp.task('bundles.js', + [ + '!bundle.js.prod.deps', + '!bundle.js.dev.deps', + '!bundle.js.min.deps', + '!bundle.web_worker.js.dev.deps', + 'bundles.js.umd.min', + '!bundle.testing', + '!bundle.ng.polyfills', + '!bundles.js.docs' + ], + function(done) { runSequence('!bundle.copy', '!bundles.js.checksize', done); }); -gulp.task( - 'build.js', - ['build.js.dev', 'build.js.prod', 'build.js.cjs', 'bundles.js', 'benchpress.bundle']); +gulp.task('build.js', + ['build.js.dev', 'build.js.prod', 'build.js.cjs', 'bundles.js', 'benchpress.bundle']); gulp.task('clean', [ - 'build/clean.tools', 'build/clean.js', 'build/clean.dart', 'build/clean.docs', + 'build/clean.tools', + 'build/clean.js', + 'build/clean.dart', + 'build/clean.docs', 'build/clean.bundles' ]); @@ -1498,8 +1466,8 @@ gulp.task('gen_protos.dart', function(done) { // change detection codegen gulp.task('build.change_detect.dart', function(done) { - return runSequence( - 'build/packages.dart', '!build/pubget.angular2.dart', '!build/change_detect.dart', done); + return runSequence('build/packages.dart', '!build/pubget.angular2.dart', + '!build/change_detect.dart', done); }); gulp.task('!build/change_detect.dart', function(done) { @@ -1514,9 +1482,8 @@ gulp.task('!build/change_detect.dart', function(done) { var genMain = path.join(srcDir, 'gen_change_detectors.dart'); var proc = spawn(DART_SDK.VM, [genMain], {stdio: ['ignore', 'pipe', 'inherit']}); proc.on('error', function(code) { - done(new Error( - 'Failed while generating change detector classes. Please run manually: ' + DART_SDK.VM + - ' ' + dartArgs.join(' '))); + done(new Error('Failed while generating change detector classes. Please run manually: ' + + DART_SDK.VM + ' ' + dartArgs.join(' '))); }); proc.on('close', function() { dartStream.close(); @@ -1532,10 +1499,9 @@ gulp.task('cleanup.builder', function() { return angularBuilder.cleanup(); }); gulp.task('benchpress.bundle', ['build/clean.bundles.benchpress', 'build.js.cjs'], function(cb) { var bundler = require('./tools/build/bundle'); - bundler.benchpressBundle( - BENCHPRESS_BUNDLE_CONFIG.entries, BENCHPRESS_BUNDLE_CONFIG.packageJson, - BENCHPRESS_BUNDLE_CONFIG.includes, BENCHPRESS_BUNDLE_CONFIG.excludes, - BENCHPRESS_BUNDLE_CONFIG.ignore, BENCHPRESS_BUNDLE_CONFIG.dest, cb); + bundler.benchpressBundle(BENCHPRESS_BUNDLE_CONFIG.entries, BENCHPRESS_BUNDLE_CONFIG.packageJson, + BENCHPRESS_BUNDLE_CONFIG.includes, BENCHPRESS_BUNDLE_CONFIG.excludes, + BENCHPRESS_BUNDLE_CONFIG.ignore, BENCHPRESS_BUNDLE_CONFIG.dest, cb); }); @@ -1571,7 +1537,7 @@ gulp.on('task_start', (e) => { analytics.buildSuccess('gulp <startup>', process.uptime() * 1000); } - analytics.buildStart('gulp ' + e.task); + analytics.buildStart('gulp ' + e.task) }); -gulp.on('task_stop', (e) => { analytics.buildSuccess('gulp ' + e.task, e.duration * 1000); }); -gulp.on('task_err', (e) => { analytics.buildError('gulp ' + e.task, e.duration * 1000); }); +gulp.on('task_stop', (e) => {analytics.buildSuccess('gulp ' + e.task, e.duration * 1000)}); +gulp.on('task_err', (e) => {analytics.buildError('gulp ' + e.task, e.duration * 1000)}); diff --git a/modules/angular1_router/src/ng_outlet.ts b/modules/angular1_router/src/ng_outlet.ts index 94059318ce..f348020287 100644 --- a/modules/angular1_router/src/ng_outlet.ts +++ b/modules/angular1_router/src/ng_outlet.ts @@ -78,7 +78,7 @@ function ngOutletDirective($animate, $q: ng.IQService, $rootRouter) { result = this.currentController.$routerCanReuse(nextInstruction, this.currentInstruction); } else { result = nextInstruction === this.currentInstruction || - angular.equals(nextInstruction.params, this.currentInstruction.params); + angular.equals(nextInstruction.params, this.currentInstruction.params); } return $q.when(result); } @@ -110,7 +110,7 @@ function ngOutletDirective($animate, $q: ng.IQService, $rootRouter) { } this.controller.$$template = '<' + dashCase(componentName) + ' $router="::$$router"></' + - dashCase(componentName) + '>'; + dashCase(componentName) + '>'; this.controller.$$router = this.router.childRouter(instruction.componentType); this.controller.$$outlet = this; @@ -165,8 +165,8 @@ function routerTriggerDirective($q) { var currentComponent = outlet.currentController = element.controller(ngOutletCtrl.$$componentName); if (currentComponent.$routerOnActivate) { - promise = $q.when(currentComponent.$routerOnActivate( - outlet.currentInstruction, outlet.previousInstruction)); + promise = $q.when(currentComponent.$routerOnActivate(outlet.currentInstruction, + outlet.previousInstruction)); } promise.then(outlet.deferredActivation.resolve, outlet.deferredActivation.reject); } @@ -213,15 +213,14 @@ function ngLinkDirective($rootRouter, $parse) { function getLink(params) { navigationInstruction = router.generate(params); - scope.$watch( - function() { return router.isRouteActive(navigationInstruction); }, - function(active) { - if (active) { - element.addClass('ng-link-active'); - } else { - element.removeClass('ng-link-active'); - } - }); + scope.$watch(function() { return router.isRouteActive(navigationInstruction); }, + function(active) { + if (active) { + element.addClass('ng-link-active'); + } else { + element.removeClass('ng-link-active'); + } + }); const navigationHref = navigationInstruction.toLinkUrl(); return $rootRouter._location.prepareExternalUrl(navigationHref); @@ -233,8 +232,8 @@ function ngLinkDirective($rootRouter, $parse) { let params = routeParamsGetter(); element.attr('href', getLink(params)); } else { - scope.$watch( - () => routeParamsGetter(scope), params => element.attr('href', getLink(params)), true); + scope.$watch(() => routeParamsGetter(scope), params => element.attr('href', getLink(params)), + true); } element.on('click', event => { diff --git a/modules/angular2/core.ts b/modules/angular2/core.ts index e2e8a41be6..f7d786ae62 100644 --- a/modules/angular2/core.ts +++ b/modules/angular2/core.ts @@ -10,7 +10,13 @@ export * from './src/core/di'; export * from './src/facade/facade'; export {enableProdMode} from 'angular2/src/facade/lang'; export {platform, createNgZone, PlatformRef, ApplicationRef} from './src/core/application_ref'; -export {APP_ID, APP_COMPONENT, APP_INITIALIZER, PACKAGE_ROOT_URL, PLATFORM_INITIALIZER} from './src/core/application_tokens'; +export { + APP_ID, + APP_COMPONENT, + APP_INITIALIZER, + PACKAGE_ROOT_URL, + PLATFORM_INITIALIZER +} from './src/core/application_tokens'; export * from './src/core/zone'; export * from './src/core/render'; export * from './src/core/linker'; diff --git a/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts b/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts index 3e7e8dd048..a9b524b80f 100644 --- a/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts +++ b/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts @@ -20,7 +20,7 @@ expect(door.lock instanceof Lock).toBe(true); // #enddocregion // #docregion resolve_forward_ref -var ref = forwardRef(() => 'refValue'); -expect(resolveForwardRef(ref)).toEqual('refValue'); -expect(resolveForwardRef('regularValue')).toEqual('regularValue'); +var ref = forwardRef(() => "refValue"); +expect(resolveForwardRef(ref)).toEqual("refValue"); +expect(resolveForwardRef("regularValue")).toEqual("regularValue"); // #enddocregion \ No newline at end of file diff --git a/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts b/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts index 04acb2d2d7..861e644817 100644 --- a/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts +++ b/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts @@ -27,7 +27,7 @@ export class AsyncPipeExample { if (this.arrived) { this.reset(); } else { - this.resolve('hi there!'); + this.resolve("hi there!"); this.arrived = true; } } @@ -35,7 +35,7 @@ export class AsyncPipeExample { // #enddocregion // #docregion AsyncPipeObservable -@Component({selector: 'task-cmp', template: 'Time: {{ time | async }}'}) +@Component({selector: "task-cmp", template: "Time: {{ time | async }}"}) class Task { time = new Observable<number>((observer: Subscriber<number>) => { setInterval(() => observer.next(new Date().getTime()), 500); diff --git a/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts b/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts index eb34b7fc4e..bfa02bf67a 100644 --- a/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts +++ b/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts @@ -1,6 +1,12 @@ import {provide, Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {CanActivate, RouteConfig, ComponentInstruction, APP_BASE_HREF, ROUTER_DIRECTIVES} from 'angular2/router'; +import { + CanActivate, + RouteConfig, + ComponentInstruction, + APP_BASE_HREF, + ROUTER_DIRECTIVES +} from 'angular2/router'; function checkIfWeHavePermission(instruction: ComponentInstruction) { return instruction.params['id'] == '1'; diff --git a/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts b/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts index b5afae99ef..e330aff1fe 100644 --- a/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts +++ b/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts @@ -1,6 +1,13 @@ import {provide, Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {CanDeactivate, RouteConfig, RouteParams, ComponentInstruction, ROUTER_DIRECTIVES, APP_BASE_HREF} from 'angular2/router'; +import { + CanDeactivate, + RouteConfig, + RouteParams, + ComponentInstruction, + ROUTER_DIRECTIVES, + APP_BASE_HREF +} from 'angular2/router'; // #docregion routerCanDeactivate @Component({ diff --git a/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts b/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts index bfbc192094..47c24bcd09 100644 --- a/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts +++ b/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts @@ -1,6 +1,12 @@ import {Component, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {OnActivate, ComponentInstruction, RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF} from 'angular2/router'; +import { + OnActivate, + ComponentInstruction, + RouteConfig, + ROUTER_DIRECTIVES, + APP_BASE_HREF +} from 'angular2/router'; // #docregion routerOnActivate @Component({template: `Child`}) diff --git a/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts b/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts index 790001cdf9..a4b4c15072 100644 --- a/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts +++ b/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts @@ -1,6 +1,12 @@ import {Component, Injectable, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {OnDeactivate, ComponentInstruction, RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF} from 'angular2/router'; +import { + OnDeactivate, + ComponentInstruction, + RouteConfig, + ROUTER_DIRECTIVES, + APP_BASE_HREF +} from 'angular2/router'; @Injectable() @@ -51,6 +57,7 @@ class AppCmp { export function main() { return bootstrap(AppCmp, [ - provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/on_deactivate'}), LogService + provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/on_deactivate'}), + LogService ]); } diff --git a/modules/angular2/examples/router/ts/reuse/reuse_example.ts b/modules/angular2/examples/router/ts/reuse/reuse_example.ts index 2b7adfc6c4..7a2b182611 100644 --- a/modules/angular2/examples/router/ts/reuse/reuse_example.ts +++ b/modules/angular2/examples/router/ts/reuse/reuse_example.ts @@ -1,6 +1,15 @@ import {Component, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {CanActivate, RouteConfig, ComponentInstruction, ROUTER_DIRECTIVES, APP_BASE_HREF, CanReuse, RouteParams, OnReuse} from 'angular2/router'; +import { + CanActivate, + RouteConfig, + ComponentInstruction, + ROUTER_DIRECTIVES, + APP_BASE_HREF, + CanReuse, + RouteParams, + OnReuse +} from 'angular2/router'; // #docregion reuseCmp @@ -44,6 +53,6 @@ class AppCmp { export function main() { - return bootstrap( - AppCmp, [provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/reuse'})]); + return bootstrap(AppCmp, + [provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/reuse'})]); } diff --git a/modules/angular2/examples/testing/ts/testing.ts b/modules/angular2/examples/testing/ts/testing.ts index 6b5dffcc2a..a8a9980354 100644 --- a/modules/angular2/examples/testing/ts/testing.ts +++ b/modules/angular2/examples/testing/ts/testing.ts @@ -1,4 +1,15 @@ -import {describe, fdescribe, xdescribe, it, fit, xit, beforeEach, afterEach, beforeEachProviders, inject} from 'angular2/testing'; +import { + describe, + fdescribe, + xdescribe, + it, + fit, + xit, + beforeEach, + afterEach, + beforeEachProviders, + inject +} from 'angular2/testing'; import {provide} from 'angular2/core'; var db: any; @@ -19,9 +30,8 @@ fdescribe('some component', () => { // This test will run. }); }); -describe('another component', () => { - it('also has a test', () => { throw 'This test will not run.'; }); -}); +describe('another component', + () => { it('also has a test', () => { throw 'This test will not run.'; }); }); // #enddocregion // #docregion xdescribe @@ -63,10 +73,9 @@ describe('some component', () => { // #docregion beforeEachProviders describe('some component', () => { beforeEachProviders(() => [provide(MyService, {useClass: MyMockService})]); - it('uses MyService', inject( - [MyService], (service: MyMockService) => { - // service is an instance of MyMockService. - })); + it('uses MyService', inject([MyService], (service: MyMockService) => { + // service is an instance of MyMockService. + })); }); // #enddocregion diff --git a/modules/angular2/http.ts b/modules/angular2/http.ts index 6b7e0d1c3b..9b003f2fca 100644 --- a/modules/angular2/http.ts +++ b/modules/angular2/http.ts @@ -16,7 +16,12 @@ import {BaseResponseOptions, ResponseOptions} from './src/http/base_response_opt export {Request} from './src/http/static_request'; export {Response} from './src/http/static_response'; -export {RequestOptionsArgs, ResponseOptionsArgs, Connection, ConnectionBackend} from './src/http/interfaces'; +export { + RequestOptionsArgs, + ResponseOptionsArgs, + Connection, + ConnectionBackend +} from './src/http/interfaces'; export {BrowserXhr} from './src/http/backends/browser_xhr'; export {BaseRequestOptions, RequestOptions} from './src/http/base_request_options'; @@ -150,13 +155,16 @@ export {URLSearchParams} from './src/http/url_search_params'; export const HTTP_PROVIDERS: any[] = [ // TODO(pascal): use factory type annotations once supported in DI // issue: https://github.com/angular/angular/issues/3183 - provide(Http, { - useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => - new Http(xhrBackend, requestOptions), - deps: [XHRBackend, RequestOptions] - }), - BrowserXhr, provide(RequestOptions, {useClass: BaseRequestOptions}), - provide(ResponseOptions, {useClass: BaseResponseOptions}), XHRBackend + provide(Http, + { + useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => + new Http(xhrBackend, requestOptions), + deps: [XHRBackend, RequestOptions] + }), + BrowserXhr, + provide(RequestOptions, {useClass: BaseRequestOptions}), + provide(ResponseOptions, {useClass: BaseResponseOptions}), + XHRBackend ]; /** @@ -276,12 +284,14 @@ export const HTTP_BINDINGS = HTTP_PROVIDERS; export const JSONP_PROVIDERS: any[] = [ // TODO(pascal): use factory type annotations once supported in DI // issue: https://github.com/angular/angular/issues/3183 - provide(Jsonp, { - useFactory: (jsonpBackend: JSONPBackend, requestOptions: RequestOptions) => - new Jsonp(jsonpBackend, requestOptions), - deps: [JSONPBackend, RequestOptions] - }), - BrowserJsonp, provide(RequestOptions, {useClass: BaseRequestOptions}), + provide(Jsonp, + { + useFactory: (jsonpBackend: JSONPBackend, requestOptions: RequestOptions) => + new Jsonp(jsonpBackend, requestOptions), + deps: [JSONPBackend, RequestOptions] + }), + BrowserJsonp, + provide(RequestOptions, {useClass: BaseRequestOptions}), provide(ResponseOptions, {useClass: BaseResponseOptions}), provide(JSONPBackend, {useClass: JSONPBackend_}) ]; diff --git a/modules/angular2/instrumentation.ts b/modules/angular2/instrumentation.ts index 1d64e85073..67049babaf 100644 --- a/modules/angular2/instrumentation.ts +++ b/modules/angular2/instrumentation.ts @@ -1 +1,7 @@ -export {wtfCreateScope, wtfLeave, wtfStartTimeRange, wtfEndTimeRange, WtfScopeFn} from './src/core/profile/profile'; +export { + wtfCreateScope, + wtfLeave, + wtfStartTimeRange, + wtfEndTimeRange, + WtfScopeFn +} from './src/core/profile/profile'; diff --git a/modules/angular2/platform/browser.ts b/modules/angular2/platform/browser.ts index ef905838f2..ee4f4498fe 100644 --- a/modules/angular2/platform/browser.ts +++ b/modules/angular2/platform/browser.ts @@ -1,12 +1,27 @@ export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint'; -export {BROWSER_PROVIDERS, CACHED_TEMPLATE_PROVIDER, ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, BrowserDomAdapter, By, Title, DOCUMENT, enableDebugTools, disableDebugTools} from 'angular2/src/platform/browser_common'; +export { + BROWSER_PROVIDERS, + CACHED_TEMPLATE_PROVIDER, + ELEMENT_PROBE_PROVIDERS, + ELEMENT_PROBE_PROVIDERS_PROD_MODE, + inspectNativeElement, + BrowserDomAdapter, + By, + Title, + DOCUMENT, + enableDebugTools, + disableDebugTools +} from 'angular2/src/platform/browser_common'; import {Type, isPresent, CONST_EXPR} from 'angular2/src/facade/lang'; -import {BROWSER_PROVIDERS, BROWSER_APP_COMMON_PROVIDERS} from 'angular2/src/platform/browser_common'; +import { + BROWSER_PROVIDERS, + BROWSER_APP_COMMON_PROVIDERS +} from 'angular2/src/platform/browser_common'; import {COMPILER_PROVIDERS} from 'angular2/compiler'; import {ComponentRef, platform, reflector} from 'angular2/core'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; -import {XHRImpl} from 'angular2/src/platform/browser/xhr_impl'; +import {XHRImpl} from "angular2/src/platform/browser/xhr_impl"; import {XHR} from 'angular2/compiler'; import {Provider} from 'angular2/src/core/di'; diff --git a/modules/angular2/platform/browser_static.ts b/modules/angular2/platform/browser_static.ts index eab25aa624..928a31639d 100644 --- a/modules/angular2/platform/browser_static.ts +++ b/modules/angular2/platform/browser_static.ts @@ -1,8 +1,21 @@ export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint'; -export {BROWSER_PROVIDERS, ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, BrowserDomAdapter, By, Title, enableDebugTools, disableDebugTools} from 'angular2/src/platform/browser_common'; +export { + BROWSER_PROVIDERS, + ELEMENT_PROBE_PROVIDERS, + ELEMENT_PROBE_PROVIDERS_PROD_MODE, + inspectNativeElement, + BrowserDomAdapter, + By, + Title, + enableDebugTools, + disableDebugTools +} from 'angular2/src/platform/browser_common'; import {Type, isPresent} from 'angular2/src/facade/lang'; -import {BROWSER_PROVIDERS, BROWSER_APP_COMMON_PROVIDERS} from 'angular2/src/platform/browser_common'; +import { + BROWSER_PROVIDERS, + BROWSER_APP_COMMON_PROVIDERS +} from 'angular2/src/platform/browser_common'; import {ComponentRef, platform} from 'angular2/core'; /** @@ -16,9 +29,9 @@ export const BROWSER_APP_PROVIDERS: Array<any /*Type | Provider | any[]*/> = /** * See {@link bootstrap} for more information. */ -export function bootstrapStatic( - appComponentType: Type, customProviders?: Array<any /*Type | Provider | any[]*/>, - initReflector?: Function): Promise<ComponentRef> { +export function bootstrapStatic(appComponentType: Type, + customProviders?: Array<any /*Type | Provider | any[]*/>, + initReflector?: Function): Promise<ComponentRef> { if (isPresent(initReflector)) { initReflector(); } diff --git a/modules/angular2/platform/common_dom.ts b/modules/angular2/platform/common_dom.ts index 2b4c8a7153..50d3b5ba04 100644 --- a/modules/angular2/platform/common_dom.ts +++ b/modules/angular2/platform/common_dom.ts @@ -6,6 +6,10 @@ export {DomRenderer} from 'angular2/src/platform/dom/dom_renderer'; export {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; export {SharedStylesHost, DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; export {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; -export {EVENT_MANAGER_PLUGINS, EventManager, EventManagerPlugin} from 'angular2/src/platform/dom/events/event_manager'; +export { + EVENT_MANAGER_PLUGINS, + EventManager, + EventManagerPlugin +} from 'angular2/src/platform/dom/events/event_manager'; export * from 'angular2/src/platform/dom/debug/by'; export * from 'angular2/src/platform/dom/debug/ng_probe'; diff --git a/modules/angular2/platform/testing/browser.ts b/modules/angular2/platform/testing/browser.ts index 4defef4d1d..d344afb44c 100644 --- a/modules/angular2/platform/testing/browser.ts +++ b/modules/angular2/platform/testing/browser.ts @@ -1,4 +1,7 @@ -import {TEST_BROWSER_STATIC_PLATFORM_PROVIDERS, ADDITIONAL_TEST_BROWSER_PROVIDERS} from 'angular2/platform/testing/browser_static'; +import { + TEST_BROWSER_STATIC_PLATFORM_PROVIDERS, + ADDITIONAL_TEST_BROWSER_PROVIDERS +} from 'angular2/platform/testing/browser_static'; import {BROWSER_APP_PROVIDERS} from 'angular2/platform/browser'; import {CONST_EXPR} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/platform/testing/browser_static.ts b/modules/angular2/platform/testing/browser_static.ts index 06dac1bef5..d1555c719b 100644 --- a/modules/angular2/platform/testing/browser_static.ts +++ b/modules/angular2/platform/testing/browser_static.ts @@ -1,4 +1,12 @@ -import {APP_ID, DirectiveResolver, NgZone, Provider, ViewResolver, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER} from 'angular2/core'; +import { + APP_ID, + DirectiveResolver, + NgZone, + Provider, + ViewResolver, + PLATFORM_COMMON_PROVIDERS, + PLATFORM_INITIALIZER +} from 'angular2/core'; import {BROWSER_APP_COMMON_PROVIDERS} from 'angular2/src/platform/browser_common'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; @@ -10,7 +18,7 @@ import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy'; import {MockNgZone} from 'angular2/src/mock/ng_zone_mock'; -import {XHRImpl} from 'angular2/src/platform/browser/xhr_impl'; +import {XHRImpl} from "angular2/src/platform/browser/xhr_impl"; import {XHR} from 'angular2/compiler'; import {TestComponentBuilder} from 'angular2/src/testing/test_component_builder'; @@ -55,6 +63,7 @@ export const ADDITIONAL_TEST_BROWSER_PROVIDERS: Array<any /*Type | Provider | an */ export const TEST_BROWSER_STATIC_APPLICATION_PROVIDERS: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([ - BROWSER_APP_COMMON_PROVIDERS, new Provider(XHR, {useClass: XHRImpl}), + BROWSER_APP_COMMON_PROVIDERS, + new Provider(XHR, {useClass: XHRImpl}), ADDITIONAL_TEST_BROWSER_PROVIDERS ]); diff --git a/modules/angular2/platform/testing/server.ts b/modules/angular2/platform/testing/server.ts index 97f7f8f26f..a6bdb3c3b1 100644 --- a/modules/angular2/platform/testing/server.ts +++ b/modules/angular2/platform/testing/server.ts @@ -1,4 +1,14 @@ -import {APP_ID, DirectiveResolver, NgZone, Provider, ViewResolver, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, APPLICATION_COMMON_PROVIDERS, Renderer} from 'angular2/core'; +import { + APP_ID, + DirectiveResolver, + NgZone, + Provider, + ViewResolver, + PLATFORM_COMMON_PROVIDERS, + PLATFORM_INITIALIZER, + APPLICATION_COMMON_PROVIDERS, + Renderer +} from 'angular2/core'; import {Parse5DomAdapter} from 'angular2/src/platform/server/parse5_adapter'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; @@ -20,7 +30,11 @@ import {RootRenderer} from 'angular2/src/core/render/api'; import {DomRootRenderer, DomRootRenderer_} from 'angular2/src/platform/dom/dom_renderer'; import {DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; -import {EventManager, EVENT_MANAGER_PLUGINS, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/common_dom'; +import { + EventManager, + EVENT_MANAGER_PLUGINS, + ELEMENT_PROBE_PROVIDERS +} from 'angular2/platform/common_dom'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; import {CONST_EXPR} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/platform/worker_app.ts b/modules/angular2/platform/worker_app.ts index 0d17735036..d3b255c430 100644 --- a/modules/angular2/platform/worker_app.ts +++ b/modules/angular2/platform/worker_app.ts @@ -1,7 +1,19 @@ -export {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION_COMMON} from 'angular2/src/platform/worker_app_common'; +export { + WORKER_APP_PLATFORM, + WORKER_APP_APPLICATION_COMMON +} from 'angular2/src/platform/worker_app_common'; export {WORKER_APP_APPLICATION} from 'angular2/src/platform/worker_app'; -export {ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments} from 'angular2/src/web_workers/shared/client_message_broker'; -export {ReceivedMessage, ServiceMessageBroker, ServiceMessageBrokerFactory} from 'angular2/src/web_workers/shared/service_message_broker'; +export { + ClientMessageBroker, + ClientMessageBrokerFactory, + FnArg, + UiArguments +} from 'angular2/src/web_workers/shared/client_message_broker'; +export { + ReceivedMessage, + ServiceMessageBroker, + ServiceMessageBrokerFactory +} from 'angular2/src/web_workers/shared/service_message_broker'; export {PRIMITIVE} from 'angular2/src/web_workers/shared/serializer'; export * from 'angular2/src/web_workers/shared/message_bus'; export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint'; diff --git a/modules/angular2/platform/worker_render.ts b/modules/angular2/platform/worker_render.ts index 41281325ee..b6b7f3ffa5 100644 --- a/modules/angular2/platform/worker_render.ts +++ b/modules/angular2/platform/worker_render.ts @@ -1,7 +1,21 @@ -export {WORKER_SCRIPT, WORKER_RENDER_PLATFORM, initializeGenericWorkerRenderer, WORKER_RENDER_APPLICATION_COMMON} from 'angular2/src/platform/worker_render_common'; +export { + WORKER_SCRIPT, + WORKER_RENDER_PLATFORM, + initializeGenericWorkerRenderer, + WORKER_RENDER_APPLICATION_COMMON +} from 'angular2/src/platform/worker_render_common'; export {WORKER_RENDER_APPLICATION, WebWorkerInstance} from 'angular2/src/platform/worker_render'; -export {ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments} from '../src/web_workers/shared/client_message_broker'; -export {ReceivedMessage, ServiceMessageBroker, ServiceMessageBrokerFactory} from '../src/web_workers/shared/service_message_broker'; +export { + ClientMessageBroker, + ClientMessageBrokerFactory, + FnArg, + UiArguments +} from '../src/web_workers/shared/client_message_broker'; +export { + ReceivedMessage, + ServiceMessageBroker, + ServiceMessageBrokerFactory +} from '../src/web_workers/shared/service_message_broker'; export {PRIMITIVE} from '../src/web_workers/shared/serializer'; export * from '../src/web_workers/shared/message_bus'; import {WORKER_RENDER_APPLICATION} from 'angular2/src/platform/worker_render'; diff --git a/modules/angular2/src/animate/animation.ts b/modules/angular2/src/animate/animation.ts index ae5f75bd97..49e14a120a 100644 --- a/modules/angular2/src/animate/animation.ts +++ b/modules/angular2/src/animate/animation.ts @@ -1,4 +1,10 @@ -import {DateWrapper, StringWrapper, RegExpWrapper, NumberWrapper, isPresent} from 'angular2/src/facade/lang'; +import { + DateWrapper, + StringWrapper, + RegExpWrapper, + NumberWrapper, + isPresent +} from 'angular2/src/facade/lang'; import {Math} from 'angular2/src/facade/math'; import {camelCaseToDashCase} from 'angular2/src/platform/dom/util'; import {StringMapWrapper} from 'angular2/src/facade/collection'; @@ -41,9 +47,8 @@ export class Animation { * @param data * @param browserDetails */ - constructor( - public element: HTMLElement, public data: CssAnimationOptions, - public browserDetails: BrowserDetails) { + constructor(public element: HTMLElement, public data: CssAnimationOptions, + public browserDetails: BrowserDetails) { this.startTime = DateWrapper.toMillis(DateWrapper.now()); this._stringPrefix = DOM.getAnimationPrefix(); this.setup(); @@ -75,16 +80,15 @@ export class Animation { this.removeClasses(this.data.classesToRemove); if (this.data.toStyles != null) this.applyStyles(this.data.toStyles); var computedStyles = DOM.getComputedStyle(this.element); - this.computedDelay = Math.max( - this.parseDurationString( - computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), - this.parseDurationString( - this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay'))); - this.computedDuration = Math.max( - this.parseDurationString( - computedStyles.getPropertyValue(this._stringPrefix + 'transition-duration')), - this.parseDurationString( - this.element.style.getPropertyValue(this._stringPrefix + 'transition-duration'))); + this.computedDelay = + Math.max(this.parseDurationString( + computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), + this.parseDurationString( + this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay'))); + this.computedDuration = Math.max(this.parseDurationString(computedStyles.getPropertyValue( + this._stringPrefix + 'transition-duration')), + this.parseDurationString(this.element.style.getPropertyValue( + this._stringPrefix + 'transition-duration'))); this.addEvents(); } diff --git a/modules/angular2/src/common/directives/core_directives.ts b/modules/angular2/src/common/directives/core_directives.ts index 39b83e914b..64772e101a 100644 --- a/modules/angular2/src/common/directives/core_directives.ts +++ b/modules/angular2/src/common/directives/core_directives.ts @@ -47,5 +47,13 @@ import {NgPlural, NgPluralCase} from './ng_plural'; * ``` */ export const CORE_DIRECTIVES: Type[] = CONST_EXPR([ - NgClass, NgFor, NgIf, NgStyle, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgPlural, NgPluralCase + NgClass, + NgFor, + NgIf, + NgStyle, + NgSwitch, + NgSwitchWhen, + NgSwitchDefault, + NgPlural, + NgPluralCase ]); diff --git a/modules/angular2/src/common/directives/ng_class.ts b/modules/angular2/src/common/directives/ng_class.ts index 2ce3d0fe16..0b997a8a88 100644 --- a/modules/angular2/src/common/directives/ng_class.ts +++ b/modules/angular2/src/common/directives/ng_class.ts @@ -1,5 +1,17 @@ import {isPresent, isString, isArray} from 'angular2/src/facade/lang'; -import {DoCheck, OnDestroy, Directive, ElementRef, IterableDiffers, KeyValueDiffers, Renderer, IterableDiffer, KeyValueDiffer, CollectionChangeRecord, KeyValueChangeRecord} from 'angular2/core'; +import { + DoCheck, + OnDestroy, + Directive, + ElementRef, + IterableDiffers, + KeyValueDiffers, + Renderer, + IterableDiffer, + KeyValueDiffer, + CollectionChangeRecord, + KeyValueChangeRecord +} from 'angular2/core'; import {StringMapWrapper, isListLikeIterable} from 'angular2/src/facade/collection'; /** @@ -66,11 +78,10 @@ export class NgClass implements DoCheck, OnDestroy { private _iterableDiffer: IterableDiffer; private _keyValueDiffer: KeyValueDiffer; private _initialClasses: string[] = []; - private _rawClass: string[]|Set<string>; + private _rawClass: string[] | Set<string>; - constructor( - private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers, - private _ngEl: ElementRef, private _renderer: Renderer) {} + constructor(private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers, + private _ngEl: ElementRef, private _renderer: Renderer) {} set initialClasses(v: string) { this._applyInitialClasses(true); @@ -79,14 +90,14 @@ export class NgClass implements DoCheck, OnDestroy { this._applyClasses(this._rawClass, false); } - set rawClass(v: string|string[]|Set<string>|{[key: string]: any}) { + set rawClass(v: string | string[] | Set<string>| {[key: string]: any}) { this._cleanupClasses(this._rawClass); if (isString(v)) { v = (<string>v).split(' '); } - this._rawClass = <string[]|Set<string>>v; + this._rawClass = <string[] | Set<string>>v; this._iterableDiffer = null; this._keyValueDiffer = null; if (isPresent(v)) { @@ -115,7 +126,7 @@ export class NgClass implements DoCheck, OnDestroy { ngOnDestroy(): void { this._cleanupClasses(this._rawClass); } - private _cleanupClasses(rawClassVal: string[]|Set<string>|{[key: string]: any}): void { + private _cleanupClasses(rawClassVal: string[] | Set<string>| {[key: string]: any}): void { this._applyClasses(rawClassVal, true); this._applyInitialClasses(false); } @@ -143,18 +154,18 @@ export class NgClass implements DoCheck, OnDestroy { this._initialClasses.forEach(className => this._toggleClass(className, !isCleanup)); } - private _applyClasses( - rawClassVal: string[]|Set<string>|{[key: string]: any}, isCleanup: boolean) { + private _applyClasses(rawClassVal: string[] | Set<string>| {[key: string]: any}, + isCleanup: boolean) { if (isPresent(rawClassVal)) { if (isArray(rawClassVal)) { (<string[]>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup)); } else if (rawClassVal instanceof Set) { (<Set<string>>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup)); } else { - StringMapWrapper.forEach( - <{[k: string]: any}>rawClassVal, (expVal: any, className: string) => { - if (isPresent(expVal)) this._toggleClass(className, !isCleanup); - }); + StringMapWrapper.forEach(<{[k: string]: any}>rawClassVal, + (expVal: any, className: string) => { + if (isPresent(expVal)) this._toggleClass(className, !isCleanup); + }); } } } diff --git a/modules/angular2/src/common/directives/ng_for.ts b/modules/angular2/src/common/directives/ng_for.ts index 7c64c581cc..07267ee632 100644 --- a/modules/angular2/src/common/directives/ng_for.ts +++ b/modules/angular2/src/common/directives/ng_for.ts @@ -1,7 +1,20 @@ -import {DoCheck, Directive, ChangeDetectorRef, IterableDiffer, IterableDiffers, ViewContainerRef, TemplateRef, EmbeddedViewRef, TrackByFn} from 'angular2/core'; +import { + DoCheck, + Directive, + ChangeDetectorRef, + IterableDiffer, + IterableDiffers, + ViewContainerRef, + TemplateRef, + EmbeddedViewRef, + TrackByFn +} from 'angular2/core'; import {isPresent, isBlank, stringify, getTypeNameForDebugging} from 'angular2/src/facade/lang'; -import {DefaultIterableDiffer, CollectionChangeRecord} from '../../core/change_detection/differs/default_iterable_differ'; -import {BaseException} from '../../facade/exceptions'; +import { + DefaultIterableDiffer, + CollectionChangeRecord +} from "../../core/change_detection/differs/default_iterable_differ"; +import {BaseException} from "../../facade/exceptions"; /** * The `NgFor` directive instantiates a template once per item from an iterable. The context for @@ -62,9 +75,8 @@ export class NgFor implements DoCheck { _ngForTrackBy: TrackByFn; private _differ: IterableDiffer; - constructor( - private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef, - private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {} + constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef, + private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {} set ngForOf(value: any) { this._ngForOf = value; @@ -97,19 +109,16 @@ export class NgFor implements DoCheck { // TODO(rado): check if change detection can produce a change record that is // easier to consume than current. var recordViewTuples: RecordViewTuple[] = []; - changes.forEachRemovedItem( - (removedRecord: CollectionChangeRecord) => - recordViewTuples.push(new RecordViewTuple(removedRecord, null))); + changes.forEachRemovedItem((removedRecord: CollectionChangeRecord) => + recordViewTuples.push(new RecordViewTuple(removedRecord, null))); - changes.forEachMovedItem( - (movedRecord: CollectionChangeRecord) => - recordViewTuples.push(new RecordViewTuple(movedRecord, null))); + changes.forEachMovedItem((movedRecord: CollectionChangeRecord) => + recordViewTuples.push(new RecordViewTuple(movedRecord, null))); var insertTuples = this._bulkRemove(recordViewTuples); - changes.forEachAddedItem( - (addedRecord: CollectionChangeRecord) => - insertTuples.push(new RecordViewTuple(addedRecord, null))); + changes.forEachAddedItem((addedRecord: CollectionChangeRecord) => + insertTuples.push(new RecordViewTuple(addedRecord, null))); this._bulkInsert(insertTuples); @@ -137,9 +146,8 @@ export class NgFor implements DoCheck { } private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] { - tuples.sort( - (a: RecordViewTuple, b: RecordViewTuple) => - a.record.previousIndex - b.record.previousIndex); + tuples.sort((a: RecordViewTuple, b: RecordViewTuple) => + a.record.previousIndex - b.record.previousIndex); var movedTuples: RecordViewTuple[] = []; for (var i = tuples.length - 1; i >= 0; i--) { var tuple = tuples[i]; diff --git a/modules/angular2/src/common/directives/ng_plural.ts b/modules/angular2/src/common/directives/ng_plural.ts index 28ac39adae..e5e892c862 100644 --- a/modules/angular2/src/common/directives/ng_plural.ts +++ b/modules/angular2/src/common/directives/ng_plural.ts @@ -1,4 +1,13 @@ -import {Directive, ViewContainerRef, TemplateRef, ContentChildren, QueryList, Attribute, AfterContentInit, Input} from 'angular2/core'; +import { + Directive, + ViewContainerRef, + TemplateRef, + ContentChildren, + QueryList, + Attribute, + AfterContentInit, + Input +} from 'angular2/core'; import {isPresent, NumberWrapper} from 'angular2/src/facade/lang'; import {Map} from 'angular2/src/facade/collection'; import {SwitchView} from './ng_switch'; @@ -67,9 +76,8 @@ export abstract class NgLocalization { abstract getPluralCategory(value: any): s export class NgPluralCase { /** @internal */ _view: SwitchView; - constructor( - @Attribute('ngPluralCase') public value: string, template: TemplateRef, - viewContainer: ViewContainerRef) { + constructor(@Attribute('ngPluralCase') public value: string, template: TemplateRef, + viewContainer: ViewContainerRef) { this._view = new SwitchView(viewContainer, template); } } @@ -127,7 +135,7 @@ export class NgPlural implements AfterContentInit { } /** @internal */ - _isValueView(pluralCase: NgPluralCase): boolean { return pluralCase.value[0] === '='; } + _isValueView(pluralCase: NgPluralCase): boolean { return pluralCase.value[0] === "="; } /** @internal */ _formatValue(pluralCase: NgPluralCase): any { diff --git a/modules/angular2/src/common/directives/ng_style.ts b/modules/angular2/src/common/directives/ng_style.ts index ed9bcc5b04..3b5824277f 100644 --- a/modules/angular2/src/common/directives/ng_style.ts +++ b/modules/angular2/src/common/directives/ng_style.ts @@ -1,6 +1,13 @@ -import {DoCheck, KeyValueDiffer, KeyValueDiffers, ElementRef, Directive, Renderer} from 'angular2/core'; +import { + DoCheck, + KeyValueDiffer, + KeyValueDiffers, + ElementRef, + Directive, + Renderer +} from 'angular2/core'; import {isPresent, isBlank, print} from 'angular2/src/facade/lang'; -import {KeyValueChangeRecord} from '../../core/change_detection/differs/default_keyvalue_differ'; +import {KeyValueChangeRecord} from "../../core/change_detection/differs/default_keyvalue_differ"; /** * The `NgStyle` directive changes styles based on a result of expression evaluation. @@ -60,8 +67,8 @@ export class NgStyle implements DoCheck { /** @internal */ _differ: KeyValueDiffer; - constructor( - private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {} + constructor(private _differs: KeyValueDiffers, private _ngEl: ElementRef, + private _renderer: Renderer) {} set rawStyle(v: {[key: string]: string}) { this._rawStyle = v; diff --git a/modules/angular2/src/common/directives/ng_switch.ts b/modules/angular2/src/common/directives/ng_switch.ts index 4ef5b9c769..62afe01b60 100644 --- a/modules/angular2/src/common/directives/ng_switch.ts +++ b/modules/angular2/src/common/directives/ng_switch.ts @@ -175,8 +175,8 @@ export class NgSwitchWhen { _view: SwitchView; private _switch: NgSwitch; - constructor( - viewContainer: ViewContainerRef, templateRef: TemplateRef, @Host() ngSwitch: NgSwitch) { + constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef, + @Host() ngSwitch: NgSwitch) { this._switch = ngSwitch; this._view = new SwitchView(viewContainer, templateRef); } @@ -195,8 +195,8 @@ export class NgSwitchWhen { */ @Directive({selector: '[ngSwitchDefault]'}) export class NgSwitchDefault { - constructor( - viewContainer: ViewContainerRef, templateRef: TemplateRef, @Host() sswitch: NgSwitch) { + constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef, + @Host() sswitch: NgSwitch) { sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef)); } } diff --git a/modules/angular2/src/common/forms.ts b/modules/angular2/src/common/forms.ts index 6a870f8164..f25b8067c2 100644 --- a/modules/angular2/src/common/forms.ts +++ b/modules/angular2/src/common/forms.ts @@ -27,10 +27,19 @@ export {ControlValueAccessor, NG_VALUE_ACCESSOR} from './forms/directives/contro export {DefaultValueAccessor} from './forms/directives/default_value_accessor'; export {NgControlStatus} from './forms/directives/ng_control_status'; export {CheckboxControlValueAccessor} from './forms/directives/checkbox_value_accessor'; -export {NgSelectOption, SelectControlValueAccessor} from './forms/directives/select_control_value_accessor'; +export { + NgSelectOption, + SelectControlValueAccessor +} from './forms/directives/select_control_value_accessor'; export {FORM_DIRECTIVES, RadioButtonState} from './forms/directives'; export {NG_VALIDATORS, NG_ASYNC_VALIDATORS, Validators} from './forms/validators'; -export {RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator, Validator} from './forms/directives/validators'; +export { + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator, + Validator +} from './forms/directives/validators'; export {FormBuilder} from './forms/form_builder'; import {FormBuilder} from './forms/form_builder'; import {RadioControlRegistry} from './forms/directives/radio_control_value_accessor'; diff --git a/modules/angular2/src/common/forms/directives.ts b/modules/angular2/src/common/forms/directives.ts index b1df6837b4..5becfaa109 100644 --- a/modules/angular2/src/common/forms/directives.ts +++ b/modules/angular2/src/common/forms/directives.ts @@ -10,8 +10,16 @@ import {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor import {NumberValueAccessor} from './directives/number_value_accessor'; import {RadioControlValueAccessor} from './directives/radio_control_value_accessor'; import {NgControlStatus} from './directives/ng_control_status'; -import {SelectControlValueAccessor, NgSelectOption} from './directives/select_control_value_accessor'; -import {RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator} from './directives/validators'; +import { + SelectControlValueAccessor, + NgSelectOption +} from './directives/select_control_value_accessor'; +import { + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator +} from './directives/validators'; export {NgControlName} from './directives/ng_control_name'; export {NgFormControl} from './directives/ng_form_control'; @@ -21,11 +29,22 @@ export {NgFormModel} from './directives/ng_form_model'; export {NgForm} from './directives/ng_form'; export {DefaultValueAccessor} from './directives/default_value_accessor'; export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor'; -export {RadioControlValueAccessor, RadioButtonState} from './directives/radio_control_value_accessor'; +export { + RadioControlValueAccessor, + RadioButtonState +} from './directives/radio_control_value_accessor'; export {NumberValueAccessor} from './directives/number_value_accessor'; export {NgControlStatus} from './directives/ng_control_status'; -export {SelectControlValueAccessor, NgSelectOption} from './directives/select_control_value_accessor'; -export {RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator} from './directives/validators'; +export { + SelectControlValueAccessor, + NgSelectOption +} from './directives/select_control_value_accessor'; +export { + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator +} from './directives/validators'; export {NgControl} from './directives/ng_control'; export {ControlValueAccessor} from './directives/control_value_accessor'; @@ -46,12 +65,24 @@ export {ControlValueAccessor} from './directives/control_value_accessor'; * ``` */ export const FORM_DIRECTIVES: Type[] = CONST_EXPR([ - NgControlName, NgControlGroup, + NgControlName, + NgControlGroup, - NgFormControl, NgModel, NgFormModel, NgForm, + NgFormControl, + NgModel, + NgFormModel, + NgForm, - NgSelectOption, DefaultValueAccessor, NumberValueAccessor, CheckboxControlValueAccessor, - SelectControlValueAccessor, RadioControlValueAccessor, NgControlStatus, + NgSelectOption, + DefaultValueAccessor, + NumberValueAccessor, + CheckboxControlValueAccessor, + SelectControlValueAccessor, + RadioControlValueAccessor, + NgControlStatus, - RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator ]); diff --git a/modules/angular2/src/common/forms/directives/control_value_accessor.ts b/modules/angular2/src/common/forms/directives/control_value_accessor.ts index 66784979e9..90820f7d70 100644 --- a/modules/angular2/src/common/forms/directives/control_value_accessor.ts +++ b/modules/angular2/src/common/forms/directives/control_value_accessor.ts @@ -31,4 +31,4 @@ export interface ControlValueAccessor { * * See {@link DefaultValueAccessor} for how to implement one. */ -export const NG_VALUE_ACCESSOR: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValueAccessor')); \ No newline at end of file +export const NG_VALUE_ACCESSOR: OpaqueToken = CONST_EXPR(new OpaqueToken("NgValueAccessor")); \ No newline at end of file diff --git a/modules/angular2/src/common/forms/directives/ng_control_group.ts b/modules/angular2/src/common/forms/directives/ng_control_group.ts index a3b643f63f..f66b6eceb2 100644 --- a/modules/angular2/src/common/forms/directives/ng_control_group.ts +++ b/modules/angular2/src/common/forms/directives/ng_control_group.ts @@ -1,4 +1,15 @@ -import {OnInit, OnDestroy, Directive, Optional, Inject, Host, SkipSelf, forwardRef, Provider, Self} from 'angular2/core'; +import { + OnInit, + OnDestroy, + Directive, + Optional, + Inject, + Host, + SkipSelf, + forwardRef, + Provider, + Self +} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; import {ControlContainer} from './control_container'; @@ -67,10 +78,9 @@ export class NgControlGroup extends ControlContainer implements OnInit, /** @internal */ _parent: ControlContainer; - constructor( - @Host() @SkipSelf() parent: ControlContainer, - @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], - @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { + constructor(@Host() @SkipSelf() parent: ControlContainer, + @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], + @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { super(); this._parent = parent; } diff --git a/modules/angular2/src/common/forms/directives/ng_control_name.ts b/modules/angular2/src/common/forms/directives/ng_control_name.ts index 3c0bfb9813..57493193fb 100644 --- a/modules/angular2/src/common/forms/directives/ng_control_name.ts +++ b/modules/angular2/src/common/forms/directives/ng_control_name.ts @@ -1,12 +1,31 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; -import {OnChanges, OnDestroy, SimpleChange, Query, Directive, forwardRef, Host, SkipSelf, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + OnChanges, + OnDestroy, + SimpleChange, + Query, + Directive, + forwardRef, + Host, + SkipSelf, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {ControlContainer} from './control_container'; import {NgControl} from './ng_control'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; -import {controlPath, composeValidators, composeAsyncValidators, isPropertyUpdated, selectValueAccessor} from './shared'; +import { + controlPath, + composeValidators, + composeAsyncValidators, + isPropertyUpdated, + selectValueAccessor +} from './shared'; import {Control} from '../model'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {ValidatorFn, AsyncValidatorFn} from './validators'; @@ -92,37 +111,35 @@ export class NgControlName extends NgControl implements OnChanges, /* Array<Validator|Function> */ any[], @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) { - super(); - this.valueAccessor = selectValueAccessor(this, valueAccessors); - } + super(); + this.valueAccessor = selectValueAccessor(this, valueAccessors); + } - ngOnChanges(changes: {[key: string]: SimpleChange}) { - if (!this._added) { - this.formDirective.addControl(this); - this._added = true; - } - if (isPropertyUpdated(changes, this.viewModel)) { - this.viewModel = this.model; - this.formDirective.updateModel(this, this.model); - } - } + ngOnChanges(changes: {[key: string]: SimpleChange}) { + if (!this._added) { + this.formDirective.addControl(this); + this._added = true; + } + if (isPropertyUpdated(changes, this.viewModel)) { + this.viewModel = this.model; + this.formDirective.updateModel(this, this.model); + } + } - ngOnDestroy(): void { this.formDirective.removeControl(this); } + ngOnDestroy(): void { this.formDirective.removeControl(this); } - viewToModelUpdate(newValue: any): void { - this.viewModel = newValue; - ObservableWrapper.callEmit(this.update, newValue); - } + viewToModelUpdate(newValue: any): void { + this.viewModel = newValue; + ObservableWrapper.callEmit(this.update, newValue); + } - get path(): string[] { return controlPath(this.name, this._parent); } + get path(): string[] { return controlPath(this.name, this._parent); } - get formDirective(): any { return this._parent.formDirective; } + get formDirective(): any { return this._parent.formDirective; } - get validator(): ValidatorFn { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): AsyncValidatorFn { - return composeAsyncValidators(this._asyncValidators); - } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } - get control(): Control { return this.formDirective.getControl(this); } + get control(): Control { return this.formDirective.getControl(this); } } diff --git a/modules/angular2/src/common/forms/directives/ng_form.ts b/modules/angular2/src/common/forms/directives/ng_form.ts index e8524d1925..639bbf4a58 100644 --- a/modules/angular2/src/common/forms/directives/ng_form.ts +++ b/modules/angular2/src/common/forms/directives/ng_form.ts @@ -1,4 +1,9 @@ -import {PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter} from 'angular2/src/facade/async'; +import { + PromiseWrapper, + ObservableWrapper, + EventEmitter, + PromiseCompleter +} from 'angular2/src/facade/async'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive, forwardRef, Provider, Optional, Inject, Self} from 'angular2/core'; @@ -85,12 +90,11 @@ export class NgForm extends ControlContainer implements Form { form: ControlGroup; ngSubmit = new EventEmitter(); - constructor( - @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], - @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { + constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], + @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); - this.form = new ControlGroup( - {}, null, composeValidators(validators), composeAsyncValidators(asyncValidators)); + this.form = new ControlGroup({}, null, composeValidators(validators), + composeAsyncValidators(asyncValidators)); } get formDirective(): Form { return this; } diff --git a/modules/angular2/src/common/forms/directives/ng_form_control.ts b/modules/angular2/src/common/forms/directives/ng_form_control.ts index b445e32e26..b69d0d9fb5 100644 --- a/modules/angular2/src/common/forms/directives/ng_form_control.ts +++ b/modules/angular2/src/common/forms/directives/ng_form_control.ts @@ -1,12 +1,28 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; -import {OnChanges, SimpleChange, Query, Directive, forwardRef, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + OnChanges, + SimpleChange, + Query, + Directive, + forwardRef, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {NgControl} from './ng_control'; import {Control} from '../model'; import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; -import {setUpControl, composeValidators, composeAsyncValidators, isPropertyUpdated, selectValueAccessor} from './shared'; +import { + setUpControl, + composeValidators, + composeAsyncValidators, + isPropertyUpdated, + selectValueAccessor +} from './shared'; import {ValidatorFn, AsyncValidatorFn} from './validators'; const formControlBinding = @@ -78,37 +94,35 @@ export class NgFormControl extends NgControl implements OnChanges { /* Array<Validator|Function> */ any[], @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) { - super(); - this.valueAccessor = selectValueAccessor(this, valueAccessors); - } + super(); + this.valueAccessor = selectValueAccessor(this, valueAccessors); + } - ngOnChanges(changes: {[key: string]: SimpleChange}): void { - if (this._isControlChanged(changes)) { - setUpControl(this.form, this); - this.form.updateValueAndValidity({emitEvent: false}); - } - if (isPropertyUpdated(changes, this.viewModel)) { - this.form.updateValue(this.model); - this.viewModel = this.model; - } - } + ngOnChanges(changes: {[key: string]: SimpleChange}): void { + if (this._isControlChanged(changes)) { + setUpControl(this.form, this); + this.form.updateValueAndValidity({emitEvent: false}); + } + if (isPropertyUpdated(changes, this.viewModel)) { + this.form.updateValue(this.model); + this.viewModel = this.model; + } + } - get path(): string[] { return []; } + get path(): string[] { return []; } - get validator(): ValidatorFn { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): AsyncValidatorFn { - return composeAsyncValidators(this._asyncValidators); - } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } - get control(): Control { return this.form; } + get control(): Control { return this.form; } - viewToModelUpdate(newValue: any): void { - this.viewModel = newValue; - ObservableWrapper.callEmit(this.update, newValue); - } + viewToModelUpdate(newValue: any): void { + this.viewModel = newValue; + ObservableWrapper.callEmit(this.update, newValue); + } - private _isControlChanged(changes: {[key: string]: any}): boolean { - return StringMapWrapper.contains(changes, 'form'); - } + private _isControlChanged(changes: {[key: string]: any}): boolean { + return StringMapWrapper.contains(changes, "form"); + } } diff --git a/modules/angular2/src/common/forms/directives/ng_form_model.ts b/modules/angular2/src/common/forms/directives/ng_form_model.ts index fecf0aa252..26ae1dff6c 100644 --- a/modules/angular2/src/common/forms/directives/ng_form_model.ts +++ b/modules/angular2/src/common/forms/directives/ng_form_model.ts @@ -1,7 +1,16 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {ObservableWrapper, EventEmitter} from 'angular2/src/facade/async'; -import {SimpleChange, OnChanges, Directive, forwardRef, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + SimpleChange, + OnChanges, + Directive, + forwardRef, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {NgControl} from './ng_control'; import {NgControlGroup} from './ng_control_group'; import {ControlContainer} from './control_container'; @@ -99,14 +108,13 @@ export class NgFormModel extends ControlContainer implements Form, directives: NgControl[] = []; ngSubmit = new EventEmitter(); - constructor( - @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], - @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { + constructor(@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], + @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { super(); } ngOnChanges(changes: {[key: string]: SimpleChange}): void { - if (StringMapWrapper.contains(changes, 'form')) { + if (StringMapWrapper.contains(changes, "form")) { var sync = composeValidators(this._validators); this.form.validator = Validators.compose([this.form.validator, sync]); diff --git a/modules/angular2/src/common/forms/directives/ng_model.ts b/modules/angular2/src/common/forms/directives/ng_model.ts index 0188c18c7d..4bcbb960df 100644 --- a/modules/angular2/src/common/forms/directives/ng_model.ts +++ b/modules/angular2/src/common/forms/directives/ng_model.ts @@ -1,11 +1,26 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; -import {OnChanges, SimpleChange, Directive, forwardRef, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + OnChanges, + SimpleChange, + Directive, + forwardRef, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; import {NgControl} from './ng_control'; import {Control} from '../model'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; -import {setUpControl, isPropertyUpdated, selectValueAccessor, composeValidators, composeAsyncValidators} from './shared'; +import { + setUpControl, + isPropertyUpdated, + selectValueAccessor, + composeValidators, + composeAsyncValidators +} from './shared'; import {ValidatorFn, AsyncValidatorFn} from './validators'; const formControlBinding = @@ -52,35 +67,33 @@ export class NgModel extends NgControl implements OnChanges { @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[], @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) { - super(); - this.valueAccessor = selectValueAccessor(this, valueAccessors); - } + super(); + this.valueAccessor = selectValueAccessor(this, valueAccessors); + } - ngOnChanges(changes: {[key: string]: SimpleChange}) { - if (!this._added) { - setUpControl(this._control, this); - this._control.updateValueAndValidity({emitEvent: false}); - this._added = true; - } + ngOnChanges(changes: {[key: string]: SimpleChange}) { + if (!this._added) { + setUpControl(this._control, this); + this._control.updateValueAndValidity({emitEvent: false}); + this._added = true; + } - if (isPropertyUpdated(changes, this.viewModel)) { - this._control.updateValue(this.model); - this.viewModel = this.model; - } - } + if (isPropertyUpdated(changes, this.viewModel)) { + this._control.updateValue(this.model); + this.viewModel = this.model; + } + } - get control(): Control { return this._control; } + get control(): Control { return this._control; } - get path(): string[] { return []; } + get path(): string[] { return []; } - get validator(): ValidatorFn { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): AsyncValidatorFn { - return composeAsyncValidators(this._asyncValidators); - } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } - viewToModelUpdate(newValue: any): void { - this.viewModel = newValue; - ObservableWrapper.callEmit(this.update, newValue); - } + viewToModelUpdate(newValue: any): void { + this.viewModel = newValue; + ObservableWrapper.callEmit(this.update, newValue); + } } diff --git a/modules/angular2/src/common/forms/directives/normalize_validator.ts b/modules/angular2/src/common/forms/directives/normalize_validator.ts index c956c8d4ae..85e2ebdfbb 100644 --- a/modules/angular2/src/common/forms/directives/normalize_validator.ts +++ b/modules/angular2/src/common/forms/directives/normalize_validator.ts @@ -1,4 +1,4 @@ -import {AbstractControl} from '../model'; +import {AbstractControl} from "../model"; import {Validator, ValidatorFn, AsyncValidatorFn} from './validators'; export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn { diff --git a/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts b/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts index 9add896a7b..ee9475643e 100644 --- a/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts +++ b/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts @@ -1,5 +1,21 @@ -import {Directive, ElementRef, Renderer, Self, forwardRef, Provider, Attribute, Input, OnInit, OnDestroy, Injector, Injectable} from 'angular2/core'; -import {NG_VALUE_ACCESSOR, ControlValueAccessor} from 'angular2/src/common/forms/directives/control_value_accessor'; +import { + Directive, + ElementRef, + Renderer, + Self, + forwardRef, + Provider, + Attribute, + Input, + OnInit, + OnDestroy, + Injector, + Injectable +} from 'angular2/core'; +import { + NG_VALUE_ACCESSOR, + ControlValueAccessor +} from 'angular2/src/common/forms/directives/control_value_accessor'; import {NgControl} from 'angular2/src/common/forms/directives/ng_control'; import {CONST_EXPR, looseIdentical, isPresent} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -82,9 +98,8 @@ export class RadioControlValueAccessor implements ControlValueAccessor, onChange = () => {}; onTouched = () => {}; - constructor( - private _renderer: Renderer, private _elementRef: ElementRef, - private _registry: RadioControlRegistry, private _injector: Injector) {} + constructor(private _renderer: Renderer, private _elementRef: ElementRef, + private _registry: RadioControlRegistry, private _injector: Injector) {} ngOnInit(): void { this._control = this._injector.get(NgControl); diff --git a/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts b/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts index 622b25320a..afc5c85797 100644 --- a/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts +++ b/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts @@ -1,6 +1,23 @@ -import {Directive, Renderer, forwardRef, Provider, ElementRef, Input, Host, OnDestroy, Optional} from 'angular2/core'; +import { + Directive, + Renderer, + forwardRef, + Provider, + ElementRef, + Input, + Host, + OnDestroy, + Optional +} from 'angular2/core'; import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor'; -import {CONST_EXPR, StringWrapper, isPrimitive, isPresent, isBlank, looseIdentical} from 'angular2/src/facade/lang'; +import { + CONST_EXPR, + StringWrapper, + isPrimitive, + isPresent, + isBlank, + looseIdentical +} from 'angular2/src/facade/lang'; import {MapWrapper} from 'angular2/src/facade/collection'; @@ -9,12 +26,12 @@ const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider( function _buildValueString(id: string, value: any): string { if (isBlank(id)) return `${value}`; - if (!isPrimitive(value)) value = 'Object'; + if (!isPrimitive(value)) value = "Object"; return StringWrapper.slice(`${id}: ${value}`, 0, 50); } function _extractId(valueString: string): string { - return valueString.split(':')[0]; + return valueString.split(":")[0]; } /** @@ -81,9 +98,8 @@ export class SelectControlValueAccessor implements ControlValueAccessor { export class NgSelectOption implements OnDestroy { id: string; - constructor( - private _element: ElementRef, private _renderer: Renderer, - @Optional() @Host() private _select: SelectControlValueAccessor) { + constructor(private _element: ElementRef, private _renderer: Renderer, + @Optional() @Host() private _select: SelectControlValueAccessor) { if (isPresent(this._select)) this.id = this._select._registerOption(); } diff --git a/modules/angular2/src/common/forms/directives/shared.ts b/modules/angular2/src/common/forms/directives/shared.ts index 2d34500186..d4b776dd4c 100644 --- a/modules/angular2/src/common/forms/directives/shared.ts +++ b/modules/angular2/src/common/forms/directives/shared.ts @@ -25,8 +25,8 @@ export function controlPath(name: string, parent: ControlContainer): string[] { } export function setUpControl(control: Control, dir: NgControl): void { - if (isBlank(control)) _throwError(dir, 'Cannot find control'); - if (isBlank(dir.valueAccessor)) _throwError(dir, 'No value accessor for'); + if (isBlank(control)) _throwError(dir, "Cannot find control"); + if (isBlank(dir.valueAccessor)) _throwError(dir, "No value accessor for"); control.validator = Validators.compose([control.validator, dir.validator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); @@ -47,13 +47,13 @@ export function setUpControl(control: Control, dir: NgControl): void { } export function setUpControlGroup(control: ControlGroup, dir: NgControlGroup) { - if (isBlank(control)) _throwError(dir, 'Cannot find control'); + if (isBlank(control)) _throwError(dir, "Cannot find control"); control.validator = Validators.compose([control.validator, dir.validator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); } function _throwError(dir: AbstractControlDirective, message: string): void { - var path = dir.path.join(' -> '); + var path = dir.path.join(" -> "); throw new BaseException(`${message} '${path}'`); } @@ -61,23 +61,23 @@ export function composeValidators(validators: /* Array<Validator|Function> */ an return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null; } -export function composeAsyncValidators(validators: /* Array<Validator|Function> */ any[]): - AsyncValidatorFn { +export function composeAsyncValidators( + validators: /* Array<Validator|Function> */ any[]): AsyncValidatorFn { return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) : null; } export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean { - if (!StringMapWrapper.contains(changes, 'model')) return false; - var change = changes['model']; + if (!StringMapWrapper.contains(changes, "model")) return false; + var change = changes["model"]; if (change.isFirstChange()) return true; return !looseIdentical(viewModel, change.currentValue); } // TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented -export function selectValueAccessor( - dir: NgControl, valueAccessors: ControlValueAccessor[]): ControlValueAccessor { +export function selectValueAccessor(dir: NgControl, + valueAccessors: ControlValueAccessor[]): ControlValueAccessor { if (isBlank(valueAccessors)) return null; var defaultAccessor: ControlValueAccessor; @@ -87,17 +87,17 @@ export function selectValueAccessor( if (hasConstructor(v, DefaultValueAccessor)) { defaultAccessor = v; - } else if ( - hasConstructor(v, CheckboxControlValueAccessor) || hasConstructor(v, NumberValueAccessor) || - hasConstructor(v, SelectControlValueAccessor) || - hasConstructor(v, RadioControlValueAccessor)) { + } else if (hasConstructor(v, CheckboxControlValueAccessor) || + hasConstructor(v, NumberValueAccessor) || + hasConstructor(v, SelectControlValueAccessor) || + hasConstructor(v, RadioControlValueAccessor)) { if (isPresent(builtinAccessor)) - _throwError(dir, 'More than one built-in value accessor matches'); + _throwError(dir, "More than one built-in value accessor matches"); builtinAccessor = v; } else { if (isPresent(customAccessor)) - _throwError(dir, 'More than one custom value accessor matches'); + _throwError(dir, "More than one custom value accessor matches"); customAccessor = v; } }); @@ -106,6 +106,6 @@ export function selectValueAccessor( if (isPresent(builtinAccessor)) return builtinAccessor; if (isPresent(defaultAccessor)) return defaultAccessor; - _throwError(dir, 'No valid value accessor for'); + _throwError(dir, "No valid value accessor for"); return null; } diff --git a/modules/angular2/src/common/forms/directives/validators.ts b/modules/angular2/src/common/forms/directives/validators.ts index 537512b6c9..27bdf3a87f 100644 --- a/modules/angular2/src/common/forms/directives/validators.ts +++ b/modules/angular2/src/common/forms/directives/validators.ts @@ -3,7 +3,7 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {Validators, NG_VALIDATORS} from '../validators'; import {AbstractControl} from '../model'; import * as modelModule from '../model'; -import {NumberWrapper} from 'angular2/src/facade/lang'; +import {NumberWrapper} from "angular2/src/facade/lang"; @@ -74,7 +74,7 @@ const MIN_LENGTH_VALIDATOR = CONST_EXPR( export class MinLengthValidator implements Validator { private _validator: ValidatorFn; - constructor(@Attribute('minlength') minLength: string) { + constructor(@Attribute("minlength") minLength: string) { this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10)); } @@ -102,7 +102,7 @@ const MAX_LENGTH_VALIDATOR = CONST_EXPR( export class MaxLengthValidator implements Validator { private _validator: ValidatorFn; - constructor(@Attribute('maxlength') maxLength: string) { + constructor(@Attribute("maxlength") maxLength: string) { this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10)); } @@ -131,7 +131,7 @@ const PATTERN_VALIDATOR = CONST_EXPR( export class PatternValidator implements Validator { private _validator: ValidatorFn; - constructor(@Attribute('pattern') pattern: string) { + constructor(@Attribute("pattern") pattern: string) { this._validator = Validators.pattern(pattern); } diff --git a/modules/angular2/src/common/forms/form_builder.ts b/modules/angular2/src/common/forms/form_builder.ts index 467b9e3ea4..960192eaa6 100644 --- a/modules/angular2/src/common/forms/form_builder.ts +++ b/modules/angular2/src/common/forms/form_builder.ts @@ -54,21 +54,21 @@ export class FormBuilder { * * See the {@link ControlGroup} constructor for more details. */ - group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): - modelModule.ControlGroup { + group(controlsConfig: {[key: string]: any}, + extra: {[key: string]: any} = null): modelModule.ControlGroup { var controls = this._reduceControls(controlsConfig); var optionals = <{[key: string]: boolean}>( - isPresent(extra) ? StringMapWrapper.get(extra, 'optionals') : null); - var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null; + isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null); + var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null; var asyncValidator: AsyncValidatorFn = - isPresent(extra) ? StringMapWrapper.get(extra, 'asyncValidator') : null; + isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null; return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); } /** * Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`. */ - control(value: Object, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null): - modelModule.Control { + control(value: Object, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null): modelModule.Control { return new modelModule.Control(value, validator, asyncValidator); } @@ -76,16 +76,15 @@ export class FormBuilder { * Construct an array of {@link Control}s from the given `controlsConfig` array of * configuration, with the given optional `validator` and `asyncValidator`. */ - array( - controlsConfig: any[], validator: ValidatorFn = null, - asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray { + array(controlsConfig: any[], validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray { var controls = controlsConfig.map(c => this._createControl(c)); return new modelModule.ControlArray(controls, validator, asyncValidator); } /** @internal */ - _reduceControls(controlsConfig: {[k: string]: any}): - {[key: string]: modelModule.AbstractControl} { + _reduceControls(controlsConfig: {[k: string]: + any}): {[key: string]: modelModule.AbstractControl} { var controls: {[key: string]: modelModule.AbstractControl} = {}; StringMapWrapper.forEach(controlsConfig, (controlConfig: any, controlName: string) => { controls[controlName] = this._createControl(controlConfig); diff --git a/modules/angular2/src/common/forms/model.ts b/modules/angular2/src/common/forms/model.ts index b50fe8717a..5e032223ee 100644 --- a/modules/angular2/src/common/forms/model.ts +++ b/modules/angular2/src/common/forms/model.ts @@ -7,41 +7,42 @@ import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; /** * Indicates that a Control is valid, i.e. that no errors exist in the input value. */ -export const VALID = 'VALID'; +export const VALID = "VALID"; /** * Indicates that a Control is invalid, i.e. that an error exists in the input value. */ -export const INVALID = 'INVALID'; +export const INVALID = "INVALID"; /** * Indicates that a Control is pending, i.e. that async validation is occurring and * errors are not yet available for the input value. */ -export const PENDING = 'PENDING'; +export const PENDING = "PENDING"; export function isControl(control: Object): boolean { return control instanceof AbstractControl; } -function _find(control: AbstractControl, path: Array<string|number>| string) { +function _find(control: AbstractControl, path: Array<string | number>| string) { if (isBlank(path)) return null; if (!(path instanceof Array)) { - path = (<string>path).split('/'); + path = (<string>path).split("/"); } if (path instanceof Array && ListWrapper.isEmpty(path)) return null; - return (<Array<string|number>>path).reduce((v, name) => { - if (v instanceof ControlGroup) { - return isPresent(v.controls[name]) ? v.controls[name] : null; - } else if (v instanceof ControlArray) { - var index = <number>name; - return isPresent(v.at(index)) ? v.at(index) : null; - } else { - return null; - } - }, control); + return (<Array<string | number>>path) + .reduce((v, name) => { + if (v instanceof ControlGroup) { + return isPresent(v.controls[name]) ? v.controls[name] : null; + } else if (v instanceof ControlArray) { + var index = <number>name; + return isPresent(v.at(index)) ? v.at(index) : null; + } else { + return null; + } + }, control); } function toObservable(r: any): Observable<any> { @@ -61,7 +62,7 @@ export abstract class AbstractControl { private _errors: {[key: string]: any}; private _pristine: boolean = true; private _touched: boolean = false; - private _parent: ControlGroup|ControlArray; + private _parent: ControlGroup | ControlArray; private _asyncValidationSubscription: any; constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {} @@ -111,10 +112,10 @@ export abstract class AbstractControl { } } - setParent(parent: ControlGroup|ControlArray): void { this._parent = parent; } + setParent(parent: ControlGroup | ControlArray): void { this._parent = parent; } - updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): - void { + updateValueAndValidity( + {onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { onlySelf = normalizeBool(onlySelf); emitEvent = isPresent(emitEvent) ? emitEvent : true; @@ -195,7 +196,7 @@ export abstract class AbstractControl { } } - find(path: Array<string|number>|string): AbstractControl { return _find(this, path); } + find(path: Array<string | number>| string): AbstractControl { return _find(this, path); } getError(errorCode: string, path: string[] = null): any { var control = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this; @@ -270,8 +271,8 @@ export class Control extends AbstractControl { /** @internal */ _onChange: Function; - constructor( - value: any = null, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) { + constructor(value: any = null, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._value = value; this.updateValueAndValidity({onlySelf: true, emitEvent: false}); @@ -334,9 +335,9 @@ export class Control extends AbstractControl { export class ControlGroup extends AbstractControl { private _optionals: {[key: string]: boolean}; - constructor( - public controls: {[key: string]: AbstractControl}, optionals: {[key: string]: boolean} = null, - validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) { + constructor(public controls: {[key: string]: AbstractControl}, + optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._optionals = isPresent(optionals) ? optionals : {}; this._initObservables(); @@ -449,9 +450,8 @@ export class ControlGroup extends AbstractControl { * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) */ export class ControlArray extends AbstractControl { - constructor( - public controls: AbstractControl[], validator: ValidatorFn = null, - asyncValidator: AsyncValidatorFn = null) { + constructor(public controls: AbstractControl[], validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._initObservables(); this._setParentForControls(); diff --git a/modules/angular2/src/common/forms/validators.ts b/modules/angular2/src/common/forms/validators.ts index f1066c50f7..7663b7263e 100644 --- a/modules/angular2/src/common/forms/validators.ts +++ b/modules/angular2/src/common/forms/validators.ts @@ -16,7 +16,7 @@ import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; * * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'} */ -export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValidators')); +export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken("NgValidators")); /** * Providers for asynchronous validators to be used for {@link Control}s @@ -26,7 +26,7 @@ export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValidato * * See {@link NG_VALIDATORS} for more details. */ -export const NG_ASYNC_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgAsyncValidators')); +export const NG_ASYNC_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken("NgAsyncValidators")); /** * Provides a set of validators used by form controls. @@ -45,9 +45,9 @@ export class Validators { * Validator that requires controls to have a non-empty value. */ static required(control: modelModule.AbstractControl): {[key: string]: boolean} { - return isBlank(control.value) || (isString(control.value) && control.value == '') ? - {'required': true} : - null; + return isBlank(control.value) || (isString(control.value) && control.value == "") ? + {"required": true} : + null; } /** @@ -58,8 +58,8 @@ export class Validators { if (isPresent(Validators.required(control))) return null; var v: string = control.value; return v.length < minLength ? - {'minlength': {'requiredLength': minLength, 'actualLength': v.length}} : - null; + {"minlength": {"requiredLength": minLength, "actualLength": v.length}} : + null; }; } @@ -71,8 +71,8 @@ export class Validators { if (isPresent(Validators.required(control))) return null; var v: string = control.value; return v.length > maxLength ? - {'maxlength': {'requiredLength': maxLength, 'actualLength': v.length}} : - null; + {"maxlength": {"requiredLength": maxLength, "actualLength": v.length}} : + null; }; } @@ -85,7 +85,7 @@ export class Validators { let regex = new RegExp(`^${pattern}$`); let v: string = control.value; return regex.test(v) ? null : - {'pattern': {'requiredPattern': `^${pattern}$`, 'actualValue': v}}; + {"pattern": {"requiredPattern": `^${pattern}$`, "actualValue": v}}; }; } @@ -124,13 +124,13 @@ function _convertToPromise(obj: any): any { return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); } -function _executeValidators( - control: modelModule.AbstractControl, validators: ValidatorFn[]): any[] { +function _executeValidators(control: modelModule.AbstractControl, + validators: ValidatorFn[]): any[] { return validators.map(v => v(control)); } -function _executeAsyncValidators( - control: modelModule.AbstractControl, validators: AsyncValidatorFn[]): any[] { +function _executeAsyncValidators(control: modelModule.AbstractControl, + validators: AsyncValidatorFn[]): any[] { return validators.map(v => v(control)); } diff --git a/modules/angular2/src/common/pipes/async_pipe.ts b/modules/angular2/src/common/pipes/async_pipe.ts index 78f3efdeed..9131cfb147 100644 --- a/modules/angular2/src/common/pipes/async_pipe.ts +++ b/modules/angular2/src/common/pipes/async_pipe.ts @@ -1,6 +1,13 @@ import {isBlank, isPresent, isPromise, CONST} from 'angular2/src/facade/lang'; import {ObservableWrapper, Observable, EventEmitter} from 'angular2/src/facade/async'; -import {Pipe, Injectable, ChangeDetectorRef, OnDestroy, PipeTransform, WrappedValue} from 'angular2/core'; +import { + Pipe, + Injectable, + ChangeDetectorRef, + OnDestroy, + PipeTransform, + WrappedValue +} from 'angular2/core'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; @@ -57,7 +64,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { /** @internal */ _subscription: Object = null; /** @internal */ - _obj: Observable<any>|Promise<any>|EventEmitter<any> = null; + _obj: Observable<any>| Promise<any>| EventEmitter<any> = null; private _strategy: any = null; /** @internal */ public _ref: ChangeDetectorRef; @@ -69,7 +76,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { } } - transform(obj: Observable<any>|Promise<any>|EventEmitter<any>, args?: any[]): any { + transform(obj: Observable<any>| Promise<any>| EventEmitter<any>, args?: any[]): any { if (isBlank(this._obj)) { if (isPresent(obj)) { this._subscribe(obj); @@ -92,7 +99,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { } /** @internal */ - _subscribe(obj: Observable<any>|Promise<any>|EventEmitter<any>): void { + _subscribe(obj: Observable<any>| Promise<any>| EventEmitter<any>): void { this._obj = obj; this._strategy = this._selectStrategy(obj); this._subscription = this._strategy.createSubscription( @@ -100,7 +107,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { } /** @internal */ - _selectStrategy(obj: Observable<any>|Promise<any>|EventEmitter<any>): any { + _selectStrategy(obj: Observable<any>| Promise<any>| EventEmitter<any>): any { if (isPromise(obj)) { return _promiseStrategy; } else if (ObservableWrapper.isObservable(obj)) { diff --git a/modules/angular2/src/common/pipes/common_pipes.ts b/modules/angular2/src/common/pipes/common_pipes.ts index d16e86ca71..cc92c09f20 100644 --- a/modules/angular2/src/common/pipes/common_pipes.ts +++ b/modules/angular2/src/common/pipes/common_pipes.ts @@ -23,6 +23,16 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; * property of the `@Component` decorator. */ export const COMMON_PIPES = CONST_EXPR([ - AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, - CurrencyPipe, DatePipe, ReplacePipe, I18nPluralPipe, I18nSelectPipe + AsyncPipe, + UpperCasePipe, + LowerCasePipe, + JsonPipe, + SlicePipe, + DecimalPipe, + PercentPipe, + CurrencyPipe, + DatePipe, + ReplacePipe, + I18nPluralPipe, + I18nSelectPipe ]); diff --git a/modules/angular2/src/common/pipes/date_pipe.ts b/modules/angular2/src/common/pipes/date_pipe.ts index 8813892774..27f38308a6 100644 --- a/modules/angular2/src/common/pipes/date_pipe.ts +++ b/modules/angular2/src/common/pipes/date_pipe.ts @@ -1,4 +1,13 @@ -import {isDate, isNumber, isPresent, Date, DateWrapper, CONST, isBlank, FunctionWrapper} from 'angular2/src/facade/lang'; +import { + isDate, + isNumber, + isPresent, + Date, + DateWrapper, + CONST, + isBlank, + FunctionWrapper +} from 'angular2/src/facade/lang'; import {DateFormatter} from 'angular2/src/facade/intl'; import {PipeTransform, WrappedValue, Pipe, Injectable} from 'angular2/core'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; diff --git a/modules/angular2/src/common/pipes/i18n_plural_pipe.ts b/modules/angular2/src/common/pipes/i18n_plural_pipe.ts index 229f48bbf2..0501441e3a 100644 --- a/modules/angular2/src/common/pipes/i18n_plural_pipe.ts +++ b/modules/angular2/src/common/pipes/i18n_plural_pipe.ts @@ -1,4 +1,10 @@ -import {CONST, isStringMap, StringWrapper, isPresent, RegExpWrapper} from 'angular2/src/facade/lang'; +import { + CONST, + isStringMap, + StringWrapper, + isPresent, + RegExpWrapper +} from 'angular2/src/facade/lang'; import {Injectable, PipeTransform, Pipe} from 'angular2/core'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; diff --git a/modules/angular2/src/common/pipes/number_pipe.ts b/modules/angular2/src/common/pipes/number_pipe.ts index 9ab437b142..d26bd53128 100644 --- a/modules/angular2/src/common/pipes/number_pipe.ts +++ b/modules/angular2/src/common/pipes/number_pipe.ts @@ -1,4 +1,13 @@ -import {isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, CONST, FunctionWrapper} from 'angular2/src/facade/lang'; +import { + isNumber, + isPresent, + isBlank, + StringWrapper, + NumberWrapper, + RegExpWrapper, + CONST, + FunctionWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/facade/intl'; import {Injectable, PipeTransform, WrappedValue, Pipe} from 'angular2/core'; @@ -16,9 +25,8 @@ var _re = RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$'); @Injectable() export class NumberPipe { /** @internal */ - static _format( - value: number, style: NumberFormatStyle, digits: string, currency: string = null, - currencyAsSymbol: boolean = false): string { + static _format(value: number, style: NumberFormatStyle, digits: string, currency: string = null, + currencyAsSymbol: boolean = false): string { if (isBlank(value)) return null; if (!isNumber(value)) { throw new InvalidPipeArgumentException(NumberPipe, value); @@ -139,7 +147,7 @@ export class CurrencyPipe extends NumberPipe implements PipeTransform { var currencyCode: string = isPresent(args) && args.length > 0 ? args[0] : 'USD'; var symbolDisplay: boolean = isPresent(args) && args.length > 1 ? args[1] : false; var digits: string = isPresent(args) && args.length > 2 ? args[2] : null; - return NumberPipe._format( - value, NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay); + return NumberPipe._format(value, NumberFormatStyle.Currency, digits, currencyCode, + symbolDisplay); } } diff --git a/modules/angular2/src/common/pipes/replace_pipe.ts b/modules/angular2/src/common/pipes/replace_pipe.ts index 6e19ba0276..de3c0e9f73 100644 --- a/modules/angular2/src/common/pipes/replace_pipe.ts +++ b/modules/angular2/src/common/pipes/replace_pipe.ts @@ -1,4 +1,11 @@ -import {isBlank, isString, isNumber, isFunction, RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang'; +import { + isBlank, + isString, + isNumber, + isFunction, + RegExpWrapper, + StringWrapper +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {Injectable, PipeTransform, Pipe} from 'angular2/core'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; diff --git a/modules/angular2/src/compiler/change_definition_factory.ts b/modules/angular2/src/compiler/change_definition_factory.ts index f7ad44e53c..51b8f61263 100644 --- a/modules/angular2/src/compiler/change_definition_factory.ts +++ b/modules/angular2/src/compiler/change_definition_factory.ts @@ -2,10 +2,34 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; import {reflector} from 'angular2/src/core/reflection/reflection'; -import {DirectiveIndex, BindingRecord, DirectiveRecord, ChangeDetectionStrategy, ChangeDetectorDefinition, ChangeDetectorGenConfig, ASTWithSource} from 'angular2/src/core/change_detection/change_detection'; +import { + DirectiveIndex, + BindingRecord, + DirectiveRecord, + ChangeDetectionStrategy, + ChangeDetectorDefinition, + ChangeDetectorGenConfig, + ASTWithSource +} from 'angular2/src/core/change_detection/change_detection'; import {CompileDirectiveMetadata, CompileTypeMetadata} from './directive_metadata'; -import {TemplateAst, ElementAst, BoundTextAst, PropertyBindingType, DirectiveAst, TemplateAstVisitor, templateVisitAll, NgContentAst, EmbeddedTemplateAst, VariableAst, BoundElementPropertyAst, BoundEventAst, BoundDirectivePropertyAst, AttrAst, TextAst} from './template_ast'; +import { + TemplateAst, + ElementAst, + BoundTextAst, + PropertyBindingType, + DirectiveAst, + TemplateAstVisitor, + templateVisitAll, + NgContentAst, + EmbeddedTemplateAst, + VariableAst, + BoundElementPropertyAst, + BoundEventAst, + BoundDirectivePropertyAst, + AttrAst, + TextAst +} from './template_ast'; import {LifecycleHooks} from 'angular2/src/core/linker/interfaces'; export function createChangeDetectorDefinitions( @@ -26,9 +50,8 @@ class ProtoViewVisitor implements TemplateAstVisitor { eventRecords: BindingRecord[] = []; directiveRecords: DirectiveRecord[] = []; - constructor( - public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[], - public strategy: ChangeDetectionStrategy) { + constructor(public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[], + public strategy: ChangeDetectionStrategy) { this.viewIndex = allVisitors.length; allVisitors.push(this); } @@ -73,9 +96,10 @@ class ProtoViewVisitor implements TemplateAstVisitor { } visitEvent(ast: BoundEventAst, directiveRecord: DirectiveRecord): any { - var bindingRecord = isPresent(directiveRecord) ? - BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) : - BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1); + var bindingRecord = + isPresent(directiveRecord) ? + BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) : + BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1); this.eventRecords.push(bindingRecord); return null; } @@ -85,21 +109,25 @@ class ProtoViewVisitor implements TemplateAstVisitor { var dirIndex = isPresent(directiveRecord) ? directiveRecord.directiveIndex : null; var bindingRecord; if (ast.type === PropertyBindingType.Property) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) : - BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) : + BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name); } else if (ast.type === PropertyBindingType.Attribute) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) : - BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) : + BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name); } else if (ast.type === PropertyBindingType.Class) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) : - BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) : + BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name); } else if (ast.type === PropertyBindingType.Style) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) : - BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) : + BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit); } this.bindingRecords.push(bindingRecord); return null; @@ -167,9 +195,8 @@ class ProtoViewVisitor implements TemplateAstVisitor { } -function createChangeDefinitions( - pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata, - genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] { +function createChangeDefinitions(pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata, + genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] { var pvVariableNames = _collectNestedProtoViewsVariableNames(pvVisitors); return pvVisitors.map(pvVisitor => { var id = `${componentType.name}_${pvVisitor.viewIndex}`; diff --git a/modules/angular2/src/compiler/change_detector_compiler.ts b/modules/angular2/src/compiler/change_detector_compiler.ts index dd3a099014..db3b727b4a 100644 --- a/modules/angular2/src/compiler/change_detector_compiler.ts +++ b/modules/angular2/src/compiler/change_detector_compiler.ts @@ -1,6 +1,8 @@ import {CompileTypeMetadata} from './directive_metadata'; import {SourceExpressions, moduleRef} from './source_module'; -import {ChangeDetectorJITGenerator} from 'angular2/src/core/change_detection/change_detection_jit_generator'; +import { + ChangeDetectorJITGenerator +} from 'angular2/src/core/change_detection/change_detection_jit_generator'; import {AbstractChangeDetector} from 'angular2/src/core/change_detection/abstract_change_detector'; import {ChangeDetectionUtil} from 'angular2/src/core/change_detection/change_detection_util'; import {ChangeDetectorState} from 'angular2/src/core/change_detection/constants'; @@ -8,16 +10,21 @@ import {ChangeDetectorState} from 'angular2/src/core/change_detection/constants' import {createChangeDetectorDefinitions} from './change_definition_factory'; import {IS_DART, isJsObject, CONST_EXPR} from 'angular2/src/facade/lang'; -import {ChangeDetectorGenConfig, ChangeDetectorDefinition, DynamicProtoChangeDetector, ChangeDetectionStrategy} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectorGenConfig, + ChangeDetectorDefinition, + DynamicProtoChangeDetector, + ChangeDetectionStrategy +} from 'angular2/src/core/change_detection/change_detection'; import {TemplateAst} from './template_ast'; import {Codegen} from 'angular2/src/transform/template_compiler/change_detector_codegen'; import {MODULE_SUFFIX} from './util'; import {Injectable} from 'angular2/src/core/di'; -const ABSTRACT_CHANGE_DETECTOR = 'AbstractChangeDetector'; -const UTIL = 'ChangeDetectionUtil'; -const CHANGE_DETECTOR_STATE = 'ChangeDetectorState'; +const ABSTRACT_CHANGE_DETECTOR = "AbstractChangeDetector"; +const UTIL = "ChangeDetectionUtil"; +const CHANGE_DETECTOR_STATE = "ChangeDetectorState"; export const CHANGE_DETECTION_JIT_IMPORTS = CONST_EXPR({ 'AbstractChangeDetector': AbstractChangeDetector, @@ -38,13 +45,12 @@ var CONSTANTS_MODULE = export class ChangeDetectionCompiler { constructor(private _genConfig: ChangeDetectorGenConfig) {} - compileComponentRuntime( - componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, - parsedTemplate: TemplateAst[]): Function[] { + compileComponentRuntime(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, + parsedTemplate: TemplateAst[]): Function[] { var changeDetectorDefinitions = createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate); - return changeDetectorDefinitions.map( - definition => this._createChangeDetectorFactory(definition)); + return changeDetectorDefinitions.map(definition => + this._createChangeDetectorFactory(definition)); } private _createChangeDetectorFactory(definition: ChangeDetectorDefinition): Function { @@ -52,9 +58,8 @@ export class ChangeDetectionCompiler { return () => proto.instantiate(); } - compileComponentCodeGen( - componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, - parsedTemplate: TemplateAst[]): SourceExpressions { + compileComponentCodeGen(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, + parsedTemplate: TemplateAst[]): SourceExpressions { var changeDetectorDefinitions = createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate); var factories = []; @@ -69,8 +74,8 @@ export class ChangeDetectionCompiler { codegen = new Codegen(PREGEN_PROTO_CHANGE_DETECTOR_MODULE); var className = `_${definition.id}`; var typeRef = (index === 0 && componentType.isHost) ? - 'dynamic' : - `${moduleRef(componentType.moduleUrl)}${componentType.name}`; + 'dynamic' : + `${moduleRef(componentType.moduleUrl)}${componentType.name}`; codegen.generate(typeRef, className, definition); factories.push(`${className}.newChangeDetector`); sourcePart = codegen.toString(); diff --git a/modules/angular2/src/compiler/compiler.ts b/modules/angular2/src/compiler/compiler.ts index cdfe4c826a..23426ce6c1 100644 --- a/modules/angular2/src/compiler/compiler.ts +++ b/modules/angular2/src/compiler/compiler.ts @@ -1,6 +1,10 @@ -import {RuntimeCompiler_} from './runtime_compiler'; +import {RuntimeCompiler_} from "./runtime_compiler"; export {TemplateCompiler} from './template_compiler'; -export {CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata} from './directive_metadata'; +export { + CompileDirectiveMetadata, + CompileTypeMetadata, + CompileTemplateMetadata +} from './directive_metadata'; export {SourceModule, SourceWithImports} from './source_module'; export {PLATFORM_DIRECTIVES, PLATFORM_PIPES} from 'angular2/src/core/platform_directives_and_pipes'; export * from 'angular2/src/compiler/template_ast'; @@ -32,12 +36,23 @@ function _createChangeDetectorGenConfig() { * A set of providers that provide `RuntimeCompiler` and its dependencies to use for * template compilation. */ -export const COMPILER_PROVIDERS: Array<Type|Provider|any[]> = CONST_EXPR([ - Lexer, Parser, HtmlParser, TemplateParser, TemplateNormalizer, RuntimeMetadataResolver, - DEFAULT_PACKAGE_URL_PROVIDER, StyleCompiler, ProtoViewCompiler, ViewCompiler, +export const COMPILER_PROVIDERS: Array<Type | Provider | any[]> = CONST_EXPR([ + Lexer, + Parser, + HtmlParser, + TemplateParser, + TemplateNormalizer, + RuntimeMetadataResolver, + DEFAULT_PACKAGE_URL_PROVIDER, + StyleCompiler, + ProtoViewCompiler, + ViewCompiler, ChangeDetectionCompiler, new Provider(ChangeDetectorGenConfig, {useFactory: _createChangeDetectorGenConfig, deps: []}), - TemplateCompiler, new Provider(RuntimeCompiler, {useClass: RuntimeCompiler_}), - new Provider(Compiler, {useExisting: RuntimeCompiler}), DomElementSchemaRegistry, - new Provider(ElementSchemaRegistry, {useExisting: DomElementSchemaRegistry}), UrlResolver + TemplateCompiler, + new Provider(RuntimeCompiler, {useClass: RuntimeCompiler_}), + new Provider(Compiler, {useExisting: RuntimeCompiler}), + DomElementSchemaRegistry, + new Provider(ElementSchemaRegistry, {useExisting: DomElementSchemaRegistry}), + UrlResolver ]); diff --git a/modules/angular2/src/compiler/css/lexer.ts b/modules/angular2/src/compiler/css/lexer.ts index e0cde08be0..1f79ea870e 100644 --- a/modules/angular2/src/compiler/css/lexer.ts +++ b/modules/angular2/src/compiler/css/lexer.ts @@ -1,9 +1,65 @@ -import {NumberWrapper, StringWrapper, isPresent, resolveEnumToken} from 'angular2/src/facade/lang'; +import {NumberWrapper, StringWrapper, isPresent, resolveEnumToken} from "angular2/src/facade/lang"; import {BaseException} from 'angular2/src/facade/exceptions'; -import {isWhitespace, $EOF, $HASH, $TILDA, $CARET, $PERCENT, $$, $_, $COLON, $SQ, $DQ, $EQ, $SLASH, $BACKSLASH, $PERIOD, $STAR, $PLUS, $LPAREN, $RPAREN, $LBRACE, $RBRACE, $LBRACKET, $RBRACKET, $PIPE, $COMMA, $SEMICOLON, $MINUS, $BANG, $QUESTION, $AT, $AMPERSAND, $GT, $a, $A, $z, $Z, $0, $9, $FF, $CR, $LF, $VTAB} from 'angular2/src/compiler/chars'; +import { + isWhitespace, + $EOF, + $HASH, + $TILDA, + $CARET, + $PERCENT, + $$, + $_, + $COLON, + $SQ, + $DQ, + $EQ, + $SLASH, + $BACKSLASH, + $PERIOD, + $STAR, + $PLUS, + $LPAREN, + $RPAREN, + $LBRACE, + $RBRACE, + $LBRACKET, + $RBRACKET, + $PIPE, + $COMMA, + $SEMICOLON, + $MINUS, + $BANG, + $QUESTION, + $AT, + $AMPERSAND, + $GT, + $a, + $A, + $z, + $Z, + $0, + $9, + $FF, + $CR, + $LF, + $VTAB +} from "angular2/src/compiler/chars"; -export {$EOF, $AT, $RBRACE, $LBRACE, $LBRACKET, $RBRACKET, $LPAREN, $RPAREN, $COMMA, $COLON, $SEMICOLON, isWhitespace} from 'angular2/src/compiler/chars'; +export { + $EOF, + $AT, + $RBRACE, + $LBRACE, + $LBRACKET, + $RBRACKET, + $LPAREN, + $RPAREN, + $COMMA, + $COLON, + $SEMICOLON, + isWhitespace +} from "angular2/src/compiler/chars"; export enum CssTokenType { EOF, @@ -38,37 +94,35 @@ export class LexedCssResult { constructor(public error: CssScannerError, public token: CssToken) {} } -export function generateErrorMessage( - input: string, message: string, errorValue: string, index: number, row: number, - column: number): string { +export function generateErrorMessage(input: string, message: string, errorValue: string, + index: number, row: number, column: number): string { return `${message} at column ${row}:${column} in expression [` + - findProblemCode(input, errorValue, index, column) + ']'; + findProblemCode(input, errorValue, index, column) + ']'; } -export function findProblemCode( - input: string, errorValue: string, index: number, column: number): string { +export function findProblemCode(input: string, errorValue: string, index: number, + column: number): string { var endOfProblemLine = index; var current = charCode(input, index); while (current > 0 && !isNewline(current)) { current = charCode(input, ++endOfProblemLine); } var choppedString = input.substring(0, endOfProblemLine); - var pointerPadding = ''; + var pointerPadding = ""; for (var i = 0; i < column; i++) { - pointerPadding += ' '; + pointerPadding += " "; } - var pointerString = ''; + var pointerString = ""; for (var i = 0; i < errorValue.length; i++) { - pointerString += '^'; + pointerString += "^"; } - return choppedString + '\n' + pointerPadding + pointerString + '\n'; + return choppedString + "\n" + pointerPadding + pointerString + "\n"; } export class CssToken { numValue: number; - constructor( - public index: number, public column: number, public line: number, public type: CssTokenType, - public strValue: string) { + constructor(public index: number, public column: number, public line: number, + public type: CssTokenType, public strValue: string) { this.numValue = charCode(strValue, 0); } } @@ -194,7 +248,7 @@ export class CssScanner { var next = output.token; if (!isPresent(next)) { - next = new CssToken(0, 0, 0, CssTokenType.EOF, 'end of file'); + next = new CssToken(0, 0, 0, CssTokenType.EOF, "end of file"); } var isMatchingType; @@ -211,17 +265,16 @@ export class CssScanner { var error = null; if (!isMatchingType || (isPresent(value) && value != next.strValue)) { - var errorMessage = resolveEnumToken(CssTokenType, next.type) + ' does not match expected ' + - resolveEnumToken(CssTokenType, type) + ' value'; + var errorMessage = resolveEnumToken(CssTokenType, next.type) + " does not match expected " + + resolveEnumToken(CssTokenType, type) + " value"; if (isPresent(value)) { errorMessage += ' ("' + next.strValue + '" should match "' + value + '")'; } error = new CssScannerError( - next, generateErrorMessage( - this.input, errorMessage, next.strValue, previousIndex, previousLine, - previousColumn)); + next, generateErrorMessage(this.input, errorMessage, next.strValue, previousIndex, + previousLine, previousColumn)); } return new LexedCssResult(error, next); @@ -301,8 +354,8 @@ export class CssScanner { } scanComment(): CssToken { - if (this.assertCondition( - isCommentStart(this.peek, this.peekPeek), 'Expected comment start value')) { + if (this.assertCondition(isCommentStart(this.peek, this.peekPeek), + "Expected comment start value")) { return null; } @@ -339,8 +392,8 @@ export class CssScanner { } scanString(): CssToken { - if (this.assertCondition( - isStringStart(this.peek, this.peekPeek), 'Unexpected non-string starting value')) { + if (this.assertCondition(isStringStart(this.peek, this.peekPeek), + "Unexpected non-string starting value")) { return null; } @@ -359,7 +412,7 @@ export class CssScanner { this.advance(); } - if (this.assertCondition(this.peek == target, 'Unterminated quote')) { + if (this.assertCondition(this.peek == target, "Unterminated quote")) { return null; } this.advance(); @@ -389,8 +442,8 @@ export class CssScanner { } scanIdentifier(): CssToken { - if (this.assertCondition( - isIdentifierStart(this.peek, this.peekPeek), 'Expected identifier starting value')) { + if (this.assertCondition(isIdentifierStart(this.peek, this.peekPeek), + 'Expected identifier starting value')) { return null; } @@ -416,9 +469,8 @@ export class CssScanner { scanCharacter(): CssToken { var start = this.index; var startingColumn = this.column; - if (this.assertCondition( - isValidCssCharacter(this.peek, this._currentMode), - charStr(this.peek) + ' is not a valid CSS character')) { + if (this.assertCondition(isValidCssCharacter(this.peek, this._currentMode), + charStr(this.peek) + ' is not a valid CSS character')) { return null; } @@ -505,12 +557,12 @@ function isIdentifierStart(code: number, next: number): boolean { } return ($a <= target && target <= $z) || ($A <= target && target <= $Z) || target == $BACKSLASH || - target == $MINUS || target == $_; + target == $MINUS || target == $_; } function isIdentifierPart(target: number): boolean { return ($a <= target && target <= $z) || ($A <= target && target <= $Z) || target == $BACKSLASH || - target == $MINUS || target == $_ || isDigit(target); + target == $MINUS || target == $_ || isDigit(target); } function isValidPseudoSelectorCharacter(code: number): boolean { diff --git a/modules/angular2/src/compiler/css/parser.ts b/modules/angular2/src/compiler/css/parser.ts index 7a28f8c1eb..00267ccca6 100644 --- a/modules/angular2/src/compiler/css/parser.ts +++ b/modules/angular2/src/compiler/css/parser.ts @@ -1,10 +1,40 @@ -import {ParseSourceSpan, ParseSourceFile, ParseLocation, ParseError} from 'angular2/src/compiler/parse_util'; +import { + ParseSourceSpan, + ParseSourceFile, + ParseLocation, + ParseError +} from "angular2/src/compiler/parse_util"; -import {bitWiseOr, bitWiseAnd, NumberWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang'; +import { + bitWiseOr, + bitWiseAnd, + NumberWrapper, + StringWrapper, + isPresent +} from "angular2/src/facade/lang"; -import {CssLexerMode, CssToken, CssTokenType, CssScanner, CssScannerError, generateErrorMessage, $AT, $EOF, $RBRACE, $LBRACE, $LBRACKET, $RBRACKET, $LPAREN, $RPAREN, $COMMA, $COLON, $SEMICOLON, isNewline} from 'angular2/src/compiler/css/lexer'; +import { + CssLexerMode, + CssToken, + CssTokenType, + CssScanner, + CssScannerError, + generateErrorMessage, + $AT, + $EOF, + $RBRACE, + $LBRACE, + $LBRACKET, + $RBRACKET, + $LPAREN, + $RPAREN, + $COMMA, + $COLON, + $SEMICOLON, + isNewline +} from "angular2/src/compiler/css/lexer"; -export {CssToken} from 'angular2/src/compiler/css/lexer'; +export {CssToken} from "angular2/src/compiler/css/lexer"; export enum BlockType { Import, @@ -30,7 +60,7 @@ const SEMICOLON_DELIM = 32; const NEWLINE_DELIM = 64; const RPAREN_DELIM = 128; -function mergeTokens(tokens: CssToken[], separator: string = ''): CssToken { +function mergeTokens(tokens: CssToken[], separator: string = ""): CssToken { var mainToken = tokens[0]; var str = mainToken.strValue; for (var i = 1; i < tokens.length; i++) { @@ -175,9 +205,8 @@ export class CssParser { var token = this._scan(); - this._assertCondition( - token.type == CssTokenType.AtKeyword, - `The CSS Rule ${token.strValue} is not a valid [@] rule.`, token); + this._assertCondition(token.type == CssTokenType.AtKeyword, + `The CSS Rule ${token.strValue} is not a valid [@] rule.`, token); var block, type = this._resolveBlockType(token); switch (type) { @@ -216,12 +245,11 @@ export class CssParser { default: var listOfTokens = []; this._scanner.setMode(CssLexerMode.ALL); - this._error( - generateErrorMessage( - this._scanner.input, - `The CSS "at" rule "${token.strValue}" is not allowed to used here`, token.strValue, - token.index, token.line, token.column), - token); + this._error(generateErrorMessage( + this._scanner.input, + `The CSS "at" rule "${token.strValue}" is not allowed to used here`, + token.strValue, token.index, token.line, token.column), + token); this._collectUntilDelim(bitWiseOr([delimiters, LBRACE_DELIM, SEMICOLON_DELIM])) .forEach((token) => { listOfTokens.push(token); }); @@ -375,7 +403,7 @@ export class CssParser { // contains an inner selector that needs to be parsed // in isolation if (this._scanner.getMode() == CssLexerMode.PSEUDO_SELECTOR && isPresent(previousToken) && - previousToken.numValue == $COLON && token.strValue == 'not' && + previousToken.numValue == $COLON && token.strValue == "not" && this._scanner.peek == $LPAREN) { selectorCssTokens.push(token); selectorCssTokens.push(this._consume(CssTokenType.Character, '(')); @@ -425,7 +453,7 @@ export class CssParser { this._scanner.setMode(CssLexerMode.STYLE_VALUE); - var strValue = ''; + var strValue = ""; var tokens = []; var previous: CssToken; while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { @@ -465,9 +493,9 @@ export class CssParser { this._consume(CssTokenType.Character, ';'); } else if (code != $RBRACE) { this._error( - generateErrorMessage( - this._scanner.input, `The CSS key/value definition did not end with a semicolon`, - previous.strValue, previous.index, previous.line, previous.column), + generateErrorMessage(this._scanner.input, + `The CSS key/value definition did not end with a semicolon`, + previous.strValue, previous.index, previous.line, previous.column), previous); } @@ -564,7 +592,7 @@ export class CssParser { remainingTokens.forEach((token) => { propStr.push(token.strValue); }); } - prop = new CssToken(prop.index, prop.column, prop.line, prop.type, propStr.join(' ')); + prop = new CssToken(prop.index, prop.column, prop.line, prop.type, propStr.join(" ")); } // this means we've reached the end of the definition and/or block @@ -580,11 +608,10 @@ export class CssParser { if (parseValue) { value = this._parseValue(delimiters); } else { - this._error( - generateErrorMessage( - this._scanner.input, `The CSS property was not paired with a style value`, - prop.strValue, prop.index, prop.line, prop.column), - prop); + this._error(generateErrorMessage(this._scanner.input, + `The CSS property was not paired with a style value`, + prop.strValue, prop.index, prop.line, prop.column), + prop); } return new CssDefinitionAST(prop, value); @@ -602,8 +629,8 @@ export class CssParser { /** @internal */ _error(message: string, problemToken: CssToken) { var length = problemToken.strValue.length; - var error = CssParseError.create( - this._file, 0, problemToken.line, problemToken.column, length, message); + var error = CssParseError.create(this._file, 0, problemToken.line, problemToken.column, length, + message); this._errors.push(error); } } @@ -630,7 +657,7 @@ export class CssKeyframeRuleAST extends CssBlockRuleAST { export class CssKeyframeDefinitionAST extends CssBlockRuleAST { public steps; constructor(_steps: CssToken[], block: CssBlockAST) { - super(BlockType.Keyframes, block, mergeTokens(_steps, ',')); + super(BlockType.Keyframes, block, mergeTokens(_steps, ",")); this.steps = _steps; } visit(visitor: CssASTVisitor, context?: any) { @@ -642,11 +669,10 @@ export class CssBlockDefinitionRuleAST extends CssBlockRuleAST { public strValue: string; constructor(type: BlockType, public query: CssToken[], block: CssBlockAST) { super(type, block); - this.strValue = query.map(token => token.strValue).join(''); + this.strValue = query.map(token => token.strValue).join(""); var firstCssToken: CssToken = query[0]; - this.name = new CssToken( - firstCssToken.index, firstCssToken.column, firstCssToken.line, CssTokenType.Identifier, - this.strValue); + this.name = new CssToken(firstCssToken.index, firstCssToken.column, firstCssToken.line, + CssTokenType.Identifier, this.strValue); } visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssBlock(this.block, context); } } @@ -666,7 +692,7 @@ export class CssSelectorRuleAST extends CssBlockRuleAST { constructor(public selectors: CssSelectorAST[], block: CssBlockAST) { super(BlockType.Selector, block); - this.strValue = selectors.map(selector => selector.strValue).join(','); + this.strValue = selectors.map(selector => selector.strValue).join(","); } visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssSelectorRule(this, context); } @@ -681,7 +707,7 @@ export class CssSelectorAST extends CssAST { public strValue; constructor(public tokens: CssToken[], public isComplex: boolean = false) { super(); - this.strValue = tokens.map(token => token.strValue).join(''); + this.strValue = tokens.map(token => token.strValue).join(""); } visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssSelector(this, context); } } @@ -697,13 +723,12 @@ export class CssStyleSheetAST extends CssAST { } export class CssParseError extends ParseError { - static create( - file: ParseSourceFile, offset: number, line: number, col: number, length: number, - errMsg: string): CssParseError { + static create(file: ParseSourceFile, offset: number, line: number, col: number, length: number, + errMsg: string): CssParseError { var start = new ParseLocation(file, offset, line, col); var end = new ParseLocation(file, offset, line, col + length); var span = new ParseSourceSpan(start, end); - return new CssParseError(span, 'CSS Parse Error: ' + errMsg); + return new CssParseError(span, "CSS Parse Error: " + errMsg); } constructor(span: ParseSourceSpan, message: string) { super(span, message); } diff --git a/modules/angular2/src/compiler/directive_metadata.ts b/modules/angular2/src/compiler/directive_metadata.ts index c1a4f253a0..1240fe12da 100644 --- a/modules/angular2/src/compiler/directive_metadata.ts +++ b/modules/angular2/src/compiler/directive_metadata.ts @@ -1,7 +1,23 @@ -import {isPresent, isBlank, isNumber, isBoolean, normalizeBool, normalizeBlank, serializeEnum, Type, isString, RegExpWrapper, StringWrapper, isArray} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + isNumber, + isBoolean, + normalizeBool, + normalizeBlank, + serializeEnum, + Type, + isString, + RegExpWrapper, + StringWrapper, + isArray +} from 'angular2/src/facade/lang'; import {unimplemented} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; -import {ChangeDetectionStrategy, CHANGE_DETECTION_STRATEGY_VALUES} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectionStrategy, + CHANGE_DETECTION_STRATEGY_VALUES +} from 'angular2/src/core/change_detection/change_detection'; import {ViewEncapsulation, VIEW_ENCAPSULATION_VALUES} from 'angular2/src/core/metadata/view'; import {CssSelector} from 'angular2/src/compiler/selector'; import {splitAtColon} from './util'; @@ -89,7 +105,7 @@ export class CompileDiDependencyMetadata { isOptional: boolean; query: CompileQueryMetadata; viewQuery: CompileQueryMetadata; - token: CompileIdentifierMetadata|string; + token: CompileIdentifierMetadata | string; constructor({isAttribute, isSelf, isHost, isSkipSelf, isOptional, query, viewQuery, token}: { isAttribute?: boolean, @@ -99,7 +115,7 @@ export class CompileDiDependencyMetadata { isOptional?: boolean, query?: CompileQueryMetadata, viewQuery?: CompileQueryMetadata, - token?: CompileIdentifierMetadata|string + token?: CompileIdentifierMetadata | string } = {}) { this.isAttribute = normalizeBool(isAttribute); this.isSelf = normalizeBool(isSelf); @@ -140,10 +156,10 @@ export class CompileDiDependencyMetadata { } export class CompileProviderMetadata { - token: CompileIdentifierMetadata|string; + token: CompileIdentifierMetadata | string; useClass: CompileTypeMetadata; useValue: any; - useExisting: CompileIdentifierMetadata|string; + useExisting: CompileIdentifierMetadata | string; useFactory: CompileFactoryMetadata; deps: CompileDiDependencyMetadata[]; multi: boolean; @@ -152,7 +168,7 @@ export class CompileProviderMetadata { token?: CompileIdentifierMetadata | string, useClass?: CompileTypeMetadata, useValue?: any, - useExisting?: CompileIdentifierMetadata|string, + useExisting?: CompileIdentifierMetadata | string, useFactory?: CompileFactoryMetadata, deps?: CompileDiDependencyMetadata[], multi?: boolean @@ -307,13 +323,13 @@ export class CompileTypeMetadata implements CompileIdentifierMetadata, CompileMe } export class CompileQueryMetadata { - selectors: Array<CompileIdentifierMetadata|string>; + selectors: Array<CompileIdentifierMetadata | string>; descendants: boolean; first: boolean; propertyName: string; constructor({selectors, descendants, first, propertyName}: { - selectors?: Array<CompileIdentifierMetadata|string>, + selectors?: Array<CompileIdentifierMetadata | string>, descendants?: boolean, first?: boolean, propertyName?: string @@ -373,8 +389,8 @@ export class CompileTemplateMetadata { static fromJson(data: {[key: string]: any}): CompileTemplateMetadata { return new CompileTemplateMetadata({ encapsulation: isPresent(data['encapsulation']) ? - VIEW_ENCAPSULATION_VALUES[data['encapsulation']] : - data['encapsulation'], + VIEW_ENCAPSULATION_VALUES[data['encapsulation']] : + data['encapsulation'], template: data['template'], templateUrl: data['templateUrl'], styles: data['styles'], @@ -385,8 +401,8 @@ export class CompileTemplateMetadata { toJson(): {[key: string]: any} { return { - 'encapsulation': isPresent(this.encapsulation) ? serializeEnum(this.encapsulation) : - this.encapsulation, + 'encapsulation': + isPresent(this.encapsulation) ? serializeEnum(this.encapsulation) : this.encapsulation, 'template': this.template, 'templateUrl': this.templateUrl, 'styles': this.styles, @@ -400,27 +416,27 @@ export class CompileTemplateMetadata { * Metadata regarding compilation of a directive. */ export class CompileDirectiveMetadata implements CompileMetadataWithType { - static create( - {type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs, - host, lifecycleHooks, providers, viewProviders, queries, viewQueries, template}: { - type?: CompileTypeMetadata, - isComponent?: boolean, - dynamicLoadable?: boolean, - selector?: string, - exportAs?: string, - changeDetection?: ChangeDetectionStrategy, - inputs?: string[], - outputs?: string[], - host?: {[key: string]: string}, - lifecycleHooks?: LifecycleHooks[], - providers?: - Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, - viewProviders?: - Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, - queries?: CompileQueryMetadata[], - viewQueries?: CompileQueryMetadata[], - template?: CompileTemplateMetadata - } = {}): CompileDirectiveMetadata { + static create({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, + outputs, host, lifecycleHooks, providers, viewProviders, queries, viewQueries, + template}: { + type?: CompileTypeMetadata, + isComponent?: boolean, + dynamicLoadable?: boolean, + selector?: string, + exportAs?: string, + changeDetection?: ChangeDetectionStrategy, + inputs?: string[], + outputs?: string[], + host?: {[key: string]: string}, + lifecycleHooks?: LifecycleHooks[], + providers?: + Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>, + viewProviders?: + Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>, + queries?: CompileQueryMetadata[], + viewQueries?: CompileQueryMetadata[], + template?: CompileTemplateMetadata + } = {}): CompileDirectiveMetadata { var hostListeners: {[key: string]: string} = {}; var hostProperties: {[key: string]: string} = {}; var hostAttributes: {[key: string]: string} = {}; @@ -487,35 +503,34 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType { hostProperties: {[key: string]: string}; hostAttributes: {[key: string]: string}; lifecycleHooks: LifecycleHooks[]; - providers: Array<CompileProviderMetadata|CompileTypeMetadata|any[]>; - viewProviders: Array<CompileProviderMetadata|CompileTypeMetadata|any[]>; + providers: Array<CompileProviderMetadata | CompileTypeMetadata | any[]>; + viewProviders: Array<CompileProviderMetadata | CompileTypeMetadata | any[]>; queries: CompileQueryMetadata[]; viewQueries: CompileQueryMetadata[]; template: CompileTemplateMetadata; - constructor( - {type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs, - hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers, viewProviders, - queries, viewQueries, template}: { - type?: CompileTypeMetadata, - isComponent?: boolean, - dynamicLoadable?: boolean, - selector?: string, - exportAs?: string, - changeDetection?: ChangeDetectionStrategy, - inputs?: {[key: string]: string}, - outputs?: {[key: string]: string}, - hostListeners?: {[key: string]: string}, - hostProperties?: {[key: string]: string}, - hostAttributes?: {[key: string]: string}, - lifecycleHooks?: LifecycleHooks[], - providers?: - Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, - viewProviders?: - Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, - queries?: CompileQueryMetadata[], - viewQueries?: CompileQueryMetadata[], - template?: CompileTemplateMetadata - } = {}) { + constructor({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, + outputs, hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers, + viewProviders, queries, viewQueries, template}: { + type?: CompileTypeMetadata, + isComponent?: boolean, + dynamicLoadable?: boolean, + selector?: string, + exportAs?: string, + changeDetection?: ChangeDetectionStrategy, + inputs?: {[key: string]: string}, + outputs?: {[key: string]: string}, + hostListeners?: {[key: string]: string}, + hostProperties?: {[key: string]: string}, + hostAttributes?: {[key: string]: string}, + lifecycleHooks?: LifecycleHooks[], + providers?: + Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>, + viewProviders?: + Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>, + queries?: CompileQueryMetadata[], + viewQueries?: CompileQueryMetadata[], + template?: CompileTemplateMetadata + } = {}) { this.type = type; this.isComponent = isComponent; this.dynamicLoadable = dynamicLoadable; @@ -545,8 +560,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType { exportAs: data['exportAs'], type: isPresent(data['type']) ? CompileTypeMetadata.fromJson(data['type']) : data['type'], changeDetection: isPresent(data['changeDetection']) ? - CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] : - data['changeDetection'], + CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] : + data['changeDetection'], inputs: data['inputs'], outputs: data['outputs'], hostListeners: data['hostListeners'], @@ -591,8 +606,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType { /** * Construct {@link CompileDirectiveMetadata} from {@link ComponentTypeMetadata} and a selector. */ -export function createHostComponentMeta( - componentType: CompileTypeMetadata, componentSelector: string): CompileDirectiveMetadata { +export function createHostComponentMeta(componentType: CompileTypeMetadata, + componentSelector: string): CompileDirectiveMetadata { var template = CssSelector.parse(componentSelector)[0].getMatchingElementTemplate(); return CompileDirectiveMetadata.create({ type: new CompileTypeMetadata({ @@ -623,9 +638,8 @@ export class CompilePipeMetadata implements CompileMetadataWithType { type: CompileTypeMetadata; name: string; pure: boolean; - constructor({type, name, pure}: {type?: CompileTypeMetadata, - name?: string, - pure?: boolean} = {}) { + constructor({type, name, + pure}: {type?: CompileTypeMetadata, name?: string, pure?: boolean} = {}) { this.type = type; this.name = name; this.pure = normalizeBool(pure); @@ -663,7 +677,7 @@ function arrayFromJson(obj: any[], fn: (a: {[key: string]: any}) => any): any { return isBlank(obj) ? null : obj.map(o => objFromJson(o, fn)); } -function arrayToJson(obj: any[]): string|{[key: string]: any} { +function arrayToJson(obj: any[]): string | {[key: string]: any} { return isBlank(obj) ? null : obj.map(objToJson); } @@ -673,7 +687,7 @@ function objFromJson(obj: any, fn: (a: {[key: string]: any}) => any): any { return fn(obj); } -function objToJson(obj: any): string|{[key: string]: any} { +function objToJson(obj: any): string | {[key: string]: any} { if (isArray(obj)) return arrayToJson(obj); if (isString(obj) || isBlank(obj) || isBoolean(obj) || isNumber(obj)) return obj; return obj.toJson(); diff --git a/modules/angular2/src/compiler/html_ast.ts b/modules/angular2/src/compiler/html_ast.ts index 5aa1d2d957..d1f18b47df 100644 --- a/modules/angular2/src/compiler/html_ast.ts +++ b/modules/angular2/src/compiler/html_ast.ts @@ -18,10 +18,9 @@ export class HtmlAttrAst implements HtmlAst { } export class HtmlElementAst implements HtmlAst { - constructor( - public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[], - public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, - public endSourceSpan: ParseSourceSpan) {} + constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[], + public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, + public endSourceSpan: ParseSourceSpan) {} visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitElement(this, context); } } diff --git a/modules/angular2/src/compiler/html_lexer.ts b/modules/angular2/src/compiler/html_lexer.ts index d2fec58215..d3a90d74aa 100644 --- a/modules/angular2/src/compiler/html_lexer.ts +++ b/modules/angular2/src/compiler/html_lexer.ts @@ -1,4 +1,11 @@ -import {StringWrapper, NumberWrapper, isPresent, isBlank, CONST_EXPR, serializeEnum} from 'angular2/src/facade/lang'; +import { + StringWrapper, + NumberWrapper, + isPresent, + isBlank, + CONST_EXPR, + serializeEnum +} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; import {ParseLocation, ParseError, ParseSourceFile, ParseSourceSpan} from './parse_util'; import {getHtmlTagDefinition, HtmlTagContentType, NAMED_ENTITIES} from './html_tags'; @@ -22,8 +29,8 @@ export enum HtmlTokenType { } export class HtmlToken { - constructor( - public type: HtmlTokenType, public parts: string[], public sourceSpan: ParseSourceSpan) {} + constructor(public type: HtmlTokenType, public parts: string[], + public sourceSpan: ParseSourceSpan) {} } export class HtmlTokenError extends ParseError { @@ -184,8 +191,8 @@ class _HtmlTokenizer { if (isBlank(end)) { end = this._getLocation(); } - var token = new HtmlToken( - this.currentTokenType, parts, new ParseSourceSpan(this.currentTokenStart, end)); + var token = new HtmlToken(this.currentTokenType, parts, + new ParseSourceSpan(this.currentTokenStart, end)); this.tokens.push(token); this.currentTokenStart = null; this.currentTokenType = null; @@ -232,8 +239,8 @@ class _HtmlTokenizer { private _requireCharCode(charCode: number) { var location = this._getLocation(); if (!this._attemptCharCode(charCode)) { - throw this._createError( - unexpectedCharacterErrorMsg(this.peek), this._getSpan(location, location)); + throw this._createError(unexpectedCharacterErrorMsg(this.peek), + this._getSpan(location, location)); } } @@ -328,12 +335,12 @@ class _HtmlTokenizer { } } - private _consumeRawText( - decodeEntities: boolean, firstCharOfEnd: number, attemptEndRest: Function): HtmlToken { + private _consumeRawText(decodeEntities: boolean, firstCharOfEnd: number, + attemptEndRest: Function): HtmlToken { var tagCloseStart; var textStart = this._getLocation(); - this._beginToken( - decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT, textStart); + this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT, + textStart); var parts = []; while (true) { tagCloseStart = this._getLocation(); @@ -536,7 +543,7 @@ function isWhitespace(code: number): boolean { function isNameEnd(code: number): boolean { return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ || - code === $EQ; + code === $EQ; } function isPrefixEnd(code: number): boolean { diff --git a/modules/angular2/src/compiler/html_parser.ts b/modules/angular2/src/compiler/html_parser.ts index d6f1d5d92e..40385eb105 100644 --- a/modules/angular2/src/compiler/html_parser.ts +++ b/modules/angular2/src/compiler/html_parser.ts @@ -1,4 +1,13 @@ -import {isPresent, isBlank, StringWrapper, stringify, assertionsEnabled, StringJoiner, serializeEnum, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + StringWrapper, + stringify, + assertionsEnabled, + StringJoiner, + serializeEnum, + CONST_EXPR +} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -26,9 +35,8 @@ export class HtmlParser { parse(sourceContent: string, sourceUrl: string): HtmlParseTreeResult { var tokensAndErrors = tokenizeHtml(sourceContent, sourceUrl); var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build(); - return new HtmlParseTreeResult( - treeAndErrors.rootNodes, - (<ParseError[]>tokensAndErrors.errors).concat(treeAndErrors.errors)); + return new HtmlParseTreeResult(treeAndErrors.rootNodes, (<ParseError[]>tokensAndErrors.errors) + .concat(treeAndErrors.errors)); } } @@ -55,9 +63,9 @@ class TreeBuilder { } else if (this.peek.type === HtmlTokenType.COMMENT_START) { this._closeVoidElement(); this._consumeComment(this._advance()); - } else if ( - this.peek.type === HtmlTokenType.TEXT || this.peek.type === HtmlTokenType.RAW_TEXT || - this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) { + } else if (this.peek.type === HtmlTokenType.TEXT || + this.peek.type === HtmlTokenType.RAW_TEXT || + this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) { this._closeVoidElement(); this._consumeText(this._advance()); } else { @@ -166,8 +174,8 @@ class TreeBuilder { var tagDef = getHtmlTagDefinition(el.name); var parentEl = this._getParentElement(); if (tagDef.requireExtraParent(isPresent(parentEl) ? parentEl.name : null)) { - var newParent = new HtmlElementAst( - tagDef.parentToAdd, [], [el], el.sourceSpan, el.startSourceSpan, el.endSourceSpan); + var newParent = new HtmlElementAst(tagDef.parentToAdd, [], [el], el.sourceSpan, + el.startSourceSpan, el.endSourceSpan); this._addToParent(newParent); this.elementStack.push(newParent); this.elementStack.push(el); @@ -184,12 +192,12 @@ class TreeBuilder { this._getParentElement().endSourceSpan = endTagToken.sourceSpan; if (getHtmlTagDefinition(fullName).isVoid) { - this.errors.push(HtmlTreeError.create( - fullName, endTagToken.sourceSpan, - `Void elements do not have end tags "${endTagToken.parts[1]}"`)); + this.errors.push( + HtmlTreeError.create(fullName, endTagToken.sourceSpan, + `Void elements do not have end tags "${endTagToken.parts[1]}"`)); } else if (!this._popElement(fullName)) { - this.errors.push(HtmlTreeError.create( - fullName, endTagToken.sourceSpan, `Unexpected closing tag "${endTagToken.parts[1]}"`)); + this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan, + `Unexpected closing tag "${endTagToken.parts[1]}"`)); } } @@ -234,8 +242,8 @@ class TreeBuilder { } } -function getElementFullName( - prefix: string, localName: string, parentElement: HtmlElementAst): string { +function getElementFullName(prefix: string, localName: string, + parentElement: HtmlElementAst): string { if (isBlank(prefix)) { prefix = getHtmlTagDefinition(localName).implicitNamespacePrefix; if (isBlank(prefix) && isPresent(parentElement)) { diff --git a/modules/angular2/src/compiler/html_tags.ts b/modules/angular2/src/compiler/html_tags.ts index 2c06bb6b23..14924f93a4 100644 --- a/modules/angular2/src/compiler/html_tags.ts +++ b/modules/angular2/src/compiler/html_tags.ts @@ -1,4 +1,10 @@ -import {isPresent, isBlank, normalizeBool, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + normalizeBool, + RegExpWrapper, + CONST_EXPR +} from 'angular2/src/facade/lang'; // see http://www.w3.org/TR/html51/syntax.html#named-character-references // see https://html.spec.whatwg.org/multipage/entities.json @@ -275,17 +281,16 @@ export class HtmlTagDefinition { public isVoid: boolean; public ignoreFirstLf: boolean; - constructor( - {closedByChildren, requiredParents, implicitNamespacePrefix, contentType, closedByParent, - isVoid, ignoreFirstLf}: { - closedByChildren?: string[], - closedByParent?: boolean, - requiredParents?: string[], - implicitNamespacePrefix?: string, - contentType?: HtmlTagContentType, - isVoid?: boolean, - ignoreFirstLf?: boolean - } = {}) { + constructor({closedByChildren, requiredParents, implicitNamespacePrefix, contentType, + closedByParent, isVoid, ignoreFirstLf}: { + closedByChildren?: string[], + closedByParent?: boolean, + requiredParents?: string[], + implicitNamespacePrefix?: string, + contentType?: HtmlTagContentType, + isVoid?: boolean, + ignoreFirstLf?: boolean + } = {}) { if (isPresent(closedByChildren) && closedByChildren.length > 0) { closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true); } @@ -337,9 +342,32 @@ var TAG_DEFINITIONS: {[key: string]: HtmlTagDefinition} = { 'wbr': new HtmlTagDefinition({isVoid: true}), 'p': new HtmlTagDefinition({ closedByChildren: [ - 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', - 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', - 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' + 'address', + 'article', + 'aside', + 'blockquote', + 'div', + 'dl', + 'fieldset', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'hr', + 'main', + 'nav', + 'ol', + 'p', + 'pre', + 'section', + 'table', + 'ul' ], closedByParent: true }), diff --git a/modules/angular2/src/compiler/legacy_template.ts b/modules/angular2/src/compiler/legacy_template.ts index 294265e2c4..6adbf78a4a 100644 --- a/modules/angular2/src/compiler/legacy_template.ts +++ b/modules/angular2/src/compiler/legacy_template.ts @@ -1,8 +1,21 @@ import {Injectable, Provider, provide} from 'angular2/src/core/di'; -import {StringWrapper, RegExpWrapper, CONST_EXPR, isBlank, isPresent} from 'angular2/src/facade/lang'; +import { + StringWrapper, + RegExpWrapper, + CONST_EXPR, + isBlank, + isPresent +} from 'angular2/src/facade/lang'; -import {HtmlAstVisitor, HtmlAttrAst, HtmlElementAst, HtmlTextAst, HtmlCommentAst, HtmlAst} from './html_ast'; +import { + HtmlAstVisitor, + HtmlAttrAst, + HtmlElementAst, + HtmlTextAst, + HtmlCommentAst, + HtmlAst +} from './html_ast'; import {HtmlParser, HtmlParseTreeResult} from './html_parser'; import {dashCaseToCamelCase, camelCaseToDashCase} from './util'; @@ -37,8 +50,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { this.visitingTemplateEl = ast.name.toLowerCase() == 'template'; let attrs = ast.attrs.map(attr => attr.visit(this, null)); let children = ast.children.map(child => child.visit(this, null)); - return new HtmlElementAst( - ast.name, attrs, children, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan); + return new HtmlElementAst(ast.name, attrs, children, ast.sourceSpan, ast.startSourceSpan, + ast.endSourceSpan); } visitAttr(originalAst: HtmlAttrAst, context: any): HtmlAttrAst { @@ -90,8 +103,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } return attrName == ast.name && attrValue == ast.value ? - ast : - new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); + ast : + new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); } private _rewriteTemplateAttribute(ast: HtmlAttrAst): HtmlAttrAst { @@ -102,8 +115,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { name = 'template'; // rewrite the directive selector - value = StringWrapper.replaceAllMapped( - value, TEMPLATE_SELECTOR_REGEXP, (m) => { return dashCaseToCamelCase(m[1]); }); + value = StringWrapper.replaceAllMapped(value, TEMPLATE_SELECTOR_REGEXP, + (m) => { return dashCaseToCamelCase(m[1]); }); // rewrite the var declarations value = StringWrapper.replaceAllMapped(value, VARIABLE_TPL_BINDING_REGEXP, m => { @@ -129,8 +142,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } else if (isPresent(m[2])) { attrName = `[(${dashCaseToCamelCase(m[2])})]`; } else if (isPresent(m[3])) { - let prop = StringWrapper.replaceAllMapped( - m[3], SPECIAL_PREFIXES_REGEXP, (m) => { return m[1].toLowerCase() + '.'; }); + let prop = StringWrapper.replaceAllMapped(m[3], SPECIAL_PREFIXES_REGEXP, + (m) => { return m[1].toLowerCase() + '.'; }); if (prop.startsWith('class.') || prop.startsWith('attr.') || prop.startsWith('style.')) { attrName = `[${prop}]`; @@ -144,8 +157,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } return attrName == ast.name && attrValue == ast.value ? - ast : - new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); + ast : + new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); } private _rewriteStar(ast: HtmlAttrAst): HtmlAttrAst { @@ -161,8 +174,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } return attrName == ast.name && attrValue == ast.value ? - ast : - new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); + ast : + new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); } private _rewriteInterpolation(ast: HtmlAttrAst): HtmlAttrAst { @@ -205,7 +218,7 @@ export class LegacyHtmlParser extends HtmlParser { let rootNodes = htmlParseTreeResult.rootNodes.map(node => node.visit(transformer, null)); return transformer.rewrittenAst.length > 0 ? - new HtmlParseTreeResult(rootNodes, htmlParseTreeResult.errors) : - htmlParseTreeResult; + new HtmlParseTreeResult(rootNodes, htmlParseTreeResult.errors) : + htmlParseTreeResult; } } diff --git a/modules/angular2/src/compiler/parse_util.ts b/modules/angular2/src/compiler/parse_util.ts index 063ca6a930..a1070f2e68 100644 --- a/modules/angular2/src/compiler/parse_util.ts +++ b/modules/angular2/src/compiler/parse_util.ts @@ -1,7 +1,6 @@ export class ParseLocation { - constructor( - public file: ParseSourceFile, public offset: number, public line: number, - public col: number) {} + constructor(public file: ParseSourceFile, public offset: number, public line: number, + public col: number) {} toString(): string { return `${this.file.url}@${this.line}:${this.col}`; } } @@ -34,7 +33,7 @@ export abstract class ParseError { while (ctxLen < 100 && ctxStart > 0) { ctxStart--; ctxLen++; - if (source[ctxStart] == '\n') { + if (source[ctxStart] == "\n") { if (++ctxLines == 3) { break; } @@ -46,7 +45,7 @@ export abstract class ParseError { while (ctxLen < 100 && ctxEnd < source.length - 1) { ctxEnd++; ctxLen++; - if (source[ctxEnd] == '\n') { + if (source[ctxEnd] == "\n") { if (++ctxLines == 3) { break; } @@ -54,7 +53,7 @@ export abstract class ParseError { } let context = source.substring(ctxStart, this.span.start.offset) + '[ERROR ->]' + - source.substring(this.span.start.offset, ctxEnd + 1); + source.substring(this.span.start.offset, ctxEnd + 1); return `${this.msg} ("${context}"): ${this.span.start}`; } diff --git a/modules/angular2/src/compiler/proto_view_compiler.ts b/modules/angular2/src/compiler/proto_view_compiler.ts index d3be41cf33..68f489505c 100644 --- a/modules/angular2/src/compiler/proto_view_compiler.ts +++ b/modules/angular2/src/compiler/proto_view_compiler.ts @@ -1,13 +1,54 @@ -import {isPresent, isBlank, Type, isString, StringWrapper, IS_DART, CONST_EXPR} from 'angular2/src/facade/lang'; -import {SetWrapper, StringMapWrapper, ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; -import {TemplateAst, TemplateAstVisitor, NgContentAst, EmbeddedTemplateAst, ElementAst, VariableAst, BoundEventAst, BoundElementPropertyAst, AttrAst, BoundTextAst, TextAst, DirectiveAst, BoundDirectivePropertyAst, templateVisitAll} from './template_ast'; -import {CompileTypeMetadata, CompileDirectiveMetadata, CompilePipeMetadata} from './directive_metadata'; +import { + isPresent, + isBlank, + Type, + isString, + StringWrapper, + IS_DART, + CONST_EXPR +} from 'angular2/src/facade/lang'; +import { + SetWrapper, + StringMapWrapper, + ListWrapper, + MapWrapper +} from 'angular2/src/facade/collection'; +import { + TemplateAst, + TemplateAstVisitor, + NgContentAst, + EmbeddedTemplateAst, + ElementAst, + VariableAst, + BoundEventAst, + BoundElementPropertyAst, + AttrAst, + BoundTextAst, + TextAst, + DirectiveAst, + BoundDirectivePropertyAst, + templateVisitAll +} from './template_ast'; +import { + CompileTypeMetadata, + CompileDirectiveMetadata, + CompilePipeMetadata +} from './directive_metadata'; import {SourceExpressions, SourceExpression, moduleRef} from './source_module'; import {AppProtoView, AppView} from 'angular2/src/core/linker/view'; import {ViewType} from 'angular2/src/core/linker/view_type'; import {AppProtoElement, AppElement} from 'angular2/src/core/linker/element'; import {ResolvedMetadataCache} from 'angular2/src/core/linker/resolved_metadata_cache'; -import {escapeSingleQuoteString, codeGenConstConstructorCall, codeGenValueFn, codeGenFnHeader, MODULE_SUFFIX, codeGenStringMap, Expression, Statement} from './util'; +import { + escapeSingleQuoteString, + codeGenConstConstructorCall, + codeGenValueFn, + codeGenFnHeader, + MODULE_SUFFIX, + codeGenStringMap, + Expression, + Statement +} from './util'; import {Injectable} from 'angular2/src/core/di'; export const PROTO_VIEW_JIT_IMPORTS = CONST_EXPR( @@ -33,20 +74,19 @@ const STYLE_ATTR = 'style'; export class ProtoViewCompiler { constructor() {} - compileProtoViewRuntime( - metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, - template: TemplateAst[], - pipes: CompilePipeMetadata[]): CompileProtoViews<AppProtoView, AppProtoElement, any> { + compileProtoViewRuntime(metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, + template: TemplateAst[], pipes: CompilePipeMetadata[]): + CompileProtoViews<AppProtoView, AppProtoElement, any> { var protoViewFactory = new RuntimeProtoViewFactory(metadataCache, component, pipes); var allProtoViews = []; protoViewFactory.createCompileProtoView(template, [], [], allProtoViews); return new CompileProtoViews<AppProtoView, AppProtoElement, any>([], allProtoViews); } - compileProtoViewCodeGen( - resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata, - template: TemplateAst[], - pipes: CompilePipeMetadata[]): CompileProtoViews<Expression, Expression, string> { + compileProtoViewCodeGen(resolvedMetadataCacheExpr: Expression, + component: CompileDirectiveMetadata, template: TemplateAst[], + pipes: CompilePipeMetadata[]): + CompileProtoViews<Expression, Expression, string> { var protoViewFactory = new CodeGenProtoViewFactory(resolvedMetadataCacheExpr, component, pipes); var allProtoViews = []; var allStatements = []; @@ -57,29 +97,26 @@ export class ProtoViewCompiler { } export class CompileProtoViews<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> { - constructor( - public declarations: STATEMENT[], - public protoViews: CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>[]) {} + constructor(public declarations: STATEMENT[], + public protoViews: CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>[]) {} } export class CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL> { - constructor( - public embeddedTemplateIndex: number, - public protoElements: CompileProtoElement<APP_PROTO_EL>[], public protoView: APP_PROTO_VIEW) { - } + constructor(public embeddedTemplateIndex: number, + public protoElements: CompileProtoElement<APP_PROTO_EL>[], + public protoView: APP_PROTO_VIEW) {} } export class CompileProtoElement<APP_PROTO_EL> { - constructor( - public boundElementIndex, public attrNameAndValues: string[][], - public variableNameAndValues: string[][], public renderEvents: BoundEventAst[], - public directives: CompileDirectiveMetadata[], public embeddedTemplateIndex: number, - public appProtoEl: APP_PROTO_EL) {} + constructor(public boundElementIndex, public attrNameAndValues: string[][], + public variableNameAndValues: string[][], public renderEvents: BoundEventAst[], + public directives: CompileDirectiveMetadata[], public embeddedTemplateIndex: number, + public appProtoEl: APP_PROTO_EL) {} } -function visitAndReturnContext( - visitor: TemplateAstVisitor, asts: TemplateAst[], context: any): any { +function visitAndReturnContext(visitor: TemplateAstVisitor, asts: TemplateAst[], + context: any): any { templateVisitAll(visitor, asts, context); return context; } @@ -87,17 +124,18 @@ function visitAndReturnContext( abstract class ProtoViewFactory<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> { constructor(public component: CompileDirectiveMetadata) {} - abstract createAppProtoView( - embeddedTemplateIndex: number, viewType: ViewType, templateVariableBindings: string[][], - targetStatements: STATEMENT[]): APP_PROTO_VIEW; + abstract createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType, + templateVariableBindings: string[][], + targetStatements: STATEMENT[]): APP_PROTO_VIEW; - abstract createAppProtoElement( - boundElementIndex: number, attrNameAndValues: string[][], variableNameAndValues: string[][], - directives: CompileDirectiveMetadata[], targetStatements: STATEMENT[]): APP_PROTO_EL; + abstract createAppProtoElement(boundElementIndex: number, attrNameAndValues: string[][], + variableNameAndValues: string[][], + directives: CompileDirectiveMetadata[], + targetStatements: STATEMENT[]): APP_PROTO_EL; - createCompileProtoView( - template: TemplateAst[], templateVariableBindings: string[][], targetStatements: STATEMENT[], - targetProtoViews: CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>[]): + createCompileProtoView(template: TemplateAst[], templateVariableBindings: string[][], + targetStatements: STATEMENT[], + targetProtoViews: CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>[]): CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL> { var embeddedTemplateIndex = targetProtoViews.length; // Note: targetProtoViews needs to be in depth first order. @@ -107,8 +145,8 @@ abstract class ProtoViewFactory<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> { this, targetStatements, targetProtoViews); templateVisitAll(builder, template); var viewType = getViewType(this.component, embeddedTemplateIndex); - var appProtoView = this.createAppProtoView( - embeddedTemplateIndex, viewType, templateVariableBindings, targetStatements); + var appProtoView = this.createAppProtoView(embeddedTemplateIndex, viewType, + templateVariableBindings, targetStatements); var cpv = new CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>( embeddedTemplateIndex, builder.protoElements, appProtoView); targetProtoViews[embeddedTemplateIndex] = cpv; @@ -119,9 +157,8 @@ abstract class ProtoViewFactory<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> { class CodeGenProtoViewFactory extends ProtoViewFactory<Expression, Expression, Statement> { private _nextVarId: number = 0; - constructor( - public resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata, - public pipes: CompilePipeMetadata[]) { + constructor(public resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata, + public pipes: CompilePipeMetadata[]) { super(component); } @@ -129,23 +166,23 @@ class CodeGenProtoViewFactory extends ProtoViewFactory<Expression, Expression, S return `appProtoView${this._nextVarId++}_${this.component.type.name}${embeddedTemplateIndex}`; } - createAppProtoView( - embeddedTemplateIndex: number, viewType: ViewType, templateVariableBindings: string[][], - targetStatements: Statement[]): Expression { + createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType, + templateVariableBindings: string[][], + targetStatements: Statement[]): Expression { var protoViewVarName = this._nextProtoViewVar(embeddedTemplateIndex); var viewTypeExpr = codeGenViewType(viewType); var pipesExpr = embeddedTemplateIndex === 0 ? - codeGenTypesArray(this.pipes.map(pipeMeta => pipeMeta.type)) : - null; + codeGenTypesArray(this.pipes.map(pipeMeta => pipeMeta.type)) : + null; var statement = `var ${protoViewVarName} = ${APP_VIEW_MODULE_REF}AppProtoView.create(${this.resolvedMetadataCacheExpr.expression}, ${viewTypeExpr}, ${pipesExpr}, ${codeGenStringMap(templateVariableBindings)});`; targetStatements.push(new Statement(statement)); return new Expression(protoViewVarName); } - createAppProtoElement( - boundElementIndex: number, attrNameAndValues: string[][], variableNameAndValues: string[][], - directives: CompileDirectiveMetadata[], targetStatements: Statement[]): Expression { + createAppProtoElement(boundElementIndex: number, attrNameAndValues: string[][], + variableNameAndValues: string[][], directives: CompileDirectiveMetadata[], + targetStatements: Statement[]): Expression { var varName = `appProtoEl${this._nextVarId++}_${this.component.type.name}`; var value = `${APP_EL_MODULE_REF}AppProtoElement.create( ${this.resolvedMetadataCacheExpr.expression}, @@ -161,29 +198,26 @@ class CodeGenProtoViewFactory extends ProtoViewFactory<Expression, Expression, S } class RuntimeProtoViewFactory extends ProtoViewFactory<AppProtoView, AppProtoElement, any> { - constructor( - public metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, - public pipes: CompilePipeMetadata[]) { + constructor(public metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, + public pipes: CompilePipeMetadata[]) { super(component); } - createAppProtoView( - embeddedTemplateIndex: number, viewType: ViewType, templateVariableBindings: string[][], - targetStatements: any[]): AppProtoView { + createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType, + templateVariableBindings: string[][], targetStatements: any[]): AppProtoView { var pipes = embeddedTemplateIndex === 0 ? this.pipes.map(pipeMeta => pipeMeta.type.runtime) : []; var templateVars = keyValueArrayToStringMap(templateVariableBindings); return AppProtoView.create(this.metadataCache, viewType, pipes, templateVars); } - createAppProtoElement( - boundElementIndex: number, attrNameAndValues: string[][], variableNameAndValues: string[][], - directives: CompileDirectiveMetadata[], targetStatements: any[]): AppProtoElement { + createAppProtoElement(boundElementIndex: number, attrNameAndValues: string[][], + variableNameAndValues: string[][], directives: CompileDirectiveMetadata[], + targetStatements: any[]): AppProtoElement { var attrs = keyValueArrayToStringMap(attrNameAndValues); - return AppProtoElement.create( - this.metadataCache, boundElementIndex, attrs, - directives.map(dirMeta => dirMeta.type.runtime), - keyValueArrayToStringMap(variableNameAndValues)); + return AppProtoElement.create(this.metadataCache, boundElementIndex, attrs, + directives.map(dirMeta => dirMeta.type.runtime), + keyValueArrayToStringMap(variableNameAndValues)); } } @@ -192,13 +226,12 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement protoElements: CompileProtoElement<APP_PROTO_EL>[] = []; boundElementCount: number = 0; - constructor( - public factory: ProtoViewFactory<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT>, - public allStatements: STATEMENT[], - public allProtoViews: CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>[]) {} + constructor(public factory: ProtoViewFactory<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT>, + public allStatements: STATEMENT[], + public allProtoViews: CompileProtoView<APP_PROTO_VIEW, APP_PROTO_EL>[]) {} - private _readAttrNameAndValues(directives: CompileDirectiveMetadata[], attrAsts: TemplateAst[]): - string[][] { + private _readAttrNameAndValues(directives: CompileDirectiveMetadata[], + attrAsts: TemplateAst[]): string[][] { var attrs = visitAndReturnContext(this, attrAsts, {}); directives.forEach(directiveMeta => { StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => { @@ -229,17 +262,15 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement var renderEvents: Map<string, BoundEventAst> = visitAndReturnContext(this, ast.outputs, new Map<string, BoundEventAst>()); ListWrapper.forEachWithIndex(ast.directives, (directiveAst: DirectiveAst, index: number) => { - directiveAst.visit( - this, new DirectiveContext( - index, boundElementIndex, renderEvents, variableNameAndValues, directives)); + directiveAst.visit(this, new DirectiveContext(index, boundElementIndex, renderEvents, + variableNameAndValues, directives)); }); var renderEventArray = []; renderEvents.forEach((eventAst, _) => renderEventArray.push(eventAst)); var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs); - this._addProtoElement( - ast.isBound(), boundElementIndex, attrNameAndValues, variableNameAndValues, - renderEventArray, directives, null); + this._addProtoElement(ast.isBound(), boundElementIndex, attrNameAndValues, + variableNameAndValues, renderEventArray, directives, null); templateVisitAll(this, ast.children); return null; } @@ -249,8 +280,8 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement var directives: CompileDirectiveMetadata[] = []; ListWrapper.forEachWithIndex(ast.directives, (directiveAst: DirectiveAst, index: number) => { directiveAst.visit( - this, new DirectiveContext( - index, boundElementIndex, new Map<string, BoundEventAst>(), [], directives)); + this, new DirectiveContext(index, boundElementIndex, new Map<string, BoundEventAst>(), [], + directives)); }); var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs); @@ -258,21 +289,19 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement varAst => [varAst.value.length > 0 ? varAst.value : IMPLICIT_TEMPLATE_VAR, varAst.name]); var nestedProtoView = this.factory.createCompileProtoView( ast.children, templateVariableBindings, this.allStatements, this.allProtoViews); - this._addProtoElement( - true, boundElementIndex, attrNameAndValues, [], [], directives, - nestedProtoView.embeddedTemplateIndex); + this._addProtoElement(true, boundElementIndex, attrNameAndValues, [], [], directives, + nestedProtoView.embeddedTemplateIndex); return null; } - private _addProtoElement( - isBound: boolean, boundElementIndex, attrNameAndValues: string[][], - variableNameAndValues: string[][], renderEvents: BoundEventAst[], - directives: CompileDirectiveMetadata[], embeddedTemplateIndex: number) { + private _addProtoElement(isBound: boolean, boundElementIndex, attrNameAndValues: string[][], + variableNameAndValues: string[][], renderEvents: BoundEventAst[], + directives: CompileDirectiveMetadata[], embeddedTemplateIndex: number) { var appProtoEl = null; if (isBound) { - appProtoEl = this.factory.createAppProtoElement( - boundElementIndex, attrNameAndValues, variableNameAndValues, directives, - this.allStatements); + appProtoEl = + this.factory.createAppProtoElement(boundElementIndex, attrNameAndValues, + variableNameAndValues, directives, this.allStatements); } var compileProtoEl = new CompileProtoElement<APP_PROTO_EL>( boundElementIndex, attrNameAndValues, variableNameAndValues, renderEvents, directives, @@ -288,9 +317,8 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement visitDirective(ast: DirectiveAst, ctx: DirectiveContext): any { ctx.targetDirectives.push(ast.directive); templateVisitAll(this, ast.hostEvents, ctx.hostEventTargetAndNames); - ast.exportAsVars.forEach(varAst => { - ctx.targetVariableNameAndValues.push([varAst.name, ctx.index]); - }); + ast.exportAsVars.forEach( + varAst => { ctx.targetVariableNameAndValues.push([varAst.name, ctx.index]); }); return null; } visitEvent(ast: BoundEventAst, eventTargetAndNames: Map<string, BoundEventAst>): any { @@ -303,14 +331,12 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement function mapToKeyValueArray(data: {[key: string]: string}): string[][] { var entryArray: string[][] = []; - StringMapWrapper.forEach(data, (value: string, name: string) => { - entryArray.push([name, value]); - }); + StringMapWrapper.forEach(data, + (value: string, name: string) => { entryArray.push([name, value]); }); // We need to sort to get a defined output order // for tests and for caching generated artifacts... - ListWrapper.sort<string[]>( - entryArray, - (entry1: string[], entry2: string[]) => StringWrapper.compare(entry1[0], entry2[0])); + ListWrapper.sort<string[]>(entryArray, (entry1: string[], entry2: string[]) => + StringWrapper.compare(entry1[0], entry2[0])); var keyValueArray: string[][] = []; entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); }); return keyValueArray; @@ -325,11 +351,10 @@ function mergeAttributeValue(attrName: string, attrValue1: string, attrValue2: s } class DirectiveContext { - constructor( - public index: number, public boundElementIndex: number, - public hostEventTargetAndNames: Map<string, BoundEventAst>, - public targetVariableNameAndValues: any[][], - public targetDirectives: CompileDirectiveMetadata[]) {} + constructor(public index: number, public boundElementIndex: number, + public hostEventTargetAndNames: Map<string, BoundEventAst>, + public targetVariableNameAndValues: any[][], + public targetDirectives: CompileDirectiveMetadata[]) {} } function keyValueArrayToStringMap(keyValueArray: any[][]): {[key: string]: any} { diff --git a/modules/angular2/src/compiler/runtime_metadata.ts b/modules/angular2/src/compiler/runtime_metadata.ts index 4bc6a2a984..6a48faac7a 100644 --- a/modules/angular2/src/compiler/runtime_metadata.ts +++ b/modules/angular2/src/compiler/runtime_metadata.ts @@ -1,5 +1,12 @@ import {resolveForwardRef} from 'angular2/src/core/di'; -import {Type, isBlank, isPresent, isArray, stringify, RegExpWrapper} from 'angular2/src/facade/lang'; +import { + Type, + isBlank, + isPresent, + isArray, + stringify, + RegExpWrapper +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import * as cpl from './directive_metadata'; import * as md from 'angular2/src/core/metadata/directives'; @@ -23,11 +30,10 @@ export class RuntimeMetadataResolver { private _anonymousTypes = new Map<Object, number>(); private _anonymousTypeIndex = 0; - constructor( - private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver, - private _viewResolver: ViewResolver, - @Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[], - @Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {} + constructor(private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver, + private _viewResolver: ViewResolver, + @Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[], + @Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {} /** * Wrap the stringify method to avoid naming things `function (arg1...) {` @@ -151,7 +157,7 @@ function flattenPipes(view: ViewMetadata, platformPipes: any[]): Type[] { return pipes; } -function flattenArray(tree: any[], out: Array<Type|any[]>): void { +function flattenArray(tree: any[], out: Array<Type | any[]>): void { for (var i = 0; i < tree.length; i++) { var item = resolveForwardRef(tree[i]); if (isArray(item)) { diff --git a/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts b/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts index 600e9a258c..84a9230fe3 100644 --- a/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts +++ b/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts @@ -18,8 +18,8 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry { if (isBlank(element)) { var nsAndName = splitNsName(tagName); element = isPresent(nsAndName[0]) ? - DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : - DOM.createElement(nsAndName[1]); + DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : + DOM.createElement(nsAndName[1]); this._protoElements.set(tagName, element); } return element; diff --git a/modules/angular2/src/compiler/selector.ts b/modules/angular2/src/compiler/selector.ts index 3c3adb32a6..deed232f37 100644 --- a/modules/angular2/src/compiler/selector.ts +++ b/modules/angular2/src/compiler/selector.ts @@ -1,5 +1,11 @@ import {Map, ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; -import {isPresent, isBlank, RegExpWrapper, RegExpMatcherWrapper, StringWrapper} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + RegExpWrapper, + RegExpMatcherWrapper, + StringWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; const _EMPTY_ATTR_VALUE = ''; @@ -30,7 +36,7 @@ export class CssSelector { var _addResult = (res: CssSelector[], cssSel) => { if (cssSel.notSelectors.length > 0 && isBlank(cssSel.element) && ListWrapper.isEmpty(cssSel.classNames) && ListWrapper.isEmpty(cssSel.attrs)) { - cssSel.element = '*'; + cssSel.element = "*"; } res.push(cssSel); }; @@ -75,7 +81,7 @@ export class CssSelector { isElementSelector(): boolean { return isPresent(this.element) && ListWrapper.isEmpty(this.classNames) && - ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0; + ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0; } setElement(element: string = null) { this.element = element; } @@ -168,8 +174,8 @@ export class SelectorMatcher { * @param cssSelector A css selector * @param callbackCtxt An opaque object that will be given to the callback of the `match` function */ - private _addSelectable( - cssSelector: CssSelector, callbackCtxt: any, listContext: SelectorListContext) { + private _addSelectable(cssSelector: CssSelector, callbackCtxt: any, + listContext: SelectorListContext) { var matcher: SelectorMatcher = this; var element = cssSelector.element; var classNames = cssSelector.classNames; @@ -223,8 +229,8 @@ export class SelectorMatcher { } } - private _addTerminal( - map: Map<string, SelectorContext[]>, name: string, selectable: SelectorContext) { + private _addTerminal(map: Map<string, SelectorContext[]>, name: string, + selectable: SelectorContext) { var terminalList = map.get(name); if (isBlank(terminalList)) { terminalList = []; @@ -261,7 +267,7 @@ export class SelectorMatcher { result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result; result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || - result; + result; if (isPresent(classNames)) { for (var index = 0; index < classNames.length; index++) { @@ -281,18 +287,18 @@ export class SelectorMatcher { var terminalValuesMap = this._attrValueMap.get(attrName); if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { - result = this._matchTerminal( - terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || - result; + result = this._matchTerminal(terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, + matchedCallback) || + result; } result = this._matchTerminal(terminalValuesMap, attrValue, cssSelector, matchedCallback) || - result; + result; var partialValuesMap = this._attrValuePartialMap.get(attrName); if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { - result = this._matchPartial( - partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || - result; + result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, + matchedCallback) || + result; } result = this._matchPartial(partialValuesMap, attrValue, cssSelector, matchedCallback) || result; @@ -302,15 +308,14 @@ export class SelectorMatcher { } /** @internal */ - _matchTerminal( - map: Map<string, SelectorContext[]>, name, cssSelector: CssSelector, - matchedCallback: (c: CssSelector, a: any) => void): boolean { + _matchTerminal(map: Map<string, SelectorContext[]>, name, cssSelector: CssSelector, + matchedCallback: (c: CssSelector, a: any) => void): boolean { if (isBlank(map) || isBlank(name)) { return false; } var selectables = map.get(name); - var starSelectables = map.get('*'); + var starSelectables = map.get("*"); if (isPresent(starSelectables)) { selectables = selectables.concat(starSelectables); } @@ -327,9 +332,8 @@ export class SelectorMatcher { } /** @internal */ - _matchPartial( - map: Map<string, SelectorMatcher>, name, cssSelector: CssSelector, - matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean { + _matchPartial(map: Map<string, SelectorMatcher>, name, cssSelector: CssSelector, + matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean { if (isBlank(map) || isBlank(name)) { return false; } @@ -355,9 +359,8 @@ export class SelectorListContext { export class SelectorContext { notSelectors: CssSelector[]; - constructor( - public selector: CssSelector, public cbContext: any, - public listContext: SelectorListContext) { + constructor(public selector: CssSelector, public cbContext: any, + public listContext: SelectorListContext) { this.notSelectors = selector.notSelectors; } diff --git a/modules/angular2/src/compiler/shadow_css.ts b/modules/angular2/src/compiler/shadow_css.ts index 2115132dcf..21775e2362 100644 --- a/modules/angular2/src/compiler/shadow_css.ts +++ b/modules/angular2/src/compiler/shadow_css.ts @@ -1,5 +1,12 @@ import {ListWrapper} from 'angular2/src/facade/collection'; -import {StringWrapper, RegExp, RegExpWrapper, RegExpMatcherWrapper, isPresent, isBlank} from 'angular2/src/facade/lang'; +import { + StringWrapper, + RegExp, + RegExpWrapper, + RegExpMatcherWrapper, + isPresent, + isBlank +} from 'angular2/src/facade/lang'; /** * This file is a port of shadowCSS from webcomponents.js to TypeScript. @@ -167,8 +174,8 @@ export class ShadowCss { **/ private _insertPolyfillDirectivesInCssText(cssText: string): string { // Difference with webcomponents.js: does not handle comments - return StringWrapper.replaceAllMapped( - cssText, _cssContentNextSelectorRe, function(m) { return m[1] + '{'; }); + return StringWrapper.replaceAllMapped(cssText, _cssContentNextSelectorRe, + function(m) { return m[1] + '{'; }); } /* @@ -272,8 +279,8 @@ export class ShadowCss { * scopeName.foo .bar { ... } */ private _convertColonHostContext(cssText: string): string { - return this._convertColonRule( - cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer); + return this._convertColonRule(cssText, _cssColonHostContextRe, + this._colonHostContextPartReplacer); } private _convertColonRule(cssText: string, regExp: RegExp, partReplacer: Function): string { @@ -332,8 +339,8 @@ export class ShadowCss { }); } - private _scopeSelector( - selector: string, scopeSelector: string, hostSelector: string, strict: boolean): string { + private _scopeSelector(selector: string, scopeSelector: string, hostSelector: string, + strict: boolean): string { var r = [], parts = selector.split(','); for (var i = 0; i < parts.length; i++) { var p = parts[i].trim(); @@ -341,8 +348,8 @@ export class ShadowCss { var shallowPart = deepParts[0]; if (this._selectorNeedsScoping(shallowPart, scopeSelector)) { deepParts[0] = strict && !StringWrapper.contains(shallowPart, _polyfillHostNoCombinator) ? - this._applyStrictSelectorScope(shallowPart, scopeSelector) : - this._applySelectorScope(shallowPart, scopeSelector, hostSelector); + this._applyStrictSelectorScope(shallowPart, scopeSelector) : + this._applySelectorScope(shallowPart, scopeSelector, hostSelector); } // replace /deep/ with a space for child selectors r.push(deepParts.join(' ')); @@ -363,15 +370,15 @@ export class ShadowCss { return RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm'); } - private _applySelectorScope(selector: string, scopeSelector: string, hostSelector: string): - string { + private _applySelectorScope(selector: string, scopeSelector: string, + hostSelector: string): string { // Difference from webcomponentsjs: scopeSelector could not be an array return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector); } // scope via name and [is=name] - private _applySimpleSelectorScope(selector: string, scopeSelector: string, hostSelector: string): - string { + private _applySimpleSelectorScope(selector: string, scopeSelector: string, + hostSelector: string): string { if (isPresent(RegExpWrapper.firstMatch(_polyfillHostRe, selector))) { var replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector; selector = StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy); @@ -390,20 +397,19 @@ export class ShadowCss { for (var i = 0; i < splits.length; i++) { var sep = splits[i]; var parts = scoped.split(sep); - scoped = parts - .map(p => { - // remove :host since it should be unnecessary - var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, ''); - if (t.length > 0 && !ListWrapper.contains(splits, t) && - !StringWrapper.contains(t, attrName)) { - var re = /([^:]*)(:*)(.*)/g; - var m = RegExpWrapper.firstMatch(re, t); - if (isPresent(m)) { - p = m[1] + attrName + m[2] + m[3]; - } - } - return p; - }) + scoped = parts.map(p => { + // remove :host since it should be unnecessary + var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, ''); + if (t.length > 0 && !ListWrapper.contains(splits, t) && + !StringWrapper.contains(t, attrName)) { + var re = /([^:]*)(:*)(.*)/g; + var m = RegExpWrapper.firstMatch(re, t); + if (isPresent(m)) { + p = m[1] + attrName + m[2] + m[3]; + } + } + return p; + }) .join(sep); } return scoped; @@ -424,13 +430,14 @@ var _polyfillHost = '-shadowcsshost'; // note: :host-context pre-processed to -shadowcsshostcontext. var _polyfillHostContext = '-shadowcsscontext'; var _parenSuffix = ')(?:\\((' + - '(?:\\([^)(]*\\)|[^)(]*)+?' + - ')\\))?([^,{]*)'; + '(?:\\([^)(]*\\)|[^)(]*)+?' + + ')\\))?([^,{]*)'; var _cssColonHostRe = RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, 'im'); var _cssColonHostContextRe = RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im'); var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator'; var _shadowDOMSelectorsRe = [ - /::shadow/g, /::content/g, + /::shadow/g, + /::content/g, // Deprecated selectors // TODO(vicb): see https://github.com/angular/clang-format/issues/16 // clang-format off diff --git a/modules/angular2/src/compiler/static_reflector.ts b/modules/angular2/src/compiler/static_reflector.ts index cf11b1bcbc..925466e4ee 100644 --- a/modules/angular2/src/compiler/static_reflector.ts +++ b/modules/angular2/src/compiler/static_reflector.ts @@ -1,6 +1,30 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {isArray, isBlank, isNumber, isPresent, isPrimitive, isString, Type} from 'angular2/src/facade/lang'; -import {AttributeMetadata, DirectiveMetadata, ComponentMetadata, ContentChildrenMetadata, ContentChildMetadata, InputMetadata, HostBindingMetadata, HostListenerMetadata, OutputMetadata, PipeMetadata, ViewMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata, QueryMetadata,} from 'angular2/src/core/metadata'; +import { + isArray, + isBlank, + isNumber, + isPresent, + isPrimitive, + isString, + Type +} from 'angular2/src/facade/lang'; +import { + AttributeMetadata, + DirectiveMetadata, + ComponentMetadata, + ContentChildrenMetadata, + ContentChildMetadata, + InputMetadata, + HostBindingMetadata, + HostListenerMetadata, + OutputMetadata, + PipeMetadata, + ViewMetadata, + ViewChildMetadata, + ViewChildrenMetadata, + ViewQueryMetadata, + QueryMetadata, +} from 'angular2/src/core/metadata'; /** * The host of the static resolver is expected to be able to provide module metadata in the form of @@ -100,62 +124,60 @@ export class StaticReflector { private initializeConversionMap(): any { let core_metadata = 'angular2/src/core/metadata'; let conversionMap = this.conversionMap; - conversionMap.set( - this.getStaticType(core_metadata, 'Directive'), (moduleContext, expression) => { - let p0 = this.getDecoratorParameter(moduleContext, expression, 0); - if (!isPresent(p0)) { - p0 = {}; - } - return new DirectiveMetadata({ - selector: p0['selector'], - inputs: p0['inputs'], - outputs: p0['outputs'], - events: p0['events'], - host: p0['host'], - bindings: p0['bindings'], - providers: p0['providers'], - exportAs: p0['exportAs'], - queries: p0['queries'], - }); - }); - conversionMap.set( - this.getStaticType(core_metadata, 'Component'), (moduleContext, expression) => { - let p0 = this.getDecoratorParameter(moduleContext, expression, 0); - if (!isPresent(p0)) { - p0 = {}; - } - return new ComponentMetadata({ - selector: p0['selector'], - inputs: p0['inputs'], - outputs: p0['outputs'], - properties: p0['properties'], - events: p0['events'], - host: p0['host'], - exportAs: p0['exportAs'], - moduleId: p0['moduleId'], - bindings: p0['bindings'], - providers: p0['providers'], - viewBindings: p0['viewBindings'], - viewProviders: p0['viewProviders'], - changeDetection: p0['changeDetection'], - queries: p0['queries'], - templateUrl: p0['templateUrl'], - template: p0['template'], - styleUrls: p0['styleUrls'], - styles: p0['styles'], - directives: p0['directives'], - pipes: p0['pipes'], - encapsulation: p0['encapsulation'] - }); - }); - conversionMap.set( - this.getStaticType(core_metadata, 'Input'), - (moduleContext, expression) => - new InputMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'Output'), - (moduleContext, expression) => - new OutputMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'Directive'), + (moduleContext, expression) => { + let p0 = this.getDecoratorParameter(moduleContext, expression, 0); + if (!isPresent(p0)) { + p0 = {}; + } + return new DirectiveMetadata({ + selector: p0['selector'], + inputs: p0['inputs'], + outputs: p0['outputs'], + events: p0['events'], + host: p0['host'], + bindings: p0['bindings'], + providers: p0['providers'], + exportAs: p0['exportAs'], + queries: p0['queries'], + }); + }); + conversionMap.set(this.getStaticType(core_metadata, 'Component'), + (moduleContext, expression) => { + let p0 = this.getDecoratorParameter(moduleContext, expression, 0); + if (!isPresent(p0)) { + p0 = {}; + } + return new ComponentMetadata({ + selector: p0['selector'], + inputs: p0['inputs'], + outputs: p0['outputs'], + properties: p0['properties'], + events: p0['events'], + host: p0['host'], + exportAs: p0['exportAs'], + moduleId: p0['moduleId'], + bindings: p0['bindings'], + providers: p0['providers'], + viewBindings: p0['viewBindings'], + viewProviders: p0['viewProviders'], + changeDetection: p0['changeDetection'], + queries: p0['queries'], + templateUrl: p0['templateUrl'], + template: p0['template'], + styleUrls: p0['styleUrls'], + styles: p0['styles'], + directives: p0['directives'], + pipes: p0['pipes'], + encapsulation: p0['encapsulation'] + }); + }); + conversionMap.set(this.getStaticType(core_metadata, 'Input'), + (moduleContext, expression) => new InputMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'Output'), + (moduleContext, expression) => new OutputMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); conversionMap.set(this.getStaticType(core_metadata, 'View'), (moduleContext, expression) => { let p0 = this.getDecoratorParameter(moduleContext, expression, 0); if (!isPresent(p0)) { @@ -170,10 +192,9 @@ export class StaticReflector { styles: p0['styles'], }); }); - conversionMap.set( - this.getStaticType(core_metadata, 'Attribute'), - (moduleContext, expression) => - new AttributeMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'Attribute'), + (moduleContext, expression) => new AttributeMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); conversionMap.set(this.getStaticType(core_metadata, 'Query'), (moduleContext, expression) => { let p0 = this.getDecoratorParameter(moduleContext, expression, 0); let p1 = this.getDecoratorParameter(moduleContext, expression, 1); @@ -182,34 +203,30 @@ export class StaticReflector { } return new QueryMetadata(p0, {descendants: p1.descendants, first: p1.first}); }); - conversionMap.set( - this.getStaticType(core_metadata, 'ContentChildren'), - (moduleContext, expression) => - new ContentChildrenMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ContentChild'), - (moduleContext, expression) => - new ContentChildMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ViewChildren'), - (moduleContext, expression) => - new ViewChildrenMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ViewChild'), - (moduleContext, expression) => - new ViewChildMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ViewQuery'), (moduleContext, expression) => { - let p0 = this.getDecoratorParameter(moduleContext, expression, 0); - let p1 = this.getDecoratorParameter(moduleContext, expression, 1); - if (!isPresent(p1)) { - p1 = {}; - } - return new ViewQueryMetadata(p0, { - descendants: p1['descendants'], - first: p1['first'], - }); - }); + conversionMap.set(this.getStaticType(core_metadata, 'ContentChildren'), + (moduleContext, expression) => new ContentChildrenMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ContentChild'), + (moduleContext, expression) => new ContentChildMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ViewChildren'), + (moduleContext, expression) => new ViewChildrenMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ViewChild'), + (moduleContext, expression) => new ViewChildMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ViewQuery'), + (moduleContext, expression) => { + let p0 = this.getDecoratorParameter(moduleContext, expression, 0); + let p1 = this.getDecoratorParameter(moduleContext, expression, 1); + if (!isPresent(p1)) { + p1 = {}; + } + return new ViewQueryMetadata(p0, { + descendants: p1['descendants'], + first: p1['first'], + }); + }); conversionMap.set(this.getStaticType(core_metadata, 'Pipe'), (moduleContext, expression) => { let p0 = this.getDecoratorParameter(moduleContext, expression, 0); if (!isPresent(p0)) { @@ -220,15 +237,13 @@ export class StaticReflector { pure: p0['pure'], }); }); - conversionMap.set( - this.getStaticType(core_metadata, 'HostBinding'), - (moduleContext, expression) => - new HostBindingMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'HostListener'), - (moduleContext, expression) => new HostListenerMetadata( - this.getDecoratorParameter(moduleContext, expression, 0), - this.getDecoratorParameter(moduleContext, expression, 1))); + conversionMap.set(this.getStaticType(core_metadata, 'HostBinding'), + (moduleContext, expression) => new HostBindingMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'HostListener'), + (moduleContext, expression) => new HostListenerMetadata( + this.getDecoratorParameter(moduleContext, expression, 0), + this.getDecoratorParameter(moduleContext, expression, 1))); return null; } @@ -249,8 +264,8 @@ export class StaticReflector { return null; } - private getDecoratorParameter( - moduleContext: string, expression: {[key: string]: any}, index: number): any { + private getDecoratorParameter(moduleContext: string, expression: {[key: string]: any}, + index: number): any { if (isMetadataSymbolicCallExpression(expression) && isPresent(expression['arguments']) && (<any[]>expression['arguments']).length <= index + 1) { return this.simplify(moduleContext, (<any[]>expression['arguments'])[index]); @@ -258,14 +273,14 @@ export class StaticReflector { return null; } - private getPropertyMetadata(moduleContext: string, value: {[key: string]: any}): - {[key: string]: any} { + private getPropertyMetadata(moduleContext: string, + value: {[key: string]: any}): {[key: string]: any} { if (isPresent(value)) { let result = {}; StringMapWrapper.forEach(value, (value, name) => { let data = this.getMemberData(moduleContext, value); if (isPresent(data)) { - let propertyData = data.filter(d => d['kind'] == 'property') + let propertyData = data.filter(d => d['kind'] == "property") .map(d => d['directives']) .reduce((p, c) => (<any[]>p).concat(<any[]>c), []); if (propertyData.length != 0) { @@ -286,11 +301,12 @@ export class StaticReflector { for (let item of member) { result.push({ kind: item['__symbolic'], - directives: isPresent(item['decorators']) ? - (<any[]>item['decorators']) - .map(decorator => this.convertKnownDecorator(moduleContext, decorator)) - .filter(d => isPresent(d)) : - null + directives: + isPresent(item['decorators']) ? + (<any[]>item['decorators']) + .map(decorator => this.convertKnownDecorator(moduleContext, decorator)) + .filter(d => isPresent(d)) : + null }); } } @@ -307,7 +323,7 @@ export class StaticReflector { } if (isArray(expression)) { let result = []; - for (let item of (<any>expression)) { + for (let item of(<any>expression)) { result.push(simplify(item)); } return result; @@ -315,7 +331,7 @@ export class StaticReflector { if (isPresent(expression)) { if (isPresent(expression['__symbolic'])) { switch (expression['__symbolic']) { - case 'binop': + case "binop": let left = simplify(expression['left']); let right = simplify(expression['right']); switch (expression['operator']) { @@ -361,7 +377,7 @@ export class StaticReflector { return left % right; } return null; - case 'pre': + case "pre": let operand = simplify(expression['operand']); switch (expression['operator']) { case '+': @@ -374,17 +390,17 @@ export class StaticReflector { return ~operand; } return null; - case 'index': + case "index": let indexTarget = simplify(expression['expression']); let index = simplify(expression['index']); if (isPresent(indexTarget) && isPrimitive(index)) return indexTarget[index]; return null; - case 'select': + case "select": let selectTarget = simplify(expression['expression']); let member = simplify(expression['member']); if (isPresent(selectTarget) && isPrimitive(member)) return selectTarget[member]; return null; - case 'reference': + case "reference": let referenceModuleName = _this.normalizeModuleName(moduleContext, expression['module']); let referenceModule = _this.getModuleMetadata(referenceModuleName); @@ -394,7 +410,7 @@ export class StaticReflector { return _this.getStaticType(referenceModuleName, expression['name']); } return _this.simplify(referenceModuleName, referenceValue); - case 'call': + case "call": return null; } return null; @@ -414,7 +430,7 @@ export class StaticReflector { if (!isPresent(moduleMetadata)) { moduleMetadata = this.host.getMetadataFor(module); if (!isPresent(moduleMetadata)) { - moduleMetadata = {__symbolic: 'module', module: module, metadata: {}}; + moduleMetadata = {__symbolic: "module", module: module, metadata: {}}; } this.metadataCache.set(module, moduleMetadata); } @@ -425,7 +441,7 @@ export class StaticReflector { let moduleMetadata = this.getModuleMetadata(type.moduleId); let result = moduleMetadata['metadata'][type.name]; if (!isPresent(result)) { - result = {__symbolic: 'class'}; + result = {__symbolic: "class"}; } return result; } @@ -444,7 +460,7 @@ function isMetadataSymbolicCallExpression(expression: any): boolean { function isMetadataSymbolicReferenceExpression(expression: any): boolean { return !isPrimitive(expression) && !isArray(expression) && - expression['__symbolic'] == 'reference'; + expression['__symbolic'] == 'reference'; } function isClassMetadata(expression: any): boolean { diff --git a/modules/angular2/src/compiler/style_compiler.ts b/modules/angular2/src/compiler/style_compiler.ts index 376bbdd36a..565e33c0c6 100644 --- a/modules/angular2/src/compiler/style_compiler.ts +++ b/modules/angular2/src/compiler/style_compiler.ts @@ -7,7 +7,12 @@ import {PromiseWrapper} from 'angular2/src/facade/async'; import {ShadowCss} from 'angular2/src/compiler/shadow_css'; import {UrlResolver} from 'angular2/src/compiler/url_resolver'; import {extractStyleUrls} from './style_url_resolver'; -import {escapeSingleQuoteString, codeGenExportVariable, codeGenToString, MODULE_SUFFIX} from './util'; +import { + escapeSingleQuoteString, + codeGenExportVariable, + codeGenToString, + MODULE_SUFFIX +} from './util'; import {Injectable} from 'angular2/src/core/di'; const COMPONENT_VARIABLE = '%COMP%'; @@ -21,11 +26,11 @@ export class StyleCompiler { constructor(private _xhr: XHR, private _urlResolver: UrlResolver) {} - compileComponentRuntime(template: CompileTemplateMetadata): Promise<Array<string|any[]>> { + compileComponentRuntime(template: CompileTemplateMetadata): Promise<Array<string | any[]>> { var styles = template.styles; var styleAbsUrls = template.styleUrls; - return this._loadStyles( - styles, styleAbsUrls, template.encapsulation === ViewEncapsulation.Emulated); + return this._loadStyles(styles, styleAbsUrls, + template.encapsulation === ViewEncapsulation.Emulated); } compileComponentCodeGen(template: CompileTemplateMetadata): SourceExpression { @@ -39,31 +44,30 @@ export class StyleCompiler { this._styleModule( stylesheetUrl, false, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, false)), - this._styleModule( - stylesheetUrl, true, - this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, true)) + this._styleModule(stylesheetUrl, true, this._styleCodeGen([styleWithImports.style], + styleWithImports.styleUrls, true)) ]; } clearCache() { this._styleCache.clear(); } - private _loadStyles(plainStyles: string[], absUrls: string[], encapsulate: boolean): - Promise<Array<string|any[]>> { + private _loadStyles(plainStyles: string[], absUrls: string[], + encapsulate: boolean): Promise<Array<string | any[]>> { var promises: Promise<string[]>[] = absUrls.map((absUrl: string): Promise<string[]> => { var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`; var result: Promise<string[]> = this._styleCache.get(cacheKey); if (isBlank(result)) { result = this._xhr.get(absUrl).then((style) => { var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style); - return this._loadStyles( - [styleWithImports.style], styleWithImports.styleUrls, encapsulate); + return this._loadStyles([styleWithImports.style], styleWithImports.styleUrls, + encapsulate); }); this._styleCache.set(cacheKey, result); } return result; }); return PromiseWrapper.all<string[]>(promises).then((nestedStyles: string[][]) => { - var result: Array<string|any[]> = + var result: Array<string | any[]> = plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate)); nestedStyles.forEach(styles => result.push(styles)); return result; @@ -83,8 +87,8 @@ export class StyleCompiler { return new SourceExpression([], expressionSource); } - private _styleModule(stylesheetUrl: string, shim: boolean, expression: SourceExpression): - SourceModule { + private _styleModule(stylesheetUrl: string, shim: boolean, + expression: SourceExpression): SourceModule { var moduleSource = ` ${expression.declarations.join('\n')} ${codeGenExportVariable('STYLES')}${expression.expression}; diff --git a/modules/angular2/src/compiler/style_url_resolver.ts b/modules/angular2/src/compiler/style_url_resolver.ts index 2603456a48..bdd229e254 100644 --- a/modules/angular2/src/compiler/style_url_resolver.ts +++ b/modules/angular2/src/compiler/style_url_resolver.ts @@ -18,8 +18,8 @@ export function isStyleUrlResolvable(url: string): boolean { * Rewrites stylesheets by resolving and removing the @import urls that * are either relative or don't have a `package:` scheme */ -export function extractStyleUrls( - resolver: UrlResolver, baseUrl: string, cssText: string): StyleWithImports { +export function extractStyleUrls(resolver: UrlResolver, baseUrl: string, + cssText: string): StyleWithImports { var foundUrls = []; var modifiedCssText = StringWrapper.replaceAllMapped(cssText, _cssImportRe, (m) => { var url = isPresent(m[1]) ? m[1] : m[2]; diff --git a/modules/angular2/src/compiler/template_ast.ts b/modules/angular2/src/compiler/template_ast.ts index 53f876d65c..1b79d32be5 100644 --- a/modules/angular2/src/compiler/template_ast.ts +++ b/modules/angular2/src/compiler/template_ast.ts @@ -22,8 +22,8 @@ export interface TemplateAst { * A segment of text within the template. */ export class TextAst implements TemplateAst { - constructor( - public value: string, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public value: string, public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitText(this, context); } } @@ -31,8 +31,8 @@ export class TextAst implements TemplateAst { * A bound expression within the text of a template. */ export class BoundTextAst implements TemplateAst { - constructor( - public value: AST, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public value: AST, public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitBoundText(this, context); } @@ -50,9 +50,8 @@ export class AttrAst implements TemplateAst { * A binding for an element property (e.g. `[property]="expression"`). */ export class BoundElementPropertyAst implements TemplateAst { - constructor( - public name: string, public type: PropertyBindingType, public value: AST, public unit: string, - public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public type: PropertyBindingType, public value: AST, + public unit: string, public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitElementProperty(this, context); } @@ -62,9 +61,8 @@ export class BoundElementPropertyAst implements TemplateAst { * A binding for an element event (e.g. `(event)="handler()"`). */ export class BoundEventAst implements TemplateAst { - constructor( - public name: string, public target: string, public handler: AST, - public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public target: string, public handler: AST, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitEvent(this, context); } @@ -91,11 +89,11 @@ export class VariableAst implements TemplateAst { * An element declaration in a template. */ export class ElementAst implements TemplateAst { - constructor( - public name: string, public attrs: AttrAst[], public inputs: BoundElementPropertyAst[], - public outputs: BoundEventAst[], public exportAsVars: VariableAst[], - public directives: DirectiveAst[], public children: TemplateAst[], - public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public attrs: AttrAst[], + public inputs: BoundElementPropertyAst[], public outputs: BoundEventAst[], + public exportAsVars: VariableAst[], public directives: DirectiveAst[], + public children: TemplateAst[], public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitElement(this, context); } @@ -104,9 +102,8 @@ export class ElementAst implements TemplateAst { * Whether the element has any active bindings (inputs, outputs, vars, or directives). */ isBound(): boolean { - return ( - this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || - this.directives.length > 0); + return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || + this.directives.length > 0); } /** @@ -114,8 +111,8 @@ export class ElementAst implements TemplateAst { */ getComponent(): CompileDirectiveMetadata { return this.directives.length > 0 && this.directives[0].directive.isComponent ? - this.directives[0].directive : - null; + this.directives[0].directive : + null; } } @@ -123,10 +120,9 @@ export class ElementAst implements TemplateAst { * A `<template>` element included in an Angular template. */ export class EmbeddedTemplateAst implements TemplateAst { - constructor( - public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[], - public directives: DirectiveAst[], public children: TemplateAst[], - public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[], + public directives: DirectiveAst[], public children: TemplateAst[], + public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitEmbeddedTemplate(this, context); } @@ -136,9 +132,8 @@ export class EmbeddedTemplateAst implements TemplateAst { * A directive property with a bound value (e.g. `*ngIf="condition"). */ export class BoundDirectivePropertyAst implements TemplateAst { - constructor( - public directiveName: string, public templateName: string, public value: AST, - public sourceSpan: ParseSourceSpan) {} + constructor(public directiveName: string, public templateName: string, public value: AST, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitDirectiveProperty(this, context); } @@ -148,10 +143,10 @@ export class BoundDirectivePropertyAst implements TemplateAst { * A directive declared on an element. */ export class DirectiveAst implements TemplateAst { - constructor( - public directive: CompileDirectiveMetadata, public inputs: BoundDirectivePropertyAst[], - public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[], - public exportAsVars: VariableAst[], public sourceSpan: ParseSourceSpan) {} + constructor(public directive: CompileDirectiveMetadata, + public inputs: BoundDirectivePropertyAst[], + public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[], + public exportAsVars: VariableAst[], public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitDirective(this, context); } @@ -161,8 +156,8 @@ export class DirectiveAst implements TemplateAst { * Position where content is to be projected (instance of `<ng-content>` in a template). */ export class NgContentAst implements TemplateAst { - constructor( - public index: number, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public index: number, public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitNgContent(this, context); } @@ -214,8 +209,8 @@ export interface TemplateAstVisitor { /** * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}. */ -export function templateVisitAll( - visitor: TemplateAstVisitor, asts: TemplateAst[], context: any = null): any[] { +export function templateVisitAll(visitor: TemplateAstVisitor, asts: TemplateAst[], + context: any = null): any[] { var result = []; asts.forEach(ast => { var astResult = ast.visit(visitor, context); diff --git a/modules/angular2/src/compiler/template_compiler.ts b/modules/angular2/src/compiler/template_compiler.ts index b7b5fe3138..ed5ff0ef78 100644 --- a/modules/angular2/src/compiler/template_compiler.ts +++ b/modules/angular2/src/compiler/template_compiler.ts @@ -1,15 +1,55 @@ -import {IS_DART, Type, Json, isBlank, isPresent, stringify, evalExpression} from 'angular2/src/facade/lang'; +import { + IS_DART, + Type, + Json, + isBlank, + isPresent, + stringify, + evalExpression +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; -import {ListWrapper, SetWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; +import { + ListWrapper, + SetWrapper, + MapWrapper, + StringMapWrapper +} from 'angular2/src/facade/collection'; import {PromiseWrapper} from 'angular2/src/facade/async'; -import {createHostComponentMeta, CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata, CompilePipeMetadata, CompileMetadataWithType} from './directive_metadata'; -import {TemplateAst, TemplateAstVisitor, NgContentAst, EmbeddedTemplateAst, ElementAst, VariableAst, BoundEventAst, BoundElementPropertyAst, AttrAst, BoundTextAst, TextAst, DirectiveAst, BoundDirectivePropertyAst, templateVisitAll} from './template_ast'; +import { + createHostComponentMeta, + CompileDirectiveMetadata, + CompileTypeMetadata, + CompileTemplateMetadata, + CompilePipeMetadata, + CompileMetadataWithType +} from './directive_metadata'; +import { + TemplateAst, + TemplateAstVisitor, + NgContentAst, + EmbeddedTemplateAst, + ElementAst, + VariableAst, + BoundEventAst, + BoundElementPropertyAst, + AttrAst, + BoundTextAst, + TextAst, + DirectiveAst, + BoundDirectivePropertyAst, + templateVisitAll +} from './template_ast'; import {Injectable} from 'angular2/src/core/di'; import {SourceModule, moduleRef, SourceExpression} from './source_module'; import {ChangeDetectionCompiler, CHANGE_DETECTION_JIT_IMPORTS} from './change_detector_compiler'; import {StyleCompiler} from './style_compiler'; import {ViewCompiler, VIEW_JIT_IMPORTS} from './view_compiler'; -import {ProtoViewCompiler, APP_VIEW_MODULE_REF, CompileProtoView, PROTO_VIEW_JIT_IMPORTS} from './proto_view_compiler'; +import { + ProtoViewCompiler, + APP_VIEW_MODULE_REF, + CompileProtoView, + PROTO_VIEW_JIT_IMPORTS +} from './proto_view_compiler'; import {TemplateParser, PipeCollector} from './template_parser'; import {TemplateNormalizer} from './template_normalizer'; import {RuntimeMetadataResolver} from './runtime_metadata'; @@ -17,7 +57,14 @@ import {HostViewFactory} from 'angular2/src/core/linker/view'; import {ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection'; import {ResolvedMetadataCache} from 'angular2/src/core/linker/resolved_metadata_cache'; -import {codeGenExportVariable, escapeSingleQuoteString, codeGenValueFn, MODULE_SUFFIX, addAll, Expression} from './util'; +import { + codeGenExportVariable, + escapeSingleQuoteString, + codeGenValueFn, + MODULE_SUFFIX, + addAll, + Expression +} from './util'; export var METADATA_CACHE_MODULE_REF = moduleRef('package:angular2/src/core/linker/resolved_metadata_cache' + MODULE_SUFFIX); @@ -33,13 +80,13 @@ export class TemplateCompiler { private _compiledTemplateCache = new Map<any, CompiledTemplate>(); private _compiledTemplateDone = new Map<any, Promise<CompiledTemplate>>(); - constructor( - private _runtimeMetadataResolver: RuntimeMetadataResolver, - private _templateNormalizer: TemplateNormalizer, private _templateParser: TemplateParser, - private _styleCompiler: StyleCompiler, private _cdCompiler: ChangeDetectionCompiler, - private _protoViewCompiler: ProtoViewCompiler, private _viewCompiler: ViewCompiler, - private _resolvedMetadataCache: ResolvedMetadataCache, - private _genConfig: ChangeDetectorGenConfig) {} + constructor(private _runtimeMetadataResolver: RuntimeMetadataResolver, + private _templateNormalizer: TemplateNormalizer, + private _templateParser: TemplateParser, private _styleCompiler: StyleCompiler, + private _cdCompiler: ChangeDetectionCompiler, + private _protoViewCompiler: ProtoViewCompiler, private _viewCompiler: ViewCompiler, + private _resolvedMetadataCache: ResolvedMetadataCache, + private _genConfig: ChangeDetectorGenConfig) {} normalizeDirectiveMetadata(directive: CompileDirectiveMetadata): Promise<CompileDirectiveMetadata> { @@ -84,9 +131,8 @@ export class TemplateCompiler { this._compileComponentRuntime(hostCacheKey, hostMeta, [compMeta], [], []); } return this._compiledTemplateDone.get(hostCacheKey) - .then( - (compiledTemplate: CompiledTemplate) => - new HostViewFactory(compMeta.selector, compiledTemplate.viewFactory)); + .then((compiledTemplate: CompiledTemplate) => + new HostViewFactory(compMeta.selector, compiledTemplate.viewFactory)); } clearCache() { @@ -104,8 +150,8 @@ export class TemplateCompiler { components.forEach(componentWithDirs => { var compMeta = <CompileDirectiveMetadata>componentWithDirs.component; assertComponent(compMeta); - this._compileComponentCodeGen( - compMeta, componentWithDirs.directives, componentWithDirs.pipes, declarations); + this._compileComponentCodeGen(compMeta, componentWithDirs.directives, componentWithDirs.pipes, + declarations); if (compMeta.dynamicLoadable) { var hostMeta = createHostComponentMeta(compMeta.type, compMeta.selector); var viewFactoryExpression = @@ -127,9 +173,10 @@ export class TemplateCompiler { - private _compileComponentRuntime( - cacheKey: any, compMeta: CompileDirectiveMetadata, viewDirectives: CompileDirectiveMetadata[], - pipes: CompilePipeMetadata[], compilingComponentsPath: any[]): CompiledTemplate { + private _compileComponentRuntime(cacheKey: any, compMeta: CompileDirectiveMetadata, + viewDirectives: CompileDirectiveMetadata[], + pipes: CompilePipeMetadata[], + compilingComponentsPath: any[]): CompiledTemplate { let uniqViewDirectives = <CompileDirectiveMetadata[]>removeDuplicates(viewDirectives); let uniqViewPipes = <CompilePipeMetadata[]>removeDuplicates(pipes); var compiledTemplate = this._compiledTemplateCache.get(cacheKey); @@ -137,37 +184,38 @@ export class TemplateCompiler { if (isBlank(compiledTemplate)) { compiledTemplate = new CompiledTemplate(); this._compiledTemplateCache.set(cacheKey, compiledTemplate); - done = - PromiseWrapper - .all([<any>this._styleCompiler.compileComponentRuntime(compMeta.template)].concat( - uniqViewDirectives.map(dirMeta => this.normalizeDirectiveMetadata(dirMeta)))) - .then((stylesAndNormalizedViewDirMetas: any[]) => { - var normalizedViewDirMetas = stylesAndNormalizedViewDirMetas.slice(1); - var styles = stylesAndNormalizedViewDirMetas[0]; - var parsedTemplate = this._templateParser.parse( - compMeta.template.template, normalizedViewDirMetas, uniqViewPipes, - compMeta.type.name); + done = PromiseWrapper + .all([<any>this._styleCompiler.compileComponentRuntime(compMeta.template)].concat( + uniqViewDirectives.map(dirMeta => this.normalizeDirectiveMetadata(dirMeta)))) + .then((stylesAndNormalizedViewDirMetas: any[]) => { + var normalizedViewDirMetas = stylesAndNormalizedViewDirMetas.slice(1); + var styles = stylesAndNormalizedViewDirMetas[0]; + var parsedTemplate = this._templateParser.parse( + compMeta.template.template, normalizedViewDirMetas, uniqViewPipes, + compMeta.type.name); - var childPromises = []; - var usedDirectives = DirectiveCollector.findUsedDirectives(parsedTemplate); - usedDirectives.components.forEach( - component => this._compileNestedComponentRuntime( - component, compilingComponentsPath, childPromises)); - return PromiseWrapper.all(childPromises).then((_) => { - var filteredPipes = filterPipes(parsedTemplate, uniqViewPipes); - compiledTemplate.init(this._createViewFactoryRuntime( - compMeta, parsedTemplate, usedDirectives.directives, styles, filteredPipes)); - return compiledTemplate; - }); - }); + var childPromises = []; + var usedDirectives = DirectiveCollector.findUsedDirectives(parsedTemplate); + usedDirectives.components.forEach( + component => this._compileNestedComponentRuntime( + component, compilingComponentsPath, childPromises)); + return PromiseWrapper.all(childPromises) + .then((_) => { + var filteredPipes = filterPipes(parsedTemplate, uniqViewPipes); + compiledTemplate.init(this._createViewFactoryRuntime( + compMeta, parsedTemplate, usedDirectives.directives, styles, + filteredPipes)); + return compiledTemplate; + }); + }); this._compiledTemplateDone.set(cacheKey, done); } return compiledTemplate; } - private _compileNestedComponentRuntime( - childComponentDir: CompileDirectiveMetadata, parentCompilingComponentsPath: any[], - childPromises: Promise<any>[]) { + private _compileNestedComponentRuntime(childComponentDir: CompileDirectiveMetadata, + parentCompilingComponentsPath: any[], + childPromises: Promise<any>[]) { var compilingComponentsPath = ListWrapper.clone(parentCompilingComponentsPath); var childCacheKey = childComponentDir.type.runtime; @@ -177,19 +225,18 @@ export class TemplateCompiler { this._runtimeMetadataResolver.getViewPipesMetadata(childComponentDir.type.runtime); var childIsRecursive = ListWrapper.contains(compilingComponentsPath, childCacheKey); compilingComponentsPath.push(childCacheKey); - this._compileComponentRuntime( - childCacheKey, childComponentDir, childViewDirectives, childViewPipes, - compilingComponentsPath); + this._compileComponentRuntime(childCacheKey, childComponentDir, childViewDirectives, + childViewPipes, compilingComponentsPath); if (!childIsRecursive) { // Only wait for a child if it is not a cycle childPromises.push(this._compiledTemplateDone.get(childCacheKey)); } } - private _createViewFactoryRuntime( - compMeta: CompileDirectiveMetadata, parsedTemplate: TemplateAst[], - directives: CompileDirectiveMetadata[], styles: string[], - pipes: CompilePipeMetadata[]): Function { + private _createViewFactoryRuntime(compMeta: CompileDirectiveMetadata, + parsedTemplate: TemplateAst[], + directives: CompileDirectiveMetadata[], styles: string[], + pipes: CompilePipeMetadata[]): Function { if (IS_DART || !this._genConfig.useJit) { var changeDetectorFactories = this._cdCompiler.compileComponentRuntime( compMeta.type, compMeta.changeDetection, parsedTemplate); @@ -200,14 +247,11 @@ export class TemplateCompiler { (compMeta) => this._getNestedComponentViewFactory(compMeta)); } else { var declarations = []; - var viewFactoryExpr = this._createViewFactoryCodeGen( - 'resolvedMetadataCache', compMeta, new SourceExpression([], 'styles'), parsedTemplate, - pipes, declarations); - var vars: {[key: string]: any} = { - 'exports': {}, - 'styles': styles, - 'resolvedMetadataCache': this._resolvedMetadataCache - }; + var viewFactoryExpr = this._createViewFactoryCodeGen('resolvedMetadataCache', compMeta, + new SourceExpression([], 'styles'), + parsedTemplate, pipes, declarations); + var vars: {[key: string]: any} = + {'exports': {}, 'styles': styles, 'resolvedMetadataCache': this._resolvedMetadataCache}; directives.forEach(dirMeta => { vars[dirMeta.type.name] = dirMeta.type.runtime; if (dirMeta.isComponent && dirMeta.type.runtime !== compMeta.type.runtime) { @@ -228,24 +272,25 @@ export class TemplateCompiler { return this._compiledTemplateCache.get(compMeta.type.runtime).viewFactory; } - private _compileComponentCodeGen( - compMeta: CompileDirectiveMetadata, directives: CompileDirectiveMetadata[], - pipes: CompilePipeMetadata[], targetDeclarations: string[]): string { + private _compileComponentCodeGen(compMeta: CompileDirectiveMetadata, + directives: CompileDirectiveMetadata[], + pipes: CompilePipeMetadata[], + targetDeclarations: string[]): string { let uniqueDirectives = <CompileDirectiveMetadata[]>removeDuplicates(directives); let uniqPipes = <CompilePipeMetadata[]>removeDuplicates(pipes); var styleExpr = this._styleCompiler.compileComponentCodeGen(compMeta.template); - var parsedTemplate = this._templateParser.parse( - compMeta.template.template, uniqueDirectives, uniqPipes, compMeta.type.name); + var parsedTemplate = this._templateParser.parse(compMeta.template.template, uniqueDirectives, + uniqPipes, compMeta.type.name); var filteredPipes = filterPipes(parsedTemplate, uniqPipes); return this._createViewFactoryCodeGen( `${METADATA_CACHE_MODULE_REF}CODEGEN_RESOLVED_METADATA_CACHE`, compMeta, styleExpr, parsedTemplate, filteredPipes, targetDeclarations); } - private _createViewFactoryCodeGen( - resolvedMetadataCacheExpr: string, compMeta: CompileDirectiveMetadata, - styleExpr: SourceExpression, parsedTemplate: TemplateAst[], pipes: CompilePipeMetadata[], - targetDeclarations: string[]): string { + private _createViewFactoryCodeGen(resolvedMetadataCacheExpr: string, + compMeta: CompileDirectiveMetadata, styleExpr: SourceExpression, + parsedTemplate: TemplateAst[], pipes: CompilePipeMetadata[], + targetDeclarations: string[]): string { var changeDetectorsExprs = this._cdCompiler.compileComponentCodeGen( compMeta.type, compMeta.changeDetection, parsedTemplate); var protoViewExprs = this._protoViewCompiler.compileProtoViewCodeGen( @@ -263,9 +308,8 @@ export class TemplateCompiler { } export class NormalizedComponentWithViewDirectives { - constructor( - public component: CompileDirectiveMetadata, public directives: CompileDirectiveMetadata[], - public pipes: CompilePipeMetadata[]) {} + constructor(public component: CompileDirectiveMetadata, + public directives: CompileDirectiveMetadata[], public pipes: CompilePipeMetadata[]) {} } class CompiledTemplate { @@ -304,9 +348,8 @@ function removeDuplicates(items: CompileMetadataWithType[]): CompileMetadataWith let res = []; items.forEach(item => { let hasMatch = - res.filter( - r => r.type.name == item.type.name && r.type.moduleUrl == item.type.moduleUrl && - r.type.runtime == item.type.runtime) + res.filter(r => r.type.name == item.type.name && r.type.moduleUrl == item.type.moduleUrl && + r.type.runtime == item.type.runtime) .length > 0; if (!hasMatch) { res.push(item); @@ -358,8 +401,8 @@ class DirectiveCollector implements TemplateAstVisitor { } -function filterPipes( - template: TemplateAst[], allPipes: CompilePipeMetadata[]): CompilePipeMetadata[] { +function filterPipes(template: TemplateAst[], + allPipes: CompilePipeMetadata[]): CompilePipeMetadata[] { var visitor = new PipeVisitor(); templateVisitAll(visitor, template); return allPipes.filter((pipeMeta) => SetWrapper.has(visitor.collector.pipes, pipeMeta.name)); diff --git a/modules/angular2/src/compiler/template_normalizer.ts b/modules/angular2/src/compiler/template_normalizer.ts index 93b637d1e7..905793bcdf 100644 --- a/modules/angular2/src/compiler/template_normalizer.ts +++ b/modules/angular2/src/compiler/template_normalizer.ts @@ -1,4 +1,8 @@ -import {CompileTypeMetadata, CompileDirectiveMetadata, CompileTemplateMetadata} from './directive_metadata'; +import { + CompileTypeMetadata, + CompileDirectiveMetadata, + CompileTemplateMetadata +} from './directive_metadata'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {PromiseWrapper} from 'angular2/src/facade/async'; @@ -10,35 +14,41 @@ import {Injectable} from 'angular2/src/core/di'; import {ViewEncapsulation} from 'angular2/src/core/metadata/view'; -import {HtmlAstVisitor, HtmlElementAst, HtmlTextAst, HtmlAttrAst, HtmlAst, HtmlCommentAst, htmlVisitAll} from './html_ast'; +import { + HtmlAstVisitor, + HtmlElementAst, + HtmlTextAst, + HtmlAttrAst, + HtmlAst, + HtmlCommentAst, + htmlVisitAll +} from './html_ast'; import {HtmlParser} from './html_parser'; import {preparseElement, PreparsedElement, PreparsedElementType} from './template_preparser'; @Injectable() export class TemplateNormalizer { - constructor( - private _xhr: XHR, private _urlResolver: UrlResolver, private _htmlParser: HtmlParser) {} + constructor(private _xhr: XHR, private _urlResolver: UrlResolver, + private _htmlParser: HtmlParser) {} - normalizeTemplate(directiveType: CompileTypeMetadata, template: CompileTemplateMetadata): - Promise<CompileTemplateMetadata> { + normalizeTemplate(directiveType: CompileTypeMetadata, + template: CompileTemplateMetadata): Promise<CompileTemplateMetadata> { if (isPresent(template.template)) { return PromiseWrapper.resolve(this.normalizeLoadedTemplate( directiveType, template, template.template, directiveType.moduleUrl)); } else if (isPresent(template.templateUrl)) { var sourceAbsUrl = this._urlResolver.resolve(directiveType.moduleUrl, template.templateUrl); return this._xhr.get(sourceAbsUrl) - .then( - templateContent => this.normalizeLoadedTemplate( - directiveType, template, templateContent, sourceAbsUrl)); + .then(templateContent => this.normalizeLoadedTemplate(directiveType, template, + templateContent, sourceAbsUrl)); } else { throw new BaseException(`No template specified for component ${directiveType.name}`); } } - normalizeLoadedTemplate( - directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata, template: string, - templateAbsUrl: string): CompileTemplateMetadata { + normalizeLoadedTemplate(directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata, + template: string, templateAbsUrl: string): CompileTemplateMetadata { var rootNodesAndErrors = this._htmlParser.parse(template, directiveType.name); if (rootNodesAndErrors.errors.length > 0) { var errorString = rootNodesAndErrors.errors.join('\n'); diff --git a/modules/angular2/src/compiler/template_parser.ts b/modules/angular2/src/compiler/template_parser.ts index 85a3e56029..75e28bd8a9 100644 --- a/modules/angular2/src/compiler/template_parser.ts +++ b/modules/angular2/src/compiler/template_parser.ts @@ -11,7 +11,23 @@ import {splitNsName, mergeNsAndName} from './html_tags'; import {ParseSourceSpan, ParseError, ParseLocation} from './parse_util'; import {RecursiveAstVisitor, BindingPipe} from 'angular2/src/core/change_detection/parser/ast'; -import {ElementAst, BoundElementPropertyAst, BoundEventAst, VariableAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, BoundTextAst, EmbeddedTemplateAst, AttrAst, NgContentAst, PropertyBindingType, DirectiveAst, BoundDirectivePropertyAst} from './template_ast'; +import { + ElementAst, + BoundElementPropertyAst, + BoundEventAst, + VariableAst, + TemplateAst, + TemplateAstVisitor, + templateVisitAll, + TextAst, + BoundTextAst, + EmbeddedTemplateAst, + AttrAst, + NgContentAst, + PropertyBindingType, + DirectiveAst, + BoundDirectivePropertyAst +} from './template_ast'; import {CssSelector, SelectorMatcher} from 'angular2/src/compiler/selector'; import {ElementSchemaRegistry} from 'angular2/src/compiler/schema/element_schema_registry'; @@ -19,7 +35,15 @@ import {preparseElement, PreparsedElement, PreparsedElementType} from './templat import {isStyleUrlResolvable} from './style_url_resolver'; -import {HtmlAstVisitor, HtmlAst, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from './html_ast'; +import { + HtmlAstVisitor, + HtmlAst, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from './html_ast'; import {splitAtColon} from './util'; @@ -65,14 +89,12 @@ export class TemplateParseResult { @Injectable() export class TemplateParser { - constructor( - private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, - private _htmlParser: HtmlParser, - @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} + constructor(private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, + private _htmlParser: HtmlParser, + @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} - parse( - template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], - templateUrl: string): TemplateAst[] { + parse(template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], + templateUrl: string): TemplateAst[] { var result = this.tryParse(template, directives, pipes, templateUrl); if (isPresent(result.errors)) { var errorString = result.errors.join('\n'); @@ -81,9 +103,8 @@ export class TemplateParser { return result.templateAst; } - tryParse( - template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], - templateUrl: string): TemplateParseResult { + tryParse(template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], + templateUrl: string): TemplateParseResult { var parseVisitor = new TemplateParseVisitor(directives, pipes, this._exprParser, this._schemaRegistry); var htmlAstWithErrors = this._htmlParser.parse(template, templateUrl); @@ -107,16 +128,15 @@ class TemplateParseVisitor implements HtmlAstVisitor { ngContentCount: number = 0; pipesByName: Map<string, CompilePipeMetadata>; - constructor( - directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], - private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { + constructor(directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], + private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { this.selectorMatcher = new SelectorMatcher(); - ListWrapper.forEachWithIndex( - directives, (directive: CompileDirectiveMetadata, index: number) => { - var selector = CssSelector.parse(directive.selector); - this.selectorMatcher.addSelectables(selector, directive); - this.directivesIndex.set(directive, index); - }); + ListWrapper.forEachWithIndex(directives, + (directive: CompileDirectiveMetadata, index: number) => { + var selector = CssSelector.parse(directive.selector); + this.selectorMatcher.addSelectables(selector, directive); + this.directivesIndex.set(directive, index); + }); this.pipesByName = new Map<string, CompilePipeMetadata>(); pipes.forEach(pipe => this.pipesByName.set(pipe.name, pipe)); } @@ -255,14 +275,13 @@ class TemplateParseVisitor implements HtmlAstVisitor { elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceSpan); var elementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directives); - var children = htmlVisitAll( - preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, - Component.create(directives)); + var children = htmlVisitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, + element.children, Component.create(directives)); // Override the actual selector when the `ngProjectAs` attribute is provided var projectionSelector = isPresent(preparsedElement.projectAs) ? - CssSelector.parse(preparsedElement.projectAs)[0] : - elementCssSelector; + CssSelector.parse(preparsedElement.projectAs)[0] : + elementCssSelector; var ngContentIndex = component.findNgContentIndex(projectionSelector); var parsedElement; @@ -277,21 +296,21 @@ class TemplateParseVisitor implements HtmlAstVisitor { this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else if (isTemplateElement) { this._assertAllEventsPublishedByDirectives(directives, events); - this._assertNoComponentsNorElementBindingsOnTemplate( - directives, elementProps, element.sourceSpan); + this._assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps, + element.sourceSpan); - parsedElement = new EmbeddedTemplateAst( - attrs, events, vars, directives, children, hasInlineTemplates ? null : ngContentIndex, - element.sourceSpan); + parsedElement = + new EmbeddedTemplateAst(attrs, events, vars, directives, children, + hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else { this._assertOnlyOneComponent(directives, element.sourceSpan); var elementExportAsVars = vars.filter(varAst => varAst.value.length === 0); let ngContentIndex = hasInlineTemplates ? null : component.findNgContentIndex(projectionSelector); - parsedElement = new ElementAst( - nodeName, attrs, elementProps, events, elementExportAsVars, directives, children, - hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); + parsedElement = + new ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives, + children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } if (hasInlineTemplates) { var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); @@ -300,19 +319,18 @@ class TemplateParseVisitor implements HtmlAstVisitor { templateElementOrDirectiveProps, [], element.sourceSpan); var templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts( element.name, templateElementOrDirectiveProps, templateDirectives); - this._assertNoComponentsNorElementBindingsOnTemplate( - templateDirectives, templateElementProps, element.sourceSpan); + this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectives, templateElementProps, + element.sourceSpan); - parsedElement = new EmbeddedTemplateAst( - [], [], templateVars, templateDirectives, [parsedElement], ngContentIndex, - element.sourceSpan); + parsedElement = new EmbeddedTemplateAst([], [], templateVars, templateDirectives, + [parsedElement], ngContentIndex, element.sourceSpan); } return parsedElement; } - private _parseInlineTemplateBinding( - attr: HtmlAttrAst, targetMatchableAttrs: string[][], - targetProps: BoundElementOrDirectiveProperty[], targetVars: VariableAst[]): boolean { + private _parseInlineTemplateBinding(attr: HtmlAttrAst, targetMatchableAttrs: string[][], + targetProps: BoundElementOrDirectiveProperty[], + targetVars: VariableAst[]): boolean { var templateBindingsSource = null; if (attr.name == TEMPLATE_ATTR) { templateBindingsSource = attr.value; @@ -328,8 +346,8 @@ class TemplateParseVisitor implements HtmlAstVisitor { targetVars.push(new VariableAst(binding.key, binding.name, attr.sourceSpan)); targetMatchableAttrs.push([binding.key, binding.name]); } else if (isPresent(binding.expression)) { - this._parsePropertyAst( - binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps); + this._parsePropertyAst(binding.key, binding.expression, attr.sourceSpan, + targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([binding.key, '']); this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps); @@ -340,10 +358,9 @@ class TemplateParseVisitor implements HtmlAstVisitor { return false; } - private _parseAttr( - attr: HtmlAttrAst, targetMatchableAttrs: string[][], - targetProps: BoundElementOrDirectiveProperty[], targetEvents: BoundEventAst[], - targetVars: VariableAst[]): boolean { + private _parseAttr(attr: HtmlAttrAst, targetMatchableAttrs: string[][], + targetProps: BoundElementOrDirectiveProperty[], targetEvents: BoundEventAst[], + targetVars: VariableAst[]): boolean { var attrName = this._normalizeAttributeName(attr.name); var attrValue = attr.value; var bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); @@ -351,8 +368,8 @@ class TemplateParseVisitor implements HtmlAstVisitor { if (isPresent(bindParts)) { hasBinding = true; if (isPresent(bindParts[1])) { // match: bind-prop - this._parseProperty( - bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetProps); } else if (isPresent( bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden" @@ -360,32 +377,32 @@ class TemplateParseVisitor implements HtmlAstVisitor { this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else if (isPresent(bindParts[3])) { // match: on-event - this._parseEvent( - bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + this._parseEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetEvents); } else if (isPresent(bindParts[4])) { // match: bindon-prop - this._parseProperty( - bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); - this._parseAssignmentEvent( - bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetProps); + this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetEvents); } else if (isPresent(bindParts[6])) { // match: [(expr)] - this._parseProperty( - bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); - this._parseAssignmentEvent( - bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + this._parseProperty(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetProps); + this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetEvents); } else if (isPresent(bindParts[7])) { // match: [expr] - this._parseProperty( - bindParts[7], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + this._parseProperty(bindParts[7], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetProps); } else if (isPresent(bindParts[8])) { // match: (event) - this._parseEvent( - bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + this._parseEvent(bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, + targetEvents); } } else { - hasBinding = this._parsePropertyInterpolation( - attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceSpan, + targetMatchableAttrs, targetProps); } if (!hasBinding) { this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps); @@ -397,25 +414,24 @@ class TemplateParseVisitor implements HtmlAstVisitor { return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName; } - private _parseVariable( - identifier: string, value: string, sourceSpan: ParseSourceSpan, targetVars: VariableAst[]) { + private _parseVariable(identifier: string, value: string, sourceSpan: ParseSourceSpan, + targetVars: VariableAst[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in variable names`, sourceSpan); } targetVars.push(new VariableAst(identifier, value, sourceSpan)); } - private _parseProperty( - name: string, expression: string, sourceSpan: ParseSourceSpan, - targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]) { - this._parsePropertyAst( - name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, - targetProps); + private _parseProperty(name: string, expression: string, sourceSpan: ParseSourceSpan, + targetMatchableAttrs: string[][], + targetProps: BoundElementOrDirectiveProperty[]) { + this._parsePropertyAst(name, this._parseBinding(expression, sourceSpan), sourceSpan, + targetMatchableAttrs, targetProps); } - private _parsePropertyInterpolation( - name: string, value: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], - targetProps: BoundElementOrDirectiveProperty[]): boolean { + private _parsePropertyInterpolation(name: string, value: string, sourceSpan: ParseSourceSpan, + targetMatchableAttrs: string[][], + targetProps: BoundElementOrDirectiveProperty[]): boolean { var expr = this._parseInterpolation(value, sourceSpan); if (isPresent(expr)) { this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps); @@ -424,23 +440,21 @@ class TemplateParseVisitor implements HtmlAstVisitor { return false; } - private _parsePropertyAst( - name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan, - targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]) { + private _parsePropertyAst(name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan, + targetMatchableAttrs: string[][], + targetProps: BoundElementOrDirectiveProperty[]) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); } - private _parseAssignmentEvent( - name: string, expression: string, sourceSpan: ParseSourceSpan, - targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { - this._parseEvent( - `${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents); + private _parseAssignmentEvent(name: string, expression: string, sourceSpan: ParseSourceSpan, + targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { + this._parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, + targetEvents); } - private _parseEvent( - name: string, expression: string, sourceSpan: ParseSourceSpan, - targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { + private _parseEvent(name: string, expression: string, sourceSpan: ParseSourceSpan, + targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { // long format: 'target: eventName' var parts = splitAtColon(name, [null, name]); var target = parts[0]; @@ -452,47 +466,46 @@ class TemplateParseVisitor implements HtmlAstVisitor { // so don't add the event name to the matchableAttrs } - private _parseLiteralAttr( - name: string, value: string, sourceSpan: ParseSourceSpan, - targetProps: BoundElementOrDirectiveProperty[]) { + private _parseLiteralAttr(name: string, value: string, sourceSpan: ParseSourceSpan, + targetProps: BoundElementOrDirectiveProperty[]) { targetProps.push(new BoundElementOrDirectiveProperty( name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); } - private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector): - CompileDirectiveMetadata[] { + private _parseDirectives(selectorMatcher: SelectorMatcher, + elementCssSelector: CssSelector): CompileDirectiveMetadata[] { var directives = []; - selectorMatcher.match( - elementCssSelector, (selector, directive) => { directives.push(directive); }); + selectorMatcher.match(elementCssSelector, + (selector, directive) => { directives.push(directive); }); // Need to sort the directives so that we get consistent results throughout, // as selectorMatcher uses Maps inside. // Also need to make components the first directive in the array - ListWrapper.sort( - directives, (dir1: CompileDirectiveMetadata, dir2: CompileDirectiveMetadata) => { - var dir1Comp = dir1.isComponent; - var dir2Comp = dir2.isComponent; - if (dir1Comp && !dir2Comp) { - return -1; - } else if (!dir1Comp && dir2Comp) { - return 1; - } else { - return this.directivesIndex.get(dir1) - this.directivesIndex.get(dir2); - } - }); + ListWrapper.sort(directives, + (dir1: CompileDirectiveMetadata, dir2: CompileDirectiveMetadata) => { + var dir1Comp = dir1.isComponent; + var dir2Comp = dir2.isComponent; + if (dir1Comp && !dir2Comp) { + return -1; + } else if (!dir1Comp && dir2Comp) { + return 1; + } else { + return this.directivesIndex.get(dir1) - this.directivesIndex.get(dir2); + } + }); return directives; } - private _createDirectiveAsts( - elementName: string, directives: CompileDirectiveMetadata[], - props: BoundElementOrDirectiveProperty[], possibleExportAsVars: VariableAst[], - sourceSpan: ParseSourceSpan): DirectiveAst[] { + private _createDirectiveAsts(elementName: string, directives: CompileDirectiveMetadata[], + props: BoundElementOrDirectiveProperty[], + possibleExportAsVars: VariableAst[], + sourceSpan: ParseSourceSpan): DirectiveAst[] { var matchedVariables = new Set<string>(); var directiveAsts = directives.map((directive: CompileDirectiveMetadata) => { var hostProperties: BoundElementPropertyAst[] = []; var hostEvents: BoundEventAst[] = []; var directiveProperties: BoundDirectivePropertyAst[] = []; - this._createDirectiveHostPropertyAsts( - elementName, directive.hostProperties, sourceSpan, hostProperties); + this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceSpan, + hostProperties); this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents); this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties); var exportAsVars = []; @@ -503,21 +516,21 @@ class TemplateParseVisitor implements HtmlAstVisitor { matchedVariables.add(varAst.name); } }); - return new DirectiveAst( - directive, directiveProperties, hostProperties, hostEvents, exportAsVars, sourceSpan); + return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, + exportAsVars, sourceSpan); }); possibleExportAsVars.forEach((varAst) => { if (varAst.value.length > 0 && !SetWrapper.has(matchedVariables, varAst.name)) { - this._reportError( - `There is no directive with "exportAs" set to "${varAst.value}"`, varAst.sourceSpan); + this._reportError(`There is no directive with "exportAs" set to "${varAst.value}"`, + varAst.sourceSpan); } }); return directiveAsts; } - private _createDirectiveHostPropertyAsts( - elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan, - targetPropertyAsts: BoundElementPropertyAst[]) { + private _createDirectiveHostPropertyAsts(elementName: string, hostProps: {[key: string]: string}, + sourceSpan: ParseSourceSpan, + targetPropertyAsts: BoundElementPropertyAst[]) { if (isPresent(hostProps)) { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { var exprAst = this._parseBinding(expression, sourceSpan); @@ -527,9 +540,9 @@ class TemplateParseVisitor implements HtmlAstVisitor { } } - private _createDirectiveHostEventAsts( - hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan, - targetEventAsts: BoundEventAst[]) { + private _createDirectiveHostEventAsts(hostListeners: {[key: string]: string}, + sourceSpan: ParseSourceSpan, + targetEventAsts: BoundEventAst[]) { if (isPresent(hostListeners)) { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); @@ -537,9 +550,9 @@ class TemplateParseVisitor implements HtmlAstVisitor { } } - private _createDirectivePropertyAsts( - directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[], - targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { + private _createDirectivePropertyAsts(directiveProperties: {[key: string]: string}, + boundProps: BoundElementOrDirectiveProperty[], + targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { if (isPresent(directiveProperties)) { var boundPropsByName = new Map<string, BoundElementOrDirectiveProperty>(); boundProps.forEach(boundProp => { @@ -562,9 +575,8 @@ class TemplateParseVisitor implements HtmlAstVisitor { } } - private _createElementPropertyAsts( - elementName: string, props: BoundElementOrDirectiveProperty[], - directives: DirectiveAst[]): BoundElementPropertyAst[] { + private _createElementPropertyAsts(elementName: string, props: BoundElementOrDirectiveProperty[], + directives: DirectiveAst[]): BoundElementPropertyAst[] { var boundElementProps: BoundElementPropertyAst[] = []; var boundDirectivePropsIndex = new Map<string, BoundDirectivePropertyAst>(); directives.forEach((directive: DirectiveAst) => { @@ -574,16 +586,15 @@ class TemplateParseVisitor implements HtmlAstVisitor { }); props.forEach((prop: BoundElementOrDirectiveProperty) => { if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { - boundElementProps.push(this._createElementPropertyAst( - elementName, prop.name, prop.expression, prop.sourceSpan)); + boundElementProps.push(this._createElementPropertyAst(elementName, prop.name, + prop.expression, prop.sourceSpan)); } }); return boundElementProps; } - private _createElementPropertyAst( - elementName: string, name: string, ast: AST, - sourceSpan: ParseSourceSpan): BoundElementPropertyAst { + private _createElementPropertyAst(elementName: string, name: string, ast: AST, + sourceSpan: ParseSourceSpan): BoundElementPropertyAst { var unit = null; var bindingType; var boundPropertyName; @@ -641,13 +652,13 @@ class TemplateParseVisitor implements HtmlAstVisitor { } } - private _assertNoComponentsNorElementBindingsOnTemplate( - directives: DirectiveAst[], elementProps: BoundElementPropertyAst[], - sourceSpan: ParseSourceSpan) { + private _assertNoComponentsNorElementBindingsOnTemplate(directives: DirectiveAst[], + elementProps: BoundElementPropertyAst[], + sourceSpan: ParseSourceSpan) { var componentTypeNames: string[] = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 0) { - this._reportError( - `Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan); + this._reportError(`Components on an embedded template: ${componentTypeNames.join(',')}`, + sourceSpan); } elementProps.forEach(prop => { this._reportError( @@ -656,13 +667,12 @@ class TemplateParseVisitor implements HtmlAstVisitor { }); } - private _assertAllEventsPublishedByDirectives( - directives: DirectiveAst[], events: BoundEventAst[]) { + private _assertAllEventsPublishedByDirectives(directives: DirectiveAst[], + events: BoundEventAst[]) { var allDirectiveEvents = new Set<string>(); directives.forEach(directive => { - StringMapWrapper.forEach(directive.directive.outputs, (eventName: string, _) => { - allDirectiveEvents.add(eventName); - }); + StringMapWrapper.forEach(directive.directive.outputs, + (eventName: string, _) => { allDirectiveEvents.add(eventName); }); }); events.forEach(event => { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { @@ -690,9 +700,8 @@ class NonBindableVisitor implements HtmlAstVisitor { var selector = createElementCssSelector(ast.name, attrNameAndValues); var ngContentIndex = component.findNgContentIndex(selector); var children = htmlVisitAll(this, ast.children, EMPTY_COMPONENT); - return new ElementAst( - ast.name, htmlVisitAll(this, ast.attrs), [], [], [], [], children, ngContentIndex, - ast.sourceSpan); + return new ElementAst(ast.name, htmlVisitAll(this, ast.attrs), [], [], [], [], children, + ngContentIndex, ast.sourceSpan); } visitComment(ast: HtmlCommentAst, context: any): any { return null; } visitAttr(ast: HtmlAttrAst, context: any): AttrAst { @@ -705,9 +714,8 @@ class NonBindableVisitor implements HtmlAstVisitor { } class BoundElementOrDirectiveProperty { - constructor( - public name: string, public expression: AST, public isLiteral: boolean, - public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public expression: AST, public isLiteral: boolean, + public sourceSpan: ParseSourceSpan) {} } export function splitClasses(classAttrValue: string): string[] { @@ -732,8 +740,8 @@ class Component { } return new Component(matcher, wildcardNgContentIndex); } - constructor( - public ngContentIndexMatcher: SelectorMatcher, public wildcardNgContentIndex: number) {} + constructor(public ngContentIndexMatcher: SelectorMatcher, + public wildcardNgContentIndex: number) {} findNgContentIndex(selector: CssSelector): number { var ngContentIndices = []; diff --git a/modules/angular2/src/compiler/template_preparser.ts b/modules/angular2/src/compiler/template_preparser.ts index 0d1b2d1586..020bb47b98 100644 --- a/modules/angular2/src/compiler/template_preparser.ts +++ b/modules/angular2/src/compiler/template_preparser.ts @@ -59,9 +59,8 @@ export enum PreparsedElementType { } export class PreparsedElement { - constructor( - public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string, - public nonBindable: boolean, public projectAs: string) {} + constructor(public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string, + public nonBindable: boolean, public projectAs: string) {} } diff --git a/modules/angular2/src/compiler/url_resolver.ts b/modules/angular2/src/compiler/url_resolver.ts index eba4a801ee..9174f8ddfb 100644 --- a/modules/angular2/src/compiler/url_resolver.ts +++ b/modules/angular2/src/compiler/url_resolver.ts @@ -1,5 +1,11 @@ import {Injectable, Inject} from 'angular2/src/core/di'; -import {StringWrapper, isPresent, isBlank, RegExpWrapper, normalizeBlank} from 'angular2/src/facade/lang'; +import { + StringWrapper, + isPresent, + isBlank, + RegExpWrapper, + normalizeBlank +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {ListWrapper} from 'angular2/src/facade/collection'; import {PACKAGE_ROOT_URL} from 'angular2/src/core/application_tokens'; @@ -15,7 +21,7 @@ export function createWithoutPackagePrefix(): UrlResolver { /** * A default provider for {@link PACKAGE_ROOT_URL} that maps to '/'. */ -export var DEFAULT_PACKAGE_URL_PROVIDER = new Provider(PACKAGE_ROOT_URL, {useValue: '/'}); +export var DEFAULT_PACKAGE_URL_PROVIDER = new Provider(PACKAGE_ROOT_URL, {useValue: "/"}); /** * Used by the {@link Compiler} when resolving HTML and CSS template URLs. @@ -34,7 +40,7 @@ export class UrlResolver { constructor(@Inject(PACKAGE_ROOT_URL) packagePrefix: string = null) { if (isPresent(packagePrefix)) { - this._packagePrefix = StringWrapper.stripRight(packagePrefix, '/') + '/'; + this._packagePrefix = StringWrapper.stripRight(packagePrefix, "/") + "/"; } } @@ -55,8 +61,8 @@ export class UrlResolver { if (isPresent(baseUrl) && baseUrl.length > 0) { resolvedUrl = _resolveUrl(baseUrl, resolvedUrl); } - if (isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == 'package') { - resolvedUrl = resolvedUrl.replace('package:', this._packagePrefix); + if (isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == "package") { + resolvedUrl = resolvedUrl.replace("package:", this._packagePrefix); } return resolvedUrl; } @@ -67,7 +73,7 @@ export class UrlResolver { */ export function getUrlScheme(url: string): string { var match = _split(url); - return (match && match[_ComponentIndex.Scheme]) || ''; + return (match && match[_ComponentIndex.Scheme]) || ""; } // The code below is adapted from Traceur: @@ -90,9 +96,9 @@ export function getUrlScheme(url: string): string { * @param {?string=} opt_fragment The URI-encoded fragment identifier. * @return {string} The fully combined URI. */ -function _buildFromEncodedParts( - opt_scheme?: string, opt_userInfo?: string, opt_domain?: string, opt_port?: string, - opt_path?: string, opt_queryData?: string, opt_fragment?: string): string { +function _buildFromEncodedParts(opt_scheme?: string, opt_userInfo?: string, opt_domain?: string, + opt_port?: string, opt_path?: string, opt_queryData?: string, + opt_fragment?: string): string { var out = []; if (isPresent(opt_scheme)) { @@ -190,24 +196,24 @@ function _buildFromEncodedParts( * @type {!RegExp} * @internal */ -var _splitRe = RegExpWrapper.create( - '^' + - '(?:' + - '([^:/?#.]+)' + // scheme - ignore special characters - // used by other URL parts such as :, - // ?, /, #, and . - ':)?' + - '(?://' + - '(?:([^/?#]*)@)?' + // userInfo - '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters, - // digits, dashes, dots, percent - // escapes, and unicode characters. - '(?::([0-9]+))?' + // port - ')?' + - '([^?#]+)?' + // path - '(?:\\?([^#]*))?' + // query - '(?:#(.*))?' + // fragment - '$'); +var _splitRe = + RegExpWrapper.create('^' + + '(?:' + + '([^:/?#.]+)' + // scheme - ignore special characters + // used by other URL parts such as :, + // ?, /, #, and . + ':)?' + + '(?://' + + '(?:([^/?#]*)@)?' + // userInfo + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters, + // digits, dashes, dots, percent + // escapes, and unicode characters. + '(?::([0-9]+))?' + // port + ')?' + + '([^?#]+)?' + // path + '(?:\\?([^#]*))?' + // query + '(?:#(.*))?' + // fragment + '$'); /** * The index of each URI component in the return value of goog.uri.utils.split. @@ -238,7 +244,7 @@ enum _ComponentIndex { * on the browser's regular expression implementation. Never null, since * arbitrary strings may still look like path names. */ -function _split(uri: string): Array<string|any> { +function _split(uri: string): Array<string | any> { return RegExpWrapper.firstMatch(_splitRe, uri); } @@ -298,10 +304,9 @@ function _joinAndCanonicalizePath(parts: any[]): string { path = isBlank(path) ? '' : _removeDotSegments(path); parts[_ComponentIndex.Path] = path; - return _buildFromEncodedParts( - parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], - parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], - parts[_ComponentIndex.Fragment]); + return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], + parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, + parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]); } /** diff --git a/modules/angular2/src/compiler/util.ts b/modules/angular2/src/compiler/util.ts index 7538796baf..f3ebdfd1a7 100644 --- a/modules/angular2/src/compiler/util.ts +++ b/modules/angular2/src/compiler/util.ts @@ -1,4 +1,11 @@ -import {IS_DART, StringWrapper, isBlank, isPresent, isString, isArray} from 'angular2/src/facade/lang'; +import { + IS_DART, + StringWrapper, + isBlank, + isPresent, + isString, + isArray +} from 'angular2/src/facade/lang'; var CAMEL_CASE_REGEXP = /([A-Z])/g; var DASH_CASE_REGEXP = /-([a-z])/g; @@ -10,13 +17,13 @@ export var MODULE_SUFFIX = IS_DART ? '.dart' : '.js'; export var CONST_VAR = IS_DART ? 'const' : 'var'; export function camelCaseToDashCase(input: string): string { - return StringWrapper.replaceAllMapped( - input, CAMEL_CASE_REGEXP, (m) => { return '-' + m[1].toLowerCase(); }); + return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, + (m) => { return '-' + m[1].toLowerCase(); }); } export function dashCaseToCamelCase(input: string): string { - return StringWrapper.replaceAllMapped( - input, DASH_CASE_REGEXP, (m) => { return m[1].toUpperCase(); }); + return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, + (m) => { return m[1].toUpperCase(); }); } export function escapeSingleQuoteString(input: string): string { diff --git a/modules/angular2/src/compiler/view_compiler.ts b/modules/angular2/src/compiler/view_compiler.ts index f4a2f6ad95..9c7f328931 100644 --- a/modules/angular2/src/compiler/view_compiler.ts +++ b/modules/angular2/src/compiler/view_compiler.ts @@ -1,18 +1,65 @@ -import {isPresent, isBlank, Type, isString, StringWrapper, IS_DART, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + Type, + isString, + StringWrapper, + IS_DART, + CONST_EXPR +} from 'angular2/src/facade/lang'; import {SetWrapper, StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; -import {TemplateAst, TemplateAstVisitor, NgContentAst, EmbeddedTemplateAst, ElementAst, VariableAst, BoundEventAst, BoundElementPropertyAst, AttrAst, BoundTextAst, TextAst, DirectiveAst, BoundDirectivePropertyAst, templateVisitAll} from './template_ast'; +import { + TemplateAst, + TemplateAstVisitor, + NgContentAst, + EmbeddedTemplateAst, + ElementAst, + VariableAst, + BoundEventAst, + BoundElementPropertyAst, + AttrAst, + BoundTextAst, + TextAst, + DirectiveAst, + BoundDirectivePropertyAst, + templateVisitAll +} from './template_ast'; import {CompileTypeMetadata, CompileDirectiveMetadata} from './directive_metadata'; import {SourceExpressions, SourceExpression, moduleRef} from './source_module'; -import {AppProtoView, AppView, flattenNestedViewRenderNodes, checkSlotCount} from 'angular2/src/core/linker/view'; +import { + AppProtoView, + AppView, + flattenNestedViewRenderNodes, + checkSlotCount +} from 'angular2/src/core/linker/view'; import {ViewType} from 'angular2/src/core/linker/view_type'; import {AppViewManager_} from 'angular2/src/core/linker/view_manager'; import {AppProtoElement, AppElement} from 'angular2/src/core/linker/element'; import {Renderer, ParentRenderer} from 'angular2/src/core/render/api'; import {ViewEncapsulation} from 'angular2/src/core/metadata/view'; -import {escapeSingleQuoteString, codeGenConstConstructorCall, codeGenValueFn, codeGenFnHeader, MODULE_SUFFIX, Statement, escapeValue, codeGenArray, codeGenFlatArray, Expression, flattenArray, CONST_VAR} from './util'; +import { + escapeSingleQuoteString, + codeGenConstConstructorCall, + codeGenValueFn, + codeGenFnHeader, + MODULE_SUFFIX, + Statement, + escapeValue, + codeGenArray, + codeGenFlatArray, + Expression, + flattenArray, + CONST_VAR +} from './util'; import {ResolvedProvider, Injectable, Injector} from 'angular2/src/core/di'; -import {APP_VIEW_MODULE_REF, APP_EL_MODULE_REF, METADATA_MODULE_REF, CompileProtoView, CompileProtoElement} from './proto_view_compiler'; +import { + APP_VIEW_MODULE_REF, + APP_EL_MODULE_REF, + METADATA_MODULE_REF, + CompileProtoView, + CompileProtoElement +} from './proto_view_compiler'; export const VIEW_JIT_IMPORTS = CONST_EXPR({ 'AppView': AppView, @@ -26,77 +73,74 @@ export const VIEW_JIT_IMPORTS = CONST_EXPR({ export class ViewCompiler { constructor() {} - compileComponentRuntime( - component: CompileDirectiveMetadata, template: TemplateAst[], styles: Array<string|any[]>, - protoViews: CompileProtoView<AppProtoView, AppProtoElement>[], - changeDetectorFactories: Function[], componentViewFactory: Function): Function { - var viewFactory = new RuntimeViewFactory( - component, styles, protoViews, changeDetectorFactories, componentViewFactory); + compileComponentRuntime(component: CompileDirectiveMetadata, template: TemplateAst[], + styles: Array<string | any[]>, + protoViews: CompileProtoView<AppProtoView, AppProtoElement>[], + changeDetectorFactories: Function[], + componentViewFactory: Function): Function { + var viewFactory = new RuntimeViewFactory(component, styles, protoViews, changeDetectorFactories, + componentViewFactory); return viewFactory.createViewFactory(template, 0, []); } - compileComponentCodeGen( - component: CompileDirectiveMetadata, template: TemplateAst[], styles: SourceExpression, - protoViews: CompileProtoView<Expression, Expression>[], - changeDetectorFactoryExpressions: SourceExpressions, - componentViewFactory: Function): SourceExpression { + compileComponentCodeGen(component: CompileDirectiveMetadata, template: TemplateAst[], + styles: SourceExpression, + protoViews: CompileProtoView<Expression, Expression>[], + changeDetectorFactoryExpressions: SourceExpressions, + componentViewFactory: Function): SourceExpression { var viewFactory = new CodeGenViewFactory( component, styles, protoViews, changeDetectorFactoryExpressions, componentViewFactory); var targetStatements: Statement[] = []; var viewFactoryExpression = viewFactory.createViewFactory(template, 0, targetStatements); - return new SourceExpression( - targetStatements.map(stmt => stmt.statement), viewFactoryExpression.expression); + return new SourceExpression(targetStatements.map(stmt => stmt.statement), + viewFactoryExpression.expression); } } interface ViewFactory<EXPRESSION, STATEMENT> { - createText(renderer: EXPRESSION, parent: EXPRESSION, text: string, targetStatements: STATEMENT[]): - EXPRESSION; + createText(renderer: EXPRESSION, parent: EXPRESSION, text: string, + targetStatements: STATEMENT[]): EXPRESSION; - createElement( - renderer: EXPRESSION, parent: EXPRESSION, name: string, rootSelector: EXPRESSION, - targetStatements: STATEMENT[]): EXPRESSION; + createElement(renderer: EXPRESSION, parent: EXPRESSION, name: string, rootSelector: EXPRESSION, + targetStatements: STATEMENT[]): EXPRESSION; - createTemplateAnchor(renderer: EXPRESSION, parent: EXPRESSION, targetStatements: STATEMENT[]): - EXPRESSION; + createTemplateAnchor(renderer: EXPRESSION, parent: EXPRESSION, + targetStatements: STATEMENT[]): EXPRESSION; - createGlobalEventListener( - renderer: EXPRESSION, view: EXPRESSION, boundElementIndex: number, eventAst: BoundEventAst, - targetStatements: STATEMENT[]): EXPRESSION; + createGlobalEventListener(renderer: EXPRESSION, view: EXPRESSION, boundElementIndex: number, + eventAst: BoundEventAst, targetStatements: STATEMENT[]): EXPRESSION; - createElementEventListener( - renderer: EXPRESSION, view: EXPRESSION, boundElementIndex: number, renderNode: EXPRESSION, - eventAst: BoundEventAst, targetStatements: STATEMENT[]): EXPRESSION; + createElementEventListener(renderer: EXPRESSION, view: EXPRESSION, boundElementIndex: number, + renderNode: EXPRESSION, eventAst: BoundEventAst, + targetStatements: STATEMENT[]): EXPRESSION; - setElementAttribute( - renderer: EXPRESSION, renderNode: EXPRESSION, attrName: string, attrValue: string, - targetStatements: STATEMENT[]); + setElementAttribute(renderer: EXPRESSION, renderNode: EXPRESSION, attrName: string, + attrValue: string, targetStatements: STATEMENT[]); - createAppElement( - appProtoEl: EXPRESSION, view: EXPRESSION, renderNode: EXPRESSION, parentAppEl: EXPRESSION, - embeddedViewFactory: EXPRESSION, targetStatements: STATEMENT[]): EXPRESSION; + createAppElement(appProtoEl: EXPRESSION, view: EXPRESSION, renderNode: EXPRESSION, + parentAppEl: EXPRESSION, embeddedViewFactory: EXPRESSION, + targetStatements: STATEMENT[]): EXPRESSION; - createAndSetComponentView( - renderer: EXPRESSION, viewManager: EXPRESSION, view: EXPRESSION, appEl: EXPRESSION, - component: CompileDirectiveMetadata, contentNodesByNgContentIndex: EXPRESSION[][], - targetStatements: STATEMENT[]); + createAndSetComponentView(renderer: EXPRESSION, viewManager: EXPRESSION, view: EXPRESSION, + appEl: EXPRESSION, component: CompileDirectiveMetadata, + contentNodesByNgContentIndex: EXPRESSION[][], + targetStatements: STATEMENT[]); getProjectedNodes(projectableNodes: EXPRESSION, ngContentIndex: number): EXPRESSION; - appendProjectedNodes( - renderer: EXPRESSION, parent: EXPRESSION, nodes: EXPRESSION, targetStatements: STATEMENT[]); + appendProjectedNodes(renderer: EXPRESSION, parent: EXPRESSION, nodes: EXPRESSION, + targetStatements: STATEMENT[]); - createViewFactory( - asts: TemplateAst[], embeddedTemplateIndex: number, - targetStatements: STATEMENT[]): EXPRESSION; + createViewFactory(asts: TemplateAst[], embeddedTemplateIndex: number, + targetStatements: STATEMENT[]): EXPRESSION; } class CodeGenViewFactory implements ViewFactory<Expression, Statement> { private _nextVarId: number = 0; - constructor( - public component: CompileDirectiveMetadata, public styles: SourceExpression, - public protoViews: CompileProtoView<Expression, Expression>[], - public changeDetectorExpressions: SourceExpressions, public componentViewFactory: Function) {} + constructor(public component: CompileDirectiveMetadata, public styles: SourceExpression, + public protoViews: CompileProtoView<Expression, Expression>[], + public changeDetectorExpressions: SourceExpressions, + public componentViewFactory: Function) {} private _nextVar(prefix: string): string { return `${prefix}${this._nextVarId++}_${this.component.type.name}`; @@ -110,8 +154,8 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return `disposable${this._nextVarId++}_${this.component.type.name}`; } - createText(renderer: Expression, parent: Expression, text: string, targetStatements: Statement[]): - Expression { + createText(renderer: Expression, parent: Expression, text: string, + targetStatements: Statement[]): Expression { var varName = this._nextRenderVar(); var statement = `var ${varName} = ${renderer.expression}.createText(${isPresent(parent) ? parent.expression : null}, ${escapeSingleQuoteString(text)});`; @@ -119,9 +163,8 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(varName); } - createElement( - renderer: Expression, parentRenderNode: Expression, name: string, rootSelector: Expression, - targetStatements: Statement[]): Expression { + createElement(renderer: Expression, parentRenderNode: Expression, name: string, + rootSelector: Expression, targetStatements: Statement[]): Expression { var varName = this._nextRenderVar(); var valueExpr; if (isPresent(rootSelector)) { @@ -137,9 +180,8 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(varName); } - createTemplateAnchor( - renderer: Expression, parentRenderNode: Expression, - targetStatements: Statement[]): Expression { + createTemplateAnchor(renderer: Expression, parentRenderNode: Expression, + targetStatements: Statement[]): Expression { var varName = this._nextRenderVar(); var valueExpr = `${renderer.expression}.createTemplateAnchor(${isPresent(parentRenderNode) ? parentRenderNode.expression : null});`; @@ -147,9 +189,8 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(varName); } - createGlobalEventListener( - renderer: Expression, appView: Expression, boundElementIndex: number, eventAst: BoundEventAst, - targetStatements: Statement[]): Expression { + createGlobalEventListener(renderer: Expression, appView: Expression, boundElementIndex: number, + eventAst: BoundEventAst, targetStatements: Statement[]): Expression { var disposableVar = this._nextDisposableVar(); var eventHandlerExpr = codeGenEventHandler(appView, boundElementIndex, eventAst.fullName); targetStatements.push(new Statement( @@ -157,9 +198,9 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(disposableVar); } - createElementEventListener( - renderer: Expression, appView: Expression, boundElementIndex: number, renderNode: Expression, - eventAst: BoundEventAst, targetStatements: Statement[]): Expression { + createElementEventListener(renderer: Expression, appView: Expression, boundElementIndex: number, + renderNode: Expression, eventAst: BoundEventAst, + targetStatements: Statement[]): Expression { var disposableVar = this._nextDisposableVar(); var eventHandlerExpr = codeGenEventHandler(appView, boundElementIndex, eventAst.fullName); targetStatements.push(new Statement( @@ -167,16 +208,15 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(disposableVar); } - setElementAttribute( - renderer: Expression, renderNode: Expression, attrName: string, attrValue: string, - targetStatements: Statement[]) { + setElementAttribute(renderer: Expression, renderNode: Expression, attrName: string, + attrValue: string, targetStatements: Statement[]) { targetStatements.push(new Statement( `${renderer.expression}.setElementAttribute(${renderNode.expression}, ${escapeSingleQuoteString(attrName)}, ${escapeSingleQuoteString(attrValue)});`)); } - createAppElement( - appProtoEl: Expression, appView: Expression, renderNode: Expression, parentAppEl: Expression, - embeddedViewFactory: Expression, targetStatements: Statement[]): Expression { + createAppElement(appProtoEl: Expression, appView: Expression, renderNode: Expression, + parentAppEl: Expression, embeddedViewFactory: Expression, + targetStatements: Statement[]): Expression { var appVar = this._nextAppVar(); var varValue = `new ${APP_EL_MODULE_REF}AppElement(${appProtoEl.expression}, ${appView.expression}, @@ -185,10 +225,10 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(appVar); } - createAndSetComponentView( - renderer: Expression, viewManager: Expression, view: Expression, appEl: Expression, - component: CompileDirectiveMetadata, contentNodesByNgContentIndex: Expression[][], - targetStatements: Statement[]) { + createAndSetComponentView(renderer: Expression, viewManager: Expression, view: Expression, + appEl: Expression, component: CompileDirectiveMetadata, + contentNodesByNgContentIndex: Expression[][], + targetStatements: Statement[]) { var codeGenContentNodes; if (this.component.type.isHost) { codeGenContentNodes = `${view.expression}.projectableNodes`; @@ -204,15 +244,14 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { return new Expression(`${projectableNodes.expression}[${ngContentIndex}]`, true); } - appendProjectedNodes( - renderer: Expression, parent: Expression, nodes: Expression, targetStatements: Statement[]) { + appendProjectedNodes(renderer: Expression, parent: Expression, nodes: Expression, + targetStatements: Statement[]) { targetStatements.push(new Statement( `${renderer.expression}.projectNodes(${parent.expression}, ${APP_VIEW_MODULE_REF}flattenNestedViewRenderNodes(${nodes.expression}));`)); } - createViewFactory( - asts: TemplateAst[], embeddedTemplateIndex: number, - targetStatements: Statement[]): Expression { + createViewFactory(asts: TemplateAst[], embeddedTemplateIndex: number, + targetStatements: Statement[]): Expression { var compileProtoView = this.protoViews[embeddedTemplateIndex]; var isHostView = this.component.type.isHost; var isComponentView = embeddedTemplateIndex === 0 && !isHostView; @@ -229,8 +268,13 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> { var viewFactoryName = codeGenViewFactoryName(this.component, embeddedTemplateIndex); var changeDetectorFactory = this.changeDetectorExpressions.expressions[embeddedTemplateIndex]; var factoryArgs = [ - 'parentRenderer', 'viewManager', 'containerEl', 'projectableNodes', 'rootSelector', - 'dynamicallyCreatedProviders', 'rootInjector' + 'parentRenderer', + 'viewManager', + 'containerEl', + 'projectableNodes', + 'rootSelector', + 'dynamicallyCreatedProviders', + 'rootInjector' ]; var initRendererStmts = []; var rendererExpr = `parentRenderer`; @@ -272,18 +316,16 @@ ${codeGenFnHeader(factoryArgs, viewFactoryName)}{ } class RuntimeViewFactory implements ViewFactory<any, any> { - constructor( - public component: CompileDirectiveMetadata, public styles: Array<string|any[]>, - public protoViews: CompileProtoView<AppProtoView, AppProtoElement>[], - public changeDetectorFactories: Function[], public componentViewFactory: Function) {} + constructor(public component: CompileDirectiveMetadata, public styles: Array<string | any[]>, + public protoViews: CompileProtoView<AppProtoView, AppProtoElement>[], + public changeDetectorFactories: Function[], public componentViewFactory: Function) {} createText(renderer: Renderer, parent: any, text: string, targetStatements: any[]): any { return renderer.createText(parent, text); } - createElement( - renderer: Renderer, parent: any, name: string, rootSelector: string, - targetStatements: any[]): any { + createElement(renderer: Renderer, parent: any, name: string, rootSelector: string, + targetStatements: any[]): any { var el; if (isPresent(rootSelector)) { el = renderer.selectRootElement(rootSelector); @@ -297,38 +339,36 @@ class RuntimeViewFactory implements ViewFactory<any, any> { return renderer.createTemplateAnchor(parent); } - createGlobalEventListener( - renderer: Renderer, appView: AppView, boundElementIndex: number, eventAst: BoundEventAst, - targetStatements: any[]): any { + createGlobalEventListener(renderer: Renderer, appView: AppView, boundElementIndex: number, + eventAst: BoundEventAst, targetStatements: any[]): any { return renderer.listenGlobal( eventAst.target, eventAst.name, (event) => appView.triggerEventHandlers(eventAst.fullName, event, boundElementIndex)); } - createElementEventListener( - renderer: Renderer, appView: AppView, boundElementIndex: number, renderNode: any, - eventAst: BoundEventAst, targetStatements: any[]): any { + createElementEventListener(renderer: Renderer, appView: AppView, boundElementIndex: number, + renderNode: any, eventAst: BoundEventAst, + targetStatements: any[]): any { return renderer.listen( renderNode, eventAst.name, (event) => appView.triggerEventHandlers(eventAst.fullName, event, boundElementIndex)); } - setElementAttribute( - renderer: Renderer, renderNode: any, attrName: string, attrValue: string, - targetStatements: any[]) { + setElementAttribute(renderer: Renderer, renderNode: any, attrName: string, attrValue: string, + targetStatements: any[]) { renderer.setElementAttribute(renderNode, attrName, attrValue); } - createAppElement( - appProtoEl: AppProtoElement, appView: AppView, renderNode: any, parentAppEl: AppElement, - embeddedViewFactory: Function, targetStatements: any[]): any { + createAppElement(appProtoEl: AppProtoElement, appView: AppView, renderNode: any, + parentAppEl: AppElement, embeddedViewFactory: Function, + targetStatements: any[]): any { return new AppElement(appProtoEl, appView, parentAppEl, renderNode, embeddedViewFactory); } - createAndSetComponentView( - renderer: Renderer, viewManager: AppViewManager_, appView: AppView, appEl: AppElement, - component: CompileDirectiveMetadata, contentNodesByNgContentIndex: Array<Array<any|any[]>>, - targetStatements: any[]) { + createAndSetComponentView(renderer: Renderer, viewManager: AppViewManager_, appView: AppView, + appEl: AppElement, component: CompileDirectiveMetadata, + contentNodesByNgContentIndex: Array<Array<any | any[]>>, + targetStatements: any[]) { var flattenedContentNodes; if (this.component.type.isHost) { flattenedContentNodes = appView.projectableNodes; @@ -349,8 +389,8 @@ class RuntimeViewFactory implements ViewFactory<any, any> { renderer.projectNodes(parent, flattenNestedViewRenderNodes(nodes)); } - createViewFactory(asts: TemplateAst[], embeddedTemplateIndex: number, targetStatements: any[]): - Function { + createViewFactory(asts: TemplateAst[], embeddedTemplateIndex: number, + targetStatements: any[]): Function { var compileProtoView = this.protoViews[embeddedTemplateIndex]; var isComponentView = compileProtoView.protoView.type === ViewType.COMPONENT; var renderComponentType = null; @@ -358,9 +398,8 @@ class RuntimeViewFactory implements ViewFactory<any, any> { projectableNodes: any[][], rootSelector: string = null, dynamicallyCreatedProviders: ResolvedProvider[] = null, rootInjector: Injector = null) => { - checkSlotCount( - this.component.type.name, this.component.template.ngContentSelectors.length, - projectableNodes); + checkSlotCount(this.component.type.name, this.component.template.ngContentSelectors.length, + projectableNodes); var renderer; if (embeddedTemplateIndex === 0) { if (isBlank(renderComponentType)) { @@ -372,17 +411,16 @@ class RuntimeViewFactory implements ViewFactory<any, any> { renderer = <Renderer>parentRenderer; } var changeDetector = this.changeDetectorFactories[embeddedTemplateIndex](); - var view = new AppView( - compileProtoView.protoView, renderer, viewManager, projectableNodes, containerEl, - dynamicallyCreatedProviders, rootInjector, changeDetector); + var view = + new AppView(compileProtoView.protoView, renderer, viewManager, projectableNodes, + containerEl, dynamicallyCreatedProviders, rootInjector, changeDetector); var visitor = new ViewBuilderVisitor<any, any>( renderer, viewManager, projectableNodes, rootSelector, view, compileProtoView, [], this); var parentRenderNode = isComponentView ? renderer.createViewRoot(containerEl.nativeElement) : null; templateVisitAll(visitor, asts, new ParentElement(parentRenderNode, null, null)); - view.init( - flattenArray(visitor.rootNodesOrAppElements, []), visitor.renderNodes, - visitor.appDisposables, visitor.appElements); + view.init(flattenArray(visitor.rootNodesOrAppElements, []), visitor.renderNodes, + visitor.appDisposables, visitor.appElements); return view; }; } @@ -391,9 +429,8 @@ class RuntimeViewFactory implements ViewFactory<any, any> { class ParentElement<EXPRESSION> { public contentNodesByNgContentIndex: Array<EXPRESSION>[]; - constructor( - public renderNode: EXPRESSION, public appEl: EXPRESSION, - public component: CompileDirectiveMetadata) { + constructor(public renderNode: EXPRESSION, public appEl: EXPRESSION, + public component: CompileDirectiveMetadata) { if (isPresent(component)) { this.contentNodesByNgContentIndex = ListWrapper.createFixedSize(component.template.ngContentSelectors.length); @@ -421,15 +458,14 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { elementCount: number = 0; - constructor( - public renderer: EXPRESSION, public viewManager: EXPRESSION, - public projectableNodes: EXPRESSION, public rootSelector: EXPRESSION, public view: EXPRESSION, - public protoView: CompileProtoView<EXPRESSION, EXPRESSION>, - public targetStatements: STATEMENT[], public factory: ViewFactory<EXPRESSION, STATEMENT>) {} + constructor(public renderer: EXPRESSION, public viewManager: EXPRESSION, + public projectableNodes: EXPRESSION, public rootSelector: EXPRESSION, + public view: EXPRESSION, public protoView: CompileProtoView<EXPRESSION, EXPRESSION>, + public targetStatements: STATEMENT[], + public factory: ViewFactory<EXPRESSION, STATEMENT>) {} - private _addRenderNode( - renderNode: EXPRESSION, appEl: EXPRESSION, ngContentIndex: number, - parent: ParentElement<EXPRESSION>) { + private _addRenderNode(renderNode: EXPRESSION, appEl: EXPRESSION, ngContentIndex: number, + parent: ParentElement<EXPRESSION>) { this.renderNodes.push(renderNode); if (isPresent(parent.component)) { if (isPresent(ngContentIndex)) { @@ -440,12 +476,12 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { } } - private _getParentRenderNode(ngContentIndex: number, parent: ParentElement<EXPRESSION>): - EXPRESSION { + private _getParentRenderNode(ngContentIndex: number, + parent: ParentElement<EXPRESSION>): EXPRESSION { return isPresent(parent.component) && - parent.component.template.encapsulation !== ViewEncapsulation.Native ? - null : - parent.renderNode; + parent.component.template.encapsulation !== ViewEncapsulation.Native ? + null : + parent.renderNode; } visitBoundText(ast: BoundTextAst, parent: ParentElement<EXPRESSION>): any { @@ -469,8 +505,8 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { } } else { if (isPresent(parent.renderNode)) { - this.factory.appendProjectedNodes( - this.renderer, parent.renderNode, nodesExpression, this.renderStmts); + this.factory.appendProjectedNodes(this.renderer, parent.renderNode, nodesExpression, + this.renderStmts); } else { this.rootNodesOrAppElements.push(nodesExpression); } @@ -493,22 +529,22 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { disposable = this.factory.createGlobalEventListener( this.renderer, this.view, protoEl.boundElementIndex, eventAst, this.renderStmts); } else { - disposable = this.factory.createElementEventListener( - this.renderer, this.view, protoEl.boundElementIndex, renderNode, eventAst, - this.renderStmts); + disposable = this.factory.createElementEventListener(this.renderer, this.view, + protoEl.boundElementIndex, renderNode, + eventAst, this.renderStmts); } this.appDisposables.push(disposable); }); for (var i = 0; i < protoEl.attrNameAndValues.length; i++) { var attrName = protoEl.attrNameAndValues[i][0]; var attrValue = protoEl.attrNameAndValues[i][1]; - this.factory.setElementAttribute( - this.renderer, renderNode, attrName, attrValue, this.renderStmts); + this.factory.setElementAttribute(this.renderer, renderNode, attrName, attrValue, + this.renderStmts); } var appEl = null; if (isPresent(protoEl.appProtoEl)) { - appEl = this.factory.createAppElement( - protoEl.appProtoEl, this.view, renderNode, parent.appEl, null, this.appStmts); + appEl = this.factory.createAppElement(protoEl.appProtoEl, this.view, renderNode, parent.appEl, + null, this.appStmts); this.appElements.push(appEl); } this._addRenderNode(renderNode, appEl, ast.ngContentIndex, parent); @@ -517,9 +553,9 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { renderNode, isPresent(appEl) ? appEl : parent.appEl, component); templateVisitAll(this, ast.children, newParent); if (isPresent(appEl) && isPresent(component)) { - this.factory.createAndSetComponentView( - this.renderer, this.viewManager, this.view, appEl, component, - newParent.contentNodesByNgContentIndex, this.appStmts); + this.factory.createAndSetComponentView(this.renderer, this.viewManager, this.view, appEl, + component, newParent.contentNodesByNgContentIndex, + this.appStmts); } return null; } @@ -533,9 +569,8 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { var embeddedViewFactory = this.factory.createViewFactory( ast.children, protoEl.embeddedTemplateIndex, this.targetStatements); - var appEl = this.factory.createAppElement( - protoEl.appProtoEl, this.view, renderNode, parent.appEl, embeddedViewFactory, - this.appStmts); + var appEl = this.factory.createAppElement(protoEl.appProtoEl, this.view, renderNode, + parent.appEl, embeddedViewFactory, this.appStmts); this._addRenderNode(renderNode, appEl, ast.ngContentIndex, parent); this.appElements.push(appEl); return null; @@ -550,15 +585,15 @@ class ViewBuilderVisitor<EXPRESSION, STATEMENT> implements TemplateAstVisitor { } -function codeGenEventHandler( - view: Expression, boundElementIndex: number, eventName: string): string { +function codeGenEventHandler(view: Expression, boundElementIndex: number, + eventName: string): string { return codeGenValueFn( ['event'], `${view.expression}.triggerEventHandlers(${escapeValue(eventName)}, event, ${boundElementIndex})`); } -function codeGenViewFactoryName( - component: CompileDirectiveMetadata, embeddedTemplateIndex: number): string { +function codeGenViewFactoryName(component: CompileDirectiveMetadata, + embeddedTemplateIndex: number): string { return `viewFactory_${component.type.name}${embeddedTemplateIndex}`; } diff --git a/modules/angular2/src/core/application_common_providers.ts b/modules/angular2/src/core/application_common_providers.ts index c3d5e3e6b9..778e5799f4 100644 --- a/modules/angular2/src/core/application_common_providers.ts +++ b/modules/angular2/src/core/application_common_providers.ts @@ -1,26 +1,40 @@ import {Type, CONST_EXPR} from 'angular2/src/facade/lang'; import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di'; -import {APP_COMPONENT_REF_PROMISE, APP_COMPONENT, APP_ID_RANDOM_PROVIDER} from './application_tokens'; -import {IterableDiffers, defaultIterableDiffers, KeyValueDiffers, defaultKeyValueDiffers} from './change_detection/change_detection'; +import { + APP_COMPONENT_REF_PROMISE, + APP_COMPONENT, + APP_ID_RANDOM_PROVIDER +} from './application_tokens'; +import { + IterableDiffers, + defaultIterableDiffers, + KeyValueDiffers, + defaultKeyValueDiffers +} from './change_detection/change_detection'; import {ResolvedMetadataCache} from 'angular2/src/core/linker/resolved_metadata_cache'; import {AppViewManager} from './linker/view_manager'; -import {AppViewManager_} from './linker/view_manager'; +import {AppViewManager_} from "./linker/view_manager"; import {ViewResolver} from './linker/view_resolver'; import {DirectiveResolver} from './linker/directive_resolver'; import {PipeResolver} from './linker/pipe_resolver'; import {Compiler} from './linker/compiler'; -import {Compiler_} from './linker/compiler'; +import {Compiler_} from "./linker/compiler"; import {DynamicComponentLoader} from './linker/dynamic_component_loader'; -import {DynamicComponentLoader_} from './linker/dynamic_component_loader'; +import {DynamicComponentLoader_} from "./linker/dynamic_component_loader"; /** * A default set of providers which should be included in any Angular * application, regardless of the platform it runs onto. */ -export const APPLICATION_COMMON_PROVIDERS: Array<Type|Provider|any[]> = CONST_EXPR([ - new Provider(Compiler, {useClass: Compiler_}), APP_ID_RANDOM_PROVIDER, ResolvedMetadataCache, - new Provider(AppViewManager, {useClass: AppViewManager_}), ViewResolver, +export const APPLICATION_COMMON_PROVIDERS: Array<Type | Provider | any[]> = CONST_EXPR([ + new Provider(Compiler, {useClass: Compiler_}), + APP_ID_RANDOM_PROVIDER, + ResolvedMetadataCache, + new Provider(AppViewManager, {useClass: AppViewManager_}), + ViewResolver, new Provider(IterableDiffers, {useValue: defaultIterableDiffers}), - new Provider(KeyValueDiffers, {useValue: defaultKeyValueDiffers}), DirectiveResolver, - PipeResolver, new Provider(DynamicComponentLoader, {useClass: DynamicComponentLoader_}) + new Provider(KeyValueDiffers, {useValue: defaultKeyValueDiffers}), + DirectiveResolver, + PipeResolver, + new Provider(DynamicComponentLoader, {useClass: DynamicComponentLoader_}) ]); \ No newline at end of file diff --git a/modules/angular2/src/core/application_ref.ts b/modules/angular2/src/core/application_ref.ts index c0a3548aac..c670f7d24f 100644 --- a/modules/angular2/src/core/application_ref.ts +++ b/modules/angular2/src/core/application_ref.ts @@ -1,12 +1,33 @@ import {NgZone, NgZoneError} from 'angular2/src/core/zone/ng_zone'; -import {Type, isBlank, isPresent, assertionsEnabled, print, IS_DART} from 'angular2/src/facade/lang'; +import { + Type, + isBlank, + isPresent, + assertionsEnabled, + print, + IS_DART +} from 'angular2/src/facade/lang'; import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di'; -import {APP_COMPONENT_REF_PROMISE, APP_COMPONENT, APP_ID_RANDOM_PROVIDER, PLATFORM_INITIALIZER, APP_INITIALIZER} from './application_tokens'; +import { + APP_COMPONENT_REF_PROMISE, + APP_COMPONENT, + APP_ID_RANDOM_PROVIDER, + PLATFORM_INITIALIZER, + APP_INITIALIZER +} from './application_tokens'; import {PromiseWrapper, PromiseCompleter, ObservableWrapper} from 'angular2/src/facade/async'; import {ListWrapper} from 'angular2/src/facade/collection'; import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability'; -import {ComponentRef, DynamicComponentLoader} from 'angular2/src/core/linker/dynamic_component_loader'; -import {BaseException, WrappedException, ExceptionHandler, unimplemented} from 'angular2/src/facade/exceptions'; +import { + ComponentRef, + DynamicComponentLoader +} from 'angular2/src/core/linker/dynamic_component_loader'; +import { + BaseException, + WrappedException, + ExceptionHandler, + unimplemented +} from 'angular2/src/facade/exceptions'; import {Console} from 'angular2/src/core/console'; import {wtfLeave, wtfCreateScope, WtfScopeFn} from './profile/profile'; import {ChangeDetectorRef} from 'angular2/src/core/change_detection/change_detector_ref'; @@ -16,33 +37,35 @@ import {ElementRef_} from 'angular2/src/core/linker/element_ref'; /** * Construct providers specific to an individual root component. */ -function _componentProviders(appComponentType: Type): Array<Type|Provider|any[]> { +function _componentProviders(appComponentType: Type): Array<Type | Provider | any[]> { return [ provide(APP_COMPONENT, {useValue: appComponentType}), - provide(APP_COMPONENT_REF_PROMISE, { - useFactory: (dynamicComponentLoader: DynamicComponentLoader, appRef: ApplicationRef_, - injector: Injector) => { - // Save the ComponentRef for disposal later. - var ref: ComponentRef; - // TODO(rado): investigate whether to support providers on root component. - return dynamicComponentLoader - .loadAsRoot(appComponentType, null, injector, () => { appRef._unloadComponent(ref); }) - .then((componentRef) => { - ref = componentRef; - var testability = injector.getOptional(Testability); - if (isPresent(testability)) { - injector.get(TestabilityRegistry) - .registerApplication(componentRef.location.nativeElement, testability); - } - return componentRef; - }); - }, - deps: [DynamicComponentLoader, ApplicationRef, Injector] - }), - provide(appComponentType, { - useFactory: (p: Promise<any>) => p.then(ref => ref.instance), - deps: [APP_COMPONENT_REF_PROMISE] - }), + provide(APP_COMPONENT_REF_PROMISE, + { + useFactory: (dynamicComponentLoader: DynamicComponentLoader, appRef: ApplicationRef_, + injector: Injector) => { + // Save the ComponentRef for disposal later. + var ref: ComponentRef; + // TODO(rado): investigate whether to support providers on root component. + return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector, + () => { appRef._unloadComponent(ref); }) + .then((componentRef) => { + ref = componentRef; + var testability = injector.getOptional(Testability); + if (isPresent(testability)) { + injector.get(TestabilityRegistry) + .registerApplication(componentRef.location.nativeElement, testability); + } + return componentRef; + }); + }, + deps: [DynamicComponentLoader, ApplicationRef, Injector] + }), + provide(appComponentType, + { + useFactory: (p: Promise<any>) => p.then(ref => ref.instance), + deps: [APP_COMPONENT_REF_PROMISE] + }), ]; } @@ -70,13 +93,13 @@ var _platformProviders: any[]; * is passed into each call. If the platform function is called with a different set of * provides, Angular will throw an exception. */ -export function platform(providers?: Array<Type|Provider|any[]>): PlatformRef { +export function platform(providers?: Array<Type | Provider | any[]>): PlatformRef { lockMode(); if (isPresent(_platform)) { if (ListWrapper.equals(_platformProviders, providers)) { return _platform; } else { - throw new BaseException('platform cannot be initialized with different sets of providers.'); + throw new BaseException("platform cannot be initialized with different sets of providers."); } } else { return _createPlatform(providers); @@ -93,7 +116,7 @@ export function disposePlatform(): void { } } -function _createPlatform(providers?: Array<Type|Provider|any[]>): PlatformRef { +function _createPlatform(providers?: Array<Type | Provider | any[]>): PlatformRef { _platformProviders = providers; let injector = Injector.resolveAndCreate(providers); _platform = new PlatformRef_(injector, () => { @@ -152,7 +175,7 @@ export abstract class PlatformRef { * * See the {@link bootstrap} documentation for more details. */ - abstract application(providers: Array<Type|Provider|any[]>): ApplicationRef; + abstract application(providers: Array<Type | Provider | any[]>): ApplicationRef; /** * Instantiate a new Angular application on the page, using providers which @@ -166,9 +189,8 @@ export abstract class PlatformRef { * new application. Once this promise resolves, the application will be * constructed in the same manner as a normal `application()`. */ - abstract asyncApplication( - bindingFn: (zone: NgZone) => Promise<Array<Type|Provider|any[]>>, - providers?: Array<Type|Provider|any[]>): Promise<ApplicationRef>; + abstract asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Provider | any[]>>, + providers?: Array<Type | Provider | any[]>): Promise<ApplicationRef>; /** * Destroy the Angular platform and all Angular applications on the page. @@ -188,25 +210,24 @@ export class PlatformRef_ extends PlatformRef { get injector(): Injector { return this._injector; } - application(providers: Array<Type|Provider|any[]>): ApplicationRef { + application(providers: Array<Type | Provider | any[]>): ApplicationRef { var app = this._initApp(createNgZone(), providers); if (PromiseWrapper.isPromise(app)) { throw new BaseException( - 'Cannot use asyncronous app initializers with application. Use asyncApplication instead.'); + "Cannot use asyncronous app initializers with application. Use asyncApplication instead."); } return <ApplicationRef>app; } - asyncApplication( - bindingFn: (zone: NgZone) => Promise<Array<Type|Provider|any[]>>, - additionalProviders?: Array<Type|Provider|any[]>): Promise<ApplicationRef> { + asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Provider | any[]>>, + additionalProviders?: Array<Type | Provider | any[]>): Promise<ApplicationRef> { var zone = createNgZone(); var completer = PromiseWrapper.completer<ApplicationRef>(); if (bindingFn === null) { completer.resolve(this._initApp(zone, additionalProviders)); } else { zone.run(() => { - PromiseWrapper.then(bindingFn(zone), (providers: Array<Type|Provider|any[]>) => { + PromiseWrapper.then(bindingFn(zone), (providers: Array<Type | Provider | any[]>) => { if (isPresent(additionalProviders)) { providers = ListWrapper.concat(providers, additionalProviders); } @@ -218,8 +239,9 @@ export class PlatformRef_ extends PlatformRef { return completer.promise; } - private _initApp(zone: NgZone, providers: Array<Type|Provider|any[]>): - Promise<ApplicationRef>|ApplicationRef { + private _initApp(zone: NgZone, + providers: Array<Type | Provider | any[]>): Promise<ApplicationRef>| + ApplicationRef { var injector: Injector; var app: ApplicationRef; zone.run(() => { @@ -316,8 +338,8 @@ export abstract class ApplicationRef { * ### Example * {@example core/ts/platform/platform.ts region='longform'} */ - abstract bootstrap(componentType: Type, providers?: Array<Type|Provider|any[]>): - Promise<ComponentRef>; + abstract bootstrap(componentType: Type, + providers?: Array<Type | Provider | any[]>): Promise<ComponentRef>; /** * Retrieve the application {@link Injector}. @@ -374,8 +396,8 @@ export class ApplicationRef_ extends ApplicationRef { constructor(private _platform: PlatformRef_, private _zone: NgZone, private _injector: Injector) { super(); if (isPresent(this._zone)) { - ObservableWrapper.subscribe( - this._zone.onMicrotaskEmpty, (_) => { this._zone.run(() => { this.tick(); }); }); + ObservableWrapper.subscribe(this._zone.onMicrotaskEmpty, + (_) => { this._zone.run(() => { this.tick(); }); }); } this._enforceNoNewChanges = assertionsEnabled(); } @@ -394,7 +416,8 @@ export class ApplicationRef_ extends ApplicationRef { ListWrapper.remove(this._changeDetectorRefs, changeDetector); } - bootstrap(componentType: Type, providers?: Array<Type|Provider|any[]>): Promise<ComponentRef> { + bootstrap(componentType: Type, + providers?: Array<Type | Provider | any[]>): Promise<ComponentRef> { var completer = PromiseWrapper.completer(); this._zone.run(() => { var componentProviders = _componentProviders(componentType); @@ -426,7 +449,7 @@ export class ApplicationRef_ extends ApplicationRef { let c = this._injector.get(Console); if (assertionsEnabled()) { c.log( - 'Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.'); + "Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode."); } return ref; }); @@ -458,7 +481,7 @@ export class ApplicationRef_ extends ApplicationRef { tick(): void { if (this._runningTick) { - throw new BaseException('ApplicationRef.tick is called recursively'); + throw new BaseException("ApplicationRef.tick is called recursively"); } var s = ApplicationRef_._tickScope(); diff --git a/modules/angular2/src/core/application_tokens.ts b/modules/angular2/src/core/application_tokens.ts index 0040f878a5..24cca2b943 100644 --- a/modules/angular2/src/core/application_tokens.ts +++ b/modules/angular2/src/core/application_tokens.ts @@ -53,15 +53,15 @@ function _randomChar(): string { * A function that will be executed when a platform is initialized. */ export const PLATFORM_INITIALIZER: OpaqueToken = - CONST_EXPR(new OpaqueToken('Platform Initializer')); + CONST_EXPR(new OpaqueToken("Platform Initializer")); /** * A function that will be executed when an application is initialized. */ -export const APP_INITIALIZER: OpaqueToken = CONST_EXPR(new OpaqueToken('Application Initializer')); +export const APP_INITIALIZER: OpaqueToken = CONST_EXPR(new OpaqueToken("Application Initializer")); /** * A token which indicates the root directory of the application */ export const PACKAGE_ROOT_URL: OpaqueToken = - CONST_EXPR(new OpaqueToken('Application Packages Root URL')); + CONST_EXPR(new OpaqueToken("Application Packages Root URL")); diff --git a/modules/angular2/src/core/change_detection.ts b/modules/angular2/src/core/change_detection.ts index f02332367b..737bb34786 100644 --- a/modules/angular2/src/core/change_detection.ts +++ b/modules/angular2/src/core/change_detection.ts @@ -4,4 +4,24 @@ * Change detection enables data binding in Angular. */ -export {ChangeDetectionStrategy, ExpressionChangedAfterItHasBeenCheckedException, ChangeDetectionError, ChangeDetectorRef, WrappedValue, SimpleChange, PipeTransform, IterableDiffers, IterableDiffer, IterableDifferFactory, KeyValueDiffers, KeyValueDiffer, KeyValueDifferFactory, CollectionChangeRecord, KeyValueChangeRecord, TrackByFn} from './change_detection/change_detection'; +export { + ChangeDetectionStrategy, + + ExpressionChangedAfterItHasBeenCheckedException, + ChangeDetectionError, + + ChangeDetectorRef, + + WrappedValue, + SimpleChange, + PipeTransform, + IterableDiffers, + IterableDiffer, + IterableDifferFactory, + KeyValueDiffers, + KeyValueDiffer, + KeyValueDifferFactory, + CollectionChangeRecord, + KeyValueChangeRecord, + TrackByFn +} from './change_detection/change_detection'; diff --git a/modules/angular2/src/core/change_detection/abstract_change_detector.ts b/modules/angular2/src/core/change_detection/abstract_change_detector.ts index ca19041c2d..cb798affe7 100644 --- a/modules/angular2/src/core/change_detection/abstract_change_detector.ts +++ b/modules/angular2/src/core/change_detection/abstract_change_detector.ts @@ -5,7 +5,13 @@ import {ChangeDetectorRef, ChangeDetectorRef_} from './change_detector_ref'; import {DirectiveIndex} from './directive_record'; import {ChangeDetector, ChangeDispatcher} from './interfaces'; import {Pipes} from './pipes'; -import {ChangeDetectionError, ExpressionChangedAfterItHasBeenCheckedException, DehydratedException, EventEvaluationErrorContext, EventEvaluationError} from './exceptions'; +import { + ChangeDetectionError, + ExpressionChangedAfterItHasBeenCheckedException, + DehydratedException, + EventEvaluationErrorContext, + EventEvaluationError +} from './exceptions'; import {BindingTarget} from './binding_record'; import {Locals} from './parser/locals'; import {ChangeDetectionStrategy, ChangeDetectorState} from './constants'; @@ -15,9 +21,8 @@ import {ObservableWrapper} from 'angular2/src/facade/async'; var _scope_check: WtfScopeFn = wtfCreateScope(`ChangeDetector#check(ascii id, bool throwOnChange)`); class _Context { - constructor( - public element: any, public componentElement: any, public context: any, public locals: any, - public injector: any, public expression: any) {} + constructor(public element: any, public componentElement: any, public context: any, + public locals: any, public injector: any, public expression: any) {} } export class AbstractChangeDetector<T> implements ChangeDetector { @@ -39,10 +44,9 @@ export class AbstractChangeDetector<T> implements ChangeDetector { dispatcher: ChangeDispatcher; - constructor( - public id: string, public numberOfPropertyProtoRecords: number, - public bindingTargets: BindingTarget[], public directiveIndices: DirectiveIndex[], - public strategy: ChangeDetectionStrategy) { + constructor(public id: string, public numberOfPropertyProtoRecords: number, + public bindingTargets: BindingTarget[], public directiveIndices: DirectiveIndex[], + public strategy: ChangeDetectionStrategy) { this.ref = new ChangeDetectorRef_(this); } @@ -75,9 +79,9 @@ export class AbstractChangeDetector<T> implements ChangeDetector { } catch (e) { var c = this.dispatcher.getDebugContext(null, elIndex, null); var context = isPresent(c) ? - new EventEvaluationErrorContext( - c.element, c.componentElement, c.context, c.locals, c.injector) : - null; + new EventEvaluationErrorContext(c.element, c.componentElement, c.context, + c.locals, c.injector) : + null; throw new EventEvaluationError(eventName, e, e.stack, context); } } @@ -267,9 +271,8 @@ export class AbstractChangeDetector<T> implements ChangeDetector { var error; try { var c = this.dispatcher.getDebugContext(null, this._currentBinding().elementIndex, null); - var context = isPresent(c) ? new _Context( - c.element, c.componentElement, c.context, c.locals, - c.injector, this._currentBinding().debug) : + var context = isPresent(c) ? new _Context(c.element, c.componentElement, c.context, c.locals, + c.injector, this._currentBinding().debug) : null; error = new ChangeDetectionError(this._currentBinding().debug, exception, stack, context); } catch (e) { @@ -281,8 +284,8 @@ export class AbstractChangeDetector<T> implements ChangeDetector { } throwOnChangeError(oldValue: any, newValue: any): void { - throw new ExpressionChangedAfterItHasBeenCheckedException( - this._currentBinding().debug, oldValue, newValue, null); + throw new ExpressionChangedAfterItHasBeenCheckedException(this._currentBinding().debug, + oldValue, newValue, null); } throwDehydratedError(detail: string): void { throw new DehydratedException(detail); } diff --git a/modules/angular2/src/core/change_detection/binding_record.ts b/modules/angular2/src/core/change_detection/binding_record.ts index 09a253b3e0..b6e3ce9b29 100644 --- a/modules/angular2/src/core/change_detection/binding_record.ts +++ b/modules/angular2/src/core/change_detection/binding_record.ts @@ -3,22 +3,21 @@ import {SetterFn} from 'angular2/src/core/reflection/types'; import {AST} from './parser/ast'; import {DirectiveIndex, DirectiveRecord} from './directive_record'; -const DIRECTIVE_LIFECYCLE = 'directiveLifecycle'; -const BINDING = 'native'; +const DIRECTIVE_LIFECYCLE = "directiveLifecycle"; +const BINDING = "native"; -const DIRECTIVE = 'directive'; -const ELEMENT_PROPERTY = 'elementProperty'; -const ELEMENT_ATTRIBUTE = 'elementAttribute'; -const ELEMENT_CLASS = 'elementClass'; -const ELEMENT_STYLE = 'elementStyle'; -const TEXT_NODE = 'textNode'; -const EVENT = 'event'; -const HOST_EVENT = 'hostEvent'; +const DIRECTIVE = "directive"; +const ELEMENT_PROPERTY = "elementProperty"; +const ELEMENT_ATTRIBUTE = "elementAttribute"; +const ELEMENT_CLASS = "elementClass"; +const ELEMENT_STYLE = "elementStyle"; +const TEXT_NODE = "textNode"; +const EVENT = "event"; +const HOST_EVENT = "hostEvent"; export class BindingTarget { - constructor( - public mode: string, public elementIndex: number, public name: string, public unit: string, - public debug: string) {} + constructor(public mode: string, public elementIndex: number, public name: string, + public unit: string, public debug: string) {} isDirective(): boolean { return this.mode === DIRECTIVE; } @@ -34,10 +33,9 @@ export class BindingTarget { } export class BindingRecord { - constructor( - public mode: string, public target: BindingTarget, public implicitReceiver: any, - public ast: AST, public setter: SetterFn, public lifecycleEvent: string, - public directiveRecord: DirectiveRecord) {} + constructor(public mode: string, public target: BindingTarget, public implicitReceiver: any, + public ast: AST, public setter: SetterFn, public lifecycleEvent: string, + public directiveRecord: DirectiveRecord) {} isDirectiveLifecycle(): boolean { return this.mode === DIRECTIVE_LIFECYCLE; } @@ -50,23 +48,22 @@ export class BindingRecord { } static createDirectiveDoCheck(directiveRecord: DirectiveRecord): BindingRecord { - return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, 'DoCheck', directiveRecord); + return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "DoCheck", directiveRecord); } static createDirectiveOnInit(directiveRecord: DirectiveRecord): BindingRecord { - return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, 'OnInit', directiveRecord); + return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "OnInit", directiveRecord); } static createDirectiveOnChanges(directiveRecord: DirectiveRecord): BindingRecord { - return new BindingRecord( - DIRECTIVE_LIFECYCLE, null, 0, null, null, 'OnChanges', directiveRecord); + return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "OnChanges", + directiveRecord); } - static createForDirective( - ast: AST, propertyName: string, setter: SetterFn, - directiveRecord: DirectiveRecord): BindingRecord { + static createForDirective(ast: AST, propertyName: string, setter: SetterFn, + directiveRecord: DirectiveRecord): BindingRecord { var elementIndex = directiveRecord.directiveIndex.elementIndex; var t = new BindingTarget(DIRECTIVE, elementIndex, propertyName, null, ast.toString()); return new BindingRecord(DIRECTIVE, t, 0, ast, setter, null, directiveRecord); @@ -74,14 +71,14 @@ export class BindingRecord { - static createForElementProperty(ast: AST, elementIndex: number, propertyName: string): - BindingRecord { + static createForElementProperty(ast: AST, elementIndex: number, + propertyName: string): BindingRecord { var t = new BindingTarget(ELEMENT_PROPERTY, elementIndex, propertyName, null, ast.toString()); return new BindingRecord(BINDING, t, 0, ast, null, null, null); } - static createForElementAttribute(ast: AST, elementIndex: number, attributeName: string): - BindingRecord { + static createForElementAttribute(ast: AST, elementIndex: number, + attributeName: string): BindingRecord { var t = new BindingTarget(ELEMENT_ATTRIBUTE, elementIndex, attributeName, null, ast.toString()); return new BindingRecord(BINDING, t, 0, ast, null, null, null); } @@ -91,39 +88,39 @@ export class BindingRecord { return new BindingRecord(BINDING, t, 0, ast, null, null, null); } - static createForElementStyle(ast: AST, elementIndex: number, styleName: string, unit: string): - BindingRecord { + static createForElementStyle(ast: AST, elementIndex: number, styleName: string, + unit: string): BindingRecord { var t = new BindingTarget(ELEMENT_STYLE, elementIndex, styleName, unit, ast.toString()); return new BindingRecord(BINDING, t, 0, ast, null, null, null); } - static createForHostProperty(directiveIndex: DirectiveIndex, ast: AST, propertyName: string): - BindingRecord { - var t = new BindingTarget( - ELEMENT_PROPERTY, directiveIndex.elementIndex, propertyName, null, ast.toString()); + static createForHostProperty(directiveIndex: DirectiveIndex, ast: AST, + propertyName: string): BindingRecord { + var t = new BindingTarget(ELEMENT_PROPERTY, directiveIndex.elementIndex, propertyName, null, + ast.toString()); return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); } - static createForHostAttribute(directiveIndex: DirectiveIndex, ast: AST, attributeName: string): - BindingRecord { - var t = new BindingTarget( - ELEMENT_ATTRIBUTE, directiveIndex.elementIndex, attributeName, null, ast.toString()); + static createForHostAttribute(directiveIndex: DirectiveIndex, ast: AST, + attributeName: string): BindingRecord { + var t = new BindingTarget(ELEMENT_ATTRIBUTE, directiveIndex.elementIndex, attributeName, null, + ast.toString()); return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); } - static createForHostClass(directiveIndex: DirectiveIndex, ast: AST, className: string): - BindingRecord { - var t = new BindingTarget( - ELEMENT_CLASS, directiveIndex.elementIndex, className, null, ast.toString()); + static createForHostClass(directiveIndex: DirectiveIndex, ast: AST, + className: string): BindingRecord { + var t = new BindingTarget(ELEMENT_CLASS, directiveIndex.elementIndex, className, null, + ast.toString()); return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); } - static createForHostStyle( - directiveIndex: DirectiveIndex, ast: AST, styleName: string, unit: string): BindingRecord { - var t = new BindingTarget( - ELEMENT_STYLE, directiveIndex.elementIndex, styleName, unit, ast.toString()); + static createForHostStyle(directiveIndex: DirectiveIndex, ast: AST, styleName: string, + unit: string): BindingRecord { + var t = new BindingTarget(ELEMENT_STYLE, directiveIndex.elementIndex, styleName, unit, + ast.toString()); return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); } @@ -141,8 +138,8 @@ export class BindingRecord { return new BindingRecord(EVENT, t, 0, ast, null, null, null); } - static createForHostEvent(ast: AST, eventName: string, directiveRecord: DirectiveRecord): - BindingRecord { + static createForHostEvent(ast: AST, eventName: string, + directiveRecord: DirectiveRecord): BindingRecord { var directiveIndex = directiveRecord.directiveIndex; var t = new BindingTarget(HOST_EVENT, directiveIndex.elementIndex, eventName, null, ast.toString()); diff --git a/modules/angular2/src/core/change_detection/change_detection.ts b/modules/angular2/src/core/change_detection/change_detection.ts index 132d349084..34a1f2c78c 100644 --- a/modules/angular2/src/core/change_detection/change_detection.ts +++ b/modules/angular2/src/core/change_detection/change_detection.ts @@ -1,19 +1,46 @@ import {IterableDiffers, IterableDifferFactory} from './differs/iterable_differs'; import {DefaultIterableDifferFactory} from './differs/default_iterable_differ'; import {KeyValueDiffers, KeyValueDifferFactory} from './differs/keyvalue_differs'; -import {DefaultKeyValueDifferFactory, KeyValueChangeRecord} from './differs/default_keyvalue_differ'; +import { + DefaultKeyValueDifferFactory, + KeyValueChangeRecord +} from './differs/default_keyvalue_differ'; import {CONST_EXPR} from 'angular2/src/facade/lang'; -export {DefaultKeyValueDifferFactory, KeyValueChangeRecord} from './differs/default_keyvalue_differ'; -export {DefaultIterableDifferFactory, CollectionChangeRecord} from './differs/default_iterable_differ'; -export {ASTWithSource, AST, AstTransformer, PropertyRead, LiteralArray, ImplicitReceiver} from './parser/ast'; +export { + DefaultKeyValueDifferFactory, + KeyValueChangeRecord +} from './differs/default_keyvalue_differ'; +export { + DefaultIterableDifferFactory, + CollectionChangeRecord +} from './differs/default_iterable_differ'; +export { + ASTWithSource, + AST, + AstTransformer, + PropertyRead, + LiteralArray, + ImplicitReceiver +} from './parser/ast'; export {Lexer} from './parser/lexer'; export {Parser} from './parser/parser'; export {Locals} from './parser/locals'; -export {DehydratedException, ExpressionChangedAfterItHasBeenCheckedException, ChangeDetectionError} from './exceptions'; -export {ProtoChangeDetector, ChangeDetector, ChangeDispatcher, ChangeDetectorDefinition, DebugContext, ChangeDetectorGenConfig} from './interfaces'; +export { + DehydratedException, + ExpressionChangedAfterItHasBeenCheckedException, + ChangeDetectionError +} from './exceptions'; +export { + ProtoChangeDetector, + ChangeDetector, + ChangeDispatcher, + ChangeDetectorDefinition, + DebugContext, + ChangeDetectorGenConfig +} from './interfaces'; export {ChangeDetectionStrategy, CHANGE_DETECTION_STRATEGY_VALUES} from './constants'; export {DynamicProtoChangeDetector} from './proto_change_detector'; export {JitProtoChangeDetector} from './jit_proto_change_detector'; @@ -21,7 +48,12 @@ export {BindingRecord, BindingTarget} from './binding_record'; export {DirectiveIndex, DirectiveRecord} from './directive_record'; export {DynamicChangeDetector} from './dynamic_change_detector'; export {ChangeDetectorRef} from './change_detector_ref'; -export {IterableDiffers, IterableDiffer, IterableDifferFactory, TrackByFn} from './differs/iterable_differs'; +export { + IterableDiffers, + IterableDiffer, + IterableDifferFactory, + TrackByFn +} from './differs/iterable_differs'; export {KeyValueDiffers, KeyValueDiffer, KeyValueDifferFactory} from './differs/keyvalue_differs'; export {PipeTransform} from './pipe_transform'; export {WrappedValue, SimpleChange} from './change_detection_util'; diff --git a/modules/angular2/src/core/change_detection/change_detection_jit_generator.ts b/modules/angular2/src/core/change_detection/change_detection_jit_generator.ts index faef72e06d..238ee94c01 100644 --- a/modules/angular2/src/core/change_detection/change_detection_jit_generator.ts +++ b/modules/angular2/src/core/change_detection/change_detection_jit_generator.ts @@ -25,8 +25,8 @@ import {createPropertyRecords, createEventRecords} from './proto_change_detector * `angular2.transform.template_compiler.change_detector_codegen` library. If you make updates * here, please make equivalent changes there. */ -const IS_CHANGED_LOCAL = 'isChanged'; -const CHANGES_LOCAL = 'changes'; +const IS_CHANGED_LOCAL = "isChanged"; +const CHANGES_LOCAL = "changes"; export class ChangeDetectorJITGenerator { private _logic: CodegenLogicUtil; @@ -41,9 +41,9 @@ export class ChangeDetectorJITGenerator { private genConfig: ChangeDetectorGenConfig; typeName: string; - constructor( - definition: ChangeDetectorDefinition, private changeDetectionUtilVarName: string, - private abstractChangeDetectorVarName: string, private changeDetectorStateVarName: string) { + constructor(definition: ChangeDetectorDefinition, private changeDetectionUtilVarName: string, + private abstractChangeDetectorVarName: string, + private changeDetectorStateVarName: string) { var propertyBindingRecords = createPropertyRecords(definition); var eventBindingRecords = createEventRecords(definition); var propertyBindingTargets = definition.bindingRecords.map(b => b.target); @@ -55,10 +55,10 @@ export class ChangeDetectorJITGenerator { this.propertyBindingTargets = propertyBindingTargets; this.eventBindings = eventBindingRecords; this.directiveRecords = definition.directiveRecords; - this._names = new CodegenNameUtil( - this.records, this.eventBindings, this.directiveRecords, this.changeDetectionUtilVarName); - this._logic = new CodegenLogicUtil( - this._names, this.changeDetectionUtilVarName, this.changeDetectorStateVarName); + this._names = new CodegenNameUtil(this.records, this.eventBindings, this.directiveRecords, + this.changeDetectionUtilVarName); + this._logic = new CodegenLogicUtil(this._names, this.changeDetectionUtilVarName, + this.changeDetectorStateVarName); this.typeName = sanitizeName(`ChangeDetector_${this.id}`); } @@ -69,10 +69,9 @@ export class ChangeDetectorJITGenerator { return new ${this.typeName}(); } `; - return new Function( - this.abstractChangeDetectorVarName, this.changeDetectionUtilVarName, - this.changeDetectorStateVarName, - factorySource)(AbstractChangeDetector, ChangeDetectionUtil, ChangeDetectorState); + return new Function(this.abstractChangeDetectorVarName, this.changeDetectionUtilVarName, + this.changeDetectorStateVarName, factorySource)( + AbstractChangeDetector, ChangeDetectionUtil, ChangeDetectorState); } generateSource(): string { @@ -113,8 +112,8 @@ export class ChangeDetectorJITGenerator { /** @internal */ _genPropertyBindingTargets(): string { - var targets = this._logic.genPropertyBindingTargets( - this.propertyBindingTargets, this.genConfig.genDebugInfo); + var targets = this._logic.genPropertyBindingTargets(this.propertyBindingTargets, + this.genConfig.genDebugInfo); return `${this.typeName}.gen_propertyBindingTargets = ${targets};`; } @@ -127,7 +126,7 @@ export class ChangeDetectorJITGenerator { /** @internal */ _maybeGenHandleEventInternal(): string { if (this.eventBindings.length > 0) { - var handlers = this.eventBindings.map(eb => this._genEventBinding(eb)).join('\n'); + var handlers = this.eventBindings.map(eb => this._genEventBinding(eb)).join("\n"); return ` ${this.typeName}.prototype.handleEventInternal = function(eventName, elIndex, locals) { var ${this._names.getPreventDefaultAccesor()} = false; @@ -184,7 +183,7 @@ export class ChangeDetectorJITGenerator { _genMarkPathToRootAsCheckOnce(r: ProtoRecord): string { var br = r.bindingRecord; if (br.isDefaultChangeDetection()) { - return ''; + return ""; } else { return `${this._names.getDetectorName(br.directiveRecord.directiveIndex)}.markPathToRootAsCheckOnce();`; } @@ -226,7 +225,7 @@ export class ChangeDetectorJITGenerator { _maybeGenAfterContentLifecycleCallbacks(): string { var notifications = this._logic.genContentLifecycleCallbacks(this.directiveRecords); if (notifications.length > 0) { - var directiveNotifications = notifications.join('\n'); + var directiveNotifications = notifications.join("\n"); return ` ${this.typeName}.prototype.afterContentLifecycleCallbacksInternal = function() { ${directiveNotifications} @@ -241,7 +240,7 @@ export class ChangeDetectorJITGenerator { _maybeGenAfterViewLifecycleCallbacks(): string { var notifications = this._logic.genViewLifecycleCallbacks(this.directiveRecords); if (notifications.length > 0) { - var directiveNotifications = notifications.join('\n'); + var directiveNotifications = notifications.join("\n"); return ` ${this.typeName}.prototype.afterViewLifecycleCallbacksInternal = function() { ${directiveNotifications} @@ -283,7 +282,7 @@ export class ChangeDetectorJITGenerator { codes.push(code); } - return codes.join('\n'); + return codes.join("\n"); } /** @internal */ @@ -316,11 +315,11 @@ export class ChangeDetectorJITGenerator { /** @internal */ _genDirectiveLifecycle(r: ProtoRecord): string { - if (r.name === 'DoCheck') { + if (r.name === "DoCheck") { return this._genOnCheck(r); - } else if (r.name === 'OnInit') { + } else if (r.name === "OnInit") { return this._genOnInit(r); - } else if (r.name === 'OnChanges') { + } else if (r.name === "OnChanges") { return this._genOnChange(r); } else { throw new BaseException(`Unknown lifecycle event '${r.name}'`); @@ -330,7 +329,7 @@ export class ChangeDetectorJITGenerator { /** @internal */ _genPipeCheck(r: ProtoRecord): string { var context = this._names.getLocalName(r.contextIndex); - var argString = r.args.map((arg) => this._names.getLocalName(arg)).join(', '); + var argString = r.args.map((arg) => this._names.getLocalName(arg)).join(", "); var oldValue = this._names.getFieldName(r.selfIndex); var newValue = this._names.getLocalName(r.selfIndex); @@ -390,7 +389,7 @@ export class ChangeDetectorJITGenerator { var genCode = r.shouldBeChecked() ? `${read}${check}` : read; if (r.isPureFunction()) { - var condition = r.args.map((a) => this._names.getChangeName(a)).join(' || '); + var condition = r.args.map((a) => this._names.getChangeName(a)).join(" || "); if (r.isUsedByOtherRecord()) { return `if (${condition}) { ${genCode} } else { ${newValue} = ${oldValue}; }`; } else { @@ -408,10 +407,10 @@ export class ChangeDetectorJITGenerator { /** @internal */ _genUpdateDirectiveOrElement(r: ProtoRecord): string { - if (!r.lastInBinding) return ''; + if (!r.lastInBinding) return ""; var newValue = this._names.getLocalName(r.selfIndex); - var notifyDebug = this.genConfig.logBindingUpdate ? `this.logBindingUpdate(${newValue});` : ''; + var notifyDebug = this.genConfig.logBindingUpdate ? `this.logBindingUpdate(${newValue});` : ""; var br = r.bindingRecord; if (br.target.isDirective()) { @@ -447,7 +446,7 @@ export class ChangeDetectorJITGenerator { _genAddToChanges(r: ProtoRecord): string { var newValue = this._names.getLocalName(r.selfIndex); var oldValue = this._names.getFieldName(r.selfIndex); - if (!r.bindingRecord.callOnChanges()) return ''; + if (!r.bindingRecord.callOnChanges()) return ""; return `${CHANGES_LOCAL} = this.addChange(${CHANGES_LOCAL}, ${oldValue}, ${newValue});`; } @@ -456,13 +455,13 @@ export class ChangeDetectorJITGenerator { var prev = ChangeDetectionUtil.protoByIndex(this.records, r.selfIndex - 1); var firstInBinding = isBlank(prev) || prev.bindingRecord !== r.bindingRecord; return firstInBinding && !r.bindingRecord.isDirectiveLifecycle() ? - `${this._names.getPropertyBindingIndex()} = ${r.propertyBindingIndex};` : - ''; + `${this._names.getPropertyBindingIndex()} = ${r.propertyBindingIndex};` : + ''; } /** @internal */ _maybeGenLastInDirective(r: ProtoRecord): string { - if (!r.lastInDirective) return ''; + if (!r.lastInDirective) return ""; return ` ${CHANGES_LOCAL} = null; ${this._genNotifyOnPushDetectors(r)} @@ -491,7 +490,7 @@ export class ChangeDetectorJITGenerator { /** @internal */ _genNotifyOnPushDetectors(r: ProtoRecord): string { var br = r.bindingRecord; - if (!r.lastInDirective || br.isDefaultChangeDetection()) return ''; + if (!r.lastInDirective || br.isDefaultChangeDetection()) return ""; var retVal = ` if(${IS_CHANGED_LOCAL}) { ${this._names.getDetectorName(br.directiveRecord.directiveIndex)}.markAsCheckOnce(); diff --git a/modules/angular2/src/core/change_detection/change_detection_util.ts b/modules/angular2/src/core/change_detection/change_detection_util.ts index 4d86be3443..88c92273b9 100644 --- a/modules/angular2/src/core/change_detection/change_detection_util.ts +++ b/modules/angular2/src/core/change_detection/change_detection_util.ts @@ -1,6 +1,20 @@ -import {CONST_EXPR, isPresent, isBlank, Type, StringWrapper, looseIdentical, isPrimitive} from 'angular2/src/facade/lang'; +import { + CONST_EXPR, + isPresent, + isBlank, + Type, + StringWrapper, + looseIdentical, + isPrimitive +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; -import {ListWrapper, MapWrapper, StringMapWrapper, isListLikeIterable, areIterablesEqual} from 'angular2/src/facade/collection'; +import { + ListWrapper, + MapWrapper, + StringMapWrapper, + isListLikeIterable, + areIterablesEqual +} from 'angular2/src/facade/collection'; import {ProtoRecord} from './proto_record'; import {ChangeDetectionStrategy, isDefaultChangeDetectionStrategy} from './constants'; import {implementsOnDestroy} from './pipe_lifecycle_reflector'; @@ -38,7 +52,10 @@ export class WrappedValue { } var _wrappedValues = [ - new WrappedValue(null), new WrappedValue(null), new WrappedValue(null), new WrappedValue(null), + new WrappedValue(null), + new WrappedValue(null), + new WrappedValue(null), + new WrappedValue(null), new WrappedValue(null) ]; @@ -156,8 +173,8 @@ export class ChangeDetectionUtil { static protoByIndex(protos: ProtoRecord[], selfIndex: number): ProtoRecord { return selfIndex < 1 ? - null : - protos[selfIndex - 1]; // self index is shifted by one because of context + null : + protos[selfIndex - 1]; // self index is shifted by one because of context } static callPipeOnDestroy(selectedPipe: SelectedPipe): void { @@ -166,9 +183,8 @@ export class ChangeDetectionUtil { } } - static bindingTarget( - mode: string, elementIndex: number, name: string, unit: string, - debug: string): BindingTarget { + static bindingTarget(mode: string, elementIndex: number, name: string, unit: string, + debug: string): BindingTarget { return new BindingTarget(mode, elementIndex, name, unit, debug); } @@ -182,8 +198,8 @@ export class ChangeDetectionUtil { if (isListLikeIterable(a) && isListLikeIterable(b)) { return areIterablesEqual(a, b, ChangeDetectionUtil.devModeEqual); - } else if ( - !isListLikeIterable(a) && !isPrimitive(a) && !isListLikeIterable(b) && !isPrimitive(b)) { + } else if (!isListLikeIterable(a) && !isPrimitive(a) && !isListLikeIterable(b) && + !isPrimitive(b)) { return true; } else { diff --git a/modules/angular2/src/core/change_detection/coalesce.ts b/modules/angular2/src/core/change_detection/coalesce.ts index 71ae799346..1a0832ecf3 100644 --- a/modules/angular2/src/core/change_detection/coalesce.ts +++ b/modules/angular2/src/core/change_detection/coalesce.ts @@ -90,9 +90,8 @@ function _optimizeSkips(srcRecords: ProtoRecord[]): ProtoRecord[] { /** * Add a new record or re-use one of the existing records. */ -function _mayBeAddRecord( - record: ProtoRecord, dstRecords: ProtoRecord[], excludedIdxs: number[], - excluded: boolean): ProtoRecord { +function _mayBeAddRecord(record: ProtoRecord, dstRecords: ProtoRecord[], excludedIdxs: number[], + excluded: boolean): ProtoRecord { let match = _findFirstMatch(record, dstRecords, excludedIdxs); if (isPresent(match)) { @@ -119,15 +118,15 @@ function _mayBeAddRecord( /** * Returns the first `ProtoRecord` that matches the record. */ -function _findFirstMatch( - record: ProtoRecord, dstRecords: ProtoRecord[], excludedIdxs: number[]): ProtoRecord { +function _findFirstMatch(record: ProtoRecord, dstRecords: ProtoRecord[], + excludedIdxs: number[]): ProtoRecord { return dstRecords.find( // TODO(vicb): optimize excludedIdxs.indexOf (sorted array) rr => excludedIdxs.indexOf(rr.selfIndex) == -1 && rr.mode !== RecordType.DirectiveLifecycle && - _haveSameDirIndex(rr, record) && rr.mode === record.mode && - looseIdentical(rr.funcOrValue, record.funcOrValue) && - rr.contextIndex === record.contextIndex && looseIdentical(rr.name, record.name) && - ListWrapper.equals(rr.args, record.args)); + _haveSameDirIndex(rr, record) && rr.mode === record.mode && + looseIdentical(rr.funcOrValue, record.funcOrValue) && + rr.contextIndex === record.contextIndex && looseIdentical(rr.name, record.name) && + ListWrapper.equals(rr.args, record.args)); } /** @@ -136,17 +135,17 @@ function _findFirstMatch( * - the context, * - self */ -function _cloneAndUpdateIndexes( - record: ProtoRecord, dstRecords: ProtoRecord[], indexMap: Map<number, number>): ProtoRecord { +function _cloneAndUpdateIndexes(record: ProtoRecord, dstRecords: ProtoRecord[], + indexMap: Map<number, number>): ProtoRecord { let args = record.args.map(src => _srcToDstSelfIndex(indexMap, src)); let contextIndex = _srcToDstSelfIndex(indexMap, record.contextIndex); let selfIndex = dstRecords.length + 1; - return new ProtoRecord( - record.mode, record.name, record.funcOrValue, args, record.fixedArgs, contextIndex, - record.directiveIndex, selfIndex, record.bindingRecord, record.lastInBinding, - record.lastInDirective, record.argumentToPureFunction, record.referencedBySelf, - record.propertyBindingIndex); + return new ProtoRecord(record.mode, record.name, record.funcOrValue, args, record.fixedArgs, + contextIndex, record.directiveIndex, selfIndex, record.bindingRecord, + record.lastInBinding, record.lastInDirective, + record.argumentToPureFunction, record.referencedBySelf, + record.propertyBindingIndex); } /** @@ -159,9 +158,9 @@ function _srcToDstSelfIndex(indexMap: Map<number, number>, srcIdx: number): numb } function _createSelfRecord(r: ProtoRecord, contextIndex: number, selfIndex: number): ProtoRecord { - return new ProtoRecord( - RecordType.Self, 'self', null, [], r.fixedArgs, contextIndex, r.directiveIndex, selfIndex, - r.bindingRecord, r.lastInBinding, r.lastInDirective, false, false, r.propertyBindingIndex); + return new ProtoRecord(RecordType.Self, "self", null, [], r.fixedArgs, contextIndex, + r.directiveIndex, selfIndex, r.bindingRecord, r.lastInBinding, + r.lastInDirective, false, false, r.propertyBindingIndex); } function _haveSameDirIndex(a: ProtoRecord, b: ProtoRecord): boolean { diff --git a/modules/angular2/src/core/change_detection/codegen_logic_util.ts b/modules/angular2/src/core/change_detection/codegen_logic_util.ts index 98b87cf248..ff3f147f13 100644 --- a/modules/angular2/src/core/change_detection/codegen_logic_util.ts +++ b/modules/angular2/src/core/change_detection/codegen_logic_util.ts @@ -10,17 +10,16 @@ import {BaseException} from 'angular2/src/facade/exceptions'; * Class responsible for providing change detection logic for change detector classes. */ export class CodegenLogicUtil { - constructor( - private _names: CodegenNameUtil, private _utilName: string, - private _changeDetectorStateName: string) {} + constructor(private _names: CodegenNameUtil, private _utilName: string, + private _changeDetectorStateName: string) {} /** * Generates a statement which updates the local variable representing `protoRec` with the current * value of the record. Used by property bindings. */ genPropertyBindingEvalValue(protoRec: ProtoRecord): string { - return this._genEvalValue( - protoRec, idx => this._names.getLocalName(idx), this._names.getLocalsAccessorName()); + return this._genEvalValue(protoRec, idx => this._names.getLocalName(idx), + this._names.getLocalsAccessorName()); } /** @@ -28,16 +27,16 @@ export class CodegenLogicUtil { * value of the record. Used by event bindings. */ genEventBindingEvalValue(eventRecord: any, protoRec: ProtoRecord): string { - return this._genEvalValue( - protoRec, idx => this._names.getEventLocalName(eventRecord, idx), 'locals'); + return this._genEvalValue(protoRec, idx => this._names.getEventLocalName(eventRecord, idx), + "locals"); } - private _genEvalValue(protoRec: ProtoRecord, getLocalName: Function, localsAccessor: string): - string { + private _genEvalValue(protoRec: ProtoRecord, getLocalName: Function, + localsAccessor: string): string { var context = (protoRec.contextIndex == -1) ? - this._names.getDirectiveName(protoRec.directiveIndex) : - getLocalName(protoRec.contextIndex); - var argString = protoRec.args.map(arg => getLocalName(arg)).join(', '); + this._names.getDirectiveName(protoRec.directiveIndex) : + getLocalName(protoRec.contextIndex); + var argString = protoRec.args.map(arg => getLocalName(arg)).join(", "); var rhs: string; switch (protoRec.mode) { @@ -109,12 +108,12 @@ export class CodegenLogicUtil { return `${getLocalName(protoRec.selfIndex)} = ${rhs};`; } - genPropertyBindingTargets(propertyBindingTargets: BindingTarget[], genDebugInfo: boolean): - string { + genPropertyBindingTargets(propertyBindingTargets: BindingTarget[], + genDebugInfo: boolean): string { var bs = propertyBindingTargets.map(b => { - if (isBlank(b)) return 'null'; + if (isBlank(b)) return "null"; - var debug = genDebugInfo ? codify(b.debug) : 'null'; + var debug = genDebugInfo ? codify(b.debug) : "null"; return `${this._utilName}.bindingTarget(${codify(b.mode)}, ${b.elementIndex}, ${codify(b.name)}, ${codify(b.unit)}, ${debug})`; }); return `[${bs.join(", ")}]`; @@ -166,7 +165,7 @@ export class CodegenLogicUtil { res.unshift(`${statementStart} = new Array(${outputCount});`); } } - return res.join('\n'); + return res.join("\n"); } genDirectivesOnDestroy(directiveRecords: DirectiveRecord[]): string { @@ -178,7 +177,7 @@ export class CodegenLogicUtil { res.push(`${dirVarName}.ngOnDestroy();`); } } - return res.join('\n'); + return res.join("\n"); } private _genEventHandler(boundElementIndex: number, eventName: string): string { @@ -200,7 +199,7 @@ export class CodegenLogicUtil { `${this._names.getDetectorName(r.directiveIndex)} = this.getDetectorFor(directives, ${i});`); } } - return res.join('\n'); + return res.join("\n"); } genContentLifecycleCallbacks(directiveRecords: DirectiveRecord[]): string[] { diff --git a/modules/angular2/src/core/change_detection/codegen_name_util.ts b/modules/angular2/src/core/change_detection/codegen_name_util.ts index 00907bc2bd..0c423edd32 100644 --- a/modules/angular2/src/core/change_detection/codegen_name_util.ts +++ b/modules/angular2/src/core/change_detection/codegen_name_util.ts @@ -8,16 +8,16 @@ import {EventBinding} from './event_binding'; // The names of these fields must be kept in sync with abstract_change_detector.ts or change // detection will fail. -const _STATE_ACCESSOR = 'state'; -const _CONTEXT_ACCESSOR = 'context'; -const _PROP_BINDING_INDEX = 'propertyBindingIndex'; -const _DIRECTIVES_ACCESSOR = 'directiveIndices'; -const _DISPATCHER_ACCESSOR = 'dispatcher'; -const _LOCALS_ACCESSOR = 'locals'; -const _MODE_ACCESSOR = 'mode'; -const _PIPES_ACCESSOR = 'pipes'; -const _PROTOS_ACCESSOR = 'protos'; -export const CONTEXT_ACCESSOR = 'context'; +const _STATE_ACCESSOR = "state"; +const _CONTEXT_ACCESSOR = "context"; +const _PROP_BINDING_INDEX = "propertyBindingIndex"; +const _DIRECTIVES_ACCESSOR = "directiveIndices"; +const _DISPATCHER_ACCESSOR = "dispatcher"; +const _LOCALS_ACCESSOR = "locals"; +const _MODE_ACCESSOR = "mode"; +const _PIPES_ACCESSOR = "pipes"; +const _PROTOS_ACCESSOR = "protos"; +export const CONTEXT_ACCESSOR = "context"; // `context` is always first. export const CONTEXT_INDEX = 0; @@ -47,9 +47,8 @@ export class CodegenNameUtil { /** @internal */ _sanitizedEventNames = new Map<EventBinding, string[]>(); - constructor( - private _records: ProtoRecord[], private _eventBindings: EventBinding[], - private _directiveRecords: any[], private _utilName: string) { + constructor(private _records: ProtoRecord[], private _eventBindings: EventBinding[], + private _directiveRecords: any[], private _utilName: string) { this._sanitizedNames = ListWrapper.createFixedSize(this._records.length + 1); this._sanitizedNames[CONTEXT_INDEX] = CONTEXT_ACCESSOR; for (var i = 0, iLen = this._records.length; i < iLen; ++i) { @@ -133,7 +132,7 @@ export class CodegenNameUtil { return res.length > 1 ? `var ${res.join(',')};` : ''; } - getPreventDefaultAccesor(): string { return 'preventDefault'; } + getPreventDefaultAccesor(): string { return "preventDefault"; } getFieldCount(): number { return this._sanitizedNames.length; } diff --git a/modules/angular2/src/core/change_detection/constants.ts b/modules/angular2/src/core/change_detection/constants.ts index dd0ae2163c..28b9e70a58 100644 --- a/modules/angular2/src/core/change_detection/constants.ts +++ b/modules/angular2/src/core/change_detection/constants.ts @@ -68,20 +68,25 @@ export enum ChangeDetectionStrategy { * List of possible {@link ChangeDetectionStrategy} values. */ export var CHANGE_DETECTION_STRATEGY_VALUES = [ - ChangeDetectionStrategy.CheckOnce, ChangeDetectionStrategy.Checked, - ChangeDetectionStrategy.CheckAlways, ChangeDetectionStrategy.Detached, - ChangeDetectionStrategy.OnPush, ChangeDetectionStrategy.Default + ChangeDetectionStrategy.CheckOnce, + ChangeDetectionStrategy.Checked, + ChangeDetectionStrategy.CheckAlways, + ChangeDetectionStrategy.Detached, + ChangeDetectionStrategy.OnPush, + ChangeDetectionStrategy.Default ]; /** * List of possible {@link ChangeDetectorState} values. */ export var CHANGE_DETECTOR_STATE_VALUES = [ - ChangeDetectorState.NeverChecked, ChangeDetectorState.CheckedBefore, ChangeDetectorState.Errored + ChangeDetectorState.NeverChecked, + ChangeDetectorState.CheckedBefore, + ChangeDetectorState.Errored ]; -export function isDefaultChangeDetectionStrategy(changeDetectionStrategy: ChangeDetectionStrategy): - boolean { +export function isDefaultChangeDetectionStrategy( + changeDetectionStrategy: ChangeDetectionStrategy): boolean { return isBlank(changeDetectionStrategy) || - changeDetectionStrategy === ChangeDetectionStrategy.Default; + changeDetectionStrategy === ChangeDetectionStrategy.Default; } diff --git a/modules/angular2/src/core/change_detection/differs/default_iterable_differ.ts b/modules/angular2/src/core/change_detection/differs/default_iterable_differ.ts index c0a36aad2b..12cb945502 100644 --- a/modules/angular2/src/core/change_detection/differs/default_iterable_differ.ts +++ b/modules/angular2/src/core/change_detection/differs/default_iterable_differ.ts @@ -2,7 +2,14 @@ import {CONST} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {isListLikeIterable, iterateListLike, ListWrapper} from 'angular2/src/facade/collection'; -import {isBlank, isPresent, stringify, getMapKey, looseIdentical, isArray} from 'angular2/src/facade/lang'; +import { + isBlank, + isPresent, + stringify, + getMapKey, + looseIdentical, + isArray +} from 'angular2/src/facade/lang'; import {ChangeDetectorRef} from '../change_detector_ref'; import {IterableDiffer, IterableDifferFactory, TrackByFn} from '../differs/iterable_differs'; @@ -163,7 +170,7 @@ export class DefaultIterableDiffer implements IterableDiffer { */ get isDirty(): boolean { return this._additionsHead !== null || this._movesHead !== null || - this._removalsHead !== null || this._identityChangesHead !== null; + this._removalsHead !== null || this._identityChangesHead !== null; } /** @@ -211,8 +218,8 @@ export class DefaultIterableDiffer implements IterableDiffer { * * @internal */ - _mismatch(record: CollectionChangeRecord, item: any, itemTrackBy: any, index: number): - CollectionChangeRecord { + _mismatch(record: CollectionChangeRecord, item: any, itemTrackBy: any, + index: number): CollectionChangeRecord { // The previous record after which we will append the current one. var previousRecord: CollectionChangeRecord; @@ -277,8 +284,8 @@ export class DefaultIterableDiffer implements IterableDiffer { * * @internal */ - _verifyReinsertion(record: CollectionChangeRecord, item: any, itemTrackBy: any, index: number): - CollectionChangeRecord { + _verifyReinsertion(record: CollectionChangeRecord, item: any, itemTrackBy: any, + index: number): CollectionChangeRecord { var reinsertRecord: CollectionChangeRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy); if (reinsertRecord !== null) { @@ -326,8 +333,8 @@ export class DefaultIterableDiffer implements IterableDiffer { } /** @internal */ - _reinsertAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: number): - CollectionChangeRecord { + _reinsertAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, + index: number): CollectionChangeRecord { if (this._unlinkedRecords !== null) { this._unlinkedRecords.remove(record); } @@ -351,8 +358,8 @@ export class DefaultIterableDiffer implements IterableDiffer { } /** @internal */ - _moveAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: number): - CollectionChangeRecord { + _moveAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, + index: number): CollectionChangeRecord { this._unlink(record); this._insertAfter(record, prevRecord, index); this._addToMoves(record, index); @@ -360,8 +367,8 @@ export class DefaultIterableDiffer implements IterableDiffer { } /** @internal */ - _addAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: number): - CollectionChangeRecord { + _addAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, + index: number): CollectionChangeRecord { this._insertAfter(record, prevRecord, index); if (this._additionsTail === null) { @@ -378,8 +385,8 @@ export class DefaultIterableDiffer implements IterableDiffer { } /** @internal */ - _insertAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: number): - CollectionChangeRecord { + _insertAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, + index: number): CollectionChangeRecord { // todo(vicb) // assert(record != prevRecord); // assert(record._next === null); @@ -520,12 +527,10 @@ export class DefaultIterableDiffer implements IterableDiffer { var identityChanges = []; this.forEachIdentityChange((record) => identityChanges.push(record)); - return 'collection: ' + list.join(', ') + '\n' + - 'previous: ' + previous.join(', ') + '\n' + - 'additions: ' + additions.join(', ') + '\n' + - 'moves: ' + moves.join(', ') + '\n' + - 'removals: ' + removals.join(', ') + '\n' + - 'identityChanges: ' + identityChanges.join(', ') + '\n'; + return "collection: " + list.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + + "additions: " + additions.join(', ') + "\n" + "moves: " + moves.join(', ') + "\n" + + "removals: " + removals.join(', ') + "\n" + "identityChanges: " + + identityChanges.join(', ') + "\n"; } } @@ -558,9 +563,10 @@ export class CollectionChangeRecord { constructor(public item: any, public trackById: any) {} toString(): string { - return this.previousIndex === this.currentIndex ? stringify(this.item) : - stringify(this.item) + '[' + - stringify(this.previousIndex) + '->' + stringify(this.currentIndex) + ']'; + return this.previousIndex === this.currentIndex ? + stringify(this.item) : + stringify(this.item) + '[' + stringify(this.previousIndex) + '->' + + stringify(this.currentIndex) + ']'; } } diff --git a/modules/angular2/src/core/change_detection/differs/default_keyvalue_differ.ts b/modules/angular2/src/core/change_detection/differs/default_keyvalue_differ.ts index 882443b0e8..1c602df46a 100644 --- a/modules/angular2/src/core/change_detection/differs/default_keyvalue_differ.ts +++ b/modules/angular2/src/core/change_detection/differs/default_keyvalue_differ.ts @@ -24,7 +24,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer { get isDirty(): boolean { return this._additionsHead !== null || this._changesHead !== null || - this._removalsHead !== null; + this._removalsHead !== null; } forEachItem(fn: Function) { @@ -206,7 +206,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer { /** @internal */ _isInRemovals(record: KeyValueChangeRecord) { return record === this._removalsHead || record._nextRemoved !== null || - record._prevRemoved !== null; + record._prevRemoved !== null; } /** @internal */ @@ -318,11 +318,9 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer { removals.push(stringify(record)); } - return 'map: ' + items.join(', ') + '\n' + - 'previous: ' + previous.join(', ') + '\n' + - 'additions: ' + additions.join(', ') + '\n' + - 'changes: ' + changes.join(', ') + '\n' + - 'removals: ' + removals.join(', ') + '\n'; + return "map: " + items.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + + "additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" + + "removals: " + removals.join(', ') + "\n"; } /** @internal */ @@ -357,8 +355,8 @@ export class KeyValueChangeRecord { toString(): string { return looseIdentical(this.previousValue, this.currentValue) ? - stringify(this.key) : - (stringify(this.key) + '[' + stringify(this.previousValue) + '->' + - stringify(this.currentValue) + ']'); + stringify(this.key) : + (stringify(this.key) + '[' + stringify(this.previousValue) + '->' + + stringify(this.currentValue) + ']'); } } diff --git a/modules/angular2/src/core/change_detection/directive_record.ts b/modules/angular2/src/core/change_detection/directive_record.ts index bc93816fc5..53c6f2e6cd 100644 --- a/modules/angular2/src/core/change_detection/directive_record.ts +++ b/modules/angular2/src/core/change_detection/directive_record.ts @@ -21,22 +21,21 @@ export class DirectiveRecord { // array of [emitter property name, eventName] outputs: string[][]; - constructor( - {directiveIndex, callAfterContentInit, callAfterContentChecked, callAfterViewInit, - callAfterViewChecked, callOnChanges, callDoCheck, callOnInit, callOnDestroy, changeDetection, - outputs}: { - directiveIndex?: DirectiveIndex, - callAfterContentInit?: boolean, - callAfterContentChecked?: boolean, - callAfterViewInit?: boolean, - callAfterViewChecked?: boolean, - callOnChanges?: boolean, - callDoCheck?: boolean, - callOnInit?: boolean, - callOnDestroy?: boolean, - changeDetection?: ChangeDetectionStrategy, - outputs?: string[][] - } = {}) { + constructor({directiveIndex, callAfterContentInit, callAfterContentChecked, callAfterViewInit, + callAfterViewChecked, callOnChanges, callDoCheck, callOnInit, callOnDestroy, + changeDetection, outputs}: { + directiveIndex?: DirectiveIndex, + callAfterContentInit?: boolean, + callAfterContentChecked?: boolean, + callAfterViewInit?: boolean, + callAfterViewChecked?: boolean, + callOnChanges?: boolean, + callDoCheck?: boolean, + callOnInit?: boolean, + callOnDestroy?: boolean, + changeDetection?: ChangeDetectionStrategy, + outputs?: string[][] + } = {}) { this.directiveIndex = directiveIndex; this.callAfterContentInit = normalizeBool(callAfterContentInit); this.callAfterContentChecked = normalizeBool(callAfterContentChecked); diff --git a/modules/angular2/src/core/change_detection/dynamic_change_detector.ts b/modules/angular2/src/core/change_detection/dynamic_change_detector.ts index dd474c544f..e9d58aba66 100644 --- a/modules/angular2/src/core/change_detection/dynamic_change_detector.ts +++ b/modules/angular2/src/core/change_detection/dynamic_change_detector.ts @@ -20,11 +20,11 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { localPipes: any[]; prevContexts: any[]; - constructor( - id: string, numberOfPropertyProtoRecords: number, propertyBindingTargets: BindingTarget[], - directiveIndices: DirectiveIndex[], strategy: ChangeDetectionStrategy, - private _records: ProtoRecord[], private _eventBindings: EventBinding[], - private _directiveRecords: DirectiveRecord[], private _genConfig: ChangeDetectorGenConfig) { + constructor(id: string, numberOfPropertyProtoRecords: number, + propertyBindingTargets: BindingTarget[], directiveIndices: DirectiveIndex[], + strategy: ChangeDetectionStrategy, private _records: ProtoRecord[], + private _eventBindings: EventBinding[], private _directiveRecords: DirectiveRecord[], + private _genConfig: ChangeDetectorGenConfig) { super(id, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy); var len = _records.length + 1; this.values = ListWrapper.createFixedSize(len); @@ -38,12 +38,13 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { handleEventInternal(eventName: string, elIndex: number, locals: Locals): boolean { var preventDefault = false; - this._matchingEventBindings(eventName, elIndex).forEach(rec => { - var res = this._processEventBinding(rec, locals); - if (res === false) { - preventDefault = true; - } - }); + this._matchingEventBindings(eventName, elIndex) + .forEach(rec => { + var res = this._processEventBinding(rec, locals); + if (res === false) { + preventDefault = true; + } + }); return preventDefault; } @@ -71,7 +72,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { } } - throw new BaseException('Cannot be reached'); + throw new BaseException("Cannot be reached"); } private _computeSkipLength(protoIndex: number, proto: ProtoRecord, values: any[]): number { @@ -89,7 +90,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { return condition ? 0 : proto.fixedArgs[0] - protoIndex - 1; } - throw new BaseException('Cannot be reached'); + throw new BaseException("Cannot be reached"); } /** @internal */ @@ -178,13 +179,12 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { } if (proto.isLifeCycleRecord()) { - if (proto.name === 'DoCheck' && !throwOnChange) { + if (proto.name === "DoCheck" && !throwOnChange) { this._getDirectiveFor(directiveRecord.directiveIndex).ngDoCheck(); - } else if ( - proto.name === 'OnInit' && !throwOnChange && - this.state == ChangeDetectorState.NeverChecked) { + } else if (proto.name === "OnInit" && !throwOnChange && + this.state == ChangeDetectorState.NeverChecked) { this._getDirectiveFor(directiveRecord.directiveIndex).ngOnInit(); - } else if (proto.name === 'OnChanges' && isPresent(changes) && !throwOnChange) { + } else if (proto.name === "OnChanges" && isPresent(changes) && !throwOnChange) { this._getDirectiveFor(directiveRecord.directiveIndex).ngOnChanges(changes); } } else if (proto.isSkipRecord()) { @@ -276,8 +276,8 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { } /** @internal */ - private _check(proto: ProtoRecord, throwOnChange: boolean, values: any[], locals: Locals): - SimpleChange { + private _check(proto: ProtoRecord, throwOnChange: boolean, values: any[], + locals: Locals): SimpleChange { if (proto.isPipeRecord()) { return this._pipeCheck(proto, throwOnChange, values); } else { @@ -286,8 +286,8 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { } /** @internal */ - private _referenceCheck( - proto: ProtoRecord, throwOnChange: boolean, values: any[], locals: Locals) { + private _referenceCheck(proto: ProtoRecord, throwOnChange: boolean, values: any[], + locals: Locals) { if (this._pureFuncAndArgsDidNotChange(proto)) { this._setChanged(proto, false); return null; @@ -298,8 +298,8 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { if (proto.shouldBeChecked()) { var prevValue = this._readSelf(proto, values); var detectedChange = throwOnChange ? - !ChangeDetectionUtil.devModeEqual(prevValue, currValue) : - ChangeDetectionUtil.looseNotIdentical(prevValue, currValue); + !ChangeDetectionUtil.devModeEqual(prevValue, currValue) : + ChangeDetectionUtil.looseNotIdentical(prevValue, currValue); if (detectedChange) { if (proto.lastInBinding) { var change = ChangeDetectionUtil.simpleChange(prevValue, currValue); @@ -379,8 +379,8 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { return args[args.length - 1]; case RecordType.InvokeClosure: - return FunctionWrapper.apply( - this._readContext(proto, values), this._readArgs(proto, values)); + return FunctionWrapper.apply(this._readContext(proto, values), + this._readArgs(proto, values)); case RecordType.Interpolate: case RecordType.PrimitiveOp: @@ -402,8 +402,8 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> { if (proto.shouldBeChecked()) { var prevValue = this._readSelf(proto, values); var detectedChange = throwOnChange ? - !ChangeDetectionUtil.devModeEqual(prevValue, currValue) : - ChangeDetectionUtil.looseNotIdentical(prevValue, currValue); + !ChangeDetectionUtil.devModeEqual(prevValue, currValue) : + ChangeDetectionUtil.looseNotIdentical(prevValue, currValue); if (detectedChange) { currValue = ChangeDetectionUtil.unwrapValue(currValue); diff --git a/modules/angular2/src/core/change_detection/event_binding.ts b/modules/angular2/src/core/change_detection/event_binding.ts index d866acf66e..52682ced2d 100644 --- a/modules/angular2/src/core/change_detection/event_binding.ts +++ b/modules/angular2/src/core/change_detection/event_binding.ts @@ -2,7 +2,6 @@ import {DirectiveIndex} from './directive_record'; import {ProtoRecord} from './proto_record'; export class EventBinding { - constructor( - public eventName: string, public elIndex: number, public dirIndex: DirectiveIndex, - public records: ProtoRecord[]) {} + constructor(public eventName: string, public elIndex: number, public dirIndex: DirectiveIndex, + public records: ProtoRecord[]) {} } \ No newline at end of file diff --git a/modules/angular2/src/core/change_detection/exceptions.ts b/modules/angular2/src/core/change_detection/exceptions.ts index 76e68b8fe7..b80ed08b8e 100644 --- a/modules/angular2/src/core/change_detection/exceptions.ts +++ b/modules/angular2/src/core/change_detection/exceptions.ts @@ -1,4 +1,4 @@ -import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; +import {BaseException, WrappedException} from "angular2/src/facade/exceptions"; /** * An error thrown if application changes model breaking the top-down data flow. @@ -35,9 +35,8 @@ import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; */ export class ExpressionChangedAfterItHasBeenCheckedException extends BaseException { constructor(exp: string, oldValue: any, currValue: any, context: any) { - super( - `Expression '${exp}' has changed after it was checked. ` + - `Previous value: '${oldValue}'. Current value: '${currValue}'`); + super(`Expression '${exp}' has changed after it was checked. ` + + `Previous value: '${oldValue}'. Current value: '${currValue}'`); } } @@ -108,7 +107,6 @@ export class EventEvaluationError extends WrappedException { * Error context included when an event handler throws an exception. */ export class EventEvaluationErrorContext { - constructor( - public element: any, public componentElement: any, public context: any, public locals: any, - public injector: any) {} + constructor(public element: any, public componentElement: any, public context: any, + public locals: any, public injector: any) {} } diff --git a/modules/angular2/src/core/change_detection/interfaces.ts b/modules/angular2/src/core/change_detection/interfaces.ts index 3f9e8668b3..0f3c165f56 100644 --- a/modules/angular2/src/core/change_detection/interfaces.ts +++ b/modules/angular2/src/core/change_detection/interfaces.ts @@ -5,9 +5,8 @@ import {ChangeDetectionStrategy} from './constants'; import {ChangeDetectorRef} from './change_detector_ref'; export class DebugContext { - constructor( - public element: any, public componentElement: any, public directive: any, public context: any, - public locals: any, public injector: any) {} + constructor(public element: any, public componentElement: any, public directive: any, + public context: any, public locals: any, public injector: any) {} } export interface ChangeDispatcher { @@ -45,13 +44,13 @@ export interface ChangeDetector { export interface ProtoChangeDetector { instantiate(): ChangeDetector; } export class ChangeDetectorGenConfig { - constructor( - public genDebugInfo: boolean, public logBindingUpdate: boolean, public useJit: boolean) {} + constructor(public genDebugInfo: boolean, public logBindingUpdate: boolean, + public useJit: boolean) {} } export class ChangeDetectorDefinition { - constructor( - public id: string, public strategy: ChangeDetectionStrategy, public variableNames: string[], - public bindingRecords: BindingRecord[], public eventRecords: BindingRecord[], - public directiveRecords: DirectiveRecord[], public genConfig: ChangeDetectorGenConfig) {} + constructor(public id: string, public strategy: ChangeDetectionStrategy, + public variableNames: string[], public bindingRecords: BindingRecord[], + public eventRecords: BindingRecord[], public directiveRecords: DirectiveRecord[], + public genConfig: ChangeDetectorGenConfig) {} } diff --git a/modules/angular2/src/core/change_detection/jit_proto_change_detector.ts b/modules/angular2/src/core/change_detection/jit_proto_change_detector.ts index d9de608cf9..bd747c4931 100644 --- a/modules/angular2/src/core/change_detection/jit_proto_change_detector.ts +++ b/modules/angular2/src/core/change_detection/jit_proto_change_detector.ts @@ -18,8 +18,8 @@ export class JitProtoChangeDetector implements ProtoChangeDetector { /** @internal */ _createFactory(definition: ChangeDetectorDefinition) { - return new ChangeDetectorJITGenerator( - definition, 'util', 'AbstractChangeDetector', 'ChangeDetectorStatus') + return new ChangeDetectorJITGenerator(definition, 'util', 'AbstractChangeDetector', + 'ChangeDetectorStatus') .generate(); } } diff --git a/modules/angular2/src/core/change_detection/parser/ast.ts b/modules/angular2/src/core/change_detection/parser/ast.ts index 55f26874c8..071506ab2c 100644 --- a/modules/angular2/src/core/change_detection/parser/ast.ts +++ b/modules/angular2/src/core/change_detection/parser/ast.ts @@ -1,8 +1,8 @@ -import {ListWrapper} from 'angular2/src/facade/collection'; +import {ListWrapper} from "angular2/src/facade/collection"; export class AST { visit(visitor: AstVisitor): any { return null; } - toString(): string { return 'AST'; } + toString(): string { return "AST"; } } /** @@ -23,7 +23,7 @@ export class Quote extends AST { super(); } visit(visitor: AstVisitor): any { return visitor.visitQuote(this); } - toString(): string { return 'Quote'; } + toString(): string { return "Quote"; } } export class EmptyExpr extends AST { @@ -55,8 +55,8 @@ export class PropertyRead extends AST { } export class PropertyWrite extends AST { - constructor( - public receiver: AST, public name: string, public setter: Function, public value: AST) { + constructor(public receiver: AST, public name: string, public setter: Function, + public value: AST) { super(); } visit(visitor: AstVisitor): any { return visitor.visitPropertyWrite(this); } @@ -138,9 +138,8 @@ export class ASTWithSource extends AST { } export class TemplateBinding { - constructor( - public key: string, public keyIsVar: boolean, public name: string, - public expression: ASTWithSource) {} + constructor(public key: string, public keyIsVar: boolean, public name: string, + public expression: ASTWithSource) {} } export interface AstVisitor { @@ -284,8 +283,8 @@ export class AstTransformer implements AstVisitor { visitPrefixNot(ast: PrefixNot): AST { return new PrefixNot(ast.expression.visit(this)); } visitConditional(ast: Conditional): AST { - return new Conditional( - ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this)); + return new Conditional(ast.condition.visit(this), ast.trueExp.visit(this), + ast.falseExp.visit(this)); } visitPipe(ast: BindingPipe): AST { diff --git a/modules/angular2/src/core/change_detection/parser/lexer.ts b/modules/angular2/src/core/change_detection/parser/lexer.ts index ced71bea15..4d81008dd4 100644 --- a/modules/angular2/src/core/change_detection/parser/lexer.ts +++ b/modules/angular2/src/core/change_detection/parser/lexer.ts @@ -1,6 +1,6 @@ import {Injectable} from 'angular2/src/core/di/decorators'; -import {ListWrapper, SetWrapper} from 'angular2/src/facade/collection'; -import {NumberWrapper, StringJoiner, StringWrapper, isPresent} from 'angular2/src/facade/lang'; +import {ListWrapper, SetWrapper} from "angular2/src/facade/collection"; +import {NumberWrapper, StringJoiner, StringWrapper, isPresent} from "angular2/src/facade/lang"; import {BaseException} from 'angular2/src/facade/exceptions'; export enum TokenType { @@ -27,9 +27,8 @@ export class Lexer { } export class Token { - constructor( - public index: number, public type: TokenType, public numValue: number, - public strValue: string) {} + constructor(public index: number, public type: TokenType, public numValue: number, + public strValue: string) {} isCharacter(code: number): boolean { return (this.type == TokenType.Character && this.numValue == code); @@ -47,17 +46,17 @@ export class Token { isKeyword(): boolean { return (this.type == TokenType.Keyword); } - isKeywordVar(): boolean { return (this.type == TokenType.Keyword && this.strValue == 'var'); } + isKeywordVar(): boolean { return (this.type == TokenType.Keyword && this.strValue == "var"); } - isKeywordNull(): boolean { return (this.type == TokenType.Keyword && this.strValue == 'null'); } + isKeywordNull(): boolean { return (this.type == TokenType.Keyword && this.strValue == "null"); } isKeywordUndefined(): boolean { - return (this.type == TokenType.Keyword && this.strValue == 'undefined'); + return (this.type == TokenType.Keyword && this.strValue == "undefined"); } - isKeywordTrue(): boolean { return (this.type == TokenType.Keyword && this.strValue == 'true'); } + isKeywordTrue(): boolean { return (this.type == TokenType.Keyword && this.strValue == "true"); } - isKeywordFalse(): boolean { return (this.type == TokenType.Keyword && this.strValue == 'false'); } + isKeywordFalse(): boolean { return (this.type == TokenType.Keyword && this.strValue == "false"); } toNumber(): number { // -1 instead of NULL ok? @@ -101,11 +100,11 @@ function newStringToken(index: number, text: string): Token { } function newNumberToken(index: number, n: number): Token { - return new Token(index, TokenType.Number, n, ''); + return new Token(index, TokenType.Number, n, ""); } -export var EOF: Token = new Token(-1, TokenType.Character, 0, ''); +export var EOF: Token = new Token(-1, TokenType.Character, 0, ""); export const $EOF = 0; export const $TAB = 9; @@ -232,8 +231,8 @@ class _Scanner { return this.scanComplexOperator(start, StringWrapper.fromCharCode(peek), $EQ, '='); case $BANG: case $EQ: - return this.scanComplexOperator( - start, StringWrapper.fromCharCode(peek), $EQ, '=', $EQ, '='); + return this.scanComplexOperator(start, StringWrapper.fromCharCode(peek), $EQ, '=', $EQ, + '='); case $AMPERSAND: return this.scanComplexOperator(start, '&', $AMPERSAND, '&'); case $BAR: @@ -269,9 +268,8 @@ class _Scanner { * @param three third symbol (part of the operator when provided and matches source expression) * @returns {Token} */ - scanComplexOperator( - start: number, one: string, twoCode: number, two: string, threeCode?: number, - three?: string): Token { + scanComplexOperator(start: number, one: string, twoCode: number, two: string, threeCode?: number, + three?: string): Token { this.advance(); var str: string = one; if (this.peek == twoCode) { @@ -402,7 +400,7 @@ export function isIdentifier(input: string): boolean { function isIdentifierPart(code: number): boolean { return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) || - (code == $_) || (code == $$); + (code == $_) || (code == $$); } function isDigit(code: number): boolean { @@ -435,8 +433,29 @@ function unescape(code: number): number { } var OPERATORS = SetWrapper.createFromList([ - '+', '-', '*', '/', '%', '^', '=', '==', '!=', '===', '!==', '<', - '>', '<=', '>=', '&&', '||', '&', '|', '!', '?', '#', '?.' + '+', + '-', + '*', + '/', + '%', + '^', + '=', + '==', + '!=', + '===', + '!==', + '<', + '>', + '<=', + '>=', + '&&', + '||', + '&', + '|', + '!', + '?', + '#', + '?.' ]); diff --git a/modules/angular2/src/core/change_detection/parser/parser.ts b/modules/angular2/src/core/change_detection/parser/parser.ts index f8b86b23b4..0992552bcd 100644 --- a/modules/angular2/src/core/change_detection/parser/parser.ts +++ b/modules/angular2/src/core/change_detection/parser/parser.ts @@ -2,9 +2,49 @@ import {Injectable} from 'angular2/src/core/di/decorators'; import {isBlank, isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {ListWrapper} from 'angular2/src/facade/collection'; -import {Lexer, EOF, isIdentifier, Token, $PERIOD, $COLON, $SEMICOLON, $LBRACKET, $RBRACKET, $COMMA, $LBRACE, $RBRACE, $LPAREN, $RPAREN} from './lexer'; +import { + Lexer, + EOF, + isIdentifier, + Token, + $PERIOD, + $COLON, + $SEMICOLON, + $LBRACKET, + $RBRACKET, + $COMMA, + $LBRACE, + $RBRACE, + $LPAREN, + $RPAREN +} from './lexer'; import {reflector, Reflector} from 'angular2/src/core/reflection/reflection'; -import {AST, EmptyExpr, ImplicitReceiver, PropertyRead, PropertyWrite, SafePropertyRead, LiteralPrimitive, Binary, PrefixNot, Conditional, BindingPipe, Chain, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, Interpolation, MethodCall, SafeMethodCall, FunctionCall, TemplateBinding, ASTWithSource, AstVisitor, Quote} from './ast'; +import { + AST, + EmptyExpr, + ImplicitReceiver, + PropertyRead, + PropertyWrite, + SafePropertyRead, + LiteralPrimitive, + Binary, + PrefixNot, + Conditional, + BindingPipe, + Chain, + KeyedRead, + KeyedWrite, + LiteralArray, + LiteralMap, + Interpolation, + MethodCall, + SafeMethodCall, + FunctionCall, + TemplateBinding, + ASTWithSource, + AstVisitor, + Quote +} from './ast'; var _implicitReceiver = new ImplicitReceiver(); @@ -112,9 +152,9 @@ export class Parser { } else if (part.trim().length > 0) { expressions.push(part); } else { - throw new ParseException( - 'Blank expressions are not allowed in interpolated strings', input, - `at column ${this._findInterpolationErrorColumn(parts, i)} in`, location); + throw new ParseException('Blank expressions are not allowed in interpolated strings', input, + `at column ${this._findInterpolationErrorColumn(parts, i)} in`, + location); } } return new SplitInterpolation(strings, expressions); @@ -127,9 +167,9 @@ export class Parser { private _checkNoInterpolation(input: string, location: any): void { var parts = StringWrapper.split(input, INTERPOLATION_REGEXP); if (parts.length > 1) { - throw new ParseException( - 'Got interpolation ({{}}) where expression was expected', input, - `at column ${this._findInterpolationErrorColumn(parts, 1)} in`, location); + throw new ParseException('Got interpolation ({{}}) where expression was expected', input, + `at column ${this._findInterpolationErrorColumn(parts, 1)} in`, + location); } } @@ -145,9 +185,8 @@ export class Parser { export class _ParseAST { index: number = 0; - constructor( - public input: string, public location: any, public tokens: any[], public reflector: Reflector, - public parseAction: boolean) {} + constructor(public input: string, public location: any, public tokens: any[], + public reflector: Reflector, public parseAction: boolean) {} peek(offset: number): Token { var i = this.index + offset; @@ -228,7 +267,7 @@ export class _ParseAST { if (this.optionalCharacter($SEMICOLON)) { if (!this.parseAction) { - this.error('Binding expression cannot contain chained expression'); + this.error("Binding expression cannot contain chained expression"); } while (this.optionalCharacter($SEMICOLON)) { } // read all semicolons @@ -243,9 +282,9 @@ export class _ParseAST { parsePipe(): AST { var result = this.parseExpression(); - if (this.optionalOperator('|')) { + if (this.optionalOperator("|")) { if (this.parseAction) { - this.error('Cannot have a pipe in an action expression'); + this.error("Cannot have a pipe in an action expression"); } do { @@ -255,7 +294,7 @@ export class _ParseAST { args.push(this.parseExpression()); } result = new BindingPipe(result, name, args); - } while (this.optionalOperator('|')); + } while (this.optionalOperator("|")); } return result; @@ -389,7 +428,7 @@ export class _ParseAST { } else if (this.optionalCharacter($LBRACKET)) { var key = this.parsePipe(); this.expectCharacter($RBRACKET); - if (this.optionalOperator('=')) { + if (this.optionalOperator("=")) { var value = this.parseConditional(); result = new KeyedWrite(result, key, value); } else { @@ -452,7 +491,7 @@ export class _ParseAST { this.error(`Unexpected token ${this.next}`); } // error() throws, so we don't reach here. - throw new BaseException('Fell through all cases in parsePrimary'); + throw new BaseException("Fell through all cases in parsePrimary"); } parseExpressionList(terminator: number): any[] { @@ -493,15 +532,15 @@ export class _ParseAST { } else { if (isSafe) { - if (this.optionalOperator('=')) { - this.error('The \'?.\' operator cannot be used in the assignment'); + if (this.optionalOperator("=")) { + this.error("The '?.' operator cannot be used in the assignment"); } else { return new SafePropertyRead(receiver, id, this.reflector.getter(id)); } } else { - if (this.optionalOperator('=')) { + if (this.optionalOperator("=")) { if (!this.parseAction) { - this.error('Bindings cannot contain assignments'); + this.error("Bindings cannot contain assignments"); } let value = this.parseConditional(); @@ -526,7 +565,7 @@ export class _ParseAST { parseBlockContent(): AST { if (!this.parseAction) { - this.error('Binding expression cannot contain chained expression'); + this.error("Binding expression cannot contain chained expression"); } var exprs = []; while (this.index < this.tokens.length && !this.next.isCharacter($RBRACE)) { @@ -579,7 +618,7 @@ export class _ParseAST { var name = null; var expression = null; if (keyIsVar) { - if (this.optionalOperator('=')) { + if (this.optionalOperator("=")) { name = this.expectTemplateBindingKey(); } else { name = '\$implicit'; diff --git a/modules/angular2/src/core/change_detection/proto_change_detector.ts b/modules/angular2/src/core/change_detection/proto_change_detector.ts index 87c6a359fe..2f2d7c22cd 100644 --- a/modules/angular2/src/core/change_detection/proto_change_detector.ts +++ b/modules/angular2/src/core/change_detection/proto_change_detector.ts @@ -2,7 +2,30 @@ import {Type, isBlank, isPresent, isString} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {PropertyRead, PropertyWrite, KeyedWrite, AST, ASTWithSource, AstVisitor, Binary, Chain, Conditional, BindingPipe, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, Quote, SafePropertyRead, SafeMethodCall} from './parser/ast'; +import { + PropertyRead, + PropertyWrite, + KeyedWrite, + AST, + ASTWithSource, + AstVisitor, + Binary, + Chain, + Conditional, + BindingPipe, + FunctionCall, + ImplicitReceiver, + Interpolation, + KeyedRead, + LiteralArray, + LiteralMap, + LiteralPrimitive, + MethodCall, + PrefixNot, + Quote, + SafePropertyRead, + SafeMethodCall +} from './parser/ast'; import {ChangeDetector, ProtoChangeDetector, ChangeDetectorDefinition} from './interfaces'; import {ChangeDetectionUtil} from './change_detection_util'; @@ -80,12 +103,12 @@ export class ProtoRecordBuilder { for (var i = startIndex; i < this.records.length; ++i) { var rec = this.records[i]; if (rec.isPureFunction()) { - rec.args.forEach( - recordIndex => this.records[recordIndex - 1].argumentToPureFunction = true); + rec.args.forEach(recordIndex => this.records[recordIndex - 1].argumentToPureFunction = + true); } if (rec.mode === RecordType.Pipe) { - rec.args.forEach( - recordIndex => this.records[recordIndex - 1].argumentToPureFunction = true); + rec.args.forEach(recordIndex => this.records[recordIndex - 1].argumentToPureFunction = + true); this.records[rec.contextIndex - 1].argumentToPureFunction = true; } } @@ -94,9 +117,9 @@ export class ProtoRecordBuilder { /** @internal */ _appendRecords(b: BindingRecord, variableNames: string[], bindingIndex: number) { if (b.isDirectiveLifecycle()) { - this.records.push(new ProtoRecord( - RecordType.DirectiveLifecycle, b.lifecycleEvent, null, [], [], -1, null, - this.records.length + 1, b, false, false, false, false, null)); + this.records.push(new ProtoRecord(RecordType.DirectiveLifecycle, b.lifecycleEvent, null, [], + [], -1, null, this.records.length + 1, b, false, false, + false, false, null)); } else { _ConvertAstIntoProtoRecords.append(this.records, b, variableNames, bindingIndex); } @@ -104,12 +127,11 @@ export class ProtoRecordBuilder { } class _ConvertAstIntoProtoRecords implements AstVisitor { - constructor( - private _records: ProtoRecord[], private _bindingRecord: BindingRecord, - private _variableNames: string[], private _bindingIndex: number) {} + constructor(private _records: ProtoRecord[], private _bindingRecord: BindingRecord, + private _variableNames: string[], private _bindingIndex: number) {} - static append( - records: ProtoRecord[], b: BindingRecord, variableNames: string[], bindingIndex: number) { + static append(records: ProtoRecord[], b: BindingRecord, variableNames: string[], + bindingIndex: number) { var c = new _ConvertAstIntoProtoRecords(records, b, variableNames, bindingIndex); b.ast.visit(c); } @@ -125,12 +147,12 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { visitInterpolation(ast: Interpolation): number { var args = this._visitAll(ast.expressions); - return this._addRecord( - RecordType.Interpolate, 'interpolate', _interpolationFn(ast.strings), args, ast.strings, 0); + return this._addRecord(RecordType.Interpolate, "interpolate", _interpolationFn(ast.strings), + args, ast.strings, 0); } visitLiteralPrimitive(ast: LiteralPrimitive): number { - return this._addRecord(RecordType.Const, 'literal', ast.value, [], null, 0); + return this._addRecord(RecordType.Const, "literal", ast.value, [], null, 0); } visitPropertyRead(ast: PropertyRead): number { @@ -150,8 +172,8 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { } else { var receiver = ast.receiver.visit(this); var value = ast.value.visit(this); - return this._addRecord( - RecordType.PropertyWrite, ast.name, ast.setter, [value], null, receiver); + return this._addRecord(RecordType.PropertyWrite, ast.name, ast.setter, [value], null, + receiver); } } @@ -172,7 +194,7 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { var args = this._visitAll(ast.args); if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name)) { var target = this._addRecord(RecordType.Local, ast.name, ast.name, [], null, receiver); - return this._addRecord(RecordType.InvokeClosure, 'closure', null, args, null, target); + return this._addRecord(RecordType.InvokeClosure, "closure", null, args, null, target); } else { return this._addRecord(RecordType.InvokeMethod, ast.name, ast.fn, args, null, receiver); } @@ -187,20 +209,20 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { visitFunctionCall(ast: FunctionCall): number { var target = ast.target.visit(this); var args = this._visitAll(ast.args); - return this._addRecord(RecordType.InvokeClosure, 'closure', null, args, null, target); + return this._addRecord(RecordType.InvokeClosure, "closure", null, args, null, target); } visitLiteralArray(ast: LiteralArray): number { var primitiveName = `arrayFn${ast.expressions.length}`; - return this._addRecord( - RecordType.CollectionLiteral, primitiveName, _arrayFn(ast.expressions.length), - this._visitAll(ast.expressions), null, 0); + return this._addRecord(RecordType.CollectionLiteral, primitiveName, + _arrayFn(ast.expressions.length), this._visitAll(ast.expressions), null, + 0); } visitLiteralMap(ast: LiteralMap): number { - return this._addRecord( - RecordType.CollectionLiteral, _mapPrimitiveName(ast.keys), - ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null, 0); + return this._addRecord(RecordType.CollectionLiteral, _mapPrimitiveName(ast.keys), + ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null, + 0); } visitBinary(ast: Binary): number { @@ -208,51 +230,48 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { switch (ast.operation) { case '&&': var branchEnd = [null]; - this._addRecord(RecordType.SkipRecordsIfNot, 'SkipRecordsIfNot', null, [], branchEnd, left); + this._addRecord(RecordType.SkipRecordsIfNot, "SkipRecordsIfNot", null, [], branchEnd, left); var right = ast.right.visit(this); branchEnd[0] = right; - return this._addRecord( - RecordType.PrimitiveOp, 'cond', ChangeDetectionUtil.cond, [left, right, left], null, 0); + return this._addRecord(RecordType.PrimitiveOp, "cond", ChangeDetectionUtil.cond, + [left, right, left], null, 0); case '||': var branchEnd = [null]; - this._addRecord(RecordType.SkipRecordsIf, 'SkipRecordsIf', null, [], branchEnd, left); + this._addRecord(RecordType.SkipRecordsIf, "SkipRecordsIf", null, [], branchEnd, left); var right = ast.right.visit(this); branchEnd[0] = right; - return this._addRecord( - RecordType.PrimitiveOp, 'cond', ChangeDetectionUtil.cond, [left, left, right], null, 0); + return this._addRecord(RecordType.PrimitiveOp, "cond", ChangeDetectionUtil.cond, + [left, left, right], null, 0); default: var right = ast.right.visit(this); - return this._addRecord( - RecordType.PrimitiveOp, _operationToPrimitiveName(ast.operation), - _operationToFunction(ast.operation), [left, right], null, 0); + return this._addRecord(RecordType.PrimitiveOp, _operationToPrimitiveName(ast.operation), + _operationToFunction(ast.operation), [left, right], null, 0); } } visitPrefixNot(ast: PrefixNot): number { var exp = ast.expression.visit(this); - return this._addRecord( - RecordType.PrimitiveOp, 'operation_negate', ChangeDetectionUtil.operation_negate, [exp], - null, 0); + return this._addRecord(RecordType.PrimitiveOp, "operation_negate", + ChangeDetectionUtil.operation_negate, [exp], null, 0); } visitConditional(ast: Conditional): number { var condition = ast.condition.visit(this); var startOfFalseBranch = [null]; var endOfFalseBranch = [null]; - this._addRecord( - RecordType.SkipRecordsIfNot, 'SkipRecordsIfNot', null, [], startOfFalseBranch, condition); + this._addRecord(RecordType.SkipRecordsIfNot, "SkipRecordsIfNot", null, [], startOfFalseBranch, + condition); var whenTrue = ast.trueExp.visit(this); var skip = - this._addRecord(RecordType.SkipRecords, 'SkipRecords', null, [], endOfFalseBranch, 0); + this._addRecord(RecordType.SkipRecords, "SkipRecords", null, [], endOfFalseBranch, 0); var whenFalse = ast.falseExp.visit(this); startOfFalseBranch[0] = skip; endOfFalseBranch[0] = whenFalse; - return this._addRecord( - RecordType.PrimitiveOp, 'cond', ChangeDetectionUtil.cond, [condition, whenTrue, whenFalse], - null, 0); + return this._addRecord(RecordType.PrimitiveOp, "cond", ChangeDetectionUtil.cond, + [condition, whenTrue, whenFalse], null, 0); } visitPipe(ast: BindingPipe): number { @@ -264,13 +283,13 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { visitKeyedRead(ast: KeyedRead): number { var obj = ast.obj.visit(this); var key = ast.key.visit(this); - return this._addRecord( - RecordType.KeyedRead, 'keyedAccess', ChangeDetectionUtil.keyedAccess, [key], null, obj); + return this._addRecord(RecordType.KeyedRead, "keyedAccess", ChangeDetectionUtil.keyedAccess, + [key], null, obj); } visitChain(ast: Chain): number { var args = ast.expressions.map(e => e.visit(this)); - return this._addRecord(RecordType.Chain, 'chain', null, args, null, 0); + return this._addRecord(RecordType.Chain, "chain", null, args, null, 0); } visitQuote(ast: Quote): void { @@ -293,13 +312,13 @@ class _ConvertAstIntoProtoRecords implements AstVisitor { private _addRecord(type, name, funcOrValue, args, fixedArgs, context): number { var selfIndex = this._records.length + 1; if (context instanceof DirectiveIndex) { - this._records.push(new ProtoRecord( - type, name, funcOrValue, args, fixedArgs, -1, context, selfIndex, this._bindingRecord, - false, false, false, false, this._bindingIndex)); + this._records.push(new ProtoRecord(type, name, funcOrValue, args, fixedArgs, -1, context, + selfIndex, this._bindingRecord, false, false, false, false, + this._bindingIndex)); } else { - this._records.push(new ProtoRecord( - type, name, funcOrValue, args, fixedArgs, context, null, selfIndex, this._bindingRecord, - false, false, false, false, this._bindingIndex)); + this._records.push(new ProtoRecord(type, name, funcOrValue, args, fixedArgs, context, null, + selfIndex, this._bindingRecord, false, false, false, false, + this._bindingIndex)); } return selfIndex; } @@ -341,31 +360,31 @@ function _mapPrimitiveName(keys: any[]) { function _operationToPrimitiveName(operation: string): string { switch (operation) { case '+': - return 'operation_add'; + return "operation_add"; case '-': - return 'operation_subtract'; + return "operation_subtract"; case '*': - return 'operation_multiply'; + return "operation_multiply"; case '/': - return 'operation_divide'; + return "operation_divide"; case '%': - return 'operation_remainder'; + return "operation_remainder"; case '==': - return 'operation_equals'; + return "operation_equals"; case '!=': - return 'operation_not_equals'; + return "operation_not_equals"; case '===': - return 'operation_identical'; + return "operation_identical"; case '!==': - return 'operation_not_identical'; + return "operation_not_identical"; case '<': - return 'operation_less_then'; + return "operation_less_then"; case '>': - return 'operation_greater_then'; + return "operation_greater_then"; case '<=': - return 'operation_less_or_equals_then'; + return "operation_less_or_equals_then"; case '>=': - return 'operation_greater_or_equals_then'; + return "operation_greater_or_equals_then"; default: throw new BaseException(`Unsupported operation ${operation}`); } @@ -437,13 +456,15 @@ function _interpolationFn(strings: any[]) { c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6; case 7: return (a1, a2, a3, a4, a5, a6, a7) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + - c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7; + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7; case 8: return (a1, a2, a3, a4, a5, a6, a7, a8) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + - c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + c8; + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + + c8; case 9: return (a1, a2, a3, a4, a5, a6, a7, a8, a9) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + - s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + c8 + s(a9) + c9; + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + + c7 + s(a8) + c8 + s(a9) + c9; default: throw new BaseException(`Does not support more than 9 expressions`); } diff --git a/modules/angular2/src/core/change_detection/proto_record.ts b/modules/angular2/src/core/change_detection/proto_record.ts index fbe1ae2bfe..f3fd76f906 100644 --- a/modules/angular2/src/core/change_detection/proto_record.ts +++ b/modules/angular2/src/core/change_detection/proto_record.ts @@ -25,12 +25,12 @@ export enum RecordType { } export class ProtoRecord { - constructor( - public mode: RecordType, public name: string, public funcOrValue, public args: any[], - public fixedArgs: any[], public contextIndex: number, public directiveIndex: DirectiveIndex, - public selfIndex: number, public bindingRecord: BindingRecord, public lastInBinding: boolean, - public lastInDirective: boolean, public argumentToPureFunction: boolean, - public referencedBySelf: boolean, public propertyBindingIndex: number) {} + constructor(public mode: RecordType, public name: string, public funcOrValue, public args: any[], + public fixedArgs: any[], public contextIndex: number, + public directiveIndex: DirectiveIndex, public selfIndex: number, + public bindingRecord: BindingRecord, public lastInBinding: boolean, + public lastInDirective: boolean, public argumentToPureFunction: boolean, + public referencedBySelf: boolean, public propertyBindingIndex: number) {} isPureFunction(): boolean { return this.mode === RecordType.Interpolate || this.mode === RecordType.CollectionLiteral; @@ -40,7 +40,7 @@ export class ProtoRecord { shouldBeChecked(): boolean { return this.argumentToPureFunction || this.lastInBinding || this.isPureFunction() || - this.isPipeRecord(); + this.isPipeRecord(); } isPipeRecord(): boolean { return this.mode === RecordType.Pipe; } diff --git a/modules/angular2/src/core/debug/debug_node.ts b/modules/angular2/src/core/debug/debug_node.ts index 955292895a..87634f09d3 100644 --- a/modules/angular2/src/core/debug/debug_node.ts +++ b/modules/angular2/src/core/debug/debug_node.ts @@ -125,8 +125,8 @@ export function asNativeElements(debugEls: DebugElement[]): any { return debugEls.map((el) => el.nativeElement); } -function _queryElementChildren( - element: DebugElement, predicate: Predicate<DebugElement>, matches: DebugElement[]) { +function _queryElementChildren(element: DebugElement, predicate: Predicate<DebugElement>, + matches: DebugElement[]) { element.childNodes.forEach(node => { if (node instanceof DebugElement) { if (predicate(node)) { @@ -137,8 +137,8 @@ function _queryElementChildren( }); } -function _queryNodeChildren( - parentNode: DebugNode, predicate: Predicate<DebugNode>, matches: DebugNode[]) { +function _queryNodeChildren(parentNode: DebugNode, predicate: Predicate<DebugNode>, + matches: DebugNode[]) { if (parentNode instanceof DebugElement) { parentNode.childNodes.forEach(node => { if (predicate(node)) { diff --git a/modules/angular2/src/core/debug/debug_renderer.ts b/modules/angular2/src/core/debug/debug_renderer.ts index d9f48f3069..c68c99352e 100644 --- a/modules/angular2/src/core/debug/debug_renderer.ts +++ b/modules/angular2/src/core/debug/debug_renderer.ts @@ -1,6 +1,18 @@ import {isPresent} from 'angular2/src/facade/lang'; -import {Renderer, RootRenderer, RenderComponentType, RenderDebugInfo} from 'angular2/src/core/render/api'; -import {DebugNode, DebugElement, EventListener, getDebugNode, indexDebugNode, removeDebugNodeFromIndex} from 'angular2/src/core/debug/debug_node'; +import { + Renderer, + RootRenderer, + RenderComponentType, + RenderDebugInfo +} from 'angular2/src/core/render/api'; +import { + DebugNode, + DebugElement, + EventListener, + getDebugNode, + indexDebugNode, + removeDebugNodeFromIndex +} from 'angular2/src/core/debug/debug_node'; export class DebugDomRootRenderer implements RootRenderer { constructor(private _delegate: RootRenderer) {} diff --git a/modules/angular2/src/core/di.ts b/modules/angular2/src/core/di.ts index edbe34391b..0689a696ef 100644 --- a/modules/angular2/src/core/di.ts +++ b/modules/angular2/src/core/di.ts @@ -4,14 +4,41 @@ * The `di` module provides dependency injection container services. */ -export {InjectMetadata, OptionalMetadata, InjectableMetadata, SelfMetadata, HostMetadata, SkipSelfMetadata, DependencyMetadata} from './di/metadata'; +export { + InjectMetadata, + OptionalMetadata, + InjectableMetadata, + SelfMetadata, + HostMetadata, + SkipSelfMetadata, + DependencyMetadata +} from './di/metadata'; // we have to reexport * because Dart and TS export two different sets of types export * from './di/decorators'; export {forwardRef, resolveForwardRef, ForwardRefFn} from './di/forward_ref'; export {Injector} from './di/injector'; -export {Binding, ProviderBuilder, ResolvedBinding, ResolvedFactory, Dependency, bind, Provider, ResolvedProvider, provide} from './di/provider'; +export { + Binding, + ProviderBuilder, + ResolvedBinding, + ResolvedFactory, + Dependency, + bind, + + Provider, + ResolvedProvider, + provide +} from './di/provider'; export {Key} from './di/key'; -export {NoProviderError, AbstractProviderError, CyclicDependencyError, InstantiationError, InvalidProviderError, NoAnnotationError, OutOfBoundsError} from './di/exceptions'; +export { + NoProviderError, + AbstractProviderError, + CyclicDependencyError, + InstantiationError, + InvalidProviderError, + NoAnnotationError, + OutOfBoundsError +} from './di/exceptions'; export {OpaqueToken} from './di/opaque_token'; diff --git a/modules/angular2/src/core/di/decorators.ts b/modules/angular2/src/core/di/decorators.ts index 40f1acd083..01126266b9 100644 --- a/modules/angular2/src/core/di/decorators.ts +++ b/modules/angular2/src/core/di/decorators.ts @@ -1,4 +1,11 @@ -import {InjectMetadata, OptionalMetadata, InjectableMetadata, SelfMetadata, HostMetadata, SkipSelfMetadata} from './metadata'; +import { + InjectMetadata, + OptionalMetadata, + InjectableMetadata, + SelfMetadata, + HostMetadata, + SkipSelfMetadata +} from './metadata'; import {makeDecorator, makeParamDecorator} from '../util/decorators'; /** diff --git a/modules/angular2/src/core/di/exceptions.ts b/modules/angular2/src/core/di/exceptions.ts index 023c10e5fc..084b1a32dd 100644 --- a/modules/angular2/src/core/di/exceptions.ts +++ b/modules/angular2/src/core/di/exceptions.ts @@ -21,9 +21,9 @@ function constructResolvingPath(keys: any[]): string { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); - return ' (' + tokenStrs.join(' -> ') + ')'; + return " (" + tokenStrs.join(' -> ') + ")"; } else { - return ''; + return ""; } } @@ -45,7 +45,7 @@ export class AbstractProviderError extends BaseException { constructResolvingMessage: Function; constructor(injector: Injector, key: Key, constructResolvingMessage: Function) { - super('DI Exception'); + super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; @@ -142,7 +142,7 @@ export class InstantiationError extends WrappedException { injectors: Injector[]; constructor(injector: Injector, originalException, originalStack, key: Key) { - super('DI Exception', originalException, originalStack, null); + super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } @@ -174,9 +174,8 @@ export class InstantiationError extends WrappedException { */ export class InvalidProviderError extends BaseException { constructor(provider) { - super( - 'Invalid provider - only instances of Provider and Type are allowed, got: ' + - provider.toString()); + super("Invalid provider - only instances of Provider and Type are allowed, got: " + + provider.toString()); } } @@ -223,10 +222,10 @@ export class NoAnnotationError extends BaseException { signature.push(parameter.map(stringify).join(' ')); } } - return 'Cannot resolve all parameters for \'' + stringify(typeOrFunc) + '\'(' + - signature.join(', ') + '). ' + - 'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' + - stringify(typeOrFunc) + '\' is decorated with Injectable.'; + return "Cannot resolve all parameters for '" + stringify(typeOrFunc) + "'(" + + signature.join(', ') + "). " + + "Make sure that all the parameters are decorated with Inject or have valid type annotations and that '" + + stringify(typeOrFunc) + "' is decorated with Injectable."; } } @@ -262,8 +261,7 @@ export class OutOfBoundsError extends BaseException { */ export class MixingMultiProvidersWithRegularProvidersError extends BaseException { constructor(provider1, provider2) { - super( - 'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' + - provider2.toString()); + super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + + provider2.toString()); } } diff --git a/modules/angular2/src/core/di/injector.ts b/modules/angular2/src/core/di/injector.ts index 22581b6ee1..6ad125539e 100644 --- a/modules/angular2/src/core/di/injector.ts +++ b/modules/angular2/src/core/di/injector.ts @@ -1,6 +1,21 @@ import {Map, MapWrapper, ListWrapper} from 'angular2/src/facade/collection'; -import {ResolvedProvider, Provider, Dependency, ProviderBuilder, ResolvedFactory, provide, resolveProviders} from './provider'; -import {AbstractProviderError, NoProviderError, CyclicDependencyError, InstantiationError, InvalidProviderError, OutOfBoundsError} from './exceptions'; +import { + ResolvedProvider, + Provider, + Dependency, + ProviderBuilder, + ResolvedFactory, + provide, + resolveProviders +} from './provider'; +import { + AbstractProviderError, + NoProviderError, + CyclicDependencyError, + InstantiationError, + InvalidProviderError, + OutOfBoundsError +} from './exceptions'; import {FunctionWrapper, Type, isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {Key} from './key'; @@ -31,7 +46,7 @@ export enum Visibility { function canSee(src: Visibility, dst: Visibility): boolean { return (src === dst) || - (dst === Visibility.PublicAndPrivate || src === Visibility.PublicAndPrivate); + (dst === Visibility.PublicAndPrivate || src === Visibility.PublicAndPrivate); } @@ -192,8 +207,8 @@ export class ProtoInjector { constructor(bwv: ProviderWithVisibility[]) { this.numberOfProviders = bwv.length; this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ? - new ProtoInjectorDynamicStrategy(this, bwv) : - new ProtoInjectorInlineStrategy(this, bwv); + new ProtoInjectorDynamicStrategy(this, bwv) : + new ProtoInjectorInlineStrategy(this, bwv); } getProviderAtIndex(index: number): ResolvedProvider { @@ -438,7 +453,7 @@ export class Injector { * * See {@link Injector#fromResolvedProviders} for more info. */ - static resolve(providers: Array<Type|Provider|any[]>): ResolvedProvider[] { + static resolve(providers: Array<Type | Provider | any[]>): ResolvedProvider[] { return resolveProviders(providers); } @@ -468,7 +483,7 @@ export class Injector { * because it needs to resolve the passed-in providers first. * See {@link Injector#resolve} and {@link Injector#fromResolvedProviders}. */ - static resolveAndCreate(providers: Array<Type|Provider|any[]>): Injector { + static resolveAndCreate(providers: Array<Type | Provider | any[]>): Injector { var resolvedProviders = Injector.resolve(providers); return Injector.fromResolvedProviders(resolvedProviders); } @@ -517,11 +532,10 @@ export class Injector { /** * Private */ - constructor( - _proto: any /* ProtoInjector */, _parent: Injector = null, - private _isHostBoundary: boolean = false, - private _depProvider: any /* DependencyProvider */ = null, - private _debugContext: Function = null) { + constructor(_proto: any /* ProtoInjector */, _parent: Injector = null, + private _isHostBoundary: boolean = false, + private _depProvider: any /* DependencyProvider */ = null, + private _debugContext: Function = null) { this._proto = _proto; this._parent = _parent; this._strategy = _proto._strategy.createInjectorStrategy(this); @@ -643,7 +657,7 @@ export class Injector { * because it needs to resolve the passed-in providers first. * See {@link Injector#resolve} and {@link Injector#createChildFromResolved}. */ - resolveAndCreateChild(providers: Array<Type|Provider|any[]>): Injector { + resolveAndCreateChild(providers: Array<Type | Provider | any[]>): Injector { var resolvedProviders = Injector.resolve(providers); return this.createChildFromResolved(resolvedProviders); } @@ -705,7 +719,7 @@ export class Injector { * expect(car).not.toBe(injector.resolveAndInstantiate(Car)); * ``` */ - resolveAndInstantiate(provider: Type|Provider): any { + resolveAndInstantiate(provider: Type | Provider): any { return this.instantiateResolved(Injector.resolve([provider])[0]); } @@ -757,8 +771,8 @@ export class Injector { } } - private _instantiate( - provider: ResolvedProvider, resolvedFactory: ResolvedFactory, visibility: Visibility): any { + private _instantiate(provider: ResolvedProvider, resolvedFactory: ResolvedFactory, + visibility: Visibility): any { var factory = resolvedFactory.factory; var deps = resolvedFactory.dependencies; var length = deps.length; @@ -869,17 +883,16 @@ export class Injector { obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16); break; case 18: - obj = factory( - d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17); + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, + d17); break; case 19: - obj = factory( - d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18); + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, + d17, d18); break; case 20: - obj = factory( - d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, - d19); + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, + d17, d18, d19); break; default: throw new BaseException( @@ -891,23 +904,21 @@ export class Injector { return obj; } - private _getByDependency( - provider: ResolvedProvider, dep: Dependency, providerVisibility: Visibility): any { + private _getByDependency(provider: ResolvedProvider, dep: Dependency, + providerVisibility: Visibility): any { var special = isPresent(this._depProvider) ? - this._depProvider.getDependency(this, provider, dep) : - UNDEFINED; + this._depProvider.getDependency(this, provider, dep) : + UNDEFINED; if (special !== UNDEFINED) { return special; } else { - return this._getByKey( - dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility, dep.optional, - providerVisibility); + return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility, + dep.optional, providerVisibility); } } - private _getByKey( - key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object, optional: boolean, - providerVisibility: Visibility): any { + private _getByKey(key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object, + optional: boolean, providerVisibility: Visibility): any { if (key === INJECTOR_KEY) { return this; } @@ -939,9 +950,8 @@ export class Injector { } /** @internal */ - _getByKeyHost( - key: Key, optional: boolean, providerVisibility: Visibility, - lowerBoundVisibility: Object): any { + _getByKeyHost(key: Key, optional: boolean, providerVisibility: Visibility, + lowerBoundVisibility: Object): any { var inj: Injector = this; if (lowerBoundVisibility instanceof SkipSelfMetadata) { @@ -973,9 +983,8 @@ export class Injector { } /** @internal */ - _getByKeyDefault( - key: Key, optional: boolean, providerVisibility: Visibility, - lowerBoundVisibility: Object): any { + _getByKeyDefault(key: Key, optional: boolean, providerVisibility: Visibility, + lowerBoundVisibility: Object): any { var inj: Injector = this; if (lowerBoundVisibility instanceof SkipSelfMetadata) { @@ -995,7 +1004,7 @@ export class Injector { } get displayName(): string { - return `Injector(providers: [${_mapProviders(this, (b: ResolvedProvider) => ` '${b.key.displayName}' `).join(", ")}])`; + return `Injector(providers: [${_mapProviders(this, (b: ResolvedProvider) => ` "${b.key.displayName}" `).join(", ")}])`; } toString(): string { return this.displayName; } diff --git a/modules/angular2/src/core/di/metadata.ts b/modules/angular2/src/core/di/metadata.ts index a93f211487..693e16d78e 100644 --- a/modules/angular2/src/core/di/metadata.ts +++ b/modules/angular2/src/core/di/metadata.ts @@ -1,4 +1,4 @@ -import {CONST, CONST_EXPR, stringify, isBlank, isPresent} from 'angular2/src/facade/lang'; +import {CONST, CONST_EXPR, stringify, isBlank, isPresent} from "angular2/src/facade/lang"; /** * A parameter metadata that specifies a dependency. diff --git a/modules/angular2/src/core/di/provider.ts b/modules/angular2/src/core/di/provider.ts index 39e8d0a0a1..f8fb22f735 100644 --- a/modules/angular2/src/core/di/provider.ts +++ b/modules/angular2/src/core/di/provider.ts @@ -1,10 +1,33 @@ -import {Type, isBlank, isPresent, CONST, CONST_EXPR, stringify, isArray, isType, isFunction, normalizeBool} from 'angular2/src/facade/lang'; +import { + Type, + isBlank, + isPresent, + CONST, + CONST_EXPR, + stringify, + isArray, + isType, + isFunction, + normalizeBool +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {MapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {Key} from './key'; -import {InjectMetadata, InjectableMetadata, OptionalMetadata, SelfMetadata, HostMetadata, SkipSelfMetadata, DependencyMetadata} from './metadata'; -import {NoAnnotationError, MixingMultiProvidersWithRegularProvidersError, InvalidProviderError} from './exceptions'; +import { + InjectMetadata, + InjectableMetadata, + OptionalMetadata, + SelfMetadata, + HostMetadata, + SkipSelfMetadata, + DependencyMetadata +} from './metadata'; +import { + NoAnnotationError, + MixingMultiProvidersWithRegularProvidersError, + InvalidProviderError +} from './exceptions'; import {resolveForwardRef} from './forward_ref'; /** @@ -12,9 +35,8 @@ import {resolveForwardRef} from './forward_ref'; * This is internal to Angular and should not be used directly. */ export class Dependency { - constructor( - public key: Key, public optional: boolean, public lowerBoundVisibility: any, - public upperBoundVisibility: any, public properties: any[]) {} + constructor(public key: Key, public optional: boolean, public lowerBoundVisibility: any, + public upperBoundVisibility: any, public properties: any[]) {} static fromKey(key: Key): Dependency { return new Dependency(key, false, null, null, []); } } @@ -302,9 +324,8 @@ export interface ResolvedProvider { export interface ResolvedBinding extends ResolvedProvider {} export class ResolvedProvider_ implements ResolvedBinding { - constructor( - public key: Key, public resolvedFactories: ResolvedFactory[], public multiProvider: boolean) { - } + constructor(public key: Key, public resolvedFactories: ResolvedFactory[], + public multiProvider: boolean) {} get resolvedFactory(): ResolvedFactory { return this.resolvedFactories[0]; } } @@ -523,7 +544,7 @@ export function resolveProvider(provider: Provider): ResolvedProvider { /** * Resolve a list of Providers. */ -export function resolveProviders(providers: Array<Type|Provider|any[]>): ResolvedProvider[] { +export function resolveProviders(providers: Array<Type | Provider | any[]>): ResolvedProvider[] { var normalized = _normalizeProviders(providers, []); var resolved = normalized.map(resolveProvider); return MapWrapper.values(mergeResolvedProviders(resolved, new Map<number, ResolvedProvider>())); @@ -565,8 +586,8 @@ export function mergeResolvedProviders( return normalizedProvidersMap; } -function _normalizeProviders( - providers: Array<Type|Provider|ProviderBuilder|any[]>, res: Provider[]): Provider[] { +function _normalizeProviders(providers: Array<Type | Provider | ProviderBuilder | any[]>, + res: Provider[]): Provider[] { providers.forEach(b => { if (b instanceof Type) { res.push(provide(b, {useClass: b})); @@ -660,8 +681,8 @@ function _extractToken(typeOrFunc, metadata /*any[] | any*/, params: any[][]): D } } -function _createDependency( - token, optional, lowerBoundVisibility, upperBoundVisibility, depProps): Dependency { - return new Dependency( - Key.get(token), optional, lowerBoundVisibility, upperBoundVisibility, depProps); +function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, + depProps): Dependency { + return new Dependency(Key.get(token), optional, lowerBoundVisibility, upperBoundVisibility, + depProps); } diff --git a/modules/angular2/src/core/linker.ts b/modules/angular2/src/core/linker.ts index 777a44fae6..b04229c4a4 100644 --- a/modules/angular2/src/core/linker.ts +++ b/modules/angular2/src/core/linker.ts @@ -1,5 +1,14 @@ // Public API for compiler -export {AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnChanges, OnDestroy, OnInit, DoCheck} from './linker/interfaces'; +export { + AfterContentInit, + AfterContentChecked, + AfterViewInit, + AfterViewChecked, + OnChanges, + OnDestroy, + OnInit, + DoCheck +} from './linker/interfaces'; export {DirectiveResolver} from './linker/directive_resolver'; export {ViewResolver} from './linker/view_resolver'; export {Compiler} from './linker/compiler'; diff --git a/modules/angular2/src/core/linker/directive_resolver.ts b/modules/angular2/src/core/linker/directive_resolver.ts index 1985daaa91..eba655f209 100644 --- a/modules/angular2/src/core/linker/directive_resolver.ts +++ b/modules/angular2/src/core/linker/directive_resolver.ts @@ -3,7 +3,18 @@ import {Type, isPresent, isBlank, stringify} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {DirectiveMetadata, ComponentMetadata, InputMetadata, OutputMetadata, HostBindingMetadata, HostListenerMetadata, ContentChildrenMetadata, ViewChildrenMetadata, ContentChildMetadata, ViewChildMetadata} from 'angular2/src/core/metadata'; +import { + DirectiveMetadata, + ComponentMetadata, + InputMetadata, + OutputMetadata, + HostBindingMetadata, + HostListenerMetadata, + ContentChildrenMetadata, + ViewChildrenMetadata, + ContentChildMetadata, + ViewChildMetadata +} from 'angular2/src/core/metadata'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {ReflectorReader} from 'angular2/src/core/reflection/reflector_reader'; @@ -46,9 +57,9 @@ export class DirectiveResolver { throw new BaseException(`No Directive annotation found on ${stringify(type)}`); } - private _mergeWithPropertyMetadata( - dm: DirectiveMetadata, propertyMetadata: {[key: string]: any[]}, - directiveType: Type): DirectiveMetadata { + private _mergeWithPropertyMetadata(dm: DirectiveMetadata, + propertyMetadata: {[key: string]: any[]}, + directiveType: Type): DirectiveMetadata { var inputs = []; var outputs = []; var host: {[key: string]: string} = {}; @@ -105,9 +116,9 @@ export class DirectiveResolver { return this._merge(dm, inputs, outputs, host, queries, directiveType); } - private _merge( - dm: DirectiveMetadata, inputs: string[], outputs: string[], host: {[key: string]: string}, - queries: {[key: string]: any}, directiveType: Type): DirectiveMetadata { + private _merge(dm: DirectiveMetadata, inputs: string[], outputs: string[], + host: {[key: string]: string}, queries: {[key: string]: any}, + directiveType: Type): DirectiveMetadata { var mergedInputs = isPresent(dm.inputs) ? ListWrapper.concat(dm.inputs, inputs) : inputs; var mergedOutputs; diff --git a/modules/angular2/src/core/linker/dynamic_component_loader.ts b/modules/angular2/src/core/linker/dynamic_component_loader.ts index 83f1bdbbc6..3a03fdf155 100644 --- a/modules/angular2/src/core/linker/dynamic_component_loader.ts +++ b/modules/angular2/src/core/linker/dynamic_component_loader.ts @@ -66,9 +66,8 @@ export class ComponentRef_ extends ComponentRef { /** * TODO(i): refactor into public/private fields */ - constructor( - location: ElementRef, instance: any, componentType: Type, injector: Injector, - private _dispose: () => void) { + constructor(location: ElementRef, instance: any, componentType: Type, injector: Injector, + private _dispose: () => void) { super(); this.location = location; this.instance = instance; @@ -141,9 +140,8 @@ export abstract class DynamicComponentLoader { * </my-app> * ``` */ - abstract loadAsRoot( - type: Type, overrideSelector: string, injector: Injector, onDispose?: () => void, - projectableNodes?: any[][]): Promise<ComponentRef>; + abstract loadAsRoot(type: Type, overrideSelector: string, injector: Injector, + onDispose?: () => void, projectableNodes?: any[][]): Promise<ComponentRef>; /** * Creates an instance of a Component and attaches it to a View Container located inside of the @@ -192,9 +190,9 @@ export abstract class DynamicComponentLoader { * </my-app> * ``` */ - abstract loadIntoLocation( - type: Type, hostLocation: ElementRef, anchorName: string, providers?: ResolvedProvider[], - projectableNodes?: any[][]): Promise<ComponentRef>; + abstract loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string, + providers?: ResolvedProvider[], + projectableNodes?: any[][]): Promise<ComponentRef>; /** * Creates an instance of a Component and attaches it to the View Container found at the @@ -236,21 +234,19 @@ export abstract class DynamicComponentLoader { * <child-component>Child</child-component> * ``` */ - abstract loadNextToLocation( - type: Type, location: ElementRef, providers?: ResolvedProvider[], - projectableNodes?: any[][]): Promise<ComponentRef>; + abstract loadNextToLocation(type: Type, location: ElementRef, providers?: ResolvedProvider[], + projectableNodes?: any[][]): Promise<ComponentRef>; } @Injectable() export class DynamicComponentLoader_ extends DynamicComponentLoader { constructor(private _compiler: Compiler, private _viewManager: AppViewManager) { super(); } - loadAsRoot( - type: Type, overrideSelector: string, injector: Injector, onDispose?: () => void, - projectableNodes?: any[][]): Promise<ComponentRef> { + loadAsRoot(type: Type, overrideSelector: string, injector: Injector, onDispose?: () => void, + projectableNodes?: any[][]): Promise<ComponentRef> { return this._compiler.compileInHost(type).then(hostProtoViewRef => { - var hostViewRef = this._viewManager.createRootHostView( - hostProtoViewRef, overrideSelector, injector, projectableNodes); + var hostViewRef = this._viewManager.createRootHostView(hostProtoViewRef, overrideSelector, + injector, projectableNodes); var newLocation = this._viewManager.getHostElement(hostViewRef); var component = this._viewManager.getComponent(newLocation); @@ -264,22 +260,20 @@ export class DynamicComponentLoader_ extends DynamicComponentLoader { }); } - loadIntoLocation( - type: Type, hostLocation: ElementRef, anchorName: string, - providers: ResolvedProvider[] = null, - projectableNodes: any[][] = null): Promise<ComponentRef> { + loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string, + providers: ResolvedProvider[] = null, + projectableNodes: any[][] = null): Promise<ComponentRef> { return this.loadNextToLocation( type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), providers, projectableNodes); } - loadNextToLocation( - type: Type, location: ElementRef, providers: ResolvedProvider[] = null, - projectableNodes: any[][] = null): Promise<ComponentRef> { + loadNextToLocation(type: Type, location: ElementRef, providers: ResolvedProvider[] = null, + projectableNodes: any[][] = null): Promise<ComponentRef> { return this._compiler.compileInHost(type).then(hostProtoViewRef => { var viewContainer = this._viewManager.getViewContainer(location); - var hostViewRef = viewContainer.createHostView( - hostProtoViewRef, viewContainer.length, providers, projectableNodes); + var hostViewRef = viewContainer.createHostView(hostProtoViewRef, viewContainer.length, + providers, projectableNodes); var newLocation = this._viewManager.getHostElement(hostViewRef); var component = this._viewManager.getComponent(newLocation); diff --git a/modules/angular2/src/core/linker/element.ts b/modules/angular2/src/core/linker/element.ts index 13cf611a1e..42b716e999 100644 --- a/modules/angular2/src/core/linker/element.ts +++ b/modules/angular2/src/core/linker/element.ts @@ -1,9 +1,36 @@ -import {isPresent, isBlank, Type, stringify, CONST_EXPR, StringWrapper} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + Type, + stringify, + CONST_EXPR, + StringWrapper +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {Injector, Key, Dependency, provide, Provider, ResolvedProvider, NoProviderError, AbstractProviderError, CyclicDependencyError, resolveForwardRef, Injectable} from 'angular2/src/core/di'; +import { + Injector, + Key, + Dependency, + provide, + Provider, + ResolvedProvider, + NoProviderError, + AbstractProviderError, + CyclicDependencyError, + resolveForwardRef, + Injectable +} from 'angular2/src/core/di'; import {mergeResolvedProviders} from 'angular2/src/core/di/provider'; -import {UNDEFINED, ProtoInjector, Visibility, InjectorInlineStrategy, InjectorDynamicStrategy, ProviderWithVisibility, DependencyProvider} from 'angular2/src/core/di/injector'; +import { + UNDEFINED, + ProtoInjector, + Visibility, + InjectorInlineStrategy, + InjectorDynamicStrategy, + ProviderWithVisibility, + DependencyProvider +} from 'angular2/src/core/di/injector'; import {resolveProvider, ResolvedFactory, ResolvedProvider_} from 'angular2/src/core/di/provider'; import {AttributeMetadata, QueryMetadata} from '../metadata/di'; @@ -17,14 +44,17 @@ import {ElementRef} from './element_ref'; import {Renderer} from 'angular2/src/core/render/api'; import {TemplateRef, TemplateRef_} from './template_ref'; import {DirectiveMetadata, ComponentMetadata} from '../metadata/directives'; -import {ChangeDetector, ChangeDetectorRef} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetector, + ChangeDetectorRef +} from 'angular2/src/core/change_detection/change_detection'; import {QueryList} from './query_list'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {SetterFn} from 'angular2/src/core/reflection/types'; import {AfterViewChecked} from 'angular2/src/core/linker/interfaces'; import {PipeProvider} from 'angular2/src/core/pipes/pipe_provider'; -import {ViewContainerRef_} from './view_container_ref'; +import {ViewContainerRef_} from "./view_container_ref"; import {ResolvedMetadataCache} from './resolved_metadata_cache'; var _staticKeys; @@ -51,9 +81,9 @@ export class StaticKeys { } export class DirectiveDependency extends Dependency { - constructor( - key: Key, optional: boolean, lowerBoundVisibility: Object, upperBoundVisibility: Object, - properties: any[], public attributeName: string, public queryDecorator: QueryMetadata) { + constructor(key: Key, optional: boolean, lowerBoundVisibility: Object, + upperBoundVisibility: Object, properties: any[], public attributeName: string, + public queryDecorator: QueryMetadata) { super(key, optional, lowerBoundVisibility, upperBoundVisibility, properties); this._verify(); } @@ -87,10 +117,9 @@ export class DirectiveDependency extends Dependency { } export class DirectiveProvider extends ResolvedProvider_ { - constructor( - key: Key, factory: Function, deps: Dependency[], public isComponent: boolean, - public providers: ResolvedProvider[], public viewProviders: ResolvedProvider[], - public queries: QueryMetadataWithSetter[]) { + constructor(key: Key, factory: Function, deps: Dependency[], public isComponent: boolean, + public providers: ResolvedProvider[], public viewProviders: ResolvedProvider[], + public queries: QueryMetadataWithSetter[]) { super(key, [new ResolvedFactory(factory, deps)], false); } @@ -107,8 +136,8 @@ export class DirectiveProvider extends ResolvedProvider_ { var isComponent = meta instanceof ComponentMetadata; var resolvedProviders = isPresent(meta.providers) ? Injector.resolve(meta.providers) : null; var resolvedViewProviders = meta instanceof ComponentMetadata && isPresent(meta.viewProviders) ? - Injector.resolve(meta.viewProviders) : - null; + Injector.resolve(meta.viewProviders) : + null; var queries = []; if (isPresent(meta.queries)) { StringMapWrapper.forEach(meta.queries, (meta, fieldName) => { @@ -123,8 +152,8 @@ export class DirectiveProvider extends ResolvedProvider_ { queries.push(new QueryMetadataWithSetter(null, d.queryDecorator)); } }); - return new DirectiveProvider( - rb.key, rf.factory, deps, isComponent, resolvedProviders, resolvedViewProviders, queries); + return new DirectiveProvider(rb.key, rf.factory, deps, isComponent, resolvedProviders, + resolvedViewProviders, queries); } } @@ -133,8 +162,8 @@ export class QueryMetadataWithSetter { } -function setProvidersVisibility( - providers: ResolvedProvider[], visibility: Visibility, result: Map<number, Visibility>) { +function setProvidersVisibility(providers: ResolvedProvider[], visibility: Visibility, + result: Map<number, Visibility>) { for (var i = 0; i < providers.length; i++) { result.set(providers[i].key.id, visibility); } @@ -143,9 +172,9 @@ function setProvidersVisibility( export class AppProtoElement { protoInjector: ProtoInjector; - static create( - metadataCache: ResolvedMetadataCache, index: number, attributes: {[key: string]: string}, - directiveTypes: Type[], directiveVariableBindings: {[key: string]: number}): AppProtoElement { + static create(metadataCache: ResolvedMetadataCache, index: number, + attributes: {[key: string]: string}, directiveTypes: Type[], + directiveVariableBindings: {[key: string]: number}): AppProtoElement { var componentDirProvider = null; var mergedProvidersMap: Map<number, ResolvedProvider> = new Map<number, ResolvedProvider>(); var providerVisibilityMap: Map<number, Visibility> = new Map<number, Visibility>(); @@ -167,8 +196,8 @@ export class AppProtoElement { } if (isPresent(dirProvider.viewProviders)) { mergeResolvedProviders(dirProvider.viewProviders, mergedProvidersMap); - setProvidersVisibility( - dirProvider.viewProviders, Visibility.Private, providerVisibilityMap); + setProvidersVisibility(dirProvider.viewProviders, Visibility.Private, + providerVisibilityMap); } for (var queryIdx = 0; queryIdx < dirProvider.queries.length; queryIdx++) { var q = dirProvider.queries[queryIdx]; @@ -178,24 +207,22 @@ export class AppProtoElement { if (isPresent(componentDirProvider) && isPresent(componentDirProvider.providers)) { // directive providers need to be prioritized over component providers mergeResolvedProviders(componentDirProvider.providers, mergedProvidersMap); - setProvidersVisibility( - componentDirProvider.providers, Visibility.Public, providerVisibilityMap); + setProvidersVisibility(componentDirProvider.providers, Visibility.Public, + providerVisibilityMap); } mergedProvidersMap.forEach((provider, _) => { providers.push( new ProviderWithVisibility(provider, providerVisibilityMap.get(provider.key.id))); }); - return new AppProtoElement( - isPresent(componentDirProvider), index, attributes, providers, protoQueryRefs, - directiveVariableBindings); + return new AppProtoElement(isPresent(componentDirProvider), index, attributes, providers, + protoQueryRefs, directiveVariableBindings); } - constructor( - public firstProviderIsComponent: boolean, public index: number, - public attributes: {[key: string]: string}, pwvs: ProviderWithVisibility[], - public protoQueryRefs: ProtoQueryRef[], - public directiveVariableBindings: {[key: string]: number}) { + constructor(public firstProviderIsComponent: boolean, public index: number, + public attributes: {[key: string]: string}, pwvs: ProviderWithVisibility[], + public protoQueryRefs: ProtoQueryRef[], + public directiveVariableBindings: {[key: string]: number}) { var length = pwvs.length; if (length > 0) { this.protoInjector = new ProtoInjector(pwvs); @@ -217,10 +244,9 @@ export class InjectorWithHostBoundary { } export class AppElement implements DependencyProvider, ElementRef, AfterViewChecked { - static getViewParentInjector( - parentViewType: ViewType, containerAppElement: AppElement, - imperativelyCreatedProviders: ResolvedProvider[], - rootInjector: Injector): InjectorWithHostBoundary { + static getViewParentInjector(parentViewType: ViewType, containerAppElement: AppElement, + imperativelyCreatedProviders: ResolvedProvider[], + rootInjector: Injector): InjectorWithHostBoundary { var parentInjector; var hostInjectorBoundary; switch (parentViewType) { @@ -230,25 +256,24 @@ export class AppElement implements DependencyProvider, ElementRef, AfterViewChec break; case ViewType.EMBEDDED: parentInjector = isPresent(containerAppElement.proto.protoInjector) ? - containerAppElement._injector.parent : - containerAppElement._injector; + containerAppElement._injector.parent : + containerAppElement._injector; hostInjectorBoundary = containerAppElement._injector.hostBoundary; break; case ViewType.HOST: if (isPresent(containerAppElement)) { // host view is attached to a container parentInjector = isPresent(containerAppElement.proto.protoInjector) ? - containerAppElement._injector.parent : - containerAppElement._injector; + containerAppElement._injector.parent : + containerAppElement._injector; if (isPresent(imperativelyCreatedProviders)) { var imperativeProvidersWithVisibility = imperativelyCreatedProviders.map( p => new ProviderWithVisibility(p, Visibility.Public)); // The imperative injector is similar to having an element between // the dynamic-loaded component and its parent => no boundary between // the component and imperativelyCreatedInjector. - parentInjector = new Injector( - new ProtoInjector(imperativeProvidersWithVisibility), parentInjector, true, null, - null); + parentInjector = new Injector(new ProtoInjector(imperativeProvidersWithVisibility), + parentInjector, true, null, null); hostInjectorBoundary = false; } else { hostInjectorBoundary = containerAppElement._injector.hostBoundary; @@ -271,9 +296,8 @@ export class AppElement implements DependencyProvider, ElementRef, AfterViewChec private _strategy: _ElementDirectiveStrategy; public ref: ElementRef_; - constructor( - public proto: AppProtoElement, public parentView: AppView, public parent: AppElement, - public nativeElement: any, public embeddedViewFactory: Function) { + constructor(public proto: AppProtoElement, public parentView: AppView, public parent: AppElement, + public nativeElement: any, public embeddedViewFactory: Function) { this.ref = new ElementRef_(this); var parentInjector = isPresent(parent) ? parent._injector : parentView.parentInjector; if (isPresent(this.proto.protoInjector)) { @@ -284,14 +308,14 @@ export class AppElement implements DependencyProvider, ElementRef, AfterViewChec isBoundary = parentView.hostInjectorBoundary; } this._queryStrategy = this._buildQueryStrategy(); - this._injector = new Injector( - this.proto.protoInjector, parentInjector, isBoundary, this, () => this._debugContext()); + this._injector = new Injector(this.proto.protoInjector, parentInjector, isBoundary, this, + () => this._debugContext()); // we couple ourselves to the injector strategy to avoid polymorphic calls var injectorStrategy = <any>this._injector.internalStrategy; this._strategy = injectorStrategy instanceof InjectorInlineStrategy ? - new ElementDirectiveInlineStrategy(injectorStrategy, this) : - new ElementDirectiveDynamicStrategy(injectorStrategy, this); + new ElementDirectiveInlineStrategy(injectorStrategy, this) : + new ElementDirectiveDynamicStrategy(injectorStrategy, this); this._strategy.init(); } else { this._queryStrategy = null; @@ -416,8 +440,8 @@ export class AppElement implements DependencyProvider, ElementRef, AfterViewChec private _buildQueryStrategy(): _QueryStrategy { if (this.proto.protoQueryRefs.length === 0) { return _emptyQueryStrategy; - } else if ( - this.proto.protoQueryRefs.length <= InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES) { + } else if (this.proto.protoQueryRefs.length <= + InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES) { return new InlineQueryStrategy(this); } else { return new DynamicQueryStrategy(this); @@ -636,7 +660,7 @@ class ElementDirectiveInlineStrategy implements _ElementDirectiveStrategy { isComponentKey(key: Key): boolean { return this._ei.proto.firstProviderIsComponent && isPresent(key) && - key.id === this.injectorStrategy.protoStrategy.keyId0; + key.id === this.injectorStrategy.protoStrategy.keyId0; } addDirectivesMatchingQuery(query: QueryMetadata, list: any[]): void { diff --git a/modules/angular2/src/core/linker/interfaces.ts b/modules/angular2/src/core/linker/interfaces.ts index d84abc7ee2..d59e38ab69 100644 --- a/modules/angular2/src/core/linker/interfaces.ts +++ b/modules/angular2/src/core/linker/interfaces.ts @@ -16,8 +16,13 @@ export enum LifecycleHooks { * @internal */ export var LIFECYCLE_HOOKS_VALUES = [ - LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges, - LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit, + LifecycleHooks.OnInit, + LifecycleHooks.OnDestroy, + LifecycleHooks.DoCheck, + LifecycleHooks.OnChanges, + LifecycleHooks.AfterContentInit, + LifecycleHooks.AfterContentChecked, + LifecycleHooks.AfterViewInit, LifecycleHooks.AfterViewChecked ]; diff --git a/modules/angular2/src/core/linker/view.ts b/modules/angular2/src/core/linker/view.ts index c9758dec37..ca446dbdf2 100644 --- a/modules/angular2/src/core/linker/view.ts +++ b/modules/angular2/src/core/linker/view.ts @@ -1,10 +1,31 @@ -import {ListWrapper, MapWrapper, Map, StringMapWrapper,} from 'angular2/src/facade/collection'; -import {ChangeDetector, ChangeDispatcher, DirectiveIndex, BindingTarget, Locals, ProtoChangeDetector, ChangeDetectorRef} from 'angular2/src/core/change_detection/change_detection'; +import { + ListWrapper, + MapWrapper, + Map, + StringMapWrapper, +} from 'angular2/src/facade/collection'; +import { + ChangeDetector, + ChangeDispatcher, + DirectiveIndex, + BindingTarget, + Locals, + ProtoChangeDetector, + ChangeDetectorRef +} from 'angular2/src/core/change_detection/change_detection'; import {ResolvedProvider, Injectable, Injector} from 'angular2/src/core/di'; import {DebugContext} from 'angular2/src/core/change_detection/interfaces'; import {AppProtoElement, AppElement, DirectiveProvider} from './element'; -import {isPresent, isBlank, Type, isArray, isNumber, CONST, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + Type, + isArray, + isNumber, + CONST, + CONST_EXPR +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Renderer, RootRenderer, RenderDebugInfo} from 'angular2/src/core/render/api'; import {ViewRef_, HostViewFactoryRef} from './view_ref'; @@ -57,11 +78,11 @@ export class AppView implements ChangeDispatcher { destroyed: boolean = false; - constructor( - public proto: AppProtoView, public renderer: Renderer, public viewManager: AppViewManager_, - public projectableNodes: Array<any|any[]>, public containerAppElement: AppElement, - imperativelyCreatedProviders: ResolvedProvider[], rootInjector: Injector, - public changeDetector: ChangeDetector) { + constructor(public proto: AppProtoView, public renderer: Renderer, + public viewManager: AppViewManager_, public projectableNodes: Array<any | any[]>, + public containerAppElement: AppElement, + imperativelyCreatedProviders: ResolvedProvider[], rootInjector: Injector, + public changeDetector: ChangeDetector) { this.ref = new ViewRef_(this); var injectorWithHostBoundary = AppElement.getViewParentInjector( this.proto.type, containerAppElement, imperativelyCreatedProviders, rootInjector); @@ -87,9 +108,8 @@ export class AppView implements ChangeDispatcher { this.context = context; } - init( - rootNodesOrAppElements: any[], allNodes: any[], disposables: Function[], - appElements: AppElement[]) { + init(rootNodesOrAppElements: any[], allNodes: any[], disposables: Function[], + appElements: AppElement[]) { this.rootNodesOrAppElements = rootNodesOrAppElements; this.allNodes = allNodes; this.disposables = disposables; @@ -106,18 +126,17 @@ export class AppView implements ChangeDispatcher { providerTokens.push(appEl.proto.protoInjector.getProviderAtIndex(j).key.token); } } - StringMapWrapper.forEach( - appEl.proto.directiveVariableBindings, (directiveIndex: number, name: string) => { - if (isBlank(directiveIndex)) { - localsMap.set(name, appEl.nativeElement); - } else { - localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex)); - } - }); + StringMapWrapper.forEach(appEl.proto.directiveVariableBindings, + (directiveIndex: number, name: string) => { + if (isBlank(directiveIndex)) { + localsMap.set(name, appEl.nativeElement); + } else { + localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex)); + } + }); this.renderer.setElementDebugInfo( - appEl.nativeElement, - new RenderDebugInfo( - appEl.getInjector(), appEl.getComponent(), providerTokens, localsMap)); + appEl.nativeElement, new RenderDebugInfo(appEl.getInjector(), appEl.getComponent(), + providerTokens, localsMap)); } var parentLocals = null; if (this.proto.type !== ViewType.COMPONENT) { @@ -178,14 +197,14 @@ export class AppView implements ChangeDispatcher { if (b.isElementProperty()) { this.renderer.setElementProperty(nativeElement, b.name, currentValue); } else if (b.isElementAttribute()) { - this.renderer.setElementAttribute( - nativeElement, b.name, isPresent(currentValue) ? `${currentValue}` : null); + this.renderer.setElementAttribute(nativeElement, b.name, + isPresent(currentValue) ? `${currentValue}` : null); } else if (b.isElementClass()) { this.renderer.setElementClass(nativeElement, b.name, currentValue); } else if (b.isElementStyle()) { var unit = isPresent(b.unit) ? b.unit : ''; - this.renderer.setElementStyle( - nativeElement, b.name, isPresent(currentValue) ? `${currentValue}${unit}` : null); + this.renderer.setElementStyle(nativeElement, b.name, + isPresent(currentValue) ? `${currentValue}${unit}` : null); } else { throw new BaseException('Unsupported directive record'); } @@ -214,8 +233,8 @@ export class AppView implements ChangeDispatcher { } } - getDebugContext(appElement: AppElement, elementIndex: number, directiveIndex: number): - DebugContext { + getDebugContext(appElement: AppElement, elementIndex: number, + directiveIndex: number): DebugContext { try { if (isBlank(appElement) && elementIndex < this.appElements.length) { appElement = this.appElements[elementIndex]; @@ -228,9 +247,8 @@ export class AppView implements ChangeDispatcher { isPresent(directiveIndex) ? appElement.getDirectiveAtIndex(directiveIndex) : null; var injector = isPresent(appElement) ? appElement.getInjector() : null; - return new DebugContext( - element, componentElement, directive, this.context, _localsToStringMap(this.locals), - injector); + return new DebugContext(element, componentElement, directive, this.context, + _localsToStringMap(this.locals), injector); } catch (e) { // TODO: vsavkin log the exception once we have a good way to log errors and warnings @@ -277,9 +295,8 @@ function _localsToStringMap(locals: Locals): {[key: string]: any} { * */ export class AppProtoView { - static create( - metadataCache: ResolvedMetadataCache, type: ViewType, pipes: Type[], - templateVariableBindings: {[key: string]: string}): AppProtoView { + static create(metadataCache: ResolvedMetadataCache, type: ViewType, pipes: Type[], + templateVariableBindings: {[key: string]: string}): AppProtoView { var protoPipes = null; if (isPresent(pipes) && pipes.length > 0) { var boundPipes = ListWrapper.createFixedSize(pipes.length); @@ -291,9 +308,8 @@ export class AppProtoView { return new AppProtoView(type, protoPipes, templateVariableBindings); } - constructor( - public type: ViewType, public protoPipes: ProtoPipes, - public templateVariableBindings: {[key: string]: string}) {} + constructor(public type: ViewType, public protoPipes: ProtoPipes, + public templateVariableBindings: {[key: string]: string}) {} } @@ -345,8 +361,8 @@ export function findLastRenderNode(node: any): any { return lastNode; } -export function checkSlotCount( - componentName: string, expectedSlotCount: number, projectableNodes: any[][]): void { +export function checkSlotCount(componentName: string, expectedSlotCount: number, + projectableNodes: any[][]): void { var givenSlotCount = isPresent(projectableNodes) ? projectableNodes.length : 0; if (givenSlotCount < expectedSlotCount) { throw new BaseException( diff --git a/modules/angular2/src/core/linker/view_container_ref.ts b/modules/angular2/src/core/linker/view_container_ref.ts index a58a420d74..759c38d3cc 100644 --- a/modules/angular2/src/core/linker/view_container_ref.ts +++ b/modules/angular2/src/core/linker/view_container_ref.ts @@ -7,7 +7,14 @@ import {AppElement} from './element'; import {ElementRef, ElementRef_} from './element_ref'; import {TemplateRef, TemplateRef_} from './template_ref'; -import {EmbeddedViewRef, HostViewRef, HostViewFactoryRef, HostViewFactoryRef_, ViewRef, ViewRef_} from './view_ref'; +import { + EmbeddedViewRef, + HostViewRef, + HostViewFactoryRef, + HostViewFactoryRef_, + ViewRef, + ViewRef_ +} from './view_ref'; /** * Represents a container where one or more Views can be attached. @@ -79,9 +86,9 @@ export abstract class ViewContainerRef { * * Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component. */ - abstract createHostView( - hostViewFactoryRef: HostViewFactoryRef, index?: number, - dynamicallyCreatedProviders?: ResolvedProvider[], projectableNodes?: any[][]): HostViewRef; + abstract createHostView(hostViewFactoryRef: HostViewFactoryRef, index?: number, + dynamicallyCreatedProviders?: ResolvedProvider[], + projectableNodes?: any[][]): HostViewRef; /** * Inserts a View identified by a {@link ViewRef} into the container at the specified `index`. @@ -132,15 +139,13 @@ export class ViewContainerRef_ extends ViewContainerRef { return vm.createEmbeddedViewInContainer(this._element.ref, index, templateRef); } - createHostView( - hostViewFactoryRef: HostViewFactoryRef, index: number = -1, - dynamicallyCreatedProviders: ResolvedProvider[] = null, - projectableNodes: any[][] = null): HostViewRef { + createHostView(hostViewFactoryRef: HostViewFactoryRef, index: number = -1, + dynamicallyCreatedProviders: ResolvedProvider[] = null, + projectableNodes: any[][] = null): HostViewRef { if (index == -1) index = this.length; var vm = this._element.parentView.viewManager; - return vm.createHostViewInContainer( - this._element.ref, index, hostViewFactoryRef, dynamicallyCreatedProviders, - projectableNodes); + return vm.createHostViewInContainer(this._element.ref, index, hostViewFactoryRef, + dynamicallyCreatedProviders, projectableNodes); } // TODO(i): refactor insert+remove into move diff --git a/modules/angular2/src/core/linker/view_manager.ts b/modules/angular2/src/core/linker/view_manager.ts index 76bb558e39..787012d20e 100644 --- a/modules/angular2/src/core/linker/view_manager.ts +++ b/modules/angular2/src/core/linker/view_manager.ts @@ -1,11 +1,25 @@ -import {Injector, Inject, Provider, Injectable, ResolvedProvider, forwardRef} from 'angular2/src/core/di'; +import { + Injector, + Inject, + Provider, + Injectable, + ResolvedProvider, + forwardRef +} from 'angular2/src/core/di'; import {isPresent, isBlank, isArray} from 'angular2/src/facade/lang'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {BaseException} from 'angular2/src/facade/exceptions'; import {AppView, HostViewFactory, flattenNestedViewRenderNodes, findLastRenderNode} from './view'; import {AppElement} from './element'; import {ElementRef, ElementRef_} from './element_ref'; -import {HostViewFactoryRef, HostViewFactoryRef_, EmbeddedViewRef, HostViewRef, ViewRef, ViewRef_} from './view_ref'; +import { + HostViewFactoryRef, + HostViewFactoryRef_, + EmbeddedViewRef, + HostViewRef, + ViewRef, + ViewRef_ +} from './view_ref'; import {ViewContainerRef} from './view_container_ref'; import {TemplateRef, TemplateRef_} from './template_ref'; import {RootRenderer, RenderComponentType} from 'angular2/src/core/render/api'; @@ -38,8 +52,8 @@ export abstract class AppViewManager { * Throws an exception if the specified `hostLocation` is not a Host Element of a Component, or if * variable `variableName` couldn't be found in the Component View of this Component. */ - abstract getNamedElementInComponentView(hostLocation: ElementRef, variableName: string): - ElementRef; + abstract getNamedElementInComponentView(hostLocation: ElementRef, + variableName: string): ElementRef; /** * Returns the component instance for the provided Host Element. @@ -99,9 +113,8 @@ export abstract class AppViewManager { * ng.bootstrap(MyApp); * ``` */ - abstract createRootHostView( - hostViewFactoryRef: HostViewFactoryRef, overrideSelector: string, injector: Injector, - projectableNodes?: any[][]): HostViewRef; + abstract createRootHostView(hostViewFactoryRef: HostViewFactoryRef, overrideSelector: string, + injector: Injector, projectableNodes?: any[][]): HostViewRef; /** * Destroys the Host View created via {@link AppViewManager#createRootHostView}. @@ -124,8 +137,8 @@ export abstract class AppViewManager { */ // TODO(i): this low-level version of ViewContainerRef#createEmbeddedView doesn't add anything new // we should make it private, otherwise we have two apis to do the same thing. - abstract createEmbeddedViewInContainer( - viewContainerLocation: ElementRef, index: number, templateRef: TemplateRef): EmbeddedViewRef; + abstract createEmbeddedViewInContainer(viewContainerLocation: ElementRef, index: number, + templateRef: TemplateRef): EmbeddedViewRef; /** * Instantiates a single {@link Component} and inserts its Host View into the View Container @@ -158,8 +171,8 @@ export abstract class AppViewManager { * See {@link AppViewManager#detachViewInContainer}. */ // TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer - abstract attachViewInContainer( - viewContainerLocation: ElementRef, index: number, viewRef: EmbeddedViewRef): EmbeddedViewRef; + abstract attachViewInContainer(viewContainerLocation: ElementRef, index: number, + viewRef: EmbeddedViewRef): EmbeddedViewRef; /** * See {@link AppViewManager#attachViewInContainer}. @@ -207,14 +220,13 @@ export class AppViewManager_ extends AppViewManager { /** @internal */ _createRootHostViewScope: WtfScopeFn = wtfCreateScope('AppViewManager#createRootHostView()'); - createRootHostView( - hostViewFactoryRef: HostViewFactoryRef, overrideSelector: string, injector: Injector, - projectableNodes: any[][] = null): HostViewRef { + createRootHostView(hostViewFactoryRef: HostViewFactoryRef, overrideSelector: string, + injector: Injector, projectableNodes: any[][] = null): HostViewRef { var s = this._createRootHostViewScope(); var hostViewFactory = (<HostViewFactoryRef_>hostViewFactoryRef).internalHostViewFactory; var selector = isPresent(overrideSelector) ? overrideSelector : hostViewFactory.selector; - var view = hostViewFactory.viewFactory( - this._renderer, this, null, projectableNodes, selector, null, injector); + var view = hostViewFactory.viewFactory(this._renderer, this, null, projectableNodes, selector, + null, injector); return wtfLeave(s, view.ref); } @@ -233,13 +245,13 @@ export class AppViewManager_ extends AppViewManager { _createEmbeddedViewInContainerScope: WtfScopeFn = wtfCreateScope('AppViewManager#createEmbeddedViewInContainer()'); - createEmbeddedViewInContainer( - viewContainerLocation: ElementRef, index: number, templateRef: TemplateRef): EmbeddedViewRef { + createEmbeddedViewInContainer(viewContainerLocation: ElementRef, index: number, + templateRef: TemplateRef): EmbeddedViewRef { var s = this._createEmbeddedViewInContainerScope(); var contextEl = (<TemplateRef_>templateRef).elementRef.internalElement; - var view: AppView = contextEl.embeddedViewFactory( - contextEl.parentView.renderer, this, contextEl, contextEl.parentView.projectableNodes, null, - null, null); + var view: AppView = + contextEl.embeddedViewFactory(contextEl.parentView.renderer, this, contextEl, + contextEl.parentView.projectableNodes, null, null, null); this._attachViewToContainer(view, (<ElementRef_>viewContainerLocation).internalElement, index); return wtfLeave(s, view.ref); } @@ -248,9 +260,10 @@ export class AppViewManager_ extends AppViewManager { _createHostViewInContainerScope: WtfScopeFn = wtfCreateScope('AppViewManager#createHostViewInContainer()'); - createHostViewInContainer( - viewContainerLocation: ElementRef, index: number, hostViewFactoryRef: HostViewFactoryRef, - dynamicallyCreatedProviders: ResolvedProvider[], projectableNodes: any[][]): HostViewRef { + createHostViewInContainer(viewContainerLocation: ElementRef, index: number, + hostViewFactoryRef: HostViewFactoryRef, + dynamicallyCreatedProviders: ResolvedProvider[], + projectableNodes: any[][]): HostViewRef { var s = this._createHostViewInContainerScope(); // TODO(tbosch): This should be specifiable via an additional argument! var viewContainerLocation_ = <ElementRef_>viewContainerLocation; @@ -278,12 +291,12 @@ export class AppViewManager_ extends AppViewManager { _attachViewInContainerScope = wtfCreateScope('AppViewMananger#attachViewInContainer()'); // TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer - attachViewInContainer(viewContainerLocation: ElementRef, index: number, viewRef: ViewRef): - EmbeddedViewRef { + attachViewInContainer(viewContainerLocation: ElementRef, index: number, + viewRef: ViewRef): EmbeddedViewRef { var viewRef_ = <ViewRef_>viewRef; var s = this._attachViewInContainerScope(); - this._attachViewToContainer( - viewRef_.internalView, (<ElementRef_>viewContainerLocation).internalElement, index); + this._attachViewToContainer(viewRef_.internalView, + (<ElementRef_>viewContainerLocation).internalElement, index); return wtfLeave(s, viewRef_); } @@ -305,10 +318,10 @@ export class AppViewManager_ extends AppViewManager { onViewDestroyed(view: AppView) {} /** @internal */ - createRenderComponentType(encapsulation: ViewEncapsulation, styles: Array<string|any[]>): - RenderComponentType { - return new RenderComponentType( - `${this._appId}-${this._nextCompTypeId++}`, encapsulation, styles); + createRenderComponentType(encapsulation: ViewEncapsulation, + styles: Array<string | any[]>): RenderComponentType { + return new RenderComponentType(`${this._appId}-${this._nextCompTypeId++}`, encapsulation, + styles); } private _attachViewToContainer(view: AppView, vcAppElement: AppElement, viewIndex: number) { @@ -325,15 +338,15 @@ export class AppViewManager_ extends AppViewManager { if (viewIndex > 0) { var prevView = nestedViews[viewIndex - 1]; refNode = prevView.rootNodesOrAppElements.length > 0 ? - prevView.rootNodesOrAppElements[prevView.rootNodesOrAppElements.length - 1] : - null; + prevView.rootNodesOrAppElements[prevView.rootNodesOrAppElements.length - 1] : + null; } else { refNode = vcAppElement.nativeElement; } if (isPresent(refNode)) { var refRenderNode = findLastRenderNode(refNode); - view.renderer.attachViewAfter( - refRenderNode, flattenNestedViewRenderNodes(view.rootNodesOrAppElements)); + view.renderer.attachViewAfter(refRenderNode, + flattenNestedViewRenderNodes(view.rootNodesOrAppElements)); } // TODO: This is only needed when a view is destroyed, // not when it is detached for reordering with ng-for... diff --git a/modules/angular2/src/core/linker/view_resolver.ts b/modules/angular2/src/core/linker/view_resolver.ts index c1a2a830a4..56340b1363 100644 --- a/modules/angular2/src/core/linker/view_resolver.ts +++ b/modules/angular2/src/core/linker/view_resolver.ts @@ -58,25 +58,25 @@ export class ViewResolver { `Component '${stringify(component)}' must have either 'template' or 'templateUrl' set.`); } else if (isPresent(compMeta.template) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('template', component); + this._throwMixingViewAndComponent("template", component); } else if (isPresent(compMeta.templateUrl) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('templateUrl', component); + this._throwMixingViewAndComponent("templateUrl", component); } else if (isPresent(compMeta.directives) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('directives', component); + this._throwMixingViewAndComponent("directives", component); } else if (isPresent(compMeta.pipes) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('pipes', component); + this._throwMixingViewAndComponent("pipes", component); } else if (isPresent(compMeta.encapsulation) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('encapsulation', component); + this._throwMixingViewAndComponent("encapsulation", component); } else if (isPresent(compMeta.styles) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('styles', component); + this._throwMixingViewAndComponent("styles", component); } else if (isPresent(compMeta.styleUrls) && isPresent(viewMeta)) { - this._throwMixingViewAndComponent('styleUrls', component); + this._throwMixingViewAndComponent("styleUrls", component); } else if (isPresent(viewMeta)) { return viewMeta; diff --git a/modules/angular2/src/core/metadata.ts b/modules/angular2/src/core/metadata.ts index 50d1e0bc27..fc671a12eb 100644 --- a/modules/angular2/src/core/metadata.ts +++ b/modules/angular2/src/core/metadata.ts @@ -3,20 +3,58 @@ * to be used by the decorator versions of these annotations. */ -export {QueryMetadata, ContentChildrenMetadata, ContentChildMetadata, ViewChildrenMetadata, ViewQueryMetadata, ViewChildMetadata, AttributeMetadata} from './metadata/di'; +export { + QueryMetadata, + ContentChildrenMetadata, + ContentChildMetadata, + ViewChildrenMetadata, + ViewQueryMetadata, + ViewChildMetadata, + AttributeMetadata +} from './metadata/di'; -export {ComponentMetadata, DirectiveMetadata, PipeMetadata, InputMetadata, OutputMetadata, HostBindingMetadata, HostListenerMetadata} from './metadata/directives'; +export { + ComponentMetadata, + DirectiveMetadata, + PipeMetadata, + InputMetadata, + OutputMetadata, + HostBindingMetadata, + HostListenerMetadata +} from './metadata/directives'; export {ViewMetadata, ViewEncapsulation} from './metadata/view'; -import {QueryMetadata, ContentChildrenMetadata, ContentChildMetadata, ViewChildrenMetadata, ViewChildMetadata, ViewQueryMetadata, AttributeMetadata} from './metadata/di'; +import { + QueryMetadata, + ContentChildrenMetadata, + ContentChildMetadata, + ViewChildrenMetadata, + ViewChildMetadata, + ViewQueryMetadata, + AttributeMetadata +} from './metadata/di'; -import {ComponentMetadata, DirectiveMetadata, PipeMetadata, InputMetadata, OutputMetadata, HostBindingMetadata, HostListenerMetadata} from './metadata/directives'; +import { + ComponentMetadata, + DirectiveMetadata, + PipeMetadata, + InputMetadata, + OutputMetadata, + HostBindingMetadata, + HostListenerMetadata +} from './metadata/directives'; import {ViewMetadata, ViewEncapsulation} from './metadata/view'; import {ChangeDetectionStrategy} from 'angular2/src/core/change_detection/change_detection'; -import {makeDecorator, makeParamDecorator, makePropDecorator, TypeDecorator, Class} from './util/decorators'; +import { + makeDecorator, + makeParamDecorator, + makePropDecorator, + TypeDecorator, + Class +} from './util/decorators'; import {Type} from 'angular2/src/facade/lang'; /** @@ -38,8 +76,8 @@ export interface ComponentDecorator extends TypeDecorator { View(obj: { templateUrl?: string, template?: string, - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, renderer?: string, styles?: string[], styleUrls?: string[], @@ -58,8 +96,8 @@ export interface ViewDecorator extends TypeDecorator { View(obj: { templateUrl?: string, template?: string, - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, renderer?: string, styles?: string[], styleUrls?: string[], @@ -176,8 +214,8 @@ export interface ComponentFactory { template?: string, styleUrls?: string[], styles?: string[], - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, encapsulation?: ViewEncapsulation }): ComponentDecorator; new (obj: { @@ -201,8 +239,8 @@ export interface ComponentFactory { template?: string, styleUrls?: string[], styles?: string[], - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, encapsulation?: ViewEncapsulation }): ComponentMetadata; } @@ -253,8 +291,8 @@ export interface ViewFactory { (obj: { templateUrl?: string, template?: string, - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, encapsulation?: ViewEncapsulation, styles?: string[], styleUrls?: string[], @@ -262,8 +300,8 @@ export interface ViewFactory { new (obj: { templateUrl?: string, template?: string, - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, encapsulation?: ViewEncapsulation, styles?: string[], styleUrls?: string[], @@ -353,40 +391,40 @@ export interface AttributeFactory { * ``` */ export interface QueryFactory { - (selector: Type|string, {descendants}?: {descendants?: boolean}): ParameterDecorator; - new (selector: Type|string, {descendants}?: {descendants?: boolean}): QueryMetadata; + (selector: Type | string, {descendants}?: {descendants?: boolean}): ParameterDecorator; + new (selector: Type | string, {descendants}?: {descendants?: boolean}): QueryMetadata; } /** * Factory for {@link ContentChildren}. */ export interface ContentChildrenFactory { - (selector: Type|string, {descendants}?: {descendants?: boolean}): any; - new (selector: Type|string, {descendants}?: {descendants?: boolean}): ContentChildrenMetadata; + (selector: Type | string, {descendants}?: {descendants?: boolean}): any; + new (selector: Type | string, {descendants}?: {descendants?: boolean}): ContentChildrenMetadata; } /** * Factory for {@link ContentChild}. */ export interface ContentChildFactory { - (selector: Type|string): any; - new (selector: Type|string): ContentChildFactory; + (selector: Type | string): any; + new (selector: Type | string): ContentChildFactory; } /** * Factory for {@link ViewChildren}. */ export interface ViewChildrenFactory { - (selector: Type|string): any; - new (selector: Type|string): ViewChildrenMetadata; + (selector: Type | string): any; + new (selector: Type | string): ViewChildrenMetadata; } /** * Factory for {@link ViewChild}. */ export interface ViewChildFactory { - (selector: Type|string): any; - new (selector: Type|string): ViewChildFactory; + (selector: Type | string): any; + new (selector: Type | string): ViewChildFactory; } diff --git a/modules/angular2/src/core/metadata/di.ts b/modules/angular2/src/core/metadata/di.ts index f9a93110dd..aa77c837dc 100644 --- a/modules/angular2/src/core/metadata/di.ts +++ b/modules/angular2/src/core/metadata/di.ts @@ -150,9 +150,8 @@ export class QueryMetadata extends DependencyMetadata { descendants: boolean; first: boolean; - constructor( - private _selector: Type|string, - {descendants = false, first = false}: {descendants?: boolean, first?: boolean} = {}) { + constructor(private _selector: Type | string, + {descendants = false, first = false}: {descendants?: boolean, first?: boolean} = {}) { super(); this.descendants = descendants; this.first = first; @@ -205,7 +204,7 @@ export class QueryMetadata extends DependencyMetadata { */ @CONST() export class ContentChildrenMetadata extends QueryMetadata { - constructor(_selector: Type|string, {descendants = false}: {descendants?: boolean} = {}) { + constructor(_selector: Type | string, {descendants = false}: {descendants?: boolean} = {}) { super(_selector, {descendants: descendants}); } } @@ -233,7 +232,7 @@ export class ContentChildrenMetadata extends QueryMetadata { */ @CONST() export class ContentChildMetadata extends QueryMetadata { - constructor(_selector: Type|string) { super(_selector, {descendants: true, first: true}); } + constructor(_selector: Type | string) { super(_selector, {descendants: true, first: true}); } } /** @@ -273,9 +272,8 @@ export class ContentChildMetadata extends QueryMetadata { */ @CONST() export class ViewQueryMetadata extends QueryMetadata { - constructor( - _selector: Type|string, - {descendants = false, first = false}: {descendants?: boolean, first?: boolean} = {}) { + constructor(_selector: Type | string, + {descendants = false, first = false}: {descendants?: boolean, first?: boolean} = {}) { super(_selector, {descendants: descendants, first: first}); } @@ -310,7 +308,7 @@ export class ViewQueryMetadata extends QueryMetadata { */ @CONST() export class ViewChildrenMetadata extends ViewQueryMetadata { - constructor(_selector: Type|string) { super(_selector, {descendants: true}); } + constructor(_selector: Type | string) { super(_selector, {descendants: true}); } } /** @@ -337,5 +335,5 @@ export class ViewChildrenMetadata extends ViewQueryMetadata { */ @CONST() export class ViewChildMetadata extends ViewQueryMetadata { - constructor(_selector: Type|string) { super(_selector, {descendants: true, first: true}); } + constructor(_selector: Type | string) { super(_selector, {descendants: true, first: true}); } } diff --git a/modules/angular2/src/core/metadata/directives.ts b/modules/angular2/src/core/metadata/directives.ts index 13b2e5f6f8..0f69f35dbf 100644 --- a/modules/angular2/src/core/metadata/directives.ts +++ b/modules/angular2/src/core/metadata/directives.ts @@ -731,20 +731,19 @@ export class DirectiveMetadata extends InjectableMetadata { */ queries: {[key: string]: any}; - constructor( - {selector, inputs, outputs, properties, events, host, bindings, providers, exportAs, - queries}: { - selector?: string, - inputs?: string[], - outputs?: string[], - properties?: string[], - events?: string[], - host?: {[key: string]: string}, - providers?: any[], - /** @deprecated */ bindings?: any[], - exportAs?: string, - queries?: {[key: string]: any} - } = {}) { + constructor({selector, inputs, outputs, properties, events, host, bindings, providers, exportAs, + queries}: { + selector?: string, + inputs?: string[], + outputs?: string[], + properties?: string[], + events?: string[], + host?: {[key: string]: string}, + providers?: any[], + /** @deprecated */ bindings?: any[], + exportAs?: string, + queries?: {[key: string]: any} + } = {}) { super(); this.selector = selector; this._inputs = inputs; @@ -872,33 +871,16 @@ export class ComponentMetadata extends DirectiveMetadata { styles: string[]; - directives: Array<Type|any[]>; + directives: Array<Type | any[]>; - pipes: Array<Type|any[]>; + pipes: Array<Type | any[]>; encapsulation: ViewEncapsulation; - constructor({selector, - inputs, - outputs, - properties, - events, - host, - exportAs, - moduleId, - bindings, - providers, - viewBindings, - viewProviders, - changeDetection = ChangeDetectionStrategy.Default, - queries, - templateUrl, - template, - styleUrls, - styles, - directives, - pipes, - encapsulation}: { + constructor({selector, inputs, outputs, properties, events, host, exportAs, moduleId, bindings, + providers, viewBindings, viewProviders, + changeDetection = ChangeDetectionStrategy.Default, queries, templateUrl, template, + styleUrls, styles, directives, pipes, encapsulation}: { selector?: string, inputs?: string[], outputs?: string[], @@ -917,8 +899,8 @@ export class ComponentMetadata extends DirectiveMetadata { template?: string, styleUrls?: string[], styles?: string[], - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, encapsulation?: ViewEncapsulation } = {}) { super({ diff --git a/modules/angular2/src/core/metadata/view.ts b/modules/angular2/src/core/metadata/view.ts index 79d3e39698..a0b00722d1 100644 --- a/modules/angular2/src/core/metadata/view.ts +++ b/modules/angular2/src/core/metadata/view.ts @@ -111,9 +111,9 @@ export class ViewMetadata { * } * ``` */ - directives: Array<Type|any[]>; + directives: Array<Type | any[]>; - pipes: Array<Type|any[]>; + pipes: Array<Type | any[]>; /** * Specify how the template and the styles should be encapsulated. @@ -126,8 +126,8 @@ export class ViewMetadata { constructor({templateUrl, template, directives, pipes, encapsulation, styles, styleUrls}: { templateUrl?: string, template?: string, - directives?: Array<Type|any[]>, - pipes?: Array<Type|any[]>, + directives?: Array<Type | any[]>, + pipes?: Array<Type | any[]>, encapsulation?: ViewEncapsulation, styles?: string[], styleUrls?: string[], diff --git a/modules/angular2/src/core/pipes/pipe_provider.ts b/modules/angular2/src/core/pipes/pipe_provider.ts index 95b381b9d1..9090c50208 100644 --- a/modules/angular2/src/core/pipes/pipe_provider.ts +++ b/modules/angular2/src/core/pipes/pipe_provider.ts @@ -4,16 +4,15 @@ import {Key, ResolvedProvider, Provider} from 'angular2/src/core/di'; import {PipeMetadata} from '../metadata/directives'; export class PipeProvider extends ResolvedProvider_ { - constructor( - public name: string, public pure: boolean, key: Key, resolvedFactories: ResolvedFactory[], - multiBinding: boolean) { + constructor(public name: string, public pure: boolean, key: Key, + resolvedFactories: ResolvedFactory[], multiBinding: boolean) { super(key, resolvedFactories, multiBinding); } static createFromType(type: Type, metadata: PipeMetadata): PipeProvider { var provider = new Provider(type, {useClass: type}); var rb = resolveProvider(provider); - return new PipeProvider( - metadata.name, metadata.pure, rb.key, rb.resolvedFactories, rb.multiProvider); + return new PipeProvider(metadata.name, metadata.pure, rb.key, rb.resolvedFactories, + rb.multiProvider); } } diff --git a/modules/angular2/src/core/pipes/pipes.ts b/modules/angular2/src/core/pipes/pipes.ts index cebbaf2ad6..08bbbb9c92 100644 --- a/modules/angular2/src/core/pipes/pipes.ts +++ b/modules/angular2/src/core/pipes/pipes.ts @@ -1,7 +1,14 @@ import {isBlank, isPresent, CONST, Type} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; -import {Injectable, OptionalMetadata, SkipSelfMetadata, Provider, Injector, bind} from 'angular2/src/core/di'; +import { + Injectable, + OptionalMetadata, + SkipSelfMetadata, + Provider, + Injector, + bind +} from 'angular2/src/core/di'; import {PipeProvider} from './pipe_provider'; import * as cd from 'angular2/src/core/change_detection/pipes'; diff --git a/modules/angular2/src/core/platform_common_providers.ts b/modules/angular2/src/core/platform_common_providers.ts index defa5483fc..5010c11b6d 100644 --- a/modules/angular2/src/core/platform_common_providers.ts +++ b/modules/angular2/src/core/platform_common_providers.ts @@ -12,7 +12,9 @@ function _reflector(): Reflector { /** * A default set of providers which should be included in any Angular platform. */ -export const PLATFORM_COMMON_PROVIDERS: Array<Type|Provider|any[]> = CONST_EXPR([ +export const PLATFORM_COMMON_PROVIDERS: Array<Type | Provider | any[]> = CONST_EXPR([ new Provider(Reflector, {useFactory: _reflector, deps: []}), - new Provider(ReflectorReader, {useExisting: Reflector}), TestabilityRegistry, Console + new Provider(ReflectorReader, {useExisting: Reflector}), + TestabilityRegistry, + Console ]); \ No newline at end of file diff --git a/modules/angular2/src/core/platform_directives_and_pipes.ts b/modules/angular2/src/core/platform_directives_and_pipes.ts index bd725c789e..58c6a9cb3b 100644 --- a/modules/angular2/src/core/platform_directives_and_pipes.ts +++ b/modules/angular2/src/core/platform_directives_and_pipes.ts @@ -1,5 +1,5 @@ -import {OpaqueToken} from 'angular2/src/core/di'; -import {CONST_EXPR} from 'angular2/src/facade/lang'; +import {OpaqueToken} from "angular2/src/core/di"; +import {CONST_EXPR} from "angular2/src/facade/lang"; /** * A token that can be provided when bootstraping an application to make an array of directives @@ -25,7 +25,7 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; * bootstrap(MyComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [OtherDirective], multi:true})]); * ``` */ -export const PLATFORM_DIRECTIVES: OpaqueToken = CONST_EXPR(new OpaqueToken('Platform Directives')); +export const PLATFORM_DIRECTIVES: OpaqueToken = CONST_EXPR(new OpaqueToken("Platform Directives")); /** * A token that can be provided when bootstraping an application to make an array of pipes @@ -50,4 +50,4 @@ export const PLATFORM_DIRECTIVES: OpaqueToken = CONST_EXPR(new OpaqueToken('Plat * bootstrap(MyComponent, [provide(PLATFORM_PIPES, {useValue: [OtherPipe], multi:true})]); * ``` */ -export const PLATFORM_PIPES: OpaqueToken = CONST_EXPR(new OpaqueToken('Platform Pipes')); +export const PLATFORM_PIPES: OpaqueToken = CONST_EXPR(new OpaqueToken("Platform Pipes")); diff --git a/modules/angular2/src/core/profile/profile.ts b/modules/angular2/src/core/profile/profile.ts index e8a6252eab..eaefd058c9 100644 --- a/modules/angular2/src/core/profile/profile.ts +++ b/modules/angular2/src/core/profile/profile.ts @@ -1,6 +1,6 @@ export {WtfScopeFn} from './wtf_impl'; -import * as impl from './wtf_impl'; +import * as impl from "./wtf_impl"; // Change exports to const once https://github.com/angular/ts2dart/issues/150 @@ -53,7 +53,7 @@ export var wtfCreateScope: (signature: string, flags?: any) => impl.WtfScopeFn = * * Returns the `returnValue for easy chaining. */ -export var wtfLeave: <T>(scope: any, returnValue?: T) => T = +export var wtfLeave:<T>(scope: any, returnValue?: T) => T = wtfEnabled ? impl.leave : (s: any, r?: any) => r; /** @@ -76,5 +76,5 @@ export var wtfStartTimeRange: (rangeType: string, action: string) => any = * [range] is the return value from [wtfStartTimeRange] Async ranges only work if WTF has been * enabled. */ -export var wtfEndTimeRange: (range: any) => void = - wtfEnabled ? impl.endTimeRange : (r: any) => null; +export var wtfEndTimeRange: (range: any) => void = wtfEnabled ? impl.endTimeRange : (r: any) => + null; diff --git a/modules/angular2/src/core/reflection/reflection_capabilities.ts b/modules/angular2/src/core/reflection/reflection_capabilities.ts index 6dbbe7ceb3..999471999a 100644 --- a/modules/angular2/src/core/reflection/reflection_capabilities.ts +++ b/modules/angular2/src/core/reflection/reflection_capabilities.ts @@ -1,4 +1,11 @@ -import {Type, isPresent, isFunction, global, stringify, ConcreteType} from 'angular2/src/facade/lang'; +import { + Type, + isPresent, + isFunction, + global, + stringify, + ConcreteType +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {GetterFn, SetterFn, MethodFn} from './types'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; @@ -65,29 +72,23 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { case 17: return (a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any) => - new t( - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17); + new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, + a17); case 18: return (a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, - a18: any) => - new t( - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, - a18); + a18: any) => new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, + a16, a17, a18); case 19: return (a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, - a18: any, a19: any) => - new t( - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, - a18, a19); + a18: any, a19: any) => new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, + a14, a15, a16, a17, a18, a19); case 20: return (a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, - a18: any, a19: any, a20: any) => - new t( - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, - a18, a19, a20); + a18: any, a19: any, a20: any) => new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, + a12, a13, a14, a15, a16, a17, a18, a19, a20); }; throw new Error( @@ -173,7 +174,7 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { } interfaces(type: Type): any[] { - throw new BaseException('JavaScript does not support interfaces'); + throw new BaseException("JavaScript does not support interfaces"); } getter(name: string): GetterFn { return <GetterFn>new Function('o', 'return o.' + name + ';'); } diff --git a/modules/angular2/src/core/reflection/reflector.ts b/modules/angular2/src/core/reflection/reflector.ts index 3cf9119371..f8253c94bc 100644 --- a/modules/angular2/src/core/reflection/reflector.ts +++ b/modules/angular2/src/core/reflection/reflector.ts @@ -1,6 +1,13 @@ import {Type, isPresent, stringify} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {ListWrapper, Map, MapWrapper, Set, SetWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; +import { + ListWrapper, + Map, + MapWrapper, + Set, + SetWrapper, + StringMapWrapper +} from 'angular2/src/facade/collection'; import {SetterFn, GetterFn, MethodFn} from './types'; import {ReflectorReader} from './reflector_reader'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; @@ -11,9 +18,8 @@ export {PlatformReflectionCapabilities} from './platform_reflection_capabilities * Reflective information about a symbol, including annotations, interfaces, and other metadata. */ export class ReflectionInfo { - constructor( - public annotations?: any[], public parameters?: any[][], public factory?: Function, - public interfaces?: any[], public propMetadata?: {[key: string]: any[]}) {} + constructor(public annotations?: any[], public parameters?: any[][], public factory?: Function, + public interfaces?: any[], public propMetadata?: {[key: string]: any[]}) {} } /** diff --git a/modules/angular2/src/core/render/api.ts b/modules/angular2/src/core/render/api.ts index 381c99d1fc..2522986db9 100644 --- a/modules/angular2/src/core/render/api.ts +++ b/modules/angular2/src/core/render/api.ts @@ -2,15 +2,13 @@ import {ViewEncapsulation} from 'angular2/src/core/metadata/view'; import {Injector, Injectable} from 'angular2/src/core/di'; export class RenderComponentType { - constructor( - public id: string, public encapsulation: ViewEncapsulation, - public styles: Array<string|any[]>) {} + constructor(public id: string, public encapsulation: ViewEncapsulation, + public styles: Array<string | any[]>) {} } export class RenderDebugInfo { - constructor( - public injector: Injector, public component: any, public providerTokens: any[], - public locals: Map<string, any>) {} + constructor(public injector: Injector, public component: any, public providerTokens: any[], + public locals: Map<string, any>) {} } export interface ParentRenderer { renderComponent(componentType: RenderComponentType): Renderer; } @@ -42,15 +40,15 @@ export abstract class Renderer implements ParentRenderer { abstract setElementProperty(renderElement: any, propertyName: string, propertyValue: any): void; - abstract setElementAttribute(renderElement: any, attributeName: string, attributeValue: string): - void; + abstract setElementAttribute(renderElement: any, attributeName: string, + attributeValue: string): void; /** * Used only in debug mode to serialize property changes to comment nodes, * such as <template> placeholders. */ - abstract setBindingDebugInfo(renderElement: any, propertyName: string, propertyValue: string): - void; + abstract setBindingDebugInfo(renderElement: any, propertyName: string, + propertyValue: string): void; abstract setElementDebugInfo(renderElement: any, info: RenderDebugInfo); diff --git a/modules/angular2/src/core/render/util.ts b/modules/angular2/src/core/render/util.ts index 41fd07256c..7f074e0f62 100644 --- a/modules/angular2/src/core/render/util.ts +++ b/modules/angular2/src/core/render/util.ts @@ -5,11 +5,11 @@ var DASH_CASE_REGEXP = /-([a-z])/g; export function camelCaseToDashCase(input: string): string { - return StringWrapper.replaceAllMapped( - input, CAMEL_CASE_REGEXP, (m) => { return '-' + m[1].toLowerCase(); }); + return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, + (m) => { return '-' + m[1].toLowerCase(); }); } export function dashCaseToCamelCase(input: string): string { - return StringWrapper.replaceAllMapped( - input, DASH_CASE_REGEXP, (m) => { return m[1].toUpperCase(); }); + return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, + (m) => { return m[1].toUpperCase(); }); } diff --git a/modules/angular2/src/core/testability/testability.ts b/modules/angular2/src/core/testability/testability.ts index b9f46fc8c2..9a0082030a 100644 --- a/modules/angular2/src/core/testability/testability.ts +++ b/modules/angular2/src/core/testability/testability.ts @@ -130,15 +130,15 @@ export class TestabilityRegistry { */ export interface GetTestability { addToWindow(registry: TestabilityRegistry): void; - findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean): - Testability; + findTestabilityInTree(registry: TestabilityRegistry, elem: any, + findInAncestors: boolean): Testability; } @CONST() class _NoopGetTestability implements GetTestability { addToWindow(registry: TestabilityRegistry): void {} - findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean): - Testability { + findTestabilityInTree(registry: TestabilityRegistry, elem: any, + findInAncestors: boolean): Testability { return null; } } diff --git a/modules/angular2/src/core/util/decorators.ts b/modules/angular2/src/core/util/decorators.ts index 907a1de78a..6e54ec84f7 100644 --- a/modules/angular2/src/core/util/decorators.ts +++ b/modules/angular2/src/core/util/decorators.ts @@ -20,13 +20,13 @@ export interface ClassDefinition { * * See {@link Class} for example of usage. */ - constructor: Function|any[]; + constructor: Function | any[]; /** * Other methods on the class. Note that values should have type 'Function' but TS requires * all properties to have a narrower type than the index signature. */ - [x: string]: Type|Function|any[]; + [x: string]: Type | Function | any[]; } /** @@ -61,7 +61,7 @@ export interface TypeDecorator { // ParameterDecorator is declared in lib.d.ts as a `declare type` // so we cannot declare this interface as a subtype. // see https://github.com/angular/angular/issues/3379#issuecomment-126169417 - (target: Object, propertyKey?: string|symbol, parameterIndex?: number): void; + (target: Object, propertyKey?: string | symbol, parameterIndex?: number): void; /** * Storage for the accumulated annotations so far used by the DSL syntax. diff --git a/modules/angular2/src/core/zone/ng_zone_impl.ts b/modules/angular2/src/core/zone/ng_zone_impl.ts index 45e523f0e5..e9d513202d 100644 --- a/modules/angular2/src/core/zone/ng_zone_impl.ts +++ b/modules/angular2/src/core/zone/ng_zone_impl.ts @@ -46,7 +46,7 @@ export class NgZoneImpl { } this.inner = this.inner.fork({ name: 'angular', - properties: <any>{'isAngularZone': true}, + properties:<any>{'isAngularZone': true}, onInvokeTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task, applyThis: any, applyArgs: any): any => { try { diff --git a/modules/angular2/src/facade/async.ts b/modules/angular2/src/facade/async.ts index e9476d7088..81d2a3308a 100644 --- a/modules/angular2/src/facade/async.ts +++ b/modules/angular2/src/facade/async.ts @@ -24,11 +24,10 @@ export class TimerWrapper { export class ObservableWrapper { // TODO(vsavkin): when we use rxnext, try inferring the generic type from the first arg - static subscribe<T>( - emitter: any, onNext: (value: T) => void, onError?: (exception: any) => void, - onComplete: () => void = () => {}): Object { - onError = (typeof onError === 'function') && onError || noop; - onComplete = (typeof onComplete === 'function') && onComplete || noop; + static subscribe<T>(emitter: any, onNext: (value: T) => void, onError?: (exception: any) => void, + onComplete: () => void = () => {}): Object { + onError = (typeof onError === "function") && onError || noop; + onComplete = (typeof onComplete === "function") && onComplete || noop; return emitter.subscribe({next: onNext, error: onError, complete: onComplete}); } diff --git a/modules/angular2/src/facade/collection.ts b/modules/angular2/src/facade/collection.ts index eeacad94fd..636bd4657d 100644 --- a/modules/angular2/src/facade/collection.ts +++ b/modules/angular2/src/facade/collection.ts @@ -1,4 +1,11 @@ -import {isJsObject, global, isPresent, isBlank, isArray, getSymbolIterator} from 'angular2/src/facade/lang'; +import { + isJsObject, + global, + isPresent, + isBlank, + isArray, + getSymbolIterator +} from 'angular2/src/facade/lang'; export var Map = global.Map; export var Set = global.Set; @@ -281,8 +288,8 @@ export class ListWrapper { export function isListLikeIterable(obj: any): boolean { if (!isJsObject(obj)) return false; return isArray(obj) || - (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v] - getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop + (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v] + getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop } export function areIterablesEqual(a: any, b: any, comparator: Function): boolean { diff --git a/modules/angular2/src/facade/exception_handler.ts b/modules/angular2/src/facade/exception_handler.ts index cbd7acb000..546d9e70c3 100644 --- a/modules/angular2/src/facade/exception_handler.ts +++ b/modules/angular2/src/facade/exception_handler.ts @@ -38,7 +38,7 @@ export class ExceptionHandler { var l = new _ArrayLogger(); var e = new ExceptionHandler(l, false); e.call(exception, stackTrace, reason); - return l.res.join('\n'); + return l.res.join("\n"); } call(exception: any, stackTrace: any = null, reason: string = null): void { @@ -49,7 +49,7 @@ export class ExceptionHandler { this._logger.logGroup(`EXCEPTION: ${this._extractMessage(exception)}`); if (isPresent(stackTrace) && isBlank(originalStack)) { - this._logger.logError('STACKTRACE:'); + this._logger.logError("STACKTRACE:"); this._logger.logError(this._longStackTrace(stackTrace)); } @@ -62,12 +62,12 @@ export class ExceptionHandler { } if (isPresent(originalStack)) { - this._logger.logError('ORIGINAL STACKTRACE:'); + this._logger.logError("ORIGINAL STACKTRACE:"); this._logger.logError(this._longStackTrace(originalStack)); } if (isPresent(context)) { - this._logger.logError('ERROR CONTEXT:'); + this._logger.logError("ERROR CONTEXT:"); this._logger.logError(context); } @@ -86,7 +86,7 @@ export class ExceptionHandler { /** @internal */ _longStackTrace(stackTrace: any): any { - return isListLikeIterable(stackTrace) ? (<any[]>stackTrace).join('\n\n-----async gap-----\n') : + return isListLikeIterable(stackTrace) ? (<any[]>stackTrace).join("\n\n-----async gap-----\n") : stackTrace.toString(); } diff --git a/modules/angular2/src/facade/exceptions.ts b/modules/angular2/src/facade/exceptions.ts index d7d097d94c..dd1065a7be 100644 --- a/modules/angular2/src/facade/exceptions.ts +++ b/modules/angular2/src/facade/exceptions.ts @@ -5,7 +5,7 @@ export {ExceptionHandler} from './exception_handler'; export class BaseException extends Error { public stack: any; - constructor(public message: string = '--') { + constructor(public message: string = "--") { super(message); this.stack = (<any>new Error(message)).stack; } @@ -19,9 +19,8 @@ export class BaseException extends Error { export class WrappedException extends BaseWrappedException { private _wrapperStack: any; - constructor( - private _wrapperMessage: string, private _originalException, private _originalStack?, - private _context?) { + constructor(private _wrapperMessage: string, private _originalException, private _originalStack?, + private _context?) { super(_wrapperMessage); this._wrapperStack = (<any>new Error(_wrapperMessage)).stack; } diff --git a/modules/angular2/src/facade/intl.ts b/modules/angular2/src/facade/intl.ts index a2cdc09848..4a0494047b 100644 --- a/modules/angular2/src/facade/intl.ts +++ b/modules/angular2/src/facade/intl.ts @@ -35,7 +35,7 @@ declare module Intl { } interface DateTimeFormat { - format(date?: Date|number): string; + format(date?: Date | number): string; } var DateTimeFormat: {new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat}; @@ -48,16 +48,15 @@ export enum NumberFormatStyle { } export class NumberFormatter { - static format( - num: number, locale: string, style: NumberFormatStyle, - {minimumIntegerDigits = 1, minimumFractionDigits = 0, maximumFractionDigits = 3, currency, - currencyAsSymbol = false}: { - minimumIntegerDigits?: number, - minimumFractionDigits?: number, - maximumFractionDigits?: number, - currency?: string, - currencyAsSymbol?: boolean - } = {}): string { + static format(num: number, locale: string, style: NumberFormatStyle, + {minimumIntegerDigits = 1, minimumFractionDigits = 0, maximumFractionDigits = 3, + currency, currencyAsSymbol = false}: { + minimumIntegerDigits?: number, + minimumFractionDigits?: number, + maximumFractionDigits?: number, + currency?: string, + currencyAsSymbol?: boolean + } = {}): string { var intlOptions: Intl.NumberFormatOptions = { minimumIntegerDigits: minimumIntegerDigits, minimumFractionDigits: minimumFractionDigits, diff --git a/modules/angular2/src/facade/lang.ts b/modules/angular2/src/facade/lang.ts index d303054b62..6166d537b2 100644 --- a/modules/angular2/src/facade/lang.ts +++ b/modules/angular2/src/facade/lang.ts @@ -112,7 +112,7 @@ export function CONST_EXPR<T>(expr: T): T { return expr; } -export function CONST(): ClassDecorator&PropertyDecorator { +export function CONST(): ClassDecorator & PropertyDecorator { return (target) => target; } @@ -125,19 +125,19 @@ export function isBlank(obj: any): boolean { } export function isBoolean(obj: any): boolean { - return typeof obj === 'boolean'; + return typeof obj === "boolean"; } export function isNumber(obj: any): boolean { - return typeof obj === 'number'; + return typeof obj === "number"; } export function isString(obj: any): boolean { - return typeof obj === 'string'; + return typeof obj === "string"; } export function isFunction(obj: any): boolean { - return typeof obj === 'function'; + return typeof obj === "function"; } export function isType(obj: any): boolean { @@ -179,7 +179,7 @@ export function stringify(token): string { } var res = token.toString(); - var newLineIndex = res.indexOf('\n'); + var newLineIndex = res.indexOf("\n"); return (newLineIndex === -1) ? res : res.substring(0, newLineIndex); } @@ -270,7 +270,7 @@ export class StringJoiner { add(part: string): void { this.parts.push(part); } - toString(): string { return this.parts.join(''); } + toString(): string { return this.parts.join(""); } } export class NumberParseError extends Error { @@ -290,7 +290,7 @@ export class NumberWrapper { static parseIntAutoRadix(text: string): number { var result: number = parseInt(text); if (isNaN(result)) { - throw new NumberParseError('Invalid integer literal when parsing ' + text); + throw new NumberParseError("Invalid integer literal when parsing " + text); } return result; } @@ -310,8 +310,8 @@ export class NumberWrapper { return result; } } - throw new NumberParseError( - 'Invalid integer literal when parsing ' + text + ' in base ' + radix); + throw new NumberParseError("Invalid integer literal when parsing " + text + " in base " + + radix); } // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. @@ -340,7 +340,11 @@ export class RegExpWrapper { regExp.lastIndex = 0; return regExp.test(input); } - static matcher(regExp: RegExp, input: string): {re: RegExp; input: string} { + static matcher(regExp: RegExp, input: string): { + re: RegExp; + input: string + } + { // Reset regex state for the case // someone did not loop over all matches // last time. @@ -365,7 +369,10 @@ export class RegExpWrapper { } export class RegExpMatcherWrapper { - static next(matcher: {re: RegExp; input: string}): RegExpExecArray { + static next(matcher: { + re: RegExp; + input: string + }): RegExpExecArray { return matcher.re.exec(matcher.input); } } @@ -376,7 +383,7 @@ export class FunctionWrapper { // JS has NaN !== NaN export function looseIdentical(a, b): boolean { - return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b); + return a === b || typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b); } // JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise) @@ -394,7 +401,7 @@ export function normalizeBool(obj: boolean): boolean { } export function isJsObject(o: any): boolean { - return o !== null && (typeof o === 'function' || typeof o === 'object'); + return o !== null && (typeof o === "function" || typeof o === "object"); } export function print(obj: Error | Object) { @@ -411,9 +418,8 @@ export class Json { } export class DateWrapper { - static create( - year: number, month: number = 1, day: number = 1, hour: number = 0, minutes: number = 0, - seconds: number = 0, milliseconds: number = 0): Date { + static create(year: number, month: number = 1, day: number = 1, hour: number = 0, + minutes: number = 0, seconds: number = 0, milliseconds: number = 0): Date { return new Date(year, month - 1, day, hour, minutes, seconds, milliseconds); } static fromISOString(str: string): Date { return new Date(str); } @@ -443,7 +449,7 @@ export function setValueOnPath(global: any, path: string, value: any) { // When Symbol.iterator doesn't exist, retrieves the key used in es6-shim declare var Symbol; var _symbolIterator = null; -export function getSymbolIterator(): string|symbol { +export function getSymbolIterator(): string | symbol { if (isBlank(_symbolIterator)) { if (isPresent(Symbol) && isPresent(Symbol.iterator)) { _symbolIterator = Symbol.iterator; @@ -462,8 +468,8 @@ export function getSymbolIterator(): string|symbol { return _symbolIterator; } -export function evalExpression( - sourceUrl: string, expr: string, declarations: string, vars: {[key: string]: any}): any { +export function evalExpression(sourceUrl: string, expr: string, declarations: string, + vars: {[key: string]: any}): any { var fnBody = `${declarations}\nreturn ${expr}\n//# sourceURL=${sourceUrl}`; var fnArgNames = []; var fnArgValues = []; diff --git a/modules/angular2/src/facade/promise.ts b/modules/angular2/src/facade/promise.ts index c99ae46d81..b4fd77dfa5 100644 --- a/modules/angular2/src/facade/promise.ts +++ b/modules/angular2/src/facade/promise.ts @@ -1,7 +1,7 @@ export class PromiseCompleter<R> { promise: Promise<R>; - resolve: (value?: R|PromiseLike<R>) => void; + resolve: (value?: R | PromiseLike<R>) => void; reject: (error?: any, stackTrace?: string) => void; constructor() { @@ -19,19 +19,18 @@ export class PromiseWrapper { // Note: We can't rename this method into `catch`, as this is not a valid // method name in Dart. - static catchError<T>(promise: Promise<T>, onError: (error: any) => T | PromiseLike<T>): - Promise<T> { + static catchError<T>(promise: Promise<T>, + onError: (error: any) => T | PromiseLike<T>): Promise<T> { return promise.catch(onError); } - static all<T>(promises: (T|Promise<T>)[]): Promise<T[]> { + static all<T>(promises: (T | Promise<T>)[]): Promise<T[]> { if (promises.length == 0) return Promise.resolve([]); return Promise.all(promises); } - static then<T, U>( - promise: Promise<T>, success: (value: T) => U | PromiseLike<U>, - rejection?: (error: any, stack?: any) => U | PromiseLike<U>): Promise<U> { + static then<T, U>(promise: Promise<T>, success: (value: T) => U | PromiseLike<U>, + rejection?: (error: any, stack?: any) => U | PromiseLike<U>): Promise<U> { return promise.then(success, rejection); } diff --git a/modules/angular2/src/http/backends/jsonp_backend.ts b/modules/angular2/src/http/backends/jsonp_backend.ts index c00e5367df..ddbe69eba2 100644 --- a/modules/angular2/src/http/backends/jsonp_backend.ts +++ b/modules/angular2/src/http/backends/jsonp_backend.ts @@ -45,8 +45,8 @@ export class JSONPConnection_ extends JSONPConnection { private _responseData: any; private _finished: boolean = false; - constructor( - req: Request, private _dom: BrowserJsonp, private baseResponseOptions?: ResponseOptions) { + constructor(req: Request, private _dom: BrowserJsonp, + private baseResponseOptions?: ResponseOptions) { super(); if (req.method !== RequestMethod.Get) { throw makeTypeError(JSONP_ERR_WRONG_METHOD); diff --git a/modules/angular2/src/http/backends/mock_backend.ts b/modules/angular2/src/http/backends/mock_backend.ts index e932dd410a..385776ca24 100644 --- a/modules/angular2/src/http/backends/mock_backend.ts +++ b/modules/angular2/src/http/backends/mock_backend.ts @@ -177,8 +177,8 @@ export class MockBackend implements ConnectionBackend { constructor() { this.connectionsArray = []; this.connections = new Subject(); - this.connections.subscribe( - (connection: MockConnection) => this.connectionsArray.push(connection)); + this.connections.subscribe((connection: MockConnection) => + this.connectionsArray.push(connection)); this.pendingConnections = new Subject(); } diff --git a/modules/angular2/src/http/base_request_options.ts b/modules/angular2/src/http/base_request_options.ts index 2b6f57a4a2..133de727f7 100644 --- a/modules/angular2/src/http/base_request_options.ts +++ b/modules/angular2/src/http/base_request_options.ts @@ -35,7 +35,7 @@ export class RequestOptions { * Http method with which to execute a {@link Request}. * Acceptable methods are defined in the {@link RequestMethod} enum. */ - method: RequestMethod|string; + method: RequestMethod | string; /** * {@link Headers} to be attached to a {@link Request}. */ @@ -58,9 +58,9 @@ export class RequestOptions { this.headers = isPresent(headers) ? headers : null; this.body = isPresent(body) ? body : null; this.url = isPresent(url) ? url : null; - this.search = isPresent(search) ? - (isString(search) ? new URLSearchParams(<string>(search)) : <URLSearchParams>(search)) : - null; + this.search = isPresent(search) ? (isString(search) ? new URLSearchParams(<string>(search)) : + <URLSearchParams>(search)) : + null; } /** @@ -95,9 +95,9 @@ export class RequestOptions { body: isPresent(options) && isPresent(options.body) ? options.body : this.body, url: isPresent(options) && isPresent(options.url) ? options.url : this.url, search: isPresent(options) && isPresent(options.search) ? - (isString(options.search) ? new URLSearchParams(<string>(options.search)) : - (<URLSearchParams>(options.search)).clone()) : - this.search + (isString(options.search) ? new URLSearchParams(<string>(options.search)) : + (<URLSearchParams>(options.search)).clone()) : + this.search }); } } diff --git a/modules/angular2/src/http/base_response_options.ts b/modules/angular2/src/http/base_response_options.ts index 2e83169f7c..a5c7eb3627 100644 --- a/modules/angular2/src/http/base_response_options.ts +++ b/modules/angular2/src/http/base_response_options.ts @@ -35,7 +35,7 @@ export class ResponseOptions { /** * String or Object representing the body of the {@link Response}. */ - body: string|Object; + body: string | Object; /** * Http {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html status code} * associated with the response. diff --git a/modules/angular2/src/http/headers.ts b/modules/angular2/src/http/headers.ts index 42ff937602..aa52de230b 100644 --- a/modules/angular2/src/http/headers.ts +++ b/modules/angular2/src/http/headers.ts @@ -1,6 +1,20 @@ -import {isPresent, isBlank, isJsObject, isType, StringWrapper, Json} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + isJsObject, + isType, + StringWrapper, + Json +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {isListLikeIterable, iterateListLike, Map, MapWrapper, StringMapWrapper, ListWrapper,} from 'angular2/src/facade/collection'; +import { + isListLikeIterable, + iterateListLike, + Map, + MapWrapper, + StringMapWrapper, + ListWrapper, +} from 'angular2/src/facade/collection'; /** * Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as @@ -31,7 +45,7 @@ import {isListLikeIterable, iterateListLike, Map, MapWrapper, StringMapWrapper, export class Headers { /** @internal */ _headersMap: Map<string, string[]>; - constructor(headers?: Headers|{[key: string]: any}) { + constructor(headers?: Headers | {[key: string]: any}) { if (headers instanceof Headers) { this._headersMap = (<Headers>headers)._headersMap; return; @@ -97,7 +111,7 @@ export class Headers { /** * Sets or overrides header value for given name. */ - set(header: string, value: string|string[]): void { + set(header: string, value: string | string[]): void { var list: string[] = []; if (isListLikeIterable(value)) { diff --git a/modules/angular2/src/http/http.ts b/modules/angular2/src/http/http.ts index 70aa6c94a9..419b4f07d3 100644 --- a/modules/angular2/src/http/http.ts +++ b/modules/angular2/src/http/http.ts @@ -12,9 +12,8 @@ function httpRequest(backend: ConnectionBackend, request: Request): Observable<R return backend.createConnection(request).response; } -function mergeOptions( - defaultOpts: BaseRequestOptions, providedOpts: RequestOptionsArgs, method: RequestMethod, - url: string): RequestOptions { +function mergeOptions(defaultOpts: BaseRequestOptions, providedOpts: RequestOptionsArgs, + method: RequestMethod, url: string): RequestOptions { var newOptions = defaultOpts; if (isPresent(providedOpts)) { // Hack so Dart can used named parameters @@ -101,7 +100,7 @@ export class Http { * object can be provided as the 2nd argument. The options object will be merged with the values * of {@link BaseRequestOptions} before performing the request. */ - request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { + request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { var responseObservable: any; if (isString(url)) { responseObservable = httpRequest( @@ -119,9 +118,8 @@ export class Http { * Performs a request with `get` http method. */ get(url: string, options?: RequestOptionsArgs): Observable<Response> { - return httpRequest( - this._backend, - new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, url))); + return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options, + RequestMethod.Get, url))); } /** @@ -129,9 +127,9 @@ export class Http { */ post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { return httpRequest( - this._backend, new Request(mergeOptions( - this._defaultOptions.merge(new RequestOptions({body: body})), options, - RequestMethod.Post, url))); + this._backend, + new Request(mergeOptions(this._defaultOptions.merge(new RequestOptions({body: body})), + options, RequestMethod.Post, url))); } /** @@ -139,18 +137,17 @@ export class Http { */ put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { return httpRequest( - this._backend, new Request(mergeOptions( - this._defaultOptions.merge(new RequestOptions({body: body})), options, - RequestMethod.Put, url))); + this._backend, + new Request(mergeOptions(this._defaultOptions.merge(new RequestOptions({body: body})), + options, RequestMethod.Put, url))); } /** * Performs a request with `delete` http method. */ delete (url: string, options?: RequestOptionsArgs): Observable<Response> { - return httpRequest( - this._backend, - new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Delete, url))); + return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options, + RequestMethod.Delete, url))); } /** @@ -158,18 +155,17 @@ export class Http { */ patch(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { return httpRequest( - this._backend, new Request(mergeOptions( - this._defaultOptions.merge(new RequestOptions({body: body})), options, - RequestMethod.Patch, url))); + this._backend, + new Request(mergeOptions(this._defaultOptions.merge(new RequestOptions({body: body})), + options, RequestMethod.Patch, url))); } /** * Performs a request with `head` http method. */ head(url: string, options?: RequestOptionsArgs): Observable<Response> { - return httpRequest( - this._backend, - new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Head, url))); + return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options, + RequestMethod.Head, url))); } } @@ -185,7 +181,7 @@ export class Jsonp extends Http { * object can be provided as the 2nd argument. The options object will be merged with the values * of {@link BaseRequestOptions} before performing the request. */ - request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { + request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { var responseObservable: any; if (isString(url)) { url = diff --git a/modules/angular2/src/http/http_utils.ts b/modules/angular2/src/http/http_utils.ts index 891cd38c63..9d02b04bef 100644 --- a/modules/angular2/src/http/http_utils.ts +++ b/modules/angular2/src/http/http_utils.ts @@ -7,9 +7,8 @@ export function normalizeMethodName(method: string | RequestMethod): RequestMeth if (isString(method)) { var originalMethod = method; method = (<string>method) - .replace( - /(\w)(\w*)/g, - (g0: string, g1: string, g2: string) => g1.toUpperCase() + g2.toLowerCase()); + .replace(/(\w)(\w*)/g, (g0: string, g1: string, g2: string) => + g1.toUpperCase() + g2.toLowerCase()); method = <number>(<{[key: string]: any}>RequestMethod)[method]; if (typeof method !== 'number') throw makeTypeError( diff --git a/modules/angular2/src/http/interfaces.ts b/modules/angular2/src/http/interfaces.ts index 1c9df0c36e..82694502dc 100644 --- a/modules/angular2/src/http/interfaces.ts +++ b/modules/angular2/src/http/interfaces.ts @@ -28,8 +28,8 @@ export abstract class Connection { */ export interface RequestOptionsArgs { url?: string; - method?: string|RequestMethod; - search?: string|URLSearchParams; + method?: string | RequestMethod; + search?: string | URLSearchParams; headers?: Headers; // TODO: Support Blob, ArrayBuffer, JSON, URLSearchParams, FormData body?: string; @@ -46,7 +46,10 @@ export interface RequestArgs extends RequestOptionsArgs { url: string; } */ export type ResponseOptionsArgs = { // TODO: Support Blob, ArrayBuffer, JSON - body?: string | Object | FormData; status?: number; statusText?: string; headers?: Headers; + body?: string | Object | FormData; + status?: number; + statusText?: string; + headers?: Headers; type?: ResponseType; url?: string; } diff --git a/modules/angular2/src/http/static_request.ts b/modules/angular2/src/http/static_request.ts index 14b2613ff6..093fa97b2f 100644 --- a/modules/angular2/src/http/static_request.ts +++ b/modules/angular2/src/http/static_request.ts @@ -2,7 +2,13 @@ import {RequestMethod} from './enums'; import {RequestArgs} from './interfaces'; import {Headers} from './headers'; import {normalizeMethodName} from './http_utils'; -import {RegExpWrapper, CONST_EXPR, isPresent, isJsObject, StringWrapper} from 'angular2/src/facade/lang'; +import { + RegExpWrapper, + CONST_EXPR, + isPresent, + isJsObject, + StringWrapper +} from 'angular2/src/facade/lang'; // TODO(jeffbcross): properly implement body accessors /** diff --git a/modules/angular2/src/http/static_response.ts b/modules/angular2/src/http/static_response.ts index 12ff7e64dc..c4e986f774 100644 --- a/modules/angular2/src/http/static_response.ts +++ b/modules/angular2/src/http/static_response.ts @@ -72,7 +72,7 @@ export class Response { */ headers: Headers; // TODO: Support ArrayBuffer, JSON, FormData, Blob - private _body: string|Object; + private _body: string | Object; constructor(responseOptions: ResponseOptions) { this._body = responseOptions.body; this.status = responseOptions.status; @@ -92,7 +92,7 @@ export class Response { * Attempts to return body as parsed `JSON` object, or raises an exception. */ json(): any { - var jsonResponse: string|Object; + var jsonResponse: string | Object; if (isJsObject(this._body)) { jsonResponse = this._body; } else if (isString(this._body)) { diff --git a/modules/angular2/src/i18n/i18n_html_parser.ts b/modules/angular2/src/i18n/i18n_html_parser.ts index 8ab173141f..e707d78c04 100644 --- a/modules/angular2/src/i18n/i18n_html_parser.ts +++ b/modules/angular2/src/i18n/i18n_html_parser.ts @@ -1,17 +1,34 @@ import {HtmlParser, HtmlParseTreeResult} from 'angular2/src/compiler/html_parser'; import {ParseSourceSpan, ParseError} from 'angular2/src/compiler/parse_util'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {RegExpWrapper, NumberWrapper, isPresent} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {Parser} from 'angular2/src/core/change_detection/parser/parser'; import {Message, id} from './message'; -import {messageFromAttribute, I18nError, I18N_ATTR_PREFIX, I18N_ATTR, partition, Part, stringifyNodes, meaning} from './shared'; +import { + messageFromAttribute, + I18nError, + I18N_ATTR_PREFIX, + I18N_ATTR, + partition, + Part, + stringifyNodes, + meaning +} from './shared'; -const _I18N_ATTR = 'i18n'; -const _PLACEHOLDER_ELEMENT = 'ph'; -const _NAME_ATTR = 'name'; -const _I18N_ATTR_PREFIX = 'i18n-'; +const _I18N_ATTR = "i18n"; +const _PLACEHOLDER_ELEMENT = "ph"; +const _NAME_ATTR = "name"; +const _I18N_ATTR_PREFIX = "i18n-"; let _PLACEHOLDER_EXPANDED_REGEXP = RegExpWrapper.create(`\\<ph(\\s)+name=("(\\d)+")\\>\\<\\/ph\\>`); /** @@ -97,9 +114,8 @@ let _PLACEHOLDER_EXPANDED_REGEXP = RegExpWrapper.create(`\\<ph(\\s)+name=("(\\d) export class I18nHtmlParser implements HtmlParser { errors: ParseError[]; - constructor( - private _htmlParser: HtmlParser, private _parser: Parser, private _messagesContent: string, - private _messages: {[key: string]: HtmlAst[]}) {} + constructor(private _htmlParser: HtmlParser, private _parser: Parser, + private _messagesContent: string, private _messages: {[key: string]: HtmlAst[]}) {} parse(sourceContent: string, sourceUrl: string): HtmlParseTreeResult { this.errors = []; @@ -145,8 +161,10 @@ export class I18nHtmlParser implements HtmlParser { let root = p.rootElement; let children = this._recurse(p.children); let attrs = this._i18nAttributes(root); - return [new HtmlElementAst( - root.name, attrs, children, root.sourceSpan, root.startSourceSpan, root.endSourceSpan)]; + return [ + new HtmlElementAst(root.name, attrs, children, root.sourceSpan, root.startSourceSpan, + root.endSourceSpan) + ]; // a text node without i18n or interpolation, nothing to do } else if (isPresent(p.rootTextNode)) { @@ -175,12 +193,14 @@ export class I18nHtmlParser implements HtmlParser { if (isPresent(p.rootElement)) { let root = p.rootElement; let attrs = this._i18nAttributes(root); - return [new HtmlElementAst( - root.name, attrs, merged, root.sourceSpan, root.startSourceSpan, root.endSourceSpan)]; + return [ + new HtmlElementAst(root.name, attrs, merged, root.sourceSpan, root.startSourceSpan, + root.endSourceSpan) + ]; // this should never happen with a part. Parts that have root text node should not be merged. } else if (isPresent(p.rootTextNode)) { - throw new BaseException('should not be reached'); + throw new BaseException("should not be reached"); } else { return merged; @@ -196,24 +216,24 @@ export class I18nHtmlParser implements HtmlParser { return t; } else { - throw new BaseException('should not be reached'); + throw new BaseException("should not be reached"); } }); } - private _mergeElementOrInterpolation( - t: HtmlElementAst, translated: HtmlAst[], mapping: HtmlAst[]): HtmlAst { + private _mergeElementOrInterpolation(t: HtmlElementAst, translated: HtmlAst[], + mapping: HtmlAst[]): HtmlAst { let name = this._getName(t); let type = name[0]; let index = NumberWrapper.parseInt(name.substring(1), 10); let originalNode = mapping[index]; - if (type == 't') { + if (type == "t") { return this._mergeTextInterpolation(t, <HtmlTextAst>originalNode); - } else if (type == 'e') { + } else if (type == "e") { return this._mergeElement(t, <HtmlElementAst>originalNode, mapping); } else { - throw new BaseException('should not be reached'); + throw new BaseException("should not be reached"); } } @@ -243,12 +263,12 @@ export class I18nHtmlParser implements HtmlParser { return new HtmlTextAst(translated, originalNode.sourceSpan); } - private _mergeElement(t: HtmlElementAst, originalNode: HtmlElementAst, mapping: HtmlAst[]): - HtmlElementAst { + private _mergeElement(t: HtmlElementAst, originalNode: HtmlElementAst, + mapping: HtmlAst[]): HtmlElementAst { let children = this._mergeTreesHelper(t.children, mapping); - return new HtmlElementAst( - originalNode.name, this._i18nAttributes(originalNode), children, originalNode.sourceSpan, - originalNode.startSourceSpan, originalNode.endSourceSpan); + return new HtmlElementAst(originalNode.name, this._i18nAttributes(originalNode), children, + originalNode.sourceSpan, originalNode.startSourceSpan, + originalNode.endSourceSpan); } private _i18nAttributes(el: HtmlElementAst): HtmlAttrAst[] { @@ -291,8 +311,8 @@ export class I18nHtmlParser implements HtmlParser { return this._replacePlaceholdersWithExpressions(messageSubstring, exps, attr.sourceSpan); }; - private _replacePlaceholdersWithExpressions( - message: string, exps: string[], sourceSpan: ParseSourceSpan): string { + private _replacePlaceholdersWithExpressions(message: string, exps: string[], + sourceSpan: ParseSourceSpan): string { return RegExpWrapper.replaceAll(_PLACEHOLDER_EXPANDED_REGEXP, message, (match) => { let nameWithQuotes = match[2]; let name = nameWithQuotes.substring(1, nameWithQuotes.length - 1); @@ -326,5 +346,5 @@ class _CreateNodeMapping implements HtmlAstVisitor { return null; } - visitComment(ast: HtmlCommentAst, context: any): any { return ''; } + visitComment(ast: HtmlCommentAst, context: any): any { return ""; } } \ No newline at end of file diff --git a/modules/angular2/src/i18n/message.ts b/modules/angular2/src/i18n/message.ts index 9c32fb14ed..2a1798c58d 100644 --- a/modules/angular2/src/i18n/message.ts +++ b/modules/angular2/src/i18n/message.ts @@ -15,7 +15,7 @@ export class Message { * Computes the id of a message */ export function id(m: Message): string { - let meaning = isPresent(m.meaning) ? m.meaning : ''; - let content = isPresent(m.content) ? m.content : ''; + let meaning = isPresent(m.meaning) ? m.meaning : ""; + let content = isPresent(m.content) ? m.content : ""; return escape(`$ng|${meaning}|${content}`); } \ No newline at end of file diff --git a/modules/angular2/src/i18n/message_extractor.ts b/modules/angular2/src/i18n/message_extractor.ts index 7389480a2b..3895294374 100644 --- a/modules/angular2/src/i18n/message_extractor.ts +++ b/modules/angular2/src/i18n/message_extractor.ts @@ -1,11 +1,28 @@ import {HtmlParser} from 'angular2/src/compiler/html_parser'; import {ParseSourceSpan, ParseError} from 'angular2/src/compiler/parse_util'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {Parser} from 'angular2/src/core/change_detection/parser/parser'; import {Message, id} from './message'; -import {I18nError, Part, I18N_ATTR_PREFIX, partition, meaning, description, stringifyNodes, messageFromAttribute} from './shared'; +import { + I18nError, + Part, + I18N_ATTR_PREFIX, + partition, + meaning, + description, + stringifyNodes, + messageFromAttribute +} from './shared'; /** * All messages extracted from a template. diff --git a/modules/angular2/src/i18n/shared.ts b/modules/angular2/src/i18n/shared.ts index ddd7a9b969..43fbdf8a95 100644 --- a/modules/angular2/src/i18n/shared.ts +++ b/modules/angular2/src/i18n/shared.ts @@ -1,11 +1,19 @@ import {ParseSourceSpan, ParseError} from 'angular2/src/compiler/parse_util'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; import {Message} from './message'; import {Parser} from 'angular2/src/core/change_detection/parser/parser'; -export const I18N_ATTR = 'i18n'; -export const I18N_ATTR_PREFIX = 'i18n-'; +export const I18N_ATTR = "i18n"; +export const I18N_ATTR_PREFIX = "i18n-"; /** * An i18n error. @@ -28,7 +36,7 @@ export function partition(nodes: HtmlAst[], errors: ParseError[]): Part[] { while (!_isClosingComment(nodes[i])) { temp.push(nodes[i++]); if (i === nodes.length) { - errors.push(new I18nError(n.sourceSpan, 'Missing closing \'i18n\' comment.')); + errors.push(new I18nError(n.sourceSpan, "Missing closing 'i18n' comment.")); break; } } @@ -46,9 +54,8 @@ export function partition(nodes: HtmlAst[], errors: ParseError[]): Part[] { } export class Part { - constructor( - public rootElement: HtmlElementAst, public rootTextNode: HtmlTextAst, - public children: HtmlAst[], public i18n: string, public hasI18n: boolean) {} + constructor(public rootElement: HtmlElementAst, public rootTextNode: HtmlTextAst, + public children: HtmlAst[], public i18n: string, public hasI18n: boolean) {} get sourceSpan(): ParseSourceSpan { if (isPresent(this.rootElement)) @@ -60,17 +67,17 @@ export class Part { } createMessage(parser: Parser): Message { - return new Message( - stringifyNodes(this.children, parser), meaning(this.i18n), description(this.i18n)); + return new Message(stringifyNodes(this.children, parser), meaning(this.i18n), + description(this.i18n)); } } function _isOpeningComment(n: HtmlAst): boolean { - return n instanceof HtmlCommentAst && isPresent(n.value) && n.value.startsWith('i18n:'); + return n instanceof HtmlCommentAst && isPresent(n.value) && n.value.startsWith("i18n:"); } function _isClosingComment(n: HtmlAst): boolean { - return n instanceof HtmlCommentAst && isPresent(n.value) && n.value == '/i18n'; + return n instanceof HtmlCommentAst && isPresent(n.value) && n.value == "/i18n"; } function _findI18nAttr(p: HtmlElementAst): HtmlAttrAst { @@ -79,18 +86,18 @@ function _findI18nAttr(p: HtmlElementAst): HtmlAttrAst { } export function meaning(i18n: string): string { - if (isBlank(i18n) || i18n == '') return null; - return i18n.split('|')[0]; + if (isBlank(i18n) || i18n == "") return null; + return i18n.split("|")[0]; } export function description(i18n: string): string { - if (isBlank(i18n) || i18n == '') return null; - let parts = i18n.split('|'); + if (isBlank(i18n) || i18n == "") return null; + let parts = i18n.split("|"); return parts.length > 1 ? parts[1] : null; } -export function messageFromAttribute( - parser: Parser, p: HtmlElementAst, attr: HtmlAttrAst): Message { +export function messageFromAttribute(parser: Parser, p: HtmlElementAst, + attr: HtmlAttrAst): Message { let expectedName = attr.name.substring(5); let matching = p.attrs.filter(a => a.name == expectedName); @@ -102,12 +109,12 @@ export function messageFromAttribute( } } -export function removeInterpolation( - value: string, source: ParseSourceSpan, parser: Parser): string { +export function removeInterpolation(value: string, source: ParseSourceSpan, + parser: Parser): string { try { let parsed = parser.splitInterpolation(value, source.toString()); if (isPresent(parsed)) { - let res = ''; + let res = ""; for (let i = 0; i < parsed.strings.length; ++i) { res += parsed.strings[i]; if (i != parsed.strings.length - 1) { @@ -125,7 +132,7 @@ export function removeInterpolation( export function stringifyNodes(nodes: HtmlAst[], parser: Parser): string { let visitor = new _StringifyVisitor(parser); - return htmlVisitAll(visitor, nodes).join(''); + return htmlVisitAll(visitor, nodes).join(""); } class _StringifyVisitor implements HtmlAstVisitor { @@ -134,7 +141,7 @@ class _StringifyVisitor implements HtmlAstVisitor { visitElement(ast: HtmlElementAst, context: any): any { let name = this._index++; - let children = this._join(htmlVisitAll(this, ast.children), ''); + let children = this._join(htmlVisitAll(this, ast.children), ""); return `<ph name="e${name}">${children}</ph>`; } @@ -150,7 +157,7 @@ class _StringifyVisitor implements HtmlAstVisitor { } } - visitComment(ast: HtmlCommentAst, context: any): any { return ''; } + visitComment(ast: HtmlCommentAst, context: any): any { return ""; } private _join(strs: string[], str: string): string { return strs.filter(s => s.length > 0).join(str); diff --git a/modules/angular2/src/i18n/xmb_serializer.ts b/modules/angular2/src/i18n/xmb_serializer.ts index 80a335526f..2dfc09244f 100644 --- a/modules/angular2/src/i18n/xmb_serializer.ts +++ b/modules/angular2/src/i18n/xmb_serializer.ts @@ -5,19 +5,18 @@ import {HtmlParser} from 'angular2/src/compiler/html_parser'; import {ParseSourceSpan, ParseError} from 'angular2/src/compiler/parse_util'; let _PLACEHOLDER_REGEXP = RegExpWrapper.create(`\\<ph(\\s)+name=("(\\w)+")\\/\\>`); -const _ID_ATTR = 'id'; -const _MSG_ELEMENT = 'msg'; -const _BUNDLE_ELEMENT = 'message-bundle'; +const _ID_ATTR = "id"; +const _MSG_ELEMENT = "msg"; +const _BUNDLE_ELEMENT = "message-bundle"; export function serializeXmb(messages: Message[]): string { - let ms = messages.map((m) => _serializeMessage(m)).join(''); + let ms = messages.map((m) => _serializeMessage(m)).join(""); return `<message-bundle>${ms}</message-bundle>`; } export class XmbDeserializationResult { - constructor( - public content: string, public messages: {[key: string]: HtmlAst[]}, - public errors: ParseError[]) {} + constructor(public content: string, public messages: {[key: string]: HtmlAst[]}, + public errors: ParseError[]) {} } export class XmbDeserializationError extends ParseError { @@ -45,17 +44,17 @@ export function deserializeXmb(content: string, url: string): XmbDeserialization _createMessages(bundleEl.children, messages, errors); return (errors.length == 0) ? - new XmbDeserializationResult(normalizedContent, messages, []) : - new XmbDeserializationResult(null, <{[key: string]: HtmlAst[]}>{}, errors); + new XmbDeserializationResult(normalizedContent, messages, []) : + new XmbDeserializationResult(null, <{[key: string]: HtmlAst[]}>{}, errors); } function _checkRootElement(nodes: HtmlAst[]): boolean { return nodes.length < 1 || !(nodes[0] instanceof HtmlElementAst) || - (<HtmlElementAst>nodes[0]).name != _BUNDLE_ELEMENT; + (<HtmlElementAst>nodes[0]).name != _BUNDLE_ELEMENT; } -function _createMessages( - nodes: HtmlAst[], messages: {[key: string]: HtmlAst[]}, errors: ParseError[]): void { +function _createMessages(nodes: HtmlAst[], messages: {[key: string]: HtmlAst[]}, + errors: ParseError[]): void { nodes.forEach((item) => { if (item instanceof HtmlElementAst) { let msg = <HtmlElementAst>item; @@ -84,7 +83,7 @@ function _id(el: HtmlElementAst): string { } function _serializeMessage(m: Message): string { - let desc = isPresent(m.description) ? ` desc='${m.description}'` : ''; + let desc = isPresent(m.description) ? ` desc='${m.description}'` : ""; return `<msg id='${id(m)}'${desc}>${m.content}</msg>`; } diff --git a/modules/angular2/src/mock/location_mock.ts b/modules/angular2/src/mock/location_mock.ts index 1f9b2c8a2f..759ab04c2b 100644 --- a/modules/angular2/src/mock/location_mock.ts +++ b/modules/angular2/src/mock/location_mock.ts @@ -71,9 +71,8 @@ export class SpyLocation implements Location { // TODO } - subscribe( - onNext: (value: any) => void, onThrow: (error: any) => void = null, - onReturn: () => void = null): Object { + subscribe(onNext: (value: any) => void, onThrow: (error: any) => void = null, + onReturn: () => void = null): Object { return ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); } diff --git a/modules/angular2/src/mock/mock_application_ref.ts b/modules/angular2/src/mock/mock_application_ref.ts index 376feca8d4..748953aa2c 100644 --- a/modules/angular2/src/mock/mock_application_ref.ts +++ b/modules/angular2/src/mock/mock_application_ref.ts @@ -14,7 +14,7 @@ export class MockApplicationRef extends ApplicationRef { registerDisposeListener(dispose: () => void): void {} - bootstrap(componentType: Type, bindings?: Array<Type|Provider|any[]>): Promise<ComponentRef> { + bootstrap(componentType: Type, bindings?: Array<Type | Provider | any[]>): Promise<ComponentRef> { return null; } diff --git a/modules/angular2/src/platform/browser/browser_adapter.ts b/modules/angular2/src/platform/browser/browser_adapter.ts index 1bfdd198a7..474e4ea1ff 100644 --- a/modules/angular2/src/platform/browser/browser_adapter.ts +++ b/modules/angular2/src/platform/browser/browser_adapter.ts @@ -58,7 +58,7 @@ var _chromeNumKeyPadMap = { */ /* tslint:disable:requireParameterType */ export class BrowserDomAdapter extends GenericBrowserDomAdapter { - parse(templateHtml: string) { throw new Error('parse not implemented'); } + parse(templateHtml: string) { throw new Error("parse not implemented"); } static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); } hasProperty(element, name: string): boolean { return name in element; } setProperty(el: /*element*/ any, name: string, value: any) { el[name] = value; } @@ -129,7 +129,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter { nodeValue(node: Node): string { return node.nodeValue; } type(node: HTMLInputElement): string { return node.type; } content(node: Node): Node { - if (this.hasProperty(node, 'content')) { + if (this.hasProperty(node, "content")) { return (<any>node).content; } else { return node; @@ -266,7 +266,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter { return matches; } isTemplateElement(el: any): boolean { - return el instanceof HTMLElement && el.nodeName == 'TEMPLATE'; + return el instanceof HTMLElement && el.nodeName == "TEMPLATE"; } isTextNode(node: Node): boolean { return node.nodeType === Node.TEXT_NODE; } isCommentNode(node: Node): boolean { return node.nodeType === Node.COMMENT_NODE; } @@ -309,11 +309,11 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter { return key; } getGlobalEventTarget(target: string): EventTarget { - if (target == 'window') { + if (target == "window") { return window; - } else if (target == 'document') { + } else if (target == "document") { return document; - } else if (target == 'body') { + } else if (target == "body") { return document.body; } } @@ -364,7 +364,7 @@ function getBaseElementHref(): string { var urlParsingNode = null; function relativePath(url): string { if (isBlank(urlParsingNode)) { - urlParsingNode = document.createElement('a'); + urlParsingNode = document.createElement("a"); } urlParsingNode.setAttribute('href', url); return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : diff --git a/modules/angular2/src/platform/browser/generic_browser_adapter.ts b/modules/angular2/src/platform/browser/generic_browser_adapter.ts index 1d144f8b90..7c20c51796 100644 --- a/modules/angular2/src/platform/browser/generic_browser_adapter.ts +++ b/modules/angular2/src/platform/browser/generic_browser_adapter.ts @@ -52,9 +52,9 @@ export abstract class GenericBrowserDomAdapter extends DomAdapter { return isFunction((<any>this.defaultDoc().body).createShadowRoot); } getAnimationPrefix(): string { - return isPresent(this._animationPrefix) ? this._animationPrefix : ''; + return isPresent(this._animationPrefix) ? this._animationPrefix : ""; } - getTransitionEnd(): string { return isPresent(this._transitionEnd) ? this._transitionEnd : ''; } + getTransitionEnd(): string { return isPresent(this._transitionEnd) ? this._transitionEnd : ""; } supportsAnimation(): boolean { return isPresent(this._animationPrefix) && isPresent(this._transitionEnd); } diff --git a/modules/angular2/src/platform/browser/testability.ts b/modules/angular2/src/platform/browser/testability.ts index cd29d1f95c..7b45856a20 100644 --- a/modules/angular2/src/platform/browser/testability.ts +++ b/modules/angular2/src/platform/browser/testability.ts @@ -5,7 +5,13 @@ import {PromiseWrapper, ObservableWrapper} from 'angular2/src/facade/async'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {Injectable, TestabilityRegistry, Testability, GetTestability, setTestabilityGetter} from 'angular2/core'; +import { + Injectable, + TestabilityRegistry, + Testability, + GetTestability, + setTestabilityGetter +} from 'angular2/core'; class PublicTestability { /** @internal */ @@ -65,8 +71,8 @@ export class BrowserGetTestability implements GetTestability { global.frameworkStabilizers.push(whenAllStable); } - findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean): - Testability { + findTestabilityInTree(registry: TestabilityRegistry, elem: any, + findInAncestors: boolean): Testability { if (elem == null) { return null; } diff --git a/modules/angular2/src/platform/browser_common.ts b/modules/angular2/src/platform/browser_common.ts index f10eb5865b..2495693f85 100644 --- a/modules/angular2/src/platform/browser_common.ts +++ b/modules/angular2/src/platform/browser_common.ts @@ -1,8 +1,20 @@ import {CONST_EXPR, IS_DART} from 'angular2/src/facade/lang'; import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di'; import {XHR} from 'angular2/src/compiler/xhr'; -import {PLATFORM_INITIALIZER, PLATFORM_DIRECTIVES, PLATFORM_PIPES, ComponentRef, platform, ExceptionHandler, Reflector, RootRenderer, reflector, APPLICATION_COMMON_PROVIDERS, PLATFORM_COMMON_PROVIDERS} from 'angular2/core'; -import {COMMON_DIRECTIVES, COMMON_PIPES, FORM_PROVIDERS} from 'angular2/common'; +import { + PLATFORM_INITIALIZER, + PLATFORM_DIRECTIVES, + PLATFORM_PIPES, + ComponentRef, + platform, + ExceptionHandler, + Reflector, + RootRenderer, + reflector, + APPLICATION_COMMON_PROVIDERS, + PLATFORM_COMMON_PROVIDERS +} from "angular2/core"; +import {COMMON_DIRECTIVES, COMMON_PIPES, FORM_PROVIDERS} from "angular2/common"; import {Testability} from 'angular2/src/core/testability/testability'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; @@ -11,19 +23,27 @@ import {HammerGesturesPlugin} from 'angular2/src/platform/dom/events/hammer_gest import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; import {DomRootRenderer, DomRootRenderer_} from 'angular2/src/platform/dom/dom_renderer'; import {DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; -import {SharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; -import {BrowserDetails} from 'angular2/src/animate/browser_details'; -import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; +import {SharedStylesHost} from "angular2/src/platform/dom/shared_styles_host"; +import {BrowserDetails} from "angular2/src/animate/browser_details"; +import {AnimationBuilder} from "angular2/src/animate/animation_builder"; import {BrowserDomAdapter} from './browser/browser_adapter'; import {BrowserGetTestability} from 'angular2/src/platform/browser/testability'; import {CachedXHR} from 'angular2/src/platform/browser/xhr_cache'; import {wtfInit} from 'angular2/src/core/profile/wtf_init'; -import {EventManager, EVENT_MANAGER_PLUGINS} from 'angular2/src/platform/dom/events/event_manager'; -import {HAMMER_GESTURE_CONFIG, HammerGestureConfig} from 'angular2/src/platform/dom/events/hammer_gestures'; +import {EventManager, EVENT_MANAGER_PLUGINS} from "angular2/src/platform/dom/events/event_manager"; +import { + HAMMER_GESTURE_CONFIG, + HammerGestureConfig +} from 'angular2/src/platform/dom/events/hammer_gestures'; import {ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/common_dom'; export {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; export {Title} from 'angular2/src/platform/browser/title'; -export {ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, By} from 'angular2/platform/common_dom'; +export { + ELEMENT_PROBE_PROVIDERS, + ELEMENT_PROBE_PROVIDERS_PROD_MODE, + inspectNativeElement, + By +} from 'angular2/platform/common_dom'; export {BrowserDomAdapter} from './browser/browser_adapter'; export {enableDebugTools, disableDebugTools} from 'angular2/src/platform/browser/tools/tools'; export {HAMMER_GESTURE_CONFIG, HammerGestureConfig} from './dom/events/hammer_gestures'; @@ -54,7 +74,8 @@ function _document(): any { * Used automatically by `bootstrap`, or can be passed to {@link PlatformRef.application}. */ export const BROWSER_APP_COMMON_PROVIDERS: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([ - APPLICATION_COMMON_PROVIDERS, FORM_PROVIDERS, + APPLICATION_COMMON_PROVIDERS, + FORM_PROVIDERS, new Provider(PLATFORM_PIPES, {useValue: COMMON_PIPES, multi: true}), new Provider(PLATFORM_DIRECTIVES, {useValue: COMMON_DIRECTIVES, multi: true}), new Provider(ExceptionHandler, {useFactory: _exceptionHandler, deps: []}), @@ -65,8 +86,13 @@ export const BROWSER_APP_COMMON_PROVIDERS: Array<any /*Type | Provider | any[]*/ new Provider(HAMMER_GESTURE_CONFIG, {useClass: HammerGestureConfig}), new Provider(DomRootRenderer, {useClass: DomRootRenderer_}), new Provider(RootRenderer, {useExisting: DomRootRenderer}), - new Provider(SharedStylesHost, {useExisting: DomSharedStylesHost}), DomSharedStylesHost, - Testability, BrowserDetails, AnimationBuilder, EventManager, ELEMENT_PROBE_PROVIDERS + new Provider(SharedStylesHost, {useExisting: DomSharedStylesHost}), + DomSharedStylesHost, + Testability, + BrowserDetails, + AnimationBuilder, + EventManager, + ELEMENT_PROBE_PROVIDERS ]); export const CACHED_TEMPLATE_PROVIDER: Array<any /*Type | Provider | any[]*/> = diff --git a/modules/angular2/src/platform/dom/debug/by.ts b/modules/angular2/src/platform/dom/debug/by.ts index 57d9e50dc0..4523d44e9c 100644 --- a/modules/angular2/src/platform/dom/debug/by.ts +++ b/modules/angular2/src/platform/dom/debug/by.ts @@ -26,8 +26,8 @@ export class By { static css(selector: string): Predicate<DebugElement> { return (debugElement) => { return isPresent(debugElement.nativeElement) ? - DOM.elementMatches(debugElement.nativeElement, selector) : - false; + DOM.elementMatches(debugElement.nativeElement, selector) : + false; }; } diff --git a/modules/angular2/src/platform/dom/debug/ng_probe.ts b/modules/angular2/src/platform/dom/debug/ng_probe.ts index 884256deba..6087a4d06c 100644 --- a/modules/angular2/src/platform/dom/debug/ng_probe.ts +++ b/modules/angular2/src/platform/dom/debug/ng_probe.ts @@ -36,8 +36,10 @@ function _createRootRenderer(rootRenderer) { /** * Providers which support debugging Angular applications (e.g. via `ng.probe`). */ -export const ELEMENT_PROBE_PROVIDERS: any[] = CONST_EXPR([new Provider( - RootRenderer, {useFactory: _createConditionalRootRenderer, deps: [DomRootRenderer]})]); +export const ELEMENT_PROBE_PROVIDERS: any[] = CONST_EXPR([ + new Provider(RootRenderer, + {useFactory: _createConditionalRootRenderer, deps: [DomRootRenderer]}) +]); export const ELEMENT_PROBE_PROVIDERS_PROD_MODE: any[] = CONST_EXPR( [new Provider(RootRenderer, {useFactory: _createRootRenderer, deps: [DomRootRenderer]})]); diff --git a/modules/angular2/src/platform/dom/dom_renderer.ts b/modules/angular2/src/platform/dom/dom_renderer.ts index 82c6bb1544..c71e6799f3 100644 --- a/modules/angular2/src/platform/dom/dom_renderer.ts +++ b/modules/angular2/src/platform/dom/dom_renderer.ts @@ -1,11 +1,25 @@ import {Inject, Injectable, OpaqueToken} from 'angular2/src/core/di'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; -import {isPresent, isBlank, Json, RegExpWrapper, CONST_EXPR, stringify, StringWrapper, isArray} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + Json, + RegExpWrapper, + CONST_EXPR, + stringify, + StringWrapper, + isArray +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {DomSharedStylesHost} from './shared_styles_host'; -import {Renderer, RootRenderer, RenderComponentType, RenderDebugInfo} from 'angular2/src/core/render/api'; +import { + Renderer, + RootRenderer, + RenderComponentType, + RenderDebugInfo +} from 'angular2/src/core/render/api'; import {EventManager} from './events/event_manager'; @@ -22,9 +36,8 @@ var TEMPLATE_BINDINGS_EXP = /^template bindings=(.*)$/g; export abstract class DomRootRenderer implements RootRenderer { private _registeredComponents: Map<string, DomRenderer> = new Map<string, DomRenderer>(); - constructor( - public document: any, public eventManager: EventManager, - public sharedStylesHost: DomSharedStylesHost, public animate: AnimationBuilder) {} + constructor(public document: any, public eventManager: EventManager, + public sharedStylesHost: DomSharedStylesHost, public animate: AnimationBuilder) {} renderComponent(componentProto: RenderComponentType): Renderer { var renderer = this._registeredComponents.get(componentProto.id); @@ -38,9 +51,8 @@ export abstract class DomRootRenderer implements RootRenderer { @Injectable() export class DomRootRenderer_ extends DomRootRenderer { - constructor( - @Inject(DOCUMENT) _document: any, _eventManager: EventManager, - sharedStylesHost: DomSharedStylesHost, animate: AnimationBuilder) { + constructor(@Inject(DOCUMENT) _document: any, _eventManager: EventManager, + sharedStylesHost: DomSharedStylesHost, animate: AnimationBuilder) { super(_document, _eventManager, sharedStylesHost, animate); } } @@ -80,8 +92,8 @@ export class DomRenderer implements Renderer { createElement(parent: Element, name: string): Node { var nsAndName = splitNamespace(name); var el = isPresent(nsAndName[0]) ? - DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : - DOM.createElement(nsAndName[1]); + DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : + DOM.createElement(nsAndName[1]); if (isPresent(this._contentAttr)) { DOM.setAttribute(el, this._contentAttr, ''); } @@ -149,13 +161,13 @@ export class DomRenderer implements Renderer { } listen(renderElement: any, name: string, callback: Function): Function { - return this._rootRenderer.eventManager.addEventListener( - renderElement, name, decoratePreventDefault(callback)); + return this._rootRenderer.eventManager.addEventListener(renderElement, name, + decoratePreventDefault(callback)); } listenGlobal(target: string, name: string, callback: Function): Function { - return this._rootRenderer.eventManager.addGlobalEventListener( - target, name, decoratePreventDefault(callback)); + return this._rootRenderer.eventManager.addGlobalEventListener(target, name, + decoratePreventDefault(callback)); } setElementProperty(renderElement: any, propertyName: string, propertyValue: any): void { @@ -191,9 +203,8 @@ export class DomRenderer implements Renderer { TEMPLATE_BINDINGS_EXP, StringWrapper.replaceAll(DOM.getText(renderElement), /\n/g, '')); var parsedBindings = Json.parse(existingBindings[1]); parsedBindings[dashCasedPropertyName] = propertyValue; - DOM.setText( - renderElement, - StringWrapper.replace(TEMPLATE_COMMENT_TEXT, '{}', Json.stringify(parsedBindings))); + DOM.setText(renderElement, StringWrapper.replace(TEMPLATE_COMMENT_TEXT, '{}', + Json.stringify(parsedBindings))); } else { this.setElementAttribute(renderElement, propertyName, propertyValue); } @@ -304,7 +315,7 @@ function _shimHostAttribute(componentShortId: string): string { return StringWrapper.replaceAll(HOST_ATTR, COMPONENT_REGEX, componentShortId); } -function _flattenStyles(compId: string, styles: Array<any|any[]>, target: string[]): string[] { +function _flattenStyles(compId: string, styles: Array<any | any[]>, target: string[]): string[] { for (var i = 0; i < styles.length; i++) { var style = styles[i]; if (isArray(style)) { diff --git a/modules/angular2/src/platform/dom/events/event_manager.ts b/modules/angular2/src/platform/dom/events/event_manager.ts index 87a3a5368e..1f2f2a1b18 100644 --- a/modules/angular2/src/platform/dom/events/event_manager.ts +++ b/modules/angular2/src/platform/dom/events/event_manager.ts @@ -5,7 +5,7 @@ import {NgZone} from 'angular2/src/core/zone/ng_zone'; import {ListWrapper} from 'angular2/src/facade/collection'; export const EVENT_MANAGER_PLUGINS: OpaqueToken = - CONST_EXPR(new OpaqueToken('EventManagerPlugins')); + CONST_EXPR(new OpaqueToken("EventManagerPlugins")); @Injectable() export class EventManager { @@ -48,10 +48,10 @@ export class EventManagerPlugin { supports(eventName: string): boolean { return false; } addEventListener(element: HTMLElement, eventName: string, handler: Function): Function { - throw 'not implemented'; + throw "not implemented"; } addGlobalEventListener(element: string, eventName: string, handler: Function): Function { - throw 'not implemented'; + throw "not implemented"; } } \ No newline at end of file diff --git a/modules/angular2/src/platform/dom/events/hammer_gestures.ts b/modules/angular2/src/platform/dom/events/hammer_gestures.ts index 381f6e49cf..5fcbb97b6b 100644 --- a/modules/angular2/src/platform/dom/events/hammer_gestures.ts +++ b/modules/angular2/src/platform/dom/events/hammer_gestures.ts @@ -4,7 +4,7 @@ import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Injectable, Inject, OpaqueToken} from 'angular2/core'; export const HAMMER_GESTURE_CONFIG: OpaqueToken = - CONST_EXPR(new OpaqueToken('HammerGestureConfig')); + CONST_EXPR(new OpaqueToken("HammerGestureConfig")); export interface HammerInstance { on(eventName: string, callback: Function): void; diff --git a/modules/angular2/src/platform/dom/events/key_events.ts b/modules/angular2/src/platform/dom/events/key_events.ts index d4e683d835..551c82f3ec 100644 --- a/modules/angular2/src/platform/dom/events/key_events.ts +++ b/modules/angular2/src/platform/dom/events/key_events.ts @@ -1,5 +1,11 @@ import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {isPresent, isBlank, StringWrapper, RegExpWrapper, NumberWrapper} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + StringWrapper, + RegExpWrapper, + NumberWrapper +} from 'angular2/src/facade/lang'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {EventManagerPlugin} from './event_manager'; import {NgZone} from 'angular2/src/core/zone/ng_zone'; @@ -28,8 +34,8 @@ export class KeyEventsPlugin extends EventManagerPlugin { element, StringMapWrapper.get(parsedEvent, 'fullKey'), handler, this.manager.getZone()); return this.manager.getZone().runOutsideAngular(() => { - return DOM.onAndCancel( - element, StringMapWrapper.get(parsedEvent, 'domEventName'), outsideHandler); + return DOM.onAndCancel(element, StringMapWrapper.get(parsedEvent, 'domEventName'), + outsideHandler); }); } @@ -85,8 +91,8 @@ export class KeyEventsPlugin extends EventManagerPlugin { return fullKey; } - static eventCallback(element: HTMLElement, fullKey: any, handler: Function, zone: NgZone): - Function { + static eventCallback(element: HTMLElement, fullKey: any, handler: Function, + zone: NgZone): Function { return (event) => { if (StringWrapper.equals(KeyEventsPlugin.getEventFullKey(event), fullKey)) { zone.run(() => handler(event)); diff --git a/modules/angular2/src/platform/dom/util.ts b/modules/angular2/src/platform/dom/util.ts index 41fd07256c..7f074e0f62 100644 --- a/modules/angular2/src/platform/dom/util.ts +++ b/modules/angular2/src/platform/dom/util.ts @@ -5,11 +5,11 @@ var DASH_CASE_REGEXP = /-([a-z])/g; export function camelCaseToDashCase(input: string): string { - return StringWrapper.replaceAllMapped( - input, CAMEL_CASE_REGEXP, (m) => { return '-' + m[1].toLowerCase(); }); + return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, + (m) => { return '-' + m[1].toLowerCase(); }); } export function dashCaseToCamelCase(input: string): string { - return StringWrapper.replaceAllMapped( - input, DASH_CASE_REGEXP, (m) => { return m[1].toUpperCase(); }); + return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, + (m) => { return m[1].toUpperCase(); }); } diff --git a/modules/angular2/src/platform/server/parse5_adapter.ts b/modules/angular2/src/platform/server/parse5_adapter.ts index 96215063a9..1d9e776229 100644 --- a/modules/angular2/src/platform/server/parse5_adapter.ts +++ b/modules/angular2/src/platform/server/parse5_adapter.ts @@ -5,7 +5,14 @@ var treeAdapter = parser.treeAdapter; import {MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {DomAdapter, setRootDomAdapter} from 'angular2/platform/common_dom'; -import {isPresent, isBlank, global, Type, setValueOnPath, DateWrapper} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + global, + Type, + setValueOnPath, + DateWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {SelectorMatcher, CssSelector} from 'angular2/src/compiler/selector'; import {XHR} from 'angular2/src/compiler/xhr'; @@ -37,7 +44,7 @@ export class Parse5DomAdapter extends DomAdapter { if (name === 'innerHTML') { this.setInnerHTML(el, value); } else if (name === 'className') { - el.attribs['class'] = el.className = value; + el.attribs["class"] = el.className = value; } else { el[name] = value; } @@ -84,7 +91,7 @@ export class Parse5DomAdapter extends DomAdapter { return true; } var result = false; - if (selector && selector.charAt(0) == '#') { + if (selector && selector.charAt(0) == "#") { result = this.getAttribute(node, 'id') == selector.substring(1); } else if (selector) { var result = false; @@ -240,9 +247,9 @@ export class Parse5DomAdapter extends DomAdapter { // However, comment node instances return the comment content for textContent getter return isRecursive ? '' : el.data; } else if (isBlank(el.childNodes) || el.childNodes.length == 0) { - return ''; + return ""; } else { - var textContent = ''; + var textContent = ""; for (var i = 0; i < el.childNodes.length; i++) { textContent += this.getText(el.childNodes[i], true); } @@ -263,7 +270,7 @@ export class Parse5DomAdapter extends DomAdapter { setChecked(el, value: boolean) { el.checked = value; } createComment(text: string): Comment { return treeAdapter.createCommentNode(text); } createTemplate(html): HTMLElement { - var template = treeAdapter.createElement('template', 'http://www.w3.org/1999/xhtml', []); + var template = treeAdapter.createElement("template", 'http://www.w3.org/1999/xhtml', []); var content = parser.parseFragment(html); treeAdapter.appendChild(template, content); return template; @@ -278,8 +285,8 @@ export class Parse5DomAdapter extends DomAdapter { return t; } createScriptTag(attrName: string, attrValue: string): HTMLElement { - return treeAdapter.createElement( - 'script', 'http://www.w3.org/1999/xhtml', [{name: attrName, value: attrValue}]); + return treeAdapter.createElement("script", 'http://www.w3.org/1999/xhtml', + [{name: attrName, value: attrValue}]); } createStyleElement(css: string): HTMLStyleElement { var style = this.createElement('style'); @@ -336,7 +343,7 @@ export class Parse5DomAdapter extends DomAdapter { return _recursive(node); } getElementsByClassName(element, name: string): HTMLElement[] { - return this.querySelectorAll(element, '.' + name); + return this.querySelectorAll(element, "." + name); } getElementsByTagName(element: any, name: string): HTMLElement[] { throw _notImplemented('getElementsByTagName'); @@ -344,8 +351,8 @@ export class Parse5DomAdapter extends DomAdapter { classList(element): string[] { var classAttrValue = null; var attributes = element.attribs; - if (attributes && attributes.hasOwnProperty('class')) { - classAttrValue = attributes['class']; + if (attributes && attributes.hasOwnProperty("class")) { + classAttrValue = attributes["class"]; } return classAttrValue ? classAttrValue.trim().split(/\s+/g) : []; } @@ -354,7 +361,7 @@ export class Parse5DomAdapter extends DomAdapter { var index = classList.indexOf(className); if (index == -1) { classList.push(className); - element.attribs['class'] = element.className = classList.join(' '); + element.attribs["class"] = element.className = classList.join(" "); } } removeClass(element, className: string) { @@ -362,7 +369,7 @@ export class Parse5DomAdapter extends DomAdapter { var index = classList.indexOf(className); if (index > -1) { classList.splice(index, 1); - element.attribs['class'] = element.className = classList.join(' '); + element.attribs["class"] = element.className = classList.join(" "); } } hasClass(element, className: string): boolean { @@ -376,8 +383,8 @@ export class Parse5DomAdapter extends DomAdapter { _readStyleAttribute(element) { var styleMap = {}; var attributes = element.attribs; - if (attributes && attributes.hasOwnProperty('style')) { - var styleAttrValue = attributes['style']; + if (attributes && attributes.hasOwnProperty("style")) { + var styleAttrValue = attributes["style"]; var styleList = styleAttrValue.split(/;+/g); for (var i = 0; i < styleList.length; i++) { if (styleList[i].length > 0) { @@ -390,14 +397,14 @@ export class Parse5DomAdapter extends DomAdapter { } /** @internal */ _writeStyleAttribute(element, styleMap) { - var styleAttrValue = ''; + var styleAttrValue = ""; for (var key in styleMap) { var newValue = styleMap[key]; if (newValue && newValue.length > 0) { - styleAttrValue += key + ':' + styleMap[key] + ';'; + styleAttrValue += key + ":" + styleMap[key] + ";"; } } - element.attribs['style'] = styleAttrValue; + element.attribs["style"] = styleAttrValue; } setStyle(element, styleName: string, styleValue: string) { var styleMap = this._readStyleAttribute(element); @@ -407,9 +414,9 @@ export class Parse5DomAdapter extends DomAdapter { removeStyle(element, styleName: string) { this.setStyle(element, styleName, null); } getStyle(element, styleName: string): string { var styleMap = this._readStyleAttribute(element); - return styleMap.hasOwnProperty(styleName) ? styleMap[styleName] : ''; + return styleMap.hasOwnProperty(styleName) ? styleMap[styleName] : ""; } - tagName(element): string { return element.tagName == 'style' ? 'STYLE' : element.tagName; } + tagName(element): string { return element.tagName == "style" ? "STYLE" : element.tagName; } attributeMap(element): Map<string, string> { var res = new Map<string, string>(); var elAttrs = treeAdapter.getAttrList(element); @@ -425,8 +432,8 @@ export class Parse5DomAdapter extends DomAdapter { hasAttributeNS(element, ns: string, attribute: string): boolean { throw 'not implemented'; } getAttribute(element, attribute: string): string { return element.attribs && element.attribs.hasOwnProperty(attribute) ? - element.attribs[attribute] : - null; + element.attribs[attribute] : + null; } getAttributeNS(element, ns: string, attribute: string): string { throw 'not implemented'; } setAttribute(element, attribute: string, value: string) { @@ -447,14 +454,14 @@ export class Parse5DomAdapter extends DomAdapter { templateAwareRoot(el): any { return this.isTemplateElement(el) ? this.content(el) : el; } createHtmlDocument(): Document { var newDoc = treeAdapter.createDocument(); - newDoc.title = 'fake title'; - var head = treeAdapter.createElement('head', null, []); - var body = treeAdapter.createElement('body', 'http://www.w3.org/1999/xhtml', []); + newDoc.title = "fake title"; + var head = treeAdapter.createElement("head", null, []); + var body = treeAdapter.createElement("body", 'http://www.w3.org/1999/xhtml', []); this.appendChild(newDoc, head); this.appendChild(newDoc, body); - StringMapWrapper.set(newDoc, 'head', head); - StringMapWrapper.set(newDoc, 'body', body); - StringMapWrapper.set(newDoc, '_window', StringMapWrapper.create()); + StringMapWrapper.set(newDoc, "head", head); + StringMapWrapper.set(newDoc, "body", body); + StringMapWrapper.set(newDoc, "_window", StringMapWrapper.create()); return newDoc; } defaultDoc(): Document { @@ -464,10 +471,10 @@ export class Parse5DomAdapter extends DomAdapter { return defDoc; } getBoundingClientRect(el): any { return {left: 0, top: 0, width: 0, height: 0}; } - getTitle(): string { return this.defaultDoc().title || ''; } + getTitle(): string { return this.defaultDoc().title || ""; } setTitle(newTitle: string) { this.defaultDoc().title = newTitle; } isTemplateElement(el: any): boolean { - return this.isElementNode(el) && this.tagName(el) === 'template'; + return this.isElementNode(el) && this.tagName(el) === "template"; } isTextNode(node): boolean { return treeAdapter.isTextNode(node); } isCommentNode(node): boolean { return treeAdapter.isCommentNode(node); } @@ -490,32 +497,31 @@ export class Parse5DomAdapter extends DomAdapter { for (var i = 0; i < parsedRules.length; i++) { var parsedRule = parsedRules[i]; var rule: {[key: string]: any} = StringMapWrapper.create(); - StringMapWrapper.set(rule, 'cssText', css); - StringMapWrapper.set(rule, 'style', {content: '', cssText: ''}); - if (parsedRule.type == 'rule') { - StringMapWrapper.set(rule, 'type', 1); - StringMapWrapper.set( - rule, 'selectorText', parsedRule.selectors.join(', ') - .replace(/\s{2,}/g, ' ') - .replace(/\s*~\s*/g, ' ~ ') - .replace(/\s*\+\s*/g, ' + ') - .replace(/\s*>\s*/g, ' > ') - .replace(/\[(\w+)=(\w+)\]/g, '[$1="$2"]')); + StringMapWrapper.set(rule, "cssText", css); + StringMapWrapper.set(rule, "style", {content: "", cssText: ""}); + if (parsedRule.type == "rule") { + StringMapWrapper.set(rule, "type", 1); + StringMapWrapper.set(rule, "selectorText", parsedRule.selectors.join(", ") + .replace(/\s{2,}/g, " ") + .replace(/\s*~\s*/g, " ~ ") + .replace(/\s*\+\s*/g, " + ") + .replace(/\s*>\s*/g, " > ") + .replace(/\[(\w+)=(\w+)\]/g, '[$1="$2"]')); if (isBlank(parsedRule.declarations)) { continue; } for (var j = 0; j < parsedRule.declarations.length; j++) { var declaration = parsedRule.declarations[j]; - StringMapWrapper.set( - StringMapWrapper.get(rule, 'style'), declaration.property, declaration.value); - StringMapWrapper.get(rule, 'style').cssText += - declaration.property + ': ' + declaration.value + ';'; + StringMapWrapper.set(StringMapWrapper.get(rule, "style"), declaration.property, + declaration.value); + StringMapWrapper.get(rule, "style").cssText += + declaration.property + ": " + declaration.value + ";"; } - } else if (parsedRule.type == 'media') { - StringMapWrapper.set(rule, 'type', 4); - StringMapWrapper.set(rule, 'media', {mediaText: parsedRule.media}); + } else if (parsedRule.type == "media") { + StringMapWrapper.set(rule, "type", 4); + StringMapWrapper.set(rule, "media", {mediaText: parsedRule.media}); if (parsedRule.rules) { - StringMapWrapper.set(rule, 'cssRules', this._buildRules(parsedRule.rules)); + StringMapWrapper.set(rule, "cssRules", this._buildRules(parsedRule.rules)); } } rules.push(rule); @@ -525,11 +531,11 @@ export class Parse5DomAdapter extends DomAdapter { supportsDOMEvents(): boolean { return false; } supportsNativeShadowDOM(): boolean { return false; } getGlobalEventTarget(target: string): any { - if (target == 'window') { + if (target == "window") { return (<any>this.defaultDoc())._window; - } else if (target == 'document') { + } else if (target == "document") { return this.defaultDoc(); - } else if (target == 'body') { + } else if (target == "body") { return this.defaultDoc().body; } } @@ -537,7 +543,7 @@ export class Parse5DomAdapter extends DomAdapter { resetBaseElement(): void { throw 'not implemented'; } getHistory(): History { throw 'not implemented'; } getLocation(): Location { throw 'not implemented'; } - getUserAgent(): string { return 'Fake user agent'; } + getUserAgent(): string { return "Fake user agent"; } getData(el, name: string): string { return this.getAttribute(el, 'data-' + name); } getComputedStyle(el): any { throw 'not implemented'; } setData(el, name: string, value: string) { this.setAttribute(el, 'data-' + name, value); } @@ -558,186 +564,186 @@ export class Parse5DomAdapter extends DomAdapter { // TODO: build a proper list, this one is all the keys of a HTMLInputElement var _HTMLElementPropertyList = [ - 'webkitEntries', - 'incremental', - 'webkitdirectory', - 'selectionDirection', - 'selectionEnd', - 'selectionStart', - 'labels', - 'validationMessage', - 'validity', - 'willValidate', - 'width', - 'valueAsNumber', - 'valueAsDate', - 'value', - 'useMap', - 'defaultValue', - 'type', - 'step', - 'src', - 'size', - 'required', - 'readOnly', - 'placeholder', - 'pattern', - 'name', - 'multiple', - 'min', - 'minLength', - 'maxLength', - 'max', - 'list', - 'indeterminate', - 'height', - 'formTarget', - 'formNoValidate', - 'formMethod', - 'formEnctype', - 'formAction', - 'files', - 'form', - 'disabled', - 'dirName', - 'checked', - 'defaultChecked', - 'autofocus', - 'autocomplete', - 'alt', - 'align', - 'accept', - 'onautocompleteerror', - 'onautocomplete', - 'onwaiting', - 'onvolumechange', - 'ontoggle', - 'ontimeupdate', - 'onsuspend', - 'onsubmit', - 'onstalled', - 'onshow', - 'onselect', - 'onseeking', - 'onseeked', - 'onscroll', - 'onresize', - 'onreset', - 'onratechange', - 'onprogress', - 'onplaying', - 'onplay', - 'onpause', - 'onmousewheel', - 'onmouseup', - 'onmouseover', - 'onmouseout', - 'onmousemove', - 'onmouseleave', - 'onmouseenter', - 'onmousedown', - 'onloadstart', - 'onloadedmetadata', - 'onloadeddata', - 'onload', - 'onkeyup', - 'onkeypress', - 'onkeydown', - 'oninvalid', - 'oninput', - 'onfocus', - 'onerror', - 'onended', - 'onemptied', - 'ondurationchange', - 'ondrop', - 'ondragstart', - 'ondragover', - 'ondragleave', - 'ondragenter', - 'ondragend', - 'ondrag', - 'ondblclick', - 'oncuechange', - 'oncontextmenu', - 'onclose', - 'onclick', - 'onchange', - 'oncanplaythrough', - 'oncanplay', - 'oncancel', - 'onblur', - 'onabort', - 'spellcheck', - 'isContentEditable', - 'contentEditable', - 'outerText', - 'innerText', - 'accessKey', - 'hidden', - 'webkitdropzone', - 'draggable', - 'tabIndex', - 'dir', - 'translate', - 'lang', - 'title', - 'childElementCount', - 'lastElementChild', - 'firstElementChild', - 'children', - 'onwebkitfullscreenerror', - 'onwebkitfullscreenchange', - 'nextElementSibling', - 'previousElementSibling', - 'onwheel', - 'onselectstart', - 'onsearch', - 'onpaste', - 'oncut', - 'oncopy', - 'onbeforepaste', - 'onbeforecut', - 'onbeforecopy', - 'shadowRoot', - 'dataset', - 'classList', - 'className', - 'outerHTML', - 'innerHTML', - 'scrollHeight', - 'scrollWidth', - 'scrollTop', - 'scrollLeft', - 'clientHeight', - 'clientWidth', - 'clientTop', - 'clientLeft', - 'offsetParent', - 'offsetHeight', - 'offsetWidth', - 'offsetTop', - 'offsetLeft', - 'localName', - 'prefix', - 'namespaceURI', - 'id', - 'style', - 'attributes', - 'tagName', - 'parentElement', - 'textContent', - 'baseURI', - 'ownerDocument', - 'nextSibling', - 'previousSibling', - 'lastChild', - 'firstChild', - 'childNodes', - 'parentNode', - 'nodeType', - 'nodeValue', - 'nodeName', - 'closure_lm_714617', - '__jsaction' + "webkitEntries", + "incremental", + "webkitdirectory", + "selectionDirection", + "selectionEnd", + "selectionStart", + "labels", + "validationMessage", + "validity", + "willValidate", + "width", + "valueAsNumber", + "valueAsDate", + "value", + "useMap", + "defaultValue", + "type", + "step", + "src", + "size", + "required", + "readOnly", + "placeholder", + "pattern", + "name", + "multiple", + "min", + "minLength", + "maxLength", + "max", + "list", + "indeterminate", + "height", + "formTarget", + "formNoValidate", + "formMethod", + "formEnctype", + "formAction", + "files", + "form", + "disabled", + "dirName", + "checked", + "defaultChecked", + "autofocus", + "autocomplete", + "alt", + "align", + "accept", + "onautocompleteerror", + "onautocomplete", + "onwaiting", + "onvolumechange", + "ontoggle", + "ontimeupdate", + "onsuspend", + "onsubmit", + "onstalled", + "onshow", + "onselect", + "onseeking", + "onseeked", + "onscroll", + "onresize", + "onreset", + "onratechange", + "onprogress", + "onplaying", + "onplay", + "onpause", + "onmousewheel", + "onmouseup", + "onmouseover", + "onmouseout", + "onmousemove", + "onmouseleave", + "onmouseenter", + "onmousedown", + "onloadstart", + "onloadedmetadata", + "onloadeddata", + "onload", + "onkeyup", + "onkeypress", + "onkeydown", + "oninvalid", + "oninput", + "onfocus", + "onerror", + "onended", + "onemptied", + "ondurationchange", + "ondrop", + "ondragstart", + "ondragover", + "ondragleave", + "ondragenter", + "ondragend", + "ondrag", + "ondblclick", + "oncuechange", + "oncontextmenu", + "onclose", + "onclick", + "onchange", + "oncanplaythrough", + "oncanplay", + "oncancel", + "onblur", + "onabort", + "spellcheck", + "isContentEditable", + "contentEditable", + "outerText", + "innerText", + "accessKey", + "hidden", + "webkitdropzone", + "draggable", + "tabIndex", + "dir", + "translate", + "lang", + "title", + "childElementCount", + "lastElementChild", + "firstElementChild", + "children", + "onwebkitfullscreenerror", + "onwebkitfullscreenchange", + "nextElementSibling", + "previousElementSibling", + "onwheel", + "onselectstart", + "onsearch", + "onpaste", + "oncut", + "oncopy", + "onbeforepaste", + "onbeforecut", + "onbeforecopy", + "shadowRoot", + "dataset", + "classList", + "className", + "outerHTML", + "innerHTML", + "scrollHeight", + "scrollWidth", + "scrollTop", + "scrollLeft", + "clientHeight", + "clientWidth", + "clientTop", + "clientLeft", + "offsetParent", + "offsetHeight", + "offsetWidth", + "offsetTop", + "offsetLeft", + "localName", + "prefix", + "namespaceURI", + "id", + "style", + "attributes", + "tagName", + "parentElement", + "textContent", + "baseURI", + "ownerDocument", + "nextSibling", + "previousSibling", + "lastChild", + "firstChild", + "childNodes", + "parentNode", + "nodeType", + "nodeValue", + "nodeName", + "closure_lm_714617", + "__jsaction" ]; diff --git a/modules/angular2/src/platform/worker_app.ts b/modules/angular2/src/platform/worker_app.ts index b1e03c7c8c..cb014694c2 100644 --- a/modules/angular2/src/platform/worker_app.ts +++ b/modules/angular2/src/platform/worker_app.ts @@ -2,7 +2,11 @@ import {NgZone} from 'angular2/src/core/zone/ng_zone'; import {Type, CONST_EXPR, isPresent} from 'angular2/src/facade/lang'; import {Provider} from 'angular2/src/core/di'; import {Parse5DomAdapter} from 'angular2/src/platform/server/parse5_adapter'; -import {PostMessageBus, PostMessageBusSink, PostMessageBusSource} from 'angular2/src/web_workers/shared/post_message_bus'; +import { + PostMessageBus, + PostMessageBusSink, + PostMessageBusSource +} from 'angular2/src/web_workers/shared/post_message_bus'; import {WORKER_APP_APPLICATION_COMMON} from './worker_app_common'; import {APP_INITIALIZER} from 'angular2/core'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; @@ -10,13 +14,14 @@ import {COMPILER_PROVIDERS} from 'angular2/src/compiler/compiler'; // TODO(jteplitz602) remove this and compile with lib.webworker.d.ts (#3492) let _postMessage = { - postMessage: (message: any, transferrables?: [ArrayBuffer]) => { + postMessage: (message: any, transferrables?:[ArrayBuffer]) => { (<any>postMessage)(message, transferrables); } }; export const WORKER_APP_APPLICATION: Array<any /*Type | Provider | any[]*/> = [ - WORKER_APP_APPLICATION_COMMON, COMPILER_PROVIDERS, + WORKER_APP_APPLICATION_COMMON, + COMPILER_PROVIDERS, new Provider(MessageBus, {useFactory: createMessageBus, deps: [NgZone]}), new Provider(APP_INITIALIZER, {useValue: setupWebWorker, multi: true}) ]; diff --git a/modules/angular2/src/platform/worker_app_common.ts b/modules/angular2/src/platform/worker_app_common.ts index 1b22ba5247..7157dfee8b 100644 --- a/modules/angular2/src/platform/worker_app_common.ts +++ b/modules/angular2/src/platform/worker_app_common.ts @@ -3,12 +3,24 @@ import {WebWorkerXHRImpl} from 'angular2/src/web_workers/worker/xhr_impl'; import {WebWorkerRootRenderer} from 'angular2/src/web_workers/worker/renderer'; import {print, Type, CONST_EXPR, isPresent} from 'angular2/src/facade/lang'; import {RootRenderer} from 'angular2/src/core/render/api'; -import {PLATFORM_DIRECTIVES, PLATFORM_PIPES, ExceptionHandler, APPLICATION_COMMON_PROVIDERS, PLATFORM_COMMON_PROVIDERS,} from 'angular2/core'; -import {COMMON_DIRECTIVES, COMMON_PIPES, FORM_PROVIDERS} from 'angular2/common'; -import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from 'angular2/src/web_workers/shared/client_message_broker'; -import {ServiceMessageBrokerFactory, ServiceMessageBrokerFactory_} from 'angular2/src/web_workers/shared/service_message_broker'; -import {Serializer} from 'angular2/src/web_workers/shared/serializer'; -import {ON_WEB_WORKER} from 'angular2/src/web_workers/shared/api'; +import { + PLATFORM_DIRECTIVES, + PLATFORM_PIPES, + ExceptionHandler, + APPLICATION_COMMON_PROVIDERS, + PLATFORM_COMMON_PROVIDERS, +} from 'angular2/core'; +import {COMMON_DIRECTIVES, COMMON_PIPES, FORM_PROVIDERS} from "angular2/common"; +import { + ClientMessageBrokerFactory, + ClientMessageBrokerFactory_ +} from 'angular2/src/web_workers/shared/client_message_broker'; +import { + ServiceMessageBrokerFactory, + ServiceMessageBrokerFactory_ +} from 'angular2/src/web_workers/shared/service_message_broker'; +import {Serializer} from "angular2/src/web_workers/shared/serializer"; +import {ON_WEB_WORKER} from "angular2/src/web_workers/shared/api"; import {Provider} from 'angular2/src/core/di'; import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; @@ -23,14 +35,19 @@ export const WORKER_APP_PLATFORM: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([PLATFORM_COMMON_PROVIDERS]); export const WORKER_APP_APPLICATION_COMMON: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([ - APPLICATION_COMMON_PROVIDERS, FORM_PROVIDERS, Serializer, + APPLICATION_COMMON_PROVIDERS, + FORM_PROVIDERS, + Serializer, new Provider(PLATFORM_PIPES, {useValue: COMMON_PIPES, multi: true}), new Provider(PLATFORM_DIRECTIVES, {useValue: COMMON_DIRECTIVES, multi: true}), new Provider(ClientMessageBrokerFactory, {useClass: ClientMessageBrokerFactory_}), new Provider(ServiceMessageBrokerFactory, {useClass: ServiceMessageBrokerFactory_}), - WebWorkerRootRenderer, new Provider(RootRenderer, {useExisting: WebWorkerRootRenderer}), - new Provider(ON_WEB_WORKER, {useValue: true}), RenderStore, - new Provider(ExceptionHandler, {useFactory: _exceptionHandler, deps: []}), WebWorkerXHRImpl, + WebWorkerRootRenderer, + new Provider(RootRenderer, {useExisting: WebWorkerRootRenderer}), + new Provider(ON_WEB_WORKER, {useValue: true}), + RenderStore, + new Provider(ExceptionHandler, {useFactory: _exceptionHandler, deps: []}), + WebWorkerXHRImpl, new Provider(XHR, {useExisting: WebWorkerXHRImpl}) ]); diff --git a/modules/angular2/src/platform/worker_render.ts b/modules/angular2/src/platform/worker_render.ts index a7b1fe6caa..2d34aaa3ee 100644 --- a/modules/angular2/src/platform/worker_render.ts +++ b/modules/angular2/src/platform/worker_render.ts @@ -1,10 +1,19 @@ -import {PostMessageBus, PostMessageBusSink, PostMessageBusSource} from 'angular2/src/web_workers/shared/post_message_bus'; +import { + PostMessageBus, + PostMessageBusSink, + PostMessageBusSource +} from 'angular2/src/web_workers/shared/post_message_bus'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; import {APP_INITIALIZER} from 'angular2/core'; import {Injector, Injectable, Provider} from 'angular2/src/core/di'; import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer'; import {MessageBasedXHRImpl} from 'angular2/src/web_workers/ui/xhr_impl'; -import {WORKER_RENDER_APPLICATION_COMMON, WORKER_RENDER_MESSAGING_PROVIDERS, WORKER_SCRIPT, initializeGenericWorkerRenderer} from 'angular2/src/platform/worker_render_common'; +import { + WORKER_RENDER_APPLICATION_COMMON, + WORKER_RENDER_MESSAGING_PROVIDERS, + WORKER_SCRIPT, + initializeGenericWorkerRenderer +} from 'angular2/src/platform/worker_render_common'; import {BaseException} from 'angular2/src/facade/exceptions'; import {CONST_EXPR} from 'angular2/src/facade/lang'; @@ -28,11 +37,14 @@ export class WebWorkerInstance { * An array of providers that should be passed into `application()` when initializing a new Worker. */ export const WORKER_RENDER_APPLICATION: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([ - WORKER_RENDER_APPLICATION_COMMON, WebWorkerInstance, new Provider(APP_INITIALIZER, { - useFactory: (injector) => () => initWebWorkerApplication(injector), - multi: true, - deps: [Injector] - }), + WORKER_RENDER_APPLICATION_COMMON, + WebWorkerInstance, + new Provider(APP_INITIALIZER, + { + useFactory: (injector) => () => initWebWorkerApplication(injector), + multi: true, + deps: [Injector] + }), new Provider(MessageBus, {useFactory: (instance) => instance.bus, deps: [WebWorkerInstance]}) ]); @@ -42,7 +54,7 @@ function initWebWorkerApplication(injector: Injector): void { scriptUri = injector.get(WORKER_SCRIPT); } catch (e) { throw new BaseException( - 'You must provide your WebWorker\'s initialization script with the WORKER_SCRIPT token'); + "You must provide your WebWorker's initialization script with the WORKER_SCRIPT token"); } let instance = injector.get(WebWorkerInstance); diff --git a/modules/angular2/src/platform/worker_render_common.ts b/modules/angular2/src/platform/worker_render_common.ts index c76fa695f8..59360b5335 100644 --- a/modules/angular2/src/platform/worker_render_common.ts +++ b/modules/angular2/src/platform/worker_render_common.ts @@ -1,7 +1,20 @@ import {CONST_EXPR, IS_DART} from 'angular2/src/facade/lang'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; import {NgZone} from 'angular2/src/core/zone/ng_zone'; -import {PLATFORM_DIRECTIVES, PLATFORM_PIPES, ComponentRef, platform, ExceptionHandler, Reflector, reflector, APPLICATION_COMMON_PROVIDERS, PLATFORM_COMMON_PROVIDERS, RootRenderer, PLATFORM_INITIALIZER, APP_INITIALIZER} from 'angular2/core'; +import { + PLATFORM_DIRECTIVES, + PLATFORM_PIPES, + ComponentRef, + platform, + ExceptionHandler, + Reflector, + reflector, + APPLICATION_COMMON_PROVIDERS, + PLATFORM_COMMON_PROVIDERS, + RootRenderer, + PLATFORM_INITIALIZER, + APP_INITIALIZER +} from 'angular2/core'; import {EVENT_MANAGER_PLUGINS, EventManager} from 'angular2/platform/common_dom'; import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di'; // TODO change these imports once dom_adapter is moved out of core @@ -12,7 +25,7 @@ import {HammerGesturesPlugin} from 'angular2/src/platform/dom/events/hammer_gest import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; import {DomRootRenderer, DomRootRenderer_} from 'angular2/src/platform/dom/dom_renderer'; import {DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; -import {SharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; +import {SharedStylesHost} from "angular2/src/platform/dom/shared_styles_host"; import {BrowserDetails} from 'angular2/src/animate/browser_details'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; import {XHR} from 'angular2/compiler'; @@ -24,14 +37,20 @@ import {wtfInit} from 'angular2/src/core/profile/wtf_init'; import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer'; import {MessageBasedXHRImpl} from 'angular2/src/web_workers/ui/xhr_impl'; import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location'; -import {ServiceMessageBrokerFactory, ServiceMessageBrokerFactory_} from 'angular2/src/web_workers/shared/service_message_broker'; -import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from 'angular2/src/web_workers/shared/client_message_broker'; +import { + ServiceMessageBrokerFactory, + ServiceMessageBrokerFactory_ +} from 'angular2/src/web_workers/shared/service_message_broker'; +import { + ClientMessageBrokerFactory, + ClientMessageBrokerFactory_ +} from 'angular2/src/web_workers/shared/client_message_broker'; import {Serializer} from 'angular2/src/web_workers/shared/serializer'; import {ON_WEB_WORKER} from 'angular2/src/web_workers/shared/api'; import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; import {HAMMER_GESTURE_CONFIG, HammerGestureConfig} from './dom/events/hammer_gestures'; -export const WORKER_SCRIPT: OpaqueToken = CONST_EXPR(new OpaqueToken('WebWorkerScript')); +export const WORKER_SCRIPT: OpaqueToken = CONST_EXPR(new OpaqueToken("WebWorkerScript")); // Message based Worker classes that listen on the MessageBus export const WORKER_RENDER_MESSAGING_PROVIDERS: Array<any /*Type | Provider | any[]*/> = @@ -50,7 +69,8 @@ export const WORKER_RENDER_ROUTER: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([BrowserPlatformLocation]); export const WORKER_RENDER_APPLICATION_COMMON: Array<any /*Type | Provider | any[]*/> = CONST_EXPR([ - APPLICATION_COMMON_PROVIDERS, WORKER_RENDER_MESSAGING_PROVIDERS, + APPLICATION_COMMON_PROVIDERS, + WORKER_RENDER_MESSAGING_PROVIDERS, new Provider(ExceptionHandler, {useFactory: _exceptionHandler, deps: []}), new Provider(DOCUMENT, {useFactory: _document, deps: []}), // TODO(jteplitz602): Investigate if we definitely need EVENT_MANAGER on the render thread @@ -62,11 +82,18 @@ export const WORKER_RENDER_APPLICATION_COMMON: Array<any /*Type | Provider | any new Provider(DomRootRenderer, {useClass: DomRootRenderer_}), new Provider(RootRenderer, {useExisting: DomRootRenderer}), new Provider(SharedStylesHost, {useExisting: DomSharedStylesHost}), - new Provider(XHR, {useClass: XHRImpl}), MessageBasedXHRImpl, + new Provider(XHR, {useClass: XHRImpl}), + MessageBasedXHRImpl, new Provider(ServiceMessageBrokerFactory, {useClass: ServiceMessageBrokerFactory_}), - new Provider(ClientMessageBrokerFactory, {useClass: ClientMessageBrokerFactory_}), Serializer, - new Provider(ON_WEB_WORKER, {useValue: false}), RenderStore, DomSharedStylesHost, Testability, - BrowserDetails, AnimationBuilder, EventManager + new Provider(ClientMessageBrokerFactory, {useClass: ClientMessageBrokerFactory_}), + Serializer, + new Provider(ON_WEB_WORKER, {useValue: false}), + RenderStore, + DomSharedStylesHost, + Testability, + BrowserDetails, + AnimationBuilder, + EventManager ]); export function initializeGenericWorkerRenderer(injector: Injector) { diff --git a/modules/angular2/src/router/directives/router_link_transform.ts b/modules/angular2/src/router/directives/router_link_transform.ts index 81fe5bdb96..0b1dc99b4e 100644 --- a/modules/angular2/src/router/directives/router_link_transform.ts +++ b/modules/angular2/src/router/directives/router_link_transform.ts @@ -1,5 +1,19 @@ -import {TemplateAstVisitor, ElementAst, BoundDirectivePropertyAst, DirectiveAst, BoundElementPropertyAst} from 'angular2/compiler'; -import {AstTransformer, Quote, AST, EmptyExpr, LiteralArray, LiteralPrimitive, ASTWithSource} from 'angular2/src/core/change_detection/parser/ast'; +import { + TemplateAstVisitor, + ElementAst, + BoundDirectivePropertyAst, + DirectiveAst, + BoundElementPropertyAst +} from 'angular2/compiler'; +import { + AstTransformer, + Quote, + AST, + EmptyExpr, + LiteralArray, + LiteralPrimitive, + ASTWithSource +} from 'angular2/src/core/change_detection/parser/ast'; import {BaseException} from 'angular2/src/facade/exceptions'; import {Injectable} from 'angular2/core'; import {Parser} from 'angular2/src/core/change_detection/parser/parser'; @@ -37,7 +51,7 @@ class RouterLinkLexer { constructor(private parser: Parser, private exp: string) {} - tokenize(): Array<FixedPart|AuxiliaryStart|AuxiliaryEnd|Params> { + tokenize(): Array<FixedPart | AuxiliaryStart | AuxiliaryEnd | Params> { let tokens = []; while (this.index < this.exp.length) { tokens.push(this._parseToken()); @@ -77,7 +91,7 @@ class RouterLinkLexer { return new Params(this.parser.parseBinding(`{${paramsContent}}`, null).ast); } } - throw new BaseException('Cannot find \')\''); + throw new BaseException("Cannot find ')'"); } private _parseFixedPart() { @@ -100,7 +114,7 @@ class RouterLinkLexer { let fixed = this.exp.substring(start, this.index); if (start === this.index || !sawNonSlash || fixed.startsWith('//')) { - throw new BaseException('Invalid router link'); + throw new BaseException("Invalid router link"); } return new FixedPart(fixed); @@ -141,7 +155,7 @@ class RouterLinkAstTransformer extends AstTransformer { constructor(private parser: Parser) { super(); } visitQuote(ast: Quote): AST { - if (ast.prefix == 'route') { + if (ast.prefix == "route") { return parseRouterLinkExpression(this.parser, ast.uninterpretedExpression); } else { return super.visitQuote(ast); @@ -171,9 +185,8 @@ export class RouterLinkTransform implements TemplateAstVisitor { let updatedChildren = ast.children.map(c => c.visit(this, context)); let updatedInputs = ast.inputs.map(c => c.visit(this, context)); let updatedDirectives = ast.directives.map(c => c.visit(this, context)); - return new ElementAst( - ast.name, ast.attrs, updatedInputs, ast.outputs, ast.exportAsVars, updatedDirectives, - updatedChildren, ast.ngContentIndex, ast.sourceSpan); + return new ElementAst(ast.name, ast.attrs, updatedInputs, ast.outputs, ast.exportAsVars, + updatedDirectives, updatedChildren, ast.ngContentIndex, ast.sourceSpan); } visitVariable(ast: any, context: any): any { return ast; } @@ -190,14 +203,13 @@ export class RouterLinkTransform implements TemplateAstVisitor { visitDirective(ast: DirectiveAst, context: any): any { let updatedInputs = ast.inputs.map(c => c.visit(this, context)); - return new DirectiveAst( - ast.directive, updatedInputs, ast.hostProperties, ast.hostEvents, ast.exportAsVars, - ast.sourceSpan); + return new DirectiveAst(ast.directive, updatedInputs, ast.hostProperties, ast.hostEvents, + ast.exportAsVars, ast.sourceSpan); } visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any { let transformedValue = ast.value.visit(this.astTransformer); - return new BoundDirectivePropertyAst( - ast.directiveName, ast.templateName, transformedValue, ast.sourceSpan); + return new BoundDirectivePropertyAst(ast.directiveName, ast.templateName, transformedValue, + ast.sourceSpan); } } \ No newline at end of file diff --git a/modules/angular2/src/router/directives/router_outlet.ts b/modules/angular2/src/router/directives/router_outlet.ts index 9f8c8cb0db..bf156ec0ef 100644 --- a/modules/angular2/src/router/directives/router_outlet.ts +++ b/modules/angular2/src/router/directives/router_outlet.ts @@ -2,7 +2,17 @@ import {PromiseWrapper} from 'angular2/src/facade/async'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {isBlank, isPresent} from 'angular2/src/facade/lang'; -import {Directive, Attribute, DynamicComponentLoader, ComponentRef, ElementRef, Injector, provide, Dependency, OnDestroy} from 'angular2/core'; +import { + Directive, + Attribute, + DynamicComponentLoader, + ComponentRef, + ElementRef, + Injector, + provide, + Dependency, + OnDestroy +} from 'angular2/core'; import * as routerMod from '../router'; import {ComponentInstruction, RouteParams, RouteData} from '../instruction'; @@ -27,9 +37,8 @@ export class RouterOutlet implements OnDestroy { private _componentRef: Promise<ComponentRef> = null; private _currentInstruction: ComponentInstruction = null; - constructor( - private _elementRef: ElementRef, private _loader: DynamicComponentLoader, - private _parentRouter: routerMod.Router, @Attribute('name') nameAttr: string) { + constructor(private _elementRef: ElementRef, private _loader: DynamicComponentLoader, + private _parentRouter: routerMod.Router, @Attribute('name') nameAttr: string) { if (isPresent(nameAttr)) { this.name = nameAttr; this._parentRouter.registerAuxOutlet(this); @@ -156,8 +165,8 @@ export class RouterOutlet implements OnDestroy { (<CanReuse>ref.instance).routerCanReuse(nextInstruction, this._currentInstruction)); } else { result = nextInstruction == this._currentInstruction || - (isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) && - StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params)); + (isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) && + StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params)); } return <Promise<boolean>>PromiseWrapper.resolve(result); } diff --git a/modules/angular2/src/router/instruction.ts b/modules/angular2/src/router/instruction.ts index 742ae19b25..eda67fce83 100644 --- a/modules/angular2/src/router/instruction.ts +++ b/modules/angular2/src/router/instruction.ts @@ -110,9 +110,8 @@ export var BLANK_ROUTE_DATA = new RouteData(); * ``` */ export abstract class Instruction { - constructor( - public component: ComponentInstruction, public child: Instruction, - public auxInstruction: {[key: string]: Instruction}) {} + constructor(public component: ComponentInstruction, public child: Instruction, + public auxInstruction: {[key: string]: Instruction}) {} get urlPath(): string { return isPresent(this.component) ? this.component.urlPath : ''; } @@ -139,7 +138,7 @@ export abstract class Instruction { /** @internal */ _toNonRootUrl(): string { return this._stringifyPathMatrixAuxPrefixed() + - (isPresent(this.child) ? this.child._toNonRootUrl() : ''); + (isPresent(this.child) ? this.child._toNonRootUrl() : ''); } toUrlQuery(): string { return this.urlParams.length > 0 ? ('?' + this.urlParams.join('&')) : ''; } @@ -157,20 +156,20 @@ export abstract class Instruction { */ toUrlPath(): string { return this.urlPath + this._stringifyAux() + - (isPresent(this.child) ? this.child._toNonRootUrl() : ''); + (isPresent(this.child) ? this.child._toNonRootUrl() : ''); } // default instructions override these toLinkUrl(): string { return this.urlPath + this._stringifyAux() + - (isPresent(this.child) ? this.child._toLinkUrl() : '') + this.toUrlQuery(); + (isPresent(this.child) ? this.child._toLinkUrl() : '') + this.toUrlQuery(); } // this is the non-root version (called recursively) /** @internal */ _toLinkUrl(): string { return this._stringifyPathMatrixAuxPrefixed() + - (isPresent(this.child) ? this.child._toLinkUrl() : ''); + (isPresent(this.child) ? this.child._toLinkUrl() : ''); } /** @internal */ @@ -213,9 +212,8 @@ export abstract class Instruction { * a resolved instruction has an outlet instruction for itself, but maybe not for... */ export class ResolvedInstruction extends Instruction { - constructor( - component: ComponentInstruction, child: Instruction, - auxInstruction: {[key: string]: Instruction}) { + constructor(component: ComponentInstruction, child: Instruction, + auxInstruction: {[key: string]: Instruction}) { super(component, child, auxInstruction); } @@ -244,9 +242,8 @@ export class DefaultInstruction extends ResolvedInstruction { * Represents a component that may need to do some redirection or lazy loading at a later time. */ export class UnresolvedInstruction extends Instruction { - constructor( - private _resolver: () => Promise<Instruction>, private _urlPath: string = '', - private _urlParams: string[] = CONST_EXPR([])) { + constructor(private _resolver: () => Promise<Instruction>, private _urlPath: string = '', + private _urlParams: string[] = CONST_EXPR([])) { super(null, null, {}); } @@ -283,9 +280,8 @@ export class UnresolvedInstruction extends Instruction { export class RedirectInstruction extends ResolvedInstruction { - constructor( - component: ComponentInstruction, child: Instruction, - auxInstruction: {[key: string]: Instruction}, private _specificity: string) { + constructor(component: ComponentInstruction, child: Instruction, + auxInstruction: {[key: string]: Instruction}, private _specificity: string) { super(component, child, auxInstruction); } @@ -312,10 +308,9 @@ export class ComponentInstruction { /** * @internal */ - constructor( - public urlPath: string, public urlParams: string[], data: RouteData, public componentType, - public terminal: boolean, public specificity: string, - public params: {[key: string]: string} = null, public routeName: string) { + constructor(public urlPath: string, public urlParams: string[], data: RouteData, + public componentType, public terminal: boolean, public specificity: string, + public params: {[key: string]: string} = null, public routeName: string) { this.routeData = isPresent(data) ? data : BLANK_ROUTE_DATA; } } diff --git a/modules/angular2/src/router/interfaces.ts b/modules/angular2/src/router/interfaces.ts index 6c5fb2a99b..a8e39993f3 100644 --- a/modules/angular2/src/router/interfaces.ts +++ b/modules/angular2/src/router/interfaces.ts @@ -26,8 +26,9 @@ var __make_dart_analyzer_happy: Promise<any> = null; * {@example router/ts/on_activate/on_activate_example.ts region='routerOnActivate'} */ export interface OnActivate { - routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): - any|Promise<any>; + routerOnActivate(nextInstruction: ComponentInstruction, + prevInstruction: ComponentInstruction): any | + Promise<any>; } /** @@ -46,8 +47,8 @@ export interface OnActivate { * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} */ export interface OnReuse { - routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any - |Promise<any>; + routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any | + Promise<any>; } /** @@ -66,8 +67,9 @@ export interface OnReuse { * {@example router/ts/on_deactivate/on_deactivate_example.ts region='routerOnDeactivate'} */ export interface OnDeactivate { - routerOnDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): - any|Promise<any>; + routerOnDeactivate(nextInstruction: ComponentInstruction, + prevInstruction: ComponentInstruction): any | + Promise<any>; } /** @@ -91,8 +93,9 @@ export interface OnDeactivate { * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} */ export interface CanReuse { - routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): - boolean|Promise<boolean>; + routerCanReuse(nextInstruction: ComponentInstruction, + prevInstruction: ComponentInstruction): boolean | + Promise<boolean>; } /** @@ -115,6 +118,7 @@ export interface CanReuse { * {@example router/ts/can_deactivate/can_deactivate_example.ts region='routerCanDeactivate'} */ export interface CanDeactivate { - routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): - boolean|Promise<boolean>; + routerCanDeactivate(nextInstruction: ComponentInstruction, + prevInstruction: ComponentInstruction): boolean | + Promise<boolean>; } diff --git a/modules/angular2/src/router/lifecycle/lifecycle_annotations.ts b/modules/angular2/src/router/lifecycle/lifecycle_annotations.ts index 94f0f1853d..c94143c665 100644 --- a/modules/angular2/src/router/lifecycle/lifecycle_annotations.ts +++ b/modules/angular2/src/router/lifecycle/lifecycle_annotations.ts @@ -7,7 +7,13 @@ import {makeDecorator} from 'angular2/src/core/util/decorators'; import {CanActivate as CanActivateAnnotation} from './lifecycle_annotations_impl'; import {ComponentInstruction} from '../instruction'; -export {routerCanReuse, routerCanDeactivate, routerOnActivate, routerOnReuse, routerOnDeactivate} from './lifecycle_annotations_impl'; +export { + routerCanReuse, + routerCanDeactivate, + routerOnActivate, + routerOnReuse, + routerOnDeactivate +} from './lifecycle_annotations_impl'; /** * Defines route lifecycle hook `CanActivate`, which is called by the router to determine @@ -35,6 +41,6 @@ export {routerCanReuse, routerCanDeactivate, routerOnActivate, routerOnReuse, ro * * {@example router/ts/can_activate/can_activate_example.ts region='canActivate' } */ -export var CanActivate: - (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) => - ClassDecorator = makeDecorator(CanActivateAnnotation); +export var CanActivate: (hook: (next: ComponentInstruction, prev: ComponentInstruction) => + Promise<boolean>| boolean) => ClassDecorator = + makeDecorator(CanActivateAnnotation); diff --git a/modules/angular2/src/router/lifecycle/lifecycle_annotations_impl.ts b/modules/angular2/src/router/lifecycle/lifecycle_annotations_impl.ts index c0059369e2..d8c83866ab 100644 --- a/modules/angular2/src/router/lifecycle/lifecycle_annotations_impl.ts +++ b/modules/angular2/src/router/lifecycle/lifecycle_annotations_impl.ts @@ -11,12 +11,12 @@ export class CanActivate { } export const routerCanReuse: RouteLifecycleHook = - CONST_EXPR(new RouteLifecycleHook('routerCanReuse')); + CONST_EXPR(new RouteLifecycleHook("routerCanReuse")); export const routerCanDeactivate: RouteLifecycleHook = - CONST_EXPR(new RouteLifecycleHook('routerCanDeactivate')); + CONST_EXPR(new RouteLifecycleHook("routerCanDeactivate")); export const routerOnActivate: RouteLifecycleHook = - CONST_EXPR(new RouteLifecycleHook('routerOnActivate')); + CONST_EXPR(new RouteLifecycleHook("routerOnActivate")); export const routerOnReuse: RouteLifecycleHook = - CONST_EXPR(new RouteLifecycleHook('routerOnReuse')); + CONST_EXPR(new RouteLifecycleHook("routerOnReuse")); export const routerOnDeactivate: RouteLifecycleHook = - CONST_EXPR(new RouteLifecycleHook('routerOnDeactivate')); + CONST_EXPR(new RouteLifecycleHook("routerOnDeactivate")); diff --git a/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.ts b/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.ts index d32e54f41f..d8345dedfc 100644 --- a/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.ts +++ b/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.ts @@ -4,7 +4,7 @@ import {reflector} from 'angular2/src/core/reflection/reflection'; export function hasLifecycleHook(e: RouteLifecycleHook, type): boolean { if (!(type instanceof Type)) return false; - return e.name in (<any>type).prototype; + return e.name in(<any>type).prototype; } export function getCanActivateHook(type): Function { diff --git a/modules/angular2/src/router/location/hash_location_strategy.ts b/modules/angular2/src/router/location/hash_location_strategy.ts index 7fe1ab2bb6..26dd67016d 100644 --- a/modules/angular2/src/router/location/hash_location_strategy.ts +++ b/modules/angular2/src/router/location/hash_location_strategy.ts @@ -1,5 +1,10 @@ import {Injectable, Inject, Optional} from 'angular2/core'; -import {LocationStrategy, joinWithSlash, APP_BASE_HREF, normalizeQueryParams} from './location_strategy'; +import { + LocationStrategy, + joinWithSlash, + APP_BASE_HREF, + normalizeQueryParams +} from './location_strategy'; import {UrlChangeListener} from './platform_location'; import {isPresent} from 'angular2/src/facade/lang'; import {PlatformLocation} from './platform_location'; @@ -45,9 +50,8 @@ import {PlatformLocation} from './platform_location'; @Injectable() export class HashLocationStrategy extends LocationStrategy { private _baseHref: string = ''; - constructor( - private _platformLocation: PlatformLocation, - @Optional() @Inject(APP_BASE_HREF) _baseHref?: string) { + constructor(private _platformLocation: PlatformLocation, + @Optional() @Inject(APP_BASE_HREF) _baseHref?: string) { super(); if (isPresent(_baseHref)) { this._baseHref = _baseHref; diff --git a/modules/angular2/src/router/location/location.ts b/modules/angular2/src/router/location/location.ts index 016129e95f..8684a34681 100644 --- a/modules/angular2/src/router/location/location.ts +++ b/modules/angular2/src/router/location/location.ts @@ -113,9 +113,8 @@ export class Location { /** * Subscribe to the platform's `popState` events. */ - subscribe( - onNext: (value: any) => void, onThrow: (exception: any) => void = null, - onReturn: () => void = null): Object { + subscribe(onNext: (value: any) => void, onThrow: (exception: any) => void = null, + onReturn: () => void = null): Object { return ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); } } diff --git a/modules/angular2/src/router/location/path_location_strategy.ts b/modules/angular2/src/router/location/path_location_strategy.ts index 5d981c9af8..7d114d1403 100644 --- a/modules/angular2/src/router/location/path_location_strategy.ts +++ b/modules/angular2/src/router/location/path_location_strategy.ts @@ -1,7 +1,12 @@ import {Injectable, Inject, Optional} from 'angular2/core'; import {isBlank} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; -import {LocationStrategy, APP_BASE_HREF, normalizeQueryParams, joinWithSlash} from './location_strategy'; +import { + LocationStrategy, + APP_BASE_HREF, + normalizeQueryParams, + joinWithSlash +} from './location_strategy'; import {PlatformLocation, UrlChangeListener} from './platform_location'; /** @@ -53,9 +58,8 @@ import {PlatformLocation, UrlChangeListener} from './platform_location'; export class PathLocationStrategy extends LocationStrategy { private _baseHref: string; - constructor( - private _platformLocation: PlatformLocation, - @Optional() @Inject(APP_BASE_HREF) href?: string) { + constructor(private _platformLocation: PlatformLocation, + @Optional() @Inject(APP_BASE_HREF) href?: string) { super(); if (isBlank(href)) { diff --git a/modules/angular2/src/router/route_config/route_config_normalizer.ts b/modules/angular2/src/router/route_config/route_config_normalizer.ts index ec88f55fdb..ec50a38047 100644 --- a/modules/angular2/src/router/route_config/route_config_normalizer.ts +++ b/modules/angular2/src/router/route_config/route_config_normalizer.ts @@ -12,8 +12,8 @@ import {RouteRegistry} from '../route_registry'; * Also wraps an AsyncRoute's loader function to add the loaded component's route config to the * `RouteRegistry`. */ -export function normalizeRouteConfig( - config: RouteDefinition, registry: RouteRegistry): RouteDefinition { +export function normalizeRouteConfig(config: RouteDefinition, + registry: RouteRegistry): RouteDefinition { if (config instanceof AsyncRoute) { var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry); return new AsyncRoute({ @@ -49,7 +49,7 @@ export function normalizeRouteConfig( }); } if (config.aux) { - return new AuxRoute({path: config.aux, component: <Type>config.component, name: config.name}); + return new AuxRoute({path: config.aux, component:<Type>config.component, name: config.name}); } if (config.component) { if (typeof config.component == 'object') { @@ -57,7 +57,7 @@ export function normalizeRouteConfig( if (componentDefinitionObject.type == 'constructor') { return new Route({ path: config.path, - component: <Type>componentDefinitionObject.constructor, + component:<Type>componentDefinitionObject.constructor, name: config.name, data: config.data, useAsDefault: config.useAsDefault diff --git a/modules/angular2/src/router/route_definition.ts b/modules/angular2/src/router/route_definition.ts index c266d50a71..233b20230a 100644 --- a/modules/angular2/src/router/route_definition.ts +++ b/modules/angular2/src/router/route_definition.ts @@ -17,7 +17,7 @@ export interface RouteDefinition { aux?: string; regex?: string; serializer?: RegexSerializer; - component?: Type|ComponentDefinition; + component?: Type | ComponentDefinition; loader?: () => Promise<Type>; redirectTo?: any[]; as?: string; diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 348053b4d0..0cf90984b1 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -1,14 +1,39 @@ import {ListWrapper, Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {PromiseWrapper} from 'angular2/src/facade/async'; -import {isPresent, isArray, isBlank, isType, isString, isStringMap, Type, StringWrapper, Math, getTypeNameForDebugging, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isArray, + isBlank, + isType, + isString, + isStringMap, + Type, + StringWrapper, + Math, + getTypeNameForDebugging, + CONST_EXPR +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {Injectable, Inject, OpaqueToken} from 'angular2/core'; -import {RouteConfig, AsyncRoute, Route, AuxRoute, Redirect, RouteDefinition} from './route_config/route_config_impl'; +import { + RouteConfig, + AsyncRoute, + Route, + AuxRoute, + Redirect, + RouteDefinition +} from './route_config/route_config_impl'; import {PathMatch, RedirectMatch, RouteMatch} from './rules/rules'; import {RuleSet} from './rules/rule_set'; -import {Instruction, ResolvedInstruction, RedirectInstruction, UnresolvedInstruction, DefaultInstruction} from './instruction'; +import { + Instruction, + ResolvedInstruction, + RedirectInstruction, + UnresolvedInstruction, + DefaultInstruction +} from './instruction'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer'; import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser'; @@ -137,8 +162,8 @@ export class RouteRegistry { /** * Recognizes all parent-child routes, but creates unresolved auxiliary routes */ - private _recognize(parsedUrl: Url, ancestorInstructions: Instruction[], _aux = false): - Promise<Instruction> { + private _recognize(parsedUrl: Url, ancestorInstructions: Instruction[], + _aux = false): Promise<Instruction> { var parentInstruction = ListWrapper.last(ancestorInstructions); var parentComponent = isPresent(parentInstruction) ? parentInstruction.component.componentType : this._rootComponent; @@ -187,9 +212,8 @@ export class RouteRegistry { if (candidate instanceof RedirectMatch) { var instruction = this.generate(candidate.redirectTo, ancestorInstructions.concat([null])); - return new RedirectInstruction( - instruction.component, instruction.child, instruction.auxInstruction, - candidate.specificity); + return new RedirectInstruction(instruction.component, instruction.child, + instruction.auxInstruction, candidate.specificity); } })); @@ -200,8 +224,8 @@ export class RouteRegistry { return PromiseWrapper.all<Instruction>(matchPromises).then(mostSpecific); } - private _auxRoutesToUnresolved(auxRoutes: Url[], parentInstructions: Instruction[]): - {[key: string]: Instruction} { + private _auxRoutesToUnresolved(auxRoutes: Url[], + parentInstructions: Instruction[]): {[key: string]: Instruction} { var unresolvedAuxInstructions: {[key: string]: Instruction} = {}; auxRoutes.forEach((auxUrl: Url) => { @@ -267,7 +291,7 @@ export class RouteRegistry { // If both exist, we throw. Otherwise, we prefer whichever exists. var childRouteExists = this.hasRoute(routeName, parentComponentType); var parentRouteExists = isPresent(grandparentComponentType) && - this.hasRoute(routeName, grandparentComponentType); + this.hasRoute(routeName, grandparentComponentType); if (parentRouteExists && childRouteExists) { let msg = @@ -316,9 +340,8 @@ export class RouteRegistry { * `prevInstruction` is the existing instruction that would be replaced, but which might have * aux routes that need to be cloned. */ - private _generate( - linkParams: any[], ancestorInstructions: Instruction[], prevInstruction: Instruction, - _aux = false, _originalLink: any[]): Instruction { + private _generate(linkParams: any[], ancestorInstructions: Instruction[], + prevInstruction: Instruction, _aux = false, _originalLink: any[]): Instruction { let parentComponentType = this._rootComponent; let componentInstruction = null; let auxInstructions: {[key: string]: Instruction} = {}; @@ -381,8 +404,8 @@ export class RouteRegistry { var generatedUrl: GeneratedUrl = routeRecognizer.generateComponentPathValues(routeParams); return new UnresolvedInstruction(() => { return routeRecognizer.handler.resolveComponentType().then((_) => { - return this._generate( - linkParams, ancestorInstructions, prevInstruction, _aux, _originalLink); + return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, + _originalLink); }); }, generatedUrl.urlPath, convertUrlParamsToArray(generatedUrl.urlParams)); } @@ -395,8 +418,8 @@ export class RouteRegistry { // If we have an ancestor instruction, we preserve whatever aux routes are active from it. while (linkParamIndex < linkParams.length && isArray(linkParams[linkParamIndex])) { let auxParentInstruction: Instruction[] = [parentInstruction]; - let auxInstruction = this._generate( - linkParams[linkParamIndex], auxParentInstruction, null, true, _originalLink); + let auxInstruction = this._generate(linkParams[linkParamIndex], auxParentInstruction, null, + true, _originalLink); // TODO: this will not work for aux routes with parameters or multiple segments auxInstructions[auxInstruction.component.urlPath] = auxInstruction; @@ -416,8 +439,8 @@ export class RouteRegistry { } else { let childAncestorComponents: Instruction[] = ancestorInstructions.concat([instruction]); let remainingLinkParams = linkParams.slice(linkParamIndex); - childInstruction = this._generate( - remainingLinkParams, childAncestorComponents, null, false, _originalLink); + childInstruction = this._generate(remainingLinkParams, childAncestorComponents, null, false, + _originalLink); } instruction.child = childInstruction; } diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index 9334b3a54b..2547279871 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -5,7 +5,10 @@ import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Inject, Injectable} from 'angular2/core'; import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from './route_registry'; -import {ComponentInstruction, Instruction,} from './instruction'; +import { + ComponentInstruction, + Instruction, +} from './instruction'; import {RouterOutlet} from './directives/router_outlet'; import {Location} from './location/location'; import {getCanActivateHook} from './lifecycle/route_lifecycle_reflector'; @@ -49,9 +52,8 @@ export class Router { private _subject: EventEmitter<any> = new EventEmitter(); - constructor( - public registry: RouteRegistry, public parent: Router, public hostComponent: any, - public root?: Router) {} + constructor(public registry: RouteRegistry, public parent: Router, public hostComponent: any, + public root?: Router) {} /** * Constructs a child router. You probably don't need to use this unless you're writing a reusable @@ -225,8 +227,8 @@ export class Router { * Navigate via the provided instruction. Returns a promise that resolves when navigation is * complete. */ - navigateByInstruction(instruction: Instruction, _skipLocationChange: boolean = false): - Promise<any> { + navigateByInstruction(instruction: Instruction, + _skipLocationChange: boolean = false): Promise<any> { if (isBlank(instruction)) { return _resolveToFalse; } @@ -265,14 +267,16 @@ export class Router { if (!result) { return false; } - return this._routerCanDeactivate(instruction).then((result: boolean) => { - if (result) { - return this.commit(instruction, _skipLocationChange).then((_) => { - this._emitNavigationFinish(instruction.toRootUrl()); - return true; + return this._routerCanDeactivate(instruction) + .then((result: boolean) => { + if (result) { + return this.commit(instruction, _skipLocationChange) + .then((_) => { + this._emitNavigationFinish(instruction.toRootUrl()); + return true; + }); + } }); - } - }); }); } @@ -298,12 +302,13 @@ export class Router { if (isBlank(instruction.component)) { return _resolveToTrue; } - return this._outlet.routerCanReuse(instruction.component).then((result) => { - instruction.component.reuse = result; - if (result && isPresent(this._childRouter) && isPresent(instruction.child)) { - return this._childRouter._routerCanReuse(instruction.child); - } - }); + return this._outlet.routerCanReuse(instruction.component) + .then((result) => { + instruction.component.reuse = result; + if (result && isPresent(this._childRouter) && isPresent(instruction.child)) { + return this._childRouter._routerCanReuse(instruction.child); + } + }); } private _canActivate(nextInstruction: Instruction): Promise<boolean> { @@ -462,46 +467,47 @@ export class RootRouter extends Router { /** @internal */ _locationSub: Object; - constructor( - registry: RouteRegistry, location: Location, - @Inject(ROUTER_PRIMARY_COMPONENT) primaryComponent: Type) { + constructor(registry: RouteRegistry, location: Location, + @Inject(ROUTER_PRIMARY_COMPONENT) primaryComponent: Type) { super(registry, null, primaryComponent); this.root = this; this._location = location; this._locationSub = this._location.subscribe((change) => { // we call recognize ourselves - this.recognize(change['url']).then((instruction) => { - if (isPresent(instruction)) { - this.navigateByInstruction(instruction, isPresent(change['pop'])).then((_) => { - // this is a popstate event; no need to change the URL - if (isPresent(change['pop']) && change['type'] != 'hashchange') { - return; - } - var emitPath = instruction.toUrlPath(); - var emitQuery = instruction.toUrlQuery(); - if (emitPath.length > 0 && emitPath[0] != '/') { - emitPath = '/' + emitPath; - } + this.recognize(change['url']) + .then((instruction) => { + if (isPresent(instruction)) { + this.navigateByInstruction(instruction, isPresent(change['pop'])) + .then((_) => { + // this is a popstate event; no need to change the URL + if (isPresent(change['pop']) && change['type'] != 'hashchange') { + return; + } + var emitPath = instruction.toUrlPath(); + var emitQuery = instruction.toUrlQuery(); + if (emitPath.length > 0 && emitPath[0] != '/') { + emitPath = '/' + emitPath; + } - // We've opted to use pushstate and popState APIs regardless of whether you - // an app uses HashLocationStrategy or PathLocationStrategy. - // However, apps that are migrating might have hash links that operate outside - // angular to which routing must respond. - // Therefore we know that all hashchange events occur outside Angular. - // To support these cases where we respond to hashchanges and redirect as a - // result, we need to replace the top item on the stack. - if (change['type'] == 'hashchange') { - if (instruction.toRootUrl() != this._location.path()) { - this._location.replaceState(emitPath, emitQuery); - } + // We've opted to use pushstate and popState APIs regardless of whether you + // an app uses HashLocationStrategy or PathLocationStrategy. + // However, apps that are migrating might have hash links that operate outside + // angular to which routing must respond. + // Therefore we know that all hashchange events occur outside Angular. + // To support these cases where we respond to hashchanges and redirect as a + // result, we need to replace the top item on the stack. + if (change['type'] == 'hashchange') { + if (instruction.toRootUrl() != this._location.path()) { + this._location.replaceState(emitPath, emitQuery); + } + } else { + this._location.go(emitPath, emitQuery); + } + }); } else { - this._location.go(emitPath, emitQuery); + this._emitNavigationFail(change['url']); } }); - } else { - this._emitNavigationFail(change['url']); - } - }); }); this.registry.configFromComponent(primaryComponent); @@ -541,23 +547,23 @@ class ChildRouter extends Router { return this.parent.navigateByUrl(url, _skipLocationChange); } - navigateByInstruction(instruction: Instruction, _skipLocationChange: boolean = false): - Promise<any> { + navigateByInstruction(instruction: Instruction, + _skipLocationChange: boolean = false): Promise<any> { // Delegate navigation to the root router return this.parent.navigateByInstruction(instruction, _skipLocationChange); } } -function canActivateOne( - nextInstruction: Instruction, prevInstruction: Instruction): Promise<boolean> { +function canActivateOne(nextInstruction: Instruction, + prevInstruction: Instruction): Promise<boolean> { var next = _resolveToTrue; if (isBlank(nextInstruction.component)) { return next; } if (isPresent(nextInstruction.child)) { - next = canActivateOne( - nextInstruction.child, isPresent(prevInstruction) ? prevInstruction.child : null); + next = canActivateOne(nextInstruction.child, + isPresent(prevInstruction) ? prevInstruction.child : null); } return next.then<boolean>((result: boolean): boolean => { if (result == false) { @@ -568,8 +574,8 @@ function canActivateOne( } var hook = getCanActivateHook(nextInstruction.component.componentType); if (isPresent(hook)) { - return hook( - nextInstruction.component, isPresent(prevInstruction) ? prevInstruction.component : null); + return hook(nextInstruction.component, + isPresent(prevInstruction) ? prevInstruction.component : null); } return true; }); diff --git a/modules/angular2/src/router/router_providers_common.ts b/modules/angular2/src/router/router_providers_common.ts index 20b87fec28..f2c3a65827 100644 --- a/modules/angular2/src/router/router_providers_common.ts +++ b/modules/angular2/src/router/router_providers_common.ts @@ -11,19 +11,22 @@ import {BaseException} from 'angular2/src/facade/exceptions'; * The Platform agnostic ROUTER PROVIDERS */ export const ROUTER_PROVIDERS_COMMON: any[] = CONST_EXPR([ - RouteRegistry, CONST_EXPR(new Provider(LocationStrategy, {useClass: PathLocationStrategy})), - Location, CONST_EXPR(new Provider(Router, { - useFactory: routerFactory, - deps: CONST_EXPR([RouteRegistry, Location, ROUTER_PRIMARY_COMPONENT, ApplicationRef]) - })), + RouteRegistry, + CONST_EXPR(new Provider(LocationStrategy, {useClass: PathLocationStrategy})), + Location, + CONST_EXPR(new Provider( + Router, + { + useFactory: routerFactory, + deps: CONST_EXPR([RouteRegistry, Location, ROUTER_PRIMARY_COMPONENT, ApplicationRef]) + })), CONST_EXPR(new Provider( ROUTER_PRIMARY_COMPONENT, {useFactory: routerPrimaryComponentFactory, deps: CONST_EXPR([ApplicationRef])})) ]); -function routerFactory( - registry: RouteRegistry, location: Location, primaryComponent: Type, - appRef: ApplicationRef): RootRouter { +function routerFactory(registry: RouteRegistry, location: Location, primaryComponent: Type, + appRef: ApplicationRef): RootRouter { var rootRouter = new RootRouter(registry, location, primaryComponent); appRef.registerDisposeListener(() => rootRouter.dispose()); return rootRouter; @@ -31,7 +34,7 @@ function routerFactory( function routerPrimaryComponentFactory(app: ApplicationRef): Type { if (app.componentTypes.length == 0) { - throw new BaseException('Bootstrap at least one component before injecting Router.'); + throw new BaseException("Bootstrap at least one component before injecting Router."); } return app.componentTypes[0]; } diff --git a/modules/angular2/src/router/rules/route_paths/param_route_path.ts b/modules/angular2/src/router/rules/route_paths/param_route_path.ts index 3c182f2e14..fc7daf3171 100644 --- a/modules/angular2/src/router/rules/route_paths/param_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/param_route_path.ts @@ -192,7 +192,7 @@ export class ParamRoutePath implements RoutePath { private _parsePathString(routePath: string) { // normalize route as not starting with a "/". Recognition will // also normalize. - if (routePath.startsWith('/')) { + if (routePath.startsWith("/")) { routePath = routePath.substring(1); } diff --git a/modules/angular2/src/router/rules/route_paths/route_path.ts b/modules/angular2/src/router/rules/route_paths/route_path.ts index 34aa2653e5..be1d5e1f6e 100644 --- a/modules/angular2/src/router/rules/route_paths/route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/route_path.ts @@ -1,9 +1,8 @@ import {Url} from '../../url_parser'; export class MatchedUrl { - constructor( - public urlPath: string, public urlParams: string[], public allParams: {[key: string]: any}, - public auxiliary: Url[], public rest: Url) {} + constructor(public urlPath: string, public urlParams: string[], + public allParams: {[key: string]: any}, public auxiliary: Url[], public rest: Url) {} } diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index f9055b5f15..9902279597 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -4,7 +4,13 @@ import {Map, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facad import {PromiseWrapper} from 'angular2/src/facade/async'; import {AbstractRule, RouteRule, RedirectRule, RouteMatch, PathMatch} from './rules'; -import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from '../route_config/route_config_impl'; +import { + Route, + AsyncRoute, + AuxRoute, + Redirect, + RouteDefinition +} from '../route_config/route_config_impl'; import {AsyncRouteHandler} from './route_handlers/async_route_handler'; import {SyncRouteHandler} from './route_handlers/sync_route_handler'; @@ -176,8 +182,8 @@ export class RuleSet { if (isPresent(config.path)) { // Auxiliary routes do not have a slash at the start let path = (config instanceof AuxRoute && config.path.startsWith('/')) ? - config.path.substring(1) : - config.path; + config.path.substring(1) : + config.path; return new ParamRoutePath(path); } throw new BaseException('Route must provide either a path or regex property'); diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 1d2609eba7..af8a1e82b6 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -14,8 +14,8 @@ import {GeneratedUrl} from './route_paths/route_path'; export abstract class RouteMatch {} export class PathMatch extends RouteMatch { - constructor( - public instruction: ComponentInstruction, public remaining: Url, public remainingAux: Url[]) { + constructor(public instruction: ComponentInstruction, public remaining: Url, + public remainingAux: Url[]) { super(); } } @@ -69,8 +69,8 @@ export class RouteRule implements AbstractRule { // TODO: cache component instruction instances by params and by ParsedUrl instance - constructor( - private _routePath: RoutePath, public handler: RouteHandler, private _routeName: string) { + constructor(private _routePath: RoutePath, public handler: RouteHandler, + private _routeName: string) { this.specificity = this._routePath.specificity; this.hash = this._routePath.hash; this.terminal = this._routePath.terminal; @@ -102,8 +102,8 @@ export class RouteRule implements AbstractRule { return this._routePath.generateUrl(params); } - private _getInstruction(urlPath: string, urlParams: string[], params: {[key: string]: any}): - ComponentInstruction { + private _getInstruction(urlPath: string, urlParams: string[], + params: {[key: string]: any}): ComponentInstruction { if (isBlank(this.handler.componentType)) { throw new BaseException(`Tried to get instruction before the type was loaded.`); } @@ -111,9 +111,9 @@ export class RouteRule implements AbstractRule { if (this._cache.has(hashKey)) { return this._cache.get(hashKey); } - var instruction = new ComponentInstruction( - urlPath, urlParams, this.handler.data, this.handler.componentType, this.terminal, - this.specificity, params, this._routeName); + var instruction = + new ComponentInstruction(urlPath, urlParams, this.handler.data, this.handler.componentType, + this.terminal, this.specificity, params, this._routeName); this._cache.set(hashKey, instruction); return instruction; diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/url_parser.ts index c91d4b9d3e..ecd91bb223 100644 --- a/modules/angular2/src/router/url_parser.ts +++ b/modules/angular2/src/router/url_parser.ts @@ -21,9 +21,9 @@ export function serializeParams(urlParams: {[key: string]: any}, joiner = '&'): * This class represents a parsed URL */ export class Url { - constructor( - public path: string, public child: Url = null, public auxiliary: Url[] = CONST_EXPR([]), - public params: {[key: string]: any} = CONST_EXPR({})) {} + constructor(public path: string, public child: Url = null, + public auxiliary: Url[] = CONST_EXPR([]), + public params: {[key: string]: any} = CONST_EXPR({})) {} toString(): string { return this.path + this._matrixParamsToString() + this._auxToString() + this._childString(); @@ -34,8 +34,8 @@ export class Url { /** @internal */ _auxToString(): string { return this.auxiliary.length > 0 ? - ('(' + this.auxiliary.map(sibling => sibling.toString()).join('//') + ')') : - ''; + ('(' + this.auxiliary.map(sibling => sibling.toString()).join('//') + ')') : + ''; } private _matrixParamsToString(): string { @@ -51,9 +51,8 @@ export class Url { } export class RootUrl extends Url { - constructor( - path: string, child: Url = null, auxiliary: Url[] = CONST_EXPR([]), - params: {[key: string]: any} = null) { + constructor(path: string, child: Url = null, auxiliary: Url[] = CONST_EXPR([]), + params: {[key: string]: any} = null) { super(path, child, auxiliary, params); } diff --git a/modules/angular2/src/testing/matchers.ts b/modules/angular2/src/testing/matchers.ts index df6564d9bc..aec11a8a80 100644 --- a/modules/angular2/src/testing/matchers.ts +++ b/modules/angular2/src/testing/matchers.ts @@ -236,7 +236,7 @@ _global.beforeEach(function() { actual(); return { pass: false, - get message() { return 'Was expected to throw, but did not throw'; } + get message() { return "Was expected to throw, but did not throw"; } }; } catch (e) { var errorMessage = e.toString(); @@ -279,7 +279,7 @@ _global.beforeEach(function() { pass: missedMethods.length == 0, get message() { return 'Expected ' + actualObject + ' to have the following methods: ' + - missedMethods.join(', '); + missedMethods.join(", "); } }; } @@ -295,7 +295,7 @@ function elementText(n) { }; if (n instanceof Array) { - return n.map(elementText).join(''); + return n.map(elementText).join(""); } if (DOM.isCommentNode(n)) { diff --git a/modules/angular2/src/testing/perf_util.ts b/modules/angular2/src/testing/perf_util.ts index 32a89bbf4c..2d4f919c8f 100644 --- a/modules/angular2/src/testing/perf_util.ts +++ b/modules/angular2/src/testing/perf_util.ts @@ -12,40 +12,42 @@ export function runClickBenchmark(config) { } export function runBenchmark(config) { - return getScaleFactor(browser.params.benchmark.scaling).then(function(scaleFactor) { - var description = {}; - var urlParams = []; - if (config.params) { - config.params.forEach(function(param) { - var name = param.name; - var value = applyScaleFactor(param.value, scaleFactor, param.scale); - urlParams.push(name + '=' + value); - description[name] = value; + return getScaleFactor(browser.params.benchmark.scaling) + .then(function(scaleFactor) { + var description = {}; + var urlParams = []; + if (config.params) { + config.params.forEach(function(param) { + var name = param.name; + var value = applyScaleFactor(param.value, scaleFactor, param.scale); + urlParams.push(name + '=' + value); + description[name] = value; + }); + } + var url = encodeURI(config.url + '?' + urlParams.join('&')); + return browser.get(url).then(function() { + return global['benchpressRunner'].sample({ + id: config.id, + execute: config.work, + prepare: config.prepare, + microMetrics: config.microMetrics, + bindings: [bind(Options.SAMPLE_DESCRIPTION).toValue(description)] + }); + }); }); - } - var url = encodeURI(config.url + '?' + urlParams.join('&')); - return browser.get(url).then(function() { - return global['benchpressRunner'].sample({ - id: config.id, - execute: config.work, - prepare: config.prepare, - microMetrics: config.microMetrics, - bindings: [bind(Options.SAMPLE_DESCRIPTION).toValue(description)] - }); - }); - }); } function getScaleFactor(possibleScalings) { - return browser.executeScript('return navigator.userAgent').then(function(userAgent: string) { - var scaleFactor = 1; - possibleScalings.forEach(function(entry) { - if (userAgent.match(entry.userAgent)) { - scaleFactor = entry.value; - } - }); - return scaleFactor; - }); + return browser.executeScript('return navigator.userAgent') + .then(function(userAgent: string) { + var scaleFactor = 1; + possibleScalings.forEach(function(entry) { + if (userAgent.match(entry.userAgent)) { + scaleFactor = entry.value; + } + }); + return scaleFactor; + }); } function applyScaleFactor(value, scaleFactor, method) { diff --git a/modules/angular2/src/testing/test_component_builder.ts b/modules/angular2/src/testing/test_component_builder.ts index 1c176e038f..8b72401f0f 100644 --- a/modules/angular2/src/testing/test_component_builder.ts +++ b/modules/angular2/src/testing/test_component_builder.ts @@ -1,4 +1,15 @@ -import {ComponentRef, DirectiveResolver, DynamicComponentLoader, Injector, Injectable, ViewMetadata, ElementRef, EmbeddedViewRef, ViewResolver, provide} from 'angular2/core'; +import { + ComponentRef, + DirectiveResolver, + DynamicComponentLoader, + Injector, + Injectable, + ViewMetadata, + ElementRef, + EmbeddedViewRef, + ViewResolver, + provide +} from 'angular2/core'; import {Type, isPresent, isBlank} from 'angular2/src/facade/lang'; import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; @@ -219,15 +230,15 @@ export class TestComponentBuilder { var mockDirectiveResolver = this._injector.get(DirectiveResolver); var mockViewResolver = this._injector.get(ViewResolver); this._viewOverrides.forEach((view, type) => mockViewResolver.setView(type, view)); - this._templateOverrides.forEach( - (template, type) => mockViewResolver.setInlineTemplate(type, template)); + this._templateOverrides.forEach((template, type) => + mockViewResolver.setInlineTemplate(type, template)); this._directiveOverrides.forEach((overrides, component) => { overrides.forEach( (to, from) => { mockViewResolver.overrideViewDirective(component, from, to); }); }); - this._bindingsOverrides.forEach( - (bindings, type) => mockDirectiveResolver.setBindingsOverride(type, bindings)); + this._bindingsOverrides.forEach((bindings, type) => + mockDirectiveResolver.setBindingsOverride(type, bindings)); this._viewBindingsOverrides.forEach( (bindings, type) => mockDirectiveResolver.setViewBindingsOverride(type, bindings)); diff --git a/modules/angular2/src/testing/test_injector.ts b/modules/angular2/src/testing/test_injector.ts index c7bca448d8..0863a8b752 100644 --- a/modules/angular2/src/testing/test_injector.ts +++ b/modules/angular2/src/testing/test_injector.ts @@ -8,7 +8,7 @@ export class TestInjector { private _injector: Injector = null; - private _providers: Array<Type|Provider|any[]> = []; + private _providers: Array<Type | Provider | any[]> = []; reset() { this._injector = null; @@ -16,11 +16,11 @@ export class TestInjector { this._instantiated = false; } - platformProviders: Array<Type|Provider|any[]> = []; + platformProviders: Array<Type | Provider | any[]> = []; - applicationProviders: Array<Type|Provider|any[]> = []; + applicationProviders: Array<Type | Provider | any[]> = []; - addProviders(providers: Array<Type|Provider|any[]>) { + addProviders(providers: Array<Type | Provider | any[]>) { if (this._instantiated) { throw new BaseException('Cannot add providers after test injector is instantiated'); } @@ -67,9 +67,8 @@ export function getTestInjector() { * Test Providers for individual platforms are available from * 'angular2/platform/testing/<platform_name>'. */ -export function setBaseTestProviders( - platformProviders: Array<Type|Provider|any[]>, - applicationProviders: Array<Type|Provider|any[]>) { +export function setBaseTestProviders(platformProviders: Array<Type | Provider | any[]>, + applicationProviders: Array<Type | Provider | any[]>) { var testInjector = getTestInjector(); if (testInjector.platformProviders.length > 0 || testInjector.applicationProviders.length > 0) { throw new BaseException('Cannot set base providers because it has already been called'); @@ -167,9 +166,8 @@ function emptyArray(): Array<any> { } export class FunctionWithParamTokens { - constructor( - private _tokens: any[], private _fn: Function, public isAsync: boolean, - public additionalProviders: () => any = emptyArray) {} + constructor(private _tokens: any[], private _fn: Function, public isAsync: boolean, + public additionalProviders: () => any = emptyArray) {} /** * Returns the value of the executed function. diff --git a/modules/angular2/src/testing/testing.ts b/modules/angular2/src/testing/testing.ts index b278318715..a271de002b 100644 --- a/modules/angular2/src/testing/testing.ts +++ b/modules/angular2/src/testing/testing.ts @@ -6,7 +6,13 @@ import {global} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; import {bind} from 'angular2/core'; -import {FunctionWithParamTokens, inject, injectAsync, TestInjector, getTestInjector} from './test_injector'; +import { + FunctionWithParamTokens, + inject, + injectAsync, + TestInjector, + getTestInjector +} from './test_injector'; export {inject, injectAsync} from './test_injector'; @@ -109,10 +115,9 @@ export function beforeEachProviders(fn): void { try { testInjector.addProviders(providers); } catch (e) { - throw new Error( - 'beforeEachProviders was called after the injector had ' + - 'been used in a beforeEach or it block. This invalidates the ' + - 'test injector'); + throw new Error('beforeEachProviders was called after the injector had ' + + 'been used in a beforeEach or it block. This invalidates the ' + + 'test injector'); } }); } @@ -121,9 +126,8 @@ function _isPromiseLike(input): boolean { return input && !!(input.then); } -function _it( - jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn, - testTimeOut: number): void { +function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn, + testTimeOut: number): void { var timeOut = testTimeOut; if (testFn instanceof FunctionWithParamTokens) { @@ -141,15 +145,13 @@ function _it( if (_isPromiseLike(returnedTestValue)) { (<Promise<any>>returnedTestValue).then(() => { done(); }, (err) => { done.fail(err); }); } else { - done.fail( - 'Error: injectAsync was expected to return a promise, but the ' + - ' returned value was: ' + returnedTestValue); + done.fail('Error: injectAsync was expected to return a promise, but the ' + + ' returned value was: ' + returnedTestValue); } } else { if (!(returnedTestValue === undefined)) { - done.fail( - 'Error: inject returned a value. Did you mean to use injectAsync? Returned ' + - 'value was: ' + returnedTestValue); + done.fail('Error: inject returned a value. Did you mean to use injectAsync? Returned ' + + 'value was: ' + returnedTestValue); } done(); } @@ -191,15 +193,13 @@ export function beforeEach(fn: FunctionWithParamTokens | AnyTestFn): void { if (_isPromiseLike(returnedTestValue)) { (<Promise<any>>returnedTestValue).then(() => { done(); }, (err) => { done.fail(err); }); } else { - done.fail( - 'Error: injectAsync was expected to return a promise, but the ' + - ' returned value was: ' + returnedTestValue); + done.fail('Error: injectAsync was expected to return a promise, but the ' + + ' returned value was: ' + returnedTestValue); } } else { if (!(returnedTestValue === undefined)) { - done.fail( - 'Error: inject returned a value. Did you mean to use injectAsync? Returned ' + - 'value was: ' + returnedTestValue); + done.fail('Error: inject returned a value. Did you mean to use injectAsync? Returned ' + + 'value was: ' + returnedTestValue); } done(); } @@ -228,8 +228,8 @@ export function beforeEach(fn: FunctionWithParamTokens | AnyTestFn): void { * * {@example testing/ts/testing.ts region='describeIt'} */ -export function it( - name: string, fn: FunctionWithParamTokens | AnyTestFn, timeOut: number = null): void { +export function it(name: string, fn: FunctionWithParamTokens | AnyTestFn, + timeOut: number = null): void { return _it(jsmIt, name, fn, timeOut); } @@ -244,16 +244,16 @@ export function it( * * {@example testing/ts/testing.ts region='xit'} */ -export function xit( - name: string, fn: FunctionWithParamTokens | AnyTestFn, timeOut: number = null): void { +export function xit(name: string, fn: FunctionWithParamTokens | AnyTestFn, + timeOut: number = null): void { return _it(jsmXIt, name, fn, timeOut); } /** * See {@link fit}. */ -export function iit( - name: string, fn: FunctionWithParamTokens | AnyTestFn, timeOut: number = null): void { +export function iit(name: string, fn: FunctionWithParamTokens | AnyTestFn, + timeOut: number = null): void { return _it(jsmIIt, name, fn, timeOut); } @@ -267,7 +267,7 @@ export function iit( * * {@example testing/ts/testing.ts region='fit'} */ -export function fit( - name: string, fn: FunctionWithParamTokens | AnyTestFn, timeOut: number = null): void { +export function fit(name: string, fn: FunctionWithParamTokens | AnyTestFn, + timeOut: number = null): void { return _it(jsmIIt, name, fn, timeOut); } diff --git a/modules/angular2/src/testing/testing_internal.ts b/modules/angular2/src/testing/testing_internal.ts index ba3d365035..7f7de03575 100644 --- a/modules/angular2/src/testing/testing_internal.ts +++ b/modules/angular2/src/testing/testing_internal.ts @@ -51,11 +51,11 @@ var testInjector = getTestInjector(); * Note: Jasmine own `beforeEach` is used by this library to handle DI providers. */ class BeforeEachRunner { - private _fns: Array<FunctionWithParamTokens|SyncTestFn> = []; + private _fns: Array<FunctionWithParamTokens | SyncTestFn> = []; constructor(private _parent: BeforeEachRunner) {} - beforeEach(fn: FunctionWithParamTokens|SyncTestFn): void { this._fns.push(fn); } + beforeEach(fn: FunctionWithParamTokens | SyncTestFn): void { this._fns.push(fn); } run(): void { if (this._parent) this._parent.run(); @@ -127,9 +127,8 @@ export function beforeEachBindings(fn): void { beforeEachProviders(fn); } -function _it( - jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn, - testTimeOut: number): void { +function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn, + testTimeOut: number): void { var runner = runnerStack[runnerStack.length - 1]; var timeOut = Math.max(globalTimeOut, testTimeOut); diff --git a/modules/angular2/src/testing/utils.ts b/modules/angular2/src/testing/utils.ts index 56825c11fd..741da95efb 100644 --- a/modules/angular2/src/testing/utils.ts +++ b/modules/angular2/src/testing/utils.ts @@ -19,7 +19,7 @@ export class Log { clear(): void { this.logItems = []; } - result(): string { return this.logItems.join('; '); } + result(): string { return this.logItems.join("; "); } } export var browserDetection: BrowserDetection = null; @@ -41,7 +41,7 @@ export class BrowserDetection { get isAndroid(): boolean { return this._ua.indexOf('Mozilla/5.0') > -1 && this._ua.indexOf('Android') > -1 && - this._ua.indexOf('AppleWebKit') > -1 && this._ua.indexOf('Chrome') == -1; + this._ua.indexOf('AppleWebKit') > -1 && this._ua.indexOf('Chrome') == -1; } get isEdge(): boolean { return this._ua.indexOf('Edge') > -1; } @@ -87,10 +87,10 @@ export function normalizeCSS(css: string): string { css = StringWrapper.replaceAll(css, /:\s/g, ':'); css = StringWrapper.replaceAll(css, /'/g, '"'); css = StringWrapper.replaceAll(css, / }/g, '}'); - css = StringWrapper.replaceAllMapped( - css, /url\((\"|\s)(.+)(\"|\s)\)(\s*)/g, (match) => `url("${match[2]}")`); - css = StringWrapper.replaceAllMapped( - css, /\[(.+)=([^"\]]+)\]/g, (match) => `[${match[1]}="${match[2]}"]`); + css = StringWrapper.replaceAllMapped(css, /url\((\"|\s)(.+)(\"|\s)\)(\s*)/g, + (match) => `url("${match[2]}")`); + css = StringWrapper.replaceAllMapped(css, /\[(.+)=([^"\]]+)\]/g, + (match) => `[${match[1]}="${match[2]}"]`); return css; } diff --git a/modules/angular2/src/transform/template_compiler/change_detector_codegen.ts b/modules/angular2/src/transform/template_compiler/change_detector_codegen.ts index c1440ffacb..300ac316ab 100644 --- a/modules/angular2/src/transform/template_compiler/change_detector_codegen.ts +++ b/modules/angular2/src/transform/template_compiler/change_detector_codegen.ts @@ -1,4 +1,6 @@ -import {ChangeDetectorDefinition,} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectorDefinition, +} from 'angular2/src/core/change_detection/change_detection'; // Note: This class is only here so that we can reference it from TypeScript code. // The actual implementation lives under modules_dart. @@ -7,7 +9,7 @@ import {ChangeDetectorDefinition,} from 'angular2/src/core/change_detection/chan export class Codegen { constructor(moduleAlias: string) {} generate(typeName: string, changeDetectorTypeName: string, def: ChangeDetectorDefinition): void { - throw 'Not implemented in JS'; + throw "Not implemented in JS"; } - toString(): string { throw 'Not implemented in JS'; } + toString(): string { throw "Not implemented in JS"; } } diff --git a/modules/angular2/src/upgrade/angular_js.ts b/modules/angular2/src/upgrade/angular_js.ts index c43a87d0c3..1c1fdf452f 100644 --- a/modules/angular2/src/upgrade/angular_js.ts +++ b/modules/angular2/src/upgrade/angular_js.ts @@ -8,7 +8,7 @@ export interface IModule { run(a: any): void; } export interface ICompileService { - (element: Element|NodeList|string, transclude?: Function): ILinkFn; + (element: Element | NodeList | string, transclude?: Function): ILinkFn; } export interface ILinkFn { (scope: IScope, cloneAttachFn?: Function, options?: ILinkFnOptions): void; @@ -35,8 +35,8 @@ export interface IDirective { compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; - bindToController?: boolean|Object; - link?: IDirectiveLinkFn|IDirectivePrePost; + bindToController?: boolean | Object; + link?: IDirectiveLinkFn | IDirectivePrePost; name?: string; priority?: number; replace?: boolean; @@ -119,20 +119,21 @@ function noNg() { throw new Error('AngularJS v1.x is not loaded!'); } -var angular: { - bootstrap: (e: Element, modules: string[], config: IAngularBootstrapConfig) => void, - module: (prefix: string, dependencies?: string[]) => IModule, - element: (e: Element) => IAugmentedJQuery, - version: {major: number}, resumeBootstrap?: () => void, - getTestability: (e: Element) => ITestabilityService -} = <any>{ - bootstrap: noNg, - module: noNg, - element: noNg, - version: noNg, - resumeBootstrap: noNg, - getTestability: noNg -}; +var angular: + { + bootstrap: (e: Element, modules: string[], config: IAngularBootstrapConfig) => void, + module: (prefix: string, dependencies?: string[]) => IModule, + element: (e: Element) => IAugmentedJQuery, + version: {major: number}, resumeBootstrap?: () => void, + getTestability: (e: Element) => ITestabilityService + } = <any>{ + bootstrap: noNg, + module: noNg, + element: noNg, + version: noNg, + resumeBootstrap: noNg, + getTestability: noNg + }; try { diff --git a/modules/angular2/src/upgrade/downgrade_ng2_adapter.ts b/modules/angular2/src/upgrade/downgrade_ng2_adapter.ts index 2200d3828b..e0051c4ae0 100644 --- a/modules/angular2/src/upgrade/downgrade_ng2_adapter.ts +++ b/modules/angular2/src/upgrade/downgrade_ng2_adapter.ts @@ -1,4 +1,13 @@ -import {provide, AppViewManager, ChangeDetectorRef, HostViewRef, Injector, OnChanges, HostViewFactoryRef, SimpleChange} from 'angular2/core'; +import { + provide, + AppViewManager, + ChangeDetectorRef, + HostViewRef, + Injector, + OnChanges, + HostViewFactoryRef, + SimpleChange +} from 'angular2/core'; import {NG1_SCOPE} from './constants'; import {ComponentInfo} from './metadata'; import Element = protractor.Element; @@ -18,11 +27,11 @@ export class DowngradeNg2ComponentAdapter { childNodes: Node[]; contentInsertionPoint: Node = null; - constructor( - private id: string, private info: ComponentInfo, private element: angular.IAugmentedJQuery, - private attrs: angular.IAttributes, private scope: angular.IScope, - private parentInjector: Injector, private parse: angular.IParseService, - private viewManager: AppViewManager, private hostViewFactory: HostViewFactoryRef) { + constructor(private id: string, private info: ComponentInfo, + private element: angular.IAugmentedJQuery, private attrs: angular.IAttributes, + private scope: angular.IScope, private parentInjector: Injector, + private parse: angular.IParseService, private viewManager: AppViewManager, + private hostViewFactory: HostViewFactoryRef) { (<any>this.element[0]).id = id; this.componentScope = scope.$new(); this.childNodes = <Node[]><any>element.contents(); @@ -114,9 +123,10 @@ export class DowngradeNg2ComponentAdapter { var bindonAttr = output.bindonAttr ? output.bindonAttr.substring(0, output.bindonAttr.length - 6) : null; - var bracketParenAttr = output.bracketParenAttr ? - `[(${output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8)})]` : - null; + var bracketParenAttr = + output.bracketParenAttr ? + `[(${output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8)})]` : + null; if (attrs.hasOwnProperty(output.onAttr)) { expr = attrs[output.onAttr]; diff --git a/modules/angular2/src/upgrade/upgrade_adapter.ts b/modules/angular2/src/upgrade/upgrade_adapter.ts index 9d09a47ca1..e78bf69cc6 100644 --- a/modules/angular2/src/upgrade/upgrade_adapter.ts +++ b/modules/angular2/src/upgrade/upgrade_adapter.ts @@ -1,11 +1,38 @@ -import {provide, platform, ApplicationRef, AppViewManager, Compiler, Injector, NgZone, PlatformRef, HostViewFactoryRef, Provider, Type, Testability, APPLICATION_COMMON_PROVIDERS} from 'angular2/core'; +import { + provide, + platform, + ApplicationRef, + AppViewManager, + Compiler, + Injector, + NgZone, + PlatformRef, + HostViewFactoryRef, + Provider, + Type, + Testability, + APPLICATION_COMMON_PROVIDERS +} from 'angular2/core'; import {global} from 'angular2/src/facade/lang'; import {ObservableWrapper} from 'angular2/src/facade/async'; import {BROWSER_PROVIDERS, BROWSER_APP_PROVIDERS} from 'angular2/platform/browser'; import {getComponentInfo, ComponentInfo} from './metadata'; import {onError, controllerKey} from './util'; -import {NG1_COMPILE, NG1_INJECTOR, NG1_PARSE, NG1_ROOT_SCOPE, NG1_SCOPE, NG1_TESTABILITY, NG2_APP_VIEW_MANAGER, NG2_COMPILER, NG2_INJECTOR, NG2_HOST_VIEW_FACTORY_REF_MAP, NG2_ZONE, REQUIRE_INJECTOR} from './constants'; +import { + NG1_COMPILE, + NG1_INJECTOR, + NG1_PARSE, + NG1_ROOT_SCOPE, + NG1_SCOPE, + NG1_TESTABILITY, + NG2_APP_VIEW_MANAGER, + NG2_COMPILER, + NG2_INJECTOR, + NG2_HOST_VIEW_FACTORY_REF_MAP, + NG2_ZONE, + REQUIRE_INJECTOR +} from './constants'; import {DowngradeNg2ComponentAdapter} from './downgrade_ng2_adapter'; import {UpgradeNg1ComponentAdapterBuilder} from './upgrade_ng1_adapter'; import * as angular from './angular_js'; @@ -89,7 +116,7 @@ export class UpgradeAdapter { /* @internal */ private downgradedComponents: {[name: string]: UpgradeNg1ComponentAdapterBuilder} = {}; /* @internal */ - private providers: Array<Type|Provider|any[]> = []; + private providers: Array<Type | Provider | any[]> = []; /** * Allows Angular v2 Component to be used from AngularJS v1. @@ -265,14 +292,16 @@ export class UpgradeAdapter { * }); * ``` */ - bootstrap(element: Element, modules?: any[], config?: angular.IAngularBootstrapConfig): - UpgradeAdapterRef { + bootstrap(element: Element, modules?: any[], + config?: angular.IAngularBootstrapConfig): UpgradeAdapterRef { var upgrade = new UpgradeAdapterRef(); var ng1Injector: angular.IInjectorService = null; var platformRef: PlatformRef = platform(BROWSER_PROVIDERS); var applicationRef: ApplicationRef = platformRef.application([ - BROWSER_APP_PROVIDERS, provide(NG1_INJECTOR, {useFactory: () => ng1Injector}), - provide(NG1_COMPILE, {useFactory: () => ng1Injector.get(NG1_COMPILE)}), this.providers + BROWSER_APP_PROVIDERS, + provide(NG1_INJECTOR, {useFactory: () => ng1Injector}), + provide(NG1_COMPILE, {useFactory: () => ng1Injector.get(NG1_COMPILE)}), + this.providers ]); var injector: Injector = applicationRef.injector; var ngZone: NgZone = injector.get(NgZone); @@ -301,7 +330,7 @@ export class UpgradeAdapter { original$applyFn = rootScopePrototype.$apply; rootScopePrototype.$apply = (exp) => delayApplyExps.push(exp); } else { - throw new Error('Failed to find \'$apply\' on \'$rootScope\'!'); + throw new Error("Failed to find '$apply' on '$rootScope'!"); } return rootScope = rootScopeDelegate; } @@ -332,11 +361,12 @@ export class UpgradeAdapter { ng1compilePromise = new Promise((resolve, reject) => { ng1Module.run([ - '$injector', '$rootScope', + '$injector', + '$rootScope', (injector: angular.IInjectorService, rootScope: angular.IRootScopeService) => { ng1Injector = injector; - ObservableWrapper.subscribe( - ngZone.onMicrotaskEmpty, (_) => ngZone.runOutsideAngular(() => rootScope.$apply())); + ObservableWrapper.subscribe(ngZone.onMicrotaskEmpty, + (_) => ngZone.runOutsideAngular(() => rootScope.$apply())); UpgradeNg1ComponentAdapterBuilder.resolve(this.downgradedComponents, injector) .then(resolve, reject); } @@ -362,11 +392,11 @@ export class UpgradeAdapter { } }); - Promise - .all([ - this.compileNg2Components(compiler, hostViewFactoryRefMap), ng1BootstrapPromise, - ng1compilePromise - ]) + Promise.all([ + this.compileNg2Components(compiler, hostViewFactoryRefMap), + ng1BootstrapPromise, + ng1compilePromise + ]) .then(() => { ngZone.run(() => { if (rootScopePrototype) { @@ -418,7 +448,7 @@ export class UpgradeAdapter { * adapter.bootstrap(document.body, ['myExample']); *``` */ - public addProvider(provider: Type|Provider|any[]): void { this.providers.push(provider); } + public addProvider(provider: Type | Provider | any[]): void { this.providers.push(provider); } /** * Allows AngularJS v1 service to be accessible from Angular v2. @@ -513,9 +543,9 @@ interface HostViewFactoryRefMap { function ng1ComponentDirective(info: ComponentInfo, idPrefix: string): Function { (<any>directiveFactory).$inject = [NG2_HOST_VIEW_FACTORY_REF_MAP, NG2_APP_VIEW_MANAGER, NG1_PARSE]; - function directiveFactory( - hostViewFactoryRefMap: HostViewFactoryRefMap, viewManager: AppViewManager, - parse: angular.IParseService): angular.IDirective { + function directiveFactory(hostViewFactoryRefMap: HostViewFactoryRefMap, + viewManager: AppViewManager, + parse: angular.IParseService): angular.IDirective { var hostViewFactory: HostViewFactoryRef = hostViewFactoryRefMap[info.selector]; if (!hostViewFactory) throw new Error('Expecting HostViewFactoryRef for: ' + info.selector); var idCount = 0; @@ -526,9 +556,9 @@ function ng1ComponentDirective(info: ComponentInfo, idPrefix: string): Function post: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, parentInjector: any, transclude: angular.ITranscludeFunction): void => { var domElement = <any>element[0]; - var facade = new DowngradeNg2ComponentAdapter( - idPrefix + (idCount++), info, element, attrs, scope, <Injector>parentInjector, parse, - viewManager, hostViewFactory); + var facade = new DowngradeNg2ComponentAdapter(idPrefix + (idCount++), info, element, + attrs, scope, <Injector>parentInjector, + parse, viewManager, hostViewFactory); facade.setupInputs(); facade.bootstrapNg2(); facade.projectContent(); diff --git a/modules/angular2/src/upgrade/upgrade_ng1_adapter.ts b/modules/angular2/src/upgrade/upgrade_ng1_adapter.ts index 7891382882..ad69eaea5a 100644 --- a/modules/angular2/src/upgrade/upgrade_ng1_adapter.ts +++ b/modules/angular2/src/upgrade/upgrade_ng1_adapter.ts @@ -1,5 +1,20 @@ -import {Directive, DoCheck, ElementRef, EventEmitter, Inject, OnChanges, SimpleChange, Type} from 'angular2/core'; -import {NG1_COMPILE, NG1_SCOPE, NG1_HTTP_BACKEND, NG1_TEMPLATE_CACHE, NG1_CONTROLLER} from './constants'; +import { + Directive, + DoCheck, + ElementRef, + EventEmitter, + Inject, + OnChanges, + SimpleChange, + Type +} from 'angular2/core'; +import { + NG1_COMPILE, + NG1_SCOPE, + NG1_HTTP_BACKEND, + NG1_TEMPLATE_CACHE, + NG1_CONTROLLER +} from './constants'; import {controllerKey} from './util'; import * as angular from './angular_js'; @@ -30,7 +45,8 @@ export class UpgradeNg1ComponentAdapterBuilder { Directive({selector: selector, inputs: this.inputsRename, outputs: this.outputsRename}) .Class({ constructor: [ - new Inject(NG1_SCOPE), ElementRef, + new Inject(NG1_SCOPE), + ElementRef, function(scope: angular.IScope, elementRef: ElementRef) { return new UpgradeNg1ComponentAdapter( self.linkFn, scope, self.directive, elementRef, self.$controller, self.inputs, @@ -112,9 +128,8 @@ export class UpgradeNg1ComponentAdapterBuilder { } } - compileTemplate( - compile: angular.ICompileService, templateCache: angular.ITemplateCacheService, - httpBackend: angular.IHttpBackendService): Promise<any> { + compileTemplate(compile: angular.ICompileService, templateCache: angular.ITemplateCacheService, + httpBackend: angular.IHttpBackendService): Promise<any> { if (this.directive.template !== undefined) { this.linkFn = compileHtml(this.directive.template); } else if (this.directive.templateUrl) { @@ -144,9 +159,8 @@ export class UpgradeNg1ComponentAdapterBuilder { } } - static resolve( - exportedComponents: {[name: string]: UpgradeNg1ComponentAdapterBuilder}, - injector: angular.IInjectorService): Promise<any> { + static resolve(exportedComponents: {[name: string]: UpgradeNg1ComponentAdapterBuilder}, + injector: angular.IInjectorService): Promise<any> { var promises = []; var compile: angular.ICompileService = injector.get(NG1_COMPILE); var templateCache: angular.ITemplateCacheService = injector.get(NG1_TEMPLATE_CACHE); @@ -170,11 +184,10 @@ class UpgradeNg1ComponentAdapter implements OnChanges, DoCheck { destinationObj: any = null; checkLastValues: any[] = []; - constructor( - linkFn: angular.ILinkFn, scope: angular.IScope, private directive: angular.IDirective, - elementRef: ElementRef, $controller: angular.IControllerService, private inputs: string[], - private outputs: string[], private propOuts: string[], private checkProperties: string[], - private propertyMap: {[key: string]: string}) { + constructor(linkFn: angular.ILinkFn, scope: angular.IScope, private directive: angular.IDirective, + elementRef: ElementRef, $controller: angular.IControllerService, + private inputs: string[], private outputs: string[], private propOuts: string[], + private checkProperties: string[], private propertyMap: {[key: string]: string}) { var element: Element = elementRef.nativeElement; var childNodes: Node[] = []; var childNode; @@ -197,8 +210,8 @@ class UpgradeNg1ComponentAdapter implements OnChanges, DoCheck { var attrs: angular.IAttributes = NOT_SUPPORTED; var transcludeFn: angular.ITranscludeFunction = NOT_SUPPORTED; var linkController = this.resolveRequired($element, directive.require); - (<angular.IDirectiveLinkFn>directive.link)( - componentScope, $element, attrs, linkController, transcludeFn); + (<angular.IDirectiveLinkFn>directive.link)(componentScope, $element, attrs, linkController, + transcludeFn); } this.destinationObj = directive.bindToController && controller ? controller : componentScope; @@ -261,7 +274,7 @@ class UpgradeNg1ComponentAdapter implements OnChanges, DoCheck { this.destinationObj[this.propertyMap[name]] = value; } - private resolveRequired($element: angular.IAugmentedJQuery, require: string|string[]): any { + private resolveRequired($element: angular.IAugmentedJQuery, require: string | string[]): any { if (!require) { return undefined; } else if (typeof require == 'string') { diff --git a/modules/angular2/src/web_workers/shared/api.ts b/modules/angular2/src/web_workers/shared/api.ts index 4a6700c0f4..34a757459c 100644 --- a/modules/angular2/src/web_workers/shared/api.ts +++ b/modules/angular2/src/web_workers/shared/api.ts @@ -1,4 +1,4 @@ -import {CONST_EXPR} from 'angular2/src/facade/lang'; -import {OpaqueToken} from 'angular2/src/core/di'; +import {CONST_EXPR} from "angular2/src/facade/lang"; +import {OpaqueToken} from "angular2/src/core/di"; export const ON_WEB_WORKER = CONST_EXPR(new OpaqueToken('WebWorker.onWebWorker')); diff --git a/modules/angular2/src/web_workers/shared/client_message_broker.ts b/modules/angular2/src/web_workers/shared/client_message_broker.ts index 168d312f80..2b4e68fe05 100644 --- a/modules/angular2/src/web_workers/shared/client_message_broker.ts +++ b/modules/angular2/src/web_workers/shared/client_message_broker.ts @@ -1,11 +1,16 @@ -import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; -import {print, isPresent, DateWrapper, stringify} from 'angular2/src/facade/lang'; -import {PromiseCompleter, PromiseWrapper, ObservableWrapper, EventEmitter} from 'angular2/src/facade/async'; -import {StringMapWrapper, MapWrapper} from 'angular2/src/facade/collection'; -import {Serializer} from 'angular2/src/web_workers/shared/serializer'; -import {Injectable} from 'angular2/src/core/di'; -import {Type, StringWrapper} from 'angular2/src/facade/lang'; -export {Type} from 'angular2/src/facade/lang'; +import {MessageBus} from "angular2/src/web_workers/shared/message_bus"; +import {print, isPresent, DateWrapper, stringify} from "angular2/src/facade/lang"; +import { + PromiseCompleter, + PromiseWrapper, + ObservableWrapper, + EventEmitter +} from "angular2/src/facade/async"; +import {StringMapWrapper, MapWrapper} from "angular2/src/facade/collection"; +import {Serializer} from "angular2/src/web_workers/shared/serializer"; +import {Injectable} from "angular2/src/core/di"; +import {Type, StringWrapper} from "angular2/src/facade/lang"; +export {Type} from "angular2/src/facade/lang"; export abstract class ClientMessageBrokerFactory { /** @@ -47,8 +52,8 @@ export class ClientMessageBroker_ extends ClientMessageBroker { this._sink = messageBus.to(channel); this._serializer = _serializer; var source = messageBus.from(channel); - ObservableWrapper.subscribe( - source, (message: {[key: string]: any}) => this._handleMessage(message)); + ObservableWrapper.subscribe(source, + (message: {[key: string]: any}) => this._handleMessage(message)); } private _generateMessageId(name: string): string { @@ -109,10 +114,10 @@ export class ClientMessageBroker_ extends ClientMessageBroker { private _handleMessage(message: {[key: string]: any}): void { var data = new MessageData(message); // TODO(jteplitz602): replace these strings with messaging constants #3685 - if (StringWrapper.equals(data.type, 'result') || StringWrapper.equals(data.type, 'error')) { + if (StringWrapper.equals(data.type, "result") || StringWrapper.equals(data.type, "error")) { var id = data.id; if (this._pending.has(id)) { - if (StringWrapper.equals(data.type, 'result')) { + if (StringWrapper.equals(data.type, "result")) { this._pending.get(id).resolve(data.value); } else { this._pending.get(id).reject(data.value, null); @@ -129,9 +134,9 @@ class MessageData { id: string; constructor(data: {[key: string]: any}) { - this.type = StringMapWrapper.get(data, 'type'); - this.id = this._getValueIfPresent(data, 'id'); - this.value = this._getValueIfPresent(data, 'value'); + this.type = StringMapWrapper.get(data, "type"); + this.id = this._getValueIfPresent(data, "id"); + this.value = this._getValueIfPresent(data, "value"); } /** diff --git a/modules/angular2/src/web_workers/shared/messaging_api.ts b/modules/angular2/src/web_workers/shared/messaging_api.ts index 055f06d238..b0207dddf0 100644 --- a/modules/angular2/src/web_workers/shared/messaging_api.ts +++ b/modules/angular2/src/web_workers/shared/messaging_api.ts @@ -2,7 +2,7 @@ * All channels used by angular's WebWorker components are listed here. * You should not use these channels in your application code. */ -export const RENDERER_CHANNEL = 'ng-Renderer'; -export const XHR_CHANNEL = 'ng-XHR'; -export const EVENT_CHANNEL = 'ng-Events'; -export const ROUTER_CHANNEL = 'ng-Router'; +export const RENDERER_CHANNEL = "ng-Renderer"; +export const XHR_CHANNEL = "ng-XHR"; +export const EVENT_CHANNEL = "ng-Events"; +export const ROUTER_CHANNEL = "ng-Router"; diff --git a/modules/angular2/src/web_workers/shared/post_message_bus.ts b/modules/angular2/src/web_workers/shared/post_message_bus.ts index 6d18c05b9d..0c1896d4f6 100644 --- a/modules/angular2/src/web_workers/shared/post_message_bus.ts +++ b/modules/angular2/src/web_workers/shared/post_message_bus.ts @@ -1,14 +1,16 @@ -import {MessageBus, MessageBusSource, MessageBusSink} from 'angular2/src/web_workers/shared/message_bus'; +import { + MessageBus, + MessageBusSource, + MessageBusSink +} from "angular2/src/web_workers/shared/message_bus"; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import {StringMapWrapper} from 'angular2/src/facade/collection'; -import {Injectable} from 'angular2/src/core/di'; +import {Injectable} from "angular2/src/core/di"; import {NgZone} from 'angular2/src/core/zone/ng_zone'; // TODO(jteplitz602) Replace this with the definition in lib.webworker.d.ts(#3492) -export interface PostMessageTarget { - postMessage: (message: any, transfer?: [ArrayBuffer]) => void; -} +export interface PostMessageTarget { postMessage: (message: any, transfer?:[ArrayBuffer]) => void; } export class PostMessageBusSink implements MessageBusSink { private _zone: NgZone; @@ -66,10 +68,10 @@ export class PostMessageBusSource implements MessageBusSource { constructor(eventTarget?: EventTarget) { if (eventTarget) { - eventTarget.addEventListener('message', (ev: MessageEvent) => this._handleMessages(ev)); + eventTarget.addEventListener("message", (ev: MessageEvent) => this._handleMessages(ev)); } else { // if no eventTarget is given we assume we're in a WebWorker and listen on the global scope - addEventListener('message', (ev: MessageEvent) => this._handleMessages(ev)); + addEventListener("message", (ev: MessageEvent) => this._handleMessages(ev)); } } diff --git a/modules/angular2/src/web_workers/shared/render_store.ts b/modules/angular2/src/web_workers/shared/render_store.ts index 1efb1f84a3..3b96c2ef26 100644 --- a/modules/angular2/src/web_workers/shared/render_store.ts +++ b/modules/angular2/src/web_workers/shared/render_store.ts @@ -1,4 +1,4 @@ -import {Injectable} from 'angular2/src/core/di'; +import {Injectable} from "angular2/src/core/di"; @Injectable() export class RenderStore { diff --git a/modules/angular2/src/web_workers/shared/serialized_types.ts b/modules/angular2/src/web_workers/shared/serialized_types.ts index fe3e963583..446537391f 100644 --- a/modules/angular2/src/web_workers/shared/serialized_types.ts +++ b/modules/angular2/src/web_workers/shared/serialized_types.ts @@ -1,8 +1,7 @@ // This file contains interface versions of browser types that can be serialized to Plain Old // JavaScript Objects export class LocationType { - constructor( - public href: string, public protocol: string, public host: string, public hostname: string, - public port: string, public pathname: string, public search: string, public hash: string, - public origin: string) {} + constructor(public href: string, public protocol: string, public host: string, + public hostname: string, public port: string, public pathname: string, + public search: string, public hash: string, public origin: string) {} } diff --git a/modules/angular2/src/web_workers/shared/serializer.ts b/modules/angular2/src/web_workers/shared/serializer.ts index 9ca8d7a7a5..87c88c0c46 100644 --- a/modules/angular2/src/web_workers/shared/serializer.ts +++ b/modules/angular2/src/web_workers/shared/serializer.ts @@ -1,9 +1,9 @@ -import {Type, isArray, isPresent, serializeEnum, deserializeEnum} from 'angular2/src/facade/lang'; +import {Type, isArray, isPresent, serializeEnum, deserializeEnum} from "angular2/src/facade/lang"; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {Map, StringMapWrapper, MapWrapper} from 'angular2/src/facade/collection'; -import {RenderComponentType} from 'angular2/src/core/render/api'; -import {Injectable} from 'angular2/src/core/di'; +import {Map, StringMapWrapper, MapWrapper} from "angular2/src/facade/collection"; +import {RenderComponentType} from "angular2/src/core/render/api"; +import {Injectable} from "angular2/src/core/di"; import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; import {ViewEncapsulation, VIEW_ENCAPSULATION_VALUES} from 'angular2/src/core/metadata/view'; import {LocationType} from './serialized_types'; @@ -35,7 +35,7 @@ export class Serializer { } else if (type === LocationType) { return this._serializeLocation(obj); } else { - throw new BaseException('No serializer for ' + type.toString()); + throw new BaseException("No serializer for " + type.toString()); } } @@ -61,7 +61,7 @@ export class Serializer { } else if (type === LocationType) { return this._deserializeLocation(map); } else { - throw new BaseException('No deserializer for ' + type.toString()); + throw new BaseException("No deserializer for " + type.toString()); } } @@ -87,8 +87,8 @@ export class Serializer { objectToMap(obj: {[key: string]: any}, type?: Type, data?: any): Map<string, any> { if (isPresent(type)) { var map = new Map<string, any>(); - StringMapWrapper.forEach( - obj, (val, key) => { map.set(key, this.deserialize(val, type, data)); }); + StringMapWrapper.forEach(obj, + (val, key) => { map.set(key, this.deserialize(val, type, data)); }); return map; } else { return MapWrapper.createFromStringMap(obj); @@ -110,9 +110,8 @@ export class Serializer { } private _deserializeLocation(loc: {[key: string]: any}): LocationType { - return new LocationType( - loc['href'], loc['protocol'], loc['host'], loc['hostname'], loc['port'], loc['pathname'], - loc['search'], loc['hash'], loc['origin']); + return new LocationType(loc['href'], loc['protocol'], loc['host'], loc['hostname'], loc['port'], + loc['pathname'], loc['search'], loc['hash'], loc['origin']); } private _serializeRenderComponentType(obj: RenderComponentType): Object { @@ -124,9 +123,9 @@ export class Serializer { } private _deserializeRenderComponentType(map: {[key: string]: any}): RenderComponentType { - return new RenderComponentType( - map['id'], this.deserialize(map['encapsulation'], ViewEncapsulation), - this.deserialize(map['styles'], PRIMITIVE)); + return new RenderComponentType(map['id'], + this.deserialize(map['encapsulation'], ViewEncapsulation), + this.deserialize(map['styles'], PRIMITIVE)); } } diff --git a/modules/angular2/src/web_workers/shared/service_message_broker.ts b/modules/angular2/src/web_workers/shared/service_message_broker.ts index 31d9698aae..eb67be1d1c 100644 --- a/modules/angular2/src/web_workers/shared/service_message_broker.ts +++ b/modules/angular2/src/web_workers/shared/service_message_broker.ts @@ -1,8 +1,8 @@ import {Injectable} from 'angular2/src/core/di'; import {ListWrapper, Map, MapWrapper} from 'angular2/src/facade/collection'; -import {Serializer} from 'angular2/src/web_workers/shared/serializer'; -import {isPresent, Type, FunctionWrapper} from 'angular2/src/facade/lang'; -import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; +import {Serializer} from "angular2/src/web_workers/shared/serializer"; +import {isPresent, Type, FunctionWrapper} from "angular2/src/facade/lang"; +import {MessageBus} from "angular2/src/web_workers/shared/message_bus"; import {EventEmitter, PromiseWrapper, ObservableWrapper} from 'angular2/src/facade/async'; export abstract class ServiceMessageBrokerFactory { @@ -29,8 +29,8 @@ export class ServiceMessageBrokerFactory_ extends ServiceMessageBrokerFactory { } export abstract class ServiceMessageBroker { - abstract registerMethod( - methodName: string, signature: Type[], method: Function, returnType?: Type): void; + abstract registerMethod(methodName: string, signature: Type[], method: Function, + returnType?: Type): void; } /** @@ -50,9 +50,8 @@ export class ServiceMessageBroker_ extends ServiceMessageBroker { ObservableWrapper.subscribe(source, (message) => this._handleMessage(message)); } - registerMethod( - methodName: string, signature: Type[], method: (..._: any[]) => Promise<any>| void, - returnType?: Type): void { + registerMethod(methodName: string, signature: Type[], method: (..._: any[]) => Promise<any>| void, + returnType?: Type): void { this._methods.set(methodName, (message: ReceivedMessage) => { var serializedArgs = message.args; let numArgs = signature === null ? 0 : signature.length; diff --git a/modules/angular2/src/web_workers/ui/event_dispatcher.ts b/modules/angular2/src/web_workers/ui/event_dispatcher.ts index 074b2f955c..194036869c 100644 --- a/modules/angular2/src/web_workers/ui/event_dispatcher.ts +++ b/modules/angular2/src/web_workers/ui/event_dispatcher.ts @@ -1,5 +1,11 @@ import {Serializer, RenderStoreObject} from 'angular2/src/web_workers/shared/serializer'; -import {serializeMouseEvent, serializeKeyboardEvent, serializeGenericEvent, serializeEventWithTarget, serializeTransitionEvent} from 'angular2/src/web_workers/ui/event_serializer'; +import { + serializeMouseEvent, + serializeKeyboardEvent, + serializeGenericEvent, + serializeEventWithTarget, + serializeTransitionEvent +} from 'angular2/src/web_workers/ui/event_serializer'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; @@ -11,90 +17,90 @@ export class EventDispatcher { var serializedEvent; // TODO (jteplitz602): support custom events #3350 switch (event.type) { - case 'click': - case 'mouseup': - case 'mousedown': - case 'dblclick': - case 'contextmenu': - case 'mouseenter': - case 'mouseleave': - case 'mousemove': - case 'mouseout': - case 'mouseover': - case 'show': + case "click": + case "mouseup": + case "mousedown": + case "dblclick": + case "contextmenu": + case "mouseenter": + case "mouseleave": + case "mousemove": + case "mouseout": + case "mouseover": + case "show": serializedEvent = serializeMouseEvent(event); break; - case 'keydown': - case 'keypress': - case 'keyup': + case "keydown": + case "keypress": + case "keyup": serializedEvent = serializeKeyboardEvent(event); break; - case 'input': - case 'change': - case 'blur': + case "input": + case "change": + case "blur": serializedEvent = serializeEventWithTarget(event); break; - case 'abort': - case 'afterprint': - case 'beforeprint': - case 'cached': - case 'canplay': - case 'canplaythrough': - case 'chargingchange': - case 'chargingtimechange': - case 'close': - case 'dischargingtimechange': - case 'DOMContentLoaded': - case 'downloading': - case 'durationchange': - case 'emptied': - case 'ended': - case 'error': - case 'fullscreenchange': - case 'fullscreenerror': - case 'invalid': - case 'languagechange': - case 'levelfchange': - case 'loadeddata': - case 'loadedmetadata': - case 'obsolete': - case 'offline': - case 'online': - case 'open': - case 'orientatoinchange': - case 'pause': - case 'pointerlockchange': - case 'pointerlockerror': - case 'play': - case 'playing': - case 'ratechange': - case 'readystatechange': - case 'reset': - case 'scroll': - case 'seeked': - case 'seeking': - case 'stalled': - case 'submit': - case 'success': - case 'suspend': - case 'timeupdate': - case 'updateready': - case 'visibilitychange': - case 'volumechange': - case 'waiting': + case "abort": + case "afterprint": + case "beforeprint": + case "cached": + case "canplay": + case "canplaythrough": + case "chargingchange": + case "chargingtimechange": + case "close": + case "dischargingtimechange": + case "DOMContentLoaded": + case "downloading": + case "durationchange": + case "emptied": + case "ended": + case "error": + case "fullscreenchange": + case "fullscreenerror": + case "invalid": + case "languagechange": + case "levelfchange": + case "loadeddata": + case "loadedmetadata": + case "obsolete": + case "offline": + case "online": + case "open": + case "orientatoinchange": + case "pause": + case "pointerlockchange": + case "pointerlockerror": + case "play": + case "playing": + case "ratechange": + case "readystatechange": + case "reset": + case "scroll": + case "seeked": + case "seeking": + case "stalled": + case "submit": + case "success": + case "suspend": + case "timeupdate": + case "updateready": + case "visibilitychange": + case "volumechange": + case "waiting": serializedEvent = serializeGenericEvent(event); break; - case 'transitionend': + case "transitionend": serializedEvent = serializeTransitionEvent(event); break; default: - throw new BaseException(eventName + ' not supported on WebWorkers'); + throw new BaseException(eventName + " not supported on WebWorkers"); } ObservableWrapper.callEmit(this._sink, { - 'element': this._serializer.serialize(element, RenderStoreObject), - 'eventName': eventName, - 'eventTarget': eventTarget, - 'event': serializedEvent + "element": this._serializer.serialize(element, RenderStoreObject), + "eventName": eventName, + "eventTarget": eventTarget, + "event": serializedEvent }); // TODO(kegluneq): Eventually, we want the user to indicate from the UI side whether the event diff --git a/modules/angular2/src/web_workers/ui/event_serializer.ts b/modules/angular2/src/web_workers/ui/event_serializer.ts index 42e41251d1..7fb743dc8a 100644 --- a/modules/angular2/src/web_workers/ui/event_serializer.ts +++ b/modules/angular2/src/web_workers/ui/event_serializer.ts @@ -2,13 +2,34 @@ import {Set} from 'angular2/src/facade/collection'; import {isPresent} from 'angular2/src/facade/lang'; const MOUSE_EVENT_PROPERTIES = [ - 'altKey', 'button', 'clientX', 'clientY', 'metaKey', 'movementX', 'movementY', 'offsetX', - 'offsetY', 'region', 'screenX', 'screenY', 'shiftKey' + "altKey", + "button", + "clientX", + "clientY", + "metaKey", + "movementX", + "movementY", + "offsetX", + "offsetY", + "region", + "screenX", + "screenY", + "shiftKey" ]; const KEYBOARD_EVENT_PROPERTIES = [ - 'altkey', 'charCode', 'code', 'ctrlKey', 'isComposing', 'key', 'keyCode', 'location', 'metaKey', - 'repeat', 'shiftKey', 'which' + 'altkey', + 'charCode', + 'code', + 'ctrlKey', + 'isComposing', + 'key', + 'keyCode', + 'location', + 'metaKey', + 'repeat', + 'shiftKey', + 'which' ]; const TRANSITION_EVENT_PROPERTIES = ['propertyName', 'elapsedTime', 'pseudoElement']; @@ -16,7 +37,7 @@ const TRANSITION_EVENT_PROPERTIES = ['propertyName', 'elapsedTime', 'pseudoEleme const EVENT_PROPERTIES = ['type', 'bubbles', 'cancelable']; const NODES_WITH_VALUE = - new Set(['input', 'select', 'option', 'button', 'li', 'meter', 'progress', 'param']); + new Set(["input", "select", "option", "button", "li", "meter", "progress", "param"]); export function serializeGenericEvent(e: Event): {[key: string]: any} { return serializeEvent(e, EVENT_PROPERTIES); diff --git a/modules/angular2/src/web_workers/ui/platform_location.ts b/modules/angular2/src/web_workers/ui/platform_location.ts index 3f5ca14921..fa9bd1c315 100644 --- a/modules/angular2/src/web_workers/ui/platform_location.ts +++ b/modules/angular2/src/web_workers/ui/platform_location.ts @@ -1,7 +1,10 @@ import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location'; import {Injectable} from 'angular2/src/core/di'; import {ROUTER_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api'; -import {ServiceMessageBrokerFactory, ServiceMessageBroker} from 'angular2/src/web_workers/shared/service_message_broker'; +import { + ServiceMessageBrokerFactory, + ServiceMessageBroker +} from 'angular2/src/web_workers/shared/service_message_broker'; import {PRIMITIVE, Serializer} from 'angular2/src/web_workers/shared/serializer'; import {bind} from './bind'; import {LocationType} from 'angular2/src/web_workers/shared/serialized_types'; @@ -14,10 +17,9 @@ export class MessageBasedPlatformLocation { private _channelSink: EventEmitter<Object>; private _broker: ServiceMessageBroker; - constructor( - private _brokerFactory: ServiceMessageBrokerFactory, - private _platformLocation: BrowserPlatformLocation, bus: MessageBus, - private _serializer: Serializer) { + constructor(private _brokerFactory: ServiceMessageBrokerFactory, + private _platformLocation: BrowserPlatformLocation, bus: MessageBus, + private _serializer: Serializer) { this._platformLocation.onPopState(<UrlChangeListener>bind(this._sendUrlChangeEvent, this)); this._platformLocation.onHashChange(<UrlChangeListener>bind(this._sendUrlChangeEvent, this)); this._broker = this._brokerFactory.createMessageBroker(ROUTER_CHANNEL); @@ -25,18 +27,16 @@ export class MessageBasedPlatformLocation { } start(): void { - this._broker.registerMethod('getLocation', null, bind(this._getLocation, this), LocationType); - this._broker.registerMethod('setPathname', [PRIMITIVE], bind(this._setPathname, this)); - this._broker.registerMethod( - 'pushState', [PRIMITIVE, PRIMITIVE, PRIMITIVE], - bind(this._platformLocation.pushState, this._platformLocation)); - this._broker.registerMethod( - 'replaceState', [PRIMITIVE, PRIMITIVE, PRIMITIVE], - bind(this._platformLocation.replaceState, this._platformLocation)); - this._broker.registerMethod( - 'forward', null, bind(this._platformLocation.forward, this._platformLocation)); - this._broker.registerMethod( - 'back', null, bind(this._platformLocation.back, this._platformLocation)); + this._broker.registerMethod("getLocation", null, bind(this._getLocation, this), LocationType); + this._broker.registerMethod("setPathname", [PRIMITIVE], bind(this._setPathname, this)); + this._broker.registerMethod("pushState", [PRIMITIVE, PRIMITIVE, PRIMITIVE], + bind(this._platformLocation.pushState, this._platformLocation)); + this._broker.registerMethod("replaceState", [PRIMITIVE, PRIMITIVE, PRIMITIVE], + bind(this._platformLocation.replaceState, this._platformLocation)); + this._broker.registerMethod("forward", null, + bind(this._platformLocation.forward, this._platformLocation)); + this._broker.registerMethod("back", null, + bind(this._platformLocation.back, this._platformLocation)); } private _getLocation(): Promise<Location> { diff --git a/modules/angular2/src/web_workers/ui/renderer.ts b/modules/angular2/src/web_workers/ui/renderer.ts index 2ba797b706..c76995feba 100644 --- a/modules/angular2/src/web_workers/ui/renderer.ts +++ b/modules/angular2/src/web_workers/ui/renderer.ts @@ -13,73 +13,65 @@ import {ServiceMessageBrokerFactory} from 'angular2/src/web_workers/shared/servi export class MessageBasedRenderer { private _eventDispatcher: EventDispatcher; - constructor( - private _brokerFactory: ServiceMessageBrokerFactory, private _bus: MessageBus, - private _serializer: Serializer, private _renderStore: RenderStore, - private _rootRenderer: RootRenderer) {} + constructor(private _brokerFactory: ServiceMessageBrokerFactory, private _bus: MessageBus, + private _serializer: Serializer, private _renderStore: RenderStore, + private _rootRenderer: RootRenderer) {} start(): void { var broker = this._brokerFactory.createMessageBroker(RENDERER_CHANNEL); this._bus.initChannel(EVENT_CHANNEL); this._eventDispatcher = new EventDispatcher(this._bus.to(EVENT_CHANNEL), this._serializer); - broker.registerMethod( - 'renderComponent', [RenderComponentType, PRIMITIVE], bind(this._renderComponent, this)); + broker.registerMethod("renderComponent", [RenderComponentType, PRIMITIVE], + bind(this._renderComponent, this)); - broker.registerMethod( - 'selectRootElement', [RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._selectRootElement, this)); - broker.registerMethod( - 'createElement', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._createElement, this)); - broker.registerMethod( - 'createViewRoot', [RenderStoreObject, RenderStoreObject, PRIMITIVE], - bind(this._createViewRoot, this)); - broker.registerMethod( - 'createTemplateAnchor', [RenderStoreObject, RenderStoreObject, PRIMITIVE], - bind(this._createTemplateAnchor, this)); - broker.registerMethod( - 'createText', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._createText, this)); - broker.registerMethod( - 'projectNodes', [RenderStoreObject, RenderStoreObject, RenderStoreObject], - bind(this._projectNodes, this)); - broker.registerMethod( - 'attachViewAfter', [RenderStoreObject, RenderStoreObject, RenderStoreObject], - bind(this._attachViewAfter, this)); - broker.registerMethod( - 'detachView', [RenderStoreObject, RenderStoreObject], bind(this._detachView, this)); - broker.registerMethod( - 'destroyView', [RenderStoreObject, RenderStoreObject, RenderStoreObject], - bind(this._destroyView, this)); - broker.registerMethod( - 'setElementProperty', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._setElementProperty, this)); - broker.registerMethod( - 'setElementAttribute', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._setElementAttribute, this)); - broker.registerMethod( - 'setBindingDebugInfo', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._setBindingDebugInfo, this)); - broker.registerMethod( - 'setElementClass', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._setElementClass, this)); - broker.registerMethod( - 'setElementStyle', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._setElementStyle, this)); - broker.registerMethod( - 'invokeElementMethod', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._invokeElementMethod, this)); - broker.registerMethod( - 'setText', [RenderStoreObject, RenderStoreObject, PRIMITIVE], bind(this._setText, this)); - broker.registerMethod( - 'listen', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], - bind(this._listen, this)); - broker.registerMethod( - 'listenGlobal', [RenderStoreObject, PRIMITIVE, PRIMITIVE, PRIMITIVE], - bind(this._listenGlobal, this)); - broker.registerMethod( - 'listenDone', [RenderStoreObject, RenderStoreObject], bind(this._listenDone, this)); + broker.registerMethod("selectRootElement", [RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._selectRootElement, this)); + broker.registerMethod("createElement", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._createElement, this)); + broker.registerMethod("createViewRoot", [RenderStoreObject, RenderStoreObject, PRIMITIVE], + bind(this._createViewRoot, this)); + broker.registerMethod("createTemplateAnchor", [RenderStoreObject, RenderStoreObject, PRIMITIVE], + bind(this._createTemplateAnchor, this)); + broker.registerMethod("createText", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._createText, this)); + broker.registerMethod("projectNodes", [RenderStoreObject, RenderStoreObject, RenderStoreObject], + bind(this._projectNodes, this)); + broker.registerMethod("attachViewAfter", + [RenderStoreObject, RenderStoreObject, RenderStoreObject], + bind(this._attachViewAfter, this)); + broker.registerMethod("detachView", [RenderStoreObject, RenderStoreObject], + bind(this._detachView, this)); + broker.registerMethod("destroyView", [RenderStoreObject, RenderStoreObject, RenderStoreObject], + bind(this._destroyView, this)); + broker.registerMethod("setElementProperty", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._setElementProperty, this)); + broker.registerMethod("setElementAttribute", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._setElementAttribute, this)); + broker.registerMethod("setBindingDebugInfo", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._setBindingDebugInfo, this)); + broker.registerMethod("setElementClass", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._setElementClass, this)); + broker.registerMethod("setElementStyle", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._setElementStyle, this)); + broker.registerMethod("invokeElementMethod", + [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._invokeElementMethod, this)); + broker.registerMethod("setText", [RenderStoreObject, RenderStoreObject, PRIMITIVE], + bind(this._setText, this)); + broker.registerMethod("listen", [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], + bind(this._listen, this)); + broker.registerMethod("listenGlobal", [RenderStoreObject, PRIMITIVE, PRIMITIVE, PRIMITIVE], + bind(this._listenGlobal, this)); + broker.registerMethod("listenDone", [RenderStoreObject, RenderStoreObject], + bind(this._listenDone, this)); } private _renderComponent(renderComponentType: RenderComponentType, rendererId: number) { @@ -129,33 +121,33 @@ export class MessageBasedRenderer { } } - private _setElementProperty( - renderer: Renderer, renderElement: any, propertyName: string, propertyValue: any) { + private _setElementProperty(renderer: Renderer, renderElement: any, propertyName: string, + propertyValue: any) { renderer.setElementProperty(renderElement, propertyName, propertyValue); } - private _setElementAttribute( - renderer: Renderer, renderElement: any, attributeName: string, attributeValue: string) { + private _setElementAttribute(renderer: Renderer, renderElement: any, attributeName: string, + attributeValue: string) { renderer.setElementAttribute(renderElement, attributeName, attributeValue); } - private _setBindingDebugInfo( - renderer: Renderer, renderElement: any, propertyName: string, propertyValue: string) { + private _setBindingDebugInfo(renderer: Renderer, renderElement: any, propertyName: string, + propertyValue: string) { renderer.setBindingDebugInfo(renderElement, propertyName, propertyValue); } - private _setElementClass( - renderer: Renderer, renderElement: any, className: string, isAdd: boolean) { + private _setElementClass(renderer: Renderer, renderElement: any, className: string, + isAdd: boolean) { renderer.setElementClass(renderElement, className, isAdd); } - private _setElementStyle( - renderer: Renderer, renderElement: any, styleName: string, styleValue: string) { + private _setElementStyle(renderer: Renderer, renderElement: any, styleName: string, + styleValue: string) { renderer.setElementStyle(renderElement, styleName, styleValue); } - private _invokeElementMethod( - renderer: Renderer, renderElement: any, methodName: string, args: any[]) { + private _invokeElementMethod(renderer: Renderer, renderElement: any, methodName: string, + args: any[]) { renderer.invokeElementMethod(renderElement, methodName, args); } @@ -164,14 +156,14 @@ export class MessageBasedRenderer { } private _listen(renderer: Renderer, renderElement: any, eventName: string, unlistenId: number) { - var unregisterCallback = renderer.listen( - renderElement, eventName, (event) => this._eventDispatcher.dispatchRenderEvent( - renderElement, null, eventName, event)); + var unregisterCallback = renderer.listen(renderElement, eventName, + (event) => this._eventDispatcher.dispatchRenderEvent( + renderElement, null, eventName, event)); this._renderStore.store(unregisterCallback, unlistenId); } - private _listenGlobal( - renderer: Renderer, eventTarget: string, eventName: string, unlistenId: number) { + private _listenGlobal(renderer: Renderer, eventTarget: string, eventName: string, + unlistenId: number) { var unregisterCallback = renderer.listenGlobal( eventTarget, eventName, (event) => this._eventDispatcher.dispatchRenderEvent(null, eventTarget, eventName, event)); diff --git a/modules/angular2/src/web_workers/ui/router_providers.ts b/modules/angular2/src/web_workers/ui/router_providers.ts index 9434ed1ad8..21edef9beb 100644 --- a/modules/angular2/src/web_workers/ui/router_providers.ts +++ b/modules/angular2/src/web_workers/ui/router_providers.ts @@ -4,10 +4,11 @@ import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_plat import {APP_INITIALIZER, Provider, Injector, NgZone} from 'angular2/core'; export const WORKER_RENDER_ROUTER = CONST_EXPR([ - MessageBasedPlatformLocation, BrowserPlatformLocation, - CONST_EXPR(new Provider( - APP_INITIALIZER, - {useFactory: initRouterListeners, multi: true, deps: CONST_EXPR([Injector])})) + MessageBasedPlatformLocation, + BrowserPlatformLocation, + CONST_EXPR( + new Provider(APP_INITIALIZER, + {useFactory: initRouterListeners, multi: true, deps: CONST_EXPR([Injector])})) ]); function initRouterListeners(injector: Injector): () => void { diff --git a/modules/angular2/src/web_workers/ui/xhr_impl.ts b/modules/angular2/src/web_workers/ui/xhr_impl.ts index 95dc7fc997..1d4d346c72 100644 --- a/modules/angular2/src/web_workers/ui/xhr_impl.ts +++ b/modules/angular2/src/web_workers/ui/xhr_impl.ts @@ -11,6 +11,6 @@ export class MessageBasedXHRImpl { start(): void { var broker = this._brokerFactory.createMessageBroker(XHR_CHANNEL); - broker.registerMethod('get', [PRIMITIVE], bind(this._xhr.get, this._xhr), PRIMITIVE); + broker.registerMethod("get", [PRIMITIVE], bind(this._xhr.get, this._xhr), PRIMITIVE); } } diff --git a/modules/angular2/src/web_workers/worker/event_deserializer.ts b/modules/angular2/src/web_workers/worker/event_deserializer.ts index 5fee619913..5a7f42ce1a 100644 --- a/modules/angular2/src/web_workers/worker/event_deserializer.ts +++ b/modules/angular2/src/web_workers/worker/event_deserializer.ts @@ -1,6 +1,6 @@ // no deserialization is necessary in TS. // This is only here to match dart interface -export function deserializeGenericEvent(serializedEvent: {[key: string]: any}): - {[key: string]: any} { +export function deserializeGenericEvent( + serializedEvent: {[key: string]: any}): {[key: string]: any} { return serializedEvent; } diff --git a/modules/angular2/src/web_workers/worker/platform_location.ts b/modules/angular2/src/web_workers/worker/platform_location.ts index 4601366ee3..59ce6bee84 100644 --- a/modules/angular2/src/web_workers/worker/platform_location.ts +++ b/modules/angular2/src/web_workers/worker/platform_location.ts @@ -1,6 +1,15 @@ import {Injectable} from 'angular2/src/core/di'; -import {PlatformLocation, UrlChangeEvent, UrlChangeListener} from 'angular2/src/router/location/platform_location'; -import {FnArg, UiArguments, ClientMessageBroker, ClientMessageBrokerFactory} from 'angular2/src/web_workers/shared/client_message_broker'; +import { + PlatformLocation, + UrlChangeEvent, + UrlChangeListener +} from 'angular2/src/router/location/platform_location'; +import { + FnArg, + UiArguments, + ClientMessageBroker, + ClientMessageBrokerFactory +} from 'angular2/src/web_workers/shared/client_message_broker'; import {ROUTER_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api'; import {LocationType} from 'angular2/src/web_workers/shared/serialized_types'; import {PromiseWrapper, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; @@ -19,8 +28,8 @@ export class WebWorkerPlatformLocation extends PlatformLocation { private _location: LocationType = null; private _channelSource: EventEmitter<Object>; - constructor( - brokerFactory: ClientMessageBrokerFactory, bus: MessageBus, private _serializer: Serializer) { + constructor(brokerFactory: ClientMessageBrokerFactory, bus: MessageBus, + private _serializer: Serializer) { super(); this._broker = brokerFactory.createMessageBroker(ROUTER_CHANNEL); @@ -29,9 +38,9 @@ export class WebWorkerPlatformLocation extends PlatformLocation { var listeners: Array<Function> = null; if (StringMapWrapper.contains(msg, 'event')) { let type: string = msg['event']['type']; - if (StringWrapper.equals(type, 'popstate')) { + if (StringWrapper.equals(type, "popstate")) { listeners = this._popStateListeners; - } else if (StringWrapper.equals(type, 'hashchange')) { + } else if (StringWrapper.equals(type, "hashchange")) { listeners = this._hashChangeListeners; } @@ -47,21 +56,18 @@ export class WebWorkerPlatformLocation extends PlatformLocation { /** @internal **/ init(): Promise<boolean> { - var args: UiArguments = new UiArguments('getLocation'); + var args: UiArguments = new UiArguments("getLocation"); var locationPromise: Promise<LocationType> = this._broker.runOnService(args, LocationType); - return PromiseWrapper.then( - locationPromise, (val: LocationType): - boolean => { - this._location = val; - return true; - }, - (err): boolean => { throw new BaseException(err); }); + return PromiseWrapper.then(locationPromise, (val: LocationType): boolean => { + this._location = val; + return true; + }, (err): boolean => { throw new BaseException(err); }); } getBaseHrefFromDOM(): string { throw new BaseException( - 'Attempt to get base href from DOM from WebWorker. You must either provide a value for the APP_BASE_HREF token through DI or use the hash location strategy.'); + "Attempt to get base href from DOM from WebWorker. You must either provide a value for the APP_BASE_HREF token through DI or use the hash location strategy."); } onPopState(fn: UrlChangeListener): void { this._popStateListeners.push(fn); } @@ -94,37 +100,37 @@ export class WebWorkerPlatformLocation extends PlatformLocation { set pathname(newPath: string) { if (this._location === null) { - throw new BaseException('Attempt to set pathname before value is obtained from UI'); + throw new BaseException("Attempt to set pathname before value is obtained from UI"); } this._location.pathname = newPath; var fnArgs = [new FnArg(newPath, PRIMITIVE)]; - var args = new UiArguments('setPathname', fnArgs); + var args = new UiArguments("setPathname", fnArgs); this._broker.runOnService(args, null); } pushState(state: any, title: string, url: string): void { var fnArgs = [new FnArg(state, PRIMITIVE), new FnArg(title, PRIMITIVE), new FnArg(url, PRIMITIVE)]; - var args = new UiArguments('pushState', fnArgs); + var args = new UiArguments("pushState", fnArgs); this._broker.runOnService(args, null); } replaceState(state: any, title: string, url: string): void { var fnArgs = [new FnArg(state, PRIMITIVE), new FnArg(title, PRIMITIVE), new FnArg(url, PRIMITIVE)]; - var args = new UiArguments('replaceState', fnArgs); + var args = new UiArguments("replaceState", fnArgs); this._broker.runOnService(args, null); } forward(): void { - var args = new UiArguments('forward'); + var args = new UiArguments("forward"); this._broker.runOnService(args, null); } back(): void { - var args = new UiArguments('back'); + var args = new UiArguments("back"); this._broker.runOnService(args, null); } } diff --git a/modules/angular2/src/web_workers/worker/renderer.ts b/modules/angular2/src/web_workers/worker/renderer.ts index 665f2069dd..0a37d972a9 100644 --- a/modules/angular2/src/web_workers/worker/renderer.ts +++ b/modules/angular2/src/web_workers/worker/renderer.ts @@ -1,8 +1,18 @@ -import {Renderer, RootRenderer, RenderComponentType, RenderDebugInfo} from 'angular2/src/core/render/api'; -import {ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments} from 'angular2/src/web_workers/shared/client_message_broker'; -import {isPresent, isBlank, print} from 'angular2/src/facade/lang'; +import { + Renderer, + RootRenderer, + RenderComponentType, + RenderDebugInfo +} from 'angular2/src/core/render/api'; +import { + ClientMessageBroker, + ClientMessageBrokerFactory, + FnArg, + UiArguments +} from "angular2/src/web_workers/shared/client_message_broker"; +import {isPresent, isBlank, print} from "angular2/src/facade/lang"; import {ListWrapper} from 'angular2/src/facade/collection'; -import {Injectable} from 'angular2/src/core/di'; +import {Injectable} from "angular2/src/core/di"; import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; import {RENDERER_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api'; import {Serializer, RenderStoreObject} from 'angular2/src/web_workers/shared/serializer'; @@ -19,9 +29,8 @@ export class WebWorkerRootRenderer implements RootRenderer { private _componentRenderers: Map<string, WebWorkerRenderer> = new Map<string, WebWorkerRenderer>(); - constructor( - messageBrokerFactory: ClientMessageBrokerFactory, bus: MessageBus, - private _serializer: Serializer, private _renderStore: RenderStore) { + constructor(messageBrokerFactory: ClientMessageBrokerFactory, bus: MessageBus, + private _serializer: Serializer, private _renderStore: RenderStore) { this._messageBroker = messageBrokerFactory.createMessageBroker(RENDERER_CHANNEL); bus.initChannel(EVENT_CHANNEL); var source = bus.from(EVENT_CHANNEL); @@ -78,8 +87,8 @@ export class WebWorkerRootRenderer implements RootRenderer { } export class WebWorkerRenderer implements Renderer, RenderStoreObject { - constructor( - private _rootRenderer: WebWorkerRootRenderer, private _componentType: RenderComponentType) {} + constructor(private _rootRenderer: WebWorkerRootRenderer, + private _componentType: RenderComponentType) {} renderComponent(componentType: RenderComponentType): Renderer { return this._rootRenderer.renderComponent(componentType); @@ -92,15 +101,16 @@ export class WebWorkerRenderer implements Renderer, RenderStoreObject { selectRootElement(selector: string): any { var node = this._rootRenderer.allocateNode(); - this._runOnService( - 'selectRootElement', [new FnArg(selector, null), new FnArg(node, RenderStoreObject)]); + this._runOnService('selectRootElement', + [new FnArg(selector, null), new FnArg(node, RenderStoreObject)]); return node; } createElement(parentElement: any, name: string): any { var node = this._rootRenderer.allocateNode(); this._runOnService('createElement', [ - new FnArg(parentElement, RenderStoreObject), new FnArg(name, null), + new FnArg(parentElement, RenderStoreObject), + new FnArg(name, null), new FnArg(node, RenderStoreObject) ]); return node; @@ -108,8 +118,8 @@ export class WebWorkerRenderer implements Renderer, RenderStoreObject { createViewRoot(hostElement: any): any { var viewRoot = this._componentType.encapsulation === ViewEncapsulation.Native ? - this._rootRenderer.allocateNode() : - hostElement; + this._rootRenderer.allocateNode() : + hostElement; this._runOnService( 'createViewRoot', [new FnArg(hostElement, RenderStoreObject), new FnArg(viewRoot, RenderStoreObject)]); @@ -127,7 +137,8 @@ export class WebWorkerRenderer implements Renderer, RenderStoreObject { createText(parentElement: any, value: string): any { var node = this._rootRenderer.allocateNode(); this._runOnService('createText', [ - new FnArg(parentElement, RenderStoreObject), new FnArg(value, null), + new FnArg(parentElement, RenderStoreObject), + new FnArg(value, null), new FnArg(node, RenderStoreObject) ]); return node; @@ -158,21 +169,24 @@ export class WebWorkerRenderer implements Renderer, RenderStoreObject { setElementProperty(renderElement: any, propertyName: string, propertyValue: any) { this._runOnService('setElementProperty', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(propertyName, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(propertyName, null), new FnArg(propertyValue, null) ]); } setElementAttribute(renderElement: any, attributeName: string, attributeValue: string) { this._runOnService('setElementAttribute', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(attributeName, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(attributeName, null), new FnArg(attributeValue, null) ]); } setBindingDebugInfo(renderElement: any, propertyName: string, propertyValue: string) { this._runOnService('setBindingDebugInfo', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(propertyName, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(propertyName, null), new FnArg(propertyValue, null) ]); } @@ -181,35 +195,39 @@ export class WebWorkerRenderer implements Renderer, RenderStoreObject { setElementClass(renderElement: any, className: string, isAdd: boolean) { this._runOnService('setElementClass', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(className, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(className, null), new FnArg(isAdd, null) ]); } setElementStyle(renderElement: any, styleName: string, styleValue: string) { this._runOnService('setElementStyle', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(styleName, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(styleName, null), new FnArg(styleValue, null) ]); } invokeElementMethod(renderElement: any, methodName: string, args: any[]) { this._runOnService('invokeElementMethod', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(methodName, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(methodName, null), new FnArg(args, null) ]); } setText(renderNode: any, text: string) { - this._runOnService( - 'setText', [new FnArg(renderNode, RenderStoreObject), new FnArg(text, null)]); + this._runOnService('setText', + [new FnArg(renderNode, RenderStoreObject), new FnArg(text, null)]); } listen(renderElement: WebWorkerRenderNode, name: string, callback: Function): Function { renderElement.events.listen(name, callback); var unlistenCallbackId = this._rootRenderer.allocateId(); this._runOnService('listen', [ - new FnArg(renderElement, RenderStoreObject), new FnArg(name, null), + new FnArg(renderElement, RenderStoreObject), + new FnArg(name, null), new FnArg(unlistenCallbackId, null) ]); return () => { diff --git a/modules/angular2/src/web_workers/worker/router_providers.ts b/modules/angular2/src/web_workers/worker/router_providers.ts index 4104e1b0df..3a07f1cdd5 100644 --- a/modules/angular2/src/web_workers/worker/router_providers.ts +++ b/modules/angular2/src/web_workers/worker/router_providers.ts @@ -4,13 +4,15 @@ import {WebWorkerPlatformLocation} from './platform_location'; import {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common'; export var WORKER_APP_ROUTER = [ - ROUTER_PROVIDERS_COMMON, new Provider(PlatformLocation, {useClass: WebWorkerPlatformLocation}), - new Provider(APP_INITIALIZER, { - useFactory: (platformLocation: WebWorkerPlatformLocation, zone: NgZone) => () => - initRouter(platformLocation, zone), - multi: true, - deps: [PlatformLocation, NgZone] - }) + ROUTER_PROVIDERS_COMMON, + new Provider(PlatformLocation, {useClass: WebWorkerPlatformLocation}), + new Provider(APP_INITIALIZER, + { + useFactory: (platformLocation: WebWorkerPlatformLocation, zone: NgZone) => () => + initRouter(platformLocation, zone), + multi: true, + deps: [PlatformLocation, NgZone] + }) ]; function initRouter(platformLocation: WebWorkerPlatformLocation, zone: NgZone): Promise<boolean> { diff --git a/modules/angular2/src/web_workers/worker/xhr_impl.ts b/modules/angular2/src/web_workers/worker/xhr_impl.ts index 0227060208..5b25ecfe76 100644 --- a/modules/angular2/src/web_workers/worker/xhr_impl.ts +++ b/modules/angular2/src/web_workers/worker/xhr_impl.ts @@ -1,6 +1,11 @@ import {Injectable} from 'angular2/src/core/di'; import {XHR} from 'angular2/src/compiler/xhr'; -import {FnArg, UiArguments, ClientMessageBroker, ClientMessageBrokerFactory} from 'angular2/src/web_workers/shared/client_message_broker'; +import { + FnArg, + UiArguments, + ClientMessageBroker, + ClientMessageBrokerFactory +} from 'angular2/src/web_workers/shared/client_message_broker'; import {XHR_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api'; /** @@ -18,7 +23,7 @@ export class WebWorkerXHRImpl extends XHR { get(url: string): Promise<string> { var fnArgs: FnArg[] = [new FnArg(url, null)]; - var args: UiArguments = new UiArguments('get', fnArgs); + var args: UiArguments = new UiArguments("get", fnArgs); return this._messageBroker.runOnService(args, String); } } diff --git a/modules/angular2/test/animate/animation_builder_spec.ts b/modules/angular2/test/animate/animation_builder_spec.ts index c9fc21aca5..ce95349236 100644 --- a/modules/angular2/test/animate/animation_builder_spec.ts +++ b/modules/angular2/test/animate/animation_builder_spec.ts @@ -3,7 +3,7 @@ import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; export function main() { - describe('AnimationBuilder', () => { + describe("AnimationBuilder", () => { it('should have data object', inject([AnimationBuilder], animate => { var animateCss = animate.css(); diff --git a/modules/angular2/test/common/directives/ng_class_spec.ts b/modules/angular2/test/common/directives/ng_class_spec.ts index 2ec1f1450b..2330f2a0a3 100644 --- a/modules/angular2/test/common/directives/ng_class_spec.ts +++ b/modules/angular2/test/common/directives/ng_class_spec.ts @@ -1,4 +1,19 @@ -import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, beforeEachProviders, ddescribe, xdescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + beforeEachProviders, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {ListWrapper, StringMapWrapper, SetWrapper} from 'angular2/src/facade/collection'; import {Component, provide} from 'angular2/core'; import {NgFor} from 'angular2/common'; diff --git a/modules/angular2/test/common/directives/ng_for_spec.ts b/modules/angular2/test/common/directives/ng_for_spec.ts index 4c05212068..f89507ef43 100644 --- a/modules/angular2/test/common/directives/ng_for_spec.ts +++ b/modules/angular2/test/common/directives/ng_for_spec.ts @@ -1,4 +1,17 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEach, beforeEachProviders, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + beforeEachProviders, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {ListWrapper} from 'angular2/src/facade/collection'; import {IS_DART} from 'angular2/src/facade/lang'; @@ -149,16 +162,18 @@ export function main() { if (!IS_DART) { it('should throw on non-iterable ref and suggest using an array', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideTemplate(TestComponent, TEMPLATE).createAsync(TestComponent).then((fixture) => { - fixture.debugElement.componentInstance.items = 'whaaa'; - try { - fixture.detectChanges() - } catch (e) { - expect(e.message).toContain( - `Cannot find a differ supporting object 'whaaa' of type 'string'. NgFor only supports binding to Iterables such as Arrays.`); - async.done(); - } - }); + tcb.overrideTemplate(TestComponent, TEMPLATE) + .createAsync(TestComponent) + .then((fixture) => { + fixture.debugElement.componentInstance.items = 'whaaa'; + try { + fixture.detectChanges() + } catch (e) { + expect(e.message).toContain( + `Cannot find a differ supporting object 'whaaa' of type 'string'. NgFor only supports binding to Iterables such as Arrays.`); + async.done(); + } + }); })); } @@ -192,12 +207,12 @@ export function main() { it('should repeat over nested arrays', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div>' + - '<div template="ngFor #item of items">' + - '<div template="ngFor #subitem of item">' + - '{{subitem}}-{{item.length}};' + - '</div>|' + - '</div>' + - '</div>'; + '<div template="ngFor #item of items">' + + '<div template="ngFor #subitem of item">' + + '{{subitem}}-{{item.length}};' + + '</div>|' + + '</div>' + + '</div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) @@ -219,9 +234,9 @@ export function main() { it('should repeat over nested arrays with no intermediate element', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div><template ngFor #item [ngForOf]="items">' + - '<div template="ngFor #subitem of item">' + - '{{subitem}}-{{item.length}};' + - '</div></template></div>'; + '<div template="ngFor #subitem of item">' + + '{{subitem}}-{{item.length}};' + + '</div></template></div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) diff --git a/modules/angular2/test/common/directives/ng_if_spec.ts b/modules/angular2/test/common/directives/ng_if_spec.ts index 9f1b75d70f..921855dc5a 100644 --- a/modules/angular2/test/common/directives/ng_if_spec.ts +++ b/modules/angular2/test/common/directives/ng_if_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; @@ -13,13 +25,15 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var html = '<div><copy-me template="ngIf booleanCondition">hello</copy-me></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello'); - async.done(); - }); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello'); + async.done(); + }); })); it('should work in a template element', @@ -27,40 +41,44 @@ export function main() { var html = '<div><template [ngIf]="booleanCondition"><copy-me>hello2</copy-me></template></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello2'); - async.done(); - }); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello2'); + async.done(); + }); })); it('should toggle node when condition changes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var html = '<div><copy-me template="ngIf booleanCondition">hello</copy-me></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.debugElement.componentInstance.booleanCondition = false; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(0); - expect(fixture.debugElement.nativeElement).toHaveText(''); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.debugElement.componentInstance.booleanCondition = false; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(0); + expect(fixture.debugElement.nativeElement).toHaveText(''); - fixture.debugElement.componentInstance.booleanCondition = true; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello'); + fixture.debugElement.componentInstance.booleanCondition = true; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello'); - fixture.debugElement.componentInstance.booleanCondition = false; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(0); - expect(fixture.debugElement.nativeElement).toHaveText(''); + fixture.debugElement.componentInstance.booleanCondition = false; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(0); + expect(fixture.debugElement.nativeElement).toHaveText(''); - async.done(); - }); + async.done(); + }); })); it('should handle nested if correctly', @@ -68,70 +86,75 @@ export function main() { var html = '<div><template [ngIf]="booleanCondition"><copy-me *ngIf="nestedBooleanCondition">hello</copy-me></template></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.debugElement.componentInstance.booleanCondition = false; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(0); - expect(fixture.debugElement.nativeElement).toHaveText(''); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.debugElement.componentInstance.booleanCondition = false; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(0); + expect(fixture.debugElement.nativeElement).toHaveText(''); - fixture.debugElement.componentInstance.booleanCondition = true; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello'); + fixture.debugElement.componentInstance.booleanCondition = true; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello'); - fixture.debugElement.componentInstance.nestedBooleanCondition = false; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(0); - expect(fixture.debugElement.nativeElement).toHaveText(''); + fixture.debugElement.componentInstance.nestedBooleanCondition = false; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(0); + expect(fixture.debugElement.nativeElement).toHaveText(''); - fixture.debugElement.componentInstance.nestedBooleanCondition = true; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello'); + fixture.debugElement.componentInstance.nestedBooleanCondition = true; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello'); - fixture.debugElement.componentInstance.booleanCondition = false; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(0); - expect(fixture.debugElement.nativeElement).toHaveText(''); + fixture.debugElement.componentInstance.booleanCondition = false; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(0); + expect(fixture.debugElement.nativeElement).toHaveText(''); - async.done(); - }); + async.done(); + }); })); it('should update several nodes with if', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var html = '<div>' + + var html = + '<div>' + '<copy-me template="ngIf numberCondition + 1 >= 2">helloNumber</copy-me>' + '<copy-me template="ngIf stringCondition == \'foo\'">helloString</copy-me>' + '<copy-me template="ngIf functionCondition(stringCondition, numberCondition)">helloFunction</copy-me>' + '</div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(3); - expect(DOM.getText(fixture.debugElement.nativeElement)) - .toEqual('helloNumberhelloStringhelloFunction'); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(3); + expect(DOM.getText(fixture.debugElement.nativeElement)) + .toEqual('helloNumberhelloStringhelloFunction'); - fixture.debugElement.componentInstance.numberCondition = 0; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('helloString'); + fixture.debugElement.componentInstance.numberCondition = 0; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('helloString'); - fixture.debugElement.componentInstance.numberCondition = 1; - fixture.debugElement.componentInstance.stringCondition = 'bar'; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('helloNumber'); - async.done(); - }); + fixture.debugElement.componentInstance.numberCondition = 1; + fixture.debugElement.componentInstance.stringCondition = "bar"; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('helloNumber'); + async.done(); + }); })); @@ -140,38 +163,44 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello'); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello'); - fixture.debugElement.componentInstance.numberCondition = 2; - fixture.detectChanges(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(1); - expect(fixture.debugElement.nativeElement).toHaveText('hello'); + fixture.debugElement.componentInstance.numberCondition = 2; + fixture.detectChanges(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(1); + expect(fixture.debugElement.nativeElement).toHaveText('hello'); - async.done(); - }); + async.done(); + }); })); it('should not recreate the element if the condition goes from true to true (JS)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - fixture.detectChanges(); - DOM.addClass(DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'), 'foo'); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + fixture.detectChanges(); + DOM.addClass(DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'), + "foo"); - fixture.debugElement.componentInstance.numberCondition = 2; - fixture.detectChanges(); - expect(DOM.hasClass( - DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'), 'foo')) - .toBe(true); + fixture.debugElement.componentInstance.numberCondition = 2; + fixture.detectChanges(); + expect( + DOM.hasClass(DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'), + "foo")) + .toBe(true); - async.done(); - }); + async.done(); + }); })); } @@ -180,13 +209,15 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>'; - tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => { - expect(() => fixture.detectChanges()).toThrowError(); - expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) - .toEqual(0); - expect(fixture.debugElement.nativeElement).toHaveText(''); - async.done(); - }); + tcb.overrideTemplate(TestComponent, html) + .createAsync(TestComponent) + .then((fixture) => { + expect(() => fixture.detectChanges()).toThrowError(); + expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + .toEqual(0); + expect(fixture.debugElement.nativeElement).toHaveText(''); + async.done(); + }); })); } @@ -204,7 +235,7 @@ class TestComponent { this.booleanCondition = true; this.nestedBooleanCondition = true; this.numberCondition = 1; - this.stringCondition = 'foo'; - this.functionCondition = function(s, n) { return s == 'foo' && n == 1; }; + this.stringCondition = "foo"; + this.functionCondition = function(s, n) { return s == "foo" && n == 1; }; } } diff --git a/modules/angular2/test/common/directives/ng_plural_spec.ts b/modules/angular2/test/common/directives/ng_plural_spec.ts index 3dfa3961af..e89d085b35 100644 --- a/modules/angular2/test/common/directives/ng_plural_spec.ts +++ b/modules/angular2/test/common/directives/ng_plural_spec.ts @@ -1,4 +1,17 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEachProviders, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEachProviders, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {Component, Injectable, provide} from 'angular2/core'; import {NgPlural, NgPluralCase, NgLocalization} from 'angular2/common'; @@ -10,10 +23,10 @@ export function main() { it('should display the template according to the exact value', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div>' + - '<ul [ngPlural]="switchValue">' + - '<template ngPluralCase="=0"><li>you have no messages.</li></template>' + - '<template ngPluralCase="=1"><li>you have one message.</li></template>' + - '</ul></div>'; + '<ul [ngPlural]="switchValue">' + + '<template ngPluralCase="=0"><li>you have no messages.</li></template>' + + '<template ngPluralCase="=1"><li>you have one message.</li></template>' + + '</ul></div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) @@ -32,7 +45,8 @@ export function main() { it('should display the template according to the category', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var template = '<div>' + + var template = + '<div>' + '<ul [ngPlural]="switchValue">' + '<template ngPluralCase="few"><li>you have a few messages.</li></template>' + '<template ngPluralCase="many"><li>you have many messages.</li></template>' + @@ -55,7 +69,8 @@ export function main() { it('should default to other when no matches are found', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var template = '<div>' + + var template = + '<div>' + '<ul [ngPlural]="switchValue">' + '<template ngPluralCase="few"><li>you have a few messages.</li></template>' + '<template ngPluralCase="other"><li>default message.</li></template>' + @@ -74,7 +89,8 @@ export function main() { it('should prioritize value matches over category matches', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var template = '<div>' + + var template = + '<div>' + '<ul [ngPlural]="switchValue">' + '<template ngPluralCase="few"><li>you have a few messages.</li></template>' + '<template ngPluralCase="=2">you have two messages.</template>' + diff --git a/modules/angular2/test/common/directives/ng_style_spec.ts b/modules/angular2/test/common/directives/ng_style_spec.ts index f5c3c11aee..4b816b05fc 100644 --- a/modules/angular2/test/common/directives/ng_style_spec.ts +++ b/modules/angular2/test/common/directives/ng_style_spec.ts @@ -1,4 +1,18 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEach, beforeEachProviders, ddescribe, xdescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + beforeEachProviders, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {StringMapWrapper} from 'angular2/src/facade/collection'; diff --git a/modules/angular2/test/common/directives/ng_switch_spec.ts b/modules/angular2/test/common/directives/ng_switch_spec.ts index 9b89c2d32c..030c17ca70 100644 --- a/modules/angular2/test/common/directives/ng_switch_spec.ts +++ b/modules/angular2/test/common/directives/ng_switch_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {Component} from 'angular2/core'; @@ -10,10 +22,10 @@ export function main() { it('should switch amongst when values', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div>' + - '<ul [ngSwitch]="switchValue">' + - '<template ngSwitchWhen="a"><li>when a</li></template>' + - '<template ngSwitchWhen="b"><li>when b</li></template>' + - '</ul></div>'; + '<ul [ngSwitch]="switchValue">' + + '<template ngSwitchWhen="a"><li>when a</li></template>' + + '<template ngSwitchWhen="b"><li>when b</li></template>' + + '</ul></div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) @@ -36,10 +48,10 @@ export function main() { it('should switch amongst when values with fallback to default', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div>' + - '<ul [ngSwitch]="switchValue">' + - '<li template="ngSwitchWhen \'a\'">when a</li>' + - '<li template="ngSwitchDefault">when default</li>' + - '</ul></div>'; + '<ul [ngSwitch]="switchValue">' + + '<li template="ngSwitchWhen \'a\'">when a</li>' + + '<li template="ngSwitchDefault">when default</li>' + + '</ul></div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) @@ -62,14 +74,14 @@ export function main() { it('should support multiple whens with the same value', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div>' + - '<ul [ngSwitch]="switchValue">' + - '<template ngSwitchWhen="a"><li>when a1;</li></template>' + - '<template ngSwitchWhen="b"><li>when b1;</li></template>' + - '<template ngSwitchWhen="a"><li>when a2;</li></template>' + - '<template ngSwitchWhen="b"><li>when b2;</li></template>' + - '<template ngSwitchDefault><li>when default1;</li></template>' + - '<template ngSwitchDefault><li>when default2;</li></template>' + - '</ul></div>'; + '<ul [ngSwitch]="switchValue">' + + '<template ngSwitchWhen="a"><li>when a1;</li></template>' + + '<template ngSwitchWhen="b"><li>when b1;</li></template>' + + '<template ngSwitchWhen="a"><li>when a2;</li></template>' + + '<template ngSwitchWhen="b"><li>when b2;</li></template>' + + '<template ngSwitchDefault><li>when default1;</li></template>' + + '<template ngSwitchDefault><li>when default2;</li></template>' + + '</ul></div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) @@ -95,11 +107,11 @@ export function main() { it('should switch amongst when values', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div>' + - '<ul [ngSwitch]="switchValue">' + - '<template [ngSwitchWhen]="when1"><li>when 1;</li></template>' + - '<template [ngSwitchWhen]="when2"><li>when 2;</li></template>' + - '<template ngSwitchDefault><li>when default;</li></template>' + - '</ul></div>'; + '<ul [ngSwitch]="switchValue">' + + '<template [ngSwitchWhen]="when1"><li>when 1;</li></template>' + + '<template [ngSwitchWhen]="when2"><li>when 2;</li></template>' + + '<template ngSwitchDefault><li>when default;</li></template>' + + '</ul></div>'; tcb.overrideTemplate(TestComponent, template) .createAsync(TestComponent) diff --git a/modules/angular2/test/common/directives/non_bindable_spec.ts b/modules/angular2/test/common/directives/non_bindable_spec.ts index 82d2143f4e..74926f2f2b 100644 --- a/modules/angular2/test/common/directives/non_bindable_spec.ts +++ b/modules/angular2/test/common/directives/non_bindable_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {Component, Directive} from 'angular2/core'; import {ElementRef} from 'angular2/src/core/linker/element_ref'; diff --git a/modules/angular2/test/common/forms/directives_spec.ts b/modules/angular2/test/common/forms/directives_spec.ts index b084aae01d..40e3ae3587 100644 --- a/modules/angular2/test/common/forms/directives_spec.ts +++ b/modules/angular2/test/common/forms/directives_spec.ts @@ -1,10 +1,41 @@ -import {ddescribe, describe, fakeAsync, flushMicrotasks, it, iit, xit, expect, beforeEach, afterEach, el, AsyncTestCompleter, inject, tick} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + fakeAsync, + flushMicrotasks, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + el, + AsyncTestCompleter, + inject, + tick +} from 'angular2/testing_internal'; import {SpyNgControl, SpyValueAccessor} from '../spies'; import {QueryList} from 'angular2/core'; -import {ControlGroup, Control, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from 'angular2/common'; +import { + ControlGroup, + Control, + NgControlName, + NgControlGroup, + NgFormModel, + ControlValueAccessor, + Validators, + NgForm, + NgModel, + NgFormControl, + NgControl, + DefaultValueAccessor, + CheckboxControlValueAccessor, + SelectControlValueAccessor, + Validator +} from 'angular2/common'; import {selectValueAccessor, composeValidators} from 'angular2/src/common/forms/directives/shared'; @@ -22,13 +53,13 @@ class DummyControlValueAccessor implements ControlValueAccessor { } class CustomValidatorDirective implements Validator { - validate(c: Control): {[key: string]: any} { return {'custom': true}; } + validate(c: Control): {[key: string]: any} { return {"custom": true}; } } function asyncValidator(expected, timeout = 0) { return (c) => { var completer = PromiseWrapper.completer(); - var res = c.value != expected ? {'async': true} : null; + var res = c.value != expected ? {"async": true} : null; if (timeout == 0) { completer.resolve(res); } else { @@ -39,74 +70,71 @@ function asyncValidator(expected, timeout = 0) { } export function main() { - describe('Form Directives', () => { + describe("Form Directives", () => { var defaultAccessor; beforeEach(() => { defaultAccessor = new DefaultValueAccessor(null, null); }); - describe('shared', () => { - describe('selectValueAccessor', () => { + describe("shared", () => { + describe("selectValueAccessor", () => { var dir: NgControl; beforeEach(() => { dir = <any>new SpyNgControl(); }); - it('should throw when given an empty array', + it("should throw when given an empty array", () => { expect(() => selectValueAccessor(dir, [])).toThrowError(); }); - it('should return the default value accessor when no other provided', + it("should return the default value accessor when no other provided", () => { expect(selectValueAccessor(dir, [defaultAccessor])).toEqual(defaultAccessor); }); - it('should return checkbox accessor when provided', () => { + it("should return checkbox accessor when provided", () => { var checkboxAccessor = new CheckboxControlValueAccessor(null, null); - expect(selectValueAccessor(dir, [ - defaultAccessor, checkboxAccessor - ])).toEqual(checkboxAccessor); + expect(selectValueAccessor(dir, [defaultAccessor, checkboxAccessor])) + .toEqual(checkboxAccessor); }); - it('should return select accessor when provided', () => { + it("should return select accessor when provided", () => { var selectAccessor = new SelectControlValueAccessor(null, null); - expect(selectValueAccessor(dir, [ - defaultAccessor, selectAccessor - ])).toEqual(selectAccessor); + expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor])) + .toEqual(selectAccessor); }); - it('should throw when more than one build-in accessor is provided', () => { + it("should throw when more than one build-in accessor is provided", () => { var checkboxAccessor = new CheckboxControlValueAccessor(null, null); var selectAccessor = new SelectControlValueAccessor(null, null); expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError(); }); - it('should return custom accessor when provided', () => { + it("should return custom accessor when provided", () => { var customAccessor = new SpyValueAccessor(); var checkboxAccessor = new CheckboxControlValueAccessor(null, null); - expect(selectValueAccessor(dir, [ - defaultAccessor, customAccessor, checkboxAccessor - ])).toEqual(customAccessor); + expect(selectValueAccessor(dir, [defaultAccessor, customAccessor, checkboxAccessor])) + .toEqual(customAccessor); }); - it('should throw when more than one custom accessor is provided', () => { + it("should throw when more than one custom accessor is provided", () => { var customAccessor: ControlValueAccessor = <any>new SpyValueAccessor(); expect(() => selectValueAccessor(dir, [customAccessor, customAccessor])).toThrowError(); }); }); - describe('composeValidators', () => { - it('should compose functions', () => { - var dummy1 = (_) => ({'dummy1': true}); - var dummy2 = (_) => ({'dummy2': true}); + describe("composeValidators", () => { + it("should compose functions", () => { + var dummy1 = (_) => ({"dummy1": true}); + var dummy2 = (_) => ({"dummy2": true}); var v = composeValidators([dummy1, dummy2]); - expect(v(new Control(''))).toEqual({'dummy1': true, 'dummy2': true}); + expect(v(new Control(""))).toEqual({"dummy1": true, "dummy2": true}); }); - it('should compose validator directives', () => { - var dummy1 = (_) => ({'dummy1': true}); + it("should compose validator directives", () => { + var dummy1 = (_) => ({"dummy1": true}); var v = composeValidators([dummy1, new CustomValidatorDirective()]); - expect(v(new Control(''))).toEqual({'dummy1': true, 'custom': true}); + expect(v(new Control(""))).toEqual({"dummy1": true, "custom": true}); }); }); }); - describe('NgFormModel', () => { + describe("NgFormModel", () => { var form; var formModel: ControlGroup; var loginControlDir; @@ -114,19 +142,19 @@ export function main() { beforeEach(() => { form = new NgFormModel([], []); formModel = new ControlGroup({ - 'login': new Control(), - 'passwords': - new ControlGroup({'password': new Control(), 'passwordConfirm': new Control()}) + "login": new Control(), + "passwords": + new ControlGroup({"password": new Control(), "passwordConfirm": new Control()}) }); form.form = formModel; - loginControlDir = new NgControlName( - form, [Validators.required], [asyncValidator('expected')], [defaultAccessor]); - loginControlDir.name = 'login'; + loginControlDir = new NgControlName(form, [Validators.required], + [asyncValidator("expected")], [defaultAccessor]); + loginControlDir.name = "login"; loginControlDir.valueAccessor = new DummyControlValueAccessor(); }); - it('should reexport control properties', () => { + it("should reexport control properties", () => { expect(form.control).toBe(formModel); expect(form.value).toBe(formModel.value); expect(form.valid).toBe(formModel.valid); @@ -137,132 +165,130 @@ export function main() { expect(form.untouched).toBe(formModel.untouched); }); - describe('addControl', () => { - it('should throw when no control found', () => { + describe("addControl", () => { + it("should throw when no control found", () => { var dir = new NgControlName(form, null, null, [defaultAccessor]); - dir.name = 'invalidName'; + dir.name = "invalidName"; expect(() => form.addControl(dir)) - .toThrowError(new RegExp('Cannot find control \'invalidName\'')); + .toThrowError(new RegExp("Cannot find control 'invalidName'")); }); - it('should throw when no value accessor', () => { + it("should throw when no value accessor", () => { var dir = new NgControlName(form, null, null, null); - dir.name = 'login'; + dir.name = "login"; expect(() => form.addControl(dir)) - .toThrowError(new RegExp('No value accessor for \'login\'')); + .toThrowError(new RegExp("No value accessor for 'login'")); }); - it('should set up validators', fakeAsync(() => { + it("should set up validators", fakeAsync(() => { form.addControl(loginControlDir); // sync validators are set - expect(formModel.hasError('required', ['login'])).toBe(true); - expect(formModel.hasError('async', ['login'])).toBe(false); + expect(formModel.hasError("required", ["login"])).toBe(true); + expect(formModel.hasError("async", ["login"])).toBe(false); - (<Control>formModel.find(['login'])).updateValue('invalid value'); + (<Control>formModel.find(["login"])).updateValue("invalid value"); // sync validator passes, running async validators expect(formModel.pending).toBe(true); tick(); - expect(formModel.hasError('required', ['login'])).toBe(false); - expect(formModel.hasError('async', ['login'])).toBe(true); + expect(formModel.hasError("required", ["login"])).toBe(false); + expect(formModel.hasError("async", ["login"])).toBe(true); })); - it('should write value to the DOM', () => { - (<Control>formModel.find(['login'])).updateValue('initValue'); + it("should write value to the DOM", () => { + (<Control>formModel.find(["login"])).updateValue("initValue"); form.addControl(loginControlDir); - expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('initValue'); + expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("initValue"); }); - it('should add the directive to the list of directives included in the form', () => { + it("should add the directive to the list of directives included in the form", () => { form.addControl(loginControlDir); expect(form.directives).toEqual([loginControlDir]); }); }); - describe('addControlGroup', () => { + describe("addControlGroup", () => { var matchingPasswordsValidator = (g) => { - if (g.controls['password'].value != g.controls['passwordConfirm'].value) { - return {'differentPasswords': true}; + if (g.controls["password"].value != g.controls["passwordConfirm"].value) { + return {"differentPasswords": true}; } else { return null; } }; - it('should set up validator', fakeAsync(() => { - var group = new NgControlGroup( - form, [matchingPasswordsValidator], [asyncValidator('expected')]); - group.name = 'passwords'; + it("should set up validator", fakeAsync(() => { + var group = new NgControlGroup(form, [matchingPasswordsValidator], + [asyncValidator('expected')]); + group.name = "passwords"; form.addControlGroup(group); - (<Control>formModel.find(['passwords', 'password'])).updateValue('somePassword'); - (<Control>formModel.find([ - 'passwords', 'passwordConfirm' - ])).updateValue('someOtherPassword'); + (<Control>formModel.find(["passwords", "password"])).updateValue("somePassword"); + (<Control>formModel.find(["passwords", "passwordConfirm"])) + .updateValue("someOtherPassword"); // sync validators are set - expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true); + expect(formModel.hasError("differentPasswords", ["passwords"])).toEqual(true); - (<Control>formModel.find([ - 'passwords', 'passwordConfirm' - ])).updateValue('somePassword'); + (<Control>formModel.find(["passwords", "passwordConfirm"])) + .updateValue("somePassword"); // sync validators pass, running async validators expect(formModel.pending).toBe(true); tick(); - expect(formModel.hasError('async', ['passwords'])).toBe(true); + expect(formModel.hasError("async", ["passwords"])).toBe(true); })); }); - describe('removeControl', () => { - it('should remove the directive to the list of directives included in the form', () => { + describe("removeControl", () => { + it("should remove the directive to the list of directives included in the form", () => { form.addControl(loginControlDir); form.removeControl(loginControlDir); expect(form.directives).toEqual([]); }); }); - describe('ngOnChanges', () => { - it('should update dom values of all the directives', () => { + describe("ngOnChanges", () => { + it("should update dom values of all the directives", () => { form.addControl(loginControlDir); - (<Control>formModel.find(['login'])).updateValue('new value'); + (<Control>formModel.find(["login"])).updateValue("new value"); form.ngOnChanges({}); - expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('new value'); + expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("new value"); }); - it('should set up a sync validator', () => { - var formValidator = (c) => ({'custom': true}); + it("should set up a sync validator", () => { + var formValidator = (c) => ({"custom": true}); var f = new NgFormModel([formValidator], []); f.form = formModel; - f.ngOnChanges({'form': new SimpleChange(null, null)}); + f.ngOnChanges({"form": new SimpleChange(null, null)}); - expect(formModel.errors).toEqual({'custom': true}); + expect(formModel.errors).toEqual({"custom": true}); }); - it('should set up an async validator', fakeAsync(() => { - var f = new NgFormModel([], [asyncValidator('expected')]); + it("should set up an async validator", fakeAsync(() => { + var f = new NgFormModel([], [asyncValidator("expected")]); f.form = formModel; - f.ngOnChanges({'form': new SimpleChange(null, null)}); + f.ngOnChanges({"form": new SimpleChange(null, null)}); tick(); - expect(formModel.errors).toEqual({'async': true}); + expect(formModel.errors).toEqual({"async": true}); })); }); }); - describe('NgForm', () => { + describe("NgForm", () => { var form; var formModel: ControlGroup; var loginControlDir; @@ -273,14 +299,14 @@ export function main() { formModel = form.form; personControlGroupDir = new NgControlGroup(form, [], []); - personControlGroupDir.name = 'person'; + personControlGroupDir.name = "person"; loginControlDir = new NgControlName(personControlGroupDir, null, null, [defaultAccessor]); - loginControlDir.name = 'login'; + loginControlDir.name = "login"; loginControlDir.valueAccessor = new DummyControlValueAccessor(); }); - it('should reexport control properties', () => { + it("should reexport control properties", () => { expect(form.control).toBe(formModel); expect(form.value).toBe(formModel.value); expect(form.valid).toBe(formModel.valid); @@ -291,21 +317,21 @@ export function main() { expect(form.untouched).toBe(formModel.untouched); }); - describe('addControl & addControlGroup', () => { - it('should create a control with the given name', fakeAsync(() => { + describe("addControl & addControlGroup", () => { + it("should create a control with the given name", fakeAsync(() => { form.addControlGroup(personControlGroupDir); form.addControl(loginControlDir); flushMicrotasks(); - expect(formModel.find(['person', 'login'])).not.toBeNull; + expect(formModel.find(["person", "login"])).not.toBeNull; })); // should update the form's value and validity }); - describe('removeControl & removeControlGroup', () => { - it('should remove control', fakeAsync(() => { + describe("removeControl & removeControlGroup", () => { + it("should remove control", fakeAsync(() => { form.addControlGroup(personControlGroupDir); form.addControl(loginControlDir); @@ -314,45 +340,45 @@ export function main() { flushMicrotasks(); - expect(formModel.find(['person'])).toBeNull(); - expect(formModel.find(['person', 'login'])).toBeNull(); + expect(formModel.find(["person"])).toBeNull(); + expect(formModel.find(["person", "login"])).toBeNull(); })); // should update the form's value and validity }); - it('should set up sync validator', fakeAsync(() => { - var formValidator = (c) => ({'custom': true}); + it("should set up sync validator", fakeAsync(() => { + var formValidator = (c) => ({"custom": true}); var f = new NgForm([formValidator], []); tick(); - expect(f.form.errors).toEqual({'custom': true}); + expect(f.form.errors).toEqual({"custom": true}); })); - it('should set up async validator', fakeAsync(() => { - var f = new NgForm([], [asyncValidator('expected')]); + it("should set up async validator", fakeAsync(() => { + var f = new NgForm([], [asyncValidator("expected")]); tick(); - expect(f.form.errors).toEqual({'async': true}); + expect(f.form.errors).toEqual({"async": true}); })); }); - describe('NgControlGroup', () => { + describe("NgControlGroup", () => { var formModel; var controlGroupDir; beforeEach(() => { - formModel = new ControlGroup({'login': new Control(null)}); + formModel = new ControlGroup({"login": new Control(null)}); var parent = new NgFormModel([], []); - parent.form = new ControlGroup({'group': formModel}); + parent.form = new ControlGroup({"group": formModel}); controlGroupDir = new NgControlGroup(parent, [], []); - controlGroupDir.name = 'group'; + controlGroupDir.name = "group"; }); - it('should reexport control properties', () => { + it("should reexport control properties", () => { expect(controlGroupDir.control).toBe(formModel); expect(controlGroupDir.value).toBe(formModel.value); expect(controlGroupDir.valid).toBe(formModel.valid); @@ -364,7 +390,7 @@ export function main() { }); }); - describe('NgFormControl', () => { + describe("NgFormControl", () => { var controlDir; var control; var checkProperties = function(control) { @@ -386,36 +412,36 @@ export function main() { controlDir.form = control; }); - it('should reexport control properties', () => { checkProperties(control); }); + it("should reexport control properties", () => { checkProperties(control); }); - it('should reexport new control properties', () => { + it("should reexport new control properties", () => { var newControl = new Control(null); controlDir.form = newControl; - controlDir.ngOnChanges({'form': new SimpleChange(control, newControl)}); + controlDir.ngOnChanges({"form": new SimpleChange(control, newControl)}); checkProperties(newControl); }); - it('should set up validator', () => { + it("should set up validator", () => { expect(control.valid).toBe(true); // this will add the required validator and recalculate the validity - controlDir.ngOnChanges({'form': new SimpleChange(null, control)}); + controlDir.ngOnChanges({"form": new SimpleChange(null, control)}); expect(control.valid).toBe(false); }); }); - describe('NgModel', () => { + describe("NgModel", () => { var ngModel; beforeEach(() => { ngModel = - new NgModel([Validators.required], [asyncValidator('expected')], [defaultAccessor]); + new NgModel([Validators.required], [asyncValidator("expected")], [defaultAccessor]); ngModel.valueAccessor = new DummyControlValueAccessor(); }); - it('should reexport control properties', () => { + it("should reexport control properties", () => { var control = ngModel.control; expect(ngModel.control).toBe(control); expect(ngModel.value).toBe(control.value); @@ -427,34 +453,34 @@ export function main() { expect(ngModel.untouched).toBe(control.untouched); }); - it('should set up validator', fakeAsync(() => { + it("should set up validator", fakeAsync(() => { // this will add the required validator and recalculate the validity ngModel.ngOnChanges({}); tick(); - expect(ngModel.control.errors).toEqual({'required': true}); + expect(ngModel.control.errors).toEqual({"required": true}); - ngModel.control.updateValue('someValue'); + ngModel.control.updateValue("someValue"); tick(); - expect(ngModel.control.errors).toEqual({'async': true}); + expect(ngModel.control.errors).toEqual({"async": true}); })); }); - describe('NgControlName', () => { + describe("NgControlName", () => { var formModel; var controlNameDir; beforeEach(() => { - formModel = new Control('name'); + formModel = new Control("name"); var parent = new NgFormModel([], []); - parent.form = new ControlGroup({'name': formModel}); + parent.form = new ControlGroup({"name": formModel}); controlNameDir = new NgControlName(parent, [], [], [defaultAccessor]); - controlNameDir.name = 'name'; + controlNameDir.name = "name"; }); - it('should reexport control properties', () => { + it("should reexport control properties", () => { expect(controlNameDir.control).toBe(formModel); expect(controlNameDir.value).toBe(formModel.value); expect(controlNameDir.valid).toBe(formModel.valid); diff --git a/modules/angular2/test/common/forms/form_builder_spec.ts b/modules/angular2/test/common/forms/form_builder_spec.ts index d683a9934c..7a863b83b8 100644 --- a/modules/angular2/test/common/forms/form_builder_spec.ts +++ b/modules/angular2/test/common/forms/form_builder_spec.ts @@ -1,4 +1,14 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, el} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + el +} from 'angular2/testing_internal'; import {Control, FormBuilder} from 'angular2/common'; import {PromiseWrapper} from 'angular2/src/facade/promise'; @@ -6,53 +16,53 @@ export function main() { function syncValidator(_) { return null; } function asyncValidator(_) { return PromiseWrapper.resolve(null); } - describe('Form Builder', () => { + describe("Form Builder", () => { var b; beforeEach(() => { b = new FormBuilder(); }); - it('should create controls from a value', () => { - var g = b.group({'login': 'some value'}); + it("should create controls from a value", () => { + var g = b.group({"login": "some value"}); - expect(g.controls['login'].value).toEqual('some value'); + expect(g.controls["login"].value).toEqual("some value"); }); - it('should create controls from an array', () => { + it("should create controls from an array", () => { var g = b.group( - {'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]}); + {"login": ["some value"], "password": ["some value", syncValidator, asyncValidator]}); - expect(g.controls['login'].value).toEqual('some value'); - expect(g.controls['password'].value).toEqual('some value'); - expect(g.controls['password'].validator).toEqual(syncValidator); - expect(g.controls['password'].asyncValidator).toEqual(asyncValidator); + expect(g.controls["login"].value).toEqual("some value"); + expect(g.controls["password"].value).toEqual("some value"); + expect(g.controls["password"].validator).toEqual(syncValidator); + expect(g.controls["password"].asyncValidator).toEqual(asyncValidator); }); - it('should use controls', () => { - var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)}); + it("should use controls", () => { + var g = b.group({"login": b.control("some value", syncValidator, asyncValidator)}); - expect(g.controls['login'].value).toEqual('some value'); - expect(g.controls['login'].validator).toBe(syncValidator); - expect(g.controls['login'].asyncValidator).toBe(asyncValidator); + expect(g.controls["login"].value).toEqual("some value"); + expect(g.controls["login"].validator).toBe(syncValidator); + expect(g.controls["login"].asyncValidator).toBe(asyncValidator); }); - it('should create groups with optional controls', () => { - var g = b.group({'login': 'some value'}, {'optionals': {'login': false}}); + it("should create groups with optional controls", () => { + var g = b.group({"login": "some value"}, {"optionals": {"login": false}}); - expect(g.contains('login')).toEqual(false); + expect(g.contains("login")).toEqual(false); }); - it('should create groups with a custom validator', () => { - var g = b.group( - {'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator}); + it("should create groups with a custom validator", () => { + var g = b.group({"login": "some value"}, + {"validator": syncValidator, "asyncValidator": asyncValidator}); expect(g.validator).toBe(syncValidator); expect(g.asyncValidator).toBe(asyncValidator); }); - it('should create control arrays', () => { - var c = b.control('three'); - var a = b.array( - ['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator); + it("should create control arrays", () => { + var c = b.control("three"); + var a = b.array(["one", ["two", syncValidator], c, b.array(['four'])], syncValidator, + asyncValidator); expect(a.value).toEqual(['one', 'two', 'three', ['four']]); expect(a.validator).toBe(syncValidator); diff --git a/modules/angular2/test/common/forms/integration_spec.ts b/modules/angular2/test/common/forms/integration_spec.ts index 0d6b1e070d..951a32f6d9 100644 --- a/modules/angular2/test/common/forms/integration_spec.ts +++ b/modules/angular2/test/common/forms/integration_spec.ts @@ -1,19 +1,51 @@ import {Component, Directive, Output, EventEmitter} from 'angular2/core'; -import {ComponentFixture, afterEach, AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, dispatchEvent, fakeAsync, tick, flushMicrotasks, expect, it, inject, iit, xit, browserDetection} from 'angular2/testing_internal'; +import { + ComponentFixture, + afterEach, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + describe, + dispatchEvent, + fakeAsync, + tick, + flushMicrotasks, + expect, + it, + inject, + iit, + xit, + browserDetection +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {Control, ControlGroup, ControlValueAccessor, FORM_DIRECTIVES, NG_VALIDATORS, NG_ASYNC_VALIDATORS, NgControl, NgIf, NgFor, NgForm, Validators, Validator, RadioButtonState} from 'angular2/common'; +import { + Control, + ControlGroup, + ControlValueAccessor, + FORM_DIRECTIVES, + NG_VALIDATORS, + NG_ASYNC_VALIDATORS, + NgControl, + NgIf, + NgFor, + NgForm, + Validators, + Validator, + RadioButtonState +} from 'angular2/common'; import {Provider, forwardRef, Input} from 'angular2/core'; import {By} from 'angular2/platform/browser'; import {ListWrapper} from 'angular2/src/facade/collection'; import {ObservableWrapper, TimerWrapper} from 'angular2/src/facade/async'; import {CONST_EXPR} from 'angular2/src/facade/lang'; -import {PromiseWrapper} from 'angular2/src/facade/promise'; +import {PromiseWrapper} from "angular2/src/facade/promise"; export function main() { - describe('integration tests', () => { + describe("integration tests", () => { - it('should initialize DOM elements with the given form object', + it("should initialize DOM elements with the given form object", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -21,18 +53,18 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'login': new Control('loginValue')}); + new ControlGroup({"login": new Control("loginValue")}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('loginValue'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("loginValue"); async.done(); }); })); - it('should update the control group values on DOM change', + it("should update the control group values on DOM change", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var form = new ControlGroup({'login': new Control('oldValue')}); + var form = new ControlGroup({"login": new Control("oldValue")}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -41,19 +73,19 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); - input.nativeElement.value = 'updatedValue'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "updatedValue"; + dispatchEvent(input.nativeElement, "input"); - expect(form.value).toEqual({'login': 'updatedValue'}); + expect(form.value).toEqual({"login": "updatedValue"}); async.done(); }); })); - it('should ignore the change event for <input type=text>', + it("should ignore the change event for <input type=text>", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var form = new ControlGroup({'login': new Control('oldValue')}); + var form = new ControlGroup({"login": new Control("oldValue")}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -62,19 +94,19 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); - input.nativeElement.value = 'updatedValue'; + input.nativeElement.value = "updatedValue"; - ObservableWrapper.subscribe( - form.valueChanges, (value) => { throw 'Should not happen'; }); - dispatchEvent(input.nativeElement, 'change'); + ObservableWrapper.subscribe(form.valueChanges, + (value) => { throw 'Should not happen'; }); + dispatchEvent(input.nativeElement, "change"); async.done(); }); })); - it('should emit ngSubmit event on submit', + it("should emit ngSubmit event on submit", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<div> <form [ngFormModel]="form" (ngSubmit)="name='updated'"></form> @@ -92,16 +124,16 @@ export function main() { tick(); - var form = fixture.debugElement.query(By.css('form')); - dispatchEvent(form.nativeElement, 'submit'); + var form = fixture.debugElement.query(By.css("form")); + dispatchEvent(form.nativeElement, "submit"); tick(); expect(fixture.debugElement.componentInstance.name).toEqual('updated'); }))); - it('should work with single controls', + it("should work with single controls", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var control = new Control('loginValue'); + var control = new Control("loginValue"); var t = `<div><input type="text" [ngFormControl]="form"></div>`; @@ -109,18 +141,18 @@ export function main() { fixture.debugElement.componentInstance.form = control; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('loginValue'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("loginValue"); - input.nativeElement.value = 'updatedValue'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "updatedValue"; + dispatchEvent(input.nativeElement, "input"); - expect(control.value).toEqual('updatedValue'); + expect(control.value).toEqual("updatedValue"); async.done(); }); })); - it('should update DOM elements when rebinding the control group', + it("should update DOM elements when rebinding the control group", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -128,23 +160,23 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'login': new Control('oldValue')}); + new ControlGroup({"login": new Control("oldValue")}); fixture.detectChanges(); fixture.debugElement.componentInstance.form = - new ControlGroup({'login': new Control('newValue')}); + new ControlGroup({"login": new Control("newValue")}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('newValue'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("newValue"); async.done(); }); })); - it('should update DOM elements when updating the value of a control', + it("should update DOM elements when updating the value of a control", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var login = new Control('oldValue'); - var form = new ControlGroup({'login': login}); + var login = new Control("oldValue"); + var form = new ControlGroup({"login": login}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -154,20 +186,20 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - login.updateValue('newValue'); + login.updateValue("newValue"); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('newValue'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("newValue"); async.done(); }); })); - it('should mark controls as touched after interacting with the DOM control', + it("should mark controls as touched after interacting with the DOM control", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var login = new Control('oldValue'); - var form = new ControlGroup({'login': login}); + var login = new Control("oldValue"); + var form = new ControlGroup({"login": login}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -177,10 +209,10 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var loginEl = fixture.debugElement.query(By.css('input')); + var loginEl = fixture.debugElement.query(By.css("input")); expect(login.touched).toBe(false); - dispatchEvent(loginEl.nativeElement, 'blur'); + dispatchEvent(loginEl.nativeElement, "blur"); expect(login.touched).toBe(true); @@ -188,8 +220,8 @@ export function main() { }); })); - describe('different control types', () => { - it('should support <input type=text>', + describe("different control types", () => { + it("should support <input type=text>", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input type="text" ngControl="text"> @@ -197,21 +229,21 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'text': new Control('old')}); + new ControlGroup({"text": new Control("old")}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('old'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("old"); - input.nativeElement.value = 'new'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "new"; + dispatchEvent(input.nativeElement, "input"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({'text': 'new'}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"text": "new"}); async.done(); }); })); - it('should support <input> without type', + it("should support <input> without type", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input ngControl="text"> @@ -219,20 +251,20 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'text': new Control('old')}); + new ControlGroup({"text": new Control("old")}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('old'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("old"); - input.nativeElement.value = 'new'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "new"; + dispatchEvent(input.nativeElement, "input"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({'text': 'new'}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"text": "new"}); async.done(); }); })); - it('should support <textarea>', + it("should support <textarea>", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <textarea ngControl="text"></textarea> @@ -240,21 +272,21 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'text': new Control('old')}); + new ControlGroup({"text": new Control('old')}); fixture.detectChanges(); - var textarea = fixture.debugElement.query(By.css('textarea')); - expect(textarea.nativeElement.value).toEqual('old'); + var textarea = fixture.debugElement.query(By.css("textarea")); + expect(textarea.nativeElement.value).toEqual("old"); - textarea.nativeElement.value = 'new'; - dispatchEvent(textarea.nativeElement, 'input'); + textarea.nativeElement.value = "new"; + dispatchEvent(textarea.nativeElement, "input"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({'text': 'new'}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"text": 'new'}); async.done(); }); })); - it('should support <type=checkbox>', + it("should support <type=checkbox>", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input type="checkbox" ngControl="checkbox"> @@ -262,21 +294,21 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'checkbox': new Control(true)}); + new ControlGroup({"checkbox": new Control(true)}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); expect(input.nativeElement.checked).toBe(true); input.nativeElement.checked = false; - dispatchEvent(input.nativeElement, 'change'); + dispatchEvent(input.nativeElement, "change"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({'checkbox': false}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"checkbox": false}); async.done(); }); })); - it('should support <type=number>', + it("should support <type=number>", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input type="number" ngControl="num"> @@ -284,21 +316,21 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'num': new Control(10)}); + new ControlGroup({"num": new Control(10)}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('10'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("10"); - input.nativeElement.value = '20'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "20"; + dispatchEvent(input.nativeElement, "input"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({'num': 20}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"num": 20}); async.done(); }); })); - it('should support <type=radio>', + it("should support <type=radio>", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<form [ngFormModel]="form"> <input type="radio" ngControl="foodChicken" name="food"> @@ -307,15 +339,15 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = new ControlGroup({ - 'foodChicken': new Control(new RadioButtonState(false, 'chicken')), - 'foodFish': new Control(new RadioButtonState(true, 'fish')) + "foodChicken": new Control(new RadioButtonState(false, 'chicken')), + "foodFish": new Control(new RadioButtonState(true, 'fish')) }); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); expect(input.nativeElement.checked).toEqual(false); - dispatchEvent(input.nativeElement, 'change'); + dispatchEvent(input.nativeElement, "change"); fixture.detectChanges(); let value = fixture.debugElement.componentInstance.form.value; @@ -325,85 +357,83 @@ export function main() { }); })); - describe('should support <select>', () => { - it('with basic selection', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<select> + describe("should support <select>", () => { + it("with basic selection", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<select> <option value="SF"></option> <option value="NYC"></option> </select>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - fixture.detectChanges(); + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var sfOption = fixture.debugElement.query(By.css('option')); + var select = fixture.debugElement.query(By.css("select")); + var sfOption = fixture.debugElement.query(By.css("option")); - expect(select.nativeElement.value).toEqual('SF'); - expect(sfOption.nativeElement.selected).toBe(true); - async.done(); - }); - })); + expect(select.nativeElement.value).toEqual("SF"); + expect(sfOption.nativeElement.selected).toBe(true); + async.done(); + }); + })); - it('with basic selection and value bindings', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<select> + it("with basic selection and value bindings", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<select> <option *ngFor="#city of list" [value]="city['id']"> {{ city['name'] }} </option> </select>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp = fixture.debugElement.componentInstance; - testComp.list = [{'id': '0', 'name': 'SF'}, {'id': '1', 'name': 'NYC'}]; - fixture.detectChanges(); + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + var testComp = fixture.debugElement.componentInstance; + testComp.list = [{"id": "0", "name": "SF"}, {"id": "1", "name": "NYC"}]; + fixture.detectChanges(); - var sfOption = fixture.debugElement.query(By.css('option')); - expect(sfOption.nativeElement.value).toEqual('0'); + var sfOption = fixture.debugElement.query(By.css("option")); + expect(sfOption.nativeElement.value).toEqual('0'); - testComp.list[0]['id'] = '2'; - fixture.detectChanges(); - expect(sfOption.nativeElement.value).toEqual('2'); - async.done(); - }); - })); + testComp.list[0]['id'] = '2'; + fixture.detectChanges(); + expect(sfOption.nativeElement.value).toEqual('2'); + async.done(); + }); + })); - it('with ngControl', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div [ngFormModel]="form"> + it("with ngControl", + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + var t = `<div [ngFormModel]="form"> <select ngControl="city"> <option value="SF"></option> <option value="NYC"></option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - fixture.debugElement.componentInstance.form = - new ControlGroup({'city': new Control('SF')}); - fixture.detectChanges(); + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + fixture.debugElement.componentInstance.form = + new ControlGroup({"city": new Control("SF")}); + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var sfOption = fixture.debugElement.query(By.css('option')); + var select = fixture.debugElement.query(By.css("select")); + var sfOption = fixture.debugElement.query(By.css("option")); - expect(select.nativeElement.value).toEqual('SF'); - expect(sfOption.nativeElement.selected).toBe(true); + expect(select.nativeElement.value).toEqual("SF"); + expect(sfOption.nativeElement.selected).toBe(true); - select.nativeElement.value = 'NYC'; - dispatchEvent(select.nativeElement, 'input'); + select.nativeElement.value = "NYC"; + dispatchEvent(select.nativeElement, "input"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({ - 'city': 'NYC' - }); - expect(sfOption.nativeElement.selected).toBe(false); - async.done(); - }); - })); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"city": 'NYC'}); + expect(sfOption.nativeElement.selected).toBe(false); + async.done(); + }); + })); - it('with a dynamic list of options', + it("with a dynamic list of options", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<div [ngFormModel]="form"> <select ngControl="city"> @@ -417,191 +447,191 @@ export function main() { tick(); fixture.debugElement.componentInstance.form = - new ControlGroup({'city': new Control('NYC')}); + new ControlGroup({"city": new Control("NYC")}); fixture.debugElement.componentInstance.data = ['SF', 'NYC']; fixture.detectChanges(); tick(); - var select = fixture.debugElement.query(By.css('select')); - expect(select.nativeElement.value).toEqual('NYC'); + var select = fixture.debugElement.query(By.css("select")); + expect(select.nativeElement.value).toEqual("NYC"); }))); - it('with option values that are objects', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div> + it("with option values that are objects", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<div> <select [(ngModel)]="selectedCity"> <option *ngFor="#c of list" [ngValue]="c">{{c['name']}}</option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp = fixture.debugElement.componentInstance; - testComp.list = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}]; - testComp.selectedCity = testComp.list[1]; - fixture.detectChanges(); + var testComp = fixture.debugElement.componentInstance; + testComp.list = [{"name": "SF"}, {"name": "NYC"}, {"name": "Buffalo"}]; + testComp.selectedCity = testComp.list[1]; + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var nycOption = fixture.debugElement.queryAll(By.css('option'))[1]; + var select = fixture.debugElement.query(By.css("select")); + var nycOption = fixture.debugElement.queryAll(By.css("option"))[1]; - expect(select.nativeElement.value).toEqual('1: Object'); - expect(nycOption.nativeElement.selected).toBe(true); + expect(select.nativeElement.value).toEqual("1: Object"); + expect(nycOption.nativeElement.selected).toBe(true); - select.nativeElement.value = '2: Object'; - dispatchEvent(select.nativeElement, 'input'); - fixture.detectChanges(); - TimerWrapper.setTimeout(() => { - expect(testComp.selectedCity['name']).toEqual('Buffalo'); - async.done(); - }, 0); - }); - })); + select.nativeElement.value = "2: Object"; + dispatchEvent(select.nativeElement, "input"); + fixture.detectChanges(); + TimerWrapper.setTimeout(() => { + expect(testComp.selectedCity['name']).toEqual("Buffalo"); + async.done(); + }, 0); + }); + })); - it('when new options are added', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div> + it("when new options are added", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<div> <select [(ngModel)]="selectedCity"> <option *ngFor="#c of list" [ngValue]="c">{{c['name']}}</option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp: MyComp = fixture.debugElement.componentInstance; - testComp.list = [{'name': 'SF'}, {'name': 'NYC'}]; - testComp.selectedCity = testComp.list[1]; - fixture.detectChanges(); + var testComp: MyComp = fixture.debugElement.componentInstance; + testComp.list = [{"name": "SF"}, {"name": "NYC"}]; + testComp.selectedCity = testComp.list[1]; + fixture.detectChanges(); - testComp.list.push({'name': 'Buffalo'}); - testComp.selectedCity = testComp.list[2]; - fixture.detectChanges(); + testComp.list.push({"name": "Buffalo"}); + testComp.selectedCity = testComp.list[2]; + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var buffalo = fixture.debugElement.queryAll(By.css('option'))[2]; - expect(select.nativeElement.value).toEqual('2: Object'); - expect(buffalo.nativeElement.selected).toBe(true); - async.done(); - }); - })); + var select = fixture.debugElement.query(By.css("select")); + var buffalo = fixture.debugElement.queryAll(By.css("option"))[2]; + expect(select.nativeElement.value).toEqual("2: Object"); + expect(buffalo.nativeElement.selected).toBe(true); + async.done(); + }); + })); - it('when options are removed', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div> + it("when options are removed", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<div> <select [(ngModel)]="selectedCity"> <option *ngFor="#c of list" [ngValue]="c">{{c}}</option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp: MyComp = fixture.debugElement.componentInstance; - testComp.list = [{'name': 'SF'}, {'name': 'NYC'}]; - testComp.selectedCity = testComp.list[1]; - fixture.detectChanges(); + var testComp: MyComp = fixture.debugElement.componentInstance; + testComp.list = [{"name": "SF"}, {"name": "NYC"}]; + testComp.selectedCity = testComp.list[1]; + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - expect(select.nativeElement.value).toEqual('1: Object'); + var select = fixture.debugElement.query(By.css("select")); + expect(select.nativeElement.value).toEqual("1: Object"); - testComp.list.pop(); - fixture.detectChanges(); + testComp.list.pop(); + fixture.detectChanges(); - expect(select.nativeElement.value).not.toEqual('1: Object'); - async.done(); - }); - })); + expect(select.nativeElement.value).not.toEqual("1: Object"); + async.done(); + }); + })); - it('when option values change identity while tracking by index', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div> + it("when option values change identity while tracking by index", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<div> <select [(ngModel)]="selectedCity"> <option *ngFor="#c of list; trackBy:customTrackBy" [ngValue]="c">{{c}}</option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp = fixture.debugElement.componentInstance; + var testComp = fixture.debugElement.componentInstance; - testComp.list = [{'name': 'SF'}, {'name': 'NYC'}]; - testComp.selectedCity = testComp.list[0]; - fixture.detectChanges(); + testComp.list = [{"name": "SF"}, {"name": "NYC"}]; + testComp.selectedCity = testComp.list[0]; + fixture.detectChanges(); - testComp.list[1] = 'Buffalo'; - testComp.selectedCity = testComp.list[1]; - fixture.detectChanges(); + testComp.list[1] = "Buffalo"; + testComp.selectedCity = testComp.list[1]; + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var buffalo = fixture.debugElement.queryAll(By.css('option'))[1]; + var select = fixture.debugElement.query(By.css("select")); + var buffalo = fixture.debugElement.queryAll(By.css("option"))[1]; - expect(select.nativeElement.value).toEqual('1: Buffalo'); - expect(buffalo.nativeElement.selected).toBe(true); - async.done(); - }); - })); + expect(select.nativeElement.value).toEqual("1: Buffalo"); + expect(buffalo.nativeElement.selected).toBe(true); + async.done(); + }); + })); - it('with duplicate option values', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div> + it("with duplicate option values", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<div> <select [(ngModel)]="selectedCity"> <option *ngFor="#c of list" [ngValue]="c">{{c}}</option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp = fixture.debugElement.componentInstance; + var testComp = fixture.debugElement.componentInstance; - testComp.list = [{'name': 'NYC'}, {'name': 'SF'}, {'name': 'SF'}]; - testComp.selectedCity = testComp.list[0]; - fixture.detectChanges(); + testComp.list = [{"name": "NYC"}, {"name": "SF"}, {"name": "SF"}]; + testComp.selectedCity = testComp.list[0]; + fixture.detectChanges(); - testComp.selectedCity = testComp.list[1]; - fixture.detectChanges(); + testComp.selectedCity = testComp.list[1]; + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var firstSF = fixture.debugElement.queryAll(By.css('option'))[1]; + var select = fixture.debugElement.query(By.css("select")); + var firstSF = fixture.debugElement.queryAll(By.css("option"))[1]; - expect(select.nativeElement.value).toEqual('1: Object'); - expect(firstSF.nativeElement.selected).toBe(true); - async.done(); - }); - })); + expect(select.nativeElement.value).toEqual("1: Object"); + expect(firstSF.nativeElement.selected).toBe(true); + async.done(); + }); + })); - it('when option values have same content, but different identities', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var t = `<div> + it("when option values have same content, but different identities", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + var t = `<div> <select [(ngModel)]="selectedCity"> <option *ngFor="#c of list" [ngValue]="c">{{c['name']}}</option> </select> </div>`; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - var testComp = fixture.debugElement.componentInstance; - testComp.list = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'NYC'}]; - testComp.selectedCity = testComp.list[0]; - fixture.detectChanges(); + var testComp = fixture.debugElement.componentInstance; + testComp.list = [{"name": "SF"}, {"name": "NYC"}, {"name": "NYC"}]; + testComp.selectedCity = testComp.list[0]; + fixture.detectChanges(); - testComp.selectedCity = testComp.list[2]; - fixture.detectChanges(); + testComp.selectedCity = testComp.list[2]; + fixture.detectChanges(); - var select = fixture.debugElement.query(By.css('select')); - var secondNYC = fixture.debugElement.queryAll(By.css('option'))[2]; + var select = fixture.debugElement.query(By.css("select")); + var secondNYC = fixture.debugElement.queryAll(By.css("option"))[2]; - expect(select.nativeElement.value).toEqual('2: Object'); - expect(secondNYC.nativeElement.selected).toBe(true); - async.done(); - }); - })); + expect(select.nativeElement.value).toEqual("2: Object"); + expect(secondNYC.nativeElement.selected).toBe(true); + async.done(); + }); + })); }); - it('should support custom value accessors', + it("should support custom value accessors", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <input type="text" ngControl="name" wrapped-value> @@ -609,20 +639,20 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'name': new Control('aa')}); + new ControlGroup({"name": new Control("aa")}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('!aa!'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("!aa!"); - input.nativeElement.value = '!bb!'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "!bb!"; + dispatchEvent(input.nativeElement, "input"); - expect(fixture.debugElement.componentInstance.form.value).toEqual({'name': 'bb'}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"name": "bb"}); async.done(); }); })); - it('should support custom value accessors on non builtin input elements that fire a change event without a \'target\' property', + it("should support custom value accessors on non builtin input elements that fire a change event without a 'target' property", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div [ngFormModel]="form"> <my-input ngControl="name"></my-input> @@ -630,14 +660,14 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = - new ControlGroup({'name': new Control('aa')}); + new ControlGroup({"name": new Control("aa")}); fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('my-input')); - expect(input.componentInstance.value).toEqual('!aa!'); + var input = fixture.debugElement.query(By.css("my-input")); + expect(input.componentInstance.value).toEqual("!aa!"); - input.componentInstance.value = '!bb!'; + input.componentInstance.value = "!bb!"; ObservableWrapper.subscribe(input.componentInstance.onInput, (value) => { - expect(fixture.debugElement.componentInstance.form.value).toEqual({'name': 'bb'}); + expect(fixture.debugElement.componentInstance.form.value).toEqual({"name": "bb"}); async.done(); }); input.componentInstance.dispatchChangeEvent(); @@ -646,11 +676,11 @@ export function main() { }); - describe('validations', () => { - it('should use sync validators defined in html', + describe("validations", () => { + it("should use sync validators defined in html", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var form = new ControlGroup( - {'login': new Control(''), 'min': new Control(''), 'max': new Control('')}); + {"login": new Control(""), "min": new Control(""), "max": new Control("")}); var t = `<div [ngFormModel]="form" login-is-empty-validator> <input type="text" ngControl="login" required> @@ -662,29 +692,29 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var required = fixture.debugElement.query(By.css('[required]')); - var minLength = fixture.debugElement.query(By.css('[minlength]')); - var maxLength = fixture.debugElement.query(By.css('[maxlength]')); + var required = fixture.debugElement.query(By.css("[required]")); + var minLength = fixture.debugElement.query(By.css("[minlength]")); + var maxLength = fixture.debugElement.query(By.css("[maxlength]")); - required.nativeElement.value = ''; - minLength.nativeElement.value = '1'; - maxLength.nativeElement.value = '1234'; - dispatchEvent(required.nativeElement, 'input'); - dispatchEvent(minLength.nativeElement, 'input'); - dispatchEvent(maxLength.nativeElement, 'input'); + required.nativeElement.value = ""; + minLength.nativeElement.value = "1"; + maxLength.nativeElement.value = "1234"; + dispatchEvent(required.nativeElement, "input"); + dispatchEvent(minLength.nativeElement, "input"); + dispatchEvent(maxLength.nativeElement, "input"); - expect(form.hasError('required', ['login'])).toEqual(true); - expect(form.hasError('minlength', ['min'])).toEqual(true); - expect(form.hasError('maxlength', ['max'])).toEqual(true); + expect(form.hasError("required", ["login"])).toEqual(true); + expect(form.hasError("minlength", ["min"])).toEqual(true); + expect(form.hasError("maxlength", ["max"])).toEqual(true); - expect(form.hasError('loginIsEmpty')).toEqual(true); + expect(form.hasError("loginIsEmpty")).toEqual(true); - required.nativeElement.value = '1'; - minLength.nativeElement.value = '123'; - maxLength.nativeElement.value = '123'; - dispatchEvent(required.nativeElement, 'input'); - dispatchEvent(minLength.nativeElement, 'input'); - dispatchEvent(maxLength.nativeElement, 'input'); + required.nativeElement.value = "1"; + minLength.nativeElement.value = "123"; + maxLength.nativeElement.value = "123"; + dispatchEvent(required.nativeElement, "input"); + dispatchEvent(minLength.nativeElement, "input"); + dispatchEvent(maxLength.nativeElement, "input"); expect(form.valid).toEqual(true); @@ -692,9 +722,9 @@ export function main() { }); })); - it('should use async validators defined in the html', + it("should use async validators defined in the html", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { - var form = new ControlGroup({'login': new Control('')}); + var form = new ControlGroup({"login": new Control("")}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login" uniq-login-validator="expected"> @@ -711,19 +741,19 @@ export function main() { tick(100); - expect(form.hasError('uniqLogin', ['login'])).toEqual(true); + expect(form.hasError("uniqLogin", ["login"])).toEqual(true); - var input = rootTC.debugElement.query(By.css('input')); - input.nativeElement.value = 'expected'; - dispatchEvent(input.nativeElement, 'input'); + var input = rootTC.debugElement.query(By.css("input")); + input.nativeElement.value = "expected"; + dispatchEvent(input.nativeElement, "input"); tick(100); expect(form.valid).toEqual(true); }))); - it('should use sync validators defined in the model', + it("should use sync validators defined in the model", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var form = new ControlGroup({'login': new Control('aa', Validators.required)}); + var form = new ControlGroup({"login": new Control("aa", Validators.required)}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> @@ -734,58 +764,58 @@ export function main() { fixture.detectChanges(); expect(form.valid).toEqual(true); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); - input.nativeElement.value = ''; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = ""; + dispatchEvent(input.nativeElement, "input"); expect(form.valid).toEqual(false); async.done(); }); })); - it('should use async validators defined in the model', + it("should use async validators defined in the model", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var control = - new Control('', Validators.required, uniqLoginAsyncValidator('expected')); - var form = new ControlGroup({'login': control}); + new Control("", Validators.required, uniqLoginAsyncValidator("expected")); + var form = new ControlGroup({"login": control}); var t = `<div [ngFormModel]="form"> <input type="text" ngControl="login"> </div>`; var fixture; - tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then( - (root) => fixture = root); + tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((root) => fixture = + root); tick(); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - expect(form.hasError('required', ['login'])).toEqual(true); + expect(form.hasError("required", ["login"])).toEqual(true); - var input = fixture.debugElement.query(By.css('input')); - input.nativeElement.value = 'wrong value'; - dispatchEvent(input.nativeElement, 'input'); + var input = fixture.debugElement.query(By.css("input")); + input.nativeElement.value = "wrong value"; + dispatchEvent(input.nativeElement, "input"); expect(form.pending).toEqual(true); tick(); - expect(form.hasError('uniqLogin', ['login'])).toEqual(true); + expect(form.hasError("uniqLogin", ["login"])).toEqual(true); - input.nativeElement.value = 'expected'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "expected"; + dispatchEvent(input.nativeElement, "input"); tick(); expect(form.valid).toEqual(true); }))); }); - describe('nested forms', () => { - it('should init DOM with the given form object', + describe("nested forms", () => { + it("should init DOM with the given form object", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var form = - new ControlGroup({'nested': new ControlGroup({'login': new Control('value')})}); + new ControlGroup({"nested": new ControlGroup({"login": new Control("value")})}); var t = `<div [ngFormModel]="form"> <div ngControlGroup="nested"> @@ -797,16 +827,16 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); - expect(input.nativeElement.value).toEqual('value'); + var input = fixture.debugElement.query(By.css("input")); + expect(input.nativeElement.value).toEqual("value"); async.done(); }); })); - it('should update the control group values on DOM change', + it("should update the control group values on DOM change", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var form = - new ControlGroup({'nested': new ControlGroup({'login': new Control('value')})}); + new ControlGroup({"nested": new ControlGroup({"login": new Control("value")})}); var t = `<div [ngFormModel]="form"> <div ngControlGroup="nested"> @@ -817,21 +847,21 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); - input.nativeElement.value = 'updatedValue'; - dispatchEvent(input.nativeElement, 'input'); + input.nativeElement.value = "updatedValue"; + dispatchEvent(input.nativeElement, "input"); - expect(form.value).toEqual({'nested': {'login': 'updatedValue'}}); + expect(form.value).toEqual({"nested": {"login": "updatedValue"}}); async.done(); }); })); }); - it('should support ngModel for complex forms', + it("should support ngModel for complex forms", inject( [TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { - var form = new ControlGroup({'name': new Control('')}); + var form = new ControlGroup({"name": new Control("")}); var t = `<div [ngFormModel]="form"><input type="text" ngControl="name" [(ngModel)]="name"></div>`; @@ -845,19 +875,19 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; - expect(input.value).toEqual('oldValue'); + var input = fixture.debugElement.query(By.css("input")).nativeElement; + expect(input.value).toEqual("oldValue"); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); tick(); - expect(fixture.debugElement.componentInstance.name).toEqual('updatedValue'); + expect(fixture.debugElement.componentInstance.name).toEqual("updatedValue"); }))); - it('should support ngModel for single fields', + it("should support ngModel for single fields", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { - var form = new Control(''); + var form = new Control(""); var t = `<div><input type="text" [ngFormControl]="form" [(ngModel)]="name"></div>`; @@ -866,21 +896,21 @@ export function main() { (root) => { fixture = root; }); tick(); fixture.debugElement.componentInstance.form = form; - fixture.debugElement.componentInstance.name = 'oldValue'; + fixture.debugElement.componentInstance.name = "oldValue"; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; - expect(input.value).toEqual('oldValue'); + var input = fixture.debugElement.query(By.css("input")).nativeElement; + expect(input.value).toEqual("oldValue"); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); tick(); - expect(fixture.debugElement.componentInstance.name).toEqual('updatedValue'); + expect(fixture.debugElement.componentInstance.name).toEqual("updatedValue"); }))); - describe('template-driven forms', () => { - it('should add new controls and control groups', + describe("template-driven forms", () => { + it("should add new controls and control groups", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<form> <div ngControlGroup="user"> @@ -904,7 +934,7 @@ export function main() { expect(form.controls['user'].controls['login']).toBeDefined(); }))); - it('should emit ngSubmit event on submit', + it("should emit ngSubmit event on submit", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<div><form (ngSubmit)="name='updated'"></form></div>`; @@ -913,15 +943,15 @@ export function main() { (root) => { fixture = root; }); tick(); fixture.debugElement.componentInstance.name = 'old'; - var form = fixture.debugElement.query(By.css('form')); + var form = fixture.debugElement.query(By.css("form")); - dispatchEvent(form.nativeElement, 'submit'); + dispatchEvent(form.nativeElement, "submit"); tick(); - expect(fixture.debugElement.componentInstance.name).toEqual('updated'); + expect(fixture.debugElement.componentInstance.name).toEqual("updated"); }))); - it('should not create a template-driven form when ngNoForm is used', + it("should not create a template-driven form when ngNoForm is used", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<form ngNoForm> </form>`; @@ -935,7 +965,7 @@ export function main() { }); })); - it('should remove controls', + it("should remove controls", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<form> <div *ngIf="name == 'show'"> @@ -962,7 +992,7 @@ export function main() { expect(form.controls['login']).not.toBeDefined(); }))); - it('should remove control groups', + it("should remove control groups", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<form> <div *ngIf="name=='show'" ngControlGroup="user"> @@ -989,7 +1019,7 @@ export function main() { expect(form.controls['user']).not.toBeDefined(); }))); - it('should support ngModel for complex forms', + it("should support ngModel for complex forms", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<form> <input type="text" ngControl="name" [(ngModel)]="name"> @@ -999,22 +1029,22 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then( (root) => { fixture = root; }); tick(); - fixture.debugElement.componentInstance.name = 'oldValue'; + fixture.debugElement.componentInstance.name = "oldValue"; fixture.detectChanges(); tick(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; - expect(input.value).toEqual('oldValue'); + var input = fixture.debugElement.query(By.css("input")).nativeElement; + expect(input.value).toEqual("oldValue"); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); tick(); - expect(fixture.debugElement.componentInstance.name).toEqual('updatedValue'); + expect(fixture.debugElement.componentInstance.name).toEqual("updatedValue"); }))); - it('should support ngModel for single fields', + it("should support ngModel for single fields", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<div><input type="text" [(ngModel)]="name"></div>`; @@ -1022,21 +1052,21 @@ export function main() { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then( (root) => { fixture = root; }); tick(); - fixture.debugElement.componentInstance.name = 'oldValue'; + fixture.debugElement.componentInstance.name = "oldValue"; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; - expect(input.value).toEqual('oldValue'); + var input = fixture.debugElement.query(By.css("input")).nativeElement; + expect(input.value).toEqual("oldValue"); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); tick(); - expect(fixture.debugElement.componentInstance.name).toEqual('updatedValue'); + expect(fixture.debugElement.componentInstance.name).toEqual("updatedValue"); }))); - it('should support <type=radio>', + it("should support <type=radio>", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<form> <input type="radio" name="food" ngControl="chicken" [(ngModel)]="data['chicken1']"> @@ -1061,10 +1091,10 @@ export function main() { fixture.detectChanges(); tick(); - var input = fixture.debugElement.query(By.css('input')); + var input = fixture.debugElement.query(By.css("input")); expect(input.nativeElement.checked).toEqual(false); - dispatchEvent(input.nativeElement, 'change'); + dispatchEvent(input.nativeElement, "change"); tick(); let data = fixture.debugElement.componentInstance.data; @@ -1077,10 +1107,10 @@ export function main() { }))); }); - describe('setting status classes', () => { - it('should work with single fields', + describe("setting status classes", () => { + it("should work with single fields", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var form = new Control('', Validators.required); + var form = new Control("", Validators.required); var t = `<div><input type="text" [ngFormControl]="form"></div>`; @@ -1088,26 +1118,26 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; + var input = fixture.debugElement.query(By.css("input")).nativeElement; expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); - dispatchEvent(input, 'blur'); + dispatchEvent(input, "blur"); fixture.detectChanges(); - expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); + expect(sortedClassList(input)).toEqual(["ng-invalid", "ng-pristine", "ng-touched"]); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); fixture.detectChanges(); - expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); + expect(sortedClassList(input)).toEqual(["ng-dirty", "ng-touched", "ng-valid"]); async.done(); }); })); - it('should work with complex model-driven forms', + it("should work with complex model-driven forms", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var form = new ControlGroup({'name': new Control('', Validators.required)}); + var form = new ControlGroup({"name": new Control("", Validators.required)}); var t = `<form [ngFormModel]="form"><input type="text" ngControl="name"></form>`; @@ -1115,53 +1145,53 @@ export function main() { fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; - expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); + var input = fixture.debugElement.query(By.css("input")).nativeElement; + expect(sortedClassList(input)).toEqual(["ng-invalid", "ng-pristine", "ng-untouched"]); - dispatchEvent(input, 'blur'); + dispatchEvent(input, "blur"); fixture.detectChanges(); - expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); + expect(sortedClassList(input)).toEqual(["ng-invalid", "ng-pristine", "ng-touched"]); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); fixture.detectChanges(); - expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); + expect(sortedClassList(input)).toEqual(["ng-dirty", "ng-touched", "ng-valid"]); async.done(); }); })); - it('should work with ngModel', + it("should work with ngModel", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var t = `<div><input [(ngModel)]="name" required></div>`; tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { - fixture.debugElement.componentInstance.name = ''; + fixture.debugElement.componentInstance.name = ""; fixture.detectChanges(); - var input = fixture.debugElement.query(By.css('input')).nativeElement; - expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); + var input = fixture.debugElement.query(By.css("input")).nativeElement; + expect(sortedClassList(input)).toEqual(["ng-invalid", "ng-pristine", "ng-untouched"]); - dispatchEvent(input, 'blur'); + dispatchEvent(input, "blur"); fixture.detectChanges(); - expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); + expect(sortedClassList(input)).toEqual(["ng-invalid", "ng-pristine", "ng-touched"]); - input.value = 'updatedValue'; - dispatchEvent(input, 'input'); + input.value = "updatedValue"; + dispatchEvent(input, "input"); fixture.detectChanges(); - expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); + expect(sortedClassList(input)).toEqual(["ng-dirty", "ng-touched", "ng-valid"]); async.done(); }); })); }); - describe('ngModel corner cases', () => { - it('should not update the view when the value initially came from the view', + describe("ngModel corner cases", () => { + it("should not update the view when the value initially came from the view", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { - var form = new Control(''); + var form = new Control(""); var t = `<div><input type="text" [ngFormControl]="form" [(ngModel)]="name"></div>`; @@ -1179,10 +1209,10 @@ export function main() { DOM.appendChild(fakeDoc.body, fixture.debugElement.nativeElement); } - var input = fixture.debugElement.query(By.css('input')).nativeElement; - input.value = 'aa'; + var input = fixture.debugElement.query(By.css("input")).nativeElement; + input.value = "aa"; input.selectionStart = 1; - dispatchEvent(input, 'input'); + dispatchEvent(input, "input"); tick(); fixture.detectChanges(); @@ -1191,39 +1221,39 @@ export function main() { expect(input.selectionStart).toEqual(1); }))); - it('should update the view when the model is set back to what used to be in the view', + it("should update the view when the model is set back to what used to be in the view", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var t = `<input type="text" [(ngModel)]="name">`; var fixture: ComponentFixture; tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then( (root) => { fixture = root; }); tick(); - fixture.debugElement.componentInstance.name = ''; + fixture.debugElement.componentInstance.name = ""; fixture.detectChanges(); // Type "aa" into the input. - var input = fixture.debugElement.query(By.css('input')).nativeElement; - input.value = 'aa'; + var input = fixture.debugElement.query(By.css("input")).nativeElement; + input.value = "aa"; input.selectionStart = 1; - dispatchEvent(input, 'input'); + dispatchEvent(input, "input"); tick(); fixture.detectChanges(); - expect(fixture.debugElement.componentInstance.name).toEqual('aa'); + expect(fixture.debugElement.componentInstance.name).toEqual("aa"); // Programatically update the input value to be "bb". - fixture.debugElement.componentInstance.name = 'bb'; + fixture.debugElement.componentInstance.name = "bb"; tick(); fixture.detectChanges(); - expect(input.value).toEqual('bb'); + expect(input.value).toEqual("bb"); // Programatically set it back to "aa". - fixture.debugElement.componentInstance.name = 'aa'; + fixture.debugElement.componentInstance.name = "aa"; tick(); fixture.detectChanges(); - expect(input.value).toEqual('aa'); + expect(input.value).toEqual("aa"); }))); - it('should not crash when validity is checked from a binding', + it("should not crash when validity is checked from a binding", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { // {{x.valid}} used to crash because valid() tried to read a property // from form.control before it was set. This test verifies this bug is @@ -1258,7 +1288,7 @@ class WrappedValue implements ControlValueAccessor { handleOnInput(value) { this.onChange(value.substring(1, value.length - 1)); } } -@Component({selector: 'my-input', template: ''}) +@Component({selector: "my-input", template: ''}) class MyInput implements ControlValueAccessor { @Output('input') onInput: EventEmitter<any> = new EventEmitter(); value: string; @@ -1279,14 +1309,14 @@ class MyInput implements ControlValueAccessor { function uniqLoginAsyncValidator(expectedValue: string) { return (c) => { var completer = PromiseWrapper.completer(); - var res = (c.value == expectedValue) ? null : {'uniqLogin': true}; + var res = (c.value == expectedValue) ? null : {"uniqLogin": true}; completer.resolve(res); return completer.promise; }; } function loginIsEmptyGroupValidator(c: ControlGroup) { - return c.controls['login'].value == '' ? {'loginIsEmpty': true} : null; + return c.controls["login"].value == "" ? {"loginIsEmpty": true} : null; } @Directive({ @@ -1298,8 +1328,10 @@ class LoginIsEmptyValidator { @Directive({ selector: '[uniq-login-validator]', - providers: [new Provider( - NG_ASYNC_VALIDATORS, {useExisting: forwardRef(() => UniqLoginValidator), multi: true})] + providers: [ + new Provider(NG_ASYNC_VALIDATORS, + {useExisting: forwardRef(() => UniqLoginValidator), multi: true}) + ] }) class UniqLoginValidator implements Validator { @Input('uniq-login-validator') expected; @@ -1308,10 +1340,16 @@ class UniqLoginValidator implements Validator { } @Component({ - selector: 'my-comp', + selector: "my-comp", template: '', directives: [ - FORM_DIRECTIVES, WrappedValue, MyInput, NgIf, NgFor, LoginIsEmptyValidator, UniqLoginValidator + FORM_DIRECTIVES, + WrappedValue, + MyInput, + NgIf, + NgFor, + LoginIsEmptyValidator, + UniqLoginValidator ] }) class MyComp { diff --git a/modules/angular2/test/common/forms/model_spec.ts b/modules/angular2/test/common/forms/model_spec.ts index ebdc271e9d..9dc4c2a989 100644 --- a/modules/angular2/test/common/forms/model_spec.ts +++ b/modules/angular2/test/common/forms/model_spec.ts @@ -1,4 +1,18 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, el, AsyncTestCompleter, fakeAsync, tick, inject} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + el, + AsyncTestCompleter, + fakeAsync, + tick, + inject +} from 'angular2/testing_internal'; import {ControlGroup, Control, ControlArray, Validators} from 'angular2/common'; import {IS_DART, isPresent, CONST_EXPR} from 'angular2/src/facade/lang'; import {PromiseWrapper} from 'angular2/src/facade/promise'; @@ -9,7 +23,7 @@ export function main() { return (c) => { var completer = PromiseWrapper.completer(); var t = isPresent(timeouts[c.value]) ? timeouts[c.value] : 0; - var res = c.value != expected ? {'async': true} : null; + var res = c.value != expected ? {"async": true} : null; if (t == 0) { completer.resolve(res); @@ -23,76 +37,76 @@ export function main() { function asyncValidatorReturningObservable(c) { var e = new EventEmitter(); - PromiseWrapper.scheduleMicrotask(() => ObservableWrapper.callEmit(e, {'async': true})); + PromiseWrapper.scheduleMicrotask(() => ObservableWrapper.callEmit(e, {"async": true})); return e; } - describe('Form Model', () => { - describe('Control', () => { - it('should default the value to null', () => { + describe("Form Model", () => { + describe("Control", () => { + it("should default the value to null", () => { var c = new Control(); expect(c.value).toBe(null); }); - describe('validator', () => { - it('should run validator with the initial value', () => { - var c = new Control('value', Validators.required); + describe("validator", () => { + it("should run validator with the initial value", () => { + var c = new Control("value", Validators.required); expect(c.valid).toEqual(true); }); - it('should rerun the validator when the value changes', () => { - var c = new Control('value', Validators.required); + it("should rerun the validator when the value changes", () => { + var c = new Control("value", Validators.required); c.updateValue(null); expect(c.valid).toEqual(false); }); - it('should return errors', () => { + it("should return errors", () => { var c = new Control(null, Validators.required); - expect(c.errors).toEqual({'required': true}); + expect(c.errors).toEqual({"required": true}); }); }); - describe('asyncValidator', () => { - it('should run validator with the initial value', fakeAsync(() => { - var c = new Control('value', null, asyncValidator('expected')); + describe("asyncValidator", () => { + it("should run validator with the initial value", fakeAsync(() => { + var c = new Control("value", null, asyncValidator("expected")); tick(); expect(c.valid).toEqual(false); - expect(c.errors).toEqual({'async': true}); + expect(c.errors).toEqual({"async": true}); })); - it('should support validators returning observables', fakeAsync(() => { - var c = new Control('value', null, asyncValidatorReturningObservable); + it("should support validators returning observables", fakeAsync(() => { + var c = new Control("value", null, asyncValidatorReturningObservable); tick(); expect(c.valid).toEqual(false); - expect(c.errors).toEqual({'async': true}); + expect(c.errors).toEqual({"async": true}); })); - it('should rerun the validator when the value changes', fakeAsync(() => { - var c = new Control('value', null, asyncValidator('expected')); + it("should rerun the validator when the value changes", fakeAsync(() => { + var c = new Control("value", null, asyncValidator("expected")); - c.updateValue('expected'); + c.updateValue("expected"); tick(); expect(c.valid).toEqual(true); })); - it('should run the async validator only when the sync validator passes', fakeAsync(() => { - var c = new Control('', Validators.required, asyncValidator('expected')); + it("should run the async validator only when the sync validator passes", fakeAsync(() => { + var c = new Control("", Validators.required, asyncValidator("expected")); tick(); - expect(c.errors).toEqual({'required': true}); + expect(c.errors).toEqual({"required": true}); - c.updateValue('some value'); + c.updateValue("some value"); tick(); - expect(c.errors).toEqual({'async': true}); + expect(c.errors).toEqual({"async": true}); })); - it('should mark the control as pending while running the async validation', + it("should mark the control as pending while running the async validation", fakeAsync(() => { - var c = new Control('', null, asyncValidator('expected')); + var c = new Control("", null, asyncValidator("expected")); expect(c.pending).toEqual(true); @@ -101,12 +115,12 @@ export function main() { expect(c.pending).toEqual(false); })); - it('should only use the latest async validation run', fakeAsync(() => { + it("should only use the latest async validation run", fakeAsync(() => { var c = - new Control('', null, asyncValidator('expected', {'long': 200, 'expected': 100})); + new Control("", null, asyncValidator("expected", {"long": 200, "expected": 100})); - c.updateValue('long'); - c.updateValue('expected'); + c.updateValue("long"); + c.updateValue("expected"); tick(300); @@ -114,202 +128,201 @@ export function main() { })); }); - describe('dirty', () => { - it('should be false after creating a control', () => { - var c = new Control('value'); + describe("dirty", () => { + it("should be false after creating a control", () => { + var c = new Control("value"); expect(c.dirty).toEqual(false); }); - it('should be true after changing the value of the control', () => { - var c = new Control('value'); + it("should be true after changing the value of the control", () => { + var c = new Control("value"); c.markAsDirty(); expect(c.dirty).toEqual(true); }); }); - describe('updateValue', () => { + describe("updateValue", () => { var g, c; beforeEach(() => { - c = new Control('oldValue'); - g = new ControlGroup({'one': c}); + c = new Control("oldValue"); + g = new ControlGroup({"one": c}); }); - it('should update the value of the control', () => { - c.updateValue('newValue'); - expect(c.value).toEqual('newValue'); + it("should update the value of the control", () => { + c.updateValue("newValue"); + expect(c.value).toEqual("newValue"); }); - it('should invoke ngOnChanges if it is present', () => { + it("should invoke ngOnChanges if it is present", () => { var ngOnChanges; - c.registerOnChange((v) => ngOnChanges = ['invoked', v]); + c.registerOnChange((v) => ngOnChanges = ["invoked", v]); - c.updateValue('newValue'); + c.updateValue("newValue"); - expect(ngOnChanges).toEqual(['invoked', 'newValue']); + expect(ngOnChanges).toEqual(["invoked", "newValue"]); }); - it('should not invoke on change when explicitly specified', () => { + it("should not invoke on change when explicitly specified", () => { var onChange = null; - c.registerOnChange((v) => onChange = ['invoked', v]); + c.registerOnChange((v) => onChange = ["invoked", v]); - c.updateValue('newValue', {emitModelToViewChange: false}); + c.updateValue("newValue", {emitModelToViewChange: false}); expect(onChange).toBeNull(); }); - it('should update the parent', () => { - c.updateValue('newValue'); - expect(g.value).toEqual({'one': 'newValue'}); + it("should update the parent", () => { + c.updateValue("newValue"); + expect(g.value).toEqual({"one": "newValue"}); }); - it('should not update the parent when explicitly specified', () => { - c.updateValue('newValue', {onlySelf: true}); - expect(g.value).toEqual({'one': 'oldValue'}); + it("should not update the parent when explicitly specified", () => { + c.updateValue("newValue", {onlySelf: true}); + expect(g.value).toEqual({"one": "oldValue"}); }); - it('should fire an event', fakeAsync(() => { - ObservableWrapper.subscribe( - c.valueChanges, (value) => { expect(value).toEqual('newValue'); }); + it("should fire an event", fakeAsync(() => { + ObservableWrapper.subscribe(c.valueChanges, + (value) => { expect(value).toEqual("newValue"); }); - c.updateValue('newValue'); + c.updateValue("newValue"); tick(); })); - it('should not fire an event when explicitly specified', fakeAsync(() => { - ObservableWrapper.subscribe(c.valueChanges, (value) => { throw 'Should not happen'; }); + it("should not fire an event when explicitly specified", fakeAsync(() => { + ObservableWrapper.subscribe(c.valueChanges, (value) => { throw "Should not happen"; }); - c.updateValue('newValue', {emitEvent: false}); + c.updateValue("newValue", {emitEvent: false}); tick(); })); }); - describe('valueChanges & statusChanges', () => { + describe("valueChanges & statusChanges", () => { var c; - beforeEach(() => { c = new Control('old', Validators.required); }); + beforeEach(() => { c = new Control("old", Validators.required); }); - it('should fire an event after the value has been updated', + it("should fire an event after the value has been updated", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(c.valueChanges, (value) => { expect(c.value).toEqual('new'); expect(value).toEqual('new'); async.done(); }); - c.updateValue('new'); + c.updateValue("new"); })); - it('should fire an event after the status has been updated to invalid', fakeAsync(() => { + it("should fire an event after the status has been updated to invalid", fakeAsync(() => { ObservableWrapper.subscribe(c.statusChanges, (status) => { expect(c.status).toEqual('INVALID'); expect(status).toEqual('INVALID'); }); - c.updateValue(''); + c.updateValue(""); tick(); })); - it('should fire an event after the status has been updated to pending', fakeAsync(() => { - var c = new Control('old', Validators.required, asyncValidator('expected')); + it("should fire an event after the status has been updated to pending", fakeAsync(() => { + var c = new Control("old", Validators.required, asyncValidator("expected")); var log = []; ObservableWrapper.subscribe(c.valueChanges, (value) => log.push(`value: '${value}'`)); - ObservableWrapper.subscribe( - c.statusChanges, (status) => log.push(`status: '${status}'`)); + ObservableWrapper.subscribe(c.statusChanges, + (status) => log.push(`status: '${status}'`)); - c.updateValue(''); + c.updateValue(""); tick(); - c.updateValue('nonEmpty'); + c.updateValue("nonEmpty"); tick(); - c.updateValue('expected'); + c.updateValue("expected"); tick(); expect(log).toEqual([ - '' + - 'value: \'\'', - 'status: \'INVALID\'', - 'value: \'nonEmpty\'', - 'status: \'PENDING\'', - 'status: \'INVALID\'', - 'value: \'expected\'', - 'status: \'PENDING\'', - 'status: \'VALID\'', + "" + "value: ''", + "status: 'INVALID'", + "value: 'nonEmpty'", + "status: 'PENDING'", + "status: 'INVALID'", + "value: 'expected'", + "status: 'PENDING'", + "status: 'VALID'", ]); })); // TODO: remove the if statement after making observable delivery sync if (!IS_DART) { - it('should update set errors and status before emitting an event', + it("should update set errors and status before emitting an event", inject([AsyncTestCompleter], (async) => { c.valueChanges.subscribe(value => { expect(c.valid).toEqual(false); - expect(c.errors).toEqual({'required': true}); + expect(c.errors).toEqual({"required": true}); async.done(); }); - c.updateValue(''); + c.updateValue(""); })); } - it('should return a cold observable', inject([AsyncTestCompleter], (async) => { - c.updateValue('will be ignored'); + it("should return a cold observable", inject([AsyncTestCompleter], (async) => { + c.updateValue("will be ignored"); ObservableWrapper.subscribe(c.valueChanges, (value) => { expect(value).toEqual('new'); async.done(); }); - c.updateValue('new'); + c.updateValue("new"); })); }); - describe('setErrors', () => { - it('should set errors on a control', () => { - var c = new Control('someValue'); + describe("setErrors", () => { + it("should set errors on a control", () => { + var c = new Control("someValue"); - c.setErrors({'someError': true}); + c.setErrors({"someError": true}); expect(c.valid).toEqual(false); - expect(c.errors).toEqual({'someError': true}); + expect(c.errors).toEqual({"someError": true}); }); - it('should reset the errors and validity when the value changes', () => { - var c = new Control('someValue', Validators.required); + it("should reset the errors and validity when the value changes", () => { + var c = new Control("someValue", Validators.required); - c.setErrors({'someError': true}); - c.updateValue(''); + c.setErrors({"someError": true}); + c.updateValue(""); - expect(c.errors).toEqual({'required': true}); + expect(c.errors).toEqual({"required": true}); }); - it('should update the parent group\'s validity', () => { - var c = new Control('someValue'); - var g = new ControlGroup({'one': c}); + it("should update the parent group's validity", () => { + var c = new Control("someValue"); + var g = new ControlGroup({"one": c}); expect(g.valid).toEqual(true); - c.setErrors({'someError': true}); + c.setErrors({"someError": true}); expect(g.valid).toEqual(false); }); - it('should not reset parent\'s errors', () => { - var c = new Control('someValue'); - var g = new ControlGroup({'one': c}); + it("should not reset parent's errors", () => { + var c = new Control("someValue"); + var g = new ControlGroup({"one": c}); - g.setErrors({'someGroupError': true}); - c.setErrors({'someError': true}); + g.setErrors({"someGroupError": true}); + c.setErrors({"someError": true}); - expect(g.errors).toEqual({'someGroupError': true}); + expect(g.errors).toEqual({"someGroupError": true}); }); - it('should reset errors when updating a value', () => { - var c = new Control('oldValue'); - var g = new ControlGroup({'one': c}); + it("should reset errors when updating a value", () => { + var c = new Control("oldValue"); + var g = new ControlGroup({"one": c}); - g.setErrors({'someGroupError': true}); - c.setErrors({'someError': true}); + g.setErrors({"someGroupError": true}); + c.setErrors({"someError": true}); - c.updateValue('newValue'); + c.updateValue("newValue"); expect(c.errors).toEqual(null); expect(g.errors).toEqual(null); @@ -317,180 +330,180 @@ export function main() { }); }); - describe('ControlGroup', () => { - describe('value', () => { - it('should be the reduced value of the child controls', () => { - var g = new ControlGroup({'one': new Control('111'), 'two': new Control('222')}); - expect(g.value).toEqual({'one': '111', 'two': '222'}); + describe("ControlGroup", () => { + describe("value", () => { + it("should be the reduced value of the child controls", () => { + var g = new ControlGroup({"one": new Control("111"), "two": new Control("222")}); + expect(g.value).toEqual({"one": "111", "two": "222"}); }); - it('should be empty when there are no child controls', () => { + it("should be empty when there are no child controls", () => { var g = new ControlGroup({}); expect(g.value).toEqual({}); }); - it('should support nested groups', () => { + it("should support nested groups", () => { var g = new ControlGroup( - {'one': new Control('111'), 'nested': new ControlGroup({'two': new Control('222')})}); - expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}}); + {"one": new Control("111"), "nested": new ControlGroup({"two": new Control("222")})}); + expect(g.value).toEqual({"one": "111", "nested": {"two": "222"}}); - (<Control>(g.controls['nested'].find('two'))).updateValue('333'); + (<Control>(g.controls["nested"].find("two"))).updateValue("333"); - expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}}); + expect(g.value).toEqual({"one": "111", "nested": {"two": "333"}}); }); }); - describe('errors', () => { - it('should run the validator when the value changes', () => { + describe("errors", () => { + it("should run the validator when the value changes", () => { var simpleValidator = (c) => - c.controls['one'].value != 'correct' ? {'broken': true} : null; + c.controls["one"].value != "correct" ? {"broken": true} : null; var c = new Control(null); - var g = new ControlGroup({'one': c}, null, simpleValidator); + var g = new ControlGroup({"one": c}, null, simpleValidator); - c.updateValue('correct'); + c.updateValue("correct"); expect(g.valid).toEqual(true); expect(g.errors).toEqual(null); - c.updateValue('incorrect'); + c.updateValue("incorrect"); expect(g.valid).toEqual(false); - expect(g.errors).toEqual({'broken': true}); + expect(g.errors).toEqual({"broken": true}); }); }); - describe('dirty', () => { + describe("dirty", () => { var c, g; beforeEach(() => { c = new Control('value'); - g = new ControlGroup({'one': c}); + g = new ControlGroup({"one": c}); }); - it('should be false after creating a control', () => { expect(g.dirty).toEqual(false); }); + it("should be false after creating a control", () => { expect(g.dirty).toEqual(false); }); - it('should be false after changing the value of the control', () => { + it("should be false after changing the value of the control", () => { c.markAsDirty(); expect(g.dirty).toEqual(true); }); }); - describe('optional components', () => { - describe('contains', () => { + describe("optional components", () => { + describe("contains", () => { var group; beforeEach(() => { group = new ControlGroup( { - 'required': new Control('requiredValue'), - 'optional': new Control('optionalValue') + "required": new Control("requiredValue"), + "optional": new Control("optionalValue") }, - {'optional': false}); + {"optional": false}); }); // rename contains into has - it('should return false when the component is not included', - () => { expect(group.contains('optional')).toEqual(false); }) + it("should return false when the component is not included", + () => { expect(group.contains("optional")).toEqual(false); }) - it('should return false when there is no component with the given name', - () => { expect(group.contains('something else')).toEqual(false); }); + it("should return false when there is no component with the given name", + () => { expect(group.contains("something else")).toEqual(false); }); - it('should return true when the component is included', () => { - expect(group.contains('required')).toEqual(true); + it("should return true when the component is included", () => { + expect(group.contains("required")).toEqual(true); - group.include('optional'); + group.include("optional"); - expect(group.contains('optional')).toEqual(true); + expect(group.contains("optional")).toEqual(true); }); }); - it('should not include an inactive component into the group value', () => { + it("should not include an inactive component into the group value", () => { var group = new ControlGroup( - {'required': new Control('requiredValue'), 'optional': new Control('optionalValue')}, - {'optional': false}); + {"required": new Control("requiredValue"), "optional": new Control("optionalValue")}, + {"optional": false}); - expect(group.value).toEqual({'required': 'requiredValue'}); + expect(group.value).toEqual({"required": "requiredValue"}); - group.include('optional'); + group.include("optional"); - expect(group.value).toEqual({'required': 'requiredValue', 'optional': 'optionalValue'}); + expect(group.value).toEqual({"required": "requiredValue", "optional": "optionalValue"}); }); - it('should not run Validators on an inactive component', () => { + it("should not run Validators on an inactive component", () => { var group = new ControlGroup( { - 'required': new Control('requiredValue', Validators.required), - 'optional': new Control('', Validators.required) + "required": new Control("requiredValue", Validators.required), + "optional": new Control("", Validators.required) }, - {'optional': false}); + {"optional": false}); expect(group.valid).toEqual(true); - group.include('optional'); + group.include("optional"); expect(group.valid).toEqual(false); }); }); - describe('valueChanges', () => { + describe("valueChanges", () => { var g, c1, c2; beforeEach(() => { - c1 = new Control('old1'); - c2 = new Control('old2'); - g = new ControlGroup({'one': c1, 'two': c2}, {'two': true}); + c1 = new Control("old1"); + c2 = new Control("old2"); + g = new ControlGroup({"one": c1, "two": c2}, {"two": true}); }); - it('should fire an event after the value has been updated', + it("should fire an event after the value has been updated", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(g.valueChanges, (value) => { expect(g.value).toEqual({'one': 'new1', 'two': 'old2'}); expect(value).toEqual({'one': 'new1', 'two': 'old2'}); async.done(); }); - c1.updateValue('new1'); + c1.updateValue("new1"); })); - it('should fire an event after the control\'s observable fired an event', + it("should fire an event after the control's observable fired an event", inject([AsyncTestCompleter], (async) => { var controlCallbackIsCalled = false; - ObservableWrapper.subscribe( - c1.valueChanges, (value) => { controlCallbackIsCalled = true; }); + ObservableWrapper.subscribe(c1.valueChanges, + (value) => { controlCallbackIsCalled = true; }); ObservableWrapper.subscribe(g.valueChanges, (value) => { expect(controlCallbackIsCalled).toBe(true); async.done(); }); - c1.updateValue('new1'); + c1.updateValue("new1"); })); - it('should fire an event when a control is excluded', + it("should fire an event when a control is excluded", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(g.valueChanges, (value) => { expect(value).toEqual({'one': 'old1'}); async.done(); }); - g.exclude('two'); + g.exclude("two"); })); - it('should fire an event when a control is included', + it("should fire an event when a control is included", inject([AsyncTestCompleter], (async) => { - g.exclude('two'); + g.exclude("two"); ObservableWrapper.subscribe(g.valueChanges, (value) => { expect(value).toEqual({'one': 'old1', 'two': 'old2'}); async.done(); }); - g.include('two'); + g.include("two"); })); - it('should fire an event every time a control is updated', + it("should fire an event every time a control is updated", inject([AsyncTestCompleter], (async) => { var loggedValues = []; @@ -498,57 +511,55 @@ export function main() { loggedValues.push(value); if (loggedValues.length == 2) { - expect(loggedValues).toEqual([ - {'one': 'new1', 'two': 'old2'}, {'one': 'new1', 'two': 'new2'} - ]); + expect(loggedValues) + .toEqual([{"one": "new1", "two": "old2"}, {"one": "new1", "two": "new2"}]); async.done(); } }); - c1.updateValue('new1'); - c2.updateValue('new2'); + c1.updateValue("new1"); + c2.updateValue("new2"); })); - xit('should not fire an event when an excluded control is updated', - inject( - [AsyncTestCompleter], (async) => { - // hard to test without hacking zones - })); + xit("should not fire an event when an excluded control is updated", + inject([AsyncTestCompleter], (async) => { + // hard to test without hacking zones + })); }); - describe('getError', () => { - it('should return the error when it is present', () => { - var c = new Control('', Validators.required); - var g = new ControlGroup({'one': c}); - expect(c.getError('required')).toEqual(true); - expect(g.getError('required', ['one'])).toEqual(true); + describe("getError", () => { + it("should return the error when it is present", () => { + var c = new Control("", Validators.required); + var g = new ControlGroup({"one": c}); + expect(c.getError("required")).toEqual(true); + expect(g.getError("required", ["one"])).toEqual(true); }); - it('should return null otherwise', () => { - var c = new Control('not empty', Validators.required); - var g = new ControlGroup({'one': c}); - expect(c.getError('invalid')).toEqual(null); - expect(g.getError('required', ['one'])).toEqual(null); - expect(g.getError('required', ['invalid'])).toEqual(null); + it("should return null otherwise", () => { + var c = new Control("not empty", Validators.required); + var g = new ControlGroup({"one": c}); + expect(c.getError("invalid")).toEqual(null); + expect(g.getError("required", ["one"])).toEqual(null); + expect(g.getError("required", ["invalid"])).toEqual(null); }); }); - describe('asyncValidator', () => { - it('should run the async validator', fakeAsync(() => { - var c = new Control('value'); - var g = new ControlGroup({'one': c}, null, null, asyncValidator('expected')); + describe("asyncValidator", () => { + it("should run the async validator", fakeAsync(() => { + var c = new Control("value"); + var g = new ControlGroup({"one": c}, null, null, asyncValidator("expected")); expect(g.pending).toEqual(true); tick(1); - expect(g.errors).toEqual({'async': true}); + expect(g.errors).toEqual({"async": true}); expect(g.pending).toEqual(false); })); - it('should set the parent group\'s status to pending', fakeAsync(() => { - var c = new Control('value', null, asyncValidator('expected')); - var g = new ControlGroup({'one': c}); + it("should set the parent group's status to pending", fakeAsync(() => { + var c = new Control("value", null, asyncValidator("expected")); + var g = new ControlGroup({"one": c}); expect(g.pending).toEqual(true); @@ -557,21 +568,21 @@ export function main() { expect(g.pending).toEqual(false); })); - it('should run the parent group\'s async validator when children are pending', + it("should run the parent group's async validator when children are pending", fakeAsync(() => { - var c = new Control('value', null, asyncValidator('expected')); - var g = new ControlGroup({'one': c}, null, null, asyncValidator('expected')); + var c = new Control("value", null, asyncValidator("expected")); + var g = new ControlGroup({"one": c}, null, null, asyncValidator("expected")); tick(1); - expect(g.errors).toEqual({'async': true}); - expect(g.find(['one']).errors).toEqual({'async': true}); + expect(g.errors).toEqual({"async": true}); + expect(g.find(["one"]).errors).toEqual({"async": true}); })); }) }); - describe('ControlArray', () => { - describe('adding/removing', () => { + describe("ControlArray", () => { + describe("adding/removing", () => { var a: ControlArray; var c1, c2, c3; @@ -582,13 +593,13 @@ export function main() { c3 = new Control(3); }); - it('should support pushing', () => { + it("should support pushing", () => { a.push(c1); expect(a.length).toEqual(1); expect(a.controls).toEqual([c1]); }); - it('should support removing', () => { + it("should support removing", () => { a.push(c1); a.push(c2); a.push(c3); @@ -598,7 +609,7 @@ export function main() { expect(a.controls).toEqual([c1, c3]); }); - it('should support inserting', () => { + it("should support inserting", () => { a.push(c1); a.push(c3); @@ -608,39 +619,39 @@ export function main() { }); }); - describe('value', () => { - it('should be the reduced value of the child controls', () => { + describe("value", () => { + it("should be the reduced value of the child controls", () => { var a = new ControlArray([new Control(1), new Control(2)]); expect(a.value).toEqual([1, 2]); }); - it('should be an empty array when there are no child controls', () => { + it("should be an empty array when there are no child controls", () => { var a = new ControlArray([]); expect(a.value).toEqual([]); }); }); - describe('errors', () => { - it('should run the validator when the value changes', () => { - var simpleValidator = (c) => c.controls[0].value != 'correct' ? {'broken': true} : null; + describe("errors", () => { + it("should run the validator when the value changes", () => { + var simpleValidator = (c) => c.controls[0].value != "correct" ? {"broken": true} : null; var c = new Control(null); var g = new ControlArray([c], simpleValidator); - c.updateValue('correct'); + c.updateValue("correct"); expect(g.valid).toEqual(true); expect(g.errors).toEqual(null); - c.updateValue('incorrect'); + c.updateValue("incorrect"); expect(g.valid).toEqual(false); - expect(g.errors).toEqual({'broken': true}); + expect(g.errors).toEqual({"broken": true}); }); }); - describe('dirty', () => { + describe("dirty", () => { var c: Control; var a: ControlArray; @@ -649,16 +660,16 @@ export function main() { a = new ControlArray([c]); }); - it('should be false after creating a control', () => { expect(a.dirty).toEqual(false); }); + it("should be false after creating a control", () => { expect(a.dirty).toEqual(false); }); - it('should be false after changing the value of the control', () => { + it("should be false after changing the value of the control", () => { c.markAsDirty(); expect(a.dirty).toEqual(true); }); }); - describe('pending', () => { + describe("pending", () => { var c: Control; var a: ControlArray; @@ -667,19 +678,19 @@ export function main() { a = new ControlArray([c]); }); - it('should be false after creating a control', () => { + it("should be false after creating a control", () => { expect(c.pending).toEqual(false); expect(a.pending).toEqual(false); }); - it('should be true after changing the value of the control', () => { + it("should be true after changing the value of the control", () => { c.markAsPending(); expect(c.pending).toEqual(true); expect(a.pending).toEqual(true); }); - it('should not update the parent when onlySelf = true', () => { + it("should not update the parent when onlySelf = true", () => { c.markAsPending({onlySelf: true}); expect(c.pending).toEqual(true); @@ -687,42 +698,42 @@ export function main() { }); }); - describe('valueChanges', () => { + describe("valueChanges", () => { var a: ControlArray; var c1, c2; beforeEach(() => { - c1 = new Control('old1'); - c2 = new Control('old2'); + c1 = new Control("old1"); + c2 = new Control("old2"); a = new ControlArray([c1, c2]); }); - it('should fire an event after the value has been updated', + it("should fire an event after the value has been updated", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(a.valueChanges, (value) => { expect(a.value).toEqual(['new1', 'old2']); expect(value).toEqual(['new1', 'old2']); async.done(); }); - c1.updateValue('new1'); + c1.updateValue("new1"); })); - it('should fire an event after the control\'s observable fired an event', + it("should fire an event after the control's observable fired an event", inject([AsyncTestCompleter], (async) => { var controlCallbackIsCalled = false; - ObservableWrapper.subscribe( - c1.valueChanges, (value) => { controlCallbackIsCalled = true; }); + ObservableWrapper.subscribe(c1.valueChanges, + (value) => { controlCallbackIsCalled = true; }); ObservableWrapper.subscribe(a.valueChanges, (value) => { expect(controlCallbackIsCalled).toBe(true); async.done(); }); - c1.updateValue('new1'); + c1.updateValue("new1"); })); - it('should fire an event when a control is removed', + it("should fire an event when a control is removed", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(a.valueChanges, (value) => { expect(value).toEqual(['old1']); @@ -732,7 +743,7 @@ export function main() { a.removeAt(1); })); - it('should fire an event when a control is added', inject([AsyncTestCompleter], (async) => { + it("should fire an event when a control is added", inject([AsyncTestCompleter], (async) => { a.removeAt(1); ObservableWrapper.subscribe(a.valueChanges, (value) => { @@ -744,49 +755,49 @@ export function main() { })); }); - describe('find', () => { - it('should return null when path is null', () => { + describe("find", () => { + it("should return null when path is null", () => { var g = new ControlGroup({}); expect(g.find(null)).toEqual(null); }); - it('should return null when path is empty', () => { + it("should return null when path is empty", () => { var g = new ControlGroup({}); expect(g.find([])).toEqual(null); }); - it('should return null when path is invalid', () => { + it("should return null when path is invalid", () => { var g = new ControlGroup({}); - expect(g.find(['one', 'two'])).toEqual(null); + expect(g.find(["one", "two"])).toEqual(null); }); - it('should return a child of a control group', () => { + it("should return a child of a control group", () => { var g = new ControlGroup( - {'one': new Control('111'), 'nested': new ControlGroup({'two': new Control('222')})}); + {"one": new Control("111"), "nested": new ControlGroup({"two": new Control("222")})}); - expect(g.find(['nested', 'two']).value).toEqual('222'); - expect(g.find(['one']).value).toEqual('111'); - expect(g.find('nested/two').value).toEqual('222'); - expect(g.find('one').value).toEqual('111'); + expect(g.find(["nested", "two"]).value).toEqual("222"); + expect(g.find(["one"]).value).toEqual("111"); + expect(g.find("nested/two").value).toEqual("222"); + expect(g.find("one").value).toEqual("111"); }); - it('should return an element of an array', () => { - var g = new ControlGroup({'array': new ControlArray([new Control('111')])}); + it("should return an element of an array", () => { + var g = new ControlGroup({"array": new ControlArray([new Control("111")])}); - expect(g.find(['array', 0]).value).toEqual('111'); + expect(g.find(["array", 0]).value).toEqual("111"); }); }); - describe('asyncValidator', () => { - it('should run the async validator', fakeAsync(() => { - var c = new Control('value'); - var g = new ControlArray([c], null, asyncValidator('expected')); + describe("asyncValidator", () => { + it("should run the async validator", fakeAsync(() => { + var c = new Control("value"); + var g = new ControlArray([c], null, asyncValidator("expected")); expect(g.pending).toEqual(true); tick(1); - expect(g.errors).toEqual({'async': true}); + expect(g.errors).toEqual({"async": true}); expect(g.pending).toEqual(false); })); }) diff --git a/modules/angular2/test/common/forms/validators_spec.ts b/modules/angular2/test/common/forms/validators_spec.ts index 683c330f63..5b049cdabc 100644 --- a/modules/angular2/test/common/forms/validators_spec.ts +++ b/modules/angular2/test/common/forms/validators_spec.ts @@ -1,4 +1,16 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, fakeAsync, tick, el} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + fakeAsync, + tick, + el +} from 'angular2/testing_internal'; import {ControlGroup, Control, Validators, AbstractControl, ControlArray} from 'angular2/common'; import {PromiseWrapper} from 'angular2/src/facade/promise'; import {EventEmitter, ObservableWrapper, TimerWrapper} from 'angular2/src/facade/async'; @@ -13,98 +25,95 @@ export function main() { } } - describe('Validators', () => { - describe('required', () => { - it('should error on an empty string', - () => { expect(Validators.required(new Control(''))).toEqual({'required': true}); }); + describe("Validators", () => { + describe("required", () => { + it("should error on an empty string", + () => { expect(Validators.required(new Control(""))).toEqual({"required": true}); }); - it('should error on null', - () => { expect(Validators.required(new Control(null))).toEqual({'required': true}); }); + it("should error on null", + () => { expect(Validators.required(new Control(null))).toEqual({"required": true}); }); - it('should not error on a non-empty string', - () => { expect(Validators.required(new Control('not empty'))).toEqual(null); }); + it("should not error on a non-empty string", + () => { expect(Validators.required(new Control("not empty"))).toEqual(null); }); - it('should accept zero as valid', + it("should accept zero as valid", () => { expect(Validators.required(new Control(0))).toEqual(null); }); }); - describe('minLength', () => { - it('should not error on an empty string', - () => { expect(Validators.minLength(2)(new Control(''))).toEqual(null); }); + describe("minLength", () => { + it("should not error on an empty string", + () => { expect(Validators.minLength(2)(new Control(""))).toEqual(null); }); - it('should not error on null', + it("should not error on null", () => { expect(Validators.minLength(2)(new Control(null))).toEqual(null); }); - it('should not error on valid strings', - () => { expect(Validators.minLength(2)(new Control('aa'))).toEqual(null); }); + it("should not error on valid strings", + () => { expect(Validators.minLength(2)(new Control("aa"))).toEqual(null); }); - it('should error on short strings', () => { - expect(Validators.minLength(2)(new Control('a'))).toEqual({ - 'minlength': {'requiredLength': 2, 'actualLength': 1} - }); + it("should error on short strings", () => { + expect(Validators.minLength(2)(new Control("a"))) + .toEqual({"minlength": {"requiredLength": 2, "actualLength": 1}}); }); }); - describe('maxLength', () => { - it('should not error on an empty string', - () => { expect(Validators.maxLength(2)(new Control(''))).toEqual(null); }); + describe("maxLength", () => { + it("should not error on an empty string", + () => { expect(Validators.maxLength(2)(new Control(""))).toEqual(null); }); - it('should not error on null', + it("should not error on null", () => { expect(Validators.maxLength(2)(new Control(null))).toEqual(null); }); - it('should not error on valid strings', - () => { expect(Validators.maxLength(2)(new Control('aa'))).toEqual(null); }); + it("should not error on valid strings", + () => { expect(Validators.maxLength(2)(new Control("aa"))).toEqual(null); }); - it('should error on long strings', () => { - expect(Validators.maxLength(2)(new Control('aaa'))).toEqual({ - 'maxlength': {'requiredLength': 2, 'actualLength': 3} - }); + it("should error on long strings", () => { + expect(Validators.maxLength(2)(new Control("aaa"))) + .toEqual({"maxlength": {"requiredLength": 2, "actualLength": 3}}); }); }); - describe('pattern', () => { - it('should not error on an empty string', - () => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(''))).toEqual(null); }); + describe("pattern", () => { + it("should not error on an empty string", + () => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(""))).toEqual(null); }); - it('should not error on null', - () => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(null))).toEqual(null); }); + it("should not error on null", + () => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(null))).toEqual(null); }); - it('should not error on valid strings', - () => { expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaAA'))).toEqual(null); }); + it("should not error on valid strings", + () => { expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaAA"))).toEqual(null); }); - it('should error on failure to match string', () => { - expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaa0'))).toEqual({ - 'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'} - }); + it("should error on failure to match string", () => { + expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaa0"))) + .toEqual({"pattern": {"requiredPattern": "^[a-zA-Z ]*$", "actualValue": "aaa0"}}); }); }); - describe('compose', () => { - it('should return null when given null', + describe("compose", () => { + it("should return null when given null", () => { expect(Validators.compose(null)).toBe(null); }); - it('should collect errors from all the validators', () => { - var c = Validators.compose([validator('a', true), validator('b', true)]); - expect(c(new Control(''))).toEqual({'a': true, 'b': true}); + it("should collect errors from all the validators", () => { + var c = Validators.compose([validator("a", true), validator("b", true)]); + expect(c(new Control(""))).toEqual({"a": true, "b": true}); }); - it('should run validators left to right', () => { - var c = Validators.compose([validator('a', 1), validator('a', 2)]); - expect(c(new Control(''))).toEqual({'a': 2}); + it("should run validators left to right", () => { + var c = Validators.compose([validator("a", 1), validator("a", 2)]); + expect(c(new Control(""))).toEqual({"a": 2}); }); - it('should return null when no errors', () => { + it("should return null when no errors", () => { var c = Validators.compose([Validators.nullValidator, Validators.nullValidator]); - expect(c(new Control(''))).toEqual(null); + expect(c(new Control(""))).toEqual(null); }); - it('should ignore nulls', () => { + it("should ignore nulls", () => { var c = Validators.compose([null, Validators.required]); - expect(c(new Control(''))).toEqual({'required': true}); + expect(c(new Control(""))).toEqual({"required": true}); }); }); - describe('composeAsync', () => { + describe("composeAsync", () => { function asyncValidator(expected, response) { return (c) => { var emitter = new EventEmitter(); @@ -121,42 +130,43 @@ export function main() { }; } - it('should return null when given null', + it("should return null when given null", () => { expect(Validators.composeAsync(null)).toEqual(null); }); - it('should collect errors from all the validators', fakeAsync(() => { + it("should collect errors from all the validators", fakeAsync(() => { var c = Validators.composeAsync([ - asyncValidator('expected', {'one': true}), asyncValidator('expected', {'two': true}) + asyncValidator("expected", {"one": true}), + asyncValidator("expected", {"two": true}) ]); var value = null; - (<Promise<any>>c(new Control('invalid'))).then(v => value = v); + (<Promise<any>>c(new Control("invalid"))).then(v => value = v); tick(1); - expect(value).toEqual({'one': true, 'two': true}); + expect(value).toEqual({"one": true, "two": true}); })); - it('should return null when no errors', fakeAsync(() => { - var c = Validators.composeAsync([asyncValidator('expected', {'one': true})]); + it("should return null when no errors", fakeAsync(() => { + var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]); var value = null; - (<Promise<any>>c(new Control('expected'))).then(v => value = v); + (<Promise<any>>c(new Control("expected"))).then(v => value = v); tick(1); expect(value).toEqual(null); })); - it('should ignore nulls', fakeAsync(() => { - var c = Validators.composeAsync([asyncValidator('expected', {'one': true}), null]); + it("should ignore nulls", fakeAsync(() => { + var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]); var value = null; - (<Promise<any>>c(new Control('invalid'))).then(v => value = v); + (<Promise<any>>c(new Control("invalid"))).then(v => value = v); tick(1); - expect(value).toEqual({'one': true}); + expect(value).toEqual({"one": true}); })); }); }); diff --git a/modules/angular2/test/common/pipes/async_pipe_spec.ts b/modules/angular2/test/common/pipes/async_pipe_spec.ts index 24d3894f02..cd30502f7d 100644 --- a/modules/angular2/test/common/pipes/async_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/async_pipe_spec.ts @@ -1,15 +1,32 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, browserDetection} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + browserDetection +} from 'angular2/testing_internal'; import {SpyChangeDetectorRef} from '../spies'; import {isBlank} from 'angular2/src/facade/lang'; import {AsyncPipe} from 'angular2/common'; import {WrappedValue} from 'angular2/core'; -import {EventEmitter, ObservableWrapper, PromiseWrapper, TimerWrapper} from 'angular2/src/facade/async'; +import { + EventEmitter, + ObservableWrapper, + PromiseWrapper, + TimerWrapper +} from 'angular2/src/facade/async'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {PromiseCompleter} from 'angular2/src/facade/promise'; export function main() { - describe('AsyncPipe', () => { + describe("AsyncPipe", () => { describe('Observable', () => { var emitter; @@ -23,11 +40,11 @@ export function main() { pipe = new AsyncPipe(ref); }); - describe('transform', () => { - it('should return null when subscribing to an observable', + describe("transform", () => { + it("should return null when subscribing to an observable", () => { expect(pipe.transform(emitter)).toBe(null); }); - it('should return the latest available value wrapped', + it("should return the latest available value wrapped", inject([AsyncTestCompleter], (async) => { pipe.transform(emitter); @@ -40,7 +57,7 @@ export function main() { })); - it('should return same value when nothing has changed since the last call', + it("should return same value when nothing has changed since the last call", inject([AsyncTestCompleter], (async) => { pipe.transform(emitter); ObservableWrapper.callEmit(emitter, message); @@ -52,7 +69,7 @@ export function main() { }, 0) })); - it('should dispose of the existing subscription when subscribing to a new observable', + it("should dispose of the existing subscription when subscribing to a new observable", inject([AsyncTestCompleter], (async) => { pipe.transform(emitter); @@ -68,7 +85,7 @@ export function main() { }, 0) })); - it('should request a change detection check upon receiving a new value', + it("should request a change detection check upon receiving a new value", inject([AsyncTestCompleter], (async) => { pipe.transform(emitter); ObservableWrapper.callEmit(emitter, message); @@ -80,11 +97,11 @@ export function main() { })); }); - describe('ngOnDestroy', () => { - it('should do nothing when no subscription', + describe("ngOnDestroy", () => { + it("should do nothing when no subscription", () => { expect(() => pipe.ngOnDestroy()).not.toThrow(); }); - it('should dispose of the existing subscription', inject([AsyncTestCompleter], (async) => { + it("should dispose of the existing subscription", inject([AsyncTestCompleter], (async) => { pipe.transform(emitter); pipe.ngOnDestroy(); @@ -98,7 +115,7 @@ export function main() { }); }); - describe('Promise', () => { + describe("Promise", () => { var message = new Object(); var pipe: AsyncPipe; var completer: PromiseCompleter<any>; @@ -112,11 +129,11 @@ export function main() { pipe = new AsyncPipe(<any>ref); }); - describe('transform', () => { - it('should return null when subscribing to a promise', + describe("transform", () => { + it("should return null when subscribing to a promise", () => { expect(pipe.transform(completer.promise)).toBe(null); }); - it('should return the latest available value', inject([AsyncTestCompleter], (async) => { + it("should return the latest available value", inject([AsyncTestCompleter], (async) => { pipe.transform(completer.promise); completer.resolve(message); @@ -127,7 +144,7 @@ export function main() { }, timer) })); - it('should return unwrapped value when nothing has changed since the last call', + it("should return unwrapped value when nothing has changed since the last call", inject([AsyncTestCompleter], (async) => { pipe.transform(completer.promise); completer.resolve(message); @@ -139,7 +156,7 @@ export function main() { }, timer) })); - it('should dispose of the existing subscription when subscribing to a new promise', + it("should dispose of the existing subscription when subscribing to a new promise", inject([AsyncTestCompleter], (async) => { pipe.transform(completer.promise); @@ -155,7 +172,7 @@ export function main() { }, timer) })); - it('should request a change detection check upon receiving a new value', + it("should request a change detection check upon receiving a new value", inject([AsyncTestCompleter], (async) => { var markForCheck = ref.spy('markForCheck'); pipe.transform(completer.promise); @@ -167,22 +184,22 @@ export function main() { }, timer) })); - describe('ngOnDestroy', () => { - it('should do nothing when no source', + describe("ngOnDestroy", () => { + it("should do nothing when no source", () => { expect(() => pipe.ngOnDestroy()).not.toThrow(); }); - it('should dispose of the existing source', inject([AsyncTestCompleter], (async) => { + it("should dispose of the existing source", inject([AsyncTestCompleter], (async) => { pipe.transform(completer.promise); expect(pipe.transform(completer.promise)).toBe(null); completer.resolve(message) - TimerWrapper.setTimeout(() => { - expect(pipe.transform(completer.promise)).toEqual(new WrappedValue(message)); - pipe.ngOnDestroy(); - expect(pipe.transform(completer.promise)).toBe(null); - async.done(); - }, timer); + TimerWrapper.setTimeout(() => { + expect(pipe.transform(completer.promise)).toEqual(new WrappedValue(message)); + pipe.ngOnDestroy(); + expect(pipe.transform(completer.promise)).toBe(null); + async.done(); + }, timer); })); }); }); @@ -198,7 +215,7 @@ export function main() { describe('other types', () => { it('should throw when given an invalid object', () => { var pipe = new AsyncPipe(null); - expect(() => pipe.transform(<any>'some bogus object', [])).toThrowError(); + expect(() => pipe.transform(<any>"some bogus object", [])).toThrowError(); }); }); }); diff --git a/modules/angular2/test/common/pipes/date_pipe_spec.ts b/modules/angular2/test/common/pipes/date_pipe_spec.ts index c04164b581..7978f3aa2b 100644 --- a/modules/angular2/test/common/pipes/date_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/date_pipe_spec.ts @@ -1,11 +1,21 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + browserDetection +} from 'angular2/testing_internal'; import {DatePipe} from 'angular2/common'; import {DateWrapper} from 'angular2/src/facade/lang'; import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver'; export function main() { - describe('DatePipe', () => { + describe("DatePipe", () => { var date; var pipe; @@ -17,11 +27,11 @@ export function main() { it('should be marked as pure', () => { expect(new PipeResolver().resolve(DatePipe).pure).toEqual(true); }); - describe('supports', () => { - it('should support date', () => { expect(pipe.supports(date)).toBe(true); }); - it('should support int', () => { expect(pipe.supports(123456789)).toBe(true); }); + describe("supports", () => { + it("should support date", () => { expect(pipe.supports(date)).toBe(true); }); + it("should support int", () => { expect(pipe.supports(123456789)).toBe(true); }); - it('should not support other objects', () => { + it("should not support other objects", () => { expect(pipe.supports(new Object())).toBe(false); expect(pipe.supports(null)).toBe(false); }); @@ -30,7 +40,7 @@ export function main() { // TODO(mlaval): enable tests when Intl API is no longer used, see // https://github.com/angular/angular/issues/3333 if (browserDetection.supportsIntlApi) { - describe('transform', () => { + describe("transform", () => { it('should format each component correctly', () => { expect(pipe.transform(date, ['y'])).toEqual('2015'); expect(pipe.transform(date, ['yy'])).toEqual('15'); diff --git a/modules/angular2/test/common/pipes/i18n_plural_pipe_spec.ts b/modules/angular2/test/common/pipes/i18n_plural_pipe_spec.ts index 848c2ddef5..6a220afd1e 100644 --- a/modules/angular2/test/common/pipes/i18n_plural_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/i18n_plural_pipe_spec.ts @@ -1,51 +1,57 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {I18nPluralPipe} from 'angular2/common'; import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver'; export function main() { - describe('I18nPluralPipe', () => { + describe("I18nPluralPipe", () => { var pipe; var mapping = {'=0': 'No messages.', '=1': 'One message.', 'other': 'There are some messages.'}; - var interpolatedMapping = { - '=0': 'No messages.', - '=1': 'One message.', - 'other': 'There are # messages, that is #.' - }; + var interpolatedMapping = + {'=0': 'No messages.', '=1': 'One message.', 'other': 'There are # messages, that is #.'}; beforeEach(() => { pipe = new I18nPluralPipe(); }); it('should be marked as pure', () => { expect(new PipeResolver().resolve(I18nPluralPipe).pure).toEqual(true); }); - describe('transform', () => { - it('should return 0 text if value is 0', () => { + describe("transform", () => { + it("should return 0 text if value is 0", () => { var val = pipe.transform(0, [mapping]); expect(val).toEqual('No messages.'); }); - it('should return 1 text if value is 1', () => { + it("should return 1 text if value is 1", () => { var val = pipe.transform(1, [mapping]); expect(val).toEqual('One message.'); }); - it('should return other text if value is anything other than 0 or 1', () => { + it("should return other text if value is anything other than 0 or 1", () => { var val = pipe.transform(6, [mapping]); expect(val).toEqual('There are some messages.'); }); - it('should interpolate the value into the text where indicated', () => { + it("should interpolate the value into the text where indicated", () => { var val = pipe.transform(6, [interpolatedMapping]); expect(val).toEqual('There are 6 messages, that is 6.'); }); - it('should use \'other\' if value is undefined', () => { + it("should use 'other' if value is undefined", () => { var messageLength; var val = pipe.transform(messageLength, [interpolatedMapping]); expect(val).toEqual('There are messages, that is .'); }); - it('should not support bad arguments', + it("should not support bad arguments", () => { expect(() => pipe.transform(0, ['hey'])).toThrowError(); }); }); diff --git a/modules/angular2/test/common/pipes/i18n_select_pipe_spec.ts b/modules/angular2/test/common/pipes/i18n_select_pipe_spec.ts index 138f0c39b8..7a9e7f21cd 100644 --- a/modules/angular2/test/common/pipes/i18n_select_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/i18n_select_pipe_spec.ts @@ -1,10 +1,19 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {I18nSelectPipe} from 'angular2/common'; import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver'; export function main() { - describe('I18nSelectPipe', () => { + describe("I18nSelectPipe", () => { var pipe; var mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'}; @@ -13,29 +22,29 @@ export function main() { it('should be marked as pure', () => { expect(new PipeResolver().resolve(I18nSelectPipe).pure).toEqual(true); }); - describe('transform', () => { - it('should return male text if value is male', () => { + describe("transform", () => { + it("should return male text if value is male", () => { var val = pipe.transform('male', [mapping]); expect(val).toEqual('Invite him.'); }); - it('should return female text if value is female', () => { + it("should return female text if value is female", () => { var val = pipe.transform('female', [mapping]); expect(val).toEqual('Invite her.'); }); - it('should return other text if value is anything other than male or female', () => { + it("should return other text if value is anything other than male or female", () => { var val = pipe.transform('Anything else', [mapping]); expect(val).toEqual('Invite them.'); }); - it('should use \'other\' if value is undefined', () => { + it("should use 'other' if value is undefined", () => { var gender; var val = pipe.transform(gender, [mapping]); expect(val).toEqual('Invite them.'); }); - it('should not support bad arguments', + it("should not support bad arguments", () => { expect(() => pipe.transform('male', ['hey'])).toThrowError(); }); }); diff --git a/modules/angular2/test/common/pipes/json_pipe_spec.ts b/modules/angular2/test/common/pipes/json_pipe_spec.ts index e9363f290f..af1492ba17 100644 --- a/modules/angular2/test/common/pipes/json_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/json_pipe_spec.ts @@ -1,11 +1,24 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, proxy, TestComponentBuilder} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + proxy, + TestComponentBuilder +} from 'angular2/testing_internal'; import {Json, RegExp, NumberWrapper, StringWrapper} from 'angular2/src/facade/lang'; import {Component} from 'angular2/core'; import {JsonPipe} from 'angular2/common'; export function main() { - describe('JsonPipe', () => { + describe("JsonPipe", () => { var regNewLine = '\n'; var inceptionObj; var inceptionObjString; @@ -15,29 +28,24 @@ export function main() { beforeEach(() => { inceptionObj = {dream: {dream: {dream: 'Limbo'}}}; - inceptionObjString = '{\n' + - ' "dream": {\n' + - ' "dream": {\n' + - ' "dream": "Limbo"\n' + - ' }\n' + - ' }\n' + - '}'; + inceptionObjString = "{\n" + " \"dream\": {\n" + " \"dream\": {\n" + + " \"dream\": \"Limbo\"\n" + " }\n" + " }\n" + "}"; pipe = new JsonPipe(); }); - describe('transform', () => { - it('should return JSON-formatted string', + describe("transform", () => { + it("should return JSON-formatted string", () => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); }); - it('should return JSON-formatted string even when normalized', () => { + it("should return JSON-formatted string even when normalized", () => { var dream1 = normalize(pipe.transform(inceptionObj)); var dream2 = normalize(inceptionObjString); expect(dream1).toEqual(dream2); }); - it('should return JSON-formatted string similar to Json.stringify', () => { + it("should return JSON-formatted string similar to Json.stringify", () => { var dream1 = normalize(pipe.transform(inceptionObj)); var dream2 = normalize(Json.stringify(inceptionObj)); expect(dream1).toEqual(dream2); @@ -51,11 +59,11 @@ export function main() { let mutable: number[] = [1]; fixture.debugElement.componentInstance.data = mutable; fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('[\n 1\n]'); + expect(fixture.debugElement.nativeElement).toHaveText("[\n 1\n]"); mutable.push(2); fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('[\n 1,\n 2\n]'); + expect(fixture.debugElement.nativeElement).toHaveText("[\n 1,\n 2\n]"); async.done(); }); diff --git a/modules/angular2/test/common/pipes/lowercase_pipe_spec.ts b/modules/angular2/test/common/pipes/lowercase_pipe_spec.ts index d85cb76a11..3dd6bebe39 100644 --- a/modules/angular2/test/common/pipes/lowercase_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/lowercase_pipe_spec.ts @@ -1,9 +1,18 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {LowerCasePipe} from 'angular2/common'; export function main() { - describe('LowerCasePipe', () => { + describe("LowerCasePipe", () => { var upper; var lower; var pipe; @@ -14,20 +23,20 @@ export function main() { pipe = new LowerCasePipe(); }); - describe('transform', () => { - it('should return lowercase', () => { + describe("transform", () => { + it("should return lowercase", () => { var val = pipe.transform(upper); expect(val).toEqual(lower); }); - it('should lowercase when there is a new value', () => { + it("should lowercase when there is a new value", () => { var val = pipe.transform(upper); expect(val).toEqual(lower); var val2 = pipe.transform('WAT'); expect(val2).toEqual('wat'); }); - it('should not support other objects', + it("should not support other objects", () => { expect(() => pipe.transform(new Object())).toThrowError(); }); }); diff --git a/modules/angular2/test/common/pipes/number_pipe_spec.ts b/modules/angular2/test/common/pipes/number_pipe_spec.ts index bfcaff25de..c141a740cf 100644 --- a/modules/angular2/test/common/pipes/number_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/number_pipe_spec.ts @@ -1,4 +1,14 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + browserDetection +} from 'angular2/testing_internal'; import {DecimalPipe, PercentPipe, CurrencyPipe} from 'angular2/common'; @@ -7,12 +17,12 @@ export function main() { // TODO(mlaval): enable tests when Intl API is no longer used, see // https://github.com/angular/angular/issues/3333 if (browserDetection.supportsIntlApi) { - describe('DecimalPipe', () => { + describe("DecimalPipe", () => { var pipe; beforeEach(() => { pipe = new DecimalPipe(); }); - describe('transform', () => { + describe("transform", () => { it('should return correct value for numbers', () => { expect(pipe.transform(12345, [])).toEqual('12,345'); expect(pipe.transform(123, ['.2'])).toEqual('123.00'); @@ -23,39 +33,39 @@ export function main() { expect(pipe.transform(1.1234, [])).toEqual('1.123'); }); - it('should not support other objects', + it("should not support other objects", () => { expect(() => pipe.transform(new Object(), [])).toThrowError(); }); }); }); - describe('PercentPipe', () => { + describe("PercentPipe", () => { var pipe; beforeEach(() => { pipe = new PercentPipe(); }); - describe('transform', () => { + describe("transform", () => { it('should return correct value for numbers', () => { expect(pipe.transform(1.23, [])).toEqual('123%'); expect(pipe.transform(1.2, ['.2'])).toEqual('120.00%'); }); - it('should not support other objects', + it("should not support other objects", () => { expect(() => pipe.transform(new Object(), [])).toThrowError(); }); }); }); - describe('CurrencyPipe', () => { + describe("CurrencyPipe", () => { var pipe; beforeEach(() => { pipe = new CurrencyPipe(); }); - describe('transform', () => { + describe("transform", () => { it('should return correct value for numbers', () => { expect(pipe.transform(123, [])).toEqual('USD123'); expect(pipe.transform(12, ['EUR', false, '.2'])).toEqual('EUR12.00'); }); - it('should not support other objects', + it("should not support other objects", () => { expect(() => pipe.transform(new Object(), [])).toThrowError(); }); }); }); diff --git a/modules/angular2/test/common/pipes/pipe_binding_spec.ts b/modules/angular2/test/common/pipes/pipe_binding_spec.ts index 6c179dc376..e6283b6a0d 100644 --- a/modules/angular2/test/common/pipes/pipe_binding_spec.ts +++ b/modules/angular2/test/common/pipes/pipe_binding_spec.ts @@ -1,4 +1,14 @@ -import {ddescribe, xdescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + xdescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {PipeProvider} from 'angular2/src/core/pipes/pipe_provider'; import {Pipe} from 'angular2/src/core/metadata'; @@ -6,7 +16,7 @@ import {Pipe} from 'angular2/src/core/metadata'; class MyPipe {} export function main() { - describe('PipeProvider', () => { + describe("PipeProvider", () => { it('should create a provider out of a type', () => { var provider = PipeProvider.createFromType(MyPipe, new Pipe({name: 'my-pipe'})); expect(provider.name).toEqual('my-pipe'); diff --git a/modules/angular2/test/common/pipes/pipes_spec.ts b/modules/angular2/test/common/pipes/pipes_spec.ts index 3d67897210..6a40613158 100644 --- a/modules/angular2/test/common/pipes/pipes_spec.ts +++ b/modules/angular2/test/common/pipes/pipes_spec.ts @@ -1,4 +1,14 @@ -import {ddescribe, xdescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + xdescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {Injector, Inject, provide, Pipe, PipeTransform, OnDestroy} from 'angular2/core'; import {ProtoPipes, Pipes} from 'angular2/src/core/pipes/pipes'; @@ -11,13 +21,13 @@ class PipeA implements PipeTransform, OnDestroy { class PipeB implements PipeTransform, OnDestroy { dep; - constructor(@Inject('dep') dep: any) { this.dep = dep; } + constructor(@Inject("dep") dep: any) { this.dep = dep; } transform(a, b) {} ngOnDestroy() {} } export function main() { - describe('Pipes', () => { + describe("Pipes", () => { var injector; beforeEach(() => { @@ -29,20 +39,20 @@ export function main() { ProtoPipes.fromProviders([PipeProvider.createFromType(PipeA, new Pipe({name: 'a'}))]); var pipes = new Pipes(proto, injector); - expect(pipes.get('a').pipe).toBeAnInstanceOf(PipeA); + expect(pipes.get("a").pipe).toBeAnInstanceOf(PipeA); }); it('should throw when no pipe found', () => { var proto = ProtoPipes.fromProviders([]); var pipes = new Pipes(proto, injector); - expect(() => pipes.get('invalid')).toThrowErrorWith('Cannot find pipe \'invalid\''); + expect(() => pipes.get("invalid")).toThrowErrorWith("Cannot find pipe 'invalid'"); }); it('should inject dependencies from the provided injector', () => { var proto = ProtoPipes.fromProviders([PipeProvider.createFromType(PipeB, new Pipe({name: 'b'}))]); var pipes = new Pipes(proto, injector); - expect((<any>pipes.get('b').pipe).dep).toEqual('dependency'); + expect((<any>pipes.get("b").pipe).dep).toEqual("dependency"); }); it('should cache pure pipes', () => { @@ -50,8 +60,8 @@ export function main() { [PipeProvider.createFromType(PipeA, new Pipe({name: 'a', pure: true}))]); var pipes = new Pipes(proto, injector); - expect(pipes.get('a').pure).toEqual(true); - expect(pipes.get('a')).toBe(pipes.get('a')); + expect(pipes.get("a").pure).toEqual(true); + expect(pipes.get("a")).toBe(pipes.get("a")); }); it('should NOT cache impure pipes', () => { @@ -59,8 +69,8 @@ export function main() { [PipeProvider.createFromType(PipeA, new Pipe({name: 'a', pure: false}))]); var pipes = new Pipes(proto, injector); - expect(pipes.get('a').pure).toEqual(false); - expect(pipes.get('a')).not.toBe(pipes.get('a')); + expect(pipes.get("a").pure).toEqual(false); + expect(pipes.get("a")).not.toBe(pipes.get("a")); }); }); } diff --git a/modules/angular2/test/common/pipes/replace_pipe_spec.ts b/modules/angular2/test/common/pipes/replace_pipe_spec.ts index 175085f8a9..fee33b2168 100644 --- a/modules/angular2/test/common/pipes/replace_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/replace_pipe_spec.ts @@ -1,10 +1,23 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection, inject, TestComponentBuilder, AsyncTestCompleter} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + browserDetection, + inject, + TestComponentBuilder, + AsyncTestCompleter +} from 'angular2/testing_internal'; import {ReplacePipe} from 'angular2/common'; import {RegExpWrapper, StringJoiner} from 'angular2/src/facade/lang'; export function main() { - describe('ReplacePipe', () => { + describe("ReplacePipe", () => { var someNumber: number; var str; var pipe; @@ -15,43 +28,43 @@ export function main() { pipe = new ReplacePipe(); }); - describe('transform', () => { + describe("transform", () => { - it('should not support input other than strings and numbers', () => { - expect(() => pipe.transform({}, ['Douglas', 'Hugh'])).toThrow(); - expect(() => pipe.transform([1, 2, 3], ['Douglas', 'Hugh'])).toThrow(); + it("should not support input other than strings and numbers", () => { + expect(() => pipe.transform({}, ["Douglas", "Hugh"])).toThrow(); + expect(() => pipe.transform([1, 2, 3], ["Douglas", "Hugh"])).toThrow(); }); - it('should not support patterns other than strings and regular expressions', () => { - expect(() => pipe.transform(str, [{}, 'Hugh'])).toThrow(); - expect(() => pipe.transform(str, [null, 'Hugh'])).toThrow(); - expect(() => pipe.transform(str, [123, 'Hugh'])).toThrow(); + it("should not support patterns other than strings and regular expressions", () => { + expect(() => pipe.transform(str, [{}, "Hugh"])).toThrow(); + expect(() => pipe.transform(str, [null, "Hugh"])).toThrow(); + expect(() => pipe.transform(str, [123, "Hugh"])).toThrow(); }); - it('should not support replacements other than strings and functions', () => { - expect(() => pipe.transform(str, ['Douglas', {}])).toThrow(); - expect(() => pipe.transform(str, ['Douglas', null])).toThrow(); - expect(() => pipe.transform(str, ['Douglas', 123])).toThrow(); + it("should not support replacements other than strings and functions", () => { + expect(() => pipe.transform(str, ["Douglas", {}])).toThrow(); + expect(() => pipe.transform(str, ["Douglas", null])).toThrow(); + expect(() => pipe.transform(str, ["Douglas", 123])).toThrow(); }); - it('should return a new string with the pattern replaced', () => { - var result1 = pipe.transform(str, ['Douglas', 'Hugh']); + it("should return a new string with the pattern replaced", () => { + var result1 = pipe.transform(str, ["Douglas", "Hugh"]); - var result2 = pipe.transform(str, [RegExpWrapper.create('a'), '_']); + var result2 = pipe.transform(str, [RegExpWrapper.create("a"), "_"]); - var result3 = pipe.transform(str, [RegExpWrapper.create('a', 'i'), '_']); + var result3 = pipe.transform(str, [RegExpWrapper.create("a", "i"), "_"]); - var f = (x => { return 'Adams!'; }); + var f = (x => { return "Adams!"; }); - var result4 = pipe.transform(str, ['Adams', f]); + var result4 = pipe.transform(str, ["Adams", f]); - var result5 = pipe.transform(someNumber, ['2', '4']); + var result5 = pipe.transform(someNumber, ["2", "4"]); - expect(result1).toEqual('Hugh Adams'); - expect(result2).toEqual('Dougl_s Ad_ms'); - expect(result3).toEqual('Dougl_s _d_ms'); - expect(result4).toEqual('Douglas Adams!'); - expect(result5).toEqual('44'); + expect(result1).toEqual("Hugh Adams"); + expect(result2).toEqual("Dougl_s Ad_ms"); + expect(result3).toEqual("Dougl_s _d_ms"); + expect(result4).toEqual("Douglas Adams!"); + expect(result5).toEqual("44"); }); }); diff --git a/modules/angular2/test/common/pipes/slice_pipe_spec.ts b/modules/angular2/test/common/pipes/slice_pipe_spec.ts index f6f66415b0..dab2236c3f 100644 --- a/modules/angular2/test/common/pipes/slice_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/slice_pipe_spec.ts @@ -1,10 +1,23 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection, inject, TestComponentBuilder, AsyncTestCompleter} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + browserDetection, + inject, + TestComponentBuilder, + AsyncTestCompleter +} from 'angular2/testing_internal'; import {Component} from 'angular2/core'; import {SlicePipe} from 'angular2/common'; export function main() { - describe('SlicePipe', () => { + describe("SlicePipe", () => { var list: number[]; var str; var pipe; @@ -15,17 +28,17 @@ export function main() { pipe = new SlicePipe(); }); - describe('supports', () => { - it('should support strings', () => { expect(pipe.supports(str)).toBe(true); }); - it('should support lists', () => { expect(pipe.supports(list)).toBe(true); }); + describe("supports", () => { + it("should support strings", () => { expect(pipe.supports(str)).toBe(true); }); + it("should support lists", () => { expect(pipe.supports(list)).toBe(true); }); - it('should not support other objects', () => { + it("should not support other objects", () => { expect(pipe.supports(new Object())).toBe(false); expect(pipe.supports(null)).toBe(false); }); }); - describe('transform', () => { + describe("transform", () => { it('should return all items after START index when START is positive and END is omitted', () => { diff --git a/modules/angular2/test/common/pipes/uppercase_pipe_spec.ts b/modules/angular2/test/common/pipes/uppercase_pipe_spec.ts index aa0673a9bc..7241c468c3 100644 --- a/modules/angular2/test/common/pipes/uppercase_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/uppercase_pipe_spec.ts @@ -1,9 +1,18 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {UpperCasePipe} from 'angular2/common'; export function main() { - describe('UpperCasePipe', () => { + describe("UpperCasePipe", () => { var upper; var lower; var pipe; @@ -14,21 +23,21 @@ export function main() { pipe = new UpperCasePipe(); }); - describe('transform', () => { + describe("transform", () => { - it('should return uppercase', () => { + it("should return uppercase", () => { var val = pipe.transform(lower); expect(val).toEqual(upper); }); - it('should uppercase when there is a new value', () => { + it("should uppercase when there is a new value", () => { var val = pipe.transform(lower); expect(val).toEqual(upper); var val2 = pipe.transform('wat'); expect(val2).toEqual('WAT'); }); - it('should not support other objects', + it("should not support other objects", () => { expect(() => pipe.transform(new Object())).toThrowError(); }); }); diff --git a/modules/angular2/test/compiler/change_definition_factory_spec.ts b/modules/angular2/test/compiler/change_definition_factory_spec.ts index e97baa02d4..300b326b11 100644 --- a/modules/angular2/test/compiler/change_definition_factory_spec.ts +++ b/modules/angular2/test/compiler/change_definition_factory_spec.ts @@ -1,8 +1,36 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder, beforeEachProviders} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + TestComponentBuilder, + beforeEachProviders +} from 'angular2/testing_internal'; import {MapWrapper} from 'angular2/src/facade/collection'; -import {CompileDirectiveMetadata, CompileTypeMetadata} from 'angular2/src/compiler/directive_metadata'; +import { + CompileDirectiveMetadata, + CompileTypeMetadata +} from 'angular2/src/compiler/directive_metadata'; import {TemplateParser} from 'angular2/src/compiler/template_parser'; -import {Parser, Lexer, ChangeDetectorDefinition, ChangeDetectorGenConfig, DynamicProtoChangeDetector, ChangeDetectionStrategy, ChangeDispatcher, DirectiveIndex, Locals, BindingTarget, ChangeDetector} from 'angular2/src/core/change_detection/change_detection'; +import { + Parser, + Lexer, + ChangeDetectorDefinition, + ChangeDetectorGenConfig, + DynamicProtoChangeDetector, + ChangeDetectionStrategy, + ChangeDispatcher, + DirectiveIndex, + Locals, + BindingTarget, + ChangeDetector +} from 'angular2/src/core/change_detection/change_detection'; import {Pipes} from 'angular2/src/core/change_detection/pipes'; import {createChangeDetectorDefinitions} from 'angular2/src/compiler/change_definition_factory'; import {TestDirective, TestDispatcher, TestPipes} from './change_detector_mocks'; @@ -29,14 +57,13 @@ export function main() { pipes = new TestPipes(); })); - function createChangeDetector( - template: string, directives: CompileDirectiveMetadata[], - protoViewIndex: number = 0): ChangeDetector { + function createChangeDetector(template: string, directives: CompileDirectiveMetadata[], + protoViewIndex: number = 0): ChangeDetector { var protoChangeDetectors = - createChangeDetectorDefinitions( - new CompileTypeMetadata({name: 'SomeComp'}), ChangeDetectionStrategy.Default, - new ChangeDetectorGenConfig(true, false, false), - parser.parse(template, directives, [], 'TestComp')) + createChangeDetectorDefinitions(new CompileTypeMetadata({name: 'SomeComp'}), + ChangeDetectionStrategy.Default, + new ChangeDetectorGenConfig(true, false, false), + parser.parse(template, directives, [], 'TestComp')) .map(definition => new DynamicProtoChangeDetector(definition)); var changeDetector = protoChangeDetectors[protoViewIndex].instantiate(); changeDetector.hydrate(context, locals, dispatcher, pipes); diff --git a/modules/angular2/test/compiler/change_detector_compiler_spec.ts b/modules/angular2/test/compiler/change_detector_compiler_spec.ts index 2cc7c5c6bf..b9630f6a50 100644 --- a/modules/angular2/test/compiler/change_detector_compiler_spec.ts +++ b/modules/angular2/test/compiler/change_detector_compiler_spec.ts @@ -1,4 +1,17 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {provide} from 'angular2/src/core/di'; import {CONST_EXPR, stringify, IS_DART} from 'angular2/src/facade/lang'; @@ -6,12 +19,28 @@ import {MapWrapper} from 'angular2/src/facade/collection'; import {ChangeDetectionCompiler} from 'angular2/src/compiler/change_detector_compiler'; -import {CompileDirectiveMetadata, CompileTypeMetadata} from 'angular2/src/compiler/directive_metadata'; -import {SourceModule, SourceExpression, SourceExpressions, moduleRef} from 'angular2/src/compiler/source_module'; +import { + CompileDirectiveMetadata, + CompileTypeMetadata +} from 'angular2/src/compiler/directive_metadata'; +import { + SourceModule, + SourceExpression, + SourceExpressions, + moduleRef +} from 'angular2/src/compiler/source_module'; import {TemplateParser} from 'angular2/src/compiler/template_parser'; -import {ChangeDetectorGenConfig, ChangeDetectionStrategy, ChangeDispatcher, DirectiveIndex, Locals, BindingTarget, ChangeDetector} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectorGenConfig, + ChangeDetectionStrategy, + ChangeDispatcher, + DirectiveIndex, + Locals, + BindingTarget, + ChangeDetector +} from 'angular2/src/core/change_detection/change_detection'; import {evalModule} from './eval_module'; @@ -31,15 +60,18 @@ export function main() { return; } describe('ChangeDetectorCompiler', () => { - beforeEachProviders(() => [TEST_PROVIDERS, provide(ChangeDetectorGenConfig, { - useValue: new ChangeDetectorGenConfig(true, false, false) - })]); + beforeEachProviders(() => [ + TEST_PROVIDERS, + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, false, false)}) + ]); var parser: TemplateParser; var compiler: ChangeDetectionCompiler; - beforeEachProviders( - () => [provide( - ChangeDetectorGenConfig, {useValue: new ChangeDetectorGenConfig(true, false, false)})]); + beforeEachProviders(() => [ + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, false, false)}) + ]); beforeEach(inject([TemplateParser, ChangeDetectionCompiler], (_parser, _compiler) => { parser = _parser; @@ -47,9 +79,8 @@ export function main() { })); describe('compileComponentRuntime', () => { - function detectChanges( - compiler: ChangeDetectionCompiler, template: string, - directives: CompileDirectiveMetadata[] = CONST_EXPR([])): string[] { + function detectChanges(compiler: ChangeDetectionCompiler, template: string, + directives: CompileDirectiveMetadata[] = CONST_EXPR([])): string[] { var type = new CompileTypeMetadata({name: stringify(SomeComponent), moduleUrl: THIS_MODULE_URL}); var parsedTemplate = parser.parse(template, directives, [], 'TestComp'); @@ -59,9 +90,8 @@ export function main() { } it('should watch element properties', () => { - expect(detectChanges(compiler, '<div [elProp]="someProp">')).toEqual([ - 'elementProperty(elProp)=someValue' - ]); + expect(detectChanges(compiler, '<div [elProp]="someProp">')) + .toEqual(['elementProperty(elProp)=someValue']); }); }); @@ -79,10 +109,11 @@ export function main() { } it('should watch element properties', inject([AsyncTestCompleter], (async) => { - detectChanges(compiler, '<div [elProp]="someProp">').then((value) => { - expect(value).toEqual(['elementProperty(elProp)=someValue']); - async.done(); - }); + detectChanges(compiler, '<div [elProp]="someProp">') + .then((value) => { + expect(value).toEqual(['elementProperty(elProp)=someValue']); + async.done(); + }); })); }); @@ -90,8 +121,8 @@ export function main() { }); } -function createTestableModule( - source: SourceExpressions, changeDetectorIndex: number): SourceModule { +function createTestableModule(source: SourceExpressions, + changeDetectorIndex: number): SourceModule { var resultExpression = `${THIS_MODULE_REF}testChangeDetector(([${source.expressions.join(',')}])[${changeDetectorIndex}])`; var testableSource = `${source.declarations.join('\n')} diff --git a/modules/angular2/test/compiler/change_detector_mocks.ts b/modules/angular2/test/compiler/change_detector_mocks.ts index 18ef45e4ee..ee8ca9b85b 100644 --- a/modules/angular2/test/compiler/change_detector_mocks.ts +++ b/modules/angular2/test/compiler/change_detector_mocks.ts @@ -1,7 +1,12 @@ import {isBlank} from 'angular2/src/facade/lang'; import {Pipes} from 'angular2/src/core/change_detection/pipes'; import {EventEmitter} from 'angular2/src/facade/async'; -import {ChangeDetector, ChangeDispatcher, DirectiveIndex, BindingTarget} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetector, + ChangeDispatcher, + DirectiveIndex, + BindingTarget +} from 'angular2/src/core/change_detection/change_detection'; export class TestDirective { eventLog: string[] = []; diff --git a/modules/angular2/test/compiler/css/lexer_spec.ts b/modules/angular2/test/compiler/css/lexer_spec.ts index 0a22cced59..ff3c01f326 100644 --- a/modules/angular2/test/compiler/css/lexer_spec.ts +++ b/modules/angular2/test/compiler/css/lexer_spec.ts @@ -1,12 +1,27 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; -import {isPresent} from 'angular2/src/facade/lang'; +import {isPresent} from "angular2/src/facade/lang"; -import {CssToken, CssScannerError, CssLexer, CssLexerMode, CssTokenType} from 'angular2/src/compiler/css/lexer'; +import { + CssToken, + CssScannerError, + CssLexer, + CssLexerMode, + CssTokenType +} from 'angular2/src/compiler/css/lexer'; export function main() { - function tokenize( - code, trackComments: boolean = false, mode: CssLexerMode = CssLexerMode.ALL): CssToken[] { + function tokenize(code, trackComments: boolean = false, + mode: CssLexerMode = CssLexerMode.ALL): CssToken[] { var scanner = new CssLexer().scan(code, trackComments); scanner.setMode(mode); @@ -26,7 +41,7 @@ export function main() { describe('CssLexer', () => { it('should lex newline characters as whitespace when whitespace mode is on', () => { - var newlines = ['\n', '\r\n', '\r', '\f']; + var newlines = ["\n", "\r\n", "\r", "\f"]; newlines.forEach((line) => { var token = tokenize(line, false, CssLexerMode.ALL_TRACK_WS)[0]; expect(token.type).toEqual(CssTokenType.Whitespace); @@ -34,7 +49,7 @@ export function main() { }); it('should combined newline characters as one newline token when whitespace mode is on', () => { - var newlines = ['\n', '\r\n', '\r', '\f'].join(''); + var newlines = ["\n", "\r\n", "\r", "\f"].join(""); var tokens = tokenize(newlines, false, CssLexerMode.ALL_TRACK_WS); expect(tokens.length).toEqual(1); expect(tokens[0].type).toEqual(CssTokenType.Whitespace); @@ -42,14 +57,13 @@ export function main() { it('should not consider whitespace or newline values at all when whitespace mode is off', () => { - var newlines = ['\n', '\r\n', '\r', '\f'].join(''); + var newlines = ["\n", "\r\n", "\r", "\f"].join(""); var tokens = tokenize(newlines); expect(tokens.length).toEqual(0); }); it('should lex simple selectors and their inner properties', () => { - var cssCode = '\n' + - ' .selector { my-prop: my-value; }\n'; + var cssCode = "\n" + " .selector { my-prop: my-value; }\n"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.Character); @@ -78,9 +92,7 @@ export function main() { }); it('should capture the column and line values for each token', () => { - var cssCode = '#id {\n' + - ' prop:value;\n' + - '}'; + var cssCode = "#id {\n" + " prop:value;\n" + "}"; var tokens = tokenize(cssCode); @@ -126,13 +138,13 @@ export function main() { }); it('should lex quoted strings and escape accordingly', () => { - var cssCode = 'prop: \'some { value } \\\' that is quoted\''; + var cssCode = "prop: 'some { value } \\' that is quoted'"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.Identifier); expect(tokens[1].type).toEqual(CssTokenType.Character); expect(tokens[2].type).toEqual(CssTokenType.String); - expect(tokens[2].strValue).toEqual('\'some { value } \\\' that is quoted\''); + expect(tokens[2].strValue).toEqual("'some { value } \\' that is quoted'"); }); it('should treat attribute operators as regular characters', () => { @@ -140,27 +152,27 @@ export function main() { }); it('should lex numbers properly and set them as numbers', () => { - var cssCode = '0 1 -2 3.0 -4.001'; + var cssCode = "0 1 -2 3.0 -4.001"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.Number); - expect(tokens[0].strValue).toEqual('0'); + expect(tokens[0].strValue).toEqual("0"); expect(tokens[1].type).toEqual(CssTokenType.Number); - expect(tokens[1].strValue).toEqual('1'); + expect(tokens[1].strValue).toEqual("1"); expect(tokens[2].type).toEqual(CssTokenType.Number); - expect(tokens[2].strValue).toEqual('-2'); + expect(tokens[2].strValue).toEqual("-2"); expect(tokens[3].type).toEqual(CssTokenType.Number); - expect(tokens[3].strValue).toEqual('3.0'); + expect(tokens[3].strValue).toEqual("3.0"); expect(tokens[4].type).toEqual(CssTokenType.Number); - expect(tokens[4].strValue).toEqual('-4.001'); + expect(tokens[4].strValue).toEqual("-4.001"); }); it('should lex @keywords', () => { - var cssCode = '@import()@something'; + var cssCode = "@import()@something"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.AtKeyword); @@ -177,7 +189,7 @@ export function main() { }); it('should still lex a number even if it has a dimension suffix', () => { - var cssCode = '40% is 40 percent'; + var cssCode = "40% is 40 percent"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.Number); @@ -194,7 +206,7 @@ export function main() { }); it('should allow escaped character and unicode character-strings in CSS selectors', () => { - var cssCode = '\\123456 .some\\thing \{\}'; + var cssCode = "\\123456 .some\\thing \{\}"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.Identifier); @@ -206,67 +218,67 @@ export function main() { }); it('should distinguish identifiers and numbers from special characters', () => { - var cssCode = 'one*two=-4+three-4-equals_value$'; + var cssCode = "one*two=-4+three-4-equals_value$"; var tokens = tokenize(cssCode); expect(tokens[0].type).toEqual(CssTokenType.Identifier); - expect(tokens[0].strValue).toEqual('one'); + expect(tokens[0].strValue).toEqual("one"); expect(tokens[1].type).toEqual(CssTokenType.Character); - expect(tokens[1].strValue).toEqual('*'); + expect(tokens[1].strValue).toEqual("*"); expect(tokens[2].type).toEqual(CssTokenType.Identifier); - expect(tokens[2].strValue).toEqual('two'); + expect(tokens[2].strValue).toEqual("two"); expect(tokens[3].type).toEqual(CssTokenType.Character); - expect(tokens[3].strValue).toEqual('='); + expect(tokens[3].strValue).toEqual("="); expect(tokens[4].type).toEqual(CssTokenType.Number); - expect(tokens[4].strValue).toEqual('-4'); + expect(tokens[4].strValue).toEqual("-4"); expect(tokens[5].type).toEqual(CssTokenType.Character); - expect(tokens[5].strValue).toEqual('+'); + expect(tokens[5].strValue).toEqual("+"); expect(tokens[6].type).toEqual(CssTokenType.Identifier); - expect(tokens[6].strValue).toEqual('three-4-equals_value'); + expect(tokens[6].strValue).toEqual("three-4-equals_value"); expect(tokens[7].type).toEqual(CssTokenType.Character); - expect(tokens[7].strValue).toEqual('$'); + expect(tokens[7].strValue).toEqual("$"); }); it('should filter out comments and whitespace by default', () => { - var cssCode = '.selector /* comment */ { /* value */ }'; + var cssCode = ".selector /* comment */ { /* value */ }"; var tokens = tokenize(cssCode); - expect(tokens[0].strValue).toEqual('.'); - expect(tokens[1].strValue).toEqual('selector'); - expect(tokens[2].strValue).toEqual('{'); - expect(tokens[3].strValue).toEqual('}'); + expect(tokens[0].strValue).toEqual("."); + expect(tokens[1].strValue).toEqual("selector"); + expect(tokens[2].strValue).toEqual("{"); + expect(tokens[3].strValue).toEqual("}"); }); it('should track comments when the flag is set to true', () => { - var cssCode = '.selector /* comment */ { /* value */ }'; + var cssCode = ".selector /* comment */ { /* value */ }"; var trackComments = true; var tokens = tokenize(cssCode, trackComments, CssLexerMode.ALL_TRACK_WS); - expect(tokens[0].strValue).toEqual('.'); - expect(tokens[1].strValue).toEqual('selector'); - expect(tokens[2].strValue).toEqual(' '); + expect(tokens[0].strValue).toEqual("."); + expect(tokens[1].strValue).toEqual("selector"); + expect(tokens[2].strValue).toEqual(" "); expect(tokens[3].type).toEqual(CssTokenType.Comment); - expect(tokens[3].strValue).toEqual('/* comment */'); + expect(tokens[3].strValue).toEqual("/* comment */"); - expect(tokens[4].strValue).toEqual(' '); - expect(tokens[5].strValue).toEqual('{'); - expect(tokens[6].strValue).toEqual(' '); + expect(tokens[4].strValue).toEqual(" "); + expect(tokens[5].strValue).toEqual("{"); + expect(tokens[6].strValue).toEqual(" "); expect(tokens[7].type).toEqual(CssTokenType.Comment); - expect(tokens[7].strValue).toEqual('/* value */'); + expect(tokens[7].strValue).toEqual("/* value */"); }); describe('Selector Mode', () => { it('should throw an error if a selector is being parsed while in the wrong mode', () => { - var cssCode = '.class > tag'; + var cssCode = ".class > tag"; var capturedMessage; try { @@ -293,18 +305,18 @@ export function main() { it('should consider attribute selectors as valid input and throw when an invalid modifier is used', () => { function tokenizeAttr(modifier) { - var cssCode = 'value' + modifier + '=\'something\''; + var cssCode = "value" + modifier + "='something'"; return tokenize(cssCode, false, CssLexerMode.ATTRIBUTE_SELECTOR); } - expect(tokenizeAttr('*').length).toEqual(4); - expect(tokenizeAttr('|').length).toEqual(4); - expect(tokenizeAttr('^').length).toEqual(4); - expect(tokenizeAttr('$').length).toEqual(4); - expect(tokenizeAttr('~').length).toEqual(4); - expect(tokenizeAttr('').length).toEqual(3); + expect(tokenizeAttr("*").length).toEqual(4); + expect(tokenizeAttr("|").length).toEqual(4); + expect(tokenizeAttr("^").length).toEqual(4); + expect(tokenizeAttr("$").length).toEqual(4); + expect(tokenizeAttr("~").length).toEqual(4); + expect(tokenizeAttr("").length).toEqual(3); - expect(() => { tokenizeAttr('+'); }).toThrow(); + expect(() => { tokenizeAttr("+"); }).toThrow(); }); }); @@ -314,15 +326,15 @@ export function main() { // the reason why the numbers are so high is because MediaQueries keep // track of the whitespace values - expect(tokenizeQuery('(prop: value)').length).toEqual(5); - expect(tokenizeQuery('(prop: value) and (prop2: value2)').length).toEqual(11); - expect(tokenizeQuery('tv and (prop: value)').length).toEqual(7); - expect(tokenizeQuery('print and ((prop: value) or (prop2: value2))').length).toEqual(15); - expect(tokenizeQuery('(content: \'something $ crazy inside &\')').length).toEqual(5); + expect(tokenizeQuery("(prop: value)").length).toEqual(5); + expect(tokenizeQuery("(prop: value) and (prop2: value2)").length).toEqual(11); + expect(tokenizeQuery("tv and (prop: value)").length).toEqual(7); + expect(tokenizeQuery("print and ((prop: value) or (prop2: value2))").length).toEqual(15); + expect(tokenizeQuery("(content: 'something $ crazy inside &')").length).toEqual(5); - expect(() => { tokenizeQuery('(max-height: 10 + 20)'); }).toThrow(); + expect(() => { tokenizeQuery("(max-height: 10 + 20)"); }).toThrow(); - expect(() => { tokenizeQuery('(max-height: fifty < 100)'); }).toThrow(); + expect(() => { tokenizeQuery("(max-height: fifty < 100)"); }).toThrow(); }); }); @@ -333,13 +345,13 @@ export function main() { return tokenize(code, false, CssLexerMode.PSEUDO_SELECTOR); } - expect(tokenizePseudo('lang(en-us)').length).toEqual(4); - expect(tokenizePseudo('hover').length).toEqual(1); - expect(tokenizePseudo('focus').length).toEqual(1); + expect(tokenizePseudo("lang(en-us)").length).toEqual(4); + expect(tokenizePseudo("hover").length).toEqual(1); + expect(tokenizePseudo("focus").length).toEqual(1); - expect(() => { tokenizePseudo('lang(something:broken)'); }).toThrow(); + expect(() => { tokenizePseudo("lang(something:broken)"); }).toThrow(); - expect(() => { tokenizePseudo('not(.selector)'); }).toThrow(); + expect(() => { tokenizePseudo("not(.selector)"); }).toThrow(); }); }); @@ -350,35 +362,32 @@ export function main() { return tokenize(code, false, CssLexerMode.PSEUDO_SELECTOR); } - expect(tokenizePseudo('lang(en-us)').length).toEqual(4); - expect(tokenizePseudo('hover').length).toEqual(1); - expect(tokenizePseudo('focus').length).toEqual(1); + expect(tokenizePseudo("lang(en-us)").length).toEqual(4); + expect(tokenizePseudo("hover").length).toEqual(1); + expect(tokenizePseudo("focus").length).toEqual(1); - expect(() => { tokenizePseudo('lang(something:broken)'); }).toThrow(); + expect(() => { tokenizePseudo("lang(something:broken)"); }).toThrow(); - expect(() => { tokenizePseudo('not(.selector)'); }).toThrow(); + expect(() => { tokenizePseudo("not(.selector)"); }).toThrow(); }); }); - describe( - 'Style Block Mode', () => { - it('should style blocks with a reduced subset of valid characters', - () => { - function tokenizeStyles(code) { - return tokenize(code, false, CssLexerMode.STYLE_BLOCK); - } + describe('Style Block Mode', () => { + it('should style blocks with a reduced subset of valid characters', () => { + function tokenizeStyles(code) { return tokenize(code, false, CssLexerMode.STYLE_BLOCK); } - expect(tokenizeStyles(` + expect(tokenizeStyles(` key: value; prop: 100; style: value3!important; - `).length).toEqual(14); + `).length) + .toEqual(14); - expect(() => tokenizeStyles(` key$: value; `)).toThrow(); - expect(() => tokenizeStyles(` key: value$; `)).toThrow(); - expect(() => tokenizeStyles(` key: value + 10; `)).toThrow(); - expect(() => tokenizeStyles(` key: &value; `)).toThrow(); - }); - }); + expect(() => tokenizeStyles(` key$: value; `)).toThrow(); + expect(() => tokenizeStyles(` key: value$; `)).toThrow(); + expect(() => tokenizeStyles(` key: value + 10; `)).toThrow(); + expect(() => tokenizeStyles(` key: &value; `)).toThrow(); + }); + }); }); } diff --git a/modules/angular2/test/compiler/css/parser_spec.ts b/modules/angular2/test/compiler/css/parser_spec.ts index 8c5116c3b8..33bc82824e 100644 --- a/modules/angular2/test/compiler/css/parser_spec.ts +++ b/modules/angular2/test/compiler/css/parser_spec.ts @@ -1,8 +1,35 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {BaseException} from 'angular2/src/facade/exceptions'; -import {ParsedCssResult, CssParser, BlockType, CssSelectorRuleAST, CssKeyframeRuleAST, CssKeyframeDefinitionAST, CssBlockDefinitionRuleAST, CssMediaQueryRuleAST, CssBlockRuleAST, CssInlineRuleAST, CssStyleValueAST, CssSelectorAST, CssDefinitionAST, CssStyleSheetAST, CssRuleAST, CssBlockAST, CssParseError} from 'angular2/src/compiler/css/parser'; +import { + ParsedCssResult, + CssParser, + BlockType, + CssSelectorRuleAST, + CssKeyframeRuleAST, + CssKeyframeDefinitionAST, + CssBlockDefinitionRuleAST, + CssMediaQueryRuleAST, + CssBlockRuleAST, + CssInlineRuleAST, + CssStyleValueAST, + CssSelectorAST, + CssDefinitionAST, + CssStyleSheetAST, + CssRuleAST, + CssBlockAST, + CssParseError +} from 'angular2/src/compiler/css/parser'; import {CssLexer} from 'angular2/src/compiler/css/lexer'; @@ -67,17 +94,17 @@ export function main() { var rule = <CssSelectorRuleAST>ast.rules[0]; expect(rule.selectors.length).toBe(7); - assertTokens(rule.selectors[0].tokens, ['.', 'class']); - assertTokens(rule.selectors[1].tokens, ['#', 'id']); - assertTokens(rule.selectors[2].tokens, ['tag']); - assertTokens(rule.selectors[3].tokens, ['[', 'attr', ']']); - assertTokens(rule.selectors[4].tokens, ['key', ' ', '+', ' ', 'value']); - assertTokens(rule.selectors[5].tokens, ['*', ' ', 'value']); - assertTokens(rule.selectors[6].tokens, [':', '-moz-any-link']); + assertTokens(rule.selectors[0].tokens, [".", "class"]); + assertTokens(rule.selectors[1].tokens, ["#", "id"]); + assertTokens(rule.selectors[2].tokens, ["tag"]); + assertTokens(rule.selectors[3].tokens, ["[", "attr", "]"]); + assertTokens(rule.selectors[4].tokens, ["key", " ", "+", " ", "value"]); + assertTokens(rule.selectors[5].tokens, ["*", " ", "value"]); + assertTokens(rule.selectors[6].tokens, [":", "-moz-any-link"]); var style1 = <CssDefinitionAST>rule.block.entries[0]; - expect(style1.property.strValue).toEqual('prop'); - assertTokens(style1.value.tokens, ['value123']); + expect(style1.property.strValue).toEqual("prop"); + assertTokens(style1.value.tokens, ["value123"]); }); it('should parse keyframe rules', () => { @@ -160,16 +187,16 @@ export function main() { var importRule = <CssInlineRuleAST>ast.rules[0]; expect(importRule.type).toEqual(BlockType.Import); - assertTokens(importRule.value.tokens, ['url', '(', 'remote', '.', 'css', ')']); + assertTokens(importRule.value.tokens, ["url", "(", "remote", ".", "css", ")"]); var charsetRule = <CssInlineRuleAST>ast.rules[1]; expect(charsetRule.type).toEqual(BlockType.Charset); - assertTokens(charsetRule.value.tokens, ['UTF-8']); + assertTokens(charsetRule.value.tokens, ["UTF-8"]); var namespaceRule = <CssInlineRuleAST>ast.rules[2]; expect(namespaceRule.type).toEqual(BlockType.Namespace); - assertTokens( - namespaceRule.value.tokens, ['ng', 'url', '(', 'http://angular.io/namespace/ng', ')']); + assertTokens(namespaceRule.value.tokens, + ["ng", "url", "(", "http://angular.io/namespace/ng", ")"]); }); it('should parse CSS values that contain functions and leave the inner function data untokenized', @@ -189,9 +216,8 @@ export function main() { expect(defs.length).toEqual(3); assertTokens((<CssDefinitionAST>defs[0]).value.tokens, ['url', '(', 'matias.css', ')']); - assertTokens( - (<CssDefinitionAST>defs[1]).value.tokens, - ['cubic-bezier', '(', '0.755, 0.050, 0.855, 0.060', ')']); + assertTokens((<CssDefinitionAST>defs[1]).value.tokens, + ['cubic-bezier', '(', '0.755, 0.050, 0.855, 0.060', ')']); assertTokens((<CssDefinitionAST>defs[2]).value.tokens, ['calc', '(', '100% - 50px', ')']); }); @@ -239,7 +265,7 @@ export function main() { var importRule = <CssInlineRuleAST>ast.rules[0]; expect(importRule.type).toEqual(BlockType.Import); - assertTokens(importRule.value.tokens, ['url', '(', 'something something', ')']); + assertTokens(importRule.value.tokens, ["url", "(", "something something", ")"]); var fontFaceRule = <CssBlockRuleAST>ast.rules[1]; expect(fontFaceRule.type).toEqual(BlockType.FontFace); @@ -304,7 +330,7 @@ export function main() { expect(documentRule.type).toEqual(BlockType.Document); var rule = <CssSelectorRuleAST>documentRule.block.entries[0]; - expect(rule.strValue).toEqual('body'); + expect(rule.strValue).toEqual("body"); }); it('should parse the @page rule', () => { @@ -322,11 +348,11 @@ export function main() { var rules = ast.rules; var pageRule1 = <CssBlockDefinitionRuleAST>rules[0]; - expect(pageRule1.strValue).toEqual('one'); + expect(pageRule1.strValue).toEqual("one"); expect(pageRule1.type).toEqual(BlockType.Page); var pageRule2 = <CssBlockDefinitionRuleAST>rules[1]; - expect(pageRule2.strValue).toEqual('two'); + expect(pageRule2.strValue).toEqual("two"); expect(pageRule2.type).toEqual(BlockType.Page); var selectorOne = <CssSelectorRuleAST>pageRule1.block.entries[0]; @@ -382,15 +408,15 @@ export function main() { expect(ast.rules.length).toEqual(3); var rule1 = <CssSelectorRuleAST>ast.rules[0]; - expect(rule1.selectors[0].strValue).toEqual('tag&'); + expect(rule1.selectors[0].strValue).toEqual("tag&"); expect(rule1.block.entries.length).toEqual(1); var rule2 = <CssSelectorRuleAST>ast.rules[1]; - expect(rule2.selectors[0].strValue).toEqual('.%tag'); + expect(rule2.selectors[0].strValue).toEqual(".%tag"); expect(rule2.block.entries.length).toEqual(1); var rule3 = <CssSelectorRuleAST>ast.rules[2]; - expect(rule3.selectors[0].strValue).toEqual('#tag$'); + expect(rule3.selectors[0].strValue).toEqual("#tag$"); expect(rule3.block.entries.length).toEqual(1); }); diff --git a/modules/angular2/test/compiler/css/visitor_spec.ts b/modules/angular2/test/compiler/css/visitor_spec.ts index f518f4c718..d6c9b7696b 100644 --- a/modules/angular2/test/compiler/css/visitor_spec.ts +++ b/modules/angular2/test/compiler/css/visitor_spec.ts @@ -1,9 +1,39 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; -import {NumberWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang'; +import {NumberWrapper, StringWrapper, isPresent} from "angular2/src/facade/lang"; import {BaseException} from 'angular2/src/facade/exceptions'; -import {CssToken, CssParser, CssParseError, BlockType, CssAST, CssSelectorRuleAST, CssKeyframeRuleAST, CssKeyframeDefinitionAST, CssBlockDefinitionRuleAST, CssMediaQueryRuleAST, CssBlockRuleAST, CssInlineRuleAST, CssStyleValueAST, CssSelectorAST, CssDefinitionAST, CssStyleSheetAST, CssRuleAST, CssBlockAST, CssASTVisitor, CssUnknownTokenListAST} from 'angular2/src/compiler/css/parser'; +import { + CssToken, + CssParser, + CssParseError, + BlockType, + CssAST, + CssSelectorRuleAST, + CssKeyframeRuleAST, + CssKeyframeDefinitionAST, + CssBlockDefinitionRuleAST, + CssMediaQueryRuleAST, + CssBlockRuleAST, + CssInlineRuleAST, + CssStyleValueAST, + CssSelectorAST, + CssDefinitionAST, + CssStyleSheetAST, + CssRuleAST, + CssBlockAST, + CssASTVisitor, + CssUnknownTokenListAST +} from 'angular2/src/compiler/css/parser'; import {CssLexer} from 'angular2/src/compiler/css/lexer'; @@ -23,49 +53,49 @@ class MyVisitor implements CssASTVisitor { constructor(ast: CssStyleSheetAST, context?: any) { ast.visit(this, context); } - visitCssValue(ast, context?: any): void { this._capture('visitCssValue', ast, context); } + visitCssValue(ast, context?: any): void { this._capture("visitCssValue", ast, context); } visitInlineCssRule(ast, context?: any): void { - this._capture('visitInlineCssRule', ast, context); + this._capture("visitInlineCssRule", ast, context); } visitCssKeyframeRule(ast: CssKeyframeRuleAST, context?: any): void { - this._capture('visitCssKeyframeRule', ast, context); + this._capture("visitCssKeyframeRule", ast, context); ast.block.visit(this, context); } visitCssKeyframeDefinition(ast: CssKeyframeDefinitionAST, context?: any): void { - this._capture('visitCssKeyframeDefinition', ast, context); + this._capture("visitCssKeyframeDefinition", ast, context); ast.block.visit(this, context); } visitCssMediaQueryRule(ast: CssMediaQueryRuleAST, context?: any): void { - this._capture('visitCssMediaQueryRule', ast, context); + this._capture("visitCssMediaQueryRule", ast, context); ast.block.visit(this, context); } visitCssSelectorRule(ast: CssSelectorRuleAST, context?: any): void { - this._capture('visitCssSelectorRule', ast, context); + this._capture("visitCssSelectorRule", ast, context); ast.selectors.forEach((selAST: CssSelectorAST) => { selAST.visit(this, context); }); ast.block.visit(this, context); } visitCssSelector(ast: CssSelectorAST, context?: any): void { - this._capture('visitCssSelector', ast, context); + this._capture("visitCssSelector", ast, context); } visitCssDefinition(ast: CssDefinitionAST, context?: any): void { - this._capture('visitCssDefinition', ast, context); + this._capture("visitCssDefinition", ast, context); ast.value.visit(this, context); } visitCssBlock(ast: CssBlockAST, context?: any): void { - this._capture('visitCssBlock', ast, context); + this._capture("visitCssBlock", ast, context); ast.entries.forEach((entryAST: CssAST) => { entryAST.visit(this, context); }); } visitCssStyleSheet(ast: CssStyleSheetAST, context?: any): void { - this._capture('visitCssStyleSheet', ast, context); + this._capture("visitCssStyleSheet", ast, context); ast.rules.forEach((ruleAST: CssRuleAST) => { ruleAST.visit(this, context); }); } @@ -178,7 +208,7 @@ export function main() { expect(captures.length).toEqual(1); var query1 = <CssMediaQueryRuleAST>captures[0][0]; - _assertTokens(query1.query, ['all', 'and', '(', 'max-width', '100', 'px', ')']); + _assertTokens(query1.query, ["all", "and", "(", "max-width", "100", "px", ")"]); expect(query1.block.entries.length).toEqual(1); }); diff --git a/modules/angular2/test/compiler/directive_metadata_spec.ts b/modules/angular2/test/compiler/directive_metadata_spec.ts index 09a3f26457..877df58648 100644 --- a/modules/angular2/test/compiler/directive_metadata_spec.ts +++ b/modules/angular2/test/compiler/directive_metadata_spec.ts @@ -1,6 +1,27 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + TestComponentBuilder +} from 'angular2/testing_internal'; -import {CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata, CompileProviderMetadata, CompileDiDependencyMetadata, CompileQueryMetadata, CompileIdentifierMetadata, CompileFactoryMetadata} from 'angular2/src/compiler/directive_metadata'; +import { + CompileDirectiveMetadata, + CompileTypeMetadata, + CompileTemplateMetadata, + CompileProviderMetadata, + CompileDiDependencyMetadata, + CompileQueryMetadata, + CompileIdentifierMetadata, + CompileFactoryMetadata +} from 'angular2/src/compiler/directive_metadata'; import {ViewEncapsulation} from 'angular2/src/core/metadata/view'; import {ChangeDetectionStrategy} from 'angular2/src/core/change_detection'; import {LifecycleHooks} from 'angular2/src/core/linker/interfaces'; @@ -46,24 +67,32 @@ export function main() { outputs: ['someEvent'], host: {'(event1)': 'handler1', '[prop1]': 'expr1', 'attr1': 'attrValue2'}, lifecycleHooks: [LifecycleHooks.OnChanges], - providers: [new CompileProviderMetadata({ - token: 'token', - useClass: fullTypeMeta, - useExisting: new CompileIdentifierMetadata({name: 'someName'}), - useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}), - useValue: 'someValue', - })], - viewProviders: [new CompileProviderMetadata({ - token: 'token', - useClass: fullTypeMeta, - useExisting: new CompileIdentifierMetadata({name: 'someName'}), - useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}), - useValue: 'someValue', - })], - queries: [new CompileQueryMetadata( - {selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'})], - viewQueries: [new CompileQueryMetadata( - {selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'})] + providers: [ + new CompileProviderMetadata({ + token: 'token', + useClass: fullTypeMeta, + useExisting: new CompileIdentifierMetadata({name: 'someName'}), + useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}), + useValue: 'someValue', + }) + ], + viewProviders: [ + new CompileProviderMetadata({ + token: 'token', + useClass: fullTypeMeta, + useExisting: new CompileIdentifierMetadata({name: 'someName'}), + useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}), + useValue: 'someValue', + }) + ], + queries: [ + new CompileQueryMetadata( + {selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'}) + ], + viewQueries: [ + new CompileQueryMetadata( + {selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'}) + ] }); }); diff --git a/modules/angular2/test/compiler/eval_module_spec.ts b/modules/angular2/test/compiler/eval_module_spec.ts index 77294337c8..8a208d20aa 100644 --- a/modules/angular2/test/compiler/eval_module_spec.ts +++ b/modules/angular2/test/compiler/eval_module_spec.ts @@ -1,4 +1,16 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject +} from 'angular2/testing_internal'; import {IS_DART} from 'angular2/src/facade/lang'; import {evalModule} from './eval_module'; @@ -19,10 +31,11 @@ export function main() { it('should call the "run" function and allow to use imports', inject([AsyncTestCompleter], (async) => { var moduleSource = IS_DART ? testDartModule : testJsModule; - evalModule(moduleSource, [[THIS_MODULE_URL, 'tst']], [1]).then((value) => { - expect(value).toEqual([1, 23]); - async.done(); - }); + evalModule(moduleSource, [[THIS_MODULE_URL, 'tst']], [1]) + .then((value) => { + expect(value).toEqual([1, 23]); + async.done(); + }); })); }); } diff --git a/modules/angular2/test/compiler/html_ast_spec_utils.ts b/modules/angular2/test/compiler/html_ast_spec_utils.ts index eabdab7095..a59476917f 100644 --- a/modules/angular2/test/compiler/html_ast_spec_utils.ts +++ b/modules/angular2/test/compiler/html_ast_spec_utils.ts @@ -1,5 +1,13 @@ import {HtmlParser, HtmlParseTreeResult, HtmlTreeError} from 'angular2/src/compiler/html_parser'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {ParseError, ParseLocation} from 'angular2/src/compiler/parse_util'; import {BaseException} from 'angular2/src/facade/exceptions'; diff --git a/modules/angular2/test/compiler/html_lexer_spec.ts b/modules/angular2/test/compiler/html_lexer_spec.ts index 1eaa58aa07..a4c32142a8 100644 --- a/modules/angular2/test/compiler/html_lexer_spec.ts +++ b/modules/angular2/test/compiler/html_lexer_spec.ts @@ -1,479 +1,584 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {BaseException} from 'angular2/src/facade/exceptions'; -import {tokenizeHtml, HtmlToken, HtmlTokenType, HtmlTokenError} from 'angular2/src/compiler/html_lexer'; +import { + tokenizeHtml, + HtmlToken, + HtmlTokenType, + HtmlTokenError +} from 'angular2/src/compiler/html_lexer'; import {ParseSourceSpan, ParseLocation, ParseSourceFile} from 'angular2/src/compiler/parse_util'; export function main() { describe('HtmlLexer', () => { describe('line/column numbers', () => { it('should work without newlines', () => { - expect(tokenizeAndHumanizeLineColumn('<t>a</t>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '0:2'], - [HtmlTokenType.TEXT, '0:3'], [HtmlTokenType.TAG_CLOSE, '0:4'], - [HtmlTokenType.EOF, '0:8'] - ]); + expect(tokenizeAndHumanizeLineColumn('<t>a</t>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '0:0'], + [HtmlTokenType.TAG_OPEN_END, '0:2'], + [HtmlTokenType.TEXT, '0:3'], + [HtmlTokenType.TAG_CLOSE, '0:4'], + [HtmlTokenType.EOF, '0:8'] + ]); }); it('should work with one newline', () => { - expect(tokenizeAndHumanizeLineColumn('<t>\na</t>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '0:2'], - [HtmlTokenType.TEXT, '0:3'], [HtmlTokenType.TAG_CLOSE, '1:1'], - [HtmlTokenType.EOF, '1:5'] - ]); + expect(tokenizeAndHumanizeLineColumn('<t>\na</t>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '0:0'], + [HtmlTokenType.TAG_OPEN_END, '0:2'], + [HtmlTokenType.TEXT, '0:3'], + [HtmlTokenType.TAG_CLOSE, '1:1'], + [HtmlTokenType.EOF, '1:5'] + ]); }); it('should work with multiple newlines', () => { - expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '1:0'], - [HtmlTokenType.TEXT, '1:1'], [HtmlTokenType.TAG_CLOSE, '2:1'], - [HtmlTokenType.EOF, '2:5'] - ]); + expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '0:0'], + [HtmlTokenType.TAG_OPEN_END, '1:0'], + [HtmlTokenType.TEXT, '1:1'], + [HtmlTokenType.TAG_CLOSE, '2:1'], + [HtmlTokenType.EOF, '2:5'] + ]); }); it('should work with CR and LF', () => { - expect(tokenizeAndHumanizeLineColumn('<t\n>\r\na\r</t>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '1:0'], - [HtmlTokenType.TEXT, '1:1'], [HtmlTokenType.TAG_CLOSE, '2:1'], - [HtmlTokenType.EOF, '2:5'] - ]); + expect(tokenizeAndHumanizeLineColumn('<t\n>\r\na\r</t>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '0:0'], + [HtmlTokenType.TAG_OPEN_END, '1:0'], + [HtmlTokenType.TEXT, '1:1'], + [HtmlTokenType.TAG_CLOSE, '2:1'], + [HtmlTokenType.EOF, '2:5'] + ]); }); }); describe('comments', () => { it('should parse comments', () => { - expect(tokenizeAndHumanizeParts('<!--t\ne\rs\r\nt-->')).toEqual([ - [HtmlTokenType.COMMENT_START], [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], - [HtmlTokenType.COMMENT_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<!--t\ne\rs\r\nt-->')) + .toEqual([ + [HtmlTokenType.COMMENT_START], + [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], + [HtmlTokenType.COMMENT_END], + [HtmlTokenType.EOF] + ]); }); it('should store the locations', - () => {expect(tokenizeAndHumanizeSourceSpans('<!--t\ne\rs\r\nt-->')).toEqual([ - [HtmlTokenType.COMMENT_START, '<!--'], [HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'], - [HtmlTokenType.COMMENT_END, '-->'], [HtmlTokenType.EOF, ''] - ])}); + () => {expect(tokenizeAndHumanizeSourceSpans('<!--t\ne\rs\r\nt-->')) + .toEqual([ + [HtmlTokenType.COMMENT_START, '<!--'], + [HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'], + [HtmlTokenType.COMMENT_END, '-->'], + [HtmlTokenType.EOF, ''] + ])}); it('should report <!- without -', () => { - expect(tokenizeAndHumanizeErrors('<!-a')).toEqual([ - [HtmlTokenType.COMMENT_START, 'Unexpected character "a"', '0:3'] - ]); + expect(tokenizeAndHumanizeErrors('<!-a')) + .toEqual([[HtmlTokenType.COMMENT_START, 'Unexpected character "a"', '0:3']]); }); it('should report missing end comment', () => { - expect(tokenizeAndHumanizeErrors('<!--')).toEqual([ - [HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4'] - ]); + expect(tokenizeAndHumanizeErrors('<!--')) + .toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4']]); }); }); describe('doctype', () => { it('should parse doctypes', () => { - expect(tokenizeAndHumanizeParts('<!doctype html>')).toEqual([ - [HtmlTokenType.DOC_TYPE, 'doctype html'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<!doctype html>')) + .toEqual([[HtmlTokenType.DOC_TYPE, 'doctype html'], [HtmlTokenType.EOF]]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('<!doctype html>')).toEqual([ - [HtmlTokenType.DOC_TYPE, '<!doctype html>'], [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('<!doctype html>')) + .toEqual([[HtmlTokenType.DOC_TYPE, '<!doctype html>'], [HtmlTokenType.EOF, '']]); }); it('should report missing end doctype', () => { - expect(tokenizeAndHumanizeErrors('<!')).toEqual([ - [HtmlTokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2'] - ]); + expect(tokenizeAndHumanizeErrors('<!')) + .toEqual([[HtmlTokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2']]); }); }); describe('CDATA', () => { it('should parse CDATA', () => { - expect(tokenizeAndHumanizeParts('<![CDATA[t\ne\rs\r\nt]]>')).toEqual([ - [HtmlTokenType.CDATA_START], [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], - [HtmlTokenType.CDATA_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<![CDATA[t\ne\rs\r\nt]]>')) + .toEqual([ + [HtmlTokenType.CDATA_START], + [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], + [HtmlTokenType.CDATA_END], + [HtmlTokenType.EOF] + ]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('<![CDATA[t\ne\rs\r\nt]]>')).toEqual([ - [HtmlTokenType.CDATA_START, '<![CDATA['], [HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'], - [HtmlTokenType.CDATA_END, ']]>'], [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('<![CDATA[t\ne\rs\r\nt]]>')) + .toEqual([ + [HtmlTokenType.CDATA_START, '<![CDATA['], + [HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'], + [HtmlTokenType.CDATA_END, ']]>'], + [HtmlTokenType.EOF, ''] + ]); }); it('should report <![ without CDATA[', () => { - expect(tokenizeAndHumanizeErrors('<![a')).toEqual([ - [HtmlTokenType.CDATA_START, 'Unexpected character "a"', '0:3'] - ]); + expect(tokenizeAndHumanizeErrors('<![a')) + .toEqual([[HtmlTokenType.CDATA_START, 'Unexpected character "a"', '0:3']]); }); it('should report missing end cdata', () => { - expect(tokenizeAndHumanizeErrors('<![CDATA[')).toEqual([ - [HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9'] - ]); + expect(tokenizeAndHumanizeErrors('<![CDATA[')) + .toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9']]); }); }); describe('open tags', () => { it('should parse open tags without prefix', () => { - expect(tokenizeAndHumanizeParts('<test>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'test'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<test>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'test'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse namespace prefix', () => { - expect(tokenizeAndHumanizeParts('<ns1:test>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, 'ns1', 'test'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<ns1:test>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, 'ns1', 'test'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse void tags', () => { - expect(tokenizeAndHumanizeParts('<test/>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'test'], [HtmlTokenType.TAG_OPEN_END_VOID], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<test/>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'test'], + [HtmlTokenType.TAG_OPEN_END_VOID], + [HtmlTokenType.EOF] + ]); }); it('should allow whitespace after the tag name', () => { - expect(tokenizeAndHumanizeParts('<test >')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'test'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<test >')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'test'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('<test>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '<test'], [HtmlTokenType.TAG_OPEN_END, '>'], - [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('<test>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '<test'], + [HtmlTokenType.TAG_OPEN_END, '>'], + [HtmlTokenType.EOF, ''] + ]); }); }); describe('attributes', () => { it('should parse attributes without prefix', () => { - expect(tokenizeAndHumanizeParts('<t a>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes with prefix', () => { - expect(tokenizeAndHumanizeParts('<t ns1:a>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, 'ns1', 'a'], - [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t ns1:a>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, 'ns1', 'a'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes whose prefix is not valid', () => { - expect(tokenizeAndHumanizeParts('<t (ns1:a)>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, '(ns1:a)'], - [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t (ns1:a)>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, '(ns1:a)'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes with single quote value', () => { - expect(tokenizeAndHumanizeParts('<t a=\'b\'>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts("<t a='b'>")) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 'b'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes with double quote value', () => { - expect(tokenizeAndHumanizeParts('<t a="b">')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a="b">')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 'b'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes with unquoted value', () => { - expect(tokenizeAndHumanizeParts('<t a=b>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a=b>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 'b'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should allow whitespace', () => { - expect(tokenizeAndHumanizeParts('<t a = b >')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a = b >')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 'b'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes with entities in values', () => { - expect(tokenizeAndHumanizeParts('<t a="AA">')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 'AA'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a="AA">')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 'AA'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should not decode entities without trailing ";"', () => { - expect(tokenizeAndHumanizeParts('<t a="&" b="c&&d">')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, '&'], [HtmlTokenType.ATTR_NAME, null, 'b'], - [HtmlTokenType.ATTR_VALUE, 'c&&d'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a="&" b="c&&d">')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, '&'], + [HtmlTokenType.ATTR_NAME, null, 'b'], + [HtmlTokenType.ATTR_VALUE, 'c&&d'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse attributes with "&" in values', () => { - expect(tokenizeAndHumanizeParts('<t a="b && c &">')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 'b && c &'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('<t a="b && c &">')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 'b && c &'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should parse values with CR and LF', () => { - expect(tokenizeAndHumanizeParts('<t a=\'t\ne\rs\r\nt\'>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'], - [HtmlTokenType.ATTR_VALUE, 't\ne\ns\nt'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts("<t a='t\ne\rs\r\nt'>")) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 't'], + [HtmlTokenType.ATTR_NAME, null, 'a'], + [HtmlTokenType.ATTR_VALUE, 't\ne\ns\nt'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.EOF] + ]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('<t a=b>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '<t'], [HtmlTokenType.ATTR_NAME, 'a'], - [HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END, '>'], - [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('<t a=b>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '<t'], + [HtmlTokenType.ATTR_NAME, 'a'], + [HtmlTokenType.ATTR_VALUE, 'b'], + [HtmlTokenType.TAG_OPEN_END, '>'], + [HtmlTokenType.EOF, ''] + ]); }); }); describe('closing tags', () => { it('should parse closing tags without prefix', () => { - expect(tokenizeAndHumanizeParts('</test>')).toEqual([ - [HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('</test>')) + .toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]); }); it('should parse closing tags with prefix', () => { - expect(tokenizeAndHumanizeParts('</ns1:test>')).toEqual([ - [HtmlTokenType.TAG_CLOSE, 'ns1', 'test'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('</ns1:test>')) + .toEqual([[HtmlTokenType.TAG_CLOSE, 'ns1', 'test'], [HtmlTokenType.EOF]]); }); it('should allow whitespace', () => { - expect(tokenizeAndHumanizeParts('</ test >')).toEqual([ - [HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('</ test >')) + .toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('</test>')).toEqual([ - [HtmlTokenType.TAG_CLOSE, '</test>'], [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('</test>')) + .toEqual([[HtmlTokenType.TAG_CLOSE, '</test>'], [HtmlTokenType.EOF, '']]); }); it('should report missing name after </', () => { - expect(tokenizeAndHumanizeErrors('</')).toEqual([ - [HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2'] - ]); + expect(tokenizeAndHumanizeErrors('</')) + .toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2']]); }); it('should report missing >', () => { - expect(tokenizeAndHumanizeErrors('</test')).toEqual([ - [HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6'] - ]); + expect(tokenizeAndHumanizeErrors('</test')) + .toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6']]); }); }); describe('entities', () => { it('should parse named entities', () => { - expect(tokenizeAndHumanizeParts('a&b')).toEqual([ - [HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('a&b')) + .toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]); }); it('should parse hexadecimal entities', () => { - expect(tokenizeAndHumanizeParts('AA')).toEqual([ - [HtmlTokenType.TEXT, 'AA'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('AA')) + .toEqual([[HtmlTokenType.TEXT, 'AA'], [HtmlTokenType.EOF]]); }); it('should parse decimal entities', () => { - expect(tokenizeAndHumanizeParts('A')).toEqual([ - [HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('A')) + .toEqual([[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('a&b')).toEqual([ - [HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('a&b')) + .toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF, '']]); }); it('should report malformed/unknown entities', () => { - expect(tokenizeAndHumanizeErrors('&tbo;')).toEqual([[ - HtmlTokenType.TEXT, - 'Unknown entity "tbo" - use the "&#<decimal>;" or "&#x<hex>;" syntax', '0:0' - ]]); - expect(tokenizeAndHumanizeErrors('&#asdf;')).toEqual([ - [HtmlTokenType.TEXT, 'Unexpected character "s"', '0:3'] - ]); - expect(tokenizeAndHumanizeErrors('
sdf;')).toEqual([ - [HtmlTokenType.TEXT, 'Unexpected character "s"', '0:4'] - ]); + expect(tokenizeAndHumanizeErrors('&tbo;')) + .toEqual([ + [ + HtmlTokenType.TEXT, + 'Unknown entity "tbo" - use the "&#<decimal>;" or "&#x<hex>;" syntax', + '0:0' + ] + ]); + expect(tokenizeAndHumanizeErrors('&#asdf;')) + .toEqual([[HtmlTokenType.TEXT, 'Unexpected character "s"', '0:3']]); + expect(tokenizeAndHumanizeErrors('
sdf;')) + .toEqual([[HtmlTokenType.TEXT, 'Unexpected character "s"', '0:4']]); - expect(tokenizeAndHumanizeErrors('઼')).toEqual([ - [HtmlTokenType.TEXT, 'Unexpected character "EOF"', '0:6'] - ]); + expect(tokenizeAndHumanizeErrors('઼')) + .toEqual([[HtmlTokenType.TEXT, 'Unexpected character "EOF"', '0:6']]); }); }); describe('regular text', () => { it('should parse text', () => { - expect(tokenizeAndHumanizeParts('a')).toEqual([ - [HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('a')) + .toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF]]); }); it('should handle CR & LF', () => { - expect(tokenizeAndHumanizeParts('t\ne\rs\r\nt')).toEqual([ - [HtmlTokenType.TEXT, 't\ne\ns\nt'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('t\ne\rs\r\nt')) + .toEqual([[HtmlTokenType.TEXT, 't\ne\ns\nt'], [HtmlTokenType.EOF]]); }); it('should parse entities', () => { - expect(tokenizeAndHumanizeParts('a&b')).toEqual([ - [HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('a&b')) + .toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]); }); it('should parse text starting with "&"', () => { - expect(tokenizeAndHumanizeParts('a && b &')).toEqual([ - [HtmlTokenType.TEXT, 'a && b &'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('a && b &')) + .toEqual([[HtmlTokenType.TEXT, 'a && b &'], [HtmlTokenType.EOF]]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans('a')).toEqual([ - [HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans('a')) + .toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF, '']]); }); it('should allow "<" in text nodes', () => { - expect(tokenizeAndHumanizeParts('{{ a < b ? c : d }}')).toEqual([ - [HtmlTokenType.TEXT, '{{ a < b ? c : d }}'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('{{ a < b ? c : d }}')) + .toEqual([[HtmlTokenType.TEXT, '{{ a < b ? c : d }}'], [HtmlTokenType.EOF]]); - expect(tokenizeAndHumanizeSourceSpans('<p>a<b</p>')).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '<p'], - [HtmlTokenType.TAG_OPEN_END, '>'], - [HtmlTokenType.TEXT, 'a<b'], - [HtmlTokenType.TAG_CLOSE, '</p>'], - [HtmlTokenType.EOF, ''], - ]); + expect(tokenizeAndHumanizeSourceSpans('<p>a<b</p>')) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '<p'], + [HtmlTokenType.TAG_OPEN_END, '>'], + [HtmlTokenType.TEXT, 'a<b'], + [HtmlTokenType.TAG_CLOSE, '</p>'], + [HtmlTokenType.EOF, ''], + ]); - expect(tokenizeAndHumanizeParts('< a>')).toEqual([ - [HtmlTokenType.TEXT, '< a>'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('< a>')) + .toEqual([[HtmlTokenType.TEXT, '< a>'], [HtmlTokenType.EOF]]); }); // TODO(vicb): make the lexer aware of Angular expressions // see https://github.com/angular/angular/issues/5679 it('should parse valid start tag in interpolation', () => { - expect(tokenizeAndHumanizeParts('{{ a <b && c > d }}')).toEqual([ - [HtmlTokenType.TEXT, '{{ a '], [HtmlTokenType.TAG_OPEN_START, null, 'b'], - [HtmlTokenType.ATTR_NAME, null, '&&'], [HtmlTokenType.ATTR_NAME, null, 'c'], - [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.TEXT, ' d }}'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts('{{ a <b && c > d }}')) + .toEqual([ + [HtmlTokenType.TEXT, '{{ a '], + [HtmlTokenType.TAG_OPEN_START, null, 'b'], + [HtmlTokenType.ATTR_NAME, null, '&&'], + [HtmlTokenType.ATTR_NAME, null, 'c'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.TEXT, ' d }}'], + [HtmlTokenType.EOF] + ]); }); }); describe('raw text', () => { it('should parse text', () => { - expect(tokenizeAndHumanizeParts(`<script>t\ne\rs\r\nt</script>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], [HtmlTokenType.TAG_CLOSE, null, 'script'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<script>t\ne\rs\r\nt</script>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'script'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], + [HtmlTokenType.TAG_CLOSE, null, 'script'], + [HtmlTokenType.EOF] + ]); }); it('should not detect entities', () => { - expect(tokenizeAndHumanizeParts(`<script>&</SCRIPT>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.RAW_TEXT, '&'], [HtmlTokenType.TAG_CLOSE, null, 'script'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<script>&</SCRIPT>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'script'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.RAW_TEXT, '&'], + [HtmlTokenType.TAG_CLOSE, null, 'script'], + [HtmlTokenType.EOF] + ]); }); it('should ignore other opening tags', () => { - expect(tokenizeAndHumanizeParts(`<script>a<div></script>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.RAW_TEXT, 'a<div>'], [HtmlTokenType.TAG_CLOSE, null, 'script'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<script>a<div></script>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'script'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.RAW_TEXT, 'a<div>'], + [HtmlTokenType.TAG_CLOSE, null, 'script'], + [HtmlTokenType.EOF] + ]); }); it('should ignore other closing tags', () => { - expect(tokenizeAndHumanizeParts(`<script>a</test></script>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.RAW_TEXT, 'a</test>'], [HtmlTokenType.TAG_CLOSE, null, 'script'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<script>a</test></script>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'script'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.RAW_TEXT, 'a</test>'], + [HtmlTokenType.TAG_CLOSE, null, 'script'], + [HtmlTokenType.EOF] + ]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '<script'], [HtmlTokenType.TAG_OPEN_END, '>'], - [HtmlTokenType.RAW_TEXT, 'a'], [HtmlTokenType.TAG_CLOSE, '</script>'], - [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '<script'], + [HtmlTokenType.TAG_OPEN_END, '>'], + [HtmlTokenType.RAW_TEXT, 'a'], + [HtmlTokenType.TAG_CLOSE, '</script>'], + [HtmlTokenType.EOF, ''] + ]); }); }); describe('escapable raw text', () => { it('should parse text', () => { - expect(tokenizeAndHumanizeParts(`<title>t\ne\rs\r\nt</title>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.ESCAPABLE_RAW_TEXT, 't\ne\ns\nt'], - [HtmlTokenType.TAG_CLOSE, null, 'title'], [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<title>t\ne\rs\r\nt</title>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'title'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.ESCAPABLE_RAW_TEXT, 't\ne\ns\nt'], + [HtmlTokenType.TAG_CLOSE, null, 'title'], + [HtmlTokenType.EOF] + ]); }); it('should detect entities', () => { - expect(tokenizeAndHumanizeParts(`<title>&</title>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.ESCAPABLE_RAW_TEXT, '&'], [HtmlTokenType.TAG_CLOSE, null, 'title'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<title>&</title>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'title'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.ESCAPABLE_RAW_TEXT, '&'], + [HtmlTokenType.TAG_CLOSE, null, 'title'], + [HtmlTokenType.EOF] + ]); }); it('should ignore other opening tags', () => { - expect(tokenizeAndHumanizeParts(`<title>a<div></title>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a<div>'], [HtmlTokenType.TAG_CLOSE, null, 'title'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<title>a<div></title>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'title'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a<div>'], + [HtmlTokenType.TAG_CLOSE, null, 'title'], + [HtmlTokenType.EOF] + ]); }); it('should ignore other closing tags', () => { - expect(tokenizeAndHumanizeParts(`<title>a</test></title>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END], - [HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a</test>'], [HtmlTokenType.TAG_CLOSE, null, 'title'], - [HtmlTokenType.EOF] - ]); + expect(tokenizeAndHumanizeParts(`<title>a</test></title>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, null, 'title'], + [HtmlTokenType.TAG_OPEN_END], + [HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a</test>'], + [HtmlTokenType.TAG_CLOSE, null, 'title'], + [HtmlTokenType.EOF] + ]); }); it('should store the locations', () => { - expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '<title'], [HtmlTokenType.TAG_OPEN_END, '>'], - [HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'], [HtmlTokenType.TAG_CLOSE, '</title>'], - [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '<title'], + [HtmlTokenType.TAG_OPEN_END, '>'], + [HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'], + [HtmlTokenType.TAG_CLOSE, '</title>'], + [HtmlTokenType.EOF, ''] + ]); }); }); describe('errors', () => { it('should include 2 lines of context in message', () => { - let src = '111\n222\n333\nE\n444\n555\n666\n'; + let src = "111\n222\n333\nE\n444\n555\n666\n"; let file = new ParseSourceFile(src, 'file://'); let location = new ParseLocation(file, 12, 123, 456); let span = new ParseSourceSpan(location, location); @@ -485,10 +590,14 @@ export function main() { describe('unicode characters', () => { it('should support unicode characters', () => { - expect(tokenizeAndHumanizeSourceSpans(`<p>Ä°</p>`)).toEqual([ - [HtmlTokenType.TAG_OPEN_START, '<p'], [HtmlTokenType.TAG_OPEN_END, '>'], - [HtmlTokenType.TEXT, 'Ä°'], [HtmlTokenType.TAG_CLOSE, '</p>'], [HtmlTokenType.EOF, ''] - ]); + expect(tokenizeAndHumanizeSourceSpans(`<p>Ä°</p>`)) + .toEqual([ + [HtmlTokenType.TAG_OPEN_START, '<p'], + [HtmlTokenType.TAG_OPEN_END, '>'], + [HtmlTokenType.TEXT, 'Ä°'], + [HtmlTokenType.TAG_CLOSE, '</p>'], + [HtmlTokenType.EOF, ''] + ]); }); }); @@ -517,14 +626,15 @@ function humanizeLineColumn(location: ParseLocation): string { } function tokenizeAndHumanizeLineColumn(input: string): any[] { - return tokenizeWithoutErrors(input).map( - token => [<any>token.type, humanizeLineColumn(token.sourceSpan.start)]); + return tokenizeWithoutErrors(input) + .map(token => [<any>token.type, humanizeLineColumn(token.sourceSpan.start)]); } function tokenizeAndHumanizeErrors(input: string): any[] { return tokenizeHtml(input, 'someUrl') - .errors.map( - tokenError => - [<any>tokenError.tokenType, tokenError.msg, - humanizeLineColumn(tokenError.span.start)]); + .errors.map(tokenError => [ + <any>tokenError.tokenType, + tokenError.msg, + humanizeLineColumn(tokenError.span.start) + ]); } diff --git a/modules/angular2/test/compiler/html_parser_spec.ts b/modules/angular2/test/compiler/html_parser_spec.ts index ab68c0e18d..3af628f315 100644 --- a/modules/angular2/test/compiler/html_parser_spec.ts +++ b/modules/angular2/test/compiler/html_parser_spec.ts @@ -1,8 +1,25 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {HtmlTokenType} from 'angular2/src/compiler/html_lexer'; import {HtmlParser, HtmlParseTreeResult, HtmlTreeError} from 'angular2/src/compiler/html_parser'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {ParseError, ParseLocation} from 'angular2/src/compiler/parse_util'; import {humanizeDom, humanizeDomSourceSpans, humanizeLineColumn} from './html_ast_spec_utils'; @@ -18,36 +35,31 @@ export function main() { }); it('should parse text nodes inside regular elements', () => { - expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1] - ]); + expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp'))) + .toEqual([[HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1]]); }); it('should parse text nodes inside template elements', () => { - expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'template', 0], [HtmlTextAst, 'a', 1] - ]); + expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp'))) + .toEqual([[HtmlElementAst, 'template', 0], [HtmlTextAst, 'a', 1]]); }); it('should parse CDATA', () => { - expect(humanizeDom(parser.parse('<![CDATA[text]]>', 'TestComp'))).toEqual([ - [HtmlTextAst, 'text', 0] - ]); + expect(humanizeDom(parser.parse('<![CDATA[text]]>', 'TestComp'))) + .toEqual([[HtmlTextAst, 'text', 0]]); }); }); describe('elements', () => { it('should parse root level elements', () => { - expect(humanizeDom(parser.parse('<div></div>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'div', 0] - ]); + expect(humanizeDom(parser.parse('<div></div>', 'TestComp'))) + .toEqual([[HtmlElementAst, 'div', 0]]); }); it('should parse elements inside of regular elements', () => { - expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'div', 0], [HtmlElementAst, 'span', 1] - ]); + expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp'))) + .toEqual([[HtmlElementAst, 'div', 0], [HtmlElementAst, 'span', 1]]); }); it('should parse elements inside of template elements', () => { @@ -78,22 +90,24 @@ export function main() { }); it('should close void elements on text nodes', () => { - expect(humanizeDom(parser.parse('<p>before<br>after</p>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'p', 0], - [HtmlTextAst, 'before', 1], - [HtmlElementAst, 'br', 1], - [HtmlTextAst, 'after', 1], - ]); + expect(humanizeDom(parser.parse('<p>before<br>after</p>', 'TestComp'))) + .toEqual([ + [HtmlElementAst, 'p', 0], + [HtmlTextAst, 'before', 1], + [HtmlElementAst, 'br', 1], + [HtmlTextAst, 'after', 1], + ]); }); it('should support optional end tags', () => { - expect(humanizeDom(parser.parse('<div><p>1<p>2</div>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'div', 0], - [HtmlElementAst, 'p', 1], - [HtmlTextAst, '1', 2], - [HtmlElementAst, 'p', 1], - [HtmlTextAst, '2', 2], - ]); + expect(humanizeDom(parser.parse('<div><p>1<p>2</div>', 'TestComp'))) + .toEqual([ + [HtmlElementAst, 'div', 0], + [HtmlElementAst, 'p', 1], + [HtmlTextAst, '1', 2], + [HtmlElementAst, 'p', 1], + [HtmlTextAst, '2', 2], + ]); }); it('should support nested elements', () => { @@ -112,59 +126,63 @@ export function main() { '<table><thead><tr head></tr></thead><tr noparent></tr><tbody><tr body></tr></tbody><tfoot><tr foot></tr></tfoot></table>', 'TestComp'))) .toEqual([ - [HtmlElementAst, 'table', 0], [HtmlElementAst, 'thead', 1], - [HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'head', ''], [HtmlElementAst, 'tbody', 1], - [HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'noparent', ''], - [HtmlElementAst, 'tbody', 1], [HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'body', ''], - [HtmlElementAst, 'tfoot', 1], [HtmlElementAst, 'tr', 2], + [HtmlElementAst, 'table', 0], + [HtmlElementAst, 'thead', 1], + [HtmlElementAst, 'tr', 2], + [HtmlAttrAst, 'head', ''], + [HtmlElementAst, 'tbody', 1], + [HtmlElementAst, 'tr', 2], + [HtmlAttrAst, 'noparent', ''], + [HtmlElementAst, 'tbody', 1], + [HtmlElementAst, 'tr', 2], + [HtmlAttrAst, 'body', ''], + [HtmlElementAst, 'tfoot', 1], + [HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'foot', ''] ]); }); it('should not add the requiredParent when the parent is a template', () => { - expect(humanizeDom(parser.parse('<template><tr></tr></template>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'template', 0], - [HtmlElementAst, 'tr', 1], - ]); + expect(humanizeDom(parser.parse('<template><tr></tr></template>', 'TestComp'))) + .toEqual([ + [HtmlElementAst, 'template', 0], + [HtmlElementAst, 'tr', 1], + ]); }); it('should support explicit mamespace', () => { - expect(humanizeDom(parser.parse('<myns:div></myns:div>', 'TestComp'))).toEqual([ - [HtmlElementAst, '@myns:div', 0] - ]); + expect(humanizeDom(parser.parse('<myns:div></myns:div>', 'TestComp'))) + .toEqual([[HtmlElementAst, '@myns:div', 0]]); }); it('should support implicit mamespace', () => { - expect(humanizeDom(parser.parse('<svg></svg>', 'TestComp'))).toEqual([ - [HtmlElementAst, '@svg:svg', 0] - ]); + expect(humanizeDom(parser.parse('<svg></svg>', 'TestComp'))) + .toEqual([[HtmlElementAst, '@svg:svg', 0]]); }); it('should propagate the namespace', () => { - expect(humanizeDom(parser.parse('<myns:div><p></p></myns:div>', 'TestComp'))).toEqual([ - [HtmlElementAst, '@myns:div', 0], [HtmlElementAst, '@myns:p', 1] - ]); + expect(humanizeDom(parser.parse('<myns:div><p></p></myns:div>', 'TestComp'))) + .toEqual([[HtmlElementAst, '@myns:div', 0], [HtmlElementAst, '@myns:p', 1]]); }); it('should match closing tags case sensitive', () => { let errors = parser.parse('<DiV><P></p></dIv>', 'TestComp').errors; expect(errors.length).toEqual(2); - expect(humanizeErrors(errors)).toEqual([ - ['p', 'Unexpected closing tag "p"', '0:8'], - ['dIv', 'Unexpected closing tag "dIv"', '0:12'], - ]); + expect(humanizeErrors(errors)) + .toEqual([ + ['p', 'Unexpected closing tag "p"', '0:8'], + ['dIv', 'Unexpected closing tag "dIv"', '0:12'], + ]); }); it('should support self closing void elements', () => { - expect(humanizeDom(parser.parse('<input />', 'TestComp'))).toEqual([ - [HtmlElementAst, 'input', 0] - ]); + expect(humanizeDom(parser.parse('<input />', 'TestComp'))) + .toEqual([[HtmlElementAst, 'input', 0]]); }); it('should support self closing foreign elements', () => { - expect(humanizeDom(parser.parse('<math />', 'TestComp'))).toEqual([ - [HtmlElementAst, '@math:math', 0] - ]); + expect(humanizeDom(parser.parse('<math />', 'TestComp'))) + .toEqual([[HtmlElementAst, '@math:math', 0]]); }); it('should ignore LF immediately after textarea, pre and listing', () => { @@ -186,43 +204,39 @@ export function main() { describe('attributes', () => { it('should parse attributes on regular elements case sensitive', () => { - expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'div', 0], - [HtmlAttrAst, 'kEy', 'v'], - [HtmlAttrAst, 'key2', 'v2'], - ]); + expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp'))) + .toEqual([ + [HtmlElementAst, 'div', 0], + [HtmlAttrAst, 'kEy', 'v'], + [HtmlAttrAst, 'key2', 'v2'], + ]); }); it('should parse attributes without values', () => { - expect(humanizeDom(parser.parse('<div k></div>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'div', 0], [HtmlAttrAst, 'k', ''] - ]); + expect(humanizeDom(parser.parse('<div k></div>', 'TestComp'))) + .toEqual([[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'k', '']]); }); it('should parse attributes on svg elements case sensitive', () => { - expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp'))).toEqual([ - [HtmlElementAst, '@svg:svg', 0], [HtmlAttrAst, 'viewBox', '0'] - ]); + expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp'))) + .toEqual([[HtmlElementAst, '@svg:svg', 0], [HtmlAttrAst, 'viewBox', '0']]); }); it('should parse attributes on template elements', () => { - expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp'))).toEqual([ - [HtmlElementAst, 'template', 0], [HtmlAttrAst, 'k', 'v'] - ]); + expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp'))) + .toEqual([[HtmlElementAst, 'template', 0], [HtmlAttrAst, 'k', 'v']]); }); it('should support mamespace', () => { - expect(humanizeDom(parser.parse('<svg:use xlink:href="Port" />', 'TestComp'))).toEqual([ - [HtmlElementAst, '@svg:use', 0], [HtmlAttrAst, '@xlink:href', 'Port'] - ]); + expect(humanizeDom(parser.parse('<svg:use xlink:href="Port" />', 'TestComp'))) + .toEqual([[HtmlElementAst, '@svg:use', 0], [HtmlAttrAst, '@xlink:href', 'Port']]); }); }); describe('comments', () => { it('should preserve comments', () => { - expect(humanizeDom(parser.parse('<!-- comment --><div></div>', 'TestComp'))).toEqual([ - [HtmlCommentAst, 'comment', 0], [HtmlElementAst, 'div', 0] - ]); + expect(humanizeDom(parser.parse('<!-- comment --><div></div>', 'TestComp'))) + .toEqual([[HtmlCommentAst, 'comment', 0], [HtmlElementAst, 'div', 0]]); }); }); @@ -261,34 +275,34 @@ export function main() { it('should report closing tag for void elements', () => { let errors = parser.parse('<input></input>', 'TestComp').errors; expect(errors.length).toEqual(1); - expect(humanizeErrors(errors)).toEqual([ - ['input', 'Void elements do not have end tags "input"', '0:7'] - ]); + expect(humanizeErrors(errors)) + .toEqual([['input', 'Void elements do not have end tags "input"', '0:7']]); }); it('should report self closing html element', () => { let errors = parser.parse('<p />', 'TestComp').errors; expect(errors.length).toEqual(1); - expect(humanizeErrors(errors)).toEqual([ - ['p', 'Only void and foreign elements can be self closed "p"', '0:0'] - ]); + expect(humanizeErrors(errors)) + .toEqual([['p', 'Only void and foreign elements can be self closed "p"', '0:0']]); }); it('should report self closing custom element', () => { let errors = parser.parse('<my-cmp />', 'TestComp').errors; expect(errors.length).toEqual(1); - expect(humanizeErrors(errors)).toEqual([ - ['my-cmp', 'Only void and foreign elements can be self closed "my-cmp"', '0:0'] - ]); + expect(humanizeErrors(errors)) + .toEqual([ + ['my-cmp', 'Only void and foreign elements can be self closed "my-cmp"', '0:0'] + ]); }); it('should also report lexer errors', () => { let errors = parser.parse('<!-err--><div></p></div>', 'TestComp').errors; expect(errors.length).toEqual(2); - expect(humanizeErrors(errors)).toEqual([ - [HtmlTokenType.COMMENT_START, 'Unexpected character "e"', '0:3'], - ['p', 'Unexpected closing tag "p"', '0:14'] - ]); + expect(humanizeErrors(errors)) + .toEqual([ + [HtmlTokenType.COMMENT_START, 'Unexpected character "e"', '0:3'], + ['p', 'Unexpected closing tag "p"', '0:14'] + ]); }); }); }); diff --git a/modules/angular2/test/compiler/legacy_template_spec.ts b/modules/angular2/test/compiler/legacy_template_spec.ts index d88e169e88..37ef47c32f 100644 --- a/modules/angular2/test/compiler/legacy_template_spec.ts +++ b/modules/angular2/test/compiler/legacy_template_spec.ts @@ -1,6 +1,26 @@ -import {TestComponentBuilder, AsyncTestCompleter, ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, beforeEachProviders, inject} from 'angular2/testing_internal'; +import { + TestComponentBuilder, + AsyncTestCompleter, + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + beforeEachProviders, + inject +} from 'angular2/testing_internal'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {LegacyHtmlAstTransformer} from 'angular2/src/compiler/legacy_template'; diff --git a/modules/angular2/test/compiler/runtime_compiler_spec.ts b/modules/angular2/test/compiler/runtime_compiler_spec.ts index 4a3895b49c..30428557ff 100644 --- a/modules/angular2/test/compiler/runtime_compiler_spec.ts +++ b/modules/angular2/test/compiler/runtime_compiler_spec.ts @@ -1,4 +1,17 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {Component, provide} from 'angular2/core'; import {PromiseWrapper} from 'angular2/src/facade/async'; @@ -25,10 +38,11 @@ export function main() { it('compileInHost should compile the template via TemplateCompiler', inject([AsyncTestCompleter], (async) => { - compiler.compileInHost(SomeComponent).then((hostViewFactoryRef) => { - expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); - async.done(); - }); + compiler.compileInHost(SomeComponent) + .then((hostViewFactoryRef) => { + expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); + async.done(); + }); })); it('should clear the cache', () => { diff --git a/modules/angular2/test/compiler/runtime_metadata_fixture.ts b/modules/angular2/test/compiler/runtime_metadata_fixture.ts index b8e19b7188..74a0a650f3 100644 --- a/modules/angular2/test/compiler/runtime_metadata_fixture.ts +++ b/modules/angular2/test/compiler/runtime_metadata_fixture.ts @@ -1,5 +1,5 @@ import {Component} from 'angular2/core'; -@Component({styles: <any>('foo'), template: ''}) +@Component({styles:<any>('foo'), template: ''}) export class MalformedStylesComponent { } diff --git a/modules/angular2/test/compiler/runtime_metadata_spec.ts b/modules/angular2/test/compiler/runtime_metadata_spec.ts index f66faf9d05..231d022720 100644 --- a/modules/angular2/test/compiler/runtime_metadata_spec.ts +++ b/modules/angular2/test/compiler/runtime_metadata_spec.ts @@ -1,9 +1,37 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {stringify} from 'angular2/src/facade/lang'; import {RuntimeMetadataResolver} from 'angular2/src/compiler/runtime_metadata'; import {LifecycleHooks, LIFECYCLE_HOOKS_VALUES} from 'angular2/src/core/linker/interfaces'; -import {Component, Directive, ViewEncapsulation, ChangeDetectionStrategy, OnChanges, OnInit, DoCheck, OnDestroy, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, SimpleChange, provide} from 'angular2/core'; +import { + Component, + Directive, + ViewEncapsulation, + ChangeDetectionStrategy, + OnChanges, + OnInit, + DoCheck, + OnDestroy, + AfterContentInit, + AfterContentChecked, + AfterViewInit, + AfterViewChecked, + SimpleChange, + provide +} from 'angular2/core'; import {TEST_PROVIDERS} from './test_bindings'; import {MODULE_SUFFIX} from 'angular2/src/compiler/util'; @@ -65,7 +93,7 @@ export function main() { .toContain(resolver.getDirectiveMetadata(SomeDirective)); })); - describe('platform directives', () => { + describe("platform directives", () => { beforeEachProviders( () => [provide(PLATFORM_DIRECTIVES, {useValue: [ADirective], multi: true})]); diff --git a/modules/angular2/test/compiler/schema/dom_element_schema_registry_spec.ts b/modules/angular2/test/compiler/schema/dom_element_schema_registry_spec.ts index 516028668b..57c32b8a76 100644 --- a/modules/angular2/test/compiler/schema/dom_element_schema_registry_spec.ts +++ b/modules/angular2/test/compiler/schema/dom_element_schema_registry_spec.ts @@ -1,4 +1,14 @@ -import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + beforeEach, + ddescribe, + xdescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; import {IS_DART} from 'angular2/src/facade/lang'; import {DomElementSchemaRegistry} from 'angular2/src/compiler/schema/dom_element_schema_registry'; diff --git a/modules/angular2/test/compiler/schema_registry_mock.ts b/modules/angular2/test/compiler/schema_registry_mock.ts index 68ff019d5b..57618e856c 100644 --- a/modules/angular2/test/compiler/schema_registry_mock.ts +++ b/modules/angular2/test/compiler/schema_registry_mock.ts @@ -2,9 +2,8 @@ import {ElementSchemaRegistry} from 'angular2/src/compiler/schema/element_schema import {isPresent} from 'angular2/src/facade/lang'; export class MockSchemaRegistry implements ElementSchemaRegistry { - constructor( - public existingProperties: {[key: string]: boolean}, - public attrPropMapping: {[key: string]: string}) {} + constructor(public existingProperties: {[key: string]: boolean}, + public attrPropMapping: {[key: string]: string}) {} hasProperty(tagName: string, property: string): boolean { var result = this.existingProperties[property]; return isPresent(result) ? result : true; diff --git a/modules/angular2/test/compiler/selector_spec.ts b/modules/angular2/test/compiler/selector_spec.ts index b3a1a22679..45204d09c0 100644 --- a/modules/angular2/test/compiler/selector_spec.ts +++ b/modules/angular2/test/compiler/selector_spec.ts @@ -72,20 +72,20 @@ export function main() { expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); - expect(matcher.match( - CssSelector.parse('[someAttr=someValue][someAttr2]')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('[someAttr=someValue][someAttr2]')[0], + selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); - expect(matcher.match( - CssSelector.parse('[someAttr2][someAttr=someValue]')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('[someAttr2][someAttr=someValue]')[0], + selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); - expect(matcher.match( - CssSelector.parse('[someAttr2=someValue][someAttr]')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('[someAttr2=someValue][someAttr]')[0], + selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); }); @@ -120,20 +120,18 @@ export function main() { it('should select by element name, class name and attribute name with value', () => { matcher.addSelectables(s1 = CssSelector.parse('someTag.someClass[someAttr=someValue]'), 1); - expect(matcher.match( - CssSelector.parse('someOtherTag.someOtherClass[someOtherAttr]')[0], - selectableCollector)) + expect(matcher.match(CssSelector.parse('someOtherTag.someOtherClass[someOtherAttr]')[0], + selectableCollector)) .toEqual(false); expect(matched).toEqual([]); - expect( - matcher.match( - CssSelector.parse('someTag.someOtherClass[someOtherAttr]')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('someTag.someOtherClass[someOtherAttr]')[0], + selectableCollector)) .toEqual(false); expect(matched).toEqual([]); - expect(matcher.match( - CssSelector.parse('someTag.someClass[someOtherAttr]')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('someTag.someClass[someOtherAttr]')[0], + selectableCollector)) .toEqual(false); expect(matched).toEqual([]); @@ -142,9 +140,8 @@ export function main() { .toEqual(false); expect(matched).toEqual([]); - expect( - matcher.match( - CssSelector.parse('someTag.someClass[someAttr=someValue]')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('someTag.someClass[someAttr=someValue]')[0], + selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1]); }); @@ -205,8 +202,8 @@ export function main() { matcher.addSelectables(s3 = CssSelector.parse(':not(.someClass)'), 3); matcher.addSelectables(s4 = CssSelector.parse(':not(.someOtherClass[someAttr])'), 4); - expect(matcher.match( - CssSelector.parse('p[someOtherAttr].someOtherClass')[0], selectableCollector)) + expect(matcher.match(CssSelector.parse('p[someOtherAttr].someOtherClass')[0], + selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2, s3[0], 3, s4[0], 4]); }); @@ -300,7 +297,7 @@ export function main() { it('should detect :not without truthy', () => { var cssSelector = CssSelector.parse(':not([attrname=attrvalue].someclass)')[0]; - expect(cssSelector.element).toEqual('*'); + expect(cssSelector.element).toEqual("*"); var notSelector = cssSelector.notSelectors[0]; expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']); @@ -310,15 +307,13 @@ export function main() { }); it('should throw when nested :not', () => { - expect(() => { - CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')[0]; - }).toThrowError('Nesting :not is not allowed in a selector'); + expect(() => { CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')[0]; }) + .toThrowError('Nesting :not is not allowed in a selector'); }); it('should throw when multiple selectors in :not', () => { - expect(() => { - CssSelector.parse('sometag:not(a,b)'); - }).toThrowError('Multiple selectors in :not are not supported'); + expect(() => { CssSelector.parse('sometag:not(a,b)'); }) + .toThrowError('Multiple selectors in :not are not supported'); }); it('should detect lists of selectors', () => { diff --git a/modules/angular2/test/compiler/shadow_css_spec.ts b/modules/angular2/test/compiler/shadow_css_spec.ts index 6c3e073cbe..19790e4d75 100644 --- a/modules/angular2/test/compiler/shadow_css_spec.ts +++ b/modules/angular2/test/compiler/shadow_css_spec.ts @@ -1,4 +1,14 @@ -import {describe, beforeEach, it, expect, ddescribe, iit, SpyObject, el, normalizeCSS} from 'angular2/testing_internal'; +import { + describe, + beforeEach, + it, + expect, + ddescribe, + iit, + SpyObject, + el, + normalizeCSS +} from 'angular2/testing_internal'; import {ShadowCss, processRules, CssRule} from 'angular2/src/compiler/shadow_css'; import {RegExpWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang'; @@ -96,7 +106,7 @@ export function main() { }); it('should support polyfill-next-selector', () => { - var css = s('polyfill-next-selector {content: \'x > y\'} z {}', 'a'); + var css = s("polyfill-next-selector {content: 'x > y'} z {}", 'a'); expect(css).toEqual('x[a] > y[a]{}'); css = s('polyfill-next-selector {content: "x > y"} z {}', 'a'); @@ -104,7 +114,7 @@ export function main() { }); it('should support polyfill-unscoped-rule', () => { - var css = s('polyfill-unscoped-rule {content: \'#menu > .bar\';color: blue;}', 'a'); + var css = s("polyfill-unscoped-rule {content: '#menu > .bar';color: blue;}", 'a'); expect(StringWrapper.contains(css, '#menu > .bar {;color:blue;}')).toBeTruthy(); css = s('polyfill-unscoped-rule {content: "#menu > .bar";color: blue;}', 'a'); @@ -112,16 +122,15 @@ export function main() { }); it('should support multiple instances polyfill-unscoped-rule', () => { - var css = - s('polyfill-unscoped-rule {content: \'foo\';color: blue;}' + - 'polyfill-unscoped-rule {content: \'bar\';color: blue;}', - 'a'); + var css = s("polyfill-unscoped-rule {content: 'foo';color: blue;}" + + "polyfill-unscoped-rule {content: 'bar';color: blue;}", + 'a'); expect(StringWrapper.contains(css, 'foo {;color:blue;}')).toBeTruthy(); expect(StringWrapper.contains(css, 'bar {;color:blue;}')).toBeTruthy(); }); it('should support polyfill-rule', () => { - var css = s('polyfill-rule {content: \':host.foo .bar\';color: blue;}', 'a', 'a-host'); + var css = s("polyfill-rule {content: ':host.foo .bar';color: blue;}", 'a', 'a-host'); expect(css).toEqual('[a-host].foo .bar {;color:blue;}'); css = s('polyfill-rule {content: ":host.foo .bar";color:blue;}', 'a', 'a-host'); @@ -190,29 +199,26 @@ export function main() { () => { expect(captureRules('a {b}')).toEqual([new CssRule('a', 'b')]); }); it('should capture css rules with nested rules', () => { - expect(captureRules('a {b {c}} d {e}')).toEqual([ - new CssRule('a', 'b {c}'), new CssRule('d', 'e') - ]); + expect(captureRules('a {b {c}} d {e}')) + .toEqual([new CssRule('a', 'b {c}'), new CssRule('d', 'e')]); }); it('should capture multiple rules where some have no body', () => { - expect(captureRules('@import a ; b {c}')).toEqual([ - new CssRule('@import a', ''), new CssRule('b', 'c') - ]); + expect(captureRules('@import a ; b {c}')) + .toEqual([new CssRule('@import a', ''), new CssRule('b', 'c')]); }); }); describe('modify rules', () => { it('should allow to change the selector while preserving whitespaces', () => { - expect(processRules( - '@import a; b {c {d}} e {f}', - (cssRule) => new CssRule(cssRule.selector + '2', cssRule.content))) + expect(processRules('@import a; b {c {d}} e {f}', + (cssRule) => new CssRule(cssRule.selector + '2', cssRule.content))) .toEqual('@import a2; b2 {c {d}} e2 {f}'); }); it('should allow to change the content', () => { - expect(processRules( - 'a {b}', (cssRule) => new CssRule(cssRule.selector, cssRule.content + '2'))) + expect(processRules('a {b}', + (cssRule) => new CssRule(cssRule.selector, cssRule.content + '2'))) .toEqual('a {b2}'); }); }); diff --git a/modules/angular2/test/compiler/source_module_spec.ts b/modules/angular2/test/compiler/source_module_spec.ts index 2aa1f1aad8..b554ee38f2 100644 --- a/modules/angular2/test/compiler/source_module_spec.ts +++ b/modules/angular2/test/compiler/source_module_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + TestComponentBuilder +} from 'angular2/testing_internal'; import {SourceModule, moduleRef} from 'angular2/src/compiler/source_module'; diff --git a/modules/angular2/test/compiler/static_reflector_spec.ts b/modules/angular2/test/compiler/static_reflector_spec.ts index 473e4f593e..fcb361a551 100644 --- a/modules/angular2/test/compiler/static_reflector_spec.ts +++ b/modules/angular2/test/compiler/static_reflector_spec.ts @@ -1,4 +1,17 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {StaticReflector, StaticReflectorHost} from 'angular2/src/compiler/static_reflector'; @@ -21,8 +34,8 @@ export function main() { let reflector = new StaticReflector(host); let NgFor = reflector.getStaticType('angular2/src/common/directives/ng_for', 'NgFor'); - let ViewContainerRef = reflector.getStaticType( - 'angular2/src/core/linker/view_container_ref', 'ViewContainerRef'); + let ViewContainerRef = reflector.getStaticType('angular2/src/core/linker/view_container_ref', + 'ViewContainerRef'); let TemplateRef = reflector.getStaticType('angular2/src/core/linker/template_ref', 'TemplateRef'); let IterableDiffers = reflector.getStaticType( @@ -31,9 +44,8 @@ export function main() { 'angular2/src/core/change_detection/change_detector_ref', 'ChangeDetectorRef'); let parameters = reflector.parameters(NgFor); - expect(parameters).toEqual([ - ViewContainerRef, TemplateRef, IterableDiffers, ChangeDetectorRef - ]); + expect(parameters) + .toEqual([ViewContainerRef, TemplateRef, IterableDiffers, ChangeDetectorRef]); }); it('should get annotations for HeroDetailComponent', () => { @@ -64,7 +76,7 @@ export function main() { expect(reflector.simplify('', 1)).toBe(1); expect(reflector.simplify('', true)).toBe(true); - expect(reflector.simplify('', 'some value')).toBe('some value'); + expect(reflector.simplify('', "some value")).toBe("some value"); }); it('should simplify an array into a copy of the array', () => { @@ -84,261 +96,196 @@ export function main() { it('should simplify &&', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '&&', left: true, right: true}))) - .toBe(true); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '&&', left: true, right: false}))) - .toBe(false); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '&&', left: false, right: true}))) - .toBe(false); - expect(reflector.simplify( - '', ({__symbolic: 'binop', operator: '&&', left: false, right: false}))) - .toBe(false); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: true, right: true}))).toBe(true); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: true, right: false}))).toBe(false); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: false, right: true}))).toBe(false); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: false, right: false}))).toBe(false); }); it('should simplify ||', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '||', left: true, right: true}))) - .toBe(true); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '||', left: true, right: false}))) - .toBe(true); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '||', left: false, right: true}))) - .toBe(true); - expect(reflector.simplify( - '', ({__symbolic: 'binop', operator: '||', left: false, right: false}))) - .toBe(false); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: true, right: true}))).toBe(true); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: true, right: false}))).toBe(true); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: false, right: true}))).toBe(true); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: false, right: false}))).toBe(false); }); it('should simplify &', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '&', left: 0x22, right: 0x0F}))) - .toBe(0x22 & 0x0F); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '&', left: 0x22, right: 0xF0}))) - .toBe(0x22 & 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&', left: 0x22, right: 0x0F}))).toBe(0x22 & 0x0F); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&', left: 0x22, right: 0xF0}))).toBe(0x22 & 0xF0); }); it('should simplify |', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F}))) - .toBe(0x22 | 0x0F); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0}))) - .toBe(0x22 | 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F}))).toBe(0x22 | 0x0F); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0}))).toBe(0x22 | 0xF0); }); it('should simplify ^', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F}))) - .toBe(0x22 | 0x0F); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0}))) - .toBe(0x22 | 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F}))).toBe(0x22 | 0x0F); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0}))).toBe(0x22 | 0xF0); }); it('should simplify ==', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '==', left: 0x22, right: 0x22}))) - .toBe(0x22 == 0x22); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '==', left: 0x22, right: 0xF0}))) - .toBe(0x22 == 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '==', left: 0x22, right: 0x22}))).toBe(0x22 == 0x22); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '==', left: 0x22, right: 0xF0}))).toBe(0x22 == 0xF0); }); it('should simplify !=', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '!=', left: 0x22, right: 0x22}))) - .toBe(0x22 != 0x22); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '!=', left: 0x22, right: 0xF0}))) - .toBe(0x22 != 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!=', left: 0x22, right: 0x22}))).toBe(0x22 != 0x22); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!=', left: 0x22, right: 0xF0}))).toBe(0x22 != 0xF0); }); it('should simplify ===', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '===', left: 0x22, right: 0x22}))) - .toBe(0x22 === 0x22); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '===', left: 0x22, right: 0xF0}))) - .toBe(0x22 === 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '===', left: 0x22, right: 0x22}))).toBe(0x22 === 0x22); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '===', left: 0x22, right: 0xF0}))).toBe(0x22 === 0xF0); }); it('should simplify !==', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '!==', left: 0x22, right: 0x22}))) - .toBe(0x22 !== 0x22); - expect( - reflector.simplify('', ({__symbolic: 'binop', operator: '!==', left: 0x22, right: 0xF0}))) - .toBe(0x22 !== 0xF0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!==', left: 0x22, right: 0x22}))).toBe(0x22 !== 0x22); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!==', left: 0x22, right: 0xF0}))).toBe(0x22 !== 0xF0); }); it('should simplify >', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>', left: 1, right: 1}))) - .toBe(1 > 1); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>', left: 1, right: 0}))) - .toBe(1 > 0); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>', left: 0, right: 1}))) - .toBe(0 > 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>', left: 1, right: 1}))).toBe(1 > 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>', left: 1, right: 0}))).toBe(1 > 0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>', left: 0, right: 1}))).toBe(0 > 1); }); it('should simplify >=', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>=', left: 1, right: 1}))) - .toBe(1 >= 1); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>=', left: 1, right: 0}))) - .toBe(1 >= 0); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>=', left: 0, right: 1}))) - .toBe(0 >= 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>=', left: 1, right: 1}))).toBe(1 >= 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>=', left: 1, right: 0}))).toBe(1 >= 0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>=', left: 0, right: 1}))).toBe(0 >= 1); }); it('should simplify <=', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<=', left: 1, right: 1}))) - .toBe(1 <= 1); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<=', left: 1, right: 0}))) - .toBe(1 <= 0); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<=', left: 0, right: 1}))) - .toBe(0 <= 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<=', left: 1, right: 1}))).toBe(1 <= 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<=', left: 1, right: 0}))).toBe(1 <= 0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<=', left: 0, right: 1}))).toBe(0 <= 1); }); it('should simplify <', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<', left: 1, right: 1}))) - .toBe(1 < 1); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<', left: 1, right: 0}))) - .toBe(1 < 0); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<', left: 0, right: 1}))) - .toBe(0 < 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<', left: 1, right: 1}))).toBe(1 < 1); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<', left: 1, right: 0}))).toBe(1 < 0); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<', left: 0, right: 1}))).toBe(0 < 1); }); it('should simplify <<', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<<', left: 0x55, right: 2}))) - .toBe(0x55 << 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<<', left: 0x55, right: 2}))).toBe(0x55 << 2); }); it('should simplify >>', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>>', left: 0x55, right: 2}))) - .toBe(0x55 >> 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>>', left: 0x55, right: 2}))).toBe(0x55 >> 2); }); it('should simplify +', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '+', left: 0x55, right: 2}))) - .toBe(0x55 + 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '+', left: 0x55, right: 2}))).toBe(0x55 + 2); }); it('should simplify -', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '-', left: 0x55, right: 2}))) - .toBe(0x55 - 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '-', left: 0x55, right: 2}))).toBe(0x55 - 2); }); it('should simplify *', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '*', left: 0x55, right: 2}))) - .toBe(0x55 * 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '*', left: 0x55, right: 2}))).toBe(0x55 * 2); }); it('should simplify /', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '/', left: 0x55, right: 2}))) - .toBe(0x55 / 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '/', left: 0x55, right: 2}))).toBe(0x55 / 2); }); it('should simplify %', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'binop', operator: '%', left: 0x55, right: 2}))) - .toBe(0x55 % 2); + expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '%', left: 0x55, right: 2}))).toBe(0x55 % 2); }); it('should simplify prefix -', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'pre', operator: '-', operand: 2}))).toBe(-2); + expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '-', operand: 2}))).toBe(-2); }); it('should simplify prefix ~', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'pre', operator: '~', operand: 2}))).toBe(~2); + expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '~', operand: 2}))).toBe(~2); }); it('should simplify prefix !', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'pre', operator: '!', operand: true}))) - .toBe(!true); - expect(reflector.simplify('', ({__symbolic: 'pre', operator: '!', operand: false}))) - .toBe(!false); + expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '!', operand: true}))).toBe(!true); + expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '!', operand: false}))).toBe(!false); }); it('should simpify an array index', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - expect(reflector.simplify('', ({__symbolic: 'index', expression: [1, 2, 3], index: 2}))) + expect(reflector.simplify('', ({__symbolic: "index", expression: [1, 2, 3], index: 2}))) .toBe(3); }); it('should simplify an object index', () => { let host = new MockReflectorHost(); let reflector = new StaticReflector(host); - let expr = {__symbolic: 'select', expression: {a: 1, b: 2, c: 3}, member: 'b'}; + let expr = {__symbolic: "select", expression: {a: 1, b: 2, c: 3}, member: "b"}; expect(reflector.simplify('', expr)).toBe(2); }); @@ -347,8 +294,8 @@ export function main() { let reflector = new StaticReflector(host); expect( - reflector.simplify('./cases', ({__symbolic: 'reference', module: './extern', name: 's'}))) - .toEqual('s'); + reflector.simplify('./cases', ({__symbolic: "reference", module: "./extern", name: "s"}))) + .toEqual("s"); }); }); } @@ -356,101 +303,139 @@ export function main() { class MockReflectorHost implements StaticReflectorHost { getMetadataFor(moduleId: string): any { return { - 'angular2/src/common/directives/ng_for': { - '__symbolic': 'module', - 'module': './ng_for', - 'metadata': { - 'NgFor': { - '__symbolic': 'class', - 'decorators': [{ - '__symbolic': 'call', - 'expression': - {'__symbolic': 'reference', 'name': 'Directive', 'module': '../../core/metadata'}, - 'arguments': [{ - 'selector': '[ngFor][ngForOf]', - 'inputs': ['ngForTrackBy', 'ngForOf', 'ngForTemplate'] - }] - }], - 'members': { - '__ctor__': [{ - '__symbolic': 'constructor', - 'parameters': [ - { - '__symbolic': 'reference', - 'module': '../../core/linker/view_container_ref', - 'name': 'ViewContainerRef' - }, - { - '__symbolic': 'reference', - 'module': '../../core/linker/template_ref', - 'name': 'TemplateRef' - }, - { - '__symbolic': 'reference', - 'module': '../../core/change_detection/differs/iterable_differs', - 'name': 'IterableDiffers' - }, - { - '__symbolic': 'reference', - 'module': '../../core/change_detection/change_detector_ref', - 'name': 'ChangeDetectorRef' - } - ] - }] - } - } - } - }, - 'angular2/src/core/linker/view_container_ref': { - 'module': './view_container_ref', - 'metadata': {'ViewContainerRef': {'__symbolic': 'class'}} - }, - 'angular2/src/core/linker/template_ref': - {'module': './template_ref', 'metadata': {'TemplateRef': {'__symbolic': 'class'}}}, - 'angular2/src/core/change_detection/differs/iterable_differs': { - 'module': './iterable_differs', - 'metadata': {'IterableDiffers': {'__symbolic': 'class'}} - }, - 'angular2/src/core/change_detection/change_detector_ref': { - 'module': './change_detector_ref', - 'metadata': {'ChangeDetectorRef': {'__symbolic': 'class'}} - }, - './app/hero-detail.component': { - '__symbolic': 'module', - 'module': './hero-detail.component', - 'metadata': { - 'HeroDetailComponent': { - '__symbolic': 'class', - 'decorators': [{ - '__symbolic': 'call', - 'expression': { - '__symbolic': 'reference', - 'name': 'Component', - 'module': 'angular2/src/core/metadata' + 'angular2/src/common/directives/ng_for': + { + "__symbolic": "module", + "module": "./ng_for", + "metadata": + { + "NgFor": + { + "__symbolic": "class", + "decorators": + [ + { + "__symbolic": "call", + "expression": { + "__symbolic": "reference", + "name": "Directive", + "module": "../../core/metadata" + }, + "arguments": + [ + { + "selector": "[ngFor][ngForOf]", + "inputs": ["ngForTrackBy", "ngForOf", "ngForTemplate"] + } + ] + } + ], + "members": + { + "__ctor__": [ + { + "__symbolic": "constructor", + "parameters": + [ + { + "__symbolic": "reference", + "module": "../../core/linker/view_container_ref", + "name": "ViewContainerRef" + }, + { + "__symbolic": "reference", + "module": "../../core/linker/template_ref", + "name": "TemplateRef" + }, + { + "__symbolic": "reference", + "module": + "../../core/change_detection/differs/iterable_differs", + "name": "IterableDiffers" + }, + { + "__symbolic": "reference", + "module": + "../../core/change_detection/change_detector_ref", + "name": "ChangeDetectorRef" + } + ] + } + ] + } + } + } + }, + 'angular2/src/core/linker/view_container_ref': + { + "module": "./view_container_ref", + "metadata": {"ViewContainerRef": {"__symbolic": "class"}} }, - 'arguments': [{ - 'selector': 'my-hero-detail', - 'template': - '\n <div *ngIf="hero">\n <h2>{{hero.name}} details!</h2>\n <div><label>id: </label>{{hero.id}}</div>\n <div>\n <label>name: </label>\n <input [(ngModel)]="hero.name" placeholder="name"/>\n </div>\n </div>\n' - }] - }], - 'members': { - 'hero': [{ - '__symbolic': 'property', - 'decorators': [{ - '__symbolic': 'call', - 'expression': { - '__symbolic': 'reference', - 'name': 'Input', - 'module': 'angular2/src/core/metadata' - } - }] - }] - } - } - } - }, - './extern': {'__symbolic': 'module', module: './extern', metadata: {s: 's'}} - }[moduleId]; + 'angular2/src/core/linker/template_ref': + {"module": "./template_ref", "metadata": {"TemplateRef": {"__symbolic": "class"}}}, + 'angular2/src/core/change_detection/differs/iterable_differs': + { + "module": "./iterable_differs", + "metadata": {"IterableDiffers": {"__symbolic": "class"}} + }, + 'angular2/src/core/change_detection/change_detector_ref': + { + "module": "./change_detector_ref", + "metadata": {"ChangeDetectorRef": {"__symbolic": "class"}} + }, + './app/hero-detail.component': + { + "__symbolic": "module", + "module": "./hero-detail.component", + "metadata": + { + "HeroDetailComponent": + { + "__symbolic": "class", + "decorators": + [ + { + "__symbolic": "call", + "expression": { + "__symbolic": "reference", + "name": "Component", + "module": "angular2/src/core/metadata" + }, + "arguments": [ + { + "selector": "my-hero-detail", + "template": "\n <div *ngIf=\"hero\">\n <h2>{{hero.name}} details!</h2>\n <div><label>id: </label>{{hero.id}}</div>\n <div>\n <label>name: </label>\n <input [(ngModel)]=\"hero.name\" placeholder=\"name\"/>\n </div>\n </div>\n" + } + ] + } + ], + "members": + { + "hero": [ + { + "__symbolic": "property", + "decorators": + [ + { + "__symbolic": "call", + "expression": + { + "__symbolic": "reference", + "name": "Input", + "module": "angular2/src/core/metadata" + } + } + ] + } + ] + } + } + } + }, + './extern': { + "__symbolic": "module", module: './extern', metadata: { s: "s" } + } + } + [moduleId]; } } diff --git a/modules/angular2/test/compiler/style_compiler_spec.ts b/modules/angular2/test/compiler/style_compiler_spec.ts index 6288660a33..349f2c90ae 100644 --- a/modules/angular2/test/compiler/style_compiler_spec.ts +++ b/modules/angular2/test/compiler/style_compiler_spec.ts @@ -1,14 +1,38 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {provide} from 'angular2/src/core/di'; import {SpyXHR} from './spies'; import {XHR} from 'angular2/src/compiler/xhr'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {CONST_EXPR, isPresent, isBlank, StringWrapper, isArray, IS_DART} from 'angular2/src/facade/lang'; +import { + CONST_EXPR, + isPresent, + isBlank, + StringWrapper, + isArray, + IS_DART +} from 'angular2/src/facade/lang'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {evalModule} from './eval_module'; import {StyleCompiler} from 'angular2/src/compiler/style_compiler'; -import {CompileDirectiveMetadata, CompileTemplateMetadata, CompileTypeMetadata} from 'angular2/src/compiler/directive_metadata'; +import { + CompileDirectiveMetadata, + CompileTemplateMetadata, + CompileTypeMetadata +} from 'angular2/src/compiler/directive_metadata'; import {SourceExpression, SourceModule} from 'angular2/src/compiler/source_module'; import {ViewEncapsulation} from 'angular2/src/core/metadata/view'; import {TEST_PROVIDERS} from './test_bindings'; @@ -52,8 +76,8 @@ export function main() { `a {color: green}@import ${IMPORT_REL_STYLESHEET_URL};`; }); - function compile(styles: string[], styleAbsUrls: string[], encapsulation: ViewEncapsulation): - Promise<string[]> { + function compile(styles: string[], styleAbsUrls: string[], + encapsulation: ViewEncapsulation): Promise<string[]> { // Note: Can't use MockXHR as the xhr is called recursively, // so we can't trigger flush. xhr.spy('get').andCallFake((url) => { @@ -72,10 +96,11 @@ export function main() { var encapsulation = ViewEncapsulation.None; it('should compile plain css rules', inject([AsyncTestCompleter], (async) => { - compile(['div {color: red}', 'span {color: blue}'], [], encapsulation).then(styles => { - expect(styles).toEqual(['div {color: red}', 'span {color: blue}']); - async.done(); - }); + compile(['div {color: red}', 'span {color: blue}'], [], encapsulation) + .then(styles => { + expect(styles).toEqual(['div {color: red}', 'span {color: blue}']); + async.done(); + }); })); it('should allow to import rules', inject([AsyncTestCompleter], (async) => { @@ -89,8 +114,8 @@ export function main() { it('should allow to import rules transitively', inject([AsyncTestCompleter], (async) => { compile(['div {color: red}'], [IMPORT_ABS_STYLESHEET_URL_WITH_IMPORT], encapsulation) .then(styles => { - expect(styles).toEqual( - ['div {color: red}', ['a {color: green}', ['span {color: blue}']]]); + expect(styles) + .toEqual(['div {color: red}', ['a {color: green}', ['span {color: blue}']]]); async.done(); }); })); @@ -122,8 +147,8 @@ export function main() { })); it('should allow to import rules transitively', inject([AsyncTestCompleter], (async) => { - compile( - ['div {\ncolor: red;\n}'], [IMPORT_ABS_STYLESHEET_URL_WITH_IMPORT], encapsulation) + compile(['div {\ncolor: red;\n}'], [IMPORT_ABS_STYLESHEET_URL_WITH_IMPORT], + encapsulation) .then(styles => { compareStyles(styles, [ 'div[_ngcontent-%COMP%] {\ncolor: red;\n}', @@ -138,11 +163,10 @@ export function main() { }); it('should cache stylesheets for parallel requests', inject([AsyncTestCompleter], (async) => { - PromiseWrapper - .all([ - compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None), - compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None) - ]) + PromiseWrapper.all([ + compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None), + compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None) + ]) .then((styleArrays) => { expect(styleArrays[0]).toEqual([['span {color: blue}']]); expect(styleArrays[1]).toEqual([['span {color: blue}']]); @@ -152,16 +176,17 @@ export function main() { })); it('should cache stylesheets for serial requests', inject([AsyncTestCompleter], (async) => { - compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None).then((styles0) => { - xhrUrlResults[IMPORT_ABS_STYLESHEET_URL] = 'span {color: black}'; - return compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None) - .then((styles1) => { - expect(styles0).toEqual([['span {color: blue}']]); - expect(styles1).toEqual([['span {color: blue}']]); - expect(xhrCount).toBe(1); - async.done(); - }); - }); + compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None) + .then((styles0) => { + xhrUrlResults[IMPORT_ABS_STYLESHEET_URL] = 'span {color: black}'; + return compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None) + .then((styles1) => { + expect(styles0).toEqual([['span {color: blue}']]); + expect(styles1).toEqual([['span {color: blue}']]); + expect(xhrCount).toBe(1); + async.done(); + }); + }); })); it('should allow to clear the cache', inject([AsyncTestCompleter], (async) => { @@ -180,8 +205,8 @@ export function main() { }); describe('compileComponentCodeGen', () => { - function compile(styles: string[], styleAbsUrls: string[], encapsulation: ViewEncapsulation): - Promise<string[]> { + function compile(styles: string[], styleAbsUrls: string[], + encapsulation: ViewEncapsulation): Promise<string[]> { var sourceExpression = compiler.compileComponentCodeGen(new CompileTemplateMetadata( {styles: styles, styleUrls: styleAbsUrls, encapsulation: encapsulation})); var sourceWithImports = testableExpression(sourceExpression).getSourceWithImports(); @@ -192,18 +217,20 @@ export function main() { var encapsulation = ViewEncapsulation.None; it('should compile plain css rules', inject([AsyncTestCompleter], (async) => { - compile(['div {color: red}', 'span {color: blue}'], [], encapsulation).then(styles => { - expect(styles).toEqual(['div {color: red}', 'span {color: blue}']); - async.done(); - }); + compile(['div {color: red}', 'span {color: blue}'], [], encapsulation) + .then(styles => { + expect(styles).toEqual(['div {color: red}', 'span {color: blue}']); + async.done(); + }); })); it('should compile css rules with newlines and quotes', inject([AsyncTestCompleter], (async) => { - compile(['div\n{"color": \'red\'}'], [], encapsulation).then(styles => { - expect(styles).toEqual(['div\n{"color": \'red\'}']); - async.done(); - }); + compile(['div\n{"color": \'red\'}'], [], encapsulation) + .then(styles => { + expect(styles).toEqual(['div\n{"color": \'red\'}']); + async.done(); + }); })); it('should allow to import rules', inject([AsyncTestCompleter], (async) => { @@ -252,12 +279,13 @@ export function main() { } it('should compile plain css rules', inject([AsyncTestCompleter], (async) => { - compile('div {color: red;}').then(stylesAndShimStyles => { - var expected = [['div {color: red;}'], ['div[_ngcontent-%COMP%] {color: red;}']]; - compareStyles(stylesAndShimStyles[0], expected[0]); - compareStyles(stylesAndShimStyles[1], expected[1]); - async.done(); - }); + compile('div {color: red;}') + .then(stylesAndShimStyles => { + var expected = [['div {color: red;}'], ['div[_ngcontent-%COMP%] {color: red;}']]; + compareStyles(stylesAndShimStyles[0], expected[0]); + compareStyles(stylesAndShimStyles[1], expected[1]); + async.done(); + }); })); it('should allow to import rules with relative paths', @@ -296,7 +324,7 @@ function testableModule(sourceModule: SourceModule): SourceModule { } // Needed for Android browsers which add an extra space at the end of some lines -function compareStyles(styles: Array<string|any[]>, expectedStyles: Array<string|any[]>) { +function compareStyles(styles: Array<string | any[]>, expectedStyles: Array<string | any[]>) { expect(styles.length).toEqual(expectedStyles.length); for (var i = 0; i < styles.length; i++) { var style = styles[i]; diff --git a/modules/angular2/test/compiler/style_url_resolver_spec.ts b/modules/angular2/test/compiler/style_url_resolver_spec.ts index 16e5ef4248..413d51a8b9 100644 --- a/modules/angular2/test/compiler/style_url_resolver_spec.ts +++ b/modules/angular2/test/compiler/style_url_resolver_spec.ts @@ -38,9 +38,8 @@ export function main() { `; var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css); expect(styleWithImports.style.trim()).toEqual(''); - expect(styleWithImports.styleUrls).toEqual([ - 'http://ng.io/3.css', 'http://ng.io/4.css', 'http://ng.io/5.css' - ]); + expect(styleWithImports.styleUrls) + .toEqual(['http://ng.io/3.css', 'http://ng.io/4.css', 'http://ng.io/5.css']); }); it('should extract "@import urls and keep rules in the same line', () => { @@ -57,9 +56,8 @@ export function main() { `; var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css); expect(styleWithImports.style.trim()).toEqual(''); - expect(styleWithImports.styleUrls).toEqual([ - 'http://ng.io/print1.css', 'http://ng.io/print2.css' - ]); + expect(styleWithImports.styleUrls) + .toEqual(['http://ng.io/print1.css', 'http://ng.io/print2.css']); }); it('should leave absolute non-package @import urls intact', () => { diff --git a/modules/angular2/test/compiler/template_compiler_spec.ts b/modules/angular2/test/compiler/template_compiler_spec.ts index 7f94a38d00..8826bb8a81 100644 --- a/modules/angular2/test/compiler/template_compiler_spec.ts +++ b/modules/angular2/test/compiler/template_compiler_spec.ts @@ -1,10 +1,31 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {Type, isPresent, isBlank, stringify, isString, IS_DART} from 'angular2/src/facade/lang'; -import {MapWrapper, SetWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; +import { + MapWrapper, + SetWrapper, + ListWrapper, + StringMapWrapper +} from 'angular2/src/facade/collection'; import {RuntimeMetadataResolver} from 'angular2/src/compiler/runtime_metadata'; -import {TemplateCompiler, NormalizedComponentWithViewDirectives} from 'angular2/src/compiler/template_compiler'; +import { + TemplateCompiler, + NormalizedComponentWithViewDirectives +} from 'angular2/src/compiler/template_compiler'; import {CompileDirectiveMetadata} from 'angular2/src/compiler/directive_metadata'; import {evalModule} from './eval_module'; import {SourceModule, moduleRef} from 'angular2/src/compiler/source_module'; @@ -19,7 +40,12 @@ import {Locals, ChangeDetectorGenConfig} from 'angular2/src/core/change_detectio import {Component, Directive, provide, RenderComponentType} from 'angular2/core'; import {TEST_PROVIDERS} from './test_bindings'; -import {codeGenValueFn, codeGenFnHeader, codeGenExportVariable, MODULE_SUFFIX} from 'angular2/src/compiler/util'; +import { + codeGenValueFn, + codeGenFnHeader, + codeGenExportVariable, + MODULE_SUFFIX +} from 'angular2/src/compiler/util'; import {PipeTransform, WrappedValue, Injectable, Pipe} from 'angular2/core'; @@ -42,11 +68,11 @@ export function main() { var runtimeMetadataResolver: RuntimeMetadataResolver; beforeEachProviders(() => TEST_PROVIDERS); - beforeEach(inject( - [TemplateCompiler, RuntimeMetadataResolver], (_compiler, _runtimeMetadataResolver) => { - compiler = _compiler; - runtimeMetadataResolver = _runtimeMetadataResolver; - })); + beforeEach(inject([TemplateCompiler, RuntimeMetadataResolver], + (_compiler, _runtimeMetadataResolver) => { + compiler = _compiler; + runtimeMetadataResolver = _runtimeMetadataResolver; + })); describe('compile templates', () => { @@ -62,96 +88,100 @@ export function main() { })); it('should compile host components', inject([AsyncTestCompleter], (async) => { - compile([CompWithBindingsAndStylesAndPipes]).then((humanizedView) => { - expect(humanizedView['styles']).toEqual([]); - expect(humanizedView['elements']).toEqual(['<comp-a>']); - expect(humanizedView['pipes']).toEqual({}); - expect(humanizedView['cd']).toEqual(['prop(title)=someHostValue']); - async.done(); - }); + compile([CompWithBindingsAndStylesAndPipes]) + .then((humanizedView) => { + expect(humanizedView['styles']).toEqual([]); + expect(humanizedView['elements']).toEqual(['<comp-a>']); + expect(humanizedView['pipes']).toEqual({}); + expect(humanizedView['cd']).toEqual(['prop(title)=someHostValue']); + async.done(); + }); })); it('should compile nested components', inject([AsyncTestCompleter], (async) => { - compile([CompWithBindingsAndStylesAndPipes]).then((humanizedView) => { - var componentView = humanizedView['componentViews'][0]; - expect(componentView['styles']).toEqual(['div {color: red}']); - expect(componentView['elements']).toEqual(['<a>']); - expect(componentView['pipes']).toEqual({'uppercase': stringify(UpperCasePipe)}); - expect(componentView['cd']).toEqual(['prop(href)=SOMECTXVALUE']); + compile([CompWithBindingsAndStylesAndPipes]) + .then((humanizedView) => { + var componentView = humanizedView['componentViews'][0]; + expect(componentView['styles']).toEqual(['div {color: red}']); + expect(componentView['elements']).toEqual(['<a>']); + expect(componentView['pipes']).toEqual({'uppercase': stringify(UpperCasePipe)}); + expect(componentView['cd']).toEqual(['prop(href)=SOMECTXVALUE']); - async.done(); - }); + async.done(); + }); })); it('should compile components at various nesting levels', inject([AsyncTestCompleter], (async) => { - compile([CompWith2NestedComps, Comp1, Comp2]).then((humanizedView) => { - expect(humanizedView['elements']).toEqual(['<comp-with-2nested>']); - expect(humanizedView['componentViews'][0]['elements']).toEqual([ - '<comp1>', '<comp2>' - ]); - expect(humanizedView['componentViews'][0]['componentViews'][0]['elements']).toEqual([ - '<a>', '<comp2>' - ]); - expect(humanizedView['componentViews'][0]['componentViews'][1]['elements']).toEqual([ - '<b>' - ]); + compile([CompWith2NestedComps, Comp1, Comp2]) + .then((humanizedView) => { + expect(humanizedView['elements']).toEqual(['<comp-with-2nested>']); + expect(humanizedView['componentViews'][0]['elements']) + .toEqual(['<comp1>', '<comp2>']); + expect(humanizedView['componentViews'][0]['componentViews'][0]['elements']) + .toEqual(['<a>', '<comp2>']); + expect(humanizedView['componentViews'][0]['componentViews'][1]['elements']) + .toEqual(['<b>']); - async.done(); - }); + async.done(); + }); })); it('should compile recursive components', inject([AsyncTestCompleter], (async) => { - compile([TreeComp]).then((humanizedView) => { - expect(humanizedView['elements']).toEqual(['<tree>']); - expect(humanizedView['componentViews'][0]['embeddedViews'][0]['elements']).toEqual([ - '<tree>' - ]); - expect(humanizedView['componentViews'][0]['embeddedViews'][0]['componentViews'][0] - ['embeddedViews'][0]['elements']) - .toEqual(['<tree>']); + compile([TreeComp]) + .then((humanizedView) => { + expect(humanizedView['elements']).toEqual(['<tree>']); + expect(humanizedView['componentViews'][0]['embeddedViews'][0]['elements']) + .toEqual(['<tree>']); + expect(humanizedView['componentViews'][0]['embeddedViews'][0]['componentViews'] + [0]['embeddedViews'][0]['elements']) + .toEqual(['<tree>']); - async.done(); - }); + async.done(); + }); })); it('should compile embedded templates', inject([AsyncTestCompleter], (async) => { - compile([CompWithEmbeddedTemplate]).then((humanizedView) => { - var embeddedView = humanizedView['componentViews'][0]['embeddedViews'][0]; - expect(embeddedView['elements']).toEqual(['<a>']); - expect(embeddedView['cd']).toEqual(['prop(href)=someEmbeddedValue']); + compile([CompWithEmbeddedTemplate]) + .then((humanizedView) => { + var embeddedView = humanizedView['componentViews'][0]['embeddedViews'][0]; + expect(embeddedView['elements']).toEqual(['<a>']); + expect(embeddedView['cd']).toEqual(['prop(href)=someEmbeddedValue']); - async.done(); - }); + async.done(); + }); })); it('should dedup directives', inject([AsyncTestCompleter], (async) => { - compile([CompWithDupDirectives, TreeComp]).then((humanizedView) => { - expect(humanizedView['componentViews'][0]['componentViews'].length).toBe(1); - async.done(); + compile([CompWithDupDirectives, TreeComp]) + .then((humanizedView) => { + expect(humanizedView['componentViews'][0]['componentViews'].length).toBe(1); + async.done(); - }); + }); })); } describe('compileHostComponentRuntime', () => { function compile(components: Type[]): Promise<any[]> { return compiler.compileHostComponentRuntime(components[0]) - .then( - (compiledHostTemplate) => humanizeViewFactory(compiledHostTemplate.viewFactory)); + .then((compiledHostTemplate) => + humanizeViewFactory(compiledHostTemplate.viewFactory)); } describe('no jit', () => { - beforeEachProviders(() => [provide(ChangeDetectorGenConfig, { - useValue: new ChangeDetectorGenConfig(true, false, false) - })]); + beforeEachProviders(() => [ + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, false, false)}) + ]); runTests(compile); }); describe('jit', () => { - beforeEachProviders(() => [provide(ChangeDetectorGenConfig, { - useValue: new ChangeDetectorGenConfig(true, false, true) - })]); + beforeEachProviders(() => [ + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, false, true)}) + ]); runTests(compile); }); @@ -173,13 +203,15 @@ export function main() { inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => { // Expecting only one xhr... xhr.expect('package:angular2/test/compiler/compUrl.html', '<a>'); - compile([CompWithTemplateUrl]).then((humanizedView0) => { - return compile([CompWithTemplateUrl]).then((humanizedView1) => { - expect(humanizedView0['componentViews'][0]['elements']).toEqual(['<a>']); - expect(humanizedView1['componentViews'][0]['elements']).toEqual(['<a>']); - async.done(); - }); - }); + compile([CompWithTemplateUrl]) + .then((humanizedView0) => { + return compile([CompWithTemplateUrl]) + .then((humanizedView1) => { + expect(humanizedView0['componentViews'][0]['elements']).toEqual(['<a>']); + expect(humanizedView1['componentViews'][0]['elements']).toEqual(['<a>']); + async.done(); + }); + }); xhr.flush(); })); @@ -203,20 +235,19 @@ export function main() { }); describe('compileTemplatesCodeGen', () => { - function normalizeComponent(component: Type): - Promise<NormalizedComponentWithViewDirectives> { + function normalizeComponent( + component: Type): Promise<NormalizedComponentWithViewDirectives> { var compAndViewDirMetas = [runtimeMetadataResolver.getDirectiveMetadata(component)].concat( runtimeMetadataResolver.getViewDirectivesMetadata(component)); var upperCasePipeMeta = runtimeMetadataResolver.getPipeMetadata(UpperCasePipe); upperCasePipeMeta.type.moduleUrl = `package:${THIS_MODULE_ID}${MODULE_SUFFIX}`; - return PromiseWrapper - .all(compAndViewDirMetas.map(meta => compiler.normalizeDirectiveMetadata(meta))) - .then( - (normalizedCompAndViewDirMetas: CompileDirectiveMetadata[]) => - new NormalizedComponentWithViewDirectives( - normalizedCompAndViewDirMetas[0], normalizedCompAndViewDirMetas.slice(1), - [upperCasePipeMeta])); + return PromiseWrapper.all(compAndViewDirMetas.map( + meta => compiler.normalizeDirectiveMetadata(meta))) + .then((normalizedCompAndViewDirMetas: CompileDirectiveMetadata[]) => + new NormalizedComponentWithViewDirectives( + normalizedCompAndViewDirMetas[0], + normalizedCompAndViewDirMetas.slice(1), [upperCasePipeMeta])); } function compile(components: Type[]): Promise<any[]> { @@ -224,8 +255,8 @@ export function main() { .then((normalizedCompWithViewDirMetas: NormalizedComponentWithViewDirectives[]) => { var sourceModule = compiler.compileTemplatesCodeGen(normalizedCompWithViewDirMetas); var sourceWithImports = - testableTemplateModule( - sourceModule, normalizedCompWithViewDirMetas[0].component) + testableTemplateModule(sourceModule, + normalizedCompWithViewDirMetas[0].component) .getSourceWithImports(); return evalModule(sourceWithImports.source, sourceWithImports.imports, null); }); @@ -249,9 +280,8 @@ export function main() { it('should normalize the template', inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => { xhr.expect('package:angular2/test/compiler/compUrl.html', 'loadedTemplate'); - compiler - .normalizeDirectiveMetadata( - runtimeMetadataResolver.getDirectiveMetadata(CompWithTemplateUrl)) + compiler.normalizeDirectiveMetadata( + runtimeMetadataResolver.getDirectiveMetadata(CompWithTemplateUrl)) .then((meta: CompileDirectiveMetadata) => { expect(meta.template.template).toEqual('loadedTemplate'); async.done(); @@ -390,8 +420,8 @@ export class Comp1 { export class CompWith2NestedComps { } -function testableTemplateModule( - sourceModule: SourceModule, normComp: CompileDirectiveMetadata): SourceModule { +function testableTemplateModule(sourceModule: SourceModule, + normComp: CompileDirectiveMetadata): SourceModule { var testableSource = ` ${sourceModule.sourceWithModuleRefs} ${codeGenFnHeader(['_'], '_run')}{ @@ -455,11 +485,11 @@ export function humanizeViewFactory( } var viewManager = new SpyAppViewManager(); viewManager.spy('createRenderComponentType') - .andCallFake((encapsulation: ViewEncapsulation, styles: Array<string|any[]>) => { + .andCallFake((encapsulation: ViewEncapsulation, styles: Array<string | any[]>) => { return new RenderComponentType('someId', encapsulation, styles); }); - var view: AppView = viewFactory( - new RecordingRenderer([]), viewManager, containerAppElement, [], null, null, null); + var view: AppView = viewFactory(new RecordingRenderer([]), viewManager, containerAppElement, [], + null, null, null); return humanizeView(view, cachedResults); } @@ -471,11 +501,9 @@ class RecordingRenderer extends SpyRenderer { super(); this.spy('renderComponent') .andCallFake((componentProto) => new RecordingRenderer(componentProto.styles)); - this.spy('setElementProperty').andCallFake((el, prop, value) => { - this.props.push(`prop(${prop})=${value}`); - }); - this.spy('createElement').andCallFake((parent, elName) => { - this.elements.push(`<${elName}>`); - }); + this.spy('setElementProperty') + .andCallFake((el, prop, value) => { this.props.push(`prop(${prop})=${value}`); }); + this.spy('createElement') + .andCallFake((parent, elName) => { this.elements.push(`<${elName}>`); }); } } diff --git a/modules/angular2/test/compiler/template_normalizer_spec.ts b/modules/angular2/test/compiler/template_normalizer_spec.ts index aa054559bd..bb861beed1 100644 --- a/modules/angular2/test/compiler/template_normalizer_spec.ts +++ b/modules/angular2/test/compiler/template_normalizer_spec.ts @@ -1,6 +1,22 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder, beforeEachProviders} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + TestComponentBuilder, + beforeEachProviders +} from 'angular2/testing_internal'; -import {CompileTypeMetadata, CompileTemplateMetadata} from 'angular2/src/compiler/directive_metadata'; +import { + CompileTypeMetadata, + CompileTemplateMetadata +} from 'angular2/src/compiler/directive_metadata'; import {ViewEncapsulation} from 'angular2/src/core/metadata/view'; import {TemplateNormalizer} from 'angular2/src/compiler/template_normalizer'; @@ -24,133 +40,121 @@ export function main() { describe('loadTemplate', () => { describe('inline template', () => { it('should store the template', - inject( - [AsyncTestCompleter, TemplateNormalizer], - (async, normalizer: TemplateNormalizer) => { - normalizer - .normalizeTemplate(dirType, new CompileTemplateMetadata({ - encapsulation: null, - template: 'a', - templateUrl: null, - styles: [], - styleUrls: ['test.css'] - })) - .then((template: CompileTemplateMetadata) => { - expect(template.template).toEqual('a'); - expect(template.templateUrl).toEqual('package:some/module/a.js'); - async.done(); - }); - })); + inject([AsyncTestCompleter, TemplateNormalizer], + (async, normalizer: TemplateNormalizer) => { + normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({ + encapsulation: null, + template: 'a', + templateUrl: null, + styles: [], + styleUrls: ['test.css'] + })) + .then((template: CompileTemplateMetadata) => { + expect(template.template).toEqual('a'); + expect(template.templateUrl).toEqual('package:some/module/a.js'); + async.done(); + }); + })); it('should resolve styles on the annotation against the moduleUrl', - inject( - [AsyncTestCompleter, TemplateNormalizer], - (async, normalizer: TemplateNormalizer) => { - normalizer - .normalizeTemplate(dirType, new CompileTemplateMetadata({ - encapsulation: null, - template: '', - templateUrl: null, - styles: [], - styleUrls: ['test.css'] - })) - .then((template: CompileTemplateMetadata) => { - expect(template.styleUrls).toEqual(['package:some/module/test.css']); - async.done(); - }); - })); + inject([AsyncTestCompleter, TemplateNormalizer], + (async, normalizer: TemplateNormalizer) => { + normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({ + encapsulation: null, + template: '', + templateUrl: null, + styles: [], + styleUrls: ['test.css'] + })) + .then((template: CompileTemplateMetadata) => { + expect(template.styleUrls).toEqual(['package:some/module/test.css']); + async.done(); + }); + })); it('should resolve styles in the template against the moduleUrl', - inject( - [AsyncTestCompleter, TemplateNormalizer], - (async, normalizer: TemplateNormalizer) => { - normalizer - .normalizeTemplate(dirType, new CompileTemplateMetadata({ - encapsulation: null, - template: '<style>@import test.css</style>', - templateUrl: null, - styles: [], - styleUrls: [] - })) - .then((template: CompileTemplateMetadata) => { - expect(template.styleUrls).toEqual(['package:some/module/test.css']); - async.done(); - }); - })); + inject([AsyncTestCompleter, TemplateNormalizer], + (async, normalizer: TemplateNormalizer) => { + normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({ + encapsulation: null, + template: '<style>@import test.css</style>', + templateUrl: null, + styles: [], + styleUrls: [] + })) + .then((template: CompileTemplateMetadata) => { + expect(template.styleUrls).toEqual(['package:some/module/test.css']); + async.done(); + }); + })); }); describe('templateUrl', () => { it('should load a template from a url that is resolved against moduleUrl', - inject( - [AsyncTestCompleter, TemplateNormalizer, XHR], - (async, normalizer: TemplateNormalizer, xhr: MockXHR) => { - xhr.expect('package:some/module/sometplurl.html', 'a'); - normalizer - .normalizeTemplate(dirType, new CompileTemplateMetadata({ - encapsulation: null, - template: null, - templateUrl: 'sometplurl.html', - styles: [], - styleUrls: ['test.css'] - })) - .then((template: CompileTemplateMetadata) => { - expect(template.template).toEqual('a'); - expect(template.templateUrl).toEqual('package:some/module/sometplurl.html'); - async.done(); - }); - xhr.flush(); - })); + inject([AsyncTestCompleter, TemplateNormalizer, XHR], + (async, normalizer: TemplateNormalizer, xhr: MockXHR) => { + xhr.expect('package:some/module/sometplurl.html', 'a'); + normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({ + encapsulation: null, + template: null, + templateUrl: 'sometplurl.html', + styles: [], + styleUrls: ['test.css'] + })) + .then((template: CompileTemplateMetadata) => { + expect(template.template).toEqual('a'); + expect(template.templateUrl) + .toEqual('package:some/module/sometplurl.html'); + async.done(); + }); + xhr.flush(); + })); it('should resolve styles on the annotation against the moduleUrl', - inject( - [AsyncTestCompleter, TemplateNormalizer, XHR], - (async, normalizer: TemplateNormalizer, xhr: MockXHR) => { - xhr.expect('package:some/module/tpl/sometplurl.html', ''); - normalizer - .normalizeTemplate(dirType, new CompileTemplateMetadata({ - encapsulation: null, - template: null, - templateUrl: 'tpl/sometplurl.html', - styles: [], - styleUrls: ['test.css'] - })) - .then((template: CompileTemplateMetadata) => { - expect(template.styleUrls).toEqual(['package:some/module/test.css']); - async.done(); - }); - xhr.flush(); - })); + inject([AsyncTestCompleter, TemplateNormalizer, XHR], + (async, normalizer: TemplateNormalizer, xhr: MockXHR) => { + xhr.expect('package:some/module/tpl/sometplurl.html', ''); + normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({ + encapsulation: null, + template: null, + templateUrl: 'tpl/sometplurl.html', + styles: [], + styleUrls: ['test.css'] + })) + .then((template: CompileTemplateMetadata) => { + expect(template.styleUrls).toEqual(['package:some/module/test.css']); + async.done(); + }); + xhr.flush(); + })); it('should resolve styles in the template against the templateUrl', - inject( - [AsyncTestCompleter, TemplateNormalizer, XHR], - (async, normalizer: TemplateNormalizer, xhr: MockXHR) => { - xhr.expect( - 'package:some/module/tpl/sometplurl.html', '<style>@import test.css</style>'); - normalizer - .normalizeTemplate(dirType, new CompileTemplateMetadata({ - encapsulation: null, - template: null, - templateUrl: 'tpl/sometplurl.html', - styles: [], - styleUrls: [] - })) - .then((template: CompileTemplateMetadata) => { - expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']); - async.done(); - }); - xhr.flush(); - })); + inject([AsyncTestCompleter, TemplateNormalizer, XHR], + (async, normalizer: TemplateNormalizer, xhr: MockXHR) => { + xhr.expect('package:some/module/tpl/sometplurl.html', + '<style>@import test.css</style>'); + normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({ + encapsulation: null, + template: null, + templateUrl: 'tpl/sometplurl.html', + styles: [], + styleUrls: [] + })) + .then((template: CompileTemplateMetadata) => { + expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']); + async.done(); + }); + xhr.flush(); + })); }); it('should throw if no template was specified', inject([TemplateNormalizer], (normalizer: TemplateNormalizer) => { - expect( - () => normalizer.normalizeTemplate( - dirType, - new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}))) + expect(() => normalizer.normalizeTemplate( + dirType, new CompileTemplateMetadata( + {encapsulation: null, styles: [], styleUrls: []}))) .toThrowError('No template specified for component SomeComp'); })); diff --git a/modules/angular2/test/compiler/template_parser_spec.ts b/modules/angular2/test/compiler/template_parser_spec.ts index b4ce9b56da..b812af8f49 100644 --- a/modules/angular2/test/compiler/template_parser_spec.ts +++ b/modules/angular2/test/compiler/template_parser_spec.ts @@ -1,11 +1,47 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {provide} from 'angular2/src/core/di'; import {TEST_PROVIDERS} from './test_bindings'; import {isPresent} from 'angular2/src/facade/lang'; -import {TemplateParser, splitClasses, TEMPLATE_TRANSFORMS} from 'angular2/src/compiler/template_parser'; -import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTypeMetadata, CompileTemplateMetadata} from 'angular2/src/compiler/directive_metadata'; -import {templateVisitAll, TemplateAstVisitor, TemplateAst, NgContentAst, EmbeddedTemplateAst, ElementAst, VariableAst, BoundEventAst, BoundElementPropertyAst, BoundDirectivePropertyAst, AttrAst, BoundTextAst, TextAst, PropertyBindingType, DirectiveAst} from 'angular2/src/compiler/template_ast'; +import { + TemplateParser, + splitClasses, + TEMPLATE_TRANSFORMS +} from 'angular2/src/compiler/template_parser'; +import { + CompileDirectiveMetadata, + CompilePipeMetadata, + CompileTypeMetadata, + CompileTemplateMetadata +} from 'angular2/src/compiler/directive_metadata'; +import { + templateVisitAll, + TemplateAstVisitor, + TemplateAst, + NgContentAst, + EmbeddedTemplateAst, + ElementAst, + VariableAst, + BoundEventAst, + BoundElementPropertyAst, + BoundDirectivePropertyAst, + AttrAst, + BoundTextAst, + TextAst, + PropertyBindingType, + DirectiveAst +} from 'angular2/src/compiler/template_ast'; import {ElementSchemaRegistry} from 'angular2/src/compiler/schema/element_schema_registry'; import {MockSchemaRegistry} from './schema_registry_mock'; @@ -14,9 +50,11 @@ import {Unparser} from '../core/change_detection/parser/unparser'; var expressionUnparser = new Unparser(); -var MOCK_SCHEMA_REGISTRY = [provide( - ElementSchemaRegistry, - {useValue: new MockSchemaRegistry({'invalidProp': false}, {'mappedAttr': 'mappedProp'})})]; +var MOCK_SCHEMA_REGISTRY = [ + provide( + ElementSchemaRegistry, + {useValue: new MockSchemaRegistry({'invalidProp': false}, {'mappedAttr': 'mappedProp'})}) +]; export function main() { var ngIf; @@ -27,14 +65,13 @@ export function main() { ngIf = CompileDirectiveMetadata.create( {selector: '[ngIf]', type: new CompileTypeMetadata({name: 'NgIf'}), inputs: ['ngIf']}); - parse = - (template: string, directives: CompileDirectiveMetadata[], - pipes: CompilePipeMetadata[] = null): TemplateAst[] => { - if (pipes === null) { - pipes = []; - } - return parser.parse(template, directives, pipes, 'TestComp'); - }; + parse = (template: string, directives: CompileDirectiveMetadata[], + pipes: CompilePipeMetadata[] = null): TemplateAst[] => { + if (pipes === null) { + pipes = []; + } + return parser.parse(template, directives, pipes, 'TestComp'); + }; })); } @@ -46,9 +83,8 @@ export function main() { describe('single', () => { commonBeforeEach(); - it('should transform TemplateAST', () => { - expect(humanizeTplAst(parse('<div>', []))).toEqual([[ElementAst, 'foo']]); - }); + it('should transform TemplateAST', + () => { expect(humanizeTplAst(parse('<div>', []))).toEqual([[ElementAst, 'foo']]); }); }); describe('multiple', () => { @@ -56,9 +92,8 @@ export function main() { () => [provide(TEMPLATE_TRANSFORMS, {useValue: new BarAstTransformer(), multi: true})]); commonBeforeEach(); - it('should compose transformers', () => { - expect(humanizeTplAst(parse('<div>', []))).toEqual([[ElementAst, 'bar']]); - }); + it('should compose transformers', + () => { expect(humanizeTplAst(parse('<div>', []))).toEqual([[ElementAst, 'bar']]); }); }); }); @@ -70,13 +105,12 @@ export function main() { describe('parse', () => { describe('nodes without bindings', () => { - it('should parse text nodes', () => { - expect(humanizeTplAst(parse('a', []))).toEqual([[TextAst, 'a']]); - }); + it('should parse text nodes', + () => { expect(humanizeTplAst(parse('a', []))).toEqual([[TextAst, 'a']]); }); it('should parse elements with attributes', () => { - expect(humanizeTplAst(parse('<div a=b>', [ - ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'a', 'b']]); + expect(humanizeTplAst(parse('<div a=b>', []))) + .toEqual([[ElementAst, 'div'], [AttrAst, 'a', 'b']]); }); }); @@ -87,10 +121,11 @@ export function main() { it('should parse ngContent regardless the namespace', () => { var parsed = parse('<svg><ng-content></ng-content></svg>', []); - expect(humanizeTplAst(parsed)).toEqual([ - [ElementAst, '@svg:svg'], - [NgContentAst], - ]); + expect(humanizeTplAst(parsed)) + .toEqual([ + [ElementAst, '@svg:svg'], + [NgContentAst], + ]); }); it('should parse bound text nodes', () => { @@ -100,52 +135,59 @@ export function main() { describe('bound properties', () => { it('should parse mixed case bound properties', () => { - expect(humanizeTplAst(parse('<div [someProp]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [someProp]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null] + ]); }); it('should parse dash case bound properties', () => { - expect(humanizeTplAst(parse('<div [some-prop]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'some-prop', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [some-prop]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'some-prop', 'v', null] + ]); }); it('should normalize property names via the element schema', () => { - expect(humanizeTplAst(parse('<div [mappedAttr]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'mappedProp', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [mappedAttr]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'mappedProp', 'v', null] + ]); }); it('should parse mixed case bound attributes', () => { - expect(humanizeTplAst(parse('<div [attr.someAttr]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [attr.someAttr]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr', 'v', null] + ]); }); it('should parse and dash case bound classes', () => { - expect(humanizeTplAst(parse('<div [class.some-class]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Class, 'some-class', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [class.some-class]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Class, 'some-class', 'v', null] + ]); }); it('should parse mixed case bound classes', () => { - expect(humanizeTplAst(parse('<div [class.someClass]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Class, 'someClass', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [class.someClass]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Class, 'someClass', 'v', null] + ]); }); it('should parse mixed case bound styles', () => { - expect(humanizeTplAst(parse('<div [style.someStyle]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Style, 'someStyle', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [style.someStyle]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Style, 'someStyle', 'v', null] + ]); }); it('should report invalid prefixes', () => { @@ -164,24 +206,27 @@ export function main() { }); it('should parse bound properties via [...] and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div [prop]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null] - ]); + expect(humanizeTplAst(parse('<div [prop]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null] + ]); }); it('should parse bound properties via bind- and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div bind-prop="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null] - ]); + expect(humanizeTplAst(parse('<div bind-prop="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null] + ]); }); it('should parse bound properties via {{...}} and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div prop="{{v}}">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null] - ]); + expect(humanizeTplAst(parse('<div prop="{{v}}">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null] + ]); }); }); @@ -189,25 +234,25 @@ export function main() { describe('events', () => { it('should parse bound events with a target', () => { - expect(humanizeTplAst(parse('<div (window:event)="v">', [ - ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', 'window', 'v']]); + expect(humanizeTplAst(parse('<div (window:event)="v">', []))) + .toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', 'window', 'v']]); }); it('should parse bound events via (...) and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div (event)="v">', [ - ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]); + expect(humanizeTplAst(parse('<div (event)="v">', []))) + .toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]); }); it('should parse event names case sensitive', () => { - expect(humanizeTplAst(parse('<div (some-event)="v">', [ - ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'some-event', null, 'v']]); - expect(humanizeTplAst(parse('<div (someEvent)="v">', [ - ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'someEvent', null, 'v']]); + expect(humanizeTplAst(parse('<div (some-event)="v">', []))) + .toEqual([[ElementAst, 'div'], [BoundEventAst, 'some-event', null, 'v']]); + expect(humanizeTplAst(parse('<div (someEvent)="v">', []))) + .toEqual([[ElementAst, 'div'], [BoundEventAst, 'someEvent', null, 'v']]); }); it('should parse bound events via on- and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div on-event="v">', [ - ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]); + expect(humanizeTplAst(parse('<div on-event="v">', []))) + .toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]); }); it('should allow events on explicit embedded templates that are emitted by a directive', @@ -217,31 +262,34 @@ export function main() { outputs: ['e'], type: new CompileTypeMetadata({name: 'DirA'}) }); - expect(humanizeTplAst(parse('<template (e)="f"></template>', [dirA]))).toEqual([ - [EmbeddedTemplateAst], - [BoundEventAst, 'e', null, 'f'], - [DirectiveAst, dirA], - ]); + expect(humanizeTplAst(parse('<template (e)="f"></template>', [dirA]))) + .toEqual([ + [EmbeddedTemplateAst], + [BoundEventAst, 'e', null, 'f'], + [DirectiveAst, dirA], + ]); }); }); describe('bindon', () => { it('should parse bound events and properties via [(...)] and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div [(prop)]="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null], - [BoundEventAst, 'propChange', null, 'v = $event'] - ]); + expect(humanizeTplAst(parse('<div [(prop)]="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null], + [BoundEventAst, 'propChange', null, 'v = $event'] + ]); }); it('should parse bound events and properties via bindon- and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div bindon-prop="v">', []))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null], - [BoundEventAst, 'propChange', null, 'v = $event'] - ]); + expect(humanizeTplAst(parse('<div bindon-prop="v">', []))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null], + [BoundEventAst, 'propChange', null, 'v = $event'] + ]); }); }); @@ -261,11 +309,17 @@ export function main() { type: new CompileTypeMetadata({name: 'ZComp'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); - expect(humanizeTplAst(parse('<div a c b>', [dirA, dirB, dirC, comp]))).toEqual([ - [ElementAst, 'div'], [AttrAst, 'a', ''], [AttrAst, 'c', ''], [AttrAst, 'b', ''], - [DirectiveAst, comp], [DirectiveAst, dirA], [DirectiveAst, dirB], - [DirectiveAst, dirC] - ]); + expect(humanizeTplAst(parse('<div a c b>', [dirA, dirB, dirC, comp]))) + .toEqual([ + [ElementAst, 'div'], + [AttrAst, 'a', ''], + [AttrAst, 'c', ''], + [AttrAst, 'b', ''], + [DirectiveAst, comp], + [DirectiveAst, dirA], + [DirectiveAst, dirB], + [DirectiveAst, dirC] + ]); }); it('should locate directives in property bindings', () => { @@ -273,20 +327,21 @@ export function main() { {selector: '[a=b]', type: new CompileTypeMetadata({name: 'DirA'})}); var dirB = CompileDirectiveMetadata.create( {selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})}); - expect(humanizeTplAst(parse('<div [a]="b">', [dirA, dirB]))).toEqual([ - [ElementAst, 'div'], - [BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'b', null], - [DirectiveAst, dirA] - ]); + expect(humanizeTplAst(parse('<div [a]="b">', [dirA, dirB]))) + .toEqual([ + [ElementAst, 'div'], + [BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'b', null], + [DirectiveAst, dirA] + ]); }); it('should locate directives in event bindings', () => { var dirA = CompileDirectiveMetadata.create( {selector: '[a]', type: new CompileTypeMetadata({name: 'DirB'})}); - expect(humanizeTplAst(parse('<div (a)="b">', [dirA]))).toEqual([ - [ElementAst, 'div'], [BoundEventAst, 'a', null, 'b'], [DirectiveAst, dirA] - ]); + expect(humanizeTplAst(parse('<div (a)="b">', [dirA]))) + .toEqual( + [[ElementAst, 'div'], [BoundEventAst, 'a', null, 'b'], [DirectiveAst, dirA]]); }); it('should parse directive host properties', () => { @@ -295,10 +350,12 @@ export function main() { type: new CompileTypeMetadata({name: 'DirA'}), host: {'[a]': 'expr'} }); - expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [DirectiveAst, dirA], - [BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'expr', null] - ]); + expect(humanizeTplAst(parse('<div></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div'], + [DirectiveAst, dirA], + [BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'expr', null] + ]); }); it('should parse directive host listeners', () => { @@ -307,35 +364,43 @@ export function main() { type: new CompileTypeMetadata({name: 'DirA'}), host: {'(a)': 'expr'} }); - expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [DirectiveAst, dirA], [BoundEventAst, 'a', null, 'expr'] - ]); + expect(humanizeTplAst(parse('<div></div>', [dirA]))) + .toEqual( + [[ElementAst, 'div'], [DirectiveAst, dirA], [BoundEventAst, 'a', null, 'expr']]); }); it('should parse directive properties', () => { var dirA = CompileDirectiveMetadata.create( {selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['aProp']}); - expect(humanizeTplAst(parse('<div [aProp]="expr"></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [DirectiveAst, dirA], - [BoundDirectivePropertyAst, 'aProp', 'expr'] - ]); + expect(humanizeTplAst(parse('<div [aProp]="expr"></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div'], + [DirectiveAst, dirA], + [BoundDirectivePropertyAst, 'aProp', 'expr'] + ]); }); it('should parse renamed directive properties', () => { var dirA = CompileDirectiveMetadata.create( {selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['b:a']}); - expect(humanizeTplAst(parse('<div [a]="expr"></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'b', 'expr'] - ]); + expect(humanizeTplAst(parse('<div [a]="expr"></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div'], + [DirectiveAst, dirA], + [BoundDirectivePropertyAst, 'b', 'expr'] + ]); }); it('should parse literal directive properties', () => { var dirA = CompileDirectiveMetadata.create( {selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']}); - expect(humanizeTplAst(parse('<div a="literal"></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [AttrAst, 'a', 'literal'], [DirectiveAst, dirA], - [BoundDirectivePropertyAst, 'a', '"literal"'] - ]); + expect(humanizeTplAst(parse('<div a="literal"></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div'], + [AttrAst, 'a', 'literal'], + [DirectiveAst, dirA], + [BoundDirectivePropertyAst, 'a', '"literal"'] + ]); }); it('should favor explicit bound properties over literal properties', () => { @@ -343,7 +408,9 @@ export function main() { {selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']}); expect(humanizeTplAst(parse('<div a="literal" [a]="\'literal2\'"></div>', [dirA]))) .toEqual([ - [ElementAst, 'div'], [AttrAst, 'a', 'literal'], [DirectiveAst, dirA], + [ElementAst, 'div'], + [AttrAst, 'a', 'literal'], + [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', '"literal2"'] ]); }); @@ -351,9 +418,8 @@ export function main() { it('should support optional directive properties', () => { var dirA = CompileDirectiveMetadata.create( {selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']}); - expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [DirectiveAst, dirA] - ]); + expect(humanizeTplAst(parse('<div></div>', [dirA]))) + .toEqual([[ElementAst, 'div'], [DirectiveAst, dirA]]); }); }); @@ -361,32 +427,35 @@ export function main() { describe('variables', () => { it('should parse variables via #... and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div #a>', [ - ]))).toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]); + expect(humanizeTplAst(parse('<div #a>', []))) + .toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]); }); it('should parse variables via var-... and not report them as attributes', () => { - expect(humanizeTplAst(parse('<div var-a>', [ - ]))).toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]); + expect(humanizeTplAst(parse('<div var-a>', []))) + .toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]); }); it('should parse camel case variables', () => { - expect(humanizeTplAst(parse('<div var-someA>', [ - ]))).toEqual([[ElementAst, 'div'], [VariableAst, 'someA', '']]); + expect(humanizeTplAst(parse('<div var-someA>', []))) + .toEqual([[ElementAst, 'div'], [VariableAst, 'someA', '']]); }); it('should assign variables with empty value to the element', () => { - expect(humanizeTplAst(parse('<div #a></div>', [ - ]))).toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]); + expect(humanizeTplAst(parse('<div #a></div>', []))) + .toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]); }); it('should assign variables to directives via exportAs', () => { var dirA = CompileDirectiveMetadata.create( {selector: '[a]', type: new CompileTypeMetadata({name: 'DirA'}), exportAs: 'dirA'}); - expect(humanizeTplAst(parse('<div a #a="dirA"></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [AttrAst, 'a', ''], [DirectiveAst, dirA], - [VariableAst, 'a', 'dirA'] - ]); + expect(humanizeTplAst(parse('<div a #a="dirA"></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div'], + [AttrAst, 'a', ''], + [DirectiveAst, dirA], + [VariableAst, 'a', 'dirA'] + ]); }); it('should report variables with values that dont match a directive as errors', () => { @@ -401,8 +470,8 @@ There is no directive with "exportAs" set to "dirA" ("<div [ERROR ->]#a="dirA">< it('should allow variables with values that dont match a directive on embedded template elements', () => { - expect(humanizeTplAst(parse('<template #a="b"></template>', [ - ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b']]); + expect(humanizeTplAst(parse('<template #a="b"></template>', []))) + .toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b']]); }); it('should assign variables with empty value to components', () => { @@ -413,52 +482,60 @@ There is no directive with "exportAs" set to "dirA" ("<div [ERROR ->]#a="dirA">< exportAs: 'dirA', template: new CompileTemplateMetadata({ngContentSelectors: []}) }); - expect(humanizeTplAst(parse('<div a #a></div>', [dirA]))).toEqual([ - [ElementAst, 'div'], [AttrAst, 'a', ''], [VariableAst, 'a', ''], [DirectiveAst, dirA], - [VariableAst, 'a', ''] - ]); + expect(humanizeTplAst(parse('<div a #a></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div'], + [AttrAst, 'a', ''], + [VariableAst, 'a', ''], + [DirectiveAst, dirA], + [VariableAst, 'a', ''] + ]); }); }); describe('explicit templates', () => { it('should create embedded templates for <template> elements', () => { - expect(humanizeTplAst(parse('<template></template>', [ - ]))).toEqual([[EmbeddedTemplateAst]]); - expect(humanizeTplAst(parse('<TEMPLATE></TEMPLATE>', [ - ]))).toEqual([[EmbeddedTemplateAst]]); + expect(humanizeTplAst(parse('<template></template>', []))) + .toEqual([[EmbeddedTemplateAst]]); + expect(humanizeTplAst(parse('<TEMPLATE></TEMPLATE>', []))) + .toEqual([[EmbeddedTemplateAst]]); }); it('should create embedded templates for <template> elements regardless the namespace', () => { - expect(humanizeTplAst(parse('<svg><template></template></svg>', []))).toEqual([ - [ElementAst, '@svg:svg'], - [EmbeddedTemplateAst], - ]); + expect(humanizeTplAst(parse('<svg><template></template></svg>', []))) + .toEqual([ + [ElementAst, '@svg:svg'], + [EmbeddedTemplateAst], + ]); }); }); describe('inline templates', () => { it('should wrap the element into an EmbeddedTemplateAST', () => { - expect(humanizeTplAst(parse('<div template>', [ - ]))).toEqual([[EmbeddedTemplateAst], [ElementAst, 'div']]); + expect(humanizeTplAst(parse('<div template>', []))) + .toEqual([[EmbeddedTemplateAst], [ElementAst, 'div']]); }); it('should parse bound properties', () => { - expect(humanizeTplAst(parse('<div template="ngIf test">', [ngIf]))).toEqual([ - [EmbeddedTemplateAst], [DirectiveAst, ngIf], - [BoundDirectivePropertyAst, 'ngIf', 'test'], [ElementAst, 'div'] - ]); + expect(humanizeTplAst(parse('<div template="ngIf test">', [ngIf]))) + .toEqual([ + [EmbeddedTemplateAst], + [DirectiveAst, ngIf], + [BoundDirectivePropertyAst, 'ngIf', 'test'], + [ElementAst, 'div'] + ]); }); it('should parse variables via #...', () => { - expect(humanizeTplAst(parse('<div template="ngIf #a=b">', [ - ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); + expect(humanizeTplAst(parse('<div template="ngIf #a=b">', []))) + .toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); }); it('should parse variables via var ...', () => { - expect(humanizeTplAst(parse('<div template="ngIf var a=b">', [ - ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); + expect(humanizeTplAst(parse('<div template="ngIf var a=b">', []))) + .toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); }); describe('directives', () => { @@ -467,10 +544,15 @@ There is no directive with "exportAs" set to "dirA" ("<div [ERROR ->]#a="dirA">< {selector: '[a=b]', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']}); var dirB = CompileDirectiveMetadata.create( {selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})}); - expect(humanizeTplAst(parse('<div template="a b" b>', [dirA, dirB]))).toEqual([ - [EmbeddedTemplateAst], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', 'b'], - [ElementAst, 'div'], [AttrAst, 'b', ''], [DirectiveAst, dirB] - ]); + expect(humanizeTplAst(parse('<div template="a b" b>', [dirA, dirB]))) + .toEqual([ + [EmbeddedTemplateAst], + [DirectiveAst, dirA], + [BoundDirectivePropertyAst, 'a', 'b'], + [ElementAst, 'div'], + [AttrAst, 'b', ''], + [DirectiveAst, dirB] + ]); }); it('should locate directives in variable bindings', () => { @@ -478,33 +560,44 @@ There is no directive with "exportAs" set to "dirA" ("<div [ERROR ->]#a="dirA">< {selector: '[a=b]', type: new CompileTypeMetadata({name: 'DirA'})}); var dirB = CompileDirectiveMetadata.create( {selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})}); - expect(humanizeTplAst(parse('<div template="#a=b" b>', [dirA, dirB]))).toEqual([ - [EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [DirectiveAst, dirA], - [ElementAst, 'div'], [AttrAst, 'b', ''], [DirectiveAst, dirB] - ]); + expect(humanizeTplAst(parse('<div template="#a=b" b>', [dirA, dirB]))) + .toEqual([ + [EmbeddedTemplateAst], + [VariableAst, 'a', 'b'], + [DirectiveAst, dirA], + [ElementAst, 'div'], + [AttrAst, 'b', ''], + [DirectiveAst, dirB] + ]); }); }); it('should work with *... and use the attribute name as property binding name', () => { - expect(humanizeTplAst(parse('<div *ngIf="test">', [ngIf]))).toEqual([ - [EmbeddedTemplateAst], [DirectiveAst, ngIf], - [BoundDirectivePropertyAst, 'ngIf', 'test'], [ElementAst, 'div'] - ]); + expect(humanizeTplAst(parse('<div *ngIf="test">', [ngIf]))) + .toEqual([ + [EmbeddedTemplateAst], + [DirectiveAst, ngIf], + [BoundDirectivePropertyAst, 'ngIf', 'test'], + [ElementAst, 'div'] + ]); }); it('should work with *... and empty value', () => { - expect(humanizeTplAst(parse('<div *ngIf>', [ngIf]))).toEqual([ - [EmbeddedTemplateAst], [DirectiveAst, ngIf], - [BoundDirectivePropertyAst, 'ngIf', 'null'], [ElementAst, 'div'] - ]); + expect(humanizeTplAst(parse('<div *ngIf>', [ngIf]))) + .toEqual([ + [EmbeddedTemplateAst], + [DirectiveAst, ngIf], + [BoundDirectivePropertyAst, 'ngIf', 'null'], + [ElementAst, 'div'] + ]); }); }); }); describe('content projection', () => { - function createComp( - selector: string, ngContentSelectors: string[]): CompileDirectiveMetadata { + function createComp(selector: string, + ngContentSelectors: string[]): CompileDirectiveMetadata { return CompileDirectiveMetadata.create({ selector: selector, isComponent: true, @@ -522,109 +615,107 @@ There is no directive with "exportAs" set to "dirA" ("<div [ERROR ->]#a="dirA">< describe('project elements', () => { it('should project elements with wildcard selector', () => { - expect(humanizeContentProjection(parse('<div><span></span></div>', [ - createComp('div', ['*']) - ]))).toEqual([['div', null], ['span', 0]]); + expect(humanizeContentProjection( + parse('<div><span></span></div>', [createComp('div', ['*'])]))) + .toEqual([['div', null], ['span', 0]]); }); it('should project elements with css selector', () => { - expect(humanizeContentProjection(parse('<div><a x></a><b></b></div>', [ - createComp('div', ['a[x]']) - ]))).toEqual([['div', null], ['a', 0], ['b', null]]); + expect(humanizeContentProjection( + parse('<div><a x></a><b></b></div>', [createComp('div', ['a[x]'])]))) + .toEqual([['div', null], ['a', 0], ['b', null]]); }); }); describe('embedded templates', () => { it('should project embedded templates with wildcard selector', () => { - expect(humanizeContentProjection(parse('<div><template></template></div>', [ - createComp('div', ['*']) - ]))).toEqual([['div', null], ['template', 0]]); + expect(humanizeContentProjection( + parse('<div><template></template></div>', [createComp('div', ['*'])]))) + .toEqual([['div', null], ['template', 0]]); }); it('should project embedded templates with css selector', () => { - expect(humanizeContentProjection(parse( - '<div><template x></template><template></template></div>', - [createComp('div', ['template[x]'])]))) + expect(humanizeContentProjection( + parse('<div><template x></template><template></template></div>', + [createComp('div', ['template[x]'])]))) .toEqual([['div', null], ['template', 0], ['template', null]]); }); }); describe('ng-content', () => { it('should project ng-content with wildcard selector', () => { - expect(humanizeContentProjection(parse('<div><ng-content></ng-content></div>', [ - createComp('div', ['*']) - ]))).toEqual([['div', null], ['ng-content', 0]]); + expect(humanizeContentProjection( + parse('<div><ng-content></ng-content></div>', [createComp('div', ['*'])]))) + .toEqual([['div', null], ['ng-content', 0]]); }); it('should project ng-content with css selector', () => { - expect(humanizeContentProjection(parse( - '<div><ng-content x></ng-content><ng-content></ng-content></div>', - [createComp('div', ['ng-content[x]'])]))) + expect(humanizeContentProjection( + parse('<div><ng-content x></ng-content><ng-content></ng-content></div>', + [createComp('div', ['ng-content[x]'])]))) .toEqual([['div', null], ['ng-content', 0], ['ng-content', null]]); }); }); it('should project into the first matching ng-content', () => { - expect(humanizeContentProjection(parse('<div>hello<b></b><a></a></div>', [ - createComp('div', ['a', 'b', '*']) - ]))).toEqual([['div', null], ['#text(hello)', 2], ['b', 1], ['a', 0]]); + expect(humanizeContentProjection( + parse('<div>hello<b></b><a></a></div>', [createComp('div', ['a', 'b', '*'])]))) + .toEqual([['div', null], ['#text(hello)', 2], ['b', 1], ['a', 0]]); }); it('should project into wildcard ng-content last', () => { - expect(humanizeContentProjection(parse('<div>hello<a></a></div>', [ - createComp('div', ['*', 'a']) - ]))).toEqual([['div', null], ['#text(hello)', 0], ['a', 1]]); + expect(humanizeContentProjection( + parse('<div>hello<a></a></div>', [createComp('div', ['*', 'a'])]))) + .toEqual([['div', null], ['#text(hello)', 0], ['a', 1]]); }); it('should only project direct child nodes', () => { - expect(humanizeContentProjection(parse('<div><span><a></a></span><a></a></div>', [ - createComp('div', ['a']) - ]))).toEqual([['div', null], ['span', null], ['a', null], ['a', 0]]); + expect(humanizeContentProjection( + parse('<div><span><a></a></span><a></a></div>', [createComp('div', ['a'])]))) + .toEqual([['div', null], ['span', null], ['a', null], ['a', 0]]); }); it('should project nodes of nested components', () => { - expect(humanizeContentProjection(parse('<a><b>hello</b></a>', [ - createComp('a', ['*']), createComp('b', ['*']) - ]))).toEqual([['a', null], ['b', 0], ['#text(hello)', 0]]); + expect(humanizeContentProjection( + parse('<a><b>hello</b></a>', [createComp('a', ['*']), createComp('b', ['*'])]))) + .toEqual([['a', null], ['b', 0], ['#text(hello)', 0]]); }); it('should project children of components with ngNonBindable', () => { - expect(humanizeContentProjection(parse('<div ngNonBindable>{{hello}}<span></span></div>', [ - createComp('div', ['*']) - ]))).toEqual([['div', null], ['#text({{hello}})', 0], ['span', 0]]); + expect(humanizeContentProjection(parse('<div ngNonBindable>{{hello}}<span></span></div>', + [createComp('div', ['*'])]))) + .toEqual([['div', null], ['#text({{hello}})', 0], ['span', 0]]); }); it('should match the element when there is an inline template', () => { - expect(humanizeContentProjection(parse('<div><b *ngIf="cond"></b></div>', [ - createComp('div', ['a', 'b']), ngIf - ]))).toEqual([['div', null], ['template', 1], ['b', null]]); + expect(humanizeContentProjection( + parse('<div><b *ngIf="cond"></b></div>', [createComp('div', ['a', 'b']), ngIf]))) + .toEqual([['div', null], ['template', 1], ['b', null]]); }); describe('ngProjectAs', () => { it('should override elements', () => { - expect(humanizeContentProjection(parse('<div><a ngProjectAs="b"></a></div>', [ - createComp('div', ['a', 'b']) - ]))).toEqual([['div', null], ['a', 1]]); + expect(humanizeContentProjection( + parse('<div><a ngProjectAs="b"></a></div>', [createComp('div', ['a', 'b'])]))) + .toEqual([['div', null], ['a', 1]]); }); it('should override <ng-content>', () => { - expect(humanizeContentProjection(parse( - '<div><ng-content ngProjectAs="b"></ng-content></div>', - [createComp('div', ['ng-content', 'b'])]))) + expect(humanizeContentProjection( + parse('<div><ng-content ngProjectAs="b"></ng-content></div>', + [createComp('div', ['ng-content', 'b'])]))) .toEqual([['div', null], ['ng-content', 1]]); }); it('should override <template>', () => { - expect(humanizeContentProjection(parse( - '<div><template ngProjectAs="b"></template></div>', - [createComp('div', ['template', 'b'])]))) + expect(humanizeContentProjection(parse('<div><template ngProjectAs="b"></template></div>', + [createComp('div', ['template', 'b'])]))) .toEqual([['div', null], ['template', 1]]); }); it('should override inline templates', () => { - expect(humanizeContentProjection(parse( - '<div><a *ngIf="cond" ngProjectAs="b"></a></div>', - [createComp('div', ['a', 'b']), ngIf]))) + expect(humanizeContentProjection(parse('<div><a *ngIf="cond" ngProjectAs="b"></a></div>', + [createComp('div', ['a', 'b']), ngIf]))) .toEqual([['div', null], ['template', 1], ['a', null]]); }); }); @@ -726,65 +817,72 @@ Property binding a not used by any directive on an embedded template ("[ERROR -> () => { expect(humanizeTplAst(parse('<link rel="stylesheet" href="http://someurl">a', []))) .toEqual([ - [ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], - [AttrAst, 'href', 'http://someurl'], [TextAst, 'a'] + [ElementAst, 'link'], + [AttrAst, 'rel', 'stylesheet'], + [AttrAst, 'href', 'http://someurl'], + [TextAst, 'a'] ]); }); it('should keep <link rel="stylesheet"> elements if they have no uri', () => { - expect(humanizeTplAst(parse('<link rel="stylesheet">a', [ - ]))).toEqual([[ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], [TextAst, 'a']]); - expect(humanizeTplAst(parse('<link REL="stylesheet">a', [ - ]))).toEqual([[ElementAst, 'link'], [AttrAst, 'REL', 'stylesheet'], [TextAst, 'a']]); + expect(humanizeTplAst(parse('<link rel="stylesheet">a', []))) + .toEqual([[ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], [TextAst, 'a']]); + expect(humanizeTplAst(parse('<link REL="stylesheet">a', []))) + .toEqual([[ElementAst, 'link'], [AttrAst, 'REL', 'stylesheet'], [TextAst, 'a']]); }); it('should ignore <link rel="stylesheet"> elements if they have a relative uri', () => { - expect(humanizeTplAst(parse('<link rel="stylesheet" href="./other.css">a', [ - ]))).toEqual([[TextAst, 'a']]); - expect(humanizeTplAst(parse('<link rel="stylesheet" HREF="./other.css">a', [ - ]))).toEqual([[TextAst, 'a']]); + expect(humanizeTplAst(parse('<link rel="stylesheet" href="./other.css">a', []))) + .toEqual([[TextAst, 'a']]); + expect(humanizeTplAst(parse('<link rel="stylesheet" HREF="./other.css">a', []))) + .toEqual([[TextAst, 'a']]); }); it('should ignore <link rel="stylesheet"> elements if they have a package: uri', () => { - expect(humanizeTplAst(parse('<link rel="stylesheet" href="package:somePackage">a', [ - ]))).toEqual([[TextAst, 'a']]); + expect(humanizeTplAst(parse('<link rel="stylesheet" href="package:somePackage">a', []))) + .toEqual([[TextAst, 'a']]); }); }); it('should ignore bindings on children of elements with ngNonBindable', () => { - expect(humanizeTplAst(parse('<div ngNonBindable>{{b}}</div>', [ - ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, '{{b}}']]); + expect(humanizeTplAst(parse('<div ngNonBindable>{{b}}</div>', []))) + .toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, '{{b}}']]); }); it('should keep nested children of elements with ngNonBindable', () => { - expect(humanizeTplAst(parse('<div ngNonBindable><span>{{b}}</span></div>', []))).toEqual([ - [ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [ElementAst, 'span'], - [TextAst, '{{b}}'] - ]); + expect(humanizeTplAst(parse('<div ngNonBindable><span>{{b}}</span></div>', []))) + .toEqual([ + [ElementAst, 'div'], + [AttrAst, 'ngNonBindable', ''], + [ElementAst, 'span'], + [TextAst, '{{b}}'] + ]); }); it('should ignore <script> elements inside of elements with ngNonBindable', () => { - expect(humanizeTplAst(parse('<div ngNonBindable><script></script>a</div>', [ - ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); + expect(humanizeTplAst(parse('<div ngNonBindable><script></script>a</div>', []))) + .toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); }); it('should ignore <style> elements inside of elements with ngNonBindable', () => { - expect(humanizeTplAst(parse('<div ngNonBindable><style></style>a</div>', [ - ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); + expect(humanizeTplAst(parse('<div ngNonBindable><style></style>a</div>', []))) + .toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); }); it('should ignore <link rel="stylesheet"> elements inside of elements with ngNonBindable', () => { - expect(humanizeTplAst(parse('<div ngNonBindable><link rel="stylesheet">a</div>', [ - ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); + expect(humanizeTplAst(parse('<div ngNonBindable><link rel="stylesheet">a</div>', []))) + .toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); }); it('should convert <ng-content> elements into regular elements inside of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable><ng-content></ng-content>a</div>', []))) .toEqual([ - [ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [ElementAst, 'ng-content'], + [ElementAst, 'div'], + [AttrAst, 'ngNonBindable', ''], + [ElementAst, 'ng-content'], [TextAst, 'a'] ]); }); @@ -794,54 +892,62 @@ Property binding a not used by any directive on an embedded template ("[ERROR -> describe('source spans', () => { it('should support ng-content', () => { var parsed = parse('<ng-content select="a">', []); - expect(humanizeTplAstSourceSpans(parsed)).toEqual([ - [NgContentAst, '<ng-content select="a">'] - ]); + expect(humanizeTplAstSourceSpans(parsed)) + .toEqual([[NgContentAst, '<ng-content select="a">']]); }); it('should support embedded template', () => { - expect(humanizeTplAstSourceSpans(parse('<template></template>', [ - ]))).toEqual([[EmbeddedTemplateAst, '<template>']]); + expect(humanizeTplAstSourceSpans(parse('<template></template>', []))) + .toEqual([[EmbeddedTemplateAst, '<template>']]); }); it('should support element and attributes', () => { - expect(humanizeTplAstSourceSpans(parse('<div key=value>', []))).toEqual([ - [ElementAst, 'div', '<div key=value>'], [AttrAst, 'key', 'value', 'key=value'] - ]); + expect(humanizeTplAstSourceSpans(parse('<div key=value>', []))) + .toEqual( + [[ElementAst, 'div', '<div key=value>'], [AttrAst, 'key', 'value', 'key=value']]); }); it('should support variables', () => { var dirA = CompileDirectiveMetadata.create( {selector: '[a]', type: new CompileTypeMetadata({name: 'DirA'}), exportAs: 'dirA'}); - expect(humanizeTplAstSourceSpans(parse('<div a #a="dirA"></div>', [dirA]))).toEqual([ - [ElementAst, 'div', '<div a #a="dirA">'], [AttrAst, 'a', '', 'a'], - [DirectiveAst, dirA, '<div a #a="dirA">'], [VariableAst, 'a', 'dirA', '#a="dirA"'] - ]); + expect(humanizeTplAstSourceSpans(parse('<div a #a="dirA"></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div', '<div a #a="dirA">'], + [AttrAst, 'a', '', 'a'], + [DirectiveAst, dirA, '<div a #a="dirA">'], + [VariableAst, 'a', 'dirA', '#a="dirA"'] + ]); }); it('should support event', () => { - expect(humanizeTplAstSourceSpans(parse('<div (window:event)="v">', []))).toEqual([ - [ElementAst, 'div', '<div (window:event)="v">'], - [BoundEventAst, 'event', 'window', 'v', '(window:event)="v"'] - ]); + expect(humanizeTplAstSourceSpans(parse('<div (window:event)="v">', []))) + .toEqual([ + [ElementAst, 'div', '<div (window:event)="v">'], + [BoundEventAst, 'event', 'window', 'v', '(window:event)="v"'] + ]); }); it('should support element property', () => { - expect(humanizeTplAstSourceSpans(parse('<div [someProp]="v">', []))).toEqual([ - [ElementAst, 'div', '<div [someProp]="v">'], - [ - BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null, - '[someProp]="v"' - ] - ]); + expect(humanizeTplAstSourceSpans(parse('<div [someProp]="v">', []))) + .toEqual([ + [ElementAst, 'div', '<div [someProp]="v">'], + [ + BoundElementPropertyAst, + PropertyBindingType.Property, + 'someProp', + 'v', + null, + '[someProp]="v"' + ] + ]); }); it('should support bound text', () => { - expect(humanizeTplAstSourceSpans(parse('{{a}}', [ - ]))).toEqual([[BoundTextAst, '{{ a }}', '{{a}}']]); + expect(humanizeTplAstSourceSpans(parse('{{a}}', []))) + .toEqual([[BoundTextAst, '{{ a }}', '{{a}}']]); }); it('should support text nodes', () => { @@ -857,12 +963,13 @@ Property binding a not used by any directive on an embedded template ("[ERROR -> type: new CompileTypeMetadata({name: 'ZComp'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); - expect(humanizeTplAstSourceSpans(parse('<div a>', [dirA, comp]))).toEqual([ - [ElementAst, 'div', '<div a>'], - [AttrAst, 'a', '', 'a'], - [DirectiveAst, comp, '<div a>'], - [DirectiveAst, dirA, '<div a>'], - ]); + expect(humanizeTplAstSourceSpans(parse('<div a>', [dirA, comp]))) + .toEqual([ + [ElementAst, 'div', '<div a>'], + [AttrAst, 'a', '', 'a'], + [DirectiveAst, comp, '<div a>'], + [DirectiveAst, dirA, '<div a>'], + ]); }); it('should support directive in namespace', () => { @@ -886,10 +993,12 @@ Property binding a not used by any directive on an embedded template ("[ERROR -> it('should support directive property', () => { var dirA = CompileDirectiveMetadata.create( {selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['aProp']}); - expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo"></div>', [dirA]))).toEqual([ - [ElementAst, 'div', '<div [aProp]="foo">'], [DirectiveAst, dirA, '<div [aProp]="foo">'], - [BoundDirectivePropertyAst, 'aProp', 'foo', '[aProp]="foo"'] - ]); + expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo"></div>', [dirA]))) + .toEqual([ + [ElementAst, 'div', '<div [aProp]="foo">'], + [DirectiveAst, dirA, '<div [aProp]="foo">'], + [BoundDirectivePropertyAst, 'aProp', 'foo', '[aProp]="foo"'] + ]); }); }); @@ -965,7 +1074,11 @@ class TemplateHumanizer implements TemplateAstVisitor { } visitElementProperty(ast: BoundElementPropertyAst, context: any): any { var res = [ - BoundElementPropertyAst, ast.type, ast.name, expressionUnparser.unparse(ast.value), ast.unit + BoundElementPropertyAst, + ast.type, + ast.name, + expressionUnparser.unparse(ast.value), + ast.unit ]; this.result.push(this._appendContext(ast, res)); return null; diff --git a/modules/angular2/test/compiler/template_preparser_spec.ts b/modules/angular2/test/compiler/template_preparser_spec.ts index 4d2dfc5931..80b550de37 100644 --- a/modules/angular2/test/compiler/template_preparser_spec.ts +++ b/modules/angular2/test/compiler/template_preparser_spec.ts @@ -1,7 +1,24 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {HtmlParser} from 'angular2/src/compiler/html_parser'; -import {preparseElement, PreparsedElementType, PreparsedElement} from 'angular2/src/compiler/template_preparser'; +import { + preparseElement, + PreparsedElementType, + PreparsedElement +} from 'angular2/src/compiler/template_preparser'; export function main() { describe('preparseElement', () => { diff --git a/modules/angular2/test/compiler/url_resolver_spec.ts b/modules/angular2/test/compiler/url_resolver_spec.ts index a83f241ab3..420ef7ae44 100644 --- a/modules/angular2/test/compiler/url_resolver_spec.ts +++ b/modules/angular2/test/compiler/url_resolver_spec.ts @@ -1,4 +1,14 @@ -import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, inject} from 'angular2/testing_internal'; +import { + describe, + it, + expect, + beforeEach, + ddescribe, + iit, + xit, + el, + inject +} from 'angular2/testing_internal'; import {IS_DART} from 'angular2/src/facade/lang'; import {UrlResolver} from 'angular2/src/compiler/url_resolver'; @@ -73,47 +83,47 @@ export function main() { it('should not resolve urls against the baseUrl when the url contains a scheme', () => { resolver = new UrlResolver('my_packages_dir'); - expect(resolver.resolve('base/', 'package:file')).toEqual('my_packages_dir/file'); - expect(resolver.resolve('base/', 'http:super_file')).toEqual('http:super_file'); - expect(resolver.resolve('base/', './mega_file')).toEqual('base/mega_file'); + expect(resolver.resolve("base/", 'package:file')).toEqual('my_packages_dir/file'); + expect(resolver.resolve("base/", 'http:super_file')).toEqual('http:super_file'); + expect(resolver.resolve("base/", './mega_file')).toEqual('base/mega_file'); }); }); - describe('packages', () => { - it('should resolve a url based on the application package', () => { - resolver = new UrlResolver('my_packages_dir'); - expect(resolver.resolve(null, 'package:some/dir/file.txt')) - .toEqual('my_packages_dir/some/dir/file.txt'); - expect(resolver.resolve(null, 'some/dir/file.txt')).toEqual('some/dir/file.txt'); - }); + describe('packages', + () => { + it('should resolve a url based on the application package', () => { + resolver = new UrlResolver('my_packages_dir'); + expect(resolver.resolve(null, 'package:some/dir/file.txt')) + .toEqual('my_packages_dir/some/dir/file.txt'); + expect(resolver.resolve(null, 'some/dir/file.txt')).toEqual('some/dir/file.txt'); + }); - it('should contain a default value of "/packages" when nothing is provided for DART', - inject([UrlResolver], (resolver: UrlResolver) => { - if (IS_DART) { - expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file'); - } - })); + it('should contain a default value of "/packages" when nothing is provided for DART', + inject([UrlResolver], (resolver: UrlResolver) => { + if (IS_DART) { + expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file'); + } + })); - it('should contain a default value of "/" when nothing is provided for TS/ESM', - inject([UrlResolver], (resolver: UrlResolver) => { - if (!IS_DART) { - expect(resolver.resolve(null, 'package:file')).toEqual('/file'); - } - })); + it('should contain a default value of "/" when nothing is provided for TS/ESM', + inject([UrlResolver], (resolver: UrlResolver) => { + if (!IS_DART) { + expect(resolver.resolve(null, 'package:file')).toEqual('/file'); + } + })); - it('should resolve a package value when present within the baseurl', () => { - resolver = new UrlResolver('/my_special_dir'); - expect(resolver.resolve('package:some_dir/', 'matias.html')) - .toEqual('/my_special_dir/some_dir/matias.html'); - }); - }) + it('should resolve a package value when present within the baseurl', () => { + resolver = new UrlResolver('/my_special_dir'); + expect(resolver.resolve('package:some_dir/', 'matias.html')) + .toEqual('/my_special_dir/some_dir/matias.html'); + }); + }) - describe('corner and error cases', () => { - it('should encode URLs before resolving', - () => { - expect(resolver.resolve('foo/baz', `<p #p>Hello + describe('corner and error cases', () => { + it('should encode URLs before resolving', () => { + expect(resolver.resolve('foo/baz', `<p #p>Hello </p>`)).toEqual('foo/%3Cp%20#p%3EHello%0A%20%20%20%20%20%20%20%20%3C/p%3E'); - }); - }); + }); + }); }); } diff --git a/modules/angular2/test/compiler/util_spec.ts b/modules/angular2/test/compiler/util_spec.ts index b91138433f..ae3c9e64f6 100644 --- a/modules/angular2/test/compiler/util_spec.ts +++ b/modules/angular2/test/compiler/util_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + TestComponentBuilder +} from 'angular2/testing_internal'; import {IS_DART} from 'angular2/src/facade/lang'; import {escapeSingleQuoteString, escapeDoubleQuoteString} from 'angular2/src/compiler/util'; diff --git a/modules/angular2/test/compiler/xhr_mock_spec.ts b/modules/angular2/test/compiler/xhr_mock_spec.ts index cd1f304264..64f45a3b4a 100644 --- a/modules/angular2/test/compiler/xhr_mock_spec.ts +++ b/modules/angular2/test/compiler/xhr_mock_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, +} from 'angular2/testing_internal'; import {MockXHR} from 'angular2/src/compiler/xhr_mock'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/test/core/application_ref_spec.ts b/modules/angular2/test/core/application_ref_spec.ts index 35dc1b4d3d..3496db1fa3 100644 --- a/modules/angular2/test/core/application_ref_spec.ts +++ b/modules/angular2/test/core/application_ref_spec.ts @@ -1,28 +1,43 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, el, AsyncTestCompleter, fakeAsync, tick, inject, SpyObject} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + el, + AsyncTestCompleter, + fakeAsync, + tick, + inject, + SpyObject +} from 'angular2/testing_internal'; import {SpyChangeDetector} from './spies'; -import {ApplicationRef_, ApplicationRef, PlatformRef_} from 'angular2/src/core/application_ref'; -import {Injector, Provider, APP_INITIALIZER} from 'angular2/core'; -import {ChangeDetectorRef_} from 'angular2/src/core/change_detection/change_detector_ref'; -import {PromiseWrapper, PromiseCompleter, TimerWrapper} from 'angular2/src/facade/async'; -import {ListWrapper} from 'angular2/src/facade/collection'; +import {ApplicationRef_, ApplicationRef, PlatformRef_} from "angular2/src/core/application_ref"; +import {Injector, Provider, APP_INITIALIZER} from "angular2/core"; +import {ChangeDetectorRef_} from "angular2/src/core/change_detection/change_detector_ref"; +import {PromiseWrapper, PromiseCompleter, TimerWrapper} from "angular2/src/facade/async"; +import {ListWrapper} from "angular2/src/facade/collection"; import {ExceptionHandler} from 'angular2/src/facade/exception_handler'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; export function main() { - describe('ApplicationRef', () => { - it('should throw when reentering tick', () => { + describe("ApplicationRef", () => { + it("should throw when reentering tick", () => { var cd = <any>new SpyChangeDetector(); var ref = new ApplicationRef_(null, null, null); ref.registerChangeDetector(new ChangeDetectorRef_(cd)); - cd.spy('detectChanges').andCallFake(() => ref.tick()); - expect(() => ref.tick()).toThrowError('ApplicationRef.tick is called recursively'); + cd.spy("detectChanges").andCallFake(() => ref.tick()); + expect(() => ref.tick()).toThrowError("ApplicationRef.tick is called recursively"); }); }); - describe('PlatformRef', () => { + describe("PlatformRef", () => { var exceptionHandler = new Provider(ExceptionHandler, {useValue: new ExceptionHandler(DOM, true)}); - describe('asyncApplication', () => { + describe("asyncApplication", () => { function expectProviders(injector: Injector, providers: Array<any>): void { for (let i = 0; i < providers.length; i++) { let provider = providers[i]; @@ -30,7 +45,7 @@ export function main() { } } - it('should merge syncronous and asyncronous providers', + it("should merge syncronous and asyncronous providers", inject([AsyncTestCompleter, Injector], (async, injector) => { let ref = new PlatformRef_(injector, null); let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()}), exceptionHandler]; @@ -43,18 +58,19 @@ export function main() { }); })); - it('should allow function to be null', + it("should allow function to be null", inject([AsyncTestCompleter, Injector], (async, injector) => { let ref = new PlatformRef_(injector, null); let SYNC_PROVIDERS = [new Provider(Bar, {useValue: new Bar()}), exceptionHandler]; - ref.asyncApplication(null, SYNC_PROVIDERS).then((appRef) => { - expectProviders(appRef.injector, SYNC_PROVIDERS); - async.done(); - }); + ref.asyncApplication(null, SYNC_PROVIDERS) + .then((appRef) => { + expectProviders(appRef.injector, SYNC_PROVIDERS); + async.done(); + }); })); - function mockAsyncAppInitializer( - completer: PromiseCompleter<any>, providers: Array<any> = null, injector?: Injector) { + function mockAsyncAppInitializer(completer: PromiseCompleter<any>, + providers: Array<any> = null, injector?: Injector) { return () => { if (providers != null) { expectProviders(injector, providers); @@ -64,54 +80,57 @@ export function main() { }; } - it('should wait for asyncronous app initializers', + it("should wait for asyncronous app initializers", inject([AsyncTestCompleter, Injector], (async, injector) => { let ref = new PlatformRef_(injector, null); let completer: PromiseCompleter<any> = PromiseWrapper.completer(); let SYNC_PROVIDERS = [ new Provider(Bar, {useValue: new Bar()}), - new Provider( - APP_INITIALIZER, {useValue: mockAsyncAppInitializer(completer), multi: true}) + new Provider(APP_INITIALIZER, + {useValue: mockAsyncAppInitializer(completer), multi: true}) ]; - ref.asyncApplication(null, [SYNC_PROVIDERS, exceptionHandler]).then((appRef) => { - expectProviders(appRef.injector, SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); - completer.promise.then((_) => async.done()); - }); + ref.asyncApplication(null, [SYNC_PROVIDERS, exceptionHandler]) + .then((appRef) => { + expectProviders(appRef.injector, + SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); + completer.promise.then((_) => async.done()); + }); })); - it('should wait for async providers and then async app initializers', + it("should wait for async providers and then async app initializers", inject([AsyncTestCompleter, Injector], (async, injector) => { let ref = new PlatformRef_(injector, null); let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()})]; let completer: PromiseCompleter<any> = PromiseWrapper.completer(); let SYNC_PROVIDERS = [ - new Provider(Bar, {useValue: new Bar()}), new Provider(APP_INITIALIZER, { - useFactory: (injector) => - mockAsyncAppInitializer(<any>completer, ASYNC_PROVIDERS, injector), - multi: true, - deps: [Injector] - }) + new Provider(Bar, {useValue: new Bar()}), + new Provider(APP_INITIALIZER, + { + useFactory: (injector) => mockAsyncAppInitializer( + <any>completer, ASYNC_PROVIDERS, injector), + multi: true, + deps: [Injector] + }) ]; - ref.asyncApplication( - (zone) => PromiseWrapper.resolve(ASYNC_PROVIDERS), - [SYNC_PROVIDERS, exceptionHandler]) + ref.asyncApplication((zone) => PromiseWrapper.resolve(ASYNC_PROVIDERS), + [SYNC_PROVIDERS, exceptionHandler]) .then((appRef) => { - expectProviders( - appRef.injector, SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); + expectProviders(appRef.injector, + SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); completer.promise.then((_) => async.done()); }); })); }); - describe('application', () => { - it('should throw if an APP_INITIIALIZER returns a promise', inject([Injector], (injector) => { + describe("application", () => { + it("should throw if an APP_INITIIALIZER returns a promise", inject([Injector], (injector) => { let ref = new PlatformRef_(injector, null); let appInitializer = new Provider( APP_INITIALIZER, {useValue: () => PromiseWrapper.resolve([]), multi: true}); expect(() => ref.application([appInitializer, exceptionHandler])) .toThrowError( - 'Cannot use asyncronous app initializers with application. Use asyncApplication instead.'); + "Cannot use asyncronous app initializers with application. Use asyncApplication instead."); })); }); }); diff --git a/modules/angular2/test/core/change_detection/change_detector_config.ts b/modules/angular2/test/core/change_detection/change_detector_config.ts index daf1657ba3..f3afe3fa4b 100644 --- a/modules/angular2/test/core/change_detection/change_detector_config.ts +++ b/modules/angular2/test/core/change_detection/change_detector_config.ts @@ -1,6 +1,16 @@ import {ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {isBlank, isPresent} from 'angular2/src/facade/lang'; -import {ChangeDetectionStrategy, BindingRecord, ChangeDetectorDefinition, DirectiveIndex, DirectiveRecord, Lexer, Locals, Parser, ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectionStrategy, + BindingRecord, + ChangeDetectorDefinition, + DirectiveIndex, + DirectiveRecord, + Lexer, + Locals, + Parser, + ChangeDetectorGenConfig +} from 'angular2/src/core/change_detection/change_detection'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; @@ -22,16 +32,16 @@ function _createBindingRecords(expression: string): BindingRecord[] { } function _createEventRecords(expression: string): BindingRecord[] { - var eq = expression.indexOf('='); + var eq = expression.indexOf("="); var eventName = expression.substring(1, eq - 1); var exp = expression.substring(eq + 2, expression.length - 1); var ast = _getParser().parseAction(exp, 'location'); return [BindingRecord.createForEvent(ast, eventName, 0)]; } -function _createHostEventRecords( - expression: string, directiveRecord: DirectiveRecord): BindingRecord[] { - var parts = expression.split('='); +function _createHostEventRecords(expression: string, + directiveRecord: DirectiveRecord): BindingRecord[] { + var parts = expression.split("="); var eventName = parts[0].substring(1, parts[0].length - 1); var exp = parts[1].substring(1, parts[1].length - 1); @@ -80,8 +90,8 @@ export function getDefinition(id: string): TestDefinition { var variableBindings = []; var eventRecords = _createBindingRecords(id); var directiveRecords = []; - let cdDef = new ChangeDetectorDefinition( - id, strategy, variableBindings, eventRecords, [], directiveRecords, genConfig); + let cdDef = new ChangeDetectorDefinition(id, strategy, variableBindings, eventRecords, [], + directiveRecords, genConfig); testDef = new TestDefinition(id, cdDef, null); } else if (ListWrapper.indexOf(_availableEventDefinitions, id) >= 0) { @@ -96,9 +106,9 @@ export function getDefinition(id: string): TestDefinition { [_DirectiveUpdating.basicRecords[0], _DirectiveUpdating.basicRecords[1]], genConfig); testDef = new TestDefinition(id, cdDef, null); - } else if (id == 'updateElementProduction') { + } else if (id == "updateElementProduction") { var genConfig = new ChangeDetectorGenConfig(false, false, true); - var records = _createBindingRecords('name'); + var records = _createBindingRecords("name"); let cdDef = new ChangeDetectorDefinition(id, null, [], records, [], [], genConfig); testDef = new TestDefinition(id, cdDef, null); } @@ -120,13 +130,13 @@ export class TestDefinition { */ export function getAllDefinitions(): TestDefinition[] { var allDefs = _availableDefinitions; - allDefs = ListWrapper.concat( - allDefs, StringMapWrapper.keys(_ExpressionWithLocals.availableDefinitions)); + allDefs = ListWrapper.concat(allDefs, + StringMapWrapper.keys(_ExpressionWithLocals.availableDefinitions)); allDefs = allDefs.concat(StringMapWrapper.keys(_ExpressionWithMode.availableDefinitions)); allDefs = allDefs.concat(StringMapWrapper.keys(_DirectiveUpdating.availableDefinitions)); allDefs = allDefs.concat(_availableEventDefinitions); allDefs = allDefs.concat(_availableHostEventDefinitions); - allDefs = allDefs.concat(['updateElementProduction']); + allDefs = allDefs.concat(["updateElementProduction"]); return allDefs.map(getDefinition); } @@ -139,8 +149,8 @@ class _ExpressionWithLocals { var bindingRecords = _createBindingRecords(this._expression); var directiveRecords = []; var genConfig = new ChangeDetectorGenConfig(true, true, true); - return new ChangeDetectorDefinition( - '(empty id)', strategy, variableBindings, bindingRecords, [], directiveRecords, genConfig); + return new ChangeDetectorDefinition('(empty id)', strategy, variableBindings, bindingRecords, + [], directiveRecords, genConfig); } /** @@ -165,9 +175,8 @@ class _ExpressionWithLocals { } class _ExpressionWithMode { - constructor( - private _strategy: ChangeDetectionStrategy, private _withRecords: boolean, - private _withEvents: boolean) {} + constructor(private _strategy: ChangeDetectionStrategy, private _withRecords: boolean, + private _withEvents: boolean) {} createChangeDetectorDefinition(): ChangeDetectorDefinition { var variableBindings = []; @@ -185,12 +194,12 @@ class _ExpressionWithMode { }); if (this._withRecords) { - var updateDirWithOnDefaultRecord = BindingRecord.createForDirective( - _getParser().parseBinding('42', 'location'), 'a', (o, v) => (<any>o).a = v, - dirRecordWithDefault); - var updateDirWithOnPushRecord = BindingRecord.createForDirective( - _getParser().parseBinding('42', 'location'), 'a', (o, v) => (<any>o).a = v, - dirRecordWithOnPush); + var updateDirWithOnDefaultRecord = + BindingRecord.createForDirective(_getParser().parseBinding('42', 'location'), 'a', + (o, v) => (<any>o).a = v, dirRecordWithDefault); + var updateDirWithOnPushRecord = + BindingRecord.createForDirective(_getParser().parseBinding('42', 'location'), 'a', + (o, v) => (<any>o).a = v, dirRecordWithOnPush); directiveRecords = [dirRecordWithDefault, dirRecordWithOnPush]; bindingRecords = [updateDirWithOnDefaultRecord, updateDirWithOnPushRecord]; @@ -198,16 +207,15 @@ class _ExpressionWithMode { if (this._withEvents) { directiveRecords = [dirRecordWithDefault, dirRecordWithOnPush]; - eventRecords = ListWrapper.concat( - _createEventRecords('(event)=\'false\''), - _createHostEventRecords('(host-event)=\'false\'', dirRecordWithOnPush)) + eventRecords = + ListWrapper.concat(_createEventRecords("(event)='false'"), + _createHostEventRecords("(host-event)='false'", dirRecordWithOnPush)) } var genConfig = new ChangeDetectorGenConfig(true, true, true); - return new ChangeDetectorDefinition( - '(empty id)', this._strategy, variableBindings, bindingRecords, eventRecords, - directiveRecords, genConfig); + return new ChangeDetectorDefinition('(empty id)', this._strategy, variableBindings, + bindingRecords, eventRecords, directiveRecords, genConfig); } /** @@ -227,29 +235,27 @@ class _ExpressionWithMode { } class _DirectiveUpdating { - constructor( - private _bindingRecords: BindingRecord[], private _directiveRecords: DirectiveRecord[]) {} + constructor(private _bindingRecords: BindingRecord[], + private _directiveRecords: DirectiveRecord[]) {} createChangeDetectorDefinition(): ChangeDetectorDefinition { var strategy = null; var variableBindings = []; var genConfig = new ChangeDetectorGenConfig(true, true, true); - return new ChangeDetectorDefinition( - '(empty id)', strategy, variableBindings, this._bindingRecords, [], this._directiveRecords, - genConfig); + return new ChangeDetectorDefinition('(empty id)', strategy, variableBindings, + this._bindingRecords, [], this._directiveRecords, + genConfig); } static updateA(expression: string, dirRecord): BindingRecord { - return BindingRecord.createForDirective( - _getParser().parseBinding(expression, 'location'), 'a', (o, v) => (<any>o).a = v, - dirRecord); + return BindingRecord.createForDirective(_getParser().parseBinding(expression, 'location'), 'a', + (o, v) => (<any>o).a = v, dirRecord); } static updateB(expression: string, dirRecord): BindingRecord { - return BindingRecord.createForDirective( - _getParser().parseBinding(expression, 'location'), 'b', (o, v) => (<any>o).b = v, - dirRecord); + return BindingRecord.createForDirective(_getParser().parseBinding(expression, 'location'), 'b', + (o, v) => (<any>o).b = v, dirRecord); } static basicRecords: DirectiveRecord[] = [ @@ -298,15 +304,16 @@ class _DirectiveUpdating { 'directNoDispatcher': new _DirectiveUpdating( [_DirectiveUpdating.updateA('42', _DirectiveUpdating.basicRecords[0])], [_DirectiveUpdating.basicRecords[0]]), - 'groupChanges': new _DirectiveUpdating( - [ - _DirectiveUpdating.updateA('1', _DirectiveUpdating.basicRecords[0]), - _DirectiveUpdating.updateB('2', _DirectiveUpdating.basicRecords[0]), - BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[0]), - _DirectiveUpdating.updateA('3', _DirectiveUpdating.basicRecords[1]), - BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[1]) - ], - [_DirectiveUpdating.basicRecords[0], _DirectiveUpdating.basicRecords[1]]), + 'groupChanges': + new _DirectiveUpdating( + [ + _DirectiveUpdating.updateA('1', _DirectiveUpdating.basicRecords[0]), + _DirectiveUpdating.updateB('2', _DirectiveUpdating.basicRecords[0]), + BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[0]), + _DirectiveUpdating.updateA('3', _DirectiveUpdating.basicRecords[1]), + BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[1]) + ], + [_DirectiveUpdating.basicRecords[0], _DirectiveUpdating.basicRecords[1]]), 'directiveDoCheck': new _DirectiveUpdating( [BindingRecord.createDirectiveDoCheck(_DirectiveUpdating.basicRecords[0])], [_DirectiveUpdating.basicRecords[0]]), @@ -318,14 +325,20 @@ class _DirectiveUpdating { 'noCallbacks': new _DirectiveUpdating( [_DirectiveUpdating.updateA('1', _DirectiveUpdating.recordNoCallbacks)], [_DirectiveUpdating.recordNoCallbacks]), - 'readingDirectives': new _DirectiveUpdating( - [BindingRecord.createForHostProperty( - new DirectiveIndex(0, 0), _getParser().parseBinding('a', 'location'), PROP_NAME)], - [_DirectiveUpdating.basicRecords[0]]), - 'interpolation': new _DirectiveUpdating( - [BindingRecord.createForElementProperty( - _getParser().parseInterpolation('B{{a}}A', 'location'), 0, PROP_NAME)], - []) + 'readingDirectives': + new _DirectiveUpdating( + [ + BindingRecord.createForHostProperty( + new DirectiveIndex(0, 0), _getParser().parseBinding('a', 'location'), PROP_NAME) + ], + [_DirectiveUpdating.basicRecords[0]]), + 'interpolation': + new _DirectiveUpdating( + [ + BindingRecord.createForElementProperty( + _getParser().parseInterpolation('B{{a}}A', 'location'), 0, PROP_NAME) + ], + []) }; } @@ -377,8 +390,8 @@ var _availableDefinitions = [ '{z: a}', 'name | pipe', '(name | pipe).length', - 'name | pipe:\'one\':address.city', - 'name | pipe:\'a\':\'b\' | pipe:0:1:2', + "name | pipe:'one':address.city", + "name | pipe:'a':'b' | pipe:0:1:2", 'value', 'a', 'address.city', diff --git a/modules/angular2/test/core/change_detection/change_detector_ref_spec.ts b/modules/angular2/test/core/change_detection/change_detector_ref_spec.ts index 977b152d3d..0da57ec15c 100644 --- a/modules/angular2/test/core/change_detection/change_detector_ref_spec.ts +++ b/modules/angular2/test/core/change_detection/change_detector_ref_spec.ts @@ -1,6 +1,20 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, tick, fakeAsync} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + tick, + fakeAsync +} from 'angular2/testing_internal'; -import {ChangeDetectorRef, ChangeDetectorRef_} from 'angular2/src/core/change_detection/change_detector_ref'; +import { + ChangeDetectorRef, + ChangeDetectorRef_ +} from 'angular2/src/core/change_detection/change_detector_ref'; import {SpyChangeDetector} from '../spies'; diff --git a/modules/angular2/test/core/change_detection/change_detector_spec.ts b/modules/angular2/test/core/change_detection/change_detector_spec.ts index adf041576b..74e40ea303 100644 --- a/modules/angular2/test/core/change_detection/change_detector_spec.ts +++ b/modules/angular2/test/core/change_detection/change_detector_spec.ts @@ -1,13 +1,50 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, tick, fakeAsync} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + tick, + fakeAsync +} from 'angular2/testing_internal'; import {SpyChangeDispatcher} from '../spies'; -import {CONST_EXPR, isPresent, isBlank, isNumber, isJsObject, FunctionWrapper, NumberWrapper, normalizeBool} from 'angular2/src/facade/lang'; +import { + CONST_EXPR, + isPresent, + isBlank, + isNumber, + isJsObject, + FunctionWrapper, + NumberWrapper, + normalizeBool +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {ChangeDispatcher, DehydratedException, DynamicChangeDetector, ChangeDetectionError, BindingRecord, DirectiveRecord, DirectiveIndex, PipeTransform, ChangeDetectionStrategy, WrappedValue, DynamicProtoChangeDetector, ChangeDetectorDefinition, Lexer, Parser, Locals, ProtoChangeDetector} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDispatcher, + DehydratedException, + DynamicChangeDetector, + ChangeDetectionError, + BindingRecord, + DirectiveRecord, + DirectiveIndex, + PipeTransform, + ChangeDetectionStrategy, + WrappedValue, + DynamicProtoChangeDetector, + ChangeDetectorDefinition, + Lexer, + Parser, + Locals, + ProtoChangeDetector +} from 'angular2/src/core/change_detection/change_detection'; import {SelectedPipe, Pipes} from 'angular2/src/core/change_detection/pipes'; import {JitProtoChangeDetector} from 'angular2/src/core/change_detection/jit_proto_change_detector'; @@ -34,8 +71,8 @@ const _DEFAULT_CONTEXT = CONST_EXPR(new Object()); */ export function main() { ['dynamic', 'JIT', 'Pregen'].forEach(cdType => { - if (cdType == 'JIT' && IS_DART) return; - if (cdType == 'Pregen' && !IS_DART) return; + if (cdType == "JIT" && IS_DART) return; + if (cdType == "Pregen" && !IS_DART) return; describe(`${cdType} Change Detector`, () => { @@ -61,8 +98,8 @@ export function main() { } - function _createChangeDetector( - expression: string, context = _DEFAULT_CONTEXT, registry = null, dispatcher = null) { + function _createChangeDetector(expression: string, context = _DEFAULT_CONTEXT, + registry = null, dispatcher = null) { if (isBlank(dispatcher)) dispatcher = new TestDispatcher(); var testDef = getDefinition(expression); var cd = _getChangeDetectorFactory(testDef.cdDef)(); @@ -79,9 +116,8 @@ export function main() { describe('short-circuit', () => { it('should support short-circuit for the ternary operator', () => { var address = new Address('Sunnyvale', '94085'); - expect(_bindSimpleValue('true ? city : zipcode', address)).toEqual([ - 'propName=Sunnyvale' - ]); + expect(_bindSimpleValue('true ? city : zipcode', address)) + .toEqual(['propName=Sunnyvale']); expect(address.cityGetterCalls).toEqual(1); expect(address.zipCodeGetterCalls).toEqual(0); @@ -376,7 +412,7 @@ export function main() { var registry = new FakePipes('pipe', () => new MultiArgPipe()); var address = new Address('two'); var person = new Person('value', address); - var val = _createChangeDetector('name | pipe:\'one\':address.city', person, registry); + var val = _createChangeDetector("name | pipe:'one':address.city", person, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['value one two default']); }); @@ -384,8 +420,7 @@ export function main() { it('should associate pipes right-to-left', () => { var registry = new FakePipes('pipe', () => new MultiArgPipe()); var person = new Person('value'); - var val = - _createChangeDetector('name | pipe:\'a\':\'b\' | pipe:0:1:2', person, registry); + var val = _createChangeDetector("name | pipe:'a':'b' | pipe:0:1:2", person, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['value a b default 0 1 2']); }); @@ -454,8 +489,8 @@ export function main() { it('should happen directly, without invoking the dispatcher', () => { var val = _createWithoutHydrate('directNoDispatcher'); - val.changeDetector.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1], []), null); + val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1], []), + null); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([]); expect(directive1.a).toEqual(42); @@ -465,8 +500,8 @@ export function main() { describe('ngOnChanges', () => { it('should notify the directive when a group of records changes', () => { var cd = _createWithoutHydrate('groupChanges').changeDetector; - cd.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null); + cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), + null); cd.detectChanges(); expect(directive1.changes).toEqual({'a': 1, 'b': 2}); expect(directive2.changes).toEqual({'a': 3}); @@ -502,8 +537,8 @@ export function main() { it('should notify the directive after it has been checked the first time', () => { var cd = _createWithoutHydrate('directiveOnInit').changeDetector; - cd.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null); + cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), + null); cd.detectChanges(); @@ -545,7 +580,7 @@ export function main() { try { cd.detectChanges(); } catch (e) { - throw new BaseException('Second detectChanges() should not have run detection.'); + throw new BaseException("Second detectChanges() should not have run detection."); } expect(directive3.ngOnInitCalled).toBe(false); }); @@ -554,8 +589,8 @@ export function main() { describe('ngAfterContentInit', () => { it('should be called after processing the content children', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; - cd.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null); + cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), + null); cd.detectChanges(); @@ -593,8 +628,8 @@ export function main() { describe('ngAfterContentChecked', () => { it('should be called after processing all the children', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; - cd.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null); + cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), + null); cd.detectChanges(); @@ -658,10 +693,10 @@ export function main() { parentDirective = new TestDirective(() => { orderOfOperations.push(parentDirective); }); - parent.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []), null); - child.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directiveInShadowDom], []), null); + parent.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []), + null); + child.hydrate(_DEFAULT_CONTEXT, null, + new TestDispatcher([directiveInShadowDom], []), null); parent.detectChanges(); expect(orderOfOperations).toEqual([parentDirective, directiveInShadowDom]); @@ -672,8 +707,8 @@ export function main() { describe('ngAfterViewInit', () => { it('should be called after processing the view children', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; - cd.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null); + cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), + null); cd.detectChanges(); @@ -712,8 +747,8 @@ export function main() { describe('ngAfterViewChecked', () => { it('should be called after processing the view children', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; - cd.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null); + cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), + null); cd.detectChanges(); @@ -777,10 +812,10 @@ export function main() { parentDirective = new TestDirective(null, () => { orderOfOperations.push(parentDirective); }); - parent.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []), null); - child.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([directiveInShadowDom], []), null); + parent.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []), + null); + child.hydrate(_DEFAULT_CONTEXT, null, + new TestDispatcher([directiveInShadowDom], []), null); parent.detectChanges(); expect(orderOfOperations).toEqual([directiveInShadowDom, parentDirective]); @@ -789,9 +824,8 @@ export function main() { describe('ngOnDestroy', () => { it('should be called on dehydration', () => { - var cd = _createChangeDetector( - 'emptyWithDirectiveRecords', _DEFAULT_CONTEXT, null, - new TestDispatcher([directive1, directive2], [])) + var cd = _createChangeDetector('emptyWithDirectiveRecords', _DEFAULT_CONTEXT, null, + new TestDispatcher([directive1, directive2], [])) .changeDetector; cd.dehydrate(); @@ -806,7 +840,7 @@ export function main() { }); }); - describe('logBindingUpdate', () => { + describe("logBindingUpdate", () => { it('should be called for element updates in the dev mode', () => { var person = new Person('bob'); var val = _createChangeDetector('name', person); @@ -815,11 +849,10 @@ export function main() { }); it('should be called for directive updates in the dev mode', () => { - var val = _createChangeDetector( - 'directNoDispatcher', _DEFAULT_CONTEXT, null, - new TestDispatcher([new TestDirective()], [])); + var val = _createChangeDetector('directNoDispatcher', _DEFAULT_CONTEXT, null, + new TestDispatcher([new TestDirective()], [])); val.changeDetector.detectChanges(); - expect(val.dispatcher.debugLog).toEqual(['a=42']); + expect(val.dispatcher.debugLog).toEqual(["a=42"]); }); it('should not be called in the prod mode', () => { @@ -836,8 +869,8 @@ export function main() { var directive = new TestDirective(); directive.a = 'aaa'; - var val = _createChangeDetector( - 'readingDirectives', _DEFAULT_CONTEXT, null, new TestDispatcher([directive], [])); + var val = _createChangeDetector('readingDirectives', _DEFAULT_CONTEXT, null, + new TestDispatcher([directive], [])); val.changeDetector.detectChanges(); @@ -885,9 +918,8 @@ export function main() { it('should handle unexpected errors in the event handler itself', () => { var throwingDispatcher = new SpyChangeDispatcher(); - throwingDispatcher.spy('getDebugContext').andCallFake((_, __) => { - throw new BaseException('boom'); - }); + throwingDispatcher.spy("getDebugContext") + .andCallFake((_, __) => { throw new BaseException('boom'); }); var val = _createChangeDetector('invalidFn(1)', _DEFAULT_CONTEXT, null, throwingDispatcher); @@ -914,21 +946,18 @@ export function main() { it('should fall back to a regular field read when the locals map' + 'does not have the requested field', () => { - expect(_bindSimpleValue('fallbackLocals', new Person('Jim'))).toEqual([ - 'propName=Jim' - ]); + expect(_bindSimpleValue('fallbackLocals', new Person('Jim'))) + .toEqual(['propName=Jim']); }); it('should correctly handle nested properties', () => { var address = new Address('Grenoble'); var person = new Person('Victor', address); - expect(_bindSimpleValue('contextNestedPropertyWithLocals', person)).toEqual([ - 'propName=Grenoble' - ]); - expect(_bindSimpleValue('localPropertyWithSimilarContext', person)).toEqual([ - 'propName=MTV' - ]); + expect(_bindSimpleValue('contextNestedPropertyWithLocals', person)) + .toEqual(['propName=Grenoble']); + expect(_bindSimpleValue('localPropertyWithSimilarContext', person)) + .toEqual(['propName=MTV']); }); }); @@ -1038,9 +1067,9 @@ export function main() { childDirectiveDetectorOnPush.hydrate(_DEFAULT_CONTEXT, null, null, null); childDirectiveDetectorOnPush.mode = ChangeDetectionStrategy.Checked; - directives = new TestDispatcher( - [new TestData(null), new TestData(null)], - [childDirectiveDetectorRegular, childDirectiveDetectorOnPush]); + directives = + new TestDispatcher([new TestData(null), new TestData(null)], + [childDirectiveDetectorRegular, childDirectiveDetectorOnPush]); }); it('should set the mode to CheckOnce when a binding is updated', () => { @@ -1061,7 +1090,7 @@ export function main() { cd.hydrate(_DEFAULT_CONTEXT, null, directives, null); cd.mode = ChangeDetectionStrategy.Checked; - cd.handleEvent('event', 0, null); + cd.handleEvent("event", 0, null); expect(cd.mode).toEqual(ChangeDetectionStrategy.CheckOnce); }); @@ -1070,7 +1099,7 @@ export function main() { var cd = _createWithoutHydrate('onPushWithHostEvent').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, directives, null); - cd.handleEvent('host-event', 0, null); + cd.handleEvent("host-event", 0, null); expect(childDirectiveDetectorOnPush.mode).toEqual(ChangeDetectionStrategy.CheckOnce); }); @@ -1148,7 +1177,7 @@ export function main() { val.changeDetector.dehydrate(); expect(() => {val.changeDetector.detectChanges()}) - .toThrowErrorWith('Attempt to use a dehydrated detector'); + .toThrowErrorWith("Attempt to use a dehydrated detector"); expect(val.dispatcher.log).toEqual(['propName=Bob']); }); }); @@ -1185,42 +1214,42 @@ export function main() { var d: TestDirective; beforeEach(() => { - event = 'EVENT'; + event = "EVENT"; d = new TestDirective(); }); it('should execute events', () => { var val = _createChangeDetector('(event)="onEvent($event)"', d, null); - val.changeDetector.handleEvent('event', 0, event); - expect(d.event).toEqual('EVENT'); + val.changeDetector.handleEvent("event", 0, event); + expect(d.event).toEqual("EVENT"); }); it('should execute host events', () => { var val = _createWithoutHydrate('(host-event)="onEvent($event)"'); - val.changeDetector.hydrate( - _DEFAULT_CONTEXT, null, new TestDispatcher([d, new TestDirective()], []), null); - val.changeDetector.handleEvent('host-event', 0, event); - expect(d.event).toEqual('EVENT'); + val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, + new TestDispatcher([d, new TestDirective()], []), null); + val.changeDetector.handleEvent("host-event", 0, event); + expect(d.event).toEqual("EVENT"); }); it('should support field assignments', () => { var val = _createChangeDetector('(event)="b=a=$event"', d, null); - val.changeDetector.handleEvent('event', 0, event); - expect(d.a).toEqual('EVENT'); - expect(d.b).toEqual('EVENT'); + val.changeDetector.handleEvent("event", 0, event); + expect(d.a).toEqual("EVENT"); + expect(d.b).toEqual("EVENT"); }); it('should support keyed assignments', () => { - d.a = ['OLD']; + d.a = ["OLD"]; var val = _createChangeDetector('(event)="a[0]=$event"', d, null); - val.changeDetector.handleEvent('event', 0, event); - expect(d.a).toEqual(['EVENT']); + val.changeDetector.handleEvent("event", 0, event); + expect(d.a).toEqual(["EVENT"]); }); it('should support chains', () => { d.a = 0; var val = _createChangeDetector('(event)="a=a+1; a=a+1;"', d, null); - val.changeDetector.handleEvent('event', 0, event); + val.changeDetector.handleEvent("event", 0, event); expect(d.a).toEqual(2); }); @@ -1233,22 +1262,22 @@ export function main() { it('should return false if the event handler returned false', () => { var val = _createChangeDetector('(event)="false"', d, null); - var res = val.changeDetector.handleEvent('event', 0, event); + var res = val.changeDetector.handleEvent("event", 0, event); expect(res).toBe(false); val = _createChangeDetector('(event)="true"', d, null); - res = val.changeDetector.handleEvent('event', 0, event); + res = val.changeDetector.handleEvent("event", 0, event); expect(res).toBe(true); val = _createChangeDetector('(event)="true; false"', d, null); - res = val.changeDetector.handleEvent('event', 0, event); + res = val.changeDetector.handleEvent("event", 0, event); expect(res).toBe(false); }); it('should support short-circuiting', () => { d.a = 0; var val = _createChangeDetector('(event)="true ? a = a + 1 : a = a + 1"', d, null); - val.changeDetector.handleEvent('event', 0, event); + val.changeDetector.handleEvent("event", 0, event); expect(d.a).toEqual(1); }); }); @@ -1258,9 +1287,8 @@ export function main() { it('should call handleEvent when an output of a directive fires', fakeAsync(() => { var directive1 = new TestDirective(); var directive2 = new TestDirective(); - _createChangeDetector( - '(host-event)="onEvent(\$event)"', new Object(), null, - new TestDispatcher([directive1, directive2])); + _createChangeDetector('(host-event)="onEvent(\$event)"', new Object(), null, + new TestDispatcher([directive1, directive2])); ObservableWrapper.callEmit(directive2.eventEmitter, 'EVENT'); tick(); @@ -1271,9 +1299,8 @@ export function main() { it('should ignore events when dehydrated', fakeAsync(() => { var directive1 = new TestDirective(); var directive2 = new TestDirective(); - var cd = _createChangeDetector( - '(host-event)="onEvent(\$event)"', new Object(), null, - new TestDispatcher([directive1, directive2])) + var cd = _createChangeDetector('(host-event)="onEvent(\$event)"', new Object(), null, + new TestDispatcher([directive1, directive2])) .changeDetector; cd.dehydrate(); ObservableWrapper.callEmit(directive2.eventEmitter, 'EVENT'); @@ -1378,9 +1405,8 @@ class TestDirective { event; eventEmitter: EventEmitter<string> = new EventEmitter<string>(); - constructor( - public ngAfterContentCheckedSpy = null, public ngAfterViewCheckedSpy = null, - public throwOnInit = false) {} + constructor(public ngAfterContentCheckedSpy = null, public ngAfterViewCheckedSpy = null, + public throwOnInit = false) {} onEvent(event) { this.event = event; } @@ -1389,7 +1415,7 @@ class TestDirective { ngOnInit() { this.ngOnInitCalled = true; if (this.throwOnInit) { - throw 'simulated ngOnInit failure'; + throw "simulated ngOnInit failure"; } } @@ -1495,8 +1521,8 @@ class TestDispatcher implements ChangeDispatcher { ngAfterViewCheckedCalled: boolean = false; ngOnDestroyCalled: boolean = false; - constructor( - public directives: Array<TestData|TestDirective> = null, public detectors: any[] = null) { + constructor(public directives: Array<TestData | TestDirective> = null, + public detectors: any[] = null) { if (isBlank(this.directives)) { this.directives = []; } diff --git a/modules/angular2/test/core/change_detection/change_detector_util_spec.ts b/modules/angular2/test/core/change_detection/change_detector_util_spec.ts index 6c2991e7f5..88625bb5ea 100644 --- a/modules/angular2/test/core/change_detection/change_detector_util_spec.ts +++ b/modules/angular2/test/core/change_detection/change_detector_util_spec.ts @@ -1,11 +1,20 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {ChangeDetectionUtil} from 'angular2/src/core/change_detection/change_detection_util'; export function main() { - describe('ChangeDetectionUtil', () => { - describe('devModeEqual', () => { - it('should do the deep comparison of iterables', () => { + describe("ChangeDetectionUtil", () => { + describe("devModeEqual", () => { + it("should do the deep comparison of iterables", () => { expect(ChangeDetectionUtil.devModeEqual([['one']], [['one']])).toBe(true); expect(ChangeDetectionUtil.devModeEqual(['one'], ['one', 'two'])).toBe(false); expect(ChangeDetectionUtil.devModeEqual(['one', 'two'], ['one'])).toBe(false); @@ -15,35 +24,35 @@ export function main() { expect(ChangeDetectionUtil.devModeEqual(new Object(), ['one'])).toBe(false); }); - it('should compare primitive numbers', () => { + it("should compare primitive numbers", () => { expect(ChangeDetectionUtil.devModeEqual(1, 1)).toBe(true); expect(ChangeDetectionUtil.devModeEqual(1, 2)).toBe(false); expect(ChangeDetectionUtil.devModeEqual(new Object(), 2)).toBe(false); expect(ChangeDetectionUtil.devModeEqual(1, new Object())).toBe(false); }); - it('should compare primitive strings', () => { + it("should compare primitive strings", () => { expect(ChangeDetectionUtil.devModeEqual('one', 'one')).toBe(true); expect(ChangeDetectionUtil.devModeEqual('one', 'two')).toBe(false); expect(ChangeDetectionUtil.devModeEqual(new Object(), 'one')).toBe(false); expect(ChangeDetectionUtil.devModeEqual('one', new Object())).toBe(false); }); - it('should compare primitive booleans', () => { + it("should compare primitive booleans", () => { expect(ChangeDetectionUtil.devModeEqual(true, true)).toBe(true); expect(ChangeDetectionUtil.devModeEqual(true, false)).toBe(false); expect(ChangeDetectionUtil.devModeEqual(new Object(), true)).toBe(false); expect(ChangeDetectionUtil.devModeEqual(true, new Object())).toBe(false); }); - it('should compare null', () => { + it("should compare null", () => { expect(ChangeDetectionUtil.devModeEqual(null, null)).toBe(true); expect(ChangeDetectionUtil.devModeEqual(null, 1)).toBe(false); expect(ChangeDetectionUtil.devModeEqual(new Object(), null)).toBe(false); expect(ChangeDetectionUtil.devModeEqual(null, new Object())).toBe(false); }); - it('should return true for other objects', () => { + it("should return true for other objects", () => { expect(ChangeDetectionUtil.devModeEqual(new Object(), new Object())).toBe(true); }); }); diff --git a/modules/angular2/test/core/change_detection/coalesce_spec.ts b/modules/angular2/test/core/change_detection/coalesce_spec.ts index d051df46ab..de8feb446a 100644 --- a/modules/angular2/test/core/change_detection/coalesce_spec.ts +++ b/modules/angular2/test/core/change_detection/coalesce_spec.ts @@ -1,4 +1,13 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {isBlank} from 'angular2/src/facade/lang'; import {coalesce} from 'angular2/src/core/change_detection/coalesce'; @@ -6,91 +15,92 @@ import {RecordType, ProtoRecord} from 'angular2/src/core/change_detection/proto_ import {DirectiveIndex} from 'angular2/src/core/change_detection/directive_record'; export function main() { - function r( - funcOrValue, args, contextIndex, selfIndex, - {lastInBinding, mode, name, directiveIndex, argumentToPureFunction, fixedArgs}: { - lastInBinding?: any, - mode?: any, - name?: any, - directiveIndex?: any, - argumentToPureFunction?: boolean, - fixedArgs?: any[] - } = {}) { + function r(funcOrValue, args, contextIndex, selfIndex, + {lastInBinding, mode, name, directiveIndex, argumentToPureFunction, fixedArgs}: { + lastInBinding?: any, + mode?: any, + name?: any, + directiveIndex?: any, + argumentToPureFunction?: boolean, + fixedArgs?: any[] + } = {}) { if (isBlank(lastInBinding)) lastInBinding = false; if (isBlank(mode)) mode = RecordType.PropertyRead; - if (isBlank(name)) name = 'name'; + if (isBlank(name)) name = "name"; if (isBlank(directiveIndex)) directiveIndex = null; if (isBlank(argumentToPureFunction)) argumentToPureFunction = false; if (isBlank(fixedArgs)) fixedArgs = null; - return new ProtoRecord( - mode, name, funcOrValue, args, fixedArgs, contextIndex, directiveIndex, selfIndex, null, - lastInBinding, false, argumentToPureFunction, false, 0); + return new ProtoRecord(mode, name, funcOrValue, args, fixedArgs, contextIndex, directiveIndex, + selfIndex, null, lastInBinding, false, argumentToPureFunction, false, 0); } - describe('change detection - coalesce', () => { - it('should work with an empty list', () => { expect(coalesce([])).toEqual([]); }); + describe("change detection - coalesce", () => { + it("should work with an empty list", () => { expect(coalesce([])).toEqual([]); }); - it('should remove non-terminal duplicate records and update the context indices referencing them', + it("should remove non-terminal duplicate records and update the context indices referencing them", () => { var rs = coalesce( - [r('user', [], 0, 1), r('first', [], 1, 2), r('user', [], 0, 3), r('last', [], 3, 4)]); + [r("user", [], 0, 1), r("first", [], 1, 2), r("user", [], 0, 3), r("last", [], 3, 4)]); - expect(rs).toEqual([r('user', [], 0, 1), r('first', [], 1, 2), r('last', [], 1, 3)]); + expect(rs).toEqual([r("user", [], 0, 1), r("first", [], 1, 2), r("last", [], 1, 3)]); }); - it('should update indices of other records', () => { + it("should update indices of other records", () => { var rs = coalesce( - [r('dup', [], 0, 1), r('dup', [], 0, 2), r('user', [], 0, 3), r('first', [3], 3, 4)]); + [r("dup", [], 0, 1), r("dup", [], 0, 2), r("user", [], 0, 3), r("first", [3], 3, 4)]); - expect(rs).toEqual([r('dup', [], 0, 1), r('user', [], 0, 2), r('first', [2], 2, 3)]); + expect(rs).toEqual([r("dup", [], 0, 1), r("user", [], 0, 2), r("first", [2], 2, 3)]); }); - it('should remove non-terminal duplicate records and update the args indices referencing them', + it("should remove non-terminal duplicate records and update the args indices referencing them", () => { var rs = coalesce([ - r('user1', [], 0, 1), r('user2', [], 0, 2), r('hi', [1], 0, 3), r('hi', [1], 0, 4), - r('hi', [2], 0, 5) + r("user1", [], 0, 1), + r("user2", [], 0, 2), + r("hi", [1], 0, 3), + r("hi", [1], 0, 4), + r("hi", [2], 0, 5) ]); expect(rs).toEqual( - [r('user1', [], 0, 1), r('user2', [], 0, 2), r('hi', [1], 0, 3), r('hi', [2], 0, 4)]); + [r("user1", [], 0, 1), r("user2", [], 0, 2), r("hi", [1], 0, 3), r("hi", [2], 0, 4)]); }); - it('should replace duplicate terminal records with self records', () => { + it("should replace duplicate terminal records with self records", () => { var rs = coalesce( - [r('user', [], 0, 1, {lastInBinding: true}), r('user', [], 0, 2, {lastInBinding: true})]); + [r("user", [], 0, 1, {lastInBinding: true}), r("user", [], 0, 2, {lastInBinding: true})]); - expect(rs[1]).toEqual(new ProtoRecord( - RecordType.Self, 'self', null, [], null, 1, null, 2, null, true, false, false, false, 0)); + expect(rs[1]).toEqual(new ProtoRecord(RecordType.Self, "self", null, [], null, 1, null, 2, + null, true, false, false, false, 0)); }); - it('should set referencedBySelf', () => { + it("should set referencedBySelf", () => { var rs = coalesce( - [r('user', [], 0, 1, {lastInBinding: true}), r('user', [], 0, 2, {lastInBinding: true})]); + [r("user", [], 0, 1, {lastInBinding: true}), r("user", [], 0, 2, {lastInBinding: true})]); expect(rs[0].referencedBySelf).toBeTruthy(); }); - it('should not coalesce directive lifecycle records', () => { + it("should not coalesce directive lifecycle records", () => { var rs = coalesce([ - r('ngDoCheck', [], 0, 1, {mode: RecordType.DirectiveLifecycle}), - r('ngDoCheck', [], 0, 1, {mode: RecordType.DirectiveLifecycle}) + r("ngDoCheck", [], 0, 1, {mode: RecordType.DirectiveLifecycle}), + r("ngDoCheck", [], 0, 1, {mode: RecordType.DirectiveLifecycle}) ]); expect(rs.length).toEqual(2); }); - it('should not coalesce protos with different names but same value', () => { + it("should not coalesce protos with different names but same value", () => { var nullFunc = () => {}; var rs = coalesce([ - r(nullFunc, [], 0, 1, {name: 'foo'}), - r(nullFunc, [], 0, 1, {name: 'bar'}), + r(nullFunc, [], 0, 1, {name: "foo"}), + r(nullFunc, [], 0, 1, {name: "bar"}), ]); expect(rs.length).toEqual(2); }); - it('should not coalesce protos with the same context index but different directive indices', + it("should not coalesce protos with the same context index but different directive indices", () => { var nullFunc = () => {}; var rs = coalesce([ @@ -104,32 +114,35 @@ export function main() { it('should preserve the argumentToPureFunction property', () => { var rs = coalesce([ - r('user', [], 0, 1), r('user', [], 0, 2, {argumentToPureFunction: true}), - r('user', [], 0, 3), r('name', [], 3, 4) + r("user", [], 0, 1), + r("user", [], 0, 2, {argumentToPureFunction: true}), + r("user", [], 0, 3), + r("name", [], 3, 4) ]); - expect(rs).toEqual( - [r('user', [], 0, 1, {argumentToPureFunction: true}), r('name', [], 1, 2)]); + expect(rs) + .toEqual([r("user", [], 0, 1, {argumentToPureFunction: true}), r("name", [], 1, 2)]); }); it('should preserve the argumentToPureFunction property (the original record)', () => { var rs = coalesce([ - r('user', [], 0, 1, {argumentToPureFunction: true}), r('user', [], 0, 2), - r('name', [], 2, 3) + r("user", [], 0, 1, {argumentToPureFunction: true}), + r("user", [], 0, 2), + r("name", [], 2, 3) ]); - expect(rs).toEqual( - [r('user', [], 0, 1, {argumentToPureFunction: true}), r('name', [], 1, 2)]); + expect(rs) + .toEqual([r("user", [], 0, 1, {argumentToPureFunction: true}), r("name", [], 1, 2)]); }); describe('short-circuit', () => { it('should not use short-circuitable records', () => { var records = [ - r('sknot', [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}), - r('a', [], 0, 2), - r('sk', [], 0, 3, {mode: RecordType.SkipRecords, fixedArgs: [4]}), - r('b', [], 0, 4), - r('cond', [2, 4], 0, 5), - r('a', [], 0, 6), - r('b', [], 0, 7), + r("sknot", [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}), + r("a", [], 0, 2), + r("sk", [], 0, 3, {mode: RecordType.SkipRecords, fixedArgs: [4]}), + r("b", [], 0, 4), + r("cond", [2, 4], 0, 5), + r("a", [], 0, 6), + r("b", [], 0, 7), ]; expect(coalesce(records)).toEqual(records); @@ -137,18 +150,18 @@ export function main() { it('should not use short-circuitable records from nested short-circuits', () => { var records = [ - r('sknot outer', [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}), - r('sknot inner', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}), - r('a', [], 0, 3), - r('sk inner', [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [5]}), - r('b', [], 0, 5), - r('cond-inner', [3, 5], 0, 6), - r('sk outer', [], 0, 7, {mode: RecordType.SkipRecords, fixedArgs: [8]}), - r('c', [], 0, 8), - r('cond-outer', [6, 8], 0, 9), - r('a', [], 0, 10), - r('b', [], 0, 11), - r('c', [], 0, 12), + r("sknot outer", [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}), + r("sknot inner", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}), + r("a", [], 0, 3), + r("sk inner", [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [5]}), + r("b", [], 0, 5), + r("cond-inner", [3, 5], 0, 6), + r("sk outer", [], 0, 7, {mode: RecordType.SkipRecords, fixedArgs: [8]}), + r("c", [], 0, 8), + r("cond-outer", [6, 8], 0, 9), + r("a", [], 0, 10), + r("b", [], 0, 11), + r("c", [], 0, 12), ]; expect(coalesce(records)).toEqual(records); @@ -156,65 +169,65 @@ export function main() { it('should collapse the true branch', () => { var rs = coalesce([ - r('a', [], 0, 1), - r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}), - r('a', [], 0, 3), - r('sk', [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [6]}), - r('a', [], 0, 5), - r('b', [], 5, 6), - r('cond', [3, 6], 0, 7), + r("a", [], 0, 1), + r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}), + r("a", [], 0, 3), + r("sk", [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [6]}), + r("a", [], 0, 5), + r("b", [], 5, 6), + r("cond", [3, 6], 0, 7), ]); expect(rs).toEqual([ - r('a', [], 0, 1), - r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIf, fixedArgs: [3]}), - r('b', [], 1, 3), - r('cond', [1, 3], 0, 4), + r("a", [], 0, 1), + r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIf, fixedArgs: [3]}), + r("b", [], 1, 3), + r("cond", [1, 3], 0, 4), ]); }); it('should collapse the false branch', () => { var rs = coalesce([ - r('a', [], 0, 1), - r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [5]}), - r('a', [], 0, 3), - r('b', [], 3, 4), - r('sk', [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}), - r('a', [], 0, 6), - r('cond', [4, 6], 0, 7), + r("a", [], 0, 1), + r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [5]}), + r("a", [], 0, 3), + r("b", [], 3, 4), + r("sk", [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}), + r("a", [], 0, 6), + r("cond", [4, 6], 0, 7), ]); expect(rs).toEqual([ - r('a', [], 0, 1), - r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}), - r('b', [], 1, 3), - r('cond', [3, 1], 0, 4), + r("a", [], 0, 1), + r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}), + r("b", [], 1, 3), + r("cond", [3, 1], 0, 4), ]); }); it('should optimize skips', () => { var rs = coalesce([ // skipIfNot(1) + skip(N) -> skipIf(+N) - r('sknot', [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [2]}), - r('sk', [], 0, 2, {mode: RecordType.SkipRecords, fixedArgs: [3]}), - r('a', [], 0, 3), + r("sknot", [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [2]}), + r("sk", [], 0, 2, {mode: RecordType.SkipRecords, fixedArgs: [3]}), + r("a", [], 0, 3), // skipIf(1) + skip(N) -> skipIfNot(N) - r('skif', [], 0, 4, {mode: RecordType.SkipRecordsIf, fixedArgs: [5]}), - r('sk', [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}), - r('b', [], 0, 6), + r("skif", [], 0, 4, {mode: RecordType.SkipRecordsIf, fixedArgs: [5]}), + r("sk", [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}), + r("b", [], 0, 6), // remove empty skips - r('sknot', [], 0, 7, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}), - r('skif', [], 0, 8, {mode: RecordType.SkipRecordsIf, fixedArgs: [8]}), - r('sk', [], 0, 9, {mode: RecordType.SkipRecords, fixedArgs: [9]}), - r('end', [], 0, 10), + r("sknot", [], 0, 7, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}), + r("skif", [], 0, 8, {mode: RecordType.SkipRecordsIf, fixedArgs: [8]}), + r("sk", [], 0, 9, {mode: RecordType.SkipRecords, fixedArgs: [9]}), + r("end", [], 0, 10), ]); expect(rs).toEqual([ - r('sknot', [], 0, 1, {mode: RecordType.SkipRecordsIf, fixedArgs: [2]}), - r('a', [], 0, 2), - r('skif', [], 0, 3, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}), - r('b', [], 0, 4), - r('end', [], 0, 5), + r("sknot", [], 0, 1, {mode: RecordType.SkipRecordsIf, fixedArgs: [2]}), + r("a", [], 0, 2), + r("skif", [], 0, 3, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}), + r("b", [], 0, 4), + r("end", [], 0, 5), ]); }); }); diff --git a/modules/angular2/test/core/change_detection/differs/default_iterable_differ_spec.ts b/modules/angular2/test/core/change_detection/differs/default_iterable_differ_spec.ts index e8f74470f4..1668d114a0 100644 --- a/modules/angular2/test/core/change_detection/differs/default_iterable_differ_spec.ts +++ b/modules/angular2/test/core/change_detection/differs/default_iterable_differ_spec.ts @@ -1,5 +1,17 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; -import {DefaultIterableDiffer, DefaultIterableDifferFactory} from 'angular2/src/core/change_detection/differs/default_iterable_differ'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; +import { + DefaultIterableDiffer, + DefaultIterableDifferFactory +} from 'angular2/src/core/change_detection/differs/default_iterable_differ'; import {NumberWrapper} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -42,19 +54,19 @@ export function main() { l.list = [1]; differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['1[null->0]'], - additions: ['1[null->0]'] - })); + expect(differ.toString()) + .toEqual( + iterableChangesAsString({collection: ['1[null->0]'], additions: ['1[null->0]']})); l.list = [2, 1]; differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['2[null->0]', '1[0->1]'], - previous: ['1[0->1]'], - additions: ['2[null->0]'], - moves: ['1[0->1]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['2[null->0]', '1[0->1]'], + previous: ['1[0->1]'], + additions: ['2[null->0]'], + moves: ['1[0->1]'] + })); }); it('should detect additions', () => { @@ -64,10 +76,9 @@ export function main() { l.push('a'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a[null->0]'], - additions: ['a[null->0]'] - })); + expect(differ.toString()) + .toEqual( + iterableChangesAsString({collection: ['a[null->0]'], additions: ['a[null->0]']})); l.push('b'); differ.check(l); @@ -82,21 +93,23 @@ export function main() { l = [1, 0]; differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['1[null->0]', '0[0->1]'], - previous: ['0[0->1]'], - additions: ['1[null->0]'], - moves: ['0[0->1]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['1[null->0]', '0[0->1]'], + previous: ['0[0->1]'], + additions: ['1[null->0]'], + moves: ['0[0->1]'] + })); l = [2, 1, 0]; differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['2[null->0]', '1[0->1]', '0[1->2]'], - previous: ['1[0->1]', '0[1->2]'], - additions: ['2[null->0]'], - moves: ['1[0->1]', '0[1->2]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['2[null->0]', '1[0->1]', '0[1->2]'], + previous: ['1[0->1]', '0[1->2]'], + additions: ['2[null->0]'], + moves: ['1[0->1]', '0[1->2]'] + })); }); it('should handle swapping element', () => { @@ -107,11 +120,12 @@ export function main() { l.push(2); l.push(1); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['2[1->0]', '1[0->1]'], - previous: ['1[0->1]', '2[1->0]'], - moves: ['2[1->0]', '1[0->1]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['2[1->0]', '1[0->1]'], + previous: ['1[0->1]', '2[1->0]'], + moves: ['2[1->0]', '1[0->1]'] + })); }); it('should handle incremental swapping element', () => { @@ -121,20 +135,22 @@ export function main() { ListWrapper.removeAt(l, 1); ListWrapper.insert(l, 0, 'b'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['b[1->0]', 'a[0->1]', 'c'], - previous: ['a[0->1]', 'b[1->0]', 'c'], - moves: ['b[1->0]', 'a[0->1]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['b[1->0]', 'a[0->1]', 'c'], + previous: ['a[0->1]', 'b[1->0]', 'c'], + moves: ['b[1->0]', 'a[0->1]'] + })); ListWrapper.removeAt(l, 1); l.push('a'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['b', 'c[2->1]', 'a[1->2]'], - previous: ['b', 'a[1->2]', 'c[2->1]'], - moves: ['c[2->1]', 'a[1->2]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['b', 'c[2->1]', 'a[1->2]'], + previous: ['b', 'a[1->2]', 'c[2->1]'], + moves: ['c[2->1]', 'a[1->2]'] + })); }); it('should detect changes in list', () => { @@ -143,10 +159,9 @@ export function main() { l.push('a'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a[null->0]'], - additions: ['a[null->0]'] - })); + expect(differ.toString()) + .toEqual( + iterableChangesAsString({collection: ['a[null->0]'], additions: ['a[null->0]']})); l.push('b'); differ.check(l); @@ -157,20 +172,22 @@ export function main() { l.push('c'); l.push('d'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a', 'b', 'c[null->2]', 'd[null->3]'], - previous: ['a', 'b'], - additions: ['c[null->2]', 'd[null->3]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['a', 'b', 'c[null->2]', 'd[null->3]'], + previous: ['a', 'b'], + additions: ['c[null->2]', 'd[null->3]'] + })); ListWrapper.removeAt(l, 2); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a', 'b', 'd[3->2]'], - previous: ['a', 'b', 'c[2->null]', 'd[3->2]'], - moves: ['d[3->2]'], - removals: ['c[2->null]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['a', 'b', 'd[3->2]'], + previous: ['a', 'b', 'c[2->null]', 'd[3->2]'], + moves: ['d[3->2]'], + removals: ['c[2->null]'] + })); ListWrapper.clear(l); l.push('d'); @@ -178,12 +195,13 @@ export function main() { l.push('b'); l.push('a'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['d[2->0]', 'c[null->1]', 'b[1->2]', 'a[0->3]'], - previous: ['a[0->3]', 'b[1->2]', 'd[2->0]'], - additions: ['c[null->1]'], - moves: ['d[2->0]', 'b[1->2]', 'a[0->3]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['d[2->0]', 'c[null->1]', 'b[1->2]', 'a[0->3]'], + previous: ['a[0->3]', 'b[1->2]', 'd[2->0]'], + additions: ['c[null->1]'], + moves: ['d[2->0]', 'b[1->2]', 'a[0->3]'] + })); }); it('should test string by value rather than by reference (Dart)', () => { @@ -202,10 +220,9 @@ export function main() { let l = [NumberWrapper.NaN]; differ.check(l); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: [NumberWrapper.NaN], - previous: [NumberWrapper.NaN] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString( + {collection: [NumberWrapper.NaN], previous: [NumberWrapper.NaN]})); }); it('should detect [NaN] moves', () => { @@ -214,12 +231,13 @@ export function main() { ListWrapper.insert<any>(l, 0, 'foo'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'], - previous: ['NaN[0->1]', 'NaN[1->2]'], - additions: ['foo[null->0]'], - moves: ['NaN[0->1]', 'NaN[1->2]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'], + previous: ['NaN[0->1]', 'NaN[1->2]'], + additions: ['foo[null->0]'], + moves: ['NaN[0->1]', 'NaN[1->2]'] + })); }); it('should remove and add same item', () => { @@ -228,21 +246,23 @@ export function main() { ListWrapper.removeAt(l, 1); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a', 'c[2->1]'], - previous: ['a', 'b[1->null]', 'c[2->1]'], - moves: ['c[2->1]'], - removals: ['b[1->null]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['a', 'c[2->1]'], + previous: ['a', 'b[1->null]', 'c[2->1]'], + moves: ['c[2->1]'], + removals: ['b[1->null]'] + })); ListWrapper.insert(l, 1, 'b'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a', 'b[null->1]', 'c[1->2]'], - previous: ['a', 'c[1->2]'], - additions: ['b[null->1]'], - moves: ['c[1->2]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['a', 'b[null->1]', 'c[1->2]'], + previous: ['a', 'c[1->2]'], + additions: ['b[null->1]'], + moves: ['c[1->2]'] + })); }); @@ -252,12 +272,13 @@ export function main() { ListWrapper.removeAt(l, 0); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['a', 'a', 'b[3->2]', 'b[4->3]'], - previous: ['a', 'a', 'a[2->null]', 'b[3->2]', 'b[4->3]'], - moves: ['b[3->2]', 'b[4->3]'], - removals: ['a[2->null]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['a', 'a', 'b[3->2]', 'b[4->3]'], + previous: ['a', 'a', 'a[2->null]', 'b[3->2]', 'b[4->3]'], + moves: ['b[3->2]', 'b[4->3]'], + removals: ['a[2->null]'] + })); }); it('should support insertions/moves', () => { @@ -266,12 +287,13 @@ export function main() { ListWrapper.insert(l, 0, 'b'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'], - previous: ['a[0->1]', 'a[1->2]', 'b[2->0]', 'b'], - additions: ['b[null->4]'], - moves: ['b[2->0]', 'a[0->1]', 'a[1->2]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'], + previous: ['a[0->1]', 'a[1->2]', 'b[2->0]', 'b'], + additions: ['b[null->4]'], + moves: ['b[2->0]', 'a[0->1]', 'a[1->2]'] + })); }); it('should not report unnecessary moves', () => { @@ -283,11 +305,12 @@ export function main() { l.push('a'); l.push('c'); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['b[1->0]', 'a[0->1]', 'c'], - previous: ['a[0->1]', 'b[1->0]', 'c'], - moves: ['b[1->0]', 'a[0->1]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['b[1->0]', 'a[0->1]', 'c'], + previous: ['a[0->1]', 'b[1->0]', 'c'], + moves: ['b[1->0]', 'a[0->1]'] + })); }); it('should not diff immutable collections if they are the same', () => { @@ -302,10 +325,9 @@ export function main() { differ.check(l1); expect(trackByCount).toBe(1); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['1[null->0]'], - additions: ['1[null->0]'] - })); + expect(differ.toString()) + .toEqual( + iterableChangesAsString({collection: ['1[null->0]'], additions: ['1[null->0]']})); trackByCount = 0; @@ -322,9 +344,8 @@ export function main() { }); describe('diff', () => { - it('should return self when there is a change', () => { - expect(differ.diff(['a', 'b'])).toBe(differ); - }); + it('should return self when there is a change', + () => { expect(differ.diff(['a', 'b'])).toBe(differ); }); it('should return null when there is no change', () => { differ.diff(['a', 'b']); @@ -333,14 +354,15 @@ export function main() { it('should treat null as an empty list', () => { differ.diff(['a', 'b']); - expect(differ.diff(null).toString()).toEqual(iterableChangesAsString({ - previous: ['a[0->null]', 'b[1->null]'], - removals: ['a[0->null]', 'b[1->null]'] - })); + expect(differ.diff(null).toString()) + .toEqual(iterableChangesAsString({ + previous: ['a[0->null]', 'b[1->null]'], + removals: ['a[0->null]', 'b[1->null]'] + })); }); it('should throw when given an invalid collection', () => { - expect(() => differ.diff('invalid')).toThrowErrorWith('Error trying to diff \'invalid\''); + expect(() => differ.diff("invalid")).toThrowErrorWith("Error trying to diff 'invalid'"); }); }); }); @@ -363,18 +385,20 @@ export function main() { it('should treat seen records as identity changes, not additions', () => { let l = buildItemList(['a', 'b', 'c']); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`], - additions: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`], + additions: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`] + })); l = buildItemList(['a', 'b', 'c']); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: [`{id: a}`, `{id: b}`, `{id: c}`], - identityChanges: [`{id: a}`, `{id: b}`, `{id: c}`], - previous: [`{id: a}`, `{id: b}`, `{id: c}`] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: [`{id: a}`, `{id: b}`, `{id: c}`], + identityChanges: [`{id: a}`, `{id: b}`, `{id: c}`], + previous: [`{id: a}`, `{id: b}`, `{id: c}`] + })); }); it('should have updated properties in identity change collection', () => { @@ -383,11 +407,12 @@ export function main() { l = [new ComplexItem('a', 'orange'), new ComplexItem('b', 'red')]; differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: [`{id: a, color: orange}`, `{id: b, color: red}`], - identityChanges: [`{id: a, color: orange}`, `{id: b, color: red}`], - previous: [`{id: a, color: orange}`, `{id: b, color: red}`] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: [`{id: a, color: orange}`, `{id: b, color: red}`], + identityChanges: [`{id: a, color: orange}`, `{id: b, color: red}`], + previous: [`{id: a, color: orange}`, `{id: b, color: red}`] + })); }); it('should track moves normally', () => { @@ -396,12 +421,13 @@ export function main() { l = buildItemList(['b', 'a', 'c']); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'], - identityChanges: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'], - previous: ['{id: a}[0->1]', '{id: b}[1->0]', '{id: c}'], - moves: ['{id: b}[1->0]', '{id: a}[0->1]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'], + identityChanges: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'], + previous: ['{id: a}[0->1]', '{id: b}[1->0]', '{id: c}'], + moves: ['{id: b}[1->0]', '{id: a}[0->1]'] + })); }); @@ -411,13 +437,14 @@ export function main() { l = buildItemList(['b', 'a', 'a']); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['{id: b}[null->0]', '{id: a}[0->1]', '{id: a}[1->2]'], - identityChanges: ['{id: a}[0->1]', '{id: a}[1->2]'], - previous: ['{id: a}[0->1]', '{id: a}[1->2]'], - moves: ['{id: a}[0->1]', '{id: a}[1->2]'], - additions: ['{id: b}[null->0]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['{id: b}[null->0]', '{id: a}[0->1]', '{id: a}[1->2]'], + identityChanges: ['{id: a}[0->1]', '{id: a}[1->2]'], + previous: ['{id: a}[0->1]', '{id: a}[1->2]'], + moves: ['{id: a}[0->1]', '{id: a}[1->2]'], + additions: ['{id: b}[null->0]'] + })); }); @@ -427,11 +454,12 @@ export function main() { ListWrapper.removeAt(l, 2); differ.check(l); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['{id: a}', '{id: b}'], - previous: ['{id: a}', '{id: b}', '{id: c}[2->null]'], - removals: ['{id: c}[2->null]'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['{id: a}', '{id: b}'], + previous: ['{id: a}', '{id: b}', '{id: c}[2->null]'], + removals: ['{id: c}[2->null]'] + })); }); }); describe('trackBy function by index', function() { @@ -446,12 +474,13 @@ export function main() { differ.check(['e', 'f', 'g', 'h']); differ.check(['e', 'f', 'h']); - expect(differ.toString()).toEqual(iterableChangesAsString({ - collection: ['e', 'f', 'h'], - previous: ['e', 'f', 'h', 'h[3->null]'], - removals: ['h[3->null]'], - identityChanges: ['h'] - })); + expect(differ.toString()) + .toEqual(iterableChangesAsString({ + collection: ['e', 'f', 'h'], + previous: ['e', 'f', 'h', 'h[3->null]'], + removals: ['h[3->null]'], + identityChanges: ['h'] + })); }); }); diff --git a/modules/angular2/test/core/change_detection/differs/default_keyvalue_differ_spec.ts b/modules/angular2/test/core/change_detection/differs/default_keyvalue_differ_spec.ts index dbaa085b4b..e44c399190 100644 --- a/modules/angular2/test/core/change_detection/differs/default_keyvalue_differ_spec.ts +++ b/modules/angular2/test/core/change_detection/differs/default_keyvalue_differ_spec.ts @@ -1,5 +1,17 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; -import {DefaultKeyValueDiffer, DefaultKeyValueDifferFactory} from 'angular2/src/core/change_detection/differs/default_keyvalue_differ'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; +import { + DefaultKeyValueDiffer, + DefaultKeyValueDifferFactory +} from 'angular2/src/core/change_detection/differs/default_keyvalue_differ'; import {NumberWrapper, isJsObject} from 'angular2/src/facade/lang'; import {kvChangesAsString} from '../../../core/change_detection/util'; @@ -40,11 +52,12 @@ export function main() { m.set(2, 10); m.set(1, 20); differ.check(m); - expect(differ.toString()).toEqual(kvChangesAsString({ - map: ['1[10->20]', '2[20->10]'], - previous: ['1[10->20]', '2[20->10]'], - changes: ['1[10->20]', '2[20->10]'] - })); + expect(differ.toString()) + .toEqual(kvChangesAsString({ + map: ['1[10->20]', '2[20->10]'], + previous: ['1[10->20]', '2[20->10]'], + changes: ['1[10->20]', '2[20->10]'] + })); }); it('should expose previous and current value', () => { @@ -82,12 +95,13 @@ export function main() { m.set('b', 'BB'); m.set('d', 'D'); differ.check(m); - expect(differ.toString()).toEqual(kvChangesAsString({ - map: ['a', 'b[B->BB]', 'd[null->D]'], - previous: ['a', 'b[B->BB]'], - additions: ['d[null->D]'], - changes: ['b[B->BB]'] - })); + expect(differ.toString()) + .toEqual(kvChangesAsString({ + map: ['a', 'b[B->BB]', 'd[null->D]'], + previous: ['a', 'b[B->BB]'], + additions: ['d[null->D]'], + changes: ['b[B->BB]'] + })); m.delete('b'); differ.check(m); @@ -97,10 +111,9 @@ export function main() { m.clear(); differ.check(m); - expect(differ.toString()).toEqual(kvChangesAsString({ - previous: ['a[A->null]', 'd[D->null]'], - removals: ['a[A->null]', 'd[D->null]'] - })); + expect(differ.toString()) + .toEqual(kvChangesAsString( + {previous: ['a[A->null]', 'd[D->null]'], removals: ['a[A->null]', 'd[D->null]']})); }); it('should test string by value rather than by reference (DART)', () => { @@ -132,7 +145,7 @@ export function main() { it('should support JS Object', () => { var f = new DefaultKeyValueDifferFactory(); expect(f.supports({})).toBeTruthy(); - expect(f.supports('not supported')).toBeFalsy(); + expect(f.supports("not supported")).toBeFalsy(); expect(f.supports(0)).toBeFalsy(); expect(f.supports(null)).toBeFalsy(); }); @@ -155,29 +168,32 @@ export function main() { m['b'] = 'BB'; m['d'] = 'D'; differ.check(m); - expect(differ.toString()).toEqual(kvChangesAsString({ - map: ['a', 'b[B->BB]', 'd[null->D]'], - previous: ['a', 'b[B->BB]'], - additions: ['d[null->D]'], - changes: ['b[B->BB]'] - })); + expect(differ.toString()) + .toEqual(kvChangesAsString({ + map: ['a', 'b[B->BB]', 'd[null->D]'], + previous: ['a', 'b[B->BB]'], + additions: ['d[null->D]'], + changes: ['b[B->BB]'] + })); m = {}; m['a'] = 'A'; m['d'] = 'D'; differ.check(m); - expect(differ.toString()).toEqual(kvChangesAsString({ - map: ['a', 'd'], - previous: ['a', 'b[BB->null]', 'd'], - removals: ['b[BB->null]'] - })); + expect(differ.toString()) + .toEqual(kvChangesAsString({ + map: ['a', 'd'], + previous: ['a', 'b[BB->null]', 'd'], + removals: ['b[BB->null]'] + })); m = {}; differ.check(m); - expect(differ.toString()).toEqual(kvChangesAsString({ - previous: ['a[A->null]', 'd[D->null]'], - removals: ['a[A->null]', 'd[D->null]'] - })); + expect(differ.toString()) + .toEqual(kvChangesAsString({ + previous: ['a[A->null]', 'd[D->null]'], + removals: ['a[A->null]', 'd[D->null]'] + })); }); }); @@ -201,8 +217,7 @@ export function main() { }); it('should throw when given an invalid collection', () => { - expect(() => differ.diff('invalid')) - .toThrowErrorWith('Error trying to diff \'invalid\''); + expect(() => differ.diff("invalid")).toThrowErrorWith("Error trying to diff 'invalid'"); }); }); } diff --git a/modules/angular2/test/core/change_detection/differs/iterable_differs_spec.ts b/modules/angular2/test/core/change_detection/differs/iterable_differs_spec.ts index b72c37841c..220bd1adf3 100644 --- a/modules/angular2/test/core/change_detection/differs/iterable_differs_spec.ts +++ b/modules/angular2/test/core/change_detection/differs/iterable_differs_spec.ts @@ -1,4 +1,13 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {SpyIterableDifferFactory} from '../../spies'; import {IterableDiffers} from 'angular2/src/core/change_detection/differs/iterable_differs'; import {Injector, provide} from 'angular2/core'; @@ -17,22 +26,22 @@ export function main() { it('should throw when no suitable implementation found', () => { var differs = new IterableDiffers([]); - expect(() => differs.find('some object')) - .toThrowErrorWith('Cannot find a differ supporting object \'some object\'') + expect(() => differs.find("some object")) + .toThrowErrorWith("Cannot find a differ supporting object 'some object'") }); it('should return the first suitable implementation', () => { - factory1.spy('supports').andReturn(false); - factory2.spy('supports').andReturn(true); - factory3.spy('supports').andReturn(true); + factory1.spy("supports").andReturn(false); + factory2.spy("supports").andReturn(true); + factory3.spy("supports").andReturn(true); var differs = IterableDiffers.create(<any>[factory1, factory2, factory3]); - expect(differs.find('some object')).toBe(factory2); + expect(differs.find("some object")).toBe(factory2); }); it('should copy over differs from the parent repo', () => { - factory1.spy('supports').andReturn(true); - factory2.spy('supports').andReturn(false); + factory1.spy("supports").andReturn(true); + factory2.spy("supports").andReturn(false); var parent = IterableDiffers.create(<any>[factory1]); var child = IterableDiffers.create(<any>[factory2], parent); @@ -40,12 +49,12 @@ export function main() { expect(child.factories).toEqual([factory2, factory1]); }); - describe('.extend()', () => { + describe(".extend()", () => { it('should throw if calling extend when creating root injector', () => { var injector = Injector.resolveAndCreate([IterableDiffers.extend([])]); expect(() => injector.get(IterableDiffers)) - .toThrowErrorWith('Cannot extend IterableDiffers without a parent injector'); + .toThrowErrorWith("Cannot extend IterableDiffers without a parent injector"); }); it('should extend di-inherited diffesr', () => { diff --git a/modules/angular2/test/core/change_detection/parser/lexer_spec.ts b/modules/angular2/test/core/change_detection/parser/lexer_spec.ts index f2c832e6b7..bd197e3213 100644 --- a/modules/angular2/test/core/change_detection/parser/lexer_spec.ts +++ b/modules/angular2/test/core/change_detection/parser/lexer_spec.ts @@ -2,7 +2,7 @@ import {ddescribe, describe, it, expect} from 'angular2/testing_internal'; import {Lexer, Token} from 'angular2/src/core/change_detection/parser/lexer'; -import {StringWrapper} from 'angular2/src/facade/lang'; +import {StringWrapper} from "angular2/src/facade/lang"; function lex(text: string): any[] { return new Lexer().tokenize(text); @@ -52,13 +52,13 @@ export function main() { describe('lexer', function() { describe('token', function() { it('should tokenize a simple identifier', function() { - var tokens: number[] = lex('j'); + var tokens: number[] = lex("j"); expect(tokens.length).toEqual(1); expectIdentifierToken(tokens[0], 0, 'j'); }); it('should tokenize a dotted identifier', function() { - var tokens: number[] = lex('j.k'); + var tokens: number[] = lex("j.k"); expect(tokens.length).toEqual(3); expectIdentifierToken(tokens[0], 0, 'j'); expectCharacterToken(tokens[1], 1, '.'); @@ -66,35 +66,35 @@ export function main() { }); it('should tokenize an operator', function() { - var tokens: number[] = lex('j-k'); + var tokens: number[] = lex("j-k"); expect(tokens.length).toEqual(3); expectOperatorToken(tokens[1], 1, '-'); }); it('should tokenize an indexed operator', function() { - var tokens: number[] = lex('j[k]'); + var tokens: number[] = lex("j[k]"); expect(tokens.length).toEqual(4); - expectCharacterToken(tokens[1], 1, '['); - expectCharacterToken(tokens[3], 3, ']'); + expectCharacterToken(tokens[1], 1, "["); + expectCharacterToken(tokens[3], 3, "]"); }); it('should tokenize numbers', function() { - var tokens: number[] = lex('88'); + var tokens: number[] = lex("88"); expect(tokens.length).toEqual(1); expectNumberToken(tokens[0], 0, 88); }); it('should tokenize numbers within index ops', - function() { expectNumberToken(lex('a[22]')[2], 2, 22); }); + function() { expectNumberToken(lex("a[22]")[2], 2, 22); }); it('should tokenize simple quoted strings', - function() { expectStringToken(lex('"a"')[0], 0, 'a'); }); + function() { expectStringToken(lex('"a"')[0], 0, "a"); }); it('should tokenize quoted strings with escaped quotes', function() { expectStringToken(lex('"a\\""')[0], 0, 'a"'); }); it('should tokenize a string', function() { - var tokens: Token[] = lex('j-a.bc[22]+1.3|f:\'a\\\'c\':"d\\"e"'); + var tokens: Token[] = lex("j-a.bc[22]+1.3|f:'a\\\'c':\"d\\\"e\""); expectIdentifierToken(tokens[0], 0, 'j'); expectOperatorToken(tokens[1], 1, '-'); expectIdentifierToken(tokens[2], 2, 'a'); @@ -108,27 +108,27 @@ export function main() { expectOperatorToken(tokens[10], 14, '|'); expectIdentifierToken(tokens[11], 15, 'f'); expectCharacterToken(tokens[12], 16, ':'); - expectStringToken(tokens[13], 17, 'a\'c'); + expectStringToken(tokens[13], 17, "a'c"); expectCharacterToken(tokens[14], 23, ':'); expectStringToken(tokens[15], 24, 'd"e'); }); it('should tokenize undefined', function() { - var tokens: Token[] = lex('undefined'); - expectKeywordToken(tokens[0], 0, 'undefined'); + var tokens: Token[] = lex("undefined"); + expectKeywordToken(tokens[0], 0, "undefined"); expect(tokens[0].isKeywordUndefined()).toBe(true); }); it('should ignore whitespace', function() { - var tokens: Token[] = lex('a \t \n \r b'); + var tokens: Token[] = lex("a \t \n \r b"); expectIdentifierToken(tokens[0], 0, 'a'); expectIdentifierToken(tokens[1], 8, 'b'); }); it('should tokenize quoted string', () => { - var str = '[\'\\\'\', "\\""]'; + var str = "['\\'', \"\\\"\"]"; var tokens: Token[] = lex(str); - expectStringToken(tokens[1], 1, '\''); + expectStringToken(tokens[1], 1, "'"); expectStringToken(tokens[3], 7, '"'); }); @@ -146,7 +146,7 @@ export function main() { }); it('should tokenize relation', function() { - var tokens: Token[] = lex('! == != < > <= >= === !=='); + var tokens: Token[] = lex("! == != < > <= >= === !=="); expectOperatorToken(tokens[0], 0, '!'); expectOperatorToken(tokens[1], 2, '=='); expectOperatorToken(tokens[2], 5, '!='); @@ -159,7 +159,7 @@ export function main() { }); it('should tokenize statements', function() { - var tokens: Token[] = lex('a;b;'); + var tokens: Token[] = lex("a;b;"); expectIdentifierToken(tokens[0], 0, 'a'); expectCharacterToken(tokens[1], 1, ';'); expectIdentifierToken(tokens[2], 2, 'b'); @@ -167,19 +167,19 @@ export function main() { }); it('should tokenize function invocation', function() { - var tokens: Token[] = lex('a()'); + var tokens: Token[] = lex("a()"); expectIdentifierToken(tokens[0], 0, 'a'); expectCharacterToken(tokens[1], 1, '('); expectCharacterToken(tokens[2], 2, ')'); }); it('should tokenize simple method invocations', function() { - var tokens: Token[] = lex('a.method()'); + var tokens: Token[] = lex("a.method()"); expectIdentifierToken(tokens[2], 2, 'method'); }); it('should tokenize method invocation', function() { - var tokens: Token[] = lex('a.b.c (d) - e.f()'); + var tokens: Token[] = lex("a.b.c (d) - e.f()"); expectIdentifierToken(tokens[0], 0, 'a'); expectCharacterToken(tokens[1], 1, '.'); expectIdentifierToken(tokens[2], 2, 'b'); @@ -197,7 +197,7 @@ export function main() { }); it('should tokenize number', function() { - var tokens: Token[] = lex('0.5'); + var tokens: Token[] = lex("0.5"); expectNumberToken(tokens[0], 0, 0.5); }); @@ -208,36 +208,34 @@ export function main() { // }); it('should tokenize number with exponent', function() { - var tokens: Token[] = lex('0.5E-10'); + var tokens: Token[] = lex("0.5E-10"); expect(tokens.length).toEqual(1); expectNumberToken(tokens[0], 0, 0.5E-10); - tokens = lex('0.5E+10'); + tokens = lex("0.5E+10"); expectNumberToken(tokens[0], 0, 0.5E+10); }); it('should throws exception for invalid exponent', function() { - expect(() => { - lex('0.5E-'); - }).toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-]'); + expect(() => { lex("0.5E-"); }) + .toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-]'); - expect(() => { - lex('0.5E-A'); - }).toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-A]'); + expect(() => { lex("0.5E-A"); }) + .toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-A]'); }); it('should tokenize number starting with a dot', function() { - var tokens: Token[] = lex('.5'); + var tokens: Token[] = lex(".5"); expectNumberToken(tokens[0], 0, 0.5); }); it('should throw error on invalid unicode', function() { - expect(() => { lex('\'\\u1\'\'bla\''); }) + expect(() => { lex("'\\u1''bla'"); }) .toThrowError( - 'Lexer Error: Invalid unicode escape [\\u1\'\'b] at column 2 in expression [\'\\u1\'\'bla\']'); + "Lexer Error: Invalid unicode escape [\\u1''b] at column 2 in expression ['\\u1''bla']"); }); it('should tokenize hash as operator', function() { - var tokens: Token[] = lex('#'); + var tokens: Token[] = lex("#"); expectOperatorToken(tokens[0], 0, '#'); }); diff --git a/modules/angular2/test/core/change_detection/parser/locals_spec.ts b/modules/angular2/test/core/change_detection/parser/locals_spec.ts index 5e5d6c0dbd..4c21cf2e10 100644 --- a/modules/angular2/test/core/change_detection/parser/locals_spec.ts +++ b/modules/angular2/test/core/change_detection/parser/locals_spec.ts @@ -13,7 +13,7 @@ export function main() { it('should support getting values', () => { expect(locals.get('key')).toBe('value'); - expect(() => locals.get('notPresent')).toThrowError(new RegExp('Cannot find')); + expect(() => locals.get('notPresent')).toThrowError(new RegExp("Cannot find")); }); it('should support checking if key is present', () => { diff --git a/modules/angular2/test/core/change_detection/parser/parser_spec.ts b/modules/angular2/test/core/change_detection/parser/parser_spec.ts index baa765a681..1970cdc944 100644 --- a/modules/angular2/test/core/change_detection/parser/parser_spec.ts +++ b/modules/angular2/test/core/change_detection/parser/parser_spec.ts @@ -53,86 +53,86 @@ export function main() { function expectBindingError(text) { return expect(() => parseBinding(text)); } - describe('parser', () => { - describe('parseAction', () => { - it('should parse numbers', () => { checkAction('1'); }); + describe("parser", () => { + describe("parseAction", () => { + it('should parse numbers', () => { checkAction("1"); }); it('should parse strings', () => { - checkAction('\'1\'', '"1"'); + checkAction("'1'", '"1"'); checkAction('"1"'); }); - it('should parse null', () => { checkAction('null'); }); + it('should parse null', () => { checkAction("null"); }); it('should parse unary - expressions', () => { - checkAction('-1', '0 - 1'); - checkAction('+1', '1'); + checkAction("-1", "0 - 1"); + checkAction("+1", "1"); }); it('should parse unary ! expressions', () => { - checkAction('!true'); - checkAction('!!true'); - checkAction('!!!true'); + checkAction("!true"); + checkAction("!!true"); + checkAction("!!!true"); }); it('should parse multiplicative expressions', - () => { checkAction('3*4/2%5', '3 * 4 / 2 % 5'); }); + () => { checkAction("3*4/2%5", "3 * 4 / 2 % 5"); }); - it('should parse additive expressions', () => { checkAction('3 + 6 - 2'); }); + it('should parse additive expressions', () => { checkAction("3 + 6 - 2"); }); it('should parse relational expressions', () => { - checkAction('2 < 3'); - checkAction('2 > 3'); - checkAction('2 <= 2'); - checkAction('2 >= 2'); + checkAction("2 < 3"); + checkAction("2 > 3"); + checkAction("2 <= 2"); + checkAction("2 >= 2"); }); it('should parse equality expressions', () => { - checkAction('2 == 3'); - checkAction('2 != 3'); + checkAction("2 == 3"); + checkAction("2 != 3"); }); it('should parse strict equality expressions', () => { - checkAction('2 === 3'); - checkAction('2 !== 3'); + checkAction("2 === 3"); + checkAction("2 !== 3"); }); it('should parse expressions', () => { - checkAction('true && true'); - checkAction('true || false'); + checkAction("true && true"); + checkAction("true || false"); }); - it('should parse grouped expressions', () => { checkAction('(1 + 2) * 3', '1 + 2 * 3'); }); + it('should parse grouped expressions', () => { checkAction("(1 + 2) * 3", "1 + 2 * 3"); }); it('should parse an empty string', () => { checkAction(''); }); - describe('literals', () => { + describe("literals", () => { it('should parse array', () => { - checkAction('[1][0]'); - checkAction('[[1]][0][0]'); - checkAction('[]'); - checkAction('[].length'); - checkAction('[1, 2].length'); + checkAction("[1][0]"); + checkAction("[[1]][0][0]"); + checkAction("[]"); + checkAction("[].length"); + checkAction("[1, 2].length"); }); it('should parse map', () => { - checkAction('{}'); - checkAction('{a: 1}[2]'); - checkAction('{}["a"]'); + checkAction("{}"); + checkAction("{a: 1}[2]"); + checkAction("{}[\"a\"]"); }); it('should only allow identifier, string, or keyword as map key', () => { - expectActionError('{(:0}').toThrowError( - new RegExp('expected identifier, keyword, or string')); + expectActionError('{(:0}') + .toThrowError(new RegExp('expected identifier, keyword, or string')); expectActionError('{1234:0}') .toThrowError(new RegExp('expected identifier, keyword, or string')); }); }); - describe('member access', () => { - it('should parse field access', () => { - checkAction('a'); - checkAction('a.a'); + describe("member access", () => { + it("should parse field access", () => { + checkAction("a"); + checkAction("a.a"); }); it('should only allow identifier or keyword as member names', () => { @@ -147,47 +147,46 @@ export function main() { }); }); - describe('method calls', () => { - it('should parse method calls', () => { - checkAction('fn()'); - checkAction('add(1, 2)'); - checkAction('a.add(1, 2)'); - checkAction('fn().add(1, 2)'); + describe("method calls", () => { + it("should parse method calls", () => { + checkAction("fn()"); + checkAction("add(1, 2)"); + checkAction("a.add(1, 2)"); + checkAction("fn().add(1, 2)"); }); }); - describe('functional calls', () => { - it('should parse function calls', () => { checkAction('fn()(1, 2)'); }); - }); + describe("functional calls", + () => { it("should parse function calls", () => { checkAction("fn()(1, 2)"); }); }); - describe('conditional', () => { + describe("conditional", () => { it('should parse ternary/conditional expressions', () => { - checkAction('7 == 3 + 4 ? 10 : 20'); - checkAction('false ? 10 : 20'); + checkAction("7 == 3 + 4 ? 10 : 20"); + checkAction("false ? 10 : 20"); }); it('should throw on incorrect ternary operator syntax', () => { - expectActionError('true?1').toThrowError(new RegExp( + expectActionError("true?1").toThrowError(new RegExp( 'Parser Error: Conditional expression true\\?1 requires all 3 expressions')); }); }); - describe('assignment', () => { - it('should support field assignments', () => { - checkAction('a = 12'); - checkAction('a.a.a = 123'); - checkAction('a = 123; b = 234;'); + describe("assignment", () => { + it("should support field assignments", () => { + checkAction("a = 12"); + checkAction("a.a.a = 123"); + checkAction("a = 123; b = 234;"); }); - it('should throw on safe field assignments', () => { - expectActionError('a?.a = 123') + it("should throw on safe field assignments", () => { + expectActionError("a?.a = 123") .toThrowError(new RegExp('cannot be used in the assignment')); }); - it('should support array updates', () => { checkAction('a[0] = 200'); }); + it("should support array updates", () => { checkAction("a[0] = 200"); }); }); - it('should error when using pipes', + it("should error when using pipes", () => { expectActionError('x|blah').toThrowError(new RegExp('Cannot have a pipe')); }); it('should store the source in the result', @@ -196,31 +195,31 @@ export function main() { it('should store the passed-in location', () => { expect(parseAction('someExpr', 'location').location).toBe('location'); }); - it('should throw when encountering interpolation', () => { - expectActionError('{{a()}}').toThrowErrorWith( - 'Got interpolation ({{}}) where expression was expected'); + it("should throw when encountering interpolation", () => { + expectActionError("{{a()}}") + .toThrowErrorWith('Got interpolation ({{}}) where expression was expected'); }); }); - describe('general error handling', () => { - it('should throw on an unexpected token', () => { - expectActionError('[1,2] trac').toThrowError(new RegExp('Unexpected token \'trac\'')); + describe("general error handling", () => { + it("should throw on an unexpected token", () => { + expectActionError("[1,2] trac").toThrowError(new RegExp('Unexpected token \'trac\'')); }); it('should throw a reasonable error for unconsumed tokens', () => { - expectActionError(')').toThrowError( - new RegExp('Unexpected token \\) at column 1 in \\[\\)\\]')); + expectActionError(")") + .toThrowError(new RegExp("Unexpected token \\) at column 1 in \\[\\)\\]")); }); it('should throw on missing expected token', () => { - expectActionError('a(b').toThrowError( - new RegExp('Missing expected \\) at the end of the expression \\[a\\(b\\]')); + expectActionError("a(b").toThrowError( + new RegExp("Missing expected \\) at the end of the expression \\[a\\(b\\]")); }); }); - describe('parseBinding', () => { - describe('pipes', () => { - it('should parse pipes', () => { + describe("parseBinding", () => { + describe("pipes", () => { + it("should parse pipes", () => { checkBinding('a(b | c)', 'a((b | c))'); checkBinding('a.b(c.d(e) | f)', 'a.b((c.d(e) | f))'); checkBinding('[1, 2, 3] | a', '([1, 2, 3] | a)'); @@ -258,16 +257,16 @@ export function main() { () => { expect(parseBinding('someExpr', 'location').location).toBe('location'); }); it('should throw on chain expressions', () => { - expect(() => parseBinding('1;2')).toThrowError(new RegExp('contain chained expression')); + expect(() => parseBinding("1;2")).toThrowError(new RegExp("contain chained expression")); }); it('should throw on assignment', () => { - expect(() => parseBinding('a=2')).toThrowError(new RegExp('contain assignments')); + expect(() => parseBinding("a=2")).toThrowError(new RegExp("contain assignments")); }); it('should throw when encountering interpolation', () => { - expectBindingError('{{a.b}}').toThrowErrorWith( - 'Got interpolation ({{}}) where expression was expected'); + expectBindingError("{{a.b}}") + .toThrowErrorWith('Got interpolation ({{}}) where expression was expected'); }); it('should parse conditional expression', () => { checkBinding('a < b ? a : b'); }); @@ -300,93 +299,90 @@ export function main() { () => { expect(keys(parseTemplateBindings('a'))).toEqual(['a']); }); it('should only allow identifier, string, or keyword including dashes as keys', () => { - var bindings = parseTemplateBindings('a:\'b\''); + var bindings = parseTemplateBindings("a:'b'"); expect(keys(bindings)).toEqual(['a']); - bindings = parseTemplateBindings('\'a\':\'b\''); + bindings = parseTemplateBindings("'a':'b'"); expect(keys(bindings)).toEqual(['a']); - bindings = parseTemplateBindings('"a":\'b\''); + bindings = parseTemplateBindings("\"a\":'b'"); expect(keys(bindings)).toEqual(['a']); - bindings = parseTemplateBindings('a-b:\'c\''); + bindings = parseTemplateBindings("a-b:'c'"); expect(keys(bindings)).toEqual(['a-b']); - expect(() => { - parseTemplateBindings('(:0'); - }).toThrowError(new RegExp('expected identifier, keyword, or string')); + expect(() => { parseTemplateBindings('(:0'); }) + .toThrowError(new RegExp('expected identifier, keyword, or string')); - expect(() => { - parseTemplateBindings('1234:0'); - }).toThrowError(new RegExp('expected identifier, keyword, or string')); + expect(() => { parseTemplateBindings('1234:0'); }) + .toThrowError(new RegExp('expected identifier, keyword, or string')); }); it('should detect expressions as value', () => { - var bindings = parseTemplateBindings('a:b'); + var bindings = parseTemplateBindings("a:b"); expect(exprSources(bindings)).toEqual(['b']); - bindings = parseTemplateBindings('a:1+1'); + bindings = parseTemplateBindings("a:1+1"); expect(exprSources(bindings)).toEqual(['1+1']); }); it('should detect names as value', () => { - var bindings = parseTemplateBindings('a:#b'); + var bindings = parseTemplateBindings("a:#b"); expect(keyValues(bindings)).toEqual(['a', '#b=\$implicit']); }); it('should allow space and colon as separators', () => { - var bindings = parseTemplateBindings('a:b'); + var bindings = parseTemplateBindings("a:b"); expect(keys(bindings)).toEqual(['a']); expect(exprSources(bindings)).toEqual(['b']); - bindings = parseTemplateBindings('a b'); + bindings = parseTemplateBindings("a b"); expect(keys(bindings)).toEqual(['a']); expect(exprSources(bindings)).toEqual(['b']); }); it('should allow multiple pairs', () => { - var bindings = parseTemplateBindings('a 1 b 2'); + var bindings = parseTemplateBindings("a 1 b 2"); expect(keys(bindings)).toEqual(['a', 'aB']); expect(exprSources(bindings)).toEqual(['1 ', '2']); }); it('should store the sources in the result', () => { - var bindings = parseTemplateBindings('a 1,b 2'); + var bindings = parseTemplateBindings("a 1,b 2"); expect(bindings[0].expression.source).toEqual('1'); expect(bindings[1].expression.source).toEqual('2'); }); it('should store the passed-in location', () => { - var bindings = parseTemplateBindings('a 1,b 2', 'location'); + var bindings = parseTemplateBindings("a 1,b 2", 'location'); expect(bindings[0].expression.location).toEqual('location'); }); it('should support var/# notation', () => { - var bindings = parseTemplateBindings('var i'); + var bindings = parseTemplateBindings("var i"); expect(keyValues(bindings)).toEqual(['#i=\$implicit']); - bindings = parseTemplateBindings('#i'); + bindings = parseTemplateBindings("#i"); expect(keyValues(bindings)).toEqual(['#i=\$implicit']); - bindings = parseTemplateBindings('var a; var b'); + bindings = parseTemplateBindings("var a; var b"); expect(keyValues(bindings)).toEqual(['#a=\$implicit', '#b=\$implicit']); - bindings = parseTemplateBindings('#a; #b;'); + bindings = parseTemplateBindings("#a; #b;"); expect(keyValues(bindings)).toEqual(['#a=\$implicit', '#b=\$implicit']); - bindings = parseTemplateBindings('var i-a = k-a'); + bindings = parseTemplateBindings("var i-a = k-a"); expect(keyValues(bindings)).toEqual(['#i-a=k-a']); - bindings = parseTemplateBindings('keyword var item; var i = k'); + bindings = parseTemplateBindings("keyword var item; var i = k"); expect(keyValues(bindings)).toEqual(['keyword', '#item=\$implicit', '#i=k']); - bindings = parseTemplateBindings('keyword: #item; #i = k'); + bindings = parseTemplateBindings("keyword: #item; #i = k"); expect(keyValues(bindings)).toEqual(['keyword', '#item=\$implicit', '#i=k']); - bindings = parseTemplateBindings('directive: var item in expr; var a = b', 'location'); - expect(keyValues(bindings)).toEqual([ - 'directive', '#item=\$implicit', 'directiveIn=expr in location', '#a=b' - ]); + bindings = parseTemplateBindings("directive: var item in expr; var a = b", 'location'); + expect(keyValues(bindings)) + .toEqual(['directive', '#item=\$implicit', 'directiveIn=expr in location', '#a=b']); }); it('should parse pipes', () => { @@ -413,14 +409,14 @@ export function main() { expect(new Unparser().unparse(ast)).toEqual(originalExp); }); - it('should throw on empty interpolation expressions', () => { - expect(() => parseInterpolation('{{}}')) + it("should throw on empty interpolation expressions", () => { + expect(() => parseInterpolation("{{}}")) .toThrowErrorWith( - 'Parser Error: Blank expressions are not allowed in interpolated strings'); + "Parser Error: Blank expressions are not allowed in interpolated strings"); - expect(() => parseInterpolation('foo {{ }}')) + expect(() => parseInterpolation("foo {{ }}")) .toThrowErrorWith( - 'Parser Error: Blank expressions are not allowed in interpolated strings'); + "Parser Error: Blank expressions are not allowed in interpolated strings"); }); it('should parse conditional expression', @@ -431,19 +427,19 @@ export function main() { }); }); - describe('parseSimpleBinding', () => { - it('should parse a field access', () => { - var p = parseSimpleBinding('name'); - expect(unparse(p)).toEqual('name'); + describe("parseSimpleBinding", () => { + it("should parse a field access", () => { + var p = parseSimpleBinding("name"); + expect(unparse(p)).toEqual("name"); }); - it('should parse a constant', () => { - var p = parseSimpleBinding('[1, 2]'); - expect(unparse(p)).toEqual('[1, 2]'); + it("should parse a constant", () => { + var p = parseSimpleBinding("[1, 2]"); + expect(unparse(p)).toEqual("[1, 2]"); }); - it('should throw when the given expression is not just a field name', () => { - expect(() => parseSimpleBinding('name + 1')) + it("should throw when the given expression is not just a field name", () => { + expect(() => parseSimpleBinding("name + 1")) .toThrowErrorWith( 'Host binding expression can only contain field access and constants'); }); @@ -456,7 +452,7 @@ export function main() { describe('wrapLiteralPrimitive', () => { it('should wrap a literal primitive', () => { - expect(unparse(createParser().wrapLiteralPrimitive('foo', null))).toEqual('"foo"'); + expect(unparse(createParser().wrapLiteralPrimitive("foo", null))).toEqual('"foo"'); }); }); }); diff --git a/modules/angular2/test/core/change_detection/parser/unparser.ts b/modules/angular2/test/core/change_detection/parser/unparser.ts index 97c5b78468..2ea8ab9133 100644 --- a/modules/angular2/test/core/change_detection/parser/unparser.ts +++ b/modules/angular2/test/core/change_detection/parser/unparser.ts @@ -1,4 +1,27 @@ -import {AST, AstVisitor, PropertyRead, PropertyWrite, Binary, Chain, Conditional, EmptyExpr, BindingPipe, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, Quote, SafePropertyRead, SafeMethodCall} from 'angular2/src/core/change_detection/parser/ast'; +import { + AST, + AstVisitor, + PropertyRead, + PropertyWrite, + Binary, + Chain, + Conditional, + EmptyExpr, + BindingPipe, + FunctionCall, + ImplicitReceiver, + Interpolation, + KeyedRead, + KeyedWrite, + LiteralArray, + LiteralMap, + LiteralPrimitive, + MethodCall, + PrefixNot, + Quote, + SafePropertyRead, + SafeMethodCall +} from 'angular2/src/core/change_detection/parser/ast'; import {StringWrapper, isPresent, isString} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/test/core/change_detection/proto_record_builder_spec.ts b/modules/angular2/test/core/change_detection/proto_record_builder_spec.ts index 5ddf3545ac..cc189c9d55 100644 --- a/modules/angular2/test/core/change_detection/proto_record_builder_spec.ts +++ b/modules/angular2/test/core/change_detection/proto_record_builder_spec.ts @@ -1,15 +1,25 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + inject +} from 'angular2/testing_internal'; import {ProtoRecordBuilder} from 'angular2/src/core/change_detection/proto_change_detector'; import {BindingRecord} from 'angular2/src/core/change_detection/binding_record'; import {Parser} from 'angular2/src/core/change_detection/parser/parser'; export function main() { - describe('ProtoRecordBuilder', () => { + describe("ProtoRecordBuilder", () => { it('should set argumentToPureFunction flag', inject([Parser], (p: Parser) => { var builder = new ProtoRecordBuilder(); - var ast = p.parseBinding('[1,2]', 'location'); // collection literal is a pure function - builder.add(BindingRecord.createForElementProperty(ast, 0, 'property'), [], 0); + var ast = p.parseBinding("[1,2]", "location"); // collection literal is a pure function + builder.add(BindingRecord.createForElementProperty(ast, 0, "property"), [], 0); var isPureFunc = builder.records.map(r => r.argumentToPureFunction); expect(isPureFunc).toEqual([true, true, false]); @@ -18,8 +28,8 @@ export function main() { it('should not set argumentToPureFunction flag when not needed', inject([Parser], (p: Parser) => { var builder = new ProtoRecordBuilder(); - var ast = p.parseBinding('f(1,2)', 'location'); - builder.add(BindingRecord.createForElementProperty(ast, 0, 'property'), [], 0); + var ast = p.parseBinding("f(1,2)", "location"); + builder.add(BindingRecord.createForElementProperty(ast, 0, "property"), [], 0); var isPureFunc = builder.records.map(r => r.argumentToPureFunction); expect(isPureFunc).toEqual([false, false, false]); diff --git a/modules/angular2/test/core/change_detection/proto_record_spec.ts b/modules/angular2/test/core/change_detection/proto_record_spec.ts index b4cad354f3..3da57243a9 100644 --- a/modules/angular2/test/core/change_detection/proto_record_spec.ts +++ b/modules/angular2/test/core/change_detection/proto_record_spec.ts @@ -1,4 +1,13 @@ -import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {isBlank} from 'angular2/src/facade/lang'; import {RecordType, ProtoRecord} from 'angular2/src/core/change_detection/proto_record'; @@ -15,17 +24,16 @@ export function main() { } = {}) { if (isBlank(lastInBinding)) lastInBinding = false; if (isBlank(mode)) mode = RecordType.PropertyRead; - if (isBlank(name)) name = 'name'; + if (isBlank(name)) name = "name"; if (isBlank(directiveIndex)) directiveIndex = null; if (isBlank(argumentToPureFunction)) argumentToPureFunction = false; if (isBlank(referencedBySelf)) referencedBySelf = false; - return new ProtoRecord( - mode, name, null, [], null, 0, directiveIndex, 0, null, lastInBinding, false, - argumentToPureFunction, referencedBySelf, 0); + return new ProtoRecord(mode, name, null, [], null, 0, directiveIndex, 0, null, lastInBinding, + false, argumentToPureFunction, referencedBySelf, 0); } - describe('ProtoRecord', () => { + describe("ProtoRecord", () => { describe('shouldBeChecked', () => { it('should be true for pure functions', () => { expect(r({mode: RecordType.CollectionLiteral}).shouldBeChecked()).toBeTruthy(); }); diff --git a/modules/angular2/test/core/change_detection/util.ts b/modules/angular2/test/core/change_detection/util.ts index 0113d0e9dc..4b86f73968 100644 --- a/modules/angular2/test/core/change_detection/util.ts +++ b/modules/angular2/test/core/change_detection/util.ts @@ -3,12 +3,10 @@ import {isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; export function iterableChangesAsString( {collection = CONST_EXPR([]), previous = CONST_EXPR([]), additions = CONST_EXPR([]), moves = CONST_EXPR([]), removals = CONST_EXPR([]), identityChanges = CONST_EXPR([])}) { - return 'collection: ' + collection.join(', ') + '\n' + - 'previous: ' + previous.join(', ') + '\n' + - 'additions: ' + additions.join(', ') + '\n' + - 'moves: ' + moves.join(', ') + '\n' + - 'removals: ' + removals.join(', ') + '\n' + - 'identityChanges: ' + identityChanges.join(', ') + '\n'; + return "collection: " + collection.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + + "additions: " + additions.join(', ') + "\n" + "moves: " + moves.join(', ') + "\n" + + "removals: " + removals.join(', ') + "\n" + "identityChanges: " + + identityChanges.join(', ') + "\n"; } export function kvChangesAsString( @@ -21,9 +19,7 @@ export function kvChangesAsString( if (isBlank(changes)) changes = []; if (isBlank(removals)) removals = []; - return 'map: ' + map.join(', ') + '\n' + - 'previous: ' + previous.join(', ') + '\n' + - 'additions: ' + additions.join(', ') + '\n' + - 'changes: ' + changes.join(', ') + '\n' + - 'removals: ' + removals.join(', ') + '\n'; + return "map: " + map.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + + "additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" + + "removals: " + removals.join(', ') + "\n"; } diff --git a/modules/angular2/test/core/debug/debug_node_spec.ts b/modules/angular2/test/core/debug/debug_node_spec.ts index 6e1486a2b9..db64592692 100644 --- a/modules/angular2/test/core/debug/debug_node_spec.ts +++ b/modules/angular2/test/core/debug/debug_node_spec.ts @@ -1,4 +1,18 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + TestComponentBuilder +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; @@ -173,70 +187,74 @@ export function main() { describe('debug element', function() { it('should list all child nodes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ParentComp) + .then((fixture) => { + fixture.detectChanges(); - // The root component has 3 elements and 2 text node children. - expect(fixture.debugElement.childNodes.length).toEqual(5); - async.done(); - }); + // The root component has 3 elements and 2 text node children. + expect(fixture.debugElement.childNodes.length).toEqual(5); + async.done(); + }); })); it('should list all component child elements', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ParentComp) + .then((fixture) => { + fixture.detectChanges(); - var childEls = fixture.debugElement.children; + var childEls = fixture.debugElement.children; - // The root component has 3 elements in its view. - expect(childEls.length).toEqual(3); - expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true); - expect(DOM.hasClass(childEls[1].nativeElement, 'parent')).toBe(true); - expect(DOM.hasClass(childEls[2].nativeElement, 'child-comp-class')).toBe(true); + // The root component has 3 elements in its view. + expect(childEls.length).toEqual(3); + expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true); + expect(DOM.hasClass(childEls[1].nativeElement, 'parent')).toBe(true); + expect(DOM.hasClass(childEls[2].nativeElement, 'child-comp-class')).toBe(true); - var nested = childEls[0].children; - expect(nested.length).toEqual(1); - expect(DOM.hasClass(nested[0].nativeElement, 'parentnested')).toBe(true); + var nested = childEls[0].children; + expect(nested.length).toEqual(1); + expect(DOM.hasClass(nested[0].nativeElement, 'parentnested')).toBe(true); - var childComponent = childEls[2]; + var childComponent = childEls[2]; - var childCompChildren = childComponent.children; - expect(childCompChildren.length).toEqual(2); - expect(DOM.hasClass(childCompChildren[0].nativeElement, 'child')).toBe(true); - expect(DOM.hasClass(childCompChildren[1].nativeElement, 'child')).toBe(true); + var childCompChildren = childComponent.children; + expect(childCompChildren.length).toEqual(2); + expect(DOM.hasClass(childCompChildren[0].nativeElement, 'child')).toBe(true); + expect(DOM.hasClass(childCompChildren[1].nativeElement, 'child')).toBe(true); - var childNested = childCompChildren[0].children; - expect(childNested.length).toEqual(1); - expect(DOM.hasClass(childNested[0].nativeElement, 'childnested')).toBe(true); + var childNested = childCompChildren[0].children; + expect(childNested.length).toEqual(1); + expect(DOM.hasClass(childNested[0].nativeElement, 'childnested')).toBe(true); - async.done(); - }); + async.done(); + }); })); it('should list conditional component child elements', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ConditionalParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ConditionalParentComp) + .then((fixture) => { + fixture.detectChanges(); - var childEls = fixture.debugElement.children; + var childEls = fixture.debugElement.children; - // The root component has 2 elements in its view. - expect(childEls.length).toEqual(2); - expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true); - expect(DOM.hasClass(childEls[1].nativeElement, 'cond-content-comp-class')).toBe(true); + // The root component has 2 elements in its view. + expect(childEls.length).toEqual(2); + expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true); + expect(DOM.hasClass(childEls[1].nativeElement, 'cond-content-comp-class')) + .toBe(true); - var conditionalContentComp = childEls[1]; + var conditionalContentComp = childEls[1]; - expect(conditionalContentComp.children.length).toEqual(0); + expect(conditionalContentComp.children.length).toEqual(0); - conditionalContentComp.componentInstance.myBool = true; - fixture.detectChanges(); + conditionalContentComp.componentInstance.myBool = true; + fixture.detectChanges(); - expect(conditionalContentComp.children.length).toEqual(1); - async.done(); - }); + expect(conditionalContentComp.children.length).toEqual(1); + async.done(); + }); })); it('should list child elements within viewports', @@ -270,103 +288,109 @@ export function main() { it('should query child elements by css', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ParentComp) + .then((fixture) => { + fixture.detectChanges(); - var childTestEls = fixture.debugElement.queryAll(By.css('child-comp')); + var childTestEls = fixture.debugElement.queryAll(By.css('child-comp')); - expect(childTestEls.length).toBe(1); - expect(DOM.hasClass(childTestEls[0].nativeElement, 'child-comp-class')).toBe(true); + expect(childTestEls.length).toBe(1); + expect(DOM.hasClass(childTestEls[0].nativeElement, 'child-comp-class')).toBe(true); - async.done(); - }); + async.done(); + }); })); it('should query child elements by directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ParentComp) + .then((fixture) => { + fixture.detectChanges(); - var childTestEls = fixture.debugElement.queryAll(By.directive(MessageDir)); + var childTestEls = fixture.debugElement.queryAll(By.directive(MessageDir)); - expect(childTestEls.length).toBe(4); - expect(DOM.hasClass(childTestEls[0].nativeElement, 'parent')).toBe(true); - expect(DOM.hasClass(childTestEls[1].nativeElement, 'parentnested')).toBe(true); - expect(DOM.hasClass(childTestEls[2].nativeElement, 'child')).toBe(true); - expect(DOM.hasClass(childTestEls[3].nativeElement, 'childnested')).toBe(true); + expect(childTestEls.length).toBe(4); + expect(DOM.hasClass(childTestEls[0].nativeElement, 'parent')).toBe(true); + expect(DOM.hasClass(childTestEls[1].nativeElement, 'parentnested')).toBe(true); + expect(DOM.hasClass(childTestEls[2].nativeElement, 'child')).toBe(true); + expect(DOM.hasClass(childTestEls[3].nativeElement, 'childnested')).toBe(true); - async.done(); - }); + async.done(); + }); })); it('should list providerTokens', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ParentComp) + .then((fixture) => { + fixture.detectChanges(); - expect(fixture.debugElement.providerTokens).toContain(Logger); + expect(fixture.debugElement.providerTokens).toContain(Logger); - async.done(); - }); + async.done(); + }); })); it('should list locals', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(LocalsComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(LocalsComp) + .then((fixture) => { + fixture.detectChanges(); - expect(fixture.debugElement.children[0].getLocal('alice')).toBeAnInstanceOf(MyDir); + expect(fixture.debugElement.children[0].getLocal('alice')).toBeAnInstanceOf(MyDir); - async.done(); - }); + async.done(); + }); })); it('should allow injecting from the element injector', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(ParentComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(ParentComp) + .then((fixture) => { + fixture.detectChanges(); - expect(fixture.debugElement.children[0].inject(Logger).log).toEqual([ - 'parent', 'nestedparent', 'child', 'nestedchild' - ]); + expect(fixture.debugElement.children[0].inject(Logger).log) + .toEqual(['parent', 'nestedparent', 'child', 'nestedchild']); - async.done(); - }); + async.done(); + }); })); it('should list event listeners', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(EventsComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(EventsComp) + .then((fixture) => { + fixture.detectChanges(); - expect(fixture.debugElement.children[0].listeners.length).toEqual(1); - expect(fixture.debugElement.children[1].listeners.length).toEqual(1); + expect(fixture.debugElement.children[0].listeners.length).toEqual(1); + expect(fixture.debugElement.children[1].listeners.length).toEqual(1); - async.done(); - }); + async.done(); + }); })); it('should trigger event handlers', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.createAsync(EventsComp).then((fixture) => { - fixture.detectChanges(); + tcb.createAsync(EventsComp) + .then((fixture) => { + fixture.detectChanges(); - expect(fixture.debugElement.componentInstance.clicked).toBe(false); - expect(fixture.debugElement.componentInstance.customed).toBe(false); + expect(fixture.debugElement.componentInstance.clicked).toBe(false); + expect(fixture.debugElement.componentInstance.customed).toBe(false); - fixture.debugElement.children[0].triggerEventHandler('click', <Event>{}); - expect(fixture.debugElement.componentInstance.clicked).toBe(true); + fixture.debugElement.children[0].triggerEventHandler('click', <Event>{}); + expect(fixture.debugElement.componentInstance.clicked).toBe(true); - fixture.debugElement.children[1].triggerEventHandler('myevent', <Event>{}); - expect(fixture.debugElement.componentInstance.customed).toBe(true); + fixture.debugElement.children[1].triggerEventHandler('myevent', <Event>{}); + expect(fixture.debugElement.componentInstance.customed).toBe(true); - async.done(); - }); + async.done(); + }); })); }); } diff --git a/modules/angular2/test/core/di/binding_spec.ts b/modules/angular2/test/core/di/binding_spec.ts index 3f3d8fbc9e..b69742538c 100644 --- a/modules/angular2/test/core/di/binding_spec.ts +++ b/modules/angular2/test/core/di/binding_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {bind, provide} from 'angular2/core'; @@ -8,15 +18,13 @@ export function main() { describe('type errors', () => { it('should throw when trying to create a class provider and not passing a class', () => { - expect(() => { - bind('foo').toClass(<any>0); - }).toThrowError('Trying to create a class provider but "0" is not a class!'); + expect(() => { bind('foo').toClass(<any>0); }) + .toThrowError('Trying to create a class provider but "0" is not a class!'); }); it('should throw when trying to create a factory provider and not passing a function', () => { - expect(() => { - bind('foo').toFactory(<any>0); - }).toThrowError('Trying to create a factory provider but "0" is not a function!'); + expect(() => { bind('foo').toFactory(<any>0); }) + .toThrowError('Trying to create a factory provider but "0" is not a function!'); }); }); }); diff --git a/modules/angular2/test/core/di/forward_ref_spec.ts b/modules/angular2/test/core/di/forward_ref_spec.ts index 8e964729b1..c4e4688a4e 100644 --- a/modules/angular2/test/core/di/forward_ref_spec.ts +++ b/modules/angular2/test/core/di/forward_ref_spec.ts @@ -1,9 +1,19 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {forwardRef, resolveForwardRef} from 'angular2/src/core/di'; import {Type} from 'angular2/src/facade/lang'; export function main() { - describe('forwardRef', function() { + describe("forwardRef", function() { it('should wrap and unwrap the reference', () => { var ref = forwardRef(() => String); expect(ref instanceof Type).toBe(true); diff --git a/modules/angular2/test/core/di/injector_spec.ts b/modules/angular2/test/core/di/injector_spec.ts index 4973a5b053..471e0e5f39 100644 --- a/modules/angular2/test/core/di/injector_spec.ts +++ b/modules/angular2/test/core/di/injector_spec.ts @@ -2,18 +2,38 @@ import {isBlank, stringify} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/testing_internal'; import {SpyDependencyProvider} from '../spies'; -import {Injector, provide, ResolvedProvider, Key, forwardRef, Injectable, InjectMetadata, SelfMetadata, HostMetadata, SkipSelfMetadata, Optional, Inject, Provider} from 'angular2/core'; +import { + Injector, + provide, + ResolvedProvider, + Key, + forwardRef, + Injectable, + InjectMetadata, + SelfMetadata, + HostMetadata, + SkipSelfMetadata, + Optional, + Inject, + Provider +} from 'angular2/core'; import {DependencyMetadata} from 'angular2/src/core/di/metadata'; import {ResolvedProvider_} from 'angular2/src/core/di/provider'; -import {InjectorInlineStrategy, InjectorDynamicStrategy, ProtoInjector, ProviderWithVisibility, Visibility} from 'angular2/src/core/di/injector'; +import { + InjectorInlineStrategy, + InjectorDynamicStrategy, + ProtoInjector, + ProviderWithVisibility, + Visibility +} from 'angular2/src/core/di/injector'; class CustomDependencyMetadata extends DependencyMetadata {} class Engine {} class BrokenEngine { - constructor() { throw new BaseException('Broken Engine'); } + constructor() { throw new BaseException("Broken Engine"); } } class DashboardSoftware {} @@ -72,28 +92,33 @@ function factoryFn(a) {} export function main() { var dynamicProviders = [ - provide('provider0', {useValue: 1}), provide('provider1', {useValue: 1}), - provide('provider2', {useValue: 1}), provide('provider3', {useValue: 1}), - provide('provider4', {useValue: 1}), provide('provider5', {useValue: 1}), - provide('provider6', {useValue: 1}), provide('provider7', {useValue: 1}), - provide('provider8', {useValue: 1}), provide('provider9', {useValue: 1}), + provide('provider0', {useValue: 1}), + provide('provider1', {useValue: 1}), + provide('provider2', {useValue: 1}), + provide('provider3', {useValue: 1}), + provide('provider4', {useValue: 1}), + provide('provider5', {useValue: 1}), + provide('provider6', {useValue: 1}), + provide('provider7', {useValue: 1}), + provide('provider8', {useValue: 1}), + provide('provider9', {useValue: 1}), provide('provider10', {useValue: 1}) ]; - [{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy}, { - strategy: 'dynamic', - providers: dynamicProviders, - strategyClass: InjectorDynamicStrategy - }].forEach((context) => { + [{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy}, + { + strategy: 'dynamic', + providers: dynamicProviders, + strategyClass: InjectorDynamicStrategy + }].forEach((context) => { function createInjector(providers: any[], parent: Injector = null, isHost: boolean = false) { - return new Injector( - ProtoInjector.fromResolvedProviders( - Injector.resolve(providers.concat(context['providers']))), - parent, isHost); + return new Injector(ProtoInjector.fromResolvedProviders( + Injector.resolve(providers.concat(context['providers']))), + parent, isHost); } describe(`injector ${context['strategy']}`, () => { - it('should use the right strategy', () => { + it("should use the right strategy", () => { var injector = createInjector([]); expect(injector.internalStrategy).toBeAnInstanceOf(context['strategyClass']); }); @@ -124,17 +149,17 @@ export function main() { it('should throw when no type and not @Inject (class case)', () => { expect(() => createInjector([NoAnnotations])) .toThrowError( - 'Cannot resolve all parameters for \'NoAnnotations\'(?). ' + + "Cannot resolve all parameters for 'NoAnnotations'(?). " + 'Make sure that all the parameters are decorated with Inject or have valid type annotations ' + - 'and that \'NoAnnotations\' is decorated with Injectable.'); + "and that 'NoAnnotations' is decorated with Injectable."); }); it('should throw when no type and not @Inject (factory case)', () => { - expect(() => createInjector([provide('someToken', {useFactory: factoryFn})])) + expect(() => createInjector([provide("someToken", {useFactory: factoryFn})])) .toThrowError( - 'Cannot resolve all parameters for \'factoryFn\'(?). ' + + "Cannot resolve all parameters for 'factoryFn'(?). " + 'Make sure that all the parameters are decorated with Inject or have valid type annotations ' + - 'and that \'factoryFn\' is decorated with Injectable.'); + "and that 'factoryFn' is decorated with Injectable."); }); it('should cache instances', () => { @@ -147,10 +172,10 @@ export function main() { }); it('should provide to a value', () => { - var injector = createInjector([provide(Engine, {useValue: 'fake engine'})]); + var injector = createInjector([provide(Engine, {useValue: "fake engine"})]); var engine = injector.get(Engine); - expect(engine).toEqual('fake engine'); + expect(engine).toEqual("fake engine"); }); it('should provide to a factory', () => { @@ -168,22 +193,42 @@ export function main() { function factoryWithTooManyArgs() { return new Car(null); } var injector = createInjector([ - Engine, provide(Car, { - useFactory: factoryWithTooManyArgs, - deps: [ - Engine, Engine, Engine, Engine, Engine, Engine, Engine, - Engine, Engine, Engine, Engine, Engine, Engine, Engine, - Engine, Engine, Engine, Engine, Engine, Engine, Engine - ] - }) + Engine, + provide(Car, + { + useFactory: factoryWithTooManyArgs, + deps: [ + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine, + Engine + ] + }) ]); try { injector.get(Car); - throw 'Must throw'; + throw "Must throw"; } catch (e) { - expect(e.message).toContain( - `Cannot instantiate 'Car' because it has more than 20 dependencies`); + expect(e.message) + .toContain(`Cannot instantiate 'Car' because it has more than 20 dependencies`); } }); @@ -195,7 +240,8 @@ export function main() { it('should provide to an alias', () => { var injector = createInjector([ - Engine, provide(SportsCar, {useClass: SportsCar}), + Engine, + provide(SportsCar, {useClass: SportsCar}), provide(Car, {useExisting: SportsCar}) ]); @@ -207,7 +253,8 @@ export function main() { it('should support multiProviders', () => { var injector = createInjector([ - Engine, new Provider(Car, {useClass: SportsCar, multi: true}), + Engine, + new Provider(Car, {useClass: SportsCar, multi: true}), new Provider(Car, {useClass: CarWithOptionalEngine, multi: true}) ]); @@ -235,7 +282,7 @@ export function main() { it('should handle forwardRef in useExisting', () => { var injector = createInjector([ provide('originalEngine', {useClass: forwardRef(() => Engine)}), - provide('aliasedEngine', {useExisting: <any>forwardRef(() => 'originalEngine')}) + provide('aliasedEngine', {useExisting:<any>forwardRef(() => 'originalEngine')}) ]); expect(injector.get('aliasedEngine')).toBeAnInstanceOf(Engine); }); @@ -256,14 +303,14 @@ export function main() { expect(car.engine).toEqual(null); }); - it('should flatten passed-in providers', () => { + it("should flatten passed-in providers", () => { var injector = createInjector([[[Engine, Car]]]); var car = injector.get(Car); expect(car).toBeAnInstanceOf(Car); }); - it('should use the last provider when there are multiple providers for same token', () => { + it("should use the last provider when there are multiple providers for same token", () => { var injector = createInjector( [provide(Engine, {useClass: Engine}), provide(Engine, {useClass: TurboEngine})]); @@ -277,7 +324,7 @@ export function main() { }); it('should throw when given invalid providers', () => { - expect(() => createInjector(<any>['blah'])) + expect(() => createInjector(<any>["blah"])) .toThrowError( 'Invalid provider - only instances of Provider and Type are allowed, got: blah'); }); @@ -319,10 +366,10 @@ export function main() { try { injector.get(Car); - throw 'Must throw'; + throw "Must throw"; } catch (e) { - expect(e.message).toContain( - `Error during instantiation of Engine! (${stringify(Car)} -> Engine)`); + expect(e.message) + .toContain(`Error during instantiation of Engine! (${stringify(Car)} -> Engine)`); expect(e.originalException instanceof BaseException).toBeTruthy(); expect(e.causeKey.token).toEqual(Engine); } @@ -337,14 +384,14 @@ export function main() { var protoChild = new ProtoInjector([new ProviderWithVisibility(carProvider, Visibility.Public)]); - var parent = new Injector(protoParent, null, false, null, () => 'parentContext'); - var child = new Injector(protoChild, parent, false, null, () => 'childContext'); + var parent = new Injector(protoParent, null, false, null, () => "parentContext"); + var child = new Injector(protoChild, parent, false, null, () => "childContext"); try { child.get(Car); - throw 'Must throw'; + throw "Must throw"; } catch (e) { - expect(e.context).toEqual('childContext'); + expect(e.context).toEqual("childContext"); } }); @@ -356,7 +403,7 @@ export function main() { provide(Engine, {useFactory: (() => isBroken ? new BrokenEngine() : new Engine())}) ]); - expect(() => injector.get(Car)).toThrowError(new RegExp('Error')); + expect(() => injector.get(Car)).toThrowError(new RegExp("Error")); isBroken = false; @@ -372,7 +419,7 @@ export function main() { var e = new Engine(); var depProvider = <any>new SpyDependencyProvider(); - depProvider.spy('getDependency').andReturn(e); + depProvider.spy("getDependency").andReturn(e); var providers = Injector.resolve([Car]); var proto = @@ -380,14 +427,14 @@ export function main() { var injector = new Injector(proto, null, false, depProvider); expect(injector.get(Car).engine).toEqual(e); - expect(depProvider.spy('getDependency')) - .toHaveBeenCalledWith( - injector, providers[0], providers[0].resolvedFactories[0].dependencies[0]); + expect(depProvider.spy("getDependency")) + .toHaveBeenCalledWith(injector, providers[0], + providers[0].resolvedFactories[0].dependencies[0]); }); }); - describe('child', () => { + describe("child", () => { it('should load instances from parent injector', () => { var parent = Injector.resolveAndCreate([Engine]); var child = parent.resolveAndCreateChild([]); @@ -398,7 +445,7 @@ export function main() { expect(engineFromChild).toBe(engineFromParent); }); - it('should not use the child providers when resolving the dependencies of a parent provider', + it("should not use the child providers when resolving the dependencies of a parent provider", () => { var parent = Injector.resolveAndCreate([Car, Engine]); var child = parent.resolveAndCreateChild([provide(Engine, {useClass: TurboEngine})]); @@ -418,7 +465,7 @@ export function main() { expect(engineFromChild).toBeAnInstanceOf(TurboEngine); }); - it('should give access to parent', () => { + it("should give access to parent", () => { var parent = Injector.resolveAndCreate([]); var child = parent.resolveAndCreateChild([]); expect(child.parent).toBe(parent); @@ -449,9 +496,9 @@ export function main() { }); }); - describe('depedency resolution', () => { - describe('@Self()', () => { - it('should return a dependency from self', () => { + describe("depedency resolution", () => { + describe("@Self()", () => { + it("should return a dependency from self", () => { var inj = Injector.resolveAndCreate([ Engine, provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]}) @@ -460,26 +507,28 @@ export function main() { expect(inj.get(Car)).toBeAnInstanceOf(Car); }); - it('should throw when not requested provider on self', () => { + it("should throw when not requested provider on self", () => { var parent = Injector.resolveAndCreate([Engine]); - var child = parent.resolveAndCreateChild([provide( - Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})]); + var child = parent.resolveAndCreateChild([ + provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]}) + ]); expect(() => child.get(Car)) .toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`); }); }); - describe('@Host()', () => { - it('should return a dependency from same host', () => { + describe("@Host()", () => { + it("should return a dependency from same host", () => { var parent = Injector.resolveAndCreate([Engine]); - var child = parent.resolveAndCreateChild([provide( - Car, {useFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})]); + var child = parent.resolveAndCreateChild([ + provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]}) + ]); expect(child.get(Car)).toBeAnInstanceOf(Car); }); - it('should return a private dependency declared at the host', () => { + it("should return a private dependency declared at the host", () => { var engine = Injector.resolve([Engine])[0]; var protoParent = new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]); @@ -492,7 +541,7 @@ export function main() { expect(child.get(Car)).toBeAnInstanceOf(Car); }); - it('should not return a public dependency declared at the host', () => { + it("should not return a public dependency declared at the host", () => { var engine = Injector.resolve([Engine])[0]; var protoParent = new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]); @@ -506,7 +555,7 @@ export function main() { .toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`); }); - it('should not skip self', () => { + it("should not skip self", () => { var parent = Injector.resolveAndCreate([Engine]); var child = parent.resolveAndCreateChild([ provide(Engine, {useClass: TurboEngine}), @@ -517,8 +566,8 @@ export function main() { }); }); - describe('default', () => { - it('should return a private dependency declared at the host', () => { + describe("default", () => { + it("should return a private dependency declared at the host", () => { var engine = Injector.resolve([Engine])[0]; var protoParent = new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]); @@ -527,16 +576,15 @@ export function main() { var child = createInjector( [ provide(Engine, {useClass: BrokenEngine}), - provide( - Car, - {useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]}) + provide(Car, + {useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]}) ], parent, true); // boundary expect(child.get(Car)).toBeAnInstanceOf(Car); }); - it('should return a public dependency declared at the host', () => { + it("should return a public dependency declared at the host", () => { var engine = Injector.resolve([Engine])[0]; var protoParent = new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]); @@ -545,16 +593,15 @@ export function main() { var child = createInjector( [ provide(Engine, {useClass: BrokenEngine}), - provide( - Car, - {useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]}) + provide(Car, + {useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]}) ], parent, true); // boundary expect(child.get(Car)).toBeAnInstanceOf(Car); }); - it('should not return a private dependency declared NOT at the host', () => { + it("should not return a private dependency declared NOT at the host", () => { var engine = Injector.resolve([Engine])[0]; var protoParent = new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]); @@ -563,9 +610,8 @@ export function main() { var child = createInjector( [ provide(Engine, {useClass: BrokenEngine}), - provide( - Car, - {useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]}) + provide(Car, + {useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]}) ], parent, false); @@ -573,7 +619,7 @@ export function main() { .toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`); }); - it('should not skip self', () => { + it("should not skip self", () => { var parent = Injector.resolveAndCreate([Engine]); var child = parent.resolveAndCreateChild([ provide(Engine, {useClass: TurboEngine}), @@ -594,7 +640,7 @@ export function main() { }); }); - it('should support multi providers', () => { + it("should support multi providers", () => { var provider = Injector.resolve([ new Provider(Engine, {useClass: BrokenEngine, multi: true}), new Provider(Engine, {useClass: TurboEngine, multi: true}) @@ -605,7 +651,7 @@ export function main() { expect(provider.resolvedFactories.length).toEqual(2); }); - it('should support multi providers with only one provider', () => { + it("should support multi providers with only one provider", () => { var provider = Injector.resolve([new Provider(Engine, {useClass: BrokenEngine, multi: true})])[0]; @@ -614,23 +660,22 @@ export function main() { expect(provider.resolvedFactories.length).toEqual(1); }); - it('should throw when mixing multi providers with regular providers', () => { + it("should throw when mixing multi providers with regular providers", () => { expect(() => { Injector.resolve([new Provider(Engine, {useClass: BrokenEngine, multi: true}), Engine]); - }).toThrowErrorWith('Cannot mix multi providers and regular providers'); + }).toThrowErrorWith("Cannot mix multi providers and regular providers"); expect(() => { Injector.resolve([Engine, new Provider(Engine, {useClass: BrokenEngine, multi: true})]); - }).toThrowErrorWith('Cannot mix multi providers and regular providers'); + }).toThrowErrorWith("Cannot mix multi providers and regular providers"); }); it('should resolve forward references', () => { var providers = Injector.resolve([ forwardRef(() => Engine), [provide(forwardRef(() => BrokenEngine), {useClass: forwardRef(() => Engine)})], - provide( - forwardRef(() => String), - {useFactory: () => 'OK', deps: [forwardRef(() => Engine)]}) + provide(forwardRef(() => String), + {useFactory: () => 'OK', deps: [forwardRef(() => Engine)]}) ]); var engineProvider = providers[0]; @@ -643,33 +688,35 @@ export function main() { }); it('should support overriding factory dependencies with dependency annotations', () => { - var providers = Injector.resolve([provide('token', { - useFactory: (e) => 'result', - deps: [[new InjectMetadata('dep'), new CustomDependencyMetadata()]] - })]); + var providers = Injector.resolve([ + provide("token", + { + useFactory: (e) => "result", + deps: [[new InjectMetadata("dep"), new CustomDependencyMetadata()]] + }) + ]); var provider = providers[0]; - expect(provider.resolvedFactories[0].dependencies[0].key.token).toEqual('dep'); - expect(provider.resolvedFactories[0].dependencies[0].properties).toEqual([ - new CustomDependencyMetadata() - ]); + expect(provider.resolvedFactories[0].dependencies[0].key.token).toEqual("dep"); + expect(provider.resolvedFactories[0].dependencies[0].properties) + .toEqual([new CustomDependencyMetadata()]); }); it('should allow declaring dependencies with flat arrays', () => { var resolved = Injector.resolve( - [provide('token', {useFactory: e => e, deps: [new InjectMetadata('dep')]})]); + [provide('token', {useFactory: e => e, deps: [new InjectMetadata("dep")]})]); var nestedResolved = Injector.resolve( - [provide('token', {useFactory: e => e, deps: [[new InjectMetadata('dep')]]})]); + [provide('token', {useFactory: e => e, deps: [[new InjectMetadata("dep")]]})]); expect(resolved[0].resolvedFactories[0].dependencies[0].key.token) .toEqual(nestedResolved[0].resolvedFactories[0].dependencies[0].key.token); }); }); - describe('displayName', () => { - it('should work', () => { + describe("displayName", () => { + it("should work", () => { expect(Injector.resolveAndCreate([Engine, BrokenEngine]).displayName) - .toEqual('Injector(providers: [ \'Engine\' , \'BrokenEngine\' ])'); + .toEqual('Injector(providers: [ "Engine" , "BrokenEngine" ])'); }); }); }); diff --git a/modules/angular2/test/core/di/key_spec.ts b/modules/angular2/test/core/di/key_spec.ts index 459c505c30..6104514345 100644 --- a/modules/angular2/test/core/di/key_spec.ts +++ b/modules/angular2/test/core/di/key_spec.ts @@ -2,7 +2,7 @@ import {describe, iit, it, expect, beforeEach} from 'angular2/testing_internal'; import {Key, KeyRegistry} from 'angular2/src/core/di/key'; export function main() { - describe('key', function() { + describe("key", function() { var registry: KeyRegistry; beforeEach(function() { registry = new KeyRegistry(); }); diff --git a/modules/angular2/test/core/directive_lifecycle_integration_spec.ts b/modules/angular2/test/core/directive_lifecycle_integration_spec.ts index 46c6a50259..58e158dda5 100644 --- a/modules/angular2/test/core/directive_lifecycle_integration_spec.ts +++ b/modules/angular2/test/core/directive_lifecycle_integration_spec.ts @@ -1,38 +1,58 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit, Log, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit, + Log, + TestComponentBuilder +} from 'angular2/testing_internal'; -import {OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked} from 'angular2/core'; +import { + OnChanges, + OnInit, + DoCheck, + AfterContentInit, + AfterContentChecked, + AfterViewInit, + AfterViewChecked +} from 'angular2/core'; import {Directive, Component, ViewMetadata} from 'angular2/src/core/metadata'; export function main() { describe('directive lifecycle integration spec', () => { it('should invoke lifecycle methods ngOnChanges > ngOnInit > ngDoCheck > ngAfterContentChecked', - inject( - [TestComponentBuilder, Log, AsyncTestCompleter], - (tcb: TestComponentBuilder, log: Log, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div [field]="123" lifecycle></div>', - directives: [LifecycleCmp] - })) - .createAsync(MyComp) - .then((tc) => { - tc.detectChanges(); + inject([TestComponentBuilder, Log, AsyncTestCompleter], (tcb: TestComponentBuilder, log: Log, + async) => { + tcb.overrideView( + MyComp, + new ViewMetadata( + {template: '<div [field]="123" lifecycle></div>', directives: [LifecycleCmp]})) + .createAsync(MyComp) + .then((tc) => { + tc.detectChanges(); - expect(log.result()) - .toEqual( - 'ngOnChanges; ngOnInit; ngDoCheck; ngAfterContentInit; ngAfterContentChecked; child_ngDoCheck; ' + - 'ngAfterViewInit; ngAfterViewChecked'); + expect(log.result()) + .toEqual( + "ngOnChanges; ngOnInit; ngDoCheck; ngAfterContentInit; ngAfterContentChecked; child_ngDoCheck; " + + "ngAfterViewInit; ngAfterViewChecked"); - log.clear(); - tc.detectChanges(); + log.clear(); + tc.detectChanges(); - expect(log.result()) - .toEqual( - 'ngDoCheck; ngAfterContentChecked; child_ngDoCheck; ngAfterViewChecked'); + expect(log.result()) + .toEqual( + "ngDoCheck; ngAfterContentChecked; child_ngDoCheck; ngAfterViewChecked"); - async.done(); - }); - })); + async.done(); + }); + })); }); } @@ -40,11 +60,11 @@ export function main() { @Directive({selector: '[lifecycle-dir]'}) class LifecycleDir implements DoCheck { constructor(private _log: Log) {} - ngDoCheck() { this._log.add('child_ngDoCheck'); } + ngDoCheck() { this._log.add("child_ngDoCheck"); } } @Component({ - selector: '[lifecycle]', + selector: "[lifecycle]", inputs: ['field'], template: `<div lifecycle-dir></div>`, directives: [LifecycleDir] @@ -54,19 +74,19 @@ class LifecycleCmp implements OnChanges, field; constructor(private _log: Log) {} - ngOnChanges(_) { this._log.add('ngOnChanges'); } + ngOnChanges(_) { this._log.add("ngOnChanges"); } - ngOnInit() { this._log.add('ngOnInit'); } + ngOnInit() { this._log.add("ngOnInit"); } - ngDoCheck() { this._log.add('ngDoCheck'); } + ngDoCheck() { this._log.add("ngDoCheck"); } - ngAfterContentInit() { this._log.add('ngAfterContentInit'); } + ngAfterContentInit() { this._log.add("ngAfterContentInit"); } - ngAfterContentChecked() { this._log.add('ngAfterContentChecked'); } + ngAfterContentChecked() { this._log.add("ngAfterContentChecked"); } - ngAfterViewInit() { this._log.add('ngAfterViewInit'); } + ngAfterViewInit() { this._log.add("ngAfterViewInit"); } - ngAfterViewChecked() { this._log.add('ngAfterViewChecked'); } + ngAfterViewChecked() { this._log.add("ngAfterViewChecked"); } } @Component({selector: 'my-comp', directives: []}) diff --git a/modules/angular2/test/core/dom/dom_adapter_spec.ts b/modules/angular2/test/core/dom/dom_adapter_spec.ts index 4ea122df14..11bf4cf7ad 100644 --- a/modules/angular2/test/core/dom/dom_adapter_spec.ts +++ b/modules/angular2/test/core/dom/dom_adapter_spec.ts @@ -1,4 +1,18 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, beforeEachProviders, SpyObject, stringifyElement} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + beforeEachProviders, + SpyObject, + stringifyElement +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; diff --git a/modules/angular2/test/core/dom/shim_spec.ts b/modules/angular2/test/core/dom/shim_spec.ts index 845afd9ea5..bd2b5c3103 100644 --- a/modules/angular2/test/core/dom/shim_spec.ts +++ b/modules/angular2/test/core/dom/shim_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; export function main() { describe('Shim', () => { diff --git a/modules/angular2/test/core/facade/observable_spec.ts b/modules/angular2/test/core/facade/observable_spec.ts index 0785eebe08..ae51a1b204 100644 --- a/modules/angular2/test/core/facade/observable_spec.ts +++ b/modules/angular2/test/core/facade/observable_spec.ts @@ -1,12 +1,24 @@ -import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, SpyObject, AsyncTestCompleter, inject} from 'angular2/testing_internal'; +import { + describe, + it, + expect, + beforeEach, + ddescribe, + iit, + xit, + el, + SpyObject, + AsyncTestCompleter, + inject +} from 'angular2/testing_internal'; import {Observable, Subject, EventEmitter, PromiseWrapper} from 'angular2/src/facade/async'; export function main() { - describe('Observable', () => { - describe('#core', () => { + describe("Observable", () => { + describe("#core", () => { - it('should call next with values', inject([AsyncTestCompleter], (async) => { + it("should call next with values", inject([AsyncTestCompleter], (async) => { let o = new Observable(sink => { sink.next(1); }); @@ -17,7 +29,7 @@ export function main() { })); - it('should call next and then complete', inject([AsyncTestCompleter], (async) => { + it("should call next and then complete", inject([AsyncTestCompleter], (async) => { let o = new Observable(sink => { sink.next(1); @@ -25,16 +37,14 @@ export function main() { }); let nexted = false; - o.subscribe( - v => { nexted = true; }, null, - () => { - expect(nexted).toBe(true); - async.done(); - }); + o.subscribe(v => { nexted = true; }, null, () => { + expect(nexted).toBe(true); + async.done(); + }); })); - it('should call error with errors', inject([AsyncTestCompleter], (async) => { + it("should call error with errors", inject([AsyncTestCompleter], (async) => { let o = new Observable(sink => { sink.error('oh noes!'); }); diff --git a/modules/angular2/test/core/forward_ref_integration_spec.ts b/modules/angular2/test/core/forward_ref_integration_spec.ts index 41b121493b..a3900e5bde 100644 --- a/modules/angular2/test/core/forward_ref_integration_spec.ts +++ b/modules/angular2/test/core/forward_ref_integration_spec.ts @@ -1,11 +1,32 @@ -import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; -import {bind, provide, forwardRef, resolveForwardRef, Component, Directive, Inject, Query, QueryList} from 'angular2/core'; +import { + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; +import { + bind, + provide, + forwardRef, + resolveForwardRef, + Component, + Directive, + Inject, + Query, + QueryList +} from 'angular2/core'; import {NgFor} from 'angular2/common'; import {Type} from 'angular2/src/facade/lang'; import {asNativeElements} from 'angular2/core'; export function main() { - describe('forwardRef integration', function() { + describe("forwardRef integration", function() { it('should instantiate components which are declared using forwardRef', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.createAsync(App).then((tc) => { @@ -35,9 +56,8 @@ class Door { locks: QueryList<Lock>; frame: Frame; - constructor( - @Query(forwardRef(() => Lock)) locks: QueryList<Lock>, - @Inject(forwardRef(() => Frame)) frame: Frame) { + constructor(@Query(forwardRef(() => Lock)) locks: QueryList<Lock>, + @Inject(forwardRef(() => Frame)) frame: Frame) { this.frame = frame; this.locks = locks; } diff --git a/modules/angular2/test/core/linker/compiler_spec.ts b/modules/angular2/test/core/linker/compiler_spec.ts index 8535e03d31..0ba3e5a34c 100644 --- a/modules/angular2/test/core/linker/compiler_spec.ts +++ b/modules/angular2/test/core/linker/compiler_spec.ts @@ -1,9 +1,22 @@ -import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal'; +import { + ddescribe, + describe, + xdescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach, + AsyncTestCompleter, + inject, + beforeEachProviders +} from 'angular2/testing_internal'; import {provide} from 'angular2/core'; import {Compiler} from 'angular2/src/core/linker/compiler'; import {reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection'; -import {Compiler_} from 'angular2/src/core/linker/compiler'; +import {Compiler_} from "angular2/src/core/linker/compiler"; import {HostViewFactory} from 'angular2/src/core/linker/view'; import {HostViewFactoryRef_} from 'angular2/src/core/linker/view_ref'; @@ -20,11 +33,12 @@ export function main() { it('should read the template from an annotation', inject([AsyncTestCompleter, Compiler], (async, compiler: Compiler) => { - compiler.compileInHost(SomeComponent).then((hostViewFactoryRef: HostViewFactoryRef_) => { - expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); - async.done(); - return null; - }); + compiler.compileInHost(SomeComponent) + .then((hostViewFactoryRef: HostViewFactoryRef_) => { + expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); + async.done(); + return null; + }); })); it('should clear the cache', inject([Compiler], (compiler) => { diff --git a/modules/angular2/test/core/linker/directive_lifecycle_spec.ts b/modules/angular2/test/core/linker/directive_lifecycle_spec.ts index 3ce130f8db..4fdc6f7b48 100644 --- a/modules/angular2/test/core/linker/directive_lifecycle_spec.ts +++ b/modules/angular2/test/core/linker/directive_lifecycle_spec.ts @@ -1,4 +1,17 @@ -import {AsyncTestCompleter, beforeEach, xdescribe, ddescribe, describe, el, expect, iit, inject, it, SpyObject, proxy} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + xdescribe, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + SpyObject, + proxy +} from 'angular2/testing_internal'; import {hasLifecycleHook} from 'angular2/src/core/linker/directive_lifecycle_reflector'; import {LifecycleHooks} from 'angular2/src/core/linker/interfaces'; @@ -7,93 +20,93 @@ export function main() { describe('Create DirectiveMetadata', () => { describe('lifecycle', () => { - describe('ngOnChanges', () => { - it('should be true when the directive has the ngOnChanges method', () => { + describe("ngOnChanges", () => { + it("should be true when the directive has the ngOnChanges method", () => { expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveWithOnChangesMethod)) .toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveNoHooks)).toBe(false); }); }); - describe('ngOnDestroy', () => { - it('should be true when the directive has the ngOnDestroy method', () => { + describe("ngOnDestroy", () => { + it("should be true when the directive has the ngOnDestroy method", () => { expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveWithOnDestroyMethod)) .toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveNoHooks)).toBe(false); }); }); - describe('ngOnInit', () => { - it('should be true when the directive has the ngOnInit method', () => { + describe("ngOnInit", () => { + it("should be true when the directive has the ngOnInit method", () => { expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveWithOnInitMethod)).toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveNoHooks)).toBe(false); }); }); - describe('ngDoCheck', () => { - it('should be true when the directive has the ngDoCheck method', () => { + describe("ngDoCheck", () => { + it("should be true when the directive has the ngDoCheck method", () => { expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveWithOnCheckMethod)).toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveNoHooks)).toBe(false); }); }); - describe('ngAfterContentInit', () => { - it('should be true when the directive has the ngAfterContentInit method', () => { - expect(hasLifecycleHook( - LifecycleHooks.AfterContentInit, DirectiveWithAfterContentInitMethod)) + describe("ngAfterContentInit", () => { + it("should be true when the directive has the ngAfterContentInit method", () => { + expect(hasLifecycleHook(LifecycleHooks.AfterContentInit, + DirectiveWithAfterContentInitMethod)) .toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.AfterContentInit, DirectiveNoHooks)).toBe(false); }); }); - describe('ngAfterContentChecked', () => { - it('should be true when the directive has the ngAfterContentChecked method', () => { - expect(hasLifecycleHook( - LifecycleHooks.AfterContentChecked, DirectiveWithAfterContentCheckedMethod)) + describe("ngAfterContentChecked", () => { + it("should be true when the directive has the ngAfterContentChecked method", () => { + expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked, + DirectiveWithAfterContentCheckedMethod)) .toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked, DirectiveNoHooks)) .toBe(false); }); }); - describe('ngAfterViewInit', () => { - it('should be true when the directive has the ngAfterViewInit method', () => { + describe("ngAfterViewInit", () => { + it("should be true when the directive has the ngAfterViewInit method", () => { expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, DirectiveWithAfterViewInitMethod)) .toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, DirectiveNoHooks)).toBe(false); }); }); - describe('ngAfterViewChecked', () => { - it('should be true when the directive has the ngAfterViewChecked method', () => { - expect(hasLifecycleHook( - LifecycleHooks.AfterViewChecked, DirectiveWithAfterViewCheckedMethod)) + describe("ngAfterViewChecked", () => { + it("should be true when the directive has the ngAfterViewChecked method", () => { + expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked, + DirectiveWithAfterViewCheckedMethod)) .toBe(true); }); - it('should be false otherwise', () => { + it("should be false otherwise", () => { expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked, DirectiveNoHooks)).toBe(false); }); }); diff --git a/modules/angular2/test/core/linker/directive_resolver_spec.ts b/modules/angular2/test/core/linker/directive_resolver_spec.ts index 777cd8348d..84a8c80cf1 100644 --- a/modules/angular2/test/core/linker/directive_resolver_spec.ts +++ b/modules/angular2/test/core/linker/directive_resolver_spec.ts @@ -1,6 +1,21 @@ import {ddescribe, describe, it, iit, expect, beforeEach} from 'angular2/testing_internal'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; -import {DirectiveMetadata, Directive, Input, Output, HostBinding, HostListener, ContentChildren, ContentChildrenMetadata, ViewChildren, ViewChildrenMetadata, ContentChild, ContentChildMetadata, ViewChild, ViewChildMetadata} from 'angular2/src/core/metadata'; +import { + DirectiveMetadata, + Directive, + Input, + Output, + HostBinding, + HostListener, + ContentChildren, + ContentChildrenMetadata, + ViewChildren, + ViewChildrenMetadata, + ContentChild, + ContentChildMetadata, + ViewChild, + ViewChildMetadata +} from 'angular2/src/core/metadata'; @Directive({selector: 'someDirective'}) class SomeDirective { @@ -13,14 +28,14 @@ class SomeChildDirective extends SomeDirective { @Directive({selector: 'someDirective', inputs: ['c']}) class SomeDirectiveWithInputs { @Input() a; - @Input('renamed') b; + @Input("renamed") b; c; } @Directive({selector: 'someDirective', outputs: ['c']}) class SomeDirectiveWithOutputs { @Output() a; - @Output('renamed') b; + @Output("renamed") b; c; } @@ -40,59 +55,64 @@ class SomeDirectiveWithEvents { @Directive({selector: 'someDirective'}) class SomeDirectiveWithSetterProps { - @Input('renamed') - set a(value) {} + @Input("renamed") + set a(value) { + } } @Directive({selector: 'someDirective'}) class SomeDirectiveWithGetterOutputs { - @Output('renamed') - get a() { return null; } + @Output("renamed") + get a() { + return null; + } } @Directive({selector: 'someDirective', host: {'[c]': 'c'}}) class SomeDirectiveWithHostBindings { @HostBinding() a; - @HostBinding('renamed') b; + @HostBinding("renamed") b; c; } @Directive({selector: 'someDirective', host: {'(c)': 'onC()'}}) class SomeDirectiveWithHostListeners { @HostListener('a') - onA() {} + onA() { + } @HostListener('b', ['$event.value']) - onB(value) {} + onB(value) { + } } -@Directive({selector: 'someDirective', queries: {'cs': new ContentChildren('c')}}) +@Directive({selector: 'someDirective', queries: {"cs": new ContentChildren("c")}}) class SomeDirectiveWithContentChildren { - @ContentChildren('a') as: any; + @ContentChildren("a") as: any; c; } -@Directive({selector: 'someDirective', queries: {'cs': new ViewChildren('c')}}) +@Directive({selector: 'someDirective', queries: {"cs": new ViewChildren("c")}}) class SomeDirectiveWithViewChildren { - @ViewChildren('a') as: any; + @ViewChildren("a") as: any; c; } -@Directive({selector: 'someDirective', queries: {'c': new ContentChild('c')}}) +@Directive({selector: 'someDirective', queries: {"c": new ContentChild("c")}}) class SomeDirectiveWithContentChild { - @ContentChild('a') a: any; + @ContentChild("a") a: any; c; } -@Directive({selector: 'someDirective', queries: {'c': new ViewChild('c')}}) +@Directive({selector: 'someDirective', queries: {"c": new ViewChild("c")}}) class SomeDirectiveWithViewChild { - @ViewChild('a') a: any; + @ViewChild("a") a: any; c; } class SomeDirectiveWithoutMetadata {} export function main() { - describe('DirectiveResolver', () => { + describe("DirectiveResolver", () => { var resolver: DirectiveResolver; beforeEach(() => { resolver = new DirectiveResolver(); }); @@ -105,9 +125,8 @@ export function main() { }); it('should throw if not matching metadata is found', () => { - expect(() => { - resolver.resolve(SomeDirectiveWithoutMetadata); - }).toThrowError('No Directive annotation found on SomeDirectiveWithoutMetadata'); + expect(() => { resolver.resolve(SomeDirectiveWithoutMetadata); }) + .toThrowError('No Directive annotation found on SomeDirectiveWithoutMetadata'); }); it('should not read parent class Directive metadata', function() { @@ -165,25 +184,25 @@ export function main() { it('should append ContentChildren', () => { var directiveMetadata = resolver.resolve(SomeDirectiveWithContentChildren); expect(directiveMetadata.queries) - .toEqual({'cs': new ContentChildren('c'), 'as': new ContentChildren('a')}); + .toEqual({"cs": new ContentChildren("c"), "as": new ContentChildren("a")}); }); it('should append ViewChildren', () => { var directiveMetadata = resolver.resolve(SomeDirectiveWithViewChildren); expect(directiveMetadata.queries) - .toEqual({'cs': new ViewChildren('c'), 'as': new ViewChildren('a')}); + .toEqual({"cs": new ViewChildren("c"), "as": new ViewChildren("a")}); }); it('should append ContentChild', () => { var directiveMetadata = resolver.resolve(SomeDirectiveWithContentChild); expect(directiveMetadata.queries) - .toEqual({'c': new ContentChild('c'), 'a': new ContentChild('a')}); + .toEqual({"c": new ContentChild("c"), "a": new ContentChild("a")}); }); it('should append ViewChild', () => { var directiveMetadata = resolver.resolve(SomeDirectiveWithViewChild); expect(directiveMetadata.queries) - .toEqual({'c': new ViewChild('c'), 'a': new ViewChild('a')}); + .toEqual({"c": new ViewChild("c"), "a": new ViewChild("a")}); }); }); }); diff --git a/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts b/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts index 7474eb7fde..2c3fd47518 100644 --- a/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts +++ b/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts @@ -1,4 +1,20 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder, ComponentFixture} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + TestComponentBuilder, + ComponentFixture +} from 'angular2/testing_internal'; import {OnDestroy} from 'angular2/core'; import {Injector} from 'angular2/core'; @@ -8,48 +24,50 @@ import {DynamicComponentLoader} from 'angular2/src/core/linker/dynamic_component import {ElementRef, ElementRef_} from 'angular2/src/core/linker/element_ref'; import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {ComponentFixture_} from 'angular2/src/testing/test_component_builder'; +import {ComponentFixture_} from "angular2/src/testing/test_component_builder"; import {BaseException} from 'angular2/src/facade/exceptions'; import {PromiseWrapper} from 'angular2/src/facade/promise'; import {stringify} from 'angular2/src/facade/lang'; export function main() { describe('DynamicComponentLoader', function() { - describe('loading into a location', () => { + describe("loading into a location", () => { it('should work', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata( - {template: '<location #loc></location>', directives: [Location]})) - .createAsync(MyComp) - .then((tc) => { - loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc').then(ref => { - expect(tc.debugElement.nativeElement) - .toHaveText('Location;DynamicallyLoaded;'); - async.done(); - }); - }); - })); + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView( + MyComp, + new ViewMetadata( + {template: '<location #loc></location>', directives: [Location]})) + .createAsync(MyComp) + .then((tc) => { + loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc') + .then(ref => { + expect(tc.debugElement.nativeElement) + .toHaveText("Location;DynamicallyLoaded;"); + async.done(); + }); + }); + })); it('should return a disposable component ref', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata( - {template: '<location #loc></location>', directives: [Location]})) - .createAsync(MyComp) - .then((tc) => { + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView( + MyComp, + new ViewMetadata( + {template: '<location #loc></location>', directives: [Location]})) + .createAsync(MyComp) + .then((tc) => { - loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc').then(ref => { - ref.dispose(); - expect(tc.debugElement.nativeElement).toHaveText('Location;'); - async.done(); - }); - }); - })); + loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc') + .then(ref => { + ref.dispose(); + expect(tc.debugElement.nativeElement).toHaveText("Location;"); + async.done(); + }); + }); + })); it('should allow to dispose even if the location has been removed', inject( @@ -75,14 +93,14 @@ export function main() { loader.loadIntoLocation(DynamicallyLoaded, childElementRef, 'loc') .then(ref => { expect(tc.debugElement.nativeElement) - .toHaveText('Location;DynamicallyLoaded;'); + .toHaveText("Location;DynamicallyLoaded;"); tc.debugElement.componentInstance.ctxBoolProp = false; tc.detectChanges(); - expect(tc.debugElement.nativeElement).toHaveText(''); + expect(tc.debugElement.nativeElement).toHaveText(""); ref.dispose(); - expect(tc.debugElement.nativeElement).toHaveText(''); + expect(tc.debugElement.nativeElement).toHaveText(""); async.done(); }); }); @@ -99,89 +117,85 @@ export function main() { .then((tc) => { loader.loadIntoLocation(DynamicallyLoadedWithHostProps, tc.elementRef, 'loc') .then(ref => { - ref.instance.id = 'new value'; + ref.instance.id = "new value"; tc.detectChanges(); var newlyInsertedElement = DOM.childNodes(tc.debugElement.nativeElement)[1]; - expect((<HTMLElement>newlyInsertedElement).id).toEqual('new value'); + expect((<HTMLElement>newlyInsertedElement).id).toEqual("new value"); async.done(); }); }); })); it('should leave the view tree in a consistent state if hydration fails', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div><location #loc></location></div>', - directives: [Location] - })) - .createAsync(MyComp) - .then((tc: ComponentFixture) => { - tc.debugElement + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><location #loc></location></div>', + directives: [Location] + })) + .createAsync(MyComp) + .then((tc: ComponentFixture) => { + tc.debugElement - PromiseWrapper.catchError( - loader.loadIntoLocation(DynamicallyLoadedThrows, tc.elementRef, 'loc'), - error => { - expect(error.message).toContain('ThrownInConstructor'); - expect(() => tc.detectChanges()).not.toThrow(); - async.done(); - return null; - }); - }); - })); + PromiseWrapper.catchError( + loader.loadIntoLocation(DynamicallyLoadedThrows, tc.elementRef, + 'loc'), + error => { + expect(error.message).toContain("ThrownInConstructor"); + expect(() => tc.detectChanges()).not.toThrow(); + async.done(); + return null; + }); + }); + })); it('should throw if the variable does not exist', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata( - {template: '<location #loc></location>', directives: [Location]})) - .createAsync(MyComp) - .then((tc) => { - expect( - () => loader.loadIntoLocation( - DynamicallyLoadedWithHostProps, tc.elementRef, 'someUnknownVariable')) - .toThrowError('Could not find variable someUnknownVariable'); - async.done(); - }); - })); + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView( + MyComp, + new ViewMetadata( + {template: '<location #loc></location>', directives: [Location]})) + .createAsync(MyComp) + .then((tc) => { + expect(() => loader.loadIntoLocation(DynamicallyLoadedWithHostProps, + tc.elementRef, 'someUnknownVariable')) + .toThrowError('Could not find variable someUnknownVariable'); + async.done(); + }); + })); it('should allow to pass projectable nodes', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div #loc></div>', directives: []})) - .createAsync(MyComp) - .then((tc) => { - loader - .loadIntoLocation( - DynamicallyLoadedWithNgContent, tc.elementRef, 'loc', null, - [[DOM.createTextNode('hello')]]) - .then(ref => { - tc.detectChanges(); - expect(tc.nativeElement).toHaveText('dynamic(hello)'); - async.done(); - }); - }); - })); + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div #loc></div>', directives: []})) + .createAsync(MyComp) + .then((tc) => { + loader.loadIntoLocation(DynamicallyLoadedWithNgContent, tc.elementRef, + 'loc', null, [[DOM.createTextNode('hello')]]) + .then(ref => { + tc.detectChanges(); + expect(tc.nativeElement).toHaveText('dynamic(hello)'); + async.done(); + }); + }); + })); it('should throw if not enough projectable nodes are passed in', inject( [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div #loc></div>', directives: []})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div #loc></div>', directives: []})) .createAsync(MyComp) .then((tc) => { PromiseWrapper.catchError( - loader.loadIntoLocation( - DynamicallyLoadedWithNgContent, tc.elementRef, 'loc', null, []), + loader.loadIntoLocation(DynamicallyLoadedWithNgContent, tc.elementRef, + 'loc', null, []), (e) => { expect(e.message).toContain( `The component ${stringify(DynamicallyLoadedWithNgContent)} has 1 <ng-content> elements, but only 0 slots were provided`); @@ -193,157 +207,152 @@ export function main() { }); - describe('loading next to a location', () => { + describe("loading next to a location", () => { it('should work', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div><location #loc></location></div>', - directives: [Location] - })) - .createAsync(MyComp) - .then((tc) => { - loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef).then(ref => { - expect(tc.debugElement.nativeElement).toHaveText('Location;'); - expect(DOM.nextSibling(tc.debugElement.nativeElement)) - .toHaveText('DynamicallyLoaded;'); + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><location #loc></location></div>', + directives: [Location] + })) + .createAsync(MyComp) + .then((tc) => { + loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef) + .then(ref => { + expect(tc.debugElement.nativeElement).toHaveText("Location;"); + expect(DOM.nextSibling(tc.debugElement.nativeElement)) + .toHaveText('DynamicallyLoaded;'); - async.done(); - }); - }); - })); + async.done(); + }); + }); + })); it('should return a disposable component ref', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div><location #loc></location></div>', - directives: [Location] - })) - . + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><location #loc></location></div>', + directives: [Location] + })) + . - createAsync(MyComp) - .then((tc) => { - loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef).then(ref => { - loader.loadNextToLocation(DynamicallyLoaded2, tc.elementRef).then(ref2 => { - var firstSibling = DOM.nextSibling(tc.debugElement.nativeElement); - var secondSibling = DOM.nextSibling(firstSibling); - expect(tc.debugElement.nativeElement).toHaveText('Location;'); - expect(firstSibling).toHaveText('DynamicallyLoaded;'); - expect(secondSibling).toHaveText('DynamicallyLoaded2;'); + createAsync(MyComp) + .then((tc) => { + loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef) + .then(ref => { + loader.loadNextToLocation(DynamicallyLoaded2, tc.elementRef) + .then(ref2 => { + var firstSibling = + DOM.nextSibling(tc.debugElement.nativeElement); + var secondSibling = DOM.nextSibling(firstSibling); + expect(tc.debugElement.nativeElement).toHaveText("Location;"); + expect(firstSibling).toHaveText("DynamicallyLoaded;"); + expect(secondSibling).toHaveText("DynamicallyLoaded2;"); - ref2.dispose(); + ref2.dispose(); - firstSibling = DOM.nextSibling(tc.debugElement.nativeElement); - secondSibling = DOM.nextSibling(firstSibling); - expect(secondSibling).toBeNull(); + firstSibling = DOM.nextSibling(tc.debugElement.nativeElement); + secondSibling = DOM.nextSibling(firstSibling); + expect(secondSibling).toBeNull(); - async.done(); - }); - }); - }); - })); + async.done(); + }); + }); + }); + })); it('should update host properties', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div><location #loc></location></div>', - directives: [Location] - })) + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><location #loc></location></div>', + directives: [Location] + })) - .createAsync(MyComp) - .then((tc) => { + .createAsync(MyComp) + .then((tc) => { - loader.loadNextToLocation(DynamicallyLoadedWithHostProps, tc.elementRef) - .then(ref => { - ref.instance.id = 'new value'; + loader.loadNextToLocation(DynamicallyLoadedWithHostProps, tc.elementRef) + .then(ref => { + ref.instance.id = "new value"; - tc.detectChanges(); + tc.detectChanges(); - var newlyInsertedElement = - DOM.nextSibling(tc.debugElement.nativeElement); - expect((<HTMLElement>newlyInsertedElement).id).toEqual('new value'); + var newlyInsertedElement = + DOM.nextSibling(tc.debugElement.nativeElement); + expect((<HTMLElement>newlyInsertedElement).id).toEqual("new value"); - async.done(); - }); - }); - })); + async.done(); + }); + }); + })); it('should allow to pass projectable nodes', - inject( - [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]})) - .createAsync(MyComp) - .then((tc) => { - loader - .loadNextToLocation( - DynamicallyLoadedWithNgContent, tc.elementRef, null, - [[DOM.createTextNode('hello')]]) - .then(ref => { - tc.detectChanges(); - var newlyInsertedElement = - DOM.nextSibling(tc.debugElement.nativeElement); - expect(newlyInsertedElement).toHaveText('dynamic(hello)'); - async.done(); - }); - }); - })); + inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]})) + .createAsync(MyComp) + .then((tc) => { + loader.loadNextToLocation(DynamicallyLoadedWithNgContent, tc.elementRef, + null, [[DOM.createTextNode('hello')]]) + .then(ref => { + tc.detectChanges(); + var newlyInsertedElement = + DOM.nextSibling(tc.debugElement.nativeElement); + expect(newlyInsertedElement).toHaveText('dynamic(hello)'); + async.done(); + }); + }); + })); }); describe('loadAsRoot', () => { it('should allow to create, update and destroy components', - inject( - [AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], - (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc, - injector: Injector) => { - var rootEl = createRootElement(doc, 'child-cmp'); - DOM.appendChild(doc.body, rootEl); - loader.loadAsRoot(ChildComp, null, injector).then((componentRef) => { - var el = new ComponentFixture_(componentRef); + inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], + (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc, + injector: Injector) => { + var rootEl = createRootElement(doc, 'child-cmp'); + DOM.appendChild(doc.body, rootEl); + loader.loadAsRoot(ChildComp, null, injector) + .then((componentRef) => { + var el = new ComponentFixture_(componentRef); - expect(rootEl.parentNode).toBe(doc.body); + expect(rootEl.parentNode).toBe(doc.body); - el.detectChanges(); + el.detectChanges(); - expect(rootEl).toHaveText('hello'); + expect(rootEl).toHaveText('hello'); - componentRef.instance.ctxProp = 'new'; + componentRef.instance.ctxProp = 'new'; - el.detectChanges(); + el.detectChanges(); - expect(rootEl).toHaveText('new'); + expect(rootEl).toHaveText('new'); - componentRef.dispose(); + componentRef.dispose(); - expect(rootEl.parentNode).toBeFalsy(); + expect(rootEl.parentNode).toBeFalsy(); - async.done(); - }); - })); + async.done(); + }); + })); it('should allow to pass projectable nodes', - inject( - [AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], - (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc, - injector: Injector) => { - var rootEl = createRootElement(doc, 'dummy'); - DOM.appendChild(doc.body, rootEl); - loader - .loadAsRoot( - DynamicallyLoadedWithNgContent, null, injector, null, - [[DOM.createTextNode('hello')]]) - .then((_) => { - expect(rootEl).toHaveText('dynamic(hello)'); + inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], + (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc, + injector: Injector) => { + var rootEl = createRootElement(doc, 'dummy'); + DOM.appendChild(doc.body, rootEl); + loader.loadAsRoot(DynamicallyLoadedWithNgContent, null, injector, null, + [[DOM.createTextNode('hello')]]) + .then((_) => { + expect(rootEl).toHaveText('dynamic(hello)'); - async.done(); - }); - })); + async.done(); + }); + })); }); @@ -372,7 +381,7 @@ class DynamicallyCreatedComponentService {} @Component({ selector: 'hello-cmp', viewProviders: [DynamicallyCreatedComponentService], - template: '{{greeting}}' + template: "{{greeting}}" }) class DynamicallyCreatedCmp implements OnDestroy { greeting: string; @@ -380,41 +389,41 @@ class DynamicallyCreatedCmp implements OnDestroy { destroyed: boolean = false; constructor(a: DynamicallyCreatedComponentService) { - this.greeting = 'hello'; + this.greeting = "hello"; this.dynamicallyCreatedComponentService = a; } ngOnDestroy() { this.destroyed = true; } } -@Component({selector: 'dummy', template: 'DynamicallyLoaded;'}) +@Component({selector: 'dummy', template: "DynamicallyLoaded;"}) class DynamicallyLoaded { } -@Component({selector: 'dummy', template: 'DynamicallyLoaded;'}) +@Component({selector: 'dummy', template: "DynamicallyLoaded;"}) class DynamicallyLoadedThrows { - constructor() { throw new BaseException('ThrownInConstructor'); } + constructor() { throw new BaseException("ThrownInConstructor"); } } -@Component({selector: 'dummy', template: 'DynamicallyLoaded2;'}) +@Component({selector: 'dummy', template: "DynamicallyLoaded2;"}) class DynamicallyLoaded2 { } -@Component({selector: 'dummy', host: {'[id]': 'id'}, template: 'DynamicallyLoadedWithHostProps;'}) +@Component({selector: 'dummy', host: {'[id]': 'id'}, template: "DynamicallyLoadedWithHostProps;"}) class DynamicallyLoadedWithHostProps { id: string; - constructor() { this.id = 'default'; } + constructor() { this.id = "default"; } } -@Component({selector: 'dummy', template: 'dynamic(<ng-content></ng-content>)'}) +@Component({selector: 'dummy', template: "dynamic(<ng-content></ng-content>)"}) class DynamicallyLoadedWithNgContent { id: string; - constructor() { this.id = 'default'; } + constructor() { this.id = "default"; } } -@Component({selector: 'location', template: 'Location;'}) +@Component({selector: 'location', template: "Location;"}) class Location { elementRef: ElementRef; diff --git a/modules/angular2/test/core/linker/element_spec.ts b/modules/angular2/test/core/linker/element_spec.ts index e6c02a6830..7265b3c148 100644 --- a/modules/angular2/test/core/linker/element_spec.ts +++ b/modules/angular2/test/core/linker/element_spec.ts @@ -48,8 +48,8 @@ import {ElementRef} from 'angular2/src/core/linker/element_ref'; import {DynamicChangeDetector, ChangeDetectorRef, Parser, Lexer} from 'angular2/src/core/change_detection/change_detection'; import {ChangeDetectorRef_} from 'angular2/src/core/change_detection/change_detector_ref'; import {QueryList} from 'angular2/src/core/linker/query_list'; -import {AppView, AppProtoView} from 'angular2/src/core/linker/view'; -import {ViewType} from 'angular2/src/core/linker/view_type'; +import {AppView, AppProtoView} from "angular2/src/core/linker/view"; +import {ViewType} from "angular2/src/core/linker/view_type"; @Directive({selector: ''}) class SimpleDirective {} @@ -101,18 +101,18 @@ class NeedsDirectiveFromHostShadowDom { @Directive({selector: ''}) class NeedsService { service: any; - constructor(@Inject('service') service) { this.service = service; } + constructor(@Inject("service") service) { this.service = service; } } @Directive({selector: ''}) class NeedsServiceFromHost { service: any; - constructor(@Host() @Inject('service') service) { this.service = service; } + constructor(@Host() @Inject("service") service) { this.service = service; } } class HasEventEmitter { emitter; - constructor() { this.emitter = 'emitter'; } + constructor() { this.emitter = "emitter"; } } @Directive({selector: ''}) @@ -149,7 +149,7 @@ class NeedsViewQuery { @Directive({selector: ''}) class NeedsQueryByVarBindings { query: QueryList<any>; - constructor(@Query('one,two') query: QueryList<any>) { this.query = query; } + constructor(@Query("one,two") query: QueryList<any>) { this.query = query; } } @Directive({selector: ''}) @@ -334,11 +334,11 @@ export function main() { })); } - describe('ProtoAppElement', () => { + describe("ProtoAppElement", () => { init(); describe('inline strategy', () => { - it('should allow for direct access using getProviderAtIndex', () => { + it("should allow for direct access using getProviderAtIndex", () => { var proto = protoAppElement(0, [SimpleDirective]); expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider); @@ -348,7 +348,7 @@ export function main() { }); describe('dynamic strategy', () => { - it('should allow for direct access using getProviderAtIndex', () => { + it("should allow for direct access using getProviderAtIndex", () => { var proto = protoAppElement(0, dynamicStrategyDirectives); expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider); @@ -359,8 +359,8 @@ export function main() { }); }); - describe('.create', () => { - it('should collect providers from all directives', () => { + describe(".create", () => { + it("should collect providers from all directives", () => { mockDirectiveMeta.set(SimpleDirective, new DirectiveMetadata({providers: [provide('injectable1', {useValue: 'injectable1'})]})); mockDirectiveMeta.set(SomeOtherDirective, new DirectiveMetadata({ providers: [provide('injectable2', {useValue: 'injectable2'})] @@ -372,21 +372,21 @@ export function main() { expect(pel.getProviderAtIndex(0).key.token).toBe(SimpleDirective); expect(pel.getProviderAtIndex(1).key.token).toBe(SomeOtherDirective); - expect(pel.getProviderAtIndex(2).key.token).toEqual('injectable1'); - expect(pel.getProviderAtIndex(3).key.token).toEqual('injectable2'); + expect(pel.getProviderAtIndex(2).key.token).toEqual("injectable1"); + expect(pel.getProviderAtIndex(3).key.token).toEqual("injectable2"); }); - it('should collect view providers from the component', () => { + it("should collect view providers from the component", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ viewProviders: [provide('injectable1', {useValue: 'injectable1'})] })); var pel = protoAppElement(0, [SimpleDirective]); expect(pel.getProviderAtIndex(0).key.token).toBe(SimpleDirective); - expect(pel.getProviderAtIndex(1).key.token).toEqual('injectable1'); + expect(pel.getProviderAtIndex(1).key.token).toEqual("injectable1"); }); - it('should flatten nested arrays in viewProviders and providers', () => { + it("should flatten nested arrays in viewProviders and providers", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ viewProviders: [[[provide('view', {useValue: 'view'})]]], providers: [[[provide('host', {useValue: 'host'})]]] @@ -394,8 +394,8 @@ export function main() { var pel = protoAppElement(0, [SimpleDirective]); expect(pel.getProviderAtIndex(0).key.token).toBe(SimpleDirective); - expect(pel.getProviderAtIndex(1).key.token).toEqual('view'); - expect(pel.getProviderAtIndex(2).key.token).toEqual('host'); + expect(pel.getProviderAtIndex(1).key.token).toEqual("view"); + expect(pel.getProviderAtIndex(2).key.token).toEqual("host"); }); it('should support an arbitrary number of providers', () => { @@ -406,7 +406,7 @@ export function main() { }); }); - describe('AppElement', () => { + describe("AppElement", () => { init(); [{ strategy: 'inline', directives: [] }, { strategy: 'dynamic', @@ -415,14 +415,14 @@ export function main() { var extraDirectives = context['directives']; describe(`${context['strategy']} strategy`, () => { - describe('injection', () => { - it('should instantiate directives that have no dependencies', () => { + describe("injection", () => { + it("should instantiate directives that have no dependencies", () => { var directives = ListWrapper.concat([SimpleDirective], extraDirectives); var el = appElement(null, directives); expect(el.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective); }); - it('should instantiate directives that depend on an arbitrary number of directives', () => { + it("should instantiate directives that depend on an arbitrary number of directives", () => { var directives = ListWrapper.concat([SimpleDirective, NeedsDirective], extraDirectives); var el = appElement(null, directives); @@ -432,7 +432,7 @@ export function main() { expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); - it('should instantiate providers that have dependencies with set visibility', + it("should instantiate providers that have dependencies with set visibility", function() { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ providers: [provide('injectable1', {useValue: 'injectable1'})] @@ -452,7 +452,7 @@ export function main() { expect(childInj.get('injectable2')).toEqual('injectable1-injectable2'); }); - it('should instantiate providers that have dependencies', () => { + it("should instantiate providers that have dependencies", () => { var providers = [ provide('injectable1', {useValue: 'injectable1'}), provide('injectable2', {useFactory: @@ -466,7 +466,7 @@ export function main() { expect(el.get('injectable2')).toEqual('injectable1-injectable2'); }); - it('should instantiate viewProviders that have dependencies', () => { + it("should instantiate viewProviders that have dependencies", () => { var viewProviders = [ provide('injectable1', {useValue: 'injectable1'}), provide('injectable2', {useFactory: @@ -481,7 +481,7 @@ export function main() { expect(el.get('injectable2')).toEqual('injectable1-injectable2'); }); - it('should instantiate components that depend on viewProviders providers', () => { + it("should instantiate components that depend on viewProviders providers", () => { mockDirectiveMeta.set(NeedsService, new ComponentMetadata({ viewProviders: [provide('service', {useValue: 'service'})] })); @@ -490,7 +490,7 @@ export function main() { expect(el.get(NeedsService).service).toEqual('service'); }); - it('should instantiate providers lazily', () => { + it("should instantiate providers lazily", () => { var created = false; mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ providers: [provide('service', {useFactory: () => created = true})] @@ -506,7 +506,7 @@ export function main() { expect(created).toBe(true); }); - it('should instantiate view providers lazily', () => { + it("should instantiate view providers lazily", () => { var created = false; mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ viewProviders: [provide('service', {useFactory: () => created = true})] @@ -522,18 +522,18 @@ export function main() { expect(created).toBe(true); }); - it('should not instantiate other directives that depend on viewProviders providers', + it("should not instantiate other directives that depend on viewProviders providers", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ - viewProviders: [provide('service', {useValue: 'service'})] + viewProviders: [provide("service", {useValue: "service"})] })); expect(() => { appElement(null, ListWrapper.concat([SimpleDirective, NeedsService], extraDirectives)); }) .toThrowError(containsRegexp( `No provider for service! (${stringify(NeedsService) } -> service)`)); }); - it('should instantiate directives that depend on providers of other directives', () => { + it("should instantiate directives that depend on providers of other directives", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ providers: [provide('service', {useValue: 'hostService'})]}) ); @@ -544,7 +544,7 @@ export function main() { expect(shadowInj.get(NeedsService).service).toEqual('hostService'); }); - it('should instantiate directives that depend on view providers of a component', () => { + it("should instantiate directives that depend on view providers of a component", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ viewProviders: [provide('service', {useValue: 'hostService'})]}) ); @@ -555,7 +555,7 @@ export function main() { expect(shadowInj.get(NeedsService).service).toEqual('hostService'); }); - it('should instantiate directives in a root embedded view that depend on view providers of a component', () => { + it("should instantiate directives in a root embedded view that depend on view providers of a component", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({ viewProviders: [provide('service', {useValue: 'hostService'})]}) ); @@ -570,9 +570,9 @@ export function main() { expect(rootEmbeddedEl.get(NeedsService).service).toEqual('hostService'); }); - it('should instantiate directives that depend on imperatively created injector (bootstrap)', () => { + it("should instantiate directives that depend on imperatively created injector (bootstrap)", () => { var rootInjector = Injector.resolveAndCreate([ - provide('service', {useValue: 'appService'}) + provide("service", {useValue: 'appService'}) ]); var view = createView(ViewType.HOST, null, null, rootInjector); expect(appElement(null, [NeedsService], view).get(NeedsService).service).toEqual('appService'); @@ -580,9 +580,9 @@ export function main() { expect(() => appElement(null, [NeedsServiceFromHost], view)).toThrowError(); }); - it('should instantiate directives that depend on imperatively created providers (root injector)', () => { + it("should instantiate directives that depend on imperatively created providers (root injector)", () => { var imperativelyCreatedProviders = Injector.resolve([ - provide('service', {useValue: 'appService'}) + provide("service", {useValue: 'appService'}) ]); var containerAppElement = appElement(null, []); var view = createView(ViewType.HOST, containerAppElement, imperativelyCreatedProviders, null); @@ -590,8 +590,8 @@ export function main() { expect(appElement(null, [NeedsServiceFromHost], view).get(NeedsServiceFromHost).service).toEqual('appService'); }); - it('should not instantiate a directive in a view that has a host dependency on providers'+ - ' of the component', () => { + it("should not instantiate a directive in a view that has a host dependency on providers"+ + " of the component", () => { mockDirectiveMeta.set(SomeOtherDirective, new DirectiveMetadata({ providers: [provide('service', {useValue: 'hostService'})]}) ); @@ -600,11 +600,11 @@ export function main() { ListWrapper.concat([SomeOtherDirective], extraDirectives), ListWrapper.concat([NeedsServiceFromHost], extraDirectives) ); - }).toThrowError(new RegExp('No provider for service!')); + }).toThrowError(new RegExp("No provider for service!")); }); - it('should not instantiate a directive in a view that has a host dependency on providers'+ - ' of a decorator directive', () => { + it("should not instantiate a directive in a view that has a host dependency on providers"+ + " of a decorator directive", () => { mockDirectiveMeta.set(SomeOtherDirective, new DirectiveMetadata({ providers: [provide('service', {useValue: 'hostService'})]})); expect(() => { @@ -612,10 +612,10 @@ export function main() { ListWrapper.concat([SimpleDirective, SomeOtherDirective], extraDirectives), ListWrapper.concat([NeedsServiceFromHost], extraDirectives) ); - }).toThrowError(new RegExp('No provider for service!')); + }).toThrowError(new RegExp("No provider for service!")); }); - it('should get directives', () => { + it("should get directives", () => { var child = hostShadowElement( ListWrapper.concat([SomeOtherDirective, SimpleDirective], extraDirectives), [NeedsDirectiveFromHostShadowDom]); @@ -626,7 +626,7 @@ export function main() { expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); - it('should get directives from the host', () => { + it("should get directives from the host", () => { var child = parentChildElements(ListWrapper.concat([SimpleDirective], extraDirectives), [NeeedsDirectiveFromHost]); @@ -636,19 +636,19 @@ export function main() { expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); - it('should throw when a dependency cannot be resolved', () => { + it("should throw when a dependency cannot be resolved", () => { expect(() => appElement(null, ListWrapper.concat([NeeedsDirectiveFromHost], extraDirectives))) .toThrowError(containsRegexp( `No provider for ${stringify(SimpleDirective) }! (${stringify(NeeedsDirectiveFromHost) } -> ${stringify(SimpleDirective) })`)); }); - it('should inject null when an optional dependency cannot be resolved', () => { + it("should inject null when an optional dependency cannot be resolved", () => { var el = appElement(null, ListWrapper.concat([OptionallyNeedsDirective], extraDirectives)); var d = el.get(OptionallyNeedsDirective); expect(d.dependency).toEqual(null); }); - it('should allow for direct access using getDirectiveAtIndex', () => { + it("should allow for direct access using getDirectiveAtIndex", () => { var providers = ListWrapper.concat([SimpleDirective], extraDirectives); @@ -662,7 +662,7 @@ export function main() { .toThrowError(`Index ${firsIndexOut} is out-of-bounds.`); }); - it('should instantiate directives that depend on the containing component', () => { + it("should instantiate directives that depend on the containing component", () => { mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata()); var shadow = hostShadowElement(ListWrapper.concat([SimpleDirective], extraDirectives), [NeeedsDirectiveFromHost]); @@ -672,7 +672,7 @@ export function main() { expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); - it('should not instantiate directives that depend on other directives in the containing component\'s ElementInjector', + it("should not instantiate directives that depend on other directives in the containing component's ElementInjector", () => { mockDirectiveMeta.set(SomeOtherDirective, new ComponentMetadata()); expect(() => @@ -708,13 +708,13 @@ export function main() { }); }); - describe('refs', () => { - it('should inject ElementRef', () => { + describe("refs", () => { + it("should inject ElementRef", () => { var el = appElement(null, ListWrapper.concat([NeedsElementRef], extraDirectives)); expect(el.get(NeedsElementRef).elementRef).toBe(el.ref); }); - it('should inject ChangeDetectorRef of the component\'s view into the component via a proxy', () => { + it("should inject ChangeDetectorRef of the component's view into the component via a proxy", () => { mockDirectiveMeta.set(ComponentNeedsChangeDetectorRef, new ComponentMetadata()); var host = appElement(null, ListWrapper.concat([ComponentNeedsChangeDetectorRef], extraDirectives)); var view = createView(ViewType.COMPONENT, host); @@ -723,7 +723,7 @@ export function main() { expect((<any>view.changeDetector).spy('markPathToRootAsCheckOnce')).toHaveBeenCalled(); }); - it('should inject ChangeDetectorRef of the containing component into directives', () => { + it("should inject ChangeDetectorRef of the containing component into directives", () => { mockDirectiveMeta.set(DirectiveNeedsChangeDetectorRef, new DirectiveMetadata()); var view = createView(ViewType.HOST); var el = appElement(null, ListWrapper.concat([DirectiveNeedsChangeDetectorRef], extraDirectives), view); @@ -735,12 +735,12 @@ export function main() { expect(el.get(NeedsViewContainer).viewContainer).toBeAnInstanceOf(ViewContainerRef_); }); - it('should inject TemplateRef', () => { + it("should inject TemplateRef", () => { var el = appElement(null, ListWrapper.concat([NeedsTemplateRef], extraDirectives), null, dummyViewFactory); expect(el.get(NeedsTemplateRef).templateRef.elementRef).toBe(el.ref); }); - it('should throw if there is no TemplateRef', () => { + it("should throw if there is no TemplateRef", () => { expect(() => appElement(null, ListWrapper.concat([NeedsTemplateRef], extraDirectives))) .toThrowError( `No provider for TemplateRef! (${stringify(NeedsTemplateRef) } -> TemplateRef)`); @@ -795,7 +795,7 @@ export function main() { var dirs:Type[] = [NeedsQueryByVarBindings]; var dirVariableBindings:{[key:string]:number} = { - 'one': null // element + "one": null // element }; var el = appElement(null, dirs.concat(extraDirectives), null, null, null, dirVariableBindings); @@ -810,8 +810,8 @@ export function main() { var dirs:Type[] = [NeedsQueryByVarBindings, NeedsDirective, SimpleDirective]; var dirVariableBindings:{[key:string]:number} = { - 'one': 2, // 2 is the index of SimpleDirective - 'two': 1 // 1 is the index of NeedsDirective + "one": 2, // 2 is the index of SimpleDirective + "two": 1 // 1 is the index of NeedsDirective }; var el = appElement(null, dirs.concat(extraDirectives), null, null, null, dirVariableBindings); diff --git a/modules/angular2/test/core/linker/integration_spec.ts b/modules/angular2/test/core/linker/integration_spec.ts index d2474c7da3..cb5603565c 100644 --- a/modules/angular2/test/core/linker/integration_spec.ts +++ b/modules/angular2/test/core/linker/integration_spec.ts @@ -1,20 +1,85 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, containsRegexp, stringifyElement, TestComponentBuilder, fakeAsync, tick, clearPendingTimers, ComponentFixture} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + containsRegexp, + stringifyElement, + TestComponentBuilder, + fakeAsync, + tick, + clearPendingTimers, + ComponentFixture +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {Type, isPresent, assertionsEnabled, isJsObject, global, stringify, isBlank, CONST, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + Type, + isPresent, + assertionsEnabled, + isJsObject, + global, + stringify, + isBlank, + CONST, + CONST_EXPR +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {PromiseWrapper, EventEmitter, ObservableWrapper, PromiseCompleter,} from 'angular2/src/facade/async'; +import { + PromiseWrapper, + EventEmitter, + ObservableWrapper, + PromiseCompleter, +} from 'angular2/src/facade/async'; -import {Injector, bind, provide, Injectable, Provider, forwardRef, OpaqueToken, Inject, Host, SkipSelf, SkipSelfMetadata, OnDestroy} from 'angular2/core'; +import { + Injector, + bind, + provide, + Injectable, + Provider, + forwardRef, + OpaqueToken, + Inject, + Host, + SkipSelf, + SkipSelfMetadata, + OnDestroy +} from 'angular2/core'; import {NgIf, NgFor} from 'angular2/common'; import {AsyncPipe} from 'angular2/common'; -import {PipeTransform, ChangeDetectorRef, ChangeDetectionStrategy, ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection'; +import { + PipeTransform, + ChangeDetectorRef, + ChangeDetectionStrategy, + ChangeDetectorGenConfig +} from 'angular2/src/core/change_detection/change_detection'; -import {Directive, Component, ViewMetadata, Attribute, Query, Pipe, Input, Output, HostBinding, HostListener} from 'angular2/src/core/metadata'; +import { + Directive, + Component, + ViewMetadata, + Attribute, + Query, + Pipe, + Input, + Output, + HostBinding, + HostListener +} from 'angular2/src/core/metadata'; import {QueryList} from 'angular2/src/core/linker/query_list'; @@ -35,16 +100,18 @@ export function main() { declareTests(); } else { describe('no jit', () => { - beforeEachProviders(() => [provide(ChangeDetectorGenConfig, { - useValue: new ChangeDetectorGenConfig(true, false, false) - })]); + beforeEachProviders(() => [ + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, false, false)}) + ]); declareTests(); }); describe('jit', () => { - beforeEachProviders(() => [provide(ChangeDetectorGenConfig, { - useValue: new ChangeDetectorGenConfig(true, false, true) - })]); + beforeEachProviders(() => [ + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, false, true)}) + ]); declareTests(); }); } @@ -98,8 +165,8 @@ function declareTests() { it('should consume binding to aria-* attributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div [attr.aria-label]="ctxProp"></div>'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div [attr.aria-label]="ctxProp"></div>'})) .createAsync(MyComp) .then((fixture) => { @@ -121,8 +188,8 @@ function declareTests() { it('should remove an attribute when attribute expression evaluates to null', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div [attr.foo]="ctxProp"></div>'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div [attr.foo]="ctxProp"></div>'})) .createAsync(MyComp) .then((fixture) => { @@ -143,8 +210,8 @@ function declareTests() { it('should remove style when when style expression evaluates to null', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div [style.height.px]="ctxProp"></div>'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div [style.height.px]="ctxProp"></div>'})) .createAsync(MyComp) .then((fixture) => { @@ -165,8 +232,8 @@ function declareTests() { it('should consume binding to property names where attr name and property name do not match', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div [tabindex]="ctxNumProp"></div>'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div [tabindex]="ctxNumProp"></div>'})) .createAsync(MyComp) .then((fixture) => { @@ -184,8 +251,8 @@ function declareTests() { it('should consume binding to camel-cased properties', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<input [readOnly]="ctxBoolProp">'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<input [readOnly]="ctxBoolProp">'})) .createAsync(MyComp) .then((fixture) => { @@ -203,8 +270,8 @@ function declareTests() { it('should consume binding to innerHtml', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<div innerHtml="{{ctxProp}}"></div>'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div innerHtml="{{ctxProp}}"></div>'})) .createAsync(MyComp) .then((fixture) => { @@ -246,11 +313,11 @@ function declareTests() { it('should consume directive watch expression change.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var tpl = '<span>' + - '<div my-dir [elprop]="ctxProp"></div>' + - '<div my-dir elprop="Hi there!"></div>' + - '<div my-dir elprop="Hi {{\'there!\'}}"></div>' + - '<div my-dir elprop="One more {{ctxProp}}"></div>' + - '</span>'; + '<div my-dir [elprop]="ctxProp"></div>' + + '<div my-dir elprop="Hi there!"></div>' + + '<div my-dir elprop="Hi {{\'there!\'}}"></div>' + + '<div my-dir elprop="One more {{ctxProp}}"></div>' + + '</span>'; tcb.overrideView(MyComp, new ViewMetadata({template: tpl, directives: [MyDir]})) .createAsync(MyComp) @@ -270,7 +337,7 @@ function declareTests() { })); describe('pipes', () => { - it('should support pipes in bindings', + it("should support pipes in bindings", inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( @@ -359,9 +426,8 @@ function declareTests() { it('should support directives where a selector matches property binding', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, - new ViewMetadata({template: '<p [id]="ctxProp"></p>', directives: [IdDir]})) + tcb.overrideView(MyComp, new ViewMetadata( + {template: '<p [id]="ctxProp"></p>', directives: [IdDir]})) .createAsync(MyComp) .then((fixture) => { @@ -485,23 +551,22 @@ function declareTests() { }); })); - describe('variable bindings', () => { + describe("variable bindings", () => { it('should assign a component to a var-', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<p><child-cmp var-alice></child-cmp></p>', - directives: [ChildComp] - })) + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<p><child-cmp var-alice></child-cmp></p>', + directives: [ChildComp] + })) - .createAsync(MyComp) - .then((fixture) => { - expect(fixture.debugElement.children[0].children[0].getLocal('alice')) - .toBeAnInstanceOf(ChildComp); + .createAsync(MyComp) + .then((fixture) => { + expect(fixture.debugElement.children[0].children[0].getLocal('alice')) + .toBeAnInstanceOf(ChildComp); - async.done(); - })})); + async.done(); + })})); it('should assign a directive to a var-', inject( @@ -564,40 +629,39 @@ function declareTests() { })})); it('should assign the component instance to a var- with shorthand syntax', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, - async) => {tcb.overrideView(MyComp, new ViewMetadata({ - template: '<child-cmp #alice></child-cmp>', - directives: [ChildComp] - })) + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, + async) => {tcb.overrideView(MyComp, new ViewMetadata({ + template: '<child-cmp #alice></child-cmp>', + directives: [ChildComp] + })) - .createAsync(MyComp) - .then((fixture) => { + .createAsync(MyComp) + .then((fixture) => { - expect(fixture.debugElement.children[0].getLocal('alice')) - .toBeAnInstanceOf(ChildComp); + expect(fixture.debugElement.children[0].getLocal('alice')) + .toBeAnInstanceOf(ChildComp); - async.done(); - })})); + async.done(); + })})); it('should assign the element instance to a user-defined variable', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata( - {template: '<div><div var-alice><i>Hello</i></div></div>'})) + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><div var-alice><i>Hello</i></div></div>' + })) - .createAsync(MyComp) - .then((fixture) => { + .createAsync(MyComp) + .then((fixture) => { - var value = fixture.debugElement.children[0].children[0].getLocal('alice'); - expect(value).not.toBe(null); - expect(value.tagName.toLowerCase()).toEqual('div'); + var value = + fixture.debugElement.children[0].children[0].getLocal('alice'); + expect(value).not.toBe(null); + expect(value.tagName.toLowerCase()).toEqual('div'); - async.done(); - })})); + async.done(); + })})); it('should preserve case', inject( @@ -617,7 +681,8 @@ function declareTests() { })); it('should allow to use variables in a for loop', - inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { tcb.overrideView( MyComp, new ViewMetadata({ template: @@ -630,69 +695,67 @@ function declareTests() { fixture.detectChanges(); // Get the element at index 2, since index 0 is the <template>. expect(DOM.childNodes(fixture.debugElement.nativeElement)[2]) - .toHaveText('1-hello'); + .toHaveText("1-hello"); async.done(); }); })); }); - describe('OnPush components', () => { - it('should use ChangeDetectorRef to manually request a check', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { + describe("OnPush components", () => { + it("should use ChangeDetectorRef to manually request a check", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<push-cmp-with-ref #cmp></push-cmp-with-ref>', - directives: [[[PushCmpWithRef]]] - })) + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<push-cmp-with-ref #cmp></push-cmp-with-ref>', + directives: [[[PushCmpWithRef]]] + })) - .createAsync(MyComp) - .then((fixture) => { + .createAsync(MyComp) + .then((fixture) => { - var cmp = fixture.debugElement.children[0].getLocal('cmp'); + var cmp = fixture.debugElement.children[0].getLocal('cmp'); - fixture.detectChanges(); - expect(cmp.numberOfChecks).toEqual(1); + fixture.detectChanges(); + expect(cmp.numberOfChecks).toEqual(1); - fixture.detectChanges(); - expect(cmp.numberOfChecks).toEqual(1); + fixture.detectChanges(); + expect(cmp.numberOfChecks).toEqual(1); - cmp.propagate(); + cmp.propagate(); - fixture.detectChanges(); - expect(cmp.numberOfChecks).toEqual(2); - async.done(); - })})); + fixture.detectChanges(); + expect(cmp.numberOfChecks).toEqual(2); + async.done(); + })})); - it('should be checked when its bindings got updated', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { + it("should be checked when its bindings got updated", + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<push-cmp [prop]="ctxProp" #cmp></push-cmp>', - directives: [[[PushCmp]]] - })) + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<push-cmp [prop]="ctxProp" #cmp></push-cmp>', + directives: [[[PushCmp]]] + })) - .createAsync(MyComp) - .then((fixture) => { - var cmp = fixture.debugElement.children[0].getLocal('cmp'); + .createAsync(MyComp) + .then((fixture) => { + var cmp = fixture.debugElement.children[0].getLocal('cmp'); - fixture.debugElement.componentInstance.ctxProp = 'one'; - fixture.detectChanges(); - expect(cmp.numberOfChecks).toEqual(1); + fixture.debugElement.componentInstance.ctxProp = "one"; + fixture.detectChanges(); + expect(cmp.numberOfChecks).toEqual(1); - fixture.debugElement.componentInstance.ctxProp = 'two'; - fixture.detectChanges(); - expect(cmp.numberOfChecks).toEqual(2); + fixture.debugElement.componentInstance.ctxProp = "two"; + fixture.detectChanges(); + expect(cmp.numberOfChecks).toEqual(2); - async.done(); - })})); + async.done(); + })})); if (DOM.supportsDOMEvents()) { - it('should allow to destroy a component from within a host event handler', + it("should allow to destroy a component from within a host event handler", inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { var fixture: ComponentFixture; @@ -716,31 +779,30 @@ function declareTests() { } it('should not affect updating properties on the component', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({ - template: - '<push-cmp-with-ref [prop]="ctxProp" #cmp></push-cmp-with-ref>', - directives: [[[PushCmpWithRef]]] - })) + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + tcb.overrideView( + MyComp, new ViewMetadata({ + template: + '<push-cmp-with-ref [prop]="ctxProp" #cmp></push-cmp-with-ref>', + directives: [[[PushCmpWithRef]]] + })) - .createAsync(MyComp) - .then((fixture) => { + .createAsync(MyComp) + .then((fixture) => { - var cmp = fixture.debugElement.children[0].getLocal('cmp'); + var cmp = fixture.debugElement.children[0].getLocal('cmp'); - fixture.debugElement.componentInstance.ctxProp = 'one'; - fixture.detectChanges(); - expect(cmp.prop).toEqual('one'); + fixture.debugElement.componentInstance.ctxProp = "one"; + fixture.detectChanges(); + expect(cmp.prop).toEqual("one"); - fixture.debugElement.componentInstance.ctxProp = 'two'; - fixture.detectChanges(); - expect(cmp.prop).toEqual('two'); + fixture.debugElement.componentInstance.ctxProp = "two"; + fixture.detectChanges(); + expect(cmp.prop).toEqual("two"); - async.done(); - })})); + async.done(); + })})); if (DOM.supportsDOMEvents()) { it('should be checked when an async pipe requests a check', @@ -774,27 +836,26 @@ function declareTests() { }); it('should create a component that injects an @Host', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: ` + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: ` <some-directive> <p> <cmp-with-host #child></cmp-with-host> </p> </some-directive>`, - directives: [SomeDirective, CompWithHost] - })) + directives: [SomeDirective, CompWithHost] + })) - .createAsync(MyComp) - .then((fixture) => { + .createAsync(MyComp) + .then((fixture) => { - var childComponent = fixture.debugElement.children[0].getLocal('child'); - expect(childComponent.myHost).toBeAnInstanceOf(SomeDirective); + var childComponent = fixture.debugElement.children[0].getLocal('child'); + expect(childComponent.myHost).toBeAnInstanceOf(SomeDirective); - async.done(); - })})); + async.done(); + })})); it('should create a component that injects an @Host through viewcontainer directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { @@ -926,9 +987,9 @@ function declareTests() { dispatchEvent(tc.nativeElement, 'domEvent'); - expect(listener.eventTypes).toEqual([ - 'domEvent', 'body_domEvent', 'document_domEvent', 'window_domEvent' - ]); + expect(listener.eventTypes) + .toEqual( + ['domEvent', 'body_domEvent', 'document_domEvent', 'window_domEvent']); fixture.destroy(); listener.eventTypes = []; @@ -950,16 +1011,16 @@ function declareTests() { .then((fixture) => { var tc = fixture.debugElement.children[0]; var listener = tc.inject(DirectiveListeningDomEvent); - dispatchEvent(DOM.getGlobalEventTarget('window'), 'domEvent'); + dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(listener.eventTypes).toEqual(['window_domEvent']); listener.eventTypes = []; - dispatchEvent(DOM.getGlobalEventTarget('document'), 'domEvent'); + dispatchEvent(DOM.getGlobalEventTarget("document"), 'domEvent'); expect(listener.eventTypes).toEqual(['document_domEvent', 'window_domEvent']); fixture.destroy(); listener.eventTypes = []; - dispatchEvent(DOM.getGlobalEventTarget('body'), 'domEvent'); + dispatchEvent(DOM.getGlobalEventTarget("body"), 'domEvent'); expect(listener.eventTypes).toEqual([]); async.done(); @@ -977,8 +1038,8 @@ function declareTests() { .then((fixture) => { fixture.detectChanges(); - expect(DOM.getAttribute(fixture.debugElement.children[0].nativeElement, 'role')) - .toEqual('button'); + expect(DOM.getAttribute(fixture.debugElement.children[0].nativeElement, "role")) + .toEqual("button"); async.done(); }); @@ -996,11 +1057,11 @@ function declareTests() { var tc = fixture.debugElement.children[0]; var updateHost = tc.inject(DirectiveUpdatingHostProperties); - updateHost.id = 'newId'; + updateHost.id = "newId"; fixture.detectChanges(); - expect(tc.nativeElement.id).toEqual('newId'); + expect(tc.nativeElement.id).toEqual("newId"); async.done(); }); @@ -1009,13 +1070,15 @@ function declareTests() { if (DOM.supportsDOMEvents()) { it('should support preventing default on render events', - inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { tcb.overrideView( MyComp, new ViewMetadata({ template: '<input type="checkbox" listenerprevent><input type="checkbox" listenernoprevent>', directives: [ - DirectiveListeningDomEventPrevent, DirectiveListeningDomEventNoPrevent + DirectiveListeningDomEventPrevent, + DirectiveListeningDomEventNoPrevent ] })) @@ -1023,10 +1086,10 @@ function declareTests() { .then((fixture) => { var dispatchedEvent = DOM.createMouseEvent('click'); var dispatchedEvent2 = DOM.createMouseEvent('click'); - DOM.dispatchEvent( - fixture.debugElement.children[0].nativeElement, dispatchedEvent); - DOM.dispatchEvent( - fixture.debugElement.children[1].nativeElement, dispatchedEvent2); + DOM.dispatchEvent(fixture.debugElement.children[0].nativeElement, + dispatchedEvent); + DOM.dispatchEvent(fixture.debugElement.children[1].nativeElement, + dispatchedEvent2); expect(DOM.isPrevented(dispatchedEvent)).toBe(true); expect(DOM.isPrevented(dispatchedEvent2)).toBe(false); expect(DOM.getChecked(fixture.debugElement.children[0].nativeElement)) @@ -1057,7 +1120,7 @@ function declareTests() { var listener = tc.inject(DirectiveListeningDomEvent); var listenerother = tc.inject(DirectiveListeningDomEventOther); - dispatchEvent(DOM.getGlobalEventTarget('window'), 'domEvent'); + dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(listener.eventTypes).toEqual(['window_domEvent']); expect(listenerother.eventType).toEqual('other_domEvent'); expect(globalCounter).toEqual(1); @@ -1065,12 +1128,12 @@ function declareTests() { fixture.debugElement.componentInstance.ctxBoolProp = false; fixture.detectChanges(); - dispatchEvent(DOM.getGlobalEventTarget('window'), 'domEvent'); + dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(globalCounter).toEqual(1); fixture.debugElement.componentInstance.ctxBoolProp = true; fixture.detectChanges(); - dispatchEvent(DOM.getGlobalEventTarget('window'), 'domEvent'); + dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(globalCounter).toEqual(2); // need to destroy to release all remaining global event listeners @@ -1082,26 +1145,25 @@ function declareTests() { describe('dynamic ViewContainers', () => { it('should allow to create a ViewContainerRef at any bound location', - inject( - [TestComponentBuilder, AsyncTestCompleter, Compiler], - (tcb: TestComponentBuilder, async, compiler) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div><dynamic-vp #dynamic></dynamic-vp></div>', - directives: [DynamicViewport] - })) + inject([TestComponentBuilder, AsyncTestCompleter, Compiler], + (tcb: TestComponentBuilder, async, compiler) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><dynamic-vp #dynamic></dynamic-vp></div>', + directives: [DynamicViewport] + })) - .createAsync(MyComp) - .then((fixture) => { - var tc = fixture.debugElement.children[0].children[0]; - var dynamicVp: DynamicViewport = tc.inject(DynamicViewport); - dynamicVp.done.then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.children[0].children[1].nativeElement) - .toHaveText('dynamic greet'); - async.done(); - }); - }); - })); + .createAsync(MyComp) + .then((fixture) => { + var tc = fixture.debugElement.children[0].children[0]; + var dynamicVp: DynamicViewport = tc.inject(DynamicViewport); + dynamicVp.done.then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.children[0].children[1].nativeElement) + .toHaveText('dynamic greet'); + async.done(); + }); + }); + })); }); @@ -1124,8 +1186,8 @@ function declareTests() { })); }); - describe('dependency injection', () => { - it('should support bindings', + describe("dependency injection", () => { + it("should support bindings", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new ViewMetadata({ @@ -1139,14 +1201,14 @@ function declareTests() { })) .createAsync(MyComp) .then((fixture) => { - var comp = fixture.debugElement.children[0].getLocal('consuming'); + var comp = fixture.debugElement.children[0].getLocal("consuming"); expect(comp.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); - it('should support viewProviders', + it("should support viewProviders", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(DirectiveProvidingInjectableInView, new ViewMetadata({ template: ` @@ -1157,14 +1219,14 @@ function declareTests() { })) .createAsync(DirectiveProvidingInjectableInView) .then((fixture) => { - var comp = fixture.debugElement.children[0].getLocal('consuming'); + var comp = fixture.debugElement.children[0].getLocal("consuming"); expect(comp.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); - it('should support unbounded lookup', + it("should support unbounded lookup", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ template: ` @@ -1187,18 +1249,17 @@ function declareTests() { .createAsync(MyComp) .then((fixture) => { - var comp = fixture.debugElement.children[0].getLocal('dir'); + var comp = fixture.debugElement.children[0].getLocal("dir"); expect(comp.directive.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); - it('should support the event-bus scenario', + it("should support the event-bus scenario", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({ - template: ` + tcb.overrideView(MyComp, new ViewMetadata({ + template: ` <grand-parent-providing-event-bus> <parent-providing-event-bus> <child-consuming-event-bus> @@ -1206,10 +1267,12 @@ function declareTests() { </parent-providing-event-bus> </grand-parent-providing-event-bus> `, - directives: [ - GrandParentProvidingEventBus, ParentProvidingEventBus, ChildConsumingEventBus - ] - })) + directives: [ + GrandParentProvidingEventBus, + ParentProvidingEventBus, + ChildConsumingEventBus + ] + })) .createAsync(MyComp) .then((fixture) => { var gpComp = fixture.debugElement.children[0]; @@ -1220,8 +1283,8 @@ function declareTests() { var parent = parentComp.inject(ParentProvidingEventBus); var child = childComp.inject(ChildConsumingEventBus); - expect(grandParent.bus.name).toEqual('grandparent'); - expect(parent.bus.name).toEqual('parent'); + expect(grandParent.bus.name).toEqual("grandparent"); + expect(parent.bus.name).toEqual("parent"); expect(parent.grandParentBus).toBe(grandParent.bus); expect(child.bus).toBe(parent.bus); @@ -1229,7 +1292,7 @@ function declareTests() { }); })); - it('should instantiate bindings lazily', + it("should instantiate bindings lazily", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new ViewMetadata({ @@ -1244,7 +1307,7 @@ function declareTests() { })) .createAsync(MyComp) .then((fixture) => { - var providing = fixture.debugElement.children[0].getLocal('providing'); + var providing = fixture.debugElement.children[0].getLocal("providing"); expect(providing.created).toBe(false); fixture.debugElement.componentInstance.ctxBoolProp = true; @@ -1257,7 +1320,7 @@ function declareTests() { })); }); - describe('corner cases', () => { + describe("corner cases", () => { it('should remove script tags from templates', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ @@ -1274,7 +1337,7 @@ function declareTests() { })); }); - describe('error handling', () => { + describe("error handling", () => { it('should report a meaningful error when a directive is missing annotation', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView( @@ -1323,8 +1386,8 @@ function declareTests() { PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { var c = e.context; - expect(DOM.nodeName(c.element).toUpperCase()).toEqual('DIRECTIVE-THROWING-ERROR'); - expect(DOM.nodeName(c.componentElement).toUpperCase()).toEqual('DIV'); + expect(DOM.nodeName(c.element).toUpperCase()).toEqual("DIRECTIVE-THROWING-ERROR"); + expect(DOM.nodeName(c.componentElement).toUpperCase()).toEqual("DIV"); expect(c.injector).toBeAnInstanceOf(Injector); async.done(); return null; @@ -1340,15 +1403,15 @@ function declareTests() { tcb.createAsync(MyComp).then(fixture => { try { fixture.detectChanges(); - throw 'Should throw'; + throw "Should throw"; } catch (e) { var c = e.context; - expect(DOM.nodeName(c.element).toUpperCase()).toEqual('INPUT'); - expect(DOM.nodeName(c.componentElement).toUpperCase()).toEqual('DIV'); + expect(DOM.nodeName(c.element).toUpperCase()).toEqual("INPUT"); + expect(DOM.nodeName(c.componentElement).toUpperCase()).toEqual("DIV"); expect(c.injector).toBeAnInstanceOf(Injector); - expect(c.expression).toContain('one.two.three'); + expect(c.expression).toContain("one.two.three"); expect(c.context).toBe(fixture.debugElement.componentInstance); - expect(c.locals['local']).toBeDefined(); + expect(c.locals["local"]).toBeDefined(); } async.done(); @@ -1363,7 +1426,7 @@ function declareTests() { tcb.createAsync(MyComp).then(fixture => { try { fixture.detectChanges(); - throw 'Should throw'; + throw "Should throw"; } catch (e) { var c = e.context; expect(c.element).toBeNull(); @@ -1389,32 +1452,33 @@ function declareTests() { tick(); var tc = fixture.debugElement.children[0]; - tc.inject(DirectiveEmittingEvent).fireEvent('boom'); + tc.inject(DirectiveEmittingEvent).fireEvent("boom"); try { tick(); - throw 'Should throw'; + throw "Should throw"; } catch (e) { clearPendingTimers(); var c = e.context; - expect(DOM.nodeName(c.element).toUpperCase()).toEqual('SPAN'); - expect(DOM.nodeName(c.componentElement).toUpperCase()).toEqual('DIV'); + expect(DOM.nodeName(c.element).toUpperCase()).toEqual("SPAN"); + expect(DOM.nodeName(c.componentElement).toUpperCase()).toEqual("DIV"); expect(c.injector).toBeAnInstanceOf(Injector); expect(c.context).toBe(fixture.debugElement.componentInstance); - expect(c.locals['local']).toBeDefined(); + expect(c.locals["local"]).toBeDefined(); } }))); } if (!IS_DART) { it('should report a meaningful error when a directive is undefined', - inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { var undefinedValue; - tcb = tcb.overrideView( - MyComp, new ViewMetadata({directives: [undefinedValue], template: ''})); + tcb = tcb.overrideView(MyComp, + new ViewMetadata({directives: [undefinedValue], template: ''})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( @@ -1426,18 +1490,17 @@ function declareTests() { } it('should specify a location of an error that happened during change detection (text)', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({template: '{{a.b}}'})) + tcb.overrideView(MyComp, new ViewMetadata({template: '{{a.b}}'})) - .createAsync(MyComp) - .then((fixture) => { - expect(() => fixture.detectChanges()) - .toThrowError(containsRegexp(`{{a.b}} in ${stringify(MyComp)}`)); - async.done(); - })})); + .createAsync(MyComp) + .then((fixture) => { + expect(() => fixture.detectChanges()) + .toThrowError(containsRegexp(`{{a.b}} in ${stringify(MyComp)}`)); + async.done(); + })})); it('should specify a location of an error that happened during change detection (element property)', inject( @@ -1454,21 +1517,20 @@ function declareTests() { })})); it('should specify a location of an error that happened during change detection (directive property)', - inject( - [TestComponentBuilder, AsyncTestCompleter], - (tcb: TestComponentBuilder, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<child-cmp [title]="a.b"></child-cmp>', - directives: [ChildComp] - })) + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<child-cmp [title]="a.b"></child-cmp>', + directives: [ChildComp] + })) - .createAsync(MyComp) - .then((fixture) => { - expect(() => fixture.detectChanges()) - .toThrowError(containsRegexp(`a.b in ${stringify(MyComp)}`)); - async.done(); - })})); + .createAsync(MyComp) + .then((fixture) => { + expect(() => fixture.detectChanges()) + .toThrowError(containsRegexp(`a.b in ${stringify(MyComp)}`)); + async.done(); + })})); }); it('should support imperative views', @@ -1485,56 +1547,57 @@ function declareTests() { })); it('should support moving embedded views around', - inject( - [TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT], - (tcb: TestComponentBuilder, async, anchorElement) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div><div *someImpvp="ctxBoolProp">hello</div></div>', - directives: [SomeImperativeViewport] - })) - .createAsync(MyComp) - .then((fixture: ComponentFixture) => { - fixture.detectChanges(); - expect(anchorElement).toHaveText(''); + inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT], + (tcb: TestComponentBuilder, async, anchorElement) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<div><div *someImpvp="ctxBoolProp">hello</div></div>', + directives: [SomeImperativeViewport] + })) + .createAsync(MyComp) + .then((fixture: ComponentFixture) => { + fixture.detectChanges(); + expect(anchorElement).toHaveText(''); - fixture.debugElement.componentInstance.ctxBoolProp = true; - fixture.detectChanges(); + fixture.debugElement.componentInstance.ctxBoolProp = true; + fixture.detectChanges(); - expect(anchorElement).toHaveText('hello'); + expect(anchorElement).toHaveText('hello'); - fixture.debugElement.componentInstance.ctxBoolProp = false; - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText(''); + fixture.debugElement.componentInstance.ctxBoolProp = false; + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText(''); - async.done(); - }); - })); + async.done(); + }); + })); describe('Property bindings', () => { if (!IS_DART) { it('should throw on bindings to unknown properties', - inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb = tcb.overrideView( - MyComp, new ViewMetadata({template: '<div unknown="{{ctxProp}}"></div>'})) + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + tcb = + tcb.overrideView(MyComp, + new ViewMetadata({template: '<div unknown="{{ctxProp}}"></div>'})) - PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { - expect(e.message).toEqual( - `Template parse errors:\nCan't bind to 'unknown' since it isn't a known native property ("<div [ERROR ->]unknown="{{ctxProp}}"></div>"): MyComp@0:5`); - async.done(); - return null; - }); + PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { + expect(e.message).toEqual( + `Template parse errors:\nCan't bind to 'unknown' since it isn't a known native property ("<div [ERROR ->]unknown="{{ctxProp}}"></div>"): MyComp@0:5`); + async.done(); + return null; + }); })); it('should not throw for property binding to a non-existing property when there is a matching directive property', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<div my-dir [elprop]="ctxProp"></div>', - directives: [MyDir] - })) - .createAsync(MyComp) - .then((val) => { async.done(); }); - })); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + tcb.overrideView( + MyComp, + new ViewMetadata( + {template: '<div my-dir [elprop]="ctxProp"></div>', directives: [MyDir]})) + .createAsync(MyComp) + .then((val) => { async.done(); }); + })); } it('should not be created when there is a directive with the same property', @@ -1545,10 +1608,10 @@ function declareTests() { })) .createAsync(MyComp) .then((fixture) => { - fixture.debugElement.componentInstance.ctxProp = 'TITLE'; + fixture.debugElement.componentInstance.ctxProp = "TITLE"; fixture.detectChanges(); - var el = DOM.querySelector(fixture.debugElement.nativeElement, 'span'); + var el = DOM.querySelector(fixture.debugElement.nativeElement, "span"); expect(isBlank(el.title) || el.title == '').toBeTruthy(); async.done(); @@ -1564,11 +1627,11 @@ function declareTests() { })) .createAsync(MyComp) .then((fixture) => { - fixture.debugElement.componentInstance.ctxProp = 'TITLE'; + fixture.debugElement.componentInstance.ctxProp = "TITLE"; fixture.detectChanges(); - var el = DOM.querySelector(fixture.debugElement.nativeElement, 'span'); - expect(el.title).toEqual('TITLE'); + var el = DOM.querySelector(fixture.debugElement.nativeElement, "span"); + expect(el.title).toEqual("TITLE"); async.done(); @@ -1577,15 +1640,16 @@ function declareTests() { }); describe('logging property updates', () => { - beforeEachProviders(() => [provide(ChangeDetectorGenConfig, { - useValue: new ChangeDetectorGenConfig(true, true, false) - })]); + beforeEachProviders(() => [ + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, true, false)}) + ]); it('should reflect property values as attributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var tpl = '<div>' + - '<div my-dir [elprop]="ctxProp"></div>' + - '</div>'; + '<div my-dir [elprop]="ctxProp"></div>' + + '</div>'; tcb.overrideView(MyComp, new ViewMetadata({template: tpl, directives: [MyDir]})) .createAsync(MyComp) @@ -1620,8 +1684,8 @@ function declareTests() { function runWithMode(mode: string) { return inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: `<!--${mode}--><div>{{ctxProp}}</div>`})) + tcb.overrideView(MyComp, + new ViewMetadata({template: `<!--${mode}--><div>{{ctxProp}}</div>`})) .createAsync(MyComp) .then((fixture) => { fixture.debugElement.componentInstance.ctxProp = 'Hello World!'; @@ -1648,7 +1712,7 @@ function declareTests() { tcb.createAsync(MyComp), (value) => { throw new BaseException( - 'Test failure: should not have come here as an exception was expected'); + "Test failure: should not have come here as an exception was expected"); }, (err) => { expect(err.message).toEqual(errMessage); @@ -1658,39 +1722,36 @@ function declareTests() { if (assertionsEnabled()) { it('should raise an error if no directive is registered for a template with template bindings', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - expectCompileError( - tcb, '<div><div template="if: foo"></div></div>', - 'Missing directive to handle \'if\' in <div template="if: foo">', - () => async.done()); - })); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + expectCompileError(tcb, '<div><div template="if: foo"></div></div>', + 'Missing directive to handle \'if\' in <div template="if: foo">', + () => async.done()); + })); it('should raise an error for missing template directive (1)', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - expectCompileError( - tcb, '<div><template foo></template></div>', - 'Missing directive to handle: <template foo>', () => async.done()); - })); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + expectCompileError(tcb, '<div><template foo></template></div>', + 'Missing directive to handle: <template foo>', () => async.done()); + })); it('should raise an error for missing template directive (2)', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - expectCompileError( - tcb, '<div><template *ngIf="condition"></template></div>', - 'Missing directive to handle: <template *ngIf="condition">', - () => async.done()); - })); + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + expectCompileError(tcb, '<div><template *ngIf="condition"></template></div>', + 'Missing directive to handle: <template *ngIf="condition">', + () => async.done()); + })); it('should raise an error for missing template directive (3)', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - expectCompileError( - tcb, '<div *ngIf="condition"></div>', - 'Missing directive to handle \'if\' in MyComp: <div *ngIf="condition">', - () => async.done()); - })); + inject([TestComponentBuilder, AsyncTestCompleter], + (tcb: TestComponentBuilder, async) => { + expectCompileError( + tcb, '<div *ngIf="condition"></div>', + 'Missing directive to handle \'if\' in MyComp: <div *ngIf="condition">', + () => async.done()); + })); } }); @@ -1706,7 +1767,7 @@ function declareTests() { .then((fixture) => { fixture.detectChanges(); var dir = fixture.debugElement.children[0].inject(DirectiveWithPropDecorators); - expect(dir.dirProp).toEqual('aaa'); + expect(dir.dirProp).toEqual("aaa"); async.done(); }); })); @@ -1721,7 +1782,7 @@ function declareTests() { .then((fixture) => { fixture.detectChanges(); var dir = fixture.debugElement.children[0].inject(DirectiveWithPropDecorators); - dir.myAttr = 'aaa'; + dir.myAttr = "aaa"; fixture.detectChanges(); expect(DOM.getOuterHTML(fixture.debugElement.children[0].nativeElement)) @@ -1749,29 +1810,28 @@ function declareTests() { tick(); - expect(fixture.debugElement.componentInstance.ctxProp).toEqual('called'); + expect(fixture.debugElement.componentInstance.ctxProp).toEqual("called"); }))); it('should support host listener decorators', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView(MyComp, new ViewMetadata({ - template: '<with-prop-decorators></with-prop-decorators>', - directives: [DirectiveWithPropDecorators] - })) - .createAsync(MyComp) - .then((fixture) => { - fixture.detectChanges(); - var dir = - fixture.debugElement.children[0].inject(DirectiveWithPropDecorators); - var native = fixture.debugElement.children[0].nativeElement; - DOM.dispatchEvent(native, DOM.createMouseEvent('click')); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + tcb.overrideView(MyComp, new ViewMetadata({ + template: '<with-prop-decorators></with-prop-decorators>', + directives: [DirectiveWithPropDecorators] + })) + .createAsync(MyComp) + .then((fixture) => { + fixture.detectChanges(); + var dir = fixture.debugElement.children[0].inject(DirectiveWithPropDecorators); + var native = fixture.debugElement.children[0].nativeElement; + DOM.dispatchEvent(native, DOM.createMouseEvent('click')); - expect(dir.target).toBe(native); - async.done(); - }); - })); + expect(dir.target).toBe(native); + async.done(); + }); + })); } it('should support defining views in the component decorator', @@ -1784,7 +1844,7 @@ function declareTests() { .then((fixture) => { fixture.detectChanges(); var native = fixture.debugElement.children[0].nativeElement; - expect(native).toHaveText('No View Decorator: 123'); + expect(native).toHaveText("No View Decorator: 123"); async.done(); }); })); @@ -1794,79 +1854,75 @@ function declareTests() { if (DOM.supportsDOMEvents()) { describe('svg', () => { it('should support svg elements', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, - new ViewMetadata({template: '<svg><use xlink:href="Port" /></svg>'})) - .createAsync(MyComp) - .then((fixture) => { - var el = fixture.debugElement.nativeElement; - var svg = DOM.childNodes(el)[0]; - var use = DOM.childNodes(svg)[0]; - expect(DOM.getProperty(<Element>svg, 'namespaceURI')) - .toEqual('http://www.w3.org/2000/svg'); - expect(DOM.getProperty(<Element>use, 'namespaceURI')) - .toEqual('http://www.w3.org/2000/svg'); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + tcb.overrideView(MyComp, + new ViewMetadata({template: '<svg><use xlink:href="Port" /></svg>'})) + .createAsync(MyComp) + .then((fixture) => { + var el = fixture.debugElement.nativeElement; + var svg = DOM.childNodes(el)[0]; + var use = DOM.childNodes(svg)[0]; + expect(DOM.getProperty(<Element>svg, 'namespaceURI')) + .toEqual('http://www.w3.org/2000/svg'); + expect(DOM.getProperty(<Element>use, 'namespaceURI')) + .toEqual('http://www.w3.org/2000/svg'); - if (!IS_DART) { - var firstAttribute = DOM.getProperty(<Element>use, 'attributes')[0]; - expect(firstAttribute.name).toEqual('xlink:href'); - expect(firstAttribute.namespaceURI) - .toEqual('http://www.w3.org/1999/xlink'); - } else { - // For Dart where '_Attr' has no instance getter 'namespaceURI' - expect(DOM.getOuterHTML(<HTMLElement>use)).toContain('xmlns:xlink'); - } + if (!IS_DART) { + var firstAttribute = DOM.getProperty(<Element>use, 'attributes')[0]; + expect(firstAttribute.name).toEqual('xlink:href'); + expect(firstAttribute.namespaceURI).toEqual('http://www.w3.org/1999/xlink'); + } else { + // For Dart where '_Attr' has no instance getter 'namespaceURI' + expect(DOM.getOuterHTML(<HTMLElement>use)).toContain('xmlns:xlink'); + } - async.done(); - }); - })); + async.done(); + }); + })); }); describe('attributes', () => { it('should support attributes with namespace', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - SomeCmp, new ViewMetadata({template: '<svg:use xlink:href="#id" />'})) - .createAsync(SomeCmp) - .then((fixture) => { - let useEl = DOM.firstChild(fixture.debugElement.nativeElement); - expect(DOM.getAttributeNS(useEl, 'http://www.w3.org/1999/xlink', 'href')) - .toEqual('#id'); - async.done(); - }); - })); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + tcb.overrideView(SomeCmp, new ViewMetadata({template: '<svg:use xlink:href="#id" />'})) + .createAsync(SomeCmp) + .then((fixture) => { + let useEl = DOM.firstChild(fixture.debugElement.nativeElement); + expect(DOM.getAttributeNS(useEl, 'http://www.w3.org/1999/xlink', 'href')) + .toEqual('#id'); + async.done(); + }); + })); it('should support binding to attributes with namespace', - inject( - [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - SomeCmp, - new ViewMetadata({template: '<svg:use [attr.xlink:href]="value" />'})) - .createAsync(SomeCmp) - .then((fixture) => { - let cmp = fixture.debugElement.componentInstance; - let useEl = DOM.firstChild(fixture.debugElement.nativeElement); + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, + async) => { + tcb.overrideView(SomeCmp, + new ViewMetadata({template: '<svg:use [attr.xlink:href]="value" />'})) + .createAsync(SomeCmp) + .then((fixture) => { + let cmp = fixture.debugElement.componentInstance; + let useEl = DOM.firstChild(fixture.debugElement.nativeElement); - cmp.value = '#id'; - fixture.detectChanges(); + cmp.value = "#id"; + fixture.detectChanges(); - expect(DOM.getAttributeNS(useEl, 'http://www.w3.org/1999/xlink', 'href')) - .toEqual('#id'); + expect(DOM.getAttributeNS(useEl, 'http://www.w3.org/1999/xlink', 'href')) + .toEqual('#id'); - cmp.value = null; - fixture.detectChanges(); + cmp.value = null; + fixture.detectChanges(); - expect(DOM.hasAttributeNS(useEl, 'http://www.w3.org/1999/xlink', 'href')) - .toEqual(false); + expect(DOM.hasAttributeNS(useEl, 'http://www.w3.org/1999/xlink', 'href')) + .toEqual(false); - async.done(); - }); - })); + async.done(); + }); + })); }); } }); @@ -1935,7 +1991,7 @@ class PushCmp { get field() { this.numberOfChecks++; - return 'fixed'; + return "fixed"; } } @@ -1958,7 +2014,7 @@ class PushCmpWithRef { get field() { this.numberOfChecks++; - return 'fixed'; + return "fixed"; } propagate() { this.ref.markForCheck(); } @@ -2112,7 +2168,7 @@ class DirectiveUpdatingHostAttributes { class DirectiveUpdatingHostProperties { id: string; - constructor() { this.id = 'one'; } + constructor() { this.id = "one"; } } @Directive({selector: '[listener]', host: {'(event)': 'onEvent($event)'}}) @@ -2138,9 +2194,9 @@ class DirectiveListeningEvent { class DirectiveListeningDomEvent { eventTypes: string[] = []; onEvent(eventType: string) { this.eventTypes.push(eventType); } - onWindowEvent(eventType: string) { this.eventTypes.push('window_' + eventType); } - onDocumentEvent(eventType: string) { this.eventTypes.push('document_' + eventType); } - onBodyEvent(eventType: string) { this.eventTypes.push('body_' + eventType); } + onWindowEvent(eventType: string) { this.eventTypes.push("window_" + eventType); } + onDocumentEvent(eventType: string) { this.eventTypes.push("document_" + eventType); } + onBodyEvent(eventType: string) { this.eventTypes.push("body_" + eventType); } } var globalCounter = 0; @@ -2151,7 +2207,7 @@ class DirectiveListeningDomEventOther { constructor() { this.eventType = ''; } onEvent(eventType: string) { globalCounter++; - this.eventType = 'other_' + eventType; + this.eventType = "other_" + eventType; } } @@ -2186,9 +2242,9 @@ class NeedsAttribute { typeAttribute; staticAttribute; fooAttribute; - constructor( - @Attribute('type') typeAttribute: String, @Attribute('static') staticAttribute: String, - @Attribute('foo') fooAttribute: String) { + constructor(@Attribute('type') typeAttribute: String, + @Attribute('static') staticAttribute: String, + @Attribute('foo') fooAttribute: String) { this.typeAttribute = typeAttribute; this.staticAttribute = staticAttribute; this.fooAttribute = fooAttribute; @@ -2268,8 +2324,9 @@ function createInjectableWithLogging(inj: Injector) { @Component({ selector: 'component-providing-logging-injectable', - providers: [new Provider( - InjectableService, {useFactory: createInjectableWithLogging, deps: [Injector]})], + providers: [ + new Provider(InjectableService, {useFactory: createInjectableWithLogging, deps: [Injector]}) + ], template: '' }) @Injectable() @@ -2324,9 +2381,8 @@ class DirectiveContainingDirectiveConsumingAnInjectable { class DirectiveConsumingInjectableUnbounded { injectable; - constructor( - injectable: InjectableService, - @SkipSelf() parent: DirectiveContainingDirectiveConsumingAnInjectable) { + constructor(injectable: InjectableService, + @SkipSelf() parent: DirectiveContainingDirectiveConsumingAnInjectable) { this.injectable = injectable; parent.directive = this; } @@ -2346,7 +2402,7 @@ class EventBus { @Directive({ selector: 'grand-parent-providing-event-bus', - providers: [new Provider(EventBus, {useValue: new EventBus(null, 'grandparent')})] + providers: [new Provider(EventBus, {useValue: new EventBus(null, "grandparent")})] }) class GrandParentProvidingEventBus { bus: EventBus; @@ -2355,13 +2411,15 @@ class GrandParentProvidingEventBus { } function createParentBus(peb) { - return new EventBus(peb, 'parent'); + return new EventBus(peb, "parent"); } @Component({ selector: 'parent-providing-event-bus', - providers: [new Provider( - EventBus, {useFactory: createParentBus, deps: [[EventBus, new SkipSelfMetadata()]]})], + providers: [ + new Provider(EventBus, + {useFactory: createParentBus, deps: [[EventBus, new SkipSelfMetadata()]]}) + ], directives: [forwardRef(() => ChildConsumingEventBus)], template: ` <child-consuming-event-bus></child-consuming-event-bus> @@ -2389,9 +2447,8 @@ class ChildConsumingEventBus { class SomeImperativeViewport { view: EmbeddedViewRef; anchor; - constructor( - public vc: ViewContainerRef, public templateRef: TemplateRef, - @Inject(ANCHOR_ELEMENT) anchor) { + constructor(public vc: ViewContainerRef, public templateRef: TemplateRef, + @Inject(ANCHOR_ELEMENT) anchor) { this.view = null; this.anchor = anchor; } @@ -2435,7 +2492,7 @@ class OtherDuplicateDir { @Directive({selector: 'directive-throwing-error'}) class DirectiveThrowingAnError { - constructor() { throw new BaseException('BOOM'); } + constructor() { throw new BaseException("BOOM"); } } @Component({ @@ -2454,9 +2511,11 @@ class DirectiveWithPropDecorators { @Input('elProp') dirProp: string; @Output('elEvent') event = new EventEmitter(); - @HostBinding('attr.my-attr') myAttr: string; - @HostListener('click', ['$event.target']) - onClick(target) { this.target = target; } + @HostBinding("attr.my-attr") myAttr: string; + @HostListener("click", ["$event.target"]) + onClick(target) { + this.target = target; + } fireEvent(msg) { ObservableWrapper.callEmit(this.event, msg); } } diff --git a/modules/angular2/test/core/linker/projection_integration_spec.ts b/modules/angular2/test/core/linker/projection_integration_spec.ts index 500897f0cd..2b7b7a7fb5 100644 --- a/modules/angular2/test/core/linker/projection_integration_spec.ts +++ b/modules/angular2/test/core/linker/projection_integration_spec.ts @@ -1,9 +1,42 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, containsRegexp, stringifyElement, TestComponentBuilder, ComponentFixture, fakeAsync, tick} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + containsRegexp, + stringifyElement, + TestComponentBuilder, + ComponentFixture, + fakeAsync, + tick +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {bind, provide, forwardRef, Component, Directive, ElementRef, TemplateRef, ViewContainerRef, ViewEncapsulation, ViewMetadata} from 'angular2/core'; -import {By,} from 'angular2/platform/common_dom'; +import { + bind, + provide, + forwardRef, + Component, + Directive, + ElementRef, + TemplateRef, + ViewContainerRef, + ViewEncapsulation, + ViewMetadata +} from 'angular2/core'; +import { + By, +} from 'angular2/platform/common_dom'; import {getAllDebugNodes} from 'angular2/src/core/debug/debug_node'; export function main() { @@ -12,8 +45,8 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<simple>' + - '<div>A</div>' + - '</simple>', + '<div>A</div>' + + '</simple>', directives: [Simple] })) .createAsync(MainComp) @@ -27,8 +60,8 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '{{\'START(\'}}<simple>' + - '{{text}}' + - '</simple>{{\')END\'}}', + '{{text}}' + + '</simple>{{\')END\'}}', directives: [Simple] })) .createAsync(MainComp) @@ -104,8 +137,8 @@ export function main() { it('should not show the light dom even if there is no content tag', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MainComp, new ViewMetadata({template: '<empty>A</empty>', directives: [Empty]})) + tcb.overrideView(MainComp, + new ViewMetadata({template: '<empty>A</empty>', directives: [Empty]})) .createAsync(MainComp) .then((main) => { @@ -118,10 +151,10 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<multiple-content-tags>' + - '<div>B</div>' + - '<div>C</div>' + - '<div class="left">A</div>' + - '</multiple-content-tags>', + '<div>B</div>' + + '<div>C</div>' + + '<div class="left">A</div>' + + '</multiple-content-tags>', directives: [MultipleContentTagsComponent] })) .createAsync(MainComp) @@ -136,9 +169,9 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<multiple-content-tags>' + - '<div>B<div class="left">A</div></div>' + - '<div>C</div>' + - '</multiple-content-tags>', + '<div>B<div class="left">A</div></div>' + + '<div>C</div>' + + '</multiple-content-tags>', directives: [MultipleContentTagsComponent] })) .createAsync(MainComp) @@ -149,13 +182,13 @@ export function main() { }); })); - it('should redistribute direct child viewcontainers when the light dom changes', + it("should redistribute direct child viewcontainers when the light dom changes", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<multiple-content-tags>' + - '<template manual class="left"><div>A1</div></template>' + - '<div>B</div>' + - '</multiple-content-tags>', + '<template manual class="left"><div>A1</div></template>' + + '<div>B</div>' + + '</multiple-content-tags>', directives: [MultipleContentTagsComponent, ManualViewportDirective] })) .createAsync(MainComp) @@ -177,13 +210,13 @@ export function main() { }); })); - it('should support nested components', + it("should support nested components", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<outer-with-indirect-nested>' + - '<div>A</div>' + - '<div>B</div>' + - '</outer-with-indirect-nested>', + '<div>A</div>' + + '<div>B</div>' + + '</outer-with-indirect-nested>', directives: [OuterWithIndirectNestedComponent] })) .createAsync(MainComp) @@ -194,14 +227,14 @@ export function main() { }); })); - it('should support nesting with content being direct child of a nested component', + it("should support nesting with content being direct child of a nested component", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<outer>' + - '<template manual class="left"><div>A</div></template>' + - '<div>B</div>' + - '<div>C</div>' + - '</outer>', + '<template manual class="left"><div>A</div></template>' + + '<div>B</div>' + + '<div>C</div>' + + '</outer>', directives: [OuterComponent, ManualViewportDirective], })) .createAsync(MainComp) @@ -223,10 +256,10 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<conditional-content>' + - '<div class="left">A</div>' + - '<div>B</div>' + - '<div>C</div>' + - '</conditional-content>', + '<div class="left">A</div>' + + '<div>B</div>' + + '<div>C</div>' + + '</conditional-content>', directives: [ConditionalContentComponent] })) .createAsync(MainComp) @@ -293,9 +326,9 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<empty>' + - ' <template manual><div>A</div></template>' + - '</empty>' + - 'START(<div project></div>)END', + ' <template manual><div>A</div></template>' + + '</empty>' + + 'START(<div project></div>)END', directives: [Empty, ProjectDirective, ManualViewportDirective], })) .createAsync(MainComp) @@ -326,7 +359,7 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<simple><template manual><div>A</div></template></simple>' + - 'START(<div project></div>)END', + 'START(<div project></div>)END', directives: [Simple, ProjectDirective, ManualViewportDirective], })) .createAsync(MainComp) @@ -351,10 +384,10 @@ export function main() { tcb.overrideView( MainComp, new ViewMetadata({ template: '<conditional-content>' + - '<div class="left">A</div>' + - '<div>B</div>' + - '</conditional-content>' + - 'START(<div project></div>)END', + '<div class="left">A</div>' + + '<div>B</div>' + + '</conditional-content>' + + 'START(<div project></div>)END', directives: [ConditionalContentComponent, ProjectDirective, ManualViewportDirective] })) @@ -386,8 +419,8 @@ export function main() { // the presence of ng-content elements! it('should still allow to implement a recursive trees', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MainComp, new ViewMetadata({template: '<tree></tree>', directives: [Tree]})) + tcb.overrideView(MainComp, + new ViewMetadata({template: '<tree></tree>', directives: [Tree]})) .createAsync(MainComp) .then((main) => { @@ -408,7 +441,7 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<simple-native1><div>A</div></simple-native1>' + - '<simple-native2><div>B</div></simple-native2>', + '<simple-native2><div>B</div></simple-native2>', directives: [SimpleNative1, SimpleNative2] })) .createAsync(MainComp) @@ -477,9 +510,8 @@ export function main() { .then((main) => { main.detectChanges(); expect(DOM.getInnerHTML(main.debugElement.nativeElement)) - .toEqual( - '<cmp-a><cmp-b><cmp-d><d>cmp-d</d></cmp-d></cmp-b>' + - '<cmp-c><c>cmp-c</c></cmp-c></cmp-a>'); + .toEqual('<cmp-a><cmp-b><cmp-d><d>cmp-d</d></cmp-d></cmp-b>' + + '<cmp-c><c>cmp-c</c></cmp-c></cmp-a>'); async.done(); }); })); @@ -494,9 +526,8 @@ export function main() { .then((main) => { main.detectChanges(); expect(DOM.getInnerHTML(main.debugElement.nativeElement)) - .toEqual( - '<cmp-a1>a1<cmp-b11>b11</cmp-b11><cmp-b12>b12</cmp-b12></cmp-a1>' + - '<cmp-a2>a2<cmp-b21>b21</cmp-b21><cmp-b22>b22</cmp-b22></cmp-a2>'); + .toEqual('<cmp-a1>a1<cmp-b11>b11</cmp-b11><cmp-b12>b12</cmp-b12></cmp-a1>' + + '<cmp-a2>a2<cmp-b21>b21</cmp-b21><cmp-b22>b22</cmp-b22></cmp-a2>'); async.done(); }); })); @@ -505,11 +536,11 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MainComp, new ViewMetadata({ template: '<conditional-content>' + - '<div class="left">A</div>' + - '<template manual class="left">B</template>' + - '<div class="left">C</div>' + - '<div>D</div>' + - '</conditional-content>', + '<div class="left">A</div>' + + '<template manual class="left">B</template>' + + '<div class="left">C</div>' + + '<div>D</div>' + + '</conditional-content>', directives: [ConditionalContentComponent, ManualViewportDirective] })) .createAsync(MainComp) diff --git a/modules/angular2/test/core/linker/query_integration_spec.ts b/modules/angular2/test/core/linker/query_integration_spec.ts index 0e076dc5f4..eaf1ba8df9 100644 --- a/modules/angular2/test/core/linker/query_integration_spec.ts +++ b/modules/angular2/test/core/linker/query_integration_spec.ts @@ -1,30 +1,61 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + TestComponentBuilder, +} from 'angular2/testing_internal'; import {isPresent} from 'angular2/src/facade/lang'; import {ObservableWrapper} from 'angular2/src/facade/async'; -import {Component, Directive, Injectable, Optional, TemplateRef, Query, QueryList, ViewQuery, ContentChildren, ViewChildren, ContentChild, ViewChild, AfterContentInit, AfterViewInit, AfterContentChecked, AfterViewChecked} from 'angular2/core'; +import { + Component, + Directive, + Injectable, + Optional, + TemplateRef, + Query, + QueryList, + ViewQuery, + ContentChildren, + ViewChildren, + ContentChild, + ViewChild, + AfterContentInit, + AfterViewInit, + AfterContentChecked, + AfterViewChecked +} from 'angular2/core'; import {NgIf, NgFor} from 'angular2/common'; import {asNativeElements, ViewContainerRef} from 'angular2/core'; export function main() { describe('Query API', () => { - describe('querying by directive type', () => { + describe("querying by directive type", () => { it('should contain all direct child directives in the light dom (constructor)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div text="1"></div>' + - '<needs-query text="2"><div text="3">' + - '<div text="too-deep"></div>' + - '</div></needs-query>' + - '<div text="4"></div>'; + '<needs-query text="2"><div text="3">' + + '<div text="too-deep"></div>' + + '</div></needs-query>' + + '<div text="4"></div>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|'); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|'); - async.done(); - }); + async.done(); + }); })); it('should contain all direct child directives in the content dom', @@ -32,18 +63,20 @@ export function main() { var template = '<needs-content-children #q><div text="foo"></div></needs-content-children>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); - var q = view.debugElement.children[0].getLocal('q'); + var q = view.debugElement.children[0].getLocal('q'); - view.detectChanges(); + view.detectChanges(); - expect(q.textDirChildren.length).toEqual(1); - expect(q.numberOfChildrenAfterContentInit).toEqual(1); + expect(q.textDirChildren.length).toEqual(1); + expect(q.numberOfChildrenAfterContentInit).toEqual(1); - async.done(); - }); + async.done(); + }); })); it('should contain the first content child', @@ -51,48 +84,58 @@ export function main() { var template = '<needs-content-child #q><div *ngIf="shouldShow" text="foo"></div></needs-content-child>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.debugElement.componentInstance.shouldShow = true; - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.debugElement.componentInstance.shouldShow = true; + view.detectChanges(); - var q = view.debugElement.children[0].getLocal('q'); + var q = view.debugElement.children[0].getLocal('q'); - expect(q.log).toEqual([['setter', 'foo'], ['init', 'foo'], ['check', 'foo']]); + expect(q.log).toEqual([["setter", "foo"], ["init", "foo"], ["check", "foo"]]); - view.debugElement.componentInstance.shouldShow = false; - view.detectChanges(); + view.debugElement.componentInstance.shouldShow = false; + view.detectChanges(); - // TODO: this fails right now! - // -> queries are not dirtied! - expect(q.log).toEqual([ - ['setter', 'foo'], ['init', 'foo'], ['check', 'foo'], ['setter', null], - ['check', null] - ]); + // TODO: this fails right now! + // -> queries are not dirtied! + expect(q.log).toEqual([ + ["setter", "foo"], + ["init", "foo"], + ["check", "foo"], + ["setter", null], + ["check", null] + ]); - async.done(); - }); + async.done(); + }); })); it('should contain the first view child', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-child #q></needs-view-child>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); - var q = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); + var q = view.debugElement.children[0].getLocal('q'); - expect(q.log).toEqual([['setter', 'foo'], ['init', 'foo'], ['check', 'foo']]); + expect(q.log).toEqual([["setter", "foo"], ["init", "foo"], ["check", "foo"]]); - q.shouldShow = false; - view.detectChanges(); + q.shouldShow = false; + view.detectChanges(); - expect(q.log).toEqual([ - ['setter', 'foo'], ['init', 'foo'], ['check', 'foo'], ['setter', null], - ['check', null] - ]); + expect(q.log).toEqual([ + ["setter", "foo"], + ["init", "foo"], + ["check", "foo"], + ["setter", null], + ["check", null] + ]); - async.done(); - }); + async.done(); + }); })); it('should contain the first view child accross embedded views', @@ -107,14 +150,17 @@ export function main() { view.detectChanges(); var q = view.debugElement.children[0].getLocal('q'); - expect(q.log).toEqual([['setter', 'foo'], ['init', 'foo'], ['check', 'foo']]); + expect(q.log).toEqual([["setter", "foo"], ["init", "foo"], ["check", "foo"]]); q.shouldShow = false; view.detectChanges(); expect(q.log).toEqual([ - ['setter', 'foo'], ['init', 'foo'], ['check', 'foo'], ['setter', null], - ['check', null] + ["setter", "foo"], + ["init", "foo"], + ["check", "foo"], + ["setter", null], + ["check", null] ]); async.done(); @@ -124,84 +170,97 @@ export function main() { it('should contain all directives in the light dom when descendants flag is used', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div text="1"></div>' + - '<needs-query-desc text="2"><div text="3">' + - '<div text="4"></div>' + - '</div></needs-query-desc>' + - '<div text="5"></div>'; + '<needs-query-desc text="2"><div text="3">' + + '<div text="4"></div>' + + '</div></needs-query-desc>' + + '<div text="5"></div>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|4|'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|4|'); - async.done(); - }); + async.done(); + }); })); it('should contain all directives in the light dom', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<div text="1"></div>' + - '<needs-query text="2"><div text="3"></div></needs-query>' + - '<div text="4"></div>'; + '<needs-query text="2"><div text="3"></div></needs-query>' + + '<div text="4"></div>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|'); - async.done(); - }); + async.done(); + }); })); it('should reflect dynamically inserted directives', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var template = '<div text="1"></div>' + + var template = + '<div text="1"></div>' + '<needs-query text="2"><div *ngIf="shouldShow" [text]="\'3\'"></div></needs-query>' + '<div text="4"></div>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { - view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|'); + view.detectChanges(); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|'); - view.debugElement.componentInstance.shouldShow = true; - view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|'); + view.debugElement.componentInstance.shouldShow = true; + view.detectChanges(); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|3|'); - async.done(); - }); + async.done(); + }); })); it('should be cleanly destroyed when a query crosses view boundaries', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var template = '<div text="1"></div>' + + var template = + '<div text="1"></div>' + '<needs-query text="2"><div *ngIf="shouldShow" [text]="\'3\'"></div></needs-query>' + '<div text="4"></div>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((fixture) => { - fixture.debugElement.componentInstance.shouldShow = true; - fixture.detectChanges(); - fixture.destroy(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((fixture) => { + fixture.debugElement.componentInstance.shouldShow = true; + fixture.detectChanges(); + fixture.destroy(); - async.done(); - }); + async.done(); + }); })); it('should reflect moved directives', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - var template = '<div text="1"></div>' + + var template = + '<div text="1"></div>' + '<needs-query text="2"><div *ngFor="var i of list" [text]="i"></div></needs-query>' + '<div text="4"></div>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|1d|2d|3d|'); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|1d|2d|3d|'); - view.debugElement.componentInstance.list = ['3d', '2d']; - view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('2|3d|2d|'); + view.debugElement.componentInstance.list = ['3d', '2d']; + view.detectChanges(); + expect(asNativeElements(view.debugElement.children)).toHaveText('2|3d|2d|'); - async.done(); - }); + async.done(); + }); })); }); @@ -209,300 +268,330 @@ export function main() { it('should find TemplateRefs in the light and shadow dom', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-tpl><template var-x="light"></template></needs-tpl>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); - var needsTpl: NeedsTpl = view.debugElement.children[0].inject(NeedsTpl); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); + var needsTpl: NeedsTpl = view.debugElement.children[0].inject(NeedsTpl); - expect(needsTpl.vc.createEmbeddedView(needsTpl.query.first).hasLocal('light')) - .toBe(true); - expect(needsTpl.vc.createEmbeddedView(needsTpl.viewQuery.first).hasLocal('shadow')) - .toBe(true); + expect(needsTpl.vc.createEmbeddedView(needsTpl.query.first).hasLocal('light')) + .toBe(true); + expect(needsTpl.vc.createEmbeddedView(needsTpl.viewQuery.first).hasLocal('shadow')) + .toBe(true); - async.done(); - }); + async.done(); + }); })); }); - describe('changes', () => { + describe("changes", () => { it('should notify query on change', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query #q>' + - '<div text="1"></div>' + - '<div *ngIf="shouldShow" text="2"></div>' + - '</needs-query>'; + '<div text="1"></div>' + + '<div *ngIf="shouldShow" text="2"></div>' + + '</needs-query>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q = view.debugElement.children[0].getLocal('q'); - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q = view.debugElement.children[0].getLocal("q"); + view.detectChanges(); - ObservableWrapper.subscribe(q.query.changes, (_) => { - expect(q.query.first.text).toEqual('1'); - expect(q.query.last.text).toEqual('2'); - async.done(); - }); + ObservableWrapper.subscribe(q.query.changes, (_) => { + expect(q.query.first.text).toEqual("1"); + expect(q.query.last.text).toEqual("2"); + async.done(); + }); - view.debugElement.componentInstance.shouldShow = true; - view.detectChanges(); - }); + view.debugElement.componentInstance.shouldShow = true; + view.detectChanges(); + }); })); - it('should notify child\'s query before notifying parent\'s query', + it("should notify child's query before notifying parent's query", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query-desc #q1>' + - '<needs-query-desc #q2>' + - '<div text="1"></div>' + - '</needs-query-desc>' + - '</needs-query-desc>'; + '<needs-query-desc #q2>' + + '<div text="1"></div>' + + '</needs-query-desc>' + + '</needs-query-desc>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q1 = view.debugElement.children[0].getLocal('q1'); - var q2 = view.debugElement.children[0].getLocal('q2'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q1 = view.debugElement.children[0].getLocal("q1"); + var q2 = view.debugElement.children[0].getLocal("q2"); - var firedQ2 = false; + var firedQ2 = false; - ObservableWrapper.subscribe(q2.query.changes, (_) => { firedQ2 = true; }); - ObservableWrapper.subscribe(q1.query.changes, (_) => { - expect(firedQ2).toBe(true); - async.done(); - }); + ObservableWrapper.subscribe(q2.query.changes, (_) => { firedQ2 = true; }); + ObservableWrapper.subscribe(q1.query.changes, (_) => { + expect(firedQ2).toBe(true); + async.done(); + }); - view.detectChanges(); - }); + view.detectChanges(); + }); })); it('should correctly clean-up when destroyed together with the directives it is querying', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query #q *ngIf="shouldShow"><div text="foo"></div></needs-query>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.debugElement.componentInstance.shouldShow = true; - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.debugElement.componentInstance.shouldShow = true; + view.detectChanges(); - var q: NeedsQuery = view.debugElement.children[0].getLocal('q'); + var q: NeedsQuery = view.debugElement.children[0].getLocal('q'); - expect(q.query.length).toEqual(1); + expect(q.query.length).toEqual(1); - view.debugElement.componentInstance.shouldShow = false; - view.detectChanges(); + view.debugElement.componentInstance.shouldShow = false; + view.detectChanges(); - view.debugElement.componentInstance.shouldShow = true; - view.detectChanges(); + view.debugElement.componentInstance.shouldShow = true; + view.detectChanges(); - var q2: NeedsQuery = view.debugElement.children[0].getLocal('q'); + var q2: NeedsQuery = view.debugElement.children[0].getLocal('q'); - expect(q2.query.length).toEqual(1); + expect(q2.query.length).toEqual(1); - async.done(); - }); + async.done(); + }); })); }); - describe('querying by var binding', () => { + describe("querying by var binding", () => { it('should contain all the child directives in the light dom with the given var binding', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query-by-var-binding #q>' + - '<div *ngFor="#item of list" [text]="item" #textLabel="textDir"></div>' + - '</needs-query-by-var-binding>'; + '<div *ngFor="#item of list" [text]="item" #textLabel="textDir"></div>' + + '</needs-query-by-var-binding>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q = view.debugElement.children[0].getLocal("q"); - view.debugElement.componentInstance.list = ['1d', '2d']; + view.debugElement.componentInstance.list = ['1d', '2d']; - view.detectChanges(); + view.detectChanges(); - expect(q.query.first.text).toEqual('1d'); - expect(q.query.last.text).toEqual('2d'); + expect(q.query.first.text).toEqual("1d"); + expect(q.query.last.text).toEqual("2d"); - async.done(); - }); + async.done(); + }); })); it('should support querying by multiple var bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query-by-var-bindings #q>' + - '<div text="one" #textLabel1="textDir"></div>' + - '<div text="two" #textLabel2="textDir"></div>' + - '</needs-query-by-var-bindings>'; + '<div text="one" #textLabel1="textDir"></div>' + + '<div text="two" #textLabel2="textDir"></div>' + + '</needs-query-by-var-bindings>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q = view.debugElement.children[0].getLocal('q'); - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q = view.debugElement.children[0].getLocal("q"); + view.detectChanges(); - expect(q.query.first.text).toEqual('one'); - expect(q.query.last.text).toEqual('two'); + expect(q.query.first.text).toEqual("one"); + expect(q.query.last.text).toEqual("two"); - async.done(); - }); + async.done(); + }); })); it('should reflect dynamically inserted directives', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query-by-var-binding #q>' + - '<div *ngFor="#item of list" [text]="item" #textLabel="textDir"></div>' + - '</needs-query-by-var-binding>'; + '<div *ngFor="#item of list" [text]="item" #textLabel="textDir"></div>' + + '</needs-query-by-var-binding>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q = view.debugElement.children[0].getLocal("q"); - view.debugElement.componentInstance.list = ['1d', '2d']; + view.debugElement.componentInstance.list = ['1d', '2d']; - view.detectChanges(); + view.detectChanges(); - view.debugElement.componentInstance.list = ['2d', '1d']; + view.debugElement.componentInstance.list = ['2d', '1d']; - view.detectChanges(); + view.detectChanges(); - expect(q.query.last.text).toEqual('1d'); + expect(q.query.last.text).toEqual("1d"); - async.done(); - }); + async.done(); + }); })); it('should contain all the elements in the light dom with the given var binding', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query-by-var-binding #q>' + - '<div template="ngFor: #item of list">' + - '<div #textLabel>{{item}}</div>' + - '</div>' + - '</needs-query-by-var-binding>'; + '<div template="ngFor: #item of list">' + + '<div #textLabel>{{item}}</div>' + + '</div>' + + '</needs-query-by-var-binding>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q = view.debugElement.children[0].getLocal("q"); - view.debugElement.componentInstance.list = ['1d', '2d']; + view.debugElement.componentInstance.list = ['1d', '2d']; - view.detectChanges(); + view.detectChanges(); - expect(q.query.first.nativeElement).toHaveText('1d'); - expect(q.query.last.nativeElement).toHaveText('2d'); + expect(q.query.first.nativeElement).toHaveText("1d"); + expect(q.query.last.nativeElement).toHaveText("2d"); - async.done(); - }); + async.done(); + }); })); it('should contain all the elements in the light dom even if they get projected', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-query-and-project #q>' + - '<div text="hello"></div><div text="world"></div>' + - '</needs-query-and-project>'; + '<div text="hello"></div><div text="world"></div>' + + '</needs-query-and-project>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); - expect(asNativeElements(view.debugElement.children)).toHaveText('hello|world|'); + expect(asNativeElements(view.debugElement.children)).toHaveText('hello|world|'); - async.done(); - }); + async.done(); + }); })); it('should support querying the view by using a view query', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query-by-var-binding #q></needs-view-query-by-var-binding>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQueryByLabel = view.debugElement.children[0].getLocal('q'); - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQueryByLabel = view.debugElement.children[0].getLocal("q"); + view.detectChanges(); - expect(q.query.first.nativeElement).toHaveText('text'); + expect(q.query.first.nativeElement).toHaveText("text"); - async.done(); - }); + async.done(); + }); })); it('should contain all child directives in the view dom', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-children #q></needs-view-children>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); - var q = view.debugElement.children[0].getLocal('q'); + var q = view.debugElement.children[0].getLocal('q'); - view.detectChanges(); + view.detectChanges(); - expect(q.textDirChildren.length).toEqual(1); - expect(q.numberOfChildrenAfterViewInit).toEqual(1); + expect(q.textDirChildren.length).toEqual(1); + expect(q.numberOfChildrenAfterViewInit).toEqual(1); - async.done(); - }); + async.done(); + }); })); }); - describe('querying in the view', () => { + describe("querying in the view", () => { it('should contain all the elements in the view with that have the given directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query #q><div text="ignoreme"></div></needs-view-query>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQuery = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQuery = view.debugElement.children[0].getLocal("q"); - view.detectChanges(); + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']); + expect(q.query.map((d: TextDirective) => d.text)).toEqual(["1", "2", "3", "4"]); - async.done(); - }); + async.done(); + }); })); it('should not include directive present on the host element', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query #q text="self"></needs-view-query>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQuery = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQuery = view.debugElement.children[0].getLocal("q"); - view.detectChanges(); + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']); + expect(q.query.map((d: TextDirective) => d.text)).toEqual(["1", "2", "3", "4"]); - async.done(); - }); + async.done(); + }); })); it('should reflect changes in the component', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query-if #q></needs-view-query-if>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQueryIf = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQueryIf = view.debugElement.children[0].getLocal("q"); - view.detectChanges(); + view.detectChanges(); - expect(q.query.length).toBe(0); + expect(q.query.length).toBe(0); - q.show = true; - view.detectChanges(); - expect(q.query.length).toBe(1); + q.show = true; + view.detectChanges(); + expect(q.query.length).toBe(1); - expect(q.query.first.text).toEqual('1'); + expect(q.query.first.text).toEqual("1"); - async.done(); - }); + async.done(); + }); })); it('should not be affected by other changes in the component', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query-nested-if #q></needs-view-query-nested-if>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQueryNestedIf = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQueryNestedIf = view.debugElement.children[0].getLocal("q"); - view.detectChanges(); + view.detectChanges(); - expect(q.query.length).toEqual(1); - expect(q.query.first.text).toEqual('1'); + expect(q.query.length).toEqual(1); + expect(q.query.first.text).toEqual("1"); - q.show = false; - view.detectChanges(); + q.show = false; + view.detectChanges(); - expect(q.query.length).toEqual(1); - expect(q.query.first.text).toEqual('1'); + expect(q.query.length).toEqual(1); + expect(q.query.first.text).toEqual("1"); - async.done(); - }); + async.done(); + }); })); @@ -510,79 +599,87 @@ export function main() { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query-order #q></needs-view-query-order>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQueryOrder = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQueryOrder = view.debugElement.children[0].getLocal("q"); - view.detectChanges(); + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']); + expect(q.query.map((d: TextDirective) => d.text)).toEqual(["1", "2", "3", "4"]); - q.list = ['-3', '2']; - view.detectChanges(); + q.list = ["-3", "2"]; + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '-3', '2', '4']); + expect(q.query.map((d: TextDirective) => d.text)).toEqual(["1", "-3", "2", "4"]); - async.done(); - }); + async.done(); + }); })); it('should maintain directives in pre-order depth-first DOM order after dynamic insertion', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query-order-with-p #q></needs-view-query-order-with-p>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQueryOrderWithParent = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQueryOrderWithParent = view.debugElement.children[0].getLocal("q"); - view.detectChanges(); + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']); + expect(q.query.map((d: TextDirective) => d.text)).toEqual(["1", "2", "3", "4"]); - q.list = ['-3', '2']; - view.detectChanges(); + q.list = ["-3", "2"]; + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '-3', '2', '4']); + expect(q.query.map((d: TextDirective) => d.text)).toEqual(["1", "-3", "2", "4"]); - async.done(); - }); + async.done(); + }); })); it('should handle long ngFor cycles', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-view-query-order #q></needs-view-query-order>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - var q: NeedsViewQueryOrder = view.debugElement.children[0].getLocal('q'); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + var q: NeedsViewQueryOrder = view.debugElement.children[0].getLocal('q'); - // no significance to 50, just a reasonably large cycle. - for (var i = 0; i < 50; i++) { - var newString = i.toString(); - q.list = [newString]; - view.detectChanges(); + // no significance to 50, just a reasonably large cycle. + for (var i = 0; i < 50; i++) { + var newString = i.toString(); + q.list = [newString]; + view.detectChanges(); - expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', newString, '4']); - } + expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', newString, '4']); + } - async.done(); - }); + async.done(); + }); })); it('should support more than three queries', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var template = '<needs-four-queries #q><div text="1"></div></needs-four-queries>'; - tcb.overrideTemplate(MyComp, template).createAsync(MyComp).then((view) => { - view.detectChanges(); + tcb.overrideTemplate(MyComp, template) + .createAsync(MyComp) + .then((view) => { + view.detectChanges(); - var q = view.debugElement.children[0].getLocal('q'); - expect(q.query1).toBeDefined(); - expect(q.query2).toBeDefined(); - expect(q.query3).toBeDefined(); - expect(q.query4).toBeDefined(); + var q = view.debugElement.children[0].getLocal('q'); + expect(q.query1).toBeDefined(); + expect(q.query2).toBeDefined(); + expect(q.query3).toBeDefined(); + expect(q.query4).toBeDefined(); - async.done(); - }); + async.done(); + }); })); }); }); @@ -625,10 +722,10 @@ class NeedsContentChild implements AfterContentInit, AfterContentChecked { get child() { return this._child; } log = []; - ngAfterContentInit() { this.log.push(['init', isPresent(this.child) ? this.child.text : null]); } + ngAfterContentInit() { this.log.push(["init", isPresent(this.child) ? this.child.text : null]); } ngAfterContentChecked() { - this.log.push(['check', isPresent(this.child) ? this.child.text : null]); + this.log.push(["check", isPresent(this.child) ? this.child.text : null]); } } @@ -653,9 +750,9 @@ class NeedsViewChild implements AfterViewInit, get child() { return this._child; } log = []; - ngAfterViewInit() { this.log.push(['init', isPresent(this.child) ? this.child.text : null]); } + ngAfterViewInit() { this.log.push(["init", isPresent(this.child) ? this.child.text : null]); } - ngAfterViewChecked() { this.log.push(['check', isPresent(this.child) ? this.child.text : null]); } + ngAfterViewChecked() { this.log.push(["check", isPresent(this.child) ? this.child.text : null]); } } @Directive({selector: '[dir]'}) @@ -700,7 +797,7 @@ class NeedsQueryDesc { @Injectable() class NeedsQueryByLabel { query: QueryList<any>; - constructor(@Query('textLabel', {descendants: true}) query: QueryList<any>) { + constructor(@Query("textLabel", {descendants: true}) query: QueryList<any>) { this.query = query; } } @@ -713,14 +810,14 @@ class NeedsQueryByLabel { @Injectable() class NeedsViewQueryByLabel { query: QueryList<any>; - constructor(@ViewQuery('textLabel') query: QueryList<any>) { this.query = query; } + constructor(@ViewQuery("textLabel") query: QueryList<any>) { this.query = query; } } @Component({selector: 'needs-query-by-var-bindings', directives: [], template: '<ng-content>'}) @Injectable() class NeedsQueryByTwoLabels { query: QueryList<any>; - constructor(@Query('textLabel1,textLabel2', {descendants: true}) query: QueryList<any>) { + constructor(@Query("textLabel1,textLabel2", {descendants: true}) query: QueryList<any>) { this.query = query; } } @@ -740,7 +837,7 @@ class NeedsQueryAndProject { selector: 'needs-view-query', directives: [TextDirective], template: '<div text="1"><div text="2"></div></div>' + - '<div text="3"></div><div text="4"></div>' + '<div text="3"></div><div text="4"></div>' }) @Injectable() class NeedsViewQuery { @@ -783,8 +880,8 @@ class NeedsViewQueryNestedIf { selector: 'needs-view-query-order', directives: [NgFor, TextDirective, InertDirective], template: '<div text="1"></div>' + - '<div *ngFor="var i of list" [text]="i"></div>' + - '<div text="4"></div>' + '<div *ngFor="var i of list" [text]="i"></div>' + + '<div text="4"></div>' }) @Injectable() class NeedsViewQueryOrder { @@ -800,8 +897,8 @@ class NeedsViewQueryOrder { selector: 'needs-view-query-order-with-p', directives: [NgFor, TextDirective, InertDirective], template: '<div dir><div text="1"></div>' + - '<div *ngFor="var i of list" [text]="i"></div>' + - '<div text="4"></div></div>' + '<div *ngFor="var i of list" [text]="i"></div>' + + '<div text="4"></div></div>' }) @Injectable() class NeedsViewQueryOrderWithParent { @@ -817,9 +914,8 @@ class NeedsViewQueryOrderWithParent { class NeedsTpl { viewQuery: QueryList<TemplateRef>; query: QueryList<TemplateRef>; - constructor( - @ViewQuery(TemplateRef) viewQuery: QueryList<TemplateRef>, - @Query(TemplateRef) query: QueryList<TemplateRef>, public vc: ViewContainerRef) { + constructor(@ViewQuery(TemplateRef) viewQuery: QueryList<TemplateRef>, + @Query(TemplateRef) query: QueryList<TemplateRef>, public vc: ViewContainerRef) { this.viewQuery = viewQuery; this.query = query; } diff --git a/modules/angular2/test/core/linker/query_list_spec.ts b/modules/angular2/test/core/linker/query_list_spec.ts index f0a3679a56..e02f309d9f 100644 --- a/modules/angular2/test/core/linker/query_list_spec.ts +++ b/modules/angular2/test/core/linker/query_list_spec.ts @@ -1,4 +1,15 @@ -import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, fakeAsync, tick} from 'angular2/testing_internal'; +import { + describe, + it, + expect, + beforeEach, + ddescribe, + iit, + xit, + el, + fakeAsync, + tick +} from 'angular2/testing_internal'; import {MapWrapper, ListWrapper, iterateListLike} from 'angular2/src/facade/collection'; import {IS_DART, StringWrapper} from 'angular2/src/facade/lang'; import {ObservableWrapper} from 'angular2/src/facade/async'; @@ -49,22 +60,22 @@ export function main() { if (!IS_DART) { it('should support filter', () => { queryList.reset(['one', 'two']); - expect((<_JsQueryList>queryList).filter((x) => x == 'one')).toEqual(['one']); + expect((<_JsQueryList>queryList).filter((x) => x == "one")).toEqual(['one']); }); it('should support reduce', () => { - queryList.reset(['one', 'two']); - expect((<_JsQueryList>queryList).reduce((a, x) => a + x, 'start:')).toEqual('start:onetwo'); + queryList.reset(["one", "two"]); + expect((<_JsQueryList>queryList).reduce((a, x) => a + x, "start:")).toEqual("start:onetwo"); }); it('should support toArray', () => { - queryList.reset(['one', 'two']); - expect((<_JsQueryList>queryList).reduce((a, x) => a + x, 'start:')).toEqual('start:onetwo'); + queryList.reset(["one", "two"]); + expect((<_JsQueryList>queryList).reduce((a, x) => a + x, "start:")).toEqual("start:onetwo"); }); it('should support toArray', () => { - queryList.reset(['one', 'two']); - expect((<_JsQueryList>queryList).toArray()).toEqual(['one', 'two']); + queryList.reset(["one", "two"]); + expect((<_JsQueryList>queryList).toArray()).toEqual(["one", "two"]); }); } @@ -102,7 +113,7 @@ export function main() { var recorded; ObservableWrapper.subscribe(queryList.changes, (v: any) => { recorded = v; }); - queryList.reset(['one']); + queryList.reset(["one"]); queryList.notifyOnChanges(); tick(); diff --git a/modules/angular2/test/core/linker/view_resolver_spec.ts b/modules/angular2/test/core/linker/view_resolver_spec.ts index 2ae36ba238..2a79078c11 100644 --- a/modules/angular2/test/core/linker/view_resolver_spec.ts +++ b/modules/angular2/test/core/linker/view_resolver_spec.ts @@ -7,29 +7,29 @@ class SomePipe {} @Component({ selector: 'sample', - template: 'some template', + template: "some template", directives: [SomeDir], pipes: [SomePipe], - styles: ['some styles'] + styles: ["some styles"] }) class ComponentWithView { } @Component({ selector: 'sample', - template: 'some template', + template: "some template", directives: [SomeDir], pipes: [SomePipe], - styles: ['some styles'] + styles: ["some styles"] }) class ComponentWithTemplate { } -@Component({selector: 'sample', template: 'some template'}) +@Component({selector: 'sample', template: "some template"}) class ComponentWithViewTemplate { } -@Component({selector: 'sample', templateUrl: 'some template url', template: 'some template'}) +@Component({selector: 'sample', templateUrl: "some template url", template: "some template"}) class ComponentWithViewTemplateUrl { } @@ -41,30 +41,31 @@ class ComponentWithoutView { class SimpleClass {} export function main() { - describe('ViewResolver', () => { + describe("ViewResolver", () => { var resolver: ViewResolver; beforeEach(() => { resolver = new ViewResolver(); }); it('should read out the View metadata from the Component metadata', () => { var viewMetadata = resolver.resolve(ComponentWithTemplate); - expect(viewMetadata).toEqual(new ViewMetadata({ - template: 'some template', - directives: [SomeDir], - pipes: [SomePipe], - styles: ['some styles'] - })); + expect(viewMetadata) + .toEqual(new ViewMetadata({ + template: "some template", + directives: [SomeDir], + pipes: [SomePipe], + styles: ["some styles"] + })); }); it('should throw when Component has no View decorator and no template is set', () => { expect(() => resolver.resolve(ComponentWithoutView)) .toThrowErrorWith( - 'Component \'ComponentWithoutView\' must have either \'template\' or \'templateUrl\' set'); + "Component 'ComponentWithoutView' must have either 'template' or 'templateUrl' set"); }); it('should throw when simple class has no View decorator and no template is set', () => { expect(() => resolver.resolve(SimpleClass)) - .toThrowErrorWith('Could not compile \'SimpleClass\' because it is not a component.'); + .toThrowErrorWith("Could not compile 'SimpleClass' because it is not a component."); }); }); } diff --git a/modules/angular2/test/core/metadata/decorators_spec.ts b/modules/angular2/test/core/metadata/decorators_spec.ts index 81fe23c626..80015ba712 100644 --- a/modules/angular2/test/core/metadata/decorators_spec.ts +++ b/modules/angular2/test/core/metadata/decorators_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {Component, Directive} from 'angular2/core'; import {reflector} from 'angular2/src/core/reflection/reflection'; diff --git a/modules/angular2/test/core/reflection/reflector_common.ts b/modules/angular2/test/core/reflection/reflector_common.ts index 3394a3b550..8bcd42f65e 100644 --- a/modules/angular2/test/core/reflection/reflector_common.ts +++ b/modules/angular2/test/core/reflection/reflector_common.ts @@ -1,4 +1,8 @@ -import {makeDecorator, makeParamDecorator, makePropDecorator} from 'angular2/src/core/util/decorators'; +import { + makeDecorator, + makeParamDecorator, + makePropDecorator +} from 'angular2/src/core/util/decorators'; export class ClassDecoratorMeta { constructor(public value) {} diff --git a/modules/angular2/test/core/reflection/reflector_spec.ts b/modules/angular2/test/core/reflection/reflector_spec.ts index d693fc7f22..bf5b295f54 100644 --- a/modules/angular2/test/core/reflection/reflector_spec.ts +++ b/modules/angular2/test/core/reflection/reflector_spec.ts @@ -1,8 +1,24 @@ -import {describe, it, iit, ddescribe, expect, beforeEach, browserDetection} from 'angular2/testing_internal'; +import { + describe, + it, + iit, + ddescribe, + expect, + beforeEach, + browserDetection +} from 'angular2/testing_internal'; import {OnInit} from 'angular2/core'; import {Reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; -import {ClassDecorator, ParamDecorator, PropDecorator, classDecorator, paramDecorator, propDecorator, HasGetterAndSetterDecorators} from './reflector_common'; +import { + ClassDecorator, + ParamDecorator, + PropDecorator, + classDecorator, + paramDecorator, + propDecorator, + HasGetterAndSetterDecorators +} from './reflector_common'; import {IS_DART} from 'angular2/src/facade/lang'; class AType { @@ -13,13 +29,14 @@ class AType { @ClassDecorator('class') class ClassWithDecorators { - @PropDecorator('p1') @PropDecorator('p2') a; + @PropDecorator("p1") @PropDecorator("p2") a; b; - @PropDecorator('p3') - set c(value) {} + @PropDecorator("p3") + set c(value) { + } - constructor(@ParamDecorator('a') a: AType, @ParamDecorator('b') b: AType) { + constructor(@ParamDecorator("a") a: AType, @ParamDecorator("b") b: AType) { this.a = a; this.b = b; } @@ -68,19 +85,19 @@ export function main() { beforeEach(() => { reflector = new Reflector(new ReflectionCapabilities()); }); - describe('usage tracking', () => { + describe("usage tracking", () => { beforeEach(() => { reflector = new Reflector(null); }); - it('should be disabled by default', () => { + it("should be disabled by default", () => { expect(() => reflector.listUnusedKeys()).toThrowError('Usage tracking is disabled'); }); - it('should report unused keys', () => { + it("should report unused keys", () => { reflector.trackUsage(); expect(reflector.listUnusedKeys()).toEqual([]); - reflector.registerType(AType, new ReflectionInfo(null, null, () => 'AType')); - reflector.registerType(TestObj, new ReflectionInfo(null, null, () => 'TestObj')); + reflector.registerType(AType, new ReflectionInfo(null, null, () => "AType")); + reflector.registerType(TestObj, new ReflectionInfo(null, null, () => "TestObj")); expect(reflector.listUnusedKeys()).toEqual([AType, TestObj]); reflector.factory(AType); @@ -91,8 +108,8 @@ export function main() { }); }); - describe('factory', () => { - it('should create a factory for the given type', () => { + describe("factory", () => { + it("should create a factory for the given type", () => { var obj = reflector.factory(TestObj)(1, 2); expect(obj.a).toEqual(1); @@ -102,7 +119,7 @@ export function main() { // Makes Edge to disconnect when running the full unit test campaign // TODO: remove when issue is solved: https://github.com/angular/angular/issues/4756 if (!browserDetection.isEdge) { - it('should check args from no to max', () => { + it("should check args from no to max", () => { var f = t => reflector.factory(t); var checkArgs = (obj, args) => expect(obj.args).toEqual(args); @@ -132,141 +149,141 @@ export function main() { }); } - it('should throw when more than 20 arguments', + it("should throw when more than 20 arguments", () => { expect(() => reflector.factory(TestObjWith21Args)).toThrowError(); }); - it('should return a registered factory if available', () => { - reflector.registerType(TestObj, new ReflectionInfo(null, null, () => 'fake')); - expect(reflector.factory(TestObj)()).toEqual('fake'); + it("should return a registered factory if available", () => { + reflector.registerType(TestObj, new ReflectionInfo(null, null, () => "fake")); + expect(reflector.factory(TestObj)()).toEqual("fake"); }); }); - describe('parameters', () => { - it('should return an array of parameters for a type', () => { + describe("parameters", () => { + it("should return an array of parameters for a type", () => { var p = reflector.parameters(ClassWithDecorators); expect(p).toEqual([[AType, paramDecorator('a')], [AType, paramDecorator('b')]]); }); - it('should work for a class without annotations', () => { + it("should work for a class without annotations", () => { var p = reflector.parameters(ClassWithoutDecorators); expect(p.length).toEqual(2); }); - it('should return registered parameters if available', () => { + it("should return registered parameters if available", () => { reflector.registerType(TestObj, new ReflectionInfo(null, [[1], [2]])); expect(reflector.parameters(TestObj)).toEqual([[1], [2]]); }); - it('should return an empty list when no parameters field in the stored type info', () => { + it("should return an empty list when no parameters field in the stored type info", () => { reflector.registerType(TestObj, new ReflectionInfo()); expect(reflector.parameters(TestObj)).toEqual([]); }); }); - describe('propMetadata', () => { - it('should return a string map of prop metadata for the given class', () => { + describe("propMetadata", () => { + it("should return a string map of prop metadata for the given class", () => { var p = reflector.propMetadata(ClassWithDecorators); - expect(p['a']).toEqual([propDecorator('p1'), propDecorator('p2')]); - expect(p['c']).toEqual([propDecorator('p3')]); + expect(p["a"]).toEqual([propDecorator("p1"), propDecorator("p2")]); + expect(p["c"]).toEqual([propDecorator("p3")]); }); - it('should return registered meta if available', () => { - reflector.registerType(TestObj, new ReflectionInfo(null, null, null, null, {'a': [1, 2]})); - expect(reflector.propMetadata(TestObj)).toEqual({'a': [1, 2]}); + it("should return registered meta if available", () => { + reflector.registerType(TestObj, new ReflectionInfo(null, null, null, null, {"a": [1, 2]})); + expect(reflector.propMetadata(TestObj)).toEqual({"a": [1, 2]}); }); if (IS_DART) { - it('should merge metadata from getters and setters', () => { + it("should merge metadata from getters and setters", () => { var p = reflector.propMetadata(HasGetterAndSetterDecorators); - expect(p['a']).toEqual([propDecorator('get'), propDecorator('set')]); + expect(p["a"]).toEqual([propDecorator("get"), propDecorator("set")]); }); } }); - describe('annotations', () => { - it('should return an array of annotations for a type', () => { + describe("annotations", () => { + it("should return an array of annotations for a type", () => { var p = reflector.annotations(ClassWithDecorators); expect(p).toEqual([classDecorator('class')]); }); - it('should return registered annotations if available', () => { + it("should return registered annotations if available", () => { reflector.registerType(TestObj, new ReflectionInfo([1, 2])); expect(reflector.annotations(TestObj)).toEqual([1, 2]); }); - it('should work for a class without annotations', () => { + it("should work for a class without annotations", () => { var p = reflector.annotations(ClassWithoutDecorators); expect(p).toEqual([]); }); }); if (IS_DART) { - describe('interfaces', () => { - it('should return an array of interfaces for a type', () => { + describe("interfaces", () => { + it("should return an array of interfaces for a type", () => { var p = reflector.interfaces(ClassImplementingInterface); expect(p).toEqual([Interface, Interface2]); }); - it('should return an empty array otherwise', () => { + it("should return an empty array otherwise", () => { var p = reflector.interfaces(ClassWithDecorators); expect(p).toEqual([]); }); - it('should throw for undeclared lifecycle interfaces', + it("should throw for undeclared lifecycle interfaces", () => { expect(() => reflector.interfaces(ClassDoesNotDeclareOnInit)).toThrowError(); }); - it('should throw for class inheriting a lifecycle impl and not declaring the interface', + it("should throw for class inheriting a lifecycle impl and not declaring the interface", () => { expect(() => reflector.interfaces(SubClassDoesNotDeclareOnInit)).toThrowError(); }); }); } - describe('getter', () => { - it('returns a function reading a property', () => { + describe("getter", () => { + it("returns a function reading a property", () => { var getA = reflector.getter('a'); expect(getA(new TestObj(1, 2))).toEqual(1); }); - it('should return a registered getter if available', () => { - reflector.registerGetters({'abc': (obj) => 'fake'}); - expect(reflector.getter('abc')('anything')).toEqual('fake'); + it("should return a registered getter if available", () => { + reflector.registerGetters({"abc": (obj) => "fake"}); + expect(reflector.getter("abc")("anything")).toEqual("fake"); }); }); - describe('setter', () => { - it('returns a function setting a property', () => { + describe("setter", () => { + it("returns a function setting a property", () => { var setA = reflector.setter('a'); var obj = new TestObj(1, 2); setA(obj, 100); expect(obj.a).toEqual(100); }); - it('should return a registered setter if available', () => { + it("should return a registered setter if available", () => { var updateMe; - reflector.registerSetters({'abc': (obj, value) => { updateMe = value; }}); - reflector.setter('abc')('anything', 'fake'); + reflector.registerSetters({"abc": (obj, value) => { updateMe = value; }}); + reflector.setter("abc")("anything", "fake"); - expect(updateMe).toEqual('fake'); + expect(updateMe).toEqual("fake"); }); }); - describe('method', () => { - it('returns a function invoking a method', () => { + describe("method", () => { + it("returns a function invoking a method", () => { var func = reflector.method('identity'); var obj = new TestObj(1, 2); expect(func(obj, ['value'])).toEqual('value'); }); - it('should return a registered method if available', () => { - reflector.registerMethods({'abc': (obj, args) => args}); - expect(reflector.method('abc')('anything', ['fake'])).toEqual(['fake']); + it("should return a registered method if available", () => { + reflector.registerMethods({"abc": (obj, args) => args}); + expect(reflector.method("abc")("anything", ["fake"])).toEqual(['fake']); }); }); if (IS_DART) { - describe('importUri', () => { - it('should return the importUri for a type', () => { + describe("importUri", () => { + it("should return the importUri for a type", () => { expect(reflector.importUri(TestObjWith00Args) .endsWith('test/core/reflection/reflector_spec.dart')) .toBe(true); @@ -337,89 +354,82 @@ class TestObjWith09Args { class TestObjWith10Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10]; } } class TestObjWith11Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11]; } } class TestObjWith12Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12]; } } class TestObjWith13Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13]; } } class TestObjWith14Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14]; } } class TestObjWith15Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15]; } } class TestObjWith16Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any, a16: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16]; } } class TestObjWith17Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17]; } } class TestObjWith18Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, + a18: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18]; } } class TestObjWith19Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, + a18: any, a19: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19]; } @@ -427,10 +437,9 @@ class TestObjWith19Args { class TestObjWith20Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any, - a20: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, + a18: any, a19: any, a20: any) { this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20]; } @@ -438,13 +447,31 @@ class TestObjWith20Args { class TestObjWith21Args { args: any[]; - constructor( - a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any, - a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any, - a20: any, a21: any) { + constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, + a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, + a18: any, a19: any, a20: any, a21: any) { this.args = [ - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, - a12, a13, a14, a15, a16, a17, a18, a19, a20, a21 + a1, + a2, + a3, + a4, + a5, + a6, + a7, + a8, + a9, + a10, + a11, + a12, + a13, + a14, + a15, + a16, + a17, + a18, + a19, + a20, + a21 ]; } } diff --git a/modules/angular2/test/core/spies.ts b/modules/angular2/test/core/spies.ts index 989ecc7eb7..03e9d9abde 100644 --- a/modules/angular2/test/core/spies.ts +++ b/modules/angular2/test/core/spies.ts @@ -1,4 +1,9 @@ -import {ChangeDetector, ChangeDetectorRef, ProtoChangeDetector, DynamicChangeDetector} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetector, + ChangeDetectorRef, + ProtoChangeDetector, + DynamicChangeDetector +} from 'angular2/src/core/change_detection/change_detection'; import {Renderer} from 'angular2/src/core/render/api'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; diff --git a/modules/angular2/test/core/testability/testability_spec.ts b/modules/angular2/test/core/testability/testability_spec.ts index 53501f9b3c..8896127db7 100644 --- a/modules/angular2/test/core/testability/testability_spec.ts +++ b/modules/angular2/test/core/testability/testability_spec.ts @@ -1,5 +1,17 @@ import {Injectable} from 'angular2/src/core/di'; -import {AsyncTestCompleter, inject, describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + describe, + ddescribe, + it, + iit, + xit, + xdescribe, + expect, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; import {Testability} from 'angular2/src/core/testability/testability'; import {NgZone} from 'angular2/src/core/zone/ng_zone'; import {normalizeBlank, scheduleMicroTask} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/test/core/util/decorators_spec.ts b/modules/angular2/test/core/util/decorators_spec.ts index 7bb5503591..0b585751a0 100644 --- a/modules/angular2/test/core/util/decorators_spec.ts +++ b/modules/angular2/test/core/util/decorators_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {makeDecorator, makeParamDecorator, Class} from 'angular2/src/core/util/decorators'; import {global} from 'angular2/src/facade/lang'; @@ -57,16 +67,19 @@ export function main() { describe('Class', () => { it('should create a class', () => { var i0, i1; - var MyClass = (<any>TestDecorator('test-works')).Class(<any>{ - extends: Class(<any>{ - constructor: function() {}, - extendWorks: function() { return 'extend ' + this.arg; } - }), - constructor: [String, function(arg) { this.arg = arg; }], - methodA: [i0 = new Inject(String), [i1 = Inject(String), Number], function(a, b) {}], - works: function() { return this.arg; }, - prototype: 'IGNORE' - }); + var MyClass = + (<any>TestDecorator('test-works')) + .Class(<any>{ + extends: Class(<any>{ + constructor: function() {}, + extendWorks: function() { return 'extend ' + this.arg; } + }), + constructor: [String, function(arg) { this.arg = arg; }], + methodA: + [i0 = new Inject(String), [i1 = Inject(String), Number], function(a, b) {}], + works: function() { return this.arg; }, + prototype: 'IGNORE' + }); var obj: any = new MyClass('WORKS'); expect(obj.arg).toEqual('WORKS'); expect(obj.works()).toEqual('WORKS'); @@ -85,39 +98,38 @@ export function main() { it('should ensure that last constructor is required', () => { expect(() => { (<Function>Class)({}); }) .toThrowError( - 'Only Function or Array is supported in Class definition for key \'constructor\' is \'undefined\''); + "Only Function or Array is supported in Class definition for key 'constructor' is 'undefined'"); }); it('should ensure that we dont accidently patch native objects', () => { - expect(() => { - (<Function>Class)({constructor: Object}); - }).toThrowError('Can not use native Object as constructor'); + expect(() => { (<Function>Class)({constructor: Object}); }) + .toThrowError("Can not use native Object as constructor"); }); it('should ensure that last position is function', () => { expect(() => {Class({constructor: []})}) .toThrowError( - 'Last position of Class method array must be Function in key constructor was \'undefined\''); + "Last position of Class method array must be Function in key constructor was 'undefined'"); }); it('should ensure that annotation count matches parameters count', () => { expect(() => {Class({constructor: [String, function MyType() {}]})}) .toThrowError( - 'Number of annotations (1) does not match number of arguments (0) in the function: MyType'); + "Number of annotations (1) does not match number of arguments (0) in the function: MyType"); }); it('should ensure that only Function|Arrays are supported', () => { expect(() => { Class(<any>{constructor: function() {}, method: 'non_function'}); }) .toThrowError( - 'Only Function or Array is supported in Class definition for key \'method\' is \'non_function\''); + "Only Function or Array is supported in Class definition for key 'method' is 'non_function'"); }); it('should ensure that extends is a Function', () => { expect(() => {(<Function>Class)({extends: 'non_type', constructor: function() {}})}) .toThrowError( - 'Class definition \'extends\' property must be a constructor function was: non_type'); + "Class definition 'extends' property must be a constructor function was: non_type"); }); }); }); diff --git a/modules/angular2/test/core/zone/ng_zone_spec.ts b/modules/angular2/test/core/zone/ng_zone_spec.ts index 2f7572dec8..56829bdb02 100644 --- a/modules/angular2/test/core/zone/ng_zone_spec.ts +++ b/modules/angular2/test/core/zone/ng_zone_spec.ts @@ -1,6 +1,24 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit, Log, browserDetection} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit, + Log, + browserDetection +} from 'angular2/testing_internal'; -import {PromiseCompleter, PromiseWrapper, TimerWrapper, ObservableWrapper} from 'angular2/src/facade/async'; +import { + PromiseCompleter, + PromiseWrapper, + TimerWrapper, + ObservableWrapper +} from 'angular2/src/facade/async'; import {BaseException} from 'angular2/src/facade/exceptions'; import {IS_DART, scheduleMicroTask, isPresent} from 'angular2/src/facade/lang'; @@ -50,7 +68,7 @@ function runNgZoneNoLog(fn: () => any) { } export function main() { - describe('NgZone', () => { + describe("NgZone", () => { function createZone(enableLongStackTrace) { return new NgZone({enableLongStackTrace: enableLongStackTrace}); @@ -103,7 +121,7 @@ export function main() { scheduleMicroTask(() => { scheduleMicroTask(() => { c.resolve(null); - throw new BaseException('ddd'); + throw new BaseException("ddd"); }); }); }); @@ -228,9 +246,8 @@ function commonTests() { macroTask(() => { expect(_log.result()) - .toEqual( - 'onUnstable; run; onMicrotaskEmpty; onMicrotaskEmpty 1; ' + - 'onMicrotaskEmpty; onMicrotaskEmpty 2; onStable'); + .toEqual('onUnstable; run; onMicrotaskEmpty; onMicrotaskEmpty 1; ' + + 'onMicrotaskEmpty; onMicrotaskEmpty 2; onStable'); async.done(); }, resultTimer); }), testTimeout); @@ -297,9 +314,8 @@ function commonTests() { macroTask(() => { expect(_log.result()) - .toEqual( - 'onUnstable; run; onMicrotaskEmpty; onMyMicrotaskEmpty; ' + - 'onMicrotaskEmpty; onMyMicrotaskEmpty; onStable'); + .toEqual('onUnstable; run; onMicrotaskEmpty; onMyMicrotaskEmpty; ' + + 'onMicrotaskEmpty; onMyMicrotaskEmpty; onStable'); async.done(); }, resultTimer); }), testTimeout); @@ -661,9 +677,8 @@ function commonTests() { macroTask(() => { expect(_log.result()) - .toEqual( - 'onUnstable; zone run; onMicrotaskEmpty; onStable; ' + - 'onUnstable; promise then; onMicrotaskEmpty; onStable'); + .toEqual('onUnstable; zone run; onMicrotaskEmpty; onStable; ' + + 'onUnstable; promise then; onMicrotaskEmpty; onStable'); async.done(); }, resultTimer); }), testTimeout); diff --git a/modules/angular2/test/dev_mode_spec.ts b/modules/angular2/test/dev_mode_spec.ts index 989a20aee3..08879ee819 100644 --- a/modules/angular2/test/dev_mode_spec.ts +++ b/modules/angular2/test/dev_mode_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {assertionsEnabled, IS_DART} from 'angular2/src/facade/lang'; @@ -13,7 +24,7 @@ export function main() { try { var s: string = <any>42; expect(s).toEqual(42); // without it, dart analyzer will complain that `s` is not used. - throw 'should not be reached'; + throw "should not be reached"; } catch (e) { } }); diff --git a/modules/angular2/test/facade/async_spec.ts b/modules/angular2/test/facade/async_spec.ts index c204b1f5f0..bed3b08408 100644 --- a/modules/angular2/test/facade/async_spec.ts +++ b/modules/angular2/test/facade/async_spec.ts @@ -1,6 +1,25 @@ -import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, SpyObject, AsyncTestCompleter, inject, browserDetection} from 'angular2/testing_internal'; +import { + describe, + it, + expect, + beforeEach, + ddescribe, + iit, + xit, + el, + SpyObject, + AsyncTestCompleter, + inject, + browserDetection +} from 'angular2/testing_internal'; -import {ObservableWrapper, Observable, Subject, EventEmitter, PromiseWrapper} from 'angular2/src/facade/async'; +import { + ObservableWrapper, + Observable, + Subject, + EventEmitter, + PromiseWrapper +} from 'angular2/src/facade/async'; export function main() { describe('EventEmitter', () => { @@ -8,7 +27,7 @@ export function main() { beforeEach(() => { emitter = new EventEmitter(); }); - it('should call the next callback', inject([AsyncTestCompleter], (async) => { + it("should call the next callback", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(emitter, (value) => { expect(value).toEqual(99); async.done(); @@ -17,26 +36,26 @@ export function main() { ObservableWrapper.callEmit(emitter, 99); })); - it('should call the throw callback', inject([AsyncTestCompleter], (async) => { + it("should call the throw callback", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(emitter, (_) => {}, (error) => { - expect(error).toEqual('Boom'); + expect(error).toEqual("Boom"); async.done(); }); - ObservableWrapper.callError(emitter, 'Boom'); + ObservableWrapper.callError(emitter, "Boom"); })); - it('should work when no throw callback is provided', inject([AsyncTestCompleter], (async) => { + it("should work when no throw callback is provided", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(emitter, (_) => {}, (_) => { async.done(); }); - ObservableWrapper.callError(emitter, 'Boom'); + ObservableWrapper.callError(emitter, "Boom"); })); - it('should call the return callback', inject([AsyncTestCompleter], (async) => { + it("should call the return callback", inject([AsyncTestCompleter], (async) => { ObservableWrapper.subscribe(emitter, (_) => {}, (_) => {}, () => { async.done(); }); ObservableWrapper.callComplete(emitter); })); - it('should subscribe to the wrapper asynchronously', () => { + it("should subscribe to the wrapper asynchronously", () => { var called = false; ObservableWrapper.subscribe(emitter, (value) => { called = true; }); @@ -47,19 +66,18 @@ export function main() { // Makes Edge to disconnect when running the full unit test campaign // TODO: remove when issue is solved: https://github.com/angular/angular/issues/4756 if (!browserDetection.isEdge) { - it('delivers next and error events asynchronously', inject([AsyncTestCompleter], (async) => { + it("delivers next and error events asynchronously", inject([AsyncTestCompleter], (async) => { let log = []; - ObservableWrapper.subscribe( - emitter, - (x) => { - log.push(x); - expect(log).toEqual([1, 3, 5, 2]); - }, - (err) => { - log.push(err); - expect(log).toEqual([1, 3, 5, 2, 4]); - async.done(); - }); + ObservableWrapper.subscribe(emitter, + (x) => { + log.push(x); + expect(log).toEqual([1, 3, 5, 2]); + }, + (err) => { + log.push(err); + expect(log).toEqual([1, 3, 5, 2, 4]); + async.done(); + }); log.push(1); ObservableWrapper.callEmit(emitter, 2); log.push(3); @@ -67,21 +85,19 @@ export function main() { log.push(5); })); - it('delivers next and complete events asynchronously', + it("delivers next and complete events asynchronously", inject([AsyncTestCompleter], (async) => { let log = []; - ObservableWrapper.subscribe( - emitter, - (x) => { - log.push(x); - expect(log).toEqual([1, 3, 5, 2]); - }, - null, - () => { - log.push(4); - expect(log).toEqual([1, 3, 5, 2, 4]); - async.done(); - }); + ObservableWrapper.subscribe(emitter, + (x) => { + log.push(x); + expect(log).toEqual([1, 3, 5, 2]); + }, + null, () => { + log.push(4); + expect(log).toEqual([1, 3, 5, 2, 4]); + async.done(); + }); log.push(1); ObservableWrapper.callEmit(emitter, 2); log.push(3); @@ -113,7 +129,7 @@ export function main() { // should call dispose on the subscription on return }); - describe('ObservableWrapper', () => { + describe("ObservableWrapper", () => { it('should correctly check isObservable for EventEmitter', () => { var e = new EventEmitter(false); @@ -137,9 +153,9 @@ export function main() { }); // See ECMAScript 6 Spec 25.4.4.1 - describe('PromiseWrapper', () => { - describe('#all', () => { - it('should combine lists of Promises', inject([AsyncTestCompleter], (async) => { + describe("PromiseWrapper", () => { + describe("#all", () => { + it("should combine lists of Promises", inject([AsyncTestCompleter], (async) => { var one = PromiseWrapper.completer(); var two = PromiseWrapper.completer(); diff --git a/modules/angular2/test/facade/collection_spec.ts b/modules/angular2/test/facade/collection_spec.ts index c23b37f149..0123e38f79 100644 --- a/modules/angular2/test/facade/collection_spec.ts +++ b/modules/angular2/test/facade/collection_spec.ts @@ -47,19 +47,16 @@ export function main() { describe('slice', () => { beforeEach(() => { l = [1, 2, 3, 4]; }); - it('should return the whole list if neither start nor end are specified', () => { - expect(ListWrapper.slice(l)).toEqual([1, 2, 3, 4]); - }); + it('should return the whole list if neither start nor end are specified', + () => { expect(ListWrapper.slice(l)).toEqual([1, 2, 3, 4]); }); - it('should return up to the end if end is not specified', () => { - expect(ListWrapper.slice(l, 1)).toEqual([2, 3, 4]); - }); + it('should return up to the end if end is not specified', + () => { expect(ListWrapper.slice(l, 1)).toEqual([2, 3, 4]); }); it('should support negative start', () => { expect(ListWrapper.slice(l, -1)).toEqual([4]); }); - it('should support negative end', () => { - expect(ListWrapper.slice(l, -3, -1)).toEqual([2, 3]); - }); + it('should support negative end', + () => { expect(ListWrapper.slice(l, -3, -1)).toEqual([2, 3]); }); it('should return empty list if start is greater than end', () => { expect(ListWrapper.slice(l, 4, 2)).toEqual([]); @@ -80,17 +77,14 @@ export function main() { }); describe('maximum', () => { - it('should return the maximal element', () => { - expect(ListWrapper.maximum([1, 2, 3, 4], x => x)).toEqual(4); - }); + it('should return the maximal element', + () => { expect(ListWrapper.maximum([1, 2, 3, 4], x => x)).toEqual(4); }); - it('should ignore null values', () => { - expect(ListWrapper.maximum([null, 2, 3, null], x => x)).toEqual(3); - }); + it('should ignore null values', + () => { expect(ListWrapper.maximum([null, 2, 3, null], x => x)).toEqual(3); }); - it('should use the provided function to determine maximum', () => { - expect(ListWrapper.maximum([1, 2, 3, 4], x => -x)).toEqual(1); - }); + it('should use the provided function to determine maximum', + () => { expect(ListWrapper.maximum([1, 2, 3, 4], x => -x)).toEqual(1); }); it('should return null for an empty list', () => { expect(ListWrapper.maximum([], x => x)).toEqual(null); }); @@ -99,12 +93,12 @@ export function main() { describe('forEachWithIndex', () => { var l; - beforeEach(() => { l = ['a', 'b']; }); + beforeEach(() => { l = ["a", "b"]; }); it('should iterate over an array passing values and indices', () => { var record = []; ListWrapper.forEachWithIndex(l, (value, index) => record.push([value, index])); - expect(record).toEqual([['a', 0], ['b', 1]]); + expect(record).toEqual([["a", 0], ["b", 1]]); }); }); }); diff --git a/modules/angular2/test/facade/exception_handler_spec.ts b/modules/angular2/test/facade/exception_handler_spec.ts index 35633f11bc..753c974333 100644 --- a/modules/angular2/test/facade/exception_handler_spec.ts +++ b/modules/angular2/test/facade/exception_handler_spec.ts @@ -1,80 +1,92 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit, Log} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit, + Log +} from 'angular2/testing_internal'; import {BaseException, WrappedException, ExceptionHandler} from 'angular2/src/facade/exceptions'; class _CustomException { - context = 'some context'; - toString(): string { return 'custom'; } + context = "some context"; + toString(): string { return "custom"; } } export function main() { describe('ExceptionHandler', () => { - it('should output exception', () => { - var e = ExceptionHandler.exceptionToString(new BaseException('message!')); - expect(e).toContain('message!'); + it("should output exception", () => { + var e = ExceptionHandler.exceptionToString(new BaseException("message!")); + expect(e).toContain("message!"); }); - it('should output stackTrace', () => { - var e = ExceptionHandler.exceptionToString(new BaseException('message!'), 'stack!'); - expect(e).toContain('stack!'); + it("should output stackTrace", () => { + var e = ExceptionHandler.exceptionToString(new BaseException("message!"), "stack!"); + expect(e).toContain("stack!"); }); - it('should join a long stackTrace', () => { + it("should join a long stackTrace", () => { var e = - ExceptionHandler.exceptionToString(new BaseException('message!'), ['stack1', 'stack2']); - expect(e).toContain('stack1'); - expect(e).toContain('stack2'); + ExceptionHandler.exceptionToString(new BaseException("message!"), ["stack1", "stack2"]); + expect(e).toContain("stack1"); + expect(e).toContain("stack2"); }); - it('should output reason when present', () => { - var e = ExceptionHandler.exceptionToString(new BaseException('message!'), null, 'reason!'); - expect(e).toContain('reason!'); + it("should output reason when present", () => { + var e = ExceptionHandler.exceptionToString(new BaseException("message!"), null, "reason!"); + expect(e).toContain("reason!"); }); - describe('context', () => { - it('should print context', () => { + describe("context", () => { + it("should print context", () => { var e = ExceptionHandler.exceptionToString( - new WrappedException('message!', null, null, 'context!')); - expect(e).toContain('context!'); + new WrappedException("message!", null, null, "context!")); + expect(e).toContain("context!"); }); - it('should print nested context', () => { - var original = new WrappedException('message!', null, null, 'context!'); - var e = ExceptionHandler.exceptionToString(new WrappedException('message', original)); - expect(e).toContain('context!'); + it("should print nested context", () => { + var original = new WrappedException("message!", null, null, "context!"); + var e = ExceptionHandler.exceptionToString(new WrappedException("message", original)); + expect(e).toContain("context!"); }); - it('should not print context when the passed-in exception is not a BaseException', () => { + it("should not print context when the passed-in exception is not a BaseException", () => { var e = ExceptionHandler.exceptionToString(new _CustomException()); - expect(e).not.toContain('context'); + expect(e).not.toContain("context"); }); }); describe('original exception', () => { - it('should print original exception message if available (original is BaseException)', () => { - var realOriginal = new BaseException('inner'); - var original = new WrappedException('wrapped', realOriginal); + it("should print original exception message if available (original is BaseException)", () => { + var realOriginal = new BaseException("inner"); + var original = new WrappedException("wrapped", realOriginal); var e = - ExceptionHandler.exceptionToString(new WrappedException('wrappedwrapped', original)); - expect(e).toContain('inner'); + ExceptionHandler.exceptionToString(new WrappedException("wrappedwrapped", original)); + expect(e).toContain("inner"); }); - it('should print original exception message if available (original is not BaseException)', + it("should print original exception message if available (original is not BaseException)", () => { var realOriginal = new _CustomException(); - var original = new WrappedException('wrapped', realOriginal); + var original = new WrappedException("wrapped", realOriginal); var e = - ExceptionHandler.exceptionToString(new WrappedException('wrappedwrapped', original)); - expect(e).toContain('custom'); + ExceptionHandler.exceptionToString(new WrappedException("wrappedwrapped", original)); + expect(e).toContain("custom"); }); }); describe('original stack', () => { - it('should print original stack if available', () => { - var realOriginal = new BaseException('inner'); - var original = new WrappedException('wrapped', realOriginal, 'originalStack'); + it("should print original stack if available", () => { + var realOriginal = new BaseException("inner"); + var original = new WrappedException("wrapped", realOriginal, "originalStack"); var e = ExceptionHandler.exceptionToString( - new WrappedException('wrappedwrapped', original, 'wrappedStack')); - expect(e).toContain('originalStack'); + new WrappedException("wrappedwrapped", original, "wrappedStack")); + expect(e).toContain("originalStack"); }); }); }); diff --git a/modules/angular2/test/facade/lang_spec.ts b/modules/angular2/test/facade/lang_spec.ts index fba6671123..4caef71444 100644 --- a/modules/angular2/test/facade/lang_spec.ts +++ b/modules/angular2/test/facade/lang_spec.ts @@ -1,5 +1,13 @@ import {describe, it, expect, beforeEach, ddescribe, iit, xit, el} from 'angular2/testing_internal'; -import {isPresent, RegExpWrapper, RegExpMatcherWrapper, StringWrapper, CONST_EXPR, hasConstructor, resolveEnumToken} from 'angular2/src/facade/lang'; +import { + isPresent, + RegExpWrapper, + RegExpMatcherWrapper, + StringWrapper, + CONST_EXPR, + hasConstructor, + resolveEnumToken +} from 'angular2/src/facade/lang'; enum UsefulEnum { MyToken, @@ -29,13 +37,13 @@ export function main() { it('should reset before it is reused', () => { var re = /^['"]/g; - var str = '\''; + var str = "'"; expect(RegExpWrapper.test(re, str)).toEqual(true); // If not reset, the second attempt to test results in false expect(RegExpWrapper.test(re, str)).toEqual(true); }); - it('should implement replace all', () => { + it("should implement replace all", () => { let re = /(\d)+/g; let m = RegExpWrapper.replaceAll(re, 'a1b2c', (match) => `!${match[1]}!`); expect(m).toEqual('a!1!b!2!c'); @@ -53,83 +61,83 @@ export function main() { var s; describe('slice', () => { - beforeEach(() => { s = 'abcdefghij'; }); + beforeEach(() => { s = "abcdefghij"; }); it('should return the whole string if neither start nor end are specified', - () => { expect(StringWrapper.slice(s)).toEqual('abcdefghij'); }); + () => { expect(StringWrapper.slice(s)).toEqual("abcdefghij"); }); it('should return up to the end if end is not specified', - () => { expect(StringWrapper.slice(s, 1)).toEqual('bcdefghij'); }); + () => { expect(StringWrapper.slice(s, 1)).toEqual("bcdefghij"); }); it('should support negative start', - () => { expect(StringWrapper.slice(s, -1)).toEqual('j'); }); + () => { expect(StringWrapper.slice(s, -1)).toEqual("j"); }); it('should support negative end', - () => { expect(StringWrapper.slice(s, -3, -1)).toEqual('hi'); }); + () => { expect(StringWrapper.slice(s, -3, -1)).toEqual("hi"); }); it('should return empty string if start is greater than end', () => { - expect(StringWrapper.slice(s, 4, 2)).toEqual(''); - expect(StringWrapper.slice(s, -2, -4)).toEqual(''); + expect(StringWrapper.slice(s, 4, 2)).toEqual(""); + expect(StringWrapper.slice(s, -2, -4)).toEqual(""); }); }); describe('stripLeft', () => { it('should strip the first character of the string if it matches the provided input', () => { - var input = '~angular2 is amazing'; - var expectedOutput = 'angular2 is amazing'; + var input = "~angular2 is amazing"; + var expectedOutput = "angular2 is amazing"; - expect(StringWrapper.stripLeft(input, '~')).toEqual(expectedOutput); + expect(StringWrapper.stripLeft(input, "~")).toEqual(expectedOutput); }); it('should keep stripping characters from the start until the first unmatched character', () => { - var input = '#####hello'; - var expectedOutput = 'hello'; - expect(StringWrapper.stripLeft(input, '#')).toEqual(expectedOutput); + var input = "#####hello"; + var expectedOutput = "hello"; + expect(StringWrapper.stripLeft(input, "#")).toEqual(expectedOutput); }); it('should not alter the provided input if the first character does not match the provided input', () => { - var input = '+angular2 is amazing'; - expect(StringWrapper.stripLeft(input, '*')).toEqual(input); + var input = "+angular2 is amazing"; + expect(StringWrapper.stripLeft(input, "*")).toEqual(input); }); it('should not do any alterations when an empty string or null value is passed in', () => { - expect(StringWrapper.stripLeft('', 'S')).toEqual(''); - expect(StringWrapper.stripLeft(null, 'S')).toEqual(null); + expect(StringWrapper.stripLeft("", "S")).toEqual(""); + expect(StringWrapper.stripLeft(null, "S")).toEqual(null); }); }); describe('stripRight', () => { it('should strip the first character of the string if it matches the provided input', () => { - var input = 'angular2 is amazing!'; - var expectedOutput = 'angular2 is amazing'; + var input = "angular2 is amazing!"; + var expectedOutput = "angular2 is amazing"; - expect(StringWrapper.stripRight(input, '!')).toEqual(expectedOutput); + expect(StringWrapper.stripRight(input, "!")).toEqual(expectedOutput); }); it('should not alter the provided input if the first character does not match the provided input', () => { - var input = 'angular2 is amazing+'; + var input = "angular2 is amazing+"; - expect(StringWrapper.stripRight(input, '*')).toEqual(input); + expect(StringWrapper.stripRight(input, "*")).toEqual(input); }); it('should keep stripping characters from the end until the first unmatched character', () => { - var input = 'hi&!&&&&&'; - var expectedOutput = 'hi&!'; - expect(StringWrapper.stripRight(input, '&')).toEqual(expectedOutput); + var input = "hi&!&&&&&"; + var expectedOutput = "hi&!"; + expect(StringWrapper.stripRight(input, "&")).toEqual(expectedOutput); }); it('should not do any alterations when an empty string or null value is passed in', () => { - expect(StringWrapper.stripRight('', 'S')).toEqual(''); - expect(StringWrapper.stripRight(null, 'S')).toEqual(null); + expect(StringWrapper.stripRight("", "S")).toEqual(""); + expect(StringWrapper.stripRight(null, "S")).toEqual(null); }); }); describe('resolveEnumToken', () => { - it('should resolve a token given an enum and index values', () => { + it("should resolve a token given an enum and index values", () => { var token = UsefulEnum.MyToken; expect(resolveEnumToken(UsefulEnum, token)).toEqual('MyToken'); @@ -139,10 +147,10 @@ export function main() { }); describe('hasConstructor', () => { - it('should be true when the type matches', + it("should be true when the type matches", () => { expect(hasConstructor(new MySuperclass(), MySuperclass)).toEqual(true); }); - it('should be false for subtypes', + it("should be false for subtypes", () => { expect(hasConstructor(new MySubclass(), MySuperclass)).toEqual(false); }); }); }); diff --git a/modules/angular2/test/http/backends/jsonp_backend_spec.ts b/modules/angular2/test/http/backends/jsonp_backend_spec.ts index 5aadd16463..878ee2bb15 100644 --- a/modules/angular2/test/http/backends/jsonp_backend_spec.ts +++ b/modules/angular2/test/http/backends/jsonp_backend_spec.ts @@ -1,7 +1,24 @@ -import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + afterEach, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, + SpyObject +} from 'angular2/testing_internal'; import {ObservableWrapper} from 'angular2/src/facade/async'; import {BrowserJsonp} from 'angular2/src/http/backends/browser_jsonp'; -import {JSONPConnection, JSONPConnection_, JSONPBackend, JSONPBackend_} from 'angular2/src/http/backends/jsonp_backend'; +import { + JSONPConnection, + JSONPConnection_, + JSONPBackend, + JSONPBackend_ +} from 'angular2/src/http/backends/jsonp_backend'; import {provide, Injector} from 'angular2/core'; import {isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {TimerWrapper} from 'angular2/src/facade/async'; @@ -76,9 +93,8 @@ export function main() { describe('JSONPConnection', () => { it('should use the injected BaseResponseOptions to create the response', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - let connection = new JSONPConnection_( - sampleRequest, new MockBrowserJsonp(), - new ResponseOptions({type: ResponseType.Error})); + let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp(), + new ResponseOptions({type: ResponseType.Error})); connection.response.subscribe(res => { expect(res.type).toBe(ResponseType.Error); async.done(); @@ -115,7 +131,7 @@ export function main() { let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp()); connection.response.subscribe( res => { - expect('response listener called').toBe(false); + expect("response listener called").toBe(false); async.done(); }, err => { @@ -132,7 +148,7 @@ export function main() { connection.response.subscribe( res => { - expect('response listener called').toBe(false); + expect("response listener called").toBe(false); async.done(); }, err => { @@ -140,7 +156,7 @@ export function main() { async.done(); }); - existingScripts[0].dispatchEvent('error', ({message: 'Oops!'})); + existingScripts[0].dispatchEvent('error', ({message: "Oops!"})); })); it('should throw if request method is not GET', () => { diff --git a/modules/angular2/test/http/backends/mock_backend_spec.ts b/modules/angular2/test/http/backends/mock_backend_spec.ts index 89987d1c18..9276a4743c 100644 --- a/modules/angular2/test/http/backends/mock_backend_spec.ts +++ b/modules/angular2/test/http/backends/mock_backend_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + afterEach, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, + SpyObject +} from 'angular2/testing_internal'; import {ObservableWrapper} from 'angular2/src/facade/async'; import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr'; import {MockConnection, MockBackend} from 'angular2/src/http/backends/mock_backend'; @@ -96,8 +108,8 @@ export function main() { let responseObservable: ReplaySubject<Response> = backend.createConnection(sampleRequest1).response; responseObservable.subscribe(res => expect(res.text()).toBe('response1')); - responseObservable.subscribe( - res => expect(res.text()).toBe('response2'), null, async.done); + responseObservable.subscribe(res => expect(res.text()).toBe('response2'), null, + async.done); })); // TODO(robwormald): readyStates are leaving? diff --git a/modules/angular2/test/http/backends/xhr_backend_spec.ts b/modules/angular2/test/http/backends/xhr_backend_spec.ts index b000e00e66..d7542c9b84 100644 --- a/modules/angular2/test/http/backends/xhr_backend_spec.ts +++ b/modules/angular2/test/http/backends/xhr_backend_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + afterEach, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, + SpyObject +} from 'angular2/testing_internal'; import {ObservableWrapper} from 'angular2/src/facade/async'; import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr'; import {XHRConnection, XHRBackend} from 'angular2/src/http/backends/xhr_backend'; @@ -76,7 +88,8 @@ export function main() { beforeEach(() => { var injector = Injector.resolveAndCreate([ provide(ResponseOptions, {useClass: BaseResponseOptions}), - provide(BrowserXhr, {useClass: MockBrowserXHR}), XHRBackend + provide(BrowserXhr, {useClass: MockBrowserXHR}), + XHRBackend ]); backend = injector.get(XHRBackend); var base = new BaseRequestOptions(); @@ -92,9 +105,8 @@ export function main() { describe('XHRConnection', () => { it('should use the injected BaseResponseOptions to create the response', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), - new ResponseOptions({type: ResponseType.Error})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({type: ResponseType.Error})); connection.response.subscribe((res: Response) => { expect(res.type).toBe(ResponseType.Error); async.done(); @@ -104,12 +116,11 @@ export function main() { })); it('should complete a request', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), - new ResponseOptions({type: ResponseType.Error})); - connection.response.subscribe( - (res: Response) => { expect(res.type).toBe(ResponseType.Error); }, null, - () => { async.done(); }); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({type: ResponseType.Error})); + connection.response.subscribe((res: Response) => { + expect(res.type).toBe(ResponseType.Error); + }, null, () => { async.done(); }); existingXHRs[0].setStatusCode(200); existingXHRs[0].dispatchEvent('load'); })); @@ -123,9 +134,8 @@ export function main() { it('should create an error Response on error', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), - new ResponseOptions({type: ResponseType.Error})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({type: ResponseType.Error})); connection.response.subscribe(null, (res: Response) => { expect(res.type).toBe(ResponseType.Error); async.done(); @@ -167,8 +177,8 @@ export function main() { it('should return the correct status code', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var statusCode = 418; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); connection.response.subscribe( (res: Response) => { @@ -188,16 +198,15 @@ export function main() { var nextCalled = false; var errorCalled = false; var statusCode = 200; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); connection.response.subscribe( (res: Response) => { nextCalled = true; expect(res.status).toBe(statusCode); }, - errRes => { errorCalled = true; }, - () => { + errRes => { errorCalled = true; }, () => { expect(nextCalled).toBe(true); expect(errorCalled).toBe(false); async.done(); @@ -212,17 +221,14 @@ export function main() { var nextCalled = false; var errorCalled = false; var statusCode = 301; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); - connection.response.subscribe( - (res: Response) => { nextCalled = true; }, - errRes => { - expect(errRes.status).toBe(statusCode); - expect(nextCalled).toBe(false); - async.done(); - }, - () => { throw 'should not be called'; }); + connection.response.subscribe((res: Response) => { nextCalled = true; }, errRes => { + expect(errRes.status).toBe(statusCode); + expect(nextCalled).toBe(false); + async.done(); + }, () => { throw 'should not be called'; }); existingXHRs[0].setStatusCode(statusCode); existingXHRs[0].dispatchEvent('load'); @@ -231,8 +237,8 @@ export function main() { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var statusCode = 1223; var normalizedCode = 204; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); connection.response.subscribe((res: Response) => { expect(res.status).toBe(normalizedCode); @@ -272,8 +278,8 @@ export function main() { it('should parse response headers and add them to the response', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var statusCode = 200; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); let responseHeaderString = `Date: Fri, 20 Nov 2015 01:45:26 GMT @@ -297,8 +303,8 @@ export function main() { it('should add the responseURL to the response', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var statusCode = 200; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); connection.response.subscribe((res: Response) => { expect(res.url).toEqual('http://google.com'); @@ -313,8 +319,8 @@ export function main() { it('should add use the X-Request-URL in CORS situations', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var statusCode = 200; - var connection = new XHRConnection( - sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); + var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), + new ResponseOptions({status: statusCode})); var responseHeaders = `X-Request-URL: http://somedomain.com Foo: Bar` diff --git a/modules/angular2/test/http/base_request_options_spec.ts b/modules/angular2/test/http/base_request_options_spec.ts index 2bfaa4025d..6b9b8174be 100644 --- a/modules/angular2/test/http/base_request_options_spec.ts +++ b/modules/angular2/test/http/base_request_options_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; import {BaseRequestOptions, RequestOptions} from 'angular2/src/http/base_request_options'; import {RequestMethod} from 'angular2/src/http/enums'; diff --git a/modules/angular2/test/http/headers_spec.ts b/modules/angular2/test/http/headers_spec.ts index f8d8043017..6b2d5216bf 100644 --- a/modules/angular2/test/http/headers_spec.ts +++ b/modules/angular2/test/http/headers_spec.ts @@ -1,7 +1,17 @@ import {Headers} from 'angular2/src/http/headers'; import {Json} from 'angular2/src/facade/lang'; import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; export function main() { describe('Headers', () => { diff --git a/modules/angular2/test/http/http_spec.ts b/modules/angular2/test/http/http_spec.ts index 770b065a35..8112ab2512 100644 --- a/modules/angular2/test/http/http_spec.ts +++ b/modules/angular2/test/http/http_spec.ts @@ -1,7 +1,33 @@ -import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + afterEach, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; import {Injector, provide} from 'angular2/core'; import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend'; -import {BaseRequestOptions, ConnectionBackend, Request, RequestMethod, RequestOptions, Response, ResponseOptions, URLSearchParams, JSONP_PROVIDERS, HTTP_PROVIDERS, XHRBackend, JSONPBackend, Http, Jsonp} from 'angular2/http'; +import { + BaseRequestOptions, + ConnectionBackend, + Request, + RequestMethod, + RequestOptions, + Response, + ResponseOptions, + URLSearchParams, + JSONP_PROVIDERS, + HTTP_PROVIDERS, + XHRBackend, + JSONPBackend, + Http, + Jsonp +} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; @@ -23,7 +49,9 @@ export function main() { ]); childInjector = parentInjector.resolveAndCreateChild([ - HTTP_PROVIDERS, JSONP_PROVIDERS, provide(XHRBackend, {useClass: MockBackend}), + HTTP_PROVIDERS, + JSONP_PROVIDERS, + provide(XHRBackend, {useClass: MockBackend}), provide(JSONPBackend, {useClass: MockBackend}) ]); @@ -67,18 +95,24 @@ export function main() { var jsonp: Jsonp; beforeEach(() => { injector = Injector.resolveAndCreate([ - BaseRequestOptions, MockBackend, provide(Http, { - useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) { - return new Http(backend, defaultOptions); - }, - deps: [MockBackend, BaseRequestOptions] - }), - provide(Jsonp, { - useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) { - return new Jsonp(backend, defaultOptions); - }, - deps: [MockBackend, BaseRequestOptions] - }) + BaseRequestOptions, + MockBackend, + provide( + Http, + { + useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) { + return new Http(backend, defaultOptions); + }, + deps: [MockBackend, BaseRequestOptions] + }), + provide( + Jsonp, + { + useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) { + return new Jsonp(backend, defaultOptions); + }, + deps: [MockBackend, BaseRequestOptions] + }) ]); http = injector.get(Http); jsonp = injector.get(Jsonp); @@ -122,10 +156,11 @@ export function main() { it('should perform a get request for given url if only passed a string', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse)); - http.request('http://basic.connection').subscribe((res: Response) => { - expect(res.text()).toBe('base response'); - async.done(); - }); + http.request('http://basic.connection') + .subscribe((res: Response) => { + expect(res.text()).toBe('base response'); + async.done(); + }); })); it('should perform a post request for given url if options include a method', @@ -135,10 +170,11 @@ export function main() { c.mockRespond(baseResponse); }); let requestOptions = new RequestOptions({method: RequestMethod.Post}); - http.request('http://basic.connection', requestOptions).subscribe((res: Response) => { - expect(res.text()).toBe('base response'); - async.done(); - }); + http.request('http://basic.connection', requestOptions) + .subscribe((res: Response) => { + expect(res.text()).toBe('base response'); + async.done(); + }); })); it('should perform a post request for given url if options include a method', @@ -148,32 +184,30 @@ export function main() { c.mockRespond(baseResponse); }); let requestOptions = {method: RequestMethod.Post}; - http.request('http://basic.connection', requestOptions).subscribe((res: Response) => { - expect(res.text()).toBe('base response'); - async.done(); - }); + http.request('http://basic.connection', requestOptions) + .subscribe((res: Response) => { + expect(res.text()).toBe('base response'); + async.done(); + }); })); it('should perform a get request and complete the response', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse)); http.request('http://basic.connection') - .subscribe( - (res: Response) => { expect(res.text()).toBe('base response'); }, null, - () => { async.done(); }); + .subscribe((res: Response) => { expect(res.text()).toBe('base response'); }, null, + () => { async.done(); }); })); it('should perform multiple get requests and complete the responses', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse)); - http.request('http://basic.connection').subscribe((res: Response) => { - expect(res.text()).toBe('base response'); - }); http.request('http://basic.connection') - .subscribe( - (res: Response) => { expect(res.text()).toBe('base response'); }, null, - () => { async.done(); }); + .subscribe((res: Response) => { expect(res.text()).toBe('base response'); }); + http.request('http://basic.connection') + .subscribe((res: Response) => { expect(res.text()).toBe('base response'); }, null, + () => { async.done(); }); })); it('should throw if url is not a string or Request', () => { @@ -339,8 +373,9 @@ export function main() { it('should allow case insensitive strings for method names', () => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { backend.connections.subscribe((c: MockConnection) => { - expect(c.request.method).toBe(RequestMethod.Post) - c.mockRespond(new Response(new ResponseOptions({body: 'Thank you'}))); + expect(c.request.method) + .toBe(RequestMethod.Post) + c.mockRespond(new Response(new ResponseOptions({body: 'Thank you'}))); async.done(); }); http.request( diff --git a/modules/angular2/test/http/url_search_params_spec.ts b/modules/angular2/test/http/url_search_params_spec.ts index 42ca2a65dc..98c30f1556 100644 --- a/modules/angular2/test/http/url_search_params_spec.ts +++ b/modules/angular2/test/http/url_search_params_spec.ts @@ -1,28 +1,38 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; import {URLSearchParams} from 'angular2/src/http/url_search_params'; export function main() { describe('URLSearchParams', () => { it('should conform to spec', () => { - var paramsString = 'q=URLUtils.searchParams&topic=api'; + var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); // Tests borrowed from example at // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams // Compliant with spec described at https://url.spec.whatwg.org/#urlsearchparams - expect(searchParams.has('topic')).toBe(true); - expect(searchParams.has('foo')).toBe(false); - expect(searchParams.get('topic')).toEqual('api'); - expect(searchParams.getAll('topic')).toEqual(['api']); - expect(searchParams.get('foo')).toBe(null); - searchParams.append('topic', 'webdev'); - expect(searchParams.getAll('topic')).toEqual(['api', 'webdev']); - expect(searchParams.toString()).toEqual('q=URLUtils.searchParams&topic=api&topic=webdev'); - searchParams.delete('topic'); - expect(searchParams.toString()).toEqual('q=URLUtils.searchParams'); + expect(searchParams.has("topic")).toBe(true); + expect(searchParams.has("foo")).toBe(false); + expect(searchParams.get("topic")).toEqual("api"); + expect(searchParams.getAll("topic")).toEqual(["api"]); + expect(searchParams.get("foo")).toBe(null); + searchParams.append("topic", "webdev"); + expect(searchParams.getAll("topic")).toEqual(["api", "webdev"]); + expect(searchParams.toString()).toEqual("q=URLUtils.searchParams&topic=api&topic=webdev"); + searchParams.delete("topic"); + expect(searchParams.toString()).toEqual("q=URLUtils.searchParams"); // Test default constructor - expect(new URLSearchParams().toString()).toBe(''); + expect(new URLSearchParams().toString()).toBe(""); }); diff --git a/modules/angular2/test/i18n/i18n_html_parser_spec.ts b/modules/angular2/test/i18n/i18n_html_parser_spec.ts index 741a3a4aa7..95d6aff8df 100644 --- a/modules/angular2/test/i18n/i18n_html_parser_spec.ts +++ b/modules/angular2/test/i18n/i18n_html_parser_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {I18nHtmlParser} from 'angular2/src/i18n/i18n_html_parser'; import {Message, id} from 'angular2/src/i18n/message'; @@ -7,7 +18,15 @@ import {Lexer} from 'angular2/src/core/change_detection/parser/lexer'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {HtmlParser, HtmlParseTreeResult} from 'angular2/src/compiler/html_parser'; -import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast'; +import { + HtmlAst, + HtmlAstVisitor, + HtmlElementAst, + HtmlAttrAst, + HtmlTextAst, + HtmlCommentAst, + htmlVisitAll +} from 'angular2/src/compiler/html_ast'; import {serializeXmb, deserializeXmb} from 'angular2/src/i18n/xmb_serializer'; import {ParseError, ParseLocation} from 'angular2/src/compiler/parse_util'; import {humanizeDom} from '../../test/compiler/html_ast_spec_utils'; @@ -23,72 +42,71 @@ export function main() { let res = deserializeXmb(`<message-bundle>${msgs}</message-bundle>`, 'someUrl'); return new I18nHtmlParser(htmlParser, parser, res.content, res.messages) - .parse(template, 'someurl'); + .parse(template, "someurl"); } - it('should delegate to the provided parser when no i18n', () => { - expect(humanizeDom(parse('<div>a</div>', {}))).toEqual([ - [HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1] - ]); + it("should delegate to the provided parser when no i18n", () => { + expect(humanizeDom(parse('<div>a</div>', {}))) + .toEqual([[HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1]]); }); - it('should replace attributes', () => { + it("should replace attributes", () => { let translations: {[key: string]: string} = {}; - translations[id(new Message('some message', 'meaning', null))] = 'another message'; + translations[id(new Message("some message", "meaning", null))] = "another message"; - expect( - humanizeDom(parse( - '<div value=\'some message\' i18n-value=\'meaning|comment\'></div>', translations))) + expect(humanizeDom(parse("<div value='some message' i18n-value='meaning|comment'></div>", + translations))) .toEqual([[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'value', 'another message']]); }); - it('should replace elements with the i18n attr', () => { + it("should replace elements with the i18n attr", () => { let translations: {[key: string]: string} = {}; - translations[id(new Message('message', 'meaning', null))] = 'another message'; + translations[id(new Message("message", "meaning", null))] = "another message"; - expect(humanizeDom(parse('<div i18n=\'meaning|desc\'>message</div>', translations))).toEqual([ - [HtmlElementAst, 'div', 0], [HtmlTextAst, 'another message', 1] - ]); + expect(humanizeDom(parse("<div i18n='meaning|desc'>message</div>", translations))) + .toEqual([[HtmlElementAst, 'div', 0], [HtmlTextAst, 'another message', 1]]); }); - it('should handle interpolation', () => { + it("should handle interpolation", () => { let translations: {[key: string]: string} = {}; translations[id(new Message('<ph name="0"/> and <ph name="1"/>', null, null))] = '<ph name="1"/> or <ph name="0"/>'; - expect(humanizeDom(parse('<div value=\'{{a}} and {{b}}\' i18n-value></div>', translations))) + expect(humanizeDom(parse("<div value='{{a}} and {{b}}' i18n-value></div>", translations))) .toEqual([[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'value', '{{b}} or {{a}}']]); }); - it('should handle nested html', () => { + it("should handle nested html", () => { let translations: {[key: string]: string} = {}; translations[id(new Message('<ph name="e0">a</ph><ph name="e2">b</ph>', null, null))] = '<ph name="e2">B</ph><ph name="e0">A</ph>'; - expect(humanizeDom(parse('<div i18n><a>a</a><b>b</b></div>', translations))).toEqual([ - [HtmlElementAst, 'div', 0], - [HtmlElementAst, 'b', 1], - [HtmlTextAst, 'B', 2], - [HtmlElementAst, 'a', 1], - [HtmlTextAst, 'A', 2], - ]); + expect(humanizeDom(parse('<div i18n><a>a</a><b>b</b></div>', translations))) + .toEqual([ + [HtmlElementAst, 'div', 0], + [HtmlElementAst, 'b', 1], + [HtmlTextAst, 'B', 2], + [HtmlElementAst, 'a', 1], + [HtmlTextAst, 'A', 2], + ]); }); - it('should support interpolation', () => { + it("should support interpolation", () => { let translations: {[key: string]: string} = {}; translations[id(new Message( '<ph name="e0">a</ph><ph name="e2"><ph name="t3">b<ph name="0"/></ph></ph>', null, null))] = '<ph name="e2"><ph name="t3"><ph name="0"/>B</ph></ph><ph name="e0">A</ph>'; - expect(humanizeDom(parse('<div i18n><a>a</a><b>b{{i}}</b></div>', translations))).toEqual([ - [HtmlElementAst, 'div', 0], - [HtmlElementAst, 'b', 1], - [HtmlTextAst, '{{i}}B', 2], - [HtmlElementAst, 'a', 1], - [HtmlTextAst, 'A', 2], - ]); + expect(humanizeDom(parse('<div i18n><a>a</a><b>b{{i}}</b></div>', translations))) + .toEqual([ + [HtmlElementAst, 'div', 0], + [HtmlElementAst, 'b', 1], + [HtmlTextAst, '{{i}}B', 2], + [HtmlElementAst, 'a', 1], + [HtmlTextAst, 'A', 2], + ]); }); - it('should i18n attributes of placeholder elements', () => { + it("should i18n attributes of placeholder elements", () => { let translations: {[key: string]: string} = {}; translations[id(new Message('<ph name="e0">a</ph>', null, null))] = '<ph name="e0">A</ph>'; translations[id(new Message('b', null, null))] = 'B'; @@ -97,19 +115,21 @@ export function main() { .toEqual([ [HtmlElementAst, 'div', 0], [HtmlElementAst, 'a', 1], - [HtmlAttrAst, 'value', 'B'], + [HtmlAttrAst, 'value', "B"], [HtmlTextAst, 'A', 2], ]); }); - it('should preserve non-i18n attributes', () => { + it("should preserve non-i18n attributes", () => { let translations: {[key: string]: string} = {}; translations[id(new Message('message', null, null))] = 'another message'; - expect(humanizeDom(parse('<div i18n value="b">message</div>', translations))).toEqual([ - [HtmlElementAst, 'div', 0], [HtmlAttrAst, 'value', 'b'], - [HtmlTextAst, 'another message', 1] - ]); + expect(humanizeDom(parse('<div i18n value="b">message</div>', translations))) + .toEqual([ + [HtmlElementAst, 'div', 0], + [HtmlAttrAst, 'value', "b"], + [HtmlTextAst, 'another message', 1] + ]); }); it('should extract from partitions', () => { @@ -119,13 +139,14 @@ export function main() { let res = parse(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n --><!-- i18n: meaning2|desc2 -->message2<!-- /i18n -->`, translations); - expect(humanizeDom(res)).toEqual([ - [HtmlTextAst, 'another message1', 0], - [HtmlTextAst, 'another message2', 0], - ]); + expect(humanizeDom(res)) + .toEqual([ + [HtmlTextAst, 'another message1', 0], + [HtmlTextAst, 'another message2', 0], + ]); }); - it('should preserve original positions', () => { + it("should preserve original positions", () => { let translations: {[key: string]: string} = {}; translations[id(new Message('<ph name="e0">a</ph><ph name="e2">b</ph>', null, null))] = '<ph name="e2">B</ph><ph name="e0">A</ph>'; @@ -137,51 +158,47 @@ export function main() { expect(res[1].sourceSpan.start.offset).toEqual(10); }); - describe('errors', () => { - it('should error when giving an invalid template', () => { - expect(humanizeErrors(parse('<a>a</b>', {}).errors)).toEqual([ - 'Unexpected closing tag "b"' - ]); + describe("errors", () => { + it("should error when giving an invalid template", () => { + expect(humanizeErrors(parse("<a>a</b>", {}).errors)) + .toEqual(['Unexpected closing tag "b"']); }); - it('should error when no matching message (attr)', () => { - let mid = id(new Message('some message', null, null)); - expect(humanizeErrors(parse('<div value=\'some message\' i18n-value></div>', {}).errors)) + it("should error when no matching message (attr)", () => { + let mid = id(new Message("some message", null, null)); + expect(humanizeErrors(parse("<div value='some message' i18n-value></div>", {}).errors)) .toEqual([`Cannot find message for id '${mid}'`]); }); - it('should error when no matching message (text)', () => { - let mid = id(new Message('some message', null, null)); - expect(humanizeErrors(parse('<div i18n>some message</div>', {}).errors)).toEqual([ - `Cannot find message for id '${mid}'` - ]); + it("should error when no matching message (text)", () => { + let mid = id(new Message("some message", null, null)); + expect(humanizeErrors(parse("<div i18n>some message</div>", {}).errors)) + .toEqual([`Cannot find message for id '${mid}'`]); }); - it('should error when a non-placeholder element appears in translation', () => { + it("should error when a non-placeholder element appears in translation", () => { let translations: {[key: string]: string} = {}; - translations[id(new Message('some message', null, null))] = '<a>a</a>'; + translations[id(new Message("some message", null, null))] = "<a>a</a>"; - expect(humanizeErrors(parse('<div i18n>some message</div>', translations).errors)).toEqual([ - `Unexpected tag "a". Only "ph" tags are allowed.` - ]); + expect(humanizeErrors(parse("<div i18n>some message</div>", translations).errors)) + .toEqual([`Unexpected tag "a". Only "ph" tags are allowed.`]); }); - it('should error when a placeholder element does not have the name attribute', () => { + it("should error when a placeholder element does not have the name attribute", () => { let translations: {[key: string]: string} = {}; - translations[id(new Message('some message', null, null))] = '<ph>a</ph>'; + translations[id(new Message("some message", null, null))] = "<ph>a</ph>"; - expect(humanizeErrors(parse('<div i18n>some message</div>', translations).errors)).toEqual([ - `Missing "name" attribute.` - ]); + expect(humanizeErrors(parse("<div i18n>some message</div>", translations).errors)) + .toEqual([`Missing "name" attribute.`]); }); - it('should error when the translation refers to an invalid expression', () => { + it("should error when the translation refers to an invalid expression", () => { let translations: {[key: string]: string} = {}; translations[id(new Message('hi <ph name="0"/>', null, null))] = 'hi <ph name="99"/>'; expect( - humanizeErrors(parse('<div value=\'hi {{a}}\' i18n-value></div>', translations).errors)) - .toEqual(['Invalid interpolation index \'99\'']); + humanizeErrors(parse("<div value='hi {{a}}' i18n-value></div>", translations).errors)) + .toEqual(["Invalid interpolation index '99'"]); }); }); diff --git a/modules/angular2/test/i18n/message_extractor_spec.ts b/modules/angular2/test/i18n/message_extractor_spec.ts index 99b73ae171..e624ad327e 100644 --- a/modules/angular2/test/i18n/message_extractor_spec.ts +++ b/modules/angular2/test/i18n/message_extractor_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, describe, ddescribe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + describe, + ddescribe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {HtmlParser} from 'angular2/src/compiler/html_parser'; import {MessageExtractor, removeDuplicates} from 'angular2/src/i18n/message_extractor'; @@ -17,140 +28,149 @@ export function main() { }); it('should extract from elements with the i18n attr', () => { - let res = extractor.extract('<div i18n=\'meaning|desc\'>message</div>', 'someurl'); - expect(res.messages).toEqual([new Message('message', 'meaning', 'desc')]); + let res = extractor.extract("<div i18n='meaning|desc'>message</div>", "someurl"); + expect(res.messages).toEqual([new Message("message", 'meaning', 'desc')]); }); it('should extract from elements with the i18n attr without a desc', () => { - let res = extractor.extract('<div i18n=\'meaning\'>message</div>', 'someurl'); - expect(res.messages).toEqual([new Message('message', 'meaning', null)]); + let res = extractor.extract("<div i18n='meaning'>message</div>", "someurl"); + expect(res.messages).toEqual([new Message("message", 'meaning', null)]); }); it('should extract from elements with the i18n attr without a meaning', () => { - let res = extractor.extract('<div i18n>message</div>', 'someurl'); - expect(res.messages).toEqual([new Message('message', null, null)]); + let res = extractor.extract("<div i18n>message</div>", "someurl"); + expect(res.messages).toEqual([new Message("message", null, null)]); }); it('should extract from attributes', () => { - let res = extractor.extract( - ` + let res = extractor.extract(` <div title1='message1' i18n-title1='meaning1|desc1' title2='message2' i18n-title2='meaning2|desc2'> </div> `, - 'someurl'); + "someurl"); - expect(res.messages).toEqual([ - new Message('message1', 'meaning1', 'desc1'), new Message('message2', 'meaning2', 'desc2') - ]); + expect(res.messages) + .toEqual([ + new Message("message1", "meaning1", "desc1"), + new Message("message2", "meaning2", "desc2") + ]); }); it('should extract from partitions', () => { - let res = extractor.extract( - ` + let res = extractor.extract(` <!-- i18n: meaning1|desc1 -->message1<!-- /i18n --> <!-- i18n: meaning2|desc2 -->message2<!-- /i18n -->`, - 'someUrl'); + "someUrl"); - expect(res.messages).toEqual([ - new Message('message1', 'meaning1', 'desc1'), new Message('message2', 'meaning2', 'desc2') - ]); + expect(res.messages) + .toEqual([ + new Message("message1", "meaning1", "desc1"), + new Message("message2", "meaning2", "desc2") + ]); }); it('should ignore other comments', () => { - let res = extractor.extract( - ` + let res = extractor.extract(` <!-- i18n: meaning1|desc1 --><!-- other -->message1<!-- /i18n -->`, - 'someUrl'); + "someUrl"); - expect(res.messages).toEqual([new Message('message1', 'meaning1', 'desc1')]); + expect(res.messages).toEqual([new Message("message1", "meaning1", "desc1")]); }); it('should replace interpolation with placeholders (text nodes)', () => { - let res = extractor.extract('<div i18n>Hi {{one}} and {{two}}</div>', 'someurl'); - expect(res.messages).toEqual([new Message( - '<ph name="t0">Hi <ph name="0"/> and <ph name="1"/></ph>', null, null)]); + let res = extractor.extract("<div i18n>Hi {{one}} and {{two}}</div>", "someurl"); + expect(res.messages) + .toEqual( + [new Message('<ph name="t0">Hi <ph name="0"/> and <ph name="1"/></ph>', null, null)]); }); it('should replace interpolation with placeholders (attributes)', () => { let res = - extractor.extract('<div title=\'Hi {{one}} and {{two}}\' i18n-title></div>', 'someurl'); - expect(res.messages).toEqual([new Message( - 'Hi <ph name="0"/> and <ph name="1"/>', null, null)]); + extractor.extract("<div title='Hi {{one}} and {{two}}' i18n-title></div>", "someurl"); + expect(res.messages) + .toEqual([new Message('Hi <ph name="0"/> and <ph name="1"/>', null, null)]); }); - it('should handle html content', () => { + it("should handle html content", () => { let res = extractor.extract( - '<div i18n><div attr="value">zero<div>one</div></div><div>two</div></div>', 'someurl'); - expect(res.messages).toEqual([new Message( - '<ph name="e0">zero<ph name="e2">one</ph></ph><ph name="e4">two</ph>', null, null)]); + '<div i18n><div attr="value">zero<div>one</div></div><div>two</div></div>', "someurl"); + expect(res.messages) + .toEqual([ + new Message('<ph name="e0">zero<ph name="e2">one</ph></ph><ph name="e4">two</ph>', null, + null) + ]); }); - it('should handle html content with interpolation', () => { + it("should handle html content with interpolation", () => { let res = - extractor.extract('<div i18n><div>zero{{a}}<div>{{b}}</div></div></div>', 'someurl'); - expect(res.messages).toEqual([new Message( - '<ph name="e0"><ph name="t1">zero<ph name="0"/></ph><ph name="e2"><ph name="t3"><ph name="0"/></ph></ph></ph>', - null, null)]); + extractor.extract('<div i18n><div>zero{{a}}<div>{{b}}</div></div></div>', "someurl"); + expect(res.messages) + .toEqual([ + new Message( + '<ph name="e0"><ph name="t1">zero<ph name="0"/></ph><ph name="e2"><ph name="t3"><ph name="0"/></ph></ph></ph>', + null, null) + ]); }); - it('should extract from nested elements', () => { + it("should extract from nested elements", () => { let res = extractor.extract( '<div title="message1" i18n-title="meaning1|desc1"><div i18n="meaning2|desc2">message2</div></div>', - 'someurl'); - expect(res.messages).toEqual([ - new Message('message2', 'meaning2', 'desc2'), new Message('message1', 'meaning1', 'desc1') - ]); + "someurl"); + expect(res.messages) + .toEqual([ + new Message("message2", "meaning2", "desc2"), + new Message("message1", "meaning1", "desc1") + ]); }); - it('should extract messages from attributes in i18n blocks', () => { + it("should extract messages from attributes in i18n blocks", () => { let res = extractor.extract( - '<div i18n><div attr="value" i18n-attr="meaning|desc">message</div></div>', 'someurl'); - expect(res.messages).toEqual([ - new Message('<ph name="e0">message</ph>', null, null), - new Message('value', 'meaning', 'desc') - ]); + '<div i18n><div attr="value" i18n-attr="meaning|desc">message</div></div>', "someurl"); + expect(res.messages) + .toEqual([ + new Message('<ph name="e0">message</ph>', null, null), + new Message('value', "meaning", "desc") + ]); }); - it('should remove duplicate messages', () => { - let res = extractor.extract( - ` + it("should remove duplicate messages", () => { + let res = extractor.extract(` <!-- i18n: meaning|desc1 -->message<!-- /i18n --> <!-- i18n: meaning|desc2 -->message<!-- /i18n -->`, - 'someUrl'); + "someUrl"); - expect(removeDuplicates(res.messages)).toEqual([ - new Message('message', 'meaning', 'desc1'), - ]); + expect(removeDuplicates(res.messages)) + .toEqual([ + new Message("message", "meaning", "desc1"), + ]); }); - describe('errors', () => { + describe("errors", () => { it('should error on i18n attributes without matching "real" attributes', () => { - let res = extractor.extract( - ` + let res = extractor.extract(` <div title1='message1' i18n-title1='meaning1|desc1' i18n-title2='meaning2|desc2'> </div> `, - 'someurl'); + "someurl"); expect(res.errors.length).toEqual(1); - expect(res.errors[0].msg).toEqual('Missing attribute \'title2\'.'); + expect(res.errors[0].msg).toEqual("Missing attribute 'title2'."); }); it('should error when cannot find a matching desc', () => { - let res = extractor.extract( - ` + let res = extractor.extract(` <!-- i18n: meaning1|desc1 -->message1`, - 'someUrl'); + "someUrl"); expect(res.errors.length).toEqual(1); - expect(res.errors[0].msg).toEqual('Missing closing \'i18n\' comment.'); + expect(res.errors[0].msg).toEqual("Missing closing 'i18n' comment."); }); - it('should return parse errors when the template is invalid', () => { - let res = extractor.extract('<input&#Besfs', 'someurl'); + it("should return parse errors when the template is invalid", () => { + let res = extractor.extract("<input&#Besfs", "someurl"); expect(res.errors.length).toEqual(1); expect(res.errors[0].msg).toEqual('Unexpected character "s"'); }); diff --git a/modules/angular2/test/i18n/message_spec.ts b/modules/angular2/test/i18n/message_spec.ts index 213e9fe0e7..cab79c1fac 100644 --- a/modules/angular2/test/i18n/message_spec.ts +++ b/modules/angular2/test/i18n/message_spec.ts @@ -1,13 +1,24 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {Message, id} from 'angular2/src/i18n/message'; export function main() { describe('Message', () => { - describe('id', () => { - it('should return a different id for messages with and without the meaning', () => { - let m1 = new Message('content', 'meaning', null); - let m2 = new Message('content', null, null); + describe("id", () => { + it("should return a different id for messages with and without the meaning", () => { + let m1 = new Message("content", "meaning", null); + let m2 = new Message("content", null, null); expect(id(m1)).toEqual(id(m1)); expect(id(m1)).not.toEqual(id(m2)); }); diff --git a/modules/angular2/test/i18n/xmb_serializer_spec.ts b/modules/angular2/test/i18n/xmb_serializer_spec.ts index 00f3d7a2ad..839e87a828 100644 --- a/modules/angular2/test/i18n/xmb_serializer_spec.ts +++ b/modules/angular2/test/i18n/xmb_serializer_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {HtmlAst} from 'angular2/src/compiler/html_ast'; import {Message, id} from 'angular2/src/i18n/message'; @@ -6,32 +17,32 @@ import {serializeXmb, deserializeXmb} from 'angular2/src/i18n/xmb_serializer'; import {ParseSourceSpan, ParseError} from 'angular2/src/compiler/parse_util'; export function main() { - describe('Xmb', () => { + describe("Xmb", () => { describe('Xmb Serialization', () => { - it('should return an empty message bundle for an empty list of messages', - () => { expect(serializeXmb([])).toEqual('<message-bundle></message-bundle>'); }); + it("should return an empty message bundle for an empty list of messages", + () => { expect(serializeXmb([])).toEqual("<message-bundle></message-bundle>"); }); - it('should serializeXmb messages without desc', () => { - let m = new Message('content', 'meaning', null); + it("should serializeXmb messages without desc", () => { + let m = new Message("content", "meaning", null); let expected = `<message-bundle><msg id='${id(m)}'>content</msg></message-bundle>`; expect(serializeXmb([m])).toEqual(expected); }); - it('should serializeXmb messages with desc', () => { - let m = new Message('content', 'meaning', 'description'); + it("should serializeXmb messages with desc", () => { + let m = new Message("content", "meaning", "description"); let expected = `<message-bundle><msg id='${id(m)}' desc='description'>content</msg></message-bundle>`; expect(serializeXmb([m])).toEqual(expected); }); }); - describe('Xmb Deserialization', () => { - it('should parse an empty bundle', () => { - let mb = '<message-bundle></message-bundle>'; - expect(deserializeXmb(mb, 'url').messages).toEqual({}); + describe("Xmb Deserialization", () => { + it("should parse an empty bundle", () => { + let mb = "<message-bundle></message-bundle>"; + expect(deserializeXmb(mb, "url").messages).toEqual({}); }); - it('should parse an non-empty bundle', () => { + it("should parse an non-empty bundle", () => { let mb = ` <message-bundle> <msg id="id1" desc="description1">content1</msg> @@ -39,59 +50,59 @@ export function main() { </message-bundle> `; - let parsed = deserializeXmb(mb, 'url').messages; - expect(_serialize(parsed['id1'])).toEqual('content1'); - expect(_serialize(parsed['id2'])).toEqual('content2'); + let parsed = deserializeXmb(mb, "url").messages; + expect(_serialize(parsed["id1"])).toEqual("content1"); + expect(_serialize(parsed["id2"])).toEqual("content2"); }); - it('should error when cannot parse the content', () => { + it("should error when cannot parse the content", () => { let mb = ` <message-bundle> <msg id="id1" desc="description1">content </message-bundle> `; - let res = deserializeXmb(mb, 'url'); + let res = deserializeXmb(mb, "url"); expect(_serializeErrors(res.errors)).toEqual(['Unexpected closing tag "message-bundle"']); }); - it('should error when cannot find the id attribute', () => { + it("should error when cannot find the id attribute", () => { let mb = ` <message-bundle> <msg>content</msg> </message-bundle> `; - let res = deserializeXmb(mb, 'url'); + let res = deserializeXmb(mb, "url"); expect(_serializeErrors(res.errors)).toEqual(['"id" attribute is missing']); }); - it('should error on empty content', () => { + it("should error on empty content", () => { let mb = ``; - let res = deserializeXmb(mb, 'url'); + let res = deserializeXmb(mb, "url"); expect(_serializeErrors(res.errors)).toEqual(['Missing element "message-bundle"']); }); - it('should error on an invalid element', () => { + it("should error on an invalid element", () => { let mb = ` <message-bundle> <invalid>content</invalid> </message-bundle> `; - let res = deserializeXmb(mb, 'url'); + let res = deserializeXmb(mb, "url"); expect(_serializeErrors(res.errors)).toEqual(['Unexpected element "invalid"']); }); - it('should expand \'ph\' elements', () => { + it("should expand 'ph' elements", () => { let mb = ` <message-bundle> <msg id="id1">a<ph name="i0"/></msg> </message-bundle> `; - let res = deserializeXmb(mb, 'url').messages['id1']; - expect((<any>res[1]).name).toEqual('ph'); + let res = deserializeXmb(mb, "url").messages["id1"]; + expect((<any>res[1]).name).toEqual("ph"); }); }); }); diff --git a/modules/angular2/test/mock/view_resolver_mock_spec.ts b/modules/angular2/test/mock/view_resolver_mock_spec.ts index 6220414aa0..1102e31402 100644 --- a/modules/angular2/test/mock/view_resolver_mock_spec.ts +++ b/modules/angular2/test/mock/view_resolver_mock_spec.ts @@ -1,4 +1,12 @@ -import {beforeEach, ddescribe, describe, el, expect, iit, it,} from 'angular2/testing_internal'; +import { + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + it, +} from 'angular2/testing_internal'; import {stringify} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/test/platform/browser/bootstrap_spec.ts b/modules/angular2/test/platform/browser/bootstrap_spec.ts index b5aad3db01..cafe68ca89 100644 --- a/modules/angular2/test/platform/browser/bootstrap_spec.ts +++ b/modules/angular2/test/platform/browser/bootstrap_spec.ts @@ -1,4 +1,17 @@ -import {AsyncTestCompleter, beforeEach, afterEach, ddescribe, describe, expect, iit, inject, it, xdescribe, Log, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + afterEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + Log, + xit +} from 'angular2/testing_internal'; import {IS_DART, isPresent, stringify} from 'angular2/src/facade/lang'; import {bootstrap} from 'angular2/platform/browser'; import {ApplicationRef} from 'angular2/src/core/application_ref'; @@ -12,7 +25,7 @@ import {provide, Inject, Injector, PLATFORM_INITIALIZER, APP_INITIALIZER} from ' import {disposePlatform} from 'angular2/src/core/application_ref'; import {ExceptionHandler, BaseException} from 'angular2/src/facade/exceptions'; import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability'; -import {ComponentRef_, ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader'; +import {ComponentRef_, ComponentRef} from "angular2/src/core/linker/dynamic_component_loader"; @Component({selector: 'hello-app', template: '{{greeting}} world!'}) class HelloRootCmp { @@ -35,7 +48,7 @@ class HelloRootCmp2 { class HelloRootCmp3 { appBinding; - constructor(@Inject('appBinding') appBinding) { this.appBinding = appBinding; } + constructor(@Inject("appBinding") appBinding) { this.appBinding = appBinding; } } @Component({selector: 'hello-app', template: ''}) @@ -97,14 +110,14 @@ export function main() { inject([AsyncTestCompleter], (async) => { var logger = new _ArrayLogger(); var exceptionHandler = new ExceptionHandler(logger, false); - var refPromise = bootstrap( - HelloRootDirectiveIsNotCmp, - [testProviders, provide(ExceptionHandler, {useValue: exceptionHandler})]); + var refPromise = + bootstrap(HelloRootDirectiveIsNotCmp, + [testProviders, provide(ExceptionHandler, {useValue: exceptionHandler})]); PromiseWrapper.then(refPromise, null, (exception) => { expect(exception).toContainError( `Could not compile '${stringify(HelloRootDirectiveIsNotCmp)}' because it is not a component.`); - expect(logger.res.join('')).toContain('Could not compile'); + expect(logger.res.join("")).toContain("Could not compile"); async.done(); }); })); @@ -146,7 +159,7 @@ export function main() { var refPromise = bootstrap(HelloRootCmp, [provide(ExceptionHandler, {useValue: exceptionHandler})]); PromiseWrapper.then(refPromise, null, (reason) => { - expect(logger.res.join('')) + expect(logger.res.join("")) .toContain('The selector "hello-app" did not match any elements'); async.done(); return null; @@ -170,43 +183,46 @@ export function main() { it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async) => { var refPromise1 = bootstrap(HelloRootCmp, testProviders); var refPromise2 = bootstrap(HelloRootCmp2, testProviders); - PromiseWrapper.all([refPromise1, refPromise2]).then((refs) => { - expect(el).toHaveText('hello world!'); - expect(el2).toHaveText('hello world, again!'); - async.done(); - }); + PromiseWrapper.all([refPromise1, refPromise2]) + .then((refs) => { + expect(el).toHaveText('hello world!'); + expect(el2).toHaveText('hello world, again!'); + async.done(); + }); })); it('should not crash if change detection is invoked when the root component is disposed', inject([AsyncTestCompleter], (async) => { - bootstrap(HelloOnDestroyTickCmp, testProviders).then((ref) => { - expect(() => ref.dispose()).not.toThrow(); - async.done(); - }); + bootstrap(HelloOnDestroyTickCmp, testProviders) + .then((ref) => { + expect(() => ref.dispose()).not.toThrow(); + async.done(); + }); })); it('should unregister change detectors when components are disposed', inject([AsyncTestCompleter], (async) => { var app = platform(BROWSER_PROVIDERS).application([BROWSER_APP_PROVIDERS, testProviders]); - app.bootstrap(HelloRootCmp).then((ref) => { - ref.dispose(); - expect(() => app.tick()).not.toThrow(); - async.done(); - }); + app.bootstrap(HelloRootCmp) + .then((ref) => { + ref.dispose(); + expect(() => app.tick()).not.toThrow(); + async.done(); + }); })); - it('should make the provided bindings available to the application component', + it("should make the provided bindings available to the application component", inject([AsyncTestCompleter], (async) => { var refPromise = bootstrap( - HelloRootCmp3, [testProviders, provide('appBinding', {useValue: 'BoundValue'})]); + HelloRootCmp3, [testProviders, provide("appBinding", {useValue: "BoundValue"})]); refPromise.then((ref) => { - expect(ref.hostComponent.appBinding).toEqual('BoundValue'); + expect(ref.hostComponent.appBinding).toEqual("BoundValue"); async.done(); }); })); - it('should avoid cyclic dependencies when root component requires Lifecycle through DI', + it("should avoid cyclic dependencies when root component requires Lifecycle through DI", inject([AsyncTestCompleter], (async) => { var refPromise = bootstrap(HelloRootCmp4, testProviders); @@ -216,21 +232,21 @@ export function main() { }); })); - it('should run platform initializers', inject([Log], (log: Log) => { + it("should run platform initializers", inject([Log], (log: Log) => { let p = platform([ BROWSER_PROVIDERS, - provide(PLATFORM_INITIALIZER, {useValue: log.fn('platform_init1'), multi: true}), - provide(PLATFORM_INITIALIZER, {useValue: log.fn('platform_init2'), multi: true}) + provide(PLATFORM_INITIALIZER, {useValue: log.fn("platform_init1"), multi: true}), + provide(PLATFORM_INITIALIZER, {useValue: log.fn("platform_init2"), multi: true}) ]); - expect(log.result()).toEqual('platform_init1; platform_init2'); + expect(log.result()).toEqual("platform_init1; platform_init2"); log.clear(); p.application([ BROWSER_APP_PROVIDERS, - provide(APP_INITIALIZER, {useValue: log.fn('app_init1'), multi: true}), - provide(APP_INITIALIZER, {useValue: log.fn('app_init2'), multi: true}) + provide(APP_INITIALIZER, {useValue: log.fn("app_init1"), multi: true}), + provide(APP_INITIALIZER, {useValue: log.fn("app_init2"), multi: true}) ]); - expect(log.result()).toEqual('app_init1; app_init2'); + expect(log.result()).toEqual("app_init1; app_init2"); })); it('should register each application with the testability registry', @@ -238,16 +254,18 @@ export function main() { var refPromise1: Promise<ComponentRef> = bootstrap(HelloRootCmp, testProviders); var refPromise2: Promise<ComponentRef> = bootstrap(HelloRootCmp2, testProviders); - PromiseWrapper.all([refPromise1, refPromise2]).then((refs: ComponentRef[]) => { - var registry = refs[0].injector.get(TestabilityRegistry); - var testabilities = - [refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; - PromiseWrapper.all(testabilities).then((testabilities: Testability[]) => { - expect(registry.findTestabilityInTree(el)).toEqual(testabilities[0]); - expect(registry.findTestabilityInTree(el2)).toEqual(testabilities[1]); - async.done(); - }); - }); + PromiseWrapper.all([refPromise1, refPromise2]) + .then((refs: ComponentRef[]) => { + var registry = refs[0].injector.get(TestabilityRegistry); + var testabilities = + [refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; + PromiseWrapper.all(testabilities) + .then((testabilities: Testability[]) => { + expect(registry.findTestabilityInTree(el)).toEqual(testabilities[0]); + expect(registry.findTestabilityInTree(el2)).toEqual(testabilities[1]); + async.done(); + }); + }); })); }); } diff --git a/modules/angular2/test/platform/browser/ruler_spec.ts b/modules/angular2/test/platform/browser/ruler_spec.ts index 006778112d..4c68c9336a 100644 --- a/modules/angular2/test/platform/browser/ruler_spec.ts +++ b/modules/angular2/test/platform/browser/ruler_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, inject, ddescribe, describe, it, iit, xit, expect, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + ddescribe, + describe, + it, + iit, + xit, + expect, + SpyObject +} from 'angular2/testing_internal'; import {SpyElementRef, SpyDomAdapter} from '../../core/spies'; import {DOM, DomAdapter} from 'angular2/src/platform/dom/dom_adapter'; @@ -33,7 +43,7 @@ export function main() { inject([AsyncTestCompleter], (async) => { var ruler = new Ruler(DOM); var elRef = <any>new SpyElementRef(); - elRef.prop('nativeElement', DOM.createElement('div')); + elRef.prop("nativeElement", DOM.createElement('div')); ruler.measure(elRef).then((rect) => { // here we are using an element created in a doc fragment so all the measures will come // back as 0 diff --git a/modules/angular2/test/platform/browser/tools/tools_spec.ts b/modules/angular2/test/platform/browser/tools/tools_spec.ts index 3b6cc87d81..1c61b2ebaa 100644 --- a/modules/angular2/test/platform/browser/tools/tools_spec.ts +++ b/modules/angular2/test/platform/browser/tools/tools_spec.ts @@ -1,4 +1,14 @@ -import {afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + afterEach, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; import {enableDebugTools, disableDebugTools} from 'angular2/platform/browser'; import {SpyComponentRef, callNgProfilerTimeChangeDetection} from './spies'; diff --git a/modules/angular2/test/platform/browser/xhr_cache_spec.ts b/modules/angular2/test/platform/browser/xhr_cache_spec.ts index c3eba1e08b..63f080bedf 100644 --- a/modules/angular2/test/platform/browser/xhr_cache_spec.ts +++ b/modules/angular2/test/platform/browser/xhr_cache_spec.ts @@ -1,6 +1,21 @@ import {Component, provide} from 'angular2/core'; import {UrlResolver, XHR} from 'angular2/compiler'; -import {AsyncTestCompleter, beforeEach, beforeEachProviders, ComponentFixture, ddescribe, describe, expect, fakeAsync, iit, inject, it, TestComponentBuilder, tick, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + beforeEachProviders, + ComponentFixture, + ddescribe, + describe, + expect, + fakeAsync, + iit, + inject, + it, + TestComponentBuilder, + tick, + xit +} from 'angular2/testing_internal'; import {BaseException} from 'angular2/src/facade/exceptions'; import {CachedXHR} from 'angular2/src/platform/browser/xhr_cache'; import {setTemplateCache} from './xhr_cache_setter'; @@ -13,25 +28,26 @@ export function main() { setTemplateCache({'test.html': '<div>Hello</div>'}); return new CachedXHR(); } - beforeEachProviders(() => [provide(UrlResolver, {useClass: TestUrlResolver}), provide(XHR, { - useFactory: createCachedXHR - })]); + beforeEachProviders(() => [ + provide(UrlResolver, {useClass: TestUrlResolver}), + provide(XHR, {useFactory: createCachedXHR}) + ]); it('should throw exception if $templateCache is not found', () => { setTemplateCache(null); - expect(() => { - xhr = new CachedXHR(); - }).toThrowErrorWith('CachedXHR: Template cache was not found in $templateCache.'); + expect(() => { xhr = new CachedXHR(); }) + .toThrowErrorWith('CachedXHR: Template cache was not found in $templateCache.'); }); it('should resolve the Promise with the cached file content on success', inject([AsyncTestCompleter], (async) => { setTemplateCache({'test.html': '<div>Hello</div>'}); xhr = new CachedXHR(); - xhr.get('test.html').then((text) => { - expect(text).toEqual('<div>Hello</div>'); - async.done(); - }); + xhr.get('test.html') + .then((text) => { + expect(text).toEqual('<div>Hello</div>'); + async.done(); + }); })); it('should reject the Promise on failure', inject([AsyncTestCompleter], (async) => { diff --git a/modules/angular2/test/platform/browser/xhr_impl_spec.ts b/modules/angular2/test/platform/browser/xhr_impl_spec.ts index af007b5abe..300b3644a5 100644 --- a/modules/angular2/test/platform/browser/xhr_impl_spec.ts +++ b/modules/angular2/test/platform/browser/xhr_impl_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit +} from 'angular2/testing_internal'; import {XHRImpl} from 'angular2/src/platform/browser/xhr_impl'; import {PromiseWrapper} from 'angular2/src/facade/async'; diff --git a/modules/angular2/test/platform/dom/dom_renderer_integration_spec.ts b/modules/angular2/test/platform/dom/dom_renderer_integration_spec.ts index 0b94caa658..3812e90c9c 100644 --- a/modules/angular2/test/platform/dom/dom_renderer_integration_spec.ts +++ b/modules/angular2/test/platform/dom/dom_renderer_integration_spec.ts @@ -1,4 +1,17 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, beforeEachProviders, SpyObject,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + el, + expect, + iit, + inject, + it, + xit, + beforeEachProviders, + SpyObject, +} from 'angular2/testing_internal'; // import {MapWrapper} from 'angular2/src/facade/collection'; // import {DOM} from 'angular2/src/platform/dom/dom_adapter'; diff --git a/modules/angular2/test/platform/dom/events/event_manager_spec.ts b/modules/angular2/test/platform/dom/events/event_manager_spec.ts index 44871ffafb..cd69ce0933 100644 --- a/modules/angular2/test/platform/dom/events/event_manager_spec.ts +++ b/modules/angular2/test/platform/dom/events/event_manager_spec.ts @@ -1,4 +1,14 @@ -import {describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, el} from 'angular2/testing_internal'; +import { + describe, + ddescribe, + it, + iit, + xit, + xdescribe, + expect, + beforeEach, + el +} from 'angular2/testing_internal'; import {EventManager, EventManagerPlugin} from 'angular2/platform/common_dom'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; import {NgZone} from 'angular2/src/core/zone/ng_zone'; @@ -69,7 +79,7 @@ export function main() { var handler = (e) => { receivedEvent = e; }; var manager = new EventManager([domEventPlugin], new FakeNgZone()); - var remover = manager.addGlobalEventListener('document', 'click', handler); + var remover = manager.addGlobalEventListener("document", 'click', handler); DOM.dispatchEvent(element, dispatchedEvent); expect(receivedEvent).toBe(dispatchedEvent); diff --git a/modules/angular2/test/platform/dom/events/key_events_spec.ts b/modules/angular2/test/platform/dom/events/key_events_spec.ts index 15472eb2cb..b09be3df04 100644 --- a/modules/angular2/test/platform/dom/events/key_events_spec.ts +++ b/modules/angular2/test/platform/dom/events/key_events_spec.ts @@ -1,4 +1,14 @@ -import {describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, el} from 'angular2/testing_internal'; +import { + describe, + ddescribe, + it, + iit, + xit, + xdescribe, + expect, + beforeEach, + el +} from 'angular2/testing_internal'; import {KeyEventsPlugin} from 'angular2/src/platform/dom/events/key_events'; export function main() { diff --git a/modules/angular2/test/platform/dom/shared_styles_host_spec.ts b/modules/angular2/test/platform/dom/shared_styles_host_spec.ts index 5c6f2e8387..72807a4ef7 100644 --- a/modules/angular2/test/platform/dom/shared_styles_host_spec.ts +++ b/modules/angular2/test/platform/dom/shared_styles_host_spec.ts @@ -1,4 +1,20 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, SpyObject, proxy} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + SpyObject, + proxy +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; diff --git a/modules/angular2/test/public_api_spec.ts b/modules/angular2/test/public_api_spec.ts index c254824ee1..ec0b1e29e8 100644 --- a/modules/angular2/test/public_api_spec.ts +++ b/modules/angular2/test/public_api_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {IS_DART, RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang'; import {getSymbolsFromLibrary} from './symbol_inspector/symbol_inspector'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -80,58 +91,136 @@ var NG_COMMON = [ ]; var NG_COMPILER = [ - 'TemplateAst:dart', - 'TemplateAstVisitor:dart', - 'DEFAULT_PACKAGE_URL_PROVIDER', - 'UrlResolver', - 'getUrlScheme', - 'AttrAst', - 'BoundDirectivePropertyAst', - 'BoundElementPropertyAst', - 'BoundEventAst', - 'BoundTextAst', - 'COMPILER_PROVIDERS', - 'CompileDirectiveMetadata', - 'CompileTemplateMetadata', - 'CompileTypeMetadata', - 'DirectiveAst', - 'ElementAst', - 'EmbeddedTemplateAst', - 'NgContentAst', - 'PLATFORM_DIRECTIVES', - 'PLATFORM_PIPES', - 'PropertyBindingType', - 'SourceModule', - 'SourceWithImports', - 'TEMPLATE_TRANSFORMS', - 'TemplateCompiler', - 'TextAst', - 'VariableAst', - 'XHR', - 'createWithoutPackagePrefix', - 'templateVisitAll' + "TemplateAst:dart", + "TemplateAstVisitor:dart", + "DEFAULT_PACKAGE_URL_PROVIDER", + "UrlResolver", + "getUrlScheme", + "AttrAst", + "BoundDirectivePropertyAst", + "BoundElementPropertyAst", + "BoundEventAst", + "BoundTextAst", + "COMPILER_PROVIDERS", + "CompileDirectiveMetadata", + "CompileTemplateMetadata", + "CompileTypeMetadata", + "DirectiveAst", + "ElementAst", + "EmbeddedTemplateAst", + "NgContentAst", + "PLATFORM_DIRECTIVES", + "PLATFORM_PIPES", + "PropertyBindingType", + "SourceModule", + "SourceWithImports", + "TEMPLATE_TRANSFORMS", + "TemplateCompiler", + "TextAst", + "VariableAst", + "XHR", + "createWithoutPackagePrefix", + "templateVisitAll" ]; var NG_CORE = [ - 'APP_COMPONENT', 'APP_INITIALIZER', 'APP_ID', 'AngularEntrypoint:dart', 'AbstractProviderError', - 'AppViewManager', 'ApplicationRef', 'APPLICATION_COMMON_PROVIDERS', 'Attribute', - 'AttributeMetadata', 'Binding', 'Provider', 'ProviderBuilder', 'PLATFORM_DIRECTIVES', - 'CollectionChangeRecord', 'ChangeDetectionError', 'ChangeDetectionStrategy', 'ChangeDetectorRef', - 'Class:js', 'Compiler', 'Component', 'ComponentMetadata', 'ComponentRef', 'ContentChild', - 'ContentChildMetadata', 'ContentChildren', 'ContentChildrenMetadata', 'CyclicDependencyError', - 'PLATFORM_PIPES', 'DebugNode', 'DebugElement', 'Dependency', 'DependencyMetadata', 'Directive', - 'DirectiveMetadata', 'DirectiveResolver', 'DynamicComponentLoader', 'ElementRef', 'Output', - 'EmbeddedViewRef', 'EventEmitter', 'ExceptionHandler', 'OutputMetadata', 'enableProdMode', - 'ExpressionChangedAfterItHasBeenCheckedException', 'Host', 'HostBinding', 'HostBindingMetadata', - 'HostListener', 'HostListenerMetadata', 'HostMetadata', 'HostViewFactoryRef', 'Inject', - 'InjectMetadata', 'Injectable', 'InjectableMetadata', 'Injector', 'InstantiationError', - 'InvalidProviderError', 'IterableDiffers', 'Key', 'KeyValueChangeRecord', 'KeyValueDiffers', - 'NgZone', 'NgZoneError', 'NoAnnotationError', 'NoProviderError', 'OpaqueToken', 'Optional', - 'OptionalMetadata', 'OutOfBoundsError', 'Pipe', 'PipeMetadata', 'PlatformRef', 'Input', - 'InputMetadata', 'Query', 'QueryList', 'QueryMetadata', 'Renderer', 'RootRenderer', - 'RenderComponentType', 'ResolvedBinding:dart', 'ResolvedProvider:dart', 'ResolvedFactory', 'Self', - 'SelfMetadata', 'SkipSelf', 'SkipSelfMetadata', 'SimpleChange', 'TemplateRef', 'Testability', - 'TestabilityRegistry', 'GetTestability:dart', 'setTestabilityGetter', 'Type', 'PACKAGE_ROOT_URL', + 'APP_COMPONENT', + 'APP_INITIALIZER', + 'APP_ID', + 'AngularEntrypoint:dart', + 'AbstractProviderError', + 'AppViewManager', + 'ApplicationRef', + 'APPLICATION_COMMON_PROVIDERS', + 'Attribute', + 'AttributeMetadata', + 'Binding', + 'Provider', + 'ProviderBuilder', + 'PLATFORM_DIRECTIVES', + "CollectionChangeRecord", + 'ChangeDetectionError', + 'ChangeDetectionStrategy', + 'ChangeDetectorRef', + 'Class:js', + 'Compiler', + 'Component', + 'ComponentMetadata', + 'ComponentRef', + 'ContentChild', + 'ContentChildMetadata', + 'ContentChildren', + 'ContentChildrenMetadata', + 'CyclicDependencyError', + 'PLATFORM_PIPES', + 'DebugNode', + 'DebugElement', + 'Dependency', + 'DependencyMetadata', + 'Directive', + 'DirectiveMetadata', + 'DirectiveResolver', + 'DynamicComponentLoader', + 'ElementRef', + 'Output', + 'EmbeddedViewRef', + 'EventEmitter', + 'ExceptionHandler', + 'OutputMetadata', + 'enableProdMode', + 'ExpressionChangedAfterItHasBeenCheckedException', + 'Host', + 'HostBinding', + 'HostBindingMetadata', + 'HostListener', + 'HostListenerMetadata', + 'HostMetadata', + 'HostViewFactoryRef', + 'Inject', + 'InjectMetadata', + 'Injectable', + 'InjectableMetadata', + 'Injector', + 'InstantiationError', + 'InvalidProviderError', + 'IterableDiffers', + 'Key', + 'KeyValueChangeRecord', + 'KeyValueDiffers', + 'NgZone', + 'NgZoneError', + 'NoAnnotationError', + 'NoProviderError', + 'OpaqueToken', + 'Optional', + 'OptionalMetadata', + 'OutOfBoundsError', + 'Pipe', + 'PipeMetadata', + 'PlatformRef', + 'Input', + 'InputMetadata', + 'Query', + 'QueryList', + 'QueryMetadata', + 'Renderer', + 'RootRenderer', + 'RenderComponentType', + 'ResolvedBinding:dart', + 'ResolvedProvider:dart', + 'ResolvedFactory', + 'Self', + 'SelfMetadata', + 'SkipSelf', + 'SkipSelfMetadata', + 'SimpleChange', + 'TemplateRef', + 'Testability', + 'TestabilityRegistry', + 'GetTestability:dart', + 'setTestabilityGetter', + 'Type', + 'PACKAGE_ROOT_URL', 'View:dart', /* 'View.directives:dart', @@ -142,16 +231,51 @@ var NG_CORE = [ 'View.template:dart', 'View.templateUrl:dart', */ - 'ViewChild', 'ViewChildMetadata', 'ViewChildren', 'ViewChildrenMetadata', 'ViewContainerRef', - 'ViewEncapsulation', 'ViewMetadata', 'ViewQuery', 'ViewQueryMetadata', 'ViewResolver', - 'WrappedException', 'WrappedValue', 'asNativeElements', 'bind', 'provide', 'createNgZone', - 'forwardRef:js', 'platform', 'resolveForwardRef:js', 'PLATFORM_COMMON_PROVIDERS', - 'PLATFORM_INITIALIZER', 'AfterContentChecked:dart', 'AfterContentInit:dart', - 'AfterViewChecked:dart', 'AfterViewInit:dart', 'DoCheck:dart', 'HostViewRef', - 'IterableDifferFactory:dart', 'IterableDiffer:dart', 'KeyValueDifferFactory:dart', - 'KeyValueDiffer:dart', 'OnChanges:dart', 'OnDestroy:dart', 'OnInit:dart', 'PipeTransform:dart', - 'reflector', 'Stream:dart', 'GetterFn:dart', 'MethodFn:dart', 'NoReflectionCapabilities:dart', - 'PlatformReflectionCapabilities:dart', 'ReflectionInfo', 'Reflector', 'SetterFn:dart', 'ViewRef', + 'ViewChild', + 'ViewChildMetadata', + 'ViewChildren', + 'ViewChildrenMetadata', + 'ViewContainerRef', + 'ViewEncapsulation', + 'ViewMetadata', + 'ViewQuery', + 'ViewQueryMetadata', + 'ViewResolver', + 'WrappedException', + 'WrappedValue', + 'asNativeElements', + 'bind', + 'provide', + 'createNgZone', + 'forwardRef:js', + 'platform', + 'resolveForwardRef:js', + 'PLATFORM_COMMON_PROVIDERS', + 'PLATFORM_INITIALIZER', + 'AfterContentChecked:dart', + 'AfterContentInit:dart', + 'AfterViewChecked:dart', + 'AfterViewInit:dart', + 'DoCheck:dart', + 'HostViewRef', + 'IterableDifferFactory:dart', + 'IterableDiffer:dart', + 'KeyValueDifferFactory:dart', + 'KeyValueDiffer:dart', + 'OnChanges:dart', + 'OnDestroy:dart', + 'OnInit:dart', + 'PipeTransform:dart', + 'reflector', + 'Stream:dart', + 'GetterFn:dart', + 'MethodFn:dart', + 'NoReflectionCapabilities:dart', + 'PlatformReflectionCapabilities:dart', + 'ReflectionInfo', + 'Reflector', + 'SetterFn:dart', + 'ViewRef', 'TrackByFn:dart' ]; @@ -159,10 +283,20 @@ var NG_INSTRUMENTATION = ['wtfCreateScope', 'wtfEndTimeRange', 'wtfLeave', 'WtfScopeFn:dart', 'wtfStartTimeRange']; var NG_PLATFORM_BROWSER = [ - 'AngularEntrypoint', 'BROWSER_APP_PROVIDERS', 'BROWSER_PROVIDERS', 'BrowserDomAdapter', 'By', - 'CACHED_TEMPLATE_PROVIDER', 'DOCUMENT', 'ELEMENT_PROBE_PROVIDERS', - 'ELEMENT_PROBE_PROVIDERS_PROD_MODE', 'Title', 'bootstrap', 'disableDebugTools', - 'enableDebugTools', 'inspectNativeElement' + 'AngularEntrypoint', + 'BROWSER_APP_PROVIDERS', + 'BROWSER_PROVIDERS', + 'BrowserDomAdapter', + 'By', + 'CACHED_TEMPLATE_PROVIDER', + 'DOCUMENT', + 'ELEMENT_PROBE_PROVIDERS', + 'ELEMENT_PROBE_PROVIDERS_PROD_MODE', + 'Title', + 'bootstrap', + 'disableDebugTools', + 'enableDebugTools', + 'inspectNativeElement' ]; var NG_UPGRADE = [ @@ -211,7 +345,7 @@ export function main() { function diff(actual: string[], expected: string[]): string[] { ListWrapper.sort(actual, compareIgnoreLang); ListWrapper.sort(expected, compareIgnoreLang); - let mode = IS_DART ? 'dart' : 'js'; + let mode = IS_DART ? "dart" : "js"; let missing = actual.filter(i => expected.indexOf(i) < 0 && expected.indexOf(`${i}:${mode}`) < 0) .map(s => `+${s}`); let extra = expected.filter(i => shouldIgnore(i) ? false : (actual.indexOf(stripLang(i)) < 0)) diff --git a/modules/angular2/test/router/directives/router_link_spec.ts b/modules/angular2/test/router/directives/router_link_spec.ts index f58ffdfa10..0105616bd5 100644 --- a/modules/angular2/test/router/directives/router_link_spec.ts +++ b/modules/angular2/test/router/directives/router_link_spec.ts @@ -1,11 +1,34 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + TestComponentBuilder +} from 'angular2/testing_internal'; import {SpyRouter, SpyLocation} from '../spies'; import {provide, Component} from 'angular2/core'; import {By} from 'angular2/platform/common_dom'; -import {Location, Router, RouteRegistry, RouterLink, RouterOutlet, Route, RouteParams, ComponentInstruction} from 'angular2/router'; +import { + Location, + Router, + RouteRegistry, + RouterLink, + RouterOutlet, + Route, + RouteParams, + ComponentInstruction +} from 'angular2/router'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {ResolvedInstruction} from 'angular2/src/router/instruction'; @@ -17,64 +40,69 @@ export function main() { describe('routerLink directive', function() { var tcb: TestComponentBuilder; - beforeEachProviders(() => [provide(Location, {useValue: makeDummyLocation()}), provide(Router, { - useValue: makeDummyRouter() - })]); + beforeEachProviders(() => [ + provide(Location, {useValue: makeDummyLocation()}), + provide(Router, {useValue: makeDummyRouter()}) + ]); beforeEach(inject([TestComponentBuilder], (tcBuilder) => { tcb = tcBuilder; })); it('should update a[href] attribute', inject([AsyncTestCompleter], (async) => { - tcb.createAsync(TestComponent).then((testComponent) => { - testComponent.detectChanges(); - let anchorElement = - testComponent.debugElement.query(By.css('a.detail-view')).nativeElement; - expect(DOM.getAttribute(anchorElement, 'href')).toEqual('detail'); - async.done(); - }); + tcb.createAsync(TestComponent) + .then((testComponent) => { + testComponent.detectChanges(); + let anchorElement = + testComponent.debugElement.query(By.css('a.detail-view')).nativeElement; + expect(DOM.getAttribute(anchorElement, 'href')).toEqual('detail'); + async.done(); + }); })); it('should call router.navigate when a link is clicked', inject([AsyncTestCompleter, Router], (async, router) => { - tcb.createAsync(TestComponent).then((testComponent) => { - testComponent.detectChanges(); - // TODO: shouldn't this be just 'click' rather than '^click'? - testComponent.debugElement.query(By.css('a.detail-view')) - .triggerEventHandler('click', null); - expect(router.spy('navigateByInstruction')).toHaveBeenCalledWith(dummyInstruction); - async.done(); - }); + tcb.createAsync(TestComponent) + .then((testComponent) => { + testComponent.detectChanges(); + // TODO: shouldn't this be just 'click' rather than '^click'? + testComponent.debugElement.query(By.css('a.detail-view')) + .triggerEventHandler('click', null); + expect(router.spy('navigateByInstruction')).toHaveBeenCalledWith(dummyInstruction); + async.done(); + }); })); it('should call router.navigate when a link is clicked if target is _self', inject([AsyncTestCompleter, Router], (async, router) => { - tcb.createAsync(TestComponent).then((testComponent) => { - testComponent.detectChanges(); - testComponent.debugElement.query(By.css('a.detail-view-self')) - .triggerEventHandler('click', null); - expect(router.spy('navigateByInstruction')).toHaveBeenCalledWith(dummyInstruction); - async.done(); - }); + tcb.createAsync(TestComponent) + .then((testComponent) => { + testComponent.detectChanges(); + testComponent.debugElement.query(By.css('a.detail-view-self')) + .triggerEventHandler('click', null); + expect(router.spy('navigateByInstruction')).toHaveBeenCalledWith(dummyInstruction); + async.done(); + }); })); it('should NOT call router.navigate when a link is clicked if target is set to other than _self', inject([AsyncTestCompleter, Router], (async, router) => { - tcb.createAsync(TestComponent).then((testComponent) => { - testComponent.detectChanges(); - testComponent.debugElement.query(By.css('a.detail-view-blank')) - .triggerEventHandler('click', null); - expect(router.spy('navigateByInstruction')).not.toHaveBeenCalled(); - async.done(); - }); + tcb.createAsync(TestComponent) + .then((testComponent) => { + testComponent.detectChanges(); + testComponent.debugElement.query(By.css('a.detail-view-blank')) + .triggerEventHandler('click', null); + expect(router.spy('navigateByInstruction')).not.toHaveBeenCalled(); + async.done(); + }); })); }); } -@Component({selector: 'user-cmp', template: 'hello {{user}}'}) +@Component({selector: 'user-cmp', template: "hello {{user}}"}) class UserCmp { user: string; constructor(params: RouteParams) { this.user = params.get('name'); } diff --git a/modules/angular2/test/router/directives/router_link_transform_spec.ts b/modules/angular2/test/router/directives/router_link_transform_spec.ts index 5efc753357..8a1642b834 100644 --- a/modules/angular2/test/router/directives/router_link_transform_spec.ts +++ b/modules/angular2/test/router/directives/router_link_transform_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, describe, proxy, it, iit, ddescribe, expect, inject, beforeEach, beforeEachBindings, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + proxy, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + beforeEachBindings, + SpyObject +} from 'angular2/testing_internal'; import {Injector, provide} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; @@ -14,43 +26,43 @@ export function main() { } describe('parseRouterLinkExpression', () => { - it('should parse simple routes', inject([Parser], (p) => { + it("should parse simple routes", inject([Parser], (p) => { check(p, `User`, `["User"]`); check(p, `/User`, `["/User"]`); check(p, `./User`, `["./User"]`); check(p, `../../User`, `["../../User"]`); })); - it('should trim the string', inject([Parser], (p) => { check(p, ` User `, `["User"]`); })); + it("should trim the string", inject([Parser], (p) => { check(p, ` User `, `["User"]`); })); - it('should parse parameters', inject([Parser], (p) => { + it("should parse parameters", inject([Parser], (p) => { check(p, `./User(id: value, name: 'Bob')`, `["./User", {id: value, name: "Bob"}]`); })); - it('should parse nested routes', inject([Parser], (p) => { + it("should parse nested routes", inject([Parser], (p) => { check(p, `User/Modal`, `["User", "Modal"]`); check(p, `/User/Modal`, `["/User", "Modal"]`); })); - it('should parse auxiliary routes', inject([Parser], (p) => { + it("should parse auxiliary routes", inject([Parser], (p) => { check(p, `User[Modal]`, `["User", ["Modal"]]`); check(p, `User[Modal1][Modal2]`, `["User", ["Modal1"], ["Modal2"]]`); check(p, `User[Modal1[Modal2]]`, `["User", ["Modal1", ["Modal2"]]]`); })); - it('should parse combinations', inject([Parser], (p) => { + it("should parse combinations", inject([Parser], (p) => { check(p, `./User(id: value)/Post(title: 'blog')`, `["./User", {id: value}, "Post", {title: "blog"}]`); check(p, `./User[Modal(param: value)]`, `["./User", ["Modal", {param: value}]]`); })); - it('should error on empty fixed parts', inject([Parser], (p) => { + it("should error on empty fixed parts", inject([Parser], (p) => { expect(() => parseRouterLinkExpression(p, `./(id: value, name: 'Bob')`)) - .toThrowErrorWith('Invalid router link'); + .toThrowErrorWith("Invalid router link"); })); - it('should error on multiple slashes', inject([Parser], (p) => { + it("should error on multiple slashes", inject([Parser], (p) => { expect(() => parseRouterLinkExpression(p, `//User`)) - .toThrowErrorWith('Invalid router link'); + .toThrowErrorWith("Invalid router link"); })); }); } \ No newline at end of file diff --git a/modules/angular2/test/router/integration/async_route_spec.ts b/modules/angular2/test/router/integration/async_route_spec.ts index 7d84f8e0b4..a7f77b6718 100644 --- a/modules/angular2/test/router/integration/async_route_spec.ts +++ b/modules/angular2/test/router/integration/async_route_spec.ts @@ -1,4 +1,12 @@ -import {describeRouter, ddescribeRouter, describeWith, describeWithout, describeWithAndWithout, itShouldRoute, TEST_ROUTER_PROVIDERS} from './util'; +import { + describeRouter, + ddescribeRouter, + describeWith, + describeWithout, + describeWithAndWithout, + itShouldRoute, + TEST_ROUTER_PROVIDERS +} from './util'; import {beforeEachProviders, describe} from 'angular2/testing_internal'; @@ -17,12 +25,12 @@ export function main() { describeWithAndWithout('params', itShouldRoute); }); - describeWith( - 'sync children', () => { describeWithAndWithout('default routes', itShouldRoute); }); + describeWith('sync children', + () => { describeWithAndWithout('default routes', itShouldRoute); }); describeWith('async children', () => { - describeWithAndWithout( - 'params', () => { describeWithout('default routes', itShouldRoute); }); + describeWithAndWithout('params', + () => { describeWithout('default routes', itShouldRoute); }); }); }); }); diff --git a/modules/angular2/test/router/integration/auxiliary_route_spec.ts b/modules/angular2/test/router/integration/auxiliary_route_spec.ts index 64accb91cb..94085d679e 100644 --- a/modules/angular2/test/router/integration/auxiliary_route_spec.ts +++ b/modules/angular2/test/router/integration/auxiliary_route_spec.ts @@ -1,6 +1,17 @@ -import {describeRouter, ddescribeRouter, describeWith, describeWithout, describeWithAndWithout, itShouldRoute, TEST_ROUTER_PROVIDERS} from './util'; +import { + describeRouter, + ddescribeRouter, + describeWith, + describeWithout, + describeWithAndWithout, + itShouldRoute, + TEST_ROUTER_PROVIDERS +} from './util'; -import {beforeEachProviders, describe,} from 'angular2/testing_internal'; +import { + beforeEachProviders, + describe, +} from 'angular2/testing_internal'; import {registerSpecs} from './impl/aux_route_spec_impl'; diff --git a/modules/angular2/test/router/integration/bootstrap_spec.ts b/modules/angular2/test/router/integration/bootstrap_spec.ts index 7883b41b6a..4e20609399 100644 --- a/modules/angular2/test/router/integration/bootstrap_spec.ts +++ b/modules/angular2/test/router/integration/bootstrap_spec.ts @@ -1,4 +1,18 @@ -import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, flushMicrotasks, inject, it, xdescribe, TestComponentBuilder, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + beforeEachProviders, + ddescribe, + describe, + expect, + iit, + flushMicrotasks, + inject, + it, + xdescribe, + TestComponentBuilder, + xit, +} from 'angular2/testing_internal'; import {bootstrap} from 'angular2/platform/browser'; import {Component, Directive} from 'angular2/src/core/metadata'; @@ -6,10 +20,23 @@ import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {Console} from 'angular2/src/core/console'; import {provide, ViewChild, AfterViewInit} from 'angular2/core'; import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; -import {RouteConfig, Route, Redirect, AuxRoute} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + Route, + Redirect, + AuxRoute +} from 'angular2/src/router/route_config/route_config_decorator'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {ROUTER_PROVIDERS, ROUTER_PRIMARY_COMPONENT, RouteParams, Router, APP_BASE_HREF, ROUTER_DIRECTIVES, LocationStrategy} from 'angular2/router'; +import { + ROUTER_PROVIDERS, + ROUTER_PRIMARY_COMPONENT, + RouteParams, + Router, + APP_BASE_HREF, + ROUTER_DIRECTIVES, + LocationStrategy +} from 'angular2/router'; import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {ApplicationRef} from 'angular2/src/core/application_ref'; @@ -21,10 +48,11 @@ class DummyConsole implements Console { export function main() { describe('router bootstrap', () => { - beforeEachProviders( - () => - [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: MockLocationStrategy}), - provide(ApplicationRef, {useClass: MockApplicationRef})]); + beforeEachProviders(() => [ + ROUTER_PROVIDERS, + provide(LocationStrategy, {useClass: MockLocationStrategy}), + provide(ApplicationRef, {useClass: MockApplicationRef}) + ]); // do not refactor out the `bootstrap` functionality. We still want to // keep this test around so we can ensure that bootstrapping a router works @@ -33,18 +61,22 @@ export function main() { var el = DOM.createElement('app-cmp', fakeDoc); DOM.appendChild(fakeDoc.body, el); - bootstrap(AppCmp, [ - ROUTER_PROVIDERS, provide(ROUTER_PRIMARY_COMPONENT, {useValue: AppCmp}), - provide(LocationStrategy, {useClass: MockLocationStrategy}), - provide(DOCUMENT, {useValue: fakeDoc}), provide(Console, {useClass: DummyConsole}) - ]).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('outer { hello }'); - expect(applicationRef.hostComponent.location.path()).toEqual(''); - async.done(); - }); - }); + bootstrap(AppCmp, + [ + ROUTER_PROVIDERS, + provide(ROUTER_PRIMARY_COMPONENT, {useValue: AppCmp}), + provide(LocationStrategy, {useClass: MockLocationStrategy}), + provide(DOCUMENT, {useValue: fakeDoc}), + provide(Console, {useClass: DummyConsole}) + ]) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('outer { hello }'); + expect(applicationRef.hostComponent.location.path()).toEqual(''); + async.done(); + }); + }); })); describe('broken app', () => { @@ -68,46 +100,47 @@ export function main() { it('should change the url without pushing a new history state for back navigations', inject([AsyncTestCompleter, TestComponentBuilder], (async, tcb: TestComponentBuilder) => { - tcb.createAsync(HierarchyAppCmp).then((fixture) => { - var router = fixture.debugElement.componentInstance.router; - var position = 0; - var flipped = false; - var history = [ - ['/parent/child', 'root { parent { hello } }', '/super-parent/child'], - ['/super-parent/child', 'root { super-parent { hello2 } }', '/parent/child'], - ['/parent/child', 'root { parent { hello } }', false] - ]; + tcb.createAsync(HierarchyAppCmp) + .then((fixture) => { + var router = fixture.debugElement.componentInstance.router; + var position = 0; + var flipped = false; + var history = [ + ['/parent/child', 'root { parent { hello } }', '/super-parent/child'], + ['/super-parent/child', 'root { super-parent { hello2 } }', '/parent/child'], + ['/parent/child', 'root { parent { hello } }', false] + ]; - router.subscribe((_) => { - var location = fixture.debugElement.componentInstance.location; - var element = fixture.debugElement.nativeElement; - var path = location.path(); + router.subscribe((_) => { + var location = fixture.debugElement.componentInstance.location; + var element = fixture.debugElement.nativeElement; + var path = location.path(); - var entry = history[position]; + var entry = history[position]; - expect(path).toEqual(entry[0]); - expect(element).toHaveText(entry[1]); + expect(path).toEqual(entry[0]); + expect(element).toHaveText(entry[1]); - var nextUrl = entry[2]; - if (nextUrl == false) { - flipped = true; - } + var nextUrl = entry[2]; + if (nextUrl == false) { + flipped = true; + } - if (flipped && position == 0) { - async.done(); - return; - } + if (flipped && position == 0) { + async.done(); + return; + } - position = position + (flipped ? -1 : 1); - if (flipped) { - location.back(); - } else { - router.navigateByUrl(nextUrl); - } - }); + position = position + (flipped ? -1 : 1); + if (flipped) { + location.back(); + } else { + router.navigateByUrl(nextUrl); + } + }); - router.navigateByUrl(history[0][0]); - }); + router.navigateByUrl(history[0][0]); + }); }), 1000); }); @@ -118,37 +151,40 @@ export function main() { it('should bootstrap an app with a hierarchy', inject([AsyncTestCompleter, TestComponentBuilder], (async, tcb: TestComponentBuilder) => { - tcb.createAsync(HierarchyAppCmp).then((fixture) => { - var router = fixture.debugElement.componentInstance.router; - router.subscribe((_) => { - expect(fixture.debugElement.nativeElement).toHaveText('root { parent { hello } }'); - expect(fixture.debugElement.componentInstance.location.path()) - .toEqual('/parent/child'); - async.done(); - }); - router.navigateByUrl('/parent/child'); - }); + tcb.createAsync(HierarchyAppCmp) + .then((fixture) => { + var router = fixture.debugElement.componentInstance.router; + router.subscribe((_) => { + expect(fixture.debugElement.nativeElement) + .toHaveText('root { parent { hello } }'); + expect(fixture.debugElement.componentInstance.location.path()) + .toEqual('/parent/child'); + async.done(); + }); + router.navigateByUrl('/parent/child'); + }); })); // TODO(btford): mock out level lower than LocationStrategy once that level exists xdescribe('custom app base ref', () => { beforeEachProviders(() => { return [provide(APP_BASE_HREF, {useValue: '/my/app'})]; }); it('should bootstrap', - inject( - [AsyncTestCompleter, TestComponentBuilder], (async, tcb: TestComponentBuilder) => { + inject([AsyncTestCompleter, TestComponentBuilder], + (async, tcb: TestComponentBuilder) => { - tcb.createAsync(HierarchyAppCmp).then((fixture) => { - var router = fixture.debugElement.componentInstance.router; - router.subscribe((_) => { - expect(fixture.debugElement.nativeElement) - .toHaveText('root { parent { hello } }'); - expect(fixture.debugElement.componentInstance.location.path()) - .toEqual('/my/app/parent/child'); - async.done(); - }); - router.navigateByUrl('/parent/child'); - }); - })); + tcb.createAsync(HierarchyAppCmp) + .then((fixture) => { + var router = fixture.debugElement.componentInstance.router; + router.subscribe((_) => { + expect(fixture.debugElement.nativeElement) + .toHaveText('root { parent { hello } }'); + expect(fixture.debugElement.componentInstance.location.path()) + .toEqual('/my/app/parent/child'); + async.done(); + }); + router.navigateByUrl('/parent/child'); + }); + })); }); }); @@ -159,21 +195,22 @@ export function main() { it('should recognize and return querystring params with the injected RouteParams', inject([AsyncTestCompleter, TestComponentBuilder], (async, tcb: TestComponentBuilder) => { - tcb.createAsync(QueryStringAppCmp).then((fixture) => { - var router = fixture.debugElement.componentInstance.router; - router.subscribe((_) => { - fixture.detectChanges(); + tcb.createAsync(QueryStringAppCmp) + .then((fixture) => { + var router = fixture.debugElement.componentInstance.router; + router.subscribe((_) => { + fixture.detectChanges(); - expect(fixture.debugElement.nativeElement) - .toHaveText('qParam = search-for-something'); - /* - expect(applicationRef.hostComponent.location.path()) - .toEqual('/qs?q=search-for-something');*/ - async.done(); - }); - router.navigateByUrl('/qs?q=search-for-something'); - fixture.detectChanges(); - }); + expect(fixture.debugElement.nativeElement) + .toHaveText('qParam = search-for-something'); + /* + expect(applicationRef.hostComponent.location.path()) + .toEqual('/qs?q=search-for-something');*/ + async.done(); + }); + router.navigateByUrl('/qs?q=search-for-something'); + fixture.detectChanges(); + }); })); }); @@ -182,28 +219,29 @@ export function main() { beforeEachProviders(() => [provide(ROUTER_PRIMARY_COMPONENT, {useValue: AppCmp})]); - beforeEach(inject( - [TestComponentBuilder], (testComponentBuilder) => { tcb = testComponentBuilder; })); + beforeEach(inject([TestComponentBuilder], + (testComponentBuilder) => { tcb = testComponentBuilder; })); it('should get a reference and pass data to components loaded inside of outlets', inject([AsyncTestCompleter], (async) => { - tcb.createAsync(AppWithViewChildren).then(fixture => { - let appInstance = fixture.debugElement.componentInstance; - let router = appInstance.router; + tcb.createAsync(AppWithViewChildren) + .then(fixture => { + let appInstance = fixture.debugElement.componentInstance; + let router = appInstance.router; - router.subscribe((_) => { - fixture.detectChanges(); + router.subscribe((_) => { + fixture.detectChanges(); - expect(appInstance.helloCmp).toBeAnInstanceOf(HelloCmp); - expect(appInstance.helloCmp.message).toBe('Ahoy'); + expect(appInstance.helloCmp).toBeAnInstanceOf(HelloCmp); + expect(appInstance.helloCmp.message).toBe('Ahoy'); - async.done(); - }); + async.done(); + }); - // TODO(juliemr): This isn't necessary for the test to pass - figure - // out what's going on. - // router.navigateByUrl('/rainbow(pony)'); - }); + // TODO(juliemr): This isn't necessary for the test to pass - figure + // out what's going on. + // router.navigateByUrl('/rainbow(pony)'); + }); })); }); }); @@ -298,7 +336,7 @@ class QueryStringAppCmp { constructor(public router: Router, public location: LocationStrategy) {} } -@Component({selector: 'oops-cmp', template: 'oh no'}) +@Component({selector: 'oops-cmp', template: "oh no"}) class BrokenCmp { constructor() { throw new BaseException('oops!'); } } diff --git a/modules/angular2/test/router/integration/impl/async_route_spec_impl.ts b/modules/angular2/test/router/integration/impl/async_route_spec_impl.ts index 2bdc981f01..3303ff2926 100644 --- a/modules/angular2/test/router/integration/impl/async_route_spec_impl.ts +++ b/modules/angular2/test/router/integration/impl/async_route_spec_impl.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, beforeEach, beforeEachProviders, expect, iit, flushMicrotasks, inject, it, TestComponentBuilder, ComponentFixture, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + beforeEachProviders, + expect, + iit, + flushMicrotasks, + inject, + it, + TestComponentBuilder, + ComponentFixture, + xit, +} from 'angular2/testing_internal'; import {By} from 'angular2/platform/common_dom'; @@ -7,7 +19,21 @@ import {specs, compile, TEST_ROUTER_PROVIDERS, clickOnElement, getHref} from '.. import {Router, AsyncRoute, Route, Location} from 'angular2/router'; -import {HelloCmp, helloCmpLoader, UserCmp, userCmpLoader, TeamCmp, asyncTeamLoader, ParentCmp, parentCmpLoader, asyncParentCmpLoader, asyncDefaultParentCmpLoader, ParentWithDefaultCmp, parentWithDefaultCmpLoader, asyncRouteDataCmp} from './fixture_components'; +import { + HelloCmp, + helloCmpLoader, + UserCmp, + userCmpLoader, + TeamCmp, + asyncTeamLoader, + ParentCmp, + parentCmpLoader, + asyncParentCmpLoader, + asyncDefaultParentCmpLoader, + ParentWithDefaultCmp, + parentWithDefaultCmpLoader, + asyncRouteDataCmp +} from './fixture_components'; function getLinkElement(rtc: ComponentFixture) { return rtc.debugElement.query(By.css('a')).nativeElement; @@ -28,8 +54,10 @@ function asyncRoutesWithoutChildrenWithRouteData() { it('should inject route data into the component', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/route-data', loader: asyncRouteDataCmp, data: {isAdmin: true}})])) + .then((_) => rtr.config([ + new AsyncRoute( + {path: '/route-data', loader: asyncRouteDataCmp, data: {isAdmin: true}}) + ])) .then((_) => rtr.navigateByUrl('/route-data')) .then((_) => { fixture.detectChanges(); @@ -42,8 +70,8 @@ function asyncRoutesWithoutChildrenWithRouteData() { inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/route-data-default', loader: asyncRouteDataCmp})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/route-data-default', loader: asyncRouteDataCmp})])) .then((_) => rtr.navigateByUrl('/route-data-default')) .then((_) => { fixture.detectChanges(); @@ -68,8 +96,8 @@ function asyncRoutesWithoutChildrenWithoutParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/test', loader: helloCmpLoader, name: 'Hello'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})])) .then((_) => rtr.navigateByUrl('/test')) .then((_) => { fixture.detectChanges(); @@ -81,8 +109,8 @@ function asyncRoutesWithoutChildrenWithoutParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/test', loader: helloCmpLoader, name: 'Hello'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})])) .then((_) => rtr.navigate(['/Hello'])) .then((_) => { fixture.detectChanges(); @@ -94,8 +122,8 @@ function asyncRoutesWithoutChildrenWithoutParams() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['Hello']">go to hello</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/test', loader: helloCmpLoader, name: 'Hello'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/test'); @@ -107,8 +135,8 @@ function asyncRoutesWithoutChildrenWithoutParams() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['Hello']">go to hello</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/test', loader: helloCmpLoader, name: 'Hello'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('go to hello | '); @@ -141,8 +169,8 @@ function asyncRoutesWithoutChildrenWithParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/user/:name', loader: userCmpLoader, name: 'User'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/user/:name', loader: userCmpLoader, name: 'User'})])) .then((_) => rtr.navigateByUrl('/user/igor')) .then((_) => { fixture.detectChanges(); @@ -154,9 +182,8 @@ function asyncRoutesWithoutChildrenWithParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => rtr.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => rtr.navigate(['/User', {name: 'brian'}])) .then((_) => { fixture.detectChanges(); @@ -168,8 +195,8 @@ function asyncRoutesWithoutChildrenWithParams() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['User', {name: 'naomi'}]">greet naomi</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/user/:name', loader: userCmpLoader, name: 'User'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/user/:name', loader: userCmpLoader, name: 'User'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/user/naomi'); @@ -181,8 +208,8 @@ function asyncRoutesWithoutChildrenWithParams() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['User', {name: 'naomi'}]">greet naomi</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/user/:name', loader: userCmpLoader, name: 'User'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/user/:name', loader: userCmpLoader, name: 'User'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('greet naomi | '); @@ -202,8 +229,8 @@ function asyncRoutesWithoutChildrenWithParams() { inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/user/:name', loader: userCmpLoader, name: 'User'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/user/:name', loader: userCmpLoader, name: 'User'})])) .then((_) => rtr.navigateByUrl('/user/brian')) .then((_) => { fixture.detectChanges(); @@ -234,8 +261,8 @@ function asyncRoutesWithSyncChildrenWithoutDefaultRoutes() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) .then((_) => rtr.navigateByUrl('/a/b')) .then((_) => { fixture.detectChanges(); @@ -247,8 +274,8 @@ function asyncRoutesWithSyncChildrenWithoutDefaultRoutes() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) .then((_) => rtr.navigate(['/Parent', 'Child'])) .then((_) => { fixture.detectChanges(); @@ -260,8 +287,8 @@ function asyncRoutesWithSyncChildrenWithoutDefaultRoutes() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['Parent']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/a'); @@ -273,8 +300,8 @@ function asyncRoutesWithSyncChildrenWithoutDefaultRoutes() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['Parent', 'Child']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config( + [new AsyncRoute({path: '/a/...', loader: parentCmpLoader, name: 'Parent'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('nav to child | outer { }'); @@ -308,8 +335,9 @@ function asyncRoutesWithSyncChildrenWithDefaultRoutes() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'}) + ])) .then((_) => rtr.navigateByUrl('/a')) .then((_) => { fixture.detectChanges(); @@ -321,8 +349,9 @@ function asyncRoutesWithSyncChildrenWithDefaultRoutes() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'}) + ])) .then((_) => rtr.navigate(['/Parent'])) .then((_) => { fixture.detectChanges(); @@ -334,8 +363,9 @@ function asyncRoutesWithSyncChildrenWithDefaultRoutes() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['/Parent']">link to inner</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'}) + ])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/a'); @@ -347,8 +377,9 @@ function asyncRoutesWithSyncChildrenWithDefaultRoutes() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['/Parent']">link to inner</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: parentWithDefaultCmpLoader, name: 'Parent'}) + ])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('link to inner | outer { }'); @@ -382,8 +413,9 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithoutDefaultRoutes() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'}) + ])) .then((_) => rtr.navigateByUrl('/a/b')) .then((_) => { rootTC.detectChanges(); @@ -395,8 +427,9 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithoutDefaultRoutes() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'}) + ])) .then((_) => rtr.navigate(['/Parent', 'Child'])) .then((_) => { rootTC.detectChanges(); @@ -408,8 +441,9 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithoutDefaultRoutes() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['Parent', 'Child']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'}) + ])) .then((_) => { rootTC.detectChanges(); expect(getHref(getLinkElement(rootTC))).toEqual('/a'); @@ -421,8 +455,9 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithoutDefaultRoutes() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['Parent', 'Child']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/a/...', loader: asyncParentCmpLoader, name: 'Parent'}) + ])) .then((_) => { rootTC.detectChanges(); expect(rootTC.debugElement.nativeElement).toHaveText('nav to child | outer { }'); @@ -456,8 +491,10 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithDefaultRoutes() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute( + {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'}) + ])) .then((_) => rtr.navigateByUrl('/a')) .then((_) => { rootTC.detectChanges(); @@ -469,8 +506,10 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithDefaultRoutes() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute( + {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'}) + ])) .then((_) => rtr.navigate(['/Parent'])) .then((_) => { rootTC.detectChanges(); @@ -482,8 +521,10 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithDefaultRoutes() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['Parent']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute( + {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'}) + ])) .then((_) => { rootTC.detectChanges(); expect(getHref(getLinkElement(rootTC))).toEqual('/a'); @@ -495,8 +536,10 @@ function asyncRoutesWithAsyncChildrenWithoutParamsWithDefaultRoutes() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['Parent']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {rootTC = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'})])) + .then((_) => rtr.config([ + new AsyncRoute( + {path: '/a/...', loader: asyncDefaultParentCmpLoader, name: 'Parent'}) + ])) .then((_) => { rootTC.detectChanges(); expect(rootTC.debugElement.nativeElement).toHaveText('nav to child | outer { }'); @@ -530,8 +573,9 @@ function asyncRoutesWithAsyncChildrenWithParamsWithoutDefaultRoutes() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `{ <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'}) + ])) .then((_) => rtr.navigateByUrl('/team/angular/user/matias')) .then((_) => { fixture.detectChanges(); @@ -544,8 +588,9 @@ function asyncRoutesWithAsyncChildrenWithParamsWithoutDefaultRoutes() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `{ <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'}) + ])) .then((_) => rtr.navigate(['/Team', {id: 'angular'}, 'User', {name: 'matias'}])) .then((_) => { fixture.detectChanges(); @@ -560,8 +605,9 @@ function asyncRoutesWithAsyncChildrenWithParamsWithoutDefaultRoutes() { tcb, `<a [routerLink]="['/Team', {id: 'angular'}, 'User', {name: 'matias'}]">nav to matias</a> { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'}) + ])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/team/angular'); @@ -575,8 +621,9 @@ function asyncRoutesWithAsyncChildrenWithParamsWithoutDefaultRoutes() { tcb, `<a [routerLink]="['/Team', {id: 'angular'}, 'User', {name: 'matias'}]">nav to matias</a> { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'})])) + .then((_) => rtr.config([ + new AsyncRoute({path: '/team/:id/...', loader: asyncTeamLoader, name: 'Team'}) + ])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('nav to matias { }'); diff --git a/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts b/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts index 8c9cb481f4..f7b26c515a 100644 --- a/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts +++ b/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts @@ -1,10 +1,30 @@ -import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, xdescribe, describe, el, expect, iit, inject, beforeEachProviders, it, xit} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + beforeEachProviders, + it, + xit +} from 'angular2/testing_internal'; import {By} from 'angular2/platform/common_dom'; import {provide, Component, Injector, Inject} from 'angular2/core'; import {Router, ROUTER_DIRECTIVES, RouteParams, RouteData, Location} from 'angular2/router'; -import {RouteConfig, Route, AuxRoute, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + Route, + AuxRoute, + Redirect +} from 'angular2/src/router/route_config/route_config_decorator'; import {specs, compile, clickOnElement, getHref} from '../util'; import {BaseException} from 'angular2/src/facade/exceptions'; @@ -218,7 +238,7 @@ class ModalCmp { @Component({ selector: 'aux-cmp', template: 'main {<router-outlet></router-outlet>} | ' + - 'aux {<router-outlet name="modal"></router-outlet>}', + 'aux {<router-outlet name="modal"></router-outlet>}', directives: [ROUTER_DIRECTIVES], }) @RouteConfig([ diff --git a/modules/angular2/test/router/integration/impl/fixture_components.ts b/modules/angular2/test/router/integration/impl/fixture_components.ts index 6bdf6ed006..cc0fdfca5d 100644 --- a/modules/angular2/test/router/integration/impl/fixture_components.ts +++ b/modules/angular2/test/router/integration/impl/fixture_components.ts @@ -1,8 +1,19 @@ import {Component} from 'angular2/core'; -import {AsyncRoute, Route, Redirect, RouteConfig, RouteParams, RouteData, ROUTER_DIRECTIVES} from 'angular2/router'; +import { + AsyncRoute, + Route, + Redirect, + RouteConfig, + RouteParams, + RouteData, + ROUTER_DIRECTIVES +} from 'angular2/router'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent} from 'angular2/src/facade/lang'; -import {DynamicComponentLoader, ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader'; +import { + DynamicComponentLoader, + ComponentRef +} from 'angular2/src/core/linker/dynamic_component_loader'; import {ElementRef} from 'angular2/src/core/linker/element_ref'; @Component({selector: 'goodbye-cmp', template: `{{farewell}}`}) @@ -136,16 +147,16 @@ export class RedirectToParentCmp { @RouteConfig([new Route({path: '/', component: HelloCmp})]) export class DynamicLoaderCmp { private _componentRef: ComponentRef = null; - constructor( - private _dynamicComponentLoader: DynamicComponentLoader, private _elementRef: ElementRef) {} + constructor(private _dynamicComponentLoader: DynamicComponentLoader, + private _elementRef: ElementRef) {} onSomeAction(): Promise<any> { if (isPresent(this._componentRef)) { this._componentRef.dispose(); this._componentRef = null; } - return this._dynamicComponentLoader - .loadIntoLocation(DynamicallyLoadedComponent, this._elementRef, 'viewport') + return this._dynamicComponentLoader.loadIntoLocation(DynamicallyLoadedComponent, + this._elementRef, 'viewport') .then((cmp) => { this._componentRef = cmp; }); } } diff --git a/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts b/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts index 244388f0d0..0a1f7af132 100644 --- a/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts +++ b/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts @@ -1,11 +1,30 @@ -import {AsyncTestCompleter, beforeEach, beforeEachProviders, expect, iit, flushMicrotasks, inject, it, TestComponentBuilder, ComponentFixture, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + beforeEachProviders, + expect, + iit, + flushMicrotasks, + inject, + it, + TestComponentBuilder, + ComponentFixture, + xit, +} from 'angular2/testing_internal'; import {specs, compile, TEST_ROUTER_PROVIDERS, clickOnElement, getHref} from '../util'; import {By} from 'angular2/platform/common_dom'; import {Router, Route, Location} from 'angular2/router'; -import {HelloCmp, UserCmp, TeamCmp, ParentCmp, ParentWithDefaultCmp, DynamicLoaderCmp} from './fixture_components'; +import { + HelloCmp, + UserCmp, + TeamCmp, + ParentCmp, + ParentWithDefaultCmp, + DynamicLoaderCmp +} from './fixture_components'; import {PromiseWrapper} from 'angular2/src/facade/async'; @@ -29,8 +48,8 @@ function syncRoutesWithoutChildrenWithoutParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then( - (_) => rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) + .then((_) => + rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) .then((_) => rtr.navigateByUrl('/test')) .then((_) => { fixture.detectChanges(); @@ -42,8 +61,8 @@ function syncRoutesWithoutChildrenWithoutParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then( - (_) => rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) + .then((_) => + rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) .then((_) => rtr.navigate(['/Hello'])) .then((_) => { fixture.detectChanges(); @@ -55,8 +74,8 @@ function syncRoutesWithoutChildrenWithoutParams() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['Hello']">go to hello</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then( - (_) => rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) + .then((_) => + rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/test'); @@ -68,8 +87,8 @@ function syncRoutesWithoutChildrenWithoutParams() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['Hello']">go to hello</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then( - (_) => rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) + .then((_) => + rtr.config([new Route({path: '/test', component: HelloCmp, name: 'Hello'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('go to hello | '); @@ -102,9 +121,8 @@ function syncRoutesWithoutChildrenWithParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => rtr.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => rtr.navigateByUrl('/user/igor')) .then((_) => { fixture.detectChanges(); @@ -116,9 +134,8 @@ function syncRoutesWithoutChildrenWithParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => rtr.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => rtr.navigate(['/User', {name: 'brian'}])) .then((_) => { fixture.detectChanges(); @@ -130,9 +147,8 @@ function syncRoutesWithoutChildrenWithParams() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['User', {name: 'naomi'}]">greet naomi</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => rtr.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/user/naomi'); @@ -144,9 +160,8 @@ function syncRoutesWithoutChildrenWithParams() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['User', {name: 'naomi'}]">greet naomi</a> | <router-outlet></router-outlet>`) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => rtr.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('greet naomi | '); @@ -166,9 +181,8 @@ function syncRoutesWithoutChildrenWithParams() { inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => rtr.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => rtr.navigateByUrl('/user/brian')) .then((_) => { fixture.detectChanges(); @@ -199,9 +213,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithoutParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) + .then((_) => rtr.config( + [new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) .then((_) => rtr.navigateByUrl('/a/b')) .then((_) => { fixture.detectChanges(); @@ -213,9 +226,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithoutParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) + .then((_) => rtr.config( + [new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) .then((_) => rtr.navigate(['/Parent', 'Child'])) .then((_) => { fixture.detectChanges(); @@ -227,9 +239,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithoutParams() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['Parent', 'Child']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) + .then((_) => rtr.config( + [new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/a/b'); @@ -241,9 +252,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithoutParams() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['Parent', 'Child']">nav to child</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then( - (_) => - rtr.config([new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) + .then((_) => rtr.config( + [new Route({path: '/a/...', component: ParentCmp, name: 'Parent'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('nav to child | outer { }'); @@ -277,8 +287,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `{ <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) + .then((_) => rtr.config( + [new Route({path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) .then((_) => rtr.navigateByUrl('/team/angular/user/matias')) .then((_) => { fixture.detectChanges(); @@ -291,8 +301,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `{ <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) + .then((_) => rtr.config( + [new Route({path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) .then((_) => rtr.navigate(['/Team', {id: 'angular'}, 'User', {name: 'matias'}])) .then((_) => { fixture.detectChanges(); @@ -307,8 +317,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithParams() { tcb, `<a [routerLink]="['/Team', {id: 'angular'}, 'User', {name: 'matias'}]">nav to matias</a> { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) + .then((_) => rtr.config( + [new Route({path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/team/angular/user/matias'); @@ -322,8 +332,8 @@ function syncRoutesWithSyncChildrenWithoutDefaultRoutesWithParams() { tcb, `<a [routerLink]="['/Team', {id: 'angular'}, 'User', {name: 'matias'}]">nav to matias</a> { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) + .then((_) => rtr.config( + [new Route({path: '/team/:id/...', component: TeamCmp, name: 'Team'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('nav to matias { }'); @@ -357,8 +367,9 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() { it('should navigate by URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) + .then( + (_) => rtr.config( + [new Route({path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) .then((_) => rtr.navigateByUrl('/a')) .then((_) => { fixture.detectChanges(); @@ -370,8 +381,9 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() { it('should navigate by link DSL', inject([AsyncTestCompleter], (async) => { compile(tcb, `outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) + .then( + (_) => rtr.config( + [new Route({path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) .then((_) => rtr.navigate(['/Parent'])) .then((_) => { fixture.detectChanges(); @@ -383,8 +395,9 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() { it('should generate a link URL', inject([AsyncTestCompleter], (async) => { compile(tcb, `<a [routerLink]="['/Parent']">link to inner</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) + .then( + (_) => rtr.config( + [new Route({path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/a'); @@ -396,8 +409,9 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() { inject([AsyncTestCompleter, Location], (async, location) => { compile(tcb, `<a [routerLink]="['/Parent']">link to inner</a> | outer { <router-outlet></router-outlet> }`) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) + .then( + (_) => rtr.config( + [new Route({path: '/a/...', component: ParentWithDefaultCmp, name: 'Parent'})])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('link to inner | outer { }'); @@ -429,38 +443,37 @@ function syncRoutesWithDynamicComponents() { it('should work', - inject( - [AsyncTestCompleter], - (async) => {tcb.createAsync(DynamicLoaderCmp) - .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route({path: '/', component: HelloCmp})])) - .then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('{ }'); - return fixture.componentInstance.onSomeAction(); - }) - .then((_) => { - fixture.detectChanges(); - return rtr.navigateByUrl('/'); - }) - .then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('{ hello }'); + inject([AsyncTestCompleter], + (async) => {tcb.createAsync(DynamicLoaderCmp) + .then((rtc) => {fixture = rtc}) + .then((_) => rtr.config([new Route({path: '/', component: HelloCmp})])) + .then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText('{ }'); + return fixture.componentInstance.onSomeAction(); + }) + .then((_) => { + fixture.detectChanges(); + return rtr.navigateByUrl('/'); + }) + .then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText('{ hello }'); - return fixture.componentInstance.onSomeAction(); - }) - .then((_) => { + return fixture.componentInstance.onSomeAction(); + }) + .then((_) => { - // TODO(i): This should be rewritten to use NgZone#onStable or - // something - // similar basically the assertion needs to run when the world is - // stable and we don't know when that is, only zones know. - PromiseWrapper.resolve(null).then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('{ hello }'); - async.done(); - }); - })})); + // TODO(i): This should be rewritten to use NgZone#onStable or + // something + // similar basically the assertion needs to run when the world is + // stable and we don't know when that is, only zones know. + PromiseWrapper.resolve(null).then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText('{ hello }'); + async.done(); + }); + })})); } diff --git a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts index 5d1faff24d..98df7f8335 100644 --- a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts +++ b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts @@ -1,13 +1,45 @@ -import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, xdescribe, describe, el, expect, iit, inject, beforeEachProviders, it, xit} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + beforeEachProviders, + it, + xit +} from 'angular2/testing_internal'; import {provide, Component, Injector, Inject} from 'angular2/core'; import {isPresent} from 'angular2/src/facade/lang'; -import {PromiseWrapper, PromiseCompleter, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; +import { + PromiseWrapper, + PromiseCompleter, + EventEmitter, + ObservableWrapper +} from 'angular2/src/facade/async'; import {Router, RouterOutlet, RouterLink, RouteParams} from 'angular2/router'; -import {RouteConfig, Route, AuxRoute, AsyncRoute, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + Route, + AuxRoute, + AsyncRoute, + Redirect +} from 'angular2/src/router/route_config/route_config_decorator'; -import {OnActivate, OnDeactivate, OnReuse, CanDeactivate, CanReuse} from 'angular2/src/router/interfaces'; +import { + OnActivate, + OnDeactivate, + OnReuse, + CanDeactivate, + CanReuse +} from 'angular2/src/router/interfaces'; import {CanActivate} from 'angular2/src/router/lifecycle/lifecycle_annotations'; import {ComponentInstruction} from 'angular2/src/router/instruction'; @@ -28,14 +60,14 @@ export function main() { beforeEachProviders(() => TEST_ROUTER_PROVIDERS); - beforeEach(inject( - [TestComponentBuilder, Router], (tcBuilder: TestComponentBuilder, router: Router) => { - tcb = tcBuilder; - rtr = router; - cmpInstanceCount = 0; - log = []; - eventBus = new EventEmitter(); - })); + beforeEach(inject([TestComponentBuilder, Router], + (tcBuilder: TestComponentBuilder, router: Router) => { + tcb = tcBuilder; + rtr = router; + cmpInstanceCount = 0; + log = []; + eventBus = new EventEmitter(); + })); it('should call the routerOnActivate hook', inject([AsyncTestCompleter], (async) => { compile(tcb) @@ -61,14 +93,16 @@ export function main() { completer.resolve(true); } }); - rtr.navigateByUrl('/parent-activate/child-activate').then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('parent {activate cmp}'); - expect(log).toEqual([ - 'parent activate: null -> /parent-activate', 'activate: null -> /child-activate' - ]); - async.done(); - }); + rtr.navigateByUrl('/parent-activate/child-activate') + .then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText('parent {activate cmp}'); + expect(log).toEqual([ + 'parent activate: null -> /parent-activate', + 'activate: null -> /child-activate' + ]); + async.done(); + }); }); })); @@ -169,12 +203,13 @@ export function main() { completer.resolve(true); } }); - rtr.navigateByUrl('/can-activate/a').then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText('routerCanActivate {A}'); - expect(log).toEqual(['routerCanActivate: null -> /can-activate']); - async.done(); - }); + rtr.navigateByUrl('/can-activate/a') + .then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText('routerCanActivate {A}'); + expect(log).toEqual(['routerCanActivate: null -> /can-activate']); + async.done(); + }); }); })); @@ -189,12 +224,13 @@ export function main() { completer.resolve(false); } }); - rtr.navigateByUrl('/can-activate/a').then((_) => { - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement).toHaveText(''); - expect(log).toEqual(['routerCanActivate: null -> /can-activate']); - async.done(); - }); + rtr.navigateByUrl('/can-activate/a') + .then((_) => { + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement).toHaveText(''); + expect(log).toEqual(['routerCanActivate: null -> /can-activate']); + async.done(); + }); }); })); @@ -343,19 +379,19 @@ export function main() { } -@Component({selector: 'a-cmp', template: 'A'}) +@Component({selector: 'a-cmp', template: "A"}) class A { } -@Component({selector: 'b-cmp', template: 'B'}) +@Component({selector: 'b-cmp', template: "B"}) class B { } function logHook(name: string, next: ComponentInstruction, prev: ComponentInstruction) { var message = name + ': ' + (isPresent(prev) ? ('/' + prev.urlPath) : 'null') + ' -> ' + - (isPresent(next) ? ('/' + next.urlPath) : 'null'); + (isPresent(next) ? ('/' + next.urlPath) : 'null'); log.push(message); ObservableWrapper.callEmit(eventBus, message); } @@ -447,8 +483,8 @@ class NeverReuseCmp implements OnReuse, @RouteConfig([new Route({path: '/a', component: A}), new Route({path: '/b', component: B})]) @CanActivate(CanActivateCmp.routerCanActivate) class CanActivateCmp { - static routerCanActivate(next: ComponentInstruction, prev: ComponentInstruction): - Promise<boolean> { + static routerCanActivate(next: ComponentInstruction, + prev: ComponentInstruction): Promise<boolean> { completer = PromiseWrapper.completer(); logHook('routerCanActivate', next, prev); return completer.promise; @@ -557,7 +593,8 @@ class ReuseHooksCmp implements OnActivate, OnReuse, OnDeactivate, CanReuse, CanD directives: [RouterOutlet] }) @RouteConfig([ - new Route({path: '/a', component: A}), new Route({path: '/on-activate', component: ActivateCmp}), + new Route({path: '/a', component: A}), + new Route({path: '/on-activate', component: ActivateCmp}), new Route({path: '/parent-activate/...', component: ParentActivateCmp}), new Route({path: '/on-deactivate', component: DeactivateCmp}), new Route({path: '/parent-deactivate/...', component: ParentDeactivateCmp}), diff --git a/modules/angular2/test/router/integration/navigation_spec.ts b/modules/angular2/test/router/integration/navigation_spec.ts index 56a275d0f7..5b341ce59e 100644 --- a/modules/angular2/test/router/integration/navigation_spec.ts +++ b/modules/angular2/test/router/integration/navigation_spec.ts @@ -1,10 +1,31 @@ -import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, xdescribe, describe, el, expect, iit, inject, beforeEachProviders, it, xit} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + beforeEachProviders, + it, + xit +} from 'angular2/testing_internal'; import {provide, Component, Injector, Inject} from 'angular2/core'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {Router, RouterOutlet, RouterLink, RouteParams, RouteData, Location} from 'angular2/router'; -import {RouteConfig, Route, AuxRoute, AsyncRoute, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + Route, + AuxRoute, + AsyncRoute, + Redirect +} from 'angular2/src/router/route_config/route_config_decorator'; import {TEST_ROUTER_PROVIDERS, RootCmp, compile} from './util'; @@ -155,8 +176,9 @@ export function main() { it('should inject route data into component', inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/route-data', component: RouteDataCmp, data: {isAdmin: true}})])) + .then((_) => rtr.config([ + new Route({path: '/route-data', component: RouteDataCmp, data: {isAdmin: true}}) + ])) .then((_) => rtr.navigateByUrl('/route-data')) .then((_) => { fixture.detectChanges(); @@ -169,8 +191,10 @@ export function main() { inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new AsyncRoute( - {path: '/route-data', loader: asyncRouteDataCmp, data: {isAdmin: true}})])) + .then((_) => rtr.config([ + new AsyncRoute( + {path: '/route-data', loader: asyncRouteDataCmp, data: {isAdmin: true}}) + ])) .then((_) => rtr.navigateByUrl('/route-data')) .then((_) => { fixture.detectChanges(); @@ -183,8 +207,8 @@ export function main() { inject([AsyncTestCompleter], (async) => { compile(tcb) .then((rtc) => {fixture = rtc}) - .then((_) => rtr.config([new Route( - {path: '/route-data-default', component: RouteDataCmp})])) + .then((_) => rtr.config( + [new Route({path: '/route-data-default', component: RouteDataCmp})])) .then((_) => rtr.navigateByUrl('/route-data-default')) .then((_) => { fixture.detectChanges(); diff --git a/modules/angular2/test/router/integration/redirect_route_spec.ts b/modules/angular2/test/router/integration/redirect_route_spec.ts index fb0020fb04..84fd398eee 100644 --- a/modules/angular2/test/router/integration/redirect_route_spec.ts +++ b/modules/angular2/test/router/integration/redirect_route_spec.ts @@ -1,7 +1,28 @@ -import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, xdescribe, describe, el, expect, iit, inject, beforeEachProviders, it, xit} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + beforeEachProviders, + it, + xit +} from 'angular2/testing_internal'; import {Router, RouterOutlet, RouterLink, RouteParams, RouteData, Location} from 'angular2/router'; -import {RouteConfig, Route, AuxRoute, AsyncRoute, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + Route, + AuxRoute, + AsyncRoute, + Redirect +} from 'angular2/src/router/route_config/route_config_decorator'; import {TEST_ROUTER_PROVIDERS, RootCmp, compile} from './util'; import {HelloCmp, GoodbyeCmp, RedirectToParentCmp} from './impl/fixture_components'; diff --git a/modules/angular2/test/router/integration/router_link_spec.ts b/modules/angular2/test/router/integration/router_link_spec.ts index d77ee0fa78..ee16a413b9 100644 --- a/modules/angular2/test/router/integration/router_link_spec.ts +++ b/modules/angular2/test/router/integration/router_link_spec.ts @@ -1,4 +1,21 @@ -import {ComponentFixture, AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder, proxy, SpyObject} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + TestComponentBuilder, + proxy, + SpyObject +} from 'angular2/testing_internal'; import {By} from 'angular2/platform/common_dom'; import {NumberWrapper} from 'angular2/src/facade/lang'; @@ -8,7 +25,20 @@ import {ListWrapper} from 'angular2/src/facade/collection'; import {provide, Component, DirectiveResolver} from 'angular2/core'; import {SpyLocation} from 'angular2/src/mock/location_mock'; -import {Location, Router, RouteRegistry, RouterLink, RouterOutlet, AsyncRoute, AuxRoute, Route, RouteParams, RouteConfig, ROUTER_DIRECTIVES, ROUTER_PRIMARY_COMPONENT} from 'angular2/router'; +import { + Location, + Router, + RouteRegistry, + RouterLink, + RouterOutlet, + AsyncRoute, + AuxRoute, + Route, + RouteParams, + RouteConfig, + ROUTER_DIRECTIVES, + ROUTER_PRIMARY_COMPONENT +} from 'angular2/router'; import {RootRouter} from 'angular2/src/router/router'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; @@ -22,21 +52,23 @@ export function main() { var router: Router; var location: Location; - beforeEachProviders( - () => - [RouteRegistry, DirectiveResolver, provide(Location, {useClass: SpyLocation}), - provide(ROUTER_PRIMARY_COMPONENT, {useValue: MyComp}), - provide(Router, {useClass: RootRouter}), - provide(TEMPLATE_TRANSFORMS, {useClass: RouterLinkTransform, multi: true})]); + beforeEachProviders(() => [ + RouteRegistry, + DirectiveResolver, + provide(Location, {useClass: SpyLocation}), + provide(ROUTER_PRIMARY_COMPONENT, {useValue: MyComp}), + provide(Router, {useClass: RootRouter}), + provide(TEMPLATE_TRANSFORMS, {useClass: RouterLinkTransform, multi: true}) + ]); - beforeEach(inject( - [TestComponentBuilder, Router, Location], (tcBuilder, rtr: Router, loc: Location) => { - tcb = tcBuilder; - router = rtr; - location = loc; - })); + beforeEach(inject([TestComponentBuilder, Router, Location], + (tcBuilder, rtr: Router, loc: Location) => { + tcb = tcBuilder; + router = rtr; + location = loc; + })); - function compile(template: string = '<router-outlet></router-outlet>') { + function compile(template: string = "<router-outlet></router-outlet>") { return tcb.overrideTemplate(MyComp, ('<div>' + template + '</div>')) .createAsync(MyComp) .then((tc) => { fixture = tc; }); @@ -46,9 +78,8 @@ export function main() { inject([AsyncTestCompleter], (async) => { (<SpyLocation>location).setBaseHref('/my/base'); compile('<a href="hello" [routerLink]="[\'./User\']"></a>') - .then( - (_) => - router.config([new Route({path: '/user', component: UserCmp, name: 'User'})])) + .then((_) => router.config( + [new Route({path: '/user', component: UserCmp, name: 'User'})])) .then((_) => router.navigateByUrl('/a/b')) .then((_) => { fixture.detectChanges(); @@ -60,9 +91,8 @@ export function main() { it('should generate link hrefs without params', inject([AsyncTestCompleter], (async) => { compile('<a href="hello" [routerLink]="[\'./User\']"></a>') - .then( - (_) => - router.config([new Route({path: '/user', component: UserCmp, name: 'User'})])) + .then((_) => router.config( + [new Route({path: '/user', component: UserCmp, name: 'User'})])) .then((_) => router.navigateByUrl('/a/b')) .then((_) => { fixture.detectChanges(); @@ -74,8 +104,8 @@ export function main() { it('should generate link hrefs with params', inject([AsyncTestCompleter], (async) => { compile('<a href="hello" [routerLink]="[\'./User\', {name: name}]">{{name}}</a>') - .then((_) => router.config([new Route( - {path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => router.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => router.navigateByUrl('/a/b')) .then((_) => { fixture.debugElement.componentInstance.name = 'brian'; @@ -89,8 +119,9 @@ export function main() { it('should generate link hrefs from a child to its sibling', inject([AsyncTestCompleter], (async) => { compile() - .then((_) => router.config([new Route( - {path: '/page/:number', component: SiblingPageCmp, name: 'Page'})])) + .then( + (_) => router.config( + [new Route({path: '/page/:number', component: SiblingPageCmp, name: 'Page'})])) .then((_) => router.navigateByUrl('/page/1')) .then((_) => { fixture.detectChanges(); @@ -102,8 +133,10 @@ export function main() { it('should generate link hrefs from a child to its sibling with no leading slash', inject([AsyncTestCompleter], (async) => { compile() - .then((_) => router.config([new Route( - {path: '/page/:number', component: NoPrefixSiblingPageCmp, name: 'Page'})])) + .then((_) => router.config([ + new Route( + {path: '/page/:number', component: NoPrefixSiblingPageCmp, name: 'Page'}) + ])) .then((_) => router.navigateByUrl('/page/1')) .then((_) => { fixture.detectChanges(); @@ -115,8 +148,9 @@ export function main() { it('should generate link hrefs to a child with no leading slash', inject([AsyncTestCompleter], (async) => { compile() - .then((_) => router.config([new Route( - {path: '/book/:title/...', component: NoPrefixBookCmp, name: 'Book'})])) + .then((_) => router.config([ + new Route({path: '/book/:title/...', component: NoPrefixBookCmp, name: 'Book'}) + ])) .then((_) => router.navigateByUrl('/book/1984/page/1')) .then((_) => { fixture.detectChanges(); @@ -128,8 +162,9 @@ export function main() { it('should throw when links without a leading slash are ambiguous', inject([AsyncTestCompleter], (async) => { compile() - .then((_) => router.config([new Route( - {path: '/book/:title/...', component: AmbiguousBookCmp, name: 'Book'})])) + .then((_) => router.config([ + new Route({path: '/book/:title/...', component: AmbiguousBookCmp, name: 'Book'}) + ])) .then((_) => router.navigateByUrl('/book/1984/page/1')) .then((_) => { var link = ListWrapper.toJSON(['Book', {number: 100}]); @@ -143,11 +178,13 @@ export function main() { it('should generate link hrefs when asynchronously loaded', inject([AsyncTestCompleter], (async) => { compile() - .then((_) => router.config([new AsyncRoute({ - path: '/child-with-grandchild/...', - loader: parentCmpLoader, - name: 'ChildWithGrandchild' - })])) + .then((_) => router.config([ + new AsyncRoute({ + path: '/child-with-grandchild/...', + loader: parentCmpLoader, + name: 'ChildWithGrandchild' + }) + ])) .then((_) => router.navigateByUrl('/child-with-grandchild/grandchild')) .then((_) => { fixture.detectChanges(); @@ -159,26 +196,24 @@ export function main() { it('should generate relative links preserving the existing parent route', inject([AsyncTestCompleter], (async) => { compile() - .then((_) => router.config([new Route( - {path: '/book/:title/...', component: BookCmp, name: 'Book'})])) + .then((_) => router.config( + [new Route({path: '/book/:title/...', component: BookCmp, name: 'Book'})])) .then((_) => router.navigateByUrl('/book/1984/page/1')) .then((_) => { fixture.detectChanges(); // TODO(juliemr): This should be one By.css('book-cmp a') query, but the parse5 // adapter // can't handle css child selectors. - expect(DOM.getAttribute( - fixture.debugElement.query(By.css('book-cmp')) - .query(By.css('a')) - .nativeElement, - 'href')) + expect(DOM.getAttribute(fixture.debugElement.query(By.css('book-cmp')) + .query(By.css('a')) + .nativeElement, + 'href')) .toEqual('/book/1984/page/100'); - expect(DOM.getAttribute( - fixture.debugElement.query(By.css('page-cmp')) - .query(By.css('a')) - .nativeElement, - 'href')) + expect(DOM.getAttribute(fixture.debugElement.query(By.css('page-cmp')) + .query(By.css('a')) + .nativeElement, + 'href')) .toEqual('/book/1984/page/2'); async.done(); }); @@ -198,11 +233,10 @@ export function main() { describe('router-link-active CSS class', () => { it('should be added to the associated element', inject([AsyncTestCompleter], (async) => { - router - .config([ - new Route({path: '/child', component: HelloCmp, name: 'Child'}), - new Route({path: '/better-child', component: Hello2Cmp, name: 'BetterChild'}) - ]) + router.config([ + new Route({path: '/child', component: HelloCmp, name: 'Child'}), + new Route({path: '/better-child', component: Hello2Cmp, name: 'BetterChild'}) + ]) .then((_) => compile(`<a [routerLink]="['./Child']" class="child-link">Child</a> <a [routerLink]="['./BetterChild']" class="better-child-link">Better Child</a> <router-outlet></router-outlet>`)) @@ -230,14 +264,14 @@ export function main() { })); it('should be added to links in child routes', inject([AsyncTestCompleter], (async) => { - router - .config([ - new Route({path: '/child', component: HelloCmp, name: 'Child'}), new Route({ - path: '/child-with-grandchild/...', - component: ParentCmp, - name: 'ChildWithGrandchild' - }) - ]) + router.config([ + new Route({path: '/child', component: HelloCmp, name: 'Child'}), + new Route({ + path: '/child-with-grandchild/...', + component: ParentCmp, + name: 'ChildWithGrandchild' + }) + ]) .then((_) => compile(`<a [routerLink]="['./Child']" class="child-link">Child</a> <a [routerLink]="['./ChildWithGrandchild/Grandchild']" class="child-with-grandchild-link">Better Child</a> <router-outlet></router-outlet>`)) @@ -274,8 +308,8 @@ export function main() { describe('router link dsl', () => { it('should generate link hrefs with params', inject([AsyncTestCompleter], (async) => { compile('<a href="hello" [routerLink]="route:./User(name: name)">{{name}}</a>') - .then((_) => router.config([new Route( - {path: '/user/:name', component: UserCmp, name: 'User'})])) + .then((_) => router.config( + [new Route({path: '/user/:name', component: UserCmp, name: 'User'})])) .then((_) => router.navigateByUrl('/a/b')) .then((_) => { fixture.debugElement.componentInstance.name = 'brian'; @@ -299,8 +333,8 @@ export function main() { it('should navigate to link hrefs without params', inject([AsyncTestCompleter], (async) => { compile('<a href="hello" [routerLink]="[\'./User\']"></a>') - .then((_) => router.config([new Route( - {path: '/user', component: UserCmp, name: 'User'})])) + .then((_) => router.config( + [new Route({path: '/user', component: UserCmp, name: 'User'})])) .then((_) => router.navigateByUrl('/a/b')) .then((_) => { fixture.detectChanges(); @@ -320,8 +354,8 @@ export function main() { inject([AsyncTestCompleter], (async) => { (<SpyLocation>location).setBaseHref('/base'); compile('<a href="hello" [routerLink]="[\'./User\']"></a>') - .then((_) => router.config([new Route( - {path: '/user', component: UserCmp, name: 'User'})])) + .then((_) => router.config( + [new Route({path: '/user', component: UserCmp, name: 'User'})])) .then((_) => router.navigateByUrl('/a/b')) .then((_) => { fixture.detectChanges(); @@ -350,7 +384,7 @@ class MyComp { name; } -@Component({selector: 'user-cmp', template: 'hello {{user}}'}) +@Component({selector: 'user-cmp', template: "hello {{user}}"}) class UserCmp { user: string; constructor(params: RouteParams) { this.user = params.get('name'); } diff --git a/modules/angular2/test/router/integration/sync_route_spec.ts b/modules/angular2/test/router/integration/sync_route_spec.ts index 612b7ce9ac..3d40441006 100644 --- a/modules/angular2/test/router/integration/sync_route_spec.ts +++ b/modules/angular2/test/router/integration/sync_route_spec.ts @@ -1,4 +1,12 @@ -import {describeRouter, ddescribeRouter, describeWith, describeWithout, describeWithAndWithout, itShouldRoute, TEST_ROUTER_PROVIDERS} from './util'; +import { + describeRouter, + ddescribeRouter, + describeWith, + describeWithout, + describeWithAndWithout, + itShouldRoute, + TEST_ROUTER_PROVIDERS +} from './util'; import {beforeEachProviders, describe, ddescribe} from 'angular2/testing_internal'; @@ -15,8 +23,8 @@ export function main() { describeWithout('children', () => { describeWithAndWithout('params', itShouldRoute); }); describeWith('sync children', () => { - describeWithout( - 'default routes', () => { describeWithAndWithout('params', itShouldRoute); }); + describeWithout('default routes', + () => { describeWithAndWithout('params', itShouldRoute); }); describeWith('default routes', () => { describeWithout('params', itShouldRoute); }); }); diff --git a/modules/angular2/test/router/integration/util.ts b/modules/angular2/test/router/integration/util.ts index 8c90ac1803..779643f6d0 100644 --- a/modules/angular2/test/router/integration/util.ts +++ b/modules/angular2/test/router/integration/util.ts @@ -2,7 +2,20 @@ import {provide, Provider, Component} from 'angular2/core'; import {Type, isBlank} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; -import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, xdescribe, describe, el, inject, beforeEachProviders, it, xit} from 'angular2/testing_internal'; +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + inject, + beforeEachProviders, + it, + xit +} from 'angular2/testing_internal'; import {RootRouter} from 'angular2/src/router/router'; import {Router, ROUTER_DIRECTIVES, ROUTER_PRIMARY_COMPONENT} from 'angular2/router'; @@ -28,14 +41,17 @@ export class RootCmp { name: string; } -export function compile( - tcb: TestComponentBuilder, template: string = '<router-outlet></router-outlet>') { +export function compile(tcb: TestComponentBuilder, + template: string = "<router-outlet></router-outlet>") { return tcb.overrideTemplate(RootCmp, ('<div>' + template + '</div>')).createAsync(RootCmp); } export var TEST_ROUTER_PROVIDERS = [ - RouteRegistry, DirectiveResolver, provide(Location, {useClass: SpyLocation}), - provide(ROUTER_PRIMARY_COMPONENT, {useValue: RootCmp}), provide(Router, {useClass: RootRouter}) + RouteRegistry, + DirectiveResolver, + provide(Location, {useClass: SpyLocation}), + provide(ROUTER_PRIMARY_COMPONENT, {useValue: RootCmp}), + provide(Router, {useClass: RootRouter}) ]; export function clickOnElement(anchorEl) { diff --git a/modules/angular2/test/router/location/hash_location_strategy_spec.ts b/modules/angular2/test/router/location/hash_location_strategy_spec.ts index 6b18e069ee..ad79255819 100644 --- a/modules/angular2/test/router/location/hash_location_strategy_spec.ts +++ b/modules/angular2/test/router/location/hash_location_strategy_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, describe, proxy, it, iit, ddescribe, expect, inject, beforeEach, beforeEachProviders, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + proxy, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + beforeEachProviders, + SpyObject +} from 'angular2/testing_internal'; import {Injector, provide} from 'angular2/core'; diff --git a/modules/angular2/test/router/location/location_spec.ts b/modules/angular2/test/router/location/location_spec.ts index e64074d96a..09e1296b97 100644 --- a/modules/angular2/test/router/location/location_spec.ts +++ b/modules/angular2/test/router/location/location_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, describe, proxy, it, iit, ddescribe, expect, inject, beforeEach, beforeEachProviders, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + proxy, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + beforeEachProviders, + SpyObject +} from 'angular2/testing_internal'; import {Injector, provide} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; @@ -69,8 +81,8 @@ export function main() { var locationStrategy = new MockLocationStrategy(); var location = new Location(locationStrategy); - location.go('/home', 'key=value'); - expect(location.path()).toEqual('/home?key=value'); + location.go('/home', "key=value"); + expect(location.path()).toEqual("/home?key=value"); }); }); } diff --git a/modules/angular2/test/router/location/path_location_strategy_spec.ts b/modules/angular2/test/router/location/path_location_strategy_spec.ts index 78d84a68c0..c884b1e6bb 100644 --- a/modules/angular2/test/router/location/path_location_strategy_spec.ts +++ b/modules/angular2/test/router/location/path_location_strategy_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, describe, proxy, it, iit, ddescribe, expect, inject, beforeEach, beforeEachProviders, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + proxy, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + beforeEachProviders, + SpyObject +} from 'angular2/testing_internal'; import {Injector, provide} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; @@ -12,9 +24,10 @@ export function main() { describe('PathLocationStrategy', () => { var platformLocation, locationStrategy; - beforeEachProviders(() => [PathLocationStrategy, provide(PlatformLocation, { - useFactory: makeSpyPlatformLocation - })]); + beforeEachProviders(() => [ + PathLocationStrategy, + provide(PlatformLocation, {useFactory: makeSpyPlatformLocation}) + ]); it('should throw without a base element or APP_BASE_HREF', () => { platformLocation = new SpyPlatformLocation(); diff --git a/modules/angular2/test/router/route_config/route_config_spec.ts b/modules/angular2/test/router/route_config/route_config_spec.ts index 3189c09156..7da0123fff 100644 --- a/modules/angular2/test/router/route_config/route_config_spec.ts +++ b/modules/angular2/test/router/route_config/route_config_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit, +} from 'angular2/testing_internal'; import {bootstrap} from 'angular2/platform/browser'; import {Component, Directive} from 'angular2/src/core/metadata'; @@ -8,7 +19,13 @@ import {provide} from 'angular2/core'; import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; import {Type, IS_DART} from 'angular2/src/facade/lang'; -import {ROUTER_PROVIDERS, Router, RouteConfig, APP_BASE_HREF, ROUTER_DIRECTIVES} from 'angular2/router'; +import { + ROUTER_PROVIDERS, + Router, + RouteConfig, + APP_BASE_HREF, + ROUTER_DIRECTIVES +} from 'angular2/router'; import {ExceptionHandler} from 'angular2/src/facade/exceptions'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy'; @@ -36,7 +53,8 @@ export function main() { var logger = new _ArrayLogger(); var exceptionHandler = new ExceptionHandler(logger, false); testBindings = [ - ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: MockLocationStrategy}), + ROUTER_PROVIDERS, + provide(LocationStrategy, {useClass: MockLocationStrategy}), provide(DOCUMENT, {useValue: fakeDoc}), provide(ExceptionHandler, {useValue: exceptionHandler}), provide(Console, {useClass: DummyConsole}) @@ -44,138 +62,153 @@ export function main() { }); it('should bootstrap an app with a hierarchy', inject([AsyncTestCompleter], (async) => { - bootstrap(HierarchyAppCmp, testBindings).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('root { parent { hello } }'); - expect(applicationRef.hostComponent.location.path()).toEqual('/parent/child'); - async.done(); - }); - router.navigateByUrl('/parent/child'); - }); + bootstrap(HierarchyAppCmp, testBindings) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('root { parent { hello } }'); + expect(applicationRef.hostComponent.location.path()).toEqual('/parent/child'); + async.done(); + }); + router.navigateByUrl('/parent/child'); + }); })); it('should work in an app with redirects', inject([AsyncTestCompleter], (async) => { - bootstrap(RedirectAppCmp, testBindings).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('root { hello }'); - expect(applicationRef.hostComponent.location.path()).toEqual('/after'); - async.done(); - }); - router.navigateByUrl('/before'); - }); + bootstrap(RedirectAppCmp, testBindings) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('root { hello }'); + expect(applicationRef.hostComponent.location.path()).toEqual('/after'); + async.done(); + }); + router.navigateByUrl('/before'); + }); })); it('should work in an app with async components', inject([AsyncTestCompleter], (async) => { - bootstrap(AsyncAppCmp, testBindings).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('root { hello }'); - expect(applicationRef.hostComponent.location.path()).toEqual('/hello'); - async.done(); - }); - router.navigateByUrl('/hello'); - }); + bootstrap(AsyncAppCmp, testBindings) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('root { hello }'); + expect(applicationRef.hostComponent.location.path()).toEqual('/hello'); + async.done(); + }); + router.navigateByUrl('/hello'); + }); })); it('should work in an app with aux routes', inject([AsyncTestCompleter], (async) => { - bootstrap(AuxAppCmp, testBindings).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('root { hello } aside { hello }'); - expect(applicationRef.hostComponent.location.path()).toEqual('/hello(aside)'); - async.done(); - }); - router.navigateByUrl('/hello(aside)'); - }); + bootstrap(AuxAppCmp, testBindings) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('root { hello } aside { hello }'); + expect(applicationRef.hostComponent.location.path()).toEqual('/hello(aside)'); + async.done(); + }); + router.navigateByUrl('/hello(aside)'); + }); })); it('should work in an app with async components defined with "loader"', inject([AsyncTestCompleter], (async) => { - bootstrap(ConciseAsyncAppCmp, testBindings).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('root { hello }'); - expect(applicationRef.hostComponent.location.path()).toEqual('/hello'); - async.done(); - }); - router.navigateByUrl('/hello'); - }); + bootstrap(ConciseAsyncAppCmp, testBindings) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('root { hello }'); + expect(applicationRef.hostComponent.location.path()).toEqual('/hello'); + async.done(); + }); + router.navigateByUrl('/hello'); + }); })); it('should work in an app with a constructor component', inject([AsyncTestCompleter], (async) => { - bootstrap(ExplicitConstructorAppCmp, testBindings).then((applicationRef) => { - var router = applicationRef.hostComponent.router; - router.subscribe((_) => { - expect(el).toHaveText('root { hello }'); - expect(applicationRef.hostComponent.location.path()).toEqual('/hello'); - async.done(); - }); - router.navigateByUrl('/hello'); - }); + bootstrap(ExplicitConstructorAppCmp, testBindings) + .then((applicationRef) => { + var router = applicationRef.hostComponent.router; + router.subscribe((_) => { + expect(el).toHaveText('root { hello }'); + expect(applicationRef.hostComponent.location.path()).toEqual('/hello'); + async.done(); + }); + router.navigateByUrl('/hello'); + }); })); it('should throw if a config is missing a target', inject( [AsyncTestCompleter], - (async) => {bootstrap(WrongConfigCmp, testBindings).catch((e) => { - expect(e.originalException) - .toContainError( - 'Route config should contain exactly one "component", "loader", or "redirectTo" property.'); - async.done(); - return null; - })})); + (async) => { + bootstrap(WrongConfigCmp, testBindings) + .catch((e) => { + expect(e.originalException) + .toContainError( + 'Route config should contain exactly one "component", "loader", or "redirectTo" property.'); + async.done(); + return null; + })})); it('should throw if a config has an invalid component type', inject( [AsyncTestCompleter], - (async) => {bootstrap(WrongComponentTypeCmp, testBindings).catch((e) => { - expect(e.originalException) - .toContainError( - 'Invalid component type "intentionallyWrongComponentType". Valid types are "constructor" and "loader".'); - async.done(); - return null; - })})); + (async) => { + bootstrap(WrongComponentTypeCmp, testBindings) + .catch((e) => { + expect(e.originalException) + .toContainError( + 'Invalid component type "intentionallyWrongComponentType". Valid types are "constructor" and "loader".'); + async.done(); + return null; + })})); it('should throw if a config has an invalid alias name', inject( [AsyncTestCompleter], - (async) => {bootstrap(BadAliasNameCmp, testBindings).catch((e) => { - expect(e.originalException) - .toContainError( - `Route "/child" with name "child" does not begin with an uppercase letter. Route names should be CamelCase like "Child".`); - async.done(); - return null; - })})); + (async) => { + bootstrap(BadAliasNameCmp, testBindings) + .catch((e) => { + expect(e.originalException) + .toContainError( + `Route "/child" with name "child" does not begin with an uppercase letter. Route names should be CamelCase like "Child".`); + async.done(); + return null; + })})); it('should throw if a config has an invalid alias name with "as"', inject( [AsyncTestCompleter], - (async) => {bootstrap(BadAliasCmp, testBindings).catch((e) => { - expect(e.originalException) - .toContainError( - `Route "/child" with name "child" does not begin with an uppercase letter. Route names should be CamelCase like "Child".`); - async.done(); - return null; - })})); + (async) => { + bootstrap(BadAliasCmp, testBindings) + .catch((e) => { + expect(e.originalException) + .toContainError( + `Route "/child" with name "child" does not begin with an uppercase letter. Route names should be CamelCase like "Child".`); + async.done(); + return null; + })})); it('should throw if a config has multiple alias properties "as" and "name"', - inject( - [AsyncTestCompleter], - (async) => {bootstrap(MultipleAliasCmp, testBindings).catch((e) => { - expect(e.originalException) - .toContainError( - `Route config should contain exactly one "as" or "name" property.`); - async.done(); - return null; - })})); + inject([AsyncTestCompleter], + (async) => { + bootstrap(MultipleAliasCmp, testBindings) + .catch((e) => { + expect(e.originalException) + .toContainError( + `Route config should contain exactly one "as" or "name" property.`); + async.done(); + return null; + })})); }); } @@ -190,7 +223,8 @@ class HelloCmp { directives: ROUTER_DIRECTIVES }) @RouteConfig([ - {path: '/before', redirectTo: ['Hello']}, {path: '/after', component: HelloCmp, name: 'Hello'} + {path: '/before', redirectTo: ['Hello']}, + {path: '/after', component: HelloCmp, name: 'Hello'} ]) class RedirectAppCmp { constructor(public router: Router, public location: LocationStrategy) {} diff --git a/modules/angular2/test/router/route_registry_spec.ts b/modules/angular2/test/router/route_registry_spec.ts index 5b9c348f77..a204cf52a1 100644 --- a/modules/angular2/test/router/route_registry_spec.ts +++ b/modules/angular2/test/router/route_registry_spec.ts @@ -1,10 +1,26 @@ -import {AsyncTestCompleter, describe, it, iit, ddescribe, expect, inject, beforeEach, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {Type, IS_DART} from 'angular2/src/facade/lang'; import {RouteRegistry} from 'angular2/src/router/route_registry'; -import {RouteConfig, Route, Redirect, AuxRoute, AsyncRoute} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + Route, + Redirect, + AuxRoute, + AsyncRoute +} from 'angular2/src/router/route_config/route_config_decorator'; export function main() { @@ -17,16 +33,16 @@ export function main() { registry.config(RootHostCmp, new Route({path: '/', component: DummyCmpA})); registry.config(RootHostCmp, new Route({path: '/test', component: DummyCmpB})); - registry.recognize('/test', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpB); - async.done(); - }); + registry.recognize('/test', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpB); + async.done(); + }); })); it('should generate URLs starting at the given component', () => { - registry.config( - RootHostCmp, - new Route({path: '/first/...', component: DummyParentCmp, name: 'FirstCmp'})); + registry.config(RootHostCmp, + new Route({path: '/first/...', component: DummyParentCmp, name: 'FirstCmp'})); var instr = registry.generate(['FirstCmp', 'SecondCmp'], []); expect(stringifyInstruction(instr)).toEqual('first/second'); @@ -76,8 +92,8 @@ export function main() { }); it('should generate URLs with extra params in the query', () => { - registry.config( - RootHostCmp, new Route({path: '/first/second', component: DummyCmpA, name: 'FirstCmp'})); + registry.config(RootHostCmp, + new Route({path: '/first/second', component: DummyCmpA, name: 'FirstCmp'})); var instruction = registry.generate(['FirstCmp', {a: 'one'}], []); expect(instruction.toLinkUrl()).toEqual('first/second?a=one'); @@ -94,78 +110,84 @@ export function main() { expect(stringifyInstruction(instruction)).toEqual('first'); - registry.recognize('/first/second', []).then((_) => { - var instruction = registry.generate(['FirstCmp', 'SecondCmp'], []); - expect(stringifyInstruction(instruction)).toEqual('first/second'); - async.done(); - }); + registry.recognize('/first/second', []) + .then((_) => { + var instruction = registry.generate(['FirstCmp', 'SecondCmp'], []); + expect(stringifyInstruction(instruction)).toEqual('first/second'); + async.done(); + }); })); it('should throw when generating a url and a parent has no config', () => { - expect(() => registry.generate(['FirstCmp', 'SecondCmp'], [ - ])).toThrowError('Component "RootHostCmp" has no route config.'); + expect(() => registry.generate(['FirstCmp', 'SecondCmp'], [])) + .toThrowError('Component "RootHostCmp" has no route config.'); }); it('should generate URLs for aux routes', () => { - registry.config( - RootHostCmp, new Route({path: '/primary', component: DummyCmpA, name: 'Primary'})); + registry.config(RootHostCmp, + new Route({path: '/primary', component: DummyCmpA, name: 'Primary'})); registry.config(RootHostCmp, new AuxRoute({path: '/aux', component: DummyCmpB, name: 'Aux'})); - expect(stringifyInstruction(registry.generate(['Primary', ['Aux']], [ - ]))).toEqual('primary(aux)'); + expect(stringifyInstruction(registry.generate(['Primary', ['Aux']], []))) + .toEqual('primary(aux)'); }); it('should prefer static segments to dynamic', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/:site', component: DummyCmpB})); registry.config(RootHostCmp, new Route({path: '/home', component: DummyCmpA})); - registry.recognize('/home', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpA); - async.done(); - }); + registry.recognize('/home', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpA); + async.done(); + }); })); it('should prefer dynamic segments to star', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/:site', component: DummyCmpA})); registry.config(RootHostCmp, new Route({path: '/*site', component: DummyCmpB})); - registry.recognize('/home', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpA); - async.done(); - }); + registry.recognize('/home', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpA); + async.done(); + }); })); it('should prefer routes with more dynamic segments', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/:first/*rest', component: DummyCmpA})); registry.config(RootHostCmp, new Route({path: '/*all', component: DummyCmpB})); - registry.recognize('/some/path', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpA); - async.done(); - }); + registry.recognize('/some/path', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpA); + async.done(); + }); })); it('should prefer routes with more static segments', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/first/:second', component: DummyCmpA})); registry.config(RootHostCmp, new Route({path: '/:first/:second', component: DummyCmpB})); - registry.recognize('/first/second', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpA); - async.done(); - }); + registry.recognize('/first/second', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpA); + async.done(); + }); })); it('should prefer routes with static segments before dynamic segments', inject([AsyncTestCompleter], (async) => { - registry.config( - RootHostCmp, new Route({path: '/first/second/:third', component: DummyCmpB})); - registry.config( - RootHostCmp, new Route({path: '/first/:second/third', component: DummyCmpA})); + registry.config(RootHostCmp, + new Route({path: '/first/second/:third', component: DummyCmpB})); + registry.config(RootHostCmp, + new Route({path: '/first/:second/third', component: DummyCmpA})); - registry.recognize('/first/second/third', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpB); - async.done(); - }); + registry.recognize('/first/second/third', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpB); + async.done(); + }); })); it('should prefer routes with high specificity over routes with children with lower specificity', @@ -173,66 +195,69 @@ export function main() { registry.config(RootHostCmp, new Route({path: '/first', component: DummyCmpA})); // terminates to DummyCmpB - registry.config( - RootHostCmp, new Route({path: '/:second/...', component: SingleSlashChildCmp})); + registry.config(RootHostCmp, + new Route({path: '/:second/...', component: SingleSlashChildCmp})); - registry.recognize('/first', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyCmpA); - async.done(); - }); + registry.recognize('/first', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyCmpA); + async.done(); + }); })); it('should match the full URL using child components', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/first/...', component: DummyParentCmp})); - registry.recognize('/first/second', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyParentCmp); - expect(instruction.child.component.componentType).toBe(DummyCmpB); - async.done(); - }); + registry.recognize('/first/second', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyParentCmp); + expect(instruction.child.component.componentType).toBe(DummyCmpB); + async.done(); + }); })); it('should match the URL using async child components', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/first/...', component: DummyAsyncCmp})); - registry.recognize('/first/second', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyAsyncCmp); + registry.recognize('/first/second', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyAsyncCmp); - instruction.child.resolveComponent().then((childComponentInstruction) => { - expect(childComponentInstruction.componentType).toBe(DummyCmpB); - async.done(); - }); - }); + instruction.child.resolveComponent().then((childComponentInstruction) => { + expect(childComponentInstruction.componentType).toBe(DummyCmpB); + async.done(); + }); + }); })); it('should match the URL using an async parent component', inject([AsyncTestCompleter], (async) => { - registry.config( - RootHostCmp, new AsyncRoute({path: '/first/...', loader: asyncParentLoader})); + registry.config(RootHostCmp, + new AsyncRoute({path: '/first/...', loader: asyncParentLoader})); - registry.recognize('/first/second', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyParentCmp); + registry.recognize('/first/second', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyParentCmp); - instruction.child.resolveComponent().then((childType) => { - expect(childType.componentType).toBe(DummyCmpB); - async.done(); - }); - }); + instruction.child.resolveComponent().then((childType) => { + expect(childType.componentType).toBe(DummyCmpB); + async.done(); + }); + }); })); it('should throw when a parent config is missing the `...` suffix any of its children add routes', () => { - expect( - () => registry.config(RootHostCmp, new Route({path: '/', component: DummyParentCmp}))) + expect(() => + registry.config(RootHostCmp, new Route({path: '/', component: DummyParentCmp}))) .toThrowError( 'Child routes are not allowed for "/". Use "..." on the parent\'s route path.'); }); it('should throw when a parent config uses `...` suffix before the end of the route', () => { - expect( - () => registry.config( - RootHostCmp, new Route({path: '/home/.../fun/', component: DummyParentCmp}))) + expect(() => registry.config(RootHostCmp, + new Route({path: '/home/.../fun/', component: DummyParentCmp}))) .toThrowError('Unexpected "..." before the end of the path for "home/.../fun/".'); }); @@ -245,32 +270,31 @@ export function main() { // This would never happen in Dart if (!IS_DART) { - expect( - () => registry.config(RootHostCmp, new Route({path: '/', component: <Type>(<any>4)}))) + expect(() => registry.config(RootHostCmp, new Route({path: '/', component:<Type>(<any>4)}))) .toThrowError('Component for route "/" is not defined, or is not a class.'); } }); it('should throw when linkParams are not terminal', () => { - registry.config( - RootHostCmp, new Route({path: '/first/...', component: DummyParentCmp, name: 'First'})); - expect(() => { - registry.generate(['First'], []); - }).toThrowError('Link "["First"]" does not resolve to a terminal instruction.'); + registry.config(RootHostCmp, + new Route({path: '/first/...', component: DummyParentCmp, name: 'First'})); + expect(() => { registry.generate(['First'], []); }) + .toThrowError('Link "["First"]" does not resolve to a terminal instruction.'); }); it('should match matrix params on child components and query params on the root component', inject([AsyncTestCompleter], (async) => { registry.config(RootHostCmp, new Route({path: '/first/...', component: DummyParentCmp})); - registry.recognize('/first/second;filter=odd?comments=all', []).then((instruction) => { - expect(instruction.component.componentType).toBe(DummyParentCmp); - expect(instruction.component.params).toEqual({'comments': 'all'}); + registry.recognize('/first/second;filter=odd?comments=all', []) + .then((instruction) => { + expect(instruction.component.componentType).toBe(DummyParentCmp); + expect(instruction.component.params).toEqual({'comments': 'all'}); - expect(instruction.child.component.componentType).toBe(DummyCmpB); - expect(instruction.child.component.params).toEqual({'filter': 'odd'}); - async.done(); - }); + expect(instruction.child.component.componentType).toBe(DummyCmpB); + expect(instruction.child.component.params).toEqual({'filter': 'odd'}); + async.done(); + }); })); it('should generate URLs with matrix and query params', () => { @@ -280,7 +304,10 @@ export function main() { var url = stringifyInstruction(registry.generate( [ - 'FirstCmp', {param: 'one', query: 'cats'}, 'SecondCmp', { + 'FirstCmp', + {param: 'one', query: 'cats'}, + 'SecondCmp', + { param: 'two', sort: 'asc', } @@ -324,8 +351,10 @@ class SingleSlashChildCmp { } -@RouteConfig([new Route( - {path: '/second/...', component: DefaultRouteCmp, name: 'SecondCmp', useAsDefault: true})]) +@RouteConfig([ + new Route( + {path: '/second/...', component: DefaultRouteCmp, name: 'SecondCmp', useAsDefault: true}) +]) class MultipleDefaultCmp { } diff --git a/modules/angular2/test/router/router_spec.ts b/modules/angular2/test/router/router_spec.ts index 1db0d06d44..687ca936d1 100644 --- a/modules/angular2/test/router/router_spec.ts +++ b/modules/angular2/test/router/router_spec.ts @@ -1,4 +1,16 @@ -import {AsyncTestCompleter, describe, proxy, it, iit, xit, ddescribe, expect, inject, beforeEach, beforeEachProviders} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + proxy, + it, + iit, + xit, + ddescribe, + expect, + inject, + beforeEach, + beforeEachProviders +} from 'angular2/testing_internal'; import {SpyRouterOutlet} from './spies'; import {Type} from 'angular2/src/facade/lang'; import {PromiseWrapper, ObservableWrapper} from 'angular2/src/facade/async'; @@ -9,7 +21,12 @@ import {SpyLocation} from 'angular2/src/mock/location_mock'; import {Location} from 'angular2/src/router/location/location'; import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/src/router/route_registry'; -import {RouteConfig, AsyncRoute, Route, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; +import { + RouteConfig, + AsyncRoute, + Route, + Redirect +} from 'angular2/src/router/route_config/route_config_decorator'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; import {provide} from 'angular2/core'; @@ -20,11 +37,13 @@ export function main() { var router: Router; var location: Location; - beforeEachProviders( - () => - [RouteRegistry, DirectiveResolver, provide(Location, {useClass: SpyLocation}), - provide(ROUTER_PRIMARY_COMPONENT, {useValue: AppCmp}), - provide(Router, {useClass: RootRouter})]); + beforeEachProviders(() => [ + RouteRegistry, + DirectiveResolver, + provide(Location, {useClass: SpyLocation}), + provide(ROUTER_PRIMARY_COMPONENT, {useValue: AppCmp}), + provide(Router, {useClass: RootRouter}) + ]); beforeEach(inject([Router, Location], (rtr: Router, loc: Location) => { @@ -64,9 +83,8 @@ export function main() { var outlet = makeDummyOutlet(); router.registerPrimaryOutlet(outlet) - .then( - (_) => - router.config([new Route({path: '/a', component: DummyComponent, name: 'A'})])) + .then((_) => router.config( + [new Route({path: '/a', component: DummyComponent, name: 'A'})])) .then((_) => router.navigate(['/A'])) .then((_) => { expect((<any>outlet).spy('activate')).toHaveBeenCalled(); @@ -191,10 +209,11 @@ export function main() { router.config([new AsyncRoute({path: '/first', loader: loader, name: 'FirstCmp'})]); var instruction = router.generate(['/FirstCmp']); - router.navigateByInstruction(instruction).then((_) => { - expect((<any>outlet).spy('activate')).toHaveBeenCalled(); - async.done(); - }); + router.navigateByInstruction(instruction) + .then((_) => { + expect((<any>outlet).spy('activate')).toHaveBeenCalled(); + async.done(); + }); })); it('should return whether a given instruction is active with isRouteActive', @@ -260,8 +279,9 @@ export function main() { it('should serialize parameters that are not part of the route definition as query string params', () => { - router.config([new Route( - {path: '/one/two/:three', component: DummyComponent, name: 'NumberUrl'})]); + router.config([ + new Route({path: '/one/two/:three', component: DummyComponent, name: 'NumberUrl'}) + ]); var instruction = router.generate(['/NumberUrl', {'three': 'three', 'four': 'four'}]); var path = stringifyInstruction(instruction); diff --git a/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts index 64d9d5b853..adb81c879e 100644 --- a/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, describe, it, iit, ddescribe, expect, inject, beforeEach, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; import {ParamRoutePath} from 'angular2/src/router/rules/route_paths/param_route_path'; import {parser, Url} from 'angular2/src/router/url_parser'; diff --git a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index 34b4560a12..9afe922f7d 100644 --- a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, describe, it, iit, ddescribe, expect, inject, beforeEach, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; import {GeneratedUrl} from 'angular2/src/router/rules/route_paths/route_path'; import {RegexRoutePath} from 'angular2/src/router/rules/route_paths/regex_route_path'; diff --git a/modules/angular2/test/router/rules/rule_set_spec.ts b/modules/angular2/test/router/rules/rule_set_spec.ts index 80ea30af07..1f07a6fb03 100644 --- a/modules/angular2/test/router/rules/rule_set_spec.ts +++ b/modules/angular2/test/router/rules/rule_set_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, describe, it, iit, ddescribe, expect, inject, beforeEach, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; @@ -20,43 +30,47 @@ export function main() { it('should recognize a static segment', inject([AsyncTestCompleter], (async) => { recognizer.config(new Route({path: '/test', component: DummyCmpA})); - recognize(recognizer, '/test').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getComponentType(solutions[0])).toEqual(DummyCmpA); - async.done(); - }); + recognize(recognizer, '/test') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getComponentType(solutions[0])).toEqual(DummyCmpA); + async.done(); + }); })); it('should recognize a single slash', inject([AsyncTestCompleter], (async) => { recognizer.config(new Route({path: '/', component: DummyCmpA})); - recognize(recognizer, '/').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getComponentType(solutions[0])).toEqual(DummyCmpA); - async.done(); - }); + recognize(recognizer, '/') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getComponentType(solutions[0])).toEqual(DummyCmpA); + async.done(); + }); })); it('should recognize a dynamic segment', inject([AsyncTestCompleter], (async) => { recognizer.config(new Route({path: '/user/:name', component: DummyCmpA})); - recognize(recognizer, '/user/brian').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getComponentType(solutions[0])).toEqual(DummyCmpA); - expect(getParams(solutions[0])).toEqual({'name': 'brian'}); - async.done(); - }); + recognize(recognizer, '/user/brian') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getComponentType(solutions[0])).toEqual(DummyCmpA); + expect(getParams(solutions[0])).toEqual({'name': 'brian'}); + async.done(); + }); })); it('should recognize a star segment', inject([AsyncTestCompleter], (async) => { recognizer.config(new Route({path: '/first/*rest', component: DummyCmpA})); - recognize(recognizer, '/first/second/third').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getComponentType(solutions[0])).toEqual(DummyCmpA); - expect(getParams(solutions[0])).toEqual({'rest': 'second/third'}); - async.done(); - }); + recognize(recognizer, '/first/second/third') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getComponentType(solutions[0])).toEqual(DummyCmpA); + expect(getParams(solutions[0])).toEqual({'rest': 'second/third'}); + async.done(); + }); })); it('should recognize a regex', inject([AsyncTestCompleter], (async) => { @@ -64,13 +78,14 @@ export function main() { recognizer.config( new Route({regex: '^(.+)/(.+)$', serializer: emptySerializer, component: DummyCmpA})); - recognize(recognizer, '/first/second').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getComponentType(solutions[0])).toEqual(DummyCmpA); - expect(getParams(solutions[0])) - .toEqual({'0': 'first/second', '1': 'first', '2': 'second'}); - async.done(); - }); + recognize(recognizer, '/first/second') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getComponentType(solutions[0])).toEqual(DummyCmpA); + expect(getParams(solutions[0])) + .toEqual({'0': 'first/second', '1': 'first', '2': 'second'}); + async.done(); + }); })); @@ -83,15 +98,13 @@ export function main() { it('should throw when given two routes that have dynamic segments in the same order', () => { recognizer.config(new Route({path: '/hello/:person/how/:doyoudou', component: DummyCmpA})); - expect( - () => recognizer.config( - new Route({path: '/hello/:friend/how/:areyou', component: DummyCmpA}))) + expect(() => recognizer.config( + new Route({path: '/hello/:friend/how/:areyou', component: DummyCmpA}))) .toThrowError( 'Configuration \'/hello/:friend/how/:areyou\' conflicts with existing route \'/hello/:person/how/:doyoudou\''); - expect( - () => recognizer.config( - new Redirect({path: '/hello/:pal/how/:goesit', redirectTo: ['/Foo']}))) + expect(() => recognizer.config( + new Redirect({path: '/hello/:pal/how/:goesit', redirectTo: ['/Foo']}))) .toThrowError( 'Configuration \'/hello/:pal/how/:goesit\' conflicts with existing route \'/hello/:person/how/:doyoudou\''); }); @@ -100,15 +113,16 @@ export function main() { it('should recognize redirects', inject([AsyncTestCompleter], (async) => { recognizer.config(new Route({path: '/b', component: DummyCmpA})); recognizer.config(new Redirect({path: '/a', redirectTo: ['B']})); - recognize(recognizer, '/a').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - var solution = solutions[0]; - expect(solution).toBeAnInstanceOf(RedirectMatch); - if (solution instanceof RedirectMatch) { - expect(solution.redirectTo).toEqual(['B']); - } - async.done(); - }); + recognize(recognizer, '/a') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + var solution = solutions[0]; + expect(solution).toBeAnInstanceOf(RedirectMatch); + if (solution instanceof RedirectMatch) { + expect(solution.redirectTo).toEqual(['B']); + } + async.done(); + }); })); @@ -152,9 +166,8 @@ export function main() { it('should throw if the route alias is not TitleCase', () => { - expect( - () => recognizer.config( - new Route({path: 'app/user/:name', component: DummyCmpA, name: 'user'}))) + expect(() => recognizer.config( + new Route({path: 'app/user/:name', component: DummyCmpA, name: 'user'}))) .toThrowError( `Route "app/user/:name" with name "user" does not begin with an uppercase letter. Route names should be CamelCase like "User".`); }); @@ -165,11 +178,12 @@ export function main() { inject([AsyncTestCompleter], (async) => { recognizer.config( new Route({path: 'profile/:name', component: DummyCmpA, name: 'User'})); - recognize(recognizer, '/profile/matsko?comments=all').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getParams(solutions[0])).toEqual({'name': 'matsko', 'comments': 'all'}); - async.done(); - }); + recognize(recognizer, '/profile/matsko?comments=all') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getParams(solutions[0])).toEqual({'name': 'matsko', 'comments': 'all'}); + async.done(); + }); })); @@ -190,11 +204,12 @@ export function main() { inject([AsyncTestCompleter], (async) => { recognizer.config( new Route({path: 'profile/:name', component: DummyCmpA, name: 'User'})); - recognize(recognizer, '/profile/yegor?name=igor').then((solutions: RouteMatch[]) => { - expect(solutions.length).toBe(1); - expect(getParams(solutions[0])).toEqual({'name': 'yegor'}); - async.done(); - }); + recognize(recognizer, '/profile/yegor?name=igor') + .then((solutions: RouteMatch[]) => { + expect(solutions.length).toBe(1); + expect(getParams(solutions[0])).toEqual({'name': 'yegor'}); + async.done(); + }); })); diff --git a/modules/angular2/test/router/url_parser_spec.ts b/modules/angular2/test/router/url_parser_spec.ts index 0f278c939d..b61792f17e 100644 --- a/modules/angular2/test/router/url_parser_spec.ts +++ b/modules/angular2/test/router/url_parser_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, describe, it, iit, ddescribe, expect, inject, beforeEach, SpyObject} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + describe, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; import {UrlParser, Url} from 'angular2/src/router/url_parser'; diff --git a/modules/angular2/test/symbol_inspector/symbol_inspector.ts b/modules/angular2/test/symbol_inspector/symbol_inspector.ts index 4b872f77f4..6c45540482 100644 --- a/modules/angular2/test/symbol_inspector/symbol_inspector.ts +++ b/modules/angular2/test/symbol_inspector/symbol_inspector.ts @@ -16,16 +16,16 @@ const LIB_MAP = { ngUpgrade }; -const IGNORE = { - captureStackTrace: true, - stackTraceLimit: true, - toString: true, - originalException: true, - originalStack: true, - wrapperMessage: true, - wrapperStack: true, - '@@observable': true -} +const IGNORE = + { + captureStackTrace: true, + stackTraceLimit: true, + toString: true, + originalException: true, + originalStack: true, + wrapperMessage: true, + wrapperStack: true, '@@observable': true + } function collectTopLevelSymbols(prefix: string, lib: any): string[] { diff --git a/modules/angular2/test/symbol_inspector/symbol_inspector_spec.ts b/modules/angular2/test/symbol_inspector/symbol_inspector_spec.ts index fc40185934..6c9ff31fca 100644 --- a/modules/angular2/test/symbol_inspector/symbol_inspector_spec.ts +++ b/modules/angular2/test/symbol_inspector/symbol_inspector_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit +} from 'angular2/testing_internal'; import {IS_DART} from 'angular2/src/facade/lang'; import {getSymbolsFromLibrary} from './symbol_inspector'; @@ -7,19 +18,38 @@ export function main() { describe('symbol inspector', () => { if (IS_DART) { it('should extract symbols (dart)', () => { - var symbols = getSymbolsFromLibrary('simple_library'); + var symbols = getSymbolsFromLibrary("simple_library"); expect(symbols).toEqual([ - 'A', 'ClosureParam', 'ClosureReturn', 'ConsParamType', 'FieldType', 'Generic', - 'GetterType', 'MethodReturnType', 'ParamType', 'SomeInterface', 'StaticFieldType', - 'TypedefParam', 'TypedefReturnType' + 'A', + 'ClosureParam', + 'ClosureReturn', + 'ConsParamType', + 'FieldType', + 'Generic', + 'GetterType', + 'MethodReturnType', + 'ParamType', + 'SomeInterface', + 'StaticFieldType', + 'TypedefParam', + 'TypedefReturnType' ]); }); } else { it('should extract symbols (js)', () => { - var symbols = getSymbolsFromLibrary('simple_library'); + var symbols = getSymbolsFromLibrary("simple_library"); expect(symbols).toEqual([ - 'A', 'ClosureParam', 'ClosureReturn', 'ConsParamType', 'FieldType', 'Generic', - 'GetterType', 'MethodReturnType', 'ParamType', 'StaticFieldType', 'TypedefParam', + 'A', + 'ClosureParam', + 'ClosureReturn', + 'ConsParamType', + 'FieldType', + 'Generic', + 'GetterType', + 'MethodReturnType', + 'ParamType', + 'StaticFieldType', + 'TypedefParam', 'TypedefReturnType' ]); }); diff --git a/modules/angular2/test/testing/fake_async_spec.ts b/modules/angular2/test/testing/fake_async_spec.ts index 971dd0a615..ccf5a69770 100644 --- a/modules/angular2/test/testing/fake_async_spec.ts +++ b/modules/angular2/test/testing/fake_async_spec.ts @@ -1,4 +1,18 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, fakeAsync, flushMicrotasks, iit, inject, it, Log, tick, xit} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + fakeAsync, + flushMicrotasks, + iit, + inject, + it, + Log, + tick, + xit +} from 'angular2/testing_internal'; import {TimerWrapper, PromiseWrapper} from 'angular2/src/facade/async'; import {BaseException} from 'angular2/src/facade/exceptions'; import {Parser} from 'angular2/src/core/change_detection/change_detection'; @@ -23,9 +37,8 @@ export function main() { inject([Parser], fakeAsync((parser) => { expect(parser).toBeAnInstanceOf(Parser); }))); it('should throw on nested calls', () => { - expect(() => { - fakeAsync(() => { fakeAsync(() => null)(); })(); - }).toThrowError('fakeAsync() calls can not be nested'); + expect(() => { fakeAsync(() => { fakeAsync(() => null)(); })(); }) + .toThrowError('fakeAsync() calls can not be nested'); }); it('should flush microtasks before returning', () => { @@ -87,9 +100,8 @@ export function main() { }); it('should complain if a test throws an exception', () => { - expect(() => { - fakeAsync(() => { throw new BaseException('sync'); })(); - }).toThrowError('sync'); + expect(() => { fakeAsync(() => { throw new BaseException('sync'); })(); }) + .toThrowError('sync'); }); }); @@ -141,15 +153,13 @@ export function main() { })); it('should throw an error on dangling timers', () => { - expect(() => { - fakeAsync(() => { TimerWrapper.setTimeout(() => {}, 10); })(); - }).toThrowError('1 timer(s) still in the queue.'); + expect(() => { fakeAsync(() => { TimerWrapper.setTimeout(() => {}, 10); })(); }) + .toThrowError('1 timer(s) still in the queue.'); }); it('should throw an error on dangling periodic timers', () => { - expect(() => { - fakeAsync(() => { TimerWrapper.setInterval(() => {}, 10); })(); - }).toThrowError('1 periodic timer(s) still in the queue.'); + expect(() => { fakeAsync(() => { TimerWrapper.setInterval(() => {}, 10); })(); }) + .toThrowError('1 periodic timer(s) still in the queue.'); }); it('should run periodic timers', fakeAsync(() => { @@ -240,15 +250,13 @@ export function main() { describe('outside of the fakeAsync zone', () => { it('calling flushMicrotasks should throw', () => { - expect(() => { - flushMicrotasks(); - }).toThrowError('The code should be running in the fakeAsync zone to call this function'); + expect(() => { flushMicrotasks(); }) + .toThrowError('The code should be running in the fakeAsync zone to call this function'); }); it('calling tick should throw', () => { - expect(() => { - tick(); - }).toThrowError('The code should be running in the fakeAsync zone to call this function'); + expect(() => { tick(); }) + .toThrowError('The code should be running in the fakeAsync zone to call this function'); }); }); diff --git a/modules/angular2/test/testing/test_component_builder_spec.ts b/modules/angular2/test/testing/test_component_builder_spec.ts index f840612836..4a07a04c0f 100644 --- a/modules/angular2/test/testing/test_component_builder_spec.ts +++ b/modules/angular2/test/testing/test_component_builder_spec.ts @@ -1,4 +1,18 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + xdescribe, + describe, + dispatchEvent, + expect, + iit, + inject, + beforeEachProviders, + it, + xit, + TestComponentBuilder +} from 'angular2/testing_internal'; import {Injectable, provide} from 'angular2/core'; import {NgIf} from 'angular2/common'; @@ -130,8 +144,8 @@ export function main() { it('should override a view', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - ChildComp, new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'})) + tcb.overrideView(ChildComp, + new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'})) .createAsync(ChildComp) .then((componentFixture) => { componentFixture.detectChanges(); @@ -155,7 +169,7 @@ export function main() { })); - it('should override child component\'s dependencies', + it("should override child component's dependencies", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp) @@ -173,8 +187,8 @@ export function main() { it('should override a provider', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideProviders( - TestBindingsComp, [provide(FancyService, {useClass: MockFancyService})]) + tcb.overrideProviders(TestBindingsComp, + [provide(FancyService, {useClass: MockFancyService})]) .createAsync(TestBindingsComp) .then((componentFixture) => { componentFixture.detectChanges(); @@ -188,8 +202,8 @@ export function main() { it('should override a viewBinding', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideViewProviders( - TestViewBindingsComp, [provide(FancyService, {useClass: MockFancyService})]) + tcb.overrideViewProviders(TestViewBindingsComp, + [provide(FancyService, {useClass: MockFancyService})]) .createAsync(TestViewBindingsComp) .then((componentFixture) => { componentFixture.detectChanges(); diff --git a/modules/angular2/test/testing/testing_internal_spec.ts b/modules/angular2/test/testing/testing_internal_spec.ts index c989f40e44..91785aa538 100644 --- a/modules/angular2/test/testing/testing_internal_spec.ts +++ b/modules/angular2/test/testing/testing_internal_spec.ts @@ -1,4 +1,15 @@ -import {describe, it, iit, ddescribe, expect, tick, SpyObject, beforeEach, proxy, containsRegexp} from 'angular2/testing_internal'; +import { + describe, + it, + iit, + ddescribe, + expect, + tick, + SpyObject, + beforeEach, + proxy, + containsRegexp +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {MapWrapper} from 'angular2/src/facade/collection'; @@ -29,25 +40,25 @@ export function main() { }); }); - describe('toHaveCssClass', () => { - it('should assert that the CSS class is present', () => { + describe("toHaveCssClass", () => { + it("should assert that the CSS class is present", () => { var el = DOM.createElement('div'); DOM.addClass(el, 'matias'); expect(el).toHaveCssClass('matias'); }); - it('should assert that the CSS class is not present', () => { + it("should assert that the CSS class is not present", () => { var el = DOM.createElement('div'); DOM.addClass(el, 'matias'); expect(el).not.toHaveCssClass('fatias'); }); }); - describe('toMatchPAttern', () => { - it('should assert that a string matches a given pattern', () => { - expect('matias').toMatchPattern(/ias$/g); - expect('tobias').toMatchPattern(/ias$/g); - expect('joonas').not.toMatchPattern(/ias$/g); + describe("toMatchPAttern", () => { + it("should assert that a string matches a given pattern", () => { + expect("matias").toMatchPattern(/ias$/g); + expect("tobias").toMatchPattern(/ias$/g); + expect("joonas").not.toMatchPattern(/ias$/g); }); }); @@ -58,64 +69,60 @@ export function main() { }); it('should detect equality for same content', () => { - expect(MapWrapper.createFromStringMap({'a': 1})).toEqual(MapWrapper.createFromStringMap({ - 'a': 1 - })); + expect(MapWrapper.createFromStringMap({'a': 1})) + .toEqual(MapWrapper.createFromStringMap({'a': 1})); }); it('should detect missing entries', () => { - expect(MapWrapper.createFromStringMap({ - 'a': 1 - })).not.toEqual(MapWrapper.createFromStringMap({})); + expect(MapWrapper.createFromStringMap({'a': 1})) + .not.toEqual(MapWrapper.createFromStringMap({})); }); it('should detect different values', () => { - expect(MapWrapper.createFromStringMap({ - 'a': 1 - })).not.toEqual(MapWrapper.createFromStringMap({'a': 2})); + expect(MapWrapper.createFromStringMap({'a': 1})) + .not.toEqual(MapWrapper.createFromStringMap({'a': 2})); }); it('should detect additional entries', () => { - expect(MapWrapper.createFromStringMap({ - 'a': 1 - })).not.toEqual(MapWrapper.createFromStringMap({'a': 1, 'b': 1})); + expect(MapWrapper.createFromStringMap({'a': 1})) + .not.toEqual(MapWrapper.createFromStringMap({'a': 1, 'b': 1})); }); }); - describe('spy objects', () => { + describe("spy objects", () => { var spyObj; beforeEach(() => { spyObj = <any>new SpyTestObj(); }); - it('should return a new spy func with no calls', - () => { expect(spyObj.spy('someFunc')).not.toHaveBeenCalled(); }); + it("should return a new spy func with no calls", + () => { expect(spyObj.spy("someFunc")).not.toHaveBeenCalled(); }); - it('should record function calls', () => { - spyObj.spy('someFunc').andCallFake((a, b) => {return a + b}); + it("should record function calls", () => { + spyObj.spy("someFunc").andCallFake((a, b) => {return a + b}); expect(spyObj.someFunc(1, 2)).toEqual(3); - expect(spyObj.spy('someFunc')).toHaveBeenCalledWith(1, 2); + expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(1, 2); }); - it('should match multiple function calls', () => { + it("should match multiple function calls", () => { spyObj.someFunc(1, 2); spyObj.someFunc(3, 4); - expect(spyObj.spy('someFunc')).toHaveBeenCalledWith(1, 2); - expect(spyObj.spy('someFunc')).toHaveBeenCalledWith(3, 4); + expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(1, 2); + expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(3, 4); }); - it('should match null arguments', () => { - spyObj.someFunc(null, 'hello'); - expect(spyObj.spy('someFunc')).toHaveBeenCalledWith(null, 'hello'); + it("should match null arguments", () => { + spyObj.someFunc(null, "hello"); + expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(null, "hello"); }); - it('should match using deep equality', () => { + it("should match using deep equality", () => { spyObj.someComplexFunc([1]); - expect(spyObj.spy('someComplexFunc')).toHaveBeenCalledWith([1]); + expect(spyObj.spy("someComplexFunc")).toHaveBeenCalledWith([1]); }); - it('should support stubs', () => { - var s = SpyObject.stub({'a': 1}, {'b': 2}); + it("should support stubs", () => { + var s = SpyObject.stub({"a": 1}, {"b": 2}); expect(s.a()).toEqual(1); expect(s.b()).toEqual(2); diff --git a/modules/angular2/test/testing/testing_public_spec.ts b/modules/angular2/test/testing/testing_public_spec.ts index 7645d4d3df..ace3c37bad 100644 --- a/modules/angular2/test/testing/testing_public_spec.ts +++ b/modules/angular2/test/testing/testing_public_spec.ts @@ -1,4 +1,20 @@ -import {it, iit, xit, describe, ddescribe, xdescribe, expect, fakeAsync, tick, beforeEach, inject, injectAsync, withProviders, beforeEachProviders, TestComponentBuilder} from 'angular2/testing'; +import { + it, + iit, + xit, + describe, + ddescribe, + xdescribe, + expect, + fakeAsync, + tick, + beforeEach, + inject, + injectAsync, + withProviders, + beforeEachProviders, + TestComponentBuilder +} from 'angular2/testing'; import {Injectable, bind} from 'angular2/core'; import {NgIf} from 'angular2/common'; @@ -173,8 +189,8 @@ export function main() { }))); describe('using beforeEach', () => { - beforeEach(inject( - [FancyService], (service) => { service.value = 'value modified in beforeEach'; })); + beforeEach(inject([FancyService], + (service) => { service.value = 'value modified in beforeEach'; })); it('should use modified providers', inject([FancyService], (service) => { expect(service.value).toEqual('value modified in beforeEach'); @@ -194,8 +210,8 @@ export function main() { describe('per test providers', () => { it('should allow per test providers', withProviders(() => [bind(FancyService).toValue(new FancyService())]) - .inject( - [FancyService], (service) => { expect(service.value).toEqual('real value'); })); + .inject([FancyService], + (service) => { expect(service.value).toEqual('real value'); })); }); }); @@ -236,13 +252,11 @@ export function main() { var itPromise = patchJasmineIt(); it('forgets to return a proimse', injectAsync([], () => { return true; })); - itPromise.then( - () => { done.fail('Expected function to throw, but it did not'); }, - (err) => { - expect(err).toEqual( - 'Error: injectAsync was expected to return a promise, but the returned value was: true'); - done(); - }); + itPromise.then(() => { done.fail('Expected function to throw, but it did not'); }, (err) => { + expect(err).toEqual( + 'Error: injectAsync was expected to return a promise, but the returned value was: true'); + done(); + }); restoreJasmineIt(); }); @@ -250,13 +264,11 @@ export function main() { var itPromise = patchJasmineIt(); it('returns a value', inject([], () => { return true; })); - itPromise.then( - () => { done.fail('Expected function to throw, but it did not'); }, - (err) => { - expect(err).toEqual( - 'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true'); - done(); - }); + itPromise.then(() => { done.fail('Expected function to throw, but it did not'); }, (err) => { + expect(err).toEqual( + 'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true'); + done(); + }); restoreJasmineIt(); }); @@ -265,8 +277,7 @@ export function main() { beforeEach(injectAsync([], () => { return true; })); beforeEachPromise.then( - () => { done.fail('Expected function to throw, but it did not'); }, - (err) => { + () => { done.fail('Expected function to throw, but it did not'); }, (err) => { expect(err).toEqual( 'Error: injectAsync was expected to return a promise, but the returned value was: true'); done(); @@ -279,8 +290,7 @@ export function main() { beforeEach(inject([], () => { return true; })); beforeEachPromise.then( - () => { done.fail('Expected function to throw, but it did not'); }, - (err) => { + () => { done.fail('Expected function to throw, but it did not'); }, (err) => { expect(err).toEqual( 'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true'); done(); @@ -292,12 +302,10 @@ export function main() { var itPromise = patchJasmineIt(); it('throws an error', inject([], () => { throw new Error('foo'); })); - itPromise.then( - () => { done.fail('Expected function to throw, but it did not'); }, - (err) => { - expect(err.message).toEqual('foo'); - done(); - }); + itPromise.then(() => { done.fail('Expected function to throw, but it did not'); }, (err) => { + expect(err.message).toEqual('foo'); + done(); + }); restoreJasmineIt(); }); @@ -308,12 +316,10 @@ export function main() { it('throws an async error', injectAsync([], () => { setTimeout(() => { throw new Error('bar'); }, 0); })); - itPromise.then( - () => { done.fail('Expected test to fail, but it did not'); }, - (err) => { - expect(err.message).toEqual('bar'); - done(); - }); + itPromise.then(() => { done.fail('Expected test to fail, but it did not'); }, (err) => { + expect(err.message).toEqual('bar'); + done(); + }); restoreJasmineIt(); }); @@ -328,12 +334,10 @@ export function main() { return p; })); - itPromise.then( - () => { done.fail('Expected test to fail, but it did not'); }, - (err) => { - expect(err).toEqual('baz'); - done(); - }); + itPromise.then(() => { done.fail('Expected test to fail, but it did not'); }, (err) => { + expect(err).toEqual('baz'); + done(); + }); restoreJasmineIt(); }); @@ -343,12 +347,10 @@ export function main() { it('should fail with an error from a promise', injectAsync([TestComponentBuilder], (tcb) => { return tcb.createAsync(BadTemplateUrl); })); - itPromise.then( - () => { done.fail('Expected test to fail, but it did not'); }, - (err) => { - expect(err).toEqual('Failed to load non-existant.html'); - done(); - }); + itPromise.then(() => { done.fail('Expected test to fail, but it did not'); }, (err) => { + expect(err).toEqual('Failed to load non-existant.html'); + done(); + }); restoreJasmineIt(); }, 10000); @@ -365,9 +367,8 @@ export function main() { expect(() => { beforeEachProviders(() => [bind(FancyService).toValue(new FancyService())]); }) - .toThrowError( - 'beforeEachProviders was called after the injector had been used ' + - 'in a beforeEach or it block. This invalidates the test injector'); + .toThrowError('beforeEachProviders was called after the injector had been used ' + + 'in a beforeEach or it block. This invalidates the test injector'); restoreJasmineBeforeEach(); }); }); @@ -413,9 +414,9 @@ export function main() { it('should override a view', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { - return tcb - .overrideView( - ChildComp, new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'})) + return tcb.overrideView( + ChildComp, + new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'})) .createAsync(ChildComp) .then((componentFixture) => { componentFixture.detectChanges(); @@ -437,7 +438,7 @@ export function main() { })); - it('should override child component\'s dependencies', + it("should override child component's dependencies", injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { return tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp) @@ -454,8 +455,8 @@ export function main() { it('should override a provider', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { - return tcb - .overrideProviders(TestProvidersComp, [bind(FancyService).toClass(MockFancyService)]) + return tcb.overrideProviders(TestProvidersComp, + [bind(FancyService).toClass(MockFancyService)]) .createAsync(TestProvidersComp) .then((componentFixture) => { componentFixture.detectChanges(); @@ -468,9 +469,8 @@ export function main() { it('should override a viewProvider', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { - return tcb - .overrideViewProviders( - TestViewProvidersComp, [bind(FancyService).toClass(MockFancyService)]) + return tcb.overrideViewProviders(TestViewProvidersComp, + [bind(FancyService).toClass(MockFancyService)]) .createAsync(TestViewProvidersComp) .then((componentFixture) => { componentFixture.detectChanges(); @@ -482,11 +482,12 @@ export function main() { it('should allow an external templateUrl', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { - return tcb.createAsync(ExternalTemplateComp).then((componentFixture) => { - componentFixture.detectChanges(); - expect(componentFixture.debugElement.nativeElement) - .toHaveText('from external template\n'); - }); + return tcb.createAsync(ExternalTemplateComp) + .then((componentFixture) => { + componentFixture.detectChanges(); + expect(componentFixture.debugElement.nativeElement) + .toHaveText('from external template\n'); + }); }), 10000); // Long timeout here because this test makes an actual XHR, and is slow on Edge. }); } diff --git a/modules/angular2/test/upgrade/metadata_spec.ts b/modules/angular2/test/upgrade/metadata_spec.ts index deb6dd4995..a35f8b807d 100644 --- a/modules/angular2/test/upgrade/metadata_spec.ts +++ b/modules/angular2/test/upgrade/metadata_spec.ts @@ -1,4 +1,15 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit, +} from 'angular2/testing_internal'; import {Component} from 'angular2/core'; import {getComponentInfo, parseFields} from 'angular2/src/upgrade/metadata'; @@ -15,12 +26,12 @@ export function main() { it('should throw on missing selector', () => { expect(() => getComponentInfo(AttributeNameComponent)) .toThrowErrorWith( - 'Only selectors matching element names are supported, got: [attr-name]'); + "Only selectors matching element names are supported, got: [attr-name]"); }); it('should throw on non element names', () => { expect(() => getComponentInfo(NoAnnotationComponent)) - .toThrowErrorWith('No Directive annotation found on NoAnnotationComponent'); + .toThrowErrorWith("No Directive annotation found on NoAnnotationComponent"); }); }); @@ -28,28 +39,29 @@ export function main() { it('should process nulls', () => { expect(parseFields(null)).toEqual([]); }); it('should process values', () => { - expect(parseFields([' name ', ' prop : attr '])).toEqual([ - { - prop: 'name', - attr: 'name', - bracketAttr: '[name]', - parenAttr: '(name)', - bracketParenAttr: '[(name)]', - onAttr: 'onName', - bindAttr: 'bindName', - bindonAttr: 'bindonName' - }, - { - prop: 'prop', - attr: 'attr', - bracketAttr: '[attr]', - parenAttr: '(attr)', - bracketParenAttr: '[(attr)]', - onAttr: 'onAttr', - bindAttr: 'bindAttr', - bindonAttr: 'bindonAttr' - } - ]); + expect(parseFields([' name ', ' prop : attr '])) + .toEqual([ + { + prop: 'name', + attr: 'name', + bracketAttr: '[name]', + parenAttr: '(name)', + bracketParenAttr: '[(name)]', + onAttr: 'onName', + bindAttr: 'bindName', + bindonAttr: 'bindonName' + }, + { + prop: 'prop', + attr: 'attr', + bracketAttr: '[attr]', + parenAttr: '(attr)', + bracketParenAttr: '[(attr)]', + onAttr: 'onAttr', + bindAttr: 'bindAttr', + bindonAttr: 'bindonAttr' + } + ]); }); }) }); diff --git a/modules/angular2/test/upgrade/upgrade_spec.ts b/modules/angular2/test/upgrade/upgrade_spec.ts index 55038d31ef..638b6226ae 100644 --- a/modules/angular2/test/upgrade/upgrade_spec.ts +++ b/modules/angular2/test/upgrade/upgrade_spec.ts @@ -1,8 +1,27 @@ -import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit,} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xdescribe, + xit, +} from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {global} from 'angular2/src/facade/lang'; -import {Component, Class, Inject, EventEmitter, ApplicationRef, provide, Testability,} from 'angular2/core'; +import { + Component, + Class, + Inject, + EventEmitter, + ApplicationRef, + provide, + Testability, +} from 'angular2/core'; import {UpgradeAdapter} from 'angular2/upgrade'; import * as angular from 'angular2/src/upgrade/angular_js'; @@ -16,16 +35,16 @@ export function main() { var Ng2 = Component({selector: 'ng2', template: `{{ 'NG2' }}(<ng-content></ng-content>)`}) .Class({constructor: function() {}}); - var element = - html('<div>{{ \'ng1[\' }}<ng2>~{{ \'ng-content\' }}~</ng2>{{ \']\' }}</div>'); + var element = html("<div>{{ 'ng1[' }}<ng2>~{{ 'ng-content' }}~</ng2>{{ ']' }}</div>"); var adapter: UpgradeAdapter = new UpgradeAdapter(); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(document.body.textContent).toEqual('ng1[NG2(~ng-content~)]'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(document.body.textContent).toEqual("ng1[NG2(~ng-content~)]"); + ref.dispose(); + async.done(); + }); })); it('should instantiate ng1 in ng2 template and project content', @@ -44,13 +63,14 @@ export function main() { }); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); - var element = html('<div>{{\'ng1(\'}}<ng2></ng2>{{\')\'}}</div>'); + var element = html("<div>{{'ng1('}}<ng2></ng2>{{')'}}</div>"); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(document.body.textContent).toEqual('ng1(ng2(ng1(transclude)))'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(document.body.textContent).toEqual("ng1(ng2(ng1(transclude)))"); + ref.dispose(); + async.done(); + }); })); describe('scope/component change-detection', () => { @@ -64,8 +84,8 @@ export function main() { }; var adapter: UpgradeAdapter = new UpgradeAdapter(); - ng1Module.directive('ng1a', () => { return {template: '{{ l(\'ng1a\') }}'}; }); - ng1Module.directive('ng1b', () => { return {template: '{{ l(\'ng1b\') }}'}; }); + ng1Module.directive('ng1a', () => { return {template: "{{ l('ng1a') }}"}; }); + ng1Module.directive('ng1b', () => { return {template: "{{ l('ng1b') }}"}; }); ng1Module.run(($rootScope) => { $rootScope.l = l; $rootScope.reset = () => log.length = 0; @@ -81,15 +101,15 @@ export function main() { ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); - var element = - html('<div>{{reset(); l(\'1A\');}}<ng2>{{l(\'1B\')}}</ng2>{{l(\'1C\')}}</div>'); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(document.body.textContent).toEqual('1A;2A;ng1a;2B;ng1b;2C;1C;'); - // https://github.com/angular/angular.js/issues/12983 - expect(log).toEqual(['1A', '1B', '1C', '2A', '2B', '2C', 'ng1a', 'ng1b']); - ref.dispose(); - async.done(); - }); + var element = html("<div>{{reset(); l('1A');}}<ng2>{{l('1B')}}</ng2>{{l('1C')}}</div>"); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(document.body.textContent).toEqual("1A;2A;ng1a;2B;ng1b;2C;1C;"); + // https://github.com/angular/angular.js/issues/12983 + expect(log).toEqual(['1A', '1B', '1C', '2A', '2B', '2C', 'ng1a', 'ng1b']); + ref.dispose(); + async.done(); + }); })); }); @@ -106,78 +126,82 @@ export function main() { $rootScope.eventA = '?'; $rootScope.eventB = '?'; }); - var Ng2 = Component({ - selector: 'ng2', - inputs: - ['literal', 'interpolate', 'oneWayA', 'oneWayB', 'twoWayA', 'twoWayB'], - outputs: [ - 'eventA', 'eventB', 'twoWayAEmitter: twoWayAChange', - 'twoWayBEmitter: twoWayBChange' - ], - template: 'ignore: {{ignore}}; ' + - 'literal: {{literal}}; interpolate: {{interpolate}}; ' + - 'oneWayA: {{oneWayA}}; oneWayB: {{oneWayB}}; ' + - 'twoWayA: {{twoWayA}}; twoWayB: {{twoWayB}}; ({{ngOnChangesCount}})' - }).Class({ - constructor: function() { - this.ngOnChangesCount = 0; - this.ignore = '-'; - this.literal = '?'; - this.interpolate = '?'; - this.oneWayA = '?'; - this.oneWayB = '?'; - this.twoWayA = '?'; - this.twoWayB = '?'; - this.eventA = new EventEmitter(); - this.eventB = new EventEmitter(); - this.twoWayAEmitter = new EventEmitter(); - this.twoWayBEmitter = new EventEmitter(); - }, - ngOnChanges: function(changes) { - var assert = (prop, value) => { - if (this[prop] != value) { - throw new Error(`Expected: '${prop}' to be '${value}' but was '${this[prop]}'`); - } - }; + var Ng2 = + Component({ + selector: 'ng2', + inputs: ['literal', 'interpolate', 'oneWayA', 'oneWayB', 'twoWayA', 'twoWayB'], + outputs: [ + 'eventA', + 'eventB', + 'twoWayAEmitter: twoWayAChange', + 'twoWayBEmitter: twoWayBChange' + ], + template: "ignore: {{ignore}}; " + + "literal: {{literal}}; interpolate: {{interpolate}}; " + + "oneWayA: {{oneWayA}}; oneWayB: {{oneWayB}}; " + + "twoWayA: {{twoWayA}}; twoWayB: {{twoWayB}}; ({{ngOnChangesCount}})" + }) + .Class({ + constructor: function() { + this.ngOnChangesCount = 0; + this.ignore = '-'; + this.literal = '?'; + this.interpolate = '?'; + this.oneWayA = '?'; + this.oneWayB = '?'; + this.twoWayA = '?'; + this.twoWayB = '?'; + this.eventA = new EventEmitter(); + this.eventB = new EventEmitter(); + this.twoWayAEmitter = new EventEmitter(); + this.twoWayBEmitter = new EventEmitter(); + }, + ngOnChanges: function(changes) { + var assert = (prop, value) => { + if (this[prop] != value) { + throw new Error( + `Expected: '${prop}' to be '${value}' but was '${this[prop]}'`); + } + }; - var assertChange = (prop, value) => { - assert(prop, value); - if (!changes[prop]) { - throw new Error(`Changes record for '${prop}' not found.`); - } - var actValue = changes[prop].currentValue; - if (actValue != value) { - throw new Error( - `Expected changes record for'${prop}' to be '${value}' but was '${actValue}'`); - } - }; + var assertChange = (prop, value) => { + assert(prop, value); + if (!changes[prop]) { + throw new Error(`Changes record for '${prop}' not found.`); + } + var actValue = changes[prop].currentValue; + if (actValue != value) { + throw new Error( + `Expected changes record for'${prop}' to be '${value}' but was '${actValue}'`); + } + }; - switch (this.ngOnChangesCount++) { - case 0: - assert('ignore', '-'); - assertChange('literal', 'Text'); - assertChange('interpolate', 'Hello world'); - assertChange('oneWayA', 'A'); - assertChange('oneWayB', 'B'); - assertChange('twoWayA', 'initModelA'); - assertChange('twoWayB', 'initModelB'); + switch (this.ngOnChangesCount++) { + case 0: + assert('ignore', '-'); + assertChange('literal', 'Text'); + assertChange('interpolate', 'Hello world'); + assertChange('oneWayA', 'A'); + assertChange('oneWayB', 'B'); + assertChange('twoWayA', 'initModelA'); + assertChange('twoWayB', 'initModelB'); - this.twoWayAEmitter.emit('newA'); - this.twoWayBEmitter.emit('newB'); - this.eventA.emit('aFired'); - this.eventB.emit('bFired'); - break; - case 1: - assertChange('twoWayA', 'newA'); - break; - case 2: - assertChange('twoWayB', 'newB'); - break; - default: - throw new Error('Called too many times! ' + JSON.stringify(changes)); - } - } - }); + this.twoWayAEmitter.emit('newA'); + this.twoWayBEmitter.emit('newB'); + this.eventA.emit('aFired'); + this.eventB.emit('bFired'); + break; + case 1: + assertChange('twoWayA', 'newA'); + break; + case 2: + assertChange('twoWayB', 'newB'); + break; + default: + throw new Error('Called too many times! ' + JSON.stringify(changes)); + } + } + }); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div> <ng2 literal="Text" interpolate="Hello {{'world'}}" @@ -186,26 +210,24 @@ export function main() { on-event-a='eventA=$event' (event-b)="eventB=$event"></ng2> | modelA: {{modelA}}; modelB: {{modelB}}; eventA: {{eventA}}; eventB: {{eventB}}; </div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)) - .toEqual( - 'ignore: -; ' + - 'literal: Text; interpolate: Hello world; ' + - 'oneWayA: A; oneWayB: B; twoWayA: initModelA; twoWayB: initModelB; (1) | ' + - 'modelA: initModelA; modelB: initModelB; eventA: ?; eventB: ?;'); - setTimeout(() => { - // we need to do setTimeout, because the EventEmitter uses setTimeout to schedule - // events, and so without this we would not see the events processed. - expect(multiTrim(document.body.textContent)) - .toEqual( - 'ignore: -; ' + - 'literal: Text; interpolate: Hello world; ' + - 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' + - 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;'); - ref.dispose(); - async.done(); - }); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)) + .toEqual( + "ignore: -; " + "literal: Text; interpolate: Hello world; " + + "oneWayA: A; oneWayB: B; twoWayA: initModelA; twoWayB: initModelB; (1) | " + + "modelA: initModelA; modelB: initModelB; eventA: ?; eventB: ?;"); + setTimeout(() => { + // we need to do setTimeout, because the EventEmitter uses setTimeout to schedule + // events, and so without this we would not see the events processed. + expect(multiTrim(document.body.textContent)) + .toEqual("ignore: -; " + "literal: Text; interpolate: Hello world; " + + "oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | " + + "modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;"); + ref.dispose(); + async.done(); + }); + }); })); @@ -224,16 +246,18 @@ export function main() { }; }); - var Ng2 = Component({selector: 'ng2', template: 'test'}).Class({ - constructor: function() {}, - ngOnDestroy: function() { onDestroyed.emit('destroyed'); } - }); + var Ng2 = Component({selector: 'ng2', template: 'test'}) + .Class({ + constructor: function() {}, + ngOnDestroy: function() { onDestroyed.emit('destroyed'); } + }); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html('<ng1></ng1>'); - adapter.bootstrap(element, ['ng1']).ready((ref) => {onDestroyed.subscribe(() => { - ref.dispose(); - async.done(); - })}); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => {onDestroyed.subscribe(() => { + ref.dispose(); + async.done(); + })}); })); }); @@ -265,38 +289,40 @@ export function main() { selector: 'ng2', template: '<ng1 fullName="{{last}}, {{first}}" [modelA]="first" [(modelB)]="last" ' + - '(event)="event=$event"></ng1>' + - '<ng1 fullName="{{\'TEST\'}}" modelA="First" modelB="Last"></ng1>' + - '{{event}}-{{last}}, {{first}}', + '(event)="event=$event"></ng1>' + + '<ng1 fullName="{{\'TEST\'}}" modelA="First" modelB="Last"></ng1>' + + '{{event}}-{{last}}, {{first}}', directives: [adapter.upgradeNg1Component('ng1')] - }).Class({ - constructor: function() { - this.first = 'Victor'; - this.last = 'Savkin'; - this.event = '?'; - } - }); + }) + .Class({ + constructor: function() { + this.first = 'Victor'; + this.last = 'Savkin'; + this.event = '?'; + } + }); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - // we need to do setTimeout, because the EventEmitter uses setTimeout to schedule - // events, and so without this we would not see the events processed. - setTimeout(() => { - expect(multiTrim(document.body.textContent)) - .toEqual( - 'Hello SAVKIN, Victor; A: VICTOR; B: SAVKIN; | Hello TEST; A: First; B: Last; | WORKS-SAVKIN, Victor'); - ref.dispose(); - async.done(); - }, 0); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + // we need to do setTimeout, because the EventEmitter uses setTimeout to schedule + // events, and so without this we would not see the events processed. + setTimeout(() => { + expect(multiTrim(document.body.textContent)) + .toEqual( + "Hello SAVKIN, Victor; A: VICTOR; B: SAVKIN; | Hello TEST; A: First; B: Last; | WORKS-SAVKIN, Victor"); + ref.dispose(); + async.done(); + }, 0); + }); })); it('should support templateUrl fetched from $httpBackend', inject([AsyncTestCompleter], (async) => { var adapter = new UpgradeAdapter(); var ng1Module = angular.module('ng1', []); - ng1Module.value( - '$httpBackend', (method, url, post, cbFn) => { cbFn(200, `${method}:${url}`); }); + ng1Module.value('$httpBackend', + (method, url, post, cbFn) => { cbFn(200, `${method}:${url}`); }); var ng1 = function() { return {templateUrl: 'url.html'}; }; ng1Module.directive('ng1', ng1); @@ -307,11 +333,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('GET:url.html'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual('GET:url.html'); + ref.dispose(); + async.done(); + }); })); it('should support empty template', inject([AsyncTestCompleter], (async) => { @@ -327,11 +354,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual(''); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual(''); + ref.dispose(); + async.done(); + }); })); it('should support templateUrl fetched from $templateCache', @@ -349,11 +377,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('WORKS'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual('WORKS'); + ref.dispose(); + async.done(); + }); })); it('should support controller with controllerAs', inject([AsyncTestCompleter], (async) => { @@ -388,11 +417,13 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('scope; isClass; NG1; published'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)) + .toEqual('scope; isClass; NG1; published'); + ref.dispose(); + async.done(); + }); })); it('should support bindToController', inject([AsyncTestCompleter], (async) => { @@ -416,11 +447,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('WORKS'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual('WORKS'); + ref.dispose(); + async.done(); + }); })); it('should support bindToController with bindings', inject([AsyncTestCompleter], (async) => { @@ -444,11 +476,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('WORKS'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual('WORKS'); + ref.dispose(); + async.done(); + }); })); it('should support single require in linking fn', inject([AsyncTestCompleter], (async) => { @@ -479,11 +512,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('WORKS'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual('WORKS'); + ref.dispose(); + async.done(); + }); })); it('should support array require in linking fn', inject([AsyncTestCompleter], (async) => { @@ -519,11 +553,12 @@ export function main() { }).Class({constructor: function() {}}); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><parent><ng2></ng2></parent></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual('PARENT:WORKS'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual('PARENT:WORKS'); + ref.dispose(); + async.done(); + }); })); it('should call $onInit of components', inject([AsyncTestCompleter], (async) => { @@ -547,11 +582,12 @@ export function main() { ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual(valueToFind); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual(valueToFind); + ref.dispose(); + async.done(); + }); })); it('should bind input properties (<) of components', inject([AsyncTestCompleter], (async) => { @@ -565,21 +601,24 @@ export function main() { }; ng1Module.component('ng1', ng1); - var Ng2 = Component({ - selector: 'ng2', - template: '<ng1 [personProfile]="goku"></ng1>', - directives: [adapter.upgradeNg1Component('ng1')] - }).Class({ - constructor: function() { this.goku = {firstName: 'GOKU', lastName: 'SAN'}; } - }); + var Ng2 = + Component({ + selector: 'ng2', + template: '<ng1 [personProfile]="goku"></ng1>', + directives: [adapter.upgradeNg1Component('ng1')] + }) + .Class({ + constructor: function() { this.goku = {firstName: 'GOKU', lastName: 'SAN'}; } + }); ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); var element = html(`<div><ng2></ng2></div>`); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(multiTrim(document.body.textContent)).toEqual(`Hello GOKU SAN`); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)).toEqual(`Hello GOKU SAN`); + ref.dispose(); + async.done(); + }); })); }); @@ -591,11 +630,12 @@ export function main() { var module = angular.module('myExample', []); adapter.addProvider(provide(SomeToken, {useValue: 'correct_value'})); module.factory('someToken', adapter.downgradeNg2Provider(SomeToken)); - adapter.bootstrap(html('<div>'), ['myExample']).ready((ref) => { - expect(ref.ng1Injector.get('someToken')).toBe('correct_value'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(html('<div>'), ['myExample']) + .ready((ref) => { + expect(ref.ng1Injector.get('someToken')).toBe('correct_value'); + ref.dispose(); + async.done(); + }); })); it('should export ng1 instance to ng2', inject([AsyncTestCompleter], (async) => { @@ -605,13 +645,14 @@ export function main() { adapter.upgradeNg1Provider('testValue'); adapter.upgradeNg1Provider('testValue', {asToken: 'testToken'}); adapter.upgradeNg1Provider('testValue', {asToken: String}); - adapter.bootstrap(html('<div>'), ['myExample']).ready((ref) => { - expect(ref.ng2Injector.get('testValue')).toBe('secreteToken'); - expect(ref.ng2Injector.get(String)).toBe('secreteToken'); - expect(ref.ng2Injector.get('testToken')).toBe('secreteToken'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(html('<div>'), ['myExample']) + .ready((ref) => { + expect(ref.ng2Injector.get('testValue')).toBe('secreteToken'); + expect(ref.ng2Injector.get(String)).toBe('secreteToken'); + expect(ref.ng2Injector.get('testToken')).toBe('secreteToken'); + ref.dispose(); + async.done(); + }); })); }); @@ -621,14 +662,15 @@ export function main() { var ng1Module = angular.module('ng1', []); var bootstrapResumed: boolean = false; - var element = html('<div></div>'); + var element = html("<div></div>"); window.name = 'NG_DEFER_BOOTSTRAP!' + window.name; - adapter.bootstrap(element, ['ng1']).ready((ref) => { - expect(bootstrapResumed).toEqual(true); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + expect(bootstrapResumed).toEqual(true); + ref.dispose(); + async.done(); + }); setTimeout(() => { bootstrapResumed = true; @@ -639,23 +681,24 @@ export function main() { it('should wait for ng2 testability', inject([AsyncTestCompleter], (async) => { var adapter: UpgradeAdapter = new UpgradeAdapter(); var ng1Module = angular.module('ng1', []); - var element = html('<div></div>'); - adapter.bootstrap(element, ['ng1']).ready((ref) => { - var ng2Testability: Testability = ref.ng2Injector.get(Testability); - ng2Testability.increasePendingRequestCount(); - var ng2Stable = false; + var element = html("<div></div>"); + adapter.bootstrap(element, ['ng1']) + .ready((ref) => { + var ng2Testability: Testability = ref.ng2Injector.get(Testability); + ng2Testability.increasePendingRequestCount(); + var ng2Stable = false; - angular.getTestability(element).whenStable(function() { - expect(ng2Stable).toEqual(true); - ref.dispose(); - async.done(); - }); + angular.getTestability(element).whenStable(function() { + expect(ng2Stable).toEqual(true); + ref.dispose(); + async.done(); + }); - setTimeout(() => { - ng2Stable = true; - ng2Testability.decreasePendingRequestCount(); - }, 100); - }); + setTimeout(() => { + ng2Stable = true; + ng2Testability.decreasePendingRequestCount(); + }, 100); + }); })); }); @@ -685,12 +728,13 @@ export function main() { document.body.innerHTML = '<ng2 name="World">project</ng2>'; - adapter.bootstrap(document.body, ['myExample']).ready((ref) => { - expect(multiTrim(document.body.textContent)) - .toEqual('ng2[ng1[Hello World!](transclude)](project)'); - ref.dispose(); - async.done(); - }); + adapter.bootstrap(document.body, ['myExample']) + .ready((ref) => { + expect(multiTrim(document.body.textContent)) + .toEqual("ng2[ng1[Hello World!](transclude)](project)"); + ref.dispose(); + async.done(); + }); })); }); }); diff --git a/modules/angular2/test/web_workers/shared/message_bus_spec.ts b/modules/angular2/test/web_workers/shared/message_bus_spec.ts index 6ebaa7caa0..1e3073c94e 100644 --- a/modules/angular2/test/web_workers/shared/message_bus_spec.ts +++ b/modules/angular2/test/web_workers/shared/message_bus_spec.ts @@ -1,4 +1,14 @@ -import {AsyncTestCompleter, inject, describe, it, expect, beforeEach, beforeEachProviders, SpyObject, proxy} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + describe, + it, + expect, + beforeEach, + beforeEachProviders, + SpyObject, + proxy +} from 'angular2/testing_internal'; import {ObservableWrapper, TimerWrapper} from 'angular2/src/facade/async'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; import {createConnectedMessageBus} from './message_bus_util'; @@ -9,15 +19,15 @@ export function main() { /** * Tests the PostMessageBus in TypeScript and the IsolateMessageBus in Dart */ - describe('MessageBus', () => { + describe("MessageBus", () => { var bus: MessageBus; beforeEach(() => { bus = createConnectedMessageBus(); }); - it('should pass messages in the same channel from sink to source', + it("should pass messages in the same channel from sink to source", inject([AsyncTestCompleter], (async) => { - const CHANNEL = 'CHANNEL 1'; - const MESSAGE = 'Test message'; + const CHANNEL = "CHANNEL 1"; + const MESSAGE = "Test message"; bus.initChannel(CHANNEL, false); var fromEmitter = bus.from(CHANNEL); @@ -29,9 +39,9 @@ export function main() { ObservableWrapper.callEmit(toEmitter, MESSAGE); })); - it('should broadcast', inject([AsyncTestCompleter], (async) => { - const CHANNEL = 'CHANNEL 1'; - const MESSAGE = 'TESTING'; + it("should broadcast", inject([AsyncTestCompleter], (async) => { + const CHANNEL = "CHANNEL 1"; + const MESSAGE = "TESTING"; const NUM_LISTENERS = 2; bus.initChannel(CHANNEL, false); @@ -53,11 +63,11 @@ export function main() { ObservableWrapper.callEmit(toEmitter, MESSAGE); })); - it('should keep channels independent', inject([AsyncTestCompleter], (async) => { - const CHANNEL_ONE = 'CHANNEL 1'; - const CHANNEL_TWO = 'CHANNEL 2'; - const MESSAGE_ONE = 'This is a message on CHANNEL 1'; - const MESSAGE_TWO = 'This is a message on CHANNEL 2'; + it("should keep channels independent", inject([AsyncTestCompleter], (async) => { + const CHANNEL_ONE = "CHANNEL 1"; + const CHANNEL_TWO = "CHANNEL 2"; + const MESSAGE_ONE = "This is a message on CHANNEL 1"; + const MESSAGE_TWO = "This is a message on CHANNEL 2"; var callCount = 0; bus.initChannel(CHANNEL_ONE, false); bus.initChannel(CHANNEL_TWO, false); @@ -87,9 +97,9 @@ export function main() { })); }); - describe('PostMessageBusSink', () => { + describe("PostMessageBusSink", () => { var bus: MessageBus; - const CHANNEL = 'Test Channel'; + const CHANNEL = "Test Channel"; function setup(runInZone: boolean, zone: NgZone) { bus.attachToZone(zone); @@ -104,13 +114,13 @@ export function main() { beforeEach(() => { bus = createConnectedMessageBus(); }); - it('should buffer messages and wait for the zone to exit before sending', + it("should buffer messages and wait for the zone to exit before sending", inject([AsyncTestCompleter, NgZone], (async, zone: MockNgZone) => { setup(true, zone); var wasCalled = false; ObservableWrapper.subscribe(bus.from(CHANNEL), (message) => { wasCalled = true; }); - ObservableWrapper.callEmit(bus.to(CHANNEL), 'hi'); + ObservableWrapper.callEmit(bus.to(CHANNEL), "hi"); flushMessages(() => { @@ -124,13 +134,13 @@ export function main() { }); }), 500); - it('should send messages immediatly when run outside the zone', + it("should send messages immediatly when run outside the zone", inject([AsyncTestCompleter, NgZone], (async, zone: MockNgZone) => { setup(false, zone); var wasCalled = false; ObservableWrapper.subscribe(bus.from(CHANNEL), (message) => { wasCalled = true; }); - ObservableWrapper.callEmit(bus.to(CHANNEL), 'hi'); + ObservableWrapper.callEmit(bus.to(CHANNEL), "hi"); flushMessages(() => { expect(wasCalled).toBeTruthy(); diff --git a/modules/angular2/test/web_workers/shared/message_bus_util.ts b/modules/angular2/test/web_workers/shared/message_bus_util.ts index 2bd2a8020f..ec76e7f691 100644 --- a/modules/angular2/test/web_workers/shared/message_bus_util.ts +++ b/modules/angular2/test/web_workers/shared/message_bus_util.ts @@ -1,4 +1,8 @@ -import {PostMessageBusSource, PostMessageBusSink, PostMessageBus} from 'angular2/src/web_workers/shared/post_message_bus'; +import { + PostMessageBusSource, + PostMessageBusSink, + PostMessageBus +} from 'angular2/src/web_workers/shared/post_message_bus'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; /* @@ -17,10 +21,10 @@ class MockPostMessage { private _listener: EventListener; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void { - if (type === 'message') { + if (type === "message") { this._listener = listener; } } - postMessage(data: any, transfer?: [ArrayBuffer]): void { this._listener(<any>{data: data}); } + postMessage(data: any, transfer?:[ArrayBuffer]): void { this._listener(<any>{data: data}); } } diff --git a/modules/angular2/test/web_workers/shared/render_store_spec.ts b/modules/angular2/test/web_workers/shared/render_store_spec.ts index 986224f29a..25646091c8 100644 --- a/modules/angular2/test/web_workers/shared/render_store_spec.ts +++ b/modules/angular2/test/web_workers/shared/render_store_spec.ts @@ -1,8 +1,16 @@ -import {AsyncTestCompleter, inject, describe, ddescribe, beforeEach, it, expect} from 'angular2/testing_internal'; -import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; +import { + AsyncTestCompleter, + inject, + describe, + ddescribe, + beforeEach, + it, + expect +} from "angular2/testing_internal"; +import {RenderStore} from "angular2/src/web_workers/shared/render_store"; export function main() { - describe('RenderStoreSpec', () => { + describe("RenderStoreSpec", () => { var store: RenderStore; beforeEach(() => { store = new RenderStore(); }); diff --git a/modules/angular2/test/web_workers/shared/service_message_broker_spec.ts b/modules/angular2/test/web_workers/shared/service_message_broker_spec.ts index a950ddabe9..3e4b747896 100644 --- a/modules/angular2/test/web_workers/shared/service_message_broker_spec.ts +++ b/modules/angular2/test/web_workers/shared/service_message_broker_spec.ts @@ -1,23 +1,38 @@ -import {AsyncTestCompleter, inject, describe, it, iit, expect, beforeEach, beforeEachProviders, SpyObject, proxy, browserDetection} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + describe, + it, + iit, + expect, + beforeEach, + beforeEachProviders, + SpyObject, + proxy, + browserDetection +} from 'angular2/testing_internal'; import {createPairedMessageBuses} from '../shared/web_worker_test_util'; import {Serializer, PRIMITIVE} from 'angular2/src/web_workers/shared/serializer'; -import {ServiceMessageBroker, ServiceMessageBroker_} from 'angular2/src/web_workers/shared/service_message_broker'; +import { + ServiceMessageBroker, + ServiceMessageBroker_ +} from 'angular2/src/web_workers/shared/service_message_broker'; import {ObservableWrapper, PromiseWrapper} from 'angular2/src/facade/async'; import {provide} from 'angular2/core'; import {ON_WEB_WORKER} from 'angular2/src/web_workers/shared/api'; import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; export function main() { - const CHANNEL = 'UIMessageBroker Test Channel'; - const TEST_METHOD = 'TEST_METHOD'; + const CHANNEL = "UIMessageBroker Test Channel"; + const TEST_METHOD = "TEST_METHOD"; const PASSED_ARG_1 = 5; const PASSED_ARG_2 = 'TEST'; const RESULT = 20; - const ID = 'methodId'; + const ID = "methodId"; beforeEachProviders(() => [Serializer, provide(ON_WEB_WORKER, {useValue: true}), RenderStore]); - describe('UIMessageBroker', () => { + describe("UIMessageBroker", () => { var messageBuses; beforeEach(() => { @@ -25,32 +40,30 @@ export function main() { messageBuses.ui.initChannel(CHANNEL); messageBuses.worker.initChannel(CHANNEL); }); - it('should call registered method with correct arguments', + it("should call registered method with correct arguments", inject([Serializer], (serializer) => { var broker = new ServiceMessageBroker_(messageBuses.ui, serializer, CHANNEL); broker.registerMethod(TEST_METHOD, [PRIMITIVE, PRIMITIVE], (arg1, arg2) => { expect(arg1).toEqual(PASSED_ARG_1); expect(arg2).toEqual(PASSED_ARG_2); }); - ObservableWrapper.callEmit( - messageBuses.worker.to(CHANNEL), - {'method': TEST_METHOD, 'args': [PASSED_ARG_1, PASSED_ARG_2]}); + ObservableWrapper.callEmit(messageBuses.worker.to(CHANNEL), + {'method': TEST_METHOD, 'args': [PASSED_ARG_1, PASSED_ARG_2]}); })); // TODO(pkozlowski): this fails only in Edge with // "No provider for RenderStore! (Serializer -> RenderStore)" if (!browserDetection.isEdge) { - it('should return promises to the worker', inject([Serializer], (serializer) => { + it("should return promises to the worker", inject([Serializer], (serializer) => { var broker = new ServiceMessageBroker_(messageBuses.ui, serializer, CHANNEL); broker.registerMethod(TEST_METHOD, [PRIMITIVE], (arg1) => { expect(arg1).toEqual(PASSED_ARG_1); return PromiseWrapper.wrap(() => { return RESULT; }); }); - ObservableWrapper.callEmit( - messageBuses.worker.to(CHANNEL), - {'method': TEST_METHOD, 'id': ID, 'args': [PASSED_ARG_1]}); + ObservableWrapper.callEmit(messageBuses.worker.to(CHANNEL), + {'method': TEST_METHOD, 'id': ID, 'args': [PASSED_ARG_1]}); ObservableWrapper.subscribe(messageBuses.worker.from(CHANNEL), (data: any) => { - expect(data.type).toEqual('result'); + expect(data.type).toEqual("result"); expect(data.id).toEqual(ID); expect(data.value).toEqual(RESULT); }); diff --git a/modules/angular2/test/web_workers/shared/web_worker_test_util.ts b/modules/angular2/test/web_workers/shared/web_worker_test_util.ts index f68e3b281b..a38dccb244 100644 --- a/modules/angular2/test/web_workers/shared/web_worker_test_util.ts +++ b/modules/angular2/test/web_workers/shared/web_worker_test_util.ts @@ -4,8 +4,15 @@ import {UiArguments} from 'angular2/src/web_workers/shared/client_message_broker import {Type, isPresent} from 'angular2/src/facade/lang'; import {SpyMessageBroker} from '../worker/spies'; import {expect} from 'angular2/src/testing/matchers'; -import {MessageBusSink, MessageBusSource, MessageBus} from 'angular2/src/web_workers/shared/message_bus'; -import {ClientMessageBroker, ClientMessageBrokerFactory_} from 'angular2/src/web_workers/shared/client_message_broker'; +import { + MessageBusSink, + MessageBusSource, + MessageBus +} from 'angular2/src/web_workers/shared/message_bus'; +import { + ClientMessageBroker, + ClientMessageBrokerFactory_ +} from 'angular2/src/web_workers/shared/client_message_broker'; import {MockEventEmitter} from './mock_event_emitter'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {NgZone} from 'angular2/src/core/zone/ng_zone'; @@ -25,9 +32,8 @@ export function createPairedMessageBuses(): PairedMessageBuses { var uiMessageBusSink = new MockMessageBusSink(secondChannels); var workerMessageBusSource = new MockMessageBusSource(secondChannels); - return new PairedMessageBuses( - new MockMessageBus(uiMessageBusSink, uiMessageBusSource), - new MockMessageBus(workerMessageBusSink, workerMessageBusSource)); + return new PairedMessageBuses(new MockMessageBus(uiMessageBusSink, uiMessageBusSource), + new MockMessageBus(workerMessageBusSink, workerMessageBusSource)); } /** @@ -36,29 +42,29 @@ export function createPairedMessageBuses(): PairedMessageBuses { * If a handler is provided it will be called to handle the request. * Only intended to be called on a given broker instance once. */ -export function expectBrokerCall( - broker: SpyMessageBroker, methodName: string, vals?: Array<any>, - handler?: (..._: any[]) => Promise<any>| void): void { - broker.spy('runOnService').andCallFake((args: UiArguments, returnType: Type) => { - expect(args.method).toEqual(methodName); - if (isPresent(vals)) { - expect(args.args.length).toEqual(vals.length); - ListWrapper.forEachWithIndex(vals, (v, i) => {expect(v).toEqual(args.args[i].value)}); - } - var promise = null; - if (isPresent(handler)) { - let givenValues = args.args.map((arg) => {arg.value}); - if (givenValues.length > 0) { - promise = handler(givenValues); - } else { - promise = handler(); - } - } - if (promise == null) { - promise = PromiseWrapper.wrap(() => {}); - } - return promise; - }); +export function expectBrokerCall(broker: SpyMessageBroker, methodName: string, vals?: Array<any>, + handler?: (..._: any[]) => Promise<any>| void): void { + broker.spy("runOnService") + .andCallFake((args: UiArguments, returnType: Type) => { + expect(args.method).toEqual(methodName); + if (isPresent(vals)) { + expect(args.args.length).toEqual(vals.length); + ListWrapper.forEachWithIndex(vals, (v, i) => {expect(v).toEqual(args.args[i].value)}); + } + var promise = null; + if (isPresent(handler)) { + let givenValues = args.args.map((arg) => {arg.value}); + if (givenValues.length > 0) { + promise = handler(givenValues); + } else { + promise = handler(); + } + } + if (promise == null) { + promise = PromiseWrapper.wrap(() => {}); + } + return promise; + }); } export class PairedMessageBuses { diff --git a/modules/angular2/test/web_workers/worker/platform_location_spec.ts b/modules/angular2/test/web_workers/worker/platform_location_spec.ts index ff1d0ce5a0..62e06d9569 100644 --- a/modules/angular2/test/web_workers/worker/platform_location_spec.ts +++ b/modules/angular2/test/web_workers/worker/platform_location_spec.ts @@ -1,39 +1,52 @@ -import {AsyncTestCompleter, inject, describe, it, expect, beforeEach, beforeEachProviders} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + describe, + it, + expect, + beforeEach, + beforeEachProviders +} from 'angular2/testing_internal'; import {SpyMessageBroker} from './spies'; import {WebWorkerPlatformLocation} from 'angular2/src/web_workers/worker/platform_location'; import {LocationType} from 'angular2/src/web_workers/shared/serialized_types'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; -import {createPairedMessageBuses, MockMessageBrokerFactory, expectBrokerCall} from '../shared/web_worker_test_util'; +import { + createPairedMessageBuses, + MockMessageBrokerFactory, + expectBrokerCall +} from '../shared/web_worker_test_util'; import {UiArguments} from 'angular2/src/web_workers/shared/client_message_broker'; import {Type} from 'angular2/src/facade/lang'; -import {PromiseWrapper} from 'angular2/src/facade/async'; +import {PromiseWrapper} from "angular2/src/facade/async"; import {CONST_EXPR} from 'angular2/src/facade/lang'; export function main() { - describe('WebWorkerPlatformLocation', () => { + describe("WebWorkerPlatformLocation", () => { var uiBus: MessageBus = null; var workerBus: MessageBus = null; var broker: any = null; - var TEST_LOCATION = new LocationType( - 'http://www.example.com', 'http', 'example.com', 'example.com', '80', '/', '', '', - 'http://www.example.com'); + var TEST_LOCATION = + new LocationType("http://www.example.com", "http", "example.com", "example.com", "80", "/", + "", "", "http://www.example.com"); function createWebWorkerPlatformLocation(loc: LocationType): WebWorkerPlatformLocation { - broker.spy('runOnService').andCallFake((args: UiArguments, returnType: Type) => { - if (args.method === 'getLocation') { - return PromiseWrapper.resolve(loc); - } - }); + broker.spy("runOnService") + .andCallFake((args: UiArguments, returnType: Type) => { + if (args.method === 'getLocation') { + return PromiseWrapper.resolve(loc); + } + }); var factory = new MockMessageBrokerFactory(broker); return new WebWorkerPlatformLocation(factory, workerBus, null); } function testPushOrReplaceState(pushState: boolean) { let platformLocation = createWebWorkerPlatformLocation(null); - const TITLE = 'foo'; - const URL = 'http://www.example.com/foo'; - expectBrokerCall(broker, pushState ? 'pushState' : 'replaceState', [null, TITLE, URL]); + const TITLE = "foo"; + const URL = "http://www.example.com/foo"; + expectBrokerCall(broker, pushState ? "pushState" : "replaceState", [null, TITLE, URL]); if (pushState) { platformLocation.pushState(null, TITLE, URL); } else { @@ -45,40 +58,40 @@ export function main() { var buses = createPairedMessageBuses(); uiBus = buses.ui; workerBus = buses.worker; - workerBus.initChannel('ng-Router'); - uiBus.initChannel('ng-Router'); + workerBus.initChannel("ng-Router"); + uiBus.initChannel("ng-Router"); broker = new SpyMessageBroker(); }); - it('should throw if getBaseHrefFromDOM is called', () => { + it("should throw if getBaseHrefFromDOM is called", () => { let platformLocation = createWebWorkerPlatformLocation(null); expect(() => platformLocation.getBaseHrefFromDOM()).toThrowError(); }); - it('should get location on init', () => { + it("should get location on init", () => { let platformLocation = createWebWorkerPlatformLocation(null); - expectBrokerCall(broker, 'getLocation'); + expectBrokerCall(broker, "getLocation"); platformLocation.init(); }); - it('should throw if set pathname is called before init finishes', () => { + it("should throw if set pathname is called before init finishes", () => { let platformLocation = createWebWorkerPlatformLocation(null); platformLocation.init(); - expect(() => platformLocation.pathname = 'TEST').toThrowError(); + expect(() => platformLocation.pathname = "TEST").toThrowError(); }); - it('should send pathname to render thread', inject([AsyncTestCompleter], (async) => { + it("should send pathname to render thread", inject([AsyncTestCompleter], (async) => { let platformLocation = createWebWorkerPlatformLocation(TEST_LOCATION); platformLocation.init().then((_) => { - let PATHNAME = '/test'; - expectBrokerCall(broker, 'setPathname', [PATHNAME]); + let PATHNAME = "/test"; + expectBrokerCall(broker, "setPathname", [PATHNAME]); platformLocation.pathname = PATHNAME; async.done(); }); })); - it('should send pushState to render thread', () => { testPushOrReplaceState(true); }); + it("should send pushState to render thread", () => { testPushOrReplaceState(true); }); - it('should send replaceState to render thread', () => { testPushOrReplaceState(false); }); + it("should send replaceState to render thread", () => { testPushOrReplaceState(false); }); }); } diff --git a/modules/angular2/test/web_workers/worker/renderer_integration_spec.ts b/modules/angular2/test/web_workers/worker/renderer_integration_spec.ts index 5a096c53c6..eff2ce2813 100644 --- a/modules/angular2/test/web_workers/worker/renderer_integration_spec.ts +++ b/modules/angular2/test/web_workers/worker/renderer_integration_spec.ts @@ -1,20 +1,53 @@ -import {AsyncTestCompleter, inject, ddescribe, describe, dispatchEvent, it, iit, expect, beforeEach, beforeEachProviders, TestInjector, TestComponentBuilder} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + ddescribe, + describe, + dispatchEvent, + it, + iit, + expect, + beforeEach, + beforeEachProviders, + TestInjector, + TestComponentBuilder +} from "angular2/testing_internal"; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; -import {bind, provide, Provider, Injector, ViewMetadata, Component, Injectable, ElementRef} from 'angular2/core'; +import { + bind, + provide, + Provider, + Injector, + ViewMetadata, + Component, + Injectable, + ElementRef +} from 'angular2/core'; import {NgIf} from 'angular2/common'; -import {WebWorkerRootRenderer} from 'angular2/src/web_workers/worker/renderer'; -import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_, UiArguments, FnArg} from 'angular2/src/web_workers/shared/client_message_broker'; -import {Serializer} from 'angular2/src/web_workers/shared/serializer'; -import {RootRenderer} from 'angular2/src/core/render/api'; +import {WebWorkerRootRenderer} from "angular2/src/web_workers/worker/renderer"; +import { + ClientMessageBrokerFactory, + ClientMessageBrokerFactory_, + UiArguments, + FnArg +} from "angular2/src/web_workers/shared/client_message_broker"; +import {Serializer} from "angular2/src/web_workers/shared/serializer"; +import {RootRenderer} from "angular2/src/core/render/api"; import {DomRootRenderer, DomRootRenderer_} from 'angular2/src/platform/dom/dom_renderer'; import {DebugDomRootRenderer} from 'angular2/src/core/debug/debug_renderer'; -import {RenderStore} from 'angular2/src/web_workers/shared/render_store'; +import {RenderStore} from "angular2/src/web_workers/shared/render_store"; import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer'; import {createPairedMessageBuses, PairedMessageBuses} from '../shared/web_worker_test_util'; -import {ServiceMessageBrokerFactory, ServiceMessageBrokerFactory_} from 'angular2/src/web_workers/shared/service_message_broker'; +import { + ServiceMessageBrokerFactory, + ServiceMessageBrokerFactory_ +} from 'angular2/src/web_workers/shared/service_message_broker'; import {ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection'; import {ElementRef_} from 'angular2/src/core/linker/element_ref'; -import {TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS} from 'angular2/platform/testing/browser'; +import { + TEST_BROWSER_PLATFORM_PROVIDERS, + TEST_BROWSER_APPLICATION_PROVIDERS +} from 'angular2/platform/testing/browser'; export function main() { function createWebWorkerBrokerFactory( @@ -29,25 +62,25 @@ export function main() { // set up the ui side var uiMessageBrokerFactory = new ServiceMessageBrokerFactory_(uiMessageBus, uiSerializer); - var renderer = new MessageBasedRenderer( - uiMessageBrokerFactory, uiMessageBus, uiSerializer, uiRenderStore, domRootRenderer); + var renderer = new MessageBasedRenderer(uiMessageBrokerFactory, uiMessageBus, uiSerializer, + uiRenderStore, domRootRenderer); renderer.start(); return webWorkerBrokerFactory; } - function createWorkerRenderer( - workerSerializer: Serializer, uiSerializer: Serializer, domRootRenderer: DomRootRenderer, - uiRenderStore: RenderStore, workerRenderStore: RenderStore): RootRenderer { + function createWorkerRenderer(workerSerializer: Serializer, uiSerializer: Serializer, + domRootRenderer: DomRootRenderer, uiRenderStore: RenderStore, + workerRenderStore: RenderStore): RootRenderer { var messageBuses = createPairedMessageBuses(); - var brokerFactory = createWebWorkerBrokerFactory( - messageBuses, workerSerializer, uiSerializer, domRootRenderer, uiRenderStore); - var workerRootRenderer = new WebWorkerRootRenderer( - brokerFactory, messageBuses.worker, workerSerializer, workerRenderStore); + var brokerFactory = createWebWorkerBrokerFactory(messageBuses, workerSerializer, uiSerializer, + domRootRenderer, uiRenderStore); + var workerRootRenderer = new WebWorkerRootRenderer(brokerFactory, messageBuses.worker, + workerSerializer, workerRenderStore); return new DebugDomRootRenderer(workerRootRenderer); } - describe('Web Worker Renderer', () => { + describe("Web Worker Renderer", () => { var uiInjector: Injector; var uiRenderStore: RenderStore; var workerRenderStore: RenderStore; @@ -58,7 +91,8 @@ export function main() { testUiInjector.platformProviders = TEST_BROWSER_PLATFORM_PROVIDERS; testUiInjector.applicationProviders = TEST_BROWSER_APPLICATION_PROVIDERS; testUiInjector.addProviders([ - Serializer, provide(RenderStore, {useValue: uiRenderStore}), + Serializer, + provide(RenderStore, {useValue: uiRenderStore}), provide(DomRootRenderer, {useClass: DomRootRenderer_}), provide(RootRenderer, {useExisting: DomRootRenderer}) ]); @@ -68,15 +102,17 @@ export function main() { workerRenderStore = new RenderStore(); return [ Serializer, - provide( - ChangeDetectorGenConfig, {useValue: new ChangeDetectorGenConfig(true, true, false)}), - provide(RenderStore, {useValue: workerRenderStore}), provide(RootRenderer, { - useFactory: (workerSerializer) => { - return createWorkerRenderer( - workerSerializer, uiSerializer, domRootRenderer, uiRenderStore, workerRenderStore); - }, - deps: [Serializer] - }) + provide(ChangeDetectorGenConfig, + {useValue: new ChangeDetectorGenConfig(true, true, false)}), + provide(RenderStore, {useValue: workerRenderStore}), + provide(RootRenderer, + { + useFactory: (workerSerializer) => { + return createWorkerRenderer(workerSerializer, uiSerializer, domRootRenderer, + uiRenderStore, workerRenderStore); + }, + deps: [Serializer] + }) ]; }); @@ -107,9 +143,8 @@ export function main() { it('should update any element property/attributes/class/style independent of the compilation on the root element and other elements', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, - new ViewMetadata({template: '<input [title]="y" style="position:absolute">'})) + tcb.overrideView(MyComp, new ViewMetadata( + {template: '<input [title]="y" style="position:absolute">'})) .createAsync(MyComp) .then((fixture) => { var checkSetters = (elr) => { @@ -191,8 +226,8 @@ export function main() { var elRef = (<ElementRef_>fixture.elementRef) .internalElement.componentView.appElements[0] .ref; - getRenderer(elRef).invokeElementMethod( - elRef.nativeElement, 'setAttribute', ['a', 'b']); + getRenderer(elRef) + .invokeElementMethod(elRef.nativeElement, 'setAttribute', ['a', 'b']); expect(DOM.getAttribute(getRenderElement(elRef), 'a')).toEqual('b'); async.done(); @@ -201,8 +236,8 @@ export function main() { it('should listen to events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { - tcb.overrideView( - MyComp, new ViewMetadata({template: '<input (change)="ctxNumProp = 1">'})) + tcb.overrideView(MyComp, + new ViewMetadata({template: '<input (change)="ctxNumProp = 1">'})) .createAsync(MyComp) .then((fixture) => { var elRef = (<ElementRef_>fixture.elementRef) diff --git a/modules/angular2/test/web_workers/worker/xhr_impl_spec.ts b/modules/angular2/test/web_workers/worker/xhr_impl_spec.ts index df45ea0717..9b6ba77c2e 100644 --- a/modules/angular2/test/web_workers/worker/xhr_impl_spec.ts +++ b/modules/angular2/test/web_workers/worker/xhr_impl_spec.ts @@ -1,20 +1,27 @@ -import {AsyncTestCompleter, inject, describe, it, expect, beforeEach, beforeEachProviders} from 'angular2/testing_internal'; +import { + AsyncTestCompleter, + inject, + describe, + it, + expect, + beforeEach, + beforeEachProviders +} from 'angular2/testing_internal'; import {SpyMessageBroker} from './spies'; -import {WebWorkerXHRImpl} from 'angular2/src/web_workers/worker/xhr_impl'; -import {PromiseWrapper} from 'angular2/src/facade/async'; -import {MockMessageBrokerFactory, expectBrokerCall} from '../shared/web_worker_test_util'; +import {WebWorkerXHRImpl} from "angular2/src/web_workers/worker/xhr_impl"; +import {PromiseWrapper} from "angular2/src/facade/async"; +import {MockMessageBrokerFactory, expectBrokerCall} from "../shared/web_worker_test_util"; export function main() { - describe('WebWorkerXHRImpl', () => { - it('should pass requests through the broker and return the response', + describe("WebWorkerXHRImpl", () => { + it("should pass requests through the broker and return the response", inject([AsyncTestCompleter], (async) => { - const URL = 'http://www.example.com/test'; - const RESPONSE = 'Example response text'; + const URL = "http://www.example.com/test"; + const RESPONSE = "Example response text"; var messageBroker = new SpyMessageBroker(); - expectBrokerCall(messageBroker, 'get', [URL], (_) => { - return PromiseWrapper.wrap(() => { return RESPONSE; }); - }); + expectBrokerCall(messageBroker, "get", [URL], + (_) => { return PromiseWrapper.wrap(() => { return RESPONSE; }); }); var xhrImpl = new WebWorkerXHRImpl(new MockMessageBrokerFactory(<any>messageBroker)); xhrImpl.get(URL).then((response) => { expect(response).toEqual(RESPONSE); diff --git a/modules/angular2/web_worker/ui.ts b/modules/angular2/web_worker/ui.ts index 4552c6bf1c..3b28fff8b8 100644 --- a/modules/angular2/web_worker/ui.ts +++ b/modules/angular2/web_worker/ui.ts @@ -1,6 +1,11 @@ export * from 'angular2/src/facade/facade'; export * from '../src/core/di'; export {platform, PlatformRef, ApplicationRef} from '../src/core/application_ref'; -export {APP_ID, APP_COMPONENT, APP_INITIALIZER, PLATFORM_INITIALIZER} from '../src/core/application_tokens'; +export { + APP_ID, + APP_COMPONENT, + APP_INITIALIZER, + PLATFORM_INITIALIZER +} from '../src/core/application_tokens'; export * from '../src/core/zone'; export * from 'angular2/platform/worker_render'; diff --git a/modules/benchmarks/e2e_test/change_detection_perf.ts b/modules/benchmarks/e2e_test/change_detection_perf.ts index 026df52e41..9a7c5d0bfd 100644 --- a/modules/benchmarks/e2e_test/change_detection_perf.ts +++ b/modules/benchmarks/e2e_test/change_detection_perf.ts @@ -12,7 +12,8 @@ describe('ng2 change detection benchmark', function() { buttons: ['#ng2ChangeDetectionDynamicReads'], id: 'ng2.changeDetection.dynamic.reads', params: [ - {name: 'numberOfChecks', value: 900000}, {name: 'iterations', value: 20, scale: 'linear'} + {name: 'numberOfChecks', value: 900000}, + {name: 'iterations', value: 20, scale: 'linear'} ], microMetrics: {'detectChangesAvg': 'avg time to detect changes (ms)'}, waitForAngular2: false @@ -25,7 +26,8 @@ describe('ng2 change detection benchmark', function() { buttons: ['#ng2ChangeDetectionDynamicWrites'], id: 'ng2.changeDetection.dynamic.writes', params: [ - {name: 'numberOfChecks', value: 900000}, {name: 'iterations', value: 20, scale: 'linear'} + {name: 'numberOfChecks', value: 900000}, + {name: 'iterations', value: 20, scale: 'linear'} ], microMetrics: {'detectChangesAvg': 'avg time to detect changes (ms)'}, waitForAngular2: false @@ -38,7 +40,8 @@ describe('ng2 change detection benchmark', function() { buttons: ['#ng2ChangeDetectionJitReads'], id: 'ng2.changeDetection.jit.reads', params: [ - {name: 'numberOfChecks', value: 900000}, {name: 'iterations', value: 20, scale: 'linear'} + {name: 'numberOfChecks', value: 900000}, + {name: 'iterations', value: 20, scale: 'linear'} ], microMetrics: {'detectChangesAvg': 'avg time to detect changes (ms)'}, waitForAngular2: false @@ -51,7 +54,8 @@ describe('ng2 change detection benchmark', function() { buttons: ['#ng2ChangeDetectionJitWrites'], id: 'ng2.changeDetection.jit.writes', params: [ - {name: 'numberOfChecks', value: 900000}, {name: 'iterations', value: 20, scale: 'linear'} + {name: 'numberOfChecks', value: 900000}, + {name: 'iterations', value: 20, scale: 'linear'} ], microMetrics: {'detectChangesAvg': 'avg time to detect changes (ms)'}, waitForAngular2: false @@ -64,7 +68,8 @@ describe('ng2 change detection benchmark', function() { buttons: ['#baselineChangeDetectionReads'], id: 'baseline.changeDetection.reads', params: [ - {name: 'numberOfChecks', value: 900000}, {name: 'iterations', value: 20, scale: 'linear'} + {name: 'numberOfChecks', value: 900000}, + {name: 'iterations', value: 20, scale: 'linear'} ], microMetrics: {'detectChangesAvg': 'avg time to detect changes (ms)'}, waitForAngular2: false @@ -77,7 +82,8 @@ describe('ng2 change detection benchmark', function() { buttons: ['#baselineChangeDetectionWrites'], id: 'baseline.changeDetection.writes', params: [ - {name: 'numberOfChecks', value: 900000}, {name: 'iterations', value: 20, scale: 'linear'} + {name: 'numberOfChecks', value: 900000}, + {name: 'iterations', value: 20, scale: 'linear'} ], microMetrics: {'detectChangesAvg': 'avg time to detect changes (ms)'}, waitForAngular2: false diff --git a/modules/benchmarks/e2e_test/largetable_perf.ts b/modules/benchmarks/e2e_test/largetable_perf.ts index d8740c616d..2cc96f043b 100644 --- a/modules/benchmarks/e2e_test/largetable_perf.ts +++ b/modules/benchmarks/e2e_test/largetable_perf.ts @@ -21,7 +21,8 @@ describe('ng2 largetable benchmark', function() { buttons: ['#ng2DestroyDom', '#ng2CreateDom'], id: 'ng2.largetable.' + benchmarkType, params: [ - {name: 'rows', value: 20, scale: 'sqrt'}, {name: 'columns', value: 20, scale: 'sqrt'}, + {name: 'rows', value: 20, scale: 'sqrt'}, + {name: 'columns', value: 20, scale: 'sqrt'}, {name: 'benchmarkType', value: benchmarkType} ] }).then(done, done.fail); @@ -34,7 +35,8 @@ describe('ng2 largetable benchmark', function() { buttons: ['#baselineDestroyDom', '#baselineCreateDom'], id: 'baseline.largetable', params: [ - {name: 'rows', value: 100, scale: 'sqrt'}, {name: 'columns', value: 20, scale: 'sqrt'}, + {name: 'rows', value: 100, scale: 'sqrt'}, + {name: 'columns', value: 20, scale: 'sqrt'}, {name: 'benchmarkType', value: 'baseline'} ] }).then(done, done.fail); diff --git a/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.ts b/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.ts index 154b535431..b32d1af68a 100644 --- a/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.ts +++ b/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.ts @@ -12,14 +12,15 @@ describe('ng2 naive infinite scroll benchmark', function() { url: URL, id: 'ng2.naive_infinite_scroll', work: function() { - browser.wait( - protractor.until.elementLocated(protractor.By.css('body /deep/ #scrollDiv')), 5000); + browser.wait(protractor.until.elementLocated(protractor.By.css('body /deep/ #scrollDiv')), + 5000); $('#reset-btn').click(); $('#run-btn').click(); browser.wait(protractor.until.elementLocated(protractor.By.css('#done')), 10000); }, params: [ - {name: 'appSize', value: appSize}, {name: 'iterationCount', value: 20, scale: 'linear'}, + {name: 'appSize', value: appSize}, + {name: 'iterationCount', value: 20, scale: 'linear'}, {name: 'scrollIncrement', value: 40} ] }).then(done, done.fail); diff --git a/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts b/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts index 7aa0ed6401..65290929bb 100644 --- a/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts +++ b/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts @@ -15,8 +15,8 @@ describe('ng2 naive infinite scroll benchmark', function() { var stageButtons = `${ allScrollItems } .row stage-buttons button`; var count = function(selector) { - return browser.executeScript( - `return ` + `document.querySelectorAll("${ selector }").length;`); + return browser.executeScript(`return ` + + `document.querySelectorAll("${ selector }").length;`); }; var clickFirstOf = function(selector) { @@ -24,8 +24,8 @@ describe('ng2 naive infinite scroll benchmark', function() { }; var firstTextOf = function(selector) { - return browser.executeScript( - `return ` + `document.querySelector("${ selector }").innerText;`); + return browser.executeScript(`return ` + + `document.querySelector("${ selector }").innerText;`); }; // Make sure rows are rendered @@ -35,17 +35,18 @@ describe('ng2 naive infinite scroll benchmark', function() { count(cells).then(function(c) { expect(c).toEqual(expectedRowCount * expectedCellsPerRow); }); // Click on first enabled button and verify stage changes - firstTextOf(`${ stageButtons }:enabled`).then(function(text) { - expect(text).toEqual('Pitched'); - clickFirstOf(`${ stageButtons }:enabled`).then(function() { - firstTextOf(`${ stageButtons }:enabled`).then(function(text) { - expect(text).toEqual('Won'); - }) - }); - }); + firstTextOf(`${ stageButtons }:enabled`) + .then(function(text) { + expect(text).toEqual('Pitched'); + clickFirstOf(`${ stageButtons }:enabled`) + .then(function() { + firstTextOf(`${ stageButtons }:enabled`) + .then(function(text) { expect(text).toEqual('Won'); }) + }); + }); - $('#reset-btn').click(); - $('#run-btn').click(); + $("#reset-btn").click(); + $("#run-btn").click(); browser.wait(() => { return $('#done').getText().then(function() { return true; }, function() { return false; }); }, 10000); diff --git a/modules/benchmarks/src/change_detection/change_detection_benchmark.ts b/modules/benchmarks/src/change_detection/change_detection_benchmark.ts index 560769429c..8417f4cdea 100644 --- a/modules/benchmarks/src/change_detection/change_detection_benchmark.ts +++ b/modules/benchmarks/src/change_detection/change_detection_benchmark.ts @@ -3,7 +3,19 @@ import {isPresent} from 'angular2/src/facade/lang'; import {getIntParameter, bindAction, microBenchmark} from 'angular2/src/testing/benchmark_util'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; -import {Lexer, Parser, ChangeDispatcher, DebugContext, DynamicProtoChangeDetector, JitProtoChangeDetector, ChangeDetectorDefinition, ChangeDetectorGenConfig, BindingRecord, DirectiveRecord, DirectiveIndex} from 'angular2/src/core/change_detection/change_detection'; +import { + Lexer, + Parser, + ChangeDispatcher, + DebugContext, + DynamicProtoChangeDetector, + JitProtoChangeDetector, + ChangeDetectorDefinition, + ChangeDetectorGenConfig, + BindingRecord, + DirectiveRecord, + DirectiveIndex +} from 'angular2/src/core/change_detection/change_detection'; // ---- SHARED @@ -242,30 +254,30 @@ function setUpChangeDetection(protoChangeDetectorFactory: Function, iterations, var directiveRecord = new DirectiveRecord({directiveIndex: new DirectiveIndex(0, 0)}); var bindings = [ - BindingRecord.createForDirective( - parser.parseBinding('field0', null), 'field0', reflector.setter('field0'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field1', null), 'field1', reflector.setter('field1'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field2', null), 'field2', reflector.setter('field2'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field3', null), 'field3', reflector.setter('field3'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field4', null), 'field4', reflector.setter('field4'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field5', null), 'field5', reflector.setter('field5'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field6', null), 'field6', reflector.setter('field6'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field7', null), 'field7', reflector.setter('field7'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field8', null), 'field8', reflector.setter('field8'), directiveRecord), - BindingRecord.createForDirective( - parser.parseBinding('field9', null), 'field9', reflector.setter('field9'), directiveRecord) + BindingRecord.createForDirective(parser.parseBinding('field0', null), "field0", + reflector.setter("field0"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field1', null), "field1", + reflector.setter("field1"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field2', null), "field2", + reflector.setter("field2"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field3', null), "field3", + reflector.setter("field3"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field4', null), "field4", + reflector.setter("field4"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field5', null), "field5", + reflector.setter("field5"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field6', null), "field6", + reflector.setter("field6"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field7', null), "field7", + reflector.setter("field7"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field8', null), "field8", + reflector.setter("field8"), directiveRecord), + BindingRecord.createForDirective(parser.parseBinding('field9', null), "field9", + reflector.setter("field9"), directiveRecord) ]; var proto = protoChangeDetectorFactory( - new ChangeDetectorDefinition('proto', null, [], bindings, [], [directiveRecord], genConfig)); + new ChangeDetectorDefinition("proto", null, [], bindings, [], [directiveRecord], genConfig)); var targetObj = new Obj(); parentCd.hydrate(object, null, new DummyDispatcher(targetObj), null); @@ -308,16 +320,13 @@ export function main() { runBaselineReads(baselineHead, 1); // warmup - bindAction( - '#baselineChangeDetectionReads', - () => microBenchmark( - 'detectChangesAvg', numberOfRuns, () => runBaselineReads(baselineHead, numberOfRuns))); + bindAction('#baselineChangeDetectionReads', + () => microBenchmark('detectChangesAvg', numberOfRuns, + () => runBaselineReads(baselineHead, numberOfRuns))); - bindAction( - '#baselineChangeDetectionWrites', - () => microBenchmark( - 'detectChangesAvg', numberOfRuns, - () => runBaselineWrites(baselineHead, numberOfRuns, object))); + bindAction('#baselineChangeDetectionWrites', + () => microBenchmark('detectChangesAvg', numberOfRuns, + () => runBaselineWrites(baselineHead, numberOfRuns, object))); @@ -330,15 +339,13 @@ export function main() { bindAction( '#ng2ChangeDetectionDynamicReads', - () => microBenchmark( - 'detectChangesAvg', numberOfRuns, - () => runChangeDetectionReads(ng2DynamicChangeDetector, numberOfRuns))); + () => microBenchmark('detectChangesAvg', numberOfRuns, + () => runChangeDetectionReads(ng2DynamicChangeDetector, numberOfRuns))); - bindAction( - '#ng2ChangeDetectionDynamicWrites', - () => microBenchmark( - 'detectChangesAvg', numberOfRuns, - () => runChangeDetectionWrites(ng2DynamicChangeDetector, numberOfRuns, object))); + bindAction('#ng2ChangeDetectionDynamicWrites', + () => microBenchmark( + 'detectChangesAvg', numberOfRuns, + () => runChangeDetectionWrites(ng2DynamicChangeDetector, numberOfRuns, object))); @@ -353,15 +360,13 @@ export function main() { bindAction( '#ng2ChangeDetectionJitReads', - () => microBenchmark( - 'detectChangesAvg', numberOfRuns, - () => runChangeDetectionReads(ng2JitChangeDetector, numberOfRuns))); + () => microBenchmark('detectChangesAvg', numberOfRuns, + () => runChangeDetectionReads(ng2JitChangeDetector, numberOfRuns))); - bindAction( - '#ng2ChangeDetectionJitWrites', - () => microBenchmark( - 'detectChangesAvg', numberOfRuns, - () => runChangeDetectionWrites(ng2JitChangeDetector, numberOfRuns, object))); + bindAction('#ng2ChangeDetectionJitWrites', + () => microBenchmark( + 'detectChangesAvg', numberOfRuns, + () => runChangeDetectionWrites(ng2JitChangeDetector, numberOfRuns, object))); } else { bindAction('#ng2ChangeDetectionJitReads', () => {}); bindAction('#ng2ChangeDetectionJitWrites', () => {}); @@ -372,13 +377,13 @@ class DummyDispatcher implements ChangeDispatcher { targetObj: Obj; constructor(targetObj) { this.targetObj = targetObj; } getDebugContext(appElement: any, elementIndex: number, directiveIndex: number): DebugContext { - throw 'getDebugContext not implemented.'; + throw "getDebugContext not implemented."; } - notifyOnBinding(bindingTarget, newValue) { throw 'Should not be used'; } - logBindingUpdate(bindingTarget, newValue) { throw 'Should not be used'; } + notifyOnBinding(bindingTarget, newValue) { throw "Should not be used"; } + logBindingUpdate(bindingTarget, newValue) { throw "Should not be used"; } notifyAfterContentChecked() {} notifyAfterViewChecked() {} notifyOnDestroy() {} - getDetectorFor(directiveIndex: DirectiveIndex): any { throw 'getDetectorFor not implemented.'; } + getDetectorFor(directiveIndex: DirectiveIndex): any { throw "getDetectorFor not implemented."; } getDirectiveFor(record) { return this.targetObj; } } diff --git a/modules/benchmarks/src/compiler/compiler_benchmark.ts b/modules/benchmarks/src/compiler/compiler_benchmark.ts index 98d260f741..37b0e16119 100644 --- a/modules/benchmarks/src/compiler/compiler_benchmark.ts +++ b/modules/benchmarks/src/compiler/compiler_benchmark.ts @@ -5,7 +5,16 @@ import {PromiseWrapper} from 'angular2/src/facade/async'; import {ListWrapper, Map, MapWrapper} from 'angular2/src/facade/collection'; import {DateWrapper, Type, print, isPresent} from 'angular2/src/facade/lang'; -import {Compiler, Component, Directive, ViewContainerRef, bind, provide, Provider, ViewMetadata} from 'angular2/core'; +import { + Compiler, + Component, + Directive, + ViewContainerRef, + bind, + provide, + Provider, + ViewMetadata +} from 'angular2/core'; import {ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection'; import {ViewResolver} from 'angular2/src/core/linker/view_resolver'; @@ -15,12 +24,13 @@ import {getIntParameter, bindAction} from 'angular2/src/testing/benchmark_util'; function _createBindings(): Provider[] { var multiplyTemplatesBy = getIntParameter('elements'); return [ - provide(ViewResolver, { - useFactory: - () => new MultiplyViewResolver( - multiplyTemplatesBy, [BenchmarkComponentNoBindings, BenchmarkComponentWithBindings]), - deps: [] - }), + provide(ViewResolver, + { + useFactory: () => new MultiplyViewResolver( + multiplyTemplatesBy, + [BenchmarkComponentNoBindings, BenchmarkComponentWithBindings]), + deps: [] + }), // Use DynamicChangeDetector as that is the only one that Dart supports as well // so that we can compare the numbers between JS and Dart provide(ChangeDetectorGenConfig, {useValue: new ChangeDetectorGenConfig(false, false, false)}) @@ -29,12 +39,14 @@ function _createBindings(): Provider[] { export function main() { BrowserDomAdapter.makeCurrent(); - bootstrap(CompilerAppComponent, _createBindings()).then((ref) => { - var app = ref.hostComponent; - bindAction('#compileNoBindings', measureWrapper(() => app.compileNoBindings(), 'No Bindings')); - bindAction( - '#compileWithBindings', measureWrapper(() => app.compileWithBindings(), 'With Bindings')); - }); + bootstrap(CompilerAppComponent, _createBindings()) + .then((ref) => { + var app = ref.hostComponent; + bindAction('#compileNoBindings', + measureWrapper(() => app.compileNoBindings(), 'No Bindings')); + bindAction('#compileWithBindings', + measureWrapper(() => app.compileWithBindings(), 'With Bindings')); + }); } function measureWrapper(func, desc) { diff --git a/modules/benchmarks/src/compiler/selector_benchmark.ts b/modules/benchmarks/src/compiler/selector_benchmark.ts index 09404deba1..3ff9ec546a 100644 --- a/modules/benchmarks/src/compiler/selector_benchmark.ts +++ b/modules/benchmarks/src/compiler/selector_benchmark.ts @@ -1,5 +1,5 @@ -import {SelectorMatcher} from 'angular2/src/compiler/selector'; -import {CssSelector} from 'angular2/src/compiler/selector'; +import {SelectorMatcher} from "angular2/src/compiler/selector"; +import {CssSelector} from "angular2/src/compiler/selector"; import {StringWrapper, Math} from 'angular2/src/facade/lang'; import {getIntParameter, bindAction} from 'angular2/src/testing/benchmark_util'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; diff --git a/modules/benchmarks/src/costs/index.ts b/modules/benchmarks/src/costs/index.ts index 96040aab70..b6b64d4131 100644 --- a/modules/benchmarks/src/costs/index.ts +++ b/modules/benchmarks/src/costs/index.ts @@ -11,34 +11,35 @@ export function main() { var size = getIntParameter('size'); testList = ListWrapper.createFixedSize(size); - bootstrap(AppComponent).then((ref) => { - var injector = ref.injector; - var app: AppComponent = ref.hostComponent; - var appRef = injector.get(ApplicationRef); + bootstrap(AppComponent) + .then((ref) => { + var injector = ref.injector; + var app: AppComponent = ref.hostComponent; + var appRef = injector.get(ApplicationRef); - bindAction('#reset', function() { - app.reset(); - appRef.tick(); - }); + bindAction('#reset', function() { + app.reset(); + appRef.tick(); + }); - // Baseline (plain components) - bindAction('#createPlainComponents', function() { - app.createPlainComponents(); - appRef.tick(); - }); + // Baseline (plain components) + bindAction('#createPlainComponents', function() { + app.createPlainComponents(); + appRef.tick(); + }); - // Components with decorators - bindAction('#createComponentsWithDirectives', function() { - app.createComponentsWithDirectives(); - appRef.tick(); - }); + // Components with decorators + bindAction('#createComponentsWithDirectives', function() { + app.createComponentsWithDirectives(); + appRef.tick(); + }); - // Components with decorators - bindAction('#createDynamicComponents', function() { - app.createDynamicComponents(); - appRef.tick(); - }); - }); + // Components with decorators + bindAction('#createDynamicComponents', function() { + app.createDynamicComponents(); + appRef.tick(); + }); + }); } diff --git a/modules/benchmarks/src/di/di_benchmark.ts b/modules/benchmarks/src/di/di_benchmark.ts index 30bff3ec22..8d9b673bf2 100644 --- a/modules/benchmarks/src/di/di_benchmark.ts +++ b/modules/benchmarks/src/di/di_benchmark.ts @@ -1,4 +1,4 @@ -import {Injectable, Injector, Key, bind, provide} from 'angular2/core'; +import {Injectable, Injector, Key, bind, provide} from "angular2/core"; import {reflector} from 'angular2/src/core/reflection/reflection'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; import {getIntParameter, bindAction, microBenchmark} from 'angular2/src/testing/benchmark_util'; @@ -81,9 +81,8 @@ export function main() { bindAction('#getChild', () => microBenchmark('injectAvg', iterations, getChild)); bindAction('#instantiate', () => microBenchmark('injectAvg', iterations, instantiate)); bindAction('#createVariety', () => microBenchmark('injectAvg', iterations, createVariety)); - bindAction( - '#createVarietyResolved', - () => microBenchmark('injectAvg', iterations, createVarietyResolved)); + bindAction('#createVarietyResolved', + () => microBenchmark('injectAvg', iterations, createVarietyResolved)); } diff --git a/modules/benchmarks/src/largetable/largetable_benchmark.ts b/modules/benchmarks/src/largetable/largetable_benchmark.ts index 3ed14ee33f..0580b9104b 100644 --- a/modules/benchmarks/src/largetable/largetable_benchmark.ts +++ b/modules/benchmarks/src/largetable/largetable_benchmark.ts @@ -1,6 +1,12 @@ import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {window, document, gc} from 'angular2/src/facade/browser'; -import {getIntParameter, getStringParameter, bindAction, windowProfile, windowProfileEnd} from 'angular2/src/testing/benchmark_util'; +import { + getIntParameter, + getStringParameter, + bindAction, + windowProfile, + windowProfileEnd +} from 'angular2/src/testing/benchmark_util'; import {bootstrap} from 'angular2/platform/browser'; import {Component, Directive, bind, provide} from 'angular2/core'; import {NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault} from 'angular2/common'; @@ -104,15 +110,16 @@ export function main() { function noop() {} function initNg2() { - bootstrap(AppComponent, _createBindings()).then((ref) => { - var injector = ref.injector; - app = ref.hostComponent; - appRef = injector.get(ApplicationRef); - bindAction('#ng2DestroyDom', ng2DestroyDom); - bindAction('#ng2CreateDom', ng2CreateDom); - bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update')); - bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create')); - }); + bootstrap(AppComponent, _createBindings()) + .then((ref) => { + var injector = ref.injector; + app = ref.hostComponent; + appRef = injector.get(ApplicationRef); + bindAction('#ng2DestroyDom', ng2DestroyDom); + bindAction('#ng2CreateDom', ng2CreateDom); + bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update')); + bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create')); + }); setupReflector(); } @@ -131,9 +138,8 @@ export function main() { bindAction('#baselineCreateDom', baselineCreateDom); bindAction('#baselineUpdateDomProfile', profile(baselineCreateDom, noop, 'baseline-update')); - bindAction( - '#baselineCreateDomProfile', - profile(baselineCreateDom, baselineDestroyDom, 'baseline-create')); + bindAction('#baselineCreateDomProfile', + profile(baselineCreateDom, baselineDestroyDom, 'baseline-create')); } initNg2(); @@ -242,9 +248,8 @@ class LargetableComponent { benchmarkType: string; rows: number; columns: number; - constructor( - @Inject(BENCHMARK_TYPE) benchmarkType, @Inject(LARGETABLE_ROWS) rows, - @Inject(LARGETABLE_COLS) columns) { + constructor(@Inject(BENCHMARK_TYPE) benchmarkType, @Inject(LARGETABLE_ROWS) rows, + @Inject(LARGETABLE_COLS) columns) { this.benchmarkType = benchmarkType; this.rows = rows; this.columns = columns; diff --git a/modules/benchmarks/src/naive_infinite_scroll/common.ts b/modules/benchmarks/src/naive_infinite_scroll/common.ts index 18dd914166..12797f6fc7 100644 --- a/modules/benchmarks/src/naive_infinite_scroll/common.ts +++ b/modules/benchmarks/src/naive_infinite_scroll/common.ts @@ -21,8 +21,9 @@ export var DUE_DATE_WIDTH = 100; export var END_DATE_WIDTH = 100; export var AAT_STATUS_WIDTH = 100; export var ROW_WIDTH = COMPANY_NAME_WIDTH + OPPORTUNITY_NAME_WIDTH + OFFERING_NAME_WIDTH + - ACCOUNT_CELL_WIDTH + BASE_POINTS_WIDTH + KICKER_POINTS_WIDTH + STAGE_BUTTONS_WIDTH + - BUNDLES_WIDTH + DUE_DATE_WIDTH + END_DATE_WIDTH + AAT_STATUS_WIDTH; + ACCOUNT_CELL_WIDTH + BASE_POINTS_WIDTH + KICKER_POINTS_WIDTH + + STAGE_BUTTONS_WIDTH + BUNDLES_WIDTH + DUE_DATE_WIDTH + END_DATE_WIDTH + + AAT_STATUS_WIDTH; export var STATUS_LIST = ['Planned', 'Pitched', 'Won', 'Lost']; diff --git a/modules/benchmarks/src/naive_infinite_scroll/random_data.ts b/modules/benchmarks/src/naive_infinite_scroll/random_data.ts index 9452a59b1d..6bae372b45 100644 --- a/modules/benchmarks/src/naive_infinite_scroll/random_data.ts +++ b/modules/benchmarks/src/naive_infinite_scroll/random_data.ts @@ -1,5 +1,13 @@ import {StringWrapper} from 'angular2/src/facade/lang'; -import {CustomDate, Offering, Company, Opportunity, Account, STATUS_LIST, AAT_STATUS_LIST} from './common'; +import { + CustomDate, + Offering, + Company, + Opportunity, + Account, + STATUS_LIST, + AAT_STATUS_LIST +} from './common'; export function generateOfferings(count: number): Offering[] { var res = []; @@ -44,7 +52,18 @@ export function generateAccount(seed: number): Account { } var names = [ - 'Foo', 'Bar', 'Baz', 'Qux', 'Quux', 'Garply', 'Waldo', 'Fred', 'Plugh', 'Xyzzy', 'Thud', 'Cruft', + 'Foo', + 'Bar', + 'Baz', + 'Qux', + 'Quux', + 'Garply', + 'Waldo', + 'Fred', + 'Plugh', + 'Xyzzy', + 'Thud', + 'Cruft', 'Stuff' ]; diff --git a/modules/benchmarks/src/naive_infinite_scroll/scroll_area.ts b/modules/benchmarks/src/naive_infinite_scroll/scroll_area.ts index 4eebace2f4..364d8e8ca8 100644 --- a/modules/benchmarks/src/naive_infinite_scroll/scroll_area.ts +++ b/modules/benchmarks/src/naive_infinite_scroll/scroll_area.ts @@ -3,7 +3,15 @@ import {Math} from 'angular2/src/facade/math'; import {Component, Directive} from 'angular2/core'; -import {Offering, ITEMS, ITEM_HEIGHT, VISIBLE_ITEMS, VIEW_PORT_HEIGHT, ROW_WIDTH, HEIGHT} from './common'; +import { + Offering, + ITEMS, + ITEM_HEIGHT, + VISIBLE_ITEMS, + VIEW_PORT_HEIGHT, + ROW_WIDTH, + HEIGHT +} from './common'; import {generateOfferings} from './random_data'; import {ScrollItemComponent} from './scroll_item'; import {NgFor} from 'angular2/common'; diff --git a/modules/benchmarks/src/naive_infinite_scroll/scroll_item.ts b/modules/benchmarks/src/naive_infinite_scroll/scroll_item.ts index a76b249fd9..fd8f8246c4 100644 --- a/modules/benchmarks/src/naive_infinite_scroll/scroll_item.ts +++ b/modules/benchmarks/src/naive_infinite_scroll/scroll_item.ts @@ -1,15 +1,40 @@ -import {CompanyNameComponent, OpportunityNameComponent, OfferingNameComponent, StageButtonsComponent, AccountCellComponent, FormattedCellComponent} from './cells'; +import { + CompanyNameComponent, + OpportunityNameComponent, + OfferingNameComponent, + StageButtonsComponent, + AccountCellComponent, + FormattedCellComponent +} from './cells'; import {Component, Directive} from 'angular2/core'; -import {Offering, ITEM_HEIGHT, COMPANY_NAME_WIDTH, OPPORTUNITY_NAME_WIDTH, OFFERING_NAME_WIDTH, ACCOUNT_CELL_WIDTH, BASE_POINTS_WIDTH, KICKER_POINTS_WIDTH, STAGE_BUTTONS_WIDTH, BUNDLES_WIDTH, DUE_DATE_WIDTH, END_DATE_WIDTH, AAT_STATUS_WIDTH} from './common'; +import { + Offering, + ITEM_HEIGHT, + COMPANY_NAME_WIDTH, + OPPORTUNITY_NAME_WIDTH, + OFFERING_NAME_WIDTH, + ACCOUNT_CELL_WIDTH, + BASE_POINTS_WIDTH, + KICKER_POINTS_WIDTH, + STAGE_BUTTONS_WIDTH, + BUNDLES_WIDTH, + DUE_DATE_WIDTH, + END_DATE_WIDTH, + AAT_STATUS_WIDTH +} from './common'; @Component({ selector: 'scroll-item', inputs: ['offering'], directives: [ - CompanyNameComponent, OpportunityNameComponent, OfferingNameComponent, StageButtonsComponent, - AccountCellComponent, FormattedCellComponent + CompanyNameComponent, + OpportunityNameComponent, + OfferingNameComponent, + StageButtonsComponent, + AccountCellComponent, + FormattedCellComponent ], template: ` <div class="row" diff --git a/modules/benchmarks/src/static_tree/tree_benchmark.ts b/modules/benchmarks/src/static_tree/tree_benchmark.ts index 5487d55c05..98b31def32 100644 --- a/modules/benchmarks/src/static_tree/tree_benchmark.ts +++ b/modules/benchmarks/src/static_tree/tree_benchmark.ts @@ -1,13 +1,27 @@ import {bootstrap} from 'angular2/platform/browser'; import {NgIf} from 'angular2/common'; -import {Compiler, Component, Directive, ViewContainerRef, bind, provide, Provider} from 'angular2/core'; +import { + Compiler, + Component, + Directive, + ViewContainerRef, + bind, + provide, + Provider +} from 'angular2/core'; import {ComponentRef_} from 'angular2/src/core/linker/dynamic_component_loader'; import {ApplicationRef} from 'angular2/src/core/application_ref'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {window, document, gc} from 'angular2/src/facade/browser'; -import {getIntParameter, getStringParameter, bindAction, windowProfile, windowProfileEnd} from 'angular2/src/testing/benchmark_util'; +import { + getIntParameter, + getStringParameter, + bindAction, + windowProfile, + windowProfileEnd +} from 'angular2/src/testing/benchmark_util'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; function createBindings(): Provider[] { @@ -78,16 +92,17 @@ export function main() { } function initNg2() { - bootstrap(AppComponentWithStaticTree, createBindings()).then((ref) => { - var injector = (<ComponentRef_>ref).injector; - appRef = injector.get(ApplicationRef); + bootstrap(AppComponentWithStaticTree, createBindings()) + .then((ref) => { + var injector = (<ComponentRef_>ref).injector; + appRef = injector.get(ApplicationRef); - app = (<ComponentRef_>ref).hostComponent; - bindAction('#ng2DestroyDom', ng2DestroyDom); - bindAction('#ng2CreateDom', ng2CreateDom); - bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update')); - bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create')); - }); + app = (<ComponentRef_>ref).hostComponent; + bindAction('#ng2DestroyDom', ng2DestroyDom); + bindAction('#ng2CreateDom', ng2CreateDom); + bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update')); + bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create')); + }); } function baselineDestroyDom() { baselineRootTreeComponent.update(null); } @@ -103,9 +118,8 @@ export function main() { bindAction('#baselineCreateDom', baselineCreateDom); bindAction('#baselineUpdateDomProfile', profile(baselineCreateDom, noop, 'baseline-update')); - bindAction( - '#baselineCreateDomProfile', - profile(baselineCreateDom, baselineDestroyDom, 'baseline-create')); + bindAction('#baselineCreateDomProfile', + profile(baselineCreateDom, baselineDestroyDom, 'baseline-create')); } initNg2(); @@ -125,9 +139,8 @@ class TreeNode { function buildTree(maxDepth, values, curDepth) { if (maxDepth === curDepth) return new TreeNode('', null, null); - return new TreeNode( - values[curDepth], buildTree(maxDepth, values, curDepth + 1), - buildTree(maxDepth, values, curDepth + 1)); + return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1), + buildTree(maxDepth, values, curDepth + 1)); } // http://jsperf.com/nextsibling-vs-childnodes diff --git a/modules/benchmarks/src/tree/tree_benchmark.ts b/modules/benchmarks/src/tree/tree_benchmark.ts index f339435a31..6a4e3792bb 100644 --- a/modules/benchmarks/src/tree/tree_benchmark.ts +++ b/modules/benchmarks/src/tree/tree_benchmark.ts @@ -1,12 +1,26 @@ import {bootstrap} from 'angular2/platform/browser'; -import {Compiler, Component, Directive, ViewContainerRef, bind, provide, Provider} from 'angular2/core'; +import { + Compiler, + Component, + Directive, + ViewContainerRef, + bind, + provide, + Provider +} from 'angular2/core'; import {NgIf} from 'angular2/common'; import {ApplicationRef} from 'angular2/src/core/application_ref'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {isPresent} from 'angular2/src/facade/lang'; import {window, document, gc} from 'angular2/src/facade/browser'; -import {getIntParameter, getStringParameter, bindAction, windowProfile, windowProfileEnd} from 'angular2/src/testing/benchmark_util'; +import { + getIntParameter, + getStringParameter, + bindAction, + windowProfile, + windowProfileEnd +} from 'angular2/src/testing/benchmark_util'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; function createProviders(): Provider[] { @@ -75,16 +89,17 @@ export function main() { function noop() {} function initNg2() { - bootstrap(AppComponent, createProviders()).then((ref) => { - var injector = ref.injector; - appRef = injector.get(ApplicationRef); + bootstrap(AppComponent, createProviders()) + .then((ref) => { + var injector = ref.injector; + appRef = injector.get(ApplicationRef); - app = ref.hostComponent; - bindAction('#ng2DestroyDom', ng2DestroyDom); - bindAction('#ng2CreateDom', ng2CreateDom); - bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update')); - bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create')); - }); + app = ref.hostComponent; + bindAction('#ng2DestroyDom', ng2DestroyDom); + bindAction('#ng2CreateDom', ng2CreateDom); + bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update')); + bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create')); + }); } function baselineDestroyDom() { baselineRootTreeComponent.update(new TreeNode('', null, null)); } @@ -105,9 +120,8 @@ export function main() { bindAction('#baselineCreateDom', baselineCreateDom); bindAction('#baselineUpdateDomProfile', profile(baselineCreateDom, noop, 'baseline-update')); - bindAction( - '#baselineCreateDomProfile', - profile(baselineCreateDom, baselineDestroyDom, 'baseline-create')); + bindAction('#baselineCreateDomProfile', + profile(baselineCreateDom, baselineDestroyDom, 'baseline-create')); } initNg2(); @@ -127,9 +141,8 @@ class TreeNode { function buildTree(maxDepth, values, curDepth) { if (maxDepth === curDepth) return new TreeNode('', null, null); - return new TreeNode( - values[curDepth], buildTree(maxDepth, values, curDepth + 1), - buildTree(maxDepth, values, curDepth + 1)); + return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1), + buildTree(maxDepth, values, curDepth + 1)); } // http://jsperf.com/nextsibling-vs-childnodes diff --git a/modules/benchmarks_external/e2e_test/naive_infinite_scroll_perf.ts b/modules/benchmarks_external/e2e_test/naive_infinite_scroll_perf.ts index 7a47938dd9..98685ac029 100644 --- a/modules/benchmarks_external/e2e_test/naive_infinite_scroll_perf.ts +++ b/modules/benchmarks_external/e2e_test/naive_infinite_scroll_perf.ts @@ -21,7 +21,8 @@ describe('ng-dart1.x naive infinite scroll benchmark', function() { browser.sleep(s); }, params: [ - {name: 'appSize', value: appSize}, {name: 'iterationCount', value: 20, scale: 'linear'}, + {name: 'appSize', value: appSize}, + {name: 'iterationCount', value: 20, scale: 'linear'}, {name: 'scrollIncrement', value: 40} ], waitForAngular2: false diff --git a/modules/benchmarks_external/src/compiler/compiler_benchmark.ts b/modules/benchmarks_external/src/compiler/compiler_benchmark.ts index fc8727297c..fcfc1ae3f7 100644 --- a/modules/benchmarks_external/src/compiler/compiler_benchmark.ts +++ b/modules/benchmarks_external/src/compiler/compiler_benchmark.ts @@ -24,71 +24,66 @@ function loadTemplate(templateId, repeatCount) { } angular.module('app', []) - .directive( - 'dir0', - [ - '$parse', - function($parse) { - return { - compile: function($element, $attrs) { - var expr = $parse($attrs.attr0); - return function($scope) { $scope.$watch(expr, angular.noop); } - } - }; - } - ]) - .directive( - 'dir1', - [ - '$parse', - function($parse) { - return { - compile: function($element, $attrs) { - var expr = $parse($attrs.attr1); - return function($scope) { $scope.$watch(expr, angular.noop); } - } - }; - } - ]) - .directive( - 'dir2', - [ - '$parse', - function($parse) { - return { - compile: function($element, $attrs) { - var expr = $parse($attrs.attr2); - return function($scope) { $scope.$watch(expr, angular.noop); } - } - }; - } - ]) - .directive( - 'dir3', - [ - '$parse', - function($parse) { - return { - compile: function($element, $attrs) { - var expr = $parse($attrs.attr3); - return function($scope) { $scope.$watch(expr, angular.noop); } - } - }; - } - ]) - .directive( - 'dir4', - [ - '$parse', - function($parse) { - return { - compile: function($element, $attrs) { - var expr = $parse($attrs.attr4); - return function($scope) { $scope.$watch(expr, angular.noop); } - } - }; - } - ]) + .directive('dir0', + [ + '$parse', + function($parse) { + return { + compile: function($element, $attrs) { + var expr = $parse($attrs.attr0); + return function($scope) { $scope.$watch(expr, angular.noop); } + } + }; + } + ]) + .directive('dir1', + [ + '$parse', + function($parse) { + return { + compile: function($element, $attrs) { + var expr = $parse($attrs.attr1); + return function($scope) { $scope.$watch(expr, angular.noop); } + } + }; + } + ]) + .directive('dir2', + [ + '$parse', + function($parse) { + return { + compile: function($element, $attrs) { + var expr = $parse($attrs.attr2); + return function($scope) { $scope.$watch(expr, angular.noop); } + } + }; + } + ]) + .directive('dir3', + [ + '$parse', + function($parse) { + return { + compile: function($element, $attrs) { + var expr = $parse($attrs.attr3); + return function($scope) { $scope.$watch(expr, angular.noop); } + } + }; + } + ]) + .directive('dir4', + [ + '$parse', + function($parse) { + return { + compile: function($element, $attrs) { + var expr = $parse($attrs.attr4); + return function($scope) { $scope.$watch(expr, angular.noop); } + } + }; + } + ]) .run([ '$compile', function($compile) { diff --git a/modules/benchmarks_external/src/largetable/largetable_benchmark.ts b/modules/benchmarks_external/src/largetable/largetable_benchmark.ts index b4228fcf28..54efce404f 100644 --- a/modules/benchmarks_external/src/largetable/largetable_benchmark.ts +++ b/modules/benchmarks_external/src/largetable/largetable_benchmark.ts @@ -16,75 +16,72 @@ angular.module('app', []) } }) .filter('noop', function() { return function(input) { return input; }; }) - .directive( - 'largetable', - function() { - return { - restrict: 'E', - templateUrl: 'largetable-js-template.html', - controller: 'DataController' - }; - }) - .controller( - 'DataController', - function($scope) { - bindAction('#destroyDom', destroyDom); - bindAction('#createDom', createDom); + .directive('largetable', + function() { + return { + restrict: 'E', + templateUrl: 'largetable-js-template.html', + controller: 'DataController' + }; + }) + .controller('DataController', + function($scope) { + bindAction('#destroyDom', destroyDom); + bindAction('#createDom', createDom); - function destroyDom() { - $scope.$apply(function() { $scope.benchmarkType = 'none'; }); - } + function destroyDom() { + $scope.$apply(function() { $scope.benchmarkType = 'none'; }); + } - function createDom() { - $scope.$apply(function() { $scope.benchmarkType = benchmarkType; }); - } + function createDom() { + $scope.$apply(function() { $scope.benchmarkType = benchmarkType; }); + } - var data = $scope.data = []; + var data = $scope.data = []; - function iGetter() { return this.i; } - function jGetter() { return this.j; } + function iGetter() { return this.i; } + function jGetter() { return this.j; } - for (var i = 0; i < totalRows; i++) { - data[i] = []; - for (var j = 0; j < totalColumns; j++) { - data[i][j] = {i: i, j: j, iFn: iGetter, jFn: jGetter}; - } - } - }) - .directive( - 'baselineBindingTable', - function() { - return { - restrict: 'E', - link: function($scope, $element) { - var i, j, row, cell, comment; - var template = document.createElement('span'); - template.setAttribute('ng-repeat', 'foo in foos'); - template.classList.add('ng-scope'); - template.appendChild(document.createElement('span')); - template.appendChild(document.createTextNode(':')); - template.appendChild(document.createElement('span')); - template.appendChild(document.createTextNode('|')); + for (var i = 0; i < totalRows; i++) { + data[i] = []; + for (var j = 0; j < totalColumns; j++) { + data[i][j] = {i: i, j: j, iFn: iGetter, jFn: jGetter}; + } + } + }) + .directive('baselineBindingTable', + function() { + return { + restrict: 'E', + link: function($scope, $element) { + var i, j, row, cell, comment; + var template = document.createElement('span'); + template.setAttribute('ng-repeat', 'foo in foos'); + template.classList.add('ng-scope'); + template.appendChild(document.createElement('span')); + template.appendChild(document.createTextNode(':')); + template.appendChild(document.createElement('span')); + template.appendChild(document.createTextNode('|')); - for (i = 0; i < totalRows; i++) { - row = document.createElement('div'); - $element[0].appendChild(row); - for (j = 0; j < totalColumns; j++) { - cell = template.cloneNode(true); - row.appendChild(cell); - cell.childNodes[0].textContent = i; - cell.childNodes[2].textContent = j; - cell.ng3992 = 'xxx'; - comment = document.createComment('ngRepeat end: bar in foo'); - row.appendChild(comment); - } + for (i = 0; i < totalRows; i++) { + row = document.createElement('div'); + $element[0].appendChild(row); + for (j = 0; j < totalColumns; j++) { + cell = template.cloneNode(true); + row.appendChild(cell); + cell.childNodes[0].textContent = i; + cell.childNodes[2].textContent = j; + cell.ng3992 = 'xxx'; + comment = document.createComment('ngRepeat end: bar in foo'); + row.appendChild(comment); + } - comment = document.createComment('ngRepeat end: foo in foos'); - $element[0].appendChild(comment); - } - } - }; - }) + comment = document.createComment('ngRepeat end: foo in foos'); + $element[0].appendChild(comment); + } + } + }; + }) .directive('baselineInterpolationTable', function() { return { restrict: 'E', diff --git a/modules/benchmarks_external/src/static_tree/tree_benchmark.ts b/modules/benchmarks_external/src/static_tree/tree_benchmark.ts index c3c267513d..10c3474f06 100644 --- a/modules/benchmarks_external/src/static_tree/tree_benchmark.ts +++ b/modules/benchmarks_external/src/static_tree/tree_benchmark.ts @@ -22,10 +22,10 @@ var module = angular.module('app', []); for (var depth = 0; depth < MAX_DEPTH; depth++) { addTreeDirective(module, depth); } -module - .config([ - '$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(false); } - ]) +module.config([ + '$compileProvider', + function($compileProvider) { $compileProvider.debugInfoEnabled(false); } + ]) .run([ '$rootScope', function($rootScope) { @@ -64,7 +64,6 @@ class TreeNode { function buildTree(maxDepth, values, curDepth) { if (maxDepth === curDepth) return new TreeNode('', null, null); - return new TreeNode( - values[curDepth], buildTree(maxDepth, values, curDepth + 1), - buildTree(maxDepth, values, curDepth + 1)); + return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1), + buildTree(maxDepth, values, curDepth + 1)); } diff --git a/modules/benchmarks_external/src/tree/react/index.ts b/modules/benchmarks_external/src/tree/react/index.ts index e7ae43431d..5cb4417ea6 100644 --- a/modules/benchmarks_external/src/tree/react/index.ts +++ b/modules/benchmarks_external/src/tree/react/index.ts @@ -11,18 +11,18 @@ var TreeComponent = React.createClass({ var left = null; if (treeNode.left) { left = React.createElement( - 'span', {}, [React.createElement(TreeComponent, {treeNode: treeNode.left}, '')]) + "span", {}, [React.createElement(TreeComponent, {treeNode: treeNode.left}, "")]) } var right = null; if (treeNode.right) { right = React.createElement( - 'span', {}, [React.createElement(TreeComponent, {treeNode: treeNode.right}, '')]) + "span", {}, [React.createElement(TreeComponent, {treeNode: treeNode.right}, "")]) } - var span = React.createElement('span', {}, [' ' + treeNode.value, left, right]); + var span = React.createElement("span", {}, [" " + treeNode.value, left, right]); - return (React.createElement('tree', {}, [span])); + return (React.createElement("tree", {}, [span])); } }); @@ -34,9 +34,8 @@ export function main() { bindAction('#createDom', createDom); var empty = new TreeNode(0, null, null); - var rootComponent = React.render( - React.createElement(TreeComponent, {treeNode: empty}, ''), - document.getElementById('rootTree')); + var rootComponent = React.render(React.createElement(TreeComponent, {treeNode: empty}, ""), + document.getElementById('rootTree')); function destroyDom() { rootComponent.setProps({treeNode: empty}); } @@ -61,7 +60,6 @@ class TreeNode { function buildTree(maxDepth, values, curDepth) { if (maxDepth === curDepth) return new TreeNode('', null, null); - return new TreeNode( - values[curDepth], buildTree(maxDepth, values, curDepth + 1), - buildTree(maxDepth, values, curDepth + 1)); + return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1), + buildTree(maxDepth, values, curDepth + 1)); } diff --git a/modules/benchmarks_external/src/tree/tree_benchmark.ts b/modules/benchmarks_external/src/tree/tree_benchmark.ts index 2a3f14b13e..5f0c6ff3b5 100644 --- a/modules/benchmarks_external/src/tree/tree_benchmark.ts +++ b/modules/benchmarks_external/src/tree/tree_benchmark.ts @@ -7,57 +7,57 @@ export function main() { } angular.module('app', []) - .directive( - 'tree', - function() { - return { - scope: {data: '='}, - template: '<span> {{data.value}}' + - ' <span tree-if="data.left"></span>' + - ' <span tree-if="data.right"></span>' + - '</span>' - }; - }) + .directive('tree', + function() { + return { + scope: {data: '='}, + template: '<span> {{data.value}}' + + ' <span tree-if="data.left"></span>' + + ' <span tree-if="data.right"></span>' + + '</span>' + }; + }) // special directive for "if" as angular 1.3 does not support // recursive components. - .directive( - 'treeIf', - [ - '$compile', '$parse', - function($compile, $parse) { - var transcludeFn; - return { - compile: function(element, attrs) { - var expr = $parse('!!' + attrs.treeIf); - var template = '<tree data="' + attrs.treeIf + '"></tree>'; - var transclude; - return function($scope, $element, $attrs) { - if (!transclude) { - transclude = $compile(template); - } - var childScope; - var childElement; - $scope.$watch(expr, function(newValue) { - if (childScope) { - childScope.$destroy(); - childElement.remove(); - childScope = null; - childElement = null; - } - if (newValue) { - childScope = $scope.$new(); - childElement = - transclude(childScope, function(clone) { $element.append(clone); }); - } - }); - } + .directive('treeIf', + [ + '$compile', + '$parse', + function($compile, $parse) { + var transcludeFn; + return { + compile: function(element, attrs) { + var expr = $parse('!!' + attrs.treeIf); + var template = '<tree data="' + attrs.treeIf + '"></tree>'; + var transclude; + return function($scope, $element, $attrs) { + if (!transclude) { + transclude = $compile(template); + } + var childScope; + var childElement; + $scope.$watch(expr, function(newValue) { + if (childScope) { + childScope.$destroy(); + childElement.remove(); + childScope = null; + childElement = null; + } + if (newValue) { + childScope = $scope.$new(); + childElement = transclude(childScope, + function(clone) { $element.append(clone); }); + } + }); + } - } - } - } - ]) + } + } + } + ]) .config([ - '$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(false); } + '$compileProvider', + function($compileProvider) { $compileProvider.debugInfoEnabled(false); } ]) .run([ '$rootScope', @@ -94,7 +94,6 @@ class TreeNode { function buildTree(maxDepth, values, curDepth) { if (maxDepth === curDepth) return new TreeNode('', null, null); - return new TreeNode( - values[curDepth], buildTree(maxDepth, values, curDepth + 1), - buildTree(maxDepth, values, curDepth + 1)); + return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1), + buildTree(maxDepth, values, curDepth + 1)); } diff --git a/modules/benchpress/src/common_options.ts b/modules/benchpress/src/common_options.ts index a74c377aaf..857240c387 100644 --- a/modules/benchpress/src/common_options.ts +++ b/modules/benchpress/src/common_options.ts @@ -49,9 +49,14 @@ var _REQUEST_COUNT = new OpaqueToken('Options.requestCount'); var _CAPTURE_FRAMES = new OpaqueToken('Options.frameCapture'); var _DEFAULT_PROVIDERS = [ - bind(_DEFAULT_DESCRIPTION).toValue({}), provide(_SAMPLE_DESCRIPTION, {useValue: {}}), - provide(_FORCE_GC, {useValue: false}), provide(_PREPARE, {useValue: false}), - provide(_MICRO_METRICS, {useValue: {}}), provide(_NOW, {useValue: () => DateWrapper.now()}), - provide(_RECEIVED_DATA, {useValue: false}), provide(_REQUEST_COUNT, {useValue: false}), + bind(_DEFAULT_DESCRIPTION) + .toValue({}), + provide(_SAMPLE_DESCRIPTION, {useValue: {}}), + provide(_FORCE_GC, {useValue: false}), + provide(_PREPARE, {useValue: false}), + provide(_MICRO_METRICS, {useValue: {}}), + provide(_NOW, {useValue: () => DateWrapper.now()}), + provide(_RECEIVED_DATA, {useValue: false}), + provide(_REQUEST_COUNT, {useValue: false}), provide(_CAPTURE_FRAMES, {useValue: false}) ]; diff --git a/modules/benchpress/src/firefox_extension/data/installed_script.ts b/modules/benchpress/src/firefox_extension/data/installed_script.ts index 8d3281c7d3..4a33c2cfd1 100644 --- a/modules/benchpress/src/firefox_extension/data/installed_script.ts +++ b/modules/benchpress/src/firefox_extension/data/installed_script.ts @@ -4,27 +4,25 @@ declare var unsafeWindow; exportFunction(function() { var curTime = unsafeWindow.performance.now(); (<any>self).port.emit('startProfiler', curTime); -}, unsafeWindow, {defineAs: 'startProfiler'}); +}, unsafeWindow, {defineAs: "startProfiler"}); -exportFunction(function() { - (<any>self).port.emit('stopProfiler'); -}, unsafeWindow, {defineAs: 'stopProfiler'}); +exportFunction(function() { (<any>self).port.emit('stopProfiler'); }, unsafeWindow, + {defineAs: "stopProfiler"}); exportFunction(function(cb) { (<any>self).port.once('perfProfile', cb); (<any>self).port.emit('getProfile'); -}, unsafeWindow, {defineAs: 'getProfile'}); +}, unsafeWindow, {defineAs: "getProfile"}); -exportFunction(function() { - (<any>self).port.emit('forceGC'); -}, unsafeWindow, {defineAs: 'forceGC'}); +exportFunction(function() { (<any>self).port.emit('forceGC'); }, unsafeWindow, + {defineAs: "forceGC"}); exportFunction(function(name) { var curTime = unsafeWindow.performance.now(); (<any>self).port.emit('markStart', name, curTime); -}, unsafeWindow, {defineAs: 'markStart'}); +}, unsafeWindow, {defineAs: "markStart"}); exportFunction(function(name) { var curTime = unsafeWindow.performance.now(); (<any>self).port.emit('markEnd', name, curTime); -}, unsafeWindow, {defineAs: 'markEnd'}); +}, unsafeWindow, {defineAs: "markEnd"}); diff --git a/modules/benchpress/src/firefox_extension/lib/main.ts b/modules/benchpress/src/firefox_extension/lib/main.ts index 5c6d76cd8a..b56dde8f23 100644 --- a/modules/benchpress/src/firefox_extension/lib/main.ts +++ b/modules/benchpress/src/firefox_extension/lib/main.ts @@ -53,13 +53,12 @@ mod.PageMod({ include: ['*'], contentScriptFile: data.url('installed_script.js'), onAttach: worker => { - worker.port.on( - 'startProfiler', - (timeStarted) => profiler.start( - /* = profiler memory */ 3000000, 0.1, ['leaf', 'js', 'stackwalk', 'gc'], timeStarted)); + worker.port.on('startProfiler', + (timeStarted) => profiler.start(/* = profiler memory */ 3000000, 0.1, + ['leaf', 'js', 'stackwalk', 'gc'], timeStarted)); worker.port.on('stopProfiler', () => profiler.stop()); - worker.port.on( - 'getProfile', () => worker.port.emit('perfProfile', profiler.getProfilePerfEvents())); + worker.port.on('getProfile', + () => worker.port.emit('perfProfile', profiler.getProfilePerfEvents())); worker.port.on('forceGC', forceGC); worker.port.on('markStart', (name, timeStarted) => profiler.addStartEvent(name, timeStarted)); worker.port.on('markEnd', (name, timeEnded) => profiler.addEndEvent(name, timeEnded)); diff --git a/modules/benchpress/src/firefox_extension/lib/test_helper.ts b/modules/benchpress/src/firefox_extension/lib/test_helper.ts index c3dab528a8..b1bb5ff7e5 100644 --- a/modules/benchpress/src/firefox_extension/lib/test_helper.ts +++ b/modules/benchpress/src/firefox_extension/lib/test_helper.ts @@ -36,8 +36,9 @@ exports.getFirefoxProfileWithExtension = function() { var savedCwd = process.cwd(); process.chdir(absPackageJsonDir); - return jpm(packageJson).then(xpiPath => { - process.chdir(savedCwd); - return exports.getFirefoxProfile(xpiPath); - }); + return jpm(packageJson) + .then(xpiPath => { + process.chdir(savedCwd); + return exports.getFirefoxProfile(xpiPath); + }); }; diff --git a/modules/benchpress/src/measure_values.ts b/modules/benchpress/src/measure_values.ts index d0e4f3e793..0aaf7f582b 100644 --- a/modules/benchpress/src/measure_values.ts +++ b/modules/benchpress/src/measure_values.ts @@ -2,8 +2,8 @@ import {Date, DateWrapper} from 'angular2/src/facade/lang'; import {Map} from 'angular2/src/facade/collection'; export class MeasureValues { - constructor( - public runIndex: number, public timeStamp: Date, public values: {[key: string]: any}) {} + constructor(public runIndex: number, public timeStamp: Date, + public values: {[key: string]: any}) {} toJson() { return { diff --git a/modules/benchpress/src/metric/multi_metric.ts b/modules/benchpress/src/metric/multi_metric.ts index 693a4d440d..384f48249a 100644 --- a/modules/benchpress/src/metric/multi_metric.ts +++ b/modules/benchpress/src/metric/multi_metric.ts @@ -7,8 +7,9 @@ import {Metric} from '../metric'; export class MultiMetric extends Metric { static createBindings(childTokens: any[]): Provider[] { return [ - bind(_CHILDREN).toFactory( - (injector: Injector) => childTokens.map(token => injector.get(token)), [Injector]), + bind(_CHILDREN) + .toFactory((injector: Injector) => childTokens.map(token => injector.get(token)), + [Injector]), bind(MultiMetric).toFactory(children => new MultiMetric(children), [_CHILDREN]) ]; } @@ -41,7 +42,7 @@ export class MultiMetric extends Metric { } } -function mergeStringMaps(maps: {[key: string]: string}[]): Object { +function mergeStringMaps(maps: { [key: string]: string }[]): Object { var result = {}; maps.forEach( map => { StringMapWrapper.forEach(map, (value, prop) => { result[prop] = value; }); }); diff --git a/modules/benchpress/src/metric/perflog_metric.ts b/modules/benchpress/src/metric/perflog_metric.ts index fdd1b377ce..9ba4895d65 100644 --- a/modules/benchpress/src/metric/perflog_metric.ts +++ b/modules/benchpress/src/metric/perflog_metric.ts @@ -1,5 +1,12 @@ import {PromiseWrapper, TimerWrapper} from 'angular2/src/facade/async'; -import {isPresent, isBlank, StringWrapper, Math, RegExpWrapper, NumberWrapper} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + StringWrapper, + Math, + RegExpWrapper, + NumberWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {bind, provide, Provider, OpaqueToken} from 'angular2/src/core/di'; @@ -27,11 +34,10 @@ export class PerflogMetric extends Metric { * @param setTimeout * @param microMetrics Name and description of metrics provided via console.time / console.timeEnd **/ - constructor( - private _driverExtension: WebDriverExtension, private _setTimeout: Function, - private _microMetrics: {[key: string]: any}, private _forceGc: boolean, - private _captureFrames: boolean, private _receivedData: boolean, - private _requestCount: boolean) { + constructor(private _driverExtension: WebDriverExtension, private _setTimeout: Function, + private _microMetrics: {[key: string]: any}, private _forceGc: boolean, + private _captureFrames: boolean, private _receivedData: boolean, + private _requestCount: boolean) { super(); this._remainingEvents = []; @@ -82,8 +88,8 @@ export class PerflogMetric extends Metric { res['frameTime.smooth'] = 'percentage of frames that hit 60fps'; } } - StringMapWrapper.forEach( - this._microMetrics, (desc, name) => { StringMapWrapper.set(res, name, desc); }); + StringMapWrapper.forEach(this._microMetrics, + (desc, name) => { StringMapWrapper.set(res, name, desc); }); return res; } @@ -142,13 +148,13 @@ export class PerflogMetric extends Metric { return result; } var completer = PromiseWrapper.completer(); - this._setTimeout( - () => completer.resolve(this._readUntilEndMark(markName, loopCount + 1)), 100); + this._setTimeout(() => completer.resolve(this._readUntilEndMark(markName, loopCount + 1)), + 100); return completer.promise; }); } - _addEvents(events: {[key: string]: string}[]) { + _addEvents(events: { [key: string]: string }[]) { var needSort = false; events.forEach(event => { if (StringWrapper.equals(event['ph'], 'X')) { @@ -256,8 +262,8 @@ export class PerflogMetric extends Metric { 'found start event for frame capture, but frame capture was not requested in benchpress') } frameCaptureStartEvent = event; - } else if ( - StringWrapper.equals(ph, 'e') && StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) { + } else if (StringWrapper.equals(ph, 'e') && + StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) { if (isBlank(frameCaptureStartEvent)) { throw new BaseException('missing start event for frame capture'); } @@ -269,9 +275,8 @@ export class PerflogMetric extends Metric { StringWrapper.equals(name, 'frame')) { frameTimestamps.push(event['ts']); if (frameTimestamps.length >= 2) { - frameTimes.push( - frameTimestamps[frameTimestamps.length - 1] - - frameTimestamps[frameTimestamps.length - 2]); + frameTimes.push(frameTimestamps[frameTimestamps.length - 1] - + frameTimestamps[frameTimestamps.length - 2]); } } } @@ -283,9 +288,8 @@ export class PerflogMetric extends Metric { } else { intervalStartCount[name]++; } - } else if ( - (StringWrapper.equals(ph, 'E') || StringWrapper.equals(ph, 'e')) && - isPresent(intervalStarts[name])) { + } else if ((StringWrapper.equals(ph, 'E') || StringWrapper.equals(ph, 'e')) && + isPresent(intervalStarts[name])) { intervalStartCount[name]--; if (intervalStartCount[name] === 0) { var startEvent = intervalStarts[name]; @@ -363,13 +367,16 @@ var _PROVIDERS = [ bind(PerflogMetric) .toFactory( (driverExtension, setTimeout, microMetrics, forceGc, captureFrames, receivedData, - requestCount) => - new PerflogMetric( - driverExtension, setTimeout, microMetrics, forceGc, captureFrames, receivedData, - requestCount), + requestCount) => new PerflogMetric(driverExtension, setTimeout, microMetrics, forceGc, + captureFrames, receivedData, requestCount), [ - WebDriverExtension, _SET_TIMEOUT, Options.MICRO_METRICS, Options.FORCE_GC, - Options.CAPTURE_FRAMES, Options.RECEIVED_DATA, Options.REQUEST_COUNT + WebDriverExtension, + _SET_TIMEOUT, + Options.MICRO_METRICS, + Options.FORCE_GC, + Options.CAPTURE_FRAMES, + Options.RECEIVED_DATA, + Options.REQUEST_COUNT ]), provide(_SET_TIMEOUT, {useValue: (fn, millis) => TimerWrapper.setTimeout(fn, millis)}) ]; diff --git a/modules/benchpress/src/reporter/console_reporter.ts b/modules/benchpress/src/reporter/console_reporter.ts index 2d8e489a7f..0f92fdd762 100644 --- a/modules/benchpress/src/reporter/console_reporter.ts +++ b/modules/benchpress/src/reporter/console_reporter.ts @@ -75,13 +75,12 @@ export class ConsoleReporter extends Reporter { var samples = validSamples.map(measureValues => measureValues.values[metricName]); var mean = Statistic.calculateMean(samples); var cv = Statistic.calculateCoefficientOfVariation(samples, mean); - var formattedMean = ConsoleReporter - ._formatNum(mean) - // Note: Don't use the unicode character for +- as it might cause - // hickups for consoles... - return NumberWrapper.isNaN(cv) ? - formattedMean : - `${formattedMean}+-${Math.floor(cv)}%`; + var formattedMean = ConsoleReporter._formatNum(mean) + // Note: Don't use the unicode character for +- as it might cause + // hickups for consoles... + return NumberWrapper.isNaN(cv) ? + formattedMean : + `${formattedMean}+-${Math.floor(cv)}%`; })); return PromiseWrapper.resolve(null); } @@ -96,9 +95,9 @@ var _PRINT = new OpaqueToken('ConsoleReporter.print'); var _COLUMN_WIDTH = new OpaqueToken('ConsoleReporter.columnWidth'); var _PROVIDERS = [ bind(ConsoleReporter) - .toFactory( - (columnWidth, sampleDescription, print) => - new ConsoleReporter(columnWidth, sampleDescription, print), - [_COLUMN_WIDTH, SampleDescription, _PRINT]), - provide(_COLUMN_WIDTH, {useValue: 18}), provide(_PRINT, {useValue: print}) + .toFactory((columnWidth, sampleDescription, print) => + new ConsoleReporter(columnWidth, sampleDescription, print), + [_COLUMN_WIDTH, SampleDescription, _PRINT]), + provide(_COLUMN_WIDTH, {useValue: 18}), + provide(_PRINT, {useValue: print}) ]; diff --git a/modules/benchpress/src/reporter/json_file_reporter.ts b/modules/benchpress/src/reporter/json_file_reporter.ts index 74c14554ba..736123397a 100644 --- a/modules/benchpress/src/reporter/json_file_reporter.ts +++ b/modules/benchpress/src/reporter/json_file_reporter.ts @@ -49,9 +49,8 @@ export class JsonFileReporter extends Reporter { var _PATH = new OpaqueToken('JsonFileReporter.path'); var _PROVIDERS = [ bind(JsonFileReporter) - .toFactory( - (sampleDescription, path, writeFile, now) => - new JsonFileReporter(sampleDescription, path, writeFile, now), - [SampleDescription, _PATH, Options.WRITE_FILE, Options.NOW]), + .toFactory((sampleDescription, path, writeFile, now) => + new JsonFileReporter(sampleDescription, path, writeFile, now), + [SampleDescription, _PATH, Options.WRITE_FILE, Options.NOW]), provide(_PATH, {useValue: '.'}) ]; diff --git a/modules/benchpress/src/reporter/multi_reporter.ts b/modules/benchpress/src/reporter/multi_reporter.ts index f959e411e1..d365820fae 100644 --- a/modules/benchpress/src/reporter/multi_reporter.ts +++ b/modules/benchpress/src/reporter/multi_reporter.ts @@ -7,8 +7,9 @@ import {Reporter} from '../reporter'; export class MultiReporter extends Reporter { static createBindings(childTokens: any[]): Provider[] { return [ - bind(_CHILDREN).toFactory( - (injector: Injector) => childTokens.map(token => injector.get(token)), [Injector]), + bind(_CHILDREN) + .toFactory((injector: Injector) => childTokens.map(token => injector.get(token)), + [Injector]), bind(MultiReporter).toFactory(children => new MultiReporter(children), [_CHILDREN]) ]; } diff --git a/modules/benchpress/src/runner.ts b/modules/benchpress/src/runner.ts index ac5331a90f..9c0d00ada1 100644 --- a/modules/benchpress/src/runner.ts +++ b/modules/benchpress/src/runner.ts @@ -37,7 +37,9 @@ export class Runner { {id: string, execute?: any, prepare?: any, microMetrics?: any, bindings?: any}): Promise<SampleState> { var sampleBindings = [ - _DEFAULT_PROVIDERS, this._defaultBindings, bind(Options.SAMPLE_ID).toValue(id), + _DEFAULT_PROVIDERS, + this._defaultBindings, + bind(Options.SAMPLE_ID).toValue(id), bind(Options.EXECUTE).toValue(execute) ]; if (isPresent(prepare)) { @@ -65,7 +67,8 @@ export class Runner { // TODO vsavkin consider changing it when toAsyncFactory is added back or when child // injectors are handled better. var injector = Injector.resolveAndCreate([ - sampleBindings, bind(Options.CAPABILITIES).toValue(capabilities), + sampleBindings, + bind(Options.CAPABILITIES).toValue(capabilities), bind(Options.USER_AGENT).toValue(userAgent), provide(WebDriverAdapter, {useValue: adapter}) ]); diff --git a/modules/benchpress/src/sample_description.ts b/modules/benchpress/src/sample_description.ts index cc5c9e89aa..4b2af6478c 100644 --- a/modules/benchpress/src/sample_description.ts +++ b/modules/benchpress/src/sample_description.ts @@ -12,9 +12,8 @@ export class SampleDescription { static get BINDINGS(): Provider[] { return _PROVIDERS; } description: {[key: string]: any}; - constructor( - public id: string, descriptions: Array<{[key: string]: any}>, - public metrics: {[key: string]: any}) { + constructor(public id: string, descriptions: Array<{[key: string]: any}>, + public metrics: {[key: string]: any}) { this.description = {}; descriptions.forEach(description => { StringMapWrapper.forEach(description, (value, prop) => this.description[prop] = value); @@ -24,17 +23,24 @@ export class SampleDescription { toJson() { return {'id': this.id, 'description': this.description, 'metrics': this.metrics}; } } -var _PROVIDERS = [bind(SampleDescription) - .toFactory( - (metric, id, forceGc, userAgent, validator, defaultDesc, userDesc) => - new SampleDescription( - id, - [ - {'forceGc': forceGc, 'userAgent': userAgent}, - validator.describe(), defaultDesc, userDesc - ], - metric.describe()), - [ - Metric, Options.SAMPLE_ID, Options.FORCE_GC, Options.USER_AGENT, - Validator, Options.DEFAULT_DESCRIPTION, Options.SAMPLE_DESCRIPTION - ])]; +var _PROVIDERS = [ + bind(SampleDescription) + .toFactory((metric, id, forceGc, userAgent, validator, defaultDesc, userDesc) => + new SampleDescription(id, + [ + {'forceGc': forceGc, 'userAgent': userAgent}, + validator.describe(), + defaultDesc, + userDesc + ], + metric.describe()), + [ + Metric, + Options.SAMPLE_ID, + Options.FORCE_GC, + Options.USER_AGENT, + Validator, + Options.DEFAULT_DESCRIPTION, + Options.SAMPLE_DESCRIPTION + ]) +]; diff --git a/modules/benchpress/src/sampler.ts b/modules/benchpress/src/sampler.ts index 272275e8dc..e7cec72f21 100644 --- a/modules/benchpress/src/sampler.ts +++ b/modules/benchpress/src/sampler.ts @@ -94,19 +94,27 @@ export class SampleState { constructor(public completeSample: any[], public validSample: any[]) {} } -var _PROVIDERS = [bind(Sampler).toFactory( - (driver, metric, reporter, validator, prepare, execute, now) => new Sampler({ - driver: driver, - reporter: reporter, - validator: validator, - metric: metric, - // TODO(tbosch): DI right now does not support null/undefined objects - // Mostly because the cache would have to be initialized with a - // special null object, which is expensive. - prepare: prepare !== false ? prepare : null, - execute: execute, - now: now - }), - [ - WebDriverAdapter, Metric, Reporter, Validator, Options.PREPARE, Options.EXECUTE, Options.NOW - ])]; +var _PROVIDERS = [ + bind(Sampler) + .toFactory((driver, metric, reporter, validator, prepare, execute, now) => new Sampler({ + driver: driver, + reporter: reporter, + validator: validator, + metric: metric, + // TODO(tbosch): DI right now does not support null/undefined objects + // Mostly because the cache would have to be initialized with a + // special null object, which is expensive. + prepare: prepare !== false ? prepare : null, + execute: execute, + now: now + }), + [ + WebDriverAdapter, + Metric, + Reporter, + Validator, + Options.PREPARE, + Options.EXECUTE, + Options.NOW + ]) +]; diff --git a/modules/benchpress/src/statistic.ts b/modules/benchpress/src/statistic.ts index 69ebbf0a42..95f3267213 100644 --- a/modules/benchpress/src/statistic.ts +++ b/modules/benchpress/src/statistic.ts @@ -21,8 +21,8 @@ export class Statistic { return deviation; } - static calculateRegressionSlope( - xValues: number[], xMean: number, yValues: number[], yMean: number) { + static calculateRegressionSlope(xValues: number[], xMean: number, yValues: number[], + yMean: number) { // See http://en.wikipedia.org/wiki/Simple_linear_regression var dividendSum = 0; var divisorSum = 0; diff --git a/modules/benchpress/src/validator/regression_slope_validator.ts b/modules/benchpress/src/validator/regression_slope_validator.ts index 5577774a73..0fcd18913c 100644 --- a/modules/benchpress/src/validator/regression_slope_validator.ts +++ b/modules/benchpress/src/validator/regression_slope_validator.ts @@ -32,8 +32,8 @@ export class RegressionSlopeValidator extends Validator { validate(completeSample: MeasureValues[]): MeasureValues[] { if (completeSample.length >= this._sampleSize) { - var latestSample = ListWrapper.slice( - completeSample, completeSample.length - this._sampleSize, completeSample.length); + var latestSample = ListWrapper.slice(completeSample, completeSample.length - this._sampleSize, + completeSample.length); var xValues = []; var yValues = []; for (var i = 0; i < latestSample.length; i++) { @@ -55,8 +55,8 @@ var _SAMPLE_SIZE = new OpaqueToken('RegressionSlopeValidator.sampleSize'); var _METRIC = new OpaqueToken('RegressionSlopeValidator.metric'); var _PROVIDERS = [ bind(RegressionSlopeValidator) - .toFactory( - (sampleSize, metric) => new RegressionSlopeValidator(sampleSize, metric), - [_SAMPLE_SIZE, _METRIC]), - provide(_SAMPLE_SIZE, {useValue: 10}), provide(_METRIC, {useValue: 'scriptTime'}) + .toFactory((sampleSize, metric) => new RegressionSlopeValidator(sampleSize, metric), + [_SAMPLE_SIZE, _METRIC]), + provide(_SAMPLE_SIZE, {useValue: 10}), + provide(_METRIC, {useValue: 'scriptTime'}) ]; diff --git a/modules/benchpress/src/validator/size_validator.ts b/modules/benchpress/src/validator/size_validator.ts index bb304b89ac..d6ba3d037a 100644 --- a/modules/benchpress/src/validator/size_validator.ts +++ b/modules/benchpress/src/validator/size_validator.ts @@ -24,8 +24,8 @@ export class SizeValidator extends Validator { validate(completeSample: MeasureValues[]): MeasureValues[] { if (completeSample.length >= this._sampleSize) { - return ListWrapper.slice( - completeSample, completeSample.length - this._sampleSize, completeSample.length); + return ListWrapper.slice(completeSample, completeSample.length - this._sampleSize, + completeSample.length); } else { return null; } @@ -34,6 +34,7 @@ export class SizeValidator extends Validator { var _SAMPLE_SIZE = new OpaqueToken('SizeValidator.sampleSize'); var _PROVIDERS = [ - bind(SizeValidator).toFactory((size) => new SizeValidator(size), [_SAMPLE_SIZE]), + bind(SizeValidator) + .toFactory((size) => new SizeValidator(size), [_SAMPLE_SIZE]), provide(_SAMPLE_SIZE, {useValue: 10}) ]; diff --git a/modules/benchpress/src/web_driver_extension.ts b/modules/benchpress/src/web_driver_extension.ts index 6af9b2bb0e..53b9ba3927 100644 --- a/modules/benchpress/src/web_driver_extension.ts +++ b/modules/benchpress/src/web_driver_extension.ts @@ -13,8 +13,9 @@ import {Options} from './common_options'; export abstract class WebDriverExtension { static bindTo(childTokens: any[]): Provider[] { var res = [ - bind(_CHILDREN).toFactory( - (injector: Injector) => childTokens.map(token => injector.get(token)), [Injector]), + bind(_CHILDREN) + .toFactory((injector: Injector) => childTokens.map(token => injector.get(token)), + [Injector]), bind(WebDriverExtension) .toFactory( (children: WebDriverExtension[], capabilities) => { diff --git a/modules/benchpress/src/webdriver/chrome_driver_extension.ts b/modules/benchpress/src/webdriver/chrome_driver_extension.ts index 4a524d0869..b91c1d39e9 100644 --- a/modules/benchpress/src/webdriver/chrome_driver_extension.ts +++ b/modules/benchpress/src/webdriver/chrome_driver_extension.ts @@ -1,6 +1,13 @@ import {bind, provide, Provider} from 'angular2/src/core/di'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {Json, isPresent, isBlank, RegExpWrapper, StringWrapper, NumberWrapper} from 'angular2/src/facade/lang'; +import { + Json, + isPresent, + isBlank, + RegExpWrapper, + StringWrapper, + NumberWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {WebDriverExtension, PerfLogFeatures} from '../web_driver_extension'; @@ -76,9 +83,8 @@ export class ChromeDriverExtension extends WebDriverExtension { }); } - private _convertPerfRecordsToEvents( - chromeEvents: Array<{[key: string]: any}>, - normalizedEvents: Array<{[key: string]: any}> = null) { + private _convertPerfRecordsToEvents(chromeEvents: Array<{[key: string]: any}>, + normalizedEvents: Array<{[key: string]: any}> = null) { if (isBlank(normalizedEvents)) { normalizedEvents = []; } @@ -88,9 +94,8 @@ export class ChromeDriverExtension extends WebDriverExtension { var name = event['name']; if (this._isEvent(categories, name, ['blink.console'])) { normalizedEvents.push(normalizeEvent(event, {'name': name})); - } else if (this._isEvent( - categories, name, ['benchmark'], - 'BenchmarkInstrumentation::ImplThreadRenderingStats')) { + } else if (this._isEvent(categories, name, ['benchmark'], + 'BenchmarkInstrumentation::ImplThreadRenderingStats')) { // TODO(goderbauer): Instead of BenchmarkInstrumentation::ImplThreadRenderingStats the // following events should be used (if available) for more accurate measurments: // 1st choice: vsync_before - ground truth on Android @@ -105,10 +110,10 @@ export class ChromeDriverExtension extends WebDriverExtension { if (frameCount == 1) { normalizedEvents.push(normalizeEvent(event, {'name': 'frame'})); } - } else if ( - this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Rasterize') || - this._isEvent( - categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers')) { + } else if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'Rasterize') || + this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'CompositeLayers')) { normalizedEvents.push(normalizeEvent(event, {'name': 'render'})); } else if (this._majorChromeVersion < 45) { var normalizedEvent = this._processAsPreChrome45Event(event, categories, majorGCPids); @@ -126,21 +131,22 @@ export class ChromeDriverExtension extends WebDriverExtension { var args = event['args']; var pid = event['pid']; var ph = event['ph']; - if (this._isEvent( - categories, name, ['disabled-by-default-devtools.timeline'], 'FunctionCall') && + if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'FunctionCall') && (isBlank(args) || isBlank(args['data']) || !StringWrapper.equals(args['data']['scriptName'], 'InjectedScript'))) { return normalizeEvent(event, {'name': 'script'}); - } else if ( - this._isEvent( - categories, name, ['disabled-by-default-devtools.timeline'], 'RecalculateStyles') || - this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Layout') || - this._isEvent( - categories, name, ['disabled-by-default-devtools.timeline'], 'UpdateLayerTree') || - this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Paint')) { + } else if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'RecalculateStyles') || + this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'Layout') || + this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'UpdateLayerTree') || + this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'Paint')) { return normalizeEvent(event, {'name': 'render'}); - } else if (this._isEvent( - categories, name, ['disabled-by-default-devtools.timeline'], 'GCEvent')) { + } else if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], + 'GCEvent')) { var normArgs = { 'usedHeapSize': isPresent(args['usedHeapSizeAfter']) ? args['usedHeapSizeAfter'] : args['usedHeapSizeBefore'] @@ -150,8 +156,8 @@ export class ChromeDriverExtension extends WebDriverExtension { } majorGCPids[pid] = false; return normalizeEvent(event, {'name': 'gc', 'args': normArgs}); - } else if ( - this._isEvent(categories, name, ['v8'], 'majorGC') && StringWrapper.equals(ph, 'B')) { + } else if (this._isEvent(categories, name, ['v8'], 'majorGC') && + StringWrapper.equals(ph, 'B')) { majorGCPids[pid] = true; } return null; // nothing useful in this event @@ -174,19 +180,17 @@ export class ChromeDriverExtension extends WebDriverExtension { args['usedHeapSizeBefore'] }; return normalizeEvent(event, {'name': 'gc', 'args': normArgs}); - } else if ( - this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'FunctionCall') && - (isBlank(args) || isBlank(args['data']) || - (!StringWrapper.equals(args['data']['scriptName'], 'InjectedScript') && - !StringWrapper.equals(args['data']['scriptName'], '')))) { + } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'FunctionCall') && + (isBlank(args) || isBlank(args['data']) || + (!StringWrapper.equals(args['data']['scriptName'], 'InjectedScript') && + !StringWrapper.equals(args['data']['scriptName'], '')))) { return normalizeEvent(event, {'name': 'script'}); - } else if (this._isEvent( - categories, name, ['devtools.timeline', 'blink'], 'UpdateLayoutTree')) { + } else if (this._isEvent(categories, name, ['devtools.timeline', 'blink'], + 'UpdateLayoutTree')) { return normalizeEvent(event, {'name': 'render'}); - } else if ( - this._isEvent(categories, name, ['devtools.timeline'], 'UpdateLayerTree') || - this._isEvent(categories, name, ['devtools.timeline'], 'Layout') || - this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) { + } else if (this._isEvent(categories, name, ['devtools.timeline'], 'UpdateLayerTree') || + this._isEvent(categories, name, ['devtools.timeline'], 'Layout') || + this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) { return normalizeEvent(event, {'name': 'render'}); } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) { let normArgs = {'encodedDataLength': args['data']['encodedDataLength']}; @@ -203,9 +207,8 @@ export class ChromeDriverExtension extends WebDriverExtension { private _parseCategories(categories: string): string[] { return categories.split(','); } - private _isEvent( - eventCategories: string[], eventName: string, expectedCategories: string[], - expectedName: string = null): boolean { + private _isEvent(eventCategories: string[], eventName: string, expectedCategories: string[], + expectedName: string = null): boolean { var hasCategories = expectedCategories.reduce( (value, cat) => { return value && ListWrapper.contains(eventCategories, cat); }, true); return isBlank(expectedName) ? hasCategories : @@ -218,12 +221,12 @@ export class ChromeDriverExtension extends WebDriverExtension { supports(capabilities: {[key: string]: any}): boolean { return this._majorChromeVersion != -1 && - StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'chrome'); + StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'chrome'); } } -function normalizeEvent( - chromeEvent: {[key: string]: any}, data: {[key: string]: any}): {[key: string]: any} { +function normalizeEvent(chromeEvent: {[key: string]: any}, + data: {[key: string]: any}): {[key: string]: any} { var ph = chromeEvent['ph']; if (StringWrapper.equals(ph, 'S')) { ph = 'b'; @@ -243,7 +246,8 @@ function normalizeEvent( return result; } -var _PROVIDERS = [bind(ChromeDriverExtension) - .toFactory( - (driver, userAgent) => new ChromeDriverExtension(driver, userAgent), - [WebDriverAdapter, Options.USER_AGENT])]; +var _PROVIDERS = [ + bind(ChromeDriverExtension) + .toFactory((driver, userAgent) => new ChromeDriverExtension(driver, userAgent), + [WebDriverAdapter, Options.USER_AGENT]) +]; diff --git a/modules/benchpress/src/webdriver/firefox_driver_extension.ts b/modules/benchpress/src/webdriver/firefox_driver_extension.ts index afe0688e42..203fc5ef70 100644 --- a/modules/benchpress/src/webdriver/firefox_driver_extension.ts +++ b/modules/benchpress/src/webdriver/firefox_driver_extension.ts @@ -42,7 +42,7 @@ export class FirefoxDriverExtension extends WebDriverExtension { } } -var _PROVIDERS = - [bind(FirefoxDriverExtension).toFactory((driver) => new FirefoxDriverExtension(driver), [ - WebDriverAdapter - ])]; +var _PROVIDERS = [ + bind(FirefoxDriverExtension) + .toFactory((driver) => new FirefoxDriverExtension(driver), [WebDriverAdapter]) +]; diff --git a/modules/benchpress/src/webdriver/ios_driver_extension.ts b/modules/benchpress/src/webdriver/ios_driver_extension.ts index ca115ad149..f423e4442d 100644 --- a/modules/benchpress/src/webdriver/ios_driver_extension.ts +++ b/modules/benchpress/src/webdriver/ios_driver_extension.ts @@ -62,11 +62,11 @@ export class IOsDriverExtension extends WebDriverExtension { events.push(createMarkStartEvent(data['message'], startTime)); } else if (StringWrapper.equals(type, 'TimeEnd')) { events.push(createMarkEndEvent(data['message'], startTime)); - } else if ( - StringWrapper.equals(type, 'RecalculateStyles') || StringWrapper.equals(type, 'Layout') || - StringWrapper.equals(type, 'UpdateLayerTree') || StringWrapper.equals(type, 'Paint') || - StringWrapper.equals(type, 'Rasterize') || - StringWrapper.equals(type, 'CompositeLayers')) { + } else if (StringWrapper.equals(type, 'RecalculateStyles') || + StringWrapper.equals(type, 'Layout') || + StringWrapper.equals(type, 'UpdateLayerTree') || + StringWrapper.equals(type, 'Paint') || StringWrapper.equals(type, 'Rasterize') || + StringWrapper.equals(type, 'CompositeLayers')) { events.push(createStartEvent('render', startTime)); endEvent = createEndEvent('render', endTime); } @@ -121,5 +121,6 @@ function createMarkEndEvent(name, time) { } var _PROVIDERS = [ - bind(IOsDriverExtension).toFactory((driver) => new IOsDriverExtension(driver), [WebDriverAdapter]) + bind(IOsDriverExtension) + .toFactory((driver) => new IOsDriverExtension(driver), [WebDriverAdapter]) ]; diff --git a/modules/benchpress/src/webdriver/selenium_webdriver_adapter.ts b/modules/benchpress/src/webdriver/selenium_webdriver_adapter.ts index 5e6630d06c..afe20a4c73 100644 --- a/modules/benchpress/src/webdriver/selenium_webdriver_adapter.ts +++ b/modules/benchpress/src/webdriver/selenium_webdriver_adapter.ts @@ -57,5 +57,6 @@ function convertToLocalProcess(data): Object { } var _PROTRACTOR_BINDINGS = [ - bind(WebDriverAdapter).toFactory(() => new SeleniumWebDriverAdapter((<any>global).browser), []) + bind(WebDriverAdapter) + .toFactory(() => new SeleniumWebDriverAdapter((<any>global).browser), []) ]; diff --git a/modules/benchpress/test/firefox_extension/parser_util_spec.ts b/modules/benchpress/test/firefox_extension/parser_util_spec.ts index a37cf6cc83..fccd1d842c 100644 --- a/modules/benchpress/test/firefox_extension/parser_util_spec.ts +++ b/modules/benchpress/test/firefox_extension/parser_util_spec.ts @@ -25,48 +25,56 @@ export function main() { it('should convert single non-instantaneous event', function() { var profileData = { - threads: [{ - samples: [ - {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, - {time: 2, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, - {time: 100, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]} - ] - }] + threads: [ + { + samples: [ + {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, + {time: 2, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, + {time: 100, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]} + ] + } + ] }; var perfEvents = convertPerfProfileToEvents(profileData); - assertEventsEqual( - perfEvents, [{ph: 'B', ts: 1, name: 'script'}, {ph: 'E', ts: 100, name: 'script'}]); + assertEventsEqual(perfEvents, + [{ph: 'B', ts: 1, name: 'script'}, {ph: 'E', ts: 100, name: 'script'}]); }); it('should convert multiple instantaneous events', function() { var profileData = { - threads: [{ - samples: [ - {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, - {time: 2, frames: [{location: 'PresShell::Paint'}]} - ] - }] + threads: [ + { + samples: [ + {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, + {time: 2, frames: [{location: 'PresShell::Paint'}]} + ] + } + ] }; var perfEvents = convertPerfProfileToEvents(profileData); - assertEventsEqual( - perfEvents, [{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}]); + assertEventsEqual(perfEvents, + [{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}]); }); it('should convert multiple mixed events', function() { var profileData = { - threads: [{ - samples: [ - {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, - {time: 2, frames: [{location: 'PresShell::Paint'}]}, - {time: 5, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, - {time: 10, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]} - ] - }] + threads: [ + { + samples: [ + {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, + {time: 2, frames: [{location: 'PresShell::Paint'}]}, + {time: 5, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, + {time: 10, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]} + ] + } + ] }; var perfEvents = convertPerfProfileToEvents(profileData); assertEventsEqual(perfEvents, [ - {ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}, - {ph: 'B', ts: 5, name: 'script'}, {ph: 'E', ts: 10, name: 'script'} + {ph: 'X', ts: 1, name: 'script'}, + {ph: 'X', ts: 2, name: 'render'}, + {ph: 'B', ts: 5, name: 'script'}, + {ph: 'E', ts: 10, name: 'script'} ]); }); @@ -78,12 +86,14 @@ export function main() { it('should skip unknown events', function() { var profileData = { - threads: [{ - samples: [ - {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, - {time: 2, frames: [{location: 'foo'}]} - ] - }] + threads: [ + { + samples: [ + {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, + {time: 2, frames: [{location: 'foo'}]} + ] + } + ] }; var perfEvents = convertPerfProfileToEvents(profileData); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]); diff --git a/modules/benchpress/test/firefox_extension/sample_benchmark.ts b/modules/benchpress/test/firefox_extension/sample_benchmark.ts index e999447d79..c3d34df92d 100644 --- a/modules/benchpress/test/firefox_extension/sample_benchmark.ts +++ b/modules/benchpress/test/firefox_extension/sample_benchmark.ts @@ -21,14 +21,12 @@ describe('deep tree baseline', function() { * Benchpress will log the collected metrics after each sample is collected, and will stop * sampling as soon as the calculated regression slope for last 20 samples is stable. */ - runner - .sample({ - id: 'baseline', - execute: function() { - $('button').click(); - }, - bindings: [benchpress.bind(benchpress.Options.SAMPLE_DESCRIPTION).toValue({depth: 9})] - }) + runner.sample({ + id: 'baseline', + execute: function() { $('button') + .click(); }, + bindings: [benchpress.bind(benchpress.Options.SAMPLE_DESCRIPTION).toValue({depth: 9})] + }) .then(done, done.fail); }); }); diff --git a/modules/benchpress/test/firefox_extension/spec.ts b/modules/benchpress/test/firefox_extension/spec.ts index 2e4a6c7459..9b9cf24bc2 100644 --- a/modules/benchpress/test/firefox_extension/spec.ts +++ b/modules/benchpress/test/firefox_extension/spec.ts @@ -21,9 +21,8 @@ describe('firefox extension', function() { browser.driver.get(TEST_URL); - browser.executeScript('window.startProfiler()').then(function() { - console.log('started measuring perf'); - }); + browser.executeScript('window.startProfiler()') + .then(function() { console.log('started measuring perf'); }); browser.executeAsyncScript('setTimeout(arguments[0], 1000);'); browser.executeScript('window.forceGC()'); diff --git a/modules/benchpress/test/metric/multi_metric_spec.ts b/modules/benchpress/test/metric/multi_metric_spec.ts index bc607ac19f..f68ff23bbc 100644 --- a/modules/benchpress/test/metric/multi_metric_spec.ts +++ b/modules/benchpress/test/metric/multi_metric_spec.ts @@ -1,4 +1,15 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {ListWrapper} from 'angular2/src/facade/collection'; import {PromiseWrapper} from 'angular2/src/facade/async'; @@ -7,38 +18,42 @@ import {Metric, MultiMetric, bind, provide, Injector} from 'benchpress/common'; export function main() { function createMetric(ids: any[]) { - var m = Injector - .resolveAndCreate([ - ids.map(id => provide(id, {useValue: new MockMetric(id)})), - MultiMetric.createBindings(ids) - ]) + var m = Injector.resolveAndCreate([ + ids.map(id => provide(id, {useValue: new MockMetric(id)})), + MultiMetric.createBindings(ids) + ]) .get(MultiMetric); return PromiseWrapper.resolve(m); } describe('multi metric', () => { it('should merge descriptions', inject([AsyncTestCompleter], (async) => { - createMetric(['m1', 'm2']).then((m) => { - expect(m.describe()).toEqual({'m1': 'describe', 'm2': 'describe'}); - async.done(); - }); + createMetric(['m1', 'm2']) + .then((m) => { + expect(m.describe()).toEqual({'m1': 'describe', 'm2': 'describe'}); + async.done(); + }); })); it('should merge all beginMeasure calls', inject([AsyncTestCompleter], (async) => { - createMetric(['m1', 'm2']).then((m) => m.beginMeasure()).then((values) => { - expect(values).toEqual(['m1_beginMeasure', 'm2_beginMeasure']); - async.done(); - }); + createMetric(['m1', 'm2']) + .then((m) => m.beginMeasure()) + .then((values) => { + expect(values).toEqual(['m1_beginMeasure', 'm2_beginMeasure']); + async.done(); + }); })); [false, true].forEach((restartFlag) => { it(`should merge all endMeasure calls for restart=${restartFlag}`, inject([AsyncTestCompleter], (async) => { - createMetric(['m1', 'm2']).then((m) => m.endMeasure(restartFlag)).then((values) => { - expect(values).toEqual( - {'m1': {'restart': restartFlag}, 'm2': {'restart': restartFlag}}); - async.done(); - }); + createMetric(['m1', 'm2']) + .then((m) => m.endMeasure(restartFlag)) + .then((values) => { + expect(values) + .toEqual({'m1': {'restart': restartFlag}, 'm2': {'restart': restartFlag}}); + async.done(); + }); })); }); diff --git a/modules/benchpress/test/metric/perflog_metric_spec.ts b/modules/benchpress/test/metric/perflog_metric_spec.ts index 4aa846e553..44fa94a746 100644 --- a/modules/benchpress/test/metric/perflog_metric_spec.ts +++ b/modules/benchpress/test/metric/perflog_metric_spec.ts @@ -1,10 +1,30 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; -import {Metric, PerflogMetric, WebDriverExtension, PerfLogFeatures, bind, provide, Injector, Options} from 'benchpress/common'; +import { + Metric, + PerflogMetric, + WebDriverExtension, + PerfLogFeatures, + bind, + provide, + Injector, + Options +} from 'benchpress/common'; import {TraceEventFactory} from '../trace_event_factory'; @@ -12,15 +32,14 @@ export function main() { var commandLog: any[]; var eventFactory = new TraceEventFactory('timeline', 'pid0'); - function createMetric( - perfLogs, perfLogFeatures, - {microMetrics, forceGc, captureFrames, receivedData, requestCount}: { - microMetrics?: {[key: string]: string}, - forceGc?: boolean, - captureFrames?: boolean, - receivedData?: boolean, - requestCount?: boolean - } = {}): Metric { + function createMetric(perfLogs, perfLogFeatures, + {microMetrics, forceGc, captureFrames, receivedData, requestCount}: { + microMetrics?: {[key: string]: string}, + forceGc?: boolean, + captureFrames?: boolean, + receivedData?: boolean, + requestCount?: boolean + } = {}): Metric { commandLog = []; if (isBlank(perfLogFeatures)) { perfLogFeatures = @@ -30,12 +49,14 @@ export function main() { microMetrics = StringMapWrapper.create(); } var bindings = [ - Options.DEFAULT_PROVIDERS, PerflogMetric.BINDINGS, + Options.DEFAULT_PROVIDERS, + PerflogMetric.BINDINGS, bind(Options.MICRO_METRICS).toValue(microMetrics), - bind(PerflogMetric.SET_TIMEOUT).toValue((fn, millis) => { - commandLog.push(['setTimeout', millis]); - fn(); - }), + bind(PerflogMetric.SET_TIMEOUT) + .toValue((fn, millis) => { + commandLog.push(['setTimeout', millis]); + fn(); + }), bind(WebDriverExtension) .toValue(new MockDriverExtension(perfLogs, commandLog, perfLogFeatures)) ]; @@ -64,31 +85,35 @@ export function main() { } it('should describe itself based on the perfLogFeatrues', () => { - expect(sortedKeys(createMetric([[]], new PerfLogFeatures()).describe())).toEqual([ - 'pureScriptTime', 'scriptTime' - ]); + expect(sortedKeys(createMetric([[]], new PerfLogFeatures()).describe())) + .toEqual(['pureScriptTime', 'scriptTime']); expect( sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: false})).describe())) .toEqual(['pureScriptTime', 'renderTime', 'scriptTime']); - expect(sortedKeys(createMetric([[]], null).describe())).toEqual([ - 'gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', 'renderTime', 'scriptTime' - ]); + expect(sortedKeys(createMetric([[]], null).describe())) + .toEqual( + ['gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', 'renderTime', 'scriptTime']); - expect(sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: true}), { - forceGc: true - }).describe())) + expect(sortedKeys( + createMetric([[]], new PerfLogFeatures({render: true, gc: true}), {forceGc: true}) + .describe())) .toEqual([ - 'forcedGcAmount', 'forcedGcTime', 'gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', - 'renderTime', 'scriptTime' + 'forcedGcAmount', + 'forcedGcTime', + 'gcAmount', + 'gcTime', + 'majorGcTime', + 'pureScriptTime', + 'renderTime', + 'scriptTime' ]); - expect(sortedKeys(createMetric([[]], new PerfLogFeatures({userTiming: true}), { - receivedData: true, - requestCount: true - }).describe())) + expect(sortedKeys(createMetric([[]], new PerfLogFeatures({userTiming: true}), + {receivedData: true, requestCount: true}) + .describe())) .toEqual(['pureScriptTime', 'receivedData', 'requestCount', 'scriptTime']); }); @@ -99,9 +124,9 @@ export function main() { }); it('should describe itself if frame capture is requested and available', () => { - var description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), { - captureFrames: true - }).describe(); + var description = + createMetric([[]], new PerfLogFeatures({frameCapture: true}), {captureFrames: true}) + .describe(); expect(description['frameTime.mean']).not.toContain('WARNING'); expect(description['frameTime.best']).not.toContain('WARNING'); expect(description['frameTime.worst']).not.toContain('WARNING'); @@ -109,9 +134,9 @@ export function main() { }); it('should describe itself if frame capture is requested and not available', () => { - var description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), { - captureFrames: true - }).describe(); + var description = + createMetric([[]], new PerfLogFeatures({frameCapture: false}), {captureFrames: true}) + .describe(); expect(description['frameTime.mean']).toContain('WARNING'); expect(description['frameTime.best']).toContain('WARNING'); expect(description['frameTime.worst']).toContain('WARNING'); @@ -144,19 +169,28 @@ export function main() { it('should mark and aggregate events in between the marks', inject([AsyncTestCompleter], (async) => { - var events = [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), - eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10) - ]]; + var events = [ + [ + eventFactory.markStart('benchpress0', 0), + eventFactory.start('script', 4), + eventFactory.end('script', 6), + eventFactory.markEnd('benchpress0', 10) + ] + ]; var metric = createMetric(events, null); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog' - ]); - expect(data['scriptTime']).toBe(2); + metric.beginMeasure() + .then((_) => metric.endMeasure(false)) + .then((data) => { + expect(commandLog) + .toEqual([ + ['timeBegin', 'benchpress0'], + ['timeEnd', 'benchpress0', null], + 'readPerfLog' + ]); + expect(data['scriptTime']).toBe(2); - async.done(); - }); + async.done(); + }); })); it('should restart timing', inject([AsyncTestCompleter], (async) => { @@ -173,10 +207,14 @@ export function main() { .then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true)) .then((_) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], - 'readPerfLog', ['timeEnd', 'benchpress1', 'benchpress2'], 'readPerfLog' - ]); + expect(commandLog) + .toEqual([ + ['timeBegin', 'benchpress0'], + ['timeEnd', 'benchpress0', 'benchpress1'], + 'readPerfLog', + ['timeEnd', 'benchpress1', 'benchpress2'], + 'readPerfLog' + ]); async.done(); }); @@ -188,32 +226,44 @@ export function main() { [eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)], [eventFactory.end('script', 2)], [ - eventFactory.start('script', 3), eventFactory.end('script', 5), + eventFactory.start('script', 3), + eventFactory.end('script', 5), eventFactory.markEnd('benchpress0', 10) ] ]; var metric = createMetric(events, null); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog', - ['setTimeout', 100], 'readPerfLog', ['setTimeout', 100], 'readPerfLog' - ]); - expect(data['scriptTime']).toBe(3); + metric.beginMeasure() + .then((_) => metric.endMeasure(false)) + .then((data) => { + expect(commandLog) + .toEqual([ + ['timeBegin', 'benchpress0'], + ['timeEnd', 'benchpress0', null], + 'readPerfLog', + ['setTimeout', 100], + 'readPerfLog', + ['setTimeout', 100], + 'readPerfLog' + ]); + expect(data['scriptTime']).toBe(3); - async.done(); - }); + async.done(); + }); })); it('should store events after the end mark for the next call', inject([AsyncTestCompleter], (async) => { var events = [ [ - eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1), - eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1), + eventFactory.markStart('benchpress0', 0), + eventFactory.markEnd('benchpress0', 1), + eventFactory.markStart('benchpress1', 1), + eventFactory.start('script', 1), eventFactory.end('script', 2) ], [ - eventFactory.start('script', 3), eventFactory.end('script', 5), + eventFactory.start('script', 3), + eventFactory.end('script', 5), eventFactory.markEnd('benchpress1', 6) ] ]; @@ -225,10 +275,14 @@ export function main() { return metric.endMeasure(true) }) .then((data) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], - 'readPerfLog', ['timeEnd', 'benchpress1', 'benchpress2'], 'readPerfLog' - ]); + expect(commandLog) + .toEqual([ + ['timeBegin', 'benchpress0'], + ['timeEnd', 'benchpress0', 'benchpress1'], + 'readPerfLog', + ['timeEnd', 'benchpress1', 'benchpress2'], + 'readPerfLog' + ]); expect(data['scriptTime']).toBe(3); async.done(); @@ -238,37 +292,51 @@ export function main() { describe('with forced gc', () => { var events; beforeEach(() => { - events = [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), - eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10), - eventFactory.markStart('benchpress1', 11), - eventFactory.start('gc', 12, {'usedHeapSize': 2500}), - eventFactory.end('gc', 15, {'usedHeapSize': 1000}), - eventFactory.markEnd('benchpress1', 20) - ]]; + events = [ + [ + eventFactory.markStart('benchpress0', 0), + eventFactory.start('script', 4), + eventFactory.end('script', 6), + eventFactory.markEnd('benchpress0', 10), + eventFactory.markStart('benchpress1', 11), + eventFactory.start('gc', 12, {'usedHeapSize': 2500}), + eventFactory.end('gc', 15, {'usedHeapSize': 1000}), + eventFactory.markEnd('benchpress1', 20) + ] + ]; }); it('should measure forced gc', inject([AsyncTestCompleter], (async) => { var metric = createMetric(events, null, {forceGc: true}); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(commandLog).toEqual([ - ['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], - 'readPerfLog', ['gc'], ['timeEnd', 'benchpress1', null], 'readPerfLog' - ]); - expect(data['forcedGcTime']).toBe(3); - expect(data['forcedGcAmount']).toBe(1.5); + metric.beginMeasure() + .then((_) => metric.endMeasure(false)) + .then((data) => { + expect(commandLog) + .toEqual([ + ['gc'], + ['timeBegin', 'benchpress0'], + ['timeEnd', 'benchpress0', 'benchpress1'], + 'readPerfLog', + ['gc'], + ['timeEnd', 'benchpress1', null], + 'readPerfLog' + ]); + expect(data['forcedGcTime']).toBe(3); + expect(data['forcedGcAmount']).toBe(1.5); - async.done(); - }); + async.done(); + }); })); it('should restart after the forced gc if needed', inject([AsyncTestCompleter], (async) => { var metric = createMetric(events, null, {forceGc: true}); - metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => { - expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']); + metric.beginMeasure() + .then((_) => metric.endMeasure(true)) + .then((data) => { + expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']); - async.done(); - }); + async.done(); + }); })); }); @@ -298,8 +366,10 @@ export function main() { it('should calculate mean frame time', inject([AsyncTestCompleter], (async) => { aggregate( [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 3), eventFactory.instant('frame', 4), + eventFactory.markStart('frameCapture', 0), + eventFactory.instant('frame', 1), + eventFactory.instant('frame', 3), + eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5) ], {captureFrames: true}) @@ -315,9 +385,8 @@ export function main() { [eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)], {captureFrames: true}), (err): any => { - expect(() => { - throw err; - }).toThrowError('missing start event for frame capture'); + expect(() => { throw err; }) + .toThrowError('missing start event for frame capture'); async.done(); }); })); @@ -342,9 +411,8 @@ export function main() { ], {captureFrames: true}), (err): any => { - expect(() => { - throw err; - }).toThrowError('can capture frames only once per benchmark run'); + expect(() => { throw err; }) + .toThrowError('can capture frames only once per benchmark run'); async.done(); }); })); @@ -373,10 +441,14 @@ export function main() { it('should calculate best and worst frame time', inject([AsyncTestCompleter], (async) => { aggregate( [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 9), eventFactory.instant('frame', 15), - eventFactory.instant('frame', 18), eventFactory.instant('frame', 28), - eventFactory.instant('frame', 32), eventFactory.markEnd('frameCapture', 10) + eventFactory.markStart('frameCapture', 0), + eventFactory.instant('frame', 1), + eventFactory.instant('frame', 9), + eventFactory.instant('frame', 15), + eventFactory.instant('frame', 18), + eventFactory.instant('frame', 28), + eventFactory.instant('frame', 32), + eventFactory.markEnd('frameCapture', 10) ], {captureFrames: true}) .then((data) => { @@ -390,8 +462,10 @@ export function main() { inject([AsyncTestCompleter], (async) => { aggregate( [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 2), eventFactory.instant('frame', 3), + eventFactory.markStart('frameCapture', 0), + eventFactory.instant('frame', 1), + eventFactory.instant('frame', 2), + eventFactory.instant('frame', 3), eventFactory.markEnd('frameCapture', 4) ], {captureFrames: true}) @@ -405,9 +479,12 @@ export function main() { inject([AsyncTestCompleter], (async) => { aggregate( [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 2), eventFactory.instant('frame', 22), - eventFactory.instant('frame', 23), eventFactory.instant('frame', 24), + eventFactory.markStart('frameCapture', 0), + eventFactory.instant('frame', 1), + eventFactory.instant('frame', 2), + eventFactory.instant('frame', 22), + eventFactory.instant('frame', 23), + eventFactory.instant('frame', 24), eventFactory.markEnd('frameCapture', 4) ], {captureFrames: true}) @@ -420,160 +497,173 @@ export function main() { }); it('should report a single interval', inject([AsyncTestCompleter], (async) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.end('script', 5) - ]).then((data) => { - expect(data['scriptTime']).toBe(5); - async.done(); - }); + aggregate([eventFactory.start('script', 0), eventFactory.end('script', 5)]) + .then((data) => { + expect(data['scriptTime']).toBe(5); + async.done(); + }); })); it('should sum up multiple intervals', inject([AsyncTestCompleter], (async) => { aggregate([ - eventFactory.start('script', 0), eventFactory.end('script', 5), - eventFactory.start('script', 10), eventFactory.end('script', 17) - ]).then((data) => { - expect(data['scriptTime']).toBe(12); - async.done(); - }); + eventFactory.start('script', 0), + eventFactory.end('script', 5), + eventFactory.start('script', 10), + eventFactory.end('script', 17) + ]) + .then((data) => { + expect(data['scriptTime']).toBe(12); + async.done(); + }); })); it('should ignore not started intervals', inject([AsyncTestCompleter], (async) => { - aggregate([eventFactory.end('script', 10)]).then((data) => { - expect(data['scriptTime']).toBe(0); - async.done(); - }); + aggregate([eventFactory.end('script', 10)]) + .then((data) => { + expect(data['scriptTime']).toBe(0); + async.done(); + }); })); it('should ignore not ended intervals', inject([AsyncTestCompleter], (async) => { - aggregate([eventFactory.start('script', 10)]).then((data) => { - expect(data['scriptTime']).toBe(0); - async.done(); - }); + aggregate([eventFactory.start('script', 10)]) + .then((data) => { + expect(data['scriptTime']).toBe(0); + async.done(); + }); })); it('should ignore nested intervals', inject([AsyncTestCompleter], (async) => { aggregate([ - eventFactory.start('script', 0), eventFactory.start('script', 5), - eventFactory.end('script', 10), eventFactory.end('script', 17) - ]).then((data) => { - expect(data['scriptTime']).toBe(17); - async.done(); - }); + eventFactory.start('script', 0), + eventFactory.start('script', 5), + eventFactory.end('script', 10), + eventFactory.end('script', 17) + ]) + .then((data) => { + expect(data['scriptTime']).toBe(17); + async.done(); + }); })); it('should ignore events from different processed as the start mark', inject([AsyncTestCompleter], (async) => { var otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); var metric = createMetric( - [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), - eventFactory.end('script', 5, null), - otherProcessEventFactory.start('script', 10, null), - otherProcessEventFactory.end('script', 17, null), - eventFactory.markEnd('benchpress0', 20) - ]], + [ + [ + eventFactory.markStart('benchpress0', 0), + eventFactory.start('script', 0, null), + eventFactory.end('script', 5, null), + otherProcessEventFactory.start('script', 10, null), + otherProcessEventFactory.end('script', 17, null), + eventFactory.markEnd('benchpress0', 20) + ] + ], null); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(data['scriptTime']).toBe(5); - async.done(); - }); + metric.beginMeasure() + .then((_) => metric.endMeasure(false)) + .then((data) => { + expect(data['scriptTime']).toBe(5); + async.done(); + }); })); it('should support scriptTime metric', inject([AsyncTestCompleter], (async) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.end('script', 5) - ]).then((data) => { - expect(data['scriptTime']).toBe(5); - async.done(); - }); + aggregate([eventFactory.start('script', 0), eventFactory.end('script', 5)]) + .then((data) => { + expect(data['scriptTime']).toBe(5); + async.done(); + }); })); it('should support renderTime metric', inject([AsyncTestCompleter], (async) => { - aggregate([ - eventFactory.start('render', 0), eventFactory.end('render', 5) - ]).then((data) => { - expect(data['renderTime']).toBe(5); - async.done(); - }); + aggregate([eventFactory.start('render', 0), eventFactory.end('render', 5)]) + .then((data) => { + expect(data['renderTime']).toBe(5); + async.done(); + }); })); it('should support gcTime/gcAmount metric', inject([AsyncTestCompleter], (async) => { aggregate([ eventFactory.start('gc', 0, {'usedHeapSize': 2500}), eventFactory.end('gc', 5, {'usedHeapSize': 1000}) - ]).then((data) => { - expect(data['gcTime']).toBe(5); - expect(data['gcAmount']).toBe(1.5); - expect(data['majorGcTime']).toBe(0); - async.done(); - }); + ]) + .then((data) => { + expect(data['gcTime']).toBe(5); + expect(data['gcAmount']).toBe(1.5); + expect(data['majorGcTime']).toBe(0); + async.done(); + }); })); it('should support majorGcTime metric', inject([AsyncTestCompleter], (async) => { aggregate([ eventFactory.start('gc', 0, {'usedHeapSize': 2500}), eventFactory.end('gc', 5, {'usedHeapSize': 1000, 'majorGc': true}) - ]).then((data) => { - expect(data['gcTime']).toBe(5); - expect(data['majorGcTime']).toBe(5); - async.done(); - }); + ]) + .then((data) => { + expect(data['gcTime']).toBe(5); + expect(data['majorGcTime']).toBe(5); + async.done(); + }); })); it('should support pureScriptTime = scriptTime-gcTime-renderTime', inject([AsyncTestCompleter], (async) => { aggregate([ - eventFactory.start('script', 0), eventFactory.start('gc', 1, {'usedHeapSize': 1000}), - eventFactory.end('gc', 4, {'usedHeapSize': 0}), eventFactory.start('render', 4), - eventFactory.end('render', 5), eventFactory.end('script', 6) - ]).then((data) => { - expect(data['scriptTime']).toBe(6); - expect(data['pureScriptTime']).toBe(2); - async.done(); - }); + eventFactory.start('script', 0), + eventFactory.start('gc', 1, {'usedHeapSize': 1000}), + eventFactory.end('gc', 4, {'usedHeapSize': 0}), + eventFactory.start('render', 4), + eventFactory.end('render', 5), + eventFactory.end('script', 6) + ]) + .then((data) => { + expect(data['scriptTime']).toBe(6); + expect(data['pureScriptTime']).toBe(2); + async.done(); + }); })); - describe( - 'receivedData', - () => { - it('should report received data since last navigationStart', - inject([AsyncTestCompleter], (async) => { - aggregate( - [ - eventFactory.instant('receivedData', 0, {'encodedDataLength': 1}), - eventFactory.instant('navigationStart', 1), - eventFactory.instant('receivedData', 2, {'encodedDataLength': 2}), - eventFactory.instant('navigationStart', 3), - eventFactory.instant('receivedData', 4, {'encodedDataLength': 4}), - eventFactory.instant('receivedData', 5, {'encodedDataLength': 8}) - ], - {receivedData: true}) - .then((data) => { - expect(data['receivedData']).toBe(12); - async.done(); - }); - }))}); + describe('receivedData', + () => {it('should report received data since last navigationStart', + inject([AsyncTestCompleter], (async) => { + aggregate( + [ + eventFactory.instant('receivedData', 0, {'encodedDataLength': 1}), + eventFactory.instant('navigationStart', 1), + eventFactory.instant('receivedData', 2, {'encodedDataLength': 2}), + eventFactory.instant('navigationStart', 3), + eventFactory.instant('receivedData', 4, {'encodedDataLength': 4}), + eventFactory.instant('receivedData', 5, {'encodedDataLength': 8}) + ], + {receivedData: true}) + .then((data) => { + expect(data['receivedData']).toBe(12); + async.done(); + }); + }))}); - describe( - 'requestCount', - () => {it( - 'should report count of requests sent since last navigationStart', - inject([AsyncTestCompleter], (async) => { - aggregate( - [ - eventFactory.instant('sendRequest', 0), - eventFactory.instant('navigationStart', 1), - eventFactory.instant('sendRequest', 2), - eventFactory.instant('navigationStart', 3), - eventFactory.instant('sendRequest', 4), eventFactory.instant('sendRequest', 5) - ], - {requestCount: true}) - .then((data) => { - expect(data['requestCount']).toBe(2); - async.done(); - }); - }))}); + describe('requestCount', + () => {it('should report count of requests sent since last navigationStart', + inject([AsyncTestCompleter], (async) => { + aggregate( + [ + eventFactory.instant('sendRequest', 0), + eventFactory.instant('navigationStart', 1), + eventFactory.instant('sendRequest', 2), + eventFactory.instant('navigationStart', 3), + eventFactory.instant('sendRequest', 4), + eventFactory.instant('sendRequest', 5) + ], + {requestCount: true}) + .then((data) => { + expect(data['requestCount']).toBe(2); + async.done(); + }); + }))}); describe('microMetrics', () => { @@ -595,10 +685,11 @@ export function main() { aggregate([ eventFactory.markStart('mm1', 0), eventFactory.markEnd('mm1', 5), - ]).then((data) => { - expect(data['mm1']).toBeFalsy(); - async.done(); - }); + ]) + .then((data) => { + expect(data['mm1']).toBeFalsy(); + async.done(); + }); })); it('should report micro metric averages', inject([AsyncTestCompleter], (async) => { @@ -622,9 +713,8 @@ export function main() { } class MockDriverExtension extends WebDriverExtension { - constructor( - private _perfLogs: any[], private _commandLog: any[], - private _perfLogFeatures: PerfLogFeatures) { + constructor(private _perfLogs: any[], private _commandLog: any[], + private _perfLogFeatures: PerfLogFeatures) { super(); } diff --git a/modules/benchpress/test/reporter/console_reporter_spec.ts b/modules/benchpress/test/reporter/console_reporter_spec.ts index 00d6893ef0..fa55fb6ea2 100644 --- a/modules/benchpress/test/reporter/console_reporter_spec.ts +++ b/modules/benchpress/test/reporter/console_reporter_spec.ts @@ -1,8 +1,26 @@ -import {describe, ddescribe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + describe, + ddescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {isBlank, isPresent, Date, DateWrapper} from 'angular2/src/facade/lang'; -import {SampleState, Reporter, bind, provide, Injector, ConsoleReporter, SampleDescription, MeasureValues} from 'benchpress/common'; +import { + SampleState, + Reporter, + bind, + provide, + Injector, + ConsoleReporter, + SampleDescription, + MeasureValues +} from 'benchpress/common'; export function main() { describe('console reporter', () => { @@ -20,8 +38,8 @@ export function main() { } var bindings = [ ConsoleReporter.BINDINGS, - provide( - SampleDescription, {useValue: new SampleDescription(sampleId, descriptions, metrics)}), + provide(SampleDescription, + {useValue: new SampleDescription(sampleId, descriptions, metrics)}), bind(ConsoleReporter.PRINT).toValue((line) => log.push(line)) ]; if (isPresent(columnWidth)) { diff --git a/modules/benchpress/test/reporter/json_file_reporter_spec.ts b/modules/benchpress/test/reporter/json_file_reporter_spec.ts index 21a0c83ef1..d65b3bbc56 100644 --- a/modules/benchpress/test/reporter/json_file_reporter_spec.ts +++ b/modules/benchpress/test/reporter/json_file_reporter_spec.ts @@ -1,9 +1,27 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {DateWrapper, Json, RegExpWrapper, isPresent} from 'angular2/src/facade/lang'; import {PromiseWrapper} from 'angular2/src/facade/async'; -import {bind, provide, Injector, SampleDescription, MeasureValues, Options} from 'benchpress/common'; +import { + bind, + provide, + Injector, + SampleDescription, + MeasureValues, + Options +} from 'benchpress/common'; import {JsonFileReporter} from 'benchpress/src/reporter/json_file_reporter'; @@ -15,14 +33,15 @@ export function main() { function createReporter({sampleId, descriptions, metrics, path}) { var bindings = [ JsonFileReporter.BINDINGS, - provide( - SampleDescription, {useValue: new SampleDescription(sampleId, descriptions, metrics)}), + provide(SampleDescription, + {useValue: new SampleDescription(sampleId, descriptions, metrics)}), bind(JsonFileReporter.PATH).toValue(path), bind(Options.NOW).toValue(() => DateWrapper.fromMillis(1234)), - bind(Options.WRITE_FILE).toValue((filename, content) => { - loggedFile = {'filename': filename, 'content': content}; - return PromiseWrapper.resolve(null); - }) + bind(Options.WRITE_FILE) + .toValue((filename, content) => { + loggedFile = {'filename': filename, 'content': content}; + return PromiseWrapper.resolve(null); + }) ]; return Injector.resolveAndCreate(bindings).get(JsonFileReporter); } @@ -34,26 +53,35 @@ export function main() { path: 'somePath', metrics: {'script': 'script time'} }) - .reportSample( - [mv(0, 0, {'a': 3, 'b': 6})], - [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]); + .reportSample([mv(0, 0, {'a': 3, 'b': 6})], + [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]); var regExp = /somePath\/someId_\d+\.json/g; expect(isPresent(RegExpWrapper.firstMatch(regExp, loggedFile['filename']))).toBe(true); var parsedContent = Json.parse(loggedFile['content']); - expect(parsedContent).toEqual({ - 'description': - {'id': 'someId', 'description': {'a': 2}, 'metrics': {'script': 'script time'}}, - 'completeSample': [ - {'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}} - ], - 'validSample': [ - {'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}}, { - 'timeStamp': '1970-01-01T00:00:00.001Z', - 'runIndex': 1, - 'values': {'a': 5, 'b': 9} - } - ] - }); + expect(parsedContent) + .toEqual({ + "description": + {"id": "someId", "description": {"a": 2}, "metrics": {"script": "script time"}}, + "completeSample": [ + { + "timeStamp": "1970-01-01T00:00:00.000Z", + "runIndex": 0, + "values": {"a": 3, "b": 6} + } + ], + "validSample": [ + { + "timeStamp": "1970-01-01T00:00:00.000Z", + "runIndex": 0, + "values": {"a": 3, "b": 6} + }, + { + "timeStamp": "1970-01-01T00:00:00.001Z", + "runIndex": 1, + "values": {"a": 5, "b": 9} + } + ] + }); async.done(); })); diff --git a/modules/benchpress/test/reporter/multi_reporter_spec.ts b/modules/benchpress/test/reporter/multi_reporter_spec.ts index 35abc8fab1..6d4dfe3ff4 100644 --- a/modules/benchpress/test/reporter/multi_reporter_spec.ts +++ b/modules/benchpress/test/reporter/multi_reporter_spec.ts @@ -1,4 +1,15 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {DateWrapper} from 'angular2/src/facade/lang'; @@ -7,11 +18,10 @@ import {Reporter, MultiReporter, bind, provide, Injector, MeasureValues} from 'b export function main() { function createReporters(ids: any[]) { - var r = Injector - .resolveAndCreate([ - ids.map(id => provide(id, {useValue: new MockReporter(id)})), - MultiReporter.createBindings(ids) - ]) + var r = Injector.resolveAndCreate([ + ids.map(id => provide(id, {useValue: new MockReporter(id)})), + MultiReporter.createBindings(ids) + ]) .get(MultiReporter); return PromiseWrapper.resolve(r); } @@ -20,16 +30,19 @@ export function main() { it('should reportMeasureValues to all', inject([AsyncTestCompleter], (async) => { var mv = new MeasureValues(0, DateWrapper.now(), {}); - createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => { + createReporters(['m1', 'm2']) + .then((r) => r.reportMeasureValues(mv)) + .then((values) => { - expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]); - async.done(); - }); + expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]); + async.done(); + }); })); it('should reportSample to call', inject([AsyncTestCompleter], (async) => { var completeSample = [ - new MeasureValues(0, DateWrapper.now(), {}), new MeasureValues(1, DateWrapper.now(), {}) + new MeasureValues(0, DateWrapper.now(), {}), + new MeasureValues(1, DateWrapper.now(), {}) ]; var validSample = [completeSample[1]]; @@ -55,8 +68,8 @@ class MockReporter extends Reporter { return PromiseWrapper.resolve({'id': this._id, 'values': values}); } - reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): - Promise<{[key: string]: any}> { + reportSample(completeSample: MeasureValues[], + validSample: MeasureValues[]): Promise<{[key: string]: any}> { return PromiseWrapper.resolve( {'id': this._id, 'completeSample': completeSample, 'validSample': validSample}); } diff --git a/modules/benchpress/test/runner_spec.ts b/modules/benchpress/test/runner_spec.ts index 8fe7f1e872..888971881c 100644 --- a/modules/benchpress/test/runner_spec.ts +++ b/modules/benchpress/test/runner_spec.ts @@ -1,5 +1,28 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; -import {Runner, Sampler, SampleDescription, Validator, bind, provide, Injector, Metric, Options, WebDriverAdapter, SampleState} from 'benchpress/common'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; +import { + Runner, + Sampler, + SampleDescription, + Validator, + bind, + provide, + Injector, + Metric, + Options, + WebDriverAdapter, + SampleState +} from 'benchpress/common'; import {isBlank} from 'angular2/src/facade/lang'; import {PromiseWrapper} from 'angular2/src/facade/async'; @@ -13,12 +36,13 @@ export function main() { defaultBindings = []; } runner = new Runner([ - defaultBindings, bind(Sampler).toFactory( - (_injector) => { - injector = _injector; - return new MockSampler(); - }, - [Injector]), + defaultBindings, + bind(Sampler).toFactory( + (_injector) => { + injector = _injector; + return new MockSampler(); + }, + [Injector]), bind(Metric).toFactory(() => new MockMetric(), []), bind(Validator).toFactory(() => new MockValidator(), []), bind(WebDriverAdapter).toFactory(() => new MockWebDriverAdapter(), []) @@ -62,35 +86,43 @@ export function main() { it('should bind Options.EXECUTE', inject([AsyncTestCompleter], (async) => { var execute = () => {}; - createRunner().sample({id: 'someId', execute: execute}).then((_) => { - expect(injector.get(Options.EXECUTE)).toEqual(execute); - async.done(); - }); + createRunner() + .sample({id: 'someId', execute: execute}) + .then((_) => { + expect(injector.get(Options.EXECUTE)).toEqual(execute); + async.done(); + }); })); it('should bind Options.PREPARE', inject([AsyncTestCompleter], (async) => { var prepare = () => {}; - createRunner().sample({id: 'someId', prepare: prepare}).then((_) => { - expect(injector.get(Options.PREPARE)).toEqual(prepare); - async.done(); - }); + createRunner() + .sample({id: 'someId', prepare: prepare}) + .then((_) => { + expect(injector.get(Options.PREPARE)).toEqual(prepare); + async.done(); + }); })); it('should bind Options.MICRO_METRICS', inject([AsyncTestCompleter], (async) => { - createRunner().sample({id: 'someId', microMetrics: {'a': 'b'}}).then((_) => { - expect(injector.get(Options.MICRO_METRICS)).toEqual({'a': 'b'}); - async.done(); - }); + createRunner() + .sample({id: 'someId', microMetrics: {'a': 'b'}}) + .then((_) => { + expect(injector.get(Options.MICRO_METRICS)).toEqual({'a': 'b'}); + async.done(); + }); })); it('should overwrite bindings per sample call', inject([AsyncTestCompleter], (async) => { createRunner([ - bind(Options.DEFAULT_DESCRIPTION).toValue({'a': 1}), + bind(Options.DEFAULT_DESCRIPTION) + .toValue({'a': 1}), ]) .sample({ id: 'someId', bindings: [ - bind(Options.DEFAULT_DESCRIPTION).toValue({'a': 2}), + bind(Options.DEFAULT_DESCRIPTION) + .toValue({'a': 2}), ] }) .then((_) => injector.get(SampleDescription)) diff --git a/modules/benchpress/test/sampler_spec.ts b/modules/benchpress/test/sampler_spec.ts index 70a232f4b4..971b48fffd 100644 --- a/modules/benchpress/test/sampler_spec.ts +++ b/modules/benchpress/test/sampler_spec.ts @@ -1,9 +1,31 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {isBlank, isPresent, stringify, Date, DateWrapper} from 'angular2/src/facade/lang'; import {PromiseWrapper} from 'angular2/src/facade/async'; -import {Sampler, WebDriverAdapter, Validator, Metric, Reporter, bind, provide, Injector, Options, MeasureValues} from 'benchpress/common'; +import { + Sampler, + WebDriverAdapter, + Validator, + Metric, + Reporter, + bind, + provide, + Injector, + Options, + MeasureValues +} from 'benchpress/common'; export function main() { var EMPTY_EXECUTE = () => {}; @@ -30,9 +52,13 @@ export function main() { driver = new MockDriverAdapter([]); } var bindings = [ - Options.DEFAULT_PROVIDERS, Sampler.BINDINGS, provide(Metric, {useValue: metric}), - provide(Reporter, {useValue: reporter}), provide(WebDriverAdapter, {useValue: driver}), - bind(Options.EXECUTE).toValue(execute), provide(Validator, {useValue: validator}), + Options.DEFAULT_PROVIDERS, + Sampler.BINDINGS, + provide(Metric, {useValue: metric}), + provide(Reporter, {useValue: reporter}), + provide(WebDriverAdapter, {useValue: driver}), + bind(Options.EXECUTE).toValue(execute), + provide(Validator, {useValue: validator}), bind(Options.NOW).toValue(() => DateWrapper.fromMillis(time++)) ]; if (isPresent(prepare)) { @@ -118,13 +144,12 @@ export function main() { var iterationCount = 1; createSampler({ validator: createCountingValidator(2), - metric: new MockMetric( - [], - () => { - var result = PromiseWrapper.resolve({'script': scriptTime}); - scriptTime = 0; - return result; - }), + metric: new MockMetric([], + () => { + var result = PromiseWrapper.resolve({'script': scriptTime}); + scriptTime = 0; + return result; + }), prepare: () => { scriptTime = 1 * iterationCount; }, execute: () => { scriptTime = 10 * iterationCount; @@ -186,7 +211,9 @@ export function main() { expect(log[0]).toEqual(['reportMeasureValues', mv(0, 1000, {'script': 0})]); expect(log[1]).toEqual(['reportMeasureValues', mv(1, 1001, {'script': 1})]); expect(log[2]).toEqual([ - 'reportSample', [mv(0, 1000, {'script': 0}), mv(1, 1001, {'script': 1})], validSample + 'reportSample', + [mv(0, 1000, {'script': 0}), mv(1, 1001, {'script': 1})], + validSample ]); async.done(); diff --git a/modules/benchpress/test/statistic_spec.ts b/modules/benchpress/test/statistic_spec.ts index 255774adf5..122b69b15f 100644 --- a/modules/benchpress/test/statistic_spec.ts +++ b/modules/benchpress/test/statistic_spec.ts @@ -1,4 +1,13 @@ -import {describe, ddescribe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + describe, + ddescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {Statistic} from 'benchpress/src/statistic'; diff --git a/modules/benchpress/test/validator/regression_slope_validator_spec.ts b/modules/benchpress/test/validator/regression_slope_validator_spec.ts index 18f8ea58c6..25abb2d7d7 100644 --- a/modules/benchpress/test/validator/regression_slope_validator_spec.ts +++ b/modules/benchpress/test/validator/regression_slope_validator_spec.ts @@ -1,20 +1,35 @@ -import {describe, ddescribe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + describe, + ddescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {Date, DateWrapper} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; -import {Validator, RegressionSlopeValidator, Injector, bind, provide, MeasureValues} from 'benchpress/common'; +import { + Validator, + RegressionSlopeValidator, + Injector, + bind, + provide, + MeasureValues +} from 'benchpress/common'; export function main() { describe('regression slope validator', () => { var validator; function createValidator({size, metric}) { - validator = Injector - .resolveAndCreate([ - RegressionSlopeValidator.BINDINGS, - bind(RegressionSlopeValidator.METRIC).toValue(metric), - bind(RegressionSlopeValidator.SAMPLE_SIZE).toValue(size) - ]) + validator = Injector.resolveAndCreate([ + RegressionSlopeValidator.BINDINGS, + bind(RegressionSlopeValidator.METRIC).toValue(metric), + bind(RegressionSlopeValidator.SAMPLE_SIZE).toValue(size) + ]) .get(RegressionSlopeValidator); } diff --git a/modules/benchpress/test/validator/size_validator_spec.ts b/modules/benchpress/test/validator/size_validator_spec.ts index 4864a1d712..064140c682 100644 --- a/modules/benchpress/test/validator/size_validator_spec.ts +++ b/modules/benchpress/test/validator/size_validator_spec.ts @@ -1,4 +1,13 @@ -import {describe, ddescribe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal'; +import { + describe, + ddescribe, + it, + iit, + xit, + expect, + beforeEach, + afterEach +} from 'angular2/testing_internal'; import {Date, DateWrapper} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -9,10 +18,10 @@ export function main() { var validator; function createValidator(size) { - validator = Injector - .resolveAndCreate( - [SizeValidator.BINDINGS, bind(SizeValidator.SAMPLE_SIZE).toValue(size)]) - .get(SizeValidator); + validator = + Injector.resolveAndCreate( + [SizeValidator.BINDINGS, bind(SizeValidator.SAMPLE_SIZE).toValue(size)]) + .get(SizeValidator); } it('should return sampleSize as description', () => { diff --git a/modules/benchpress/test/web_driver_extension_spec.ts b/modules/benchpress/test/web_driver_extension_spec.ts index ad4f1f5710..2bfc96b5ee 100644 --- a/modules/benchpress/test/web_driver_extension_spec.ts +++ b/modules/benchpress/test/web_driver_extension_spec.ts @@ -1,4 +1,15 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {PromiseWrapper} from 'angular2/src/facade/async'; @@ -8,11 +19,11 @@ import {WebDriverExtension, bind, provide, Injector, Options} from 'benchpress/c export function main() { function createExtension(ids: any[], caps) { return PromiseWrapper.wrap(() => { - return Injector - .resolveAndCreate([ - ids.map(id => provide(id, {useValue: new MockExtension(id)})), - bind(Options.CAPABILITIES).toValue(caps), WebDriverExtension.bindTo(ids) - ]) + return Injector.resolveAndCreate([ + ids.map(id => provide(id, {useValue: new MockExtension(id)})), + bind(Options.CAPABILITIES).toValue(caps), + WebDriverExtension.bindTo(ids) + ]) .get(WebDriverExtension); }); } @@ -21,10 +32,11 @@ export function main() { it('should bind the extension that matches the capabilities', inject([AsyncTestCompleter], (async) => { - createExtension(['m1', 'm2', 'm3'], {'browser': 'm2'}).then((m) => { - expect(m.id).toEqual('m2'); - async.done(); - }); + createExtension(['m1', 'm2', 'm3'], {'browser': 'm2'}) + .then((m) => { + expect(m.id).toEqual('m2'); + async.done(); + }); })); it('should throw if there is no match', inject([AsyncTestCompleter], (async) => { diff --git a/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts b/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts index 1a6b74ec5a..1dd974332b 100644 --- a/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts +++ b/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts @@ -1,9 +1,28 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {Json, isBlank} from 'angular2/src/facade/lang'; -import {WebDriverExtension, ChromeDriverExtension, WebDriverAdapter, Injector, bind, provide, Options} from 'benchpress/common'; +import { + WebDriverExtension, + ChromeDriverExtension, + WebDriverAdapter, + Injector, + bind, + provide, + Options +} from 'benchpress/common'; import {TraceEventFactory} from '../trace_event_factory'; @@ -29,9 +48,8 @@ export function main() { var benchmarkEvents = new TraceEventFactory('benchmark', 'pid0'); var normEvents = new TraceEventFactory('timeline', 'pid0'); - function createExtension( - perfRecords = null, userAgent = null, - messageMethod = 'Tracing.dataCollected'): WebDriverExtension { + function createExtension(perfRecords = null, userAgent = null, + messageMethod = 'Tracing.dataCollected'): WebDriverExtension { if (isBlank(perfRecords)) { perfRecords = []; } @@ -39,13 +57,12 @@ export function main() { userAgent = CHROME44_USER_AGENT; } log = []; - extension = Injector - .resolveAndCreate([ - ChromeDriverExtension.BINDINGS, - bind(WebDriverAdapter) - .toValue(new MockDriverAdapter(log, perfRecords, messageMethod)), - bind(Options.USER_AGENT).toValue(userAgent) - ]) + extension = Injector.resolveAndCreate([ + ChromeDriverExtension.BINDINGS, + bind(WebDriverAdapter) + .toValue(new MockDriverAdapter(log, perfRecords, messageMethod)), + bind(Options.USER_AGENT).toValue(userAgent) + ]) .get(ChromeDriverExtension); return extension; } @@ -58,26 +75,32 @@ export function main() { })); it('should mark the timeline via console.time()', inject([AsyncTestCompleter], (async) => { - createExtension().timeBegin('someName').then((_) => { - expect(log).toEqual([['executeScript', `console.time('someName');`]]); - async.done(); - }); + createExtension() + .timeBegin('someName') + .then((_) => { + expect(log).toEqual([['executeScript', `console.time('someName');`]]); + async.done(); + }); })); it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { - createExtension().timeEnd('someName', null).then((_) => { - expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); - async.done(); - }); + createExtension() + .timeEnd('someName', null) + .then((_) => { + expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); + async.done(); + }); })); it('should mark the timeline via console.time() and console.timeEnd()', inject([AsyncTestCompleter], (async) => { - createExtension().timeEnd('name1', 'name2').then((_) => { - expect(log).toEqual( - [['executeScript', `console.timeEnd('name1');console.time('name2');`]]); - async.done(); - }); + createExtension() + .timeEnd('name1', 'name2') + .then((_) => { + expect(log) + .toEqual([['executeScript', `console.timeEnd('name1');console.time('name2');`]]); + async.done(); + }); })); describe('readPerfLog Chrome44', () => { @@ -183,8 +206,10 @@ export function main() { }); it('should ignore FunctionCalls from webdriver', inject([AsyncTestCompleter], (async) => { - createExtension([chromeTimelineEvents.start( - 'FunctionCall', 0, {'data': {'scriptName': 'InjectedScript'}})]) + createExtension([ + chromeTimelineEvents.start('FunctionCall', 0, + {'data': {'scriptName': 'InjectedScript'}}) + ]) .readPerfLog() .then((events) => { expect(events).toEqual([]); @@ -198,9 +223,8 @@ export function main() { describe('readPerfLog Chrome45', () => { it('should normalize times to ms and forward ph and pid event properties', inject([AsyncTestCompleter], (async) => { - createExtension( - [chromeTimelineV8Events.complete('FunctionCall', 1100, 5500, null)], - CHROME45_USER_AGENT) + createExtension([chromeTimelineV8Events.complete('FunctionCall', 1100, 5500, null)], + CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ @@ -213,12 +237,14 @@ export function main() { it('should normalize "tdur" to "dur"', inject([AsyncTestCompleter], (async) => { var event = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null); event['tdur'] = 5500; - createExtension([event], CHROME45_USER_AGENT).readPerfLog().then((events) => { - expect(events).toEqual([ - normEvents.complete('script', 1.1, 5.5, null), - ]); - async.done(); - }); + createExtension([event], CHROME45_USER_AGENT) + .readPerfLog() + .then((events) => { + expect(events).toEqual([ + normEvents.complete('script', 1.1, 5.5, null), + ]); + async.done(); + }); })); it('should report FunctionCall events as "script"', inject([AsyncTestCompleter], (async) => { @@ -244,8 +270,8 @@ export function main() { expect(events.length).toEqual(2); expect(events[0]).toEqual( normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': false})); - expect(events[1]).toEqual( - normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': false})); + expect(events[1]) + .toEqual(normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': false})); async.done(); }); })); @@ -260,10 +286,10 @@ export function main() { .readPerfLog() .then((events) => { expect(events.length).toEqual(2); - expect(events[0]).toEqual( - normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': true})); - expect(events[1]).toEqual( - normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': true})); + expect(events[0]) + .toEqual(normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': true})); + expect(events[1]) + .toEqual(normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': true})); async.done(); }); })); @@ -307,8 +333,10 @@ export function main() { it('should ignore FunctionCalls from webdriver', inject([AsyncTestCompleter], (async) => { - createExtension([chromeTimelineV8Events.start( - 'FunctionCall', 0, {'data': {'scriptName': 'InjectedScript'}})]) + createExtension([ + chromeTimelineV8Events.start('FunctionCall', 0, + {'data': {'scriptName': 'InjectedScript'}}) + ]) .readPerfLog() .then((events) => { expect(events).toEqual([]); @@ -328,8 +356,8 @@ export function main() { })); it('should report navigationStart', inject([AsyncTestCompleter], (async) => { - createExtension( - [chromeBlinkUserTimingEvents.start('navigationStart', 1234)], CHROME45_USER_AGENT) + createExtension([chromeBlinkUserTimingEvents.start('navigationStart', 1234)], + CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([normEvents.start('navigationStart', 1.234)]); @@ -339,8 +367,10 @@ export function main() { it('should report receivedData', inject([AsyncTestCompleter], (async) => { createExtension( - [chrome45TimelineEvents.instant( - 'ResourceReceivedData', 1234, {'data': {'encodedDataLength': 987}})], + [ + chrome45TimelineEvents.instant('ResourceReceivedData', 1234, + {'data': {'encodedDataLength': 987}}) + ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { @@ -352,14 +382,18 @@ export function main() { it('should report sendRequest', inject([AsyncTestCompleter], (async) => { createExtension( - [chrome45TimelineEvents.instant( - 'ResourceSendRequest', 1234, - {'data': {'url': 'http://here', 'requestMethod': 'GET'}})], + [ + chrome45TimelineEvents.instant( + 'ResourceSendRequest', 1234, + {'data': {'url': 'http://here', 'requestMethod': 'GET'}}) + ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { - expect(events).toEqual([normEvents.instant( - 'sendRequest', 1.234, {'url': 'http://here', 'method': 'GET'})]); + expect(events).toEqual([ + normEvents.instant('sendRequest', 1.234, + {'url': 'http://here', 'method': 'GET'}) + ]); async.done(); }); })); @@ -400,9 +434,10 @@ export function main() { describe('frame metrics', () => { it('should report ImplThreadRenderingStats as frame event', inject([AsyncTestCompleter], (async) => { - createExtension([benchmarkEvents.instant( - 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, - {'data': {'frame_count': 1}})]) + createExtension([ + benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, + {'data': {'frame_count': 1}}) + ]) .readPerfLog() .then((events) => { expect(events).toEqual([ @@ -414,9 +449,10 @@ export function main() { it('should not report ImplThreadRenderingStats with zero frames', inject([AsyncTestCompleter], (async) => { - createExtension([benchmarkEvents.instant( - 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, - {'data': {'frame_count': 0}})]) + createExtension([ + benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, + {'data': {'frame_count': 0}}) + ]) .readPerfLog() .then((events) => { expect(events).toEqual([]); @@ -428,14 +464,12 @@ export function main() { inject([AsyncTestCompleter], (async) => { PromiseWrapper.catchError( createExtension([ - benchmarkEvents.instant( - 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, - {'data': {'frame_count': 2}}) + benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', + 1100, {'data': {'frame_count': 2}}) ]).readPerfLog(), (err): any => { - expect(() => { - throw err; - }).toThrowError('multi-frame render stats not supported'); + expect(() => { throw err; }) + .toThrowError('multi-frame render stats not supported'); async.done(); }); })); @@ -469,9 +503,8 @@ export function main() { CHROME45_USER_AGENT, 'Tracing.bufferUsage') .readPerfLog(), (err): any => { - expect(() => { - throw err; - }).toThrowError('The DevTools trace buffer filled during the test!'); + expect(() => { throw err; }) + .toThrowError('The DevTools trace buffer filled during the test!'); async.done(); }); })); diff --git a/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts b/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts index f8072346eb..39131eeb02 100644 --- a/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts +++ b/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts @@ -1,9 +1,27 @@ -import {afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal'; +import { + afterEach, + AsyncTestCompleter, + beforeEach, + ddescribe, + describe, + expect, + iit, + inject, + it, + xit, +} from 'angular2/testing_internal'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {Json, isBlank, isPresent} from 'angular2/src/facade/lang'; -import {WebDriverExtension, IOsDriverExtension, WebDriverAdapter, Injector, bind, provide} from 'benchpress/common'; +import { + WebDriverExtension, + IOsDriverExtension, + WebDriverAdapter, + Injector, + bind, + provide +} from 'benchpress/common'; import {TraceEventFactory} from '../trace_event_factory'; @@ -20,11 +38,10 @@ export function main() { } log = []; extension = - Injector - .resolveAndCreate([ - IOsDriverExtension.BINDINGS, - provide(WebDriverAdapter, {useValue: new MockDriverAdapter(log, perfRecords)}) - ]) + Injector.resolveAndCreate([ + IOsDriverExtension.BINDINGS, + provide(WebDriverAdapter, {useValue: new MockDriverAdapter(log, perfRecords)}) + ]) .get(IOsDriverExtension); return extension; } @@ -34,26 +51,32 @@ export function main() { }); it('should mark the timeline via console.time()', inject([AsyncTestCompleter], (async) => { - createExtension().timeBegin('someName').then((_) => { - expect(log).toEqual([['executeScript', `console.time('someName');`]]); - async.done(); - }); + createExtension() + .timeBegin('someName') + .then((_) => { + expect(log).toEqual([['executeScript', `console.time('someName');`]]); + async.done(); + }); })); it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { - createExtension().timeEnd('someName', null).then((_) => { - expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); - async.done(); - }); + createExtension() + .timeEnd('someName', null) + .then((_) => { + expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); + async.done(); + }); })); it('should mark the timeline via console.time() and console.timeEnd()', inject([AsyncTestCompleter], (async) => { - createExtension().timeEnd('name1', 'name2').then((_) => { - expect(log).toEqual( - [['executeScript', `console.timeEnd('name1');console.time('name2');`]]); - async.done(); - }); + createExtension() + .timeEnd('name1', 'name2') + .then((_) => { + expect(log) + .toEqual([['executeScript', `console.timeEnd('name1');console.time('name2');`]]); + async.done(); + }); })); describe('readPerfLog', () => { @@ -70,31 +93,40 @@ export function main() { })); it('should report FunctionCall records as "script"', inject([AsyncTestCompleter], (async) => { - createExtension([durationRecord('FunctionCall', 1, 5)]).readPerfLog().then((events) => { - expect(events).toEqual([normEvents.start('script', 1), normEvents.end('script', 5)]); - async.done(); - }); + createExtension([durationRecord('FunctionCall', 1, 5)]) + .readPerfLog() + .then((events) => { + expect(events) + .toEqual([normEvents.start('script', 1), normEvents.end('script', 5)]); + async.done(); + }); })); it('should ignore FunctionCalls from webdriver', inject([AsyncTestCompleter], (async) => { - createExtension([internalScriptRecord(1, 5)]).readPerfLog().then((events) => { - expect(events).toEqual([]); - async.done(); - }); + createExtension([internalScriptRecord(1, 5)]) + .readPerfLog() + .then((events) => { + expect(events).toEqual([]); + async.done(); + }); })); it('should report begin time', inject([AsyncTestCompleter], (async) => { - createExtension([timeBeginRecord('someName', 12)]).readPerfLog().then((events) => { - expect(events).toEqual([normEvents.markStart('someName', 12)]); - async.done(); - }); + createExtension([timeBeginRecord('someName', 12)]) + .readPerfLog() + .then((events) => { + expect(events).toEqual([normEvents.markStart('someName', 12)]); + async.done(); + }); })); it('should report end timestamps', inject([AsyncTestCompleter], (async) => { - createExtension([timeEndRecord('someName', 12)]).readPerfLog().then((events) => { - expect(events).toEqual([normEvents.markEnd('someName', 12)]); - async.done(); - }); + createExtension([timeEndRecord('someName', 12)]) + .readPerfLog() + .then((events) => { + expect(events).toEqual([normEvents.markEnd('someName', 12)]); + async.done(); + }); })); ['RecalculateStyles', 'Layout', 'UpdateLayerTree', 'Paint', 'Rasterize', 'CompositeLayers'] @@ -118,7 +150,8 @@ export function main() { .readPerfLog() .then((events) => { expect(events).toEqual([ - normEvents.start('script', 1), normEvents.markStart('someName', 2), + normEvents.start('script', 1), + normEvents.markStart('someName', 2), normEvents.end('script', 5) ]); async.done(); diff --git a/modules/playground/e2e_test/hash_routing/hash_location_spec.ts b/modules/playground/e2e_test/hash_routing/hash_location_spec.ts index f1eb6c4d00..d495deae84 100644 --- a/modules/playground/e2e_test/hash_routing/hash_location_spec.ts +++ b/modules/playground/e2e_test/hash_routing/hash_location_spec.ts @@ -35,9 +35,9 @@ describe('hash routing example app', function() { element(by.css('#goodbye-link-blank')).click(); expect(browser.driver.getCurrentUrl()).not.toContain('#/bye'); browser.getAllWindowHandles().then(function(windows) { - browser.switchTo().window(windows[1]).then(function() { - expect(browser.driver.getCurrentUrl()).toContain('#/bye'); - }); + browser.switchTo() + .window(windows[1]) + .then(function() { expect(browser.driver.getCurrentUrl()).toContain("#/bye"); }); }); }); }); diff --git a/modules/playground/e2e_test/hello_world/hello_world_spec.ts b/modules/playground/e2e_test/hello_world/hello_world_spec.ts index ab33315896..abc00e7511 100644 --- a/modules/playground/e2e_test/hello_world/hello_world_spec.ts +++ b/modules/playground/e2e_test/hello_world/hello_world_spec.ts @@ -24,13 +24,11 @@ describe('hello world', function() { }); function getComponentText(selector, innerSelector) { - return browser.executeScript( - 'return document.querySelector("' + selector + '").querySelector("' + innerSelector + - '").textContent'); + return browser.executeScript('return document.querySelector("' + selector + '").querySelector("' + + innerSelector + '").textContent'); } function clickComponentButton(selector, innerSelector) { - return browser.executeScript( - 'return document.querySelector("' + selector + '").querySelector("' + innerSelector + - '").click()'); + return browser.executeScript('return document.querySelector("' + selector + '").querySelector("' + + innerSelector + '").click()'); } diff --git a/modules/playground/e2e_test/http/http_spec.ts b/modules/playground/e2e_test/http/http_spec.ts index a49376471e..fb94cff8ed 100644 --- a/modules/playground/e2e_test/http/http_spec.ts +++ b/modules/playground/e2e_test/http/http_spec.ts @@ -17,7 +17,6 @@ describe('http', function() { }); function getComponentText(selector, innerSelector) { - return browser.executeScript( - 'return document.querySelector("' + selector + '").querySelector("' + innerSelector + - '").textContent.trim()'); + return browser.executeScript('return document.querySelector("' + selector + '").querySelector("' + + innerSelector + '").textContent.trim()'); } diff --git a/modules/playground/e2e_test/jsonp/jsonp_spec.ts b/modules/playground/e2e_test/jsonp/jsonp_spec.ts index e465f37c11..a8261b7524 100644 --- a/modules/playground/e2e_test/jsonp/jsonp_spec.ts +++ b/modules/playground/e2e_test/jsonp/jsonp_spec.ts @@ -17,7 +17,6 @@ describe('jsonp', function() { }); function getComponentText(selector, innerSelector) { - return browser.executeScript( - 'return document.querySelector("' + selector + '").querySelector("' + innerSelector + - '").textContent.trim()'); + return browser.executeScript('return document.querySelector("' + selector + '").querySelector("' + + innerSelector + '").textContent.trim()'); } diff --git a/modules/playground/e2e_test/routing/routing_spec.ts b/modules/playground/e2e_test/routing/routing_spec.ts index bccc175a5b..670d7f8947 100644 --- a/modules/playground/e2e_test/routing/routing_spec.ts +++ b/modules/playground/e2e_test/routing/routing_spec.ts @@ -62,8 +62,8 @@ describe('routing inbox-app', () => { waitForElement('#item-10'); element(by.css('#item-10')).click(); waitForElement('#record-id'); - var recordId = element(by.css('#record-id')); - browser.wait(protractor.until.elementTextIs(recordId, 'ID: 10'), 5000); + var recordId = element(by.css("#record-id")); + browser.wait(protractor.until.elementTextIs(recordId, "ID: 10"), 5000); expect(recordId.getText()).toEqual('ID: 10'); }); @@ -85,7 +85,7 @@ describe('routing inbox-app', () => { element(by.css('.sort-button')).click(); expect(browser.getCurrentUrl()).toMatch(/\/#\?sort=date$/); waitForElement('.inbox-item-record'); - expect(element(by.css('.inbox-item-record > a')).getAttribute('id')).toEqual('item-137'); + expect(element(by.css(".inbox-item-record > a")).getAttribute("id")).toEqual("item-137"); }); }) }); diff --git a/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts b/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts index d429e411b5..83784542d1 100644 --- a/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts +++ b/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts @@ -30,19 +30,19 @@ describe('sourcemaps', function() { const content = - fs.readFileSync('dist/js/dev/es5/playground/src/sourcemap/index.js').toString('utf8'); - const marker = '//# sourceMappingURL=data:application/json;base64,'; + fs.readFileSync('dist/js/dev/es5/playground/src/sourcemap/index.js').toString("utf8"); + const marker = "//# sourceMappingURL=data:application/json;base64,"; const index = content.indexOf(marker); const sourceMapData = - new Buffer(content.substring(index + marker.length), 'base64').toString('utf8'); + new Buffer(content.substring(index + marker.length), 'base64').toString("utf8"); var decoder = new sourceMap.SourceMapConsumer(JSON.parse(sourceMapData)); var originalPosition = decoder.originalPositionFor({line: errorLine, column: errorColumn}); - var sourceCodeLines = fs.readFileSync('modules/playground/src/sourcemap/index.ts', { - encoding: 'UTF-8' - }).split('\n'); + var sourceCodeLines = + fs.readFileSync('modules/playground/src/sourcemap/index.ts', {encoding: 'UTF-8'}) + .split('\n'); expect(sourceCodeLines[originalPosition.line - 1]) .toMatch(/throw new BaseException\(\'Sourcemap test\'\)/); }); diff --git a/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts b/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts index 99f81873bc..e4da453e51 100644 --- a/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts +++ b/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts @@ -5,8 +5,8 @@ describe('WebWorkers Kitchen Sink', function() { verifyNoBrowserErrors(); browser.ignoreSynchronization = false; }); - var selector = 'hello-app .greeting'; - var URL = 'playground/src/web_workers/kitchen_sink/index.html'; + var selector = "hello-app .greeting"; + var URL = "playground/src/web_workers/kitchen_sink/index.html"; it('should greet', () => { // This test can't wait for Angular 2 as Testability is not available when using WebWorker @@ -16,7 +16,7 @@ describe('WebWorkers Kitchen Sink', function() { browser.wait(protractor.until.elementLocated(by.css(selector)), 15000); var elem = element(by.css(selector)); browser.wait(protractor.until.elementTextIs(elem, 'hello world!'), 5000); - expect(elem.getText()).toEqual('hello world!'); + expect(elem.getText()).toEqual("hello world!"); }); @@ -29,21 +29,21 @@ describe('WebWorkers Kitchen Sink', function() { browser.wait(protractor.until.elementLocated(by.css(changeButtonSelector)), 15000); element(by.css(changeButtonSelector)).click(); var elem = element(by.css(selector)); - browser.wait(protractor.until.elementTextIs(elem, 'howdy world!'), 5000); - expect(elem.getText()).toEqual('howdy world!'); + browser.wait(protractor.until.elementTextIs(elem, "howdy world!"), 5000); + expect(elem.getText()).toEqual("howdy world!"); }); - it('should display correct key names', () => { + it("should display correct key names", () => { // This test can't wait for Angular 2 as Testability is not available when using WebWorker browser.ignoreSynchronization = true; browser.get(URL); - browser.wait(protractor.until.elementLocated(by.css('.sample-area')), 15000); + browser.wait(protractor.until.elementLocated(by.css(".sample-area")), 15000); - var area = element.all(by.css('.sample-area')).first(); + var area = element.all(by.css(".sample-area")).first(); expect(area.getText()).toEqual('(none)'); area.sendKeys('u'); - browser.wait(protractor.until.elementTextIs(area, 'U'), 5000); - expect(area.getText()).toEqual('U'); + browser.wait(protractor.until.elementTextIs(area, "U"), 5000); + expect(area.getText()).toEqual("U"); }); }); diff --git a/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts b/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts index 71cb6b75d7..3300852d8a 100644 --- a/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts +++ b/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts @@ -1,39 +1,39 @@ -import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util'; -import {PromiseWrapper} from 'angular2/src/facade/async'; +import {verifyNoBrowserErrors} from "angular2/src/testing/e2e_util"; +import {PromiseWrapper} from "angular2/src/facade/async"; var URL = 'playground/src/web_workers/message_broker/index.html'; -describe('MessageBroker', function() { +describe("MessageBroker", function() { afterEach(() => { verifyNoBrowserErrors(); browser.ignoreSynchronization = false; }); - it('should bootstrap', () => { + it("should bootstrap", () => { // This test can't wait for Angular 2 as Testability is not available when using WebWorker browser.ignoreSynchronization = true; browser.get(URL); waitForBootstrap(); - expect(element(by.css('app h1')).getText()).toEqual('WebWorker MessageBroker Test'); + expect(element(by.css("app h1")).getText()).toEqual("WebWorker MessageBroker Test"); }); - it('should echo messages', () => { - const VALUE = 'Hi There'; + it("should echo messages", () => { + const VALUE = "Hi There"; // This test can't wait for Angular 2 as Testability is not available when using WebWorker browser.ignoreSynchronization = true; browser.get(URL); waitForBootstrap(); - var input = element.all(by.css('#echo_input')).first(); + var input = element.all(by.css("#echo_input")).first(); input.sendKeys(VALUE); - element(by.css('#send_echo')).click(); - var area = element(by.css('#echo_result')); + element(by.css("#send_echo")).click(); + var area = element(by.css("#echo_result")); browser.wait(protractor.until.elementTextIs(area, VALUE), 5000); expect(area.getText()).toEqual(VALUE); }); }); function waitForBootstrap(): void { - browser.wait(protractor.until.elementLocated(by.css('app h1')), 15000); + browser.wait(protractor.until.elementLocated(by.css("app h1")), 15000); } diff --git a/modules/playground/e2e_test/web_workers/router/router_spec.ts b/modules/playground/e2e_test/web_workers/router/router_spec.ts index be5a08683f..fe4523d86a 100644 --- a/modules/playground/e2e_test/web_workers/router/router_spec.ts +++ b/modules/playground/e2e_test/web_workers/router/router_spec.ts @@ -1,6 +1,6 @@ import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util'; -describe('WebWorker Router', () => { +describe("WebWorker Router", () => { beforeEach(() => { // This test can't wait for Angular 2 as Testability is not available when using WebWorker browser.ignoreSynchronization = true; @@ -12,43 +12,43 @@ describe('WebWorker Router', () => { browser.ignoreSynchronization = false; }); - let contentSelector = 'app main h1'; - let navSelector = 'app nav ul'; - var baseUrl = 'playground/src/web_workers/router/index.html'; + let contentSelector = "app main h1"; + let navSelector = "app nav ul"; + var baseUrl = "playground/src/web_workers/router/index.html"; - it('should route on click', () => { + it("should route on click", () => { browser.get(baseUrl); waitForElement(contentSelector); var content = element(by.css(contentSelector)); - expect(content.getText()).toEqual('Start'); + expect(content.getText()).toEqual("Start"); - let aboutBtn = element(by.css(navSelector + ' .about')); + let aboutBtn = element(by.css(navSelector + " .about")); aboutBtn.click(); waitForUrl(/\/about/); waitForElement(contentSelector); - waitForElementText(contentSelector, 'About'); + waitForElementText(contentSelector, "About"); content = element(by.css(contentSelector)); - expect(content.getText()).toEqual('About'); + expect(content.getText()).toEqual("About"); expect(browser.getCurrentUrl()).toMatch(/\/about/); - let contactBtn = element(by.css(navSelector + ' .contact')); + let contactBtn = element(by.css(navSelector + " .contact")); contactBtn.click(); waitForUrl(/\/contact/); waitForElement(contentSelector); - waitForElementText(contentSelector, 'Contact'); + waitForElementText(contentSelector, "Contact"); content = element(by.css(contentSelector)); - expect(content.getText()).toEqual('Contact'); + expect(content.getText()).toEqual("Contact"); expect(browser.getCurrentUrl()).toMatch(/\/contact/); }); - it('should load the correct route from the URL', () => { - browser.get(baseUrl + '#/about'); + it("should load the correct route from the URL", () => { + browser.get(baseUrl + "#/about"); waitForElement(contentSelector); - waitForElementText(contentSelector, 'About'); + waitForElementText(contentSelector, "About"); let content = element(by.css(contentSelector)); - expect(content.getText()).toEqual('About'); + expect(content.getText()).toEqual("About"); }); function waitForElement(selector: string): void { diff --git a/modules/playground/e2e_test/web_workers/todo/todo_spec.ts b/modules/playground/e2e_test/web_workers/todo/todo_spec.ts index cb88458835..b587954eda 100644 --- a/modules/playground/e2e_test/web_workers/todo/todo_spec.ts +++ b/modules/playground/e2e_test/web_workers/todo/todo_spec.ts @@ -6,7 +6,7 @@ describe('WebWorkers Todo', function() { browser.ignoreSynchronization = false; }); - var URL = 'playground/src/web_workers/todo/index.html'; + var URL = "playground/src/web_workers/todo/index.html"; it('should bootstrap', () => { // This test can't wait for Angular 2 as Testability is not available when using WebWorker @@ -14,11 +14,11 @@ describe('WebWorkers Todo', function() { browser.get(URL); waitForBootstrap(); - expect(element(by.css('#todoapp header')).getText()).toEqual('todos'); + expect(element(by.css("#todoapp header")).getText()).toEqual("todos"); }); }); function waitForBootstrap(): void { - browser.wait(protractor.until.elementLocated(by.css('todo-app #todoapp')), 15000); + browser.wait(protractor.until.elementLocated(by.css("todo-app #todoapp")), 15000); } diff --git a/modules/playground/src/hash_routing/index.ts b/modules/playground/src/hash_routing/index.ts index 540dcff1cb..94f24135bf 100644 --- a/modules/playground/src/hash_routing/index.ts +++ b/modules/playground/src/hash_routing/index.ts @@ -1,6 +1,13 @@ import {Component, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {RouteConfig, Route, ROUTER_PROVIDERS, ROUTER_DIRECTIVES, HashLocationStrategy, LocationStrategy} from 'angular2/router'; +import { + RouteConfig, + Route, + ROUTER_PROVIDERS, + ROUTER_DIRECTIVES, + HashLocationStrategy, + LocationStrategy +} from 'angular2/router'; @Component({selector: 'hello-cmp', template: `hello`}) @@ -37,6 +44,6 @@ class AppCmp { export function main() { - bootstrap( - AppCmp, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]); + bootstrap(AppCmp, + [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]); } diff --git a/modules/playground/src/model_driven_forms/index.ts b/modules/playground/src/model_driven_forms/index.ts index 04b5c39e2f..73a6a865dd 100644 --- a/modules/playground/src/model_driven_forms/index.ts +++ b/modules/playground/src/model_driven_forms/index.ts @@ -1,5 +1,14 @@ import {bootstrap} from 'angular2/platform/browser'; -import {FORM_DIRECTIVES, ControlGroup, NgControl, Validators, NgFormModel, FormBuilder, NgIf, NgFor} from 'angular2/common'; +import { + FORM_DIRECTIVES, + ControlGroup, + NgControl, + Validators, + NgFormModel, + FormBuilder, + NgIf, + NgFor +} from 'angular2/common'; import {Component, Directive, Host} from 'angular2/core'; import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang'; @@ -12,7 +21,7 @@ function creditCardValidator(c: AbstractControl): {[key: string]: boolean} { if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) { return null; } else { - return {'invalidCreditCard': true}; + return {"invalidCreditCard": true}; } } @@ -132,19 +141,19 @@ class ModelDrivenForms { constructor(fb: FormBuilder) { this.form = fb.group({ - 'firstName': ['', Validators.required], - 'middleName': [''], - 'lastName': ['', Validators.required], - 'country': ['Canada', Validators.required], - 'creditCard': ['', Validators.compose([Validators.required, creditCardValidator])], - 'amount': [0, Validators.required], - 'email': ['', Validators.required], - 'comments': [''] + "firstName": ["", Validators.required], + "middleName": [""], + "lastName": ["", Validators.required], + "country": ["Canada", Validators.required], + "creditCard": ["", Validators.compose([Validators.required, creditCardValidator])], + "amount": [0, Validators.required], + "email": ["", Validators.required], + "comments": [""] }); } onSubmit(): void { - print('Submitting:'); + print("Submitting:"); print(this.form.value); } } diff --git a/modules/playground/src/order_management/index.ts b/modules/playground/src/order_management/index.ts index 29c750c692..96a344703f 100644 --- a/modules/playground/src/order_management/index.ts +++ b/modules/playground/src/order_management/index.ts @@ -1,5 +1,15 @@ import {bootstrap} from 'angular2/platform/browser'; -import {Component, Directive, Host, forwardRef, Provider, EventEmitter, Injectable, Input, Output} from 'angular2/core'; +import { + Component, + Directive, + Host, + forwardRef, + Provider, + EventEmitter, + Injectable, + Input, + Output +} from 'angular2/core'; import {NgIf, NgFor, FORM_DIRECTIVES} from 'angular2/common'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -12,17 +22,15 @@ import {ListWrapper} from 'angular2/src/facade/collection'; // ---- model class OrderItem { - constructor( - public orderItemId: number, public orderId: number, public productName: string, - public qty: number, public unitPrice: number) {} + constructor(public orderItemId: number, public orderId: number, public productName: string, + public qty: number, public unitPrice: number) {} get total(): number { return this.qty * this.unitPrice; } } class Order { - constructor( - public orderId: number, public customerName: string, public limit: number, - private _dataService: DataService) {} + constructor(public orderId: number, public customerName: string, public limit: number, + private _dataService: DataService) {} get items(): OrderItem[] { return this._dataService.itemsFor(this); } get total(): number { return this.items.map(i => i.total).reduce((a, b) => a + b, 0); } @@ -41,16 +49,17 @@ class DataService { constructor() { this.orders = [ - new Order(_nextId++, 'J. Coltrane', 100, this), new Order(_nextId++, 'B. Evans', 200, this) + new Order(_nextId++, "J. Coltrane", 100, this), + new Order(_nextId++, "B. Evans", 200, this) ]; this.orderItems = [ - new OrderItem(_nextId++, this.orders[0].orderId, 'Bread', 5, 1), - new OrderItem(_nextId++, this.orders[0].orderId, 'Brie', 5, 2), - new OrderItem(_nextId++, this.orders[0].orderId, 'IPA', 5, 3), + new OrderItem(_nextId++, this.orders[0].orderId, "Bread", 5, 1), + new OrderItem(_nextId++, this.orders[0].orderId, "Brie", 5, 2), + new OrderItem(_nextId++, this.orders[0].orderId, "IPA", 5, 3), - new OrderItem(_nextId++, this.orders[1].orderId, 'Mozzarella', 5, 2), - new OrderItem(_nextId++, this.orders[1].orderId, 'Wine', 5, 3) + new OrderItem(_nextId++, this.orders[1].orderId, "Mozzarella", 5, 2), + new OrderItem(_nextId++, this.orders[1].orderId, "Wine", 5, 3) ]; } @@ -59,7 +68,7 @@ class DataService { } addItemForOrder(order: Order): void { - this.orderItems.push(new OrderItem(_nextId++, order.orderId, '', 0, 0)); + this.orderItems.push(new OrderItem(_nextId++, order.orderId, "", 0, 0)); } deleteItem(item: OrderItem): void { ListWrapper.remove(this.orderItems, item); } diff --git a/modules/playground/src/person_management/index.ts b/modules/playground/src/person_management/index.ts index aaa4444df4..81419a7244 100644 --- a/modules/playground/src/person_management/index.ts +++ b/modules/playground/src/person_management/index.ts @@ -45,11 +45,16 @@ class DataService { constructor() { this.persons = [ - new Person('Victor', 'Savkin', 1930), new Person('Igor', 'Minar', 1920), - new Person('John', 'Papa', 1910), new Person('Nancy', 'Duarte', 1910), - new Person('Jack', 'Papa', 1910), new Person('Jill', 'Papa', 1910), - new Person('Ward', 'Bell', 1910), new Person('Robert', 'Bell', 1910), - new Person('Tracy', 'Ward', 1910), new Person('Dan', 'Wahlin', 1910) + new Person('Victor', 'Savkin', 1930), + new Person('Igor', 'Minar', 1920), + new Person('John', 'Papa', 1910), + new Person('Nancy', 'Duarte', 1910), + new Person('Jack', 'Papa', 1910), + new Person('Jill', 'Papa', 1910), + new Person('Ward', 'Bell', 1910), + new Person('Robert', 'Bell', 1910), + new Person('Tracy', 'Ward', 1910), + new Person('Dan', 'Wahlin', 1910) ]; this.persons[0].friends = [0, 1, 2, 6, 9].map(_ => this.persons[_]); diff --git a/modules/playground/src/routing/data.ts b/modules/playground/src/routing/data.ts index 2234c1084f..a984dd6ea3 100644 --- a/modules/playground/src/routing/data.ts +++ b/modules/playground/src/routing/data.ts @@ -1,2116 +1,2116 @@ export var data = [ { - 'id': '1', - 'first-name': 'Montana', - 'last-name': 'Prosacco', - 'email': 'jairo.bergnaum@bergnaum.org', - 'date': '1991-10-12 15:12:46 -0700', - 'content': - 'Et quisquam veniam voluptatem enim temporibus itaque. Ipsam voluptatem et. Occaecati rerum animi.', - 'subject': 'Quidem quo ipsam architecto soluta numquam et' + "id": "1", + "first-name": "Montana", + "last-name": "Prosacco", + "email": "jairo.bergnaum@bergnaum.org", + "date": "1991-10-12 15:12:46 -0700", + "content": + "Et quisquam veniam voluptatem enim temporibus itaque. Ipsam voluptatem et. Occaecati rerum animi.", + "subject": "Quidem quo ipsam architecto soluta numquam et" }, { - 'id': '2', - 'first-name': 'Frances', - 'last-name': 'Schaden', - 'email': 'pierre_tromp@adams.com', - 'date': '2001-05-06 08:22:33 -0700', - 'content': 'Porro ea tempore numquam deserunt voluptas qui. Est quis suscipit.', - 'subject': 'Voluptatibus dolore porro animi' + "id": "2", + "first-name": "Frances", + "last-name": "Schaden", + "email": "pierre_tromp@adams.com", + "date": "2001-05-06 08:22:33 -0700", + "content": "Porro ea tempore numquam deserunt voluptas qui. Est quis suscipit.", + "subject": "Voluptatibus dolore porro animi" }, { - 'id': '3', - 'first-name': 'Jayne', - 'last-name': 'Kreiger', - 'email': 'breanne@howell.net', - 'date': '2001-05-22 14:28:41 -0700', - 'content': 'Voluptas et est laborum non ullam.', - 'subject': 'Ratione ut illum fuga non' + "id": "3", + "first-name": "Jayne", + "last-name": "Kreiger", + "email": "breanne@howell.net", + "date": "2001-05-22 14:28:41 -0700", + "content": "Voluptas et est laborum non ullam.", + "subject": "Ratione ut illum fuga non" }, { - 'id': '4', - 'first-name': 'Hester', - 'last-name': 'Wyman', - 'email': 'fausto@steuber.com', - 'date': '1996-07-20 02:13:12 -0700', - 'content': - 'Iusto enim laborum. Autem sed quas laborum deserunt quibusdam dolorem. Laboriosam nesciunt debitis possimus ut aut quae.', - 'subject': 'Ea quas et quia beatae dolores' + "id": "4", + "first-name": "Hester", + "last-name": "Wyman", + "email": "fausto@steuber.com", + "date": "1996-07-20 02:13:12 -0700", + "content": + "Iusto enim laborum. Autem sed quas laborum deserunt quibusdam dolorem. Laboriosam nesciunt debitis possimus ut aut quae.", + "subject": "Ea quas et quia beatae dolores" }, { - 'id': '5', - 'first-name': 'Alexandre', - 'last-name': 'Dietrich', - 'email': 'carmella_mante@moendibbert.biz', - 'date': '2006-03-20 23:44:38 -0800', - 'content': 'Voluptates voluptatem dolorem non quod dolores.', - 'subject': 'Nostrum ad modi non consequatur repellendus et harum' + "id": "5", + "first-name": "Alexandre", + "last-name": "Dietrich", + "email": "carmella_mante@moendibbert.biz", + "date": "2006-03-20 23:44:38 -0800", + "content": "Voluptates voluptatem dolorem non quod dolores.", + "subject": "Nostrum ad modi non consequatur repellendus et harum" }, { - 'id': '6', - 'first-name': 'Ena', - 'last-name': 'Green', - 'email': 'jan_koepp@glover.name', - 'date': '1988-03-21 02:00:36 -0800', - 'content': - 'Nam inventore voluptatum eaque ratione nisi nesciunt. Qui ex qui omnis aliquid. Dolorem ipsum expedita.', - 'subject': 'Qui sint vero accusamus quam id vitae quis quia' + "id": "6", + "first-name": "Ena", + "last-name": "Green", + "email": "jan_koepp@glover.name", + "date": "1988-03-21 02:00:36 -0800", + "content": + "Nam inventore voluptatum eaque ratione nisi nesciunt. Qui ex qui omnis aliquid. Dolorem ipsum expedita.", + "subject": "Qui sint vero accusamus quam id vitae quis quia" }, { - 'id': '7', - 'first-name': 'Rebecca', - 'last-name': 'Walsh', - 'email': 'marta@mueller.biz', - 'date': '1974-05-09 02:40:20 -0700', - 'content': - 'Voluptas vel ut. Rerum vero repellat accusantium earum. Ea atque exercitationem expedita id dolores dolorem.', - 'subject': 'Suscipit et inventore exercitationem ut voluptatum esse vero' + "id": "7", + "first-name": "Rebecca", + "last-name": "Walsh", + "email": "marta@mueller.biz", + "date": "1974-05-09 02:40:20 -0700", + "content": + "Voluptas vel ut. Rerum vero repellat accusantium earum. Ea atque exercitationem expedita id dolores dolorem.", + "subject": "Suscipit et inventore exercitationem ut voluptatum esse vero" }, { - 'id': '8', - 'first-name': 'Jed', - 'last-name': 'Rogahn', - 'email': 'talia_crist@mertzfadel.info', - 'date': '2006-10-17 01:28:46 -0700', - 'content': 'Cupiditate nam blanditiis.', - 'subject': 'Dolore nulla qui sequi ut enim sed' + "id": "8", + "first-name": "Jed", + "last-name": "Rogahn", + "email": "talia_crist@mertzfadel.info", + "date": "2006-10-17 01:28:46 -0700", + "content": "Cupiditate nam blanditiis.", + "subject": "Dolore nulla qui sequi ut enim sed" }, { - 'id': '9', - 'first-name': 'Fabiola', - 'last-name': 'Olson', - 'email': 'henderson@casper.org', - 'date': '2008-02-29 11:46:44 -0800', - 'content': - 'Similique nesciunt omnis beatae omnis pariatur quas. Voluptatem eum consequatur id impedit fugit dignissimos ut.', - 'subject': 'Sit quasi accusamus aut et eum' + "id": "9", + "first-name": "Fabiola", + "last-name": "Olson", + "email": "henderson@casper.org", + "date": "2008-02-29 11:46:44 -0800", + "content": + "Similique nesciunt omnis beatae omnis pariatur quas. Voluptatem eum consequatur id impedit fugit dignissimos ut.", + "subject": "Sit quasi accusamus aut et eum" }, { - 'id': '10', - 'first-name': 'Alex', - 'last-name': 'Turcotte', - 'email': 'mya@stokes.org', - 'date': '1974-03-29 12:02:53 -0700', - 'content': - 'Ut pariatur porro maiores. Saepe soluta aspernatur est sed suscipit. Excepturi incidunt aut atque nostrum cum non.', - 'subject': 'Rerum dolore sunt veniam provident' + "id": "10", + "first-name": "Alex", + "last-name": "Turcotte", + "email": "mya@stokes.org", + "date": "1974-03-29 12:02:53 -0700", + "content": + "Ut pariatur porro maiores. Saepe soluta aspernatur est sed suscipit. Excepturi incidunt aut atque nostrum cum non.", + "subject": "Rerum dolore sunt veniam provident" }, { - 'id': '11', - 'first-name': 'Jerome', - 'last-name': 'Greenholt', - 'email': 'jazmyne.dibbert@abshire.org', - 'date': '1997-01-12 02:48:08 -0800', - 'content': 'Natus error id.', - 'subject': 'Rerum nemo aperiam veritatis veniam' + "id": "11", + "first-name": "Jerome", + "last-name": "Greenholt", + "email": "jazmyne.dibbert@abshire.org", + "date": "1997-01-12 02:48:08 -0800", + "content": "Natus error id.", + "subject": "Rerum nemo aperiam veritatis veniam" }, { - 'id': '12', - 'first-name': 'Antwan', - 'last-name': 'Kreiger', - 'email': 'delilah@dibbert.name', - 'date': '1971-05-08 10:45:01 -0700', - 'content': - 'Perspiciatis sed quo. Eum dignissimos quia expedita dolorem illum minima enim. Fugiat ducimus nostrum quia reiciendis autem nisi placeat.', - 'subject': 'Esse ipsum pariatur voluptatum rerum labore id odit' + "id": "12", + "first-name": "Antwan", + "last-name": "Kreiger", + "email": "delilah@dibbert.name", + "date": "1971-05-08 10:45:01 -0700", + "content": + "Perspiciatis sed quo. Eum dignissimos quia expedita dolorem illum minima enim. Fugiat ducimus nostrum quia reiciendis autem nisi placeat.", + "subject": "Esse ipsum pariatur voluptatum rerum labore id odit" }, { - 'id': '13', - 'first-name': 'Kyleigh', - 'last-name': 'Rogahn', - 'email': 'ralph_ledner@bartolettifay.info', - 'date': '2013-11-28 16:10:15 -0800', - 'content': 'Molestias repudiandae dicta vel.', - 'subject': 'Facilis occaecati pariatur qui incidunt reprehenderit sunt' + "id": "13", + "first-name": "Kyleigh", + "last-name": "Rogahn", + "email": "ralph_ledner@bartolettifay.info", + "date": "2013-11-28 16:10:15 -0800", + "content": "Molestias repudiandae dicta vel.", + "subject": "Facilis occaecati pariatur qui incidunt reprehenderit sunt" }, { - 'id': '14', - 'first-name': 'Henriette', - 'last-name': 'Gottlieb', - 'email': 'adeline.rowe@lubowitz.net', - 'date': '1983-02-11 06:45:49 -0800', - 'content': 'Eveniet ut voluptas eos ut rerum voluptatum.', - 'subject': 'Natus voluptas voluptatem alias' + "id": "14", + "first-name": "Henriette", + "last-name": "Gottlieb", + "email": "adeline.rowe@lubowitz.net", + "date": "1983-02-11 06:45:49 -0800", + "content": "Eveniet ut voluptas eos ut rerum voluptatum.", + "subject": "Natus voluptas voluptatem alias" }, { - 'id': '15', - 'first-name': 'Jacklyn', - 'last-name': 'White', - 'email': 'milton_keebler@braun.biz', - 'date': '1992-01-07 12:27:59 -0800', - 'content': 'Reiciendis et aperiam. Doloremque totam repudiandae velit fuga fugiat.', - 'subject': 'Nulla est magnam ducimus porro commodi' + "id": "15", + "first-name": "Jacklyn", + "last-name": "White", + "email": "milton_keebler@braun.biz", + "date": "1992-01-07 12:27:59 -0800", + "content": "Reiciendis et aperiam. Doloremque totam repudiandae velit fuga fugiat.", + "subject": "Nulla est magnam ducimus porro commodi" }, { - 'id': '16', - 'first-name': 'Charlotte', - 'last-name': 'Ziemann', - 'email': 'brett@purdymills.com', - 'date': '1972-06-06 02:42:50 -0700', - 'content': - 'Voluptatem corporis tempore. Consectetur fugit perspiciatis libero dolore consequatur asperiores. Voluptates ea accusamus.', - 'subject': 'Ea adipisci reiciendis excepturi suscipit necessitatibus ut sed' + "id": "16", + "first-name": "Charlotte", + "last-name": "Ziemann", + "email": "brett@purdymills.com", + "date": "1972-06-06 02:42:50 -0700", + "content": + "Voluptatem corporis tempore. Consectetur fugit perspiciatis libero dolore consequatur asperiores. Voluptates ea accusamus.", + "subject": "Ea adipisci reiciendis excepturi suscipit necessitatibus ut sed" }, { - 'id': '17', - 'first-name': 'Giovanny', - 'last-name': 'Runolfsdottir', - 'email': 'dustin.sanford@rippin.com', - 'date': '1987-04-14 19:29:11 -0700', - 'content': - 'Dolor consequuntur sed aspernatur qui. Sit cumque id animi ut sed id. Asperiores voluptatem similique voluptas.', - 'subject': 'Id ut voluptatum culpa molestiae quo' + "id": "17", + "first-name": "Giovanny", + "last-name": "Runolfsdottir", + "email": "dustin.sanford@rippin.com", + "date": "1987-04-14 19:29:11 -0700", + "content": + "Dolor consequuntur sed aspernatur qui. Sit cumque id animi ut sed id. Asperiores voluptatem similique voluptas.", + "subject": "Id ut voluptatum culpa molestiae quo" }, { - 'id': '18', - 'first-name': 'Savion', - 'last-name': 'McCullough', - 'email': 'don@gorczanysimonis.name', - 'date': '1974-01-18 14:40:40 -0700', - 'content': - 'Autem voluptatem dignissimos vel debitis ipsum voluptatem consequuntur. Voluptatum et saepe.', - 'subject': 'Ipsa similique quo nostrum' + "id": "18", + "first-name": "Savion", + "last-name": "McCullough", + "email": "don@gorczanysimonis.name", + "date": "1974-01-18 14:40:40 -0700", + "content": + "Autem voluptatem dignissimos vel debitis ipsum voluptatem consequuntur. Voluptatum et saepe.", + "subject": "Ipsa similique quo nostrum" }, { - 'id': '19', - 'first-name': 'Robbie', - 'last-name': 'Kohler', - 'email': 'haley@waters.biz', - 'date': '2002-09-28 08:35:10 -0700', - 'content': - 'Quo ut accusantium similique necessitatibus. Sunt impedit commodi ut et odit voluptatibus error.', - 'subject': 'Voluptate eum quo error' + "id": "19", + "first-name": "Robbie", + "last-name": "Kohler", + "email": "haley@waters.biz", + "date": "2002-09-28 08:35:10 -0700", + "content": + "Quo ut accusantium similique necessitatibus. Sunt impedit commodi ut et odit voluptatibus error.", + "subject": "Voluptate eum quo error" }, { - 'id': '20', - 'first-name': 'Eulalia', - 'last-name': 'Effertz', - 'email': 'rodrigo_parisian@bergecartwright.net', - 'date': '2006-07-29 21:47:56 -0700', - 'content': - 'Eum repudiandae rem aliquid dolorum suscipit vel. Autem vel voluptas et iure magni.', - 'subject': 'Est dolorum modi et error consequuntur qui' + "id": "20", + "first-name": "Eulalia", + "last-name": "Effertz", + "email": "rodrigo_parisian@bergecartwright.net", + "date": "2006-07-29 21:47:56 -0700", + "content": + "Eum repudiandae rem aliquid dolorum suscipit vel. Autem vel voluptas et iure magni.", + "subject": "Est dolorum modi et error consequuntur qui" }, { - 'id': '21', - 'first-name': 'Gregoria', - 'last-name': 'Boehm', - 'email': 'miles@jerde.org', - 'date': '1997-04-11 19:49:38 -0700', - 'content': - 'Qui necessitatibus veniam. Maiores impedit in natus aspernatur adipisci. Ad sapiente iste.', - 'subject': 'Doloribus ipsum a eius voluptatem nulla' + "id": "21", + "first-name": "Gregoria", + "last-name": "Boehm", + "email": "miles@jerde.org", + "date": "1997-04-11 19:49:38 -0700", + "content": + "Qui necessitatibus veniam. Maiores impedit in natus aspernatur adipisci. Ad sapiente iste.", + "subject": "Doloribus ipsum a eius voluptatem nulla" }, { - 'id': '22', - 'first-name': 'Berry', - 'last-name': 'Collier', - 'email': 'larry_rath@rathbernier.info', - 'date': '1981-06-26 05:26:47 -0700', - 'content': - 'Numquam rerum quia similique enim sequi eos inventore. Numquam inventore aliquam commodi neque maiores. Hic et vel aut velit corrupti.', - 'subject': 'Optio ab delectus pariatur vel tempore' + "id": "22", + "first-name": "Berry", + "last-name": "Collier", + "email": "larry_rath@rathbernier.info", + "date": "1981-06-26 05:26:47 -0700", + "content": + "Numquam rerum quia similique enim sequi eos inventore. Numquam inventore aliquam commodi neque maiores. Hic et vel aut velit corrupti.", + "subject": "Optio ab delectus pariatur vel tempore" }, { - 'id': '23', - 'first-name': 'Crawford', - 'last-name': 'Ryan', - 'email': 'cindy_ziemann@harvey.org', - 'date': '1997-06-12 07:56:32 -0700', - 'content': 'Odio ea nostrum molestiae. Doloribus ducimus occaecati facilis pariatur ut est.', - 'subject': 'Quo fugit at totam voluptate est' + "id": "23", + "first-name": "Crawford", + "last-name": "Ryan", + "email": "cindy_ziemann@harvey.org", + "date": "1997-06-12 07:56:32 -0700", + "content": "Odio ea nostrum molestiae. Doloribus ducimus occaecati facilis pariatur ut est.", + "subject": "Quo fugit at totam voluptate est" }, { - 'id': '24', - 'first-name': 'Kelsie', - 'last-name': 'Stokes', - 'email': 'jackson_ferry@connelly.name', - 'date': '1986-07-30 21:39:50 -0700', - 'content': - 'Amet voluptatem ea nesciunt sunt. Quidem pariatur sit. Minus aliquam itaque laudantium in quibusdam laboriosam.', - 'subject': 'Labore voluptas dolor repellendus accusantium tempora' + "id": "24", + "first-name": "Kelsie", + "last-name": "Stokes", + "email": "jackson_ferry@connelly.name", + "date": "1986-07-30 21:39:50 -0700", + "content": + "Amet voluptatem ea nesciunt sunt. Quidem pariatur sit. Minus aliquam itaque laudantium in quibusdam laboriosam.", + "subject": "Labore voluptas dolor repellendus accusantium tempora" }, { - 'id': '25', - 'first-name': 'Josefa', - 'last-name': 'Predovic', - 'email': 'moises@sauer.info', - 'date': '1976-04-09 22:38:31 -0800', - 'content': - 'Aliquam consectetur et non soluta. Quia dolore molestiae facilis eos nihil vel. Quidem eos et.', - 'subject': 'Qui architecto inventore alias non aut dolorum porro' + "id": "25", + "first-name": "Josefa", + "last-name": "Predovic", + "email": "moises@sauer.info", + "date": "1976-04-09 22:38:31 -0800", + "content": + "Aliquam consectetur et non soluta. Quia dolore molestiae facilis eos nihil vel. Quidem eos et.", + "subject": "Qui architecto inventore alias non aut dolorum porro" }, { - 'id': '26', - 'first-name': 'Toby', - 'last-name': 'Wehner', - 'email': 'janet@mohr.org', - 'date': '2003-05-08 07:44:26 -0700', - 'content': 'Suscipit cumque alias debitis necessitatibus et qui.', - 'subject': 'Possimus laudantium exercitationem ut deleniti similique' + "id": "26", + "first-name": "Toby", + "last-name": "Wehner", + "email": "janet@mohr.org", + "date": "2003-05-08 07:44:26 -0700", + "content": "Suscipit cumque alias debitis necessitatibus et qui.", + "subject": "Possimus laudantium exercitationem ut deleniti similique" }, { - 'id': '27', - 'first-name': 'Keira', - 'last-name': 'Stamm', - 'email': 'karlie@witting.info', - 'date': '2010-11-11 16:17:29 -0800', - 'content': - 'Rerum cum at autem repellat quod nihil. Quasi voluptates minus autem accusantium debitis cumque qui.', - 'subject': 'Nostrum repudiandae voluptatum adipisci ut error sunt et sint' + "id": "27", + "first-name": "Keira", + "last-name": "Stamm", + "email": "karlie@witting.info", + "date": "2010-11-11 16:17:29 -0800", + "content": + "Rerum cum at autem repellat quod nihil. Quasi voluptates minus autem accusantium debitis cumque qui.", + "subject": "Nostrum repudiandae voluptatum adipisci ut error sunt et sint" }, { - 'id': '28', - 'first-name': 'Clark', - 'last-name': 'Predovic', - 'email': 'palma@ankundingbednar.biz', - 'date': '1978-02-10 16:55:54 -0800', - 'content': - 'Non ex aperiam porro. At harum vitae ut exercitationem qui qui. Quae sed sapiente sed debitis officiis quis unde.', - 'subject': 'Eos eligendi voluptatum consequatur reprehenderit' + "id": "28", + "first-name": "Clark", + "last-name": "Predovic", + "email": "palma@ankundingbednar.biz", + "date": "1978-02-10 16:55:54 -0800", + "content": + "Non ex aperiam porro. At harum vitae ut exercitationem qui qui. Quae sed sapiente sed debitis officiis quis unde.", + "subject": "Eos eligendi voluptatum consequatur reprehenderit" }, { - 'id': '29', - 'first-name': 'Colby', - 'last-name': 'Jacobson', - 'email': 'rozella@spencer.com', - 'date': '1978-01-04 00:18:51 -0800', - 'content': - 'Molestiae laudantium voluptas ipsa est laborum vel. Dolorem et est nihil distinctio numquam.', - 'subject': 'Aut et sint deleniti mollitia debitis' + "id": "29", + "first-name": "Colby", + "last-name": "Jacobson", + "email": "rozella@spencer.com", + "date": "1978-01-04 00:18:51 -0800", + "content": + "Molestiae laudantium voluptas ipsa est laborum vel. Dolorem et est nihil distinctio numquam.", + "subject": "Aut et sint deleniti mollitia debitis" }, { - 'id': '30', - 'first-name': 'Kayley', - 'last-name': 'Connelly', - 'email': 'rowland.thiel@gutmannorn.info', - 'date': '2012-12-10 09:59:08 -0800', - 'content': - 'Eligendi quia repellat distinctio eum voluptas debitis. Totam a alias qui voluptates dolor.', - 'subject': 'Ipsum consequatur culpa repellat quae mollitia quia unde' + "id": "30", + "first-name": "Kayley", + "last-name": "Connelly", + "email": "rowland.thiel@gutmannorn.info", + "date": "2012-12-10 09:59:08 -0800", + "content": + "Eligendi quia repellat distinctio eum voluptas debitis. Totam a alias qui voluptates dolor.", + "subject": "Ipsum consequatur culpa repellat quae mollitia quia unde" }, { - 'id': '31', - 'first-name': 'Kay', - 'last-name': 'Reynolds', - 'email': 'lexie.frami@beattyschoen.info', - 'date': '1991-05-27 22:37:41 -0700', - 'content': - 'Laborum quod iusto in voluptas et adipisci dolor. Totam et voluptatibus id tempora. Asperiores magnam dolorem quo iste sapiente.', - 'subject': 'Tempora et eligendi quia dolorem alias ullam maiores doloremque' + "id": "31", + "first-name": "Kay", + "last-name": "Reynolds", + "email": "lexie.frami@beattyschoen.info", + "date": "1991-05-27 22:37:41 -0700", + "content": + "Laborum quod iusto in voluptas et adipisci dolor. Totam et voluptatibus id tempora. Asperiores magnam dolorem quo iste sapiente.", + "subject": "Tempora et eligendi quia dolorem alias ullam maiores doloremque" }, { - 'id': '32', - 'first-name': 'Ellsworth', - 'last-name': 'Veum', - 'email': 'estefania_hermann@murray.biz', - 'date': '1974-12-07 03:43:52 -0800', - 'content': - 'Et commodi molestiae hic distinctio et iusto. Quod illo natus unde est aut. Laborum rem rerum totam.', - 'subject': 'Expedita nostrum consectetur sint velit modi maxime quisquam' + "id": "32", + "first-name": "Ellsworth", + "last-name": "Veum", + "email": "estefania_hermann@murray.biz", + "date": "1974-12-07 03:43:52 -0800", + "content": + "Et commodi molestiae hic distinctio et iusto. Quod illo natus unde est aut. Laborum rem rerum totam.", + "subject": "Expedita nostrum consectetur sint velit modi maxime quisquam" }, { - 'id': '33', - 'first-name': 'Adeline', - 'last-name': 'Altenwerth', - 'email': 'francesco@weberstroman.com', - 'date': '1988-03-25 22:52:39 -0800', - 'content': - 'Quod deserunt eum dignissimos eius et veniam. Non exercitationem omnis molestiae corrupti aliquid commodi repudiandae.', - 'subject': 'Dolor incidunt debitis possimus temporibus rerum quibusdam eaque' + "id": "33", + "first-name": "Adeline", + "last-name": "Altenwerth", + "email": "francesco@weberstroman.com", + "date": "1988-03-25 22:52:39 -0800", + "content": + "Quod deserunt eum dignissimos eius et veniam. Non exercitationem omnis molestiae corrupti aliquid commodi repudiandae.", + "subject": "Dolor incidunt debitis possimus temporibus rerum quibusdam eaque" }, { - 'id': '34', - 'first-name': 'River', - 'last-name': 'Roob', - 'email': 'lester.hodkiewicz@hoppemcglynn.name', - 'date': '1981-01-03 06:04:53 -0800', - 'content': - 'Sed dolorem et laborum voluptate perspiciatis doloremque aliquam. Recusandae et odit. Sit esse consequatur occaecati fuga sed.', - 'subject': 'Dolorem ut quia repudiandae accusamus reprehenderit dignissimos iste cupiditate' + "id": "34", + "first-name": "River", + "last-name": "Roob", + "email": "lester.hodkiewicz@hoppemcglynn.name", + "date": "1981-01-03 06:04:53 -0800", + "content": + "Sed dolorem et laborum voluptate perspiciatis doloremque aliquam. Recusandae et odit. Sit esse consequatur occaecati fuga sed.", + "subject": "Dolorem ut quia repudiandae accusamus reprehenderit dignissimos iste cupiditate" }, { - 'id': '35', - 'first-name': 'Chaya', - 'last-name': 'Stokes', - 'email': 'rebekah.baumbach@toy.org', - 'date': '1979-09-03 07:52:52 -0700', - 'content': 'Ea voluptas minus hic omnis.', - 'subject': 'Ab repellendus quia eos eius' + "id": "35", + "first-name": "Chaya", + "last-name": "Stokes", + "email": "rebekah.baumbach@toy.org", + "date": "1979-09-03 07:52:52 -0700", + "content": "Ea voluptas minus hic omnis.", + "subject": "Ab repellendus quia eos eius" }, { - 'id': '36', - 'first-name': 'Cara', - 'last-name': 'Brown', - 'email': 'natasha_gibson@bins.name', - 'date': '1985-12-19 03:29:37 -0800', - 'content': - 'Numquam nobis consectetur modi eligendi. Facere adipisci aut velit quis dolor quidem totam. Consequatur qui placeat aut molestiae dignissimos.', - 'subject': 'Est quia reiciendis enim et totam temporibus' + "id": "36", + "first-name": "Cara", + "last-name": "Brown", + "email": "natasha_gibson@bins.name", + "date": "1985-12-19 03:29:37 -0800", + "content": + "Numquam nobis consectetur modi eligendi. Facere adipisci aut velit quis dolor quidem totam. Consequatur qui placeat aut molestiae dignissimos.", + "subject": "Est quia reiciendis enim et totam temporibus" }, { - 'id': '37', - 'first-name': 'Laron', - 'last-name': 'Wunsch', - 'email': 'erna@heathcote.com', - 'date': '2004-06-28 16:53:07 -0700', - 'content': - 'Quisquam maxime nostrum explicabo corrupti ut. Et accusantium culpa occaecati officiis quo.', - 'subject': 'Et et nulla aspernatur quas distinctio' + "id": "37", + "first-name": "Laron", + "last-name": "Wunsch", + "email": "erna@heathcote.com", + "date": "2004-06-28 16:53:07 -0700", + "content": + "Quisquam maxime nostrum explicabo corrupti ut. Et accusantium culpa occaecati officiis quo.", + "subject": "Et et nulla aspernatur quas distinctio" }, { - 'id': '38', - 'first-name': 'Lessie', - 'last-name': 'Roob', - 'email': 'ona_olson@dicki.biz', - 'date': '1980-02-10 00:18:48 -0800', - 'content': - 'Facere veritatis aut quam praesentium ut. Consectetur praesentium explicabo consequuntur quia vel rem.', - 'subject': 'Tenetur ducimus mollitia consequatur dicta' + "id": "38", + "first-name": "Lessie", + "last-name": "Roob", + "email": "ona_olson@dicki.biz", + "date": "1980-02-10 00:18:48 -0800", + "content": + "Facere veritatis aut quam praesentium ut. Consectetur praesentium explicabo consequuntur quia vel rem.", + "subject": "Tenetur ducimus mollitia consequatur dicta" }, { - 'id': '39', - 'first-name': 'Felton', - 'last-name': 'Labadie', - 'email': 'stone.kihn@vonruedenbartoletti.biz', - 'date': '2002-04-04 17:29:31 -0800', - 'content': - 'Iure ad nesciunt. Excepturi impedit eum suscipit dignissimos est. Corrupti accusamus sapiente ratione eaque iure aut mollitia.', - 'subject': 'Sunt et eius et iusto accusamus voluptas eum' + "id": "39", + "first-name": "Felton", + "last-name": "Labadie", + "email": "stone.kihn@vonruedenbartoletti.biz", + "date": "2002-04-04 17:29:31 -0800", + "content": + "Iure ad nesciunt. Excepturi impedit eum suscipit dignissimos est. Corrupti accusamus sapiente ratione eaque iure aut mollitia.", + "subject": "Sunt et eius et iusto accusamus voluptas eum" }, { - 'id': '40', - 'first-name': 'Verna', - 'last-name': 'Hoppe', - 'email': 'arthur_schiller@daniel.org', - 'date': '2013-05-15 16:04:25 -0700', - 'content': - 'Veniam quia omnis at sapiente. Est est fugit eum. Impedit suscipit hic similique eum quibusdam.', - 'subject': 'Voluptatum ipsum libero et vitae odio dolore tenetur perspiciatis' + "id": "40", + "first-name": "Verna", + "last-name": "Hoppe", + "email": "arthur_schiller@daniel.org", + "date": "2013-05-15 16:04:25 -0700", + "content": + "Veniam quia omnis at sapiente. Est est fugit eum. Impedit suscipit hic similique eum quibusdam.", + "subject": "Voluptatum ipsum libero et vitae odio dolore tenetur perspiciatis" }, { - 'id': '41', - 'first-name': 'Velda', - 'last-name': 'Veum', - 'email': 'christy@feil.org', - 'date': '1988-10-24 12:42:25 -0700', - 'content': 'Rem inventore necessitatibus iste et quia vero laudantium.', - 'subject': 'Suscipit similique provident officia est explicabo sed' + "id": "41", + "first-name": "Velda", + "last-name": "Veum", + "email": "christy@feil.org", + "date": "1988-10-24 12:42:25 -0700", + "content": "Rem inventore necessitatibus iste et quia vero laudantium.", + "subject": "Suscipit similique provident officia est explicabo sed" }, { - 'id': '42', - 'first-name': 'Mackenzie', - 'last-name': 'Schroeder', - 'email': 'miles.dietrich@stehrkuhic.org', - 'date': '1990-01-07 22:38:09 -0800', - 'content': 'Non autem delectus. Architecto recusandae unde quia rerum inventore repudiandae.', - 'subject': 'Molestiae odio et repudiandae ut' + "id": "42", + "first-name": "Mackenzie", + "last-name": "Schroeder", + "email": "miles.dietrich@stehrkuhic.org", + "date": "1990-01-07 22:38:09 -0800", + "content": "Non autem delectus. Architecto recusandae unde quia rerum inventore repudiandae.", + "subject": "Molestiae odio et repudiandae ut" }, { - 'id': '43', - 'first-name': 'Natalie', - 'last-name': 'Hoeger', - 'email': 'gregorio_mosciski@schneiderframi.net', - 'date': '1976-04-06 06:23:07 -0800', - 'content': - 'Iste id illo cupiditate enim aut quo. Vel ut eos qui. Aut at in eum maiores voluptatem quidem.', - 'subject': 'Quia officiis sit sint aliquid ad quibusdam et' + "id": "43", + "first-name": "Natalie", + "last-name": "Hoeger", + "email": "gregorio_mosciski@schneiderframi.net", + "date": "1976-04-06 06:23:07 -0800", + "content": + "Iste id illo cupiditate enim aut quo. Vel ut eos qui. Aut at in eum maiores voluptatem quidem.", + "subject": "Quia officiis sit sint aliquid ad quibusdam et" }, { - 'id': '44', - 'first-name': 'Joan', - 'last-name': 'Mosciski', - 'email': 'thad@dickivolkman.info', - 'date': '1990-12-26 15:04:40 -0800', - 'content': 'Culpa est officia veritatis esse.', - 'subject': 'Est eum ullam quo' + "id": "44", + "first-name": "Joan", + "last-name": "Mosciski", + "email": "thad@dickivolkman.info", + "date": "1990-12-26 15:04:40 -0800", + "content": "Culpa est officia veritatis esse.", + "subject": "Est eum ullam quo" }, { - 'id': '45', - 'first-name': 'Emmitt', - 'last-name': 'Keeling', - 'email': 'cali@ferry.info', - 'date': '2009-04-10 10:14:57 -0700', - 'content': - 'Numquam velit sunt sed et ut. Laudantium qui laboriosam quibusdam qui. Odio non maxime soluta vero qui.', - 'subject': 'Accusantium saepe id totam aut reiciendis at esse magnam' + "id": "45", + "first-name": "Emmitt", + "last-name": "Keeling", + "email": "cali@ferry.info", + "date": "2009-04-10 10:14:57 -0700", + "content": + "Numquam velit sunt sed et ut. Laudantium qui laboriosam quibusdam qui. Odio non maxime soluta vero qui.", + "subject": "Accusantium saepe id totam aut reiciendis at esse magnam" }, { - 'id': '46', - 'first-name': 'Guy', - 'last-name': 'Renner', - 'email': 'naomie_klein@streich.name', - 'date': '1970-12-18 13:09:51 -0800', - 'content': 'Iure quia at excepturi sit consequatur.', - 'subject': 'Commodi aut ipsa accusantium dolor repudiandae in' + "id": "46", + "first-name": "Guy", + "last-name": "Renner", + "email": "naomie_klein@streich.name", + "date": "1970-12-18 13:09:51 -0800", + "content": "Iure quia at excepturi sit consequatur.", + "subject": "Commodi aut ipsa accusantium dolor repudiandae in" }, { - 'id': '47', - 'first-name': 'Eric', - 'last-name': 'Kihn', - 'email': 'dock.schmeler@langworth.biz', - 'date': '1993-12-17 11:17:07 -0800', - 'content': 'Facere voluptate omnis qui officia dicta.', - 'subject': 'Incidunt a libero ab asperiores fuga ut quo illum' + "id": "47", + "first-name": "Eric", + "last-name": "Kihn", + "email": "dock.schmeler@langworth.biz", + "date": "1993-12-17 11:17:07 -0800", + "content": "Facere voluptate omnis qui officia dicta.", + "subject": "Incidunt a libero ab asperiores fuga ut quo illum" }, { - 'id': '48', - 'first-name': 'Kraig', - 'last-name': 'Keeling', - 'email': 'alejandrin@streichwiegand.org', - 'date': '1977-12-09 14:54:22 -0800', - 'content': 'Asperiores expedita incidunt in cum ex vel hic.', - 'subject': 'In illum quisquam ut est eligendi aut' + "id": "48", + "first-name": "Kraig", + "last-name": "Keeling", + "email": "alejandrin@streichwiegand.org", + "date": "1977-12-09 14:54:22 -0800", + "content": "Asperiores expedita incidunt in cum ex vel hic.", + "subject": "In illum quisquam ut est eligendi aut" }, { - 'id': '49', - 'first-name': 'Justice', - 'last-name': 'Leuschke', - 'email': 'florencio@conn.info', - 'date': '1991-12-14 09:38:08 -0800', - 'content': - 'Aspernatur nesciunt voluptas sit. Cum architecto enim et blanditiis soluta dolor. Recusandae numquam occaecati esse animi et aut.', - 'subject': 'Quaerat voluptatibus eum sapiente iure deserunt' + "id": "49", + "first-name": "Justice", + "last-name": "Leuschke", + "email": "florencio@conn.info", + "date": "1991-12-14 09:38:08 -0800", + "content": + "Aspernatur nesciunt voluptas sit. Cum architecto enim et blanditiis soluta dolor. Recusandae numquam occaecati esse animi et aut.", + "subject": "Quaerat voluptatibus eum sapiente iure deserunt" }, { - 'id': '50', - 'first-name': 'Jodie', - 'last-name': 'O\'Hara', - 'email': 'rick@stehrboehm.info', - 'date': '2000-07-21 05:34:03 -0700', - 'content': - 'Labore repudiandae dolor nostrum quo tempora eos. Natus ea fugit voluptas doloremque distinctio quaerat unde. Ut aut nostrum.', - 'subject': 'Tempore in quam id aliquam fuga eos dolor' + "id": "50", + "first-name": "Jodie", + "last-name": "O'Hara", + "email": "rick@stehrboehm.info", + "date": "2000-07-21 05:34:03 -0700", + "content": + "Labore repudiandae dolor nostrum quo tempora eos. Natus ea fugit voluptas doloremque distinctio quaerat unde. Ut aut nostrum.", + "subject": "Tempore in quam id aliquam fuga eos dolor" }, { - 'id': '51', - 'first-name': 'Dannie', - 'last-name': 'Vandervort', - 'email': 'mariana@abbottruecker.biz', - 'date': '2001-09-15 19:00:54 -0700', - 'content': 'Consectetur dolore voluptas.', - 'subject': 'Tenetur possimus et fuga mollitia perferendis omnis corporis' + "id": "51", + "first-name": "Dannie", + "last-name": "Vandervort", + "email": "mariana@abbottruecker.biz", + "date": "2001-09-15 19:00:54 -0700", + "content": "Consectetur dolore voluptas.", + "subject": "Tenetur possimus et fuga mollitia perferendis omnis corporis" }, { - 'id': '52', - 'first-name': 'Delaney', - 'last-name': 'Champlin', - 'email': 'kyler_welch@krisrowe.biz', - 'date': '2014-07-22 07:09:07 -0700', - 'content': 'Voluptates qui aut.', - 'subject': 'Quam eos laborum nisi delectus' + "id": "52", + "first-name": "Delaney", + "last-name": "Champlin", + "email": "kyler_welch@krisrowe.biz", + "date": "2014-07-22 07:09:07 -0700", + "content": "Voluptates qui aut.", + "subject": "Quam eos laborum nisi delectus" }, { - 'id': '53', - 'first-name': 'Barbara', - 'last-name': 'Kihn', - 'email': 'tyrese.casper@keebler.net', - 'date': '1996-02-29 20:04:40 -0800', - 'content': 'Totam labore voluptatem eos qui temporibus velit.', - 'subject': 'Eum neque sed aut sunt' + "id": "53", + "first-name": "Barbara", + "last-name": "Kihn", + "email": "tyrese.casper@keebler.net", + "date": "1996-02-29 20:04:40 -0800", + "content": "Totam labore voluptatem eos qui temporibus velit.", + "subject": "Eum neque sed aut sunt" }, { - 'id': '54', - 'first-name': 'Jarred', - 'last-name': 'Shanahan', - 'email': 'coralie@weinat.net', - 'date': '1977-06-08 01:46:22 -0700', - 'content': 'Sed et voluptatum ut est quo et aut.', - 'subject': 'Aut eligendi voluptas mollitia et accusamus sint nemo' + "id": "54", + "first-name": "Jarred", + "last-name": "Shanahan", + "email": "coralie@weinat.net", + "date": "1977-06-08 01:46:22 -0700", + "content": "Sed et voluptatum ut est quo et aut.", + "subject": "Aut eligendi voluptas mollitia et accusamus sint nemo" }, { - 'id': '55', - 'first-name': 'Llewellyn', - 'last-name': 'Bechtelar', - 'email': 'kaci@jast.com', - 'date': '1998-12-01 21:14:32 -0800', - 'content': 'Architecto eligendi et ut occaecati temporibus voluptas quia.', - 'subject': 'Sint quis vitae voluptatem dolor aut quo maiores quas' + "id": "55", + "first-name": "Llewellyn", + "last-name": "Bechtelar", + "email": "kaci@jast.com", + "date": "1998-12-01 21:14:32 -0800", + "content": "Architecto eligendi et ut occaecati temporibus voluptas quia.", + "subject": "Sint quis vitae voluptatem dolor aut quo maiores quas" }, { - 'id': '56', - 'first-name': 'Albertha', - 'last-name': 'Upton', - 'email': 'august@bradtkemiller.net', - 'date': '2006-11-16 14:38:45 -0800', - 'content': - 'Voluptas perspiciatis recusandae et. Sequi eum eius dicta dolorem. Alias reprehenderit explicabo doloribus exercitationem sint.', - 'subject': 'Quo nihil fuga dolores cumque rerum eos asperiores' + "id": "56", + "first-name": "Albertha", + "last-name": "Upton", + "email": "august@bradtkemiller.net", + "date": "2006-11-16 14:38:45 -0800", + "content": + "Voluptas perspiciatis recusandae et. Sequi eum eius dicta dolorem. Alias reprehenderit explicabo doloribus exercitationem sint.", + "subject": "Quo nihil fuga dolores cumque rerum eos asperiores" }, { - 'id': '57', - 'first-name': 'Christy', - 'last-name': 'Considine', - 'email': 'eliseo@veum.com', - 'date': '1997-05-17 13:54:41 -0700', - 'content': - 'Consequatur rerum laudantium distinctio magni. Iusto ullam et suscipit nemo ex velit voluptatem.', - 'subject': 'Ut ea quisquam libero qui repudiandae aut officia' + "id": "57", + "first-name": "Christy", + "last-name": "Considine", + "email": "eliseo@veum.com", + "date": "1997-05-17 13:54:41 -0700", + "content": + "Consequatur rerum laudantium distinctio magni. Iusto ullam et suscipit nemo ex velit voluptatem.", + "subject": "Ut ea quisquam libero qui repudiandae aut officia" }, { - 'id': '58', - 'first-name': 'Jessica', - 'last-name': 'Simonis', - 'email': 'rickey@mertz.info', - 'date': '2012-10-04 00:32:34 -0700', - 'content': - 'Neque tenetur sunt sunt ratione. Rerum dolorem illo ab blanditiis quisquam architecto. Quidem ea exercitationem enim eos.', - 'subject': 'Atque quo nemo explicabo voluptas blanditiis accusantium et' + "id": "58", + "first-name": "Jessica", + "last-name": "Simonis", + "email": "rickey@mertz.info", + "date": "2012-10-04 00:32:34 -0700", + "content": + "Neque tenetur sunt sunt ratione. Rerum dolorem illo ab blanditiis quisquam architecto. Quidem ea exercitationem enim eos.", + "subject": "Atque quo nemo explicabo voluptas blanditiis accusantium et" }, { - 'id': '59', - 'first-name': 'Justen', - 'last-name': 'Davis', - 'email': 'karen@jaskolskigleason.org', - 'date': '1994-08-10 02:33:43 -0700', - 'content': 'Eius tenetur mollitia ad alias ab.', - 'subject': 'Ut accusantium sunt qui nostrum eligendi' + "id": "59", + "first-name": "Justen", + "last-name": "Davis", + "email": "karen@jaskolskigleason.org", + "date": "1994-08-10 02:33:43 -0700", + "content": "Eius tenetur mollitia ad alias ab.", + "subject": "Ut accusantium sunt qui nostrum eligendi" }, { - 'id': '60', - 'first-name': 'Elwin', - 'last-name': 'Daugherty', - 'email': 'milo@ko.net', - 'date': '1976-06-30 05:16:38 -0700', - 'content': 'Sit necessitatibus minus.', - 'subject': 'A molestiae voluptates ducimus id est recusandae' + "id": "60", + "first-name": "Elwin", + "last-name": "Daugherty", + "email": "milo@ko.net", + "date": "1976-06-30 05:16:38 -0700", + "content": "Sit necessitatibus minus.", + "subject": "A molestiae voluptates ducimus id est recusandae" }, { - 'id': '61', - 'first-name': 'Clair', - 'last-name': 'Raynor', - 'email': 'zella.hermiston@batz.org', - 'date': '1985-12-18 14:30:18 -0800', - 'content': 'Aut aliquid est sit pariatur voluptatem dolorum.', - 'subject': 'Consectetur reprehenderit temporibus vel voluptatem voluptatem et rem fuga' + "id": "61", + "first-name": "Clair", + "last-name": "Raynor", + "email": "zella.hermiston@batz.org", + "date": "1985-12-18 14:30:18 -0800", + "content": "Aut aliquid est sit pariatur voluptatem dolorum.", + "subject": "Consectetur reprehenderit temporibus vel voluptatem voluptatem et rem fuga" }, { - 'id': '62', - 'first-name': 'Hilario', - 'last-name': 'Klein', - 'email': 'adrain@stark.biz', - 'date': '1980-09-08 18:06:43 -0700', - 'content': 'Eum dolore optio quos animi.', - 'subject': 'Illum nihil vitae molestiae laboriosam beatae modi' + "id": "62", + "first-name": "Hilario", + "last-name": "Klein", + "email": "adrain@stark.biz", + "date": "1980-09-08 18:06:43 -0700", + "content": "Eum dolore optio quos animi.", + "subject": "Illum nihil vitae molestiae laboriosam beatae modi" }, { - 'id': '63', - 'first-name': 'Greta', - 'last-name': 'Murray', - 'email': 'ethelyn@fritsch.org', - 'date': '1970-05-23 02:27:54 -0700', - 'content': - 'Quisquam animi et recusandae rem modi eos ipsa. Eaque et expedita qui animi veritatis temporibus.', - 'subject': 'Repellendus fuga sint nemo' + "id": "63", + "first-name": "Greta", + "last-name": "Murray", + "email": "ethelyn@fritsch.org", + "date": "1970-05-23 02:27:54 -0700", + "content": + "Quisquam animi et recusandae rem modi eos ipsa. Eaque et expedita qui animi veritatis temporibus.", + "subject": "Repellendus fuga sint nemo" }, { - 'id': '64', - 'first-name': 'Anissa', - 'last-name': 'Adams', - 'email': 'edward@armstrong.com', - 'date': '1997-01-26 22:21:57 -0800', - 'content': 'Laudantium culpa rem voluptas tempore. Sit modi dolor est sunt rem.', - 'subject': 'Autem unde minima quia beatae totam' + "id": "64", + "first-name": "Anissa", + "last-name": "Adams", + "email": "edward@armstrong.com", + "date": "1997-01-26 22:21:57 -0800", + "content": "Laudantium culpa rem voluptas tempore. Sit modi dolor est sunt rem.", + "subject": "Autem unde minima quia beatae totam" }, { - 'id': '65', - 'first-name': 'Kaylah', - 'last-name': 'Conroy', - 'email': 'brian.cormier@hyatt.org', - 'date': '2015-02-02 07:44:37 -0800', - 'content': 'Voluptates vitae nulla expedita. Possimus et quo aut eum.', - 'subject': 'Molestiae minus enim adipisci et' + "id": "65", + "first-name": "Kaylah", + "last-name": "Conroy", + "email": "brian.cormier@hyatt.org", + "date": "2015-02-02 07:44:37 -0800", + "content": "Voluptates vitae nulla expedita. Possimus et quo aut eum.", + "subject": "Molestiae minus enim adipisci et" }, { - 'id': '66', - 'first-name': 'Jamey', - 'last-name': 'Ebert', - 'email': 'seth@pfannerstillrodriguez.name', - 'date': '1987-09-29 09:40:59 -0700', - 'content': 'Voluptatem est quae.', - 'subject': 'Similique nemo placeat id tempore dolorum' + "id": "66", + "first-name": "Jamey", + "last-name": "Ebert", + "email": "seth@pfannerstillrodriguez.name", + "date": "1987-09-29 09:40:59 -0700", + "content": "Voluptatem est quae.", + "subject": "Similique nemo placeat id tempore dolorum" }, { - 'id': '67', - 'first-name': 'Johnson', - 'last-name': 'Mosciski', - 'email': 'morton@littel.net', - 'date': '1989-02-14 11:15:10 -0800', - 'content': - 'Molestias expedita exercitationem et praesentium et vel delectus. Qui fuga molestias porro.', - 'subject': 'Aut rerum quidem est iste in blanditiis sit' + "id": "67", + "first-name": "Johnson", + "last-name": "Mosciski", + "email": "morton@littel.net", + "date": "1989-02-14 11:15:10 -0800", + "content": + "Molestias expedita exercitationem et praesentium et vel delectus. Qui fuga molestias porro.", + "subject": "Aut rerum quidem est iste in blanditiis sit" }, { - 'id': '68', - 'first-name': 'Ellis', - 'last-name': 'O\'Keefe', - 'email': 'taurean@ullrich.biz', - 'date': '1987-03-09 11:29:05 -0800', - 'content': - 'Facere sint doloribus qui illo autem consequatur culpa. Est quisquam enim accusantium praesentium.', - 'subject': 'Quis beatae quia velit deserunt est sit odit quisquam' + "id": "68", + "first-name": "Ellis", + "last-name": "O'Keefe", + "email": "taurean@ullrich.biz", + "date": "1987-03-09 11:29:05 -0800", + "content": + "Facere sint doloribus qui illo autem consequatur culpa. Est quisquam enim accusantium praesentium.", + "subject": "Quis beatae quia velit deserunt est sit odit quisquam" }, { - 'id': '69', - 'first-name': 'Marlen', - 'last-name': 'Ritchie', - 'email': 'rodger_schamberger@thiel.net', - 'date': '1989-07-23 03:03:52 -0700', - 'content': 'Doloribus porro hic quis explicabo fuga veritatis vero.', - 'subject': 'Et doloribus est consequatur unde' + "id": "69", + "first-name": "Marlen", + "last-name": "Ritchie", + "email": "rodger_schamberger@thiel.net", + "date": "1989-07-23 03:03:52 -0700", + "content": "Doloribus porro hic quis explicabo fuga veritatis vero.", + "subject": "Et doloribus est consequatur unde" }, { - 'id': '70', - 'first-name': 'Maddison', - 'last-name': 'Kuhic', - 'email': 'rosetta@von.biz', - 'date': '1975-06-22 10:34:58 -0700', - 'content': - 'Sit ut eos libero error sapiente veritatis. Est dolore qui impedit recusandae quas animi rerum.', - 'subject': 'Quos culpa assumenda enim eius aliquid dolorum' + "id": "70", + "first-name": "Maddison", + "last-name": "Kuhic", + "email": "rosetta@von.biz", + "date": "1975-06-22 10:34:58 -0700", + "content": + "Sit ut eos libero error sapiente veritatis. Est dolore qui impedit recusandae quas animi rerum.", + "subject": "Quos culpa assumenda enim eius aliquid dolorum" }, { - 'id': '71', - 'first-name': 'Whitney', - 'last-name': 'Parisian', - 'email': 'everardo@langworth.name', - 'date': '1970-11-04 01:17:28 -0800', - 'content': - 'Quam dolores pariatur ut possimus. Alias tenetur ex accusantium quasi. Nihil dolorem mollitia quidem.', - 'subject': 'Officia totam excepturi sed illum et tempore commodi sit' + "id": "71", + "first-name": "Whitney", + "last-name": "Parisian", + "email": "everardo@langworth.name", + "date": "1970-11-04 01:17:28 -0800", + "content": + "Quam dolores pariatur ut possimus. Alias tenetur ex accusantium quasi. Nihil dolorem mollitia quidem.", + "subject": "Officia totam excepturi sed illum et tempore commodi sit" }, { - 'id': '72', - 'first-name': 'Madyson', - 'last-name': 'Streich', - 'email': 'imani@murray.biz', - 'date': '1983-07-16 11:27:34 -0700', - 'content': - 'Veritatis molestiae id placeat dolorem consectetur a est. Est enim aut. Magnam aut distinctio quo sapiente ea est accusantium.', - 'subject': 'Aut sunt esse eligendi et qui ut sed' + "id": "72", + "first-name": "Madyson", + "last-name": "Streich", + "email": "imani@murray.biz", + "date": "1983-07-16 11:27:34 -0700", + "content": + "Veritatis molestiae id placeat dolorem consectetur a est. Est enim aut. Magnam aut distinctio quo sapiente ea est accusantium.", + "subject": "Aut sunt esse eligendi et qui ut sed" }, { - 'id': '73', - 'first-name': 'Laurie', - 'last-name': 'Purdy', - 'email': 'jarrell@paucek.biz', - 'date': '1992-10-18 12:48:31 -0700', - 'content': - 'Saepe facilis est repellendus praesentium autem. Qui soluta voluptas ullam sequi. Molestias aut quibusdam.', - 'subject': 'Quo ullam totam sit dolores' + "id": "73", + "first-name": "Laurie", + "last-name": "Purdy", + "email": "jarrell@paucek.biz", + "date": "1992-10-18 12:48:31 -0700", + "content": + "Saepe facilis est repellendus praesentium autem. Qui soluta voluptas ullam sequi. Molestias aut quibusdam.", + "subject": "Quo ullam totam sit dolores" }, { - 'id': '74', - 'first-name': 'Ollie', - 'last-name': 'Lowe', - 'email': 'corene@kris.info', - 'date': '1976-08-24 16:28:46 -0700', - 'content': 'Nostrum qui eaque aperiam possimus libero non. Quae aut enim non.', - 'subject': 'Optio minus aut officiis voluptates reiciendis sit dicta' + "id": "74", + "first-name": "Ollie", + "last-name": "Lowe", + "email": "corene@kris.info", + "date": "1976-08-24 16:28:46 -0700", + "content": "Nostrum qui eaque aperiam possimus libero non. Quae aut enim non.", + "subject": "Optio minus aut officiis voluptates reiciendis sit dicta" }, { - 'id': '75', - 'first-name': 'Ian', - 'last-name': 'Murray', - 'email': 'adelia_bernhard@maggio.com', - 'date': '1982-04-08 00:25:22 -0800', - 'content': 'Quod dolores quibusdam nihil aut vel. Sit ab vitae necessitatibus eum.', - 'subject': 'Quia praesentium nam debitis nulla repellendus quos' + "id": "75", + "first-name": "Ian", + "last-name": "Murray", + "email": "adelia_bernhard@maggio.com", + "date": "1982-04-08 00:25:22 -0800", + "content": "Quod dolores quibusdam nihil aut vel. Sit ab vitae necessitatibus eum.", + "subject": "Quia praesentium nam debitis nulla repellendus quos" }, { - 'id': '76', - 'first-name': 'Bernard', - 'last-name': 'Zieme', - 'email': 'kaelyn.johnson@markswalsh.net', - 'date': '2014-01-17 03:47:35 -0800', - 'content': 'Repellendus qui reiciendis quibusdam voluptatum voluptate omnis.', - 'subject': 'Mollitia ut omnis tempore aut debitis ratione alias illum' + "id": "76", + "first-name": "Bernard", + "last-name": "Zieme", + "email": "kaelyn.johnson@markswalsh.net", + "date": "2014-01-17 03:47:35 -0800", + "content": "Repellendus qui reiciendis quibusdam voluptatum voluptate omnis.", + "subject": "Mollitia ut omnis tempore aut debitis ratione alias illum" }, { - 'id': '77', - 'first-name': 'Megane', - 'last-name': 'Kuvalis', - 'email': 'otis@donnellypouros.name', - 'date': '1987-09-29 22:10:00 -0700', - 'content': - 'Explicabo repellat qui placeat inventore velit. Tempora accusamus minima facilis dicta architecto unde. Excepturi enim eos.', - 'subject': 'Quam molestias amet officiis' + "id": "77", + "first-name": "Megane", + "last-name": "Kuvalis", + "email": "otis@donnellypouros.name", + "date": "1987-09-29 22:10:00 -0700", + "content": + "Explicabo repellat qui placeat inventore velit. Tempora accusamus minima facilis dicta architecto unde. Excepturi enim eos.", + "subject": "Quam molestias amet officiis" }, { - 'id': '78', - 'first-name': 'Freeman', - 'last-name': 'Nader', - 'email': 'samara_hoppe@dachcorkery.info', - 'date': '2009-02-02 12:08:30 -0800', - 'content': 'Perferendis aut minus in.', - 'subject': 'Voluptates odio neque laudantium accusamus ipsa accusantium' + "id": "78", + "first-name": "Freeman", + "last-name": "Nader", + "email": "samara_hoppe@dachcorkery.info", + "date": "2009-02-02 12:08:30 -0800", + "content": "Perferendis aut minus in.", + "subject": "Voluptates odio neque laudantium accusamus ipsa accusantium" }, { - 'id': '79', - 'first-name': 'Margarita', - 'last-name': 'Heller', - 'email': 'heloise@rogahn.name', - 'date': '1984-01-04 10:41:32 -0800', - 'content': 'Officiis voluptas omnis. Nihil consectetur id reiciendis qui nemo est.', - 'subject': 'Velit in molestias quo repudiandae accusamus et excepturi et' + "id": "79", + "first-name": "Margarita", + "last-name": "Heller", + "email": "heloise@rogahn.name", + "date": "1984-01-04 10:41:32 -0800", + "content": "Officiis voluptas omnis. Nihil consectetur id reiciendis qui nemo est.", + "subject": "Velit in molestias quo repudiandae accusamus et excepturi et" }, { - 'id': '80', - 'first-name': 'Lonny', - 'last-name': 'Goodwin', - 'email': 'darian@kundebernier.info', - 'date': '1999-02-08 07:00:38 -0800', - 'content': - 'Earum provident et minima aliquam iusto sint. Sed numquam ducimus voluptatem quos enim.', - 'subject': 'Commodi beatae vitae aut quos dolor consequatur' + "id": "80", + "first-name": "Lonny", + "last-name": "Goodwin", + "email": "darian@kundebernier.info", + "date": "1999-02-08 07:00:38 -0800", + "content": + "Earum provident et minima aliquam iusto sint. Sed numquam ducimus voluptatem quos enim.", + "subject": "Commodi beatae vitae aut quos dolor consequatur" }, { - 'id': '81', - 'first-name': 'Jazlyn', - 'last-name': 'Bayer', - 'email': 'harvey@rempel.org', - 'date': '2009-09-28 16:50:32 -0700', - 'content': 'Ipsum voluptas perferendis aperiam dolor.', - 'subject': 'Omnis inventore nobis cupiditate quas quis tenetur' + "id": "81", + "first-name": "Jazlyn", + "last-name": "Bayer", + "email": "harvey@rempel.org", + "date": "2009-09-28 16:50:32 -0700", + "content": "Ipsum voluptas perferendis aperiam dolor.", + "subject": "Omnis inventore nobis cupiditate quas quis tenetur" }, { - 'id': '82', - 'first-name': 'Jakob', - 'last-name': 'Conn', - 'email': 'rylee@vandervort.net', - 'date': '2008-11-12 17:22:34 -0800', - 'content': - 'Aut temporibus perferendis neque nulla et. Totam ab neque inventore et facere eligendi.', - 'subject': 'A optio ut molestiae iste et nam' + "id": "82", + "first-name": "Jakob", + "last-name": "Conn", + "email": "rylee@vandervort.net", + "date": "2008-11-12 17:22:34 -0800", + "content": + "Aut temporibus perferendis neque nulla et. Totam ab neque inventore et facere eligendi.", + "subject": "A optio ut molestiae iste et nam" }, { - 'id': '83', - 'first-name': 'Mikayla', - 'last-name': 'Romaguera', - 'email': 'rebecca_moriette@stracke.net', - 'date': '1986-08-09 12:39:31 -0700', - 'content': 'Dicta et reiciendis corrupti.', - 'subject': 'Neque odio voluptates aut quam' + "id": "83", + "first-name": "Mikayla", + "last-name": "Romaguera", + "email": "rebecca_moriette@stracke.net", + "date": "1986-08-09 12:39:31 -0700", + "content": "Dicta et reiciendis corrupti.", + "subject": "Neque odio voluptates aut quam" }, { - 'id': '84', - 'first-name': 'Brianne', - 'last-name': 'West', - 'email': 'sheila@terry.com', - 'date': '1972-04-25 22:32:20 -0800', - 'content': - 'Nulla sit mollitia qui odit sit corrupti repudiandae. Voluptas consequuntur voluptatibus molestiae. Illo quidem nostrum odio et.', - 'subject': 'Deserunt voluptas et accusamus' + "id": "84", + "first-name": "Brianne", + "last-name": "West", + "email": "sheila@terry.com", + "date": "1972-04-25 22:32:20 -0800", + "content": + "Nulla sit mollitia qui odit sit corrupti repudiandae. Voluptas consequuntur voluptatibus molestiae. Illo quidem nostrum odio et.", + "subject": "Deserunt voluptas et accusamus" }, { - 'id': '85', - 'first-name': 'Destiny', - 'last-name': 'Mohr', - 'email': 'ernestine.waters@connellypfannerstill.com', - 'date': '2012-10-30 15:02:35 -0700', - 'content': - 'Eveniet voluptatem molestias dolores aut voluptates. Quisquam nemo ipsam dicta numquam aut temporibus.', - 'subject': 'Pariatur nisi facilis tempora' + "id": "85", + "first-name": "Destiny", + "last-name": "Mohr", + "email": "ernestine.waters@connellypfannerstill.com", + "date": "2012-10-30 15:02:35 -0700", + "content": + "Eveniet voluptatem molestias dolores aut voluptates. Quisquam nemo ipsam dicta numquam aut temporibus.", + "subject": "Pariatur nisi facilis tempora" }, { - 'id': '86', - 'first-name': 'Brooks', - 'last-name': 'Herman', - 'email': 'brendan_smith@treutel.info', - 'date': '1972-04-01 17:10:07 -0800', - 'content': 'Qui sunt dolore molestiae minima. Suscipit ea quia a aut sunt et.', - 'subject': 'Magni quia perferendis possimus ipsam' + "id": "86", + "first-name": "Brooks", + "last-name": "Herman", + "email": "brendan_smith@treutel.info", + "date": "1972-04-01 17:10:07 -0800", + "content": "Qui sunt dolore molestiae minima. Suscipit ea quia a aut sunt et.", + "subject": "Magni quia perferendis possimus ipsam" }, { - 'id': '87', - 'first-name': 'Celestino', - 'last-name': 'Dickens', - 'email': 'cruz.mcdermott@ziemann.org', - 'date': '2007-08-14 14:55:17 -0700', - 'content': 'Saepe libero tenetur.', - 'subject': 'Molestiae nulla aut laborum placeat perferendis aliquam' + "id": "87", + "first-name": "Celestino", + "last-name": "Dickens", + "email": "cruz.mcdermott@ziemann.org", + "date": "2007-08-14 14:55:17 -0700", + "content": "Saepe libero tenetur.", + "subject": "Molestiae nulla aut laborum placeat perferendis aliquam" }, { - 'id': '88', - 'first-name': 'Angel', - 'last-name': 'Tillman', - 'email': 'shayna_baumbach@durgan.biz', - 'date': '1978-08-31 01:02:14 -0700', - 'content': - 'Libero sequi ea dolore. Numquam quia temporibus voluptatum rerum. Deserunt tenetur nesciunt veritatis debitis.', - 'subject': 'Occaecati quo omnis adipisci sit perspiciatis aut modi cum' + "id": "88", + "first-name": "Angel", + "last-name": "Tillman", + "email": "shayna_baumbach@durgan.biz", + "date": "1978-08-31 01:02:14 -0700", + "content": + "Libero sequi ea dolore. Numquam quia temporibus voluptatum rerum. Deserunt tenetur nesciunt veritatis debitis.", + "subject": "Occaecati quo omnis adipisci sit perspiciatis aut modi cum" }, { - 'id': '89', - 'first-name': 'Verlie', - 'last-name': 'Tillman', - 'email': 'aurelia@gorczany.name', - 'date': '1995-07-27 01:25:55 -0700', - 'content': 'Iure est veritatis qui et. Sit tempore ducimus repellat cupiditate.', - 'subject': 'Dolorum similique expedita praesentium quisquam quasi dolorem eligendi' + "id": "89", + "first-name": "Verlie", + "last-name": "Tillman", + "email": "aurelia@gorczany.name", + "date": "1995-07-27 01:25:55 -0700", + "content": "Iure est veritatis qui et. Sit tempore ducimus repellat cupiditate.", + "subject": "Dolorum similique expedita praesentium quisquam quasi dolorem eligendi" }, { - 'id': '90', - 'first-name': 'Cornell', - 'last-name': 'Padberg', - 'email': 'rhianna@thiel.name', - 'date': '2009-12-14 14:21:13 -0800', - 'content': - 'Ea modi consequatur. Necessitatibus sit qui voluptatem et accusantium. Cumque rerum omnis.', - 'subject': 'Molestiae nostrum aut officiis porro tempore' + "id": "90", + "first-name": "Cornell", + "last-name": "Padberg", + "email": "rhianna@thiel.name", + "date": "2009-12-14 14:21:13 -0800", + "content": + "Ea modi consequatur. Necessitatibus sit qui voluptatem et accusantium. Cumque rerum omnis.", + "subject": "Molestiae nostrum aut officiis porro tempore" }, { - 'id': '91', - 'first-name': 'Carmelo', - 'last-name': 'Kunde', - 'email': 'beulah@rolfsonschaefer.info', - 'date': '2010-08-14 23:10:58 -0700', - 'content': 'Ut molestiae dolorem fuga in aliquam est provident.', - 'subject': 'Atque occaecati temporibus et autem est' + "id": "91", + "first-name": "Carmelo", + "last-name": "Kunde", + "email": "beulah@rolfsonschaefer.info", + "date": "2010-08-14 23:10:58 -0700", + "content": "Ut molestiae dolorem fuga in aliquam est provident.", + "subject": "Atque occaecati temporibus et autem est" }, { - 'id': '92', - 'first-name': 'Jess', - 'last-name': 'Corwin', - 'email': 'korey.barrows@reillyankunding.com', - 'date': '1976-11-13 05:09:16 -0800', - 'content': - 'Commodi eveniet aspernatur earum nisi aut sit dolor. Odio vero facilis reprehenderit dolore. Provident voluptatibus atque qui assumenda quaerat.', - 'subject': 'Commodi laboriosam accusamus quis dolores tempora eos' + "id": "92", + "first-name": "Jess", + "last-name": "Corwin", + "email": "korey.barrows@reillyankunding.com", + "date": "1976-11-13 05:09:16 -0800", + "content": + "Commodi eveniet aspernatur earum nisi aut sit dolor. Odio vero facilis reprehenderit dolore. Provident voluptatibus atque qui assumenda quaerat.", + "subject": "Commodi laboriosam accusamus quis dolores tempora eos" }, { - 'id': '93', - 'first-name': 'Hugh', - 'last-name': 'Hirthe', - 'email': 'verla.dickens@keeling.name', - 'date': '1971-03-17 23:51:15 -0800', - 'content': - 'Voluptatibus saepe dolor voluptas sed cupiditate incidunt. Magni velit ut beatae minus. Consequatur recusandae voluptas ad ex dolores modi quos.', - 'subject': 'Ut pariatur odit mollitia soluta eaque magnam' + "id": "93", + "first-name": "Hugh", + "last-name": "Hirthe", + "email": "verla.dickens@keeling.name", + "date": "1971-03-17 23:51:15 -0800", + "content": + "Voluptatibus saepe dolor voluptas sed cupiditate incidunt. Magni velit ut beatae minus. Consequatur recusandae voluptas ad ex dolores modi quos.", + "subject": "Ut pariatur odit mollitia soluta eaque magnam" }, { - 'id': '94', - 'first-name': 'Elsa', - 'last-name': 'Morissette', - 'email': 'otto@ohara.org', - 'date': '2006-11-27 01:10:16 -0800', - 'content': - 'Et architecto ipsam asperiores vitae quo. Fugiat error quidem facilis. Eaque officiis est veniam.', - 'subject': 'Autem rerum consequatur suscipit veritatis' + "id": "94", + "first-name": "Elsa", + "last-name": "Morissette", + "email": "otto@ohara.org", + "date": "2006-11-27 01:10:16 -0800", + "content": + "Et architecto ipsam asperiores vitae quo. Fugiat error quidem facilis. Eaque officiis est veniam.", + "subject": "Autem rerum consequatur suscipit veritatis" }, { - 'id': '95', - 'first-name': 'Gianni', - 'last-name': 'Nitzsche', - 'email': 'maxine.carter@schimmelfritsch.com', - 'date': '2006-02-22 21:52:15 -0800', - 'content': - 'Nam aut at esse. Adipisci tenetur in voluptas. Dolore quia nobis voluptatibus iure sit eaque fugit.', - 'subject': 'Et est rerum non aut eum' + "id": "95", + "first-name": "Gianni", + "last-name": "Nitzsche", + "email": "maxine.carter@schimmelfritsch.com", + "date": "2006-02-22 21:52:15 -0800", + "content": + "Nam aut at esse. Adipisci tenetur in voluptas. Dolore quia nobis voluptatibus iure sit eaque fugit.", + "subject": "Et est rerum non aut eum" }, { - 'id': '96', - 'first-name': 'Reed', - 'last-name': 'Kirlin', - 'email': 'keaton@gutmann.net', - 'date': '2001-08-15 19:41:38 -0700', - 'content': 'Mollitia hic numquam dicta.', - 'subject': 'Est accusantium et nam dolores aliquam' + "id": "96", + "first-name": "Reed", + "last-name": "Kirlin", + "email": "keaton@gutmann.net", + "date": "2001-08-15 19:41:38 -0700", + "content": "Mollitia hic numquam dicta.", + "subject": "Est accusantium et nam dolores aliquam" }, { - 'id': '97', - 'first-name': 'Thelma', - 'last-name': 'Labadie', - 'email': 'leonor@bahringer.biz', - 'date': '1993-01-04 20:38:12 -0800', - 'content': - 'Porro rerum ea similique. Vel qui est. Temporibus a distinctio dolor doloremque eos beatae.', - 'subject': 'Aut et quasi aut' + "id": "97", + "first-name": "Thelma", + "last-name": "Labadie", + "email": "leonor@bahringer.biz", + "date": "1993-01-04 20:38:12 -0800", + "content": + "Porro rerum ea similique. Vel qui est. Temporibus a distinctio dolor doloremque eos beatae.", + "subject": "Aut et quasi aut" }, { - 'id': '98', - 'first-name': 'Neva', - 'last-name': 'Stehr', - 'email': 'clifton.turner@beeroconnell.name', - 'date': '1983-03-21 03:23:41 -0800', - 'content': 'Voluptatem impedit sed minus. Incidunt ad est consequatur rerum mollitia.', - 'subject': 'Eum sapiente quis placeat' + "id": "98", + "first-name": "Neva", + "last-name": "Stehr", + "email": "clifton.turner@beeroconnell.name", + "date": "1983-03-21 03:23:41 -0800", + "content": "Voluptatem impedit sed minus. Incidunt ad est consequatur rerum mollitia.", + "subject": "Eum sapiente quis placeat" }, { - 'id': '99', - 'first-name': 'Jovan', - 'last-name': 'Kunze', - 'email': 'grady_keler@casper.net', - 'date': '1985-11-17 01:24:57 -0800', - 'content': - 'Molestiae laboriosam quia adipisci delectus praesentium nam. Dolorum repudiandae delectus esse quis voluptatem similique. Illum tempore vitae quia minus.', - 'subject': 'Nihil qui repellendus animi nostrum voluptas quisquam aut minima' + "id": "99", + "first-name": "Jovan", + "last-name": "Kunze", + "email": "grady_keler@casper.net", + "date": "1985-11-17 01:24:57 -0800", + "content": + "Molestiae laboriosam quia adipisci delectus praesentium nam. Dolorum repudiandae delectus esse quis voluptatem similique. Illum tempore vitae quia minus.", + "subject": "Nihil qui repellendus animi nostrum voluptas quisquam aut minima" }, { - 'id': '100', - 'first-name': 'Agustin', - 'last-name': 'Rowe', - 'email': 'roderick@cartermckenzie.name', - 'date': '2013-08-15 06:42:43 -0700', - 'content': 'Quo eaque non laboriosam sunt. Ad aliquid laudantium quia. Aut nisi magnam.', - 'subject': 'Aut hic iste maiores sit' + "id": "100", + "first-name": "Agustin", + "last-name": "Rowe", + "email": "roderick@cartermckenzie.name", + "date": "2013-08-15 06:42:43 -0700", + "content": "Quo eaque non laboriosam sunt. Ad aliquid laudantium quia. Aut nisi magnam.", + "subject": "Aut hic iste maiores sit" }, { - 'id': '101', - 'first-name': 'Lennie', - 'last-name': 'Pacocha', - 'email': 'valentine@goldnerryan.com', - 'date': '1995-11-23 15:07:48 -0800', - 'content': - 'Provident sit voluptate odio qui. Est consequatur nobis. Quibusdam exercitationem ducimus aspernatur.', - 'subject': 'Perferendis adipisci necessitatibus qui similique' + "id": "101", + "first-name": "Lennie", + "last-name": "Pacocha", + "email": "valentine@goldnerryan.com", + "date": "1995-11-23 15:07:48 -0800", + "content": + "Provident sit voluptate odio qui. Est consequatur nobis. Quibusdam exercitationem ducimus aspernatur.", + "subject": "Perferendis adipisci necessitatibus qui similique" }, { - 'id': '102', - 'first-name': 'Brionna', - 'last-name': 'Brown', - 'email': 'jesus@gusikowski.info', - 'date': '2007-12-21 20:22:44 -0800', - 'content': - 'Qui deleniti quaerat ratione doloremque ea quod consequatur. Illo consequatur nisi eos molestiae quos ullam. Enim neque rerum perspiciatis inventore consectetur.', - 'subject': 'Perferendis ratione voluptatem quae non magnam' + "id": "102", + "first-name": "Brionna", + "last-name": "Brown", + "email": "jesus@gusikowski.info", + "date": "2007-12-21 20:22:44 -0800", + "content": + "Qui deleniti quaerat ratione doloremque ea quod consequatur. Illo consequatur nisi eos molestiae quos ullam. Enim neque rerum perspiciatis inventore consectetur.", + "subject": "Perferendis ratione voluptatem quae non magnam" }, { - 'id': '103', - 'first-name': 'Ceasar', - 'last-name': 'Becker', - 'email': 'barney@conn.biz', - 'date': '1991-03-31 18:06:07 -0800', - 'content': 'Cupiditate ipsa minus. Recusandae consequatur aperiam ab ut sint expedita.', - 'subject': 'Dolore voluptatum maiores repudiandae ipsam qui consectetur veniam et' + "id": "103", + "first-name": "Ceasar", + "last-name": "Becker", + "email": "barney@conn.biz", + "date": "1991-03-31 18:06:07 -0800", + "content": "Cupiditate ipsa minus. Recusandae consequatur aperiam ab ut sint expedita.", + "subject": "Dolore voluptatum maiores repudiandae ipsam qui consectetur veniam et" }, { - 'id': '104', - 'first-name': 'Jadon', - 'last-name': 'Walker', - 'email': 'alexie@brownspencer.biz', - 'date': '2014-05-05 03:04:04 -0700', - 'content': - 'Ipsam ut molestias necessitatibus consequatur eligendi adipisci nihil. Nemo voluptatem dolores iure enim fuga.', - 'subject': 'Sunt officia voluptas porro et voluptatum exercitationem aut id' + "id": "104", + "first-name": "Jadon", + "last-name": "Walker", + "email": "alexie@brownspencer.biz", + "date": "2014-05-05 03:04:04 -0700", + "content": + "Ipsam ut molestias necessitatibus consequatur eligendi adipisci nihil. Nemo voluptatem dolores iure enim fuga.", + "subject": "Sunt officia voluptas porro et voluptatum exercitationem aut id" }, { - 'id': '105', - 'first-name': 'Harvey', - 'last-name': 'Little', - 'email': 'dell_reichel@mayert.name', - 'date': '1997-05-17 16:09:39 -0700', - 'content': - 'Saepe et voluptate enim facere. Nihil est et sint odit aut quae. Deserunt molestiae explicabo impedit iure quod ratione.', - 'subject': 'Veniam ipsum est eum dolorem neque aut' + "id": "105", + "first-name": "Harvey", + "last-name": "Little", + "email": "dell_reichel@mayert.name", + "date": "1997-05-17 16:09:39 -0700", + "content": + "Saepe et voluptate enim facere. Nihil est et sint odit aut quae. Deserunt molestiae explicabo impedit iure quod ratione.", + "subject": "Veniam ipsum est eum dolorem neque aut" }, { - 'id': '106', - 'first-name': 'Kailey', - 'last-name': 'Doyle', - 'email': 'golda@hayesdavis.name', - 'date': '1992-07-01 10:53:52 -0700', - 'content': - 'Necessitatibus aspernatur nesciunt rerum nam. Qui quaerat modi. Et voluptatem ut quod perspiciatis quo eligendi.', - 'subject': 'Exercitationem voluptatem sunt hic debitis' + "id": "106", + "first-name": "Kailey", + "last-name": "Doyle", + "email": "golda@hayesdavis.name", + "date": "1992-07-01 10:53:52 -0700", + "content": + "Necessitatibus aspernatur nesciunt rerum nam. Qui quaerat modi. Et voluptatem ut quod perspiciatis quo eligendi.", + "subject": "Exercitationem voluptatem sunt hic debitis" }, { - 'id': '107', - 'first-name': 'Emily', - 'last-name': 'Gutmann', - 'email': 'mazie@bashirian.biz', - 'date': '1999-12-26 09:22:07 -0800', - 'content': - 'Rem debitis qui quia. Nihil quis quia omnis et ea aliquid. Quam praesentium commodi itaque.', - 'subject': 'Maiores ea alias fuga' + "id": "107", + "first-name": "Emily", + "last-name": "Gutmann", + "email": "mazie@bashirian.biz", + "date": "1999-12-26 09:22:07 -0800", + "content": + "Rem debitis qui quia. Nihil quis quia omnis et ea aliquid. Quam praesentium commodi itaque.", + "subject": "Maiores ea alias fuga" }, { - 'id': '108', - 'first-name': 'Jack', - 'last-name': 'O\'Keefe', - 'email': 'carlos@wilkinson.biz', - 'date': '1988-04-28 18:31:09 -0700', - 'content': 'Ab aspernatur vel et. Architecto occaecati qui. Adipisci ut sequi culpa.', - 'subject': 'Qui fuga rerum quo' + "id": "108", + "first-name": "Jack", + "last-name": "O'Keefe", + "email": "carlos@wilkinson.biz", + "date": "1988-04-28 18:31:09 -0700", + "content": "Ab aspernatur vel et. Architecto occaecati qui. Adipisci ut sequi culpa.", + "subject": "Qui fuga rerum quo" }, { - 'id': '109', - 'first-name': 'Mylene', - 'last-name': 'Barton', - 'email': 'sherman.kunde@block.info', - 'date': '1996-04-16 20:06:02 -0700', - 'content': 'Nostrum iste laboriosam corporis omnis.', - 'subject': 'Nihil et minima odit iste et beatae' + "id": "109", + "first-name": "Mylene", + "last-name": "Barton", + "email": "sherman.kunde@block.info", + "date": "1996-04-16 20:06:02 -0700", + "content": "Nostrum iste laboriosam corporis omnis.", + "subject": "Nihil et minima odit iste et beatae" }, { - 'id': '110', - 'first-name': 'Cristopher', - 'last-name': 'Krajcik', - 'email': 'levi@oconnell.com', - 'date': '1989-11-08 03:06:37 -0800', - 'content': 'Assumenda qui et accusamus magnam deserunt ut nobis.', - 'subject': 'Aut numquam saepe placeat facilis at' + "id": "110", + "first-name": "Cristopher", + "last-name": "Krajcik", + "email": "levi@oconnell.com", + "date": "1989-11-08 03:06:37 -0800", + "content": "Assumenda qui et accusamus magnam deserunt ut nobis.", + "subject": "Aut numquam saepe placeat facilis at" }, { - 'id': '111', - 'first-name': 'Amya', - 'last-name': 'Anderson', - 'email': 'travis@waelchigottlieb.biz', - 'date': '1986-12-25 15:27:02 -0800', - 'content': 'Iure numquam ea omnis nemo illo.', - 'subject': 'Labore sit aut ea in nemo et deleniti' + "id": "111", + "first-name": "Amya", + "last-name": "Anderson", + "email": "travis@waelchigottlieb.biz", + "date": "1986-12-25 15:27:02 -0800", + "content": "Iure numquam ea omnis nemo illo.", + "subject": "Labore sit aut ea in nemo et deleniti" }, { - 'id': '112', - 'first-name': 'Alphonso', - 'last-name': 'Buckridge', - 'email': 'duncan@barton.name', - 'date': '1991-02-27 01:09:28 -0800', - 'content': 'Sint ducimus sed temporibus quo. Voluptas possimus eaque earum aut.', - 'subject': 'Quidem aliquid blanditiis quasi' + "id": "112", + "first-name": "Alphonso", + "last-name": "Buckridge", + "email": "duncan@barton.name", + "date": "1991-02-27 01:09:28 -0800", + "content": "Sint ducimus sed temporibus quo. Voluptas possimus eaque earum aut.", + "subject": "Quidem aliquid blanditiis quasi" }, { - 'id': '113', - 'first-name': 'Jovani', - 'last-name': 'Thompson', - 'email': 'lewis.greenfelder@stark.biz', - 'date': '1970-10-29 18:08:36 -0800', - 'content': 'Modi aut ut amet ut qui.', - 'subject': 'Deserunt est autem sed dicta qui' + "id": "113", + "first-name": "Jovani", + "last-name": "Thompson", + "email": "lewis.greenfelder@stark.biz", + "date": "1970-10-29 18:08:36 -0800", + "content": "Modi aut ut amet ut qui.", + "subject": "Deserunt est autem sed dicta qui" }, { - 'id': '114', - 'first-name': 'Roosevelt', - 'last-name': 'Blick', - 'email': 'sophie_kaulke@kunze.biz', - 'date': '2001-11-11 17:45:44 -0800', - 'content': 'Debitis non exercitationem vero nostrum dignissimos. Et voluptates ad nulla.', - 'subject': 'Quasi est ipsam accusantium sint' + "id": "114", + "first-name": "Roosevelt", + "last-name": "Blick", + "email": "sophie_kaulke@kunze.biz", + "date": "2001-11-11 17:45:44 -0800", + "content": "Debitis non exercitationem vero nostrum dignissimos. Et voluptates ad nulla.", + "subject": "Quasi est ipsam accusantium sint" }, { - 'id': '115', - 'first-name': 'Darren', - 'last-name': 'Brown', - 'email': 'jammie@hickle.net', - 'date': '2007-10-05 11:14:49 -0700', - 'content': - 'Quas ut odio blanditiis corrupti quia dolor. Id enim in veniam voluptatem. Laborum delectus quidem voluptatem beatae facilis ut.', - 'subject': 'Fugiat totam dolores harum soluta iusto et' + "id": "115", + "first-name": "Darren", + "last-name": "Brown", + "email": "jammie@hickle.net", + "date": "2007-10-05 11:14:49 -0700", + "content": + "Quas ut odio blanditiis corrupti quia dolor. Id enim in veniam voluptatem. Laborum delectus quidem voluptatem beatae facilis ut.", + "subject": "Fugiat totam dolores harum soluta iusto et" }, { - 'id': '116', - 'first-name': 'Dexter', - 'last-name': 'Schroeder', - 'email': 'efrain.corwin@hane.name', - 'date': '1973-09-30 19:52:23 -0700', - 'content': 'Debitis assumenda fugit. Sunt omnis in quod aut quibusdam qui.', - 'subject': 'Aut iure molestias suscipit laboriosam dolores' + "id": "116", + "first-name": "Dexter", + "last-name": "Schroeder", + "email": "efrain.corwin@hane.name", + "date": "1973-09-30 19:52:23 -0700", + "content": "Debitis assumenda fugit. Sunt omnis in quod aut quibusdam qui.", + "subject": "Aut iure molestias suscipit laboriosam dolores" }, { - 'id': '117', - 'first-name': 'Mellie', - 'last-name': 'Hilpert', - 'email': 'amiya_haley@douglasbins.org', - 'date': '1992-05-14 20:52:23 -0700', - 'content': - 'Vero aut perferendis commodi. Quod dolorem distinctio sint. Error nostrum reprehenderit aut quaerat officiis eaque.', - 'subject': 'Omnis aliquid rerum fuga vero molestiae quidem eveniet' + "id": "117", + "first-name": "Mellie", + "last-name": "Hilpert", + "email": "amiya_haley@douglasbins.org", + "date": "1992-05-14 20:52:23 -0700", + "content": + "Vero aut perferendis commodi. Quod dolorem distinctio sint. Error nostrum reprehenderit aut quaerat officiis eaque.", + "subject": "Omnis aliquid rerum fuga vero molestiae quidem eveniet" }, { - 'id': '118', - 'first-name': 'Laura', - 'last-name': 'Koepp', - 'email': 'gus@hagenes.biz', - 'date': '2007-08-04 22:19:10 -0700', - 'content': - 'Quibusdam fugiat quasi consequatur. Ipsam corporis nesciunt quae ipsa aliquid hic eius.', - 'subject': 'Asperiores quisquam voluptatem aut quam dolores' + "id": "118", + "first-name": "Laura", + "last-name": "Koepp", + "email": "gus@hagenes.biz", + "date": "2007-08-04 22:19:10 -0700", + "content": + "Quibusdam fugiat quasi consequatur. Ipsam corporis nesciunt quae ipsa aliquid hic eius.", + "subject": "Asperiores quisquam voluptatem aut quam dolores" }, { - 'id': '119', - 'first-name': 'Amara', - 'last-name': 'Jerde', - 'email': 'estelle@marksdonnelly.info', - 'date': '1989-08-19 01:24:43 -0700', - 'content': - 'Architecto voluptatum quas pariatur expedita exercitationem quo. Sint eum perferendis a. Et similique est amet dolores.', - 'subject': 'Id consequuntur nesciunt tenetur impedit sit voluptas' + "id": "119", + "first-name": "Amara", + "last-name": "Jerde", + "email": "estelle@marksdonnelly.info", + "date": "1989-08-19 01:24:43 -0700", + "content": + "Architecto voluptatum quas pariatur expedita exercitationem quo. Sint eum perferendis a. Et similique est amet dolores.", + "subject": "Id consequuntur nesciunt tenetur impedit sit voluptas" }, { - 'id': '120', - 'first-name': 'Jacquelyn', - 'last-name': 'Barton', - 'email': 'antwon_mayer@kshleringibson.info', - 'date': '1989-08-19 13:07:02 -0700', - 'content': 'Quos enim repellendus praesentium sit rerum deserunt.', - 'subject': 'Et omnis hic autem ipsa tempora impedit perspiciatis' + "id": "120", + "first-name": "Jacquelyn", + "last-name": "Barton", + "email": "antwon_mayer@kshleringibson.info", + "date": "1989-08-19 13:07:02 -0700", + "content": "Quos enim repellendus praesentium sit rerum deserunt.", + "subject": "Et omnis hic autem ipsa tempora impedit perspiciatis" }, { - 'id': '121', - 'first-name': 'Micaela', - 'last-name': 'Runte', - 'email': 'vivianne.graham@vonrueden.org', - 'date': '1986-09-27 01:16:29 -0700', - 'content': 'Et neque rem.', - 'subject': 'Enim facere corrupti accusamus quam consequatur beatae aspernatur vero' + "id": "121", + "first-name": "Micaela", + "last-name": "Runte", + "email": "vivianne.graham@vonrueden.org", + "date": "1986-09-27 01:16:29 -0700", + "content": "Et neque rem.", + "subject": "Enim facere corrupti accusamus quam consequatur beatae aspernatur vero" }, { - 'id': '122', - 'first-name': 'Millie', - 'last-name': 'Flatley', - 'email': 'gino@kihn.biz', - 'date': '1980-02-09 01:35:05 -0800', - 'content': 'Rerum sint quis esse minus. Aut at asperiores. Amet magni beatae atque.', - 'subject': 'Illo vitae blanditiis et impedit in dolor' + "id": "122", + "first-name": "Millie", + "last-name": "Flatley", + "email": "gino@kihn.biz", + "date": "1980-02-09 01:35:05 -0800", + "content": "Rerum sint quis esse minus. Aut at asperiores. Amet magni beatae atque.", + "subject": "Illo vitae blanditiis et impedit in dolor" }, { - 'id': '123', - 'first-name': 'Sincere', - 'last-name': 'Rohan', - 'email': 'zora@beattyerdman.org', - 'date': '2002-11-11 22:02:22 -0800', - 'content': 'Ut error voluptatem aut ratione molestiae. Omnis qui rem delectus.', - 'subject': 'Unde sed voluptas assumenda non animi quo' + "id": "123", + "first-name": "Sincere", + "last-name": "Rohan", + "email": "zora@beattyerdman.org", + "date": "2002-11-11 22:02:22 -0800", + "content": "Ut error voluptatem aut ratione molestiae. Omnis qui rem delectus.", + "subject": "Unde sed voluptas assumenda non animi quo" }, { - 'id': '124', - 'first-name': 'Vicky', - 'last-name': 'Kautzer', - 'email': 'mustafa.lueilwitz@tremblay.name', - 'date': '2014-08-15 11:18:05 -0700', - 'content': - 'Nostrum quis et et molestiae molestiae. Corporis corrupti deleniti qui fugiat eos. Porro qui quis mollitia.', - 'subject': 'Quisquam ex esse dolore' + "id": "124", + "first-name": "Vicky", + "last-name": "Kautzer", + "email": "mustafa.lueilwitz@tremblay.name", + "date": "2014-08-15 11:18:05 -0700", + "content": + "Nostrum quis et et molestiae molestiae. Corporis corrupti deleniti qui fugiat eos. Porro qui quis mollitia.", + "subject": "Quisquam ex esse dolore" }, { - 'id': '125', - 'first-name': 'Lavon', - 'last-name': 'Padberg', - 'email': 'destin_sanford@reynolds.net', - 'date': '2005-07-11 21:24:34 -0700', - 'content': 'Officia dolorem autem beatae soluta numquam aperiam et.', - 'subject': 'Ad labore aut corporis' + "id": "125", + "first-name": "Lavon", + "last-name": "Padberg", + "email": "destin_sanford@reynolds.net", + "date": "2005-07-11 21:24:34 -0700", + "content": "Officia dolorem autem beatae soluta numquam aperiam et.", + "subject": "Ad labore aut corporis" }, { - 'id': '126', - 'first-name': 'Shaina', - 'last-name': 'Dare', - 'email': 'carrie_sawayn@buckridge.net', - 'date': '2001-10-12 08:02:09 -0700', - 'content': 'Ex doloremque dolor deleniti.', - 'subject': 'Asperiores recusandae reprehenderit quia tempore qui ipsam sit' + "id": "126", + "first-name": "Shaina", + "last-name": "Dare", + "email": "carrie_sawayn@buckridge.net", + "date": "2001-10-12 08:02:09 -0700", + "content": "Ex doloremque dolor deleniti.", + "subject": "Asperiores recusandae reprehenderit quia tempore qui ipsam sit" }, { - 'id': '127', - 'first-name': 'Sigrid', - 'last-name': 'Farrell', - 'email': 'soledad_abshire@miller.net', - 'date': '2003-03-24 17:55:50 -0800', - 'content': 'Debitis ea soluta eos ut omnis. Ut et laboriosam. Quaerat sit velit impedit.', - 'subject': 'Eum et nesciunt quidem quo repudiandae rerum doloremque beatae' + "id": "127", + "first-name": "Sigrid", + "last-name": "Farrell", + "email": "soledad_abshire@miller.net", + "date": "2003-03-24 17:55:50 -0800", + "content": "Debitis ea soluta eos ut omnis. Ut et laboriosam. Quaerat sit velit impedit.", + "subject": "Eum et nesciunt quidem quo repudiandae rerum doloremque beatae" }, { - 'id': '128', - 'first-name': 'Viola', - 'last-name': 'Dooley', - 'email': 'myrtice_grant@zemlakbashirian.com', - 'date': '2006-06-01 21:17:02 -0700', - 'content': 'Sit doloremque est aut voluptatem.', - 'subject': 'Aut accusamus consectetur nihil iusto' + "id": "128", + "first-name": "Viola", + "last-name": "Dooley", + "email": "myrtice_grant@zemlakbashirian.com", + "date": "2006-06-01 21:17:02 -0700", + "content": "Sit doloremque est aut voluptatem.", + "subject": "Aut accusamus consectetur nihil iusto" }, { - 'id': '129', - 'first-name': 'Davion', - 'last-name': 'Conn', - 'email': 'travis@bins.biz', - 'date': '1993-11-26 09:03:37 -0800', - 'content': - 'Voluptatibus ipsum mollitia fugit aspernatur enim sint. Laudantium exercitationem sed voluptas consequatur quis.', - 'subject': 'Illum aspernatur tempora amet itaque ipsam distinctio aliquid' + "id": "129", + "first-name": "Davion", + "last-name": "Conn", + "email": "travis@bins.biz", + "date": "1993-11-26 09:03:37 -0800", + "content": + "Voluptatibus ipsum mollitia fugit aspernatur enim sint. Laudantium exercitationem sed voluptas consequatur quis.", + "subject": "Illum aspernatur tempora amet itaque ipsam distinctio aliquid" }, { - 'id': '130', - 'first-name': 'Hobart', - 'last-name': 'Oberbrunner', - 'email': 'eric@wisozk.net', - 'date': '2000-02-11 07:40:02 -0800', - 'content': 'Quis aut sint officia sunt.', - 'subject': 'Ut pariatur explicabo consequatur libero distinctio nulla consequatur placeat' + "id": "130", + "first-name": "Hobart", + "last-name": "Oberbrunner", + "email": "eric@wisozk.net", + "date": "2000-02-11 07:40:02 -0800", + "content": "Quis aut sint officia sunt.", + "subject": "Ut pariatur explicabo consequatur libero distinctio nulla consequatur placeat" }, { - 'id': '131', - 'first-name': 'Raleigh', - 'last-name': 'Hegmann', - 'email': 'jasen.koepp@hickle.name', - 'date': '1993-03-01 22:48:23 -0800', - 'content': - 'Delectus aut quod maxime incidunt et consequatur. Nihil eos et eveniet quo iure. Alias facilis earum dicta nulla quo sed.', - 'subject': 'Aliquam eos aliquid dolor' + "id": "131", + "first-name": "Raleigh", + "last-name": "Hegmann", + "email": "jasen.koepp@hickle.name", + "date": "1993-03-01 22:48:23 -0800", + "content": + "Delectus aut quod maxime incidunt et consequatur. Nihil eos et eveniet quo iure. Alias facilis earum dicta nulla quo sed.", + "subject": "Aliquam eos aliquid dolor" }, { - 'id': '132', - 'first-name': 'Hector', - 'last-name': 'Denesik', - 'email': 'bernice@leuschke.biz', - 'date': '2013-08-03 14:45:55 -0700', - 'content': 'Et ut dicta. Qui sunt vel et voluptas hic suscipit.', - 'subject': 'Ipsum quo est consequatur' + "id": "132", + "first-name": "Hector", + "last-name": "Denesik", + "email": "bernice@leuschke.biz", + "date": "2013-08-03 14:45:55 -0700", + "content": "Et ut dicta. Qui sunt vel et voluptas hic suscipit.", + "subject": "Ipsum quo est consequatur" }, { - 'id': '133', - 'first-name': 'Nikko', - 'last-name': 'Rolfson', - 'email': 'crystel@upton.net', - 'date': '1977-02-19 16:22:15 -0800', - 'content': 'Velit quo repellendus consequatur.', - 'subject': 'Exercitationem omnis aut id deserunt nihil et inventore' + "id": "133", + "first-name": "Nikko", + "last-name": "Rolfson", + "email": "crystel@upton.net", + "date": "1977-02-19 16:22:15 -0800", + "content": "Velit quo repellendus consequatur.", + "subject": "Exercitationem omnis aut id deserunt nihil et inventore" }, { - 'id': '134', - 'first-name': 'Jovany', - 'last-name': 'Nienow', - 'email': 'neil.muller@lakin.info', - 'date': '2004-09-28 21:55:43 -0700', - 'content': - 'Voluptatibus numquam blanditiis quibusdam. Illum suscipit dolorum. Sunt amet est sint.', - 'subject': 'Esse nihil est voluptas rerum ea' + "id": "134", + "first-name": "Jovany", + "last-name": "Nienow", + "email": "neil.muller@lakin.info", + "date": "2004-09-28 21:55:43 -0700", + "content": + "Voluptatibus numquam blanditiis quibusdam. Illum suscipit dolorum. Sunt amet est sint.", + "subject": "Esse nihil est voluptas rerum ea" }, { - 'id': '135', - 'first-name': 'Ellis', - 'last-name': 'Kohler', - 'email': 'cordie_bartoletti@barrows.net', - 'date': '1989-09-19 13:57:30 -0700', - 'content': - 'Eum corporis nobis laborum fugiat amet alias. Voluptatum quasi ducimus fuga corrupti. Mollitia modi laborum.', - 'subject': 'Ipsum modi nulla et' + "id": "135", + "first-name": "Ellis", + "last-name": "Kohler", + "email": "cordie_bartoletti@barrows.net", + "date": "1989-09-19 13:57:30 -0700", + "content": + "Eum corporis nobis laborum fugiat amet alias. Voluptatum quasi ducimus fuga corrupti. Mollitia modi laborum.", + "subject": "Ipsum modi nulla et" }, { - 'id': '136', - 'first-name': 'Marley', - 'last-name': 'Runolfsson', - 'email': 'kian_vonrueden@collier.info', - 'date': '2003-01-17 06:33:04 -0800', - 'content': 'Et rerum explicabo iusto ipsa ipsum. Quia ipsa ab sed perspiciatis.', - 'subject': 'Voluptas esse iure quia hic dolor eligendi velit maiores' + "id": "136", + "first-name": "Marley", + "last-name": "Runolfsson", + "email": "kian_vonrueden@collier.info", + "date": "2003-01-17 06:33:04 -0800", + "content": "Et rerum explicabo iusto ipsa ipsum. Quia ipsa ab sed perspiciatis.", + "subject": "Voluptas esse iure quia hic dolor eligendi velit maiores" }, { - 'id': '137', - 'first-name': 'Grant', - 'last-name': 'Jenkins', - 'email': 'hayden.altenwerth@corkeryankunding.net', - 'date': '1970-03-24 13:04:46 -0800', - 'content': 'Tenetur odit ratione voluptatum dolore qui.', - 'subject': 'Tempore est molestiae id' + "id": "137", + "first-name": "Grant", + "last-name": "Jenkins", + "email": "hayden.altenwerth@corkeryankunding.net", + "date": "1970-03-24 13:04:46 -0800", + "content": "Tenetur odit ratione voluptatum dolore qui.", + "subject": "Tempore est molestiae id" }, { - 'id': '138', - 'first-name': 'Deangelo', - 'last-name': 'Koss', - 'email': 'reba.skiles@bruen.com', - 'date': '1999-10-16 20:28:42 -0700', - 'content': 'Sit vero sint ut beatae iure. Minima harum tempora sit rerum aut.', - 'subject': 'Aspernatur cumque non consequatur blanditiis enim quas quam' + "id": "138", + "first-name": "Deangelo", + "last-name": "Koss", + "email": "reba.skiles@bruen.com", + "date": "1999-10-16 20:28:42 -0700", + "content": "Sit vero sint ut beatae iure. Minima harum tempora sit rerum aut.", + "subject": "Aspernatur cumque non consequatur blanditiis enim quas quam" }, { - 'id': '139', - 'first-name': 'Mariana', - 'last-name': 'Jakubowski', - 'email': 'brett@swift.biz', - 'date': '1970-07-04 08:54:29 -0700', - 'content': 'Beatae expedita praesentium ea corrupti. Aut sint ad et sunt.', - 'subject': 'Dolore distinctio consequatur aut laudantium officiis aliquid soluta' + "id": "139", + "first-name": "Mariana", + "last-name": "Jakubowski", + "email": "brett@swift.biz", + "date": "1970-07-04 08:54:29 -0700", + "content": "Beatae expedita praesentium ea corrupti. Aut sint ad et sunt.", + "subject": "Dolore distinctio consequatur aut laudantium officiis aliquid soluta" }, { - 'id': '140', - 'first-name': 'Leonard', - 'last-name': 'Kovacek', - 'email': 'jermain@dachbruen.biz', - 'date': '1981-10-15 00:39:10 -0700', - 'content': - 'Deserunt cupiditate modi. Eius consequatur aut dolor nostrum porro dignissimos. Labore consequatur quod est et distinctio possimus ducimus.', - 'subject': 'Et rerum id voluptates et iure eligendi rerum' + "id": "140", + "first-name": "Leonard", + "last-name": "Kovacek", + "email": "jermain@dachbruen.biz", + "date": "1981-10-15 00:39:10 -0700", + "content": + "Deserunt cupiditate modi. Eius consequatur aut dolor nostrum porro dignissimos. Labore consequatur quod est et distinctio possimus ducimus.", + "subject": "Et rerum id voluptates et iure eligendi rerum" }, { - 'id': '141', - 'first-name': 'Etha', - 'last-name': 'Ondricka', - 'email': 'noemy@okuneva.org', - 'date': '1994-04-29 12:19:51 -0700', - 'content': - 'Velit fuga quasi pariatur consectetur est nihil. Dolore nisi dolores quia qui voluptatem inventore provident.', - 'subject': 'Enim est commodi nisi autem asperiores molestiae minima' + "id": "141", + "first-name": "Etha", + "last-name": "Ondricka", + "email": "noemy@okuneva.org", + "date": "1994-04-29 12:19:51 -0700", + "content": + "Velit fuga quasi pariatur consectetur est nihil. Dolore nisi dolores quia qui voluptatem inventore provident.", + "subject": "Enim est commodi nisi autem asperiores molestiae minima" }, { - 'id': '142', - 'first-name': 'Nannie', - 'last-name': 'Fadel', - 'email': 'frida.streich@prosacco.org', - 'date': '2012-12-15 16:56:24 -0800', - 'content': 'Rerum id quo. Recusandae aut optio voluptate perspiciatis tempore sed nemo.', - 'subject': 'Pariatur soluta praesentium enim quo quam alias consequuntur in' + "id": "142", + "first-name": "Nannie", + "last-name": "Fadel", + "email": "frida.streich@prosacco.org", + "date": "2012-12-15 16:56:24 -0800", + "content": "Rerum id quo. Recusandae aut optio voluptate perspiciatis tempore sed nemo.", + "subject": "Pariatur soluta praesentium enim quo quam alias consequuntur in" }, { - 'id': '143', - 'first-name': 'Shyanne', - 'last-name': 'Kunze', - 'email': 'annabel@littel.net', - 'date': '1992-12-09 23:41:23 -0800', - 'content': 'Dolores iure iste unde. Illo esse autem harum perspiciatis.', - 'subject': 'Atque illum et qui' + "id": "143", + "first-name": "Shyanne", + "last-name": "Kunze", + "email": "annabel@littel.net", + "date": "1992-12-09 23:41:23 -0800", + "content": "Dolores iure iste unde. Illo esse autem harum perspiciatis.", + "subject": "Atque illum et qui" }, { - 'id': '144', - 'first-name': 'Eloy', - 'last-name': 'Barton', - 'email': 'leonie_gulgowski@skiles.com', - 'date': '2013-01-12 20:05:57 -0800', - 'content': 'Cumque id sapiente explicabo. Voluptas pariatur quibusdam dolores et.', - 'subject': 'Ut dolore velit qui omnis' + "id": "144", + "first-name": "Eloy", + "last-name": "Barton", + "email": "leonie_gulgowski@skiles.com", + "date": "2013-01-12 20:05:57 -0800", + "content": "Cumque id sapiente explicabo. Voluptas pariatur quibusdam dolores et.", + "subject": "Ut dolore velit qui omnis" }, { - 'id': '145', - 'first-name': 'Rosalinda', - 'last-name': 'Pfeffer', - 'email': 'anabelle@langworth.com', - 'date': '2001-05-17 05:43:52 -0700', - 'content': 'Et voluptatem quasi voluptatum.', - 'subject': 'Voluptatum quia incidunt ut repudiandae blanditiis' + "id": "145", + "first-name": "Rosalinda", + "last-name": "Pfeffer", + "email": "anabelle@langworth.com", + "date": "2001-05-17 05:43:52 -0700", + "content": "Et voluptatem quasi voluptatum.", + "subject": "Voluptatum quia incidunt ut repudiandae blanditiis" }, { - 'id': '146', - 'first-name': 'William', - 'last-name': 'Bogisich', - 'email': 'bertha@gibsonrohan.info', - 'date': '2009-11-01 04:28:13 -0800', - 'content': - 'Quaerat dolorem odio et dolor saepe quia odit. Corporis molestiae ab ipsa occaecati autem fuga dicta. Voluptate ratione sunt.', - 'subject': 'Ipsam quidem mollitia blanditiis magnam ut et' + "id": "146", + "first-name": "William", + "last-name": "Bogisich", + "email": "bertha@gibsonrohan.info", + "date": "2009-11-01 04:28:13 -0800", + "content": + "Quaerat dolorem odio et dolor saepe quia odit. Corporis molestiae ab ipsa occaecati autem fuga dicta. Voluptate ratione sunt.", + "subject": "Ipsam quidem mollitia blanditiis magnam ut et" }, { - 'id': '147', - 'first-name': 'Laurianne', - 'last-name': 'Bergstrom', - 'email': 'brisa_howe@dare.net', - 'date': '2003-03-23 21:58:11 -0800', - 'content': 'Et porro recusandae aut. Tenetur voluptas aperiam ut vitae.', - 'subject': 'Molestias autem qui nisi mollitia nulla dolorum repudiandae hic' + "id": "147", + "first-name": "Laurianne", + "last-name": "Bergstrom", + "email": "brisa_howe@dare.net", + "date": "2003-03-23 21:58:11 -0800", + "content": "Et porro recusandae aut. Tenetur voluptas aperiam ut vitae.", + "subject": "Molestias autem qui nisi mollitia nulla dolorum repudiandae hic" }, { - 'id': '148', - 'first-name': 'Carroll', - 'last-name': 'Hickle', - 'email': 'noemi.grady@grimesritchie.com', - 'date': '1996-07-15 02:55:52 -0700', - 'content': 'Quia voluptas assumenda. Numquam inventore facilis dicta qui ipsa reiciendis.', - 'subject': 'Perferendis rerum vel incidunt molestias recusandae' + "id": "148", + "first-name": "Carroll", + "last-name": "Hickle", + "email": "noemi.grady@grimesritchie.com", + "date": "1996-07-15 02:55:52 -0700", + "content": "Quia voluptas assumenda. Numquam inventore facilis dicta qui ipsa reiciendis.", + "subject": "Perferendis rerum vel incidunt molestias recusandae" }, { - 'id': '149', - 'first-name': 'Jasen', - 'last-name': 'Romaguera', - 'email': 'jayce@berge.name', - 'date': '1984-04-12 11:56:39 -0800', - 'content': 'Consectetur molestias perspiciatis ut omnis aliquid.', - 'subject': 'Hic optio accusamus qui adipisci repellendus ipsa in' + "id": "149", + "first-name": "Jasen", + "last-name": "Romaguera", + "email": "jayce@berge.name", + "date": "1984-04-12 11:56:39 -0800", + "content": "Consectetur molestias perspiciatis ut omnis aliquid.", + "subject": "Hic optio accusamus qui adipisci repellendus ipsa in" }, { - 'id': '150', - 'first-name': 'Heaven', - 'last-name': 'Fay', - 'email': 'enola@sanfordsteuber.net', - 'date': '2000-11-23 00:18:07 -0800', - 'content': - 'Quia itaque temporibus. Provident ducimus quidem consectetur qui voluptatum. Sunt cum quis dolorum hic.', - 'subject': 'Ad excepturi illum doloremque ducimus corporis ut qui omnis' + "id": "150", + "first-name": "Heaven", + "last-name": "Fay", + "email": "enola@sanfordsteuber.net", + "date": "2000-11-23 00:18:07 -0800", + "content": + "Quia itaque temporibus. Provident ducimus quidem consectetur qui voluptatum. Sunt cum quis dolorum hic.", + "subject": "Ad excepturi illum doloremque ducimus corporis ut qui omnis" }, { - 'id': '151', - 'first-name': 'Wilburn', - 'last-name': 'Cartwright', - 'email': 'jaida_erdman@nitzsche.com', - 'date': '2011-09-19 01:58:53 -0700', - 'content': 'Autem iure magni ut odio amet et.', - 'subject': 'Fuga quis quidem sint laborum et delectus iste' + "id": "151", + "first-name": "Wilburn", + "last-name": "Cartwright", + "email": "jaida_erdman@nitzsche.com", + "date": "2011-09-19 01:58:53 -0700", + "content": "Autem iure magni ut odio amet et.", + "subject": "Fuga quis quidem sint laborum et delectus iste" }, { - 'id': '152', - 'first-name': 'Concepcion', - 'last-name': 'McLaughlin', - 'email': 'bernardo_langworth@jakubowski.org', - 'date': '1992-08-20 13:35:09 -0700', - 'content': 'Rerum laboriosam omnis nobis eaque odit sequi dicta.', - 'subject': 'Sint accusantium ab quis sed ipsa' + "id": "152", + "first-name": "Concepcion", + "last-name": "McLaughlin", + "email": "bernardo_langworth@jakubowski.org", + "date": "1992-08-20 13:35:09 -0700", + "content": "Rerum laboriosam omnis nobis eaque odit sequi dicta.", + "subject": "Sint accusantium ab quis sed ipsa" }, { - 'id': '153', - 'first-name': 'Vita', - 'last-name': 'Fisher', - 'email': 'chanelle_gulgowski@roob.info', - 'date': '2005-09-21 12:09:45 -0700', - 'content': - 'Sunt quibusdam adipisci accusantium laborum distinctio voluptate autem. Quis pariatur culpa ut et. Fuga similique dignissimos culpa dolorum neque reiciendis.', - 'subject': 'Nulla enim et fugiat eveniet ducimus delectus' + "id": "153", + "first-name": "Vita", + "last-name": "Fisher", + "email": "chanelle_gulgowski@roob.info", + "date": "2005-09-21 12:09:45 -0700", + "content": + "Sunt quibusdam adipisci accusantium laborum distinctio voluptate autem. Quis pariatur culpa ut et. Fuga similique dignissimos culpa dolorum neque reiciendis.", + "subject": "Nulla enim et fugiat eveniet ducimus delectus" }, { - 'id': '154', - 'first-name': 'Elliott', - 'last-name': 'Champlin', - 'email': 'kamille@kulascain.biz', - 'date': '2003-05-20 15:42:54 -0700', - 'content': - 'Eos quisquam et voluptates rerum vel. Consectetur veniam voluptatem minus totam numquam in.', - 'subject': 'Deleniti ipsum et odio' + "id": "154", + "first-name": "Elliott", + "last-name": "Champlin", + "email": "kamille@kulascain.biz", + "date": "2003-05-20 15:42:54 -0700", + "content": + "Eos quisquam et voluptates rerum vel. Consectetur veniam voluptatem minus totam numquam in.", + "subject": "Deleniti ipsum et odio" }, { - 'id': '155', - 'first-name': 'Heidi', - 'last-name': 'Macejkovic', - 'email': 'stefanie@barrowshagenes.info', - 'date': '1983-06-02 17:59:14 -0700', - 'content': 'Ut officiis animi exercitationem delectus suscipit qui voluptatibus.', - 'subject': 'Eveniet ipsam asperiores qui aut consectetur vel provident' + "id": "155", + "first-name": "Heidi", + "last-name": "Macejkovic", + "email": "stefanie@barrowshagenes.info", + "date": "1983-06-02 17:59:14 -0700", + "content": "Ut officiis animi exercitationem delectus suscipit qui voluptatibus.", + "subject": "Eveniet ipsam asperiores qui aut consectetur vel provident" }, { - 'id': '156', - 'first-name': 'Janae', - 'last-name': 'Pollich', - 'email': 'brianne.sauer@marquardtsteuber.com', - 'date': '2000-05-14 07:13:30 -0700', - 'content': 'Facilis sit ut odit.', - 'subject': 'Sapiente explicabo sequi molestias illo saepe' + "id": "156", + "first-name": "Janae", + "last-name": "Pollich", + "email": "brianne.sauer@marquardtsteuber.com", + "date": "2000-05-14 07:13:30 -0700", + "content": "Facilis sit ut odit.", + "subject": "Sapiente explicabo sequi molestias illo saepe" }, { - 'id': '157', - 'first-name': 'Kaylin', - 'last-name': 'Lindgren', - 'email': 'urban.franecki@wilkinsonwilderman.org', - 'date': '2014-09-09 00:48:38 -0700', - 'content': 'Eaque ad repellendus est nihil iste vero.', - 'subject': 'Deserunt qui dolor rerum ut beatae aut' + "id": "157", + "first-name": "Kaylin", + "last-name": "Lindgren", + "email": "urban.franecki@wilkinsonwilderman.org", + "date": "2014-09-09 00:48:38 -0700", + "content": "Eaque ad repellendus est nihil iste vero.", + "subject": "Deserunt qui dolor rerum ut beatae aut" }, { - 'id': '158', - 'first-name': 'Garland', - 'last-name': 'Nienow', - 'email': 'ellen.schultz@kihn.org', - 'date': '2013-10-27 00:18:14 -0700', - 'content': 'Quam voluptatem nam est.', - 'subject': 'Et occaecati quisquam impedit dolore quod' + "id": "158", + "first-name": "Garland", + "last-name": "Nienow", + "email": "ellen.schultz@kihn.org", + "date": "2013-10-27 00:18:14 -0700", + "content": "Quam voluptatem nam est.", + "subject": "Et occaecati quisquam impedit dolore quod" }, { - 'id': '159', - 'first-name': 'Lilly', - 'last-name': 'Hills', - 'email': 'macey@labadie.biz', - 'date': '1981-02-23 03:46:55 -0800', - 'content': - 'Quia perferendis est consequuntur voluptates cumque commodi. Laboriosam expedita sit excepturi.', - 'subject': 'Eos doloribus repellendus provident' + "id": "159", + "first-name": "Lilly", + "last-name": "Hills", + "email": "macey@labadie.biz", + "date": "1981-02-23 03:46:55 -0800", + "content": + "Quia perferendis est consequuntur voluptates cumque commodi. Laboriosam expedita sit excepturi.", + "subject": "Eos doloribus repellendus provident" }, { - 'id': '160', - 'first-name': 'Lilla', - 'last-name': 'Abshire', - 'email': 'roselyn@rippin.org', - 'date': '1998-05-16 00:55:49 -0700', - 'content': 'Ratione deserunt ut ut beatae praesentium qui. Nulla ut ipsam tempore.', - 'subject': 'Autem nostrum tempora iure laborum' + "id": "160", + "first-name": "Lilla", + "last-name": "Abshire", + "email": "roselyn@rippin.org", + "date": "1998-05-16 00:55:49 -0700", + "content": "Ratione deserunt ut ut beatae praesentium qui. Nulla ut ipsam tempore.", + "subject": "Autem nostrum tempora iure laborum" }, { - 'id': '161', - 'first-name': 'Alessandro', - 'last-name': 'Hayes', - 'email': 'gia_bradtke@schimmelwalsh.biz', - 'date': '2001-11-28 23:52:57 -0800', - 'content': - 'Quasi perspiciatis tenetur dolorum. Quae cupiditate fuga molestiae et tempore soluta.', - 'subject': 'Non ipsam quis soluta' + "id": "161", + "first-name": "Alessandro", + "last-name": "Hayes", + "email": "gia_bradtke@schimmelwalsh.biz", + "date": "2001-11-28 23:52:57 -0800", + "content": + "Quasi perspiciatis tenetur dolorum. Quae cupiditate fuga molestiae et tempore soluta.", + "subject": "Non ipsam quis soluta" }, { - 'id': '162', - 'first-name': 'Sharon', - 'last-name': 'Goodwin', - 'email': 'ulices.schimmel@oreillyabshire.name', - 'date': '2010-03-12 00:46:00 -0800', - 'content': 'Neque omnis in. Qui ad sint. Velit voluptatibus repellat esse at.', - 'subject': 'Magni exercitationem quas consectetur qui quia id' + "id": "162", + "first-name": "Sharon", + "last-name": "Goodwin", + "email": "ulices.schimmel@oreillyabshire.name", + "date": "2010-03-12 00:46:00 -0800", + "content": "Neque omnis in. Qui ad sint. Velit voluptatibus repellat esse at.", + "subject": "Magni exercitationem quas consectetur qui quia id" }, { - 'id': '163', - 'first-name': 'Claude', - 'last-name': 'Gleason', - 'email': 'ken.gulgowski@labadie.net', - 'date': '2003-05-30 14:58:54 -0700', - 'content': 'Et sit non harum quo sunt. Odio beatae voluptatem ad. Nemo in hic nulla.', - 'subject': 'Nobis consequatur non sunt sequi ex nihil' + "id": "163", + "first-name": "Claude", + "last-name": "Gleason", + "email": "ken.gulgowski@labadie.net", + "date": "2003-05-30 14:58:54 -0700", + "content": "Et sit non harum quo sunt. Odio beatae voluptatem ad. Nemo in hic nulla.", + "subject": "Nobis consequatur non sunt sequi ex nihil" }, { - 'id': '164', - 'first-name': 'Maximilian', - 'last-name': 'Mann', - 'email': 'samir@stehr.biz', - 'date': '1993-08-21 15:54:18 -0700', - 'content': - 'Minus quae voluptatem sequi. Distinctio voluptatem amet iusto velit et praesentium. Distinctio ipsum voluptas voluptas.', - 'subject': 'Facere voluptatem laudantium laboriosam omnis' + "id": "164", + "first-name": "Maximilian", + "last-name": "Mann", + "email": "samir@stehr.biz", + "date": "1993-08-21 15:54:18 -0700", + "content": + "Minus quae voluptatem sequi. Distinctio voluptatem amet iusto velit et praesentium. Distinctio ipsum voluptas voluptas.", + "subject": "Facere voluptatem laudantium laboriosam omnis" }, { - 'id': '165', - 'first-name': 'Jennyfer', - 'last-name': 'Satterfield', - 'email': 'janiya_senger@olson.info', - 'date': '2006-09-21 00:36:50 -0700', - 'content': 'Doloribus praesentium excepturi omnis.', - 'subject': 'Non fuga unde incidunt ad exercitationem maxime laboriosam qui' + "id": "165", + "first-name": "Jennyfer", + "last-name": "Satterfield", + "email": "janiya_senger@olson.info", + "date": "2006-09-21 00:36:50 -0700", + "content": "Doloribus praesentium excepturi omnis.", + "subject": "Non fuga unde incidunt ad exercitationem maxime laboriosam qui" }, { - 'id': '166', - 'first-name': 'Robin', - 'last-name': 'Murray', - 'email': 'alycia@cruickshank.name', - 'date': '1985-10-04 03:44:39 -0700', - 'content': 'Repudiandae dolorem ut. Possimus earum dignissimos temporibus amet vel eum.', - 'subject': 'Vel culpa debitis quam' + "id": "166", + "first-name": "Robin", + "last-name": "Murray", + "email": "alycia@cruickshank.name", + "date": "1985-10-04 03:44:39 -0700", + "content": "Repudiandae dolorem ut. Possimus earum dignissimos temporibus amet vel eum.", + "subject": "Vel culpa debitis quam" }, { - 'id': '167', - 'first-name': 'Albina', - 'last-name': 'Reinger', - 'email': 'guie.gleason@gorczany.info', - 'date': '1985-10-02 08:07:53 -0700', - 'content': 'Natus rerum repellat voluptas. Distinctio dolor est in dolores.', - 'subject': 'Modi perspiciatis iure odio hic et dignissimos rem qui' + "id": "167", + "first-name": "Albina", + "last-name": "Reinger", + "email": "guie.gleason@gorczany.info", + "date": "1985-10-02 08:07:53 -0700", + "content": "Natus rerum repellat voluptas. Distinctio dolor est in dolores.", + "subject": "Modi perspiciatis iure odio hic et dignissimos rem qui" }, { - 'id': '168', - 'first-name': 'Eloisa', - 'last-name': 'Wolf', - 'email': 'leopold@jenkins.info', - 'date': '2007-02-19 09:25:29 -0800', - 'content': 'Corporis ut dolorem ullam quidem ratione. Nam eveniet dicta autem eum.', - 'subject': 'Facilis voluptas vel repellat et aut amet est' + "id": "168", + "first-name": "Eloisa", + "last-name": "Wolf", + "email": "leopold@jenkins.info", + "date": "2007-02-19 09:25:29 -0800", + "content": "Corporis ut dolorem ullam quidem ratione. Nam eveniet dicta autem eum.", + "subject": "Facilis voluptas vel repellat et aut amet est" }, { - 'id': '169', - 'first-name': 'Caden', - 'last-name': 'Cartwright', - 'email': 'mohammad_lockman@okoncrooks.net', - 'date': '1974-11-14 03:12:44 -0800', - 'content': - 'Sunt nobis voluptate quasi sapiente magni a officia. Laudantium perspiciatis quod quis quidem voluptatum pariatur. Sit ut optio tempora.', - 'subject': 'Nihil maxime officia et repellat' + "id": "169", + "first-name": "Caden", + "last-name": "Cartwright", + "email": "mohammad_lockman@okoncrooks.net", + "date": "1974-11-14 03:12:44 -0800", + "content": + "Sunt nobis voluptate quasi sapiente magni a officia. Laudantium perspiciatis quod quis quidem voluptatum pariatur. Sit ut optio tempora.", + "subject": "Nihil maxime officia et repellat" }, { - 'id': '170', - 'first-name': 'Raul', - 'last-name': 'Sipes', - 'email': 'danial.miller@kulas.info', - 'date': '1996-12-11 14:14:16 -0800', - 'content': - 'Ea rerum quo id omnis. Hic est voluptate voluptatem ut. Rerum eos ipsa laboriosam et ut expedita.', - 'subject': 'Aliquam reiciendis quam expedita sed ad neque voluptas' + "id": "170", + "first-name": "Raul", + "last-name": "Sipes", + "email": "danial.miller@kulas.info", + "date": "1996-12-11 14:14:16 -0800", + "content": + "Ea rerum quo id omnis. Hic est voluptate voluptatem ut. Rerum eos ipsa laboriosam et ut expedita.", + "subject": "Aliquam reiciendis quam expedita sed ad neque voluptas" }, { - 'id': '171', - 'first-name': 'Allie', - 'last-name': 'Runolfsson', - 'email': 'skye@marvin.com', - 'date': '2011-07-31 19:37:22 -0700', - 'content': 'Perspiciatis mollitia fugit sunt et.', - 'subject': 'Nihil expedita neque reprehenderit' + "id": "171", + "first-name": "Allie", + "last-name": "Runolfsson", + "email": "skye@marvin.com", + "date": "2011-07-31 19:37:22 -0700", + "content": "Perspiciatis mollitia fugit sunt et.", + "subject": "Nihil expedita neque reprehenderit" }, { - 'id': '172', - 'first-name': 'Belle', - 'last-name': 'Nader', - 'email': 'eugenia@mante.info', - 'date': '1995-09-06 05:30:08 -0700', - 'content': 'Expedita delectus quis ipsa dolore voluptatum.', - 'subject': 'Recusandae quasi ullam consequatur assumenda aliquid unde' + "id": "172", + "first-name": "Belle", + "last-name": "Nader", + "email": "eugenia@mante.info", + "date": "1995-09-06 05:30:08 -0700", + "content": "Expedita delectus quis ipsa dolore voluptatum.", + "subject": "Recusandae quasi ullam consequatur assumenda aliquid unde" }, { - 'id': '173', - 'first-name': 'Clemens', - 'last-name': 'Tromp', - 'email': 'geovanny@kilback.org', - 'date': '1980-11-28 08:48:35 -0800', - 'content': 'Sint eos ea quidem tempora.', - 'subject': 'Velit aperiam consequatur ut et aliquam at' + "id": "173", + "first-name": "Clemens", + "last-name": "Tromp", + "email": "geovanny@kilback.org", + "date": "1980-11-28 08:48:35 -0800", + "content": "Sint eos ea quidem tempora.", + "subject": "Velit aperiam consequatur ut et aliquam at" }, { - 'id': '174', - 'first-name': 'Bettie', - 'last-name': 'Mueller', - 'email': 'edgardo@little.net', - 'date': '1983-06-26 14:10:56 -0700', - 'content': 'Dolore tempore accusamus.', - 'subject': 'Autem tempore et ut' + "id": "174", + "first-name": "Bettie", + "last-name": "Mueller", + "email": "edgardo@little.net", + "date": "1983-06-26 14:10:56 -0700", + "content": "Dolore tempore accusamus.", + "subject": "Autem tempore et ut" }, { - 'id': '175', - 'first-name': 'Guy', - 'last-name': 'King', - 'email': 'macie@schmeler.info', - 'date': '1999-03-28 22:34:59 -0800', - 'content': 'Recusandae laborum ut et eaque eum.', - 'subject': 'Dolor ullam totam consequatur eos fuga' + "id": "175", + "first-name": "Guy", + "last-name": "King", + "email": "macie@schmeler.info", + "date": "1999-03-28 22:34:59 -0800", + "content": "Recusandae laborum ut et eaque eum.", + "subject": "Dolor ullam totam consequatur eos fuga" }, { - 'id': '176', - 'first-name': 'Cydney', - 'last-name': 'Cronin', - 'email': 'camren@thompson.org', - 'date': '1993-10-23 02:50:41 -0700', - 'content': 'Exercitationem modi eos sint vero. Iste possimus quis. Non est voluptas.', - 'subject': 'Tempora ipsum soluta ut corrupti omnis in' + "id": "176", + "first-name": "Cydney", + "last-name": "Cronin", + "email": "camren@thompson.org", + "date": "1993-10-23 02:50:41 -0700", + "content": "Exercitationem modi eos sint vero. Iste possimus quis. Non est voluptas.", + "subject": "Tempora ipsum soluta ut corrupti omnis in" }, { - 'id': '177', - 'first-name': 'Ludwig', - 'last-name': 'Hoeger', - 'email': 'javon@torpolson.info', - 'date': '2007-12-20 19:09:13 -0800', - 'content': 'Architecto ut optio tempore pariatur itaque saepe.', - 'subject': 'Earum unde quis officiis doloremque et animi qui' + "id": "177", + "first-name": "Ludwig", + "last-name": "Hoeger", + "email": "javon@torpolson.info", + "date": "2007-12-20 19:09:13 -0800", + "content": "Architecto ut optio tempore pariatur itaque saepe.", + "subject": "Earum unde quis officiis doloremque et animi qui" }, { - 'id': '178', - 'first-name': 'Travon', - 'last-name': 'Jacobi', - 'email': 'jameson_streich@hansen.org', - 'date': '2013-02-03 09:53:51 -0800', - 'content': 'Autem dolorem totam atque id sit. Consectetur dolor maiores.', - 'subject': 'Quia autem deleniti ullam neque odio' + "id": "178", + "first-name": "Travon", + "last-name": "Jacobi", + "email": "jameson_streich@hansen.org", + "date": "2013-02-03 09:53:51 -0800", + "content": "Autem dolorem totam atque id sit. Consectetur dolor maiores.", + "subject": "Quia autem deleniti ullam neque odio" }, { - 'id': '179', - 'first-name': 'Brennan', - 'last-name': 'Jaskolski', - 'email': 'harold_thompson@schaefer.info', - 'date': '2004-01-13 10:53:47 -0800', - 'content': 'Libero et dolorem nihil. Omnis consequuntur possimus ut.', - 'subject': 'Eum labore omnis ipsa doloremque consequuntur soluta esse fuga' + "id": "179", + "first-name": "Brennan", + "last-name": "Jaskolski", + "email": "harold_thompson@schaefer.info", + "date": "2004-01-13 10:53:47 -0800", + "content": "Libero et dolorem nihil. Omnis consequuntur possimus ut.", + "subject": "Eum labore omnis ipsa doloremque consequuntur soluta esse fuga" }, { - 'id': '180', - 'first-name': 'Clifton', - 'last-name': 'Boyer', - 'email': 'justine@skiles.biz', - 'date': '2000-01-28 22:33:14 -0800', - 'content': - 'Nobis recusandae fugiat quibusdam doloribus. Aut praesentium corrupti tenetur ullam quia.', - 'subject': 'Ea dolorem voluptas aut cumque inventore delectus non molestiae' + "id": "180", + "first-name": "Clifton", + "last-name": "Boyer", + "email": "justine@skiles.biz", + "date": "2000-01-28 22:33:14 -0800", + "content": + "Nobis recusandae fugiat quibusdam doloribus. Aut praesentium corrupti tenetur ullam quia.", + "subject": "Ea dolorem voluptas aut cumque inventore delectus non molestiae" }, { - 'id': '181', - 'first-name': 'Walker', - 'last-name': 'Rogahn', - 'email': 'stanton@rempel.net', - 'date': '2012-04-02 20:05:38 -0700', - 'content': 'Consectetur et soluta. Minus voluptatem quod aut vitae praesentium.', - 'subject': 'Tenetur architecto reprehenderit corporis fuga et rerum vel' + "id": "181", + "first-name": "Walker", + "last-name": "Rogahn", + "email": "stanton@rempel.net", + "date": "2012-04-02 20:05:38 -0700", + "content": "Consectetur et soluta. Minus voluptatem quod aut vitae praesentium.", + "subject": "Tenetur architecto reprehenderit corporis fuga et rerum vel" }, { - 'id': '182', - 'first-name': 'Jennings', - 'last-name': 'Hills', - 'email': 'kenton@murrayharvey.biz', - 'date': '2007-09-24 22:09:51 -0700', - 'content': - 'Velit porro quidem nostrum. Perspiciatis consequatur consectetur reiciendis sunt cupiditate quae. Vitae et ut autem iure.', - 'subject': 'Cupiditate quis maiores omnis' + "id": "182", + "first-name": "Jennings", + "last-name": "Hills", + "email": "kenton@murrayharvey.biz", + "date": "2007-09-24 22:09:51 -0700", + "content": + "Velit porro quidem nostrum. Perspiciatis consequatur consectetur reiciendis sunt cupiditate quae. Vitae et ut autem iure.", + "subject": "Cupiditate quis maiores omnis" }, { - 'id': '183', - 'first-name': 'Julianne', - 'last-name': 'O\'Kon', - 'email': 'helene@abshire.com', - 'date': '1987-02-09 22:56:12 -0800', - 'content': - 'Voluptas voluptatem veniam porro dolorem maxime. Itaque eveniet laborum optio sed aspernatur omnis. Veritatis enim itaque sint illo ipsam eius.', - 'subject': 'Corporis et laboriosam aspernatur aut' + "id": "183", + "first-name": "Julianne", + "last-name": "O'Kon", + "email": "helene@abshire.com", + "date": "1987-02-09 22:56:12 -0800", + "content": + "Voluptas voluptatem veniam porro dolorem maxime. Itaque eveniet laborum optio sed aspernatur omnis. Veritatis enim itaque sint illo ipsam eius.", + "subject": "Corporis et laboriosam aspernatur aut" }, { - 'id': '184', - 'first-name': 'Raymond', - 'last-name': 'Orn', - 'email': 'cloyd@rempel.biz', - 'date': '2014-02-04 04:33:02 -0800', - 'content': - 'Eum voluptatibus accusantium rem. Deleniti harum eum. Illo est facere illum saepe voluptas.', - 'subject': 'Eveniet est architecto id ut rerum nam quidem' + "id": "184", + "first-name": "Raymond", + "last-name": "Orn", + "email": "cloyd@rempel.biz", + "date": "2014-02-04 04:33:02 -0800", + "content": + "Eum voluptatibus accusantium rem. Deleniti harum eum. Illo est facere illum saepe voluptas.", + "subject": "Eveniet est architecto id ut rerum nam quidem" }, { - 'id': '185', - 'first-name': 'Johan', - 'last-name': 'Legros', - 'email': 'rosie_ernser@wolf.com', - 'date': '1989-03-02 11:17:10 -0800', - 'content': 'Architecto explicabo praesentium amet eaque quibusdam.', - 'subject': 'Consectetur fugiat iusto omnis aspernatur ut' + "id": "185", + "first-name": "Johan", + "last-name": "Legros", + "email": "rosie_ernser@wolf.com", + "date": "1989-03-02 11:17:10 -0800", + "content": "Architecto explicabo praesentium amet eaque quibusdam.", + "subject": "Consectetur fugiat iusto omnis aspernatur ut" }, { - 'id': '186', - 'first-name': 'Daryl', - 'last-name': 'Labadie', - 'email': 'ashly_thompson@casper.net', - 'date': '2003-01-28 00:02:56 -0800', - 'content': 'Et est doloribus. Fuga hic sed voluptatibus ullam officia aspernatur.', - 'subject': 'A sunt eum quas accusamus' + "id": "186", + "first-name": "Daryl", + "last-name": "Labadie", + "email": "ashly_thompson@casper.net", + "date": "2003-01-28 00:02:56 -0800", + "content": "Et est doloribus. Fuga hic sed voluptatibus ullam officia aspernatur.", + "subject": "A sunt eum quas accusamus" }, { - 'id': '187', - 'first-name': 'Gavin', - 'last-name': 'Moore', - 'email': 'dahlia@leffleroberbrunner.biz', - 'date': '1970-10-15 07:36:57 -0700', - 'content': 'Sapiente ipsum magni dolore est dolor.', - 'subject': 'Est maxime consequatur esse qui dicta aut quaerat' + "id": "187", + "first-name": "Gavin", + "last-name": "Moore", + "email": "dahlia@leffleroberbrunner.biz", + "date": "1970-10-15 07:36:57 -0700", + "content": "Sapiente ipsum magni dolore est dolor.", + "subject": "Est maxime consequatur esse qui dicta aut quaerat" }, { - 'id': '188', - 'first-name': 'Coby', - 'last-name': 'Swaniawski', - 'email': 'millie.labadie@wuckert.name', - 'date': '2012-09-14 00:25:46 -0700', - 'content': - 'Magni qui molestias debitis reprehenderit vel quo est. Blanditiis debitis autem neque non illo.', - 'subject': 'Rerum accusantium magni dolorem in reprehenderit et voluptas' + "id": "188", + "first-name": "Coby", + "last-name": "Swaniawski", + "email": "millie.labadie@wuckert.name", + "date": "2012-09-14 00:25:46 -0700", + "content": + "Magni qui molestias debitis reprehenderit vel quo est. Blanditiis debitis autem neque non illo.", + "subject": "Rerum accusantium magni dolorem in reprehenderit et voluptas" }, { - 'id': '189', - 'first-name': 'Luis', - 'last-name': 'Stracke', - 'email': 'merle@mrazswaniawski.biz', - 'date': '2007-11-11 05:28:46 -0800', - 'content': 'Neque magnam sint porro reprehenderit quo. In et reiciendis non velit et eum quos.', - 'subject': 'Sit voluptates nulla perspiciatis debitis dolor eaque a' + "id": "189", + "first-name": "Luis", + "last-name": "Stracke", + "email": "merle@mrazswaniawski.biz", + "date": "2007-11-11 05:28:46 -0800", + "content": "Neque magnam sint porro reprehenderit quo. In et reiciendis non velit et eum quos.", + "subject": "Sit voluptates nulla perspiciatis debitis dolor eaque a" }, { - 'id': '190', - 'first-name': 'Leone', - 'last-name': 'Huel', - 'email': 'emil@botsford.biz', - 'date': '2004-03-16 23:46:45 -0800', - 'content': 'Vitae amet et quae ullam.', - 'subject': 'Rerum enim voluptate qui' + "id": "190", + "first-name": "Leone", + "last-name": "Huel", + "email": "emil@botsford.biz", + "date": "2004-03-16 23:46:45 -0800", + "content": "Vitae amet et quae ullam.", + "subject": "Rerum enim voluptate qui" }, { - 'id': '191', - 'first-name': 'Aylin', - 'last-name': 'Kling', - 'email': 'anderson_jast@kozeyparisian.com', - 'date': '1979-06-17 04:05:50 -0700', - 'content': 'Quam eligendi numquam sint. Non ipsa et qui error dolor velit.', - 'subject': 'Culpa iste rerum facere praesentium deleniti sequi' + "id": "191", + "first-name": "Aylin", + "last-name": "Kling", + "email": "anderson_jast@kozeyparisian.com", + "date": "1979-06-17 04:05:50 -0700", + "content": "Quam eligendi numquam sint. Non ipsa et qui error dolor velit.", + "subject": "Culpa iste rerum facere praesentium deleniti sequi" }, { - 'id': '192', - 'first-name': 'Junior', - 'last-name': 'Bartoletti', - 'email': 'te@kuvalis.net', - 'date': '1994-12-09 11:00:34 -0800', - 'content': 'Velit eos et nemo dolore eum necessitatibus. Ea inventore adipisci.', - 'subject': 'Velit dolorem cumque ipsa' + "id": "192", + "first-name": "Junior", + "last-name": "Bartoletti", + "email": "te@kuvalis.net", + "date": "1994-12-09 11:00:34 -0800", + "content": "Velit eos et nemo dolore eum necessitatibus. Ea inventore adipisci.", + "subject": "Velit dolorem cumque ipsa" }, { - 'id': '193', - 'first-name': 'Nathanael', - 'last-name': 'Hermiston', - 'email': 'macy.cole@wittingcasper.info', - 'date': '2002-01-06 17:45:52 -0800', - 'content': - 'Corporis occaecati quidem quia repudiandae repellendus beatae similique. Inventore quo ullam.', - 'subject': 'Quidem expedita quia inventore dolores ratione totam et dignissimos' + "id": "193", + "first-name": "Nathanael", + "last-name": "Hermiston", + "email": "macy.cole@wittingcasper.info", + "date": "2002-01-06 17:45:52 -0800", + "content": + "Corporis occaecati quidem quia repudiandae repellendus beatae similique. Inventore quo ullam.", + "subject": "Quidem expedita quia inventore dolores ratione totam et dignissimos" }, { - 'id': '194', - 'first-name': 'Hal', - 'last-name': 'Bruen', - 'email': 'nathen.ziemann@gerlachko.name', - 'date': '1996-03-01 01:35:30 -0800', - 'content': - 'Qui eius aspernatur et aut et vel in. Adipisci aliquid consequatur dolores et ut. Est aut temporibus.', - 'subject': 'Voluptas placeat eveniet non quas assumenda quam minus' + "id": "194", + "first-name": "Hal", + "last-name": "Bruen", + "email": "nathen.ziemann@gerlachko.name", + "date": "1996-03-01 01:35:30 -0800", + "content": + "Qui eius aspernatur et aut et vel in. Adipisci aliquid consequatur dolores et ut. Est aut temporibus.", + "subject": "Voluptas placeat eveniet non quas assumenda quam minus" }, { - 'id': '195', - 'first-name': 'Freddie', - 'last-name': 'Thompson', - 'email': 'elia@aufderharbrown.org', - 'date': '2005-03-20 05:07:30 -0800', - 'content': 'Dolor nemo sed molestiae quae quia.', - 'subject': 'Quam sint et voluptatem et fuga sint ut saepe' + "id": "195", + "first-name": "Freddie", + "last-name": "Thompson", + "email": "elia@aufderharbrown.org", + "date": "2005-03-20 05:07:30 -0800", + "content": "Dolor nemo sed molestiae quae quia.", + "subject": "Quam sint et voluptatem et fuga sint ut saepe" }, { - 'id': '196', - 'first-name': 'Aida', - 'last-name': 'Gorczany', - 'email': 'olga.labadie@abshire.name', - 'date': '1989-07-26 04:26:19 -0700', - 'content': - 'Sit qui voluptatem facere. Similique alias quia sit ipsum. Ut corrupti tempore molestiae.', - 'subject': 'Qui veniam blanditiis nesciunt beatae tempore aut fugiat maiores' + "id": "196", + "first-name": "Aida", + "last-name": "Gorczany", + "email": "olga.labadie@abshire.name", + "date": "1989-07-26 04:26:19 -0700", + "content": + "Sit qui voluptatem facere. Similique alias quia sit ipsum. Ut corrupti tempore molestiae.", + "subject": "Qui veniam blanditiis nesciunt beatae tempore aut fugiat maiores" }, { - 'id': '197', - 'first-name': 'Isabelle', - 'last-name': 'Collier', - 'email': 'christiana_gottlieb@borer.biz', - 'date': '1978-05-15 13:13:34 -0700', - 'content': 'Aliquam earum velit ut.', - 'subject': 'Neque et voluptate ratione totam voluptas est nulla ipsum' + "id": "197", + "first-name": "Isabelle", + "last-name": "Collier", + "email": "christiana_gottlieb@borer.biz", + "date": "1978-05-15 13:13:34 -0700", + "content": "Aliquam earum velit ut.", + "subject": "Neque et voluptate ratione totam voluptas est nulla ipsum" }, { - 'id': '198', - 'first-name': 'Ida', - 'last-name': 'Reichert', - 'email': 'mervin@keeling.com', - 'date': '1991-02-06 05:02:15 -0800', - 'content': - 'Velit in at et dicta tenetur. Doloremque cupiditate est. Excepturi non minus aspernatur dolores qui quaerat architecto.', - 'subject': 'Ut voluptas qui ad minus' + "id": "198", + "first-name": "Ida", + "last-name": "Reichert", + "email": "mervin@keeling.com", + "date": "1991-02-06 05:02:15 -0800", + "content": + "Velit in at et dicta tenetur. Doloremque cupiditate est. Excepturi non minus aspernatur dolores qui quaerat architecto.", + "subject": "Ut voluptas qui ad minus" }, { - 'id': '199', - 'first-name': 'Angelina', - 'last-name': 'Mueller', - 'email': 'leonel@purdyschroeder.org', - 'date': '2008-06-17 01:01:57 -0700', - 'content': - 'Recusandae eius non necessitatibus. Quisquam qui quo. Voluptas dolorem dolorem sit repellat laudantium ducimus qui.', - 'subject': 'Dolorem atque impedit qui soluta' + "id": "199", + "first-name": "Angelina", + "last-name": "Mueller", + "email": "leonel@purdyschroeder.org", + "date": "2008-06-17 01:01:57 -0700", + "content": + "Recusandae eius non necessitatibus. Quisquam qui quo. Voluptas dolorem dolorem sit repellat laudantium ducimus qui.", + "subject": "Dolorem atque impedit qui soluta" }, { - 'id': '200', - 'first-name': 'Marcelle', - 'last-name': 'Connelly', - 'email': 'heath@leuschke.net', - 'date': '1983-10-02 18:32:18 -0700', - 'content': - 'Debitis quasi voluptates et voluptatibus rerum. Et explicabo quia qui qui voluptate dolor.', - 'subject': 'Rem molestiae nobis consequatur eligendi ut' + "id": "200", + "first-name": "Marcelle", + "last-name": "Connelly", + "email": "heath@leuschke.net", + "date": "1983-10-02 18:32:18 -0700", + "content": + "Debitis quasi voluptates et voluptatibus rerum. Et explicabo quia qui qui voluptate dolor.", + "subject": "Rem molestiae nobis consequatur eligendi ut" }, { - 'id': '201', - 'first-name': 'Bob', - 'last-name': 'Brown', - 'email': 'bob@brown.net', - 'date': '1983-10-02 18:32:18 -0700', - 'content': - 'Debitis quasi voluptates et voluptatibus rerum. Et explicabo quia qui qui voluptate dolor.', - 'subject': 'Urgent question about whipped cream', - 'draft': true + "id": "201", + "first-name": "Bob", + "last-name": "Brown", + "email": "bob@brown.net", + "date": "1983-10-02 18:32:18 -0700", + "content": + "Debitis quasi voluptates et voluptatibus rerum. Et explicabo quia qui qui voluptate dolor.", + "subject": "Urgent question about whipped cream", + "draft": true }, { - 'id': '202', - 'first-name': 'Mary', - 'last-name': 'Jones', - 'email': 'mary@jones.net', - 'date': '1983-10-02 18:32:18 -0700', - 'content': - 'Debitis quasi voluptates et voluptatibus rerum. Et explicabo quia qui qui voluptate dolor.', - 'subject': 'Fwd: wedding photos', - 'draft': true + "id": "202", + "first-name": "Mary", + "last-name": "Jones", + "email": "mary@jones.net", + "date": "1983-10-02 18:32:18 -0700", + "content": + "Debitis quasi voluptates et voluptatibus rerum. Et explicabo quia qui qui voluptate dolor.", + "subject": "Fwd: wedding photos", + "draft": true } ] diff --git a/modules/playground/src/routing/inbox-app.ts b/modules/playground/src/routing/inbox-app.ts index 751f27cb2e..d8a0d63751 100644 --- a/modules/playground/src/routing/inbox-app.ts +++ b/modules/playground/src/routing/inbox-app.ts @@ -1,5 +1,13 @@ import {Component, Injectable} from 'angular2/core'; -import {RouterLink, RouteConfig, Router, Route, RouterOutlet, Location, RouteParams} from 'angular2/router'; +import { + RouterLink, + RouteConfig, + Router, + Route, + RouterOutlet, + Location, + RouteParams +} from 'angular2/router'; import * as db from './data'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent, DateWrapper} from 'angular2/src/facade/lang'; @@ -64,8 +72,8 @@ class DbService { } emails(): Promise<any[]> { - return this.getData().then( - (data: any[]): any[] => data.filter(record => !isPresent(record['draft']))); + return this.getData().then((data: any[]): any[] => + data.filter(record => !isPresent(record['draft']))); } email(id): Promise<any> { @@ -99,19 +107,18 @@ class InboxCmp { constructor(public router: Router, db: DbService, params: RouteParams) { var sortType = params.get('sort'); - var sortEmailsByDate = isPresent(sortType) && sortType == 'date'; + var sortEmailsByDate = isPresent(sortType) && sortType == "date"; PromiseWrapper.then(db.emails(), (emails: any[]) => { this.ready = true; this.items = emails.map(data => new InboxRecord(data)); if (sortEmailsByDate) { - this.items.sort( - (a: InboxRecord, b: InboxRecord) => - DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) < - DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ? - -1 : - 1); + this.items.sort((a: InboxRecord, b: InboxRecord) => + DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) < + DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ? + -1 : + 1); } }); } diff --git a/modules/playground/src/routing/index.ts b/modules/playground/src/routing/index.ts index b7ef83791a..c745adeb23 100644 --- a/modules/playground/src/routing/index.ts +++ b/modules/playground/src/routing/index.ts @@ -4,6 +4,6 @@ import {bootstrap} from 'angular2/platform/browser'; import {ROUTER_PROVIDERS, HashLocationStrategy, LocationStrategy} from 'angular2/router'; export function main() { - bootstrap( - InboxApp, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]); + bootstrap(InboxApp, + [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]); } diff --git a/modules/playground/src/template_driven_forms/index.ts b/modules/playground/src/template_driven_forms/index.ts index 130f64e887..adaef4ebe8 100644 --- a/modules/playground/src/template_driven_forms/index.ts +++ b/modules/playground/src/template_driven_forms/index.ts @@ -1,6 +1,15 @@ import {bootstrap} from 'angular2/platform/browser'; import {Component, Directive, Host, forwardRef, Provider} from 'angular2/core'; -import {ControlGroup, NgIf, NgFor, NG_VALIDATORS, FORM_DIRECTIVES, NgControl, Validators, NgForm} from 'angular2/common'; +import { + ControlGroup, + NgIf, + NgFor, + NG_VALIDATORS, + FORM_DIRECTIVES, + NgControl, + Validators, + NgForm +} from 'angular2/common'; import {RegExpWrapper, print, isPresent, CONST_EXPR} from 'angular2/src/facade/lang'; @@ -11,7 +20,7 @@ class CheckoutModel { firstName: string; middleName: string; lastName: string; - country: string = 'Canada'; + country: string = "Canada"; creditCard: string; amount: number; @@ -26,7 +35,7 @@ function creditCardValidator(c): {[key: string]: boolean} { if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) { return null; } else { - return {'invalidCreditCard': true}; + return {"invalidCreditCard": true}; } } @@ -151,7 +160,7 @@ class TemplateDrivenForms { countries = ['US', 'Canada']; onSubmit(): void { - print('Submitting:'); + print("Submitting:"); print(this.model); } } diff --git a/modules/playground/src/upgrade/index.ts b/modules/playground/src/upgrade/index.ts index 1e199681e6..e886105307 100644 --- a/modules/playground/src/upgrade/index.ts +++ b/modules/playground/src/upgrade/index.ts @@ -2,7 +2,8 @@ import {Component, Input, Output, EventEmitter} from 'angular2/core'; import {UpgradeAdapter} from 'angular2/upgrade'; import * as angular from '../../../angular2/src/upgrade/angular_js'; -var styles = [` +var styles = [ + ` .border { border: solid 2px DodgerBlue; } @@ -14,7 +15,8 @@ var styles = [` .content { padding: 1em; } - `]; + ` +]; var adapter: UpgradeAdapter = new UpgradeAdapter(); diff --git a/modules/playground/src/web_workers/images/b64.d.ts b/modules/playground/src/web_workers/images/b64.d.ts index cb874ee6f2..d34048ed49 100644 --- a/modules/playground/src/web_workers/images/b64.d.ts +++ b/modules/playground/src/web_workers/images/b64.d.ts @@ -1,4 +1,4 @@ -declare module 'B64' { +declare module "B64" { export function fromByteArray(arr: Uint8Array): string; export function toByteArray(str: string): Uint8Array; } \ No newline at end of file diff --git a/modules/playground/src/web_workers/images/background_index.ts b/modules/playground/src/web_workers/images/background_index.ts index 59caddeb7c..addba4ae4e 100644 --- a/modules/playground/src/web_workers/images/background_index.ts +++ b/modules/playground/src/web_workers/images/background_index.ts @@ -1,6 +1,6 @@ -import {ImageDemo} from './index_common'; -import {platform} from 'angular2/core'; -import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from 'angular2/platform/worker_app'; +import {ImageDemo} from "./index_common"; +import {platform} from "angular2/core"; +import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from "angular2/platform/worker_app"; export function main() { platform([WORKER_APP_PLATFORM]).application([WORKER_APP_APPLICATION]).bootstrap(ImageDemo) diff --git a/modules/playground/src/web_workers/images/bitmap.d.ts b/modules/playground/src/web_workers/images/bitmap.d.ts index 24102ab536..b8820d20a5 100644 --- a/modules/playground/src/web_workers/images/bitmap.d.ts +++ b/modules/playground/src/web_workers/images/bitmap.d.ts @@ -4,5 +4,5 @@ declare class Bitmap { subsample(n: number): void; dataURL(): string; - pixel: [any]; + pixel:[any]; } diff --git a/modules/playground/src/web_workers/images/index.ts b/modules/playground/src/web_workers/images/index.ts index 87e5f952d3..e158157e5f 100644 --- a/modules/playground/src/web_workers/images/index.ts +++ b/modules/playground/src/web_workers/images/index.ts @@ -1,6 +1,9 @@ import {platform, Provider} from 'angular2/core'; -import {WORKER_RENDER_APPLICATION, WORKER_RENDER_PLATFORM, WORKER_SCRIPT} from 'angular2/platform/worker_render'; +import { + WORKER_RENDER_APPLICATION, + WORKER_RENDER_PLATFORM, + WORKER_SCRIPT +} from 'angular2/platform/worker_render'; -platform([WORKER_RENDER_PLATFORM]).application([ - WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: 'loader.js'}) -]); +platform([WORKER_RENDER_PLATFORM]) + .application([WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: "loader.js"})]); diff --git a/modules/playground/src/web_workers/images/index_common.ts b/modules/playground/src/web_workers/images/index_common.ts index 931ca13e4a..71b9ba565d 100644 --- a/modules/playground/src/web_workers/images/index_common.ts +++ b/modules/playground/src/web_workers/images/index_common.ts @@ -14,7 +14,7 @@ export class ImageDemo { uploadFiles(files) { for (var i = 0; i < files.length; i++) { var reader = new FileReader(); - reader.addEventListener('load', this.handleReaderLoad(reader)); + reader.addEventListener("load", this.handleReaderLoad(reader)); reader.readAsArrayBuffer(files[i]); } } diff --git a/modules/playground/src/web_workers/images/services/bitmap.ts b/modules/playground/src/web_workers/images/services/bitmap.ts index 3ed3af3299..0b6004240b 100644 --- a/modules/playground/src/web_workers/images/services/bitmap.ts +++ b/modules/playground/src/web_workers/images/services/bitmap.ts @@ -4,7 +4,10 @@ declare var base64js; // Temporary fix for Typescript issue #4220 (https://github.com/Microsoft/TypeScript/issues/4220) // var _ImageData: (width: number, height: number) => void = <any>postMessage; -var _ImageData: {prototype: ImageData, new (width: number, height: number): ImageData;} = ImageData; +var _ImageData: { + prototype: ImageData, new (width: number, height: number): ImageData; +} += ImageData; // This class is based on the Bitmap examples at: // http://www.i-programmer.info/projects/36-web/6234-reading-a-bmp-file-in-javascript.html @@ -60,7 +63,7 @@ export class BitmapService { return imageData; } - private _swap(data: Uint8Array|number[], index1: number, index2: number) { + private _swap(data: Uint8Array | number[], index1: number, index2: number) { var temp = data[index1]; data[index1] = data[index2]; data[index2] = temp; @@ -72,22 +75,22 @@ export class BitmapService { var numFileBytes = this._getLittleEndianHex(imageData.width * imageData.height); var w = this._getLittleEndianHex(imageData.width); var h = this._getLittleEndianHex(imageData.height); - return 'BM' + // Signature - numFileBytes + // size of the file (bytes)* - '\x00\x00' + // reserved - '\x00\x00' + // reserved - '\x36\x00\x00\x00' + // offset of where BMP data lives (54 bytes) - '\x28\x00\x00\x00' + // number of remaining bytes in header from here (40 bytes) - w + // the width of the bitmap in pixels* - h + // the height of the bitmap in pixels* - '\x01\x00' + // the number of color planes (1) - '\x20\x00' + // 32 bits / pixel - '\x00\x00\x00\x00' + // No compression (0) - '\x00\x00\x00\x00' + // size of the BMP data (bytes)* - '\x13\x0B\x00\x00' + // 2835 pixels/meter - horizontal resolution - '\x13\x0B\x00\x00' + // 2835 pixels/meter - the vertical resolution - '\x00\x00\x00\x00' + // Number of colors in the palette (keep 0 for 32-bit) - '\x00\x00\x00\x00'; // 0 important colors (means all colors are important) + return 'BM' + // Signature + numFileBytes + // size of the file (bytes)* + '\x00\x00' + // reserved + '\x00\x00' + // reserved + '\x36\x00\x00\x00' + // offset of where BMP data lives (54 bytes) + '\x28\x00\x00\x00' + // number of remaining bytes in header from here (40 bytes) + w + // the width of the bitmap in pixels* + h + // the height of the bitmap in pixels* + '\x01\x00' + // the number of color planes (1) + '\x20\x00' + // 32 bits / pixel + '\x00\x00\x00\x00' + // No compression (0) + '\x00\x00\x00\x00' + // size of the BMP data (bytes)* + '\x13\x0B\x00\x00' + // 2835 pixels/meter - horizontal resolution + '\x13\x0B\x00\x00' + // 2835 pixels/meter - the vertical resolution + '\x00\x00\x00\x00' + // Number of colors in the palette (keep 0 for 32-bit) + '\x00\x00\x00\x00'; // 0 important colors (means all colors are important) } private _BMPToImageData(bmp: BitmapFile): ImageData { @@ -161,10 +164,18 @@ export class BitmapService { interface BitmapFile { fileHeader: { - bfType: number; bfSize: number; bfReserved1: number; bfReserved2: number; bfOffBits: number; + bfType: number; + bfSize: number; + bfReserved1: number; + bfReserved2: number; + bfOffBits: number; }; infoHeader: { - biSize: number; biWidth: number; biHeight: number; biPlanes: number; biBitCount: number; + biSize: number; + biWidth: number; + biHeight: number; + biPlanes: number; + biBitCount: number; biCompression: number; biSizeImage: number; biXPelsPerMeter: number; diff --git a/modules/playground/src/web_workers/images/single_thread.ts b/modules/playground/src/web_workers/images/single_thread.ts index e103345e63..94dab0f498 100644 --- a/modules/playground/src/web_workers/images/single_thread.ts +++ b/modules/playground/src/web_workers/images/single_thread.ts @@ -1,5 +1,5 @@ -import {bootstrap} from 'angular2/platform/browser'; -import {ImageDemo} from './index_common'; +import {bootstrap} from "angular2/platform/browser"; +import {ImageDemo} from "./index_common"; export function main() { bootstrap(ImageDemo); diff --git a/modules/playground/src/web_workers/kitchen_sink/background_index.ts b/modules/playground/src/web_workers/kitchen_sink/background_index.ts index 870d3fe998..b59f76a443 100644 --- a/modules/playground/src/web_workers/kitchen_sink/background_index.ts +++ b/modules/playground/src/web_workers/kitchen_sink/background_index.ts @@ -1,6 +1,6 @@ -import {HelloCmp} from './index_common'; -import {platform} from 'angular2/core'; -import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from 'angular2/platform/worker_app'; +import {HelloCmp} from "./index_common"; +import {platform} from "angular2/core"; +import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from "angular2/platform/worker_app"; export function main() { platform([WORKER_APP_PLATFORM]).application([WORKER_APP_APPLICATION]).bootstrap(HelloCmp); diff --git a/modules/playground/src/web_workers/kitchen_sink/index.ts b/modules/playground/src/web_workers/kitchen_sink/index.ts index 87e5f952d3..e158157e5f 100644 --- a/modules/playground/src/web_workers/kitchen_sink/index.ts +++ b/modules/playground/src/web_workers/kitchen_sink/index.ts @@ -1,6 +1,9 @@ import {platform, Provider} from 'angular2/core'; -import {WORKER_RENDER_APPLICATION, WORKER_RENDER_PLATFORM, WORKER_SCRIPT} from 'angular2/platform/worker_render'; +import { + WORKER_RENDER_APPLICATION, + WORKER_RENDER_PLATFORM, + WORKER_SCRIPT +} from 'angular2/platform/worker_render'; -platform([WORKER_RENDER_PLATFORM]).application([ - WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: 'loader.js'}) -]); +platform([WORKER_RENDER_PLATFORM]) + .application([WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: "loader.js"})]); diff --git a/modules/playground/src/web_workers/message_broker/background_index.ts b/modules/playground/src/web_workers/message_broker/background_index.ts index 5100ac50ae..4b12ba8cbb 100644 --- a/modules/playground/src/web_workers/message_broker/background_index.ts +++ b/modules/playground/src/web_workers/message_broker/background_index.ts @@ -1,6 +1,6 @@ -import {platform} from 'angular2/core'; -import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from 'angular2/platform/worker_app'; -import {App} from './index_common'; +import {platform} from "angular2/core"; +import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from "angular2/platform/worker_app"; +import {App} from "./index_common"; export function main() { platform([WORKER_APP_PLATFORM]).application([WORKER_APP_APPLICATION]).bootstrap(App) diff --git a/modules/playground/src/web_workers/message_broker/index.ts b/modules/playground/src/web_workers/message_broker/index.ts index c5d8dba6ff..2d49b80d81 100644 --- a/modules/playground/src/web_workers/message_broker/index.ts +++ b/modules/playground/src/web_workers/message_broker/index.ts @@ -1,27 +1,38 @@ import {platform, Provider} from 'angular2/core'; -import {WORKER_RENDER_APPLICATION, WORKER_RENDER_PLATFORM, WORKER_SCRIPT, UiArguments, FnArg, PRIMITIVE, ClientMessageBrokerFactory} from 'angular2/platform/worker_render'; +import { + WORKER_RENDER_APPLICATION, + WORKER_RENDER_PLATFORM, + WORKER_SCRIPT, + UiArguments, + FnArg, + PRIMITIVE, + ClientMessageBrokerFactory +} from 'angular2/platform/worker_render'; -const ECHO_CHANNEL = 'ECHO'; +const ECHO_CHANNEL = "ECHO"; -let ref = platform([WORKER_RENDER_PLATFORM]).application([ - WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: 'loader.js'}) -]); +let ref = + platform([WORKER_RENDER_PLATFORM]) + .application( + [WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: "loader.js"})]); let brokerFactory: ClientMessageBrokerFactory = ref.injector.get(ClientMessageBrokerFactory); var broker = brokerFactory.createMessageBroker(ECHO_CHANNEL, false); -document.getElementById('send_echo').addEventListener('click', (e) => { - var val = (<HTMLInputElement>document.getElementById('echo_input')).value; - // TODO(jteplitz602): Replace default constructors with real constructors - // once they're in the .d.ts file (#3926) - var args = new UiArguments('echo'); - args.method = 'echo'; - var fnArg = new FnArg(val, PRIMITIVE); - fnArg.value = val; - fnArg.type = PRIMITIVE; - args.args = [fnArg]; +document.getElementById("send_echo") + .addEventListener("click", (e) => { + var val = (<HTMLInputElement>document.getElementById("echo_input")).value; + // TODO(jteplitz602): Replace default constructors with real constructors + // once they're in the .d.ts file (#3926) + var args = new UiArguments("echo"); + args.method = "echo"; + var fnArg = new FnArg(val, PRIMITIVE); + fnArg.value = val; + fnArg.type = PRIMITIVE; + args.args = [fnArg]; - broker.runOnService(args, PRIMITIVE).then((echo_result: string) => { - document.getElementById('echo_result').innerHTML = - `<span class='response'>${echo_result}</span>`; - }); -}); + broker.runOnService(args, PRIMITIVE) + .then((echo_result: string) => { + document.getElementById("echo_result").innerHTML = + `<span class='response'>${echo_result}</span>`; + }); + }); diff --git a/modules/playground/src/web_workers/message_broker/index_common.ts b/modules/playground/src/web_workers/message_broker/index_common.ts index 99c7ba4b55..ea716ca931 100644 --- a/modules/playground/src/web_workers/message_broker/index_common.ts +++ b/modules/playground/src/web_workers/message_broker/index_common.ts @@ -1,14 +1,14 @@ -import {PromiseWrapper} from 'angular2/src/facade/async'; -import {Component} from 'angular2/core'; -import {ServiceMessageBrokerFactory, PRIMITIVE} from 'angular2/platform/worker_app'; +import {PromiseWrapper} from "angular2/src/facade/async"; +import {Component} from "angular2/core"; +import {ServiceMessageBrokerFactory, PRIMITIVE} from "angular2/platform/worker_app"; -const ECHO_CHANNEL = 'ECHO'; +const ECHO_CHANNEL = "ECHO"; -@Component({selector: 'app', template: '<h1>WebWorker MessageBroker Test</h1>'}) +@Component({selector: 'app', template: "<h1>WebWorker MessageBroker Test</h1>"}) export class App { constructor(private _serviceBrokerFactory: ServiceMessageBrokerFactory) { var broker = _serviceBrokerFactory.createMessageBroker(ECHO_CHANNEL, false); - broker.registerMethod('echo', [PRIMITIVE], this._echo, PRIMITIVE); + broker.registerMethod("echo", [PRIMITIVE], this._echo, PRIMITIVE); } private _echo(val: string) { diff --git a/modules/playground/src/web_workers/router/background_index.ts b/modules/playground/src/web_workers/router/background_index.ts index 0e52025f8e..e9fe6157be 100644 --- a/modules/playground/src/web_workers/router/background_index.ts +++ b/modules/playground/src/web_workers/router/background_index.ts @@ -1,12 +1,18 @@ -import {platform, Provider, NgZone} from 'angular2/core'; -import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION, WORKER_APP_ROUTER} from 'angular2/platform/worker_app'; -import {App} from './index_common'; -import {HashLocationStrategy, LocationStrategy} from 'angular2/router'; +import {platform, Provider, NgZone} from "angular2/core"; +import { + WORKER_APP_PLATFORM, + WORKER_APP_APPLICATION, + WORKER_APP_ROUTER +} from "angular2/platform/worker_app"; +import {App} from "./index_common"; +import {HashLocationStrategy, LocationStrategy} from "angular2/router"; export function main() { - let refPromise = platform([WORKER_APP_PLATFORM]).asyncApplication(null, [ - WORKER_APP_APPLICATION, WORKER_APP_ROUTER, - new Provider(LocationStrategy, {useClass: HashLocationStrategy}) - ]); + let refPromise = platform([WORKER_APP_PLATFORM]) + .asyncApplication(null, [ + WORKER_APP_APPLICATION, + WORKER_APP_ROUTER, + new Provider(LocationStrategy, {useClass: HashLocationStrategy}) + ]); refPromise.then((ref) => ref.bootstrap(App)); } diff --git a/modules/playground/src/web_workers/router/index.ts b/modules/playground/src/web_workers/router/index.ts index 65d16364f6..29f66f3ee4 100644 --- a/modules/playground/src/web_workers/router/index.ts +++ b/modules/playground/src/web_workers/router/index.ts @@ -1,8 +1,16 @@ import {platform, Provider} from 'angular2/core'; -import {WORKER_RENDER_APP, WORKER_RENDER_PLATFORM, WORKER_SCRIPT, WORKER_RENDER_ROUTER} from 'angular2/platform/worker_render'; -import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location'; -import {MessageBasedPlatformLocation} from 'angular2/src/web_workers/ui/platform_location'; +import { + WORKER_RENDER_APP, + WORKER_RENDER_PLATFORM, + WORKER_SCRIPT, + WORKER_RENDER_ROUTER +} from 'angular2/platform/worker_render'; +import {BrowserPlatformLocation} from "angular2/src/router/location/browser_platform_location"; +import {MessageBasedPlatformLocation} from "angular2/src/web_workers/ui/platform_location"; -let ref = platform([WORKER_RENDER_PLATFORM]).application([ - WORKER_RENDER_APP, new Provider(WORKER_SCRIPT, {useValue: 'loader.js'}), WORKER_RENDER_ROUTER -]); \ No newline at end of file +let ref = platform([WORKER_RENDER_PLATFORM]) + .application([ + WORKER_RENDER_APP, + new Provider(WORKER_SCRIPT, {useValue: "loader.js"}), + WORKER_RENDER_ROUTER + ]); \ No newline at end of file diff --git a/modules/playground/src/web_workers/router/index_common.ts b/modules/playground/src/web_workers/router/index_common.ts index 0c887625b6..af57be334d 100644 --- a/modules/playground/src/web_workers/router/index_common.ts +++ b/modules/playground/src/web_workers/router/index_common.ts @@ -6,9 +6,9 @@ import {ROUTER_DIRECTIVES, RouteConfig, Route} from 'angular2/router'; @Component({selector: 'app', directives: [ROUTER_DIRECTIVES], templateUrl: 'app.html'}) @RouteConfig([ - new Route({path: '/', component: Start, name: 'Start'}), - new Route({path: '/contact', component: Contact, name: 'Contact'}), - new Route({path: '/about', component: About, name: 'About'}) + new Route({path: '/', component: Start, name: "Start"}), + new Route({path: '/contact', component: Contact, name: "Contact"}), + new Route({path: '/about', component: About, name: "About"}) ]) export class App { } diff --git a/modules/playground/src/web_workers/todo/background_index.ts b/modules/playground/src/web_workers/todo/background_index.ts index e2ccff013a..5b4d630786 100644 --- a/modules/playground/src/web_workers/todo/background_index.ts +++ b/modules/playground/src/web_workers/todo/background_index.ts @@ -1,6 +1,6 @@ -import {TodoApp} from './index_common'; -import {platform} from 'angular2/core'; -import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from 'angular2/platform/worker_app'; +import {TodoApp} from "./index_common"; +import {platform} from "angular2/core"; +import {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION} from "angular2/platform/worker_app"; export function main() { platform([WORKER_APP_PLATFORM]).application([WORKER_APP_APPLICATION]).bootstrap(TodoApp) diff --git a/modules/playground/src/web_workers/todo/index.ts b/modules/playground/src/web_workers/todo/index.ts index d37239f4ac..f48911768f 100644 --- a/modules/playground/src/web_workers/todo/index.ts +++ b/modules/playground/src/web_workers/todo/index.ts @@ -1,6 +1,9 @@ import {platform, Provider} from 'angular2/core'; -import {WORKER_RENDER_APPLICATION, WORKER_RENDER_PLATFORM, WORKER_SCRIPT} from 'angular2/platform/worker_render'; +import { + WORKER_RENDER_APPLICATION, + WORKER_RENDER_PLATFORM, + WORKER_SCRIPT +} from 'angular2/platform/worker_render'; -platform([WORKER_RENDER_PLATFORM]).application([ - WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: 'loader.js'}) -]); \ No newline at end of file +platform([WORKER_RENDER_PLATFORM]) + .application([WORKER_RENDER_APPLICATION, new Provider(WORKER_SCRIPT, {useValue: "loader.js"})]); \ No newline at end of file diff --git a/modules/playground/src/web_workers/todo/index_common.ts b/modules/playground/src/web_workers/todo/index_common.ts index 2551e80188..0e020cfa79 100644 --- a/modules/playground/src/web_workers/todo/index_common.ts +++ b/modules/playground/src/web_workers/todo/index_common.ts @@ -19,7 +19,7 @@ export class TodoApp { enterTodo(): void { this.addTodo(this.inputValue); - this.inputValue = ''; + this.inputValue = ""; } doneEditing($event, todo: Todo): void { diff --git a/npm-shrinkwrap.clean.json b/npm-shrinkwrap.clean.json index 1103b6da06..6d6ba4e22f 100644 --- a/npm-shrinkwrap.clean.json +++ b/npm-shrinkwrap.clean.json @@ -1629,15 +1629,7 @@ "version": "1.0.2" }, "clang-format": { - "version": "1.0.37", - "dependencies": { - "async": { - "version": "1.5.2" - }, - "glob": { - "version": "7.0.3" - } - } + "version": "1.0.32" }, "cli-color": { "version": "1.1.0", @@ -5460,7 +5452,7 @@ "version": "0.0.6" }, "typescript": { - "version": "1.7.3" + "version": "1.7.5" }, "ua-parser-js": { "version": "0.7.10" @@ -5831,5 +5823,5 @@ } }, "name": "angular-srcs", - "version": "2.0.0-beta.14" + "version": "2.0.0-beta.12" } diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index f95247c58d..fe76af852c 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "2.0.0-beta.14", + "version": "2.0.0-beta.12", "dependencies": { "abbrev": { "version": "1.0.7", @@ -2547,21 +2547,9 @@ "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" }, "clang-format": { - "version": "1.0.37", - "from": "clang-format@1.0.37", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.0.37.tgz", - "dependencies": { - "async": { - "version": "1.5.2", - "from": "async@>=1.5.2 <2.0.0", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz" - }, - "glob": { - "version": "7.0.3", - "from": "glob@>=7.0.0 <8.0.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.0.3.tgz" - } - } + "version": "1.0.32", + "from": "clang-format@1.0.32", + "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.0.32.tgz" }, "cli-color": { "version": "1.1.0", @@ -8703,9 +8691,9 @@ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz" }, "typescript": { - "version": "1.7.3", - "from": "typescript@1.7.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.7.3.tgz" + "version": "1.7.5", + "from": "typescript@1.7.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.7.5.tgz" }, "ua-parser-js": { "version": "0.7.10", diff --git a/tools/broccoli/angular_builder.ts b/tools/broccoli/angular_builder.ts index 0e53edd3cd..7a047de834 100644 --- a/tools/broccoli/angular_builder.ts +++ b/tools/broccoli/angular_builder.ts @@ -11,7 +11,10 @@ export type ProjectMap = { }; export type Options = { - projects: ProjectMap; noTypeChecks: boolean; generateEs6: boolean; useBundles: boolean; + projects: ProjectMap; + noTypeChecks: boolean; + generateEs6: boolean; + useBundles: boolean; }; export interface AngularBuilderOptions { @@ -155,17 +158,16 @@ function writeBuildLog(result: BuildResult, name: string) { function broccoliNodeToBuildNode(broccoliNode) { let tree = broccoliNode.tree.newStyleTree || broccoliNode.tree; - return new BuildNode( - tree.description || tree.constructor.name, - tree.inputPath ? [tree.inputPath] : tree.inputPaths, tree.cachePath, tree.outputPath, - broccoliNode.selfTime / (1000 * 1000 * 1000), broccoliNode.totalTime / (1000 * 1000 * 1000), - broccoliNode.subtrees.map(broccoliNodeToBuildNode)); + return new BuildNode(tree.description || tree.constructor.name, + tree.inputPath ? [tree.inputPath] : tree.inputPaths, tree.cachePath, + tree.outputPath, broccoliNode.selfTime / (1000 * 1000 * 1000), + broccoliNode.totalTime / (1000 * 1000 * 1000), + broccoliNode.subtrees.map(broccoliNodeToBuildNode)); } class BuildNode { - constructor( - public pluginName: string, public inputPaths: string[], public cachePath: string, - public outputPath: string, public selfTime: number, public totalTime: number, - public inputNodes: BroccoliNode[]) {} + constructor(public pluginName: string, public inputPaths: string[], public cachePath: string, + public outputPath: string, public selfTime: number, public totalTime: number, + public inputNodes: BroccoliNode[]) {} } diff --git a/tools/broccoli/broccoli-check-imports.ts b/tools/broccoli/broccoli-check-imports.ts index 85fab031e9..f1d53c0076 100644 --- a/tools/broccoli/broccoli-check-imports.ts +++ b/tools/broccoli/broccoli-check-imports.ts @@ -9,15 +9,15 @@ import {wrapDiffingPlugin, DiffingBroccoliPlugin, DiffResult} from './diffing-br * This guarantees that platform-independent modules remain platoform-independent. */ class CheckImports implements DiffingBroccoliPlugin { - static IMPORT_DECL_REGEXP = new RegExp(`^import[^;]+;`, 'mg'); - static IMPORT_PATH_REGEXP = new RegExp(`['"]([^'"]+)+['"]`, 'm'); + static IMPORT_DECL_REGEXP = new RegExp(`^import[^;]+;`, "mg"); + static IMPORT_PATH_REGEXP = new RegExp(`['"]([^'"]+)+['"]`, "m"); static ALLOWED_IMPORTS = { - 'angular2/src/core': ['angular2/src/facade'], - 'angular2/src/facade': ['rxjs'], - 'angular2/src/common': ['angular2/core', 'angular2/src/facade'], - 'angular2/src/http': ['angular2/core', 'angular2/src/facade', 'rxjs'], - 'angular2/src/upgrade': ['angular2/core', 'angular2/src/facade', 'angular2/platform/browser'] + "angular2/src/core": ["angular2/src/facade"], + "angular2/src/facade": ["rxjs"], + "angular2/src/common": ["angular2/core", "angular2/src/facade"], + "angular2/src/http": ["angular2/core", "angular2/src/facade", "rxjs"], + "angular2/src/upgrade": ["angular2/core", "angular2/src/facade", "angular2/platform/browser"] //"angular2/src/render": [ // "angular2/animate", // "angular2/core", @@ -54,8 +54,8 @@ class CheckImports implements DiffingBroccoliPlugin { private checkFilePath(filePath: string) { const sourceFilePath = path.join(this.inputPath, filePath); - if (endsWith(sourceFilePath, '.ts') && fs.existsSync(sourceFilePath)) { - const content = fs.readFileSync(sourceFilePath, 'UTF-8'); + if (endsWith(sourceFilePath, ".ts") && fs.existsSync(sourceFilePath)) { + const content = fs.readFileSync(sourceFilePath, "UTF-8"); const imports = content.match(CheckImports.IMPORT_DECL_REGEXP); if (imports) { return imports.filter(i => !this.isAllowedImport(filePath, i)) @@ -72,14 +72,14 @@ class CheckImports implements DiffingBroccoliPlugin { if (!res || res.length < 2) return true; // non-es6 import const importPath = res[1]; - if (startsWith(importPath, './') || startsWith(importPath, '../')) return true; + if (startsWith(importPath, "./") || startsWith(importPath, "../")) return true; const c = CheckImports.ALLOWED_IMPORTS; for (var prop in c) { if (c.hasOwnProperty(prop) && startsWith(sourceFile, prop)) { const allowedPaths = c[prop]; return startsWith(importPath, prop) || - allowedPaths.filter(p => startsWith(importPath, p)).length > 0; + allowedPaths.filter(p => startsWith(importPath, p)).length > 0; } } @@ -87,7 +87,7 @@ class CheckImports implements DiffingBroccoliPlugin { } private formatError(filePath: string, importPath: string): string { - const i = importPath.replace(new RegExp(`\n`, 'g'), '\\n'); + const i = importPath.replace(new RegExp(`\n`, 'g'), "\\n"); return `${filePath}: ${i}`; } } diff --git a/tools/broccoli/broccoli-dartfmt.ts b/tools/broccoli/broccoli-dartfmt.ts index b84e421e71..7872c81a4d 100644 --- a/tools/broccoli/broccoli-dartfmt.ts +++ b/tools/broccoli/broccoli-dartfmt.ts @@ -24,7 +24,7 @@ class DartFormatter implements DiffingBroccoliPlugin { private firstBuild: boolean = true; constructor(public inputPath: string, public cachePath: string, options) { - if (!options.dartSDK) throw new Error('Missing Dart SDK'); + if (!options.dartSDK) throw new Error("Missing Dart SDK"); this.DARTFMT = options.dartSDK.DARTFMT; this.verbose = options.logs.dartfmt; } @@ -34,21 +34,22 @@ class DartFormatter implements DiffingBroccoliPlugin { let argsLength = 2; let argPackages = []; let firstBuild = this.firstBuild; - treeDiff.addedPaths.concat(treeDiff.changedPaths).forEach((changedFile) => { - let sourcePath = path.join(this.inputPath, changedFile); - let destPath = path.join(this.cachePath, changedFile); - if (!firstBuild && /\.dart$/.test(changedFile)) { - if ((argsLength + destPath.length + 2) >= 0x2000) { - // Win32 command line arguments length - argPackages.push(args); - args = ['-w']; - argsLength = 2; - } - args.push(destPath); - argsLength += destPath.length + 2; - } - fse.copySync(sourcePath, destPath); - }); + treeDiff.addedPaths.concat(treeDiff.changedPaths) + .forEach((changedFile) => { + let sourcePath = path.join(this.inputPath, changedFile); + let destPath = path.join(this.cachePath, changedFile); + if (!firstBuild && /\.dart$/.test(changedFile)) { + if ((argsLength + destPath.length + 2) >= 0x2000) { + // Win32 command line arguments length + argPackages.push(args); + args = ['-w']; + argsLength = 2; + } + args.push(destPath); + argsLength += destPath.length + 2; + } + fse.copySync(sourcePath, destPath); + }); treeDiff.removedPaths.forEach((removedFile) => { let destPath = path.join(this.cachePath, removedFile); fse.removeSync(destPath); diff --git a/tools/broccoli/broccoli-dest-copy.ts b/tools/broccoli/broccoli-dest-copy.ts index fdc4a23fe5..ecfd90a482 100644 --- a/tools/broccoli/broccoli-dest-copy.ts +++ b/tools/broccoli/broccoli-dest-copy.ts @@ -15,13 +15,14 @@ class DestCopy implements DiffingBroccoliPlugin { rebuild(treeDiff: DiffResult) { - treeDiff.addedPaths.concat(treeDiff.changedPaths).forEach((changedFilePath) => { - var destFilePath = path.join(this.outputRoot, changedFilePath); + treeDiff.addedPaths.concat(treeDiff.changedPaths) + .forEach((changedFilePath) => { + var destFilePath = path.join(this.outputRoot, changedFilePath); - var destDirPath = path.dirname(destFilePath); - fse.mkdirsSync(destDirPath); - fse.copySync(path.join(this.inputPath, changedFilePath), destFilePath); - }); + var destDirPath = path.dirname(destFilePath); + fse.mkdirsSync(destDirPath); + fse.copySync(path.join(this.inputPath, changedFilePath), destFilePath); + }); treeDiff.removedPaths.forEach((removedFilePath) => { var destFilePath = path.join(this.outputRoot, removedFilePath); diff --git a/tools/broccoli/broccoli-flatten.spec.ts b/tools/broccoli/broccoli-flatten.spec.ts index a00b4636dd..b58fd585d5 100644 --- a/tools/broccoli/broccoli-flatten.spec.ts +++ b/tools/broccoli/broccoli-flatten.spec.ts @@ -12,9 +12,9 @@ describe('Flatten', () => { function flatten(inputPaths) { return new DiffingFlatten(inputPaths, 'output', null); } - function read(path) { return fs.readFileSync(path, {encoding: 'utf-8'}); } + function read(path) { return fs.readFileSync(path, {encoding: "utf-8"}); } function rm(path) { return fs.unlinkSync(path); } - function write(path, content) { fs.writeFileSync(path, content, {encoding: 'utf-8'}); } + function write(path, content) { fs.writeFileSync(path, content, {encoding: "utf-8"}); } it('should flatten files and be incremental', () => { @@ -70,8 +70,7 @@ describe('Flatten', () => { let differ = new TreeDiffer('testLabel', 'input'); let flattenedTree = flatten('input'); expect(() => flattenedTree.rebuild(differ.diffTree())) - .toThrowError( - 'Duplicate file \'file-1.txt\' found in path \'dir1' + path.sep + 'subdir-1' + - path.sep + 'file-1.txt\''); + .toThrowError("Duplicate file 'file-1.txt' found in path 'dir1" + path.sep + "subdir-1" + + path.sep + "file-1.txt'"); }); }); diff --git a/tools/broccoli/broccoli-flatten.ts b/tools/broccoli/broccoli-flatten.ts index 8de28959f1..079c15f671 100644 --- a/tools/broccoli/broccoli-flatten.ts +++ b/tools/broccoli/broccoli-flatten.ts @@ -36,9 +36,8 @@ export class DiffingFlatten implements DiffingBroccoliPlugin { if (!fs.existsSync(destFilePath)) { symlinkOrCopy(sourceFilePath, destFilePath); } else { - throw new Error( - `Duplicate file '${path.basename(changedFilePath)}' ` + - `found in path '${changedFilePath}'`); + throw new Error(`Duplicate file '${path.basename(changedFilePath)}' ` + + `found in path '${changedFilePath}'`); } }); diff --git a/tools/broccoli/broccoli-lodash.ts b/tools/broccoli/broccoli-lodash.ts index 6b01f5d617..a3f675dd1a 100644 --- a/tools/broccoli/broccoli-lodash.ts +++ b/tools/broccoli/broccoli-lodash.ts @@ -23,9 +23,8 @@ const kDefaultOptions: LodashRendererOptions = { * the associated changes. */ export class LodashRenderer implements DiffingBroccoliPlugin { - constructor( - private inputPath, private cachePath, - private options: LodashRendererOptions = kDefaultOptions) {} + constructor(private inputPath, private cachePath, + private options: LodashRendererOptions = kDefaultOptions) {} rebuild(treeDiff: DiffResult) { let {encoding = 'utf-8', context = {}} = this.options; diff --git a/tools/broccoli/broccoli-merge-trees.spec.ts b/tools/broccoli/broccoli-merge-trees.spec.ts index c46c653fab..c1c659f546 100644 --- a/tools/broccoli/broccoli-merge-trees.spec.ts +++ b/tools/broccoli/broccoli-merge-trees.spec.ts @@ -19,7 +19,7 @@ describe('MergeTrees', () => { return treeDiffers; } - function read(path) { return fs.readFileSync(path, 'utf-8'); } + function read(path) { return fs.readFileSync(path, "utf-8"); } it('should copy the file from the right-most inputTree with overwrite=true', () => { let testDir: any = { diff --git a/tools/broccoli/broccoli-merge-trees.ts b/tools/broccoli/broccoli-merge-trees.ts index 9689b38d35..1efee93ec8 100644 --- a/tools/broccoli/broccoli-merge-trees.ts +++ b/tools/broccoli/broccoli-merge-trees.ts @@ -24,8 +24,8 @@ export class MergeTrees implements DiffingBroccoliPlugin { public options: MergeTreesOptions; private firstBuild: boolean = true; - constructor( - public inputPaths: string[], public cachePath: string, options: MergeTreesOptions = {}) { + constructor(public inputPaths: string[], public cachePath: string, + options: MergeTreesOptions = {}) { this.options = options || {}; } diff --git a/tools/broccoli/broccoli-replace.ts b/tools/broccoli/broccoli-replace.ts index 372d9ddcf4..7583dd5b3b 100644 --- a/tools/broccoli/broccoli-replace.ts +++ b/tools/broccoli/broccoli-replace.ts @@ -17,36 +17,37 @@ class DiffingReplace implements DiffingBroccoliPlugin { var patterns = this.options.patterns; var files = this.options.files; - treeDiff.addedPaths.concat(treeDiff.changedPaths).forEach((changedFilePath) => { - var sourceFilePath = path.join(this.inputPath, changedFilePath); - var destFilePath = path.join(this.cachePath, changedFilePath); - var destDirPath = path.dirname(destFilePath); + treeDiff.addedPaths.concat(treeDiff.changedPaths) + .forEach((changedFilePath) => { + var sourceFilePath = path.join(this.inputPath, changedFilePath); + var destFilePath = path.join(this.cachePath, changedFilePath); + var destDirPath = path.dirname(destFilePath); - if (!fs.existsSync(destDirPath)) { - fse.mkdirpSync(destDirPath); - } - - var fileMatches = files.some((filePath) => minimatch(changedFilePath, filePath)); - if (fileMatches) { - var content = fs.readFileSync(sourceFilePath, FILE_ENCODING); - patterns.forEach((pattern) => { - var replacement = pattern.replacement; - if (typeof replacement === 'function') { - replacement = function(content) { - return pattern.replacement(content, changedFilePath); - }; + if (!fs.existsSync(destDirPath)) { + fse.mkdirpSync(destDirPath); + } + + var fileMatches = files.some((filePath) => minimatch(changedFilePath, filePath)); + if (fileMatches) { + var content = fs.readFileSync(sourceFilePath, FILE_ENCODING); + patterns.forEach((pattern) => { + var replacement = pattern.replacement; + if (typeof replacement === 'function') { + replacement = function(content) { + return pattern.replacement(content, changedFilePath); + }; + } + content = content.replace(pattern.match, replacement); + }); + fs.writeFileSync(destFilePath, content, FILE_ENCODING); + } else if (!fs.existsSync(destFilePath)) { + try { + fs.symlinkSync(sourceFilePath, destFilePath); + } catch (e) { + fs.writeFileSync(destFilePath, fs.readFileSync(sourceFilePath)); + } } - content = content.replace(pattern.match, replacement); }); - fs.writeFileSync(destFilePath, content, FILE_ENCODING); - } else if (!fs.existsSync(destFilePath)) { - try { - fs.symlinkSync(sourceFilePath, destFilePath); - } catch (e) { - fs.writeFileSync(destFilePath, fs.readFileSync(sourceFilePath)); - } - } - }); treeDiff.removedPaths.forEach((removedFilePath) => { var destFilePath = path.join(this.cachePath, removedFilePath); diff --git a/tools/broccoli/broccoli-ts2dart.ts b/tools/broccoli/broccoli-ts2dart.ts index 6e9f3a142b..44f9a38d1b 100644 --- a/tools/broccoli/broccoli-ts2dart.ts +++ b/tools/broccoli/broccoli-ts2dart.ts @@ -11,9 +11,8 @@ class TSToDartTranspiler implements DiffingBroccoliPlugin { private transpiler: any /*ts2dart.Transpiler*/; - constructor( - public inputPath: string, public cachePath: string, - public options: any /*ts2dart.TranspilerOptions*/) { + constructor(public inputPath: string, public cachePath: string, + public options: any /*ts2dart.TranspilerOptions*/) { options.basePath = inputPath; // Workaround for https://github.com/dart-lang/dart_style/issues/493 var ts2dart = require('ts2dart'); @@ -27,16 +26,17 @@ class TSToDartTranspiler implements DiffingBroccoliPlugin { path.resolve(this.inputPath, 'angular2/typings/es6-collections/es6-collections.d.ts') ]; let getDartFilePath = (path: string) => path.replace(/((\.js)|(\.ts))$/i, '.dart'); - treeDiff.addedPaths.concat(treeDiff.changedPaths).forEach((changedPath) => { - let inputFilePath = path.resolve(this.inputPath, changedPath); + treeDiff.addedPaths.concat(treeDiff.changedPaths) + .forEach((changedPath) => { + let inputFilePath = path.resolve(this.inputPath, changedPath); - // Ignore files which don't need to be transpiled to Dart - let dartInputFilePath = getDartFilePath(inputFilePath); - if (fs.existsSync(dartInputFilePath)) return; + // Ignore files which don't need to be transpiled to Dart + let dartInputFilePath = getDartFilePath(inputFilePath); + if (fs.existsSync(dartInputFilePath)) return; - // Prepare to rebuild - toEmit.push(path.resolve(this.inputPath, changedPath)); - }); + // Prepare to rebuild + toEmit.push(path.resolve(this.inputPath, changedPath)); + }); treeDiff.removedPaths.forEach((removedPath) => { let absolutePath = path.resolve(this.inputPath, removedPath); diff --git a/tools/broccoli/broccoli-typescript.ts b/tools/broccoli/broccoli-typescript.ts index 0dea425e94..637b519a05 100644 --- a/tools/broccoli/broccoli-typescript.ts +++ b/tools/broccoli/broccoli-typescript.ts @@ -85,8 +85,8 @@ class DiffingTSCompiler implements DiffingBroccoliPlugin { this.tsOpts.rootDir = inputPath; this.tsOpts.outDir = this.cachePath; - this.tsServiceHost = new CustomLanguageServiceHost( - this.tsOpts, this.rootFilePaths, this.fileRegistry, this.inputPath); + this.tsServiceHost = new CustomLanguageServiceHost(this.tsOpts, this.rootFilePaths, + this.fileRegistry, this.inputPath); this.tsService = ts.createLanguageService(this.tsServiceHost, ts.createDocumentRegistry()); this.metadataCollector = new MetadataCollector(); } @@ -97,16 +97,17 @@ class DiffingTSCompiler implements DiffingBroccoliPlugin { let pathsWithErrors = []; let errorMessages = []; - treeDiff.addedPaths.concat(treeDiff.changedPaths).forEach((tsFilePath) => { - if (!this.fileRegistry[tsFilePath]) { - this.fileRegistry[tsFilePath] = {version: 0}; - this.rootFilePaths.push(tsFilePath); - } else { - this.fileRegistry[tsFilePath].version++; - } + treeDiff.addedPaths.concat(treeDiff.changedPaths) + .forEach((tsFilePath) => { + if (!this.fileRegistry[tsFilePath]) { + this.fileRegistry[tsFilePath] = {version: 0}; + this.rootFilePaths.push(tsFilePath); + } else { + this.fileRegistry[tsFilePath].version++; + } - pathsToEmit.push(path.join(this.inputPath, tsFilePath)); - }); + pathsToEmit.push(path.join(this.inputPath, tsFilePath)); + }); treeDiff.removedPaths.forEach((tsFilePath) => { console.log('removing outputs for', tsFilePath); @@ -180,7 +181,7 @@ class DiffingTSCompiler implements DiffingBroccoliPlugin { let errors = []; allDiagnostics.forEach(diagnostic => { - let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); if (diagnostic.file) { let {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); errors.push(` ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); @@ -256,8 +257,8 @@ class DiffingTSCompiler implements DiffingBroccoliPlugin { * Emit a .metadata.json file to correspond to the .d.ts file if the module contains classes that * use decorators or exported constants. */ - private emitMetadata( - dtsFileName: string, sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker) { + private emitMetadata(dtsFileName: string, sourceFile: ts.SourceFile, + typeChecker: ts.TypeChecker) { if (sourceFile) { const metadata = this.metadataCollector.getMetadata(sourceFile, typeChecker); if (metadata && metadata.metadata) { @@ -280,16 +281,16 @@ class DiffingTSCompiler implements DiffingBroccoliPlugin { */ private fixSourceMapSources(content: string): string { try { - const marker = '//# sourceMappingURL=data:application/json;base64,'; + const marker = "//# sourceMappingURL=data:application/json;base64,"; const index = content.indexOf(marker); if (index == -1) return content; const base = content.substring(0, index + marker.length); const sourceMapBit = - new Buffer(content.substring(index + marker.length), 'base64').toString('utf8'); + new Buffer(content.substring(index + marker.length), 'base64').toString("utf8"); const sourceMaps = JSON.parse(sourceMapBit); const source = sourceMaps.sources[0]; - sourceMaps.sources = [source.substring(source.lastIndexOf('../') + 3)]; + sourceMaps.sources = [source.substring(source.lastIndexOf("../") + 3)]; return `${base}${new Buffer(JSON.stringify(sourceMaps)).toString('base64')}`; } catch (e) { return content; @@ -318,9 +319,8 @@ class CustomLanguageServiceHost implements ts.LanguageServiceHost { private defaultLibFilePath: string; - constructor( - private compilerOptions: ts.CompilerOptions, private fileNames: string[], - private fileRegistry: FileRegistry, private treeInputPath: string) { + constructor(private compilerOptions: ts.CompilerOptions, private fileNames: string[], + private fileRegistry: FileRegistry, private treeInputPath: string) { this.currentDirectory = process.cwd(); this.defaultLibFilePath = ts.getDefaultLibFilePath(compilerOptions).replace(/\\/g, '/'); } diff --git a/tools/broccoli/broccoli-writer.d.ts b/tools/broccoli/broccoli-writer.d.ts index b1b96d5bb4..5d821fa4f9 100644 --- a/tools/broccoli/broccoli-writer.d.ts +++ b/tools/broccoli/broccoli-writer.d.ts @@ -1,6 +1,6 @@ /// <reference path="../typings/es6-promise/es6-promise.d.ts" /> -declare module 'broccoli-writer' { +declare module "broccoli-writer" { class Writer { write(readTree: (tree) => Promise<string>, destDir: string): Promise<any>; } diff --git a/tools/broccoli/broccoli.d.ts b/tools/broccoli/broccoli.d.ts index 0ea6688a2d..d058488c82 100644 --- a/tools/broccoli/broccoli.d.ts +++ b/tools/broccoli/broccoli.d.ts @@ -66,13 +66,13 @@ interface BroccoliTree { */ description?: string; - rebuild(): (Promise<any>|void); + rebuild(): (Promise<any>| void); cleanup(): void; } interface OldBroccoliTree { - read?(readTree: (tree: BroccoliTree) => Promise<string>): (Promise<string>|string); + read?(readTree: (tree: BroccoliTree) => Promise<string>): (Promise<string>| string); } diff --git a/tools/broccoli/diffing-broccoli-plugin.ts b/tools/broccoli/diffing-broccoli-plugin.ts index fdc02cd002..9105d0b944 100644 --- a/tools/broccoli/diffing-broccoli-plugin.ts +++ b/tools/broccoli/diffing-broccoli-plugin.ts @@ -28,8 +28,8 @@ export function wrapDiffingPlugin(pluginClass): DiffingPluginWrapperFactory { export interface DiffingBroccoliPlugin { - rebuild(diff: (DiffResult|DiffResult[])): (Promise<DiffResult|void>|DiffResult|void); - cleanup?(): void; + rebuild(diff: (DiffResult | DiffResult[])): (Promise<DiffResult | void>| DiffResult | void); + cleanup ? () : void; } @@ -64,7 +64,7 @@ class DiffingPluginWrapper implements BroccoliTree { this.description = this.pluginClass.name; } - private getDiffResult(): (DiffResult|DiffResult[]) { + private getDiffResult(): (DiffResult | DiffResult[]) { let returnOrCalculateDiffResult = (tree, index) => { // returnOrCalculateDiffResult will do one of two things: // @@ -85,16 +85,16 @@ class DiffingPluginWrapper implements BroccoliTree { } else if (this.inputTree) { return returnOrCalculateDiffResult(this.inputTree, false); } else { - throw new Error('Missing TreeDiffer'); + throw new Error("Missing TreeDiffer"); } } - private maybeStoreDiffResult(value: (DiffResult|void)) { + private maybeStoreDiffResult(value: (DiffResult | void)) { if (!(value instanceof DiffResult)) value = null; this.diffResult = <DiffResult>(value); } - rebuild(): (Promise<any>|void) { + rebuild(): (Promise<any>| void) { try { let firstRun = !this.initialized; this.init(); @@ -104,7 +104,7 @@ class DiffingPluginWrapper implements BroccoliTree { let result = this.wrappedPlugin.rebuild(diffResult); if (result) { - let resultPromise = <Promise<DiffResult|void>>(result); + let resultPromise = <Promise<DiffResult | void>>(result); if (resultPromise.then) { // rebuild() -> Promise<> return resultPromise.then((result: (DiffResult | void)) => { @@ -144,15 +144,15 @@ class DiffingPluginWrapper implements BroccoliTree { let description = this.description; this.initialized = true; if (this.inputPaths) { - this.treeDiffers = this.inputPaths.map( - (inputPath) => - new TreeDiffer(description, inputPath, includeExtensions, excludeExtensions)); + this.treeDiffers = + this.inputPaths.map((inputPath) => new TreeDiffer( + description, inputPath, includeExtensions, excludeExtensions)); } else if (this.inputPath) { this.treeDiffer = new TreeDiffer(description, this.inputPath, includeExtensions, excludeExtensions); } - this.wrappedPlugin = new this.pluginClass( - this.inputPaths || this.inputPath, this.cachePath, this.wrappedPluginArguments[1]); + this.wrappedPlugin = new this.pluginClass(this.inputPaths || this.inputPath, this.cachePath, + this.wrappedPluginArguments[1]); } } @@ -182,9 +182,8 @@ class DiffingPluginWrapper implements BroccoliTree { // Since it's not safe to use instanceof operator in node, we are checking the constructor.name. // // New-style/rebuild trees should always be stable. - let isNewStyleTree = - !!(tree['newStyleTree'] || typeof tree.rebuild === 'function' || - tree['isReadAPICompatTree'] || tree.constructor['name'] === 'Funnel'); + let isNewStyleTree = !!(tree['newStyleTree'] || typeof tree.rebuild === 'function' || + tree['isReadAPICompatTree'] || tree.constructor['name'] === 'Funnel'); return isNewStyleTree ? tree : stabilizeTree(tree); } diff --git a/tools/broccoli/html-replace/index.ts b/tools/broccoli/html-replace/index.ts index 39a4449cf1..5f401061ac 100644 --- a/tools/broccoli/html-replace/index.ts +++ b/tools/broccoli/html-replace/index.ts @@ -3,9 +3,9 @@ var path = require('path'); module.exports = read; function read(file) { - var content = fs.readFileSync( - path.join('tools/broccoli/html-replace', file + '.html'), {encoding: 'utf-8'}); + var content = fs.readFileSync(path.join('tools/broccoli/html-replace', file + '.html'), + {encoding: 'utf-8'}); // TODO(broccoli): we don't really need this, it's here to make the output match the // tools/build/html - return content.substring(0, content.lastIndexOf('\n')); + return content.substring(0, content.lastIndexOf("\n")); } diff --git a/tools/broccoli/js-replace/index.ts b/tools/broccoli/js-replace/index.ts index 73c9c28444..0b5495eefa 100644 --- a/tools/broccoli/js-replace/index.ts +++ b/tools/broccoli/js-replace/index.ts @@ -7,5 +7,5 @@ function readJs(file) { fs.readFileSync(path.join('tools/broccoli/js-replace', file + '.js'), {encoding: 'utf-8'}); // TODO(broccoli): we don't really need this, it's here to make the output match the // tools/build/html - return content.substring(0, content.lastIndexOf('\n')); + return content.substring(0, content.lastIndexOf("\n")); } diff --git a/tools/broccoli/multi_copy.ts b/tools/broccoli/multi_copy.ts index fe1b9f601a..18573be43b 100644 --- a/tools/broccoli/multi_copy.ts +++ b/tools/broccoli/multi_copy.ts @@ -26,23 +26,24 @@ export class MultiCopy extends Writer { constructor(private inputTree, private options: MultiCopyOptions) { super(); } write(readTree: (tree) => Promise<string>, destDir: string): Promise<any> { - return readTree(this.inputTree).then((inputPath: string) => { - var fileName = path.basename(this.options.srcPath); - var data = fs.readFileSync(path.join(inputPath, this.options.srcPath), 'utf-8'); + return readTree(this.inputTree) + .then((inputPath: string) => { + var fileName = path.basename(this.options.srcPath); + var data = fs.readFileSync(path.join(inputPath, this.options.srcPath), 'utf-8'); - this.options.targetPatterns.forEach(pattern => { - var paths: string[] = glob.sync(pattern); - paths = paths.filter(p => fs.statSync(p).isDirectory()); - if (this.options.exclude) { - paths = paths.filter(p => !this.options.exclude.some((excl) => minimatch(p, excl))); - } - paths.forEach(p => { - var folder = path.join(destDir, p); - fsx.mkdirsSync(folder); - var outputPath = path.join(folder, fileName); - fs.writeFileSync(outputPath, data); + this.options.targetPatterns.forEach(pattern => { + var paths: string[] = glob.sync(pattern); + paths = paths.filter(p => fs.statSync(p).isDirectory()); + if (this.options.exclude) { + paths = paths.filter(p => !this.options.exclude.some((excl) => minimatch(p, excl))); + } + paths.forEach(p => { + var folder = path.join(destDir, p); + fsx.mkdirsSync(folder); + var outputPath = path.join(folder, fileName); + fs.writeFileSync(outputPath, data); + }); + }); }); - }); - }); } } diff --git a/tools/broccoli/tree-differ.spec.ts b/tools/broccoli/tree-differ.spec.ts index dd2edaa04a..0a2205ca52 100644 --- a/tools/broccoli/tree-differ.spec.ts +++ b/tools/broccoli/tree-differ.spec.ts @@ -31,9 +31,8 @@ describe('TreeDiffer', () => { let diffResult = differ.diffTree(); - expect(diffResult.addedPaths).toEqual([ - 'file-1.txt', 'file-2.txt', 'subdir-1' + path.sep + 'file-1.1.txt' - ]); + expect(diffResult.addedPaths) + .toEqual(['file-1.txt', 'file-2.txt', 'subdir-1' + path.sep + 'file-1.1.txt']); expect(diffResult.changedPaths).toEqual([]); expect(diffResult.removedPaths).toEqual([]); @@ -85,9 +84,8 @@ describe('TreeDiffer', () => { let diffResult = differ.diffTree(); - expect(diffResult.addedPaths).toEqual([ - 'file-1.txt', 'file-2.txt', 'subdir-1' + path.sep + 'file-1.1.txt' - ]); + expect(diffResult.addedPaths) + .toEqual(['file-1.txt', 'file-2.txt', 'subdir-1' + path.sep + 'file-1.1.txt']); // change two files testDir['dir1']['file-1.txt'] = mockfs.file({content: 'new content', mtime: new Date(1000)}); @@ -97,9 +95,8 @@ describe('TreeDiffer', () => { diffResult = differ.diffTree(); - expect(diffResult.changedPaths).toEqual([ - 'file-1.txt', 'subdir-1' + path.sep + 'file-1.1.txt' - ]); + expect(diffResult.changedPaths) + .toEqual(['file-1.txt', 'subdir-1' + path.sep + 'file-1.1.txt']); expect(diffResult.removedPaths).toEqual([]); @@ -134,9 +131,8 @@ describe('TreeDiffer', () => { let diffResult = differ.diffTree(); - expect(diffResult.addedPaths).toEqual([ - 'file-1.txt', 'file-2.txt', 'subdir-1' + path.sep + 'file-1.1.txt' - ]); + expect(diffResult.addedPaths) + .toEqual(['file-1.txt', 'file-2.txt', 'subdir-1' + path.sep + 'file-1.1.txt']); // change two files testDir['orig_path']['file-1.txt'] = @@ -148,9 +144,8 @@ describe('TreeDiffer', () => { diffResult = differ.diffTree(); expect(diffResult.addedPaths).toEqual([]); - expect(diffResult.changedPaths).toEqual([ - 'file-1.txt', 'subdir-1' + path.sep + 'file-1.1.txt' - ]); + expect(diffResult.changedPaths) + .toEqual(['file-1.txt', 'subdir-1' + path.sep + 'file-1.1.txt']); expect(diffResult.removedPaths).toEqual([]); // change one file @@ -189,14 +184,14 @@ describe('TreeDiffer', () => { }); - it('should throw an error if an extension isn\'t prefixed with doc', () => { + it("should throw an error if an extension isn't prefixed with doc", () => { // includeExtensions expect(() => new TreeDiffer('testLabel', 'dir1', ['js'])) - .toThrowError('Extension must begin with \'.\'. Was: \'js\''); + .toThrowError("Extension must begin with '.'. Was: 'js'"); // excludeExtentions expect(() => new TreeDiffer('testLabel', 'dir1', [], ['js'])) - .toThrowError('Extension must begin with \'.\'. Was: \'js\''); + .toThrowError("Extension must begin with '.'. Was: 'js'"); }); diff --git a/tools/broccoli/tree-differ.ts b/tools/broccoli/tree-differ.ts index 931ba211c8..af3000670f 100644 --- a/tools/broccoli/tree-differ.ts +++ b/tools/broccoli/tree-differ.ts @@ -8,7 +8,7 @@ function tryStatSync(path) { try { return fs.statSync(path); } catch (e) { - if (e.code === 'ENOENT') return null; + if (e.code === "ENOENT") return null; throw e; } } @@ -21,18 +21,17 @@ export class TreeDiffer { private include: RegExp = null; private exclude: RegExp = null; - constructor( - private label: string, private rootPath: string, includeExtensions?: string[], - excludeExtensions?: string[]) { + constructor(private label: string, private rootPath: string, includeExtensions?: string[], + excludeExtensions?: string[]) { this.rootDirName = path.basename(rootPath); - let buildRegexp = (arr) => new RegExp(`(${arr.reduce(combine, "")})$`, 'i'); + let buildRegexp = (arr) => new RegExp(`(${arr.reduce(combine, "")})$`, "i"); this.include = (includeExtensions || []).length ? buildRegexp(includeExtensions) : null; this.exclude = (excludeExtensions || []).length ? buildRegexp(excludeExtensions) : null; function combine(prev, curr) { - if (curr.charAt(0) !== '.') { + if (curr.charAt(0) !== ".") { throw new Error(`Extension must begin with '.'. Was: '${curr}'`); } let kSpecialRegexpChars = /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g; @@ -147,17 +146,17 @@ class DirtyCheckingDiffResult extends DiffResult { toString() { return `${pad(this.label, 30)}, ${pad(this.endTime - this.startTime, 5)}ms, ` + - `${pad(this.addedPaths.length + this.changedPaths.length + this.removedPaths.length, 5)} changes ` + - `(files: ${pad(this.filesChecked, 5)}, dirs: ${pad(this.directoriesChecked, 4)})`; + `${pad(this.addedPaths.length + this.changedPaths.length + this.removedPaths.length, 5)} changes ` + + `(files: ${pad(this.filesChecked, 5)}, dirs: ${pad(this.directoriesChecked, 4)})`; } log(verbose) { let prefixedPaths = this.addedPaths.map(p => `+ ${p}`) .concat(this.changedPaths.map(p => `* ${p}`)) .concat(this.removedPaths.map(p => `- ${p}`)); - console.log( - `Tree diff: ${this}` + - ((verbose && prefixedPaths.length) ? ` [\n ${prefixedPaths.join('\n ')}\n]` : '')); + console.log(`Tree diff: ${this}` + ((verbose && prefixedPaths.length) ? + ` [\n ${prefixedPaths.join('\n ')}\n]` : + '')); } } diff --git a/tools/broccoli/trees/browser_tree.ts b/tools/broccoli/trees/browser_tree.ts index b5171e05a6..4f36a8bb93 100644 --- a/tools/broccoli/trees/browser_tree.ts +++ b/tools/broccoli/trees/browser_tree.ts @@ -16,27 +16,51 @@ import checkImports from '../broccoli-check-imports'; const kServedPaths = [ // Relative (to /modules) paths to benchmark directories - 'benchmarks/src', 'benchmarks/src/change_detection', 'benchmarks/src/compiler', - 'benchmarks/src/costs', 'benchmarks/src/di', 'benchmarks/src/element_injector', - 'benchmarks/src/largetable', 'benchmarks/src/naive_infinite_scroll', 'benchmarks/src/tree', + 'benchmarks/src', + 'benchmarks/src/change_detection', + 'benchmarks/src/compiler', + 'benchmarks/src/costs', + 'benchmarks/src/di', + 'benchmarks/src/element_injector', + 'benchmarks/src/largetable', + 'benchmarks/src/naive_infinite_scroll', + 'benchmarks/src/tree', 'benchmarks/src/static_tree', // Relative (to /modules) paths to external benchmark directories - 'benchmarks_external/src', 'benchmarks_external/src/compiler', - 'benchmarks_external/src/largetable', 'benchmarks_external/src/naive_infinite_scroll', - 'benchmarks_external/src/tree', 'benchmarks_external/src/tree/react', + 'benchmarks_external/src', + 'benchmarks_external/src/compiler', + 'benchmarks_external/src/largetable', + 'benchmarks_external/src/naive_infinite_scroll', + 'benchmarks_external/src/tree', + 'benchmarks_external/src/tree/react', 'benchmarks_external/src/static_tree', // Relative (to /modules) paths to example directories - 'playground/src/animate', 'playground/src/benchpress', 'playground/src/model_driven_forms', - 'playground/src/template_driven_forms', 'playground/src/person_management', - 'playground/src/order_management', 'playground/src/gestures', 'playground/src/hash_routing', - 'playground/src/hello_world', 'playground/src/http', 'playground/src/jsonp', - 'playground/src/key_events', 'playground/src/relative_assets', 'playground/src/routing', - 'playground/src/sourcemap', 'playground/src/svg', 'playground/src/todo', 'playground/src/upgrade', - 'playground/src/zippy_component', 'playground/src/async', - 'playground/src/web_workers/kitchen_sink', 'playground/src/web_workers/todo', - 'playground/src/web_workers/images', 'playground/src/web_workers/message_broker', + 'playground/src/animate', + 'playground/src/benchpress', + 'playground/src/model_driven_forms', + 'playground/src/template_driven_forms', + 'playground/src/person_management', + 'playground/src/order_management', + 'playground/src/gestures', + 'playground/src/hash_routing', + 'playground/src/hello_world', + 'playground/src/http', + 'playground/src/jsonp', + 'playground/src/key_events', + 'playground/src/relative_assets', + 'playground/src/routing', + 'playground/src/sourcemap', + 'playground/src/svg', + 'playground/src/todo', + 'playground/src/upgrade', + 'playground/src/zippy_component', + 'playground/src/async', + 'playground/src/web_workers/kitchen_sink', + 'playground/src/web_workers/todo', + 'playground/src/web_workers/images', + 'playground/src/web_workers/message_broker', 'playground/src/web_workers/router' ]; @@ -60,9 +84,9 @@ module.exports = function makeBrowserTree(options, destinationPath) { } if (modules.benchmarks) { - var benchmarksTree = new Funnel( - 'modules/benchmarks', - {include: ['**/**'], exclude: ['e2e_test/**'], destDir: '/benchmarks/'}); + var benchmarksTree = + new Funnel('modules/benchmarks', + {include: ['**/**'], exclude: ['e2e_test/**'], destDir: '/benchmarks/'}); } if (modules.benchmarks_external) { @@ -72,21 +96,21 @@ module.exports = function makeBrowserTree(options, destinationPath) { } if (modules.payload_tests) { - var payloadTestsTree = new Funnel( - 'modules/payload_tests', - {include: ['**/ts/**'], exclude: ['e2e_test/**'], destDir: '/payload_tests/'}); + var payloadTestsTree = + new Funnel('modules/payload_tests', + {include: ['**/ts/**'], exclude: ['e2e_test/**'], destDir: '/payload_tests/'}); } if (modules.playground) { - var playgroundTree = new Funnel( - 'modules/playground', - {include: ['**/**'], exclude: ['e2e_test/**'], destDir: '/playground/'}); + var playgroundTree = + new Funnel('modules/playground', + {include: ['**/**'], exclude: ['e2e_test/**'], destDir: '/playground/'}); } if (modules.benchpress) { - var benchpressTree = new Funnel( - 'modules/benchpress', - {include: ['**/**'], exclude: ['e2e_test/**'], destDir: '/benchpress/'}); + var benchpressTree = + new Funnel('modules/benchpress', + {include: ['**/**'], exclude: ['e2e_test/**'], destDir: '/benchpress/'}); } let externalTypings = @@ -133,13 +157,15 @@ module.exports = function makeBrowserTree(options, destinationPath) { modulesTree = checkImports(modulesTree); modulesTree = replace(modulesTree, { - files: ['playground*/**/*.js'], + files: ["playground*/**/*.js"], patterns: [{match: /\$SCRIPTS\$/, replacement: jsReplace('SCRIPTS')}] }); let ambientTypings = [ - 'angular2/typings/hammerjs/hammerjs.d.ts', 'angular2/typings/node/node.d.ts', - 'node_modules/zone.js/dist/zone.js.d.ts', 'angular2/manual_typings/globals.d.ts', + 'angular2/typings/hammerjs/hammerjs.d.ts', + 'angular2/typings/node/node.d.ts', + 'node_modules/zone.js/dist/zone.js.d.ts', + 'angular2/manual_typings/globals.d.ts', 'angular2/typings/es6-collections/es6-collections.d.ts', 'angular2/typings/es6-promise/es6-promise.d.ts' ]; @@ -161,9 +187,11 @@ module.exports = function makeBrowserTree(options, destinationPath) { var vendorScriptsTree = flatten(new Funnel('.', { files: [ - 'node_modules/es6-shim/es6-shim.js', 'node_modules/zone.js/dist/zone.js', + 'node_modules/es6-shim/es6-shim.js', + 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', - 'node_modules/systemjs/dist/system.src.js', 'node_modules/base64-js/lib/b64.js', + 'node_modules/systemjs/dist/system.src.js', + 'node_modules/base64-js/lib/b64.js', 'node_modules/reflect-metadata/Reflect.js' ] })); @@ -202,8 +230,10 @@ module.exports = function makeBrowserTree(options, destinationPath) { htmlTree = replace(htmlTree, { files: ['playground*/**/*.html'], patterns: [ - {match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS')}, scriptPathPatternReplacement, - scriptFilePatternReplacement, useBundlesPatternReplacement + {match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS')}, + scriptPathPatternReplacement, + scriptFilePatternReplacement, + useBundlesPatternReplacement ] }); } @@ -213,7 +243,9 @@ module.exports = function makeBrowserTree(options, destinationPath) { files: ['benchmarks/**'], patterns: [ {match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS_benchmarks')}, - scriptPathPatternReplacement, scriptFilePatternReplacement, useBundlesPatternReplacement + scriptPathPatternReplacement, + scriptFilePatternReplacement, + useBundlesPatternReplacement ] }); } @@ -223,7 +255,9 @@ module.exports = function makeBrowserTree(options, destinationPath) { files: ['benchmarks_external/**'], patterns: [ {match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS_benchmarks_external')}, - scriptPathPatternReplacement, scriptFilePatternReplacement, useBundlesPatternReplacement + scriptPathPatternReplacement, + scriptFilePatternReplacement, + useBundlesPatternReplacement ] }); } @@ -233,7 +267,7 @@ module.exports = function makeBrowserTree(options, destinationPath) { // for web-worker e2e tests. htmlTree = replace(htmlTree, { files: ['playground*/**/web_workers/**/*.html'], - patterns: [{match: '/bundle/angular2.dev.js', replacement: '/bundle/web_worker/ui.dev.js'}] + patterns: [{match: "/bundle/angular2.dev.js", replacement: "/bundle/web_worker/ui.dev.js"}] }); } @@ -244,8 +278,10 @@ module.exports = function makeBrowserTree(options, destinationPath) { if (modules.benchmarks_external) { var polymerFiles = new Funnel('.', { files: [ - 'bower_components/polymer/polymer.html', 'bower_components/polymer/polymer-micro.html', - 'bower_components/polymer/polymer-mini.html', 'tools/build/snippets/url_params_to_form.js' + 'bower_components/polymer/polymer.html', + 'bower_components/polymer/polymer-micro.html', + 'bower_components/polymer/polymer-mini.html', + 'tools/build/snippets/url_params_to_form.js' ] }); var polymer = stew.mv(flatten(polymerFiles), 'benchmarks_external/src/tree/polymer'); diff --git a/tools/broccoli/trees/dart_tree.ts b/tools/broccoli/trees/dart_tree.ts index be7f11e2c1..2e33a0756c 100644 --- a/tools/broccoli/trees/dart_tree.ts +++ b/tools/broccoli/trees/dart_tree.ts @@ -14,10 +14,19 @@ import replace from '../broccoli-replace'; import {AngularBuilderOptions} from '../angular_builder'; var global_excludes = [ - 'angular2/examples/**/ts/**/*', 'angular2/http*', 'angular2/http/**/*', 'angular2/src/http/**/*', - 'angular2/src/upgrade/**/*', 'angular2/test/http/**/*', 'angular2/test/upgrade/**/*', - 'angular2/upgrade*', 'payload_tests/**/ts/**/*', 'playground/src/http/**/*', - 'playground/src/jsonp/**/*', 'playground/test/http/**/*', 'playground/test/jsonp/**/*' + 'angular2/examples/**/ts/**/*', + 'angular2/http*', + 'angular2/http/**/*', + 'angular2/src/http/**/*', + 'angular2/src/upgrade/**/*', + 'angular2/test/http/**/*', + 'angular2/test/upgrade/**/*', + 'angular2/upgrade*', + 'payload_tests/**/ts/**/*', + 'playground/src/http/**/*', + 'playground/src/jsonp/**/*', + 'playground/test/http/**/*', + 'playground/test/jsonp/**/*' ]; @@ -41,7 +50,7 @@ function replaceScriptTagInHtml(placeholder: string, relativePath: string): stri } var scriptName = relativePath.replace(/\\/g, '/').replace(/.*\/([^/]+)\.html$/, '$1.dart'); scriptTags += '<script src="' + scriptName + '" type="application/dart"></script>\n' + - '<script src="packages/browser/dart.js" type="text/javascript"></script>'; + '<script src="packages/browser/dart.js" type="text/javascript"></script>'; return scriptTags; } @@ -70,11 +79,13 @@ function fixDartFolderLayout(sourceTree) { return stew.rename(sourceTree, function(relativePath) { // If a file matches the `pattern`, insert the given `insertion` as the second path part. var replacements = [ - {pattern: /^benchmarks\/test\//, insertion: ''}, {pattern: /^benchmarks\//, insertion: 'web'}, + {pattern: /^benchmarks\/test\//, insertion: ''}, + {pattern: /^benchmarks\//, insertion: 'web'}, {pattern: /^benchmarks_external\/test\//, insertion: ''}, {pattern: /^benchmarks_external\//, insertion: 'web'}, {pattern: /^playground\/test\//, insertion: ''}, - {pattern: /^playground\//, insertion: 'web/'}, {pattern: /^[^\/]*\/test\//, insertion: ''}, + {pattern: /^playground\//, insertion: 'web/'}, + {pattern: /^[^\/]*\/test\//, insertion: ''}, {pattern: /^./, insertion: 'lib'}, // catch all. ]; @@ -136,7 +147,9 @@ function getDocsTree() { srcPath: 'LICENSE', targetPatterns: ['modules/*'], exclude: [ - '*/angular1_router', '*/angular2/src/http', '*/payload_tests', + '*/angular1_router', + '*/angular2/src/http', + '*/payload_tests', '*/upgrade' ] // Not in dart. }); @@ -144,12 +157,11 @@ function getDocsTree() { // Documentation. // Rename *.dart.md -> *.dart. - var mdTree = stew.rename( - modulesFunnel(['**/*.dart.md']), relativePath => relativePath.replace(/\.dart\.md$/, '.md')); + var mdTree = stew.rename(modulesFunnel(['**/*.dart.md']), + relativePath => relativePath.replace(/\.dart\.md$/, '.md')); // Copy all assets, ignore .js. and .dart. (handled above). - var docs = modulesFunnel( - ['**/*.md', '**/*.png', '**/*.html', '**/*.css', '**/*.scss'], - ['**/*.js.md', '**/*.dart.md', 'angular1_router/**/*']); + var docs = modulesFunnel(['**/*.md', '**/*.png', '**/*.html', '**/*.css', '**/*.scss'], + ['**/*.js.md', '**/*.dart.md', 'angular1_router/**/*']); var assets = modulesFunnel(['playground/**/*.json']); diff --git a/tools/broccoli/trees/node_tree.ts b/tools/broccoli/trees/node_tree.ts index 56d66b5d6f..a58a34daed 100644 --- a/tools/broccoli/trees/node_tree.ts +++ b/tools/broccoli/trees/node_tree.ts @@ -1,7 +1,8 @@ 'use strict'; import destCopy from '../broccoli-dest-copy'; -import compileWithTypescript, {INTERNAL_TYPINGS_PATH} from '../broccoli-typescript'; +import compileWithTypescript, { INTERNAL_TYPINGS_PATH } +from '../broccoli-typescript'; var Funnel = require('broccoli-funnel'); import mergeTrees from '../broccoli-merge-trees'; var path = require('path'); @@ -19,17 +20,26 @@ module.exports = function makeNodeTree(projects, destinationPath) { let srcTree = new Funnel('modules', { include: ['angular2/**'], exclude: [ - '**/e2e_test/**', 'angular2/test/**', 'angular2/examples/**', + '**/e2e_test/**', + 'angular2/test/**', + 'angular2/examples/**', - 'angular2/src/testing/**', 'angular2/testing.ts', 'angular2/testing_internal.ts', - 'angular2/src/upgrade/**', 'angular2/upgrade.ts', 'angular2/platform/testing/**', - 'angular2/manual_typings/**', 'angular2/typings/**' + 'angular2/src/testing/**', + 'angular2/testing.ts', + 'angular2/testing_internal.ts', + 'angular2/src/upgrade/**', + 'angular2/upgrade.ts', + 'angular2/platform/testing/**', + 'angular2/manual_typings/**', + 'angular2/typings/**' ] }); let externalTypings = [ - 'angular2/typings/hammerjs/hammerjs.d.ts', 'angular2/typings/node/node.d.ts', - 'angular2/manual_typings/globals.d.ts', 'angular2/typings/es6-collections/es6-collections.d.ts', + 'angular2/typings/hammerjs/hammerjs.d.ts', + 'angular2/typings/node/node.d.ts', + 'angular2/manual_typings/globals.d.ts', + 'angular2/typings/es6-collections/es6-collections.d.ts', 'angular2/typings/es6-promise/es6-promise.d.ts' ]; @@ -62,21 +72,29 @@ module.exports = function makeNodeTree(projects, destinationPath) { ], exclude: [ // the following code and tests are not compatible with CJS/node environment - 'angular2/test/animate/**', 'angular2/test/core/zone/**', - 'angular2/test/testing/fake_async_spec.ts', 'angular2/test/testing/testing_public_spec.ts', - 'angular2/test/platform/xhr_impl_spec.ts', 'angular2/test/platform/browser/**/*.ts', - 'angular2/test/common/forms/**', 'angular2/manual_typings/**', 'angular2/typings/**', + 'angular2/test/animate/**', + 'angular2/test/core/zone/**', + 'angular2/test/testing/fake_async_spec.ts', + 'angular2/test/testing/testing_public_spec.ts', + 'angular2/test/platform/xhr_impl_spec.ts', + 'angular2/test/platform/browser/**/*.ts', + 'angular2/test/common/forms/**', + 'angular2/manual_typings/**', + 'angular2/typings/**', // we call browser's bootstrap 'angular2/test/router/route_config/route_config_spec.ts', 'angular2/test/router/integration/bootstrap_spec.ts', // we check the public api by importing angular2/angular2 - 'angular2/test/symbol_inspector/**/*.ts', 'angular2/test/public_api_spec.ts', + 'angular2/test/symbol_inspector/**/*.ts', + 'angular2/test/public_api_spec.ts', 'angular2/test/web_workers/worker/renderer_integration_spec.ts', - 'angular2/test/upgrade/**/*.ts', 'angular1_router/**', 'payload_tests/**' + 'angular2/test/upgrade/**/*.ts', + 'angular1_router/**', + 'payload_tests/**' ] }); @@ -119,19 +137,20 @@ module.exports = function makeNodeTree(projects, destinationPath) { // Copy es6 typings so quickstart doesn't require typings install let typingsTree = mergeTrees([ - new Funnel('modules', { - include: [ - 'angular2/typings/es6-collections/es6-collections.d.ts', - 'angular2/typings/es6-promise/es6-promise.d.ts', - ] - }), - writeFile( - 'angular2/typings/browser.d.ts', '// Typings needed for compilation with --target=es5\n' + - '///<reference path="./es6-collections/es6-collections.d.ts"/>\n' + - '///<reference path="./es6-promise/es6-promise.d.ts"/>\n' + - '// Workaround for https://github.com/ReactiveX/RxJS/issues/1270\n' + - '// to be removed when angular2 upgrades to rxjs beta.2\n' + - 'declare type PromiseConstructor = typeof Promise;\n') + new Funnel('modules', + { + include: [ + 'angular2/typings/es6-collections/es6-collections.d.ts', + 'angular2/typings/es6-promise/es6-promise.d.ts', + ] + }), + writeFile('angular2/typings/browser.d.ts', + '// Typings needed for compilation with --target=es5\n' + + '///<reference path="./es6-collections/es6-collections.d.ts"/>\n' + + '///<reference path="./es6-promise/es6-promise.d.ts"/>\n' + + '// Workaround for https://github.com/ReactiveX/RxJS/issues/1270\n' + + '// to be removed when angular2 upgrades to rxjs beta.2\n' + + 'declare type PromiseConstructor = typeof Promise;\n') ]); var nodeTree = @@ -146,9 +165,9 @@ module.exports = function makeNodeTree(projects, destinationPath) { replacement: () => `var parse5Adapter = require('angular2/src/platform/server/parse5_adapter');\r\n` + - `parse5Adapter.Parse5DomAdapter.makeCurrent();` + `parse5Adapter.Parse5DomAdapter.makeCurrent();` }, - {match: /$/, replacement: (_, relativePath) => '\r\n main(); \r\n'} + {match: /$/, replacement: (_, relativePath) => "\r\n main(); \r\n"} ] }); @@ -163,20 +182,20 @@ module.exports = function makeNodeTree(projects, destinationPath) { function compileTree(tree, genInternalTypings, rootFilePaths: string[] = []) { return compileWithTypescript(tree, { // build pipeline options - 'rootFilePaths': rootFilePaths, - 'internalTypings': genInternalTypings, + "rootFilePaths": rootFilePaths, + "internalTypings": genInternalTypings, // tsc options - 'emitDecoratorMetadata': true, - 'experimentalDecorators': true, - 'declaration': true, - 'stripInternal': true, - 'module': 'commonjs', - 'moduleResolution': 'classic', - 'noEmitOnError': true, - 'rootDir': '.', - 'inlineSourceMap': true, - 'inlineSources': true, - 'target': 'es5' + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "declaration": true, + "stripInternal": true, + "module": "commonjs", + "moduleResolution": "classic", + "noEmitOnError": true, + "rootDir": ".", + "inlineSourceMap": true, + "inlineSources": true, + "target": "es5" }); } diff --git a/tools/metadata/src/collector.ts b/tools/metadata/src/collector.ts index d68e626ab5..6e26619cdb 100644 --- a/tools/metadata/src/collector.ts +++ b/tools/metadata/src/collector.ts @@ -1,7 +1,17 @@ import * as ts from 'typescript'; import {Evaluator} from './evaluator'; import {Symbols} from './symbols'; -import {ClassMetadata, ConstructorMetadata, ModuleMetadata, MemberMetadata, MetadataMap, MetadataSymbolicExpression, MetadataSymbolicReferenceExpression, MetadataValue, MethodMetadata} from './schema'; +import { + ClassMetadata, + ConstructorMetadata, + ModuleMetadata, + MemberMetadata, + MetadataMap, + MetadataSymbolicExpression, + MetadataSymbolicReferenceExpression, + MetadataValue, + MethodMetadata +} from './schema'; import * as path from 'path'; @@ -65,7 +75,7 @@ export class MetadataCollector { const declaration = symbol.declarations[0]; const sourceFile = declaration.getSourceFile(); return { - __symbolic: 'reference', + __symbolic: "reference", module: moduleNameOf(sourceFile.fileName), name: symbol.name }; @@ -75,9 +85,8 @@ export class MetadataCollector { } function classMetadataOf(classDeclaration: ts.ClassDeclaration): ClassMetadata { - let result: ClassMetadata = { - __symbolic: 'class' - } + let result: ClassMetadata = + { __symbolic: "class" } function getDecorators(decorators: ts.Decorator[]): MetadataSymbolicExpression[] { @@ -106,7 +115,7 @@ export class MetadataCollector { isConstructor = true; // fallthrough case ts.SyntaxKind.MethodDeclaration: - const method = <ts.MethodDeclaration|ts.ConstructorDeclaration>member; + const method = <ts.MethodDeclaration | ts.ConstructorDeclaration>member; const methodDecorators = getDecorators(method.decorators); const parameters = method.parameters; const parameterDecoratorData: MetadataSymbolicExpression[][] = []; @@ -124,8 +133,8 @@ export class MetadataCollector { } } if (methodDecorators || hasDecoratorData || hasParameterData) { - const data: MethodMetadata = {__symbolic: isConstructor ? 'constructor' : 'method'}; - const name = isConstructor ? '__ctor__' : evaluator.nameOf(member.name); + const data: MethodMetadata = {__symbolic: isConstructor ? "constructor" : "method"}; + const name = isConstructor ? "__ctor__" : evaluator.nameOf(member.name); if (methodDecorators) { data.decorators = methodDecorators; } @@ -144,9 +153,8 @@ export class MetadataCollector { const property = <ts.PropertyDeclaration>member; const propertyDecorators = getDecorators(property.decorators); if (propertyDecorators) { - recordMember( - evaluator.nameOf(property.name), - {__symbolic: 'property', decorators: propertyDecorators}); + recordMember(evaluator.nameOf(property.name), + {__symbolic: 'property', decorators: propertyDecorators}); } break; } @@ -188,6 +196,6 @@ export class MetadataCollector { } } } - return metadata && {__symbolic: 'module', module: moduleNameOf(sourceFile.fileName), metadata}; + return metadata && {__symbolic: "module", module: moduleNameOf(sourceFile.fileName), metadata}; } } diff --git a/tools/metadata/src/evaluator.ts b/tools/metadata/src/evaluator.ts index 7d06a33563..d654b95140 100644 --- a/tools/metadata/src/evaluator.ts +++ b/tools/metadata/src/evaluator.ts @@ -1,7 +1,12 @@ import * as ts from 'typescript'; import {Symbols} from './symbols'; -import {MetadataValue, MetadataObject, MetadataSymbolicCallExpression, MetadataSymbolicReferenceExpression} from './schema'; +import { + MetadataValue, + MetadataObject, + MetadataSymbolicCallExpression, + MetadataSymbolicReferenceExpression +} from './schema'; // TOOD: Remove when tools directory is upgraded to support es6 target interface Map<K, V> { @@ -58,9 +63,8 @@ function isDefined(obj: any): boolean { * possible. */ export class Evaluator { - constructor( - private typeChecker: ts.TypeChecker, private symbols: Symbols, - private moduleNameOf: (fileName: string) => string) {} + constructor(private typeChecker: ts.TypeChecker, private symbols: Symbols, + private moduleNameOf: (fileName: string) => string) {} // TODO: Determine if the first declaration is deterministic. private symbolFileName(symbol: ts.Symbol): string { @@ -83,7 +87,7 @@ export class Evaluator { if (symbol) { const name = symbol.name; const module = this.moduleNameOf(this.symbolFileName(symbol)); - return {__symbolic: 'reference', name, module}; + return {__symbolic: "reference", name, module}; } } @@ -134,7 +138,7 @@ export class Evaluator { case ts.SyntaxKind.CallExpression: const callExpression = <ts.CallExpression>node; // We can fold a <array>.concat(<v>). - if (isMethodCallOf(callExpression, 'concat') && callExpression.arguments.length === 1) { + if (isMethodCallOf(callExpression, "concat") && callExpression.arguments.length === 1) { const arrayNode = (<ts.PropertyAccessExpression>callExpression.expression).expression; if (this.isFoldableWorker(arrayNode, folding) && this.isFoldableWorker(callExpression.arguments[0], folding)) { @@ -146,7 +150,7 @@ export class Evaluator { } } // We can fold a call to CONST_EXPR - if (isCallOf(callExpression, 'CONST_EXPR') && callExpression.arguments.length === 1) + if (isCallOf(callExpression, "CONST_EXPR") && callExpression.arguments.length === 1) return this.isFoldableWorker(callExpression.arguments[0], folding); return false; case ts.SyntaxKind.NoSubstitutionTemplateLiteral: @@ -170,7 +174,7 @@ export class Evaluator { case ts.SyntaxKind.AmpersandAmpersandToken: case ts.SyntaxKind.BarBarToken: return this.isFoldableWorker(binaryExpression.left, folding) && - this.isFoldableWorker(binaryExpression.right, folding); + this.isFoldableWorker(binaryExpression.right, folding); } case ts.SyntaxKind.PropertyAccessExpression: const propertyAccessExpression = <ts.PropertyAccessExpression>node; @@ -178,7 +182,7 @@ export class Evaluator { case ts.SyntaxKind.ElementAccessExpression: const elementAccessExpression = <ts.ElementAccessExpression>node; return this.isFoldableWorker(elementAccessExpression.expression, folding) && - this.isFoldableWorker(elementAccessExpression.argumentExpression, folding); + this.isFoldableWorker(elementAccessExpression.argumentExpression, folding); case ts.SyntaxKind.Identifier: let symbol = this.typeChecker.getSymbolAtLocation(node); if (symbol.flags & ts.SymbolFlags.Alias) { @@ -241,20 +245,20 @@ export class Evaluator { const callExpression = <ts.CallExpression>node; const args = callExpression.arguments.map(arg => this.evaluateNode(arg)); if (this.isFoldable(callExpression)) { - if (isMethodCallOf(callExpression, 'concat')) { + if (isMethodCallOf(callExpression, "concat")) { const arrayValue = <MetadataValue[]>this.evaluateNode( (<ts.PropertyAccessExpression>callExpression.expression).expression); return arrayValue.concat(args[0]); } } // Always fold a CONST_EXPR even if the argument is not foldable. - if (isCallOf(callExpression, 'CONST_EXPR') && callExpression.arguments.length === 1) { + if (isCallOf(callExpression, "CONST_EXPR") && callExpression.arguments.length === 1) { return args[0]; } const expression = this.evaluateNode(callExpression.expression); if (isDefined(expression) && args.every(isDefined)) { const result: MetadataSymbolicCallExpression = { - __symbolic: 'call', + __symbolic: "call", expression: this.evaluateNode(callExpression.expression) }; if (args && args.length) { @@ -269,7 +273,7 @@ export class Evaluator { const member = this.nameOf(propertyAccessExpression.name); if (this.isFoldable(propertyAccessExpression.expression)) return expression[member]; if (isDefined(expression)) { - return {__symbolic: 'select', expression, member}; + return {__symbolic: "select", expression, member}; } break; } @@ -279,9 +283,9 @@ export class Evaluator { const index = this.evaluateNode(elementAccessExpression.argumentExpression); if (this.isFoldable(elementAccessExpression.expression) && this.isFoldable(elementAccessExpression.argumentExpression)) - return expression[<string|number>index]; + return expression[<string | number>index]; if (isDefined(expression) && isDefined(index)) { - return {__symbolic: 'index', expression, index}; + return {__symbolic: "index", expression, index}; } break; } @@ -348,7 +352,7 @@ export class Evaluator { default: return undefined; } - return {__symbolic: 'pre', operator: operatorText, operand: operand}; + return {__symbolic: "pre", operator: operatorText, operand: operand }; case ts.SyntaxKind.BinaryExpression: const binaryExpression = <ts.BinaryExpression>node; const left = this.evaluateNode(binaryExpression.left); @@ -400,7 +404,7 @@ export class Evaluator { return <any>left % <any>right; } return { - __symbolic: 'binop', + __symbolic: "binop", operator: binaryExpression.operatorToken.getText(), left: left, right: right diff --git a/tools/metadata/src/schema.ts b/tools/metadata/src/schema.ts index a6af23a410..746c4d6d98 100644 --- a/tools/metadata/src/schema.ts +++ b/tools/metadata/src/schema.ts @@ -6,7 +6,7 @@ export interface ModuleMetadata { metadata: {[name: string]: (ClassMetadata | MetadataValue)}; } export function isModuleMetadata(value: any): value is ModuleMetadata { - return value && value.__symbolic === 'module'; + return value && value.__symbolic === "module"; } export interface ClassMetadata { @@ -15,7 +15,7 @@ export interface ClassMetadata { members?: MetadataMap; } export function isClassMetadata(value: any): value is ClassMetadata { - return value && value.__symbolic === 'class'; + return value && value.__symbolic === "class"; } export interface MetadataMap { [name: string]: MemberMetadata[]; } @@ -27,9 +27,9 @@ export interface MemberMetadata { export function isMemberMetadata(value: any): value is MemberMetadata { if (value) { switch (value.__symbolic) { - case 'constructor': - case 'method': - case 'property': + case "constructor": + case "method": + case "property": return true; } } @@ -41,7 +41,7 @@ export interface MethodMetadata extends MemberMetadata { parameterDecorators?: MetadataSymbolicExpression[][]; } export function isMethodMetadata(value: any): value is MemberMetadata { - return value && (value.__symbolic === 'constructor' || value.__symbolic === 'method'); + return value && (value.__symbolic === "constructor" || value.__symbolic === "method"); } export interface ConstructorMetadata extends MethodMetadata { @@ -49,7 +49,7 @@ export interface ConstructorMetadata extends MethodMetadata { parameters?: MetadataSymbolicExpression[]; } export function isConstructorMetadata(value: any): value is ConstructorMetadata { - return value && value.__symbolic === 'constructor'; + return value && value.__symbolic === "constructor"; } export type MetadataValue = @@ -65,12 +65,12 @@ export interface MetadataSymbolicExpression { export function isMetadataSymbolicExpression(value: any): value is MetadataSymbolicExpression { if (value) { switch (value.__symbolic) { - case 'binary': - case 'call': - case 'index': - case 'pre': - case 'reference': - case 'select': + case "binary": + case "call": + case "index": + case "pre": + case "reference": + case "select": return true; } } @@ -85,9 +85,9 @@ export interface MetadataSymbolicBinaryExpression extends MetadataSymbolicExpres left: MetadataValue; right: MetadataValue; } -export function isMetadataSymbolicBinaryExpression(value: any): - value is MetadataSymbolicBinaryExpression { - return value && value.__symbolic === 'binary'; +export function isMetadataSymbolicBinaryExpression( + value: any): value is MetadataSymbolicBinaryExpression { + return value && value.__symbolic === "binary"; } export interface MetadataSymbolicIndexExpression extends MetadataSymbolicExpression { @@ -95,9 +95,9 @@ export interface MetadataSymbolicIndexExpression extends MetadataSymbolicExpress expression: MetadataValue; index: MetadataValue; } -export function isMetadataSymbolicIndexExpression(value: any): - value is MetadataSymbolicIndexExpression { - return value && value.__symbolic === 'index'; +export function isMetadataSymbolicIndexExpression( + value: any): value is MetadataSymbolicIndexExpression { + return value && value.__symbolic === "index"; } export interface MetadataSymbolicCallExpression extends MetadataSymbolicExpression { @@ -105,9 +105,9 @@ export interface MetadataSymbolicCallExpression extends MetadataSymbolicExpressi expression: MetadataValue; arguments?: MetadataValue[]; } -export function isMetadataSymbolicCallExpression(value: any): - value is MetadataSymbolicCallExpression { - return value && value.__symbolic === 'call'; +export function isMetadataSymbolicCallExpression( + value: any): value is MetadataSymbolicCallExpression { + return value && value.__symbolic === "call"; } export interface MetadataSymbolicPrefixExpression extends MetadataSymbolicExpression { @@ -115,9 +115,9 @@ export interface MetadataSymbolicPrefixExpression extends MetadataSymbolicExpres operator: string; // "+" | "-" | "~" | "!"; operand: MetadataValue; } -export function isMetadataSymbolicPrefixExpression(value: any): - value is MetadataSymbolicPrefixExpression { - return value && value.__symbolic === 'pre'; +export function isMetadataSymbolicPrefixExpression( + value: any): value is MetadataSymbolicPrefixExpression { + return value && value.__symbolic === "pre"; } export interface MetadataSymbolicReferenceExpression extends MetadataSymbolicExpression { @@ -125,9 +125,9 @@ export interface MetadataSymbolicReferenceExpression extends MetadataSymbolicExp name: string; module: string; } -export function isMetadataSymbolicReferenceExpression(value: any): - value is MetadataSymbolicReferenceExpression { - return value && value.__symbolic === 'reference'; +export function isMetadataSymbolicReferenceExpression( + value: any): value is MetadataSymbolicReferenceExpression { + return value && value.__symbolic === "reference"; } export interface MetadataSymbolicSelectExpression extends MetadataSymbolicExpression { @@ -135,7 +135,7 @@ export interface MetadataSymbolicSelectExpression extends MetadataSymbolicExpres expression: MetadataValue; name: string; } -export function isMetadataSymbolicSelectExpression(value: any): - value is MetadataSymbolicSelectExpression { - return value && value.__symbolic === 'select'; +export function isMetadataSymbolicSelectExpression( + value: any): value is MetadataSymbolicSelectExpression { + return value && value.__symbolic === "select"; } diff --git a/tools/metadata/test/collector.spec.ts b/tools/metadata/test/collector.spec.ts index 4fbf9db52a..652a0ea024 100644 --- a/tools/metadata/test/collector.spec.ts +++ b/tools/metadata/test/collector.spec.ts @@ -29,7 +29,7 @@ describe('Collector', () => { expect(metadata).toBeUndefined(); }); - it('should be able to collect a simple component\'s metadata', () => { + it("should be able to collect a simple component's metadata", () => { const sourceFile = program.getSourceFile('app/hero-detail.component.ts'); const metadata = collector.getMetadata(sourceFile, typeChecker); expect(metadata).toEqual({ @@ -38,12 +38,14 @@ describe('Collector', () => { metadata: { HeroDetailComponent: { __symbolic: 'class', - decorators: [{ - __symbolic: 'call', - expression: {__symbolic: 'reference', name: 'Component', module: 'angular2/core'}, - arguments: [{ - selector: 'my-hero-detail', - template: ` + decorators: [ + { + __symbolic: 'call', + expression: {__symbolic: 'reference', name: 'Component', module: 'angular2/core'}, + arguments: [ + { + selector: 'my-hero-detail', + template: ` <div *ngIf="hero"> <h2>{{hero.name}} details!</h2> <div><label>id: </label>{{hero.id}}</div> @@ -53,24 +55,30 @@ describe('Collector', () => { </div> </div> ` - }] - }], + } + ] + } + ], members: { - hero: [{ - __symbolic: 'property', - decorators: [{ - __symbolic: 'call', - expression: - {__symbolic: 'reference', name: 'Input', module: 'angular2/core'} - }] - }] + hero: [ + { + __symbolic: 'property', + decorators: [ + { + __symbolic: 'call', + expression: + {__symbolic: 'reference', name: 'Input', module: 'angular2/core'} + } + ] + } + ] } } } }); }); - it('should be able to get a more complicated component\'s metadata', () => { + it("should be able to get a more complicated component's metadata", () => { const sourceFile = program.getSourceFile('/app/app.component.ts'); const metadata = collector.getMetadata(sourceFile, typeChecker); expect(metadata).toEqual({ @@ -79,12 +87,14 @@ describe('Collector', () => { metadata: { AppComponent: { __symbolic: 'class', - decorators: [{ - __symbolic: 'call', - expression: {__symbolic: 'reference', name: 'Component', module: 'angular2/core'}, - arguments: [{ - selector: 'my-app', - template: ` + decorators: [ + { + __symbolic: 'call', + expression: {__symbolic: 'reference', name: 'Component', module: 'angular2/core'}, + arguments: [ + { + selector: 'my-app', + template: ` <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="#hero of heroes" @@ -95,27 +105,37 @@ describe('Collector', () => { </ul> <my-hero-detail [hero]="selectedHero"></my-hero-detail> `, - directives: [ - { - __symbolic: 'reference', - name: 'HeroDetailComponent', - module: './hero-detail.component' - }, - {__symbolic: 'reference', name: 'NgFor', module: 'angular2/common'} - ], - providers: [{__symbolic: 'reference', name: 'HeroService', module: './hero.service'}], - pipes: [ - {__symbolic: 'reference', name: 'LowerCasePipe', module: 'angular2/common'}, - {__symbolic: 'reference', name: 'UpperCasePipe', module: 'angular2/common'} + directives: [ + { + __symbolic: 'reference', + name: 'HeroDetailComponent', + module: './hero-detail.component' + }, + {__symbolic: 'reference', name: 'NgFor', module: 'angular2/common'} + ], + providers: + [{__symbolic: 'reference', name: 'HeroService', module: './hero.service'}], + pipes: [ + {__symbolic: 'reference', name: 'LowerCasePipe', module: 'angular2/common'}, + { + __symbolic: 'reference', + name: 'UpperCasePipe', + module: 'angular2/common' + } + ] + } ] - }] - }], + } + ], members: { - __ctor__: [{ - __symbolic: 'constructor', - parameters: - [{__symbolic: 'reference', module: './hero.service', name: 'HeroService'}] - }] + __ctor__: [ + { + __symbolic: 'constructor', + parameters: [ + {__symbolic: 'reference', module: './hero.service', name: 'HeroService'} + ] + } + ] } } } @@ -130,11 +150,16 @@ describe('Collector', () => { module: './mock-heroes', metadata: { HEROES: [ - {'id': 11, 'name': 'Mr. Nice'}, {'id': 12, 'name': 'Narco'}, - {'id': 13, 'name': 'Bombasto'}, {'id': 14, 'name': 'Celeritas'}, - {'id': 15, 'name': 'Magneta'}, {'id': 16, 'name': 'RubberMan'}, - {'id': 17, 'name': 'Dynama'}, {'id': 18, 'name': 'Dr IQ'}, {'id': 19, 'name': 'Magma'}, - {'id': 20, 'name': 'Tornado'} + {"id": 11, "name": "Mr. Nice"}, + {"id": 12, "name": "Narco"}, + {"id": 13, "name": "Bombasto"}, + {"id": 14, "name": "Celeritas"}, + {"id": 15, "name": "Magneta"}, + {"id": 16, "name": "RubberMan"}, + {"id": 17, "name": "Dynama"}, + {"id": 18, "name": "Dr IQ"}, + {"id": 19, "name": "Magma"}, + {"id": 20, "name": "Tornado"} ] } }); @@ -164,14 +189,18 @@ describe('Collector', () => { it('should record annotations on set and get declartions', () => { const propertyData = { - name: [{ - __symbolic: 'property', - decorators: [{ - __symbolic: 'call', - expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Input'}, - arguments: ['firstName'] - }] - }] + name: [ + { + __symbolic: 'property', + decorators: [ + { + __symbolic: 'call', + expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Input'}, + arguments: ['firstName'] + } + ] + } + ] }; const caseGetProp = <ClassMetadata>casesMetadata.metadata['GetProp']; expect(caseGetProp.members).toEqual(propertyData); @@ -194,8 +223,7 @@ const FILES: Directory = { @Component({ selector: 'my-app', - template:` + - '`' + ` + template:` + "`" + ` <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="#hero of heroes" @@ -206,7 +234,7 @@ const FILES: Directory = { </ul> <my-hero-detail [hero]="selectedHero"></my-hero-detail> ` + - '`' + `, + "`" + `, directives: [HeroDetailComponent, NgFor], providers: [HeroService], pipes: [LowerCasePipe, UpperCasePipe] @@ -239,8 +267,7 @@ const FILES: Directory = { @Component({ selector: 'my-hero-detail', - template: ` + - '`' + ` + template: ` + "`" + ` <div *ngIf="hero"> <h2>{{hero.name}} details!</h2> <div><label>id: </label>{{hero.id}}</div> @@ -249,8 +276,7 @@ const FILES: Directory = { <input [(ngModel)]="hero.name" placeholder="name"/> </div> </div> - ` + - '`' + `, + ` + "`" + `, }) export class HeroDetailComponent { @Input() public hero: Hero; diff --git a/tools/metadata/test/evaluator.spec.ts b/tools/metadata/test/evaluator.spec.ts index 0e34e4c1af..f52a03982b 100644 --- a/tools/metadata/test/evaluator.spec.ts +++ b/tools/metadata/test/evaluator.spec.ts @@ -73,13 +73,13 @@ describe('Evaluator', () => { expect(evaluator.evaluateNode(findVar(expressions, 'bBAnd').initializer)).toEqual(0x11 & 0x03); expect(evaluator.evaluateNode(findVar(expressions, 'bXor').initializer)).toEqual(0x11 ^ 0x21); expect(evaluator.evaluateNode(findVar(expressions, 'bEqual').initializer)) - .toEqual(1 == <any>'1'); + .toEqual(1 == <any>"1"); expect(evaluator.evaluateNode(findVar(expressions, 'bNotEqual').initializer)) - .toEqual(1 != <any>'1'); + .toEqual(1 != <any>"1"); expect(evaluator.evaluateNode(findVar(expressions, 'bIdentical').initializer)) - .toEqual(1 === <any>'1'); + .toEqual(1 === <any>"1"); expect(evaluator.evaluateNode(findVar(expressions, 'bNotIdentical').initializer)) - .toEqual(1 !== <any>'1'); + .toEqual(1 !== <any>"1"); expect(evaluator.evaluateNode(findVar(expressions, 'bLessThan').initializer)).toEqual(1 < 2); expect(evaluator.evaluateNode(findVar(expressions, 'bGreaterThan').initializer)).toEqual(1 > 2); expect(evaluator.evaluateNode(findVar(expressions, 'bLessThanEqual').initializer)) @@ -97,9 +97,9 @@ describe('Evaluator', () => { it('should report recursive references as symbolic', () => { var expressions = program.getSourceFile('expressions.ts'); expect(evaluator.evaluateNode(findVar(expressions, 'recursiveA').initializer)) - .toEqual({__symbolic: 'reference', name: 'recursiveB', module: 'expressions.ts'}); + .toEqual({__symbolic: "reference", name: "recursiveB", module: "expressions.ts"}); expect(evaluator.evaluateNode(findVar(expressions, 'recursiveB').initializer)) - .toEqual({__symbolic: 'reference', name: 'recursiveA', module: 'expressions.ts'}); + .toEqual({__symbolic: "reference", name: "recursiveA", module: "expressions.ts"}); }); }); diff --git a/tools/metadata/test/typescript.mocks.ts b/tools/metadata/test/typescript.mocks.ts index 5f90d9058c..c2c5a6b50f 100644 --- a/tools/metadata/test/typescript.mocks.ts +++ b/tools/metadata/test/typescript.mocks.ts @@ -2,7 +2,7 @@ import * as path from 'path'; import * as fs from 'fs'; import * as ts from 'typescript'; -export interface Directory { [name: string]: (Directory|string); } +export interface Directory { [name: string]: (Directory | string); } export class Host implements ts.LanguageServiceHost { constructor(private directory: Directory, private scripts: string[]) {} @@ -17,7 +17,7 @@ export class Host implements ts.LanguageServiceHost { getScriptFileNames(): string[] { return this.scripts; } - getScriptVersion(fileName: string): string { return '1'; } + getScriptVersion(fileName: string): string { return "1"; } getScriptSnapshot(fileName: string): ts.IScriptSnapshot { let content = this.getFileContent(fileName); @@ -33,7 +33,7 @@ export class Host implements ts.LanguageServiceHost { if (names[names.length - 1] === 'lib.d.ts') { return fs.readFileSync(ts.getDefaultLibFilePath(this.getCompilationSettings()), 'utf8'); } - let current: Directory|string = this.directory; + let current: Directory | string = this.directory; if (names.length && names[0] === '') names.shift(); for (const name of names) { if (!current || typeof current === 'string') return undefined; @@ -44,9 +44,8 @@ export class Host implements ts.LanguageServiceHost { } export class MockNode implements ts.Node { - constructor( - public kind: ts.SyntaxKind = ts.SyntaxKind.Identifier, public flags: ts.NodeFlags = 0, - public pos: number = 0, public end: number = 0) {} + constructor(public kind: ts.SyntaxKind = ts.SyntaxKind.Identifier, public flags: ts.NodeFlags = 0, + public pos: number = 0, public end: number = 0) {} getSourceFile(): ts.SourceFile { return null; } getChildCount(sourceFile?: ts.SourceFile): number { return 0 } getChildAt(index: number, sourceFile?: ts.SourceFile): ts.Node { return null; } @@ -72,9 +71,8 @@ export class MockIdentifier extends MockNode implements ts.Identifier { public _unaryExpressionBrand: any; public _expressionBrand: any; - constructor( - public name: string, kind: ts.SyntaxKind = ts.SyntaxKind.Identifier, flags: ts.NodeFlags = 0, - pos: number = 0, end: number = 0) { + constructor(public name: string, kind: ts.SyntaxKind = ts.SyntaxKind.Identifier, + flags: ts.NodeFlags = 0, pos: number = 0, end: number = 0) { super(kind, flags, pos, end); this.text = name; } @@ -83,33 +81,31 @@ export class MockIdentifier extends MockNode implements ts.Identifier { export class MockVariableDeclaration extends MockNode implements ts.VariableDeclaration { public _declarationBrand: any; - constructor( - public name: ts.Identifier, kind: ts.SyntaxKind = ts.SyntaxKind.VariableDeclaration, - flags: ts.NodeFlags = 0, pos: number = 0, end: number = 0) { + constructor(public name: ts.Identifier, kind: ts.SyntaxKind = ts.SyntaxKind.VariableDeclaration, + flags: ts.NodeFlags = 0, pos: number = 0, end: number = 0) { super(kind, flags, pos, end); } - static of (name: string): MockVariableDeclaration { + static of(name: string): MockVariableDeclaration { return new MockVariableDeclaration(new MockIdentifier(name)); } } export class MockSymbol implements ts.Symbol { - constructor( - public name: string, private node: ts.Declaration = MockVariableDeclaration.of(name), - public flags: ts.SymbolFlags = 0) {} + constructor(public name: string, private node: ts.Declaration = MockVariableDeclaration.of(name), + public flags: ts.SymbolFlags = 0) {} getFlags(): ts.SymbolFlags { return this.flags; } getName(): string { return this.name; } getDeclarations(): ts.Declaration[] { return [this.node]; } getDocumentationComment(): ts.SymbolDisplayPart[] { return []; } - static of (name: string): MockSymbol { return new MockSymbol(name); } + static of(name: string): MockSymbol { return new MockSymbol(name); } } export function expectNoDiagnostics(diagnostics: ts.Diagnostic[]) { for (const diagnostic of diagnostics) { - let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); let {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } @@ -135,13 +131,13 @@ export function allChildren<T>(node: ts.Node, cb: (node: ts.Node) => T) { } export function findClass(sourceFile: ts.SourceFile, name: string): ts.ClassDeclaration { - return ts.forEachChild( - sourceFile, node => isClass(node) && isNamed(node.name, name) ? node : undefined); + return ts.forEachChild(sourceFile, + node => isClass(node) && isNamed(node.name, name) ? node : undefined); } export function findVar(sourceFile: ts.SourceFile, name: string): ts.VariableDeclaration { - return allChildren( - sourceFile, node => isVar(node) && isNamed(node.name, name) ? node : undefined); + return allChildren(sourceFile, + node => isVar(node) && isNamed(node.name, name) ? node : undefined); } export function isClass(node: ts.Node): node is ts.ClassDeclaration { diff --git a/tools/public_api_guard/public_api_spec.ts b/tools/public_api_guard/public_api_spec.ts index c252131c92..b5e2c5047f 100644 --- a/tools/public_api_guard/public_api_spec.ts +++ b/tools/public_api_guard/public_api_spec.ts @@ -12,15 +12,23 @@ import {publicApi} from 'ts-api-guardian'; // ================================================================================================= const CORE = [ - 'AbstractProviderError', 'AbstractProviderError.addKey(injector:Injector, key:Key):void', + 'AbstractProviderError', + 'AbstractProviderError.addKey(injector:Injector, key:Key):void', 'AbstractProviderError.constructResolvingMessage:Function', 'AbstractProviderError.constructor(injector:Injector, key:Key, constructResolvingMessage:Function)', - 'AbstractProviderError.context:any', 'AbstractProviderError.injectors:Injector[]', - 'AbstractProviderError.keys:Key[]', 'AbstractProviderError.message:string', 'AfterContentChecked', - 'AfterContentChecked.ngAfterContentChecked():any', 'AfterContentInit', - 'AfterContentInit.ngAfterContentInit():any', 'AfterViewChecked', - 'AfterViewChecked.ngAfterViewChecked():any', 'AfterViewInit', - 'AfterViewInit.ngAfterViewInit():any', 'AppViewManager', + 'AbstractProviderError.context:any', + 'AbstractProviderError.injectors:Injector[]', + 'AbstractProviderError.keys:Key[]', + 'AbstractProviderError.message:string', + 'AfterContentChecked', + 'AfterContentChecked.ngAfterContentChecked():any', + 'AfterContentInit', + 'AfterContentInit.ngAfterContentInit():any', + 'AfterViewChecked', + 'AfterViewChecked.ngAfterViewChecked():any', + 'AfterViewInit', + 'AfterViewInit.ngAfterViewInit():any', + 'AppViewManager', 'AppViewManager.attachViewInContainer(viewContainerLocation:ElementRef, index:number, viewRef:EmbeddedViewRef):EmbeddedViewRef', 'AppViewManager.createEmbeddedViewInContainer(viewContainerLocation:ElementRef, index:number, templateRef:TemplateRef):EmbeddedViewRef', 'AppViewManager.createHostViewInContainer(viewContainerLocation:ElementRef, index:number, hostViewFactoryRef:HostViewFactoryRef, dynamicallyCreatedProviders:ResolvedProvider[], projectableNodes:any[][]):HostViewRef', @@ -31,186 +39,348 @@ const CORE = [ 'AppViewManager.getComponent(hostLocation:ElementRef):any', 'AppViewManager.getHostElement(hostViewRef:HostViewRef):ElementRef', 'AppViewManager.getNamedElementInComponentView(hostLocation:ElementRef, variableName:string):ElementRef', - 'AppViewManager.getViewContainer(location:ElementRef):ViewContainerRef', 'ApplicationRef', + 'AppViewManager.getViewContainer(location:ElementRef):ViewContainerRef', + 'ApplicationRef', 'ApplicationRef.bootstrap(componentType:Type, providers:Array<Type|Provider|any[]>):Promise<ComponentRef>', - 'ApplicationRef.componentTypes:Type[]', 'ApplicationRef.dispose():void', + 'ApplicationRef.componentTypes:Type[]', + 'ApplicationRef.dispose():void', 'ApplicationRef.injector:Injector', 'ApplicationRef.registerBootstrapListener(listener:(ref: ComponentRef) => void):void', - 'ApplicationRef.registerDisposeListener(dispose:() => void):void', 'ApplicationRef.tick():void', - 'ApplicationRef.zone:NgZone', 'AttributeFactory', 'AttributeMetadata', - 'AttributeMetadata.constructor(attributeName:string)', 'AttributeMetadata.toString():string', - 'AttributeMetadata.token:AttributeMetadata', 'Binding', + 'ApplicationRef.registerDisposeListener(dispose:() => void):void', + 'ApplicationRef.tick():void', + 'ApplicationRef.zone:NgZone', + 'AttributeFactory', + 'AttributeMetadata', + 'AttributeMetadata.constructor(attributeName:string)', + 'AttributeMetadata.toString():string', + 'AttributeMetadata.token:AttributeMetadata', + 'Binding', 'Binding.constructor(token:any, {toClass,toValue,toAlias,toFactory,deps,multi}:{toClass?:Type, toValue?:any, toAlias?:any, toFactory:Function, deps?:Object[], multi?:boolean})', - 'Binding.toAlias:any', 'Binding.toClass:any', 'Binding.toFactory:any', 'Binding.toValue:any', + 'Binding.toAlias:any', + 'Binding.toClass:any', + 'Binding.toFactory:any', + 'Binding.toValue:any', 'ChangeDetectionError', 'ChangeDetectionError.constructor(exp:string, originalException:any, originalStack:any, context:any)', - 'ChangeDetectionError.location:string', 'ChangeDetectionStrategy', - 'ChangeDetectionStrategy.CheckAlways', 'ChangeDetectionStrategy.CheckOnce', - 'ChangeDetectionStrategy.Checked', 'ChangeDetectionStrategy.Default', - 'ChangeDetectionStrategy.Detached', 'ChangeDetectionStrategy.OnPush', 'ChangeDetectorRef', - 'ChangeDetectorRef.checkNoChanges():void', 'ChangeDetectorRef.detach():void', - 'ChangeDetectorRef.detectChanges():void', 'ChangeDetectorRef.markForCheck():void', - 'ChangeDetectorRef.reattach():void', 'Class(clsDef:ClassDefinition):ConcreteType', - 'ClassDefinition', 'ClassDefinition.constructor:Function|any[]', 'ClassDefinition.extends:Type', - 'CollectionChangeRecord', 'CollectionChangeRecord.constructor(item:any, trackById:any)', - 'CollectionChangeRecord.currentIndex:number', 'CollectionChangeRecord.previousIndex:number', - 'CollectionChangeRecord.toString():string', 'Compiler', 'Compiler.clearCache():any', - 'Compiler.compileInHost(componentType:Type):Promise<HostViewFactoryRef>', 'ComponentDecorator', + 'ChangeDetectionError.location:string', + 'ChangeDetectionStrategy', + 'ChangeDetectionStrategy.CheckAlways', + 'ChangeDetectionStrategy.CheckOnce', + 'ChangeDetectionStrategy.Checked', + 'ChangeDetectionStrategy.Default', + 'ChangeDetectionStrategy.Detached', + 'ChangeDetectionStrategy.OnPush', + 'ChangeDetectorRef', + 'ChangeDetectorRef.checkNoChanges():void', + 'ChangeDetectorRef.detach():void', + 'ChangeDetectorRef.detectChanges():void', + 'ChangeDetectorRef.markForCheck():void', + 'ChangeDetectorRef.reattach():void', + 'Class(clsDef:ClassDefinition):ConcreteType', + 'ClassDefinition', + 'ClassDefinition.constructor:Function|any[]', + 'ClassDefinition.extends:Type', + 'CollectionChangeRecord', + 'CollectionChangeRecord.constructor(item:any, trackById:any)', + 'CollectionChangeRecord.currentIndex:number', + 'CollectionChangeRecord.previousIndex:number', + 'CollectionChangeRecord.toString():string', + 'Compiler', + 'Compiler.clearCache():any', + 'Compiler.compileInHost(componentType:Type):Promise<HostViewFactoryRef>', + 'ComponentDecorator', 'ComponentDecorator.View(obj:{templateUrl?:string, template?:string, directives?:Array<Type|any[]>, pipes?:Array<Type|any[]>, renderer?:string, styles?:string[], styleUrls?:string[]}):ViewDecorator', - 'ComponentFactory', 'ComponentMetadata', + 'ComponentFactory', + 'ComponentMetadata', 'ComponentMetadata.changeDetection:ChangeDetectionStrategy', 'ComponentMetadata.constructor({selector,inputs,outputs,properties,events,host,exportAs,moduleId,bindings,providers,viewBindings,viewProviders,changeDetection=ChangeDetectionStrategy.Default,queries,templateUrl,template,styleUrls,styles,directives,pipes,encapsulation}:{selector?:string, inputs?:string[], outputs?:string[], properties?:string[], events?:string[], host?:{[key:string]:string}, bindings?:any[], providers?:any[], exportAs?:string, moduleId?:string, viewBindings?:any[], viewProviders?:any[], queries?:{[key:string]:any}, changeDetection?:ChangeDetectionStrategy, templateUrl?:string, template?:string, styleUrls?:string[], styles?:string[], directives?:Array<Type|any[]>, pipes?:Array<Type|any[]>, encapsulation?:ViewEncapsulation})', 'ComponentMetadata.directives:Array<Type|any[]>', - 'ComponentMetadata.encapsulation:ViewEncapsulation', 'ComponentMetadata.moduleId:string', - 'ComponentMetadata.pipes:Array<Type|any[]>', 'ComponentMetadata.styleUrls:string[]', - 'ComponentMetadata.styles:string[]', 'ComponentMetadata.template:string', - 'ComponentMetadata.templateUrl:string', 'ComponentMetadata.viewBindings:any[]', - 'ComponentMetadata.viewProviders:any[]', 'ComponentRef', 'ComponentRef.componentType:Type', - 'ComponentRef.dispose():void', 'ComponentRef.hostComponent:any', - 'ComponentRef.hostView:HostViewRef', 'ComponentRef.injector:Injector', - 'ComponentRef.instance:any', 'ComponentRef.location:ElementRef', 'ConcreteType', - 'ContentChildFactory', 'ContentChildMetadata', - 'ContentChildMetadata.constructor(_selector:Type|string)', 'ContentChildrenFactory', + 'ComponentMetadata.encapsulation:ViewEncapsulation', + 'ComponentMetadata.moduleId:string', + 'ComponentMetadata.pipes:Array<Type|any[]>', + 'ComponentMetadata.styleUrls:string[]', + 'ComponentMetadata.styles:string[]', + 'ComponentMetadata.template:string', + 'ComponentMetadata.templateUrl:string', + 'ComponentMetadata.viewBindings:any[]', + 'ComponentMetadata.viewProviders:any[]', + 'ComponentRef', + 'ComponentRef.componentType:Type', + 'ComponentRef.dispose():void', + 'ComponentRef.hostComponent:any', + 'ComponentRef.hostView:HostViewRef', + 'ComponentRef.injector:Injector', + 'ComponentRef.instance:any', + 'ComponentRef.location:ElementRef', + 'ConcreteType', + 'ContentChildFactory', + 'ContentChildMetadata', + 'ContentChildMetadata.constructor(_selector:Type|string)', + 'ContentChildrenFactory', 'ContentChildrenMetadata', 'ContentChildrenMetadata.constructor(_selector:Type|string, {descendants=false}:{descendants?:boolean})', - 'CyclicDependencyError', 'CyclicDependencyError.constructor(injector:Injector, key:Key)', - 'DebugNode', 'DebugNode.componentInstance:any', - 'DebugNode.constructor(nativeNode:any, parent:DebugNode)', 'DebugNode.getLocal(name:string):any', - 'DebugNode.inject(token:any):any', 'DebugNode.injector:Injector', - 'DebugNode.listeners:EventListener[]', 'DebugNode.locals:Map<string, any>', - 'DebugNode.nativeNode:any', 'DebugNode.parent:DebugElement', 'DebugNode.providerTokens:any[]', - 'DebugNode.setDebugInfo(info:RenderDebugInfo):any', 'DebugElement', - 'DebugElement.children:DebugElement[]', 'DebugElement.nativeElement:any', - 'DebugElement.addChild(child:DebugNode):any', 'DebugElement.attributes:Map<string, any>', - 'DebugElement.childNodes:DebugNode[]', 'DebugElement.constructor(nativeNode:any, parent:any)', + 'CyclicDependencyError', + 'CyclicDependencyError.constructor(injector:Injector, key:Key)', + 'DebugNode', + 'DebugNode.componentInstance:any', + 'DebugNode.constructor(nativeNode:any, parent:DebugNode)', + 'DebugNode.getLocal(name:string):any', + 'DebugNode.inject(token:any):any', + 'DebugNode.injector:Injector', + 'DebugNode.listeners:EventListener[]', + 'DebugNode.locals:Map<string, any>', + 'DebugNode.nativeNode:any', + 'DebugNode.parent:DebugElement', + 'DebugNode.providerTokens:any[]', + 'DebugNode.setDebugInfo(info:RenderDebugInfo):any', + 'DebugElement', + 'DebugElement.children:DebugElement[]', + 'DebugElement.nativeElement:any', + 'DebugElement.addChild(child:DebugNode):any', + 'DebugElement.attributes:Map<string, any>', + 'DebugElement.childNodes:DebugNode[]', + 'DebugElement.constructor(nativeNode:any, parent:any)', 'DebugElement.insertChildrenAfter(child:DebugNode, newChildren:DebugNode[]):any', - 'DebugElement.name:string', 'DebugElement.properties:Map<string, any>', + 'DebugElement.name:string', + 'DebugElement.properties:Map<string, any>', 'DebugElement.query(predicate:Predicate<DebugElement>):DebugElement', 'DebugElement.queryAll(predicate:Predicate<DebugElement>):DebugElement[]', 'DebugElement.queryAllNodes(predicate:Predicate<DebugNode>):DebugNode[]', 'DebugElement.removeChild(child:DebugNode):any', 'DebugElement.triggerEventHandler(eventName:string, eventObj:Event):any', - 'asNativeElements(debugEls:DebugElement[]):any', 'Dependency', + 'asNativeElements(debugEls:DebugElement[]):any', + 'Dependency', 'Dependency.constructor(key:Key, optional:boolean, lowerBoundVisibility:any, upperBoundVisibility:any, properties:any[])', - 'Dependency.fromKey(key:Key):Dependency', 'DependencyMetadata', 'DependencyMetadata.token:any', - 'DirectiveDecorator', 'DirectiveFactory', 'DirectiveMetadata', 'DirectiveMetadata.bindings:any[]', + 'Dependency.fromKey(key:Key):Dependency', + 'DependencyMetadata', + 'DependencyMetadata.token:any', + 'DirectiveDecorator', + 'DirectiveFactory', + 'DirectiveMetadata', + 'DirectiveMetadata.bindings:any[]', 'DirectiveMetadata.constructor({selector,inputs,outputs,properties,events,host,bindings,providers,exportAs,queries}:{selector?:string, inputs?:string[], outputs?:string[], properties?:string[], events?:string[], host?:{[key:string]:string}, providers?:any[], bindings?:any[], exportAs?:string, queries?:{[key:string]:any}})', - 'DirectiveMetadata.events:string[]', 'DirectiveMetadata.exportAs:string', - 'DirectiveMetadata.host:{[key:string]:string}', 'DirectiveMetadata.inputs:string[]', - 'DirectiveMetadata.outputs:string[]', 'DirectiveMetadata.properties:string[]', - 'DirectiveMetadata.providers:any[]', 'DirectiveMetadata.queries:{[key:string]:any}', - 'DirectiveMetadata.selector:string', 'DirectiveResolver', + 'DirectiveMetadata.events:string[]', + 'DirectiveMetadata.exportAs:string', + 'DirectiveMetadata.host:{[key:string]:string}', + 'DirectiveMetadata.inputs:string[]', + 'DirectiveMetadata.outputs:string[]', + 'DirectiveMetadata.properties:string[]', + 'DirectiveMetadata.providers:any[]', + 'DirectiveMetadata.queries:{[key:string]:any}', + 'DirectiveMetadata.selector:string', + 'DirectiveResolver', 'DirectiveResolver.constructor(_reflector:ReflectorReader)', - 'DirectiveResolver.resolve(type:Type):DirectiveMetadata', 'DoCheck', 'DoCheck.ngDoCheck():any', + 'DirectiveResolver.resolve(type:Type):DirectiveMetadata', + 'DoCheck', + 'DoCheck.ngDoCheck():any', 'DynamicComponentLoader', 'DynamicComponentLoader.loadAsRoot(type:Type, overrideSelector:string, injector:Injector, onDispose:() => void, projectableNodes:any[][]):Promise<ComponentRef>', 'DynamicComponentLoader.loadIntoLocation(type:Type, hostLocation:ElementRef, anchorName:string, providers:ResolvedProvider[], projectableNodes:any[][]):Promise<ComponentRef>', 'DynamicComponentLoader.loadNextToLocation(type:Type, location:ElementRef, providers:ResolvedProvider[], projectableNodes:any[][]):Promise<ComponentRef>', - 'ElementRef', 'ElementRef.nativeElement:any', 'EmbeddedViewRef', - 'EmbeddedViewRef.hasLocal(variableName:string):boolean', 'EmbeddedViewRef.rootNodes:any[]', + 'ElementRef', + 'ElementRef.nativeElement:any', + 'EmbeddedViewRef', + 'EmbeddedViewRef.hasLocal(variableName:string):boolean', + 'EmbeddedViewRef.rootNodes:any[]', 'EmbeddedViewRef.setLocal(variableName:string, value:any):void', - 'EventEmitter.constructor(isAsync:boolean)', 'EventEmitter.emit(value:T):any', + 'EventEmitter.constructor(isAsync:boolean)', + 'EventEmitter.emit(value:T):any', 'EventEmitter.next(value:any):any', - 'EventEmitter.subscribe(generatorOrNext:any, error:any, complete:any):any', 'EventEmitter<T>', - 'ExceptionHandler', 'ExceptionHandler.call(exception:any, stackTrace:any, reason:string):void', + 'EventEmitter.subscribe(generatorOrNext:any, error:any, complete:any):any', + 'EventEmitter<T>', + 'ExceptionHandler', + 'ExceptionHandler.call(exception:any, stackTrace:any, reason:string):void', 'ExceptionHandler.constructor(_logger:any, _rethrowException:boolean)', 'ExceptionHandler.exceptionToString(exception:any, stackTrace:any, reason:string):string', 'ExpressionChangedAfterItHasBeenCheckedException', 'ExpressionChangedAfterItHasBeenCheckedException.constructor(exp:string, oldValue:any, currValue:any, context:any)', - 'ForwardRefFn', 'GetTestability', 'GetTestability.addToWindow(registry:TestabilityRegistry):void', + 'ForwardRefFn', + 'GetTestability', + 'GetTestability.addToWindow(registry:TestabilityRegistry):void', 'GetTestability.findTestabilityInTree(registry:TestabilityRegistry, elem:any, findInAncestors:boolean):Testability', - 'HostBindingFactory', 'HostBindingMetadata', - 'HostBindingMetadata.constructor(hostPropertyName:string)', 'HostFactory', 'HostListenerFactory', - 'HostListenerMetadata', 'HostListenerMetadata.constructor(eventName:string, args:string[])', - 'HostMetadata', 'HostMetadata.toString():string', 'HostViewFactoryRef', 'HostViewRef', - 'HostViewRef.rootNodes:any[]', 'InjectFactory', 'InjectMetadata', - 'InjectMetadata.constructor(token:any)', 'InjectMetadata.toString():string', 'InjectableFactory', - 'InjectableMetadata', 'InjectableMetadata.constructor()', 'Injector', + 'HostBindingFactory', + 'HostBindingMetadata', + 'HostBindingMetadata.constructor(hostPropertyName:string)', + 'HostFactory', + 'HostListenerFactory', + 'HostListenerMetadata', + 'HostListenerMetadata.constructor(eventName:string, args:string[])', + 'HostMetadata', + 'HostMetadata.toString():string', + 'HostViewFactoryRef', + 'HostViewRef', + 'HostViewRef.rootNodes:any[]', + 'InjectFactory', + 'InjectMetadata', + 'InjectMetadata.constructor(token:any)', + 'InjectMetadata.toString():string', + 'InjectableFactory', + 'InjectableMetadata', + 'InjectableMetadata.constructor()', + 'Injector', 'Injector.constructor(_proto:any, _parent:Injector, _isHostBoundary:boolean, _depProvider:any, _debugContext:Function)', 'Injector.createChildFromResolved(providers:ResolvedProvider[]):Injector', - 'Injector.debugContext():any', 'Injector.displayName:string', + 'Injector.debugContext():any', + 'Injector.displayName:string', 'Injector.fromResolvedBindings(providers:ResolvedProvider[]):Injector', 'Injector.fromResolvedProviders(providers:ResolvedProvider[]):Injector', - 'Injector.get(token:any):any', 'Injector.getAt(index:number):any', - 'Injector.getOptional(token:any):any', 'Injector.hostBoundary:any', - 'Injector.instantiateResolved(provider:ResolvedProvider):any', 'Injector.internalStrategy:any', + 'Injector.get(token:any):any', + 'Injector.getAt(index:number):any', + 'Injector.getOptional(token:any):any', + 'Injector.hostBoundary:any', + 'Injector.instantiateResolved(provider:ResolvedProvider):any', + 'Injector.internalStrategy:any', 'Injector.parent:Injector', 'Injector.resolve(providers:Array<Type|Provider|any[]>):ResolvedProvider[]', 'Injector.resolveAndCreate(providers:Array<Type|Provider|any[]>):Injector', 'Injector.resolveAndCreateChild(providers:Array<Type|Provider|any[]>):Injector', - 'Injector.resolveAndInstantiate(provider:Type|Provider):any', 'Injector.toString():string', - 'InputFactory', 'InputMetadata', 'InputMetadata.constructor(bindingPropertyName:string)', - 'InstantiationError', 'InstantiationError.addKey(injector:Injector, key:Key):void', + 'Injector.resolveAndInstantiate(provider:Type|Provider):any', + 'Injector.toString():string', + 'InputFactory', + 'InputMetadata', + 'InputMetadata.constructor(bindingPropertyName:string)', + 'InstantiationError', + 'InstantiationError.addKey(injector:Injector, key:Key):void', 'InstantiationError.causeKey:Key', 'InstantiationError.constructor(injector:Injector, originalException:any, originalStack:any, key:Key)', - 'InstantiationError.context:any', 'InstantiationError.injectors:Injector[]', - 'InstantiationError.keys:Key[]', 'InstantiationError.wrapperMessage:string', - 'InvalidProviderError', 'InvalidProviderError.constructor(provider:any)', 'IterableDiffer', - 'IterableDiffer.diff(object:any):any', 'IterableDiffer.onDestroy():any', 'IterableDifferFactory', + 'InstantiationError.context:any', + 'InstantiationError.injectors:Injector[]', + 'InstantiationError.keys:Key[]', + 'InstantiationError.wrapperMessage:string', + 'InvalidProviderError', + 'InvalidProviderError.constructor(provider:any)', + 'IterableDiffer', + 'IterableDiffer.diff(object:any):any', + 'IterableDiffer.onDestroy():any', + 'IterableDifferFactory', 'IterableDifferFactory.create(cdRef:ChangeDetectorRef, trackByFn:TrackByFn):IterableDiffer', - 'IterableDifferFactory.supports(objects:any):boolean', 'IterableDiffers', + 'IterableDifferFactory.supports(objects:any):boolean', + 'IterableDiffers', 'IterableDiffers.constructor(factories:IterableDifferFactory[])', 'IterableDiffers.create(factories:IterableDifferFactory[], parent:IterableDiffers):IterableDiffers', 'IterableDiffers.extend(factories:IterableDifferFactory[]):Provider', - 'IterableDiffers.find(iterable:any):IterableDifferFactory', 'Key', - 'Key.constructor(token:Object, id:number)', 'Key.displayName:string', 'Key.get(token:Object):Key', - 'Key.numberOfKeys:number', 'KeyValueChangeRecord', 'KeyValueChangeRecord.constructor(key:any)', - 'KeyValueChangeRecord.currentValue:any', 'KeyValueChangeRecord.previousValue:any', - 'KeyValueChangeRecord.toString():string', 'KeyValueDiffer', 'KeyValueDiffer.diff(object:any):any', - 'KeyValueDiffer.onDestroy():any', 'KeyValueDifferFactory', + 'IterableDiffers.find(iterable:any):IterableDifferFactory', + 'Key', + 'Key.constructor(token:Object, id:number)', + 'Key.displayName:string', + 'Key.get(token:Object):Key', + 'Key.numberOfKeys:number', + 'KeyValueChangeRecord', + 'KeyValueChangeRecord.constructor(key:any)', + 'KeyValueChangeRecord.currentValue:any', + 'KeyValueChangeRecord.previousValue:any', + 'KeyValueChangeRecord.toString():string', + 'KeyValueDiffer', + 'KeyValueDiffer.diff(object:any):any', + 'KeyValueDiffer.onDestroy():any', + 'KeyValueDifferFactory', 'KeyValueDifferFactory.create(cdRef:ChangeDetectorRef):KeyValueDiffer', - 'KeyValueDifferFactory.supports(objects:any):boolean', 'KeyValueDiffers', + 'KeyValueDifferFactory.supports(objects:any):boolean', + 'KeyValueDiffers', 'KeyValueDiffers.constructor(factories:KeyValueDifferFactory[])', 'KeyValueDiffers.create(factories:KeyValueDifferFactory[], parent:KeyValueDiffers):KeyValueDiffers', 'KeyValueDiffers.extend(factories:KeyValueDifferFactory[]):Provider', - 'KeyValueDiffers.find(kv:Object):KeyValueDifferFactory', 'NgZone', - 'NgZone.constructor({enableLongStackTrace=false}:any)', 'NgZone.assertInAngularZone():void', - 'NgZone.assertNotInAngularZone():void', 'NgZone.isInAngularZone():boolean', - 'NgZone.hasPendingMacrotasks:boolean', 'NgZone.hasPendingMicrotasks:boolean', - 'NgZone.onError:EventEmitter<any>', 'NgZone.onStable:EventEmitter<any>', - 'NgZone.onMicrotaskEmpty:EventEmitter<any>', 'NgZone.onUnstable:EventEmitter<any>', - 'NgZone.run(fn:() => any):any', 'NgZone.runOutsideAngular(fn:() => any):any', 'NgZoneError', - 'NgZoneError.constructor(error:any, stackTrace:any)', 'NoAnnotationError', - 'NoAnnotationError.constructor(typeOrFunc:any, params:any[][])', 'NoProviderError', - 'NoProviderError.constructor(injector:Injector, key:Key)', 'OnChanges', - 'OnChanges.ngOnChanges(changes:{[key:string]:SimpleChange}):any', 'OnDestroy', - 'OnDestroy.ngOnDestroy():any', 'OnInit', 'OnInit.ngOnInit():any', 'OpaqueToken', - 'OpaqueToken.constructor(_desc:string)', 'OpaqueToken.toString():string', 'OptionalFactory', - 'OptionalMetadata', 'OptionalMetadata.toString():string', 'OutOfBoundsError', - 'OutOfBoundsError.constructor(index:any)', 'OutputFactory', 'OutputMetadata', - 'OutputMetadata.constructor(bindingPropertyName:string)', 'PipeFactory', 'PipeMetadata', - 'PipeMetadata.constructor({name,pure}:{name:string, pure?:boolean})', 'PipeMetadata.name:string', - 'PipeMetadata.pure:boolean', 'PipeTransform', - 'PipeTransform.transform(value:any, args:any[]):any', 'PlatformRef', + 'KeyValueDiffers.find(kv:Object):KeyValueDifferFactory', + 'NgZone', + 'NgZone.constructor({enableLongStackTrace=false}:any)', + 'NgZone.assertInAngularZone():void', + 'NgZone.assertNotInAngularZone():void', + 'NgZone.isInAngularZone():boolean', + 'NgZone.hasPendingMacrotasks:boolean', + 'NgZone.hasPendingMicrotasks:boolean', + 'NgZone.onError:EventEmitter<any>', + 'NgZone.onStable:EventEmitter<any>', + 'NgZone.onMicrotaskEmpty:EventEmitter<any>', + 'NgZone.onUnstable:EventEmitter<any>', + 'NgZone.run(fn:() => any):any', + 'NgZone.runOutsideAngular(fn:() => any):any', + 'NgZoneError', + 'NgZoneError.constructor(error:any, stackTrace:any)', + 'NoAnnotationError', + 'NoAnnotationError.constructor(typeOrFunc:any, params:any[][])', + 'NoProviderError', + 'NoProviderError.constructor(injector:Injector, key:Key)', + 'OnChanges', + 'OnChanges.ngOnChanges(changes:{[key:string]:SimpleChange}):any', + 'OnDestroy', + 'OnDestroy.ngOnDestroy():any', + 'OnInit', + 'OnInit.ngOnInit():any', + 'OpaqueToken', + 'OpaqueToken.constructor(_desc:string)', + 'OpaqueToken.toString():string', + 'OptionalFactory', + 'OptionalMetadata', + 'OptionalMetadata.toString():string', + 'OutOfBoundsError', + 'OutOfBoundsError.constructor(index:any)', + 'OutputFactory', + 'OutputMetadata', + 'OutputMetadata.constructor(bindingPropertyName:string)', + 'PipeFactory', + 'PipeMetadata', + 'PipeMetadata.constructor({name,pure}:{name:string, pure?:boolean})', + 'PipeMetadata.name:string', + 'PipeMetadata.pure:boolean', + 'PipeTransform', + 'PipeTransform.transform(value:any, args:any[]):any', + 'PlatformRef', 'PlatformRef.application(providers:Array<Type|Provider|any[]>):ApplicationRef', - 'PlatformRef.asyncApplication(bindingFn:(zone: NgZone) => Promise<Array<Type|Provider|any[]>>, providers:Array<Type|Provider|any[]>):Promise<ApplicationRef>', - 'PlatformRef.dispose():void', 'PlatformRef.injector:Injector', - 'PlatformRef.registerDisposeListener(dispose:() => void):void', 'Provider', + 'PlatformRef.asyncApplication(bindingFn:(zone: NgZone) => Promise<Array<Type | Provider | any[]>>, providers:Array<Type|Provider|any[]>):Promise<ApplicationRef>', + 'PlatformRef.dispose():void', + 'PlatformRef.injector:Injector', + 'PlatformRef.registerDisposeListener(dispose:() => void):void', + 'Provider', 'Provider.constructor(token:any, {useClass,useValue,useExisting,useFactory,deps,multi}:{useClass?:Type, useValue?:any, useExisting?:any, useFactory?:Function, deps?:Object[], multi?:boolean})', - 'Provider.dependencies:Object[]', 'Provider.multi:boolean', 'Provider.token:any', - 'Provider.useClass:Type', 'Provider.useExisting:any', 'Provider.useFactory:Function', - 'Provider.useValue:any', 'ProviderBuilder', 'ProviderBuilder.constructor(token:any)', - 'ProviderBuilder.toAlias(aliasToken:any):Provider', 'ProviderBuilder.toClass(type:Type):Provider', + 'Provider.dependencies:Object[]', + 'Provider.multi:boolean', + 'Provider.token:any', + 'Provider.useClass:Type', + 'Provider.useExisting:any', + 'Provider.useFactory:Function', + 'Provider.useValue:any', + 'ProviderBuilder', + 'ProviderBuilder.constructor(token:any)', + 'ProviderBuilder.toAlias(aliasToken:any):Provider', + 'ProviderBuilder.toClass(type:Type):Provider', 'ProviderBuilder.toFactory(factory:Function, dependencies:any[]):Provider', - 'ProviderBuilder.toValue(value:any):Provider', 'QueryFactory', - 'QueryList.changes:Observable<any>', 'QueryList.filter(fn:(item: T) => boolean):T[]', - 'QueryList.first:T', 'QueryList.forEach(fn:(item: T) => void):void', 'QueryList.last:T', - 'QueryList.length:number', 'QueryList.map(fn:(item: T) => U):U[]', - 'QueryList.notifyOnChanges():void', 'QueryList.reduce(fn:(acc: U, item: T) => U, init:U):U', - 'QueryList.reset(res:T[]):void', 'QueryList.toArray():T[]', 'QueryList.toString():string', - 'QueryList<T>', 'QueryMetadata', + 'ProviderBuilder.toValue(value:any):Provider', + 'QueryFactory', + 'QueryList.changes:Observable<any>', + 'QueryList.filter(fn:(item: T) => boolean):T[]', + 'QueryList.first:T', + 'QueryList.forEach(fn:(item: T) => void):void', + 'QueryList.last:T', + 'QueryList.length:number', + 'QueryList.map(fn:(item: T) => U):U[]', + 'QueryList.notifyOnChanges():void', + 'QueryList.reduce(fn:(acc: U, item: T) => U, init:U):U', + 'QueryList.reset(res:T[]):void', + 'QueryList.toArray():T[]', + 'QueryList.toString():string', + 'QueryList<T>', + 'QueryMetadata', 'QueryMetadata.constructor(_selector:Type|string, {descendants=false,first=false}:{descendants?:boolean, first?:boolean})', - 'QueryMetadata.descendants:boolean', 'QueryMetadata.first:boolean', - 'QueryMetadata.isVarBindingQuery:boolean', 'QueryMetadata.isViewQuery:boolean', - 'QueryMetadata.selector:any', 'QueryMetadata.toString():string', - 'QueryMetadata.varBindings:string[]', 'ReflectionInfo', + 'QueryMetadata.descendants:boolean', + 'QueryMetadata.first:boolean', + 'QueryMetadata.isVarBindingQuery:boolean', + 'QueryMetadata.isViewQuery:boolean', + 'QueryMetadata.selector:any', + 'QueryMetadata.toString():string', + 'QueryMetadata.varBindings:string[]', + 'ReflectionInfo', 'ReflectionInfo.constructor(annotations:any[], parameters:any[][], factory:Function, interfaces:any[], propMetadata:{[key:string]:any[]})', - 'Reflector', 'Reflector.annotations(typeOrFunc:any):any[]', + 'Reflector', + 'Reflector.annotations(typeOrFunc:any):any[]', 'Reflector.constructor(reflectionCapabilities:PlatformReflectionCapabilities)', - 'Reflector.factory(type:Type):Function', 'Reflector.getter(name:string):GetterFn', - 'Reflector.importUri(type:Type):string', 'Reflector.interfaces(type:Type):any[]', - 'Reflector.isReflectionEnabled():boolean', 'Reflector.listUnusedKeys():any[]', - 'Reflector.method(name:string):MethodFn', 'Reflector.parameters(typeOrFunc:any):any[][]', + 'Reflector.factory(type:Type):Function', + 'Reflector.getter(name:string):GetterFn', + 'Reflector.importUri(type:Type):string', + 'Reflector.interfaces(type:Type):any[]', + 'Reflector.isReflectionEnabled():boolean', + 'Reflector.listUnusedKeys():any[]', + 'Reflector.method(name:string):MethodFn', + 'Reflector.parameters(typeOrFunc:any):any[][]', 'Reflector.propMetadata(typeOrFunc:any):{[key:string]:any[]}', 'Reflector.reflectionCapabilities:PlatformReflectionCapabilities', 'Reflector.registerFunction(func:Function, funcInfo:ReflectionInfo):void', @@ -218,9 +388,12 @@ const CORE = [ 'Reflector.registerMethods(methods:{[key:string]:MethodFn}):void', 'Reflector.registerSetters(setters:{[key:string]:SetterFn}):void', 'Reflector.registerType(type:Type, typeInfo:ReflectionInfo):void', - 'Reflector.setter(name:string):SetterFn', 'Reflector.trackUsage():void', 'RenderComponentType', + 'Reflector.setter(name:string):SetterFn', + 'Reflector.trackUsage():void', + 'RenderComponentType', 'RenderComponentType.constructor(id:string, encapsulation:ViewEncapsulation, styles:Array<string|any[]>)', - 'Renderer', 'Renderer.attachViewAfter(node:any, viewRootNodes:any[]):void', + 'Renderer', + 'Renderer.attachViewAfter(node:any, viewRootNodes:any[]):void', 'Renderer.createElement(parentElement:any, name:string):any', 'Renderer.createTemplateAnchor(parentElement:any):any', 'Renderer.createText(parentElement:any, value:string):any', @@ -239,262 +412,454 @@ const CORE = [ 'Renderer.setElementProperty(renderElement:any, propertyName:string, propertyValue:any):void', 'Renderer.setElementStyle(renderElement:any, styleName:string, styleValue:string):any', 'Renderer.setText(renderNode:any, text:string):any', - 'Renderer.setElementDebugInfo(renderElement:any, info:RenderDebugInfo):any', 'ResolvedBinding', - 'ResolvedFactory', 'ResolvedFactory.constructor(factory:Function, dependencies:Dependency[])', - 'ResolvedProvider', 'ResolvedProvider.key:Key', 'ResolvedProvider.multiProvider:boolean', - 'ResolvedProvider.resolvedFactories:ResolvedFactory[]', 'RootRenderer', - 'RootRenderer.renderComponent(componentType:RenderComponentType):Renderer', 'SelfFactory', - 'SelfMetadata', 'SelfMetadata.toString():string', 'SimpleChange', + 'Renderer.setElementDebugInfo(renderElement:any, info:RenderDebugInfo):any', + 'ResolvedBinding', + 'ResolvedFactory', + 'ResolvedFactory.constructor(factory:Function, dependencies:Dependency[])', + 'ResolvedProvider', + 'ResolvedProvider.key:Key', + 'ResolvedProvider.multiProvider:boolean', + 'ResolvedProvider.resolvedFactories:ResolvedFactory[]', + 'RootRenderer', + 'RootRenderer.renderComponent(componentType:RenderComponentType):Renderer', + 'SelfFactory', + 'SelfMetadata', + 'SelfMetadata.toString():string', + 'SimpleChange', 'SimpleChange.constructor(previousValue:any, currentValue:any)', - 'SimpleChange.isFirstChange():boolean', 'SkipSelfFactory', 'SkipSelfMetadata', - 'SkipSelfMetadata.toString():string', 'TemplateRef', 'TemplateRef.elementRef:ElementRef', - 'Testability', 'Testability.constructor(_ngZone:NgZone)', + 'SimpleChange.isFirstChange():boolean', + 'SkipSelfFactory', + 'SkipSelfMetadata', + 'SkipSelfMetadata.toString():string', + 'TemplateRef', + 'TemplateRef.elementRef:ElementRef', + 'Testability', + 'Testability.constructor(_ngZone:NgZone)', 'Testability.decreasePendingRequestCount():number', 'Testability.findBindings(using:any, provider:string, exactMatch:boolean):any[]', 'Testability.findProviders(using:any, provider:string, exactMatch:boolean):any[]', - 'Testability.getPendingRequestCount():number', 'Testability.increasePendingRequestCount():number', - 'Testability.isStable():boolean', 'Testability.whenStable(callback:Function):void', - 'TestabilityRegistry', 'TestabilityRegistry.constructor()', + 'Testability.getPendingRequestCount():number', + 'Testability.increasePendingRequestCount():number', + 'Testability.isStable():boolean', + 'Testability.whenStable(callback:Function):void', + 'TestabilityRegistry', + 'TestabilityRegistry.constructor()', 'TestabilityRegistry.findTestabilityInTree(elem:Node, findInAncestors:boolean):Testability', 'TestabilityRegistry.getAllTestabilities():Testability[]', 'TestabilityRegistry.getAllRootElements():any[]', 'TestabilityRegistry.getTestability(elem:any):Testability', - 'TestabilityRegistry.registerApplication(token:any, testability:Testability):any', 'TrackByFn', - 'TypeDecorator', 'TypeDecorator.Class(obj:ClassDefinition):ConcreteType', - 'TypeDecorator.annotations:any[]', 'ViewChildFactory', 'ViewChildMetadata', - 'ViewChildMetadata.constructor(_selector:Type|string)', 'ViewChildrenFactory', - 'ViewChildrenMetadata', 'ViewChildrenMetadata.constructor(_selector:Type|string)', - 'ViewContainerRef', 'ViewContainerRef.clear():void', + 'TestabilityRegistry.registerApplication(token:any, testability:Testability):any', + 'TrackByFn', + 'TypeDecorator', + 'TypeDecorator.Class(obj:ClassDefinition):ConcreteType', + 'TypeDecorator.annotations:any[]', + 'ViewChildFactory', + 'ViewChildMetadata', + 'ViewChildMetadata.constructor(_selector:Type|string)', + 'ViewChildrenFactory', + 'ViewChildrenMetadata', + 'ViewChildrenMetadata.constructor(_selector:Type|string)', + 'ViewContainerRef', + 'ViewContainerRef.clear():void', 'ViewContainerRef.createEmbeddedView(templateRef:TemplateRef, index:number):EmbeddedViewRef', 'ViewContainerRef.createHostView(hostViewFactoryRef:HostViewFactoryRef, index:number, dynamicallyCreatedProviders:ResolvedProvider[], projectableNodes:any[][]):HostViewRef', - 'ViewContainerRef.detach(index:number):EmbeddedViewRef', 'ViewContainerRef.element:ElementRef', - 'ViewContainerRef.get(index:number):ViewRef', 'ViewContainerRef.indexOf(viewRef:ViewRef):number', + 'ViewContainerRef.detach(index:number):EmbeddedViewRef', + 'ViewContainerRef.element:ElementRef', + 'ViewContainerRef.get(index:number):ViewRef', + 'ViewContainerRef.indexOf(viewRef:ViewRef):number', 'ViewContainerRef.insert(viewRef:EmbeddedViewRef, index:number):EmbeddedViewRef', - 'ViewContainerRef.length:number', 'ViewContainerRef.remove(index:number):void', 'ViewDecorator', + 'ViewContainerRef.length:number', + 'ViewContainerRef.remove(index:number):void', + 'ViewDecorator', 'ViewDecorator.View(obj:{templateUrl?:string, template?:string, directives?:Array<Type|any[]>, pipes?:Array<Type|any[]>, renderer?:string, styles?:string[], styleUrls?:string[]}):ViewDecorator', 'ViewEncapsulation', - 'ViewEncapsulation.Emulated', 'ViewEncapsulation.Native', 'ViewEncapsulation.None', 'ViewFactory', 'ViewMetadata', 'ViewMetadata.constructor({templateUrl,template,directives,pipes,encapsulation,styles,styleUrls}:{templateUrl?:string, template?:string, directives?:Array<Type|any[]>, pipes?:Array<Type|any[]>, encapsulation?:ViewEncapsulation, styles?:string[], styleUrls?:string[]})', - 'ViewMetadata.directives:Array<Type|any[]>', 'ViewMetadata.encapsulation:ViewEncapsulation', - 'ViewMetadata.pipes:Array<Type|any[]>', 'ViewMetadata.styleUrls:string[]', - 'ViewMetadata.styles:string[]', 'ViewMetadata.template:string', 'ViewMetadata.templateUrl:string', + 'ViewEncapsulation.Emulated', + 'ViewEncapsulation.Native', + 'ViewEncapsulation.None', + 'ViewFactory', + 'ViewMetadata', + 'ViewMetadata.constructor({templateUrl,template,directives,pipes,encapsulation,styles,styleUrls}:{templateUrl?:string, template?:string, directives?:Array<Type|any[]>, pipes?:Array<Type|any[]>, encapsulation?:ViewEncapsulation, styles?:string[], styleUrls?:string[]})', + 'ViewMetadata.directives:Array<Type|any[]>', + 'ViewMetadata.encapsulation:ViewEncapsulation', + 'ViewMetadata.pipes:Array<Type|any[]>', + 'ViewMetadata.styleUrls:string[]', + 'ViewMetadata.styles:string[]', + 'ViewMetadata.template:string', + 'ViewMetadata.templateUrl:string', 'ViewQueryMetadata', 'ViewQueryMetadata.constructor(_selector:Type|string, {descendants=false,first=false}:{descendants?:boolean, first?:boolean})', - 'ViewQueryMetadata.isViewQuery:any', 'ViewQueryMetadata.toString():string', 'ViewRef', - 'ViewRef.changeDetectorRef:ChangeDetectorRef', 'ViewRef.destroyed:boolean', 'ViewResolver', + 'ViewQueryMetadata.isViewQuery:any', + 'ViewQueryMetadata.toString():string', + 'ViewRef', + 'ViewRef.changeDetectorRef:ChangeDetectorRef', + 'ViewRef.destroyed:boolean', + 'ViewResolver', 'ViewResolver.constructor(_reflector:ReflectorReader)', - 'ViewResolver.resolve(component:Type):ViewMetadata', 'WrappedException', + 'ViewResolver.resolve(component:Type):ViewMetadata', + 'WrappedException', 'WrappedException.constructor(_wrapperMessage:string, _originalException:any, _originalStack:any, _context:any)', - 'WrappedException.context:any', 'WrappedException.message:string', - 'WrappedException.originalException:any', 'WrappedException.originalStack:any', - 'WrappedException.toString():string', 'WrappedException.wrapperMessage:string', - 'WrappedException.wrapperStack:any', 'WrappedValue', 'WrappedValue.constructor(wrapped:any)', - 'WrappedValue.wrap(value:any):WrappedValue', 'bind(token:any):ProviderBuilder', + 'WrappedException.context:any', + 'WrappedException.message:string', + 'WrappedException.originalException:any', + 'WrappedException.originalStack:any', + 'WrappedException.toString():string', + 'WrappedException.wrapperMessage:string', + 'WrappedException.wrapperStack:any', + 'WrappedValue', + 'WrappedValue.constructor(wrapped:any)', + 'WrappedValue.wrap(value:any):WrappedValue', + 'bind(token:any):ProviderBuilder', 'const APPLICATION_COMMON_PROVIDERS:Array<Type|Provider|any[]>', - 'const APP_COMPONENT:OpaqueToken', 'const APP_ID:OpaqueToken', - 'const APP_INITIALIZER:OpaqueToken', 'const PACKAGE_ROOT_URL:OpaqueToken', + 'const APP_COMPONENT:OpaqueToken', + 'const APP_ID:OpaqueToken', + 'const APP_INITIALIZER:OpaqueToken', + 'const PACKAGE_ROOT_URL:OpaqueToken', 'const PLATFORM_COMMON_PROVIDERS:Array<Type|Provider|any[]>', - 'const PLATFORM_DIRECTIVES:OpaqueToken', 'const PLATFORM_INITIALIZER:OpaqueToken', - 'const PLATFORM_PIPES:OpaqueToken', 'createNgZone():NgZone', 'enableProdMode():any', + 'const PLATFORM_DIRECTIVES:OpaqueToken', + 'const PLATFORM_INITIALIZER:OpaqueToken', + 'const PLATFORM_PIPES:OpaqueToken', + 'createNgZone():NgZone', + 'enableProdMode():any', 'forwardRef(forwardRefFn:ForwardRefFn):Type', 'platform(providers:Array<Type|Provider|any[]>):PlatformRef', 'provide(token:any, {useClass,useValue,useExisting,useFactory,deps,multi}:{useClass?:Type, useValue?:any, useExisting?:any, useFactory?:Function, deps?:Object[], multi?:boolean}):Provider', - 'resolveForwardRef(type:any):any', 'setTestabilityGetter(getter:GetTestability):void', - 'var Attribute:AttributeFactory', 'var Component:ComponentFactory', - 'var ContentChild:ContentChildFactory', 'var ContentChildren:ContentChildrenFactory', - 'var Directive:DirectiveFactory', 'var Host:HostFactory', 'var HostBinding:HostBindingFactory', - 'var HostListener:HostListenerFactory', 'var Inject:InjectFactory', - 'var Injectable:InjectableFactory', 'var Input:InputFactory', 'var Optional:OptionalFactory', - 'var Output:OutputFactory', 'var Pipe:PipeFactory', 'var Query:QueryFactory', - 'var Self:SelfFactory', 'var SkipSelf:SkipSelfFactory', 'var Type:any', - 'var ViewChild:ViewChildFactory', 'var ViewChildren:ViewChildrenFactory', - 'var ViewQuery:QueryFactory', 'var reflector:any' + 'resolveForwardRef(type:any):any', + 'setTestabilityGetter(getter:GetTestability):void', + 'var Attribute:AttributeFactory', + 'var Component:ComponentFactory', + 'var ContentChild:ContentChildFactory', + 'var ContentChildren:ContentChildrenFactory', + 'var Directive:DirectiveFactory', + 'var Host:HostFactory', + 'var HostBinding:HostBindingFactory', + 'var HostListener:HostListenerFactory', + 'var Inject:InjectFactory', + 'var Injectable:InjectableFactory', + 'var Input:InputFactory', + 'var Optional:OptionalFactory', + 'var Output:OutputFactory', + 'var Pipe:PipeFactory', + 'var Query:QueryFactory', + 'var Self:SelfFactory', + 'var SkipSelf:SkipSelfFactory', + 'var Type:any', + 'var ViewChild:ViewChildFactory', + 'var ViewChildren:ViewChildrenFactory', + 'var ViewQuery:QueryFactory', + 'var reflector:any' ]; const COMMON = [ 'AbstractControl', 'AbstractControl.constructor(validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', - 'AbstractControl.dirty:boolean', 'AbstractControl.errors:{[key:string]:any}', + 'AbstractControl.dirty:boolean', + 'AbstractControl.errors:{[key:string]:any}', 'AbstractControl.find(path:Array<string|number>|string):AbstractControl', 'AbstractControl.getError(errorCode:string, path:string[]):any', 'AbstractControl.hasError(errorCode:string, path:string[]):boolean', 'AbstractControl.markAsDirty({onlySelf}:{onlySelf?:boolean}):void', 'AbstractControl.markAsPending({onlySelf}:{onlySelf?:boolean}):void', - 'AbstractControl.markAsTouched():void', 'AbstractControl.pending:boolean', + 'AbstractControl.markAsTouched():void', + 'AbstractControl.pending:boolean', 'AbstractControl.pristine:boolean', 'AbstractControl.setErrors(errors:{[key:string]:any}, {emitEvent}:{emitEvent?:boolean}):void', 'AbstractControl.setParent(parent:ControlGroup|ControlArray):void', - 'AbstractControl.status:string', 'AbstractControl.statusChanges:Observable<any>', - 'AbstractControl.touched:boolean', 'AbstractControl.untouched:boolean', + 'AbstractControl.status:string', + 'AbstractControl.statusChanges:Observable<any>', + 'AbstractControl.touched:boolean', + 'AbstractControl.untouched:boolean', 'AbstractControl.updateValueAndValidity({onlySelf,emitEvent}:{onlySelf?:boolean, emitEvent?:boolean}):void', - 'AbstractControl.valid:boolean', 'AbstractControl.value:any', - 'AbstractControl.root:AbstractControl', 'AbstractControl.valueChanges:Observable<any>', - 'AbstractControlDirective', 'AbstractControlDirective.control:AbstractControl', - 'AbstractControlDirective.dirty:boolean', 'AbstractControlDirective.errors:{[key:string]:any}', - 'AbstractControlDirective.path:string[]', 'AbstractControlDirective.pristine:boolean', - 'AbstractControlDirective.touched:boolean', 'AbstractControlDirective.untouched:boolean', - 'AbstractControlDirective.valid:boolean', 'AbstractControlDirective.value:any', 'AsyncPipe', - 'AsyncPipe.constructor(_ref:ChangeDetectorRef)', 'AsyncPipe.ngOnDestroy():void', + 'AbstractControl.valid:boolean', + 'AbstractControl.value:any', + 'AbstractControl.root:AbstractControl', + 'AbstractControl.valueChanges:Observable<any>', + 'AbstractControlDirective', + 'AbstractControlDirective.control:AbstractControl', + 'AbstractControlDirective.dirty:boolean', + 'AbstractControlDirective.errors:{[key:string]:any}', + 'AbstractControlDirective.path:string[]', + 'AbstractControlDirective.pristine:boolean', + 'AbstractControlDirective.touched:boolean', + 'AbstractControlDirective.untouched:boolean', + 'AbstractControlDirective.valid:boolean', + 'AbstractControlDirective.value:any', + 'AsyncPipe', + 'AsyncPipe.constructor(_ref:ChangeDetectorRef)', + 'AsyncPipe.ngOnDestroy():void', 'AsyncPipe.transform(obj:Observable<any>|Promise<any>|EventEmitter<any>, args:any[]):any', 'CheckboxControlValueAccessor', 'CheckboxControlValueAccessor.constructor(_renderer:Renderer, _elementRef:ElementRef)', - 'CheckboxControlValueAccessor.onChange:any', 'CheckboxControlValueAccessor.onTouched:any', + 'CheckboxControlValueAccessor.onChange:any', + 'CheckboxControlValueAccessor.onTouched:any', 'CheckboxControlValueAccessor.registerOnChange(fn:(_: any) => {}):void', 'CheckboxControlValueAccessor.registerOnTouched(fn:() => {}):void', - 'CheckboxControlValueAccessor.writeValue(value:any):void', 'Control', + 'CheckboxControlValueAccessor.writeValue(value:any):void', + 'Control', 'Control.constructor(value:any, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', 'Control.registerOnChange(fn:Function):void', 'Control.updateValue(value:any, {onlySelf,emitEvent,emitModelToViewChange}:{onlySelf?:boolean, emitEvent?:boolean, emitModelToViewChange?:boolean}):void', - 'ControlArray', 'ControlArray.at(index:number):AbstractControl', + 'ControlArray', + 'ControlArray.at(index:number):AbstractControl', 'ControlArray.constructor(controls:AbstractControl[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', - 'ControlArray.insert(index:number, control:AbstractControl):void', 'ControlArray.length:number', - 'ControlArray.push(control:AbstractControl):void', 'ControlArray.removeAt(index:number):void', - 'ControlContainer', 'ControlContainer.formDirective:Form', 'ControlContainer.name:string', - 'ControlContainer.path:string[]', 'ControlGroup', + 'ControlArray.insert(index:number, control:AbstractControl):void', + 'ControlArray.length:number', + 'ControlArray.push(control:AbstractControl):void', + 'ControlArray.removeAt(index:number):void', + 'ControlContainer', + 'ControlContainer.formDirective:Form', + 'ControlContainer.name:string', + 'ControlContainer.path:string[]', + 'ControlGroup', 'ControlGroup.addControl(name:string, control:AbstractControl):void', 'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', 'ControlGroup.contains(controlName:string):boolean', - 'ControlGroup.exclude(controlName:string):void', 'ControlGroup.include(controlName:string):void', - 'ControlGroup.removeControl(name:string):void', 'ControlValueAccessor', + 'ControlGroup.exclude(controlName:string):void', + 'ControlGroup.include(controlName:string):void', + 'ControlGroup.removeControl(name:string):void', + 'ControlValueAccessor', 'ControlValueAccessor.registerOnChange(fn:any):void', 'ControlValueAccessor.registerOnTouched(fn:any):void', - 'ControlValueAccessor.writeValue(obj:any):void', 'CurrencyPipe', - 'CurrencyPipe.transform(value:any, args:any[]):string', 'DatePipe', - 'DatePipe.supports(obj:any):boolean', 'DatePipe.transform(value:any, args:any[]):string', - 'DecimalPipe', 'DecimalPipe.transform(value:any, args:any[]):string', 'DefaultValueAccessor', + 'ControlValueAccessor.writeValue(obj:any):void', + 'CurrencyPipe', + 'CurrencyPipe.transform(value:any, args:any[]):string', + 'DatePipe', + 'DatePipe.supports(obj:any):boolean', + 'DatePipe.transform(value:any, args:any[]):string', + 'DecimalPipe', + 'DecimalPipe.transform(value:any, args:any[]):string', + 'DefaultValueAccessor', 'DefaultValueAccessor.constructor(_renderer:Renderer, _elementRef:ElementRef)', - 'DefaultValueAccessor.onChange:any', 'DefaultValueAccessor.onTouched:any', + 'DefaultValueAccessor.onChange:any', + 'DefaultValueAccessor.onTouched:any', 'DefaultValueAccessor.registerOnChange(fn:(_: any) => void):void', 'DefaultValueAccessor.registerOnTouched(fn:() => void):void', - 'DefaultValueAccessor.writeValue(value:any):void', 'Form', 'Form.addControl(dir:NgControl):void', - 'Form.addControlGroup(dir:NgControlGroup):void', 'Form.getControl(dir:NgControl):Control', - 'Form.getControlGroup(dir:NgControlGroup):ControlGroup', 'Form.removeControl(dir:NgControl):void', + 'DefaultValueAccessor.writeValue(value:any):void', + 'Form', + 'Form.addControl(dir:NgControl):void', + 'Form.addControlGroup(dir:NgControlGroup):void', + 'Form.getControl(dir:NgControl):Control', + 'Form.getControlGroup(dir:NgControlGroup):ControlGroup', + 'Form.removeControl(dir:NgControl):void', 'Form.removeControlGroup(dir:NgControlGroup):void', - 'Form.updateModel(dir:NgControl, value:any):void', 'FormBuilder', + 'Form.updateModel(dir:NgControl, value:any):void', + 'FormBuilder', 'FormBuilder.array(controlsConfig:any[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn):ControlArray', 'FormBuilder.control(value:Object, validator:ValidatorFn, asyncValidator:AsyncValidatorFn):Control', 'FormBuilder.group(controlsConfig:{[key:string]:any}, extra:{[key:string]:any}):ControlGroup', - 'I18nPluralPipe', 'I18nPluralPipe.transform(value:number, args:any[]):string', 'I18nSelectPipe', - 'I18nSelectPipe.transform(value:string, args:any[]):string', 'JsonPipe', - 'JsonPipe.transform(value:any, args:any[]):string', 'LowerCasePipe', - 'LowerCasePipe.transform(value:string, args:any[]):string', 'MaxLengthValidator', + 'I18nPluralPipe', + 'I18nPluralPipe.transform(value:number, args:any[]):string', + 'I18nSelectPipe', + 'I18nSelectPipe.transform(value:string, args:any[]):string', + 'JsonPipe', + 'JsonPipe.transform(value:any, args:any[]):string', + 'LowerCasePipe', + 'LowerCasePipe.transform(value:string, args:any[]):string', + 'MaxLengthValidator', 'MaxLengthValidator.constructor(maxLength:string)', - 'MaxLengthValidator.validate(c:AbstractControl):{[key:string]:any}', 'MinLengthValidator', + 'MaxLengthValidator.validate(c:AbstractControl):{[key:string]:any}', + 'MinLengthValidator', 'MinLengthValidator.constructor(minLength:string)', - 'MinLengthValidator.validate(c:AbstractControl):{[key:string]:any}', 'NgClass', + 'MinLengthValidator.validate(c:AbstractControl):{[key:string]:any}', + 'NgClass', 'NgClass.constructor(_iterableDiffers:IterableDiffers, _keyValueDiffers:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)', - 'NgClass.initialClasses=(v:string)', 'NgClass.ngDoCheck():void', 'NgClass.ngOnDestroy():void', - 'NgClass.rawClass=(v:string|string[]|Set<string>|{[key:string]:any})', 'NgControl', - 'NgControl.asyncValidator:AsyncValidatorFn', 'NgControl.name:string', - 'NgControl.validator:ValidatorFn', 'NgControl.valueAccessor:ControlValueAccessor', - 'NgControl.viewToModelUpdate(newValue:any):void', 'NgControlGroup', + 'NgClass.initialClasses=(v:string)', + 'NgClass.ngDoCheck():void', + 'NgClass.ngOnDestroy():void', + 'NgClass.rawClass=(v:string|string[]|Set<string>|{[key:string]:any})', + 'NgControl', + 'NgControl.asyncValidator:AsyncValidatorFn', + 'NgControl.name:string', + 'NgControl.validator:ValidatorFn', + 'NgControl.valueAccessor:ControlValueAccessor', + 'NgControl.viewToModelUpdate(newValue:any):void', + 'NgControlGroup', 'NgControlGroup.asyncValidator:AsyncValidatorFn', 'NgControlGroup.constructor(parent:ControlContainer, _validators:any[], _asyncValidators:any[])', - 'NgControlGroup.control:ControlGroup', 'NgControlGroup.formDirective:Form', - 'NgControlGroup.ngOnDestroy():void', 'NgControlGroup.ngOnInit():void', - 'NgControlGroup.path:string[]', 'NgControlGroup.validator:ValidatorFn', 'NgControlName', + 'NgControlGroup.control:ControlGroup', + 'NgControlGroup.formDirective:Form', + 'NgControlGroup.ngOnDestroy():void', + 'NgControlGroup.ngOnInit():void', + 'NgControlGroup.path:string[]', + 'NgControlGroup.validator:ValidatorFn', + 'NgControlName', 'NgControlName.asyncValidator:AsyncValidatorFn', 'NgControlName.constructor(_parent:ControlContainer, _validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', - 'NgControlName.control:Control', 'NgControlName.formDirective:any', 'NgControlName.model:any', + 'NgControlName.control:Control', + 'NgControlName.formDirective:any', + 'NgControlName.model:any', 'NgControlName.ngOnChanges(changes:{[key:string]:SimpleChange}):any', - 'NgControlName.ngOnDestroy():void', 'NgControlName.path:string[]', 'NgControlName.update:any', - 'NgControlName.validator:ValidatorFn', 'NgControlName.viewModel:any', - 'NgControlName.viewToModelUpdate(newValue:any):void', 'NgControlStatus', - 'NgControlStatus.constructor(cd:NgControl)', 'NgControlStatus.ngClassDirty:boolean', - 'NgControlStatus.ngClassInvalid:boolean', 'NgControlStatus.ngClassPristine:boolean', - 'NgControlStatus.ngClassTouched:boolean', 'NgControlStatus.ngClassUntouched:boolean', - 'NgControlStatus.ngClassValid:boolean', 'NgFor', + 'NgControlName.ngOnDestroy():void', + 'NgControlName.path:string[]', + 'NgControlName.update:any', + 'NgControlName.validator:ValidatorFn', + 'NgControlName.viewModel:any', + 'NgControlName.viewToModelUpdate(newValue:any):void', + 'NgControlStatus', + 'NgControlStatus.constructor(cd:NgControl)', + 'NgControlStatus.ngClassDirty:boolean', + 'NgControlStatus.ngClassInvalid:boolean', + 'NgControlStatus.ngClassPristine:boolean', + 'NgControlStatus.ngClassTouched:boolean', + 'NgControlStatus.ngClassUntouched:boolean', + 'NgControlStatus.ngClassValid:boolean', + 'NgFor', 'NgFor.constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef, _iterableDiffers:IterableDiffers, _cdr:ChangeDetectorRef)', - 'NgFor.ngDoCheck():any', 'NgFor.ngForOf=(value:any)', 'NgFor.ngForTemplate=(value:TemplateRef)', - 'NgFor.ngForTrackBy=(value:TrackByFn)', 'NgForm', 'NgForm.addControl(dir:NgControl):void', + 'NgFor.ngDoCheck():any', + 'NgFor.ngForOf=(value:any)', + 'NgFor.ngForTemplate=(value:TemplateRef)', + 'NgFor.ngForTrackBy=(value:TrackByFn)', + 'NgForm', + 'NgForm.addControl(dir:NgControl):void', 'NgForm.addControlGroup(dir:NgControlGroup):void', - 'NgForm.constructor(validators:any[], asyncValidators:any[])', 'NgForm.control:ControlGroup', - 'NgForm.controls:{[key:string]:AbstractControl}', 'NgForm.form:ControlGroup', - 'NgForm.formDirective:Form', 'NgForm.getControl(dir:NgControl):Control', - 'NgForm.getControlGroup(dir:NgControlGroup):ControlGroup', 'NgForm.ngSubmit:any', - 'NgForm.onSubmit():boolean', 'NgForm.path:string[]', 'NgForm.removeControl(dir:NgControl):void', + 'NgForm.constructor(validators:any[], asyncValidators:any[])', + 'NgForm.control:ControlGroup', + 'NgForm.controls:{[key:string]:AbstractControl}', + 'NgForm.form:ControlGroup', + 'NgForm.formDirective:Form', + 'NgForm.getControl(dir:NgControl):Control', + 'NgForm.getControlGroup(dir:NgControlGroup):ControlGroup', + 'NgForm.ngSubmit:any', + 'NgForm.onSubmit():boolean', + 'NgForm.path:string[]', + 'NgForm.removeControl(dir:NgControl):void', 'NgForm.removeControlGroup(dir:NgControlGroup):void', - 'NgForm.updateModel(dir:NgControl, value:any):void', 'NgFormControl', + 'NgForm.updateModel(dir:NgControl, value:any):void', + 'NgFormControl', 'NgFormControl.asyncValidator:AsyncValidatorFn', 'NgFormControl.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', - 'NgFormControl.control:Control', 'NgFormControl.form:Control', 'NgFormControl.model:any', + 'NgFormControl.control:Control', + 'NgFormControl.form:Control', + 'NgFormControl.model:any', 'NgFormControl.ngOnChanges(changes:{[key:string]:SimpleChange}):void', - 'NgFormControl.path:string[]', 'NgFormControl.update:any', 'NgFormControl.validator:ValidatorFn', - 'NgFormControl.viewModel:any', 'NgFormControl.viewToModelUpdate(newValue:any):void', - 'NgFormModel', 'NgFormModel.addControl(dir:NgControl):void', + 'NgFormControl.path:string[]', + 'NgFormControl.update:any', + 'NgFormControl.validator:ValidatorFn', + 'NgFormControl.viewModel:any', + 'NgFormControl.viewToModelUpdate(newValue:any):void', + 'NgFormModel', + 'NgFormModel.addControl(dir:NgControl):void', 'NgFormModel.addControlGroup(dir:NgControlGroup):any', 'NgFormModel.constructor(_validators:any[], _asyncValidators:any[])', - 'NgFormModel.control:ControlGroup', 'NgFormModel.directives:NgControl[]', - 'NgFormModel.form:ControlGroup', 'NgFormModel.formDirective:Form', + 'NgFormModel.control:ControlGroup', + 'NgFormModel.directives:NgControl[]', + 'NgFormModel.form:ControlGroup', + 'NgFormModel.formDirective:Form', 'NgFormModel.getControl(dir:NgControl):Control', 'NgFormModel.getControlGroup(dir:NgControlGroup):ControlGroup', - 'NgFormModel.ngOnChanges(changes:{[key:string]:SimpleChange}):void', 'NgFormModel.ngSubmit:any', - 'NgFormModel.onSubmit():boolean', 'NgFormModel.path:string[]', + 'NgFormModel.ngOnChanges(changes:{[key:string]:SimpleChange}):void', + 'NgFormModel.ngSubmit:any', + 'NgFormModel.onSubmit():boolean', + 'NgFormModel.path:string[]', 'NgFormModel.removeControl(dir:NgControl):void', 'NgFormModel.removeControlGroup(dir:NgControlGroup):any', - 'NgFormModel.updateModel(dir:NgControl, value:any):void', 'NgIf', + 'NgFormModel.updateModel(dir:NgControl, value:any):void', + 'NgIf', 'NgIf.constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef)', - 'NgIf.ngIf=(newCondition:any)', 'NgLocalization', - 'NgLocalization.getPluralCategory(value:any):string', 'NgModel', + 'NgIf.ngIf=(newCondition:any)', + 'NgLocalization', + 'NgLocalization.getPluralCategory(value:any):string', + 'NgModel', 'NgModel.asyncValidator:AsyncValidatorFn', 'NgModel.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', - 'NgModel.control:Control', 'NgModel.model:any', - 'NgModel.ngOnChanges(changes:{[key:string]:SimpleChange}):any', 'NgModel.path:string[]', - 'NgModel.update:any', 'NgModel.validator:ValidatorFn', 'NgModel.viewModel:any', - 'NgModel.viewToModelUpdate(newValue:any):void', 'NgPlural', - 'NgPlural.cases:QueryList<NgPluralCase>', 'NgPlural.constructor(_localization:NgLocalization)', + 'NgModel.control:Control', + 'NgModel.model:any', + 'NgModel.ngOnChanges(changes:{[key:string]:SimpleChange}):any', + 'NgModel.path:string[]', + 'NgModel.update:any', + 'NgModel.validator:ValidatorFn', + 'NgModel.viewModel:any', + 'NgModel.viewToModelUpdate(newValue:any):void', + 'NgPlural', + 'NgPlural.cases:QueryList<NgPluralCase>', + 'NgPlural.constructor(_localization:NgLocalization)', 'NgPlural.ngAfterContentInit():any', 'NgPluralCase.constructor(value:string, template:TemplateRef, viewContainer:ViewContainerRef)', - 'NgPlural.ngPlural=(value:number)', 'NgPluralCase', 'NgSelectOption', + 'NgPlural.ngPlural=(value:number)', + 'NgPluralCase', + 'NgSelectOption', 'NgSelectOption.constructor(_element:ElementRef, _renderer:Renderer, _select:SelectControlValueAccessor)', - 'NgSelectOption.id:string', 'NgSelectOption.ngOnDestroy():any', - 'NgSelectOption.ngValue=(value:any)', 'NgSelectOption.value=(value:any)', 'NgStyle', + 'NgSelectOption.id:string', + 'NgSelectOption.ngOnDestroy():any', + 'NgSelectOption.ngValue=(value:any)', + 'NgSelectOption.value=(value:any)', + 'NgStyle', 'NgStyle.constructor(_differs:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)', - 'NgStyle.ngDoCheck():any', 'NgStyle.rawStyle=(v:{[key:string]:string})', 'NgSwitch', - 'NgSwitch.ngSwitch=(value:any)', 'NgSwitchDefault', + 'NgStyle.ngDoCheck():any', + 'NgStyle.rawStyle=(v:{[key:string]:string})', + 'NgSwitch', + 'NgSwitch.ngSwitch=(value:any)', + 'NgSwitchDefault', 'NgSwitchDefault.constructor(viewContainer:ViewContainerRef, templateRef:TemplateRef, sswitch:NgSwitch)', 'NgSwitchWhen', 'NgSwitchWhen.constructor(viewContainer:ViewContainerRef, templateRef:TemplateRef, ngSwitch:NgSwitch)', - 'NgSwitchWhen.ngSwitchWhen=(value:any)', 'NumberPipe', 'PatternValidator', + 'NgSwitchWhen.ngSwitchWhen=(value:any)', + 'NumberPipe', + 'PatternValidator', 'PatternValidator.constructor(pattern:string)', - 'PatternValidator.validate(c:AbstractControl):{[key:string]:any}', 'PercentPipe', - 'PercentPipe.transform(value:any, args:any[]):string', 'ReplacePipe', - 'ReplacePipe.transform(value:any, args:any[]):any', 'RequiredValidator', + 'PatternValidator.validate(c:AbstractControl):{[key:string]:any}', + 'PercentPipe', + 'PercentPipe.transform(value:any, args:any[]):string', + 'ReplacePipe', + 'ReplacePipe.transform(value:any, args:any[]):any', + 'RequiredValidator', 'SelectControlValueAccessor', 'SelectControlValueAccessor.constructor(_renderer:Renderer, _elementRef:ElementRef)', - 'SelectControlValueAccessor.onChange:any', 'SelectControlValueAccessor.onTouched:any', + 'SelectControlValueAccessor.onChange:any', + 'SelectControlValueAccessor.onTouched:any', 'SelectControlValueAccessor.registerOnChange(fn:(value: any) => any):void', 'SelectControlValueAccessor.registerOnTouched(fn:() => any):void', - 'SelectControlValueAccessor.value:any', 'SelectControlValueAccessor.writeValue(value:any):void', - 'SlicePipe', 'SlicePipe.transform(value:any, args:any[]):any', 'UpperCasePipe', - 'UpperCasePipe.transform(value:string, args:any[]):string', 'Validator', - 'Validator.validate(c:AbstractControl):{[key:string]:any}', 'Validators', + 'SelectControlValueAccessor.value:any', + 'SelectControlValueAccessor.writeValue(value:any):void', + 'SlicePipe', + 'SlicePipe.transform(value:any, args:any[]):any', + 'UpperCasePipe', + 'UpperCasePipe.transform(value:string, args:any[]):string', + 'Validator', + 'Validator.validate(c:AbstractControl):{[key:string]:any}', + 'Validators', 'Validators.compose(validators:ValidatorFn[]):ValidatorFn', 'Validators.composeAsync(validators:AsyncValidatorFn[]):AsyncValidatorFn', 'Validators.maxLength(maxLength:number):ValidatorFn', 'Validators.minLength(minLength:number):ValidatorFn', 'Validators.nullValidator(c:AbstractControl):{[key:string]:boolean}', 'Validators.pattern(pattern:string):ValidatorFn', - 'Validators.required(control:AbstractControl):{[key:string]:boolean}', 'RadioButtonState', - 'RadioButtonState.constructor(checked:boolean, value:string)', 'const COMMON_DIRECTIVES:Type[][]', - 'const COMMON_PIPES:any', 'const CORE_DIRECTIVES:Type[]', 'const FORM_BINDINGS:any', - 'const FORM_DIRECTIVES:Type[]', 'const FORM_PROVIDERS:Type[]', - 'const NG_ASYNC_VALIDATORS:OpaqueToken', 'const NG_VALIDATORS:OpaqueToken', - 'const NG_VALUE_ACCESSOR:OpaqueToken', 'var workaround_empty_observable_list_diff:any' + 'Validators.required(control:AbstractControl):{[key:string]:boolean}', + 'RadioButtonState', + 'RadioButtonState.constructor(checked:boolean, value:string)', + 'const COMMON_DIRECTIVES:Type[][]', + 'const COMMON_PIPES:any', + 'const CORE_DIRECTIVES:Type[]', + 'const FORM_BINDINGS:any', + 'const FORM_DIRECTIVES:Type[]', + 'const FORM_PROVIDERS:Type[]', + 'const NG_ASYNC_VALIDATORS:OpaqueToken', + 'const NG_VALIDATORS:OpaqueToken', + 'const NG_VALUE_ACCESSOR:OpaqueToken', + 'var workaround_empty_observable_list_diff:any' ]; const COMPILER = [ - 'AttrAst', 'AttrAst.constructor(name:string, value:string, sourceSpan:ParseSourceSpan)', - 'AttrAst.visit(visitor:TemplateAstVisitor, context:any):any', 'BoundDirectivePropertyAst', + 'AttrAst', + 'AttrAst.constructor(name:string, value:string, sourceSpan:ParseSourceSpan)', + 'AttrAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'BoundDirectivePropertyAst', 'BoundDirectivePropertyAst.constructor(directiveName:string, templateName:string, value:AST, sourceSpan:ParseSourceSpan)', 'BoundDirectivePropertyAst.visit(visitor:TemplateAstVisitor, context:any):any', 'BoundElementPropertyAst', 'BoundElementPropertyAst.constructor(name:string, type:PropertyBindingType, value:AST, unit:string, sourceSpan:ParseSourceSpan)', - 'BoundElementPropertyAst.visit(visitor:TemplateAstVisitor, context:any):any', 'BoundEventAst', + 'BoundElementPropertyAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'BoundEventAst', 'BoundEventAst.constructor(name:string, target:string, handler:AST, sourceSpan:ParseSourceSpan)', 'BoundEventAst.fullName:any', - 'BoundEventAst.visit(visitor:TemplateAstVisitor, context:any):any', 'BoundTextAst', - 'BoundTextAst.constructor(value:AST, ngContentIndex:number, sourceSpan:ParseSourceSpan)', 'BoundTextAst.visit(visitor:TemplateAstVisitor, context:any):any', 'CompileDirectiveMetadata', 'CompileDirectiveMetadata.changeDetection:ChangeDetectionStrategy', 'CompileDirectiveMetadata.constructor({type,isComponent,dynamicLoadable,selector,exportAs,changeDetection,inputs,outputs,hostListeners,hostProperties,hostAttributes,lifecycleHooks,providers,viewProviders,queries,viewQueries,template}:{type?:CompileTypeMetadata, isComponent?:boolean, dynamicLoadable?:boolean, selector?:string, exportAs?:string, changeDetection?:ChangeDetectionStrategy, inputs?:{[key:string]:string}, outputs?:{[key:string]:string}, hostListeners?:{[key:string]:string}, hostProperties?:{[key:string]:string}, hostAttributes?:{[key:string]:string}, lifecycleHooks?:LifecycleHooks[], providers?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, viewProviders?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, queries?:CompileQueryMetadata[], viewQueries?:CompileQueryMetadata[], template?:CompileTemplateMetadata})', 'CompileDirectiveMetadata.create({type,isComponent,dynamicLoadable,selector,exportAs,changeDetection,inputs,outputs,host,lifecycleHooks,providers,viewProviders,queries,viewQueries,template}:{type?:CompileTypeMetadata, isComponent?:boolean, dynamicLoadable?:boolean, selector?:string, exportAs?:string, changeDetection?:ChangeDetectionStrategy, inputs?:string[], outputs?:string[], host?:{[key:string]:string}, lifecycleHooks?:LifecycleHooks[], providers?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, viewProviders?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, queries?:CompileQueryMetadata[], viewQueries?:CompileQueryMetadata[], template?:CompileTemplateMetadata}):CompileDirectiveMetadata', + 'BoundEventAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'BoundTextAst', + 'BoundTextAst.constructor(value:AST, ngContentIndex:number, sourceSpan:ParseSourceSpan)', + 'BoundTextAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'CompileDirectiveMetadata', + 'CompileDirectiveMetadata.changeDetection:ChangeDetectionStrategy', + 'CompileDirectiveMetadata.constructor({type,isComponent,dynamicLoadable,selector,exportAs,changeDetection,inputs,outputs,hostListeners,hostProperties,hostAttributes,lifecycleHooks,providers,viewProviders,queries,viewQueries,template}:{type?:CompileTypeMetadata, isComponent?:boolean, dynamicLoadable?:boolean, selector?:string, exportAs?:string, changeDetection?:ChangeDetectionStrategy, inputs?:{[key:string]:string}, outputs?:{[key:string]:string}, hostListeners?:{[key:string]:string}, hostProperties?:{[key:string]:string}, hostAttributes?:{[key:string]:string}, lifecycleHooks?:LifecycleHooks[], providers?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, viewProviders?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, queries?:CompileQueryMetadata[], viewQueries?:CompileQueryMetadata[], template?:CompileTemplateMetadata})', + 'CompileDirectiveMetadata.create({type,isComponent,dynamicLoadable,selector,exportAs,changeDetection,inputs,outputs,host,lifecycleHooks,providers,viewProviders,queries,viewQueries,template}:{type?:CompileTypeMetadata, isComponent?:boolean, dynamicLoadable?:boolean, selector?:string, exportAs?:string, changeDetection?:ChangeDetectionStrategy, inputs?:string[], outputs?:string[], host?:{[key:string]:string}, lifecycleHooks?:LifecycleHooks[], providers?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, viewProviders?:Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>, queries?:CompileQueryMetadata[], viewQueries?:CompileQueryMetadata[], template?:CompileTemplateMetadata}):CompileDirectiveMetadata', 'CompileDirectiveMetadata.providers:Array<CompileProviderMetadata|CompileTypeMetadata|any[]>', 'CompileDirectiveMetadata.queries:CompileQueryMetadata[]', 'CompileDirectiveMetadata.viewProviders:Array<CompileProviderMetadata|CompileTypeMetadata|any[]>', @@ -513,40 +878,60 @@ const COMPILER = 'CompileDirectiveMetadata.template:CompileTemplateMetadata', 'CompileDirectiveMetadata.toJson():{[key:string]:any}', 'CompileDirectiveMetadata.type:CompileTypeMetadata', - 'CompileDirectiveMetadata.identifier:CompileIdentifierMetadata', 'CompileTemplateMetadata', + 'CompileDirectiveMetadata.identifier:CompileIdentifierMetadata', + 'CompileTemplateMetadata', 'CompileTemplateMetadata.constructor({encapsulation,template,templateUrl,styles,styleUrls,ngContentSelectors}:{encapsulation?:ViewEncapsulation, template?:string, templateUrl?:string, styles?:string[], styleUrls?:string[], ngContentSelectors?:string[]})', 'CompileTemplateMetadata.encapsulation:ViewEncapsulation', 'CompileTemplateMetadata.fromJson(data:{[key:string]:any}):CompileTemplateMetadata', 'CompileTemplateMetadata.ngContentSelectors:string[]', - 'CompileTemplateMetadata.styleUrls:string[]', 'CompileTemplateMetadata.styles:string[]', - 'CompileTemplateMetadata.template:string', 'CompileTemplateMetadata.templateUrl:string', - 'CompileTemplateMetadata.toJson():{[key:string]:any}', 'CompileTypeMetadata', + 'CompileTemplateMetadata.styleUrls:string[]', + 'CompileTemplateMetadata.styles:string[]', + 'CompileTemplateMetadata.template:string', + 'CompileTemplateMetadata.templateUrl:string', + 'CompileTemplateMetadata.toJson():{[key:string]:any}', + 'CompileTypeMetadata', 'CompileTypeMetadata.constructor({runtime,name,moduleUrl,prefix,isHost,constConstructor,value,diDeps}:{runtime?:Type, name?:string, moduleUrl?:string, prefix?:string, isHost?:boolean, constConstructor?:boolean, value?:any, diDeps?:CompileDiDependencyMetadata[]})', 'CompileTypeMetadata.fromJson(data:{[key:string]:any}):CompileTypeMetadata', - 'CompileTypeMetadata.value:any', 'CompileTypeMetadata.isHost:boolean', - 'CompileTypeMetadata.moduleUrl:string', 'CompileTypeMetadata.name:string', - 'CompileTypeMetadata.runtime:Type', 'CompileTypeMetadata.toJson():{[key:string]:any}', + 'CompileTypeMetadata.value:any', + 'CompileTypeMetadata.isHost:boolean', + 'CompileTypeMetadata.moduleUrl:string', + 'CompileTypeMetadata.name:string', + 'CompileTypeMetadata.runtime:Type', + 'CompileTypeMetadata.toJson():{[key:string]:any}', 'CompileTypeMetadata.diDeps:CompileDiDependencyMetadata[]', - 'CompileTypeMetadata.prefix:string', 'CompileTypeMetadata.constConstructor:boolean', + 'CompileTypeMetadata.prefix:string', + 'CompileTypeMetadata.constConstructor:boolean', 'CompileTypeMetadata.identifier:CompileIdentifierMetadata', - 'CompileTypeMetadata.type:CompileTypeMetadata', 'DirectiveAst', + 'CompileTypeMetadata.type:CompileTypeMetadata', + 'DirectiveAst', 'DirectiveAst.constructor(directive:CompileDirectiveMetadata, inputs:BoundDirectivePropertyAst[], hostProperties:BoundElementPropertyAst[], hostEvents:BoundEventAst[], exportAsVars:VariableAst[], sourceSpan:ParseSourceSpan)', - 'DirectiveAst.visit(visitor:TemplateAstVisitor, context:any):any', 'ElementAst', + 'DirectiveAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'ElementAst', 'ElementAst.constructor(name:string, attrs:AttrAst[], inputs:BoundElementPropertyAst[], outputs:BoundEventAst[], exportAsVars:VariableAst[], directives:DirectiveAst[], children:TemplateAst[], ngContentIndex:number, sourceSpan:ParseSourceSpan)', - 'ElementAst.getComponent():CompileDirectiveMetadata', 'ElementAst.isBound():boolean', - 'ElementAst.visit(visitor:TemplateAstVisitor, context:any):any', 'EmbeddedTemplateAst', + 'ElementAst.getComponent():CompileDirectiveMetadata', + 'ElementAst.isBound():boolean', + 'ElementAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'EmbeddedTemplateAst', 'EmbeddedTemplateAst.constructor(attrs:AttrAst[], outputs:BoundEventAst[], vars:VariableAst[], directives:DirectiveAst[], children:TemplateAst[], ngContentIndex:number, sourceSpan:ParseSourceSpan)', - 'EmbeddedTemplateAst.visit(visitor:TemplateAstVisitor, context:any):any', 'NgContentAst', + 'EmbeddedTemplateAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'NgContentAst', 'NgContentAst.constructor(index:number, ngContentIndex:number, sourceSpan:ParseSourceSpan)', - 'NgContentAst.visit(visitor:TemplateAstVisitor, context:any):any', 'PropertyBindingType', - 'PropertyBindingType.Attribute', 'PropertyBindingType.Class', 'PropertyBindingType.Property', - 'PropertyBindingType.Style', 'SourceModule', + 'NgContentAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'PropertyBindingType', + 'PropertyBindingType.Attribute', + 'PropertyBindingType.Class', + 'PropertyBindingType.Property', + 'PropertyBindingType.Style', + 'SourceModule', 'SourceModule.constructor(moduleUrl:string, sourceWithModuleRefs:string)', 'SourceModule.getSourceWithImports():SourceWithImports', 'SourceModule.getSourceWithoutImports(sourceWithModuleRefs:string):string', - 'SourceWithImports', 'SourceWithImports.constructor(source:string, imports:string[][])', - 'TemplateAst', 'TemplateAst.sourceSpan:ParseSourceSpan', - 'TemplateAst.visit(visitor:TemplateAstVisitor, context:any):any', 'TemplateAstVisitor', + 'SourceWithImports', + 'SourceWithImports.constructor(source:string, imports:string[][])', + 'TemplateAst', + 'TemplateAst.sourceSpan:ParseSourceSpan', + 'TemplateAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'TemplateAstVisitor', 'TemplateAstVisitor.visitAttr(ast:AttrAst, context:any):any', 'TemplateAstVisitor.visitBoundText(ast:BoundTextAst, context:any):any', 'TemplateAstVisitor.visitDirective(ast:DirectiveAst, context:any):any', @@ -557,55 +942,76 @@ const COMPILER = 'TemplateAstVisitor.visitEvent(ast:BoundEventAst, context:any):any', 'TemplateAstVisitor.visitNgContent(ast:NgContentAst, context:any):any', 'TemplateAstVisitor.visitText(ast:TextAst, context:any):any', - 'TemplateAstVisitor.visitVariable(ast:VariableAst, context:any):any', 'TemplateCompiler', + 'TemplateAstVisitor.visitVariable(ast:VariableAst, context:any):any', + 'TemplateCompiler', 'TemplateCompiler.clearCache():any', 'TemplateCompiler.compileHostComponentRuntime(type:Type):Promise<HostViewFactory>', - 'TemplateCompiler.compileStylesheetCodeGen(stylesheetUrl:string, cssText:string):SourceModule[]', 'TemplateCompiler.compileTemplatesCodeGen(components:NormalizedComponentWithViewDirectives[]):SourceModule', 'TemplateCompiler.constructor(_runtimeMetadataResolver:RuntimeMetadataResolver, _templateNormalizer:TemplateNormalizer, _templateParser:TemplateParser, _styleCompiler:StyleCompiler, _cdCompiler:ChangeDetectionCompiler, _protoViewCompiler:ProtoViewCompiler, _viewCompiler:ViewCompiler, _resolvedMetadataCache:ResolvedMetadataCache, _genConfig:ChangeDetectorGenConfig)', + 'TemplateCompiler.compileStylesheetCodeGen(stylesheetUrl:string, cssText:string):SourceModule[]', + 'TemplateCompiler.compileTemplatesCodeGen(components:NormalizedComponentWithViewDirectives[]):SourceModule', + 'TemplateCompiler.constructor(_runtimeMetadataResolver:RuntimeMetadataResolver, _templateNormalizer:TemplateNormalizer, _templateParser:TemplateParser, _styleCompiler:StyleCompiler, _cdCompiler:ChangeDetectionCompiler, _protoViewCompiler:ProtoViewCompiler, _viewCompiler:ViewCompiler, _resolvedMetadataCache:ResolvedMetadataCache, _genConfig:ChangeDetectorGenConfig)', 'TemplateCompiler.normalizeDirectiveMetadata(directive:CompileDirectiveMetadata):Promise<CompileDirectiveMetadata>', 'TextAst', 'TextAst.constructor(value:string, ngContentIndex:number, sourceSpan:ParseSourceSpan)', - 'TextAst.visit(visitor:TemplateAstVisitor, context:any):any', 'UrlResolver', + 'TextAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'UrlResolver', 'UrlResolver.constructor(packagePrefix:string)', - 'UrlResolver.resolve(baseUrl:string, url:string):string', 'VariableAst', + 'UrlResolver.resolve(baseUrl:string, url:string):string', + 'VariableAst', 'VariableAst.constructor(name:string, value:string, sourceSpan:ParseSourceSpan)', - 'VariableAst.visit(visitor:TemplateAstVisitor, context:any):any', 'XHR', - 'XHR.get(url:string):Promise<string>', 'const COMPILER_PROVIDERS:Array<Type|Provider|any[]>', - 'const PLATFORM_DIRECTIVES:OpaqueToken', 'const PLATFORM_PIPES:OpaqueToken', - 'const TEMPLATE_TRANSFORMS:any', 'createWithoutPackagePrefix():UrlResolver', + 'VariableAst.visit(visitor:TemplateAstVisitor, context:any):any', + 'XHR', + 'XHR.get(url:string):Promise<string>', + 'const COMPILER_PROVIDERS:Array<Type|Provider|any[]>', + 'const PLATFORM_DIRECTIVES:OpaqueToken', + 'const PLATFORM_PIPES:OpaqueToken', + 'const TEMPLATE_TRANSFORMS:any', + 'createWithoutPackagePrefix():UrlResolver', 'getUrlScheme(url:string):string', 'templateVisitAll(visitor:TemplateAstVisitor, asts:TemplateAst[], context:any):any[]', 'var DEFAULT_PACKAGE_URL_PROVIDER:any' ]; const INSTRUMENTATION = [ - 'WtfScopeFn', 'var wtfCreateScope:(signature: string, flags?: any) => impl.WtfScopeFn', - 'var wtfEndTimeRange:(range: any) => void', 'var wtfLeave:<T>(scope: any, returnValue?: T) => T', + 'WtfScopeFn', + 'var wtfCreateScope:(signature: string, flags?: any) => impl.WtfScopeFn', + 'var wtfEndTimeRange:(range: any) => void', + 'var wtfLeave:<T>(scope: any, returnValue?: T) => T', 'var wtfStartTimeRange:(rangeType: string, action: string) => any' ]; const UPGRADE = [ - 'UpgradeAdapter', 'UpgradeAdapter.addProvider(provider:Type|Provider|any[]):void', + 'UpgradeAdapter', + 'UpgradeAdapter.addProvider(provider:Type|Provider|any[]):void', 'UpgradeAdapter.bootstrap(element:Element, modules:any[], config:IAngularBootstrapConfig):UpgradeAdapterRef', 'UpgradeAdapter.downgradeNg2Component(type:Type):Function', 'UpgradeAdapter.downgradeNg2Provider(token:any):Function', 'UpgradeAdapter.upgradeNg1Component(name:string):Type', - 'UpgradeAdapter.upgradeNg1Provider(name:string, options:{asToken:any}):any', 'UpgradeAdapterRef', - 'UpgradeAdapterRef.dispose():any', 'UpgradeAdapterRef.ng1Injector:IInjectorService', + 'UpgradeAdapter.upgradeNg1Provider(name:string, options:{asToken:any}):any', + 'UpgradeAdapterRef', + 'UpgradeAdapterRef.dispose():any', + 'UpgradeAdapterRef.ng1Injector:IInjectorService', 'UpgradeAdapterRef.ng1RootScope:IRootScopeService', - 'UpgradeAdapterRef.ng2ApplicationRef:ApplicationRef', 'UpgradeAdapterRef.ng2Injector:Injector', + 'UpgradeAdapterRef.ng2ApplicationRef:ApplicationRef', + 'UpgradeAdapterRef.ng2Injector:Injector', 'UpgradeAdapterRef.ready(fn:(upgradeAdapterRef?: UpgradeAdapterRef) => void):any' ]; const BROWSER = [ - 'AngularEntrypoint', 'AngularEntrypoint.constructor(name:String)', 'BrowserDomAdapter', + 'AngularEntrypoint', + 'AngularEntrypoint.constructor(name:String)', + 'BrowserDomAdapter', 'BrowserDomAdapter.addClass(element:any, className:string):any', 'BrowserDomAdapter.adoptNode(node:Node):any', - 'BrowserDomAdapter.appendChild(el:any, node:any):any', 'BrowserDomAdapter.attrToPropMap:any', + 'BrowserDomAdapter.appendChild(el:any, node:any):any', + 'BrowserDomAdapter.attrToPropMap:any', 'BrowserDomAdapter.attributeMap(element:any):Map<string, string>', 'BrowserDomAdapter.cancelAnimationFrame(id:number):any', - 'BrowserDomAdapter.childNodes(el:any):Node[]', 'BrowserDomAdapter.childNodesAsList(el:any):any[]', - 'BrowserDomAdapter.classList(element:any):any[]', 'BrowserDomAdapter.clearNodes(el:any):any', - 'BrowserDomAdapter.clone(node:Node):Node', 'BrowserDomAdapter.content(node:Node):Node', + 'BrowserDomAdapter.childNodes(el:any):Node[]', + 'BrowserDomAdapter.childNodesAsList(el:any):any[]', + 'BrowserDomAdapter.classList(element:any):any[]', + 'BrowserDomAdapter.clearNodes(el:any):any', + 'BrowserDomAdapter.clone(node:Node):Node', + 'BrowserDomAdapter.content(node:Node):Node', 'BrowserDomAdapter.createComment(text:string):Comment', 'BrowserDomAdapter.createElement(tagName:any, doc:any):HTMLElement', 'BrowserDomAdapter.createElementNS(ns:any, tagName:any, doc:any):Element', @@ -623,7 +1029,8 @@ const BROWSER = [ 'BrowserDomAdapter.firstChild(el:any):Node', 'BrowserDomAdapter.getAttribute(element:any, attribute:string):string', 'BrowserDomAdapter.getAttributeNS(element:any, ns:string, name:string):string', - 'BrowserDomAdapter.getBaseHref():string', 'BrowserDomAdapter.getBoundingClientRect(el:any):any', + 'BrowserDomAdapter.getBaseHref():string', + 'BrowserDomAdapter.getBoundingClientRect(el:any):any', 'BrowserDomAdapter.getChecked(el:any):boolean', 'BrowserDomAdapter.getComputedStyle(element:any):any', 'BrowserDomAdapter.getData(element:any, name:string):string', @@ -631,14 +1038,19 @@ const BROWSER = [ 'BrowserDomAdapter.getElementsByTagName(element:any, name:string):HTMLElement[]', 'BrowserDomAdapter.getEventKey(event:any):string', 'BrowserDomAdapter.getGlobalEventTarget(target:string):EventTarget', - 'BrowserDomAdapter.getHistory():History', 'BrowserDomAdapter.getHost(el:HTMLElement):HTMLElement', - 'BrowserDomAdapter.getHref(el:Element):string', 'BrowserDomAdapter.getInnerHTML(el:any):string', - 'BrowserDomAdapter.getLocation():Location', 'BrowserDomAdapter.getOuterHTML(el:any):string', + 'BrowserDomAdapter.getHistory():History', + 'BrowserDomAdapter.getHost(el:HTMLElement):HTMLElement', + 'BrowserDomAdapter.getHref(el:Element):string', + 'BrowserDomAdapter.getInnerHTML(el:any):string', + 'BrowserDomAdapter.getLocation():Location', + 'BrowserDomAdapter.getOuterHTML(el:any):string', 'BrowserDomAdapter.getProperty(el:any, name:string):any', 'BrowserDomAdapter.getShadowRoot(el:HTMLElement):DocumentFragment', 'BrowserDomAdapter.getStyle(element:any, stylename:string):string', - 'BrowserDomAdapter.getText(el:any):string', 'BrowserDomAdapter.getTitle():string', - 'BrowserDomAdapter.getUserAgent():string', 'BrowserDomAdapter.getValue(el:any):string', + 'BrowserDomAdapter.getText(el:any):string', + 'BrowserDomAdapter.getTitle():string', + 'BrowserDomAdapter.getUserAgent():string', + 'BrowserDomAdapter.getValue(el:any):string', 'BrowserDomAdapter.hasAttribute(element:any, attribute:string):boolean', 'BrowserDomAdapter.hasAttributeNS(element:any, ns:string, attribute:string):boolean', 'BrowserDomAdapter.hasClass(element:any, className:string):boolean', @@ -655,16 +1067,22 @@ const BROWSER = [ 'BrowserDomAdapter.isPrevented(evt:Event):boolean', 'BrowserDomAdapter.isShadowRoot(node:any):boolean', 'BrowserDomAdapter.isTemplateElement(el:any):boolean', - 'BrowserDomAdapter.isTextNode(node:Node):boolean', 'BrowserDomAdapter.log(error:any):any', - 'BrowserDomAdapter.logError(error:any):any', 'BrowserDomAdapter.logGroup(error:any):any', - 'BrowserDomAdapter.logGroupEnd():any', 'BrowserDomAdapter.makeCurrent():any', - 'BrowserDomAdapter.nextSibling(el:any):Node', 'BrowserDomAdapter.nodeName(node:Node):string', + 'BrowserDomAdapter.isTextNode(node:Node):boolean', + 'BrowserDomAdapter.log(error:any):any', + 'BrowserDomAdapter.logError(error:any):any', + 'BrowserDomAdapter.logGroup(error:any):any', + 'BrowserDomAdapter.logGroupEnd():any', + 'BrowserDomAdapter.makeCurrent():any', + 'BrowserDomAdapter.nextSibling(el:any):Node', + 'BrowserDomAdapter.nodeName(node:Node):string', 'BrowserDomAdapter.nodeValue(node:Node):string', 'BrowserDomAdapter.on(el:any, evt:any, listener:any):any', 'BrowserDomAdapter.onAndCancel(el:any, evt:any, listener:any):Function', 'BrowserDomAdapter.parentElement(el:any):Node', - 'BrowserDomAdapter.parse(templateHtml:string):any', 'BrowserDomAdapter.performanceNow():number', - 'BrowserDomAdapter.preventDefault(evt:Event):any', 'BrowserDomAdapter.query(selector:string):any', + 'BrowserDomAdapter.parse(templateHtml:string):any', + 'BrowserDomAdapter.performanceNow():number', + 'BrowserDomAdapter.preventDefault(evt:Event):any', + 'BrowserDomAdapter.query(selector:string):any', 'BrowserDomAdapter.querySelector(el:any, selector:string):HTMLElement', 'BrowserDomAdapter.querySelectorAll(el:any, selector:string):any[]', 'BrowserDomAdapter.remove(node:any):Node', @@ -689,27 +1107,34 @@ const BROWSER = [ 'BrowserDomAdapter.setValue(el:any, value:string):any', 'BrowserDomAdapter.tagName(element:any):string', 'BrowserDomAdapter.templateAwareRoot(el:any):any', - 'BrowserDomAdapter.type(node:HTMLInputElement):string', 'By', 'By.all():Predicate<DebugElement>', + 'BrowserDomAdapter.type(node:HTMLInputElement):string', + 'By', + 'By.all():Predicate<DebugElement>', 'By.css(selector:string):Predicate<DebugElement>', - 'By.directive(type:Type):Predicate<DebugElement>', 'Title', 'Title.getTitle():string', + 'By.directive(type:Type):Predicate<DebugElement>', + 'Title', + 'Title.getTitle():string', 'Title.setTitle(newTitle:string):any', 'bootstrapStatic(appComponentType:Type, customProviders:Array<any>, initReflector:Function):Promise<ComponentRef>', - 'const BROWSER_APP_PROVIDERS:Array<any>', 'const BROWSER_PROVIDERS:Array<any>', - 'const ELEMENT_PROBE_PROVIDERS:any[]', 'const ELEMENT_PROBE_PROVIDERS_PROD_MODE:any[]', - 'disableDebugTools():void', 'enableDebugTools(ref:ComponentRef):void', + 'const BROWSER_APP_PROVIDERS:Array<any>', + 'const BROWSER_PROVIDERS:Array<any>', + 'const ELEMENT_PROBE_PROVIDERS:any[]', + 'const ELEMENT_PROBE_PROVIDERS_PROD_MODE:any[]', + 'disableDebugTools():void', + 'enableDebugTools(ref:ComponentRef):void', 'inspectNativeElement(element:any):DebugNode' ]; describe('public API', () => { - it('should check core.ts', () => { checkPublicApi('modules/angular2/core.ts', CORE); }); - it('should check common.ts', () => { checkPublicApi('modules/angular2/common.ts', COMMON); }); - it('should check compiler.ts', - () => { checkPublicApi('modules/angular2/compiler.ts', COMPILER); }); - it('should check instrumentation.ts', - () => { checkPublicApi('modules/angular2/instrumentation.ts', INSTRUMENTATION); }); - it('should check upgrade.ts', () => { checkPublicApi('modules/angular2/upgrade.ts', UPGRADE); }); - it('should check browser.ts', - () => { checkPublicApi('modules/angular2/platform/browser_static.ts', BROWSER); }); + it("should check core.ts", () => { checkPublicApi("modules/angular2/core.ts", CORE); }); + it("should check common.ts", () => { checkPublicApi("modules/angular2/common.ts", COMMON); }); + it("should check compiler.ts", + () => { checkPublicApi("modules/angular2/compiler.ts", COMPILER); }); + it("should check instrumentation.ts", + () => { checkPublicApi("modules/angular2/instrumentation.ts", INSTRUMENTATION); }); + it("should check upgrade.ts", () => { checkPublicApi("modules/angular2/upgrade.ts", UPGRADE); }); + it("should check browser.ts", + () => { checkPublicApi("modules/angular2/platform/browser_static.ts", BROWSER); }); }); function checkPublicApi(file: string, expected: string[]) { @@ -719,12 +1144,12 @@ function checkPublicApi(file: string, expected: string[]) { const extra = sortedExpected.filter((i) => sortedActual.indexOf(i) < 0); if (missing.length > 0) { - console.log('Missing:'); + console.log("Missing:"); missing.forEach((m) => console.log(m)); } if (extra.length > 0) { - console.log('Extra:'); + console.log("Extra:"); extra.forEach((m) => console.log(m)); } diff --git a/tools/tslint/requireInternalWithUnderscoreRule.ts b/tools/tslint/requireInternalWithUnderscoreRule.ts index a6742ac539..6ee936af3b 100644 --- a/tools/tslint/requireInternalWithUnderscoreRule.ts +++ b/tools/tslint/requireInternalWithUnderscoreRule.ts @@ -24,7 +24,7 @@ class TypedefWalker extends RuleWalker { private hasInternalAnnotation(range: ts.CommentRange): boolean { let text = this.getSourceFile().text; let comment = text.substring(range.pos, range.end); - return comment.indexOf('@internal') >= 0; + return comment.indexOf("@internal") >= 0; } private assertInternalAnnotationPresent(node: ts.Declaration) { diff --git a/tools/tslint/requireParameterTypeRule.ts b/tools/tslint/requireParameterTypeRule.ts index 9611f2ccf0..d5e9999232 100644 --- a/tools/tslint/requireParameterTypeRule.ts +++ b/tools/tslint/requireParameterTypeRule.ts @@ -4,7 +4,7 @@ import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'typescript'; export class Rule extends AbstractRule { - public static FAILURE_STRING = 'missing type declaration'; + public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.SourceFile): RuleFailure[] { const typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); @@ -28,12 +28,12 @@ class TypedefWalker extends RuleWalker { private checkTypeAnnotation(location: number, typeAnnotation: ts.TypeNode, name?: ts.Node) { if (typeAnnotation == null) { - let ns = '<name missing>'; + let ns = "<name missing>"; if (name != null && name.kind === ts.SyntaxKind.Identifier) { ns = (<ts.Identifier>name).text; } if (ns.charAt(0) === '_') return; - let failure = this.createFailure(location, 1, 'expected parameter ' + ns + ' to have a type'); + let failure = this.createFailure(location, 1, "expected parameter " + ns + " to have a type"); this.addFailure(failure); } } diff --git a/tools/tslint/requireReturnTypeRule.ts b/tools/tslint/requireReturnTypeRule.ts index f8433572d0..6bf3c0634f 100644 --- a/tools/tslint/requireReturnTypeRule.ts +++ b/tools/tslint/requireReturnTypeRule.ts @@ -4,7 +4,7 @@ import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'typescript'; export class Rule extends AbstractRule { - public static FAILURE_STRING = 'missing type declaration'; + public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.SourceFile): RuleFailure[] { const typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); @@ -50,12 +50,12 @@ class TypedefWalker extends RuleWalker { private checkTypeAnnotation(typeAnnotation: ts.TypeNode, name: ts.Node, start: number) { if (typeAnnotation == null) { - let ns = '<name missing>'; + let ns = "<name missing>"; if (name != null && name.kind === ts.SyntaxKind.Identifier) { ns = (<ts.Identifier>name).text; } if (ns.charAt(0) === '_') return; - let failure = this.createFailure(start, 1, 'expected ' + ns + ' to have a return type'); + let failure = this.createFailure(start, 1, "expected " + ns + " to have a return type"); this.addFailure(failure); } }