[polymer] switch comment style

R=sigmund@google.com

Review URL: https://codereview.chromium.org//180373003

git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart@33046 260f80e4-7a28-3924-810f-c04153c831b5
This commit is contained in:
jmesserly@google.com 2014-02-25 23:43:45 +00:00
parent a2c2718e9f
commit ff3aa2f569
37 changed files with 692 additions and 900 deletions

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.deploy2_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.deploy3_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.deploy_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works during development. */
/// Tests how canonicalization works during development.
library canonicalization.dev2_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works during development. */
/// Tests how canonicalization works during development.
library canonicalization.dev3_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works during development. */
/// Tests how canonicalization works during development.
library canonicalization.dev_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests canonicalization at deployment time from a subdir. */
/// Tests canonicalization at deployment time from a subdir.
library canonicalization.dir.deploy2_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests canonicalization at deployment time from a subdir. */
/// Tests canonicalization at deployment time from a subdir.
library canonicalization.dir.deploy_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests canonicalization during development from a subdir. */
/// Tests canonicalization during development from a subdir.
library canonicalization.dir.dev2_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests canonicalization during development from a subdir. */
/// Tests canonicalization during development from a subdir.
library canonicalization.dir.dev_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.dev3_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.bad_lib_import_negative;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.dev3_test;
import 'package:unittest/unittest.dart';

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests how canonicalization works when using the deployed app. */
/// Tests how canonicalization works when using the deployed app.
library canonicalization.bad_lib_import_negative;
import 'package:unittest/unittest.dart';

View file

@ -7,9 +7,7 @@ import 'package:polymer/polymer.dart';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';
/**
* This test runs the news example and checks the state of the initial page.
*/
/// This test runs the news example and checks the state of the initial page.
main() {
initPolymer();
useHtmlConfiguration();

View file

@ -2,83 +2,81 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Common logic to make it easy to run the polymer linter and deploy tool.
*
* The functions in this library are designed to make it easier to create
* `build.dart` files. A `build.dart` file is a Dart script that can be invoked
* from the command line, but that can also invoked automatically by the Dart
* Editor whenever a file in your project changes or when selecting some menu
* options, such as 'Reanalyze Sources'.
*
* To work correctly, place the `build.dart` in the root of your project (where
* pubspec.yaml lives). The file must be named exactly `build.dart`.
*
* It's quite likely that in the near future `build.dart` will be replaced with
* something else. For example, `pub deploy` will deal with deploying
* applications automatically, and the Dart Editor might provide other
* mechanisms to hook linters.
*
* There are three important functions exposed by this library [build], [lint],
* and [deploy]. The following examples show common uses of these functions when
* writing a `build.dart` file.
*
* **Example 1**: Uses build.dart to run the linter tool.
*
* import 'dart:io';
* import 'package:polymer/builder.dart';
*
* main() {
* lint();
* }
*
* **Example 2**: Runs the linter and creates a deployable version of the app
* every time.
*
* import 'dart:io';
* import 'package:polymer/builder.dart';
*
* main() {
* deploy(); // deploy also calls the linter internally.
* }
*
* **Example 3**: Always run the linter, but conditionally build a deployable
* version. See [parseOptions] for a description of options parsed automatically
* by this helper library.
*
* import 'dart:io';
* import 'package:polymer/builder.dart';
*
* main(args) {
* var options = parseOptions(args);
* if (options.forceDeploy) {
* deploy();
* } else {
* lint();
* }
* }
*
* **Example 4**: Same as above, but uses [build] (which internally calls either
* [lint] or [deploy]).
*
* import 'dart:io';
* import 'package:polymer/builder.dart';
*
* main(args) {
* build(options: parseOptions(args));
* }
*
* **Example 5**: Like the previous example, but indicates to the linter and
* deploy tool which files are actually used as entry point files. See the
* documentation of [build] below for more details.
*
* import 'dart:io';
* import 'package:polymer/builder.dart';
*
* main(args) {
* build(entryPoints: ['web/index.html'], options: parseOptions(args));
* }
*/
/// Common logic to make it easy to run the polymer linter and deploy tool.
///
/// The functions in this library are designed to make it easier to create
/// `build.dart` files. A `build.dart` file is a Dart script that can be invoked
/// from the command line, but that can also invoked automatically by the Dart
/// Editor whenever a file in your project changes or when selecting some menu
/// options, such as 'Reanalyze Sources'.
///
/// To work correctly, place the `build.dart` in the root of your project (where
/// pubspec.yaml lives). The file must be named exactly `build.dart`.
///
/// It's quite likely that in the near future `build.dart` will be replaced with
/// something else. For example, `pub deploy` will deal with deploying
/// applications automatically, and the Dart Editor might provide other
/// mechanisms to hook linters.
///
/// There are three important functions exposed by this library [build], [lint],
/// and [deploy]. The following examples show common uses of these functions
/// when writing a `build.dart` file.
///
/// **Example 1**: Uses build.dart to run the linter tool.
///
/// import 'dart:io';
/// import 'package:polymer/builder.dart';
///
/// main() {
/// lint();
/// }
///
/// **Example 2**: Runs the linter and creates a deployable version of the app
/// every time.
///
/// import 'dart:io';
/// import 'package:polymer/builder.dart';
///
/// main() {
/// deploy(); // deploy also calls the linter internally.
/// }
///
/// **Example 3**: Always run the linter, but conditionally build a deployable
/// version. See [parseOptions] for a description of options parsed
/// automatically by this helper library.
///
/// import 'dart:io';
/// import 'package:polymer/builder.dart';
///
/// main(args) {
/// var options = parseOptions(args);
/// if (options.forceDeploy) {
/// deploy();
/// } else {
/// lint();
/// }
/// }
///
/// **Example 4**: Same as above, but uses [build] (which internally calls
/// either [lint] or [deploy]).
///
/// import 'dart:io';
/// import 'package:polymer/builder.dart';
///
/// main(args) {
/// build(options: parseOptions(args));
/// }
///
/// **Example 5**: Like the previous example, but indicates to the linter and
/// deploy tool which files are actually used as entry point files. See the
/// documentation of [build] below for more details.
///
/// import 'dart:io';
/// import 'package:polymer/builder.dart';
///
/// main(args) {
/// build(entryPoints: ['web/index.html'], options: parseOptions(args));
/// }
library polymer.builder;
import 'dart:async';
@ -93,26 +91,24 @@ import 'src/build/common.dart';
import 'transformer.dart';
/**
* Runs the polymer linter on any relevant file in your package, such as any
* .html file under 'lib/', 'asset/', and 'web/'. And, if requested, creates a
* directory suitable for deploying a Polymer application to a server.
*
* The [entryPoints] list contains files under web/ that should be treated as
* entry points. Each entry on this list is a relative path from the package
* root (for example 'web/index.html'). If null, all files under 'web/' are
* treated as possible entry points.
*
* Options must be passed by
* passing the [options] argument. The deploy operation is run only when the
* command-line argument `--deploy` is present, or equivalently when
* `options.forceDeploy` is true.
*
* The linter and deploy steps needs to know the name of the [currentPackage]
* and the location where to find the code for any package it depends on
* ([packageDirs]). This is inferred automatically, but can be overriden if
* those arguments are provided.
*/
/// Runs the polymer linter on any relevant file in your package, such as any
/// .html file under 'lib/', 'asset/', and 'web/'. And, if requested, creates a
/// directory suitable for deploying a Polymer application to a server.
///
/// The [entryPoints] list contains files under web/ that should be treated as
/// entry points. Each entry on this list is a relative path from the package
/// root (for example 'web/index.html'). If null, all files under 'web/' are
/// treated as possible entry points.
///
/// Options must be passed by
/// passing the [options] argument. The deploy operation is run only when the
/// command-line argument `--deploy` is present, or equivalently when
/// `options.forceDeploy` is true.
///
/// The linter and deploy steps needs to know the name of the [currentPackage]
/// and the location where to find the code for any package it depends on
/// ([packageDirs]). This is inferred automatically, but can be overriden if
/// those arguments are provided.
Future build({List<String> entryPoints, CommandLineOptions options,
String currentPackage, Map<String, String> packageDirs}) {
if (options == null) {
@ -128,21 +124,19 @@ Future build({List<String> entryPoints, CommandLineOptions options,
}
/**
* Runs the polymer linter on any relevant file in your package,
* such as any .html file under 'lib/', 'asset/', and 'web/'.
*
* The [entryPoints] list contains files under web/ that should be treated as
* entry points. Each entry on this list is a relative path from the package
* root (for example 'web/index.html'). If null, all files under 'web/' are
* treated as possible entry points.
*
* Options must be passed by passing the [options] argument.
*
* The linter needs to know the name of the [currentPackage] and the location
* where to find the code for any package it depends on ([packageDirs]). This is
* inferred automatically, but can be overriden if those arguments are provided.
*/
/// Runs the polymer linter on any relevant file in your package,
/// such as any .html file under 'lib/', 'asset/', and 'web/'.
///
/// The [entryPoints] list contains files under web/ that should be treated as
/// entry points. Each entry on this list is a relative path from the package
/// root (for example 'web/index.html'). If null, all files under 'web/' are
/// treated as possible entry points.
///
/// Options must be passed by passing the [options] argument.
///
/// The linter needs to know the name of the [currentPackage] and the location
/// where to find the code for any package it depends on ([packageDirs]). This
/// is inferred automatically, but can be overriden by passing the arguments.
Future lint({List<String> entryPoints, CommandLineOptions options,
String currentPackage, Map<String, String> packageDirs}) {
if (options == null) {
@ -158,24 +152,23 @@ Future lint({List<String> entryPoints, CommandLineOptions options,
machineFormat: options.machineFormat));
}
/**
* Creates a directory suitable for deploying a Polymer application to a server.
*
* **Note**: this function will be replaced in the future by the `pub deploy`
* command.
*
* The [entryPoints] list contains files under web/ that should be treated as
* entry points. Each entry on this list is a relative path from the package
* root (for example 'web/index.html'). If null, all files under 'web/' are
* treated as possible entry points.
*
* Options must be passed by passing the [options] list.
*
* The deploy step needs to know the name of the [currentPackage] and the
* location where to find the code for any package it depends on
* ([packageDirs]). This is inferred automatically, but can be overriden if
* those arguments are provided.
*/
/// Creates a directory suitable for deploying a Polymer application to a
/// server.
///
/// **Note**: this function will be replaced in the future by the `pub deploy`
/// command.
///
/// The [entryPoints] list contains files under web/ that should be treated as
/// entry points. Each entry on this list is a relative path from the package
/// root (for example 'web/index.html'). If null, all files under 'web/' are
/// treated as possible entry points.
///
/// Options must be passed by passing the [options] list.
///
/// The deploy step needs to know the name of the [currentPackage] and the
/// location where to find the code for any package it depends on
/// ([packageDirs]). This is inferred automatically, but can be overriden if
/// those arguments are provided.
Future deploy({List<String> entryPoints, CommandLineOptions options,
String currentPackage, Map<String, String> packageDirs}) {
if (options == null) {
@ -203,45 +196,39 @@ Future deploy({List<String> entryPoints, CommandLineOptions options,
}
/**
* Options that may be used either in build.dart or by the linter and deploy
* tools.
*/
/// Options that may be used either in build.dart or by the linter and deploy
/// tools.
class CommandLineOptions {
/** Files marked as changed. */
/// Files marked as changed.
final List<String> changedFiles;
/** Files marked as removed. */
/// Files marked as removed.
final List<String> removedFiles;
/** Whether to clean intermediate artifacts, if any. */
/// Whether to clean intermediate artifacts, if any.
final bool clean;
/** Whether to do a full build (as if all files have changed). */
/// Whether to do a full build (as if all files have changed).
final bool full;
/** Whether to print results using a machine parseable format. */
/// Whether to print results using a machine parseable format.
final bool machineFormat;
/** Whether the force deploy option was passed in the command line. */
/// Whether the force deploy option was passed in the command line.
final bool forceDeploy;
/** Location where to generate output files. */
/// Location where to generate output files.
final String outDir;
/** True to use the CSP-compliant JS file. */
/// True to use the CSP-compliant JS file.
final bool contentSecurityPolicy;
/**
* True to include the JS script tag directly, without the
* "packages/browser/dart.js" trampoline.
*/
/// True to include the JS script tag directly, without the
/// "packages/browser/dart.js" trampoline.
final bool directlyIncludeJS;
/**
* Run transformers in release mode. For instance, uses the minified versions
* of the web_components polyfill.
*/
/// Run transformers in release mode. For instance, uses the minified versions
/// of the web_components polyfill.
final bool releaseMode;
CommandLineOptions(this.changedFiles, this.removedFiles, this.clean,
@ -250,32 +237,30 @@ class CommandLineOptions {
this.releaseMode);
}
/**
* Parse command-line arguments and return a [CommandLineOptions] object. The
* following flags are parsed by this method.
*
* * `--changed file-path`: notify of a file change.
* * `--removed file-path`: notify that a file was removed.
* * `--clean`: remove temporary artifacts (if any)
* * `--full`: build everything, similar to marking every file as changed
* * `--machine`: produce output that can be parsed by tools, such as the Dart
* Editor.
* * `--deploy`: force deploy.
* * `--no-js`: deploy replaces *.dart scripts with *.dart.js. You can turn
* this feature off with --no-js, which leaves "packages/browser/dart.js".
* * `--csp`: replaces *.dart with *.dart.precompiled.js to comply with
* Content Security Policy restrictions.
* * `--help`: print documentation for each option and exit.
*
* Currently not all the flags are used by [lint] or [deploy] above, but they
* are available so they can be used from your `build.dart`. For instance, see
* the top-level library documentation for an example that uses the force-deploy
* option to conditionally call [deploy].
*
* If this documentation becomes out of date, the best way to discover which
* flags are supported is to invoke this function from your build.dart, and run
* it with the `--help` command-line flag.
*/
/// Parse command-line arguments and return a [CommandLineOptions] object. The
/// following flags are parsed by this method.
///
/// * `--changed file-path`: notify of a file change.
/// * `--removed file-path`: notify that a file was removed.
/// * `--clean`: remove temporary artifacts (if any)
/// * `--full`: build everything, similar to marking every file as changed
/// * `--machine`: produce output that can be parsed by tools, such as the
/// Dart Editor.
/// * `--deploy`: force deploy.
/// * `--no-js`: deploy replaces *.dart scripts with *.dart.js. You can turn
/// this feature off with --no-js, which leaves "packages/browser/dart.js".
/// * `--csp`: replaces *.dart with *.dart.precompiled.js to comply with
/// Content Security Policy restrictions.
/// * `--help`: print documentation for each option and exit.
///
/// Currently not all the flags are used by [lint] or [deploy] above, but they
/// are available so they can be used from your `build.dart`. For instance, see
/// the top-level library documentation for an example that uses the
/// force-deploy option to conditionally call [deploy].
///
/// If this documentation becomes out of date, the best way to discover which
/// flags are supported is to invoke this function from your build.dart, and run
/// it with the `--help` command-line flag.
CommandLineOptions parseOptions([List<String> args]) {
if (args == null) {
print('warning: the list of arguments from main(List<String> args) now '

View file

@ -2,24 +2,22 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* **Note**: If you already have a `build.dart` in your application, we
* recommend to use the `package:polymer/builder.dart` library instead.
/// **Note**: If you already have a `build.dart` in your application, we
/// recommend to use the `package:polymer/builder.dart` library instead.
* Temporary deploy command used to create a version of the app that can be
* compiled with dart2js and deployed. Following pub layout conventions, this
* script will treat any HTML file under a package 'web/' and 'test/'
* directories as entry points.
*
* From an application package you can run deploy by creating a small program
* as follows:
*
* import "package:polymer/deploy.dart" as deploy;
* main() => deploy.main();
*
* This library should go away once `pub deploy` can be configured to run
* barback transformers.
*/
/// Temporary deploy command used to create a version of the app that can be
/// compiled with dart2js and deployed. Following pub layout conventions, this
/// script will treat any HTML file under a package 'web/' and 'test/'
/// directories as entry points.
///
/// From an application package you can run deploy by creating a small program
/// as follows:
///
/// import "package:polymer/deploy.dart" as deploy;
/// main() => deploy.main();
///
/// This library should go away once `pub deploy` can be configured to run
/// barback transformers.
library polymer.deploy;
import 'dart:io';

View file

@ -2,20 +2,18 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Library that automatically initializes polymer elements without having to
* write a main for your application.
*
* If a polymer application is written entirely with `<polymer-element>` tags
* and there is no initialization code that needs to happen before these
* elements are created, then, instead of creating your own `main`, you can
* simply include a script tag loading this library:
*
* <script type="application/dart">import "package:polymer/init.dart";
* </script>
*
* This script tag should be placed after all HTML imports on your page.
*/
/// Library that automatically initializes polymer elements without having to
/// write a main for your application.
///
/// If a polymer application is written entirely with `<polymer-element>` tags
/// and there is no initialization code that needs to happen before these
/// elements are created, then, instead of creating your own `main`, you can
/// simply include a script tag loading this library:
///
/// <script type="application/dart">import "package:polymer/init.dart";
/// </script>
///
/// This script tag should be placed after all HTML imports on your page.
library polymer.init;
import 'package:polymer/polymer.dart';

View file

@ -2,41 +2,39 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Custom HTML tags, data binding, and templates for building
* structured, encapsulated, client-side web apps.
*
* Polymer.dart, the next evolution of Web UI,
* is an in-progress Dart port of the
* [Polymer project](http://www.polymer-project.org/).
* Polymer.dart compiles to JavaScript and runs across the modern web.
*
* To use polymer.dart in your application,
* first add a
* [dependency](http://pub.dartlang.org/doc/dependencies.html)
* to the app's pubspec.yaml file.
* Instead of using the open-ended `any` version specifier,
* we recommend using a range of version numbers, as in this example:
*
* dependencies:
* polymer: '>=0.7.1 <0.8'
*
* Then import the library into your application:
*
* import 'package:polymer/polymer.dart';
*
* ## Other resources
*
* * [Polymer.dart homepage](http://www.dartlang.org/polymer-dart/):
* Example code, project status, and
* information about how to get started using Polymer.dart in your apps.
*
* * [polymer.dart package](http://pub.dartlang.org/packages/polymer):
* More details, such as the current major release number.
*
* * [Upgrading to Polymer.dart](http://www.dartlang.org/polymer-dart/upgrading-to-polymer-from-web-ui.html):
* Tips for converting your apps from Web UI to Polymer.dart.
*/
/// Custom HTML tags, data binding, and templates for building
/// structured, encapsulated, client-side web apps.
///
/// Polymer.dart, the next evolution of Web UI,
/// is an in-progress Dart port of the
/// [Polymer project](http://www.polymer-project.org/).
/// Polymer.dart compiles to JavaScript and runs across the modern web.
///
/// To use polymer.dart in your application,
/// first add a
/// [dependency](http://pub.dartlang.org/doc/dependencies.html)
/// to the app's pubspec.yaml file.
/// Instead of using the open-ended `any` version specifier,
/// we recommend using a range of version numbers, as in this example:
///
/// dependencies:
/// polymer: '>=0.7.1 <0.8'
///
/// Then import the library into your application:
///
/// import 'package:polymer/polymer.dart';
///
/// ## Other resources
///
/// * [Polymer.dart homepage](http://www.dartlang.org/polymer-dart/):
/// Example code, project status, and
/// information about how to get started using Polymer.dart in your apps.
///
/// * [polymer.dart package](http://pub.dartlang.org/packages/polymer):
/// More details, such as the current major release number.
///
/// * [Upgrading to Polymer.dart](http://www.dartlang.org/polymer-dart/upgrading-to-polymer-from-web-ui.html):
/// Tips for converting your apps from Web UI to Polymer.dart.
library polymer;
import 'dart:async';

View file

@ -2,10 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Ported from `polymer/src/boot.js`. **/
/// Ported from `polymer/src/boot.js`. *
part of polymer;
/** Prevent a flash of unstyled content. */
/// Prevent a flash of unstyled content.
_preventFlashOfUnstyledContent() {
var style = new StyleElement();

View file

@ -2,10 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Final phase of the polymer transformation: removes any files that are not
* needed for deployment.
*/
/// Final phase of the polymer transformation: removes any files that are not
/// needed for deployment.
library polymer.src.build.build_filter;
import 'dart:async';
@ -13,10 +11,8 @@ import 'dart:async';
import 'package:barback/barback.dart';
import 'common.dart';
/**
* Removes any files not needed for deployment, such as internal build artifacts
* and non-entry HTML files.
*/
/// Removes any files not needed for deployment, such as internal build
/// artifacts and non-entry HTML files.
class BuildFilter extends Transformer with PolymerTransformer {
final TransformOptions options;
BuildFilter(this.options);

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Transfomer that extracts inlined script code into separate assets. */
/// Transfomer that extracts inlined script code into separate assets.
library polymer.src.build.code_extractor;
import 'dart:async';
@ -16,16 +16,14 @@ import 'package:path/path.dart' as path;
import 'common.dart';
/**
* Transformer that extracts Dart code inlined in HTML script tags and outputs a
* separate file for each.
*/
/// Transformer that extracts Dart code inlined in HTML script tags and outputs
/// a separate file for each.
class InlineCodeExtractor extends Transformer with PolymerTransformer {
final TransformOptions options;
InlineCodeExtractor(this.options);
/** Only run this transformer on .html files. */
/// Only run this transformer on .html files.
final String allowedExtensions = ".html";
Future apply(Transform transform) {
@ -69,7 +67,7 @@ class InlineCodeExtractor extends Transformer with PolymerTransformer {
}
}
/** Parse [code] and determine whether it has a library directive. */
/// Parse [code] and determine whether it has a library directive.
bool _hasLibraryDirective(String code) {
var errorListener = new _ErrorCollector();
var reader = new CharSequenceReader(code);

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Common methods used by transfomers. */
/// Common methods used by transfomers.
library polymer.src.build.common;
import 'dart:async';
@ -15,10 +15,8 @@ import 'package:path/path.dart' as path;
import 'package:observe/transformer.dart' show ObservableTransformer;
import 'package:source_maps/span.dart' show Span;
/**
* Parses an HTML file [contents] and returns a DOM-like tree. Adds emitted
* error/warning to [logger].
*/
/// Parses an HTML file [contents] and returns a DOM-like tree. Adds emitted
/// error/warning to [logger].
Document _parseHtml(String contents, String sourcePath, TransformLogger logger,
{bool checkDocType: true}) {
// TODO(jmesserly): make HTTP encoding configurable
@ -36,38 +34,30 @@ Document _parseHtml(String contents, String sourcePath, TransformLogger logger,
return document;
}
/** Additional options used by polymer transformers */
/// Additional options used by polymer transformers
class TransformOptions {
/**
* List of entrypoints paths. The paths are relative to the package root and
* are represented using posix style, which matches the representation used in
* asset ids in barback. If null, anything under 'web/' or 'test/' is
* considered an entry point.
*/
/// List of entrypoints paths. The paths are relative to the package root and
/// are represented using posix style, which matches the representation used
/// in asset ids in barback. If null, anything under 'web/' or 'test/' is
/// considered an entry point.
final List<String> entryPoints;
/**
* True to enable Content Security Policy.
* This means the HTML page will include *.dart.precompiled.js
*
* This flag has no effect unless [directlyIncludeJS] is enabled.
*/
/// True to enable Content Security Policy.
/// This means the HTML page will include *.dart.precompiled.js
///
/// This flag has no effect unless [directlyIncludeJS] is enabled.
final bool contentSecurityPolicy;
/**
* True to include the compiled JavaScript directly from the HTML page.
* If enabled this will remove "packages/browser/dart.js" and replace
* `type="application/dart"` scripts with equivalent *.dart.js files.
*
* If [contentSecurityPolicy] enabled, this will reference files
* named *.dart.precompiled.js.
*/
/// True to include the compiled JavaScript directly from the HTML page.
/// If enabled this will remove "packages/browser/dart.js" and replace
/// `type="application/dart"` scripts with equivalent *.dart.js files.
///
/// If [contentSecurityPolicy] enabled, this will reference files
/// named *.dart.precompiled.js.
final bool directlyIncludeJS;
/**
* Run transformers to create a releasable app. For example, include the
* minified versions of the polyfills rather than the debug versions.
*/
/// Run transformers to create a releasable app. For example, include the
/// minified versions of the polyfills rather than the debug versions.
final bool releaseMode;
TransformOptions({entryPoints, this.contentSecurityPolicy: false,
@ -75,7 +65,7 @@ class TransformOptions {
: entryPoints = entryPoints == null ? null
: entryPoints.map(_systemToAssetPath).toList();
/** Whether an asset with [id] is an entry point HTML file. */
/// Whether an asset with [id] is an entry point HTML file.
bool isHtmlEntryPoint(AssetId id) {
if (id.extension != '.html') return false;
@ -88,7 +78,7 @@ class TransformOptions {
}
}
/** Mixin for polymer transformers. */
/// Mixin for polymer transformers.
abstract class PolymerTransformer {
TransformOptions get options;
@ -111,17 +101,15 @@ abstract class PolymerTransformer {
});
}
/**
* Gets the appropriate URL to use in a [Span] to produce messages
* (e.g. warnings) for users. This will attempt to format the URL in the most
* useful way:
*
* - If the asset is within the primary package, then use the [id.path],
* the user will know it is a file from their own code.
* - If the asset is from another package, then use [assetUrlFor], this will
* likely be a "package:" url to the file in the other package, which is
* enough for users to identify where the error is.
*/
/// Gets the appropriate URL to use in a [Span] to produce messages
/// (e.g. warnings) for users. This will attempt to format the URL in the most
/// useful way:
///
/// - If the asset is within the primary package, then use the [id.path],
/// the user will know it is a file from their own code.
/// - If the asset is from another package, then use [assetUrlFor], this will
/// likely be a "package:" url to the file in the other package, which is
/// enough for users to identify where the error is.
String spanUrlFor(AssetId id, Transform transform) {
var primaryId = transform.primaryInput.id;
bool samePackage = id.package == primaryId.package;
@ -135,16 +123,14 @@ abstract class PolymerTransformer {
String toString() => 'polymer ($runtimeType)';
}
/** Transformer phases which should be applied to the Polymer package. */
/// Transformer phases which should be applied to the Polymer package.
List<List<Transformer>> get phasesForPolymer =>
[[new ObservableTransformer(['lib/src/instance.dart'])]];
/**
* Create an [AssetId] for a [url] seen in the [source] asset. By default this
* is used to resolve relative urls that occur in HTML assets, including
* cross-package urls of the form "packages/foo/bar.html". Dart-style "package:"
* urls are not resolved unless [source] is Dart file (has a .dart extension).
*/
/// Create an [AssetId] for a [url] seen in the [source] asset. By default this
/// is used to resolve relative urls that occur in HTML assets, including
/// cross-package urls of the form "packages/foo/bar.html". Dart "package:"
/// urls are not resolved unless [source] is Dart file (has a .dart extension).
// TODO(sigmund): delete once this is part of barback (dartbug.com/12610)
AssetId resolve(AssetId source, String url, TransformLogger logger, Span span,
{bool allowAbsolute: false}) {
@ -228,10 +214,8 @@ AssetId _extractOtherPackageId(int index, List segments,
path.url.join(folder, path.url.joinAll(segments.sublist(index + 2))));
}
/**
* Generate the import url for a file described by [id], referenced by a file
* with [sourceId].
*/
/// Generate the import url for a file described by [id], referenced by a file
/// with [sourceId].
// TODO(sigmund): this should also be in barback (dartbug.com/12610)
String assetUrlFor(AssetId id, AssetId sourceId, TransformLogger logger,
{bool allowAssetUrl: false}) {
@ -261,7 +245,7 @@ String assetUrlFor(AssetId id, AssetId sourceId, TransformLogger logger,
}
/** Convert system paths to asset paths (asset paths are posix style). */
/// Convert system paths to asset paths (asset paths are posix style).
String _systemToAssetPath(String assetPath) {
if (path.Style.platform != path.Style.windows) return assetPath;
return path.posix.joinAll(path.split(assetPath));

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Transfomer that inlines polymer-element definitions from html imports. */
/// Transfomer that inlines polymer-element definitions from html imports.
library polymer.src.build.import_inliner;
import 'dart:async';
@ -55,14 +55,12 @@ class _HtmlInliner extends PolymerTransformer {
}));
}
/**
* Visits imports in [document] and add the imported documents to documents.
* Documents are added in the order they appear, transitive imports are added
* first.
*
* Returns `true` if and only if the document was changed and should be
* written out.
*/
/// Visits imports in [document] and add the imported documents to documents.
/// Documents are added in the order they appear, transitive imports are added
/// first.
///
/// Returns `true` if and only if the document was changed and should be
/// written out.
Future<bool> _visitImports(Document document, AssetId sourceId) {
bool changed = false;
@ -94,15 +92,13 @@ class _HtmlInliner extends PolymerTransformer {
}).then((_) => changed);
}
/**
* To preserve the order of scripts with respect to inlined
* link rel=import, we move both of those into the body before we do any
* inlining.
*
* Note: we do this for stylesheets as well to preserve ordering with
* respect to eachother, because stylesheets can be pulled in transitively
* from imports.
*/
/// To preserve the order of scripts with respect to inlined
/// link rel=import, we move both of those into the body before we do any
/// inlining.
///
/// Note: we do this for stylesheets as well to preserve ordering with
/// respect to eachother, because stylesheets can be pulled in transitively
/// from imports.
// TODO(jmesserly): vulcanizer doesn't need this because they inline JS
// scripts, causing them to be naturally moved as part of the inlining.
// Should we do the same? Alternatively could we inline head into head and
@ -146,12 +142,10 @@ class _HtmlInliner extends PolymerTransformer {
});
}
/**
* Split Dart script tags from all the other elements. Now that Dartium
* only allows a single script tag per page, we can't inline script
* tags. Instead, we collect the urls of each script tag so we import
* them directly from the Dart bootstrap code.
*/
/// Split Dart script tags from all the other elements. Now that Dartium
/// only allows a single script tag per page, we can't inline script
/// tags. Instead, we collect the urls of each script tag so we import
/// them directly from the Dart bootstrap code.
void _extractScripts(Document document) {
bool first = true;
for (var script in document.querySelectorAll('script')) {
@ -182,21 +176,20 @@ class _HtmlInliner extends PolymerTransformer {
}
}
/**
* Recursively inlines the contents of HTML imports. Produces as output a single
* HTML file that inlines the polymer-element definitions, and a text file that
* contains, in order, the URIs to each library that sourced in a script tag.
*
* This transformer assumes that all script tags point to external files. To
* support script tags with inlined code, use this transformer after running
* [InlineCodeExtractor] on an earlier phase.
*/
/// Recursively inlines the contents of HTML imports. Produces as output a
/// single HTML file that inlines the polymer-element definitions, and a text
/// file that contains, in order, the URIs to each library that sourced in a
/// script tag.
///
/// This transformer assumes that all script tags point to external files. To
/// support script tags with inlined code, use this transformer after running
/// [InlineCodeExtractor] on an earlier phase.
class ImportInliner extends Transformer {
final TransformOptions options;
ImportInliner(this.options);
/** Only run on entry point .html files. */
/// Only run on entry point .html files.
Future<bool> isPrimary(Asset input) =>
new Future.value(options.isHtmlEntryPoint(input.id));
@ -205,11 +198,11 @@ class ImportInliner extends Transformer {
}
/** Internally adjusts urls in the html that we are about to inline. */
/// Internally adjusts urls in the html that we are about to inline.
class _UrlNormalizer extends TreeVisitor {
final Transform transform;
/** Asset where the original content (and original url) was found. */
/// Asset where the original content (and original url) was found.
final AssetId sourceId;
_UrlNormalizer(this.transform, this.sourceId);
@ -229,7 +222,7 @@ class _UrlNormalizer extends TreeVisitor {
static final _URL = new RegExp(r'url\(([^)]*)\)', multiLine: true);
static final _QUOTE = new RegExp('["\']', multiLine: true);
/** Visit the CSS text and replace any relative URLs so we can inline it. */
/// Visit the CSS text and replace any relative URLs so we can inline it.
// Ported from:
// https://github.com/Polymer/vulcanize/blob/c14f63696797cda18dc3d372b78aa3378acc691f/lib/vulcan.js#L149
// TODO(jmesserly): use csslib here instead? Parsing with RegEx is sadness.
@ -278,13 +271,11 @@ class _UrlNormalizer extends TreeVisitor {
}
}
/**
* HTML attributes that expect a URL value.
* <http://dev.w3.org/html5/spec/section-index.html#attributes-1>
*
* Every one of these attributes is a URL in every context where it is used in
* the DOM. The comments show every DOM element where an attribute can be used.
*/
/// HTML attributes that expect a URL value.
/// <http://dev.w3.org/html5/spec/section-index.html#attributes-1>
///
/// Every one of these attributes is a URL in every context where it is used in
/// the DOM. The comments show every DOM element where an attribute can be used.
const _urlAttributes = const [
'action', // in form
'background', // in body

View file

@ -2,10 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Logic to validate that developers are correctly using Polymer constructs.
* This is mainly used to produce warnings for feedback in the editor.
*/
/// Logic to validate that developers are correctly using Polymer constructs.
/// This is mainly used to produce warnings for feedback in the editor.
library polymer.src.build.linter;
import 'dart:async';
@ -18,15 +16,13 @@ import 'package:source_maps/span.dart';
import 'common.dart';
import 'utils.dart';
/**
* A linter that checks for common Polymer errors and produces warnings to
* show on the editor or the command line. Leaves sources unchanged, but creates
* a new asset containing all the warnings.
*/
/// A linter that checks for common Polymer errors and produces warnings to
/// show on the editor or the command line. Leaves sources unchanged, but
/// creates a new asset containing all the warnings.
class Linter extends Transformer with PolymerTransformer {
final TransformOptions options;
/** Only run on .html files. */
/// Only run on .html files.
final String allowedExtensions = '.html';
Linter(this.options);
@ -46,12 +42,10 @@ class Linter extends Transformer with PolymerTransformer {
});
}
/**
* Collect into [elements] any data about each polymer-element defined in
* [document] or any of it's imports, unless they have already been [seen].
* Elements are added in the order they appear, transitive imports are added
* first.
*/
/// Collect into [elements] any data about each polymer-element defined in
/// [document] or any of it's imports, unless they have already been [seen].
/// Elements are added in the order they appear, transitive imports are added
/// first.
Future<Map<String, _ElementSummary>> _collectElements(
Document document, AssetId sourceId, Transform transform,
Set<AssetId> seen, [Map<String, _ElementSummary> elements]) {
@ -120,13 +114,11 @@ class Linter extends Transformer with PolymerTransformer {
}
/**
* Information needed about other polymer-element tags in order to validate
* how they are used and extended.
*
* Note: these are only created for polymer-element, because pure custom
* elements don't have a declarative form.
*/
/// Information needed about other polymer-element tags in order to validate
/// how they are used and extended.
///
/// Note: these are only created for polymer-element, because pure custom
/// elements don't have a declarative form.
class _ElementSummary {
final String tagName;
final String extendsTag;
@ -181,7 +173,7 @@ class _LinterVisitor extends TreeVisitor {
}
}
/** Produce warnings for invalid link-rel tags. */
/// Produce warnings for invalid link-rel tags.
void _validateLinkElement(Element node) {
var rel = node.attributes['rel'];
if (rel != 'import' && rel != 'stylesheet') return;
@ -199,16 +191,14 @@ class _LinterVisitor extends TreeVisitor {
_logger.warning('link rel="$rel" missing href.', span: node.sourceSpan);
}
/** Produce warnings if using `<element>` instead of `<polymer-element>`. */
/// Produce warnings if using `<element>` instead of `<polymer-element>`.
void _validateElementElement(Element node) {
_logger.warning('<element> elements are not supported, use'
' <polymer-element> instead', span: node.sourceSpan);
}
/**
* Produce warnings if using `<polymer-element>` in the wrong place or if the
* definition is not complete.
*/
/// Produce warnings if using `<polymer-element>` in the wrong place or if the
/// definition is not complete.
void _validatePolymerElement(Element node) {
if (_inPolymerElement) {
_logger.error('Nested polymer element definitions are not allowed.',
@ -254,17 +244,15 @@ class _LinterVisitor extends TreeVisitor {
_inPolymerElement = oldValue;
}
/**
* Produces warnings for malformed script tags. In html5 leaving off type= is
* fine, but it defaults to text/javascript. Because this might be a common
* error, we warn about it when src file ends in .dart, but the type is
* incorrect, or when users write code in an inline script tag of a custom
* element.
*
* The hope is that these cases shouldn't break existing valid code, but that
* they'll help Polymer authors avoid having their Dart code accidentally
* interpreted as JavaScript by the browser.
*/
/// Produces warnings for malformed script tags. In html5 leaving off type= is
/// fine, but it defaults to text/javascript. Because this might be a common
/// error, we warn about it when src file ends in .dart, but the type is
/// incorrect, or when users write code in an inline script tag of a custom
/// element.
///
/// The hope is that these cases shouldn't break existing valid code, but that
/// they'll help Polymer authors avoid having their Dart code accidentally
/// interpreted as JavaScript by the browser.
void _validateScriptElement(Element node) {
var scriptType = node.attributes['type'];
var isDart = scriptType == 'application/dart';
@ -314,10 +302,8 @@ class _LinterVisitor extends TreeVisitor {
}
}
/**
* Produces warnings for misuses of on-foo event handlers, and for instanting
* custom tags incorrectly.
*/
/// Produces warnings for misuses of on-foo event handlers, and for instanting
/// custom tags incorrectly.
void _validateNormalElement(Element node) {
// Event handlers only allowed inside polymer-elements
node.attributes.forEach((name, value) {
@ -380,9 +366,7 @@ class _LinterVisitor extends TreeVisitor {
}
}
/**
* Validate an attribute on a custom-element. Returns true if valid.
*/
/// Validate an attribute on a custom-element. Returns true if valid.
bool _validateCustomAttributeName(String name, FileSpan span) {
if (name.contains('-')) {
var newName = toCamelCase(name);
@ -394,7 +378,7 @@ class _LinterVisitor extends TreeVisitor {
return true;
}
/** Validate event handlers are used correctly. */
/// Validate event handlers are used correctly.
void _validateEventHandler(Element node, String name, String value) {
if (!name.startsWith('on-')) {
_logger.warning('Event handler "$name" will be interpreted as an inline'
@ -434,10 +418,8 @@ var _invalidTagNames = const {
'missing-glyph': '',
};
/**
* Returns true if this is a valid custom element name. See:
* <https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/index.html#dfn-custom-element-name>
*/
/// Returns true if this is a valid custom element name. See:
/// <https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/index.html#dfn-custom-element-name>
bool _isCustomTag(String name) {
if (name == null || !name.contains('-')) return false;
return !_invalidTagNames.containsKey(name);

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Includes any additional polyfills that may needed by the deployed app. */
/// Includes any additional polyfills that may needed by the deployed app.
library polymer.src.build.polyfill_injector;
import 'dart:async';
@ -13,20 +13,18 @@ import 'package:html5lib/dom.dart' show
import 'package:html5lib/parser.dart' show parseFragment;
import 'common.dart';
/**
* Ensures that any scripts and polyfills needed to run a polymer application
* are included. For example, this transformer will ensure that there is a
* script tag that loads the polyfills and interop.js (used for css shimming).
*
* This step also replaces "packages/browser/dart.js" and the Dart script tag
* with a script tag that loads the dart2js compiled code directly.
*/
/// Ensures that any scripts and polyfills needed to run a polymer application
/// are included. For example, this transformer will ensure that there is a
/// script tag that loads the polyfills and interop.js (used for css shimming).
///
/// This step also replaces "packages/browser/dart.js" and the Dart script tag
/// with a script tag that loads the dart2js compiled code directly.
class PolyfillInjector extends Transformer with PolymerTransformer {
final TransformOptions options;
PolyfillInjector(this.options);
/** Only run on entry point .html files. */
/// Only run on entry point .html files.
Future<bool> isPrimary(Asset input) =>
new Future.value(options.isHtmlEntryPoint(input.id));

View file

@ -2,10 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Definitions used to run the polymer linter and deploy tools without using
* pub serve or pub deploy.
*/
/// Definitions used to run the polymer linter and deploy tools without using
/// pub serve or pub deploy.
library polymer.src.build.runner;
import 'dart:async';
@ -18,49 +16,39 @@ import 'package:stack_trace/stack_trace.dart';
import 'package:yaml/yaml.dart';
/** Collects different parameters needed to configure and run barback. */
/// Collects different parameters needed to configure and run barback.
class BarbackOptions {
/**
* Phases of transformers to run for the current package.
* Use packagePhases to specify phases for other packages.
*/
/// Phases of transformers to run for the current package.
/// Use packagePhases to specify phases for other packages.
final List<List<Transformer>> phases;
/** Package to treat as the current package in barback. */
/// Package to treat as the current package in barback.
final String currentPackage;
/** Directory root for the current package. */
/// Directory root for the current package.
final String packageHome;
/**
* Mapping between package names and the path in the file system where
* to find the sources of such package.
*/
/// Mapping between package names and the path in the file system where
/// to find the sources of such package.
final Map<String, String> packageDirs;
/** Whether to run transformers on the test folder. */
/// Whether to run transformers on the test folder.
final bool transformTests;
/** Directory where to generate code, if any. */
/// Directory where to generate code, if any.
final String outDir;
/**
* Whether to print error messages using a json-format that tools, such as the
* Dart Editor, can process.
*/
/// Whether to print error messages using a json-format that tools, such as
/// the Dart Editor, can process.
final bool machineFormat;
/**
* Whether to follow symlinks when listing directories. By default this is
* false because directories have symlinks for the packages directory created
* by pub, but it can be turned on for custom uses of this library.
*/
/// Whether to follow symlinks when listing directories. By default this is
/// false because directories have symlinks for the packages directory created
/// by pub, but it can be turned on for custom uses of this library.
final bool followLinks;
/**
* Phases of transformers to apply to packages other than the current
* package, keyed by the package name.
*/
/// Phases of transformers to apply to packages other than the current
/// package, keyed by the package name.
final Map<String, List<List<Transformer>>> packagePhases;
BarbackOptions(this.phases, this.outDir, {currentPackage, String packageHome,
@ -75,11 +63,9 @@ class BarbackOptions {
}
/**
* Creates a barback system as specified by [options] and runs it. Returns a
* future that contains the list of assets generated after barback runs to
* completion.
*/
/// Creates a barback system as specified by [options] and runs it. Returns a
/// future that contains the list of assets generated after barback runs to
/// completion.
Future<AssetSet> runBarback(BarbackOptions options) {
var barback = new Barback(new _PackageProvider(options.packageDirs));
_initBarback(barback, options);
@ -88,7 +74,7 @@ Future<AssetSet> runBarback(BarbackOptions options) {
return _emitAllFiles(barback, options);
}
/** Extract the current package from the pubspec.yaml file. */
/// Extract the current package from the pubspec.yaml file.
String readCurrentPackageFromPubspec([String dir]) {
var pubspec = new File(
dir == null ? 'pubspec.yaml' : path.join(dir, 'pubspec.yaml'));
@ -100,12 +86,10 @@ String readCurrentPackageFromPubspec([String dir]) {
return loadYaml(pubspec.readAsStringSync())['name'];
}
/**
* Extract a mapping between package names and the path in the file system where
* to find the sources of such package. This map will contain an entry for the
* current package and everything it depends on (extracted via `pub
* list-package-dirs`).
*/
/// Extract a mapping between package names and the path in the file system
/// which has the source of the package. This map will contain an entry for the
/// current package and everything it depends on (extracted via `pub
/// list-package-dirs`).
Map<String, String> readPackageDirsFromPub(
[String packageHome, String currentPackage]) {
var cachedDir = Directory.current;
@ -138,7 +122,7 @@ Map<String, String> readPackageDirsFromPub(
return map;
}
/** Return the relative path of each file under [subDir] in [package]. */
/// Return the relative path of each file under [subDir] in [package].
Iterable<String> _listPackageDir(String package, String subDir,
BarbackOptions options) {
var packageDir = options.packageDirs[package];
@ -150,7 +134,7 @@ Iterable<String> _listPackageDir(String package, String subDir,
.map((f) => path.relative(f.path, from: packageDir));
}
/** A simple provider that reads files directly from the pub cache. */
/// A simple provider that reads files directly from the pub cache.
class _PackageProvider implements PackageProvider {
Map<String, String> packageDirs;
Iterable<String> get packages => packageDirs.keys;
@ -162,13 +146,13 @@ class _PackageProvider implements PackageProvider {
_toSystemPath(id.path))));
}
/** Convert asset paths to system paths (Assets always use the posix style). */
/// Convert asset paths to system paths (Assets always use the posix style).
String _toSystemPath(String assetPath) {
if (path.Style.platform != path.Style.windows) return assetPath;
return path.joinAll(path.posix.split(assetPath));
}
/** Tell barback which transformers to use and which assets to process. */
/// Tell barback which transformers to use and which assets to process.
void _initBarback(Barback barback, BarbackOptions options) {
var assets = [];
void addAssets(String package, String subDir) {
@ -197,7 +181,7 @@ void _initBarback(Barback barback, BarbackOptions options) {
barback.updateSources(assets);
}
/** Attach error listeners on [barback] so we can report errors. */
/// Attach error listeners on [barback] so we can report errors.
void _attachListeners(Barback barback, BarbackOptions options) {
// Listen for errors and results
barback.errors.listen((e) {
@ -226,10 +210,8 @@ void _attachListeners(Barback barback, BarbackOptions options) {
});
}
/**
* Emits all outputs of [barback] and copies files that we didn't process (like
* dependent package's libraries).
*/
/// Emits all outputs of [barback] and copies files that we didn't process (like
/// dependent package's libraries).
Future _emitAllFiles(Barback barback, BarbackOptions options) {
return barback.getAllAssets().then((assets) {
// Delete existing output folder before we generate anything
@ -272,10 +254,8 @@ Future _emitTransformedFiles(AssetSet assets, BarbackOptions options) {
});
}
/**
* Adds a package symlink from each directory under `out/web/foo/` to
* `out/packages`.
*/
/// Adds a package symlink from each directory under `out/web/foo/` to
/// `out/packages`.
void _addPackagesSymlinks(AssetSet assets, BarbackOptions options) {
var outPackages = path.join(options.outDir, 'packages');
var currentPackage = options.currentPackage;
@ -299,10 +279,8 @@ void _addPackagesSymlinks(AssetSet assets, BarbackOptions options) {
}
}
/**
* Emits a 'packages' directory directly under `out/packages` with the contents
* of every file that was not transformed by barback.
*/
/// Emits a 'packages' directory directly under `out/packages` with the contents
/// of every file that was not transformed by barback.
Future _emitPackagesDir(BarbackOptions options) {
var outPackages = path.join(options.outDir, 'packages');
_ensureDir(outPackages);
@ -319,28 +297,26 @@ Future _emitPackagesDir(BarbackOptions options) {
});
}
/** Ensure [dirpath] exists. */
/// Ensure [dirpath] exists.
void _ensureDir(String dirpath) {
new Directory(dirpath).createSync(recursive: true);
}
/**
* Returns the first directory name on a url-style path, or null if there are no
* slashes.
*/
/// Returns the first directory name on a url-style path, or null if there are
/// no slashes.
String _firstDir(String url) {
var firstSlash = url.indexOf('/');
if (firstSlash == -1) return null;
return url.substring(0, firstSlash);
}
/** Copy a file from [inpath] to [outpath]. */
/// Copy a file from [inpath] to [outpath].
Future _copyFile(String inpath, String outpath) {
_ensureDir(path.dirname(outpath));
return new File(inpath).openRead().pipe(new File(outpath).openWrite());
}
/** Write contents of an [asset] into a file at [filepath]. */
/// Write contents of an [asset] into a file at [filepath].
Future _writeAsset(String filepath, Asset asset) {
_ensureDir(path.dirname(filepath));
return asset.read().pipe(new File(filepath).openWrite());
@ -352,10 +328,8 @@ String _kindFromEntry(LogEntry entry) {
: (level == LogLevel.WARNING ? 'warning' : 'info');
}
/**
* Formatter that generates messages using a format that can be parsed
* by tools, such as the Dart Editor, for reporting error messages.
*/
/// Formatter that generates messages using a format that can be parsed
/// by tools, such as the Dart Editor, for reporting error messages.
String _jsonFormatter(LogEntry entry) {
var kind = _kindFromEntry(entry);
var span = entry.span;
@ -371,10 +345,8 @@ String _jsonFormatter(LogEntry entry) {
}}]);
}
/**
* Formatter that generates messages that are easy to read on the console (used
* by default).
*/
/// Formatter that generates messages that are easy to read on the console (used
/// by default).
String _consoleFormatter(LogEntry entry) {
var kind = _kindFromEntry(entry);
var useColors = stdioType(stdout) == StdioType.TERMINAL;

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Transfomer that combines multiple dart script tags into a single one. */
/// Transfomer that combines multiple dart script tags into a single one.
library polymer.src.build.script_compactor;
import 'dart:async';
@ -19,24 +19,22 @@ import 'package:source_maps/span.dart' show SourceFile;
import 'code_extractor.dart'; // import just for documentation.
import 'common.dart';
/**
* Combines Dart script tags into a single script tag, and creates a new Dart
* file that calls the main function of each of the original script tags.
*
* This transformer assumes that all script tags point to external files. To
* support script tags with inlined code, use this transformer after running
* [InlineCodeExtractor] on an earlier phase.
*
* Internally, this transformer will convert each script tag into an import
* statement to a library, and then uses `initPolymer` (see polymer.dart) to
* process `@initMethod` and `@CustomTag` annotations in those libraries.
*/
/// Combines Dart script tags into a single script tag, and creates a new Dart
/// file that calls the main function of each of the original script tags.
///
/// This transformer assumes that all script tags point to external files. To
/// support script tags with inlined code, use this transformer after running
/// [InlineCodeExtractor] on an earlier phase.
///
/// Internally, this transformer will convert each script tag into an import
/// statement to a library, and then uses `initPolymer` (see polymer.dart) to
/// process `@initMethod` and `@CustomTag` annotations in those libraries.
class ScriptCompactor extends Transformer with PolymerTransformer {
final TransformOptions options;
ScriptCompactor(this.options);
/** Only run on entry point .html files. */
/// Only run on entry point .html files.
Future<bool> isPrimary(Asset input) =>
new Future.value(options.isHtmlEntryPoint(input.id));
@ -123,11 +121,9 @@ class ScriptCompactor extends Transformer with PolymerTransformer {
});
}
/**
* Computes the initializers of [dartLibrary]. That is, a closure that calls
* Polymer.register for each @CustomTag, and any public top-level methods
* labeled with @initMethod.
*/
/// Computes the initializers of [dartLibrary]. That is, a closure that calls
/// Polymer.register for each @CustomTag, and any public top-level methods
/// labeled with @initMethod.
Future<List<_Initializer>> _initializersOf(
AssetId dartLibrary, Transform transform, TransformLogger logger) {
var initializers = [];
@ -171,10 +167,8 @@ class ScriptCompactor extends Transformer with PolymerTransformer {
source.path.startsWith('lib/')
? 'package:${source.package}/${source.path.substring(4)}' : source.path;
/**
* Filter [exportedInitializers] according to [directive]'s show/hide
* combinators and add the result to [initializers].
*/
/// Filter [exportedInitializers] according to [directive]'s show/hide
/// combinators and add the result to [initializers].
// TODO(sigmund): call the analyzer's resolver instead?
static _processExportDirective(ExportDirective directive,
List<_Initializer> exportedInitializers,
@ -191,10 +185,8 @@ class ScriptCompactor extends Transformer with PolymerTransformer {
initializers.addAll(exportedInitializers);
}
/**
* Add an initializer to register [node] as a polymer element if it contains
* an appropriate [CustomTag] annotation.
*/
/// Add an initializer to register [node] as a polymer element if it contains
/// an appropriate [CustomTag] annotation.
static _processClassDeclaration(ClassDeclaration node,
List<_Initializer> initializers, SourceFile file,
TransformLogger logger) {
@ -218,7 +210,7 @@ class ScriptCompactor extends Transformer with PolymerTransformer {
}
}
/** a method initializer for [function]. */
/// Add a method initializer for [function].
static _processFunctionDeclaration(FunctionDeclaration function,
List<_Initializer> initializers, SourceFile file,
TransformLogger logger) {
@ -232,7 +224,7 @@ class ScriptCompactor extends Transformer with PolymerTransformer {
}
}
/** Parse [code] using analyzer. */
/// Parse [code] using analyzer.
CompilationUnit _parseCompilationUnit(String code) {
var errorListener = new _ErrorCollector();
var reader = new CharSequenceReader(code);

View file

@ -4,11 +4,9 @@
library polymer.src.utils;
/**
* Converts a string name with hyphens into an identifier, by removing hyphens
* and capitalizing the following letter. Optionally [startUppercase] to
* captialize the first letter.
*/
/// Converts a string name with hyphens into an identifier, by removing hyphens
/// and capitalizing the following letter. Optionally [startUppercase] to
/// captialize the first letter.
String toCamelCase(String hyphenedName, {bool startUppercase: false}) {
var segments = hyphenedName.split('-');
int start = startUppercase ? 0 : 1;
@ -22,7 +20,7 @@ String toCamelCase(String hyphenedName, {bool startUppercase: false}) {
return segments.join('');
}
/** Reverse of [toCamelCase]. */
/// Reverse of [toCamelCase].
String toHyphenedName(String word) {
var sb = new StringBuffer();
for (int i = 0; i < word.length; i++) {

View file

@ -4,13 +4,11 @@
part of polymer;
/**
* **Warning**: this class is experiental and subject to change.
*
* The implementation for the `polymer-element` element.
*
* Normally you do not need to use this class directly, see [PolymerElement].
*/
/// **Warning**: this class is experiental and subject to change.
///
/// The implementation for the `polymer-element` element.
///
/// Normally you do not need to use this class directly, see [PolymerElement].
class PolymerDeclaration extends HtmlElement {
static const _TAG = 'polymer-element';
@ -46,21 +44,19 @@ class PolymerDeclaration extends HtmlElement {
String _name;
String get name => _name;
/**
* Map of publish properties. Can be a field or a property getter, but if this
* map contains a getter, is because it also has a corresponding setter.
*
* Note: technically these are always single properties, so we could use a
* Symbol instead of a PropertyPath. However there are lookups between this
* map and [_observe] so it is easier to just track paths.
*/
/// Map of publish properties. Can be a field or a property getter, but if
/// this map contains a getter, is because it also has a corresponding setter.
///
/// Note: technically these are always single properties, so we could use a
/// Symbol instead of a PropertyPath. However there are lookups between this
/// map and [_observe] so it is easier to just track paths.
Map<PropertyPath, smoke.Declaration> _publish;
/** The names of published properties for this polymer-element. */
/// The names of published properties for this polymer-element.
Iterable<String> get publishedProperties =>
_publish != null ? _publish.keys.map((p) => '$p') : const [];
/** Same as [_publish] but with lower case names. */
/// Same as [_publish] but with lower case names.
Map<String, smoke.Declaration> _publishLC;
Map<PropertyPath, List<Symbol>> _observe;
@ -78,10 +74,10 @@ class PolymerDeclaration extends HtmlElement {
return template != null ? templateBind(template).content : null;
}
/** Maps event names and their associated method in the element class. */
/// Maps event names and their associated method in the element class.
final Map<String, String> _eventDelegates = {};
/** Expected events per element node. */
/// Expected events per element node.
// TODO(sigmund): investigate whether we need more than 1 set of local events
// per element (why does the js implementation stores 1 per template node?)
Expando<Set<String>> _templateDelegates;
@ -174,13 +170,11 @@ class PolymerDeclaration extends HtmlElement {
// publishConstructor();
}
/**
* Gets the Dart type registered for this name, and sets up declarative
* features. Fills in the [type] and [supertype] fields.
*
* *Note*: unlike the JavaScript version, we do not have to metaprogram the
* prototype, which simplifies this method.
*/
/// Gets the Dart type registered for this name, and sets up declarative
/// features. Fills in the [type] and [supertype] fields.
///
/// *Note*: unlike the JavaScript version, we do not have to metaprogram the
/// prototype, which simplifies this method.
void buildType(String name, String extendee) {
// get our custom type
_type = _getRegisteredType(name);
@ -207,7 +201,7 @@ class PolymerDeclaration extends HtmlElement {
// x-platform fixup
}
/** Implement various declarative features. */
/// Implement various declarative features.
void desugar(name, extendee) {
// compile list of attributes to copy to instances
accumulateInstanceAttributes();
@ -328,7 +322,7 @@ class PolymerDeclaration extends HtmlElement {
return !blackList.containsKey(name) && !name.startsWith('on-');
}
/** Extracts events from the element tag attributes. */
/// Extracts events from the element tag attributes.
void parseHostEvents() {
addAttributeDelegates(_eventDelegates);
}
@ -351,10 +345,8 @@ class PolymerDeclaration extends HtmlElement {
return (url.split('/')..removeLast()..add('')).join('/');
}
/**
* Install external stylesheets loaded in <element> elements into the
* element's template.
*/
/// Install external stylesheets loaded in <element> elements into the
/// element's template.
void installSheets() {
cacheSheets();
cacheStyles();
@ -372,14 +364,12 @@ class PolymerDeclaration extends HtmlElement {
for (var s in styles) s.remove();
}
/**
* Takes external stylesheets loaded in an `<element>` element and moves
* their content into a style element inside the `<element>`'s template.
* The sheet is then removed from the `<element>`. This is done only so
* that if the element is loaded in the main document, the sheet does
* not become active.
* Note, ignores sheets with the attribute 'polymer-scope'.
*/
/// Takes external stylesheets loaded in an `<element>` element and moves
/// their content into a style element inside the `<element>`'s template.
/// The sheet is then removed from the `<element>`. This is done only so
/// that if the element is loaded in the main document, the sheet does
/// not become active.
/// Note, ignores sheets with the attribute 'polymer-scope'.
void installLocalSheets() {
var sheets = this.sheets.where(
(s) => !s.attributes.containsKey(_SCOPE_ATTR));
@ -407,13 +397,11 @@ class PolymerDeclaration extends HtmlElement {
return nodes;
}
/**
* Promotes external stylesheets and style elements with the attribute
* polymer-scope='global' into global scope.
* This is particularly useful for defining @keyframe rules which
* currently do not function in scoped or shadow style elements.
* (See wkb.ug/72462)
*/
/// Promotes external stylesheets and style elements with the attribute
/// polymer-scope='global' into global scope.
/// This is particularly useful for defining @keyframe rules which
/// currently do not function in scoped or shadow style elements.
/// (See wkb.ug/72462)
// TODO(sorvell): remove when wkb.ug/72462 is addressed.
void installGlobalStyles() {
var style = styleForScope(_STYLE_GLOBAL_SCOPE);
@ -449,10 +437,8 @@ class PolymerDeclaration extends HtmlElement {
..attributes[_STYLE_SCOPE_ATTRIBUTE] = '$name-$scopeDescriptor';
}
/**
* Fetch a list of all *Changed methods so we can observe the associated
* properties.
*/
/// Fetch a list of all *Changed methods so we can observe the associated
/// properties.
void inferObservers() {
var options = const smoke.QueryOptions(includeFields: false,
includeProperties: false, includeMethods: true, includeInherited: true);
@ -468,10 +454,8 @@ class PolymerDeclaration extends HtmlElement {
}
}
/**
* Fetch a list of all methods annotated with [ObserveProperty] so we can
* observe the associated properties.
*/
/// Fetch a list of all methods annotated with [ObserveProperty] so we can
/// observe the associated properties.
void explodeObservers() {
var options = const smoke.QueryOptions(includeFields: false,
includeProperties: false, includeMethods: true, includeInherited: true,
@ -544,17 +528,15 @@ Map<PropertyPath, smoke.Declaration> _getPublishedProperties(
return props;
}
/** Attribute prefix used for declarative event handlers. */
/// Attribute prefix used for declarative event handlers.
const _EVENT_PREFIX = 'on-';
/** Whether an attribute declares an event. */
/// Whether an attribute declares an event.
bool _hasEventPrefix(String attr) => attr.startsWith(_EVENT_PREFIX);
String _removeEventPrefix(String name) => name.substring(_EVENT_PREFIX.length);
/**
* Using Polymer's platform/src/ShadowCSS.js passing the style tag's content.
*/
/// Using Polymer's platform/src/ShadowCSS.js passing the style tag's content.
void _shimShadowDomStyling(DocumentFragment template, String name,
String extendee) {
if (template == null || !_hasShadowDomPolyfill) return;

View file

@ -4,35 +4,31 @@
part of polymer;
/**
* Use this annotation to publish a field as an attribute. For example:
*
* class MyPlaybackElement extends PolymerElement {
* // This will be available as an HTML attribute, for example:
* // <my-playback volume="11">
* @published double volume;
* }
*/
/// Use this annotation to publish a field as an attribute. For example:
///
/// class MyPlaybackElement extends PolymerElement {
/// // This will be available as an HTML attribute, for example:
/// // <my-playback volume="11">
/// @published double volume;
/// }
const published = const PublishedProperty();
/** An annotation used to publish a field as an attribute. See [published]. */
/// An annotation used to publish a field as an attribute. See [published].
class PublishedProperty extends ObservableProperty {
const PublishedProperty();
}
/**
* Use this type to observe a property and have the method be called when it
* changes. For example:
*
* @ObserveProperty('foo.bar baz qux')
* validate() {
* // use this.foo.bar, this.baz, and this.qux in validation
* ...
* }
*
* Note that you can observe a property path, and more than a single property
* can be specified in a space-delimited list or as a constant List.
*/
/// Use this type to observe a property and have the method be called when it
/// changes. For example:
///
/// @ObserveProperty('foo.bar baz qux')
/// validate() {
/// // use this.foo.bar, this.baz, and this.qux in validation
/// ...
/// }
///
/// Note that you can observe a property path, and more than a single property
/// can be specified in a space-delimited list or as a constant List.
class ObserveProperty {
final _names;
@ -51,13 +47,11 @@ class ObserveProperty {
const ObserveProperty(this._names);
}
/**
* The mixin class for Polymer elements. It provides convenience features on top
* of the custom elements web standard.
*
* If this class is used as a mixin,
* you must call `polymerCreated()` from the body of your constructor.
*/
/// The mixin class for Polymer elements. It provides convenience features on
/// top of the custom elements web standard.
///
/// If this class is used as a mixin,
/// you must call `polymerCreated()` from the body of your constructor.
abstract class Polymer implements Element, Observable, NodeBindExtension {
// Fully ported from revision:
// https://github.com/Polymer/polymer/blob/37eea00e13b9f86ab21c85a955585e8e4237e3d2
@ -72,18 +66,16 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
// src/instance/utils.js
// TODO(jmesserly): should this really be public?
/** Regular expression that matches data-bindings. */
/// Regular expression that matches data-bindings.
static final bindPattern = new RegExp(r'\{\{([^{}]*)}}');
/**
* Like [document.register] but for Polymer elements.
*
* Use the [name] to specify custom elment's tag name, for example:
* "fancy-button" if the tag is used as `<fancy-button>`.
*
* The [type] is the type to construct. If not supplied, it defaults to
* [PolymerElement].
*/
/// Like [document.register] but for Polymer elements.
///
/// Use the [name] to specify custom elment's tag name, for example:
/// "fancy-button" if the tag is used as `<fancy-button>`.
///
/// The [type] is the type to construct. If not supplied, it defaults to
/// [PolymerElement].
// NOTE: this is called "element" in src/declaration/polymer-element.js, and
// exported as "Polymer".
static void register(String name, [Type type]) {
@ -103,15 +95,13 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
static final Completer _ready = new Completer();
/**
* Future indicating that the Polymer library has been loaded and is ready
* for use.
*/
/// Future indicating that the Polymer library has been loaded and is ready
/// for use.
static Future get onReady => _ready.future;
PolymerDeclaration _declaration;
/** The most derived `<polymer-element>` declaration for this element. */
/// The most derived `<polymer-element>` declaration for this element.
PolymerDeclaration get declaration => _declaration;
Map<String, StreamSubscription> _observers;
@ -129,12 +119,10 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
BindingDelegate syntax = _polymerSyntax;
/**
* Shadow roots created by [parseElement]. See [getShadowRoot].
*/
/// Shadow roots created by [parseElement]. See [getShadowRoot].
final _shadowRoots = new HashMap<String, ShadowRoot>();
/** Map of items in the shadow root(s) by their [Element.id]. */
/// Map of items in the shadow root(s) by their [Element.id].
// TODO(jmesserly): various issues:
// * wrap in UnmodifiableMapView?
// * should we have an object that implements noSuchMethod?
@ -146,23 +134,19 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
@reflectable final Map<String, Element> $ =
new ObservableMap<String, Element>();
/**
* Gets the shadow root associated with the corresponding custom element.
*
* This is identical to [shadowRoot], unless there are multiple levels of
* inheritance and they each have their own shadow root. For example,
* this can happen if the base class and subclass both have `<template>` tags
* in their `<polymer-element>` tags.
*/
/// Gets the shadow root associated with the corresponding custom element.
///
/// This is identical to [shadowRoot], unless there are multiple levels of
/// inheritance and they each have their own shadow root. For example,
/// this can happen if the base class and subclass both have `<template>` tags
/// in their `<polymer-element>` tags.
// TODO(jmesserly): Polymer does not have this feature. Reconcile.
ShadowRoot getShadowRoot(String customTagName) => _shadowRoots[customTagName];
/**
* If this class is used as a mixin, this method must be called from inside
* of the `created()` constructor.
*
* If this class is a superclass, calling `super.created()` is sufficient.
*/
/// If this class is used as a mixin, this method must be called from inside
/// of the `created()` constructor.
///
/// If this class is a superclass, calling `super.created()` is sufficient.
void polymerCreated() {
if (this.ownerDocument.window != null || alwaysPrepare ||
_preparingElements > 0) {
@ -170,7 +154,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
}
/** Retrieves the custom element name by inspecting the host node. */
/// Retrieves the custom element name by inspecting the host node.
String get _customTagName {
var isAttr = attributes['is'];
return (isAttr == null || isAttr == '') ? localName : isAttr;
@ -198,7 +182,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
ready();
}
/** Called when [prepareElement] is finished. */
/// Called when [prepareElement] is finished.
void ready() {}
void enteredView() {
@ -212,7 +196,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
if (!preventDispose) asyncUnbindAll();
}
/** Recursive ancestral <element> initialization, oldest first. */
/// Recursive ancestral <element> initialization, oldest first.
void parseDeclarations(PolymerDeclaration declaration) {
if (declaration != null) {
parseDeclarations(declaration.superDeclaration);
@ -220,9 +204,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
}
/**
* Parse input `<polymer-element>` as needed, override for custom behavior.
*/
/// Parse input `<polymer-element>` as needed, override for custom behavior.
void parseDeclaration(Element elementElement) {
var template = fetchTemplate(elementElement);
@ -243,15 +225,11 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
_shadowRoots[name] = root;
}
/**
* Return a shadow-root template (if desired), override for custom behavior.
*/
/// Return a shadow-root template (if desired), override for custom behavior.
Element fetchTemplate(Element elementElement) =>
elementElement.querySelector('template');
/**
* Utility function that stamps a `<template>` into light-dom.
*/
/// Utility function that stamps a `<template>` into light-dom.
Node lightFromTemplate(Element template) {
if (template == null) return null;
// stamp template
@ -267,19 +245,16 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
return dom;
}
/**
* Utility function that creates a shadow root from a `<template>`.
*
* The base implementation will return a [ShadowRoot], but you can replace it
* with your own code and skip ShadowRoot creation. In that case, you should
* return `null`.
*
* In your overridden method, you can use [instanceTemplate] to stamp the
* template and initialize data binding, and [shadowRootReady] to intialize
* other Polymer features like event handlers. It is fine to call
* shadowRootReady with a node something other than a ShadowRoot; for example,
* with this Node.
*/
/// Utility function that creates a shadow root from a `<template>`.
///
/// The base implementation will return a [ShadowRoot], but you can replace it
/// with your own code and skip ShadowRoot creation. In that case, you should
/// return `null`.
///
/// In your overridden method, you can use [instanceTemplate] to stamp the
/// template and initialize data binding, and [shadowRootReady] to intialize
/// other Polymer features like event handlers. It is fine to call
/// shadowRootReady with a node other than a ShadowRoot such as with `this`.
ShadowRoot shadowFromTemplate(Element template) {
if (template == null) return null;
// cache elder shadow root (if any)
@ -315,7 +290,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
// PointerGestures.register(root);
}
/** Locate nodes with id and store references to them in [$] hash. */
/// Locate nodes with id and store references to them in [$] hash.
void marshalNodeReferences(Node root) {
if (root == null) return;
for (var n in (root as dynamic).querySelectorAll('[id]')) {
@ -330,12 +305,10 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
// TODO(jmesserly): this could be a top level method.
/**
* Returns a future when `node` changes, or when its children or subtree
* changes.
*
* Use [MutationObserver] if you want to listen to a stream of changes.
*/
/// Returns a future when `node` changes, or when its children or subtree
/// changes.
///
/// Use [MutationObserver] if you want to listen to a stream of changes.
Future<List<MutationRecord>> onMutation(Node node) {
var completer = new Completer();
new MutationObserver((mutations, observer) {
@ -356,10 +329,8 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
attributes.forEach(attributeToProperty);
}
/**
* If attribute [name] is mapped to a property, deserialize
* [value] into that property.
*/
/// If attribute [name] is mapped to a property, deserialize
/// [value] into that property.
void attributeToProperty(String name, String value) {
// try to match this attribute to a property (attributes are
// all lower-case, so this is case-insensitive search)
@ -388,7 +359,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
}
/** Return the published property matching name, or null. */
/// Return the published property matching name, or null.
// TODO(jmesserly): should we just return Symbol here?
smoke.Declaration propertyForAttribute(String name) {
final publishLC = _declaration._publishLC;
@ -397,9 +368,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
return publishLC[name];
}
/**
* Convert representation of [value] based on [type] and [currentValue].
*/
/// Convert representation of [value] based on [type] and [currentValue].
Object deserializeValue(String value, Object currentValue, Type type) =>
deserialize.deserializeValue(value, currentValue, type);
@ -434,19 +403,17 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
}
/**
* Creates the document fragment to use for each instance of the custom
* element, given the `<template>` node. By default this is equivalent to:
*
* templateBind(template).createInstance(this, polymerSyntax);
*
* Where polymerSyntax is a singleton `PolymerExpressions` instance from the
* [polymer_expressions](https://pub.dartlang.org/packages/polymer_expressions)
* package.
*
* You can override this method to change the instantiation behavior of the
* template, for example to use a different data-binding syntax.
*/
/// Creates the document fragment to use for each instance of the custom
/// element, given the `<template>` node. By default this is equivalent to:
///
/// templateBind(template).createInstance(this, polymerSyntax);
///
/// Where polymerSyntax is a singleton `PolymerExpressions` instance from the
/// [polymer_expressions](https://pub.dartlang.org/packages/polymer_expressions)
/// package.
///
/// You can override this method to change the instantiation behavior of the
/// template, for example to use a different data-binding syntax.
DocumentFragment instanceTemplate(Element template) =>
templateBind(template).createInstance(this, syntax);
@ -541,7 +508,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
}
/** Set up property observers. */
/// Set up property observers.
void observeProperties() {
final observe = _declaration._observe;
final publish = _declaration._publish;
@ -573,7 +540,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
/** Responds to property changes on this element. */
/// Responds to property changes on this element.
void notifyPropertyChanges(List newValues, Map oldValues, List paths) {
final observe = _declaration._observe;
final publish = _declaration._publish;
@ -645,7 +612,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
unregisterObservers();
}
/** Bookkeeping observers for memory management. */
/// Bookkeeping observers for memory management.
void registerObserver(String name, StreamSubscription sub) {
if (_observers == null) {
_observers = new Map<String, StreamSubscription>();
@ -667,17 +634,15 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
_observers = null;
}
/**
* Bind a [property] in this object to a [path] in model. *Note* in Dart it
* is necessary to also define the field:
*
* var myProperty;
*
* ready() {
* super.ready();
* bindProperty(#myProperty, this, 'myModel.path.to.otherProp');
* }
*/
/// Bind a [property] in this object to a [path] in model. *Note* in Dart it
/// is necessary to also define the field:
///
/// var myProperty;
///
/// ready() {
/// super.ready();
/// bindProperty(#myProperty, this, 'myModel.path.to.otherProp');
/// }
Bindable bindProperty(Symbol name, Bindable bindable) {
// Dart note: normally we only reach this code when we know it's a
// property, but if someone uses bindProperty directly they might get a
@ -703,7 +668,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
return new _PolymerBinding(this, name, bindable);
}
/** Attach event listeners on the host (this) element. */
/// Attach event listeners on the host (this) element.
void addHostListeners() {
var events = _declaration._eventDelegates;
if (events.isEmpty) return;
@ -752,10 +717,8 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
String findEventDelegate(Event event) =>
_declaration._eventDelegates[_eventNameFromType(event.type)];
/**
* Calls [methodOrCallback] with [args] if it is a closure, otherwise, treat
* it as a method name in [object], and invoke it.
*/
/// Calls [methodOrCallback] with [args] if it is a closure, otherwise, treat
/// it as a method name in [object], and invoke it.
void dispatchMethod(object, callbackOrMethod, List args) {
bool log = _eventsLog.isLoggable(Level.FINE);
if (log) _eventsLog.fine('>>> [$localName]: dispatch $callbackOrMethod');
@ -778,15 +741,13 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
if (log) _eventsLog.info('<<< [$localName]: dispatch $callbackOrMethod');
}
/**
* Bind events via attributes of the form `on-eventName`. This method can be
* use to hooks into the model syntax and adds event listeners as needed. By
* default, binding paths are always method names on the root model, the
* custom element in which the node exists. Adding a '@' in the path directs
* the event binding to use the model path as the event listener. In both
* cases, the actual listener is attached to a generic method which evaluates
* the bound path at event execution time.
*/
/// Bind events via attributes of the form `on-eventName`. This method can be
/// use to hooks into the model syntax and adds event listeners as needed. By
/// default, binding paths are always method names on the root model, the
/// custom element in which the node exists. Adding a '@' in the path directs
/// the event binding to use the model path as the event listener. In both
/// cases, the actual listener is attached to a generic method which evaluates
/// the bound path at event execution time.
// from src/instance/event.js#prepareBinding
static PrepareBindingFunction prepareBinding(String path, String name, node) {
@ -804,18 +765,16 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
};
}
/** Call [methodName] method on this object with [args]. */
/// Call [methodName] method on this object with [args].
invokeMethod(Symbol methodName, List args) =>
smoke.invoke(this, methodName, args, adjust: true);
/**
* Invokes a function asynchronously.
* This will call `Platform.flush()` and then return a `new Timer`
* with the provided [method] and [timeout].
*
* If you would prefer to run the callback using
* [window.requestAnimationFrame], see the [async] method.
*/
/// Invokes a function asynchronously.
/// This will call `Platform.flush()` and then return a `new Timer`
/// with the provided [method] and [timeout].
///
/// If you would prefer to run the callback using
/// [window.requestAnimationFrame], see the [async] method.
// Dart note: "async" is split into 2 methods so it can have a sensible type
// signatures. Also removed the various features that don't make sense in a
// Dart world, like binding to "this" and taking arguments list.
@ -826,15 +785,13 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
return new Timer(timeout, method);
}
/**
* Invokes a function asynchronously.
* This will call `Platform.flush()` and then call
* [window.requestAnimationFrame] with the provided [method] and return the
* result.
*
* If you would prefer to run the callback after a given duration, see
* the [asyncTimer] method.
*/
/// Invokes a function asynchronously.
/// This will call `Platform.flush()` and then call
/// [window.requestAnimationFrame] with the provided [method] and return the
/// result.
///
/// If you would prefer to run the callback after a given duration, see
/// the [asyncTimer] method.
int async(RequestAnimationFrameCallback method) {
// when polyfilling Object.observe, ensure changes
// propagate before executing the async method
@ -842,10 +799,8 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
return window.requestAnimationFrame(method);
}
/**
* Fire a [CustomEvent] targeting [toNode], or this if toNode is not
* supplied. Returns the [detail] object.
*/
/// Fire a [CustomEvent] targeting [toNode], or this if toNode is not
/// supplied. Returns the [detail] object.
Object fire(String type, {Object detail, Node toNode, bool canBubble}) {
var node = toNode != null ? toNode : this;
//log.events && console.log('[%s]: sending [%s]', node.localName, inType);
@ -857,9 +812,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
return detail;
}
/**
* Fire an event asynchronously. See [async] and [fire].
*/
/// Fire an event asynchronously. See [async] and [fire].
asyncFire(String type, {Object detail, Node toNode, bool canBubble}) {
// TODO(jmesserly): I'm not sure this method adds much in Dart, it's easy to
// add "() =>"
@ -867,9 +820,7 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
type, detail: detail, toNode: toNode, canBubble: canBubble));
}
/**
* Remove [className] from [old], add class to [anew], if they exist.
*/
/// Remove [className] from [old], add class to [anew], if they exist.
void classFollows(Element anew, Element old, String className) {
if (old != null) {
old.classes.remove(className);
@ -879,23 +830,21 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
}
}
/**
* Installs external stylesheets and <style> elements with the attribute
* polymer-scope='controller' into the scope of element. This is intended
* to be a called during custom element construction. Note, this incurs a
* per instance cost and should be used sparingly.
*
* The need for this type of styling should go away when the shadowDOM spec
* addresses these issues:
*
* https://www.w3.org/Bugs/Public/show_bug.cgi?id=21391
* https://www.w3.org/Bugs/Public/show_bug.cgi?id=21390
* https://www.w3.org/Bugs/Public/show_bug.cgi?id=21389
*
* @param element The custom element instance into whose controller (parent)
* scope styles will be installed.
* @param elementElement The <element> containing controller styles.
*/
/// Installs external stylesheets and <style> elements with the attribute
/// polymer-scope='controller' into the scope of element. This is intended
/// to be a called during custom element construction. Note, this incurs a
/// per instance cost and should be used sparingly.
///
/// The need for this type of styling should go away when the shadowDOM spec
/// addresses these issues:
///
/// https://www.w3.org/Bugs/Public/show_bug.cgi?id=21391
/// https://www.w3.org/Bugs/Public/show_bug.cgi?id=21390
/// https://www.w3.org/Bugs/Public/show_bug.cgi?id=21389
///
/// @param element The custom element instance into whose controller (parent)
/// scope styles will be installed.
/// @param elementElement The <element> containing controller styles.
// TODO(sorvell): remove when spec issues are addressed
void installControllerStyles() {
var scope = findStyleController();
@ -953,13 +902,11 @@ abstract class Polymer implements Element, Observable, NodeBindExtension {
scope.append(clone);
}
/**
* Prevents flash of unstyled content
* This is the list of selectors for veiled elements
*/
/// Prevents flash of unstyled content
/// This is the list of selectors for veiled elements
static List<Element> veiledElements = ['body'];
/** Apply unveil class. */
/// Apply unveil class.
static void unveilElements() {
window.requestAnimationFrame((_) {
var nodes = document.querySelectorAll('.$_VEILED_CLASS');
@ -1037,11 +984,9 @@ final Expando _shadowHost = new Expando<Polymer>();
final Expando _eventHandledTable = new Expando<Set<Node>>();
/**
* Base class for PolymerElements deriving from HtmlElement.
*
* See [Polymer].
*/
/// Base class for PolymerElements deriving from HtmlElement.
///
/// See [Polymer].
class PolymerElement extends HtmlElement with Polymer, Observable {
PolymerElement.created() : super.created() {
polymerCreated();

View file

@ -4,14 +4,12 @@
part of polymer;
/**
* Invoke [callback] in [wait], unless the job is re-registered,
* which resets the timer. For example:
*
* _myJob = runJob(_myJob, callback, const Duration(milliseconds: 100));
*
* Returns a job handle which can be used to re-register a job.
*/
/// Invoke [callback] in [wait], unless the job is re-registered,
/// which resets the timer. For example:
///
/// _myJob = runJob(_myJob, callback, const Duration(milliseconds: 100));
///
/// Returns a job handle which can be used to re-register a job.
// Dart note: renamed to runJob to avoid conflict with instance member "job".
_Job _runJob(_Job job, void callback(), Duration wait) {
if (job != null) {

View file

@ -4,28 +4,24 @@
part of polymer;
/** Annotation used to automatically register polymer elements. */
/// Annotation used to automatically register polymer elements.
class CustomTag {
final String tagName;
const CustomTag(this.tagName);
}
/**
* Metadata used to label static or top-level methods that are called
* automatically when loading the library of a custom element.
*/
/// Metadata used to label static or top-level methods that are called
/// automatically when loading the library of a custom element.
const initMethod = const _InitMethodAnnotation();
/**
* Initializes a polymer application as follows:
* * set up up polling for observable changes
* * initialize Model-Driven Views
* * Include some style to prevent flash of unstyled content (FOUC)
* * for each library included transitively from HTML and HTML imports,
* register custom elements declared there (labeled with [CustomTag]) and
* invoke the initialization method on it (top-level functions annotated with
* [initMethod]).
*/
/// Initializes a polymer application as follows:
/// * set up up polling for observable changes
/// * initialize Model-Driven Views
/// * Include some style to prevent flash of unstyled content (FOUC)
/// * for each library included transitively from HTML and HTML imports,
/// register custom elements declared there (labeled with [CustomTag]) and
/// invoke the initialization method on it (top-level functions annotated with
/// [initMethod]).
Zone initPolymer() {
// We use this pattern, and not the inline lazy initialization pattern, so we
// can help dart2js detect that _discoverInitializers can be tree-shaken for
@ -42,13 +38,11 @@ Zone initPolymer() {
return initPolymerOptimized();
}
/**
* Same as [initPolymer], but runs the version that is optimized for deployment
* to the internet. The biggest difference is it omits the [Zone] that
* automatically invokes [Observable.dirtyCheck], and the list of initializers
* must be supplied instead of being dynamically searched for at runtime using
* mirrors.
*/
/// Same as [initPolymer], but runs the version that is optimized for deployment
/// to the internet. The biggest difference is it omits the [Zone] that
/// automatically invokes [Observable.dirtyCheck], and the list of initializers
/// must be supplied instead of being dynamically searched for at runtime using
/// mirrors.
Zone initPolymerOptimized() {
// TODO(sigmund): refactor this so we can replace it by codegen.
smoke.useMirrors();
@ -69,30 +63,25 @@ Zone initPolymerOptimized() {
return Zone.current;
}
/**
* Configures [initPolymer] making it optimized for deployment to the internet.
* With this setup the initializer list is supplied instead of being dynamically
* searched for at runtime. Additionally, after this method is called,
* [initPolymer] omits the [Zone] that automatically invokes
* [Observable.dirtyCheck].
*/
/// Configures [initPolymer] making it optimized for deployment to the internet.
/// With this setup the initializer list is supplied instead of searched for
/// at runtime. Additionally, after this method is called [initPolymer] omits
/// the [Zone] that automatically invokes [Observable.dirtyCheck].
void configureForDeployment(List<Function> initializers) {
_initializers = initializers;
_deployMode = true;
}
/**
* List of initializers that by default will be executed when calling
* initPolymer. If null, initPolymer will compute the list of initializers by
* crawling HTML imports, searchfing for script tags, and including an
* initializer for each type tagged with a [CustomTag] annotation and for each
* top-level method annotated with [initMethod]. The value of this field is
* assigned programatically by the code generated from the polymer deploy
* scripts.
*/
/// List of initializers that by default will be executed when calling
/// initPolymer. If null, initPolymer will compute the list of initializers by
/// crawling HTML imports, searchfing for script tags, and including an
/// initializer for each type tagged with a [CustomTag] annotation and for each
/// top-level method annotated with [initMethod]. The value of this field is
/// assigned programatically by the code generated from the polymer deploy
/// scripts.
List<Function> _initializers;
/** True if we're in deployment mode. */
/// True if we're in deployment mode.
bool _deployMode = false;
List<Function> _discoverInitializers() {
@ -110,13 +99,11 @@ List<Function> _discoverInitializers() {
return initializers;
}
/**
* Walks the HTML import structure to discover all script tags that are
* implicitly loaded. This code is only used in Dartium and should only be
* called after all HTML imports are resolved. Polymer ensures this by asking
* users to put their Dart script tags after all HTML imports (this is checked
* by the linter, and Dartium will otherwise show an error message).
*/
/// Walks the HTML import structure to discover all script tags that are
/// implicitly loaded. This code is only used in Dartium and should only be
/// called after all HTML imports are resolved. Polymer ensures this by asking
/// users to put their Dart script tags after all HTML imports (this is checked
/// by the linter, and Dartium will otherwise show an error message).
List<String> _discoverScripts(Document doc, String baseUri,
[Set<Document> seen, List<String> scripts]) {
if (seen == null) seen = new Set<Document>();
@ -146,7 +133,7 @@ List<String> _discoverScripts(Document doc, String baseUri,
return scripts;
}
/** All libraries in the current isolate. */
/// All libraries in the current isolate.
final _libs = currentMirrorSystem().libraries;
// TODO(sigmund): explore other (cheaper) ways to resolve URIs relative to the
@ -164,16 +151,14 @@ bool _isHttpStylePackageUrl(Uri uri) {
(uriPath.contains('/packages/') || uriPath.startsWith('packages/'));
}
/**
* Reads the library at [uriString] (which can be an absolute URI or a relative
* URI from the root library), and:
*
* * If present, invokes any top-level and static functions marked
* with the [initMethod] annotation (in the order they appear).
*
* * Registers any [PolymerElement] that is marked with the [CustomTag]
* annotation.
*/
/// Reads the library at [uriString] (which can be an absolute URI or a relative
/// URI from the root library), and:
///
/// * If present, invokes any top-level and static functions marked
/// with the [initMethod] annotation (in the order they appear).
///
/// * Registers any [PolymerElement] that is marked with the [CustomTag]
/// annotation.
void _loadLibrary(String uriString, List<Function> initializers) {
var uri = _rootUri.resolve(uriString);
var lib = _libs[uri];

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Transfomer used for pub-serve and pub-deploy. */
/// Transfomer used for pub-serve and pub-deploy.
library polymer.transformer;
import 'package:barback/barback.dart';
@ -16,17 +16,15 @@ import 'src/build/linter.dart';
import 'src/build/polyfill_injector.dart';
import 'src/build/script_compactor.dart';
/**
* The Polymer transformer, which internally runs several phases that will:
* * Extract inlined script tags into their separate files
* * Apply the observable transformer on every Dart script.
* * Inline imported html files
* * Combine scripts from multiple files into a single script tag
* * Inject extra polyfills needed to run on all browsers.
*
* At the end of these phases, this tranformer produces a single entrypoint HTML
* file with a single Dart script that can later be compiled with dart2js.
*/
/// The Polymer transformer, which internally runs several phases that will:
/// * Extract inlined script tags into their separate files
/// * Apply the observable transformer on every Dart script.
/// * Inline imported html files
/// * Combine scripts from multiple files into a single script tag
/// * Inject extra polyfills needed to run on all browsers.
///
/// At the end of these phases, this tranformer produces a single entrypoint
/// HTML file with a single Dart script that can later be compiled with dart2js.
class PolymerTransformerGroup implements TransformerGroup {
final Iterable<Iterable> phases;

View file

@ -20,15 +20,11 @@ String _removeTrailingWhitespace(String str) =>
str.splitMapJoin('\n',
onNonMatch: (s) => s.replaceAll(new RegExp(r'\s+$'), ''));
/**
* A helper package provider that has files stored in memory, also wraps
* [Barback] to simply our tests.
*/
/// A helper package provider that has files stored in memory, also wraps
/// [Barback] to simply our tests.
class TestHelper implements PackageProvider {
/**
* Maps from an asset string identifier of the form 'package|path' to the
* file contents.
*/
/// Maps from an asset string identifier of the form 'package|path' to the
/// file contents.
final Map<String, String> files;
final Iterable<String> packages;
final List<String> messages;
@ -88,10 +84,8 @@ class TestHelper implements PackageProvider {
logSubscription.cancel();
}
/**
* Tells barback which files have changed, and thus anything that depends on
* it on should be computed. By default mark all the input files.
*/
/// Tells barback which files have changed, and thus anything that depends on
/// it on should be computed. By default mark all the input files.
void run([Iterable<String> paths]) {
if (paths == null) paths = files.keys;
barback.updateSources(paths.map(idFromString));

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/** Tests for some of the utility helper functions used by the compiler. */
/// Tests for some of the utility helper functions used by the compiler.
library polymer.test.utils_test;
import 'package:unittest/compact_vm_config.dart';

View file

@ -57,11 +57,13 @@ String fixContents(List<String> lines, String path) {
line = null;
} else {
var match = blockLine.firstMatch(line);
var comment = match[1];
if (comment != '') {
line = '$indent/// $comment';
} else {
line = '$indent///';
if (match != null) {
var comment = match[1];
if (comment != '') {
line = '$indent/// $comment';
} else {
line = '$indent///';
}
}
}
} else {