A user account is required in order to edit this wiki, but we've had to disable public user registrations due to spam.

To request an account, ask an autoconfirmed user on Chat (such as one of these permanent autoconfirmed members).

Component Model: Difference between revisions

From WHATWG Wiki
Jump to navigation Jump to search
(move Isolation brainstorming content to a separate page)
No edit summary
 
(137 intermediate revisions by 5 users not shown)
Line 1: Line 1:
Here's a good starting point for learning about the component model spec, which is currently [https://github.com/dglazkov/component-model under development] (also see periodically updating [http://dglazkov.github.com/component-model/ gh-pages]).
Here's a good starting point for learning about the [https://github.com/dglazkov/component-model component model spec], which is being developed by applying a [[Component_Model_Methodology | defined methodology]].


=Introduction=
=Introduction=


''TODO'' Populate with beautifully crafted words.
The '''Component Model''' introduces comprehensive support for creating DOM elements. [[Component_Model_Use_Cases | Examples]] include layout managers, combinations of Dojo and jQuery widgets, isolated widgets, such as Like/+1 buttons, and built-in HTML elements themselves.  Reflecting on the experience of Mozilla's XBL  and Microsoft Internet Explorer's HTML components, the Component Model formalizes the concept of loosely coupled, coherent units of [[Behavior Attachment | behavior]]  in the [http://www.w3.org/wiki/Open_Web_Platform Web platform]. The functionality goals of the Component Model resemble  the goals of [http://dev.w3.org/2006/xbl2/ XBL2]; unlike XBL2, the Component Model seeks to be more incremental and modular while leveraging and integrating with new technologies.


Related links:
* [[Behavior_Attachment | Behavior Attachment]] -- a general overview of the behavior attachment problem
* [[Component_Model_Methodology | Component Model Methodology]]
* [[Component_Model_Use_Cases | Component Model Use Cases]]
* [[Component_Model_Use_Cases | Component Model Use Cases]]
* [[Behavior_Attachment| Behavior Attachment]]
* [http://dglazkov.github.com/component-model/ Current Component Model Spec] ([https://github.com/dglazkov/component-model Github project])
 
=Properties=
 
The component model aims to satisfy several key properties. These properties were extracted from the [[Component_Model_Use_Cases | use cases]]. This section explains component model basics by studying each property.
 
==Extensibility==
 
The component model enables creation of new types of DOM elements by allowing the use of existing DOM elements in JavaScript prototype chain. For example, here's how you would create a new sub-type of HTMLElement:
<code>
<pre>
function LayoutManagerPanel() {
    HTMLElement.call(this);
}
 
LayoutManagerPanel.prototype = Object.create(HTMLElement.prototype);
 
// ...
 
// 1) Will not be able to add instances of LayoutManagerPanel to document without this call.
// 2) First parameter specifies the tagName of the element being registered and must be a string prefixed with "x-".
Element.register("x-layout-manager-panel", LayoutManagerPanel);
 
// ...


=Overview=
var panel = new LayoutManagerPanel();
document.body.appendChild(panel);
// or
document.body.innerHTML = "<x-layout-manager-panel></x-layout-manager-panel>";
</pre>
</code>


==Composability==
The resulting <code>panel</code> instance is a Javascript object that is a valid DOM element, which can be added to the DOM tree. You can then extend this object using standard Javascript prototype inheritance.
 
Required Building Blocks:
* [[#Constructable_DOM_Types | Constructable DOM Types]]
* [[#Registering_Elements | Registering Elements]]


==Consistency==
==Consistency==
Because components are just DOM objects, they inherently share the same traversal and manipulation APIs, as defined by the [http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html DOM4]. The authors of components can extend these APIs by adding custom methods and properties on DOM objects, using standard JavaScript inheritance:
<code>
<pre>
Widget.prototype = Object.create(HTMLElement.prototype, {
    update: {
        value: function() { /* ... */ }
    },
    value: {
        get: function() { /* ... */ },
        set: function() { /* ... */ }
    },
  // ...
});
</pre>
</code>
The common API surface and the ability to extend it serves as a natural API boundary for framework authors, enabling interoperability.
Required Building Blocks:
* [[#Constructable_DOM_Types | Constructable DOM Types]]


==Encapsulation==
==Encapsulation==
Encapsulation refers to ability of the component to hide its implementation details and state from the document. To enable hiding of the implementation details, the component model provides a way to build a DOM tree that is not accessible from the document DOM tree, but is rendered as part of the document. This DOM tree, associated with the component is the [http://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/ shadow DOM]. The boundary between the document DOM tree and shadow DOM tree provides complete encapsulation, and ensures that:
* no shadow DOM tree nodes cross this boundary during event dispatch;
* document DOM tree has no access to nodes in the shadow DOM tree.
Additionally, the boundary serves as a convenient style application lever, giving the component a choice of letting (or not letting) document CSS affect the shadow DOM tree.
Every DOM element instance may only have (or ''host'') one shadow DOM tree. A shadow tree is instantiated by creating an instance of the <code>ShadowRoot</code> object, which takes a reference to the hosting element as a parameter. Attempting to create more than one instance for the same element throws an exception:


== Isolation ==
<code>
<pre>
function LayoutManagerPanel() {
    HTMLElement.call(this);
    var shadow = new ShadowRoot(this);
    var shadow2 = new ShadowRoot(this); // throws an exception.
  // ...
}
</pre>
</code>


[[Component_Model_Isolation_Brainstorming | Brainstorming page]]
Required Building Blocks:
* [[#Shadow_DOM | Shadow DOM]]


==Extensibility==
==Composability==


New element types are created by extending DOM elements. Each descendant can create its own shadow DOM subtree. If the descendant chooses to do so, the parent shadow DOM subtree becomes inaccessible and invisible. It's still there (to ensure that the code written to exercise it doesn't freak out), but it isn't rendered -- it's a ''ghost tree''. A child may return this tree back to life by using <code>&lt;inherited&gt;</code> element anywhere in its shadow DOM subtree. The <code>&lt;inherited&gt;</code> is replaced with the parent shadow DOM subtree when rendering.
Being DOM objects, components fit naturally into the document DOM tree and support all of its composition properties. In addition, the <code>content</code> element allows controlling interaction between shadow and document DOM trees. A <code>content</code> element specifies places where immediate document tree children of the component are rendered ''inside'' the shadow tree.


The essential mechanics of this behavior are probably as follows:
There can be more than one <code>content</code> element in the shadow tree. The <code>includes</code> attribute provides a convenient way to sort element's children by CSS selector. For example, a <code>DockLayoutPanel</code> component could be used like this in the document DOM tree:
* when initializing element, walk up to the prototype chain until top
<code>
* walking down, for each member of the prototype chain, create shadow DOM subtree
<pre>
* render only the tree at the bottom of the chain.
&lt;x-dock-layout-panel&gt;
    &lt;h1 class=&quot;north&quot;&gt;On Gardens&lt;/h1&gt;
    &lt;ul class=&quot;west&quot;&gt;
        &lt;li&gt;Automatic Gardens&lt;/li&gt;
        &lt;li&gt;Gardening on minefields&lt;/li&gt;
    &lt;/ul&gt;
    &lt;p&gt;I love gardening.&lt;/p&gt;
    &lt;div class=&quot;south&quot;&gt;Written by Chauncey Gardiner.&lt;/div&gt;
&lt;/x-dock-layout-panel&gt;
</pre>
</code>
Provided that its shadow DOM tree looks like this:
<code>
<pre>
&lt;#shadow-root&gt;
    &lt;div class=&quot;north&quot;&gt;
        &lt;content includes=&quot;.north&quot;&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;div class=&quot;west&quot;&gt;
            &lt;content includes=&quot;.west&quot;&gt;
        &lt;/div&gt;
        &lt;div class=&quot;east&quot;&gt;
            &lt;content&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;south&quot;&gt;
        &lt;content includes=&quot;.south&quot;&gt;
    &lt;/div&gt;
&lt;#shadow-root&gt;
</pre>
</code>
The document DOM tree children on of <code>x-dock-layout-panel</code> will be rendered as if composed from this tree:
<code>
<pre>
&lt;x-dock-layout-panel&gt;
    &lt;div class=&quot;north&quot;&gt;
        &lt;h1 class=&quot;north&quot;&gt;On Gardens&lt;/h1&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;div class=&quot;west&quot;&gt;
            &lt;ul class=&quot;west&quot;&gt;
                &lt;li&gt;Automatic Gardens&lt;/li&gt;
                &lt;li&gt;Gardening on minefields&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
        &lt;div class=&quot;east&quot;&gt;
            &lt;p&gt;I love gardening.&lt;/p&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;south&quot;&gt;
        &lt;div class=&quot;south&quot;&gt;Written by Avid Gardener.&lt;/div&gt;
    &lt;/div&gt;
&lt;/x-dock-layout-panel&gt;
</pre>
</code>


Every instance also gets an opportunity to create its own shadow DOM subtree by using the <code>shadow</code> property. If the property is set, the newly blessed shadow DOM subtree behaves as if it was stuck at the bottom of the prototype chain, turning its prototype shadow DOM subtree into a ghost.
Required Building Blocks:
* [[#Content_Element | Content Element]]


==Desugaring==
==Desugaring==
The component model also explains pretty well how the native HTML elements are built and dispels some of the magic associated with the "DOM object vs. JavaScript object" juxtaposition.
Allowing DOM elements to participate in the JavaScript inheritance chain makes DOM elements more approachable and easier to work with.
Complex DOM elements that are rendered with more than one CSS box (and aren't specified in terms of CSS, like [http://dev.w3.org/csswg/css3-lists/ lists]) are just components that have shadow DOM. Coincidentally, this also explains why you can't add shadow DOM subtrees to <code>input</code> or <code>details</code> elements -- their <code>ShadowRoot</code>s are claimed by <code>HTMLInputElement</code> and <code>HTMLDetailsElement</code> constructors, respectively.
Required Building Blocks:
* [[#Shadow_DOM | Shadow DOM]]
* [[#Content_Element | Content Element]]
==Performance==
Considering the way Web works, the component model must allow decoupling of the instantiation and the declaration of the components in order to provide reasonable performance characteristics. It's an unfortunate, but necessary requirement. In other words, we must be able to handle situations where a component instance is created before it is declared. Here's an simple example:
<code>
<pre>
// somewhere in view.js
...
document.body.innerHTML = '<div class="awesome"><x-layout><x-spring-panel>...</x-spring-panel></x-layout>';
...
// somewhere in layout.js
Element.register('x-layout', Layout);
Element.register('x-spring-panel', SpringPanel);
</pre>
</code>
In this situation, there is no room for error: <code>view.js</code> ''must'' wait for <code>layout.js</code> to load before executing. You can't load <code>layout.js</code> lazily or in any different order, since it defines the components that are used in <code>view.js</code>. Given that asynchronous, deferred or lazy-loading of script are all common performance techniques in today's Web, we must do better than block or throw an exception in such cases.
The component model offers this solution:
When an unknown DOM element with an "x-"-prefixed <code>tagName</code> is encountered, we put a placeholder <code>HTMLUnknownElement</code> instance in its place. As soon as the element is defined, all placeholder instances are replaced ([http://www.w3.org/TR/DOM-Level-3-Core/core.html#Document3-renameNode Document.renameNode]) with the new, proper DOM element.
Required Building Blocks:
* [[#Registering_Elements | Registering Elements]]
== Confinement ==
Confinement refers to the document protecting its implementation details and state from the component and can be viewed as the inverse of [[#Encapsulation | encapsulation]].
Required Building Blocks:
* [[#Confinement_Primitives | Confinement Primitives]]
=Building Blocks=
The component model is comprised of the following building blocks.
==Shadow DOM==
Any DOM element can host a shadow DOM subtree. The shadow DOM subtree originates at <code>ShadowRoot</code>, which is coupled the hosting element at the time of its construction. You don't need any other building blocks in order to take advantage of the shadow DOM:
<code>
<pre>
var element = document.createElement("div");
var shadow = new ShadowRoot(element);
shadow.appendChild(document.createElement("p")).textContent = "weee!!';
</pre>
</code>
A <code>ShadowRoot</code> instance is a [http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-node Node], and acts as the root of the element's shadow DOM subtree. The <code>ShadowRoot</code> itself is never rendered, nor has styles. In this regard, it's similar to the [http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-documentfragment DocumentFragment]. It has two properties:
* <code>applyAuthorSheets</code>, which is either '''true''' (that is, apply author style sheets from the document), or '''false''' (don't);
* <code>shadowHost</code>, which points to the hosting element.
==Content Element==
The <code>content</code> element is used with [[#Shadow_DOM | Shadow DOM]] and provides a mechanism for distributing hosting element's children inside of its shadow subtree. To preserve the [[#Encapsulation | encapsulation]] property, the <code>content</code> elements act as insertion points and do not leak any information about hosting element's children to the shadow DOM subtree or vise versa.
==Constructable DOM Types==
The inability to construct DOM element using <code>new</code> (with some exceptions) or use them in the prototype inheritance chain had confounded many Web developers since the beginning of DOM. This building block intends to rectify at least the latter by allowing <code>HTMLElement.call</code> invocation and thus enabling creation of JavaScript objects with DOM elements in the prototype chain.
==Registering Elements==
Working in conjunction with  [[#Constructable_DOM_Types | Constructable DOM Types]], this building block makes the list of valid markup tag names extensible by exposing <code>Element.register</code>:
<code>
<pre>
partial interface Element {
    static void register(in String tagName, in Function constructor);
}
</pre>
</code>
It is possible to envisage a milder (though less elegant) version of element registration by keeping DOM element construction magical (thus decoupling it from [[#Constructable_DOM_Types | Constructable DOM Types]]) and making <code>Element.register</code> use a callback, rather than <code>constructor</code> as parameter. The callback would be invoked with an already-constructed DOM object with the specified <code>tagName</code>, leaving the work of setting up properties on this object to the callback.
==Confinement Primitives==
The API surface of the component model lends itself well to proper confinement. Here's an approach that could be used to provide it (very early brainstorming):
* Confinement is not tied to the component model. Instead, it's a new twist on the method of loading scripts. A script could be loaded as usual or it could be ''confined'', or loaded into its own context.
* When confined, a script has its own global and document objects. These objects only reveal some safe limited subset of the actual document objects.  Think of it as a same-origin iframe with restrictions on document and window.
* You can communicate with the main document using <code>window.postMessage</code>.
* The confined document DOM tree is always empty. Attempting to insert into it throws exceptions.
* ... except when you append to elements in shadow DOM. That's right, you can do <code>Element.register</code> and <code>new ShadowRoot</code> in the confined document.
* Whenever you register an element, it registers ''in the main document'' as well. Creating an instance of a component from an confined document produces a functional DOM element shell that proxies to the actual element in the confined document.
Proposed API: introduce a new <code>confined</code> attribute to the <code>script</code> element. Presence of this attribute triggers loading scripts in the confined context.
Confinement of script execution could be useful outside of the component model and also could be related to [https://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html Content Security Policy].
* [[Component_Model_Isolation_Brainstorming | Isolation Brainstorm]]
=Building Blocks Use Case Coverage=
Here's a list of building blocks, tabulated against the [[Component_Model_Use_Cases | use cases]] and approximate percentage of satisfying them:
{| cellpadding="10" cellspacing="0" style="border-collapse: collapse;"
|- valign="top" style="border-bottom: 1px solid LightGray;"
! align="left" | Building Block
! align="left" | [[Component_Model_Use_Cases#Layout_Manager | Layout Manager]]
! align="left" | [[Component_Model_Use_Cases#Widget_Mix-and-Match | Mix-and-Match]]
! align="left" | [[Component_Model_Use_Cases#Rendering_Form_Controls_with_SVG | SVG Controls]]
! align="left" | [[Component_Model_Use_Cases#Contacts_Widget | Contacts Widget]]
! align="left" | [[Component_Model_Use_Cases#Like.2F.2B1_Button | Like/+1 Button]]
! align="left" | [[Component_Model_Use_Cases#Media_Controls_For_The_Video_Element | Media Controls for the Video Element]]
! align="left" | [[Component_Model_Use_Cases#Details.2FSummary_Elements | Details/Summary Element]]
|- valign="top" style="border-bottom: 1px solid LightGray;"
| [[Component_Model#Shadow_DOM | Shadow DOM]]
| 25%
| -
| 34%
| 100%
| 25%
| 100%
| 50%
|- valign="top" style="border-bottom: 1px solid LightGray;"
| [[Component_Model#Content_Element | Content Element]]
| 25%
| -
| -
| -
| -
| -
| 50%
|- valign="top" style="border-bottom: 1px solid LightGray;"
| [[Component_Model#Constructable_DOM_Types | Constructable DOM Types]]
| 25%
| 50%
| 33%
| -
| 25%
| -
| -
|- valign="top" style="border-bottom: 1px solid LightGray;"
| [[Component_Model#Registering_Elements | Registering Elements]]
| 25%
| 50%
| 33%
| -
| 25%
| -
| -
|- valign="top" style="border-bottom: 1px solid LightGray;"
| [[Component_Model#Confinement_Primitives | Confinement Primitives]]
| -
| -
| -
| -
| 25%
| -
| -
|}
=Comparison With Existing Specs and Implementations=


From component model's perspective, all native form controls or elements with non-trivial behavior are also sub-classes of more primitive DOM elements with shadow DOM subtrees and behaviors attached. Thus, you can extend them and override shadow DOM subtrees just like you would with any component.
Here's a brief overview of existing similar specifications and implementations:
* [http://msdn.microsoft.com/en-us/library/ms531018(v=vs.85).aspx HTML Components] is a [http://windows.microsoft.com/en-US/internet-explorer/products/ie/home Microsoft Internet Explorer]-specific method of creating custom DOM elements. Also see [http://www.w3.org/TR/NOTE-HTMLComponents HTML Components Note] (implemented in IE5+).
* [http://www.w3.org/TR/2001/NOTE-xbl-20010223/ XBL], currently implemented in Mozilla.
* [http://dev.w3.org/2006/xbl2/ XBL2], the ancestral spec of the Component Model, and a revision of XBL.


For example, in [[Component_Model_Use_Cases#Rendering_Form_Controls_with_SVG | Rendering Form Controls with SVG]] use case, this allows the engineer to override appearance of a form element completely or to reuse it and supplement it with extra bits of appearance.
Here's a handy overview of how each of these specs satisfies the component model [[#Properties | properties]]:


==Differences From Existing Specs==
{| cellpadding="10" cellspacing="0" style="border-collapse: collapse;"
|- valign="top" style="border-bottom: 1px solid LightGray;"
! align="left" width="12%" | Spec/Implementation
! align="left" width="12%" | [[#Extensibility | Extensibility]]
! align="left" width="12%" | [[#Consistency | Consistency]]
! align="left" width="12%" | [[#Encapsulation | Encapsulation]]
! align="left" width="12%" | [[#Composability | Composability]]
! align="left" width="12%" | [[#Desugaring | Desugaring]]
! align="left" width="12%" | [[#Performance | Performance]]
! align="left" width="12%" | [[#Confinement | Confinement]]
|- valign="top" style="border-bottom: 1px solid LightGray;"
! align="left" | HTML Components
| '''No'''. Components are magic, inextensible objects.
| '''Almost'''. Implementation provides ways to add properties, methods, events to element API, and the components are ''almost'' DOM elements. However, custom tags don't support all properties of a DOM element.
| '''Not much'''. There are some provisions for event encapsulation, nothing else.
| '''Not much'''. No provisions for handling document children vs. component-defined children.
| '''No'''.
| '''Not sure'''.
| '''No'''.
|- valign="top" style="border-bottom: 1px solid LightGray;"
! align="left" | XBL
| '''No'''. The mechanism for extending bindings is entirely independent of DOM type or Javascript extensibility.
| '''Yes-ish'''. Bindings can override properties on the DOM element, although the mechanism is highly unnatural (XML declarations).
| '''Yes'''? Hard to say looking at TR note.
| '''Yes'''
| '''Yes'''. Some HTML elements in Gecko are implemented using it.
| '''Not sure'''.
| '''No'''.
|- valign="top" style="border-bottom: 1px solid LightGray;"
! align="left" | XBL2
| '''No'''. Same as XBL.
| '''No'''. Bindings are discouraged from establishing an API surface on a bound element.
| '''Yes'''.
| '''Yes'''.
| '''No'''. The spec didn't intend to describe how native elements are built.
| '''Somewhat'''. The lifecycle of a binding is well-defined and initialization stages are well-decoupled. However, there is no way to build a binding imperatively without loading a binding document.
| '''No'''.
|}


The key differences between XBL2 and the Component Model are:
* The Component Model fully embraces the [[Behavior_Attachment#Behavior_Attachment_Methods | element behavior attachment]] by allowing creation of new types of DOM elements within a document. This is something Web Framework developers always wanted and repeatedly try to do with parallel object hierarchies. Eliminating ephemerality of the attachment simplifies and clarifies how things work conceptually -- there is no longer a place for "spooky action at a distance", caused by a change of a random CSS selector or even removing an element from the tree.
* The Component Model is strongly biased toward reusing existing bits of the platform and well-established techniques instead of inventing new ones. For instance, instead of bindings inheritance, we rely on prototype inheritance. Instead of endeavoring to solve the incredibly complex, yet dubious problem of multiple bindings or shadow DOM trees, we simply suggest composition.
* The Component Model strives to add capabilities in layers (see [[#Building_Blocks | building blocks]]), each able to function on its own. The omnibus nature of XBL2 removes opportunities for layering, particularly as element identity, life cycle, and scripting are concerned. Perhaps this could be repaired somehow, but Component Model solves these issues without further complicating an already large, difficult to understand spec.


=Templates=
==See Also==
=Events=
=Attachment=
=Styles=


<style scoped> is a natural way to limit style sheets to only affect the shadow tree of a component. The component model follows the implementation suggested in [http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2011-June/032056.html this www-style thread]. That is, a selector is only matched up to, and including, the scoping element - i.e., the parent element of <style scoped> - but not further. The exceptions are:
Strawman pages:


* the selector contains the :root pseudo-class (note that this will fail if not used within the first selector sequence), or
* [http://wiki.whatwg.org/wiki/Component_Model_Strawman:_Decorators Decorators]
* the selector contains the :scope pseudo-class
* [http://wiki.whatwg.org/wiki/Component_Model_Strawman:_Element_Registration Element Registration]
* [http://wiki.whatwg.org/wiki/Component_Model_Strawman:_Styling Styling]
* [http://wiki.whatwg.org/wiki/Component_Model_Strawman:_Isolation Isolation]


'''CSS4''': care must be taken that the subject of a selector is the scoping element or a descendant thereof.
* [[Component_Model_Declarative_Syntax | Component Model Declarative Syntax]]
* [[Component_Model_Progressive_Enhancement | Component Model Progressive Enhancement]]
* [[Custom_Tags_Analysis | Custom Tags Analysis]]


[TODO: notes on crossing the boundary from/into the shadow tree]
Discussion and brainstorming pages:


=Scripting API=
* [http://wiki.whatwg.org/wiki/Component_Model_Discussion Main discussion page with open questions]
* [http://wiki.whatwg.org/wiki/Component_Model_Discussion:_Rendering Rendering-specific discussion]
* [http://wiki.whatwg.org/wiki/Component_Model_Brainstorming general brainstorming]
* [http://wiki.whatwg.org/wiki/Component_Model_CSS_Brainstorming brainstorming page about CSS and styling]
* [http://wiki.whatwg.org/wiki/Component_Model_Isolation_Brainstorming brainstorming page about isolation and confinement]
* [http://wiki.whatwg.org/wiki/Component_Model_Decorator_Brainstorming brainstorming page about decorators]
* [http://wiki.whatwg.org/wiki/Component_Model_IDL_Brainstorming brainstorming page about IDLs and communication across boundaries]
* [http://wiki.whatwg.org/wiki/Component_Model_Aspect-oriented_Components_Brainstorming brainstorming about aspect-oriented components]




[[Category:Proposals]]
[[Category:Proposals]]

Latest revision as of 19:18, 23 November 2011

Here's a good starting point for learning about the component model spec, which is being developed by applying a defined methodology.

Introduction

The Component Model introduces comprehensive support for creating DOM elements. Examples include layout managers, combinations of Dojo and jQuery widgets, isolated widgets, such as Like/+1 buttons, and built-in HTML elements themselves. Reflecting on the experience of Mozilla's XBL and Microsoft Internet Explorer's HTML components, the Component Model formalizes the concept of loosely coupled, coherent units of behavior in the Web platform. The functionality goals of the Component Model resemble the goals of XBL2; unlike XBL2, the Component Model seeks to be more incremental and modular while leveraging and integrating with new technologies.

Related links:

Properties

The component model aims to satisfy several key properties. These properties were extracted from the use cases. This section explains component model basics by studying each property.

Extensibility

The component model enables creation of new types of DOM elements by allowing the use of existing DOM elements in JavaScript prototype chain. For example, here's how you would create a new sub-type of HTMLElement:

function LayoutManagerPanel() {
    HTMLElement.call(this);
}

LayoutManagerPanel.prototype = Object.create(HTMLElement.prototype);

// ...

// 1) Will not be able to add instances of LayoutManagerPanel to document without this call.
// 2) First parameter specifies the tagName of the element being registered and must be a string prefixed with "x-".
Element.register("x-layout-manager-panel", LayoutManagerPanel);

// ...

var panel = new LayoutManagerPanel();
document.body.appendChild(panel);
// or
document.body.innerHTML = "<x-layout-manager-panel></x-layout-manager-panel>";

The resulting panel instance is a Javascript object that is a valid DOM element, which can be added to the DOM tree. You can then extend this object using standard Javascript prototype inheritance.

Required Building Blocks:

Consistency

Because components are just DOM objects, they inherently share the same traversal and manipulation APIs, as defined by the DOM4. The authors of components can extend these APIs by adding custom methods and properties on DOM objects, using standard JavaScript inheritance:

Widget.prototype = Object.create(HTMLElement.prototype, {
    update: {
        value: function() { /* ... */ }
    },
    value: {
        get: function() { /* ... */ },
        set: function() { /* ... */ }
    },
   // ...
});

The common API surface and the ability to extend it serves as a natural API boundary for framework authors, enabling interoperability.

Required Building Blocks:

Encapsulation

Encapsulation refers to ability of the component to hide its implementation details and state from the document. To enable hiding of the implementation details, the component model provides a way to build a DOM tree that is not accessible from the document DOM tree, but is rendered as part of the document. This DOM tree, associated with the component is the shadow DOM. The boundary between the document DOM tree and shadow DOM tree provides complete encapsulation, and ensures that:

  • no shadow DOM tree nodes cross this boundary during event dispatch;
  • document DOM tree has no access to nodes in the shadow DOM tree.

Additionally, the boundary serves as a convenient style application lever, giving the component a choice of letting (or not letting) document CSS affect the shadow DOM tree.

Every DOM element instance may only have (or host) one shadow DOM tree. A shadow tree is instantiated by creating an instance of the ShadowRoot object, which takes a reference to the hosting element as a parameter. Attempting to create more than one instance for the same element throws an exception:

function LayoutManagerPanel() {
    HTMLElement.call(this);
    var shadow = new ShadowRoot(this);
    var shadow2 = new ShadowRoot(this); // throws an exception.
   // ...
}

Required Building Blocks:

Composability

Being DOM objects, components fit naturally into the document DOM tree and support all of its composition properties. In addition, the content element allows controlling interaction between shadow and document DOM trees. A content element specifies places where immediate document tree children of the component are rendered inside the shadow tree.

There can be more than one content element in the shadow tree. The includes attribute provides a convenient way to sort element's children by CSS selector. For example, a DockLayoutPanel component could be used like this in the document DOM tree:

<x-dock-layout-panel>
    <h1 class="north">On Gardens</h1>
    <ul class="west">
        <li>Automatic Gardens</li>
        <li>Gardening on minefields</li>
    </ul>
    <p>I love gardening.</p>
    <div class="south">Written by Chauncey Gardiner.</div>
</x-dock-layout-panel>

Provided that its shadow DOM tree looks like this:

<#shadow-root>
    <div class="north">
        <content includes=".north">
    </div>
    <div>
        <div class="west">
            <content includes=".west">
        </div>
        <div class="east">
            <content>
        </div>
    </div>
    <div class="south">
        <content includes=".south">
    </div>
<#shadow-root>

The document DOM tree children on of x-dock-layout-panel will be rendered as if composed from this tree:

<x-dock-layout-panel>
    <div class="north">
        <h1 class="north">On Gardens</h1>
    </div>
    <div>
        <div class="west">
            <ul class="west">
                <li>Automatic Gardens</li>
                <li>Gardening on minefields</li>
            </ul>
        </div>
        <div class="east">
            <p>I love gardening.</p>
        </div>
    </div>
    <div class="south">
        <div class="south">Written by Avid Gardener.</div>
    </div>
</x-dock-layout-panel>

Required Building Blocks:

Desugaring

The component model also explains pretty well how the native HTML elements are built and dispels some of the magic associated with the "DOM object vs. JavaScript object" juxtaposition.

Allowing DOM elements to participate in the JavaScript inheritance chain makes DOM elements more approachable and easier to work with.

Complex DOM elements that are rendered with more than one CSS box (and aren't specified in terms of CSS, like lists) are just components that have shadow DOM. Coincidentally, this also explains why you can't add shadow DOM subtrees to input or details elements -- their ShadowRoots are claimed by HTMLInputElement and HTMLDetailsElement constructors, respectively.

Required Building Blocks:

Performance

Considering the way Web works, the component model must allow decoupling of the instantiation and the declaration of the components in order to provide reasonable performance characteristics. It's an unfortunate, but necessary requirement. In other words, we must be able to handle situations where a component instance is created before it is declared. Here's an simple example:

// somewhere in view.js
...
document.body.innerHTML = '<div class="awesome"><x-layout><x-spring-panel>...</x-spring-panel></x-layout>';

...
// somewhere in layout.js
Element.register('x-layout', Layout);
Element.register('x-spring-panel', SpringPanel);

In this situation, there is no room for error: view.js must wait for layout.js to load before executing. You can't load layout.js lazily or in any different order, since it defines the components that are used in view.js. Given that asynchronous, deferred or lazy-loading of script are all common performance techniques in today's Web, we must do better than block or throw an exception in such cases.

The component model offers this solution:

When an unknown DOM element with an "x-"-prefixed tagName is encountered, we put a placeholder HTMLUnknownElement instance in its place. As soon as the element is defined, all placeholder instances are replaced (Document.renameNode) with the new, proper DOM element.

Required Building Blocks:

Confinement

Confinement refers to the document protecting its implementation details and state from the component and can be viewed as the inverse of encapsulation.

Required Building Blocks:

Building Blocks

The component model is comprised of the following building blocks.

Shadow DOM

Any DOM element can host a shadow DOM subtree. The shadow DOM subtree originates at ShadowRoot, which is coupled the hosting element at the time of its construction. You don't need any other building blocks in order to take advantage of the shadow DOM:

var element = document.createElement("div");
var shadow = new ShadowRoot(element);
shadow.appendChild(document.createElement("p")).textContent = "weee!!';

A ShadowRoot instance is a Node, and acts as the root of the element's shadow DOM subtree. The ShadowRoot itself is never rendered, nor has styles. In this regard, it's similar to the DocumentFragment. It has two properties:

  • applyAuthorSheets, which is either true (that is, apply author style sheets from the document), or false (don't);
  • shadowHost, which points to the hosting element.

Content Element

The content element is used with Shadow DOM and provides a mechanism for distributing hosting element's children inside of its shadow subtree. To preserve the encapsulation property, the content elements act as insertion points and do not leak any information about hosting element's children to the shadow DOM subtree or vise versa.

Constructable DOM Types

The inability to construct DOM element using new (with some exceptions) or use them in the prototype inheritance chain had confounded many Web developers since the beginning of DOM. This building block intends to rectify at least the latter by allowing HTMLElement.call invocation and thus enabling creation of JavaScript objects with DOM elements in the prototype chain.

Registering Elements

Working in conjunction with Constructable DOM Types, this building block makes the list of valid markup tag names extensible by exposing Element.register:

partial interface Element {
    static void register(in String tagName, in Function constructor);
}

It is possible to envisage a milder (though less elegant) version of element registration by keeping DOM element construction magical (thus decoupling it from Constructable DOM Types) and making Element.register use a callback, rather than constructor as parameter. The callback would be invoked with an already-constructed DOM object with the specified tagName, leaving the work of setting up properties on this object to the callback.

Confinement Primitives

The API surface of the component model lends itself well to proper confinement. Here's an approach that could be used to provide it (very early brainstorming):

  • Confinement is not tied to the component model. Instead, it's a new twist on the method of loading scripts. A script could be loaded as usual or it could be confined, or loaded into its own context.
  • When confined, a script has its own global and document objects. These objects only reveal some safe limited subset of the actual document objects. Think of it as a same-origin iframe with restrictions on document and window.
  • You can communicate with the main document using window.postMessage.
  • The confined document DOM tree is always empty. Attempting to insert into it throws exceptions.
  • ... except when you append to elements in shadow DOM. That's right, you can do Element.register and new ShadowRoot in the confined document.
  • Whenever you register an element, it registers in the main document as well. Creating an instance of a component from an confined document produces a functional DOM element shell that proxies to the actual element in the confined document.

Proposed API: introduce a new confined attribute to the script element. Presence of this attribute triggers loading scripts in the confined context.

Confinement of script execution could be useful outside of the component model and also could be related to Content Security Policy.

Building Blocks Use Case Coverage

Here's a list of building blocks, tabulated against the use cases and approximate percentage of satisfying them:

Building Block Layout Manager Mix-and-Match SVG Controls Contacts Widget Like/+1 Button Media Controls for the Video Element Details/Summary Element
Shadow DOM 25% - 34% 100% 25% 100% 50%
Content Element 25% - - - - - 50%
Constructable DOM Types 25% 50% 33% - 25% - -
Registering Elements 25% 50% 33% - 25% - -
Confinement Primitives - - - - 25% - -

Comparison With Existing Specs and Implementations

Here's a brief overview of existing similar specifications and implementations:

Here's a handy overview of how each of these specs satisfies the component model properties:

Spec/Implementation Extensibility Consistency Encapsulation Composability Desugaring Performance Confinement
HTML Components No. Components are magic, inextensible objects. Almost. Implementation provides ways to add properties, methods, events to element API, and the components are almost DOM elements. However, custom tags don't support all properties of a DOM element. Not much. There are some provisions for event encapsulation, nothing else. Not much. No provisions for handling document children vs. component-defined children. No. Not sure. No.
XBL No. The mechanism for extending bindings is entirely independent of DOM type or Javascript extensibility. Yes-ish. Bindings can override properties on the DOM element, although the mechanism is highly unnatural (XML declarations). Yes? Hard to say looking at TR note. Yes Yes. Some HTML elements in Gecko are implemented using it. Not sure. No.
XBL2 No. Same as XBL. No. Bindings are discouraged from establishing an API surface on a bound element. Yes. Yes. No. The spec didn't intend to describe how native elements are built. Somewhat. The lifecycle of a binding is well-defined and initialization stages are well-decoupled. However, there is no way to build a binding imperatively without loading a binding document. No.

The key differences between XBL2 and the Component Model are:

  • The Component Model fully embraces the element behavior attachment by allowing creation of new types of DOM elements within a document. This is something Web Framework developers always wanted and repeatedly try to do with parallel object hierarchies. Eliminating ephemerality of the attachment simplifies and clarifies how things work conceptually -- there is no longer a place for "spooky action at a distance", caused by a change of a random CSS selector or even removing an element from the tree.
  • The Component Model is strongly biased toward reusing existing bits of the platform and well-established techniques instead of inventing new ones. For instance, instead of bindings inheritance, we rely on prototype inheritance. Instead of endeavoring to solve the incredibly complex, yet dubious problem of multiple bindings or shadow DOM trees, we simply suggest composition.
  • The Component Model strives to add capabilities in layers (see building blocks), each able to function on its own. The omnibus nature of XBL2 removes opportunities for layering, particularly as element identity, life cycle, and scripting are concerned. Perhaps this could be repaired somehow, but Component Model solves these issues without further complicating an already large, difficult to understand spec.

See Also

Strawman pages:

Discussion and brainstorming pages: