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
Copy file name to clipboardExpand all lines: 8-web-components/5-slots-composition/article.md
+83-83Lines changed: 83 additions & 83 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,33 +1,33 @@
1
1
# Shadow DOM slots, composition
2
2
3
-
Many types of components, such as tabs, menus, image galleries, and so on, need the content to render.
3
+
Molti tipi di components, come tabs, menù, gallerie di immagini e così via, necessitano di contenuti da visualizzare.
4
4
5
-
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.
5
+
Proprio come gli elementi built-in del browser, dove `<select>`si aspetta degli elementi `<option>`, i nostri `<custom-tabs>`potrebbero aspettarsi che gli venga passato l'attuale contenuto del tab. Ed un`<custom-menu>`, ad esempio, si aspetterebbe degli elemetni del menù.
6
6
7
-
The code that makes use of`<custom-menu>`can look like this:
7
+
Il codice che fa uso del`<custom-menu>`potrebbe essere questo:
8
8
9
9
```html
10
10
<custom-menu>
11
-
<title>Candy menu</title>
12
-
<item>Lollipop</item>
13
-
<item>Fruit Toast</item>
11
+
<title>Menù dei dolciumi</title>
12
+
<item>Lecca-lecca</item>
13
+
<item>Toast alla frutta</item>
14
14
<item>Cup Cake</item>
15
15
</custom-menu>
16
16
```
17
17
18
-
...Then our component should render it properly, as a nice menu with given title and items, handle menu events, etc.
18
+
...Quindi il nostro "component" dovrebbe visualizzarsi correttamente, come un menù con titolo e relativi elementi, gestione degli eventi e tutto il resto...
19
19
20
-
How to implement it?
20
+
Come si può implementare?
21
21
22
-
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.
22
+
Possiamo provare ad analizzare il contenuto dell'elemento, e copiare e poi riarrangiare dinamicamente i nodi DOM. Ciò è sicuramente fattibile, ma se stiamo spostando gli elementi nello shadow DOM, e quindi gli stili CSS del documento non verranno applicati in quella sezione, potremmo perdere lo stile visuale. Ed anche questo richiederebbe un po' di gestione lato codice.
23
23
24
-
Luckily, we don't have to. Shadow DOM supports `<slot>` elements, that are automatically filled by the content from light DOM.
24
+
Fortunatamente, non è necessario. Lo Shadow DOM supporta gli elementi `<slot>`, che vengono automaticamente riempiti dal contenuto del light DOM.
25
25
26
26
## Named slots
27
27
28
-
Let's see how slots work on a simple example.
28
+
Diamo un'occhiata al funzionamento degli slots con un esempio basilare.
29
29
30
-
Here, `<user-card>`shadow DOM provides two slots, filled from light DOM:
30
+
Qui, lo shadow DOM `<user-card>`fornisce due slots, riempiti dal light DOM:
31
31
32
32
```html run autorun="no-epub" untrusted height=80
33
33
<script>
@@ -56,11 +56,11 @@ customElements.define('user-card', class extends HTMLElement {
56
56
</user-card>
57
57
```
58
58
59
-
In the shadow DOM, `<slot name="X">`defines an "insertion point", a place where elements with `slot="X"` are rendered.
59
+
Nello shadow DOM, `<slot name="X">`definisce un "punto di inserimento", un posto dove vengono visualizzati gli elementi con `slot="X"`.
60
60
61
-
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 component that can be filled with data.
61
+
Quindi il browser esegue la "composizione": prende gli elementi dal light DOM e ne esegue il rendering negli slots corrispondenti dello shadow DOM. Quindi alla fine, avremo esattamente quello che vogliamo: un componente che può essere riempito con dei dati.
62
62
63
-
Here's the DOM structure after the script, not taking composition into account:
63
+
Ecco come sarà la struttura dopo lo script, senza il coinvolgimento della composition:
64
64
65
65
```html
66
66
<user-card>
@@ -76,20 +76,20 @@ Here's the DOM structure after the script, not taking composition into account:
76
76
</user-card>
77
77
```
78
78
79
-
We created the shadow DOM, so here it is, under`#shadow-root`. Now the element has both light and shadow DOM.
79
+
Abbiamo creato lo shadow DOM, quindi eccolo, dentro`#shadow-root`. Ora ha sia lo shadow che il light DOM.
80
80
81
-
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:
81
+
Per esigenze di rendering, per ogni`<slot name="...">`dello shadow DOM, il browser cerca uno`slot="..."`con lo stesso nome all'interno del light DOM. Questi elementi vengono renderizzati dentro gli slots:
82
82
83
83

84
84
85
-
The result is called "flattened" DOM:
85
+
Il risultato viene soprannominato "flattened" DOM:
86
86
87
87
```html
88
88
<user-card>
89
89
#shadow-root
90
90
<div>Name:
91
91
<slotname="username">
92
-
<!-- slotted element is inserted into the slot -->
92
+
<!--l'elemento slotted viene inserito nello slot -->
93
93
<spanslot="username">John Smith</span>
94
94
</slot>
95
95
</div>
@@ -101,43 +101,43 @@ The result is called "flattened" DOM:
101
101
</user-card>
102
102
```
103
103
104
-
...But the flattened DOM exists only for rendering and event-handling purposes. It's kind of "virtual". That's how things are shown. But the nodes in the document are actually not moved around!
104
+
...Ma il flattened DOM esiste poer scopi puramente di rendering e di gestione degli eventi. È come se fosse "virtuale". Le cose vengono mostrate così. Ma i nodi nel documento non vengono spostati!
105
105
106
-
That can be easily checked if we run `querySelectorAll`: nodes are still at their places.
106
+
Ciò può essere facilmente verificato se andiamo ad eseguire `querySelectorAll`: i nodi saranno al proprio posto.
107
107
108
108
```js
109
-
//light DOM <span> nodes are still at the same place, under `<user-card>`
109
+
//gli nodi degli <span> del light DOM sono ancora nella stessa posizione, dentro `<user-card>`
So, the flattened DOM is derived from shadow DOM by inserting slots. The browser renders it and uses for style inheritance, event propagation (more about that later). But JavaScript still sees the document "as is", before flattening.
113
+
Quindi, il flattened DOM deriva dallo shadow DOM andando ad inserire gli slots. Il browser ne effettua il rendering e li usa per ereditare gli stili e per la propagazione degli eventi (vedremo questi aspetti più avanti). Ma JavaScript vede ancora il documento "per quello che è", cioè come era prima del flattening.
114
114
115
-
````warn header="Only top-level children may have slot=\"...\"attribute"
116
-
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.
115
+
````warn header="Solo i figli top-level possono avere l'attributo slot=\"...\" "
116
+
L'attrbibuto `slot="..."` è valido solamente per i figli diretti dello shadow host (nel nostro esempio, l'elemento `<user-card>`). Per gli elementi annidati vengono ignorati.
117
117
118
-
For example, the second `<span>` here is ignored (as it's not a top-level child of `<user-card>`):
118
+
Ad esempio, qui il secondo `<span>` viene ignorato (dal momento che non è un figlio top-level di `<user-card>`):
119
119
```html
120
120
<user-card>
121
121
<span slot="username">John Smith</span>
122
122
<div>
123
-
<!-- invalid slot, must be direct child of user-card -->
123
+
<!-- slot non valido, deve essere un figlio diretto di user-card -->
124
124
<span slot="birthday">01.01.2001</span>
125
125
</div>
126
126
</user-card>
127
127
```
128
128
````
129
129
130
-
If there are multiple elements in light DOM with the same slot name, they are appended into the slot, one after another.
130
+
Se ci sono più elementi nel light DOM con lo stesso slot name, vengono inseriti nello slot, uno dopo l'altro, in successione.
131
131
132
-
For example, this:
132
+
Per esempio, qui abbiamo:
133
133
```html
134
134
<user-card>
135
135
<spanslot="username">John</span>
136
136
<spanslot="username">Smith</span>
137
137
</user-card>
138
138
```
139
139
140
-
Gives this flattened DOM with two elements in`<slot name="username">`:
140
+
Restituisce questo flattened DOM con due elementi dentro`<slot name="username">`:
141
141
142
142
```html
143
143
<user-card>
@@ -156,21 +156,21 @@ Gives this flattened DOM with two elements in `<slot name="username">`:
156
156
157
157
## Slot fallback content
158
158
159
-
If we put something inside a `<slot>`, it becomes the fallback, "default" content. The browser shows it if there's no corresponding filler in light DOM.
159
+
Se inseriamo qualcosa dentro uno `<slot>`, diverrà il contenuto di ripiego, quello "default". Il browser mostrerà questo, nel caso in cui non vi fossero contenuti corrispondenti nel light DOM.
160
160
161
-
For example, in this piece of shadow DOM, `Anonymous`renders if there's no`slot="username"`in light DOM.
161
+
Per esempio, in questo pezzo di shadow DOM, verrà visualizzato `Anonymous`se non ci sono`slot="username"`nel light DOM.
162
162
163
163
```html
164
164
<div>Name:
165
165
<slotname="username">Anonymous</slot>
166
166
</div>
167
167
```
168
168
169
-
## Default slot: first unnamed
169
+
## Slot "default": il primo senza nome
170
170
171
-
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.
171
+
Il primo`<slot>`dello shadow DOM privo di nome è uno slot "default". Esso riceve tutti i nodi dal light DOM che non sono stati slottati da nessuna parte.
172
172
173
-
For example, let's add the default slot to our `<user-card>`that shows all unslotted information about the user:
173
+
Per esempio, aggiungiamo lo slot default al nostro `<user-card>`che mostrerà tutte le informazioni non slottate dell'utente:
174
174
175
175
```html run autorun="no-epub" untrusted height=140
176
176
<script>
@@ -197,21 +197,21 @@ customElements.define('user-card', class extends HTMLElement {
197
197
198
198
<user-card>
199
199
*!*
200
-
<div>I like to swim.</div>
200
+
<div>Mi piace nuotare.</div>
201
201
*/!*
202
202
<spanslot="username">John Smith</span>
203
203
<spanslot="birthday">01.01.2001</span>
204
204
*!*
205
-
<div>...And play volleyball too!</div>
205
+
<div>...ed anche giocare a pallavolo!</div>
206
206
*/!*
207
207
</user-card>
208
208
```
209
209
210
-
All the unslotted light DOM content gets into the "Other information" fieldset.
210
+
Tutti i contenuti del light DOM non slottati andranno a finire dentro il fieldset "Other information".
211
211
212
-
Elements are appended to a slot one after another, so both unslotted pieces of information are in the default slot together.
212
+
Glie elementi vengono accodati su uno slot, uno dopo l'altro, quindi anche i pezzi di informazione non slottare vanno a finire dentro lo slot default tutti insieme.
213
213
214
-
The flattened DOM looks like this:
214
+
Il flattened DOM apparirà come questo:
215
215
216
216
```html
217
217
<user-card>
@@ -238,24 +238,24 @@ The flattened DOM looks like this:
238
238
</user-card>
239
239
```
240
240
241
-
## Menu example
241
+
## Esempio di menù
242
242
243
-
Now let's back to `<custom-menu>`, mentioned at the beginning of the chapter.
243
+
Torniamo adesso al `<custom-menu>`, citato all'inizio del capitolo.
244
244
245
-
We can use slots to distribute elements.
245
+
Possiamo usare gli slot per distribuire gli elementi.
246
246
247
-
Here's the markup for`<custom-menu>`:
247
+
Ecco il markup per il`<custom-menu>`:
248
248
249
249
```html
250
250
<custom-menu>
251
-
<spanslot="title">Candy menu</span>
252
-
<lislot="item">Lollipop</li>
253
-
<lislot="item">Fruit Toast</li>
251
+
<spanslot="title">Menù dei dolciumi</span>
252
+
<lislot="item">Lecca-lecca</li>
253
+
<lislot="item">Toast alla frutta</li>
254
254
<lislot="item">Cup Cake</li>
255
255
</custom-menu>
256
256
```
257
257
258
-
The shadow DOM template with proper slots:
258
+
Invece il template dello shadow DOM con gli slot appropriati:
259
259
260
260
```html
261
261
<templateid="tmpl">
@@ -267,72 +267,72 @@ The shadow DOM template with proper slots:
2.There are many`<li slot="item">` in the template, but only one`<slot name="item">`in the template. So all such`<li slot="item">`are appended to`<slot name="item">`one after another, thus forming the list.
270
+
1.`<span slot="title">`andrà a finire dentro`<slot name="title">`.
271
+
2.Ci sono tanti`<li slot="item">`, ma solo uno`<slot name="item">`nel template. Quindi tutti questi`<li slot="item">`verranno inseriti dentro`<slot name="item">`uno dopo l'altro, così da formare la lista.
272
272
273
-
The flattened DOM becomes:
273
+
Il flattened DOM diventa:
274
274
275
275
```html
276
276
<custom-menu>
277
277
#shadow-root
278
278
<style>/* menu styles */</style>
279
279
<divclass="menu">
280
280
<slotname="title">
281
-
<spanslot="title">Candy menu</span>
281
+
<spanslot="title">Menù dei dolciumi</span>
282
282
</slot>
283
283
<ul>
284
284
<slotname="item">
285
-
<lislot="item">Lollipop</li>
286
-
<lislot="item">Fruit Toast</li>
285
+
<lislot="item">Lecca-lecca</li>
286
+
<lislot="item">Toast alla frutta</li>
287
287
<lislot="item">Cup Cake</li>
288
288
</slot>
289
289
</ul>
290
290
</div>
291
291
</custom-menu>
292
292
```
293
293
294
-
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.
294
+
Qualcuno potrebbe fare notare che, in un DOM valido, un `<li>`dovrebbe essere figlio diretto di `<ul>`. Ma questo è un flattened DOM, che descrive come il componente verrà renderizzato, quindi è perfettamente regolare.
295
295
296
-
We just need to add a`click`handler to open/close the list, and the`<custom-menu>`is ready:
296
+
Dobbiamo solo aggiungere un gestire al`click`per aprire e chiudere la lista, ed il`<custom-menu>`sarà pronto:
Of course, we can add more functionality to it: events, methods and so on.
319
+
Certamente possiamo andare ad aggiungere più funzionalità: eventi metodi e via dicendo.
320
320
321
-
## Updating slots
321
+
## Aggiornamento degli slots
322
322
323
-
What if the outer code wants to add/remove menu items dynamically?
323
+
E se volessimo aggiungere e rimuovere elementi del menù dinamicamente?
324
324
325
-
**The browser monitors slots and updates the rendering if slotted elements are added/removed.**
325
+
**Il browser monitora dgli slots e aggiorna la visualizzazione all'inserimento o rimozione di elementi slottati.**
326
326
327
-
Also, as light DOM nodes are not copied, but just rendered in slots, the changes inside them immediately become visible.
327
+
Inoltre, dal momento che i nodi del light DOM non vengono copiati, ma solo visualizzati negli slots, le modifiche al loro interno divengono immmediatamente visibili.
328
328
329
-
So we don't have to do anything to update rendering. But if the component code wants to know about slot changes, then `slotchange` event is available.
329
+
Quindi non dobbiamo fare nulla per aggiornare la visualizzazione. Ma se il codice del componente vuole avere dei dettagli sulla modifica degli slots, allora si potrà usare l'evento `slotchange`.
330
330
331
-
For example, here the menu item is inserted dynamically after 1 second, and the title changes after 2 seconds:
331
+
Per esempio, qui l'elemento del menù viene inserito dinamicamente dopo un secondo, ed il titolo cambia dopo 2 secondi:
332
332
333
333
```html run untrusted height=80
334
334
<custom-menuid="menu">
335
-
<spanslot="title">Candy menu</span>
335
+
<spanslot="title">Menù dei dolciumi</span>
336
336
</custom-menu>
337
337
338
338
<script>
@@ -344,46 +344,46 @@ customElements.define('custom-menu', class extends HTMLElement {
344
344
<ul><slotname="item"></slot></ul>
345
345
</div>`;
346
346
347
-
// shadowRoot can't have event handlers, so using the first child
347
+
// shadowRoot non puo' gestori di evento, quindi usiamo il primo nodo figlio
The menu rendering updates each time without our intervention.
364
+
Il rendering del menù, viene aggiornato ogni volta senza la necessità di un nostro intervento.
365
365
366
-
There are two `slotchange` events here:
366
+
In questo esempio, ci sono due eventi `slotchange`:
367
367
368
-
1.At initialization:
368
+
1.Nella inizializzazione:
369
369
370
-
`slotchange: title`triggers immediately, as the `slot="title"`from the light DOM gets into the corresponding slot.
371
-
2.After 1 second:
370
+
`slotchange: title`viene scaturito immediatamente, dal momento che `slot="title"`dal light DOM va a finire nello slot corrispondente.
371
+
2.Dopo 1 secondo:
372
372
373
-
`slotchange: item`triggers, when a new `<li slot="item">` is added.
373
+
`slotchange: item`viene scaturito quando viene aggiunto un nuovo `<li slot="item">`.
374
374
375
-
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.
375
+
Norta bene: non ci sono eventi `slotchange`dopo 2 secondi, quando viene modificato il contenuto di `slot="title"`. Questo perché non ci sono modifiche slot. Abbiamo modificato il contenuto dentro l'elemento slotted, che è tutt'altra cosa.
376
376
377
-
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).
377
+
Se volessimo tenere traccia delle modifiche interne del light DOM tramite JavaScript, si potrebbe anche usare un meccanismo più generico: I[MutationObserver](info:mutation-observer).
378
378
379
379
## Slot API
380
380
381
-
Finally, let's mention the slot-related JavaScript methods.
381
+
Infine, citiamo i metodi JavaScript inerenti gli slots.
382
382
383
-
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:
383
+
Come già visto, JavaScript osserva il DOM "effettivo", privo di flattening. Ma, se lo shadow tree ha il `{mode: 'open'}`, possiamo vedere quali elementi vengono assegnati a uno slot e, vice versa, lo slot con l'elemento al suo interno:
384
384
385
-
-`node.assignedSlot` -- returns the`<slot>`element that the `node` is assigned to.
386
-
-`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.
385
+
-`node.assignedSlot` -- restiuisce l'elemento`<slot>`a cui è assegnato il `node`.
386
+
-`slot.assignedNodes({flatten: true/false})` -- nodi DOM, assegnati allo slot. L'opzione`flatten`è `false`di default. Se impostata 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.
387
387
-`slot.assignedElements({flatten: true/false})` -- DOM elements, assigned to the slot (same as above, but only element nodes).
388
388
389
389
These methods are useful when we need not just show the slotted content, but also track it in JavaScript.
0 commit comments