Showing posts with label shadow dom. Show all posts
Showing posts with label shadow dom. Show all posts

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

Friday, February 7, 2014

Application CSS in Polymers Redux


This is my favorite time when writing books: when all the stuff I worked on in the first month breaks. This seems inevitable both because my initial work is… well, my first take on a subject. But also, things inevitably break because I am usually working on new stuff under active development. Last night, I ran into the latter kind of breakage.

I have a couple of Polymers, the parent <pricing-plans> and the child (singular) <pricing-plan> element. I used them to write a small amount of custom HTML to generate a lot of Bootstrap structured <div> tags. The end result is that I can write a small amount of meaningful HTML:
<pricing-plans>
  <pricing-plan name="Multi-Language">
    <ul>
      <li>Get the <strong>JavaScript</strong> version!</li>
      <li>Get the <strong>Dart</strong> version!</li>
      <li>Private <strong>GitHub repository</strong> access to see how
        it's done.</li>
    </ul>
  </pricing-plan>
  <!-- ... -->
</pricing-plans>
And get a Bootstrapped styled result:



The page has to include Bootstrap CSS, which the Polymer can then apply with applyAuthorStyles:
    Polymer('pricing-plans', {
      applyAuthorStyles: true
    });
The applyAuthorStyles setting means that the Polymer honors styles from the page in which it is included. Except it doesn't. Not anymore.

As Günter Zöchbauer was kind enough to point out, applyAuthorStyles is deprecated. In fact, it seems this deprecation is imminent in Chrome. When I was mucking about with the cat and hat shadow DOM CSS selectors last night, I had to enable the experimental chrome://flags setting for #enable-experimental-web-platform-features:



When I do that and reload the same page, I no longer see my nicely styled Bootstrap panels. I just see the vanilla styles of the raw HTML:



So, if CSS from the parent document can no longer be applied to Polymers, how do I get those styles in there? Put another way, if I install Bootstrap at the application level, how can it be applied inside the Polymer?

That turns out to be fairly easy (although it does require one weird trick!). I can include the application level Bootstrap via the usual <link> tag, but that <link> tag needs to go inside the Polymer's <template> tag:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="pricing-plans">
  <template>
    <div id="price">
      <div class="container">
        <div class="col-md-12 col-sm-4">
          <content></content>
        </div>
      </div>
    </div>
    <link type="text/css" rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
  </template>
  <script>
    Polymer('pricing-plans');
  </script>
</polymer-element>
As I found last night, CSS that applies to the shadow DOM—the cat and hat CSS selectors—can go outside the <template> tag. The shadow DOM aware selectors can penetrate the shadow DOM to do their styling work. But plain old CSS like that in Bootstrap only applies when included inside the document fragment of the Polymer's shadow DOM.

With that, I have my Polymer properly styled again:



Even the cat and hat styles are applying there. So this would seem to be approximately the proper approach. Now to start rewriting a chapter or two in Patterns in Polymer


Day #1,020

Wednesday, October 2, 2013

TDD the Shadow DOM in Polymer.dart


I am digging messing about with Polymer.dart and Shadow DOM. That's some good clean fun.

Without much difficulty, I have used Polymer to create an <ice-code-editor> tag that embeds nicely into a regular web page:



It seems that it was easy, in part, because I cheated. The actual code editor is not part of the shadow DOM that contains the title of the element:



In some respects, this might qualify as no-harm, no-foul. After all, it works and no harm is being caused by the ICE Code Editor being part of the main DOM tree. On the other hand, encapsulating all of a Polymer element inside the shadow DOM can keep the contents secure. More relevant to this particular case, it will prevent conflicts between elements. ICE has been developed primarily for a one-instance-per-page use case. It might work with multiple instances, but why risk conflicts if I don't have to?

Anyhow, tonight, I am going to attempt to drive the editor into the shadow DOM using tests (that's a pretty cool sentence, eh?). After last night, I already have some tests that are probing the shadow DOM:
    test("can set line number", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('(42)')
      );
    });
Using that test as a basis, I can describe my expectations as:
    test("creates an editor and preview", (){
      expect(
        query('ice-code-editor').shadowRoot.query('.ice-code-editor-editor'),
        isNotNull
      );

      expect(
        query('ice-code-editor').shadowRoot.query('.ice-code-editor-preview'),
        isNotNull
      );
    });
And, just like that, I have a failing test:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
FAIL: [polymer] creates an editor and preview
  Expected: not null
    Actual: <null>
A quick look at my Polymer code shows where I need to address the situation:
@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  @published String src;
  @published int line_number;

  void created() {
    super.created();

    var container = new DivElement();
    host.append(container);
    var editor = new ICE.Editor(container);
    // Other setup...
  }
}
Instead of adding the container element to the document, I need only add it to the Polymer element's shadow root:
@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  @published String src;
  @published int line_number;

  void created() {
    super.created();

    var container = new DivElement();
    shadowRoot.append(container);
    var editor = new ICE.Editor(container);
    // Other setup...
  }
}
Easy peasy. Except, of course, it does not work at all.

It turns out that the JavaScript code editor (ACE code editor) that is being used via js-interop does a lot of mucking with the DOM. The real DOM. The DOM that needs to have access to document and various top-level methods.

So I am pretty much out of luck in trying to add the editor to the shadow DOM. At least until the underlying JavaScript code supports the shadow DOM. That said, I am not at a complete dead end. Even though the editor part of ICE cannot be added to the shadow DOM, the preview layer can be:
    test("creates a shadow preview", (){
      expect(
        query('ice-code-editor').shadowRoot.query('.ice-code-editor-preview'),
        isNotNull
      );
    });
I make that test pass by adding a <div> to the shadow DOM and then passing it to the ICE Editor constructor:
@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  // ...
  void created() {
    super.created();

    var container = new DivElement();
    host.append(container);

    var preview_el = new DivElement();
    shadowRoot.append(preview_el);

    var editor = new ICE.Editor(container, preview_el: preview_el);
    // Other setup...
  }
}
Now that I think about it, it will not hurt to test that the editor is added to the main DOM tree as well:
    test("creates an editor", (){
      expect(
        query('ice-code-editor').query('.ice-code-editor-editor'),
        isNotNull
      );
    });
With that, I have four passing tests:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor 
 
All 4 tests passed. 
Best of all, I drove new behavior—element encapsulation—with tests. At some point I will need to verify that multiple instances of <ice-code-editor> on the same page will not cause trouble, but I will leave that for another day. This first pass at TDDing Polymer.dart features seems a fine stopping point for tonight.


Day #892

Tuesday, October 1, 2013

Testing the Shadow DOM


Yet again, the gap between where I expect to find trouble and where I actually find it… amazes. Last night I set out to test a Polymer.dart version of the ICE Code Editor. I cobbled something akin to a test together, but it proved unexpectedly difficult in unexpected ways.

I intentionally kept the implementation and the test heavy—the custom <ice-code-editor> tag has elements of js-interop and HTTP request while the test was of the full-stack variety. I had expected the js-interop or HTTP request bits to cause me problems—and they probably will, if I can get to them. The main problem wound up being the full-stack test.

I suppose that I should have expected this. “Full stack,” as it relates to Polymer, include multiple parts. There is the actual page that uses the custom Polymer element. When testing, this looks something like:
<html>
  <head>
    <link rel="import" href="packages/ice_code_editor/polymer/ice_code_editor.html">
    <!-- Polymer and test setup here --> 
    <script type="application/dart" src="test.dart"></script>
  </head>
  <body>
    <ice-code-editor src="embed.html" line_number="0"></ice-code-editor>
  </body>
</html>
For the <ice-code-editor> element to work, Polymer has to import the definition in the linked ice_code_editor.html file. Even that is not sufficient as ice_code_editor.html contains a reference to the backing class, which is located in yet another file:
<polymer-element name="ice-code-editor" attributes="src,line_number">
  <template><!-- template work here --></template>
  <script type="application/dart" src="ice_code_editor_element.dart"></script>
</polymer-element>
Last night's problem was in the initial load of the ice_code_editor.html template. When I load the test page in Dartium, I get a lovely CORS violation:
XMLHttpRequest cannot load 
  file:///home/chris/repos/ice-code-editor/test/polymer/packages/ice_code_editor/polymer/ice_code_editor.html. 
Cross origin requests are only supported for HTTP.
I was able to get the test working by loading the test page (and everything else) from a simple web server. Possibly because all of my client-side Dart testing to date has been from file:// URLs, running a web server to support tests—even full stack tests—feels like overkill. Realistically, Polymer testing will likely have to involve at least some full-blown web server work. Tonight, I would like to see if I can skip it by supplying a command line option to Dartium.

The --allow-file-access-from-files option should do the trick, so I close Dartium and restart it with:
$ chrome --allow-file-access-from-files
Currently, my test does not actually set an expectation, so I am only checking that everything compiles. In this case, it does as I see no errors or warnings in the console—only a pleasant, test successful message:



But what about real testing? When I use the <ice-code-editor> element on a real page, it currently places an <h1> above the actual code editor that mirror the attributes used in the tag:



If I set the src and line_number attributes in my test page, then I ought to be able to query that <h1> for those values:
<ice-code-editor src="embed.html" line_number="42"></ice-code-editor>
In test.dart, I try to query for the src value by checking the text contents of the first <h1> on the page:
    test("can embed code", (){
      expect(query('h1').text, 'foo');
    });
But that fails. In fact there is no <h1> on the page—not even in the working sample page. The <h1> is in the shadow DOM of the <ice-code-editor>. That is, I now have a DOM fragment that is completely separate from the main document DOM. This shadow DOM is included when the page is rendered, but it is entirely encapsulated within the <ice-code-editor>'s shadow root.

All of this means that I need to query for the <h1> inside the shadow root of <ice-code-editor>:
test("can embed code", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('embed.html')
      );
    });
And that works!
PASS: [polymer] can embed code
All 1 tests passed. 
Just for the heck of it, I write a separate test to query for the line number. This works without incident. The end result test looks as follows:
library polymer_test;

import 'package:unittest/unittest.dart';
import 'dart:html';
import 'dart:async';

main() {
  setUp((){
    var ready = new Completer();
    new Timer(
      new Duration(milliseconds: 250),
      ready.complete
    );
    return ready.future;
  });

  group("[polymer]", (){
    test("can embed code", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('embed.html')
      );
    });
    test("can set line number", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('(42)')
      );
    });
  });
}
The 250 millisecond delay in the setUp() gives ICE enough time to get up and running. I am unsure why (something to investigate another night) such a high number is needed more when running the test page from content_shell than directly in Dartium. I will find a better way of implementing that delay another day. More pressing is that, when I inspect things in the JavaScript console, I find that that the ICE code editor is outside of the <ice-code-editor> shadow root. It is actually in the main document DOM tree, which violates the spirit of Polymer. And I would still like to get this tested without relying on the --allow-file-access-from-files command line option for Dartium.

Those issues aside, I have two simple tests of my Polymer custom element. Once I figured out that --allow-file-access-from-files trick, it was pretty darn easy to write these tests. And where there are tests… robust, accurate, maintainable code is sure to follow.



Day #891