You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The idea behind shadow tree is to encapsulate internal implementation details of a component.
3
+
Головна мета створення тіньового дерева – це інкапсуляція внутрішньої реалізації компоненту.
4
4
5
-
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.
5
+
Скажімо, було виконано подію click всередині тіньового DOM компоненту`<user-card>`. Але ж скріпти в головному документі і гадки не мають про внутрішню будову тіньового DOM, особливо, якщо компонент походить зі сторонньої бібліотеки. Отже, для збереження інкапсуляції вмісту, браузер *змінює у цієї події цільовий елемент*.
6
6
7
-
So, to keep the details encapsulated, the browser *retargets* the event.
7
+
**Події, що відбуваються у тіньовому DOM, впливають на батьківський елемент, навіть якщо відбулися за межами компоненту.**
8
8
9
-
**Events that happen in shadow DOM have the host element as the target, when caught outside of the component.**
10
-
11
-
Here's a simple example:
9
+
Розглянемо простий приклад:
12
10
13
11
```html run autorun="no-epub" untrusted height=60
14
12
<user-card></user-card>
@@ -21,30 +19,31 @@ customElements.define('user-card', class extends HTMLElement {
Клікнувши на кнопку, отримаємо наступні повідомлення:
32
+
33
+
1. Внутрішній цільовий елемент: `BUTTON` – внутрішній обробник подій отримує правильну ціль – елемент всередині тіньового DOM
34
+
2. Зовнішній цільовий елемент: `USER-CARD` – обробник подій документу отримує тіньовий хост в якості цільового елементу
34
35
35
-
1. Inner target: `BUTTON` -- internal event handler gets the correct target, the element inside shadow DOM.
36
-
2. Outer target: `USER-CARD` -- document event handler gets shadow host as the target.
37
36
38
-
Event retargeting is a great thing to have, because the outer document doesn't have to know about component internals. From its point of view, the event happened on`<user-card>`.
37
+
Зміна цільового елементу – чудова річ, тому що зовнішній документ не повинен знати про внутрішній вміст компоненту. З цієї точки зору, подія відбулась в`<user-card>`.
39
38
40
-
**Retargeting does not occur if the event occurs on a slotted element, that physically lives in the light DOM.**
39
+
**Зміна цільового елементу не відбувається, якщо подія починається з елементу зі слота, що фактично знаходиться в звичайному світлому DOM.**
41
40
42
-
For example, if a user clicks on `<span slot="username">`in the example below, the event target is exactly this `span`element, for both shadow and light handlers:
41
+
Наприклад, якщо користувач клікає на `<span slot="username">`у прикладі, наведеному нижче, цільовим елементом є саме цей `span`елемент, для обох обробників – звичайного (світлого) та тіньового:
43
42
44
43
```html run autorun="no-epub" untrusted height=60
45
44
<user-cardid="userCard">
46
45
*!*
47
-
<spanslot="username">John Smith</span>
46
+
<spanslot="username">Іван Коваль</span>
48
47
*/!*
49
48
</user-card>
50
49
@@ -57,80 +56,80 @@ customElements.define('user-card', class extends HTMLElement {
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.
67
+
Якщо клік відбувся на `"Іван Коваль"`, для обох – внутрішнього та зовнішнього – обробників цільовим елементом є `<span slot="username">`. Так як це елемент зі світлого DOM, то зміни цільового елементу не відбувається.
69
68
70
-
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>`.
69
+
З іншого боку, якщо клік відбувся на елементі з тіньового DOM, т.я.`<b>Name</b>`, тоді він вспливає з тіньового DOM, a його цільовим елементом`event.target`стає`<user-card>`.
71
70
72
-
## Bubbling, event.composedPath()
71
+
## Спливання, event.composedPath()
73
72
74
-
For purposes of event bubbling, flattened DOM is used.
73
+
Для цілей спливання подій (бульбашковий механізм) використовується розгорнутий DOM.
75
74
76
-
So, if we have a slotted element, and an event occurs somewhere inside it, then it bubbles up to the `<slot>`and upwards.
75
+
Отже, якщо у нас є елемент у слоті, і подія відбувається десь усередині цього елементу, тоді вона підіймається до `<slot>`і вище.
77
76
78
-
The full path to the original event target, with all the shadow elements, can be obtained using `event.composedPath()`. As we can see from the name of the method, that path is taken after the composition.
77
+
Повний шлях до початкового цільового елементу з усіма тіньовими елементами можна отримати за допомогою `event.composedPath()`. Як видно з назви методу, він повертає шлях після композиції.
79
78
80
-
In the example above, the flattened DOM is:
79
+
У наведеному вище прикладі зведений DOM виглядає так:
81
80
82
81
```html
83
82
<user-cardid="userCard">
84
83
#shadow-root
85
84
<div>
86
85
<b>Name:</b>
87
86
<slotname="username">
88
-
<spanslot="username">John Smith</span>
87
+
<spanslot="username">Іван Коваль</span>
89
88
</slot>
90
89
</div>
91
90
</user-card>
92
91
```
93
92
94
93
95
-
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.
94
+
Отже, для кліку по `<span slot="username">` виклик `event.composedPath()`повертає масив: [`span`, `slot`, `div`, `shadow-root`, `user-card`, `body`, `html`, `document`, `window`], що цілковито відображає батьківський ланцюжок, починаючи з цільового елемента у зведеному DOM після композиції.
96
95
97
-
```warn header="Shadow tree details are only provided for `{mode:'open'}` trees"
98
-
If the shadow tree was created with `{mode: 'closed'}`, then the composed path starts from the host: `user-card`and upwards.
96
+
```warn header="Деталі тіньового дерева надаються лише для дерев з `{mode:'open'}`"
97
+
Якщо тіньове дерево було створено з `{mode: 'closed'}`, то тоді складений (composed) шлях починається від хоста: `user-card`і вище.
99
98
100
-
That's the similar principle as for other methods that work with shadow DOM. Internals of closed trees are completely hidden.
99
+
Це той самий принцип, що і для інших методів, які працюють із тіньовим DOM. Внутрішні частини закритих дерев повністю приховані.
101
100
```
102
101
103
102
104
-
## event.composed
103
+
## Властивість event.composed
105
104
106
-
Most events successfully bubble through a shadow DOM boundary. There are few events that do not.
105
+
Більшість подій успішно проходять через тіньову межу DOM. Є кілька подій, які цього не роблять.
107
106
108
-
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.
107
+
Це регулюється властивістю об’єкта події `composed`. Якщо це `true`, то подія дійсно перетинає межу. В іншому випадку його можна буде перехопити лише зсередини тіньового DOM.
109
108
110
-
If you take a look at [UI Events specification](https://www.w3.org/TR/uievents), most events have `composed: true`:
109
+
Якщо ви подивитесь на [UI Events specification](https://www.w3.org/TR/uievents), більшість подій мають `composed: true`:
All touch events and pointer events also have `composed: true`.
117
+
Усі сенсорні події та події курсору також мають `composed: true`.
119
118
120
-
There are some events that have `composed: false` though:
119
+
Та існують деякі події, що мають `composed: false`:
121
120
122
-
- `mouseenter`, `mouseleave` (they do not bubble at all),
121
+
- `mouseenter`, `mouseleave` (ці події взагалі не спливають вгору),
123
122
- `load`, `unload`, `abort`, `error`,
124
123
- `select`,
125
124
- `slotchange`.
126
125
127
-
These events can be caught only on elements within the same DOM, where the event target resides.
126
+
Ці події можна перехопити лише на елементах у межах того ж самого DOM, де знаходиться цільовий елемент події.
128
127
129
-
## Custom events
128
+
## Генерація подій (сustom events)
130
129
131
-
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.
130
+
Коли ми генеруємо користувацькі події, нам потрібно встановити для властивостей `bubbles` і `composed` значення `true`, щоб вони спливали та виходили за межі компонента.
132
131
133
-
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:
132
+
Наприклад, тут ми створюємо `div#inner` у тіньовому DOM `div#outer` і запускаємо дві події для нього. Лише та, що має `composed: true`, виходить за межі документа:
-`mouseenter`, `mouseleave` (зовсім не спливають),
184
183
-`load`, `unload`, `abort`, `error`,
185
184
-`select`,
186
185
-`slotchange`.
187
186
188
-
These events can be caught only on elements within the same DOM.
187
+
Ці події можуть бути перехоплені тільки на елементах у межах того самого DOM.
189
188
190
-
If we dispatch a `CustomEvent`, then we should explicitly set`composed: true`.
189
+
Якщо ми генеруємо `CustomEvent`, тоді нам слід явно встановити`composed: true`.
191
190
192
-
Please note that in case of nested components, one shadow DOM may be nested into another. In that case 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 and set `composed: false`. Then it's out of the component shadow DOM, but won't bubble up to higher-level DOM.
191
+
Зверніть увагу, що у випадку вкладених компонентів один тіньовий DOM може бути вкладений в інший. У цьому випадку складені події проходять через усі тіньові межі DOM. Отже, якщо подія призначена лише для безпосередньо найближчого зовнішнього батьківського компонента, ми також можемо ініціювати її на тіньовому хості і встановити `composed: false`. В такому разі подія виходить із тіньової DOM компонента, але не переходить до DOM вищого рівня.
0 commit comments