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
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.
3
+
Тіньовий DOM ('Shadow DOM') використовується для інкапсуляції. Він дозволяє компоненті мати своє власне "тіньове" DOM-дерево, що не може бути випадково змінено з головного документу, a також може мати власні локальні стилі, та ін.
4
4
5
-
## Built-in shadow DOM
5
+
## Вбудований тіньовий DOM
6
6
7
-
Did you ever think how complex browser controls are created and styled?
7
+
Чи замислювались ви коли-небудь, як влаштовані та стилізовані складні браузерні інтерактивні елементи?
8
8
9
-
Such as`<input type="range">`:
9
+
Такі як`<input type="range">`:
10
10
11
11
<p>
12
12
<inputtype="range">
13
13
</p>
14
14
15
-
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.
15
+
Браузер використовує DOM/CSS на свій розсуд, щоб відобразити їх. Така структура DOM зазвичай прихована від нас, але ми можемо її побачити в інструментах розробника. Наприклад, у Chrome нам знадобиться активувати опцію "Show user agent shadow DOM".
16
16
17
-
Then`<input type="range">`looks like this:
17
+
Отже,`<input type="range">`виглядає так:
18
18
19
19

20
20
21
-
What you see under`#shadow-root`is called "shadow DOM".
21
+
Те, що відображено під`#shadow-root`і є "тіньовим DOM" (shadow DOM).
22
22
23
-
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.
23
+
Ми не можемо отримати доступ до тіньового DOM вбудованих елементів звичайними засобами JavaScript чи за допомогою селекторів. Це не просто дочірні елементи, а потужний спосіб інкапсуляції, тобто захисту від зовнішнього втручання у внутрішню структуру.
24
24
25
-
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:
25
+
У вищенаведеному прикладі зверніть увагу на корисний атрибут `pseudo`. Він є нестандартним та існує через історичні причини. Його можна використовувати задля стилізації вкладених елементів через CSS, наприклад, так:
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 standardized to allow us, developers, to do the similar thing.
38
+
Наголошуємо, `pseudo`є нестандартним атрибутом. Історично, браузери спочатку почали експерементувати зі внутрішнімі DOM-структурами для створення інтерактивних елементів, і тільки потім, через певний час, тіньовий DOM було стандартизовано, щоб надати можливість нам, розробникам, робити те саме.
39
39
40
-
Further on, we'll use the modern shadow DOM standard, covered by[DOM spec](https://dom.spec.whatwg.org/#shadow-trees)and other related specifications.
40
+
Надалі ми використовуватимемо сучасний тіньовий стандарт DOM, відображений у[DOM специфікації](https://dom.spec.whatwg.org/#shadow-trees)та в інших споріднених специфікаціях.
41
41
42
-
## Shadow tree
42
+
## Тіньове дерево
43
43
44
-
A DOM element can have two types of DOM subtrees:
44
+
DOM-елемент може мати два типи DOM піддерев:
45
45
46
-
1. Light tree -- a regular DOM subtree, made of HTML children. All subtrees that we've seen in previous chapters were "light".
47
-
2. Shadow tree -- a hidden DOM subtree, not reflected in HTML, hidden from prying eyes.
46
+
1. Light tree -- звичайне "cвітле" DOM піддерево, що складається з HTML-нащадків. Усі піддерева, про які йшлося у попередніх розділах, були "cвітлі".
47
+
2. Shadow tree -- приховане "тіньове" DOM піддерево, не відображене у HTML та сховане від сторонніх очей.
48
48
49
-
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>.
49
+
Якщо елемент має обидва, то браузер відображає тільки тіньове дерево. Також ми можемо встановити певний вид композиції (взаємодії) між тіньовим та світлим деревами. Ми обговоримо ці деталі надалі у розділі<info:slots-composition>.
50
50
51
-
Shadow tree can be used in Custom Elements to hide component internals and apply component-local styles.
51
+
Тіньове дерево може бути використаним в користувацьких елементах (сustom elements), щоб приховати внутрішню структуру компонента і застосувати до нього локальні стилі, захищені від зовнішнього втручання.
52
52
53
-
For example, this`<show-hello>`element hides its internal DOM in shadow tree:
53
+
Наприклад, цей`<show-hello>`елемент приховує свій внутрішній DOM у тіньовому дереві:
54
54
55
55
```html run autorun height=60
56
56
<script>
@@ -67,46 +67,46 @@ customElements.define('show-hello', class extends HTMLElement {
67
67
<show-helloname="John"></show-hello>
68
68
```
69
69
70
-
That's how the resulting DOM looks in Chrome dev tools, all the content is under "#shadow-root":
70
+
Ось так отриманий DOM виглядає в інструментах розробника Chrome, увесь контент всередині "#shadow-root":
71
71
72
72

73
73
74
-
First, the call to `elem.attachShadow({mode: …})`creates a shadow tree.
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.
76
+
Існує два обмеження:
77
+
1.Для одного елементу можливо створити тільки один тіньовий root.
78
+
2.`elem`повинен бути або кастомним елементом, або одним з наступних: "article", "aside", "blockquote", "body", "div", "footer", "h1..h6", "header", "main" "nav", "p", "section", or "span". Інші елементи, такі як `<img>`, не можуть містити тіньове дерево.
79
79
80
-
The`mode`option sets the encapsulation level. It must have any of two values:
81
-
-`"open"` -- the shadow root is available as`elem.shadowRoot`.
80
+
Опція`mode`встановлює рівень інкапсуляції, вона повинна мати одне з двох значень:
Any code is able to access the shadow tree of`elem`.
84
-
-`"closed"` -- `elem.shadowRoot`is always`null`.
83
+
Будь-який код має доступ до тіньового дерева`elem`.
84
+
-`"closed"` -- `elem.shadowRoot`завжди`null`.
85
85
86
-
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.
86
+
Ми можемо отримати доступ до тіньового DOM тільки по посиланню, яке повертається`attachShadow` (і, можливо, приховане у класі). Вбудовані браузерні нативні дерева, такі, як `<input type="range">`, є закритими, до них не дістатись.
87
87
88
-
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.
88
+
[Тіньовий root](https://dom.spec.whatwg.org/#shadowroot), який повертає`attachShadow`, поводиться як елемент: ми можемо використовувати`innerHTML`чи DOM-методи, такі як`append`, щоб заповнити його.
89
89
90
-
The element with a shadow root is called a "shadow tree host", and is available as the shadow root `host`property:
90
+
Елемент з тіньового root називається "shadow tree host" і доступний як властивість `host`у shadow root.
91
91
92
92
```js
93
-
//assuming {mode: "open"}, otherwise elem.shadowRoot is null
93
+
//за умови {mode: "open"}, інакше elem.shadowRoot це null
94
94
alert(elem.shadowRoot.host=== elem); // true
95
95
```
96
96
97
-
## Encapsulation
97
+
## Інкапсуляція
98
98
99
-
Shadow DOM is strongly delimited from the main document:
99
+
Тіньовий DOM цілковито відокремлений від основного документу:
100
100
101
-
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 must be unique only within the shadow tree.
102
-
2.Shadow DOM has own stylesheets. Style rules from the outer DOM don't get applied.
101
+
1.Елементи тіньового DOM невидимі для `querySelector`зі світлого DOM. Зокрема, тіньовий DOM елемент може мати всередині атрибути `id` зі значеннями, що конфліктують з однойменними зі світлого DOM. Вони повинні бути унікальними тільки всередині тіньового дерева.
102
+
2.Тіньовий DOM має власні стилі. Стильові правила з зовнішнього DOM не застосовуються.
103
103
104
-
For example:
104
+
Наприклад:
105
105
106
106
```html run untrusted height=40
107
107
<style>
108
108
*!*
109
-
/*document style won't apply to the shadow tree inside #elem (1) */
109
+
/*стилі документа не застосовуються до тіньового дерева всередині #elem (1) */
110
110
*/!*
111
111
p { color: red; }
112
112
</style>
@@ -116,42 +116,42 @@ For example:
116
116
<script>
117
117
elem.attachShadow({mode:'open'});
118
118
*!*
119
-
//shadow tree has its own style (2)
119
+
//тіньове дерево має власні стилі (2)
120
120
*/!*
121
121
elem.shadowRoot.innerHTML=`
122
122
<style>p { font-weight: bold; } </style>
123
123
<p>Hello, John!</p>
124
124
`;
125
125
126
126
*!*
127
-
// <p> is only visible from queries inside the shadow tree (3)
127
+
// <p> видимий тільки запитам зсередини тіньового дерева (3)
-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`.
-Тіньовий DOM згадується у багатьох інших специфікаціях, наприклад, [DOM Parsing](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin)вказує на те, що у shadow root є`innerHTML`.
143
143
144
144
145
-
## Summary
145
+
## Підсумки
146
146
147
-
Shadow DOM is a way to create a component-local DOM.
147
+
Тіньовий DOM -- це спосіб створити ізольоване DOM-дерево для компоненти.
148
148
149
-
1.`shadowRoot = elem.attachShadow({mode: open|closed})` -- creates shadow DOM for`elem`. If`mode="open"`, then it's accessible as `elem.shadowRoot` property.
150
-
2.We can populate `shadowRoot` using`innerHTML`or other DOM methods.
149
+
1.`shadowRoot = elem.attachShadow({mode: open|closed})` -- створює тіньовий DOM для`elem`. Якщо`mode="open"`, то він є досяжним як властивість `elem.shadowRoot`.
150
+
2.Ми можемо записати щось всередину `shadowRoot`, використовуючи`innerHTML`чи інші DOM-методи.
151
151
152
-
Shadow DOM elements:
153
-
-Have their own ids space,
154
-
-Invisible to JavaScript selectors from the main document, such as `querySelector`,
155
-
-Use styles only from the shadow tree, not from the main document.
152
+
Тіньові елементи DOM:
153
+
-Мають окрему область для унікальності значень в атрибутах `id` HTML-елементів,
154
+
-Невидимі для селекторів JavaScript з головного документу, таким методам, як `querySelector`;
155
+
-Використовують стилі тільки з тіньового дерева, а не глобальні стилі документу.
156
156
157
-
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.
157
+
Тіньовий DOM, якщо існує, рендериться браузером замість так званого "світлого DOM" (звичайних нащадків). У главі <info:slots-composition>ми розберемо, як поєднювати їх.
0 commit comments