components
This commit is contained in:
parent
304d578b54
commit
6fb4aabcba
344 changed files with 669 additions and 406 deletions
|
@ -1,6 +1,8 @@
|
|||
# Shadow DOM slots, composition
|
||||
|
||||
Our components should be generic. For instance, when we create a `<custom-tabs>` or `<custom-menu>`, we need to let others will it with data.
|
||||
Many types of components, such as tabs, menus, image galleries, and so on, need the content to render.
|
||||
|
||||
Just like built-in browser `<select>` expects `<option>` items, our `<custom-tabs>` may expect the actual tab content to be passed. And a `<custom-menu>` may expect menu items.
|
||||
|
||||
The code that makes use of `<custom-menu>` can look like this:
|
||||
|
||||
|
@ -13,19 +15,19 @@ The code that makes use of `<custom-menu>` can look like this:
|
|||
</custom-menu>
|
||||
```
|
||||
|
||||
...Then our component should render it properly, as a nice menu with event handlers etc.
|
||||
...Then our component should render it properly, as a nice menu with given title and items, handle menu events, etc.
|
||||
|
||||
How to implement it?
|
||||
|
||||
One way is to analyze the element content and dynamically copy-rearrange DOM nodes. That's posssible, but requires some coding. Also, if we're moving things to shadow DOM, then CSS styles from the document do not apply any more, so the visual styling may be lost.
|
||||
We could try to analyze the element content and dynamically copy-rearrange DOM nodes. That's possible, but if we're moving elements to shadow DOM, then CSS styles from the document do not apply in there, so the visual styling may be lost. Also that requires some coding.
|
||||
|
||||
Another way is to use `<slot>` elements in shadow DOM. They allow to specify content in light DOM that the browser renders in component slots.
|
||||
|
||||
It's easy to grasp by example.
|
||||
Luckily, we don't have to. Shadow DOM supports `<slot>` elements, that are automatically filled by the content from light DOM.
|
||||
|
||||
## Named slots
|
||||
|
||||
Here, `<user-card>` shadow DOM provides two slots, and the component user should fill them:
|
||||
Let's see how slots work on a simple example.
|
||||
|
||||
Here, `<user-card>` shadow DOM provides two slots, filled from light DOM:
|
||||
|
||||
```html run autorun="no-epub" untrusted height=80
|
||||
<script>
|
||||
|
@ -54,11 +56,11 @@ customElements.define('user-card', class extends HTMLElement {
|
|||
</user-card>
|
||||
```
|
||||
|
||||
In shadow DOM `<slot name="X">` defines an "insertion point", a place where the elements with `slot="X"` are rendered.
|
||||
In the shadow DOM, `<slot name="X">` defines an "insertion point", a place where elements with `slot="X"` are rendered.
|
||||
|
||||
The process of re-rendering light DOM inside shadow DOM is rather untypical, so let's go into details.
|
||||
Then the browser performs "composition": it takes elements from the light DOM and renders them in corresponding slots of the shadow DOM. At the end, we have exactly what we want -- a generic component that can be filled with data.
|
||||
|
||||
First, after the script has finished we created the shadow DOM, leading to this DOM structure:
|
||||
Here's the DOM structure after the script, not taking composition into account:
|
||||
|
||||
```html
|
||||
<user-card>
|
||||
|
@ -74,21 +76,20 @@ First, after the script has finished we created the shadow DOM, leading to this
|
|||
</user-card>
|
||||
```
|
||||
|
||||
Now the element has both light and shadow DOM. In such case only shadow DOM is rendered.
|
||||
There's nothing odd here. We created the shadow DOM, so here it is. Now the element has both light and shadow DOM.
|
||||
|
||||
After that, for each `<slot name="...">` in shadow DOM, the browser looks for `slot="..."` with the same name in the light DOM.
|
||||
|
||||
These elements are rendered -- as a whole, inside the slots:
|
||||
For rendering purposes, for each `<slot name="...">` in shadow DOM, the browser looks for `slot="..."` with the same name in the light DOM. These elements are rendered inside the slots:
|
||||
|
||||

|
||||
|
||||
At the end, the so-called "flattened" DOM looks like this:
|
||||
The result is called "flattened" DOM:
|
||||
|
||||
```html
|
||||
<user-card>
|
||||
#shadow-root
|
||||
<div>Name:
|
||||
<slot name="username">
|
||||
<!-- slotted element is inserted into the slot as a whole -->
|
||||
<span slot="username">John Smith</span>
|
||||
</slot>
|
||||
</div>
|
||||
|
@ -100,50 +101,51 @@ At the end, the so-called "flattened" DOM looks like this:
|
|||
</user-card>
|
||||
```
|
||||
|
||||
So, slotted content fills its containers.
|
||||
...But the "flattened" DOM is only created for rendering and event-handling purposes. That's how things are shown. The nodes are actually not moved around!
|
||||
|
||||
...But the nodes are actually not moved around! That can be easily checked if we run `querySelector`: nodes are still at their places.
|
||||
That can be easily checked if we run `querySelector`: nodes are still at their places.
|
||||
|
||||
```js
|
||||
// light DOM nodes <span> are physically at place
|
||||
// light DOM <span> nodes are still at the same place, under `<user-card>`
|
||||
alert( document.querySelector('user-card span').length ); // 2
|
||||
```
|
||||
|
||||
It looks bizarre indeed, from the first sight, but so it is. The browser renders nodes from light DOM inside the shadow DOM.
|
||||
|
||||
````smart header="Slot default content"
|
||||
If we put something inside a `<slot>`, it becomes the default content. The browser shows it if there's no corresponding filler in light DOM.
|
||||
|
||||
For example, in this piece of shadow DOM, `Anonymous` renders if there's no `slot="username"` in corresponding light DOM.
|
||||
|
||||
```html
|
||||
<div>Name:
|
||||
<slot name="username">Anonymous</slot>
|
||||
</div>
|
||||
```
|
||||
````
|
||||
It may look bizarre, but for shadow DOM with slots we have one more "DOM level", the "flattened" DOM -- result of slot insertion. The browser renders it and uses for style inheritance, event propagation. But JavaScript still sees the document "as is", before flattening.
|
||||
|
||||
````warn header="Only top-level children may have slot=\"...\" attribute"
|
||||
The `slot="..."` attribute is only valid for direct children of the shadow host (in our example, `<user-card>` element). For nested elements it's ignored.
|
||||
|
||||
For example, the second `<span>` here is ignored (as it's not a top-level child of `<user-card>`):
|
||||
```
|
||||
```html
|
||||
<user-card>
|
||||
<span slot="username">John Smith</span>
|
||||
<div><span slot="birthday">01.01.2001</span></div>
|
||||
<div>
|
||||
<!-- bad slot, not top-level: -->
|
||||
<span slot="birthday">01.01.2001</span>
|
||||
</div>
|
||||
</user-card>
|
||||
```
|
||||
|
||||
In practice, there's no sense in slotting a deeply nested element, so this limitation just ensures the correct DOM structure.
|
||||
````
|
||||
|
||||
## Slot fallback content
|
||||
|
||||
If we put something inside a `<slot>`, it becomes the fallback content. The browser shows it if there's no corresponding filler in light DOM.
|
||||
|
||||
For example, in this piece of shadow DOM, `Anonymous` renders if there's no `slot="username"` in light DOM.
|
||||
|
||||
```html
|
||||
<div>Name:
|
||||
<slot name="username">Anonymous</slot>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Default slot
|
||||
|
||||
The first `<slot>` in shadow DOM that doesn't have a name is a "default" slot.
|
||||
The first `<slot>` in shadow DOM that doesn't have a name is a "default" slot. It gets all nodes from the light DOM that aren't slotted elsewhere.
|
||||
|
||||
It gets any data from the light DOM that isn't slotted elsewhere.
|
||||
|
||||
For example, let's add a "bio" field to our `<user-card>` that collects any unslotted information about the user:
|
||||
For example, let's add the default slot to our `<user-card>` that collects any unslotted information about the user:
|
||||
|
||||
```html run autorun="no-epub" untrusted height=140
|
||||
<script>
|
||||
|
@ -158,7 +160,7 @@ customElements.define('user-card', class extends HTMLElement {
|
|||
<slot name="birthday"></slot>
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend>About me</legend>
|
||||
<legend>Other information</legend>
|
||||
*!*
|
||||
<slot></slot>
|
||||
*/!*
|
||||
|
@ -170,19 +172,21 @@ customElements.define('user-card', class extends HTMLElement {
|
|||
|
||||
<user-card>
|
||||
*!*
|
||||
<div>Hello</div>
|
||||
<div>I like to swim.</div>
|
||||
*/!*
|
||||
<span slot="username">John Smith</span>
|
||||
<span slot="birthday">01.01.2001</span>
|
||||
*!*
|
||||
<div>I am John!</div>
|
||||
<div>...And play volleyball too!</div>
|
||||
*/!*
|
||||
</user-card>
|
||||
```
|
||||
|
||||
All the unslotted light DOM content gets into the `<fieldset>`.
|
||||
All the unslotted light DOM content gets into the "Other information" fieldset.
|
||||
|
||||
Elements are appended to the slot one after another, so the flattened DOM looks like this:
|
||||
Elements are appended to a slot one after another, so both unslotted pieces of information are in the default slot together.
|
||||
|
||||
The flattened DOM looks like this:
|
||||
|
||||
```html
|
||||
<user-card>
|
||||
|
@ -197,15 +201,15 @@ Elements are appended to the slot one after another, so the flattened DOM looks
|
|||
<span slot="birthday">01.01.2001</span>
|
||||
</slot>
|
||||
</div>
|
||||
*!*
|
||||
<fieldset>
|
||||
<legend>About me</legend>
|
||||
*!*
|
||||
<slot>
|
||||
<div>Hello</div>
|
||||
<div>I am John!</div>
|
||||
</slot>
|
||||
</fieldset>
|
||||
*/!*
|
||||
</fieldset>
|
||||
</user-card>
|
||||
```
|
||||
|
||||
|
@ -213,7 +217,9 @@ Elements are appended to the slot one after another, so the flattened DOM looks
|
|||
|
||||
Now let's back to `<custom-menu>`, mentioned at the beginning of the chapter.
|
||||
|
||||
We can use slots to distribute elements: title and items:
|
||||
We can use slots to distribute elements.
|
||||
|
||||
Here's the markup for `<custom-menu>`:
|
||||
|
||||
```html
|
||||
<custom-menu>
|
||||
|
@ -224,7 +230,7 @@ We can use slots to distribute elements: title and items:
|
|||
</custom-menu>
|
||||
```
|
||||
|
||||
The shadow DOM template:
|
||||
The shadow DOM template with proper slots:
|
||||
|
||||
```html
|
||||
<template id="tmpl">
|
||||
|
@ -236,28 +242,33 @@ The shadow DOM template:
|
|||
</template>
|
||||
```
|
||||
|
||||
As you can see, for `<slot name="item">` there are multiple `<li>` elements in light DOM, with the same `slot="item"`. In that case they all get appended to the slot, one after another.
|
||||
1. `<span slot="title">` goes into `<slot name="title">`.
|
||||
2. There are many `<li slot="item">` in the template, but only one `<slot name="item">` in the template. That's perfectly normal. All elements with `slot="item"` get appended to `<slot name="item">` one after another, thus forming the list.
|
||||
|
||||
So the flattened DOM becomes:
|
||||
The flattened DOM becomes:
|
||||
|
||||
```html
|
||||
<div class="menu">
|
||||
<slot name="title">
|
||||
<span slot="title">Candy menu</span>
|
||||
</slot>
|
||||
<ul>
|
||||
<slot name="item">
|
||||
<li slot="item">Lollipop</li>
|
||||
<li slot="item">Fruit Toast</li>
|
||||
<li slot="item">Cup Cake</li>
|
||||
</slot>
|
||||
</ul>
|
||||
</div>
|
||||
<custom-menu>
|
||||
#shadow-root
|
||||
<style> /* menu styles */ </style>
|
||||
<div class="menu">
|
||||
<slot name="title">
|
||||
<span slot="title">Candy menu</span>
|
||||
</slot>
|
||||
<ul>
|
||||
<slot name="item">
|
||||
<li slot="item">Lollipop</li>
|
||||
<li slot="item">Fruit Toast</li>
|
||||
<li slot="item">Cup Cake</li>
|
||||
</slot>
|
||||
</ul>
|
||||
</div>
|
||||
</custom-menu>
|
||||
```
|
||||
|
||||
One might notice that, in a valid DOM, `<li>` must be a direct child of `<ul>`, so we have an oddity here. But that's flattened DOM, it describes how the component is rendered. Physically nodes are still at their places.
|
||||
One might notice that, in a valid DOM, `<li>` must be a direct child of `<ul>`. But that's flattened DOM, it describes how the component is rendered, such thing happens naturally here.
|
||||
|
||||
We just need to add an `onclick` handler, and the custom element is ready:
|
||||
We just need to add a `click` handler to open/close the list, and the `<custom-menu>` is ready:
|
||||
|
||||
```js
|
||||
customElements.define('custom-menu', class extends HTMLElement {
|
||||
|
@ -280,18 +291,142 @@ Here's the full demo:
|
|||
|
||||
[iframe src="menu" height=140 edit]
|
||||
|
||||
Now, as we have elements from light DOM in the shadow DOM, styles from the document and shadow DOM can mix. There are few simple rules for that. We'll see the details in the next chapter.
|
||||
Of course, we can add more functionality to it: events, methods and so on.
|
||||
|
||||
## Monitoring slots
|
||||
|
||||
What if the outer code wants to add/remove menu items dynamically?
|
||||
|
||||
**The browser monitors slots and updates the rendering if slotted elements are added/removed.**
|
||||
|
||||
Also, as light DOM nodes are not copied, but just rendered in slots, the changes inside them immediately become visible.
|
||||
|
||||
So we don't have to do anything to update rendering. But if the component wants to know about slot changes, then `slotchange` event is available.
|
||||
|
||||
For example, here the menu item is inserted dynamically after 1 second, and the title changes after 2 seconds:
|
||||
|
||||
```html run untrusted height=80
|
||||
<custom-menu id="menu">
|
||||
<span slot="title">Candy menu</span>
|
||||
</custom-menu>
|
||||
|
||||
<script>
|
||||
customElements.define('custom-menu', class extends HTMLElement {
|
||||
connectedCallback() {
|
||||
this.attachShadow({mode: 'open'});
|
||||
this.shadowRoot.innerHTML = `<div class="menu">
|
||||
<slot name="title"></slot>
|
||||
<ul><slot name="item"></slot></ul>
|
||||
</div>`;
|
||||
|
||||
// shadowRoot can't have event handlers, so using the first child
|
||||
this.shadowRoot.firstElementChild.addEventListener('slotchange',
|
||||
e => alert("slotchange: " + e.target.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
menu.insertAdjacentHTML('beforeEnd', '<li slot="item">Lollipop</li>')
|
||||
}, 1000);
|
||||
|
||||
setTimeout(() => {
|
||||
menu.querySelector('[slot="title"]').innerHTML = "New menu";
|
||||
}, 2000);
|
||||
</script>
|
||||
```
|
||||
|
||||
The menu rendering updates each time without our intervention.
|
||||
|
||||
There are two `slotchange` events here:
|
||||
|
||||
1. At initialization:
|
||||
|
||||
`slotchange: title` triggers immediately, as the `slot="title"` from the light DOM gets into the corresponding slot.
|
||||
2. After 1 second:
|
||||
|
||||
`slotchange: item` triggers, when a new `<li slot="item">` is added.
|
||||
|
||||
Please note: there's no `slotchange` event after 2 seconds, when the content of `slot="title"` is modified. That's because there's no slot change. We modify the content inside the slotted element, that's another thing.
|
||||
|
||||
If we'd like to track internal modifications of light DOM from JavaScript, that's also possible using a more generic mechanism: [MutationObserver](info:mutation-observer).
|
||||
|
||||
## Slot API
|
||||
|
||||
Finally, let's mention the slot-related JavaScript methods.
|
||||
|
||||
As we've seen before, JavaScript looks at the "real" DOM, without flattening. But, if the shadow tree has `{mode: 'open'}`, then we can figure out which elements assigned to a slot and, vise-versa, the slot by the element inside it:
|
||||
|
||||
- `node.assignedSlot` -- returns the `<slot>` element that the `node` is assigned to.
|
||||
- `slot.assignedNodes({flatten: true/false})` -- DOM nodes, assigned to the slot. The `flatten` option is `false` by default. If explicitly set to `true`, then it looks more deeply into the flattened DOM, returning nested slots in case of nested components and the fallback content if no node assigned.
|
||||
- `slot.assignedElements({flatten: true/false})` -- DOM elements, assigned to the slot (same as above, but only element nodes).
|
||||
|
||||
These methods are useful when we need not just show the slotted content, but also track it in JavaScript.
|
||||
|
||||
For example, if `<custom-menu>` component wants to know, what it shows, then it could track `slotchange` and get the items from `slot.assignedElements`:
|
||||
|
||||
```html run untrusted height=120
|
||||
<custom-menu id="menu">
|
||||
<span slot="title">Candy menu</span>
|
||||
<li slot="item">Lollipop</li>
|
||||
<li slot="item">Fruit Toast</li>
|
||||
</custom-menu>
|
||||
|
||||
<script>
|
||||
customElements.define('custom-menu', class extends HTMLElement {
|
||||
items = []
|
||||
|
||||
connectedCallback() {
|
||||
this.attachShadow({mode: 'open'});
|
||||
this.shadowRoot.innerHTML = `<div class="menu">
|
||||
<slot name="title"></slot>
|
||||
<ul><slot name="item"></slot></ul>
|
||||
</div>`;
|
||||
|
||||
// slottable is added/removed/replaced
|
||||
*!*
|
||||
this.shadowRoot.firstElementChild.addEventListener('slotchange', e => {
|
||||
let slot = e.target;
|
||||
if (slot.name == 'item') {
|
||||
this.items = slot.assignedElements().map(elem => elem.textContent);
|
||||
alert("Items: " + this.items);
|
||||
}
|
||||
});
|
||||
*/!*
|
||||
}
|
||||
});
|
||||
|
||||
// items update after 1 second
|
||||
setTimeout(() => {
|
||||
menu.insertAdjacentHTML('beforeEnd', '<li slot="item">Cup Cake</li>')
|
||||
}, 1000);
|
||||
</script>
|
||||
```
|
||||
|
||||
|
||||
## Итого
|
||||
## Summary
|
||||
|
||||
Shadow DOM -- это средство для создания отдельного DOM-дерева внутри элемента, которое не видно снаружи без применения специальных методов.
|
||||
Slots allow to show light DOM children in shadow DOM.
|
||||
|
||||
- Ряд браузерных элементов со сложной структурой уже имеют Shadow DOM.
|
||||
- Можно создать Shadow DOM внутри любого элемента вызовом `elem.createShadowRoot()`. В дальнейшем его корень будет доступен как `elem.shadowRoot`. У встроенных элементов он недоступен.
|
||||
- Как только у элемента появляется Shadow DOM, его изначальное содержимое скрывается. Теперь показывается только Shadow DOM, который может указать, какое содержимое хозяина куда вставлять, при помощи элемента `<content>`. Можно указать селектор `<content select="селектор">` и размещать разное содержимое в разных местах Shadow DOM.
|
||||
- Элемент `<content>` перемещает содержимое исходного элемента в Shadow DOM только визуально, в структуре DOM оно остаётся на тех же местах.
|
||||
There are two kinds of slots:
|
||||
|
||||
Подробнее спецификация описана по адресу <http://w3c.github.io/webcomponents/spec/shadow/>.
|
||||
- Named slots: `<slot name="X">...</slot>` -- gets light children with `slot="X"`.
|
||||
- Default slot: the first `<slot>` without a name (subsequent unnamed slots are ignored) -- gets unslotted light children.
|
||||
- If there are many elements for the same slot -- they are appended one after another.
|
||||
- The content of `<slot>` element is used as a fallback. It's shown if there are no light children for the slot.
|
||||
|
||||
Далее мы рассмотрим работу с шаблонами, которые также являются частью платформы Web Components и не заменяют существующие шаблонные системы, но дополняют их важными встроенными в браузер возможностями.
|
||||
The process of rendering slotted elements inside their slots is called "composition". The result is called a "flattened DOM".
|
||||
|
||||
Composition does not really move nodes, from JavaScript point of view the DOM is still same.
|
||||
|
||||
JavaScript can access slots using methods:
|
||||
- `slot.assignedNodes/Elements()` -- returns nodes/elements inside the `slot`
|
||||
- `node.assignedSlot` -- the reverse meethod, returns slot by a node.
|
||||
|
||||
If we'd like to know what we're showing, we can track slot contents using:
|
||||
- `slotchange` event -- triggers the first time a slot is filled, and on any add/remove/replace operation of the slotted element, but not its children. The slot is `event.target`.
|
||||
- [MutationObserver](info:mutation-observer) to go deeper into slot content, watch changes inside it.
|
||||
|
||||
Now, as we have elements from light DOM in the shadow DOM, let's see how to style them properly. The basic rule is that shadow elements are styled inside, and light elements -- outside, but there are notable exceptions.
|
||||
|
||||
We'll see the details in the next chapter.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue