Skip to content

Commit 6c0d96a

Browse files
traduzione
1 parent cdfdc60 commit 6c0d96a

File tree

1 file changed

+83
-83
lines changed

1 file changed

+83
-83
lines changed

8-web-components/5-slots-composition/article.md

Lines changed: 83 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11
# Shadow DOM slots, composition
22

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

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ù.
66

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:
88

99
```html
1010
<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>
1414
<item>Cup Cake</item>
1515
</custom-menu>
1616
```
1717

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

20-
How to implement it?
20+
Come si può implementare?
2121

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

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

2626
## Named slots
2727

28-
Let's see how slots work on a simple example.
28+
Diamo un'occhiata al funzionamento degli slots con un esempio basilare.
2929

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:
3131

3232
```html run autorun="no-epub" untrusted height=80
3333
<script>
@@ -56,11 +56,11 @@ customElements.define('user-card', class extends HTMLElement {
5656
</user-card>
5757
```
5858

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"`.
6060

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

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:
6464

6565
```html
6666
<user-card>
@@ -76,20 +76,20 @@ Here's the DOM structure after the script, not taking composition into account:
7676
</user-card>
7777
```
7878

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

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:
8282

8383
![](shadow-dom-user-card.svg)
8484

85-
The result is called "flattened" DOM:
85+
Il risultato viene soprannominato "flattened" DOM:
8686

8787
```html
8888
<user-card>
8989
#shadow-root
9090
<div>Name:
9191
<slot name="username">
92-
<!-- slotted element is inserted into the slot -->
92+
<!-- l'elemento slotted viene inserito nello slot -->
9393
<span slot="username">John Smith</span>
9494
</slot>
9595
</div>
@@ -101,43 +101,43 @@ The result is called "flattened" DOM:
101101
</user-card>
102102
```
103103

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!
105105

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

108108
```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>`
110110
alert( document.querySelectorAll('user-card span').length ); // 2
111111
```
112112

113-
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.
114114

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.
117117
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>`):
119119
```html
120120
<user-card>
121121
<span slot="username">John Smith</span>
122122
<div>
123-
<!-- invalid slot, must be direct child of user-card -->
123+
<!-- slot non valido, deve essere un figlio diretto di user-card -->
124124
<span slot="birthday">01.01.2001</span>
125125
</div>
126126
</user-card>
127127
```
128128
````
129129

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

132-
For example, this:
132+
Per esempio, qui abbiamo:
133133
```html
134134
<user-card>
135135
<span slot="username">John</span>
136136
<span slot="username">Smith</span>
137137
</user-card>
138138
```
139139

140-
Gives this flattened DOM with two elements in `<slot name="username">`:
140+
Restituisce questo flattened DOM con due elementi dentro `<slot name="username">`:
141141

142142
```html
143143
<user-card>
@@ -156,21 +156,21 @@ Gives this flattened DOM with two elements in `<slot name="username">`:
156156

157157
## Slot fallback content
158158

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

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

163163
```html
164164
<div>Name:
165165
<slot name="username">Anonymous</slot>
166166
</div>
167167
```
168168

169-
## Default slot: first unnamed
169+
## Slot "default": il primo senza nome
170170

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

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:
174174

175175
```html run autorun="no-epub" untrusted height=140
176176
<script>
@@ -197,21 +197,21 @@ customElements.define('user-card', class extends HTMLElement {
197197

198198
<user-card>
199199
*!*
200-
<div>I like to swim.</div>
200+
<div>Mi piace nuotare.</div>
201201
*/!*
202202
<span slot="username">John Smith</span>
203203
<span slot="birthday">01.01.2001</span>
204204
*!*
205-
<div>...And play volleyball too!</div>
205+
<div>...ed anche giocare a pallavolo!</div>
206206
*/!*
207207
</user-card>
208208
```
209209

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".
211211

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

214-
The flattened DOM looks like this:
214+
Il flattened DOM apparirà come questo:
215215

216216
```html
217217
<user-card>
@@ -238,24 +238,24 @@ The flattened DOM looks like this:
238238
</user-card>
239239
```
240240

241-
## Menu example
241+
## Esempio di menù
242242

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

245-
We can use slots to distribute elements.
245+
Possiamo usare gli slot per distribuire gli elementi.
246246

247-
Here's the markup for `<custom-menu>`:
247+
Ecco il markup per il `<custom-menu>`:
248248

249249
```html
250250
<custom-menu>
251-
<span slot="title">Candy menu</span>
252-
<li slot="item">Lollipop</li>
253-
<li slot="item">Fruit Toast</li>
251+
<span slot="title">Menù dei dolciumi</span>
252+
<li slot="item">Lecca-lecca</li>
253+
<li slot="item">Toast alla frutta</li>
254254
<li slot="item">Cup Cake</li>
255255
</custom-menu>
256256
```
257257

258-
The shadow DOM template with proper slots:
258+
Invece il template dello shadow DOM con gli slot appropriati:
259259

260260
```html
261261
<template id="tmpl">
@@ -267,72 +267,72 @@ The shadow DOM template with proper slots:
267267
</template>
268268
```
269269

270-
1. `<span slot="title">` goes into `<slot name="title">`.
271-
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.
272272

273-
The flattened DOM becomes:
273+
Il flattened DOM diventa:
274274

275275
```html
276276
<custom-menu>
277277
#shadow-root
278278
<style> /* menu styles */ </style>
279279
<div class="menu">
280280
<slot name="title">
281-
<span slot="title">Candy menu</span>
281+
<span slot="title">Menù dei dolciumi</span>
282282
</slot>
283283
<ul>
284284
<slot name="item">
285-
<li slot="item">Lollipop</li>
286-
<li slot="item">Fruit Toast</li>
285+
<li slot="item">Lecca-lecca</li>
286+
<li slot="item">Toast alla frutta</li>
287287
<li slot="item">Cup Cake</li>
288288
</slot>
289289
</ul>
290290
</div>
291291
</custom-menu>
292292
```
293293

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

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:
297297

298298
```js
299299
customElements.define('custom-menu', class extends HTMLElement {
300300
connectedCallback() {
301301
this.attachShadow({mode: 'open'});
302302

303-
// tmpl is the shadow DOM template (above)
303+
// tmpl e' il template dello shadow DOM (sopra)
304304
this.shadowRoot.append( tmpl.content.cloneNode(true) );
305305

306-
// we can't select light DOM nodes, so let's handle clicks on the slot
306+
// non possiamo selezionare nodi del light DOM, quindi andiamo a gestire gli eventi nello slot
307307
this.shadowRoot.querySelector('slot[name="title"]').onclick = () => {
308-
// open/close the menu
308+
// apre e chiude il menu'
309309
this.shadowRoot.querySelector('.menu').classList.toggle('closed');
310310
};
311311
}
312312
});
313313
```
314314

315-
Here's the full demo:
315+
Ecco la demo completa:
316316

317317
[iframe src="menu" height=140 edit]
318318

319-
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.
320320

321-
## Updating slots
321+
## Aggiornamento degli slots
322322

323-
What if the outer code wants to add/remove menu items dynamically?
323+
E se volessimo aggiungere e rimuovere elementi del menù dinamicamente?
324324

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.**
326326

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

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

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:
332332

333333
```html run untrusted height=80
334334
<custom-menu id="menu">
335-
<span slot="title">Candy menu</span>
335+
<span slot="title">Menù dei dolciumi</span>
336336
</custom-menu>
337337

338338
<script>
@@ -344,46 +344,46 @@ customElements.define('custom-menu', class extends HTMLElement {
344344
<ul><slot name="item"></slot></ul>
345345
</div>`;
346346
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
348348
this.shadowRoot.firstElementChild.addEventListener('slotchange',
349349
e => alert("slotchange: " + e.target.name)
350350
);
351351
}
352352
});
353353
354354
setTimeout(() => {
355-
menu.insertAdjacentHTML('beforeEnd', '<li slot="item">Lollipop</li>')
355+
menu.insertAdjacentHTML('beforeEnd', '<li slot="item">Lecca-lecca</li>')
356356
}, 1000);
357357
358358
setTimeout(() => {
359-
menu.querySelector('[slot="title"]').innerHTML = "New menu";
359+
menu.querySelector('[slot="title"]').innerHTML = "Nuovo menù";
360360
}, 2000);
361361
</script>
362362
```
363363

364-
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.
365365

366-
There are two `slotchange` events here:
366+
In questo esempio, ci sono due eventi `slotchange`:
367367

368-
1. At initialization:
368+
1. Nella inizializzazione:
369369

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:
372372

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">`.
374374

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

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).
378378

379379
## Slot API
380380

381-
Finally, let's mention the slot-related JavaScript methods.
381+
Infine, citiamo i metodi JavaScript inerenti gli slots.
382382

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:
384384

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.
387387
- `slot.assignedElements({flatten: true/false})` -- DOM elements, assigned to the slot (same as above, but only element nodes).
388388

389389
These methods are useful when we need not just show the slotted content, but also track it in JavaScript.

0 commit comments

Comments
 (0)