by Bill Heaton @pixelhandler
We’ll take a look at for both Web Components and Ember Components, and blur the lines between the two.
With the Ember 2.X Evolution on the way, you will have a new generation of first class citizens for your DOM.
Design your Ember Components with future standards in mind, learn easy ways for components to communicate using native events, & how to use native Web Components in synchronicity with Ember Components.
What are Native Web Components and Ember.Components, and how can I leverage them?
How can my use of Ember Components reflect Web Components specifications (not an official W3C adopted standard, yet)?
You’ve been waiting for browsers vendors to come up to bat and implement the spec for Web Components, well one has done just that.
So, you’re developing a product and want to use the latest, greatest tools available, and you’re ready to place your bets.
Is it time to start building with the Web Component specification? …Only if you can force your users to browse your app with Google Chrome.
So yeah, Web Components are not ready for prime time (across the board). But, strategically you can use them now…
- Let’s Define our Terms, What is…
- An Ember.Component
- A Web Component: HTMLImport, Template, Custom Element, Shadow DOM
- Compare & Contrast
- Design Concerns / What about the Spec?
- Encapsulation (beauty of OOP)
- The Ember 2.X Evolution
- A new generation of first class citizens for your DOM - Just because you can do it with Ember, should you?
- Blurring the lines between Web Components and Ember Components
- Building Components for Distribution
- Brocolli.js as your Build Pipeline
- Ember CLI, plus a Standalone Release
http://emberjs.com/api/classes/Ember.Component.html
An Ember.Component is a view that is completely isolated.
- Property access in its templates go to the view object
- Actions are targeted at the view object
- No access to the surrounding context or outer controller
- All contextual information must be passed in
Easy way: If you name a template components/my-foo, you will be able to use {{my-foo}} in other templates, which will make an instance of the isolated component.
{{app-profile person=currentUser}}
You can use yield inside a template to include the contents of any block attached to the component. The block will be executed in the context of the surrounding context or outer controller:
<!-- app-profile template -->
<h1>{{person.title}}</h1>
<img {{bind-attr src=person.avatar}}>
<p class='signature'>{{person.signature}}</p>
tagName, layoutName, willInsertElement, didInsertElement, actions, sendAction, targetObject, willDestroyElement, $, on, off
A Draft of Specifications:
- Template (HTML5)
- HTMLImport (Working Draft)
- Custom Element (Editor's Draft)
- Shadow DOM (Editor's Draft)
http://www.w3.org/TR/components-intro/
http://www.w3.org/TR/html5/scripting-1.html#the-template-element
http://www.w3.org/TR/html-imports/
http://w3c.github.io/webcomponents/spec/custom/
http://w3c.github.io/webcomponents/spec/shadow/
http://www.w3.org/wiki/WebComponents/
The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script. W3C Template Element: http://www.w3.org/TR/html5/scripting-1.html#the-template-element
When web pages dynamically alter the contents of their documents, they may require fragments of HTML which may require further modification before use, e.g the insertion of values appropriate for the usage context.
template.content Returns the template contents, which are stored in a DocumentFragment associated with a different Document (to avoid the template contents interfering with the main Document).
Introduction to Template Element
The template element doesn't provide data binding. <template> provides an ability to insert 'inert HTML tags' into a document.
By using 'inert HTML tags':
- Inlined scripts won't be executed without being stamped out
- Resources such as
<img>or<video>won't be fetched without being stamped out
To define a template, simply wrap your content with a <template> tag.
<template id="template">
<style>
...
</style>
<div>
<h1>Web Components</h1>
<img src="http://webcomponents.org/img/logo.svg">
</div>
</template>In order to stamp out the <template>, you'll need to write a bit of JavaScript.
<script>
var template = document.querySelector('#template');
var clone = document.importNode(template.content, true);
var host = document.querySelector('#host');
host.appendChild(clone);
</script>
<div id="host"></div>HTML Imports are a way to include and reuse HTML documents in other HTML documents. W3C HTML Imports: http://www.w3.org/TR/html-imports/
Imports are HTML docs, linked as external resources, from another HTML doc. The document that links to an import is called an import referrer. An import has an import referrer ancestor as its import referrer.
An import referrer which has its own browsing context is called a master document. Each import is associated with one master document.
The URL of an import is called the import location. In the import referrer, an import is represented as a Document, called the imported document. The imported documents don't have browsing context.
The set of all imports associated with the master document forms an import map of the master document. The maps stores imports as its items with their import locations as keys.
Provides a way for Web developers to build their own, fully-featured DOM elements.
It's possible to create DOM elements with any tag names in HTML, but these elements aren't very functional. Custom elements inform the parser how to properly construct an element & to react to lifecycle changes.
Rationalize the platform. The spec ensures that all of its new features & abilities are in concert with how the relevant bits of the Web platform work today
createdCallback- invoked after custom element instance is created and its definition is registeredattachedCallback- whenever custom element is inserted into a documentdetachedCallback- whenever custom element is removed from the documenattributeChangedCallback- whenever custom element's attribute is added, changed or removed.
A particularly pernicious aspect of the lack of encapsulation is that if you upgrade the library and the internal details of the widget’s DOM changes, your styles and scripts might break in unpredictable ways.
Shadow DOM addresses the DOM tree encapsulation problem.
Elements can get a new kind of node associated with them, a shadow root. An element with a shadow root is a shadow host. The content of a shadow host isn’t rendered; the content of the shadow root is rendered instead.
With Shadow DOM, all markup and CSS are scoped to the host element. CSS styles defined inside a Shadow Root won't affect its parent document, CSS styles defined outside the Shadow Root won't affect the main page.
Tutorials
- Design Concerns / What about the Spec?
- Encapsulation (Beauty of OOP)
[Encapsulation] is the packing of data & functions into a single component… It allows selective hiding of properties & methods in an object by building an impenetrable wall to protect the code from accidental corruption. [Encapsulation]: http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29
The [HTML5Rocks tutorials] on the subject of Web Components are an excellent resource for comparing/contrasting Web Components with Ember Components. [HTML5Rocks tutorials]: http://www.html5rocks.com/en/search?q=Web+Components
- Scope is isolated, only knows the context passed in. Compared with a view that knows the scope of the current controller. Body of component (between the opening and closing tags) is in the same scope of the template it belongs too.
- No encapsulation of styles, best to use a custom element and define a base style for the component.
- You can use in an Ember App today, in any modern browser.
- Specification - only works with Ember.js
- Can use a 'layout' (template); compile with your build pipeline, e.g. ember-cli
- Built-in data-binding (using Ember)
- Lifecycle callbacks (Events):
didInsertElement,parentViewDidChange,willClearRender,willDestroyElement,willInsertElement - Create components that extend from other components
- Bundle custom functionality into a single component
- Use a custom tagName (custom element)
- No stable 'ideal' way to distribute components, Ember CLI addons story is still in its infancy
- caniuse Custom Element
- Feature detecting is a matter of checking if
document.registerElement()exists - The most important API primitive under the Web Components umbrella
- Define new HTML/DOM elements
- Create elements that extend from other elements
- Logically bundle together custom functionality into a single tag
- Extend the API of existing DOM elements
var XFoo = document.registerElement('x-foo', {
prototype: Object.create(HTMLElement.prototype, {
bar: {
get: function() { return 5; }
},
foo: {
value: function() {
alert('foo() called');
}
}
})
});Lifecycle callback methods:
createdCallbackan instance of the element is createdattachedCallbackan instance was inserted into the documentdetachedCallbackan instance was removed from the documentattributeChangedCallback(attrName, oldVal, newVal)an attribute was added, removed, or updated
- caniuse Shadow DOM
- Shadow DOM is 'really' completely isolated, both in scope (context) and style.
- The shadow root has it's own stylesheet.
- There is a way with CSS to define styles outside of the component using
::shadowpseudo-element. - By 'really' isolated we mean there is only a couple backdoors e.g.
::shadowor/deep/using CSS or JavaScript (querySelector) - You can use only in Chrome
- Specification is a work in progress
For example, if an element is hosting a shadow root, you can write #host::shadow span {} to style all of the spans within its shadow tree.
<style>
#host::shadow span { color: red; }
</style>
<div id="host"><span>Light DOM</span></div>
<script>
var host = document.querySelector('div');
var root = host.createShadowRoot();
root.innerHTML = '<span>Shadow DOM</span>' +
'<content></content>';
</script>Using JavaScript can the shadow tree be accessed? Yes, with the power comes the responsibility to respect encapsulation.
document.querySelector('x-tabs::shadow x-panel::shadow #foo');
Do the ::shadow pseudo-element and /deep/ combinator defeat the purpose of style encapsulation? Shadow DOM prevents accidental styling from outsiders but never promises to be a bullet proof vest.
Developers should be allowed to intentionally style inner parts of your Shadow tree...if they know what they're doing. Having more control is also good for flexibility, theming, and the re-usability of your elements.
- caniuse HTML Import
- To detect support, check if .import exists on the element
'import' in document.createElement('link') - How many imports to you want to link to in the head of a document.
- Perhaps you still need a build pipeline to minimize http requests
- An import is just a document. The content of an import is called an
importdocument$('link[rel="import"]')[0].import; - Script in the import is executed in the context of the window that contains the importing document
- Imports do not block parsing of the main page
- The HTML Template element is a natural fit for HTML Imports
- An ideal way to distribute Web Components
- caniuse Template
- Looks good to go in modern browsers (not Internet Explorer)
- No built-in data-bindings, use Object.observe
- caniuse Object.observe
- Feature detect
<template>, create the DOM element and check that the .content property exists -'content' in document.createElement('template') - Content is effectively inert until activated
- Content within a template won't have side effects
- Content is considered not to be in the document
- The .content property is a read-only
DocumentFragmentcontaining the guts of the template - Create a deep copy of its .content using
document.importNode()
var t = document.querySelector('#mytemplate');
// Populate the src at runtime.
t.content.querySelector('img').src = 'logo.png';
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);- A new generation of first class citizens,
Componentsfor your DOM - http://www.emberaddons.com/?query=component
- Just because you can do it with Ember, should you?
Blurring the lines between Web Components and Ember Components
- Upgrade a native custom element into a Web Component
- alert-box-web-components
- jayphelps jsbin
Code Walkthrough:
- pixelhandler/alert-box-web-components
- Web Component only
- Ember.js app using (native) Web Component
- As an Ember.Component only
- Upgrade a native custom element into a Web Component
- alert-box-web-components - see examples/app.html
- jayphelps jsbin
<script type="text/x-handlebars">
{{input value=value}}
<x-ember class="blue"></x-ember>
<x-native foo={{value}} class="red">
{{value}}
</x-native>
</script>
<script type="text/x-handlebars" data-template-name="components/x-ember">
I am an ember component
</script>Setup component generation...
window.EmberENV = {
FEATURES: {
'ember-htmlbars-component-generation': true
}
};Create a native Web Component...
// Native Web Component
function XNativeElement() {}
XNativeElement.prototype = Object.create(HTMLElement.prototype);
document.registerElement('x-native', XNativeElement);
// Upgraded to an Ember Component using `x-native` element
App.XNativeComponent = Ember.Component.extend({
tagName: 'x-native',
attributeBindings: ['foo']
});Alert Box Web Component...
<!--
Web Component: Alert Box
-->
<template id="alert-box">
<style>
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
/* alert-box */
:host {
display: none;
width: 400px;
margin: 15px 0;
}
:host(.ready) {
display: block;
}
section {
background-color: #337ab7;
}
:host(.red) section,
:host([type="danger"]) section,
:host([type="fail"]) section {
background-color: #D9534F;
}
:host(.orange) section,
:host([type="warning"]) section {
background-color: #F0AD4E;
}
:host(.green) section,
:host([type="success"]) section {
background-color: #5CB85C;
}
:host(.blue) section,
:host([type="info"]) section {
background-color: #337ab7;
}
main {
color: #fff;
background-color: transparent;
font-family: 'Fira Sans', sans-serif;
overflow: visible;
display: flex;
flex-flow: row;
height: 60px;
}
section {
border-radius: 4px;
margin-right: 2px;
padding: 0;
display: flex;
justify-content: space-around;
align-items: center;
flex-flow: row;
}
section.notice {
flex: 10.5 10%;
}
section.action {
flex: 1 10%;
}
section.action:hover {
cursor: pointer;
}
aside {
flex: 1 10%;
padding: 6px 0 0 0;
}
article {
flex: 9 10%;
}
div {
flex: 1 auto;
align-self: center;
text-align: center;
padding: 6px 0 0 0;
}
div .close {
text-align: center;
}
</style>
<main class="alert-box">
<section class="notice">
<aside>
<content select=".icon"></content>
</aside>
<article>
<content select=".message"></content>
</article>
</section>
<section class="action">
<div>
<content select=".close"></content>
</div>
</section>
</main>
</template>
<script type="text/javascript" charset="utf-8">
document.addEventListener('DOMContentLoaded', function () {
'use-strict';
window.AlertBoxElement = document.registerElement('alert-box', {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function () {
this.addEventListener('click', this.clickHandler);
}
},
attachedCallback: {
value: function () {
if (this.innerHTML !== '') {
var template = document.getElementById('alert-box');
var clone = document.importNode(template.content, true);
this.createShadowRoot().appendChild(clone);
}
this.classList.add('ready');
}
},
detachedCallback: {
value: function () {
this.removeEventListener('click', this.clickHandler);
}
},
clickHandler: {
value: function (evt) {
evt = new CustomEvent('alert-box-click', evt);
this.dispatchEvent(evt);
this.parentNode.removeChild(this);
}
}
})
});
});
</script>
<!--
Web Component: Icon Info
-->
<template id="info-icon">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
<g>
<path fill="#FFFFFF" d="M51.833,39.464c0,0.919-0.68,1.68-1.76,1.68c-1.04,0-1.72-0.76-1.72-1.68c0-0.92,0.68-1.68,1.72-1.68
C51.153,37.785,51.833,38.544,51.833,39.464z M48.954,67.899V46.983h2.32v20.917H48.954z"/>
</g>
<circle fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" cx="49.95" cy="50.198" r="29.416"/>
</svg>
</template>
<script type="text/javascript" charset="utf-8">
document.addEventListener('DOMContentLoaded', function () {
'use-strict';
window.IconInfoElement = document.registerElement('icon-info', {
prototype: Object.create(HTMLElement.prototype, {
attachedCallback: {
value: function () {
var template = document.getElementById('info-icon');
var clone = document.importNode(template.content, true);
this.createShadowRoot().appendChild(clone);
}
},
})
});
});
</script>
<!--
Web Component: Icon X
-->
<template id="icon-x">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
<g>
<path fill="#FFFFFF" d="M61.059,64.036L49.884,49.837L39.005,64.036h-3.058l12.35-15.459L37.182,35.303h3.176l9.585,11.972
l9.467-11.972h3.059L51.59,48.451l12.643,15.585H61.059z"/>
</g>
</svg>
</template>
<script type="text/javascript" charset="utf-8">
document.addEventListener('DOMContentLoaded', function () {
'use-strict';
window.IconXElement = document.registerElement('icon-x', {
prototype: Object.create(HTMLElement.prototype, {
attachedCallback: {
value: function () {
var template = document.getElementById('icon-x');
var clone = document.importNode(template.content, true);
this.createShadowRoot().appendChild(clone);
}
},
})
});
});
</script>Upgraded Web Component to an Ember.Component...
<!--
Upgraded Web Component (to an Ember.Component) used within a template...
Ember Components utilizing native `<alert-box>` Web Component.
-->
<script type="text/x-handlebars" data-template-name="components/countdown-info">
<p class="message">Info Alert Box, Countdown is Over.</p>
<icon-info class="icon"></icon-info>
<icon-x class="close"></icon-x>
</script>Ember.Component template for content of native template...
<script type="text/x-handlebars" data-template-name="components/countdown-warning">
<p class="message">
Warning Alert Box w/ Countdown:<br>
<span class="minutes">{{minutes}}</span> minutes
<span class="seconds">{{seconds}}</span> seconds.
</p>
<icon-warning class="icon"></icon-warning>
<icon-x class="close"></icon-x>
</script>Ember.Component upgrade from Web Component...
// AlertBoxComponents and components that extend it upgrade
// a native Web Component `<alert-box>`
// NOTE: without alert-box being defined in ember...
// The feature for `ember-htmlbars-component-generation: true`
// would bug out on `<alert-box>` used in a template
App.AlertBoxComponent = Ember.Component.extend({
tagName: 'alert-box',
attributeBindings: ['type'],
type: 'info'
});
App.CountdownWarningComponent = App.AlertBoxComponent.extend({
classNames: ['fixed'],
attributeBindings: ['minutes:data-minutes', 'seconds:data-seconds'],
layoutName: 'countdown-warning',
type: 'warning',
minutes: 0,
seconds: 0
});
App.CountdownInfoComponent = App.AlertBoxComponent.extend({
classNames: ['fixed'],
layoutName: 'countdown-info'
});Ember.Component only (not using the Web Component)...
<script type="text/x-handlebars" data-template-name="components/alert-box">
<div class="notice box">
<div class="left">
{{partial iconTemplateName}}
</div>
<div class="middle">
<p class="message">
{{yield}}
</p>
</div>
</div>
<div class="action box">
<div class="right">
{{#if hasCloseContent}}
{{closeContent}}
{{else}}
{{partial closeTemplateName}}
{{/if}}
</div>
</div>
</script>- Broccoli.js as your [Build][alert-box-build] Pipeline
- [Ember CLI, plus a Standalone Release][sharing-as-ember-cli-addons] for non-ember-cli apps [alert-box-build]: https://github.com/pixelhandler/alert-box-web-components/blob/master/Brocfile.js [sharing-as-ember-cli-addons]: http://pixelhandler.com/posts/develop-embercomponents-for-sharing-as-ember-cli-addons-a-practical-example