Fun With Polymer 1.1
Google's web UI framework can be a powerful web development tool if you know when to use it and how to use it. This article will give you a firm understanding.
Join the DZone community and get the full member experience.Join For Free
what is polymer?
polymer is google’s open source web component ui framework. the goal is to allow developers to utilize the latest web standards for web components in a cross browser way, today. web components is an umbrella of standards, specifically shadow dom , custom elements , and html imports .
these are the core technologies needed in browsers to build web components. given the web community is “design by committee”, it’s actually quite a fast moving standard in that context, thus much has changed between polymer version 0.5 and version 1.x. that said, google’s done a great job of shielding you from a lot of these core changes as well as including new features that iterate on top of previous work.
… the whole point of creating a ui framework, heh.
in short, polymer allows you to create your own ui controls more easily than you could in the past, built on web standards, and with performance in mind. that, and they already follow the material design guidelines .
what does the code look like in practice?
while this is native in browsers now:
results in this:
you can now do this:
and you’ll see this:
notice in bootstrap , you have to apply the css classes to the tag:
you’ll see a common theme with polymer is mainly focused around markup, specifically html tags. if you come from angular or react , you’ll immediately get that concept of creating your own elements to use. polymer is the same way.
the reason for this is attempting to mitigate “div soup”, where you have a lot of nested divs that use css styles create the user interface, as well as helping create semantics: allowing various technologies to glean meaning from your page. the semantics help for search engine optimization, accessibility, and even during development to lessen the cognitive overhead from developers and designers.
contrast how gmail is built:
versus using custom components:
although polymer’s nomenclature is about “tags” and “custom elements”, what you’re really doing is creating “components”: visual and non-visual.
why even do this?
components, composition, encapsulation, and design.
components: it’s how interfaces start
once you’ve got a few applications built under your belt, you start recognizing 2 patterns that emerge every project. you have a visual style guide, whether official or unofficial, that you follow. how buttons look, work, what colors the button is vs. the text, and its shape are all examples of the minutiae.
the other pattern is re-use. this is not just a programming concept related to dry , but a design one as well. the rule is you’re supposed to use the same ui controls for the same user actions so users can more easily use your application. jakob nielsen covers that in the “2. inconsistency” section of his top 10 application design mistakes article .
whether using angular, react, or polymer, you’re going to create 1 button, 1 time, and use it every where in your application a button is needed.
this applies to all user controls. polymer’s core concept is building these components while providing many of which you need out of the box so you don’t have to create everything from scratch. that said, if you wish to opt-out of material design, you can use the core web component libraries it provides to use your own look and feel.
composition: it’s how interfaces are made
once you have your components built, you then start composing them together into large components that house other components. this is called composition , using something in another thing. you either build more complex components using these pieces together, or build containers. this can be a customized button inside of a calendar control:
which is created by one html tag:
or a button and a text field input inside of a self-contained login form:
which is also created by one html tag:
lastly, you’ll sometimes create containers that house dynamic content and use html’s declarative nature. polymer’s <paper-card> is a perfect example. not only can you house custom content, they also gave you 2 areas for it to live, the ‘content’ and ‘actions’ area for buttons:
the more complex the components and screens, the more composition and containers you’ll create. polymer easily enables composition and containers.
encapsulation: do one thing well and don’t tell anyone how you do it
while functional & reactive programming are in, object oriented programming is still how most projects are primarily done and how most programming is still taught. good oop is when you create components that have a well understood api and don’t leak too much detail and state.
polymer attempts to fix the encapsulation problems the web has.
shadow dom enables you to hide dom from the document. just like you can’t open a native <button>, your normal dom api code won’t dig into your component.
this is in flux, but similar to html, the css styles you define in your shadow dom only apply to that component. they don’t leak out and overwrite other styles. conversely, you effectively have an umbrella from cascading styles so your component’s styles aren’t overwritten if they have the same names of something else. you can confidently put your component in any other application and be assured it’ll look the same.
beyond making object.prototype easier to work with, they don’t do much here since the web component has a lot of other solutions for this. however, they do make it easier to import via html imports. whether your code is code or visual code, both can be imported using the same tag.
the work google has done with polymer means you only have to do 2 steps to use a component you or someone else has written: import it and use it.
and then use it as normal html, in the light dom or shadow dom:
that is way easier than the copious devops, transpilers, and module libraries i and others use today. this is also why angular dart years ago went to the component model , and where angular 2 is going with class annotation . while functional is in, the basic concepts of modules, package organization, and encapsulation are still valid, good concepts to use and build applications with.
design the ui, it then (mostly) builds itself
designing applications is different from designing websites. the web development world is vast, complex, and there are a variety of approaches. the only consistency i’ve seen regarding design is that those building applications tend to encapsulate their design into the components they use to build applications whereas the web designers tend to do this from their css/less/scss.
polymer is clearly on the developers side on this one in that embracing shadow dom, i can layout my component’s visual pieces, code it to work, and style it all in the same place. once i distribute it, i don’t have to worry about style names that make sense, how the css is organized, what build task i use to re-compile the less, etc.
instead, you either just code the css inline with your component with confidence you aren’t negatively affecting another component, or you use common styles which are a safe, opt-in approach. that way, if you want to share a single style sheet, or support theming, you can do that without breaking encapsulation.
at this point, you help mitigate the biggest problem web designers have: developers.
most developers i’ve met say they care about design, but in practice don’t. this isn’t malicious, they’re just focused on their job and that’s making things work. they’re held accountable when they don’t work. if the color or font is wrong? that’s ok. doesn’t compile or show the data correctly from the database? that’s not ok.
this culture reinforces developers to stay away from design concerns unless they have too since a lot of design changes can’t easily be unit tested like their code can.
with polymer, once you hand a developer a component with the padding, fonts, and colors already correct, it’s pretty hard for them to screw that up unless they dive into the source components. for a designer, that’s powerful. for a developer who hates css or loves design but doesn’t have time for it, it’s awesome. for a business analyst, that’s less jira tickets that pollute the backlog and never get done in time for people to remember what the ticket was referring to.
additionally, for other designers, you can expose components via variables to allow them to break through the shadow dom in a clean and well documented manner, yet still abstract the implementation in case you have to refactor the component later.
components enable designers to ensure the building blocks developers use aren’t as easily broken, and developers in turn don’t have to worry as much about “crap, i forgot to re-add that css class which i can’t remember it’s name after i refactored that partial.”
so… why again?
application interfaces are typically built by composing components within components to create more complex views and screens. polymer can use polymer components inside of polymer components. you can also create containers to enable this dynamically.
polymer encapsulates html names and id’s via shadow dom ensuring you don’t have naming conflicts that break your application without a runtime exception letting you know it break based on some random design change. it also encapsulates your css there as well, inverting the control of how css works, ensuring the only css changes you can make are opt-in, or explicit via easily found keywords like /deep/, or developer created variables.
for developers, it enables easier encapsulation and adherence to oop concepts by making it easy to re-use the visual and non-visual components you create.
for designers, it helps ensure their css is harder to break by developers who don’t know any better by wrapping them in core building block components the developers don’t need to go into.
how do i use it?
i chose the hard way. i suggest you have more fun and choose the easy ways.
first, check out the yeoman generator-polymer . it’ll get you up and running fast, and has a build system already setup for you.
second, if yeoman ain’t yo thing, go straight to the starter kit (it’s what the generator helps get started for you).
third, you can just go straight to the seed element to get up and running with something simple and smaller locally to play with.
fourth, what was most enlightening for me was to build a component using the 0.5 docs “ your first polymer application “. they haven’t been updated for 1.0, but if you don’t mind hitting the migration guide , it still gets you 90% of the way there with the core concepts.
here some of the things that threw me for a loop.
when you read the docs for the iron and paper elements, they have properties and method documentation, but not events. as someone who builds gui’s, this seems like a glaring oversight. to fix it, first, memorize how events work via the fire method .
if someone goes:
then you know the event to listen for is ‘on-change’:
every single one of the paper elements links directly to the source code. dig in there for a “fire” method. if you don’t find it, then see which behaviors it implements (think decorator pattern or multiple inheritance ) and find their source code in the polymer repo via the search function. otherwise, scroll back to the top, and see what components it’s using. the fire method bubbles by default, so the components its using by composition could be the ones who actually fire the original event.
remember, fire(‘moo-cow’) results in a <component on-moo-cow=”onwubwubwub()”></component>. if you use camelcase instead of dash-case for fire events, you’ll drive yourself nuts when things don’t work.
once you start getting knee deep in building visual polymer components for a few days, you forget that you could build non-visual ones as well. since you can only use inheritance on native controls, most of your code will be composition: enhancing existing tags.
core things nobody tells you about
if you’ve been building applications on the front end for awhile, you start to have some expectations on where the basic things are. here they are.
use iron-ajax .
making selectable lists
use iron-selector .
basic css layout
responsive layouts / media queries
when you’re building components or screens that have 2 layouts, you use the iron-media-query inline. if you start duplicating markup for each media query, just refactor it to a component.
there’s like 5 icon classes… ignore them. just install iron-icons , then import the ones you need or all of them. to see which ones are available, navigate to the bower_components/iron-icons/demo/ folder on your local web server to see which ones you can use.
infinite scrolling list
… ah, the question you wish c# developers would ask you on interviews vs. red/black tree sorting… *ahem* if you need one, use iron-list .
they have a really cool uber-image component called iron-image . way better than img tags.
they have a nice wrapper around localstorage called iron-localstorage that would of saved me a lot of time. basically allows you to use polymer’s built-in data-binding with localstorage.
polymer doesn’t ship with a router. they did in 0.5, but in 1.x they assume you’ll use a router that’s right for you. there are a few polymer specific ones on github and customelements.io .
i tried a few, but none work with the way i work with mediator view’s doing most of the heavy lifting. some weren’t declarative enough or didn’t support custom <templates>. worse, the majority only supported 0.5, not 1.x.
injector and wiredep
as your project grows, you’ll need some type of module system. the nice thing about polymer is that it handles load order for you; as long as you have all your imports there, it doesn’t matter what order they are in. however, vulcanize , the build tool for polymer, doesn’t always work with 3rd party libraries. i use injector ( grunt / gulp ) which now embeds wiredep so it automatically puts script tags for all your npm and bower classes.
i couldn’t get the web components tester to work. after spending hours in grunt fighting with various missing paths, i gave up. i reckon if i had used the yeoman generator, it’d work. i did get the sample seed-element project’s tests working though.
what about x-tags ?
why would i use polymer vs. something like bootstrap or foundation?
polymer is part component framework, but it’s also a way to use the newest stuff, now, and help give google feedback on direction. since last year, polymer has been the “living prototype” of the web components standards and has changed as both people have used it, the ideas google has had to improve upon it, and the standards committee has started standardizing on the implementations.
unlike bootstrap/ foundation , you’re building real web components, not divs with decoration.
a lot of the value that polymer provides is that it implements google’s material design. if you don’t want that look and feel, you can still use most of the iron and neon animation elements and just stay away from paper.
for those of us in enterprise development building large applications, bootstrap reigns supreme, mainly because it has all the components we need, now. contrast that with polymer, i had to build a calendar / date picker since most of the ones i found were 0.5 only. i then found another v1 the next day. the community does build a lot on github, but quality does vary, and it’s not a single project like bootstrap’s is.
bottom line, bootstrap just has more of everything you need, both in design, typography, components, and layout.
could i use polymer with angular, backbone, or react?
if you’re going to use it with angular, try angular material first. you’re basically marrying yourself to material design’s look and feel, but most clients i know would be mostly ok with that.
if you want to do it yourself, i don’t recommend it. angular 1.0 doesn’t yet play well with shadow dom, whereas angular 2 is getting there. you get weird bugs unless you do it just right … which doesn’t really feel right. if you do forge ahead, you’ll enjoy that most of your angular directives can merely have this as their template:
notice it’s template, not templateurl, which means this is a nice way to give your polymer components controllers… sort of. while the methods work, binding and events were hard to figure out if they were working or not.
i haven’t tried this myself, but i know of one big bank that was investigating this approach last year mainly because they still have a lot of jsp and portals where full applications cannot be built, so instead they share mini-applications. polymer seems a great fit for this.
after having some experience using their composition strategy, both angular and backbone are way harder to integrate with than i originally thought since once you’re out of the polymer realm, things get harder to work with. binding doesn’t work, so you have to get/set things. events aren’t data bound, so you have to use addeventlistener. things like that. it’s just easier to live and work in the polymer realm, and take the same approach you do in backbone architecture: add as you need yagni style.
more investigation is needed as i might of missed some things or did outside world integration wrong.
react makes no sense with polymer. they both are trying to solve the same thing: faster and easier dom. react claims that it’s fast , whereas a lot of the polymer justification of the <template> tag and shadow dom is performance. i don’t know who’s right, but both build reusable components, have data binding, have a nice component lifecycle, make the dom easier to work with, and have no implied mvc architecture on top. it’d be easier to use react within polymer i think, but again, i don’t see the point unless you believe the speed benefits could help in the shadow dom realm.
polymer’s great. i like the v1.1 release a lot. using components feels natural, and is how i built applications from my director, flash, silverlight, and flex days. while i hate css, i enjoy that flexbox mostly works, and much of material design is already implemented for me. i like the iron and paper components i have out the box.
i’m disappointed it’s not as many as bootstrap. i also miss all of the angular features i’ve become accustomed to, mainly ui-router, controllers, and dependency injection for easier unit testing. jury’s out on devops. i also miss the 0.5 docs; i’m guessing the plethora of standards changes at google is just really fast and maybe their short on documentation resources, or don’t have an easy way for open source to contribute on that front.
if i had a smaller gig where i wasn’t building a large, year long application with 20+ developers, and i could justify the time building the missing bootstrap components/css if any, i’d definitely choose polymer. as someone who was forced to the web, it’s certainly made it a lot more fun to work with.
Published at DZone with permission of James Warden, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.