Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

Saturday, October 4, 2014

Testing Computed Style in Dart


I was able to test CSS styling last night, making getComputedStyle() my new best friend. Seriously, I have wanted to do just this kind of testing before, but never knew it was possible. Which begs the question, is it possible in Dart?

Presumably, it is. Especially since getComputedStyle() is part of core dart:html. Even better, getComputedStyle() in Dart is available on any Element, so no need to run it through the top-level window version.

As yesterday, I am testing some Bootstrap styles applied to a custom Polymer element for a chapter in Patterns in Polymer. More precisely, I am using Polymer.dart for the Dart version of this chapter.

The setup for testing this creates the <pricing-plan> elements that should use Bootstrap styles:
  var _el;
  group("styles", (){
    setUp((){
      _el = createElement('''
        <pricing-plans>
          <pricing-plan type="primary">plan content</pricing-plan>
        </pricing-plans>
      ''');
      document.body.append(_el);
    });
    // Test goes here...
  });
The type="primary" attribute will generate a Bootstrap panel-primary class that results in a panel with a blue heading like the one on the right:



To test this, I need the same computed style as from last night's JavaScript test. I need grab the <pricing-plan> element, then query for the panel heading, and finally ask for the computed style:
    test("come from external sources", (){
      var primary_el = _el.query('pricing-plan'),
          heading_el = primary_el.shadowRoot.query('.panel-heading'),
          style = heading_el.getComputedStyle();

      expect(style.backgroundColor, 'rgb(66, 139, 202)');
    });
The expectation is then that the panel's background color will be default Bootstrap primary blue. But this turns out not to work:
CONSOLE MESSAGE: FAIL: styles come from external sources
  Expected: 'rgb(66, 139, 202)'
    Actual: 'rgba(0, 0, 0, 0)'
     Which: is different.
Interesting, I note that the smoke test web page is making XHR requests for Bootstrap:
XHR finished loading: GET "http://localhost:8080/packages/bootstrap_example/assets/bootstrap.min.css".
This occurs even though Bootstrap is being imported with @import in the Polymer definition:
<link rel="import" href="../../../packages/polymer/polymer.html">
<polymer-element name="pricing-plan">
  <template>
    <div class="col-md-{{size}}"><!-- ... --></div>
    <style>
      @import '/packages/bootstrap_example/assets/bootstrap.min.css';
    </style>
  </template>
  <script type="application/dart" src="pricing_plan.dart"></script>
</polymer-element>
I presume this is the Polymer transformer doing this. Since I cannot change it, I need a workaround. Like running pub serve:
$ pub serve
Loading source assets... 
Loading polymer transformers... 
Serving bootstrap_example web  on http://localhost:8080
Serving bootstrap_example test on http://localhost:8081
The tests are kindly served up from 8081, so I point content_shell there:
$ content_shell --dump-render-tree http://localhost:8081                         
CONSOLE MESSAGE: unittest-suite-wait-for-done
CONSOLE MESSAGE: PASS: styles come from external sources
CONSOLE MESSAGE: PASS: [defaults] name is "Plan"
CONSOLE MESSAGE: PASS: [defaults] can embed code
CONSOLE MESSAGE: 
CONSOLE MESSAGE: All 3 tests passed.
CONSOLE MESSAGE: unittest-suite-success
CONSOLE WARNING: line 213: PASS
So yay! Aside from the tiny XHR curveball with the @import CSS, it is just as easy to test styles in Polymer.dart as in the JavaScript version.


Day #203

Friday, October 3, 2014

Testing CSS Colors in Polymer


I have 5 whole tests covering the functionality of the Bootstrap styled Polymer element. And it is occurs to me that not a single one of those tests has anything to do with the intention of this chapter in Patterns in Polymer, which is styling Polymer elements.

The Polymer element in this case is a simple pricing plans element:



So it seems to me that I ought to be able to test that one of the individual pricing plans in the test is blue.

I have to fiddle with the setup, but I eventually get the following Jasmine test to work:
  describe('defaults', function(){
    var el;
    beforeEach(function(done){
      el = document.querySelector('pricing-plans');
      setTimeout(done, 10);
    });

    it('gets styles from external sources', function(){
      var primary_el = el.querySelectorAll('pricing-plan')[2],
          heading_el = primary_el.shadowRoot.querySelector('.panel-heading'),
          style = window.getComputedStyle(heading_el);

      expect(style.backgroundColor).toEqual('rgb(66, 139, 202)');
    });
  });
This finds the last <pricing-plan> element in my fixture file:
<pricing-plans>
<pricing-plan name="pricing plan 01">desc 01</pricing-plan>
<pricing-plan name="pricing plan 02">desc 02</pricing-plan>
<pricing-plan type="primary" name="pricing plan 03">desc 03</pricing-plan>
</pricing-plans>
The last element has the primary type set which Bootstrap will color blue by default. I had originally tried to grab the <pricing-plan> element directly to test, but found that I had to dive into that shadow DOM to grab the panel header to find the element that actually is blue.

The test then uses the getComputedStyle() method on window to find the background color of this element, which should be the specified shade of blue.

Among the tricks that I need to get this working is the setTimeout() dance in this test's setup—this gives the page time to load Bootstrap CSS and apply it (I am running this with Karma, so loading from a server does work). If I opt to use the apply-author-styles Polymer tag, I will also have to apply Bootstrap CSS to the main testing page. But, since this is just the @import solution for external CSS inside a Polymer element, this is all I need for tonight.

The end result is that the test passes:
...
SUCCESS  gets styles from external sources
Skipped 0 tests
And, more importantly, the test fails if I change the fixture from a panel-primary to a panel-success:
FAILED  gets styles from external sources
Expected 'rgb(223, 240, 216)' to equal 'rgb(66, 139, 202)'.
I was unsure how easy it would be to accomplish this, but testing computed CSS in Polymer elements turns out to be fairly clean and easy.


Day #202

Wednesday, October 1, 2014

Bootstrap CSS with Polymer (Revisited)


I maintain that there are times that developers will want web components to look like the rest of their site, not like Material Design. Toward that end, I include a chapter on Bootstrap CSS in Patterns in Polymer. Today, I double check that my solution stills works after upgrading all code the latest versions of Polymer.dart (for the Dart version of the book) and Polymer (for the JavaScript version of the book).

And, thankfully, my solution does continue to work:



One could certainly argue that this solution trades one popular-on-the-verge-of-overused styling approach for another. I would probably agree. The point is not to use a specific style, just to use a common style to validate an approach.

At the risk of spoiling the joy of reading the chapter, the solution boils down to an @import of the common CSS:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="pricing-plan" attributes="name type size">
  <template>
    <div class="col-md-{{size}}"><!- ... --></div>
    <style>
      @import '../bower_components/bootstrap/dist/css/bootstrap.min.css';
    </style>
  </template>
  <script src="pricing_plan.js"></script>
</polymer-element>
There is a little more to the solution (so really, you should read the book), but that is the gist.

But this got me thinking, perhaps the <apply-author-styles> custom Polymer element would work as well. So, in the JavaScript version of the code, I install it with Bower:
$ bower install --save eee-c/apply-author-styles
...
bower apply-author-styles#*               install apply-author-styles#434679b8da
bower core-ajax#~0.3.2                    install core-ajax#0.3.6

apply-author-styles#434679b8da bower_components/apply-author-styles
├── core-ajax#0.3.6
└── polymer#0.4.0

core-ajax#0.3.6 bower_components/core-ajax
└── polymer#0.4.0
Then, in my Polymer element HTML definitions, I remove the @import style and instead add the <apply-author-styles> tag:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import"
      href="../bower_components/apply-author-styles/apply-author-styles.html">
<polymer-element name="pricing-plan" attributes="name type size">
  <template>
    <apply-author-styles></apply-author-styles>
    <div class="col-md-{{size}}"><!-- ... -></div>
  </template>
  <script src="pricing_plan.js"></script>
</polymer-element>
And that works perfectly:



That is nice. I do not know if I will offer that as the solution to applying external styles in Patterns in Polymer, but it seems worth a mention. Worth it if it works in Dart as well.

So I switch over to the Dart version of the chapter code, which is configured to install Bower components in lib/elements by way of a .bowerrc file:
$ cat .bowerrc
{
  "directory": "lib/bower_components"
} 
I again execute bower install --save eee-c/apply-author-styles, this time in my Dart project.

I update my element to use the Bower installed <apply-author-styles>:
<link rel="import" href="../../../packages/polymer/polymer.html">
<link rel="import"
      href="../bower_components/apply-author-styles/apply-author-styles.html">
<polymer-element name="pricing-plan">
  <template>
    <apply-author-styles></apply-author-styles>
    <div class="col-md-{{size}}"><!-- ... --></div>
    <!-- <style> -->
    <!--   @import '/packages/bootstrap_example/assets/bootstrap.min.css'; -->
    <!-- </style> -->
  </template>
  <script type="application/dart" src="pricing_plan.dart"></script>
</polymer-element>
But run into problems that I have seen before. Actually, when I saw this previously, the error was much more helpful. This time, all I get is:
Uncaught TypeError: undefined is not a function    polymer.js:96
  (anonymous function)                             polymer.js:96
  (anonymous function)                             polymer.js:99
And:
Exception: NoSuchMethodError: method not found: 'whenPolymerReady'
Receiver: Instance of 'JsFunction'
Arguments: [Closure: () => dynamic]               package:polymer/src/loader.dart:103
Eventually, I realize that the polymer.js generating the error is the one installed via Bower, not the one bundled with Polymer.dart. So I have to do what I did before: hand-edit core-xhr.html in lib/bower_components to point to the Polymer.dart version. Horrible.

I do not think this is easily solved. It would seem that any JavaScript Polymer element that depends on core-xhr and, by extension, core-ajax, will not be usable in Polymer.dart. Since <apply-author-styles> is such a beast, it would seem that I am out of luck, leaving the @import solution as the best and only available. Unless I am willing to rewrite and maintain apply-author-styles in Dart as well...



Day #200

Monday, August 25, 2014

At the Bottom of the Rabbit Hole, I Find Polyfill-Next-Selector


The more I investigate styling and theming Polymer elements, the less a grasp I feel like I have on it. The core-style continues to vex. Beyond that, I am also having difficulty applying consistent CSS styles on my elements.

I am unsure if my current problems are with Polymer or with the Core Elements and Paper Elements built on top of Polymer. The most recent issue that I find is that the <paper-button> inside of a sample Polymer element that I am trying to create do not share styles. Specifically, the border is not included on all paper-buttons:



Both the top buttons and the dialog buttons are <paper-button> elements. Both should be covered by my core-style CSS:
<polymer-element name="lorem-dialog">
  <template>
    <paper-button label="Bottom" on-tap="{{toggleDialog}}"></paper-button>
    <paper-button label="Center" on-tap="{{toggleDialog}}"></paper-button>

    <paper-dialog heading="Bottom Dialog" transition="paper-dialog-transition-bottom">
      <!-- ... -->
      <paper-button label="Accept" affirmative autofocus></paper-button>
    </paper-dialog><
    <!-- ... -->
    <core-style id="theme">
      :host /deep/ paper-button {
        color: {{g.primaryColor}};
        border: 5px solid {{g.secondaryColor}};
        padding: 2px 5px;
      }
    </core-style>
    <core-style ref="theme"></core-style>
  </template>
  <script>
    Polymer('lorem-dialog', {/* ... */});
  </script>
</polymer-element>
The core-style CSS is applied with the /deep/ CSS modifier. My understanding of /deep/ is that my styles should penetrate any shadow DOMs that are under the current element. And it kinda/sorta does what I expect. The primary color, themed from the containing page, is set to orange and it does apply to all paper-button elements. But darn it, why are the borders not in place for the paper-buttons in the dialogs?

My first thought is that perhaps this is a native shadow DOM vs. polyfill issue, so I load the demo page up in Firefox. This only makes things worse:



The borders are applied to all paper-buttons, but none of the core-style global settings are in place. Bleh.

Taking a step back, I know from last night that core-style does not like the way that I am using it. I take that out of the equation by removing the id/ref core-style pair of tags, replacing them with a straight forward <style> tag:
<polymer-element name="lorem-dialog">
  <template>
    <!-- ... -->
    <style>
      :host /deep/ paper-button {
        color: orange;
        border: 5px solid green;
        padding: 2px 5px;
      }
    </style>
  </template>
  <script>
    Polymer('lorem-dialog', {/* ... */});
  </script>
</polymer-element>
That solve my Firefox problem. The polyfills now correctly style my paper-button elements:



But this remains unchanged in Chrome (stable through unstable). On the surface, it would seem that Polymer styles are just broken at this point, but I refuse to indulge in select-is-broken thoughts. At least not yet.

If I peek at one of the paper-button elements in the Chrome inspector, I find that my border style is being overridden:



But what is that double-colon content thingy? I have no idea how that applies to my paper-button elements, let alone is more specific (in a CSS selector sense) than my /deep/ paper-button selector. Furthermore, I am hindered by the odd lack of file and line number for this selector. How can I understand and work around the darn thing if I cannot even find it?

To the ack machine Robin!

Amazingly, that actually finds something:
$ ack -l ::content                                                  
bower_components/platform/platform.js
bower_components/platform/platform.js.map
bower_components/paper-dialog/paper-dialog.css
bower_components/core-style/elements.html
bower_components/core-component-page/core-component-page.html
Only one of those is a CSS file and just so happens to be the element (paper-dialog) that is wrapping my misbehaving paper-buttons. Taking a look at the offending CSS, I find:
polymer-next-selector { content: ':host > *'; }
::content > * {
  font: inherit;
  border: 0;
}
That is exactly the definition of the culprit that I found in the DOM inspector. A quick review of the other matching files reveals that none of them have the same style definition. So the question becomes… what the heck is a polymer-next-selector? More importantly, how do I override it?

The answer to the first question seems to be that polymer-next-selector is also known as polyfill-next-selector. It seems to be a way to apply styles in the polyfills, but which work natively with the shadow DOM if present. Only, the precedence on these things is crazy high.

Try as I might, I cannot target the distributed nodes of the paper-dialog from my custom element that tries to use paper-dialog. I am surprised that targeting the distributed nodes of paper-dialog has no effect:
<polymer-element name="lorem-dialog">
  <template>
    <!-- ... -->
    <style>
      :host /deep/ paper-button {
        color: orange;
        border: 5px solid green;
        padding: 2px 5px;
      }

      paper-dialog::content > * {
        border: 5px dashed blue;
      }
    </style>
  </template>
  <script>
    Polymer('lorem-dialog', {/* ... */});
  </script>
</polymer-element>
In the end, I give up trying to work with ::content and simply add an !important to the border style:
<polymer-element name="lorem-dialog">
  <template>
    <!-- ... -->
    <style>
      :host /deep/ paper-button {
        color: orange;
        border: 5px solid green !important;
        padding: 2px 5px;
      }
    </style>
  </template>
  <script>
    Polymer('lorem-dialog', {/* ... */});
  </script>
</polymer-element>
That does the trick:



But it feels like a cheat.

I cannot figure out why the ::content distributed node selector has such high precedence or why my attempts to influence it failed. I am probably overlooking some selector combinator that would allow me to target paper-button distributed into paper-dialog, but I wish it were easier to find that combinator. And if there is no easier way to do this, then why is paper-dialog using such a high precedence selector to ensure that none of its nodes have borders?

I have a solution, but I have more questions than answers to go along with that solution. Which makes this feel like a cheat.




Day #163

Sunday, August 24, 2014

Crazy Theming Polymer.dart with Core-Style


I am resigned.

Resigned that the core-style element and I disagree on how it should support theming. I have no illusions that I am in the right on this one, but I will attempt to make my case anyway.

When I think of custom themes, I think of setting a few colors and maybe a few other atomic values that can be used by a widget to look more or less like it fits in with the rest of the web page. In core-style, parlance, this looks like:
      <script>
        CoreStyle.g.primaryColor = 'orange';
        CoreStyle.g.secondaryColor = 'green';
      </script>
Or, alternatively, as:
        CoreStyle.g = {
          primaryColor: 'orange',
          secondaryColor = 'green'
        };
I would think that web page trying to use a widget would set these values and the widget would then honor the values. As best I can tell, this is not how core-style works.

Instead, core-style wants these global settings defined by the containing page and it wants the containing page to define styles that will apply to the internals of the widgets being used. That is, if I know that my <lorem-dialog> custom Polymer element contains paper-button elements, then core-style would have me define the global property setting and the detailed widget styling on the containing page:
  <body>
    <h1>Play Paper</h1>
    <lorem-dialog></lorem-dialog>
    <core-style id="theme">
      :host paper-button {
        border: 5px solid {{g.primaryColor}};
        padding: 2px 5px;
      }
    </core-style>
    <script>
      CoreStyle.g.primaryColor = 'orange';
    </script>
  </body>
I cannot help but think this requires the containing page to know too much about the internal implementation of the widget (the Polymer element).

I realize that I am almost certainly making a dumb assumption here. I am probably abusing this. Or not thinking right. Knowing this does not help me. Making the problem worse usually does. If I push this further—feel more pain in coding the wrong way—then I usually figure out how to do it right.

Last night, I was able to get core-style to work like I want by making the core-style's g property available in the backing Polymer element class:
Polymer('lorem-dialog', {
  created: function() {
    this.g = CoreStyle.g;
  },
  // ...
}
I could then use this reference inside the Polymer template:
<polymer-element name="lorem-dialog">
  <template>
    <!-- ... -->
    <core-style id="theme">
      :host paper-button {
        border: 5px solid {{g.primaryColor}};
        padding: 2px 5px;
      }
    </core-style>
    <core-style ref="theme"></core-style>
  </template>
  <script>
    Polymer('lorem-dialog', { /* ... */ });
  </script>
</polymer-element>
Unfortunately, that does not work in Polymer.dart. Try as I might, there is no g property on the core-style object in Dart. But…

I know that the Dart versions of the core and paper elements are just thin wrappers around the JavaScript versions. Since I know how to get the global core-style values from JavaScript, perhaps I can use Dart's awesome JavaScript interoperability to resolve this dilemma.

So, I import the dart:js packages and define a g getter to return the value of CoreStyle.g from JavaScript:
import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:js';

@CustomTag('lorem-dialog')
class LoremDialog extends PolymerElement {
  LoremDialog.created(): super.created();

  get g => context['CoreStyle']['g'];
  // ...
}
And that actually works. In the template, I can define and reference a “theme” style that makes use of the global values from the web page using my Polymer element:
<polymer-element name="lorem-dialog">
  <template>
    <!-- ... -->
    <core-style ref="theme"></core-style>
    <core-style id="theme">
      paper-button {
        border: 5px solid {{g['secondaryColor']}};
        color: {{g['primaryColor']}};
        font-weight: bold;
        padding: 2px 5px;
      }
    </core-style>
  </template>
  <script type="application/dart" src="lorem_dialog.dart"></script>
</polymer-element>

I strongly doubt that I will offer this up as a solution in Patterns in Polymer, but it does work in both JavaScript and Dart. Even so, the amount of resistance that I get from the library is strongly suggesting to me that I am doing something wrong. But even pushing this hard against core-style is not suggesting to me the right way to tackle this problem. Hopefully something will come to me (or someone can point me in the right direction) over the course of the next few days...


Day #162

Saturday, August 23, 2014

Where Core-Style Global Properties Can Be Used


I am struggling with the core-style element in Polymer.dart. I can implement simple styles—both as a source and referencing them later. But I have not been able to get arguably the coolest feature working yet: setting group variables.

For instance, I might want to theme some elements with the primary color of orange. From the container page, I ought to be able to set this in a script like so:
    <script>
      CoreStyle.g.primaryColor = 'orange';
    </script>
Custom Polymer elements should then honor this primary color with settings like:
<link rel="import"
      href="../../../packages/polymer/polymer.html">
<!-- ... -->
<link rel="import"
      href="../../../packages/core_elements/core_style.html">
<polymer-element name="lorem-dialog">
  <template>
    <paper-button label="Bottom" on-tap="{{toggleDialog}}"></paper-button>
    <paper-button label="Center" on-tap="{{toggleDialog}}"></paper-button>
    <!-- ... -->
    <core-style id="theme">
      paper-button {
        border: 5px solid {{g.primaryColor}};
        padding: 2px 5px;
      }
    </core-style>
    <core-style ref="theme"></core-style>
  </template>
  <script type="application/dart" src="lorem_dialog.dart"></script>
</polymer-element>
Try as I might, I cannot get this to work. I wind up with an error about the g property not being defined:
Exception: Error evaluating expression 'CoreStyle.g.primaryColor': Class 'LoremDialog' has no instance getter 'CoreStyle'.

NoSuchMethodError: method not found: 'CoreStyle'
Receiver: Instance of 'LoremDialog'
Arguments: []
A hint from James Hurford suggests that including the script that sets the global color on the same page that defines the styles will work:
  <body>
    <h1>Play Paper</h1>

    <lorem-dialog></lorem-dialog>

    <core-style id="legacy-button">
      :host paper-button {
        border: 5px solid {{g.primaryColor}};
        padding: 2px 5px;
      }
    </core-style>
    <script>
      CoreStyle.g.primaryColor = 'orange';
    </script>
  </body>
In fact, that does work. My Polymer element can then reference the "legacy-button" core style and the buttons will have orange borders. But that does not seem right to me. I feel like I ought to set the global property in the main page and use it inside Polymer elements. I should not have to build the entire style in the containing page—the containing page then needs to know too much about the internals of my Polymer element. That defeats the purpose of encapsulating all of this stuff inside Polymer elements, does it not?

To decide which I right, I try it in JavaScript as well. And find… the same thing. In JavaScript, I do not get the exceptions that I do from Dart, but I still do not see global core styles inside Polymer element <core-style> elements:
<link rel="import"
      href="/bower_components/polymer/polymer.html">
<!-- ... -->
<link rel="import"
      href="/bower_components/core-style/core-style.html">
<polymer-element name="lorem-dialog">
  <template>
    <paper-button label="Bottom" on-tap="{{toggleDialog}}"></paper-button>
    <paper-button label="Center" on-tap="{{toggleDialog}}"></paper-button>
    <!-- ... -->
    <core-style id="theme">
      :host paper-button {
        border: 5px solid {{g.primaryColor}};
        padding: 2px 5px;
      }
    </core-style>
    <core-style ref="theme"></core-style>
  </template>
  <script>
    Polymer('lorem-dialog', {/* ... */});
  </script>
</polymer-element>
With this, I get 5px solid button borders, but the color is empty so the buttons default to black:



What I can do in the JavaScript version of Polymer that did not work in Polymer.dart is make a local copy of the g property in my sample Polymer class:
<link rel="import"
      href="/bower_components/polymer/polymer.html">
<!-- ... -->
<link rel="import"
      href="/bower_components/core-style/core-style.html">
<polymer-element name="lorem-dialog">
  <template><!-- ... --> </template>
  <script>
    Polymer('lorem-dialog', {
      created: function() {
        this.g = CoreStyle.g;
      },
      // ...
    });
  </script>
</polymer-element>
This makes the g property available inside the <template> of my Polymer element:



So am I wrong in my assumption that I should be able to set a global CoreStyle property in the containing page and use it inside elements? It sure seems that way. I have a workaround, but a workaround implies that I am working against the library, not using it as intended. So the question remains: am I doing something wrong or is core-style not meant to work like this?


Day #161


Friday, August 22, 2014

Getting Started with Core-Style for Theming Polymer


I have enjoyed investigating Material Design. It provided much needed inspiration and new ideas on design—especially with regards to the use of motion in design. I remain concerned on how or if to use things like Paper Elements in “legacy” applications.

Paper elements are a Material take on custom Polymer elements. They look pretty, but they wind up looking—for lack of a better word—Googly:



Heck, even if I am following Material design without Paper elements, I find myself building applications that might look quite at home in a Google property:



In many cases, this would be a good thing. Let's face it, if I am designing something, it would always be a good thing. But there are times that a client wants to continue using their own styles in Polymer elements. There are even times that the people writing the checks cannot be convinced to stray at all from something like Bootstrap.

So what to do in those cases? Is a polymer element designed with Material principles impossible to use in legacy designs without looking impossibly out of place? To a certain extent, this is why I built <apply-author-styles>—to pull styles from a containing pages into a Polymer element.

That is helpful, but not really a theming solution. For theming, the Polymer team introduced core-style. Let's say that a client insists on a large orange border with initial caps and the lovely Arial font. From last night, paper buttons look like:



To get my legacy style in there, I can import core-style using the usual Polymer.dart:
  <head>
    <!-- Load platform polyfills -->
    <script src="packages/web_components/platform.js"></script>
    <script src="packages/web_components/dart_support.js"></script>

    <!-- Load component(s) -->
    <link rel="import"
          href="packages/paper_elements/paper_dialog_transition.html">
    <link rel="import"
          href="packages/paper_elements/paper_dialog.html">
    <link rel="import"
          href="packages/paper_elements/paper_button.html">
    <link rel="import"
          href="packages/core_elements/core_style.html">

    <!-- Start Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
  </head>
Actually using core-style is a two step process. First I need to define the styles that I want to use:
    <core-style id="legacy-button">
      paper-button {
        text-transform: initial;
        font-family: Arial, sans-serif;
        border: 5px orange solid;
        padding: 2px 5px;
      }
    </core-style>
That should keep my clients happy. Now I need to actually apply it. In core-style parlance, I need to reference it:
    <core-style ref="legacy-button"></core-style>
With that, get:



This is a simple example. For actual theming, I might want to expose style variables that can be set. Core-style supports setting these in the global style group with CoreStyle.g. If I wanted to style my example <lorem-dialog> element, I might do so with:
    <lorem-dialog></lorem-dialog>
    <script>
      CoreStyle.g.fontFamily = 'Arial, sans-serif';
      CoreStyle.g.buttonBorder = '5px orange solid';
    </script>
I could then apply these inside my element with something along the lines of:
<link rel="import"
      href="../../../packages/polymer/polymer.html">
<link rel="import"
      href="../../../packages/core_elements/core_style.html">
<!-- ... -->
<polymer-element name="lorem-dialog">
  <template>
    <!-- ... -->
    <core-style id="legacy-button">
      paper-button {
        text-transform: initial;
        font-family: {{g.fontFamily}};
        border: {{g.buttonBorder}};
        padding: 2px 5px;
      }
    </core-style>
    <core-style ref="legacy-button"></core-style>
  </template>
  <script type="application/dart" src="lorem_dialog.dart"></script>
</polymer-element>
Only I am unable to make this work in Polymer.dart. Try as I might, the g property is not available:
Exception: Error evaluating expression 'g.buttonBorder': Class 'LoremDialog' has no instance getter 'g'.

NoSuchMethodError: method not found: 'g'
Receiver: Instance of 'LoremDialog'
Arguments: []
Darn it.

I think I am doing this right, but I am unable to discern a way to tease the g property into my Polymer.dart element. I will likely give this a try in JavaScript tomorrow to make sure that I am not overlooking something obvious.


Day #160

Thursday, June 19, 2014

Testing JavaScript Polymers… With Dart


Look, this isn't that hard. In order to test my <apply-author-styles> Polymer element, I need a test page that:
  1. holds a test Polymer element that uses <apply-author-styles>
  2. Can run in a server so that XHR request can be made
  3. Has custom styles that can be pulled from the page into the test custom element
Try as I might with grunt-contrib-jasmine and Karma, I cannot do this. grunt-contrib-jasmine and Polymer do not get along. Karma refuses to allow me to add custom CSS to the test context—at least not statically.

So you know what? I give up. I'm testing with Dart.

I already have Grunt setup in this project, so I stick with it here. In this case, I want a simple static server against which to run my tests (there is a simple Ajax component). I already have that in the form of grunt-contrib-connect. Now I need a way to run Dart tests against this JavaScript element (yes, I'm serious).

Since there is no grunt-contrib-dart yet (why not?!), I install grunt-shell:
$ npm install --save-dev grunt-shell
Then I add this to the imported tasks in my Gruntfile.js and define my test_runner.sh shell task that will run my Dart tests:
module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    // ...
    connect: {
      server: {
        options: {
          port: 8100,
          keepalive: false
        }
      }
    },
    shell: {
      test: {
        command: 'test/test_runner.sh'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-contrib-connect');

  grunt.registerTask('default', ['connect', 'shell:test']);
};
The test_runner.sh script is a simple fork of content_shell that comes bundled with Dart for headless testing—but real headless testing with an actual browser. The test_runner.sh script looks like:
#!/bin/bash

# Run a set of Dart Unit tests
results=$(content_shell --dump-render-tree http://localhost:8100/test/ 2>&1)
echo -e "$results"

# check to see if DumpRenderTree tests
# fails, since it always returns 0
if [[ "$results" == *"Some tests failed"* ]]
then
    exit 1
fi

echo
echo "Looks good!"
OK with that, I have my runner in place. Grunt will start grunt-contrib-connect as part of the default task and content_shell will run my test at http://localhost:8100/test/. Now I just need to define the test.

I start with a test context page that *I* can write:
<head>
  <!-- Load Polymer -->
  <script src="/bower_components/platform/platform.js"></script>

  <!-- Load component(s) -->
  <link rel="import" href="x-foo.html">

  <!-- Style that will apply to both page and Polymer elements -->
  <style>
    button { border: 5px solid orange; }
  </style>
</head>
<body>
  <div id=test><!-- Test element -->
    <x-foo></x-foo>
  </div>
  <div id=page><!-- Page element -->
    <button type=button>Test in Main Page</button>
  </div>
</body>
In there, I have the page style—orange buttons—that I want to apply to my <x-foo> test element that makes use of <apply-author-styles>. The <x-foo> element was defined a couple of days ago as:
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="apply-author-styles/apply-author-styles.html">
<polymer-element name="x-foo" noscript>
  <template>
    <apply-author-styles></apply-author-styles>
    <button id=test type=button>Test</button>
  </template>
</polymer-element>
That <apply-author-styles> should change the style of the button inside the element (something the old, deprecated applyAuthorStyles Polymer property used to do). I don't need to actually test that the button is orange. I may try that another day, but for now, I just need to know that that page style has been copied to the shadow DOM of my element. Or, in test form:
library main_test;

import 'package:scheduled_test/scheduled_test.dart';
import 'dart:html';

main(){
  group("[styles]", (){
    test('the app returns OK', (){
      var xFoo = query('x-foo');
      expect(xFoo.shadowRoot.text, contains('orange'));
    });
  });
}
Which does the trick:
CONSOLE MESSAGE: unittest-suite-wait-for-done
CONSOLE MESSAGE: PASS: [styles] the app returns OK
CONSOLE MESSAGE: All 1 tests passed.
CONSOLE MESSAGE: unittest-suite-success
That is not quite perfect—there is some discrepancy between running it in the browser and from content_shell that bears some investigation. Still, it is so very nice to have a testing framework that runs in the browser, can test easily against a custom page context, and actually passes.

As crazy as it might seem to run a Dart test runner for JavaScript code, the crazier thing might be fighting ever more obscure JavaScript testing frameworks. So I may end up sticking with this.


Day #98

Wednesday, June 18, 2014

Getting Started on grunt-contrib-jasmine for Polymer Testing (Thwarted)


Yesterday was one of those days that I start something I truly believe is easy only to wind up fighting every single decision and ultimately fail to accomplish my task. With a day between me and that failure, I believe my failure was not so much due to underestimating the difficulty of the problem. Rather, it was a stubborn inability to recognize that I was fighting my chosen tools too much.

I am trying to test the new apply-author-styles tag. It is a relatively simple Polymer element to be used in other Polymer elements so that these elements can adapt the same styles that are used on the page using the elements. That is, if my page styles <button> elements to have orange borders, then <apply-author-styles> inside another custom element should ensure that <button> elements in the custom element will have an orange border as well.

To test, I need two things: a page with styles and a custom Polymer element with <apply-author-styles> in its template. Yesterday I got the latter setup without difficulty. The <x-foo> test element should do the trick nicely:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../apply-author-styles.html">
<polymer-element name="x-foo" noscript>
  <template>
    <apply-author-styles></apply-author-styles>
    <button id=test type=button>Test</button>
  </template>
</polymer-element>
After some unrelated fights with both Karma and Jasmine, I finally realized that I had no way to hand alter the test page that Karma uses as its testing environment. I had no way to add the various styles that I need to test.

To be clear, I could dynamically add <link> and <style> tags to the Karma test page, but part of the functionality that I spiked into <apply-author-styles> was to ignore dynamically added styles. I fought with Karma. A lot. Eventually I found that there is no way to specify an alternate test context page in Karma. Which just stinks.

So I am faced with two options: fight Karma again or trying something new. Both have their appeal (I think I could hack in basic support for alternate context.html), but I opt for something new tonight. Specifically, grunt-contrib-jasmine.

I start by installing it:
$ npm install grunt-contrib-jasmine --save-dev
...
Done. Phantomjs binary available at /home/chris/repos/apply-author-styles/node_modules/grunt-contrib-jasmine/node_modules/grunt-lib-phantomjs/node_modules/phantomjs/lib/phantom/bin/phantomjs
grunt-contrib-jasmine@0.6.5 node_modules/grunt-contrib-jasmine
├── es5-shim@2.3.0
├── lodash@2.4.1
├── rimraf@2.1.4 (graceful-fs@1.2.3)
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
└── grunt-lib-phantomjs@0.4.0 (eventemitter2@0.4.13, semver@1.0.14, temporary@0.0.8, phantomjs@1.9.7-9)
I believe that I am going to need a simple web server to test this, so I also install grunt-contrib-connect:
$ npm install grunt-contrib-connect --save-dev
In addition to the previous dependencies that I have in this project, my package.json configuration file now looks like:
{
  "name": "apply-author-styles",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-contrib-jasmine": "~0.6.5",
    "grunt-contrib-connect": "~0.8.0"
  }
}
I add both tasks to my Gruntfile.js:
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    // ...
  });
  // ...
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-contrib-connect');
};
Then I configure both such that the tests will run on port 8100:
module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    // ...
    connect: {
      server: {
        options: {
          port: 8100
        }
      }
    },
    jasmine: {
      src: ['app/**/*.js'],
      options: {
        host: 'http://127.0.0.1:8100/',
        specs: 'test/*Spec.js',
      }
    }
  });
  // ...
};
The last thing that I need in there is a task that will start the test server and then run my tests:
module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    // ...
  });
  // ...
  grunt.registerTask('default', ['connect', 'jasmine']);
};
I make this my default task because I hope that this will be my main use for Grunt in this project.

I already have NOP spec in the test directory from my work yesterday and, it works:
$ grunt
Running "connect:server" (connect) task
Started connect web server on http://0.0.0.0:8100

Running "jasmine:src" (jasmine) task
Testing jasmine specs via PhantomJS

 <apply-author-styles>
   styles of elements using is
     ✓ should apply page CSS from <style> tags

1 spec in 0.017s.
>> 0 failures

Done, without errors.
All of this looks promising… until I try to add Polymer to the mix. I have a setup script that I can add as a helper in grunt-contrib-jasmine:
    // ...
    jasmine: {
      src: ['app/**/*.js'],
      options: {
        host: 'http://127.0.0.1:8100/',
        helpers: ['test/PolymerSetup.js'],
        specs: 'test/*Spec.js'
      }
    }
    // ...
The setup script adds the usual Polymer links and scripts to the page <head> and it works fine in Karma. But, when I run this in grunt-contrib-jasmine, I get:
➜  apply-author-styles git:(master) ✗ grunt
Running "connect:server" (connect) task
Started connect web server on http://0.0.0.0:8100

Running "jasmine:src" (jasmine) task
Testing jasmine specs via PhantomJS


log: platform.js is not the first script on the page. See http://www.polymer-project.org/docs/start/platform.html#setup for details.
>> ReferenceError: Can't find variable: Window at
>> http:/127.0.0.1:8100/bower_components/platform/platform.js:13 
>> http:/127.0.0.1:8100/bower_components/platform/platform.js:13 
...
And then I realize that I have already given up on PhantomJS (which is used by grunt-contrib-jasmine) with Polymer.

Ugh. I just don't think any of the objections from back then have been resolved. So it looks like I'm back to Karma and that ugliness. Sometimes it really is difficult to be so obsessive about testing...



Day #97

Tuesday, June 17, 2014

Karma Testing CSS in Polymer (Thwarted)


Up tonight, a bit of CSS testing. I don't know that I have ever tested code whose primary purpose was manipulating CSS, but how hard can it be?

The testing will apply to the newly minted <apply-author-styles> element. I will use the familiar combination of Karma and Jasmine to run the tests.

I start from a fixture page. In my test I will use a sample Polymer element, <x-foo>, and assert that various page classes should apply:
<polymer-element name="x-foo">
  <template>
    <apply-author-styles></apply-author-styles>
    <button id=test>Test</button>
  </template>
</polymer-element>
I start by forcing my HTML files in Karma to be treated as HTML source files, not fixtures (which would be available in the __html__ top-level lookup):
// ...
    preprocessors: null,

    files: [
      'test/PolymerSetup.js',
      {pattern: 'apply-author-styles.html', included: false, served: true},
      {pattern: 'apply_author_styles.js', included: false, served: true},
      {pattern: 'bower_components/**', included: false, served: true},
      'test/**/*Spec.js',
      {pattern: 'test/*.html', included: false, served: true}
    ],
    // ...
Then, in the PolymerSetup.js file that I still use for my Polymer testing, I load the definition for this test Polymer element in addition to loading <apply-author-styles>:
// ...

// 2. Load component(s)
var link = document.createElement("link");
link.rel = "import";
link.href = "/base/apply-author-styles.html";
document.getElementsByTagName("head")[0].appendChild(link);

var fixtureLink = document.createElement("link");
fixtureLink.rel = "import";
fixtureLink.href = "/base/test/x-foo.html";
document.getElementsByTagName("head")[0].appendChild(fixtureLink);

I keep forgetting that I am using Jasmine 2.0 nowadays and it takes me a while to remember how to install that. I need to add it to my NPM package.json file:
{
  "name": "apply-author-styles",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "karma-jasmine": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
And then run npm install. How could I possibly forget to configure and run a server-side package manager when configuring a client-side testing framework? It is completely obvious.

Ahem.

Finally, I am able to write a test:
describe('<apply-author-styles>', function(){
  var container, el;

  beforeEach(function(){
    container = document.createElement("div");
    el = document.createElement("x-foo");
    container.appendChild(el);
    document.body.appendChild(container);

  });

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

  describe('styles of elements using is', function(){
    it('should apply page CSS from <style> tags', function(){
      // ???
    });
  });
});
Unfortunately, I wind up stuck trying to test my specific element at this point. One of the main features of <apply-author-styles> is that it ignores styles that are not hard-coded in the original HTML document. Unfortunately, getting access to the original source document that is used to hold Karma tests—and to change it for a particular test run—seems difficult. At best.

I may have to alter my approach. Tomorrow.



Day #96

Monday, June 16, 2014

A Tag Named apply-author-styles


It occurs to me that, in the absence of the now-deprecated applyAuthorStyles in Polymer, it might be nice to have an <apply-author-styles> tag in Polymer. That is, if I define my custom polymer elements with <apply-author-styles>:
<link rel="import"
      href="apply-author-styles.html">
<script src="../bower_components/snap.svg/dist/snap.svg.js"></script>
<polymer-element name="x-pizza">
  <template>
    <apply-author-styles></apply-author-styles>
    <!-- ... --->
  </template>
  <script src="x_pizza.js"></script>
</polymer-element>
Then native elements (e.g. buttons) should pick up whatever crazy styles are defined in the top level document:



I figured out how to apply “author” styles over the past two nights. Now it is mostly a question of “if” and “how” to accomplish the same from a child custom element.

To find out, I remove all of the previous nights' code from my custom pizza building <x-pizza> Polymer element. With apply-author-styles.html imported and <apply-author-styles> in <x-pizza>'s <template> tag as from the beginning of this post, I am ready to start on the actual <apply-author-styles> Polymer definition.

I begin with the <polymer-element> definition in apply-author-styles.html:
<link rel="import"
      href="../bower_components/core-ajax/core-ajax.html">
<polymer-element name="apply-author-styles">
  <script src="apply_author_styles.js"></script>
</polymer-element>
This is simple enough. I import <core-ajax> to fetch the original parent page for comparison (as done last night). The rest sources the apply_author_styles.js backing class definition—there is no UI presence for this element.

With that out of the way, I start the JavaScript definition finding the main page document and the shadow root of the element that I am targeting:
Polymer('apply-author-styles', {
  attached: function() {
    this.parent = this.parentNode;
    this.authorDocument = this.ownerDocument;
    this.fetchOriginalOwnerDocument();
  },
  // ...
});
I need the parent node for access to the shadow root of the element that is holding <apply-author-styles>. I need the main document so that I only apply styles from the original, un-JavaScripted source. To get access, I fetch it with another, core Polymer element, <core-ajax> and, once I get it I start applying styles:
Polymer('apply-author-styles', {
  attached: function() {
    // ...
    this.fetchOriginalOwnerDocument();
  },

  fetchOriginalOwnerDocument: function() {
    var doc = this.originalAuthorDocument = document.createElement('core-ajax');
    doc.addEventListener('core-complete', this.addExternalCss.bind(this));
    doc.url = this.authorDocument.location.href;
    doc.go();
  },
  // ...
});
The addExternalCss() method is nearly identical to yesterday's version:
Polymer('apply-author-styles', {
  // ...
  fetchOriginalOwnerDocument: function() {
    var doc = this.originalAuthorDocument = document.createElement('core-ajax');
    doc.addEventListener('core-complete', this.addExternalCss.bind(this));
    doc.url = this.authorDocument.location.href;
    doc.go();
  },

  addExternalCss: function() {
    for (var i=0; i<this.authorDocument.head.children.length; i++) {
      var el = this.authorDocument.head.children[i];
      if (!this._isSupportedTag(el)) continue;
      if (!this._isFromOriginalAuthorDocument(el)) continue;

      var clone = el.cloneNode(true);
      if (clone.href != 'undefined') {
        clone.href = new URL(clone.href, document.baseURI).href;
      }
      this.parent.appendChild(clone);
    }

    // TODO: is this really the best way to handle this?
    this.element.convertSheetsToStyles(this.parent);
  },
  // ...
});
I gain access to Polymer's convertSheetsToStyles() method, which creates Polymer-ready versions of the various styles that are copied into the shadow root of <x-pizza>, not through <x-pizza>, but through <apple-author-styles>. I call that method with <x-pizza>'s shadow root, which feels a little wrong… except that it works

Not only does it work in Chrome, but in Firefox and even Internet Explorer:



So it looks like applyAuthorStyles is back—now in Polymer custom element form.

Without further ado… I introduce apply-author-styles.


Day #95

Sunday, June 15, 2014

Comparing the Original Owner Document


This is going to be a little esoteric, I think...

I have a means to replicate the old, deprecated applyAuthorStyles in Polymer elements. The idea is that I want certain elements—especially native elements like buttons—to look the same inside of custom elements as they do on the rest of the page. Until recently, this was the purview of the applyAuthorStyles setting in Polymer objects.

The working solution that I have is something of a brute force approach to the problem: I copy all stylesheet <link> and <style> tags into the shadow DOM of my custom element. It turns out that, with a few tweaks, this approach works just fine—even with odd orange borders applied to Bootstrap.com buttons:



A nice benefit of this approach is that there is no secondary request for external <link> stylesheets. The browser makes a request for the resource when it sees the <link> tag in the <head> of the page, but then relies on browser cache when it see a request for the same resource later:



The only drawback to this approach is that it pulls in all of the stylesheet <link> and <style> tags into the shadow DOM—even those that were added dynamically by Polymer. This does not result in any additional HTTP requests nor does it appear to affect styles, but I still object to this.

To get around this, I am going to compare the current CSS-related content in the main page—the “owner document” in Polymer parlance—with the original content of the main page. The only way to accomplish this (that I know of) is to re-fetch the original document via XHR. This seems ugly, but let's get on with it...

I replace yesterday's immediate copying of page styles into my Polymer element:
  attached: function() {
    this.addExternalCss();
    this.updatePizzaState();
  },
With a fetch of the original page via XHR:
Polymer('x-pizza', {
  created: function(){
    this.fetchOriginalOwnerDocument();
  },

Or, since this is Polymer, I use <core-ajax> to fetch the resource:
  fetchOriginalOwnerDocument: function() {
    var doc = this.originalOwnerDocument = document.createElement('core-ajax');
    doc.addEventListener('core-complete', this.addExternalCss.bind(this));
    doc.url = this.ownerDocument.location.href;
    doc.go();
  },
When the original owner document is fetched, then I call yesterday's addExternalCss() method. It still runs through the children of the owner document's <head>. Instead of skipping non-<style> and non-<link> tags. I now need an additional check to skip text that does not match content in the original document. Regular expressions to the rescue:
  addExternalCss: function() {
    var originalHtml = this.originalOwnerDocument.response;

    for (var i=0; i<this.ownerDocument.head.children.length; i++) {
      var el = this.ownerDocument.head.children[i];
      if (el.tagName != 'LINK' && el.tagName != 'STYLE') continue;

      var re = new RegExp(el.outerHTML);
      if (!re.test(originalHtml)) continue;

      var clone = el.cloneNode(true);
      if (clone.href != 'undefined') {
        clone.href = new URL(clone.href, document.baseURI).href;
      }
      this.shadowRoot.appendChild(clone);
    }

    // TODO: is this really the best way to handle this?
    this.element.convertSheetsToStyles(this.shadowRoot);
  },
That actually does the trick. I now have only three new stylesheet related tags appended to my shodow DOM:



I do find that some of the dynamically added CSS does not generate valid regular expressions. Rather than spend time parsing them and dealing with edge cases, I ignore them for now with a lovely try-catch:
  addExternalCss: function() {
    var originalHtml = this.originalOwnerDocument.response;

    for (var i=0; i<this.ownerDocument.head.children.length; i++) {
      var el = this.ownerDocument.head.children[i];
      if (el.tagName != 'LINK' && el.tagName != 'STYLE') continue;

      var re;
        try {
          re = new RegExp(el.outerHTML);
        } catch (x) {
          continue;
        }
      if (!re.test(originalHtml)) continue;

      var clone = el.cloneNode(true);
      if (clone.href != 'undefined') {
        clone.href = new URL(clone.href, document.baseURI).href;
      }
      this.shadowRoot.appendChild(clone);
    }

    // TODO: is this really the best way to handle this?
    this.element.convertSheetsToStyles(this.shadowRoot);
  },
That method is getting out of hand. It was not great before the try-catch, but it just looks way too big now. Still, it works. Hopefully I can distill this down into something easily resusable. Tomorrow.


Day #94

Saturday, June 14, 2014

Applying All the Page Styles Inside Polymer Elements


Up tonight a follow-up to yesterday's dynamic, external stylesheet styling of Polymer elements. Instead of applying arbitrary styles from external stylesheets, I would like to apply all styles from the “owner document” — the page that contains the custom Polymer element.

I am styling the page containing the pizza building <x-pizza> Polymer element with Bootstrap:
<!DOCTYPE html>
<html lang="en">
  <head>
    <link type="text/css" rel="stylesheet" href="assets/bootstrap.min.css">
    <script src="bower_components/platform/platform.js"></script>
    <link rel="import" href="elements/x-pizza.html">
  </head>
  <body>
    <div class="container">
      <h1>JavaScript Pizza Builder</h1>
      <x-pizza></x-pizza>
    </div>
  </body>
</html>
The goal today will be to apply that style—along with any other in the <head> section of the owner document—in my custom element. Toward that end, I add styles before and after the Bootstrap <link> tag:
    <!-- ... -->
    <style>
      .btn-default { color: yellow; }
    </style>
    <link type="text/css" rel="stylesheet" href="assets/bootstrap.min.css">
    <style>
      .btn-default { border: 5px solid orange; }
    </style>
    <!-- ... -->
Bootstrap overrides the yellow in the first <style> while the orange border in the second overrides Boostrap resulting in:



I hard-coded Bootstrap into my custom element yesterday, but without the <style> tags, button elements lack the amazing orange border:



To pull in both the Bootstrap <link> and styles, I replace yesterday's hard-coded Boostrap:
Polymer('x-pizza', {
 // ...
  addExternalCss: function() {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = '/assets/bootstrap.min.css';
    this.shadowRoot.appendChild(link);

    this.element.convertSheetsToStyles(this.shadowRoot);
  },
  // ...
});
Instead, I loop through the owner document's <head> in search of <link> and <style> tags to clone and add to my Polymer element's shadow root:
  addExternalCss: function() {
    for (var i=0; i<this.ownerDocument.head.children.length; i++) {
      var el = this.ownerDocument.head.children[i];
      if (el.tagName != 'LINK' && el.tagName != 'STYLE') continue;

      var clone = el.cloneNode(true);
      this.shadowRoot.appendChild(clone);
    }

    // TODO: is this really the best way to handle this?
    this.element.convertSheetsToStyles(this.shadowRoot);
  },
The convertSheetsToStyles() method call comes from yesterday's efforts. I defer the commented question above it for another day.

As for the rest of the code, it almost works. I specified the href in the stylesheet <link> as a relative URL. Inside the element, this URL no longer resolves. So I need an extra step to specify the absolute URL. The URL() constructor does that for me:
  addExternalCss: function() {
    for (var i=0; i<this.ownerDocument.head.children.length; i++) {
      var el = this.ownerDocument.head.children[i];
      if (el.tagName != 'LINK' && el.tagName != 'STYLE') continue;

      var clone = el.cloneNode(true);
      if (clone.href != 'undefined') {
        clone.href = new URL(clone.href, document.baseURI).href;
      }
      this.shadowRoot.appendChild(clone);
    }

    // TODO: is this really the best way to handle this?
    this.element.convertSheetsToStyles(this.shadowRoot);
  },
Which does the trick. Now the native elements in my Polymer look exactly as they do on the page:



In addition to the question about convertSheetsToStyles() being the best approach, I now have an additional problem: this approach pulls in styles that are dynamically added to the page—and there are several from Polymer alone. Although they do not have an effect, it would be nice to be able to apply only hard-coded styles. Still, this works and is relatively low on the amount of code. So I take my small victory and call it a day here.



Day #93

Friday, June 13, 2014

Dynamically Adding External Styles to Polymer Elements


I am still trying to dynamically apply page styles inside a Polymer element. Without this capability, things like native elements (buttons, drop downs, etc.) will default to native browser styles as in the pizza toppings choosers at the bottom of my <x-pizza> custom element:



Styling Polymer elements is easy—just put some CSS in the <template> part of the Polymer element definition. All the usual ways to style work, including @import, <link>, and <style>. How they work is the question to which I still lack a good answer. The hope is that, once I have that answer, I will be able to dynamically pull in external CSS—like that from the containing page.

I believe that last night's Platform.ShadowCSS was useful, but likely not the right path. Tonight, I take a closer look at what Polymer and its associated polyfills are doing. Specifically, how are they applying CSS from external sources? To answer that, I start with a <link> stylesheet tag inside my Polymer <template> definition:
<link rel="import"
      href="../bower_components/polymer/polymer.html">
<polymer-element name="x-pizza">
  <template>
    <link type="text/css" rel="stylesheet" href="/assets/bootstrap.min.css">
    <!-- Actual Polymer template definition here... -->
  </template>
  <script src="x_pizza.js"></script>
</polymer-element>
As expected, that has the desired behavior. Manually defining CSS works fine with Polymer, but is of limited use in this case. I might think my <x-pizza> element looks good with Bootstrap styles:



But potential designers might have other ideas. If I want my element to gain widespread support, it cannot rigidly adhere to one look. Note: this used to be the purview of the since deprecated applyAuthorStyles.

Anyhow, if I inspect the <link> tag in my custom element's shadow DOM, I find… that it is gone. In its place is an inline <style> tag that contains the contents of the external stylesheet:



Interesting. So something in Polymer is loading that stylesheet and using it to replace the original <link> tag. That sounds like exactly what I need—only I need to be able to run whatever that is after the normal Polymer initialization.

Taking a closer look at the JavaScript console, I see:
...
XHR finished loading: GET "http://localhost:8000/bower_components/polymer/polymer.html". Loader.js:171
XHR finished loading: GET "http://localhost:8000/bower_components/polymer/layout.html". Loader.js:171
XHR finished loading: GET "http://localhost:8000/assets/bootstrap.min.css". loader.js:87
...
(I have enabled “Log XMLHttpRequests” in Chrome's console settings)

Furthermore, if I expand the details of the XHR request, I find:
XHR finished loading: GET "http://localhost:8000/assets/bootstrap.min.css". loader.js:87
b.xhr loader.js:87
b.fetch loader.js:66
b.process loader.js:40
b.resolve styleloader.js:25
b.resolveNode styleloader.js:34
b.loadStyles styleloader.js:61
n.loadStyles styles.js:36
d.loadResources polymer-element.js:113
d.init polymer-element.js:36
d.createdCallback polymer-element.js:27
k CustomElements.js:294
h CustomElements.js:247
s CustomElements.js:397
h Observer.js:85
...
y Observer.js:314
d.parse Parser.js:34
d.parseImport Parser.js:47
d.parseLink Parser.js:42
(anonymous function) Parser.js:30
d.parse Parser.js:29
b boot.js:11
(anonymous function) boot.js:33
c HTMLImports.js:220
d HTMLImports.js:225
k.parseImport Parser.js:104
k.parseLink Parser.js:123
k.parse Parser.js:55
k.parseNext Parser.js:44
d Parser.js:149
That is quite a stacktrace (and I even cut a bunch of observable stacks out). But I focus my efforts on the loadResources() and loadStyles() portions of the stack. Although the latter seems the most promising (view the method on GitHub), it does not work for me because the fetchTemplate() method always returns undefined. Perhaps this is because the polyfill code has already fetched the template by this time.

But as luck would have it, I happen upon convertSheetsToStyles() (view the method on GitHub). This, like loadStyles(), is a method on PolymerElement, not the Polymer in my backing definition:
Polymer('x-pizza', {
  // ...
  attached: function() {
    this.addExternalCss();
    // ...
  },

  addExternalCss: function() {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = '/assets/bootstrap.min.css';
    this.shadowRoot.appendChild(link);
  },
  // ...
});
The PolymerElement is available in the element property. So I add a call to its convertSheetsToStyles() method after I have dynamically added the stylesheet <link> to the element's shadowRoot:
  // ...
  addExternalCss: function() {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = '/assets/bootstrap.min.css';
    this.shadowRoot.appendChild(link);

    this.element.convertSheetsToStyles(this.shadowRoot);
  },
  // ...
That does not result in an XHR request to load the contents of the stylesheet. But it does replace the <link> with an @import equivalent:



And that actually works. All of the native elements in <x-pizza> now have Bootstrap styles applied to them. Even better, this works in Firefox and even Internet Explorer:



That is pretty cool.

I would imagine that the @import is converted by Polymer into a full-blown inline <style> to better prevent FOUC in Polymer elements (something that Polymer is very good about). But I do not really have to worry about FOUC in this case—the stylesheet would have already been loaded in the <head> of the original document. This approach pulls the same stylesheet into the shadow DOM via @import, but no second request is needed—it is already in browser cache.

I feel a little bad about reaching under the PolymerElement covers like that. But not too bad!



Day #92