components

This commit is contained in:
Ilya Kantor 2019-04-02 14:01:44 +03:00
parent 304d578b54
commit 6fb4aabcba
344 changed files with 669 additions and 406 deletions

View file

@ -70,5 +70,6 @@ There exist many frameworks and development methodologies to build them, each on
- [Custom elements](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements) -- to define custom HTML elements.
- [Shadow DOM](https://dom.spec.whatwg.org/#shadow-trees) -- to create an internal DOM for the component, hidden from the others.
- [CSS Scoping](https://drafts.csswg.org/css-scoping/) -- to declare styles that only apply inside the Shadow DOM of the component.
- [Event retargeting](https://dom.spec.whatwg.org/#retarget) and other minor stuff to make custom components better fit the development.
In the next chapter we'll go into details of "Custom Elements" -- the fundamental and well-supported feature of web components, good on its own.

View file

@ -361,11 +361,39 @@ customElements.define('hello-button', HelloButton, {extends: 'button'});
Our new button extends the built-in one. So it keeps the same styles and standard features like `disabled` attribute.
## Итого
## References
Мы рассмотрели, как создавать свои DOM-элементы при помощи стандарта [Custom Elements](http://www.w3.org/TR/custom-elements/).
- HTML Living Standard: <https://html.spec.whatwg.org/#custom-elements>.
- Compatiblity: <https://caniuse.com/#feat=custom-elements>.
POLYFILL
Edge is a bit lagging behind, but there's a polyfill <https://github.com/webcomponents/webcomponentsjs> that covers
## Summary
Далее мы перейдём к изучению дополнительных возможностей по работе с DOM.
Custom elements can be of two types:
1. "Autonomous" -- new tags, extending `HTMLElement`.
Definition scheme:
```js
class MyElement extends HTMLElement {
constructor() { super(); /* ... */ }
connectedCallback() { /* ... */ }
disconnectedCallback() { /* ... */ }
static get observedAttributes() { return [/* ... */]; }
attributeChangedCallback(name, oldValue, newValue) { /* ... */ }
adoptedCallback() { /* ... */ }
}
customElements.define('my-element', MyElement);
/* <my-element> */
```
2. "Customized built-in elements" -- extensions of existing elements.
Requires one more `.define` argument, and `is="..."` in HTML:
```js
class MyButton extends HTMLButtonElement { /*...*/ }
customElements.define('my-button', MyElement, {extends: 'button'});
/* <button is="my-button"> */
```
Custom elements are well-supported among browsers. Edge is a bit behind, but there's a polyfill <https://github.com/webcomponents/webcomponentsjs>.

View file

@ -1,20 +1,26 @@
# Shadow DOM
Did you ever think how complex browser controls like `<input type="range">` are created and styled?
Shadow DOM serves for encapsulation. It allows a component to have its very own "shadow" DOM tree, that can't be accidentally accessed from the main document, may have local style rules, and more.
The browser uses DOM/CSS internally to draw this kind of thing:
## Built-in shadow DOM
Did you ever think how complex browser controls are created and styled?
Such as `<input type="range">`:
<p>
<input type="range">
</p>
The associated DOM structure is normally hidden from us, but we can see it in developer tools. E.g. in Chrome, we need to enable in Dev Tools "Show user agent shadow DOM" option.
The browser uses DOM/CSS internally to draw them. That DOM structure is normally hidden from us, but we can see it in developer tools. E.g. in Chrome, we need to enable in Dev Tools "Show user agent shadow DOM" option.
Then `<input type="range">` looks like this:
![](shadow-dom-range.png)
What you see under `#shadow-root` is called "Shadow DOM".
What you see under `#shadow-root` is called "shadow DOM".
We can't get built-in Shadow DOM elements by regular JavaScript calls or selectors. These are not regular children, but a powerful encapsulation technique.
We can't get built-in shadow DOM elements by regular JavaScript calls or selectors. These are not regular children, but a powerful encapsulation technique.
In the example above, we can see a useful attribute `pseudo`. It's non-standard, exists for historical reasons. We can use it style subelements with CSS, like this:
@ -29,29 +35,31 @@ input::-webkit-slider-runnable-track {
<input type="range">
```
Once again, `pseudo` is a non-standard attribute. Chronologically, browsers first started to experiment with internal DOM structures to implement controls, and then, after time, Shadow DOM was standartized to allow us, developers, to do the similar thing.
Once again, `pseudo` is a non-standard attribute. Chronologically, browsers first started to experiment with internal DOM structures to implement controls, and then, after time, shadow DOM was standartized to allow us, developers, to do the similar thing.
Furhter on, we'll use the modern Shadow DOM standard.
Furhter on, we'll use the modern shadow DOM standard, covered by [DOM spec](https://dom.spec.whatwg.org/#shadow-trees) other related specifications.
## Shadow tree
A DOM element can have two types of DOM subtrees:
1. Light tree -- a regular DOM subtree, made of HTML children. All subtrees that we've seen before are light.
1. Light tree -- a regular DOM subtree, made of HTML children. All subtrees that we've seen in previous chapters were "light".
2. Shadow tree -- a hidden DOM subtree, not reflected in HTML, hidden from prying eyes.
If an element has both at the same time, then the browser renders only the shadow tree. But we can setup a kind of composition between two trees as well. We'll see the details later in the chapter <info:slots-composition>.
If an element has both, then the browser renders only the shadow tree. But we can setup a kind of composition between shadow and light trees as well. We'll see the details later in the chapter <info:slots-composition>.
Shadow tree can be used in Custom Elements to hide internal implementation details.
Shadow tree can be used in Custom Elements to hide component internals and apply component-local styles.
For example, this `<show-hello>` element hides its internal DOM in shadow tree:
```html run autorun height=40
```html run autorun height=60
<script>
customElements.define('show-hello', class extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `<p>Hello, ${this.getAttribute('name')}!</p>`;
shadow.innerHTML = `<p>
Hello, ${this.getAttribute('name')}
</p>`;
}
});
</script>
@ -59,20 +67,35 @@ customElements.define('show-hello', class extends HTMLElement {
<show-hello name="John"></show-hello>
```
The call to `elem.attachShadow({mode: …})` creates a shadow tree root for the element. There are two limitations:
1. We can create only one shadow root per element.
2. The `elem` must be either a custom element, or one of: "article", "aside", "blockquote", "body", "div", "footer", "h1..h6", "header", "main" "nav", "p", "section", "span".
The `mode` option sets the encapsulation level. It must have any of two values:
- **`"open"`** -- then the shadow root is available as DOM property `elem.shadowRoot`, so any code is able to access it.
- **`"closed"`** -- `elem.shadowRoot` is always `null`. Browser-native shadow trees, such as `<input type="range">`, are closed.
The [shadow root object](https://dom.spec.whatwg.org/#shadowroot) is like an element: we can use `innerHTML` or DOM methods to populate it.
That's how the resulting DOM looks in Chrome dev tools:
That's how the resulting DOM looks in Chrome dev tools, all the content is under "#shadow-root":
![](shadow-dom-say-hello.png)
First, the call to `elem.attachShadow({mode: …})` creates a shadow tree.
There are two limitations:
1. We can create only one shadow root per element.
2. The `elem` must be either a custom element, or one of: "article", "aside", "blockquote", "body", "div", "footer", "h1..h6", "header", "main" "nav", "p", "section", or "span". Other elements, like `<img>`, can't host shadow tree.
The `mode` option sets the encapsulation level. It must have any of two values:
- `"open"` -- the shadow root is available as `elem.shadowRoot`.
Any code is able to access the shadow tree of `elem`.
- `"closed"` -- `elem.shadowRoot` is always `null`.
We can only access the shadow DOM by the reference returned by `attachShadow` (and probably hidden inside a class). Browser-native shadow trees, such as `<input type="range">`, are closed. There's no way to access them.
The [shadow root](https://dom.spec.whatwg.org/#shadowroot), returned by `attachShadow`, is like an element: we can use `innerHTML` or DOM methods, such as `append`, to populate it.
The element with a shadow root is called a "shadow tree host", and is available as the shadow root `host` property:
```js
// assuming {mode: "open"}, otherwise elem.shadowRoot is null
alert(elem.shadowRoot.host === elem); // true
```
## Encapsulation
Shadow DOM is strongly delimited from the main document:
1. Shadow DOM elements are not visible to `querySelector` from the light DOM. In particular, Shadow DOM elements may have ids that conflict with those in the light DOM. They be unique only within the shadow tree.
@ -83,7 +106,7 @@ For example:
```html run untrusted height=40
<style>
*!*
/* document style doesn't apply to shadow tree (2) */
/* document style won't apply to the shadow tree inside #elem (1) */
*/!*
p { color: red; }
</style>
@ -93,7 +116,7 @@ For example:
<script>
elem.attachShadow({mode: 'open'});
*!*
// shadow tree has its own style (1)
// shadow tree has its own style (2)
*/!*
elem.shadowRoot.innerHTML = `
<style> p { font-weight: bold; } </style>
@ -112,232 +135,23 @@ For example:
2. ...But the style from the inside works.
3. To get elements in shadow tree, we must query from inside the tree.
The element with a shadow root is called a "shadow tree host", and is available as the shadow root `host` property:
## References
```js
// assuming {mode: "open"}, otherwise elem.shadowRoot is null
alert(elem.shadowRoot.host === elem); // true
```
- DOM: <https://dom.spec.whatwg.org/#shadow-trees>
- Compatibility: <https://caniuse.com/#feat=shadowdomv1>
- Shadow DOM is mentioned in many other specifications, e.g. [DOM Parsing](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin) specifies that shadow root has `innerHTML`.
## Slots, composition
## Summary
Quite often, our components should be generic. Like tabs, menus, etc -- we should be able to fill them with content.
Shadow DOM is a way to create a component-local DOM.
Something like this:
1. `shadowRoot = elem.attachShadow({mode: open|closed})` -- creates shadow DOM for `elem`. If `mode="open"`, then it's accessible as `elem.shadowRoot` property.
2. We can populate `shadowRoot` using `innerHTML` or other DOM methods.
Shadow DOM elements:
- Have their own ids space,
- Invisible to JavaScript selectors from the main document, such as `querySelector`,
- Use styles only from the shadow tree, not from the main document.
<custom-menu>
<title>Please choose:</title>
<item>Candy</item>
<item>
<div slot="birthday">01.01.2001</div>
<p>I am John</p>
</user-card>
Let's say we need to create a `<user-card>` custom element, for showing user cards.
```html run
<user-card>
<p>Hello</p>
<div slot="username">John Smith</div>
<div slot="birthday">01.01.2001</div>
<p>I am John</p>
</user-card>
<script>
customElements.define('user-card', class extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot = `
<slot name="username"></slot>
<slot name="birthday"></slot>
<slot></slot>
`;
}
});
</script>
```
Let's say we'd like to create a generic `<user-card>` element for showing the information about the user. The element itself should be generic and contain "bio", "birthday" and "avatar" image.
Another developer should be able to add `<user-card>` on the page
Shadow DOM with "slots", e.g. articles, tabs, menus, that can be filled by
polyfill https://github.com/webcomponents/webcomponentsjs
<hr>
[Shadow tree](https://dom.spec.whatwg.org/#concept-shadow-tree) is a DOM tree that отдельным стандартом. Частично он уже используется для обычных DOM-элементов, но также применяется для создания веб-компонентов.
*Shadow DOM* -- это внутренний DOM элемента, который существует отдельно от внешнего документа. В нём могут быть свои ID, свои стили и так далее. Причём снаружи его, без применения специальных техник, не видно, поэтому не возникает конфликтов.
## Внутри браузера
Концепция Shadow DOM начала применяться довольно давно внутри самих браузеров. Когда браузер показывает сложные элементы управления, наподобие слайдера `<input type="range">` или календаря `<input type="date">` -- внутри себя он конструирует их из самых обычных стилизованных `<div>`, `<span>` и так далее.
С первого взгляда они незаметны, но если в настройках Chrome Development Tools выбрать показ Shadow DOM, то их можно легко увидеть.
Например, вот такое содержимое будет у `<input type="date">`:
![](shadow-dom-chrome.png)
То, что находится под `#shadow-root` -- это и есть Shadow DOM.
**Получить элементы из Shadow DOM можно только при помощи специальных JavaScript-вызовов или селекторов. Это не обычные дети, а намного более мощное средство отделения содержимого.**
В Shadow DOM выше можно увидеть полезный атрибут `pseudo`. Он нестандартный, существует по историческим причинам. С его помощью можно стилизовать подэлементы через CSS, например, сделаем поле редактирования даты красным:
```html run no-beautify
<style>
*!*
input::-webkit-datetime-edit {
*/!*
background: red;
}
</style>
<input type="date">
```
Ещё раз заметим, что `pseudo` -- нестандартный атрибут. Если говорить хронологически, то сначала браузеры начали экспериментировать внутри себя с инкапсуляцией внутренних DOM-структур, а уже потом, через некоторое время, появился стандарт Shadow DOM, который позволяет делать то же самое разработчикам.
Далее мы рассмотрим работу с Shadow DOM из JavaScript, по стандарту [Shadow DOM](http://w3c.github.io/webcomponents/spec/shadow/).
## Создание Shadow DOM
Shadow DOM можно создать внутри любого элемента вызовом `elem.createShadowRoot()`.
Например:
```html run autorun="no-epub"
<p id="elem">Доброе утро, страна!</p>
<script>
var root = elem.createShadowRoot();
root.innerHTML = "<p>Привет из подполья!</p>";
</script>
```
Если вы запустите этот пример, то увидите, что изначальное содержимое элемента куда-то исчезло и показывается только "Привет из подполья!". Это потому, что у элемента есть Shadow DOM.
**С момента создания Shadow DOM обычное содержимое (дети) элемента не отображается, а показывается только Shadow DOM.**
Внутрь этого Shadow DOM, при желании, можно поместить обычное содержимое. Для этого нужно указать, куда. В Shadow DOM это делается через "точку вставки" (insertion point). Она объявляется при помощи тега `<content>`, например:
```html run autorun="no-epub"
<p id="elem">Доброе утро, страна!</p>
<script>
var root = elem.createShadowRoot();
root.innerHTML = "<h3>*!*<content></content>*/!*</h3> <p>Привет из подполья!</p>";
</script>
```
Теперь вы увидите две строчки: "Доброе утро, страна!" в заголовке, а затем "Привет из подполья".
Shadow DOM примера выше в инструментах разработки:
![](shadow-content.png)
Важные детали:
- Тег `<content>` влияет только на отображение, он не перемещает узлы физически. Как видно из картинки выше, текстовый узел "Доброе утро, страна!" остался внутри `p#elem`. Его можно даже получить при помощи `elem.firstElementChild`.
- Внутри `<content>` показывается не элемент целиком `<p id="elem">`, а его содержимое, то есть в данном случае текст "Доброе утро, страна!".
**В `<content>` атрибутом `select` можно указать конкретный селектор содержимого, которое нужно переносить. Например, `<content select="h3"></content>` перенесёт только заголовки.**
Внутри Shadow DOM можно использовать `<content>` много раз с разными значениями `select`, указывая таким образом, где конкретно какие части исходного содержимого разместить. Но при этом дублирование узлов невозможно. Если узел показан в одном `<content>`, то в следующем он будет пропущен.
Например, если сначала идёт `<content select="h3.title">`, а затем `<content select="h3">`, то в первом `<content>` будут показаны заголовки `<h3>` с классом `title`, а во втором -- все остальные, кроме уже показанных.</li>
В примере выше тег `<content></content>` внутри пуст. Если в нём указать содержимое, то оно будет показано только в том случае, если узлов для вставки нет. Например потому что ни один узел не подпал под указанный `select`, или все они уже отображены другими, более ранними `<content>`.
Например:
```html run autorun="no-epub" no-beautify
<section id="elem">
<h1>Новости</h1>
<article>Жили-были <i>старик со старухой</i>, но недавно...</article>
</section>
<script>
var root = elem.createShadowRoot();
root.innerHTML = "<content select='h1'></content> \
<content select='.author'>Без автора.</content> \
<content></content>";
</script>
<button onclick="alert(root.innerHTML)">root.innerHTML</button>
```
При запуске мы увидим, что:
- Первый `<content select='h1'>` выведет заголовок.
- Второй `<content select=".author">` вывел бы автора, но так как такого элемента нет -- выводится содержимое самого `<content select=".author">`, то есть "Без автора".
- Третий `<content>` выведет остальное содержимое исходного элемента -- уже без заголовка `<h1>`, он выведен ранее!
Ещё раз обратим внимание, что `<content>` физически не перемещает узлы по DOM. Он только показывает, где их отображать, а также, как мы увидим далее, влияет на применение стилей.
## Корень shadowRoot
После создания корень внутреннего DOM-дерева доступен как `elem.shadowRoot`.
Он представляет собой специальный объект, поддерживающий основные методы CSS-запросов и подробно описанный в стандарте как [ShadowRoot](http://w3c.github.io/webcomponents/spec/shadow/#shadowroot-object).
Если нужно работать с содержимым в Shadow DOM, то нужно перейти к нему через `elem.shadowRoot`. Можно и создать новое Shadow DOM-дерево из JavaScript, например:
```html run autorun="no-epub"
<p id="elem">Доброе утро, страна!</p>
<script>
*!*
// создать новое дерево Shadow DOM для elem
*/!*
var root = elem.createShadowRoot();
root.innerHTML = "<h3><content></content></h3> <p>Привет из подполья!</p> <hr>";
</script>
<script>
*!*
// прочитать данные из Shadow DOM для elem
*/!*
var root = elem.shadowRoot;
// Привет из подполья!
document.write("<p>p:" + root.querySelector('p').innerHTML);
// пусто, так как физически узлы - вне content
document.write("<p>content:" + root.querySelector('content').innerHTML);
</script>
```
```warn header="Внутрь встроенных элементов так \"залезть\" нельзя"
На момент написания статьи `shadowRoot` можно получить только для Shadow DOM, созданного описанным выше способом, но не встроенного, как в элементах типа `<input type="date">`.
```
## Итого
Shadow DOM -- это средство для создания отдельного DOM-дерева внутри элемента, которое не видно снаружи без применения специальных методов.
- Ряд браузерных элементов со сложной структурой уже имеют Shadow DOM.
- Можно создать Shadow DOM внутри любого элемента вызовом `elem.createShadowRoot()`. В дальнейшем его корень будет доступен как `elem.shadowRoot`. У встроенных элементов он недоступен.
- Как только у элемента появляется Shadow DOM, его изначальное содержимое скрывается. Теперь показывается только Shadow DOM, который может указать, какое содержимое хозяина куда вставлять, при помощи элемента `<content>`. Можно указать селектор `<content select="селектор">` и размещать разное содержимое в разных местах Shadow DOM.
- Элемент `<content>` перемещает содержимое исходного элемента в Shadow DOM только визуально, в структуре DOM оно остаётся на тех же местах.
Подробнее спецификация описана по адресу <http://w3c.github.io/webcomponents/spec/shadow/>.
Далее мы рассмотрим работу с шаблонами, которые также являются частью платформы Web Components и не заменяют существующие шаблонные системы, но дополняют их важными встроенными в браузер возможностями.
Shadow DOM, if exists, is rendered by the browser instead of so-called "light DOM" (regular children). In the chapter <info:slots-composition> we'll see how to compose them.

View file

@ -1,11 +1,11 @@
# Template tags
# Template element
A built-in `<template>` element serves as a storage for markup. The browser ignores it contents, only checks for syntax validity.
A built-in `<template>` element serves as a storage for markup. The browser ignores it contents, only checks for syntax validity, but we can access and use it in JavaScript, to create other elements.
Of course, there are many ways to create an invisible element somewhere in HTML for markup purposes. What's special about `<template>`?
In theory, we could to create any invisible element somewhere in HTML for markup storage purposes. What's special about `<template>`?
First, as the content is ignored, it can be any valid HTML.
First, its content can be any valid HTML, even if it normally requires a proper enclosing tag.
For example, we can put there a table row `<tr>`:
```html
@ -18,32 +18,57 @@ For example, we can put there a table row `<tr>`:
Usually, if we try to put `<tr>` inside, say, a `<div>`, the browser detects the invalid DOM structure and "fixes" it, adds `<table>` around. That's not what we want. On the other hand, `<template>` keeps exactly what we place there.
We can put there styles:
We can put styles and scripts into `<template>` as well:
```html
<template>
<style>
p { font-weight: bold; }
</style>
<script>
alert("Hello");
</script>
</template>
```
The browser considers `<template>` content "out of the document", so the style is not applied.
The browser considers `<template>` content "out of the document", so the style is not applied, scripts are executed, `<video autoplay>` is not run, etc.
More than that, we can also have `<video>`, `<audio>` and even `<script>` in the template. It becomes live (the script executes) when we insert it.
The content becomes live (the script executes) when we insert it.
## Inserting template
The template content is available in its `content` property as a `DocumentFragment` -- a special type of DOM node.
The template content is available in its `content` property as a [DocumentFragment](info:modifying-document#document-fragment) -- a special type of DOM node.
We can treat it as any other DOM node, except one special property: when we insert it somewhere, its children are inserted instead.
For example, let's rewrite a Shadow DOM example from the previous chapter using `<template>`:
For example:
```html run
<template id="tmpl">
<script>
alert("Hello");
</script>
<div class="message">Hello, world!</div>
</template>
<script>
let elem = document.createElement('div');
*!*
// Clone the template content to reuse it multiple times
elem.append(tmpl.content.cloneNode(true));
*/!*
document.body.append(elem);
// Now the script from <template> runs
</script>
```
Let's rewrite a Shadow DOM example from the previous chapter using `<template>`:
```html run untrusted autorun="no-epub" height=60
<template id="tmpl">
<style> p { font-weight: bold; } </style>
<script> alert("I am alive!"); </script>
<p id="message"></p>
</template>
@ -62,31 +87,30 @@ For example, let's rewrite a Shadow DOM example from the previous chapter using
</script>
```
In the line `(*)` when we clone and insert `tmpl.content`, its children (`<style>`, `<p>`) are inserted instead, they form the shadow DOM:
In the line `(*)` when we clone and insert `tmpl.content`, its children (`<style>`, `<p>`) are inserted instead.
They form the shadow DOM:
```html
<div id="elem">
#shadow-root
<style> p { font-weight: bold; } </style>
<script> alert("I am alive!"); </script>
<p id="message"></p>
</div>
```
Please note that the template `<script>` runs exactly when it's added into the document. If we clone `template.content` multiple times, it executes each time.
## Summary
To summarize:
- `<template>` content can be any syntactically correct HTML.
- `<template>` content is considered "out of the document", so it doesn't affect anything.
- We can access `template.content` from JavaScript, clone it to render new component or for other purposes.
- We can access `template.content` from JavaScript, clone it to reuse in a new component.
The `<template>` tag is quite unique, because:
- The browser checks the syntax inside it (as opposed to using a template string inside a script).
- ...But still allows to use any top-level HTML tags, even those that don't make sense without proper wrappers (e.g. `<tr>`).
- The content becomes interactive: scripts run, `<video autoplay>` plays etc, when the insert it into the document (as opposed to assigning it with `elem.innerHTML=` that doesn't do that).
- The content becomes interactive: scripts run, `<video autoplay>` plays etc, when inserted into the document.
The `<template>` tag does not feature any sophisticated iteration mechanisms or variable substitutions, making it less powerful than frameworks. But it's built-in and ready to serve.
The `<template>` tag does not feature any sophisticated iteration mechanisms, data binding or variable substitutions, making it less powerful than frameworks. But we can build those on top of it.

View file

@ -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:
![](shadow-dom-user-card.png)
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.

View file

@ -1,20 +1,21 @@
# Shadow DOM styling
Shadow DOM may include both `<style>` and `<link rel="stylesheeet" href="…">` tags. In the latter case, stylesheets are HTTP-cached, so they are not redownloaded.
Shadow DOM may include both `<style>` and `<link rel="stylesheet" href="…">` tags. In the latter case, stylesheets are HTTP-cached, so they are not redownloaded. There's no overhead in @importing or linking same styles for many components.
As a general rule, local styles work only inside the shadow tree, and document styles work outside of it. But there are few exceptions.
## :host
The `:host` selector allows to select the shadow host: the element containing the shadow tree.
The `:host` selector allows to select the shadow host (the element containing the shadow tree).
For instance, we're making `<custom-dialog>` element that should be centered. For that we need to style not something inside `<custom-dialog>`, but the element itself.
For instance, we're making `<custom-dialog>` element that should be centered. For that we need to style the `<custom-dialog>` element itself.
That's exactly what `:host` selects:
That's exactly what `:host` does:
```html run autorun="no-epub" untrusted height=80
<template id="tmpl">
<style>
/* the style will be applied from inside to the custom-dialog element */
:host {
position: fixed;
left: 50%;
@ -43,11 +44,11 @@ customElements.define('custom-dialog', class extends HTMLElement {
## Cascading
The shadow host (`<custom-dialog>` itself) is a member of the outer document, so it's affected by the main CSS cascade.
The shadow host (`<custom-dialog>` itself) resides in the light DOM, so it's affected by the main CSS cascade.
If there's a property styled both in `:host` locally, and in the document, then the document style takes precedence.
For instance, if in the outer document we had:
For instance, if in the document we had:
```html
<style>
custom-dialog {
@ -55,18 +56,18 @@ custom-dialog {
}
</style>
```
...Then the dialog would be without padding.
...Then the `<custom-dialog>` would be without padding.
It's very convenient, as we can setup "default" styles in the component `:host` rule, and then easily override them in the document.
The exception is when a local property is labelled `!important`. For important properties, local styles take precedence.
The exception is when a local property is labelled `!important`, for such properties, local styles take precedence.
## :host(selector)
Same as `:host`, but the shadow host also must the selector.
Same as `:host`, but applied only if the shadow host matches the `selector`.
For example, we'd like to center the custom dialog only if it has `centered` attribute:
For example, we'd like to center the `<custom-dialog>` only if it has `centered` attribute:
```html run autorun="no-epub" untrusted height=80
<template id="tmpl">
@ -111,35 +112,28 @@ Now the additional centering styles are only applied to the first dialog `<custo
## :host-context(selector)
Same as `:host`, the shadow host or any of its ancestors in the outer document must match the selector.
Same as `:host`, but applied only if the shadow host or any of its ancestors in the outer document matches the `selector`.
E.g. if we add a rule `:host-context(.top)` to the example above, it matches for following cases if an ancestor matches `.top`:
E.g. `:host-context(.dark-theme)` matches only if there's `dark-theme` class on `<custom-dialog>` on above it:
```html
<header class="top">
<div>
<custom-dialog>...</custom-dialog>
<div>
</header>
<body class="dark-theme">
<!--
:host-context(.dark-theme) applies to custom-dialogs inside .dark-theme
-->
<custom-dialog>...</custom-dialog>
</body>
```
...Or when the dialog matches `.top`:
```html
<custom-dialog class="top">...</custom-dialog>
```
```smart
The `:host-context(selector)` is the only CSS rule that can somewhat test the outer document context, outside the shadow host.
```
To summarize, we can use `:host`-family of selectors to style the main element of the component, depending on the context. These styles (unless `!important`) can be overridden by the document.
## Styling slotted content
Now let's consider the situation with slots.
Elements, that come from light DOM, keep their document styles. Local styles do not affect them, as they are physically not in the shadow DOM.
Slotted elements come from light DOM, so they use document styles. Local styles do not affect slotted content.
For example, here `<span>` takes the document style, but not the local one:
In the example below, slotted `<span>` is bold, as per document style, but does not take `background` from the local style:
```html run autorun="no-epub" untrusted height=80
<style>
*!*
@ -170,9 +164,9 @@ customElements.define('user-card', class extends HTMLElement {
The result is bold, but not red.
If we'd like to style slotted elements, there are two choices.
If we'd like to style slotted elements in our component, there are two choices.
First, we can style the `<slot>` itself and rely on style inheritance:
First, we can style the `<slot>` itself and rely on CSS inheritance:
```html run autorun="no-epub" untrusted height=80
<user-card>
@ -196,15 +190,20 @@ customElements.define('user-card', class extends HTMLElement {
</script>
```
Here `<p>John Smith</p>` becomes bold, because of CSS inheritance from it's "flattened parent" slot. But not all CSS properties are inherited.
Here `<p>John Smith</p>` becomes bold, because CSS inheritance is in effect between the `<slot>` and its contents. But not all CSS properties are inherited.
Another option is to use `::slotted(selector)` pseudo-class. It allows to select elements that are inserted into slots and match the selector.
Another option is to use `::slotted(selector)` pseudo-class. It matches elements based on two conditions:
In our example, `::slotted(div)` selects exactly `<div slot="username">`:
1. The element from the light DOOM that is inserted into a `<slot>`. Then slot name doesn't matter. Just any slotted element, but only the element itself, not its children.
2. The element matches the `selector`.
In our example, `::slotted(div)` selects exactly `<div slot="username">`, but not its children:
```html run autorun="no-epub" untrusted height=80
<user-card>
<div slot="username">*!*<span>John Smith</span>*/!*</div>
<div slot="username">
<div>John Smith</div>
</div>
</user-card>
<script>
@ -214,7 +213,7 @@ customElements.define('user-card', class extends HTMLElement {
this.shadowRoot.innerHTML = `
<style>
*!*
::slotted(div) { display: inline; border: 1px solid red; }
::slotted(div) { border: 1px solid red; }
*/!*
</style>
Name: <slot name="username"></slot>
@ -224,7 +223,7 @@ customElements.define('user-card', class extends HTMLElement {
</script>
```
Please note, we can't descend any further. These selectors are invalid:
Please note, `::slotted` selector can't descend any further into the slot. These selectors are invalid:
```css
::slotted(div span) {
@ -236,15 +235,13 @@ Please note, we can't descend any further. These selectors are invalid:
}
```
Also, `::slotted` can't be used in JavaScript `querySelector`. That's CSS only pseudo-class.
Also, `::slotted` can only be used in CSS. We can't use it in `querySelector`.
## Using CSS properties
## CSS hooks with custom properties
How do we style a component in-depth?
How do we style a component in-depth from the main document?
Naturally, we can style its main element, `<custom-dialog>` or `<user-card>`, etc.
But how can we affect its internals? For instance, in `<user-card>` we'd like to allow the outer document change how user fields look.
Naturally, document styles apply to `<custom-dialog>` element or `<user-card>`, etc. But how can we affect its internals? For instance, in `<user-card>` we'd like to allow the outer document change how user fields look.
Just as we expose methods to interact with our component, we can expose CSS variables (custom CSS properties) to style it.
@ -255,8 +252,8 @@ For example, in shadow DOM we can use `--user-card-field-color` CSS variable to
```html
<style>
.field {
/* if --user-card-field-color is not defined, use black */
color: var(--user-card-field-color, black);
/* if --user-card-field-color is not defined, use black */
}
</style>
<div class="field">Name: <slot name="username"></slot></div>
@ -277,11 +274,21 @@ Custom CSS properties pierce through shadow DOM, they are visible everywhere, so
Here's the full example:
```html run autorun="no-epub" untrusted height=80
<style>
*!*
user-card {
--user-card-field-color: green;
}
*/!*
</style>
<template id="tmpl">
<style>
*!*
.field {
color: var(--user-card-field-color, black);
}
*/!*
</style>
<div class="field">Name: <slot name="username"></slot></div>
<div class="field">Birthday: <slot name="birthday"></slot></div>
@ -296,11 +303,6 @@ customElements.define('user-card', class extends HTMLElement {
});
</script>
<style>
user-card {
--user-card-field-color: green;
}
</style>
<user-card>
<span slot="username">John Smith</span>
<span slot="birthday">01.01.2001</span>
@ -315,18 +317,18 @@ Shadow DOM can include styles, such as `<style>` or `<link rel="stylesheet">`.
Local styles can affect:
- shadow tree,
- shadow host (from the outer document),
- slotted elements (from the outer document).
- shadow host with `:host`-family pseudoclasses,
- slotted elements (coming from light DOM), `::slotted(selector)` allows to select slotted elements themselves, but not their children.
Document styles can affect:
- shadow host (as it's in the outer document)
- slotted elements and their contents (as it's physically in the outer document)
When CSS properties intersect, normally document styles have precedence, unless the property is labelled as `!important`. Then local styles have precedence.
When CSS properties conflict, normally document styles have precedence, unless the property is labelled as `!important`. Then local styles have precedence.
CSS custom properties pierce through shadow DOM. They are used as "hooks" to style the component:
1. The component uses CSS properties to style key elements, such as `var(--component-name-title, <default value>)` for a title.
1. The component uses a custom CSS property to style key elements, such as `var(--component-name-title, <default value>)`.
2. Component author publishes these properties for developers, they are same important as other public component methods.
3. When a developer wants to style a title, they assign `--component-name-title` CSS property for the shadow host (as in the example above) or one of its parents.
3. When a developer wants to style a title, they assign `--component-name-title` CSS property for the shadow host or above.
4. Profit!

View file

@ -0,0 +1,192 @@
# Shadow DOM and events
The idea behind shadow tree is to encapsulate internal implementation details of a component.
Let's say, a click event happens inside a shadow DOM of `<user-card>` component. But scripts in the main document have no idea about the shadow DOM internals, especially if the component comes from a 3rd-party library or so.
So, to keep things simple, the browser *retargets* the event.
**Events that happen in shadow DOM have the host element as the target, when caught outside of the component.**
Here's a simple example:
```html run autorun="no-epub" untrusted height=60
<user-card></user-card>
<script>
customElements.define('user-card', class extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `<p>
<button>Click me</button>
</p>`;
this.shadowRoot.firstElementChild.onclick =
e => alert("Inner target: " + e.target.tagName);
}
});
document.onclick =
e => alert("Outer target: " + e.target.tagName);
</script>
```
If you click on the button, the messages are:
1. Inner target: `BUTTON` -- internal event handler gets the correct target, the element inside shadow DOM.
2. Outer target: `USER-CARD` -- document event handler gets shadow host as the target.
Event retargeting is a great thing to have, because the outer document doesn't have no know about component internals. From its point of view, the event happened on `<user-card>`.
**Retargeting does not occur if the event occurs on a slotted element, that physically lives in the light DOM.**
For example, if a user clicks on `<span slot="username">` in the example below, the event target is exactly this element, for both shadow and light handlers:
```html run autorun="no-epub" untrusted height=60
<user-card id="userCard">
*!*
<span slot="username">John Smith</span>
*/!*
</user-card>
<script>
customElements.define('user-card', class extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `<div>
<b>Name:</b> <slot name="username"></slot>
</div>`;
this.shadowRoot.firstElementChild.onclick =
e => alert("Inner target: " + e.target.tagName);
}
});
userCard.onclick = e => alert(`Outer target: ${e.target.tagName}`);
</script>
```
If a click happens on `"John Smith"`, for both inner and outer handlers the target is `<span slot="username">`. That's an element from the light DOM, so no retargeting.
On the other hand, if the click occurs on an element originating from shadow DOM, e.g. on `<b>Name</b>`, then, as it bubbles out of the shadow DOM, its `event.target` is reset to `<user-card>`.
## Bubbling, event.composedPath()
For purposes of event bubbling, flattened DOM is used.
So, if we have a slotted element, and an event occurs somewhere inside it, then it bubbles up to the `<slot>` and upwards.
The full path to the original event target, with all the shadow root elements, can be obtained using `event.composedPath()`. As we can see from the name of the method, that path is taken after the composition.
In the example above, the flattened DOM is:
```html
<user-card id="userCard">
#shadow-root
<div>
<b>Name:</b>
<slot name="username">
<span slot="username">John Smith</span>
</slot>
</div>
</user-card>
```
So, for a click on `<span slot="username">`, a call to `event.composedPath()` returns an array: [`span`, `slot`, `div`, `shadow-root`, `user-card`, `body`, `html`, `document`, `window`]. That's exactly the parent chain from the target element in the flattened DOM, after the composition.
```warn header="Shadow tree details are only provided for `{mode:'open'}` trees"
If the shadow tree was created with `{mode: 'closed'}`, then the composed path starts from the host: `user-card` and upwards.
That's the similar principle as for other methods that work with shadow DOM. Internals of closed trees are completely hidden.
```
## event.composed
Most events successfully bubble through a shadow DOM boundary. There are few events that do not.
This is governed by the `composed` event object property. If it's `true`, then the event does cross the boundary. Otherwise, it only can be caught from inside the shadow DOM.
If you take a look at [UI Events specification](https://www.w3.org/TR/uievents), most events have `composed: true`:
- `blur`, `focus`, `focusin`, `focusout`,
- `click`, `dblclick`,
- `mousedown`, `mouseup` `mousemove`, `mouseout`, `mouseover`,
- `wheel`,
- `beforeinput`, `input`, `keydown`, `keyup`.
All touch events and pointer events also have `composed: true`.
There are some events that have `composed: false` though:
- `mouseenter`, `mouseleave` (they also do not bubble),
- `load`, `unload`, `abort`, `error`,
- `select`,
- `slotchange`.
These events can be caught only on elements within the same DOM, where the event target resides.
## Custom events
When we dispatch custom events, we need to set both `bubbles` and `composed` properties to `true` for it to bubble up and out of the component.
For example, here we create `div#inner` in the shadow DOM of `div#outer` and trigger two events on it. Only the one with `composed: true` makes it outside to the document:
```html run untrusted height=0
<div id="outer"></div>
<script>
outer.attachShadow({mode: 'open'});
let inner = document.createElement('div');
outer.shadowRoot.append(inner);
/*
div(id=outer)
#shadow-dom
div(id=inner)
*/
document.addEventListener('test', event => alert(event.detail));
inner.dispatchEvent(new CustomEvent('test', {
bubbles: true,
*!*
composed: true,
*/!*
detail: "composed"
}));
inner.dispatchEvent(new CustomEvent('test', {
bubbles: true,
*!*
composed: false,
*/!*
detail: "not composed"
}));
</script>
```
## Summary
Events only cross shadow DOM boundaries if their `composed` flag is set to `true`.
Built-in events mostly have `composed: true`, as described in the relevant specifications:
- UI Events <https://www.w3.org/TR/uievents>.
- Touch Events <https://w3c.github.io/touch-events>.
- Pointer Events <https://www.w3.org/TR/pointerevents>.
- ...And so on.
Some built-in events that have `composed: false`:
- `mouseenter`, `mouseleave` (also do not bubble),
- `load`, `unload`, `abort`, `error`,
- `select`,
- `slotchange`.
These events can be caught only on elements within the same DOM.
If we dispatch a `CustomEvent`, then we should explicitly set `composed: true`.
Please note that in case of nested components, composed events bubble through all shadow DOM boundaries. So, if an event is intended only for the immediate enclosing component, we can also dispatch it on the shadow host. Then it's out of the shadow DOM already.