Tuesday, January 7, 2014

Importing Per-Polymer Configuration


I had a good time updating and improving <ice-code-editor>, the Polymer version of the ICE Code Editor. I even have a nice demo page for my efforts. As cool as that was, I was unable to explore one aspect of the Polymer that I would have liked: importing config directly into the Polymer's <content>.

So tonight, I would like to see if I can import configuration into a Polymer instance. And instead of a complex Polymer that wraps a large codebase adding too many moving parts to the equation, I start with a small test case. What I am hoping to get working tonight it the ability to import configuration when using a Polymer. For a simple <hello-you> tag, that would be in the form of the usual Polymer usage plus a <link> tag inside the tag:
  <head>
    <!-- 1. Load the polyfills required to make the platform work -->
    <script src="bower_components/platform/platform.js"></script>
    <!-- 2. Load component(s) -->
    <link rel="import" href="scripts/hello-you.html">
  </head>
  <body>
    <div class="container">
      <hello-you>
        <link rel="import" href="scripts/config2.json">
      </hello-you>
    </div>
  </body>
Something that is inside a Polymer like that can be distributed into the rendered Polymer if the Polymer's template contains a <content> tag. For tonight's purposes, I stick with a version that does not include a <content> tag in the template:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-you">
  <template>
    <h2>{{hello}} {{your_name}}</h2>
    <p>
      <input value="{{your_name}}">
      <input type=submit value="{{done}}!" on-click="{{feelingLucky}}">
    </p>
    <!-- ... -->
  </template>
  <script>
    Polymer('hello-you', {
      your_name: '',
      hello: 'Hello',
      done: 'Done',
      instructions: 'Introduce yourself for an amazing personalized experience!',
      feelingLucky: function() { /* ... */ }
    });
  </script>
</polymer-element>
To load the configuration, I need to add a ready() lifecycle method to this Polymer. It needs to the query the element for all <link> tags that contain JSON configuration. If there are any, it needs to parse the JSON and update the this.hello attribute for a configured greeting value. This should work:
      ready: function() {
        var links = this.
          querySelectorAll('link[rel=import]').
          array().
          filter(function(el) {
            return el.href.match(/config.*\.json/)
          });

        if (!links.length) return;

        var json = links[0].import.textContent.replace(/import/, '');
        var config = JSON.parse(json);
        if (config['greeting'] !== undefined) this.hello = config['greeting'];
      },
The only trick in there is to remove the word “import” from the text content of the <link> tag's import. I am unsure why this is there, but removing it leaves me with just the JSON, which can be parsed.

If I create a JSON config file with the following:
{
  "greeting": "Howdy"
}
Then I it works! When I load the page with my small test case, I get the configured “Howdy” greeting instead of the default “Hello”:



And, if I comment out the configuration import:
      <hello-you>
        <-- link rel="import" href="scripts/config2.json" -->
      </hello-you>

Then I get the default “Hello” greeting:



So this would seem legit! There are still some questions to answer. Most pressing is how this would work if I need to distribute nodes and import configuration. I also need to see if I can get this working in Dart. But, for a first attempt, this seems promising.


Day #989

Monday, January 6, 2014

Too Many Parts


I think I have done all I can to ready <ice-code-editor>, the Polymer version of the ICE Code Editor, for deployment. Despite best efforts, I cannot generate minified JavaScript, though the regular dart2js output works just fine. There is still a trick or two I would like to try.

First, I tried rebasing my polymer branch back onto my master branch, hoping some of the more recent changes might help with the minified output. It doesn't. I also tried minifying the dart2js output with both the YUI Compressor and Closure. Neither is able to parse the dart2js output. So again, I am stuck with the non-minified dart2js from yesterday.

At least I tried.

I have been working on the configuration chapter in Patterns in Polymer and, at the risk of treating that like a golden hammer, I am curious if I might be able to use that technique in this Polymer. It is not quite a direct application because that chapter works with configuration in the Polymer definition itself. Here, I would like to configure individual <ice-code-editor> elements. Specifically, I want to specify the data to be included in the in-page editor.

Currently, this is accomplished with a src attribute:
<ice-code-editor src="embed_a.html" line_number="21"></ice-code-editor>
Here, the emdeb_a.html is a separate resource that contains the content that is ready to edit and creates the preview:



This is currently retrieved via an HttpRequest, but perhaps something like a <link> import would work:
<ice-code-editor line_number="21">
  <link rel="import" href="embed_a.html">
</ice-code-editor>

But ultimately, I run into too many problems that are likely related to the underlying ICE Code Editor. The ICE Code Editor is meant to manipulate the DOM of the containing page. Placing the code in a document fragment like the one created by Polymer seems to be an effective way of keeping the ICE code from trying to manipulate the main document. But this <link> import gives the code access to the main document.

The result is that ICE puts the imported Three.js simulation directly on the page rather than in the editor:



This still seems like it might be a worthwhile approach. The import seems to be working—a little too good in this case—but it does seem as though data is imported. For now, I will stick with the src + HttpRequest import. But I will try the <link> import another day with a smaller Polymer.

Update: Added a live demo.



Day #988

Sunday, January 5, 2014

Cannot Minify Polymer.dart


I very much want to put a working example of <ice-code-editor> up for public consumption. This is the Polymer version of the ICE Code Editor. After the work of the past few days, I could do so—especially after figuring out how to swap out the debugging libraries for minified versions upon deployment. But deployment on the web usually means codebases that are south of the 2.5MB range.

And, unfortunately for me, that is where my Polymer currently resides:
ls -lh build/polymer.html*
-rw-r--r-- 1 chris chris  797 Jan  5 12:11 build/polymer.html
-rw-r--r-- 1 chris chris 2.6M Jan  5 22:12 build/polymer.html_bootstrap.dart.js
Although I might prefer to fix the root of the problem, that might take me more time than I have at my disposal. Since I am getting rather adept at writing Dart deployment transformers, I thought I might have a go at transforming that polymer.html_bootstrap.dart.js file. Its problem is that it contains the entire Dart core in JavaScript form. Since I have no need of web audio, web sql, svg, etc., I try manually removing their definitions from polymer.html_bootstrap.dart.js. Sadly, that gets me nowhere. Even if my code is not directly using these libraries, other parts of the JavaScript are using them. It was worth a go.

If I cannot treat the symptoms, let's see about the root cause of the problem. I start by upgrading the various “any” version dependencies that are present:
➜  ice-code-editor git:(polymer) ✗ pub upgrade
Resolving dependencies...............................................
Downloading js 0.2.1 from hosted...
Downloading browser 0.9.1 from hosted...
Dependencies upgraded!
That actually seems promising. I know, for instance, that the js-interop package recently closed a bug that was causing excessive dart2js code sizes.

So I pub build my Polymer to find:
➜  ice-code-editor git:(polymer) ✗ pub build
...
[Warning in Dart2JS]:
web/polymer.html_bootstrap.dart:1:1: Hint: 449 methods retained for use by dart:mirrors out of 2399 total methods (19%).
...
[Info in Dart2JS]:
Generated ice_code_editor|web/polymer.html_bootstrap.dart.js (416281 characters) in 0:00:09.092775
That is an improvement. Not only the in size, which really is less:
➜  ice-code-editor git:(polymer) ✗ ls -lh build/polymer.html*
-rw-r--r-- 1 chris chris  797 Jan  5 22:52 build/polymer.html
-rw-r--r-- 1 chris chris 407K Jan  5 22:52 build/polymer.html_bootstrap.dart.js
The build time is also less than half what it was. Great!

Except that now the Polymer will not run. Instead, I get:
Uncaught Error: NoSuchMethodError : method not found: 'Symbol("giR")'
Receiver: Instance of 'pk'
Arguments: [] polymer.html_bootstrap.dart.js:1846
Stack Trace: 
Error
    at Object.b (http://localhost:8000/polymer.html_bootstrap.dart.js:1117:3)
    at pk.a.T (http://localhost:8000/polymer.html_bootstrap.dart.js:6138:25)
    at pk.T (http://localhost:8000/polymer.html_bootstrap.dart.js:8671:22)
    at pk.giR (http://localhost:8000/polymer.html_bootstrap.dart.js:13237:59)
    at cz.A0 (http://localhost:8000/polymer.html_bootstrap.dart.js:8376:8)
    at Fv.call$1 (http://localhost:8000/polymer.html_bootstrap.dart.js:8508:34)
    at vs.GP (http://localhost:8000/polymer.html_bootstrap.dart.js:3505:34)
    at jb.call$0 (http://localhost:8000/polymer.html_bootstrap.dart.js:3653:25)
    at Object.T8 (http://localhost:8000/polymer.html_bootstrap.dart.js:3272:26)
    at R8.Gr (http://localhost:8000/polymer.html_bootstrap.dart.js:4595:25)
 polymer.html_bootstrap.dart.js:1846
It seems that this error has been seen once before. Only once, as best I can tell. By me.

I always love it when that happens. It seems that I am doing something wrong in a way that is uniquely me. No one else is wrongheaded in quite the same way as me. I could definitely use a pair at this point, but failing that, I try my solution from back then: building the code without minifying it. But how to do that?

The pub build page suggests using the --mode=debug option. That does not seem to work:
➜  ice-code-editor git:(polymer) ✗ pub build --mode=debug         
Could not find an option named "mode".
Run "pub help" to see available options.
And, sadly, I cannot figure this out. I know there must be a way to get this working in debug (non-minified) mode, but I cannot find it.

Update: I was able to finally get this working. The option is --no-minify, not --mode=debug. The end result is that I am less than half of what I started with, but am still uncomfortably large:
➜  ice-code-editor git:(polymer) ✗ ls -lh build/polymer.html*
-rw-r--r-- 1 chris chris  801 Jan  6 00:07 build/polymer.html
-rw-r--r-- 1 chris chris 945K Jan  6 00:07 build/polymer.html_bootstrap.dart.js
I may have a go at tweaking some of the JavaScript interoperability code in the ICE Code Editor tomorrow to see if that might fix my minified version of the code.



Day #987

Saturday, January 4, 2014

Building Minified Polymer Libraries from Dart


There are debug statements in my build code. Why are there debug statements in my build code?

I was pleased with my progress at getting my “old” Polymer version of the ICE Code Editor back up and running—even to the point that I could build it for JavaScript-only browsers. Only... why is that debug code in the generated HTML?
<html><head><script src="packages/shadow_dom/shadow_dom.debug.js"></script>
<script src="packages/custom_element/custom-elements.debug.js"></script>
<script src="packages/browser/interop.js"></script>
  <script src="polymer.html_bootstrap.dart.js"></script>
</head>
<body><polymer-element name="ice-code-editor"><!-- ... -->
</body></html>
It actually takes me a fair bit of digging, but I eventually find the following in polymer/src/build/polyfill_injector.dart:
      // TODO(sigmund): enable using .min.js. This currently fails in checked
      // mode because of bugs in dart2js mirrors (dartbug.com/14720).
      // var suffix = options.releaseMode ? '.min.js' : '.debug.js';
      var suffix = '.debug.js';
I am not quite sure that I follow the bug, but it seems like only affects unit testing. That is, I think that code would still work if the “min.js” versions were used, but there is currently no way for Polymer.dart to verify that it works. To put that theory to the test, I manually change both of the debug <script> tags to use the min versions instead:
<html><head><script src="packages/shadow_dom/shadow_dom.min.js"></script>
<script src="packages/custom_element/custom-elements.min.js"></script>
<script src="packages/browser/interop.js"></script>
  <script src="polymer.html_bootstrap.dart.js"></script>
</head>
<body><polymer-element name="ice-code-editor">
<!-- ... -->
</body></html>
And that seems to do the trick. When I load my smoke test page, the Polymers still work and the Network tab confirms that the minified versions of the two libraries are being used:



The Polymers even work in Internet Explorer so I think I am good:



Hand editing code is never a useful thing to do. I could write a script that always does this for me, but I would still have to remember to run that every time I build my application. Actually, I know how to do this. I already wrote one pub transformer. I can do it again. I start by adding an application specific transformer to my pubspec.yaml:
name: ice_code_editor
version: 0.0.11
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: any
transformers:
- polymer:
    entry_points: web/polymer.html
- ice_code_editor:
    entry_points: web/polymer.html
The transformer is then more or less a copy and paste job from that other transformer. The overall structure is identical (which means that I probably ought to extract it out into a library). The only difference is the name of the transformer (ProductionMode) and the regular expression replacement performed by the transformer's apply() method:
class ProductionMode extends Transformer {
  // ...
  Future apply(Transform transform) {
    var input = transform.primaryInput;
    return transform.
      readInputAsString(input.id).
      then((html){
        var fixed = html.replaceAllMapped(
          new RegExp(r'\.debug\.js'),
          (m) => '.min.js'
        );
        transform.addOutput(new Asset.fromString(input.id, fixed));
      });
  }
}
And that does the trick. It does not speed up the build transformation by any stretch of the imagination, but whenever I do build my Polymer for deployment, it now includes the minified version of the JavaScript libraries instead of the debugging versions.

With that, I have a repeatable means of generating a minified version of my Polymer. At least until that bug is fixed.

Day #986

Friday, January 3, 2014

Packing Old Polymers for New Browsers


This is crazy. Somehow I do not have a running sample of an <ice-code-editor> Polymer available anywhere. At various times I had gotten this working. I even have a post from last year that worked at one point. But now nothing. Since I wanted to explore wrapping Polymer around existing, large codebases anyway, this seems a good opportunity.

First, it has been a while since I last tried to Polymerize the ICE Code Editor. None of the samples that I include in the web directory are working anymore. A quick scan of git log reveals that my last Polymer work was pre-Dart 1.0:



I cherry-pick that 1.0 commit (git cherry-pick f698145) rather than rebasing the polymer branch onto the latest master branch. Hopefully that is all I need to get things working again and it seems less likely to (a) devolve into resolving multiple merge conflicts and (b) introduce other, unrelated problems.

And that does get most of the examples working. It even gets an embedded example working:



But that was a pre-Polymer attempt at a similar solution. Unfortunately, I seem to have a Polymer bug. Hopefully it is just an old-version-of-polymer bug:
Internal error: 'package:polymer_expressions/polymer_expressions.dart': Error: line 53 pos 34: cannot resolve class 'BindingDelegate' from 'PolymerExpressions'
class PolymerExpressions extends BindingDelegate {
                                 ^ 
And, holy cow, I am using an old, modified, locally installed version of Polymer per my pubspec.yaml:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: {path: /home/chris/repos/dart/dart/pkg/polymer}
Heh. Any time I think I am living too close to the bleeding edge for Patterns in Polymer I can now remind myself that at least this kind of hacking is no longer necessary.

I switch to the latest, packaged Polymer:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: any
After that change, I pub get, which gets me to one of my favorite games: “my, how things have changed!”

Instead of the old combination of JavaScript boot script and Polymer import, I switch to the new export-init-script:
<head>
  <!-- Load component(s) -->
  <link rel="import" href="packages/ice_code_editor/polymer/ice_code_editor.html">
  <!-- Load Polymer -->
  <script type="application/dart">
    export 'package:polymer/init.dart';
  </script>
</head>
In the olden days of 2013, I had to mixin an observable class into my Polymer definition—no more. There used to be a create() lifecycle method as in the JavaScript version of Polymer—now it is a named constructor. Lastly, to manipulate the DOM of the current element, I previously had to go through the host property—now I can call append() directly.

The end result looks much more familiar to me after my recent 1.5 month deep-dive into all things Polymer:
import 'package:polymer/polymer.dart';

import 'dart:html';
import 'package:ice_code_editor/ice.dart' as ICE;

@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement {
  @published String src;
  @published int line_number = 0;
  ICE.Editor editor;

  IceCodeEditorElement.created(): super.created() {
    var container = new DivElement()
      ..id = 'ice-${this.hashCode}'
      ..style.width = '600px'
      ..style.height = '400px';

    append(container);
    // ...
  }
  // ...
}
And that does the trick. I have my custom <ice-code-editor> element back and am able to embed multiple instances of it:



But that is only half of tonight's battle. I also wanted to deploy this. That raises a very important question: how the heck do you deploy Polymer.dart code?

I know that I need at least one thing added to make that happen—a Pub transformer. To make ready its custom elements, Polymer.dart includes a build “transformer” that does all of the necessary work. Specifying a transformer is done in the pubspec.yaml file:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: any
transformers:
- polymer:
    entry_points: web/polymer.html
But, even though this worked fine from Dartium, the resultant pub serve fails. When I load the polymer.html test page, I get a 404 for http://localhost:8080/polymer.html_bootstrap.dart.js. Checking the output from the pub serve web server log, I see a bunch of warnings and errors—errors like:
Build error:
Transform Dart2JS on ice_code_editor|web/polymer.html_bootstrap.dart threw error: 'file:///mnt/data/b/build/slave/dart-editor-linux-stable/build/dart/
sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart': malformed type: line 118: type 'CompilerException' is not loaded
                if (error is CompilerException) return; 
                             ^
malformed type used.
../../../../mnt/data/b/build/slave/dart-editor-linux-stable/build/dart/sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart 118  Dart2JSTransformer.apply.<fn>.<fn>
Eventually, I read enough of the errors to realize that one of them contains useful information. It seems that I have one last holdover from the ancient 2013 version of Polymer.dart. The method signature for attributeChanged(), which I am overriding in my Polymer, has changed:
packages/ice_code_editor/polymer/ice_code_editor_element.dart:33:8: Error: Cannot override method 'attributeChanged' in 'Polymer'; the parameters do not match.
  void attributeChanged(String name, String oldValue) {
       ^^^^^^^^^^^^^^^^
After fixing that (it now requires a third, newValue parameter), I am in business. My <ice-code-editor> Polymer works in Chrome just like it did in Dartium:



Once that is working, I can pub build my page, which dumps output into the build subdirectory. Once it is done, I start a simple HTTP server in there:
➜  build git:(polymer) ✗ python -m SimpleHTTPServer 8000
Serving HTTP on 0.0.0.0 port 8000 ...
With that, I can access my Polymer from any static site with any modern web browser:



Nice! I still need to build for production (this includes some debug code). I would also like to see if I can shrink the codesize down some. Between the editor and the visualization layer, there is a lot of code. Still the current 2.5 MB seems excessive. But hopefully the hard part is out of the way.

Day #985

Thursday, January 2, 2014

Creating a Polymer Package for Bower Installs


At the risk of sounding like a broken record, I know how to bundle a Polymer in Dart. Like any package in Dart, you create a Dart Pub package and you are done. But how do you do the same thing in JavaScript?

Given that Polymer has made Bower its de facto package management solution, I think the answer likely lies in creating some kind of Bower package. I have no idea how to do that. Reading through the documentation some, it seems like Bower, like Dart's Pub, allows installs from git repositories (local and remote). To test this out, I create a new, local git repository and make some educated guesses as to bower init values:
➜  repos  mkdir hello-you
➜  repos  cd !$
➜  repos  cd hello-you
➜  hello-you  git init
Initialized empty Git repository in /home/chris/repos/hello-you/.git/
➜  hello-you git:(master) bower init
[?] name: hello-you
[?] version: 0.0.0
[?] description: A super cool Polymer. Tell your friends.
[?] main file: 
[?] keywords: polymer
[?] authors: Chris Strom 
[?] license: MIT
[?] homepage: https://github.com/eee-c/hello-you
[?] set currently installed components as dependencies? No
[?] add commonly ignored files to ignore list? Yes
[?] would you like to mark this package as private which prevents it from being accidentally published to the registry? No

{
  name: 'hello-you',
  version: '0.0.0',
  authors: [
    'Chris Strom '
  ],
  description: 'A super cool Polymer. Tell your friends.',
  keywords: [
    'polymer'
  ],
  license: 'MIT',
  homepage: 'https://github.com/eee-c/hello-you',
  ignore: [
    '**/.*',
    'node_modules',
    'bower_components',
    'test',
    'tests'
  ]
}
I also add Polymer as a dependency in the generated bower.json:
{
  "name": "hello-you",
  // ...
  "dependencies": {
    "polymer": "Polymer/polymer#~0.1.1"
  }
}
The various <polymer-*> project elements, like polymer-ajax, are all defined in separate, Bower-enabled repositories. They all seem to keep the Polymer definition in the main directory, so I start with that.

In there, I create hello-you.html with a skeleton version of the trivial app that I have been using:
<link rel="import" href="../polymer/polymer.html">
<polymer-element name="hello-you">
  <template>
    <h2>Hello {{your_name}}</h2>
    <p>
      <input value="{{your_name}}">
      <input type=submit value="Colorize!" on-click="{{feelingLucky}}">
    </p>
    <!-- ... -->
  </template>
  <script>
    Polymer('hello-you', {
      your_name: '',

      feelingLucky: function() {
        // Randomly change the color here...
      }
    });
  </script>
</polymer-element>
Here, I am borrowing the location for the Polymer library from the <polymer-*> elements. Since this polymer will be installed with Bower, it will be installed in the bower_components directory alongside Polymer. Hence I do not need to include bower_components in the URL path.

One thing that I cannot figure out is how to smoke test my Polymer. If I create a smoke.html in the main directory that uses hello-you.html from the same directory, it looks like:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Smoke Test for Hello You Polymer</title>
    <!-- 1. Load Polymer before any code that touches the DOM. -->
    <script src="bower_components/platform/platform.js"></script>
    <!-- 2. Load component(s) -->
    <link rel="import" href="hello-you.html">
  </head>
  <body>
    <div class="container">
      <hello-you></hello-you>
    </div>
  </body>
</html>
The problem is that hello-you.html is importing polymer not from a local bower_components, but is using ../polymer/polymer.html, which winds up trying to access a resource from the wrong location:
XMLHttpRequest cannot load http://polymer/polymer.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. smoke.html:1
I think the <polymer-*> elements may get around this by running a web server from the directory containing the individual repositories. That feels a bit ugly, so I shelve that for today. Instead, to smoke test, I temporarily change the import in my Polymer to explicitly use the bower_components path:
<link rel="import" href="bower_components/polymer/polymer.html">
<!-- <link rel="import" href="../polymer/polymer.html"> -->
<polymer-element name="hello-you">
  <!-- ... -->
</polymer-element>
After verifying that things are working, I remove the bower_components import, check my code in, and am ready to try installing this elsewhere.

In an empty directory, I bower install my Polymer:
➜  js git:(master) bower install ~/repos/hello-you 
bower hello-you#*           not-cached /home/chris/repos/hello-you#*
bower hello-you#*              resolve /home/chris/repos/hello-you#*
bower hello-you#*             checkout master
bower hello-you#*             resolved /home/chris/repos/hello-you#0476883f8c
bower polymer#~0.1.1            cached git://github.com/Polymer/polymer.git#0.1.1
bower polymer#~0.1.1          validate 0.1.1 against git://github.com/Polymer/polymer.git#~0.1.1
bower platform#0.1.1            cached git://github.com/Polymer/platform.git#0.1.1
bower platform#0.1.1          validate 0.1.1 against git://github.com/Polymer/platform.git#0.1.1
bower hello-you#*              install hello-you#0476883f8c
bower polymer#~0.1.1           install polymer#0.1.1
bower platform#0.1.1           install platform#0.1.1

hello-you#0476883f8c bower_components/hello-you
└── polymer#0.1.1

polymer#0.1.1 bower_components/polymer
└── platform#0.1.1

platform#0.1.1 bower_components/platform
That looks promising!

In the same directory, I create an index.html that uses both the necessary platform polyfills and my bower <hello-you> Polymer:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Testing a Bower Polymer</title>
    <!-- 1. Load Polymer before any code that touches the DOM. -->
    <script src="bower_components/platform/platform.js"></script>
    <!-- 2. Load component(s) -->
    <link rel="import" href="bower_components/hello-you/hello-you.html">
  </head>
  <body>
    <div class="container">
      <hello-you></hello-you>
    </div>
  </body>
</html>
And, after starting up a simple server, it works:



Nice! I could complain that this is not quite as smooth as running a pub serve web server—especially for smoke testing my the bower package. But really, this is pretty easy and miles easier than doing it without a package manager, so yay!


Day #984

Wednesday, January 1, 2014

Calling JavaScript Libraries from Polymer.dart


I started writing a chapter for Patterns in Polymer and realized that it really wasn't any kind of pattern—at least not for Dart. The latest chapter in the book was to discuss using third party libraries with Polymer. My problem is that Dart is brilliant at package management. Thanks to Dart Pub, using third party libraries is not so much a pattern as it is everyday, humdrum language tools.

So what is a poor author to do? Abandon the pattern because it does not apply to both JavaScript and Dart? That does not seem right since it really does take some thinking in JavaScript. Write a JavaScript-only chapter? Rip-off for the readers of the Dart-only version of the book! Instead, I think that I will give it a go using third party JavaScript libraries from Polymer.dart. Surely there will be a use case for that so it is not completely contrived. Right?

Since my JavaScript example makes use of the debounce() method from the venerable Underscore.js, I think that I will try using the same method from Dart. This is a little contrived because debouncing (aka throttling a function so that it cannot happen again until some time has elapsed) is pretty easy in vanilla Dart. Still, there are some things that JavaScript libraries can do that JavaScript cannot just yet. I think. I mean, there must be, right? Well, assuming there are...

I start with a basic pubspec.yaml for my example “underscore” application:
name: underscore
dependencies:
  polymer: any
A quick pub get and I have all of the Dart dependencies that I am going to need.

I start from the outside of my application with the web page that will hold my Underscore-powered <hello-you> Polymer:
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... -->
    <!-- Load component(s) -->
    <link rel="import" href="/packages/underscore/hello-you.html">
    <!-- Load Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
  </head>
  <body>
    <div class="container">
      <hello-you></hello-you>
    </div>
  </body>
</html>
There is nothing new there—just importing the <hello-you> definition and using it in the page. What is especially nice is that I do not have to declare any JavaScript dependencies or pollute my main page with dart:js-related <script> tags. I can do that entirely in my Polymer definition itself.

Speaking of the Polymer definition, it looks very much like any other <polymer-element> definition, with a <template> describing the HTML used and a <script> tag referencing the actual code. The only thing out of the ordinary is the opening of the file, which includes the dart:js <script> tags and a reference to Underscore:
<script src="../../packages/browser/dart.js"></script>
<script src="../../packages/browser/interop.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<polymer-element name="hello-you">
  <template>
    <h2>Hello {{your_name}}</h2>
    <p>
      <input value="{{your_name}}">
      <input type=submit value="Colorize!" on-click="{{feelingLucky}}">
    </p>
    <!-- ... -->
  </template>
  <script type="application/dart" src="hello_you.dart"></script>
</polymer-element>
Even if the main web page needed to use some JavaScript of its own, this would still work. The main web page could point <script> tags to the same dart:js script tags without worry—modern browsers will retrieve and execute the same script only once.

All that remains is the hello_you.dart backing code. It needs to import the dart:js package in order to have access to the nice JavaScript interoperation methods:
import 'package:polymer/polymer.dart';
import 'dart:math';
import 'dart:js';

@CustomTag('hello-you')
class HelloYou extends PolymerElement {
  HelloYou.created(): super.created();

  var _debouncedLucky;
  feelingLucky() {
    _ensureDebouncedLucky();
    _debouncedLucky.apply([]);
  }

  _ensureDebouncedLucky() {
    if (_debouncedLucky != null) return;
    _debouncedLucky = context['_'].callMethod('debounce', [_feelingLucky, 750, true]);
  }

  _feelingLucky() {
    // Normal Dart definition here...
  }
}
In there, I callMethod() on Underscore to get a “debounced” version of the regular _feelingLucky() method. To invoke this JavaScript debounced method whenever the Polymer invokes feelingLucky() via the on-click attribute, I use dart:js's apply().

And that does the trick:



I can click the “Colorize!” button as often as I like, but will only see a change if I wait for the debounce-mandated 750 milliseconds between clicks. Nice!

As I said, using Underscore from Dart is almost certainly useless. What features of Underscore that are not built into Dart are readily available from packages, including an Underscore Dart package. Still, this is simple enough—and close enough to the JavaScript narrative—that I think it is worth including in the book.


Day #983