Skip to content

Commit 79324d0

Browse files
committed
draft
1 parent 8de6fa6 commit 79324d0

File tree

17 files changed

+809
-502
lines changed

17 files changed

+809
-502
lines changed
Loading

Diff for: 2-ui/1-document/11-coordinates/[email protected]

720 KB
Loading

Diff for: 8-web-components/2-custom-elements/article.md

+6-3
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ For example, there already exists `<time>` element in HTML, for date/time. But i
6767
Let's create `<time-formatted>` element that does the formatting:
6868
6969
70-
```html run height=50 autorun
70+
```html run height=50 autorun="no-epub"
7171
<script>
7272
class TimeFormatted extends HTMLElement {
7373
@@ -133,7 +133,7 @@ Please note that in the current implementation, after the element is rendered, f
133133
134134
We can observe attributes by providing their list in `observedAttributes()` static getter, and then update the element in `attributeChangedCallback`. It's called for changes only in the listed attributes for performance reasons.
135135
136-
```html run autorun height=50
136+
```html run autorun="no-epub" height=50
137137
<script>
138138
class TimeFormatted extends HTMLElement {
139139
@@ -286,7 +286,7 @@ We could use special [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessi
286286

287287
Built-in elements can be customized by inheriting from their classes. HTML buttons are instances of `HTMLButtonElement`, so let's extend it:
288288

289-
```html run autorun
289+
```html run autorun="no-epub"
290290
<script>
291291
// The button that says "hello" on click
292292
class HelloButton extends HTMLButtonElement {
@@ -324,4 +324,7 @@ customElements.define('hello-button', HelloButton, {extends: 'button'}); // 2
324324

325325
Мы рассмотрели, как создавать свои DOM-элементы при помощи стандарта [Custom Elements](http://www.w3.org/TR/custom-elements/).
326326

327+
POLYFILL
328+
Edge is a bit lagging behind, but there's a polyfill <https://github.com/webcomponents/webcomponentsjs> that covers
329+
327330
Далее мы перейдём к изучению дополнительных возможностей по работе с DOM.

Diff for: 8-web-components/3-shadow-dom/article.md

+53-8
Original file line numberDiff line numberDiff line change
@@ -75,16 +75,15 @@ That's how it looks in Chrome dev tools:
7575

7676
**Shadow DOM is strongly delimited from the main document:**
7777

78-
1. Shadow tree has own stylesheets. Style rules from the outer DOM don't get applied.
79-
2. Shadow tree is not visible by `document.querySelector`.
80-
3. Shadow tree element ids may match those in the outer document. They be unique only within the shadow tree.
78+
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.
79+
2. Shadow DOM has own stylesheets. Style rules from the outer DOM don't get applied.
8180

8281
For example:
8382

8483
```html run untrusted height=40
8584
<style>
8685
*!*
87-
/* document style not applied to shadow tree (2) */
86+
/* document style doesn't apply to shadow tree (2) */
8887
*/!*
8988
p { color: red; }
9089
</style>
@@ -94,15 +93,15 @@ For example:
9493
<script>
9594
elem.attachShadow({mode: 'open'});
9695
*!*
97-
// inner style is applied to shadow tree (1)
96+
// shadow tree has its own style (1)
9897
*/!*
9998
elem.shadowRoot.innerHTML = `
10099
<style> p { font-weight: bold; } </style>
101100
<p>Hello, John!</p>
102101
`;
103102
104103
*!*
105-
// <p> is only visible from inside the shadow tree (3)
104+
// <p> is only visible from queries inside the shadow tree (3)
106105
*/!*
107106
alert(document.querySelectorAll('p').length); // 0
108107
alert(elem.shadowRoot.querySelectorAll('p').length); // 1
@@ -120,9 +119,55 @@ The element with a shadow root is called a "shadow tree host", and is available
120119
alert(elem.shadowRoot.host === elem); // true
121120
```
122121

123-
## Composition
124122

125-
We can create "slotted" components, e.g. articles, tabs, menus, that can be filled by
123+
## Slots, composition
124+
125+
Quite often, our components should be generic. Like tabs, menus, etc -- we should be able to fill them with content.
126+
127+
Something like this:
128+
129+
<custom-menu>
130+
<title>Please choose:</title>
131+
<item>Candy</item>
132+
<item>
133+
<div slot="birthday">01.01.2001</div>
134+
<p>I am John</p>
135+
</user-card>
136+
137+
138+
Let's say we need to create a `<user-card>` custom element, for showing user cards.
139+
140+
```html run
141+
<user-card>
142+
<p>Hello</p>
143+
<div slot="username">John Smith</div>
144+
<div slot="birthday">01.01.2001</div>
145+
<p>I am John</p>
146+
</user-card>
147+
148+
<script>
149+
customElements.define('user-card', class extends HTMLElement {
150+
connectedCallback() {
151+
this.attachShadow({mode: 'open'});
152+
this.shadowRoot = `
153+
<slot name="username"></slot>
154+
<slot name="birthday"></slot>
155+
<slot></slot>
156+
`;
157+
}
158+
});
159+
</script>
160+
```
161+
162+
163+
164+
165+
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.
166+
167+
Another developer should be able to add `<user-card>` on the page
168+
169+
170+
Shadow DOM with "slots", e.g. articles, tabs, menus, that can be filled by
126171

127172
polyfill https://github.com/webcomponents/webcomponentsjs
128173

Diff for: 8-web-components/4-template-tag/article.md

+67-28
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,92 @@
11

2-
# Шаблоны <template>
2+
# Template tags
33

4-
Элемент `<template>` предназначен для хранения "образца" разметки, невидимого и предназначенного для вставки куда-либо.
4+
A built-in `<template>` element serves as a storage for markup. The browser ignores it contents, only checks for syntax validity.
55

6-
Конечно, есть много способов записать произвольный невидимый текст в HTML. В чём же особенность `<template>`?
6+
Of course, there are many ways to create an invisible element somewhere in HTML for markup purposes. What's special about `<template>`?
77

8-
Его отличие от обычных тегов в том, что его содержимое обрабатывается особым образом. Оно не только скрыто, но и считается находящимся вообще "вне документа". А при вставке автоматически "оживает", выполняются из него скрипты, начинает проигрываться видео и т.п.
8+
First, as the content is ignored, it can be any valid HTML.
99

10-
Содержимое тега `<template>`, в отличие, к примеру, от шаблонов или `<script type="неизвестный тип">`, обрабатывается браузером. А значит, должно быть корректным HTML.
10+
For example, we can put there a table row `<tr>`:
11+
```html
12+
<template>
13+
<tr>
14+
<td>Contents</td>
15+
</tr>
16+
</template>
17+
```
18+
19+
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.
20+
21+
We can put there styles:
22+
23+
```html
24+
<template>
25+
<style>
26+
p { font-weight: bold; }
27+
</style>
28+
</template>
29+
```
1130

12-
Оно доступно как `DocumentFragment` в свойстве тега `content`. Предполагается, что мы, при необходимости, возьмём `content` и вставим, куда надо.
31+
The browser considers `<template>` content "out of the document", so the style is not applied.
1332

14-
## Вставка шаблона
33+
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.
1534

16-
Пример вставки шаблона `tmpl` в Shadow DOM элемента `elem`:
35+
## Inserting template
1736

18-
```html run autorun="no-epub"
19-
<p id="elem">
20-
Доброе утро, страна!</p>
37+
The template content is available in its `content` property as a `DocumentFragment` -- a special type of DOM node.
2138

39+
We can treat it as any other DOM node, except one special property: when we insert it somewhere, its children are inserted instead.
40+
41+
For example, let's rewrite a Shadow DOM example from the previous chapter using `<template>`:
42+
43+
```html run untrusted autorun="no-epub" height=60
2244
<template id="tmpl">
23-
<h3><content></content></h3>
24-
<p>Привет из подполья!</p>
25-
<script>
26-
document.write('...document.write:Новость!');
27-
</script>
45+
<style> p { font-weight: bold; } </style>
46+
<script> alert("I am alive!"); </script>
47+
<p id="message"></p>
2848
</template>
2949

50+
<div id="elem">Click me</div>
51+
3052
<script>
31-
var root = elem.createShadowRoot();
32-
root.appendChild(tmpl.content.cloneNode(true));
53+
elem.onclick = function() {
54+
elem.attachShadow({mode: 'open'});
55+
56+
*!*
57+
elem.shadowRoot.append(tmpl.content.cloneNode(true)); // (*)
58+
*/!*
59+
60+
elem.shadowRoot.getElementById('message').innerHTML = "Hello from the shadows!";
61+
};
3362
</script>
3463
```
3564

36-
У нас получилось, что:
65+
In the line `(*)` when we clone and insert `tmpl.content`, its children (`<style>`, `<p>`) are inserted instead, they form the shadow DOM:
3766

38-
1. В элементе `#elem` содержатся данные в некоторой оговорённой разметке.
39-
2. Шаблон `#tmpl` указывает, как их отобразить, куда и в какие HTML-теги завернуть содержимое `#elem`.
40-
3. Здесь шаблон показывается в Shadow DOM тега. Технически, это не обязательно, шаблон можно использовать и без Shadow DOM, но тогда не сработает тег `<content>`.
67+
```html
68+
<div id="elem">
69+
#shadow-root
70+
<style> p { font-weight: bold; } </style>
71+
<script> alert("I am alive!"); </script>
72+
<p id="message"></p>
73+
</div>
74+
```
4175

42-
Можно также заметить, что скрипт из шаблона выполнился. Это важнейшее отличие вставки шаблона от вставки HTML через `innerHTML` и от обычного `DocumentFragment`.
76+
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.
4377

44-
Также мы вставили не сам `tmpl.content`, а его клон. Это обычная практика, чтобы можно было использовать один шаблон много раз.
78+
## Summary
4579

46-
## Итого
80+
To summarize:
4781

48-
Тег `<template>` не призван заменить системы шаблонизации. В нём нет хитрых операторов итерации, привязок к данным.
82+
- `<template>` content can be any syntactically correct HTML.
83+
- `<template>` content is considered "out of the document", so it doesn't affect anything.
84+
- We can access `template.content` from JavaScript, clone it to render new component or for other purposes.
4985

50-
Его основная особенность -- это возможность вставки "живого" содержимого, вместе со скриптами.
86+
The `<template>` tag is quite unique, because:
5187

52-
И, конечно, мелочь, но удобно, что он не требует никаких библиотек.
88+
- The browser checks the syntax inside it (as opposed to using a template string inside a script).
89+
- ...But still allows to use any top-level HTML tags, even those that don't make sense without proper wrappers (e.g. `<tr>`).
90+
- 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).
5391

92+
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.

0 commit comments

Comments
 (0)