Skip to content

Commit d7c87ad

Browse files
authored
Update article.md
Переклад українською
1 parent 067602f commit d7c87ad

File tree

1 file changed

+52
-53
lines changed

1 file changed

+52
-53
lines changed
Lines changed: 52 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
# Shadow DOM and events
1+
# Тіньовий DOM та події
22

3-
The idea behind shadow tree is to encapsulate internal implementation details of a component.
3+
Головна мета створення тіньового дерева – це інкапсуляція внутрішньої реалізації компоненту.
44

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, особливо, якщо компонент походить зі сторонньої бібліотеки. Отже, для збереження інкапсуляції вмісту, браузер *змінює у цієї події цільовий елемент*.
66

7-
So, to keep the details encapsulated, the browser *retargets* the event.
7+
**Події, що відбуваються у тіньовому DOM, впливають на батьківський елемент, навіть якщо відбулися за межами компоненту.**
88

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+
Розглянемо простий приклад:
1210

1311
```html run autorun="no-epub" untrusted height=60
1412
<user-card></user-card>
@@ -21,30 +19,31 @@ customElements.define('user-card', class extends HTMLElement {
2119
<button>Click me</button>
2220
</p>`;
2321
this.shadowRoot.firstElementChild.onclick =
24-
e => alert("Inner target: " + e.target.tagName);
22+
e => alert("Внутрішній цільовий елемент: " + e.target.tagName);
2523
}
2624
});
2725
2826
document.onclick =
29-
e => alert("Outer target: " + e.target.tagName);
27+
e => alert("Зовнішній цільовий елемент: " + e.target.tagName);
3028
</script>
3129
```
3230

33-
If you click on the button, the messages are:
31+
Клікнувши на кнопку, отримаємо наступні повідомлення:
32+
33+
1. Внутрішній цільовий елемент: `BUTTON` – внутрішній обробник подій отримує правильну ціль – елемент всередині тіньового DOM
34+
2. Зовнішній цільовий елемент: `USER-CARD` – обробник подій документу отримує тіньовий хост в якості цільового елементу
3435

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.
3736

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>`.
3938

40-
**Retargeting does not occur if the event occurs on a slotted element, that physically lives in the light DOM.**
39+
**Зміна цільового елементу не відбувається, якщо подія починається з елементу зі слота, що фактично знаходиться в звичайному світлому DOM.**
4140

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` елемент, для обох обробників – звичайного (світлого) та тіньового:
4342

4443
```html run autorun="no-epub" untrusted height=60
4544
<user-card id="userCard">
4645
*!*
47-
<span slot="username">John Smith</span>
46+
<span slot="username">Іван Коваль</span>
4847
*/!*
4948
</user-card>
5049

@@ -57,80 +56,80 @@ customElements.define('user-card', class extends HTMLElement {
5756
</div>`;
5857
5958
this.shadowRoot.firstElementChild.onclick =
60-
e => alert("Inner target: " + e.target.tagName);
59+
e => alert("Внутрішній цільовий елемент: " + e.target.tagName);
6160
}
6261
});
6362
64-
userCard.onclick = e => alert(`Outer target: ${e.target.tagName}`);
63+
userCard.onclick = e => alert(`Зовнішній цільовий елемент: ${e.target.tagName}`);
6564
</script>
6665
```
6766

68-
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, то зміни цільового елементу не відбувається.
6968

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>`.
7170

72-
## Bubbling, event.composedPath()
71+
## Спливання, event.composedPath()
7372

74-
For purposes of event bubbling, flattened DOM is used.
73+
Для цілей спливання подій (бульбашковий механізм) використовується розгорнутий DOM.
7574

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>` і вище.
7776

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()`. Як видно з назви методу, він повертає шлях після композиції.
7978

80-
In the example above, the flattened DOM is:
79+
У наведеному вище прикладі зведений DOM виглядає так:
8180

8281
```html
8382
<user-card id="userCard">
8483
#shadow-root
8584
<div>
8685
<b>Name:</b>
8786
<slot name="username">
88-
<span slot="username">John Smith</span>
87+
<span slot="username">Іван Коваль</span>
8988
</slot>
9089
</div>
9190
</user-card>
9291
```
9392

9493

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 після композиції.
9695

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` і вище.
9998

100-
That's the similar principle as for other methods that work with shadow DOM. Internals of closed trees are completely hidden.
99+
Це той самий принцип, що і для інших методів, які працюють із тіньовим DOM. Внутрішні частини закритих дерев повністю приховані.
101100
```
102101
103102
104-
## event.composed
103+
## Властивість event.composed
105104
106-
Most events successfully bubble through a shadow DOM boundary. There are few events that do not.
105+
Більшість подій успішно проходять через тіньову межу DOM. Є кілька подій, які цього не роблять.
107106
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.
109108
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`:
111110
112111
- `blur`, `focus`, `focusin`, `focusout`,
113112
- `click`, `dblclick`,
114113
- `mousedown`, `mouseup` `mousemove`, `mouseout`, `mouseover`,
115114
- `wheel`,
116115
- `beforeinput`, `input`, `keydown`, `keyup`.
117116
118-
All touch events and pointer events also have `composed: true`.
117+
Усі сенсорні події та події курсору також мають `composed: true`.
119118
120-
There are some events that have `composed: false` though:
119+
Та існують деякі події, що мають `composed: false`:
121120
122-
- `mouseenter`, `mouseleave` (they do not bubble at all),
121+
- `mouseenter`, `mouseleave` (ці події взагалі не спливають вгору),
123122
- `load`, `unload`, `abort`, `error`,
124123
- `select`,
125124
- `slotchange`.
126125
127-
These events can be caught only on elements within the same DOM, where the event target resides.
126+
Ці події можна перехопити лише на елементах у межах того ж самого DOM, де знаходиться цільовий елемент події.
128127
129-
## Custom events
128+
## Генерація подій (сustom events)
130129
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`, щоб вони спливали та виходили за межі компонента.
132131
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`, виходить за межі документа:
134133
135134
```html run untrusted height=0
136135
<div id="outer"></div>
@@ -167,26 +166,26 @@ inner.dispatchEvent(new CustomEvent('test', {
167166
</script>
168167
```
169168

170-
## Summary
169+
## Підсумки
171170

172-
Events only cross shadow DOM boundaries if their `composed` flag is set to `true`.
171+
Лише ті події перетинають тіньові межі DOM, для прапорця `composed` яких встановлено значення `true`.
173172

174-
Built-in events mostly have `composed: true`, as described in the relevant specifications:
173+
Вбудовані події здебільшого мають `composed: true`, як описано у відповідних специфікаціях:
175174

176-
- UI Events <https://www.w3.org/TR/uievents>.
177-
- Touch Events <https://w3c.github.io/touch-events>.
178-
- Pointer Events <https://www.w3.org/TR/pointerevents>.
179-
- ...And so on.
175+
- Події інтерфейсу користувача (UI Events) <https://www.w3.org/TR/uievents>.
176+
- Сенсорні події (Touch Events) <https://w3c.github.io/touch-events>.
177+
- Події курсору (Pointer Events) <https://www.w3.org/TR/pointerevents>.
178+
- ...тощо.
180179

181-
Some built-in events that have `composed: false`:
180+
Деякі вбудовані події, що мають `composed: false`:
182181

183-
- `mouseenter`, `mouseleave` (also do not bubble),
182+
- `mouseenter`, `mouseleave` (зовсім не спливають),
184183
- `load`, `unload`, `abort`, `error`,
185184
- `select`,
186185
- `slotchange`.
187186

188-
These events can be caught only on elements within the same DOM.
187+
Ці події можуть бути перехоплені тільки на елементах у межах того самого DOM.
189188

190-
If we dispatch a `CustomEvent`, then we should explicitly set `composed: true`.
189+
Якщо ми генеруємо `CustomEvent`, тоді нам слід явно встановити `composed: true`.
191190

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

Comments
 (0)