chore(format): update to latest formatter

Closes #7958
This commit is contained in:
Alex Eagle 2016-04-07 17:17:50 -07:00 committed by Alex Eagle
parent 83b8f59297
commit 03627aa84d
527 changed files with 13975 additions and 19252 deletions

View File

@ -43,9 +43,7 @@ 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) => {
var cliArgsProjects = (cliArgs.projects || allProjects).split(',').reduce((map, projectName) => {
map[projectName] = true;
return map;
}, {});
@ -55,9 +53,9 @@ 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');
}
}
@ -105,8 +103,9 @@ 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) {
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.
@ -143,12 +142,8 @@ 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/*';
@ -174,8 +169,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}}
@ -197,18 +192,19 @@ 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); });
// ------------
@ -218,12 +214,14 @@ gulp.task('!build/tree.dart',
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',
gulp.task(
'build/pubspec.dart',
pubget.subDir(gulp, gulpPlugins, {dir: CONFIG.dest.dart, command: DART_SDK.PUB}));
@ -245,7 +243,8 @@ gulp.task('!build/remove-pub-symlinks', function(done) {
return;
}
exec('find dist/dart/angular2/test/ -name packages | xargs rm -r',
exec(
'find dist/dart/angular2/test/ -name packages | xargs rm -r',
function(error, stdout, stderr) {
if (error) {
done(stderr);
@ -269,15 +268,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,
return dartapidocs(
gulp, gulpPlugins,
{dest: CONFIG.dest.dart, output: os.tmpdir(), command: DART_SDK.DARTDOCGEN});
});
@ -288,7 +288,8 @@ gulp.task('build/check.apidocs.dart', () => {
gulp.task(
'build/pubbuild.dart',
pubbuild.subdirs(gulp, gulpPlugins,
pubbuild.subdirs(
gulp, gulpPlugins,
{src: CONFIG.dest.dart, dest: CONFIG.dest.js.dart2js, command: DART_SDK.PUB}));
// ------------
@ -304,14 +305,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);
});
});
@ -321,14 +322,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/**'])
@ -348,7 +349,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) {
@ -419,25 +420,28 @@ 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,
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,
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,
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) {
@ -466,13 +470,14 @@ 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); });
@ -495,23 +500,25 @@ 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' &&
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' &&
} else if (
provider && provider == 'BS' &&
browserProvidersConf.browserstackAliases.hasOwnProperty(input.toUpperCase())) {
outputList = outputList.concat(browserProvidersConf.browserstackAliases[input.toUpperCase()]);
isProvider = true;
@ -566,7 +573,8 @@ gulp.task('test.unit.js.browserstack', ['build.js.dev'], function(done) {
function launchKarmaWithExternalBrowsers(reporters, browsers, done) {
var karma = require('karma');
new karma.Server(
new karma
.Server(
{
configFile: __dirname + '/karma-js.conf.js',
singleRun: true,
@ -622,7 +630,8 @@ 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'},
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
@ -639,7 +648,8 @@ 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',
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');
@ -651,8 +661,7 @@ gulp.task('test.unit.dart', function(done) {
}
// treatTestErrorsAsFatal = false;
watch(['modules/angular2/**'],
['!build/tree.dart', '!test.unit.dart/run/angular2']);
watch(['modules/angular2/**'], ['!build/tree.dart', '!test.unit.dart/run/angular2']);
});
});
@ -662,21 +671,25 @@ 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',
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',
return reportSize(
'modules_dart/payload/hello_world/build/web/*.dart.js',
{failConditions: _DART_PAYLOAD_SIZE_LIMITS, prefix: 'hello_world'});
});
@ -701,7 +714,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
@ -713,8 +726,7 @@ 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())
@ -744,10 +756,8 @@ 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())
@ -763,12 +773,13 @@ 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) + '/' +
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) {
@ -778,7 +789,8 @@ 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',
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');
@ -797,7 +809,8 @@ gulp.task('test.unit.router/ci', function(done) {
var karma = require('karma');
var browserConf = getBrowsersFromCLI();
new karma.Server(
new karma
.Server(
{
configFile: __dirname + '/modules/angular1_router/karma-router.conf.js',
singleRun: true,
@ -812,7 +825,8 @@ gulp.task('test.unit.js/ci', function(done) {
var karma = require('karma');
var browserConf = getBrowsersFromCLI();
new karma.Server(
new karma
.Server(
{
configFile: __dirname + '/karma-js.conf.js',
singleRun: true,
@ -840,7 +854,8 @@ 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',
runSequence(
'test.dart.dartium_symlink', '!test.unit.dart/run/angular2',
'!test.unit.dart/run/angular2_testing', '!test.unit.dart/run/benchpress',
sequenceComplete(done));
});
@ -895,8 +910,9 @@ 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');
@ -917,19 +933,21 @@ 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},
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},
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) {
@ -953,8 +971,9 @@ 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
@ -989,7 +1008,8 @@ gulp.task('!pre.test.typings.layoutNodeModule', ['build.js.cjs'], function() {
});
gulp.task('!pre.test.typings.copyDeps', function() {
return gulp.src(
return gulp
.src(
[
'modules/angular2/typings/angular-protractor/*.ts',
'modules/angular2/typings/jasmine/*.ts',
@ -1003,17 +1023,16 @@ gulp.task('!pre.test.typings.copyTypingsSpec', function() {
return gulp.src(['modules/angular2/examples/**/*.ts']).pipe(gulp.dest(tmpdir));
});
gulp.task('test.typings',
gulp.task(
'test.typings',
[
'!pre.test.typings.layoutNodeModule',
'!pre.test.typings.copyTypingsSpec',
'!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({
return gulp.src([tmpdir + '/**/*.ts', '!' + tmpdir + '/node_modules/**/*']).pipe(tsc({
target: 'ES6',
module: 'commonjs',
experimentalDecorators: true,
@ -1032,13 +1051,15 @@ gulp.task('test.typings',
//
// 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',
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([
return gulp
.src([
'modules_dart/**/*',
'!modules_dart/**/*.proto',
'!modules_dart/**/packages{,/**}',
@ -1055,7 +1076,8 @@ gulp.task('build/pure-packages.dart/license', function() {
gulp.task('build/pure-packages.dart/angular2', function() {
return gulp.src([
return gulp
.src([
'modules_dart/transform/**/*',
'!modules_dart/transform/**/*.proto',
'!modules_dart/transform/pubspec.yaml',
@ -1066,21 +1088,24 @@ gulp.task('build/pure-packages.dart/angular2', function() {
// 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',
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
@ -1088,9 +1113,7 @@ 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({
var stream = gulp.src(['tools/**/*.ts']).pipe(sourcemaps.init()).pipe(tsc({
target: 'ES5',
module: 'commonjs',
declaration: true,
@ -1117,8 +1140,9 @@ 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,
@ -1134,18 +1158,21 @@ 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;
@ -1154,7 +1181,8 @@ var firstBuildJsCjs = true;
* private task
*/
gulp.task('!build.js.cjs', function() {
return angularBuilder.rebuildNodeTree({
return angularBuilder
.rebuildNodeTree({
generateEs6: generateEs6,
projects: cliArgsProjects,
noTypeChecks: cliArgs.noTypeChecks,
@ -1172,7 +1200,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.
@ -1192,10 +1220,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)
]);
});
});
@ -1206,16 +1234,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)
]);
});
});
@ -1226,34 +1254,37 @@ 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});
});
});
@ -1261,9 +1292,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',
return bundler.bundle(
devBundleConfig, TESTING_BUNDLE_CONTENT, './dist/js/bundle/testing.dev.js',
{sourceMaps: true});
});
@ -1330,12 +1362,13 @@ 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'))
]);
});
@ -1353,7 +1386,8 @@ 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'),
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'))
@ -1364,7 +1398,8 @@ 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'),
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'))
@ -1372,12 +1407,12 @@ gulp.task('!bundle.js.min.deps', ['!bundle.js.min'], function() {
.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'
@ -1395,7 +1430,8 @@ 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'),
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'))
@ -1404,13 +1440,15 @@ gulp.task('!bundle.js.dev.deps', ['!bundle.js.dev'], function() {
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')),
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')));
});
@ -1419,27 +1457,21 @@ gulp.task('!bundles.js.checksize', function(done) {
return reportSize('dist/js/bundle/**/*.js', {printToConsole: ['gzip level=2']});
});
gulp.task('bundles.js',
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'
'!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',
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'
]);
@ -1466,8 +1498,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) {
@ -1482,8 +1514,9 @@ 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();
@ -1499,7 +1532,8 @@ 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,
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);
});
@ -1537,7 +1571,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); });

View File

@ -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,7 +213,8 @@ function ngLinkDirective($rootRouter, $parse) {
function getLink(params) {
navigationInstruction = router.generate(params);
scope.$watch(function() { return router.isRouteActive(navigationInstruction); },
scope.$watch(
function() { return router.isRouteActive(navigationInstruction); },
function(active) {
if (active) {
element.addClass('ng-link-active');
@ -232,8 +233,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 => {

View File

@ -10,13 +10,7 @@ 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';

View File

@ -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

View File

@ -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);

View File

@ -1,12 +1,6 @@
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';

View File

@ -1,13 +1,6 @@
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({

View File

@ -1,12 +1,6 @@
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`})

View File

@ -1,12 +1,6 @@
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()
@ -57,7 +51,6 @@ 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
]);
}

View File

@ -1,15 +1,6 @@
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
@ -53,6 +44,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'})]);
}

View File

@ -1,15 +1,4 @@
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;
@ -30,8 +19,9 @@ 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
@ -73,7 +63,8 @@ describe('some component', () => {
// #docregion beforeEachProviders
describe('some component', () => {
beforeEachProviders(() => [provide(MyService, {useClass: MyMockService})]);
it('uses MyService', inject([MyService], (service: MyMockService) => {
it('uses MyService', inject(
[MyService], (service: MyMockService) => {
// service is an instance of MyMockService.
}));
});

View File

@ -16,12 +16,7 @@ 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';
@ -155,16 +150,13 @@ 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,
{
provide(Http, {
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
new Http(xhrBackend, requestOptions),
deps: [XHRBackend, RequestOptions]
}),
BrowserXhr,
provide(RequestOptions, {useClass: BaseRequestOptions}),
provide(ResponseOptions, {useClass: BaseResponseOptions}),
XHRBackend
BrowserXhr, provide(RequestOptions, {useClass: BaseRequestOptions}),
provide(ResponseOptions, {useClass: BaseResponseOptions}), XHRBackend
];
/**
@ -284,14 +276,12 @@ 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,
{
provide(Jsonp, {
useFactory: (jsonpBackend: JSONPBackend, requestOptions: RequestOptions) =>
new Jsonp(jsonpBackend, requestOptions),
deps: [JSONPBackend, RequestOptions]
}),
BrowserJsonp,
provide(RequestOptions, {useClass: BaseRequestOptions}),
BrowserJsonp, provide(RequestOptions, {useClass: BaseRequestOptions}),
provide(ResponseOptions, {useClass: BaseResponseOptions}),
provide(JSONPBackend, {useClass: JSONPBackend_})
];

View File

@ -1,7 +1 @@
export {
wtfCreateScope,
wtfLeave,
wtfStartTimeRange,
wtfEndTimeRange,
WtfScopeFn
} from './src/core/profile/profile';
export {wtfCreateScope, wtfLeave, wtfStartTimeRange, wtfEndTimeRange, WtfScopeFn} from './src/core/profile/profile';

View File

@ -1,27 +1,12 @@
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';

View File

@ -1,21 +1,8 @@
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';
/**
@ -29,8 +16,8 @@ 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[]*/>,
export function bootstrapStatic(
appComponentType: Type, customProviders?: Array<any /*Type | Provider | any[]*/>,
initReflector?: Function): Promise<ComponentRef> {
if (isPresent(initReflector)) {
initReflector();

View File

@ -6,10 +6,6 @@ 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';

View File

@ -1,7 +1,4 @@
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';

View File

@ -1,12 +1,4 @@
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';
@ -18,7 +10,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';
@ -63,7 +55,6 @@ 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
]);

View File

@ -1,14 +1,4 @@
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';
@ -30,11 +20,7 @@ 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';

View File

@ -1,19 +1,7 @@
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';

View File

@ -1,21 +1,7 @@
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';

View File

@ -1,10 +1,4 @@
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';
@ -47,7 +41,8 @@ export class Animation {
* @param data
* @param browserDetails
*/
constructor(public element: HTMLElement, public data: CssAnimationOptions,
constructor(
public element: HTMLElement, public data: CssAnimationOptions,
public browserDetails: BrowserDetails) {
this.startTime = DateWrapper.toMillis(DateWrapper.now());
this._stringPrefix = DOM.getAnimationPrefix();
@ -80,15 +75,16 @@ 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(
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.computedDuration = Math.max(
this.parseDurationString(
computedStyles.getPropertyValue(this._stringPrefix + 'transition-duration')),
this.parseDurationString(
this.element.style.getPropertyValue(this._stringPrefix + 'transition-duration')));
this.addEvents();
}

View File

@ -47,13 +47,5 @@ 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
]);

View File

@ -1,17 +1,5 @@
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';
/**
@ -80,7 +68,8 @@ export class NgClass implements DoCheck, OnDestroy {
private _initialClasses: string[] = [];
private _rawClass: string[]|Set<string>;
constructor(private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
constructor(
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
private _ngEl: ElementRef, private _renderer: Renderer) {}
set initialClasses(v: string) {
@ -154,16 +143,16 @@ 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) => {
StringMapWrapper.forEach(
<{[k: string]: any}>rawClassVal, (expVal: any, className: string) => {
if (isPresent(expVal)) this._toggleClass(className, !isCleanup);
});
}

View File

@ -1,20 +1,7 @@
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
@ -75,7 +62,8 @@ export class NgFor implements DoCheck {
_ngForTrackBy: TrackByFn;
private _differ: IterableDiffer;
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef,
constructor(
private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef,
private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {}
set ngForOf(value: any) {
@ -109,15 +97,18 @@ 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) =>
changes.forEachRemovedItem(
(removedRecord: CollectionChangeRecord) =>
recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord: CollectionChangeRecord) =>
changes.forEachMovedItem(
(movedRecord: CollectionChangeRecord) =>
recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
changes.forEachAddedItem((addedRecord: CollectionChangeRecord) =>
changes.forEachAddedItem(
(addedRecord: CollectionChangeRecord) =>
insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples);
@ -146,7 +137,8 @@ export class NgFor implements DoCheck {
}
private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a: RecordViewTuple, b: RecordViewTuple) =>
tuples.sort(
(a: RecordViewTuple, b: RecordViewTuple) =>
a.record.previousIndex - b.record.previousIndex);
var movedTuples: RecordViewTuple[] = [];
for (var i = tuples.length - 1; i >= 0; i--) {

View File

@ -1,13 +1,4 @@
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';
@ -76,7 +67,8 @@ export abstract class NgLocalization { abstract getPluralCategory(value: any): s
export class NgPluralCase {
/** @internal */
_view: SwitchView;
constructor(@Attribute('ngPluralCase') public value: string, template: TemplateRef,
constructor(
@Attribute('ngPluralCase') public value: string, template: TemplateRef,
viewContainer: ViewContainerRef) {
this._view = new SwitchView(viewContainer, template);
}
@ -135,7 +127,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 {

View File

@ -1,13 +1,6 @@
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.
@ -67,8 +60,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;

View File

@ -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));
}
}

View File

@ -27,19 +27,10 @@ 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';

View File

@ -10,16 +10,8 @@ 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';
@ -29,22 +21,11 @@ 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';
@ -65,24 +46,12 @@ 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
]);

View File

@ -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"));
export const NG_VALUE_ACCESSOR: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValueAccessor'));

View File

@ -1,15 +1,4 @@
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';
@ -78,7 +67,8 @@ export class NgControlGroup extends ControlContainer implements OnInit,
/** @internal */
_parent: ControlContainer;
constructor(@Host() @SkipSelf() parent: ControlContainer,
constructor(
@Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();

View File

@ -1,31 +1,12 @@
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';
@ -139,7 +120,9 @@ export class NgControlName extends NgControl implements OnChanges,
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); }
}

View File

@ -1,9 +1,4 @@
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';
@ -90,11 +85,12 @@ export class NgForm extends ControlContainer implements Form {
form: ControlGroup;
ngSubmit = new EventEmitter();
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: 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; }

View File

@ -1,28 +1,12 @@
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 =
@ -113,7 +97,9 @@ export class NgFormControl extends NgControl implements OnChanges {
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; }
@ -123,6 +109,6 @@ export class NgFormControl extends NgControl implements OnChanges {
}
private _isControlChanged(changes: {[key: string]: any}): boolean {
return StringMapWrapper.contains(changes, "form");
return StringMapWrapper.contains(changes, 'form');
}
}

View File

@ -1,16 +1,7 @@
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';
@ -108,13 +99,14 @@ export class NgFormModel extends ControlContainer implements Form,
directives: NgControl[] = [];
ngSubmit = new EventEmitter();
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: 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]);

View File

@ -1,26 +1,11 @@
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 =
@ -90,7 +75,9 @@ export class NgModel extends NgControl implements OnChanges {
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;

View File

@ -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 {

View File

@ -1,21 +1,5 @@
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';
@ -98,7 +82,8 @@ export class RadioControlValueAccessor implements ControlValueAccessor,
onChange = () => {};
onTouched = () => {};
constructor(private _renderer: Renderer, private _elementRef: ElementRef,
constructor(
private _renderer: Renderer, private _elementRef: ElementRef,
private _registry: RadioControlRegistry, private _injector: Injector) {}
ngOnInit(): void {

View File

@ -1,23 +1,6 @@
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';
@ -26,12 +9,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];
}
/**
@ -98,7 +81,8 @@ export class SelectControlValueAccessor implements ControlValueAccessor {
export class NgSelectOption implements OnDestroy {
id: string;
constructor(private _element: ElementRef, private _renderer: Renderer,
constructor(
private _element: ElementRef, private _renderer: Renderer,
@Optional() @Host() private _select: SelectControlValueAccessor) {
if (isPresent(this._select)) this.id = this._select._registerOption();
}

View File

@ -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(dir: NgControl,
if (hasConstructor(v, DefaultValueAccessor)) {
defaultAccessor = v;
} else if (hasConstructor(v, CheckboxControlValueAccessor) ||
hasConstructor(v, NumberValueAccessor) ||
} 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(dir: NgControl,
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;
}

View File

@ -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);
}

View File

@ -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,15 +76,16 @@ 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,
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);

View File

@ -7,18 +7,18 @@ 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;
@ -28,12 +28,11 @@ 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) => {
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) {
@ -114,8 +113,8 @@ export abstract class AbstractControl {
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;
@ -271,8 +270,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});
@ -335,9 +334,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();
@ -450,7 +449,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,
constructor(
public controls: AbstractControl[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._initObservables();

View File

@ -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,8 +45,8 @@ 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} :
return isBlank(control.value) || (isString(control.value) && control.value == '') ?
{'required': true} :
null;
}
@ -58,7 +58,7 @@ 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}} :
{'minlength': {'requiredLength': minLength, 'actualLength': v.length}} :
null;
};
}
@ -71,7 +71,7 @@ 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}} :
{'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));
}

View File

@ -1,13 +1,6 @@
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';

View File

@ -23,16 +23,6 @@ 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
]);

View File

@ -1,13 +1,4 @@
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';

View File

@ -1,10 +1,4 @@
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';

View File

@ -1,13 +1,4 @@
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';
@ -25,7 +16,8 @@ var _re = RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$');
@Injectable()
export class NumberPipe {
/** @internal */
static _format(value: number, style: NumberFormatStyle, digits: string, currency: string = null,
static _format(
value: number, style: NumberFormatStyle, digits: string, currency: string = null,
currencyAsSymbol: boolean = false): string {
if (isBlank(value)) return null;
if (!isNumber(value)) {
@ -147,7 +139,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);
}
}

View File

@ -1,11 +1,4 @@
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';

View File

@ -2,34 +2,10 @@ 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(
@ -50,7 +26,8 @@ class ProtoViewVisitor implements TemplateAstVisitor {
eventRecords: BindingRecord[] = [];
directiveRecords: DirectiveRecord[] = [];
constructor(public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[],
constructor(
public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[],
public strategy: ChangeDetectionStrategy) {
this.viewIndex = allVisitors.length;
allVisitors.push(this);
@ -96,8 +73,7 @@ class ProtoViewVisitor implements TemplateAstVisitor {
}
visitEvent(ast: BoundEventAst, directiveRecord: DirectiveRecord): any {
var bindingRecord =
isPresent(directiveRecord) ?
var bindingRecord = isPresent(directiveRecord) ?
BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) :
BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1);
this.eventRecords.push(bindingRecord);
@ -109,23 +85,19 @@ class ProtoViewVisitor implements TemplateAstVisitor {
var dirIndex = isPresent(directiveRecord) ? directiveRecord.directiveIndex : null;
var bindingRecord;
if (ast.type === PropertyBindingType.Property) {
bindingRecord =
isPresent(dirIndex) ?
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 = 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 = 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 = isPresent(dirIndex) ?
BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) :
BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit);
}
@ -195,7 +167,8 @@ class ProtoViewVisitor implements TemplateAstVisitor {
}
function createChangeDefinitions(pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata,
function createChangeDefinitions(
pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata,
genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] {
var pvVariableNames = _collectNestedProtoViewsVariableNames(pvVisitors);
return pvVisitors.map(pvVisitor => {

View File

@ -1,8 +1,6 @@
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';
@ -10,21 +8,16 @@ 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,
@ -45,12 +38,13 @@ var CONSTANTS_MODULE =
export class ChangeDetectionCompiler {
constructor(private _genConfig: ChangeDetectorGenConfig) {}
compileComponentRuntime(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
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 {
@ -58,7 +52,8 @@ export class ChangeDetectionCompiler {
return () => proto.instantiate();
}
compileComponentCodeGen(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
compileComponentCodeGen(
componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
parsedTemplate: TemplateAst[]): SourceExpressions {
var changeDetectorDefinitions =
createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate);

View File

@ -1,10 +1,6 @@
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';
@ -37,22 +33,11 @@ function _createChangeDetectorGenConfig() {
* 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,
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
]);

View File

@ -1,65 +1,9 @@
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,
@ -94,35 +38,37 @@ 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) + ']';
}
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);
}
}
@ -248,7 +194,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;
@ -265,16 +211,17 @@ 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);
@ -354,8 +301,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;
}
@ -392,8 +339,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;
}
@ -412,7 +359,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();
@ -442,8 +389,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;
}
@ -469,7 +416,8 @@ export class CssScanner {
scanCharacter(): CssToken {
var start = this.index;
var startingColumn = this.column;
if (this.assertCondition(isValidCssCharacter(this.peek, this._currentMode),
if (this.assertCondition(
isValidCssCharacter(this.peek, this._currentMode),
charStr(this.peek) + ' is not a valid CSS character')) {
return null;
}

View File

@ -1,40 +1,10 @@
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,
@ -60,7 +30,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++) {
@ -205,7 +175,8 @@ export class CssParser {
var token = this._scan();
this._assertCondition(token.type == CssTokenType.AtKeyword,
this._assertCondition(
token.type == CssTokenType.AtKeyword,
`The CSS Rule ${token.strValue} is not a valid [@] rule.`, token);
var block, type = this._resolveBlockType(token);
@ -245,10 +216,11 @@ export class CssParser {
default:
var listOfTokens = [];
this._scanner.setMode(CssLexerMode.ALL);
this._error(generateErrorMessage(
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),
`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]))
@ -403,7 +375,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, '('));
@ -453,7 +425,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)) {
@ -493,8 +465,8 @@ 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`,
generateErrorMessage(
this._scanner.input, `The CSS key/value definition did not end with a semicolon`,
previous.strValue, previous.index, previous.line, previous.column),
previous);
}
@ -592,7 +564,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
@ -608,8 +580,9 @@ 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`,
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);
}
@ -629,8 +602,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);
}
}
@ -657,7 +630,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) {
@ -669,10 +642,11 @@ 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); }
}
@ -692,7 +666,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); }
@ -707,7 +681,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); }
}
@ -723,12 +697,13 @@ export class CssStyleSheetAST extends CssAST {
}
export class CssParseError extends ParseError {
static create(file: ParseSourceFile, offset: number, line: number, col: number, length: number,
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); }

View File

@ -1,23 +1,7 @@
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';
@ -401,8 +385,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,
@ -416,9 +400,9 @@ 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}: {
static create(
{type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs,
host, lifecycleHooks, providers, viewProviders, queries, viewQueries, template}: {
type?: CompileTypeMetadata,
isComponent?: boolean,
dynamicLoadable?: boolean,
@ -508,9 +492,10 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType {
queries: CompileQueryMetadata[];
viewQueries: CompileQueryMetadata[];
template: CompileTemplateMetadata;
constructor({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs,
outputs, hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers,
viewProviders, queries, viewQueries, template}: {
constructor(
{type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs,
hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers, viewProviders,
queries, viewQueries, template}: {
type?: CompileTypeMetadata,
isComponent?: boolean,
dynamicLoadable?: boolean,
@ -606,8 +591,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({
@ -638,8 +623,9 @@ 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);

View File

@ -18,7 +18,8 @@ export class HtmlAttrAst implements HtmlAst {
}
export class HtmlElementAst implements HtmlAst {
constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
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); }

View File

@ -1,11 +1,4 @@
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';
@ -29,8 +22,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 {
@ -191,8 +184,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;
@ -239,8 +232,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));
}
}
@ -335,12 +328,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();

View File

@ -1,13 +1,4 @@
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';
@ -35,8 +26,9 @@ 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));
}
}
@ -63,8 +55,8 @@ 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 ||
} 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());
@ -174,8 +166,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);
@ -192,12 +184,12 @@ class TreeBuilder {
this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
if (getHtmlTagDefinition(fullName).isVoid) {
this.errors.push(
HtmlTreeError.create(fullName, endTagToken.sourceSpan,
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]}"`));
}
}
@ -242,8 +234,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)) {

View File

@ -1,10 +1,4 @@
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
@ -281,8 +275,9 @@ export class HtmlTagDefinition {
public isVoid: boolean;
public ignoreFirstLf: boolean;
constructor({closedByChildren, requiredParents, implicitNamespacePrefix, contentType,
closedByParent, isVoid, ignoreFirstLf}: {
constructor(
{closedByChildren, requiredParents, implicitNamespacePrefix, contentType, closedByParent,
isVoid, ignoreFirstLf}: {
closedByChildren?: string[],
closedByParent?: boolean,
requiredParents?: string[],
@ -342,32 +337,9 @@ 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
}),

View File

@ -1,21 +1,8 @@
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';
@ -50,8 +37,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 {
@ -115,8 +102,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 => {
@ -142,8 +129,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}]`;

View File

@ -1,5 +1,6 @@
export class ParseLocation {
constructor(public file: ParseSourceFile, public offset: number, public line: number,
constructor(
public file: ParseSourceFile, public offset: number, public line: number,
public col: number) {}
toString(): string { return `${this.file.url}@${this.line}:${this.col}`; }
@ -33,7 +34,7 @@ export abstract class ParseError {
while (ctxLen < 100 && ctxStart > 0) {
ctxStart--;
ctxLen++;
if (source[ctxStart] == "\n") {
if (source[ctxStart] == '\n') {
if (++ctxLines == 3) {
break;
}
@ -45,7 +46,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;
}

View File

@ -1,54 +1,13 @@
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(
@ -74,19 +33,20 @@ 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 = [];
@ -97,26 +57,29 @@ export class ProtoViewCompiler {
}
export class CompileProtoViews<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> {
constructor(public declarations: STATEMENT[],
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[][],
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;
}
@ -124,17 +87,16 @@ function visitAndReturnContext(visitor: TemplateAstVisitor, asts: TemplateAst[],
abstract class ProtoViewFactory<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> {
constructor(public component: CompileDirectiveMetadata) {}
abstract createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType,
templateVariableBindings: string[][],
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[],
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;
@ -145,8 +107,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;
@ -157,7 +119,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,
constructor(
public resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata,
public pipes: CompilePipeMetadata[]) {
super(component);
}
@ -166,8 +129,8 @@ class CodeGenProtoViewFactory extends ProtoViewFactory<Expression, Expression, S
return `appProtoView${this._nextVarId++}_${this.component.type.name}${embeddedTemplateIndex}`;
}
createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType,
templateVariableBindings: string[][],
createAppProtoView(
embeddedTemplateIndex: number, viewType: ViewType, templateVariableBindings: string[][],
targetStatements: Statement[]): Expression {
var protoViewVarName = this._nextProtoViewVar(embeddedTemplateIndex);
var viewTypeExpr = codeGenViewType(viewType);
@ -180,9 +143,9 @@ class CodeGenProtoViewFactory extends ProtoViewFactory<Expression, Expression, S
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},
@ -198,24 +161,27 @@ class CodeGenProtoViewFactory extends ProtoViewFactory<Expression, Expression, S
}
class RuntimeProtoViewFactory extends ProtoViewFactory<AppProtoView, AppProtoElement, any> {
constructor(public metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata,
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,
return AppProtoElement.create(
this.metadataCache, boundElementIndex, attrs,
directives.map(dirMeta => dirMeta.type.runtime),
keyValueArrayToStringMap(variableNameAndValues));
}
@ -226,12 +192,13 @@ 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>,
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) => {
@ -262,15 +229,17 @@ 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;
}
@ -280,8 +249,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);
@ -289,19 +258,21 @@ 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,
this._addProtoElement(
true, boundElementIndex, attrNameAndValues, [], [], directives,
nestedProtoView.embeddedTemplateIndex);
return null;
}
private _addProtoElement(isBound: boolean, boundElementIndex, attrNameAndValues: string[][],
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,
@ -317,8 +288,9 @@ 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 {
@ -331,12 +303,14 @@ 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;
@ -351,7 +325,8 @@ function mergeAttributeValue(attrName: string, attrValue1: string, attrValue2: s
}
class DirectiveContext {
constructor(public index: number, public boundElementIndex: number,
constructor(
public index: number, public boundElementIndex: number,
public hostEventTargetAndNames: Map<string, BoundEventAst>,
public targetVariableNameAndValues: any[][],
public targetDirectives: CompileDirectiveMetadata[]) {}

View File

@ -1,12 +1,5 @@
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';
@ -30,7 +23,8 @@ export class RuntimeMetadataResolver {
private _anonymousTypes = new Map<Object, number>();
private _anonymousTypeIndex = 0;
constructor(private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver,
constructor(
private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver,
private _viewResolver: ViewResolver,
@Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[],
@Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {}

View File

@ -1,11 +1,5 @@
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 = '';
@ -36,7 +30,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);
};
@ -174,8 +168,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;
@ -229,8 +223,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 = [];
@ -287,8 +281,8 @@ 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 = this._matchTerminal(
terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) ||
result;
}
result = this._matchTerminal(terminalValuesMap, attrValue, cssSelector, matchedCallback) ||
@ -296,8 +290,8 @@ export class SelectorMatcher {
var partialValuesMap = this._attrValuePartialMap.get(attrName);
if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) {
result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector,
matchedCallback) ||
result = this._matchPartial(
partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) ||
result;
}
result =
@ -308,14 +302,15 @@ export class SelectorMatcher {
}
/** @internal */
_matchTerminal(map: Map<string, SelectorContext[]>, name, cssSelector: CssSelector,
_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);
}
@ -332,7 +327,8 @@ export class SelectorMatcher {
}
/** @internal */
_matchPartial(map: Map<string, SelectorMatcher>, name, cssSelector: CssSelector,
_matchPartial(
map: Map<string, SelectorMatcher>, name, cssSelector: CssSelector,
matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean {
if (isBlank(map) || isBlank(name)) {
return false;
@ -359,7 +355,8 @@ export class SelectorListContext {
export class SelectorContext {
notSelectors: CssSelector[];
constructor(public selector: CssSelector, public cbContext: any,
constructor(
public selector: CssSelector, public cbContext: any,
public listContext: SelectorListContext) {
this.notSelectors = selector.notSelectors;
}

View File

@ -1,12 +1,5 @@
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.
@ -174,8 +167,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] + '{'; });
}
/*
@ -279,8 +272,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 {
@ -339,8 +332,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();
@ -370,15 +363,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);
@ -397,7 +390,8 @@ export class ShadowCss {
for (var i = 0; i < splits.length; i++) {
var sep = splits[i];
var parts = scoped.split(sep);
scoped = parts.map(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) &&
@ -436,8 +430,7 @@ var _cssColonHostRe = RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, '
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

View File

@ -1,30 +1,6 @@
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
@ -124,8 +100,8 @@ 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) => {
conversionMap.set(
this.getStaticType(core_metadata, 'Directive'), (moduleContext, expression) => {
let p0 = this.getDecoratorParameter(moduleContext, expression, 0);
if (!isPresent(p0)) {
p0 = {};
@ -142,8 +118,8 @@ export class StaticReflector {
queries: p0['queries'],
});
});
conversionMap.set(this.getStaticType(core_metadata, 'Component'),
(moduleContext, expression) => {
conversionMap.set(
this.getStaticType(core_metadata, 'Component'), (moduleContext, expression) => {
let p0 = this.getDecoratorParameter(moduleContext, expression, 0);
if (!isPresent(p0)) {
p0 = {};
@ -172,12 +148,14 @@ export class StaticReflector {
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, '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)) {
@ -192,9 +170,10 @@ 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);
@ -203,20 +182,24 @@ 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) => {
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)) {
@ -237,10 +220,12 @@ 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'),
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)));
@ -264,8 +249,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]);
@ -273,14 +258,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) {
@ -301,8 +286,7 @@ export class StaticReflector {
for (let item of member) {
result.push({
kind: item['__symbolic'],
directives:
isPresent(item['decorators']) ?
directives: isPresent(item['decorators']) ?
(<any[]>item['decorators'])
.map(decorator => this.convertKnownDecorator(moduleContext, decorator))
.filter(d => isPresent(d)) :
@ -331,7 +315,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']) {
@ -377,7 +361,7 @@ export class StaticReflector {
return left % right;
}
return null;
case "pre":
case 'pre':
let operand = simplify(expression['operand']);
switch (expression['operator']) {
case '+':
@ -390,17 +374,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);
@ -410,7 +394,7 @@ export class StaticReflector {
return _this.getStaticType(referenceModuleName, expression['name']);
}
return _this.simplify(referenceModuleName, referenceValue);
case "call":
case 'call':
return null;
}
return null;
@ -430,7 +414,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);
}
@ -441,7 +425,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;
}

View File

@ -7,12 +7,7 @@ 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%';
@ -29,8 +24,8 @@ export class StyleCompiler {
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 {
@ -44,23 +39,24 @@ 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);
}
@ -87,8 +83,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};

View File

@ -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];

View File

@ -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,8 +50,9 @@ 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);
}
@ -61,7 +62,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,
constructor(
public name: string, public target: string, public handler: AST,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitEvent(this, context);
@ -89,11 +91,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);
}
@ -102,7 +104,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 ||
return (
this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 ||
this.directives.length > 0);
}
@ -120,7 +123,8 @@ 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[],
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 {
@ -132,7 +136,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,
constructor(
public directiveName: string, public templateName: string, public value: AST,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitDirectiveProperty(this, context);
@ -143,8 +148,8 @@ export class BoundDirectivePropertyAst implements TemplateAst {
* A directive declared on an element.
*/
export class DirectiveAst implements TemplateAst {
constructor(public directive: CompileDirectiveMetadata,
public inputs: BoundDirectivePropertyAst[],
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 {
@ -156,8 +161,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);
}
@ -209,8 +214,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);

View File

@ -1,55 +1,15 @@
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';
@ -57,14 +17,7 @@ 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);
@ -80,10 +33,10 @@ 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,
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) {}
@ -131,7 +84,8 @@ export class TemplateCompiler {
this._compileComponentRuntime(hostCacheKey, hostMeta, [compMeta], [], []);
}
return this._compiledTemplateDone.get(hostCacheKey)
.then((compiledTemplate: CompiledTemplate) =>
.then(
(compiledTemplate: CompiledTemplate) =>
new HostViewFactory(compMeta.selector, compiledTemplate.viewFactory));
}
@ -150,8 +104,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 =
@ -173,10 +127,9 @@ 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);
@ -184,7 +137,8 @@ export class TemplateCompiler {
if (isBlank(compiledTemplate)) {
compiledTemplate = new CompiledTemplate();
this._compiledTemplateCache.set(cacheKey, compiledTemplate);
done = PromiseWrapper
done =
PromiseWrapper
.all([<any>this._styleCompiler.compileComponentRuntime(compMeta.template)].concat(
uniqViewDirectives.map(dirMeta => this.normalizeDirectiveMetadata(dirMeta))))
.then((stylesAndNormalizedViewDirMetas: any[]) => {
@ -199,12 +153,10 @@ export class TemplateCompiler {
usedDirectives.components.forEach(
component => this._compileNestedComponentRuntime(
component, compilingComponentsPath, childPromises));
return PromiseWrapper.all(childPromises)
.then((_) => {
return PromiseWrapper.all(childPromises).then((_) => {
var filteredPipes = filterPipes(parsedTemplate, uniqViewPipes);
compiledTemplate.init(this._createViewFactoryRuntime(
compMeta, parsedTemplate, usedDirectives.directives, styles,
filteredPipes));
compMeta, parsedTemplate, usedDirectives.directives, styles, filteredPipes));
return compiledTemplate;
});
});
@ -213,8 +165,8 @@ export class TemplateCompiler {
return compiledTemplate;
}
private _compileNestedComponentRuntime(childComponentDir: CompileDirectiveMetadata,
parentCompilingComponentsPath: any[],
private _compileNestedComponentRuntime(
childComponentDir: CompileDirectiveMetadata, parentCompilingComponentsPath: any[],
childPromises: Promise<any>[]) {
var compilingComponentsPath = ListWrapper.clone(parentCompilingComponentsPath);
@ -225,16 +177,17 @@ 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[],
private _createViewFactoryRuntime(
compMeta: CompileDirectiveMetadata, parsedTemplate: TemplateAst[],
directives: CompileDirectiveMetadata[], styles: string[],
pipes: CompilePipeMetadata[]): Function {
if (IS_DART || !this._genConfig.useJit) {
@ -247,11 +200,14 @@ 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) {
@ -272,24 +228,23 @@ 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[],
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);
@ -308,8 +263,9 @@ 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 {
@ -348,7 +304,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 &&
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) {
@ -401,8 +358,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));

View File

@ -1,8 +1,4 @@
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';
@ -14,41 +10,35 @@ 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');

View File

@ -11,23 +11,7 @@ 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';
@ -35,15 +19,7 @@ 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';
@ -89,11 +65,13 @@ export class TemplateParseResult {
@Injectable()
export class TemplateParser {
constructor(private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry,
constructor(
private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry,
private _htmlParser: HtmlParser,
@Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {}
parse(template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[],
parse(
template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[],
templateUrl: string): TemplateAst[] {
var result = this.tryParse(template, directives, pipes, templateUrl);
if (isPresent(result.errors)) {
@ -103,7 +81,8 @@ export class TemplateParser {
return result.templateAst;
}
tryParse(template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[],
tryParse(
template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[],
templateUrl: string): TemplateParseResult {
var parseVisitor =
new TemplateParseVisitor(directives, pipes, this._exprParser, this._schemaRegistry);
@ -128,11 +107,12 @@ class TemplateParseVisitor implements HtmlAstVisitor {
ngContentCount: number = 0;
pipesByName: Map<string, CompilePipeMetadata>;
constructor(directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[],
constructor(
directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[],
private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) {
this.selectorMatcher = new SelectorMatcher();
ListWrapper.forEachWithIndex(directives,
(directive: CompileDirectiveMetadata, index: number) => {
ListWrapper.forEachWithIndex(
directives, (directive: CompileDirectiveMetadata, index: number) => {
var selector = CssSelector.parse(directive.selector);
this.selectorMatcher.addSelectables(selector, directive);
this.directivesIndex.set(directive, index);
@ -275,8 +255,9 @@ 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) ?
@ -296,21 +277,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);
@ -319,18 +300,19 @@ 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;
@ -346,8 +328,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);
@ -358,7 +340,8 @@ class TemplateParseVisitor implements HtmlAstVisitor {
return false;
}
private _parseAttr(attr: HtmlAttrAst, targetMatchableAttrs: string[][],
private _parseAttr(
attr: HtmlAttrAst, targetMatchableAttrs: string[][],
targetProps: BoundElementOrDirectiveProperty[], targetEvents: BoundEventAst[],
targetVars: VariableAst[]): boolean {
var attrName = this._normalizeAttributeName(attr.name);
@ -368,8 +351,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"
@ -377,32 +360,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);
@ -414,23 +397,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[][],
private _parsePropertyInterpolation(
name: string, value: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][],
targetProps: BoundElementOrDirectiveProperty[]): boolean {
var expr = this._parseInterpolation(value, sourceSpan);
if (isPresent(expr)) {
@ -440,20 +424,22 @@ 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,
private _parseAssignmentEvent(
name: string, expression: string, sourceSpan: ParseSourceSpan,
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
this._parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs,
targetEvents);
this._parseEvent(
`${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents);
}
private _parseEvent(name: string, expression: string, sourceSpan: ParseSourceSpan,
private _parseEvent(
name: string, expression: string, sourceSpan: ParseSourceSpan,
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
// long format: 'target: eventName'
var parts = splitAtColon(name, [null, name]);
@ -466,22 +452,23 @@ class TemplateParseVisitor implements HtmlAstVisitor {
// so don't add the event name to the matchableAttrs
}
private _parseLiteralAttr(name: string, value: string, sourceSpan: ParseSourceSpan,
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) => {
ListWrapper.sort(
directives, (dir1: CompileDirectiveMetadata, dir2: CompileDirectiveMetadata) => {
var dir1Comp = dir1.isComponent;
var dir2Comp = dir2.isComponent;
if (dir1Comp && !dir2Comp) {
@ -495,17 +482,17 @@ class TemplateParseVisitor implements HtmlAstVisitor {
return directives;
}
private _createDirectiveAsts(elementName: string, directives: CompileDirectiveMetadata[],
props: BoundElementOrDirectiveProperty[],
possibleExportAsVars: VariableAst[],
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 = [];
@ -516,20 +503,20 @@ 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,
private _createDirectiveHostPropertyAsts(
elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan,
targetPropertyAsts: BoundElementPropertyAst[]) {
if (isPresent(hostProps)) {
StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => {
@ -540,8 +527,8 @@ class TemplateParseVisitor implements HtmlAstVisitor {
}
}
private _createDirectiveHostEventAsts(hostListeners: {[key: string]: string},
sourceSpan: ParseSourceSpan,
private _createDirectiveHostEventAsts(
hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan,
targetEventAsts: BoundEventAst[]) {
if (isPresent(hostListeners)) {
StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => {
@ -550,8 +537,8 @@ class TemplateParseVisitor implements HtmlAstVisitor {
}
}
private _createDirectivePropertyAsts(directiveProperties: {[key: string]: string},
boundProps: BoundElementOrDirectiveProperty[],
private _createDirectivePropertyAsts(
directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[],
targetBoundDirectiveProps: BoundDirectivePropertyAst[]) {
if (isPresent(directiveProperties)) {
var boundPropsByName = new Map<string, BoundElementOrDirectiveProperty>();
@ -575,7 +562,8 @@ class TemplateParseVisitor implements HtmlAstVisitor {
}
}
private _createElementPropertyAsts(elementName: string, props: BoundElementOrDirectiveProperty[],
private _createElementPropertyAsts(
elementName: string, props: BoundElementOrDirectiveProperty[],
directives: DirectiveAst[]): BoundElementPropertyAst[] {
var boundElementProps: BoundElementPropertyAst[] = [];
var boundDirectivePropsIndex = new Map<string, BoundDirectivePropertyAst>();
@ -586,14 +574,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,
private _createElementPropertyAst(
elementName: string, name: string, ast: AST,
sourceSpan: ParseSourceSpan): BoundElementPropertyAst {
var unit = null;
var bindingType;
@ -652,13 +641,13 @@ class TemplateParseVisitor implements HtmlAstVisitor {
}
}
private _assertNoComponentsNorElementBindingsOnTemplate(directives: DirectiveAst[],
elementProps: BoundElementPropertyAst[],
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(
@ -667,12 +656,13 @@ 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)) {
@ -700,8 +690,9 @@ 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 {
@ -714,7 +705,8 @@ class NonBindableVisitor implements HtmlAstVisitor {
}
class BoundElementOrDirectiveProperty {
constructor(public name: string, public expression: AST, public isLiteral: boolean,
constructor(
public name: string, public expression: AST, public isLiteral: boolean,
public sourceSpan: ParseSourceSpan) {}
}
@ -740,8 +732,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 = [];

View File

@ -59,7 +59,8 @@ export enum PreparsedElementType {
}
export class PreparsedElement {
constructor(public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string,
constructor(
public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string,
public nonBindable: boolean, public projectAs: string) {}
}

View File

@ -1,11 +1,5 @@
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';
@ -21,7 +15,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.
@ -40,7 +34,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, '/') + '/';
}
}
@ -61,8 +55,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;
}
@ -73,7 +67,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:
@ -96,9 +90,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)) {
@ -196,8 +190,8 @@ function _buildFromEncodedParts(opt_scheme?: string, opt_userInfo?: string, opt_
* @type {!RegExp}
* @internal
*/
var _splitRe =
RegExpWrapper.create('^' +
var _splitRe = RegExpWrapper.create(
'^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
// used by other URL parts such as :,
@ -304,9 +298,10 @@ 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]);
}
/**

View File

@ -1,11 +1,4 @@
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;
@ -17,13 +10,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 {

View File

@ -1,65 +1,18 @@
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,
@ -73,18 +26,17 @@ export const VIEW_JIT_IMPORTS = CONST_EXPR({
export class ViewCompiler {
constructor() {}
compileComponentRuntime(component: CompileDirectiveMetadata, template: TemplateAst[],
styles: Array<string | any[]>,
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);
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,
compileComponentCodeGen(
component: CompileDirectiveMetadata, template: TemplateAst[], styles: SourceExpression,
protoViews: CompileProtoView<Expression, Expression>[],
changeDetectorFactoryExpressions: SourceExpressions,
componentViewFactory: Function): SourceExpression {
@ -92,55 +44,59 @@ export class ViewCompiler {
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,
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,
createTemplateAnchor(renderer: EXPRESSION, parent: EXPRESSION, targetStatements: STATEMENT[]):
EXPRESSION;
createGlobalEventListener(
renderer: EXPRESSION, view: EXPRESSION, boundElementIndex: number, eventAst: BoundEventAst,
targetStatements: STATEMENT[]): EXPRESSION;
createTemplateAnchor(renderer: EXPRESSION, parent: EXPRESSION,
targetStatements: STATEMENT[]): EXPRESSION;
createGlobalEventListener(renderer: EXPRESSION, view: EXPRESSION, boundElementIndex: number,
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[][],
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,
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,
constructor(
public component: CompileDirectiveMetadata, public styles: SourceExpression,
public protoViews: CompileProtoView<Expression, Expression>[],
public changeDetectorExpressions: SourceExpressions,
public componentViewFactory: Function) {}
public changeDetectorExpressions: SourceExpressions, public componentViewFactory: Function) {}
private _nextVar(prefix: string): string {
return `${prefix}${this._nextVarId++}_${this.component.type.name}`;
@ -154,8 +110,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)});`;
@ -163,8 +119,9 @@ 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)) {
@ -180,7 +137,8 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> {
return new Expression(varName);
}
createTemplateAnchor(renderer: Expression, parentRenderNode: Expression,
createTemplateAnchor(
renderer: Expression, parentRenderNode: Expression,
targetStatements: Statement[]): Expression {
var varName = this._nextRenderVar();
var valueExpr =
@ -189,8 +147,9 @@ 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(
@ -198,9 +157,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(
@ -208,15 +167,16 @@ 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},
@ -225,9 +185,9 @@ class CodeGenViewFactory implements ViewFactory<Expression, Statement> {
return new Expression(appVar);
}
createAndSetComponentView(renderer: Expression, viewManager: Expression, view: Expression,
appEl: Expression, component: CompileDirectiveMetadata,
contentNodesByNgContentIndex: Expression[][],
createAndSetComponentView(
renderer: Expression, viewManager: Expression, view: Expression, appEl: Expression,
component: CompileDirectiveMetadata, contentNodesByNgContentIndex: Expression[][],
targetStatements: Statement[]) {
var codeGenContentNodes;
if (this.component.type.isHost) {
@ -244,13 +204,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,
createViewFactory(
asts: TemplateAst[], embeddedTemplateIndex: number,
targetStatements: Statement[]): Expression {
var compileProtoView = this.protoViews[embeddedTemplateIndex];
var isHostView = this.component.type.isHost;
@ -268,13 +229,8 @@ 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`;
@ -316,7 +272,8 @@ ${codeGenFnHeader(factoryArgs, viewFactoryName)}{
}
class RuntimeViewFactory implements ViewFactory<any, any> {
constructor(public component: CompileDirectiveMetadata, public styles: Array<string | any[]>,
constructor(
public component: CompileDirectiveMetadata, public styles: Array<string|any[]>,
public protoViews: CompileProtoView<AppProtoView, AppProtoElement>[],
public changeDetectorFactories: Function[], public componentViewFactory: Function) {}
@ -324,7 +281,8 @@ class RuntimeViewFactory implements ViewFactory<any, any> {
return renderer.createText(parent, text);
}
createElement(renderer: Renderer, parent: any, name: string, rootSelector: string,
createElement(
renderer: Renderer, parent: any, name: string, rootSelector: string,
targetStatements: any[]): any {
var el;
if (isPresent(rootSelector)) {
@ -339,35 +297,37 @@ 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,
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[]>>,
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) {
@ -389,8 +349,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;
@ -398,7 +358,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,
checkSlotCount(
this.component.type.name, this.component.template.ngContentSelectors.length,
projectableNodes);
var renderer;
if (embeddedTemplateIndex === 0) {
@ -411,15 +372,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,
view.init(
flattenArray(visitor.rootNodesOrAppElements, []), visitor.renderNodes,
visitor.appDisposables, visitor.appElements);
return view;
};
@ -429,7 +391,8 @@ class RuntimeViewFactory implements ViewFactory<any, any> {
class ParentElement<EXPRESSION> {
public contentNodesByNgContentIndex: Array<EXPRESSION>[];
constructor(public renderNode: EXPRESSION, public appEl: EXPRESSION,
constructor(
public renderNode: EXPRESSION, public appEl: EXPRESSION,
public component: CompileDirectiveMetadata) {
if (isPresent(component)) {
this.contentNodesByNgContentIndex =
@ -458,13 +421,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,
private _addRenderNode(
renderNode: EXPRESSION, appEl: EXPRESSION, ngContentIndex: number,
parent: ParentElement<EXPRESSION>) {
this.renderNodes.push(renderNode);
if (isPresent(parent.component)) {
@ -476,8 +440,8 @@ 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 :
@ -505,8 +469,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);
}
@ -529,22 +493,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);
@ -553,9 +517,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;
}
@ -569,8 +533,9 @@ 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;
@ -585,15 +550,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}`;
}

View File

@ -1,40 +1,26 @@
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,
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_})
]);

View File

@ -1,33 +1,12 @@
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';
@ -40,15 +19,14 @@ import {ElementRef_} from 'angular2/src/core/linker/element_ref';
function _componentProviders(appComponentType: Type): Array<Type|Provider|any[]> {
return [
provide(APP_COMPONENT, {useValue: appComponentType}),
provide(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); })
return dynamicComponentLoader
.loadAsRoot(appComponentType, null, injector, () => { appRef._unloadComponent(ref); })
.then((componentRef) => {
ref = componentRef;
var testability = injector.getOptional(Testability);
@ -61,8 +39,7 @@ function _componentProviders(appComponentType: Type): Array<Type | Provider | an
},
deps: [DynamicComponentLoader, ApplicationRef, Injector]
}),
provide(appComponentType,
{
provide(appComponentType, {
useFactory: (p: Promise<any>) => p.then(ref => ref.instance),
deps: [APP_COMPONENT_REF_PROMISE]
}),
@ -99,7 +76,7 @@ export function platform(providers?: Array<Type | Provider | any[]>): PlatformRe
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);
@ -189,7 +166,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[]>>,
abstract asyncApplication(
bindingFn: (zone: NgZone) => Promise<Array<Type|Provider|any[]>>,
providers?: Array<Type|Provider|any[]>): Promise<ApplicationRef>;
/**
@ -214,12 +192,13 @@ export class PlatformRef_ extends PlatformRef {
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[]>>,
asyncApplication(
bindingFn: (zone: NgZone) => Promise<Array<Type|Provider|any[]>>,
additionalProviders?: Array<Type|Provider|any[]>): Promise<ApplicationRef> {
var zone = createNgZone();
var completer = PromiseWrapper.completer<ApplicationRef>();
@ -239,9 +218,8 @@ 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(() => {
@ -338,8 +316,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}.
@ -396,8 +374,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();
}
@ -416,8 +394,7 @@ 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);
@ -449,7 +426,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;
});
@ -481,7 +458,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();

View File

@ -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'));

View File

@ -4,24 +4,4 @@
* 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';

View File

@ -5,13 +5,7 @@ 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';
@ -21,8 +15,9 @@ 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 {
@ -44,7 +39,8 @@ export class AbstractChangeDetector<T> implements ChangeDetector {
dispatcher: ChangeDispatcher;
constructor(public id: string, public numberOfPropertyProtoRecords: number,
constructor(
public id: string, public numberOfPropertyProtoRecords: number,
public bindingTargets: BindingTarget[], public directiveIndices: DirectiveIndex[],
public strategy: ChangeDetectionStrategy) {
this.ref = new ChangeDetectorRef_(this);
@ -79,8 +75,8 @@ 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) :
new EventEvaluationErrorContext(
c.element, c.componentElement, c.context, c.locals, c.injector) :
null;
throw new EventEvaluationError(eventName, e, e.stack, context);
}
@ -271,7 +267,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,
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);
@ -284,8 +281,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); }

View File

@ -3,21 +3,22 @@ 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; }
@ -33,7 +34,8 @@ export class BindingTarget {
}
export class BindingRecord {
constructor(public mode: string, public target: BindingTarget, public implicitReceiver: any,
constructor(
public mode: string, public target: BindingTarget, public implicitReceiver: any,
public ast: AST, public setter: SetterFn, public lifecycleEvent: string,
public directiveRecord: DirectiveRecord) {}
@ -48,21 +50,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,
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());
@ -71,14 +74,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);
}
@ -88,39 +91,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);
}
@ -138,8 +141,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());

View File

@ -1,46 +1,19 @@
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';
@ -48,12 +21,7 @@ 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';

View File

@ -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,9 +69,10 @@ 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 {
@ -112,8 +113,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};`;
}
@ -126,7 +127,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;
@ -183,7 +184,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();`;
}
@ -225,7 +226,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}
@ -240,7 +241,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}
@ -282,7 +283,7 @@ export class ChangeDetectorJITGenerator {
codes.push(code);
}
return codes.join("\n");
return codes.join('\n');
}
/** @internal */
@ -315,11 +316,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}'`);
@ -329,7 +330,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);
@ -389,7 +390,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 {
@ -407,10 +408,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()) {
@ -446,7 +447,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});`;
}
@ -461,7 +462,7 @@ export class ChangeDetectorJITGenerator {
/** @internal */
_maybeGenLastInDirective(r: ProtoRecord): string {
if (!r.lastInDirective) return "";
if (!r.lastInDirective) return '';
return `
${CHANGES_LOCAL} = null;
${this._genNotifyOnPushDetectors(r)}
@ -490,7 +491,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();

View File

@ -1,20 +1,6 @@
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';
@ -52,10 +38,7 @@ 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)
];
@ -183,7 +166,8 @@ export class ChangeDetectionUtil {
}
}
static bindingTarget(mode: string, elementIndex: number, name: string, unit: string,
static bindingTarget(
mode: string, elementIndex: number, name: string, unit: string,
debug: string): BindingTarget {
return new BindingTarget(mode, elementIndex, name, unit, debug);
}
@ -198,8 +182,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 {

View File

@ -90,7 +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[],
function _mayBeAddRecord(
record: ProtoRecord, dstRecords: ProtoRecord[], excludedIdxs: number[],
excluded: boolean): ProtoRecord {
let match = _findFirstMatch(record, dstRecords, excludedIdxs);
@ -118,8 +119,8 @@ function _mayBeAddRecord(record: ProtoRecord, dstRecords: ProtoRecord[], exclude
/**
* 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 &&
@ -135,16 +136,16 @@ function _findFirstMatch(record: ProtoRecord, dstRecords: ProtoRecord[],
* - 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,
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);
}
@ -158,9 +159,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 {

View File

@ -10,7 +10,8 @@ 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,
constructor(
private _names: CodegenNameUtil, private _utilName: string,
private _changeDetectorStateName: string) {}
/**
@ -18,8 +19,8 @@ export class CodegenLogicUtil {
* 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());
}
/**
@ -27,16 +28,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(", ");
var argString = protoRec.args.map(arg => getLocalName(arg)).join(', ');
var rhs: string;
switch (protoRec.mode) {
@ -108,12 +109,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(", ")}]`;
@ -165,7 +166,7 @@ export class CodegenLogicUtil {
res.unshift(`${statementStart} = new Array(${outputCount});`);
}
}
return res.join("\n");
return res.join('\n');
}
genDirectivesOnDestroy(directiveRecords: DirectiveRecord[]): string {
@ -177,7 +178,7 @@ export class CodegenLogicUtil {
res.push(`${dirVarName}.ngOnDestroy();`);
}
}
return res.join("\n");
return res.join('\n');
}
private _genEventHandler(boundElementIndex: number, eventName: string): string {
@ -199,7 +200,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[] {

View File

@ -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,7 +47,8 @@ export class CodegenNameUtil {
/** @internal */
_sanitizedEventNames = new Map<EventBinding, string[]>();
constructor(private _records: ProtoRecord[], private _eventBindings: EventBinding[],
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;
@ -132,7 +133,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; }

View File

@ -68,25 +68,20 @@ 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;
}

View File

@ -2,14 +2,7 @@ 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';
@ -218,8 +211,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;
@ -284,8 +277,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) {
@ -333,8 +326,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);
}
@ -358,8 +351,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);
@ -367,8 +360,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) {
@ -385,8 +378,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);
@ -527,10 +520,12 @@ 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';
}
}
@ -563,10 +558,9 @@ 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) + ']';
}
}

View File

@ -318,9 +318,11 @@ 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 */

View File

@ -21,9 +21,10 @@ export class DirectiveRecord {
// array of [emitter property name, eventName]
outputs: string[][];
constructor({directiveIndex, callAfterContentInit, callAfterContentChecked, callAfterViewInit,
callAfterViewChecked, callOnChanges, callDoCheck, callOnInit, callOnDestroy,
changeDetection, outputs}: {
constructor(
{directiveIndex, callAfterContentInit, callAfterContentChecked, callAfterViewInit,
callAfterViewChecked, callOnChanges, callDoCheck, callOnInit, callOnDestroy, changeDetection,
outputs}: {
directiveIndex?: DirectiveIndex,
callAfterContentInit?: boolean,
callAfterContentChecked?: boolean,

View File

@ -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,8 +38,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
handleEventInternal(eventName: string, elIndex: number, locals: Locals): boolean {
var preventDefault = false;
this._matchingEventBindings(eventName, elIndex)
.forEach(rec => {
this._matchingEventBindings(eventName, elIndex).forEach(rec => {
var res = this._processEventBinding(rec, locals);
if (res === false) {
preventDefault = true;
@ -72,7 +71,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 {
@ -90,7 +89,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 */
@ -179,12 +178,13 @@ 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 &&
} 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;
@ -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:

View File

@ -2,6 +2,7 @@ import {DirectiveIndex} from './directive_record';
import {ProtoRecord} from './proto_record';
export class EventBinding {
constructor(public eventName: string, public elIndex: number, public dirIndex: DirectiveIndex,
constructor(
public eventName: string, public elIndex: number, public dirIndex: DirectiveIndex,
public records: ProtoRecord[]) {}
}

View File

@ -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,7 +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. ` +
super(
`Expression '${exp}' has changed after it was checked. ` +
`Previous value: '${oldValue}'. Current value: '${currValue}'`);
}
}
@ -107,6 +108,7 @@ 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) {}
}

View File

@ -5,8 +5,9 @@ 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 {
@ -44,13 +45,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) {}
}

View File

@ -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();
}
}

View File

@ -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,7 +138,8 @@ export class ASTWithSource extends AST {
}
export class TemplateBinding {
constructor(public key: string, public keyIsVar: boolean, public name: string,
constructor(
public key: string, public keyIsVar: boolean, public name: string,
public expression: ASTWithSource) {}
}
@ -283,8 +284,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 {

Some files were not shown because too many files have changed in this diff Show More