Tuesday, January 28, 2014

Trying Recompiling Angular Directives to see Polymer Changes


I am still trying to get my AngularJS application to bind to my <x-pizza> Polymer element. It is fairly easy to push changes from Angular down into my Polymer via normal binding, but two way binding thus far has eluded me.

Actually, after last night, I have a solution that relies on an Angular directive that triggers its own $apply, but I would rather just have Angular recognize that $apply needs to be called during its normal course of operations.

Today, I am thinking that Angular is not aware of my Polymer's attribute changing because the attribute is redefined after Angular finishes binding. So I try recompiling:
directive('polymerDirective', function($timeout, $compile) {
  return {
    restrict: 'A',
    link : function(scope, element, attrs) {
      element.removeAttr('polymer-directive');
      element.attr('delayed-polymer','');
      $timeout(
        function(){
            //debugger
          var el = element.parent().children()[0];
          $compile(el)(scope);
        },
        500
      );
    }
  };

After half a second, I recompile the attribute with a new directive:
directive('delayedPolymer', function() {
  return {
    restrict: 'A',
    link : function(scope, element, attrs) {
      console.log('yo ' + attrs.state);
      scope.$watch(
        'attrs.state',
        function(value) {
          console.log('change seen');
          scope.pizzaState = value;
        }
      );
    }
  };
}).
But that still does not quite work. Even delaying the application of the directive until Polymer has done its initialization thing does not enable Angular to watch changes on the Polymer's attribute. It seems that last night's solution may be the best that I can do for now.

Day #1,010

Monday, January 27, 2014

Better Angular $apply and Polymer


OK. One more crack at it. Just one more.

I continue to struggle getting AngularJS to double bind variables from Polymer. I am working on an <x-pizza> Polymer that builds an SVG representation of a pizza:



Additionally, I have it publishing the current state of the pizza in an state attribute so that the element ends up looking something like:
<x-pizza state="pepperoni,green peppers
sausage
sausage"><x-pizza>
In the Angular application, I have a directive that tries to bind that state so that it can be reflected elsewhere in the application:
<pre ng-bind="pizzaState"></pre>
<p>
  <x-pizza polymer-directive state="{{pizzaState}}"></x-pizza>
</p>
But Angular refuses to bind that variable—not without some manual intervention.

In my custom polymer-directive, I would expect that I can $observe() or $watch() for changes on attrs.state, but that does me no good. However Angular is compiling the attributes, it is not able to see subsequent updates from Polymer.

Actually, it can read the updated attributes via element.attr('state'), but it cannot listen for changes from Polymer. So I exploited that last night by setting a regular Angular $interval to $apply() the usual Angular event loop—the same event loop that a change in a normal element would trigger automatically. And that worked, save for either the delay in the $interval() or higher than normal load as the $interval() reran $apply().

So tonight, I try for something a little less broad. Instead of re-rerunning $apply(), I only do so when there is an event in the Polymer that contains my directive:
var pizzaStoreApp = angular.module('pizzaStoreApp', [ /* ... */ ]).
directive('polymerDirective', function($interval, $timeout) {
  return {
    restrict: 'A',
    link : function(scope, element, attrs) {
      scope.$watch(
        function() {
          return element.attr('state');
        },
        function(value) {
          scope.pizzaState = value;
        }
      );

      element.on('click keyup', function(){
        scope.$apply();
      });
      // $interval(function(){},500);
    }
  };
});
But that does not work. What is interesting about that not working is that the element—my <x-pizza> Polymer—does not appear to be generating events that Angular's element can see. But it is generating events that the rest of the page sees. And it is not as if Angular is looking at the wrong element—after all, I can get the current attribute value through element. Somehow, Polymer seems to be confusing part of Angular's element and attr. I hate to put out a solution in Patterns in Polymer that involves such flakiness, but it is starting to seem like I am going to have to accept some level of oddness.

Anyhow, even though I cannot listen for events on element, I can listen for events on element.parent():
      // ...
      element.parent().on('click keyup', function(){
        scope.$apply();
      });
      // ...
That works fairly well. Whenever there is a click or keyup event in my Polymer, the Angular directive runs through the $apply() / $digest() loop, which includes the watcher for changes to element.attr('state').

I do find that this works best if I yield the browser event loop for one cycle, giving the Polymer a chance to fully update its internal state as well as its attribute. The easiest way to accomplish this in Angular is with a simple $timeout for zero seconds—it doesn't even need to do anything, just wait:
      // ...
      element.parent().on('click keyup', function(){
        $interval(function(){},500);
      });
      // ...
With that, I have my Angular application more or less updating only when changes might reasonably occur in my Polymer:



About the only thing that does not work in this scenario is if the Polymer were to generate some kind of update in response to something aside from a user action. I do not see anyway around this other than listening for some kind of custom change event or by accepting some delay in notification to the Angular application when using an $interval. This is pretty darn close, but… I may actually take one more day to try to solve this.

Day #1,009

Sunday, January 26, 2014

Holy Cow: Binding Angular to Polymer Take 2


I really hoped to finish writing the SVG chapter in Patterns in Polymer last night. As it turns out, AngularJS had other ideas. Like not working at all like I expected.

Last night's question was how can I bind an AngularJS application so that it has access to data inside a Polymer? I have already done this in the Dart versions of both libraries, so I thought this would be an easy question to answer in the JavaScript equivalents. Thanks to angular_node_bind in Dart, I could use square brackets to establish two-way binding between Polymer and Angular:
<h3>Oooh! Let's make beautiful pizza together</h3>
<pre>{{ pizza }}</pre>
<p>
  <x-pizza pizzaState="[[ pizza ]]"></x-pizza>
</p>
That did not work in JavaScript. I note that there was a long discussion on the subject some time ago—and the syntax for Dart's angular_node_bind seems to have been at least partially inspired from that post. But, if there a JavaScript equivalent out there, my Google-fu fails me.

I next tried to write my own directive to accomplish this. Even if it is not a generalized solution (and I still suspect there is already one out there somewhere), this should not be too difficult, right? I write the JavaScript version as:
<h3>Oooh! Let's make beautiful pizza together</h3>
<pre ng-bind="state"></pre>
<p>
  <x-pizza polymer-directive state="state"></x-pizza>
</p>
The state variable in both cases can be two-way bound if that polymer-directive scopes the attribute with =:
var pizzaStoreApp = angular.module('pizzaStoreApp', [ /* Angular modules here... */ ]).
directive('polymerDirective', function($interval) {
  return {
    restrict: 'A',
    scope: { state: '=' },
    // ...
  };
});
That should make an attribute directive (“A”) that binds the value of state in the local scope with the value of the same name in the parent scope. From there, I can establish a simple watch on the state attribute from the <x-pizza> Polymer:
directive('polymerDirective', function($interval) {
  return {
    restrict: 'A',
    scope: { state: '=' },
    link : function(scope, element, attrs) {
      scope.$watch(
        function() { // The value being watched..
          return element.attr('state');
        },
        function(value) { // What to do when the value changes ...
          scope.state = value;
        }
      );
    }
  };
});
But darn it, that does not work. The <x-pizza> Polymer is correctly updating the value of the state attribute, but Angular is not acknowledging the change:



It turns out that Angular is not calling the $digest event loop, and so the $watch is never being evaluated. If I add an <input ng-model>—even one that is not tied to a model used anywhere else—then typing in that input field will invoke $digest, which, in turn, calls my $watch:



So my ultimate solution is to set an interval in my digest. By default, $interval will evaluate the digest loop, so the interval function does not need to do anything:
directive('polymerDirective', function($interval) {
  return {
    restrict: 'A',
    scope: { state: '=' },
    link : function(scope, element, attrs) {
      scope.$watch(
        function() {
          return element.attr('state');
        },
        function(value) {
          scope.state = value;
        }
      );

      $interval(function(){},500);
    }
  };
});
And that seems to do the trick:



But is that the best way to do this?


Day #1,008

Saturday, January 25, 2014

Binding Angular to Polymer


I am mildly concerned that I am less than a month away from the release of Patterns in Polymer while still having so many outstanding questions. That said, all I can do is answer one question tonight and hope the rest take care of themselves in the days to come. And tonight's question is, how do I get data out of Polymer?

I already answered this question in the Dart version of Polymer.dart. Hopefully the answer in JavaScript will be similarly easy.

This turns out to be not quite so easy, however. I try the obvious approach—binding Angular variables:
<h3>Oooh! Let's make beautiful pizza together</h3>

<pre ng-bind="value">
</pre>

<p>
  <x-pizza state="{{value}}"></x-pizza>
</p>
But I wind up with nothing in the <pre> element even though the state attribute in <x-pizza> is definitely updated:



And I have to admit that I am stumped here. No matter what I try in the Polymer use (ng-state, ng-attr-state, etc). I cannot seem to get Angular to recognize this as an attribute—at least not as an attribute that is being updated.

I know that this works when changes are pushed down into Polymer. There is a nice little demo that describes it. In fact, I can see this here. If I add an ng-model INPUT element, I can update the value of the pizza state down in the Polymer. But when the Polymer in turn updates its state, Angular is not seeing the change.

Bother. Even trying to set $scope.watch() on the attribute seems to have no effect. It seems that I may have to dig further than I would have liked into this.

Day #1,007

Friday, January 24, 2014

Getting Started with Protractor (But Not Really)


So Protractor: do I need it? Well, since it has been announced as the official end-to-end testing framework for AngularJS, I probably need it. But do I need it for Polymer and will it prove useful for Patterns in Polymer?

I think today I will explore that by using Protractor to test last night's Angular + Polymer + SVG application:



I start by installing Protractor with npm:
$ npm install -g protractor
...
/home/chris/local/node-v0.10.20/bin/protractor -> /home/chris/local/node-v0.10.20/lib/node_modules/protractor/bin/protractor
/home/chris/local/node-v0.10.20/bin/webdriver-manager -> /home/chris/local/node-v0.10.20/lib/node_modules/protractor/bin/webdriver-manager
protractor@0.17.0 /home/chris/local/node-v0.10.20/lib/node_modules/protractor
├── saucelabs@0.1.1
├── minijasminenode@0.2.7
├── adm-zip@0.4.3
├── optimist@0.6.0 (wordwrap@0.0.2, minimist@0.0.5)
├── glob@3.2.8 (inherits@2.0.1, minimatch@0.2.14)
└── selenium-webdriver@2.39.0
Protractor does not seem to come with slick setup and configuration initializers just yet, but it does have example config that I can copy from the installation directory:
$ mkdir protractor
$ cp /home/chris/local/node-v0.10.20/lib/node_modules/protractor/example/* protractor/
I am going to test with the Chrome driver tonight, so I download:
$ wget http://chromedriver.storage.googleapis.com/2.8/chromedriver_linux64.zip
And install it:
$ unzip chromedriver_linux64.zip
$ mv chromedriver protractor/
With that, I can run the example Protractor test:
$ protractor protractor/chromeOnlyConf.js                                     
Using ChromeDriver directly...
...

Finished in 10.63 seconds
3 tests, 5 assertions, 0 failures
To test my own application, I start a protractor/conf.js for my current angular application:
exports.config = {
  chromeOnly: true,
  chromeDriver: 'chromedriver',
  capabilities: {
    'browserName': 'chrome'
  },
  specs: ['pizza_spec.js'],
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  }
};
But that is about as far as I get. I try what I think is a simple test to click on the <a> tag to get to the next page in my app where I can verify that that <x-pizza> tag is present:
describe('pizza store', function() {
  beforeEach(function() {
    browser.get('http://localhost:8000');
  });

  describe('pizza builder', function() {
    beforeEach(function() {
      var finder = by.id('mk-custom');
      var el = element(finder);
      el.click();
    });

    it('should have an <x-pizza> Polymer', function() {
      var el = by.css('x-pizza');
      expect(browser.isElementPresent(el)).toBe(true);
    });
  });
});
Bu no matter what I try, I get stale element errors:
protractor protractor/conf.js
Using ChromeDriver directly...
F

Failures:  

  1) pizza store pizza builder should have an <x-pizza> Polymer
   Message:
     StaleElementReferenceError: stale element reference: element is not attached to the page document
  (Session info: chrome=34.0.1797.2)
  (Driver info: chromedriver=2.8.240825,platform=Linux 3.5.0-18-generic x86_64)
   Stacktrace:
     StaleElementReferenceError: stale element reference: element is not attached to the page document
  (Session info: chrome=34.0.1797.2)
  (Driver info: chromedriver=2.8.240825,platform=Linux 3.5.0-18-generic x86_64)
==== async task ====
WebElement.click()
    at element.(anonymous function) [as click] (/home/chris/local/node-v0.10.20/lib/node_modules/protractor/lib/protractor.js:440:32)
    at /home/chris/local/node-v0.10.20/lib/node_modules/protractor/lib/protractor.js:89:34
I suspect this has something to do with my use of partials—especially on the start page, but I'll be darned if I can figure out how to convince Protractor that there really is a clickable link tag.

Bother. I may try this again tomorrow, but I cannot afford too much time. There are many more Polymer things to research before I am done.


Day #1,006

Thursday, January 23, 2014

Using Polymer Tags in an AngularJS Application (with Routing)


The question I would like to answer today is how to go about getting a Polymer working inside of an AngularJS application. I already know how to do this in the Dart version of both libraries, so hopefully this will prove to be an easy answer.

They are never easy answers.

After last night, I have an <x-pizza> Polymer that builds pizzas:



Let's see if I can use that Polymer in an Angular pizza shop application. As with the Dart version, I will try to get this working with a simple, routing-only Angular application. In my mind at least, including the routing ensures that I am exercising a decent amount of the library. That goes against my usual approach of limiting the number of moving parts, but without some interesting bits of the library in place, I feel as though it is too easy to think I have it legitimately incorporated.

I start with a Bower install of Angular: bower install angular --save. I could have used Angular from the CDN, but I am already using Bower for Polymer so I stay consistent. For the routing, I also need to bower install angular-route --save.

That leaves me with a bower.json with the following dependencies:
{
  "name": "angular_example",
  // ...
  "dependencies": {
    "angular": "~1.2.9",
    "polymer": "~0.1.3",
    "angular-route": "~1.2.9"
  }
}
One thing that the JavaScript world makes easier than the Dart equivalent is the ability to run any number of scripts and libraries at the same time. There is a cost to doing so, of course, but in this case it helps.

In my main page, I include everything. I include the Polymer library. I include the Polymer definition from last night. I include Angular and the Angular routing library. I include the Angular application. And I point the page to the Angular application and include an ng-view tag to hold the application:
<!doctype html>
<html ng-app="pizzaStoreApp">
  <head>
    <title>Pizza!</title>
    <script src="bower_components/platform/platform.js"></script>
    <link rel="import" href="elements/x-pizza.html">
    <script src="bower_components/angular/angular.min.js"></script>
    <script src="bower_components/angular-route/angular-route.min.js"></script>
    <script src="scripts/pizza_store.js"></script>
  </head>
  <body>
    <div class="container">
      <h1>JavaScript Pizza Shoppe</h1>
      <div ng-view></div>
    </div>
  </body>
</html>
The ng-app attribute on the <html> tag ties this page to an Angular application named pizzaStoreApp. I define that in scripts/pizza_store.js as a simple router-only Angular application:
'ngRoute'
]);

pizzaStoreApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/home', {
        templateUrl: 'scripts/partials/home.html'
      }).
      when('/pizza/custom', {
        templateUrl: 'scripts/partials/custom.html'
      }).
      otherwise({
        redirectTo: '/home'
      });
  }
]);
The two partials are simple HTML samples. I use last night's SVG-based Polymer in the custom.html partial:
<h3>Oooh! Let's make beautiful pizza together</h3>
<p>
  <x-pizza></x-pizza>
</p>
And that turns out to be all that is needed:



That was pleasantly easy. Much of that was made easier for having already done it in Dart, but I do think the JavaScript version of Angular remains slightly more polished than its Dart cousin. Regardless, I now have Angular and Polymer playing nicely together in both JavaScript and Dart.


Day #1,005

Wednesday, January 22, 2014

JavaScript Polymer SVG: Testing with Jasmine


OK tonight I go back to get SVG working with my JavaScript flavored <x-pizza> element. No more of the sweet, sweet nectar of Dart—I will eat my vegetables!

I kid, of course, I still love JavaScript. That love is not rewarded with a nice SVG API, however. In Dart, I could create the various elements that made up the pizza and its toppings with code like:
  _svgPepperoni() =>
    new CircleElement()..attributes = {'r': '10', 'fill': 'red'};
It seems that JavaScript lacks a constructor for circle SVG elements, leaving me to write much longer code like:
  _svgPepperoni: function() {
    var el = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    el.setAttribute('r', '10');
    el.setAttribute('fill', 'red');
    return el;
  }
I make a bunch of changes along those lines (for other toppings and groups of toppings). I also have to manually convert a lot of Dart code into JS:
  • removing method cascades
  • changing innerHtml to the crazy innerHTML
  • add the this keyword absolutely everywhere
  • add the that variable where scope is an issue
  • Remove string interpolation in “favor” of plussing strings together.
It's a pain.

But it works:



I have been a little remiss in my testing, so I pick back up here with a Karma / Jasmine test. I have to update the list of files being tested and/or served to include not only my <x-pizza> elements in the elements directory, but I also need to be sure to grab the bower directory for Polymer:
...
    // list of files / patterns to load in the browser
    files: [
      'test/PolymerSetup.js',
      {pattern: 'elements/**', included: false, served: true},
      {pattern: 'bower_components/**', included: false, served: true},
      'test/**/*Spec.js'
    ],
...
My test setup is similar to what I have used in the past, updated only for new file names.

As for the test itself, I create a setup that adds <x-pizza> to the test page:
describe('<x-pizza>', function(){
  var container;

  beforeEach(function(){
    container = document.createElement("div");
    container.innerHTML = '<x-pizza></x-pizza>';
    document.body.appendChild(container);
    waits(0); // One event loop for elements to register in Polymer
  });

  afterEach(function(){
    document.body.removeChild(container);
  });

  // Tests here...
});
Then I can test the contents of the SVG element on the Polymer's shadow root:
  describe('defaults', function(){
    it('to a blank pizza', function() {
      var el = document.querySelector('x-pizza');
      var svg = el.shadowRoot.querySelector('svg');
      expect(svg.innerHTML).toContain('circle cx="150" cy="150" r="150" fill="tan"');
    });
  });
For now, I just verify that the SVG element is present and that it contains a dynamically generated <circle> element with all of the right attributes.

And it works:
INFO [watcher]: Changed file "/home/chris/repos/polymer-book/play/svg/js/test/XPizzaSpec.js".
Chrome 34.0.1797 (Linux): Executed 1 of 1 SUCCESS (0.701 secs / 0.403 secs)
Though it is better than nothing, that is a frail test. I ought to (and will before it is added to support a Patterns in Polymer chapter) query for the circle element and set expectations on it attributes rather than hoping that attributes retain their order. Still, I am happy to have gotten this converted over in relatively short order—better still to have actual tests to verify that it does what I think.


Day #1,004