Skip to content

Shadow DOM and events #290

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 54 additions & 54 deletions 8-web-components/3-shadow-dom/article.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
# Shadow DOM

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.
Lo Shadow DOM serve all'incapsulamento e permette al componente di avere il proprio DOM "shadow", al quale il documento principale non può accedere nemmeno accidentalmente. Inoltre può avere regole di stile con scope locale e molto altro ancora.

## Built-in shadow DOM
## Shadow DOM built-in

Did you ever think how complex browser controls are created and styled?
Avete mai pensato a come, dei controlli così complessi come quelli del browser, vengono creati e stilizzati?

Such as `<input type="range">`:
Prendiamo `<input type="range">` come esempio:

<p>
<input type="range">
</p>

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.
Il browser usa la combinazione DOM e CSS internamente, per visualizzarli a schermo. Normalmente la struttura del DOM ci è invisibile, ma possiamo visualizzarla negli strumenti dello sviluppatore dei browser. Ad esempio, negli strumenti di sviluppo di Chrome, si può attivarne la visualizzazione nelle impostazioni generiche, l'opzione "Show user agent shadow DOM".

Then `<input type="range">` looks like this:
Così facendo `<input type="range">` verrà mostrato in questo modo:

![](shadow-dom-range.png)

What you see under `#shadow-root` is called "shadow DOM".
Quello che vediamo alla voce `#shadow-root` viene chiamato "Shadow DOM".

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.
Non possiamo lavorare sugli elementi built-in dello Shadow DOM tramite normale chiamate o selettori CSS. Non sono nodi figli normali, ma una potente tecnica di incapsulamento.

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:
Nell'esempio precedente, possiamo notare l'attributo `pseudo` che è molto utile. Non è un attributo standard, esiste per ragioni storiche e possiamo usarlo per stilizzare i sottoelementi tramite CSS, in questo modo:

```html run autorun
<style>
/* make the slider track red */
/* colora la traccia di rosso */
input::-webkit-slider-runnable-track {
background: red;
}
Expand All @@ -35,22 +35,22 @@ input::-webkit-slider-runnable-track {
<input type="range">
```

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.
Ripetiamolo ancora una volta, `pseudo` non è un attributo standard. Storicamente, i browser hanno cominciato a sperimentare con le strutture interne del DOM per implementare dei controlli, e con il passare del tempo, lo Shadow DOM è stato standardizzato per permettere a noi sviluppatori, di fare alla stessa maniera.

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.
Più avanti, utilizzeremo lo standard Shadow DOM moderno, nella sezione delle [specifiche DOM](https://dom.spec.whatwg.org/#shadow-trees) ed altre specifiche correlate.

## Shadow tree

A DOM element can have two types of DOM subtrees:
Un elemento DOM può contenere due tipi di sottoalberi:

1. Light tree -- a regular DOM subtree, made of HTML children. All subtrees that we've seen in previous chapters were "light".
2. Shadow tree -- a hidden DOM subtree, not reflected in HTML, hidden from prying eyes.
1. Light tree -- un normale sottoalbero DOM, fatto di figli HTML. Tutti i sottoalberi affrontati nei capitoli precedenti appartengono a questa categoria "light".
2. Shadow tree -- un sottoalbero DOM nascosto, senza un elemento corrispondente nell'HTML, nascosto da "occhi indiscreti".

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>.
Se un elemento li ha entrambi, il browser renderizza solo lo Shadow tree. Tuttavia possiamo impostare una sorta di composizione tra gli il light e lo Shadow tree. Vedremo in dettaglio l'argomento nell'apposita sezione <info:slots-composition>.

Shadow tree can be used in Custom Elements to hide component internals and apply component-local styles.
Lo Shadow tree può essere usato all'interno dei Custom Elements per nascondere i componenti interni ed applicare gli stili localmente all'interno componente.

For example, this `<show-hello>` element hides its internal DOM in shadow tree:
Per esempio, questo elemento, `<show-hello>` nasconde il suo DOM interno dell' Shadow tree:

```html run autorun height=60
<script>
Expand All @@ -67,46 +67,46 @@ customElements.define('show-hello', class extends HTMLElement {
<show-hello name="John"></show-hello>
```

That's how the resulting DOM looks in Chrome dev tools, all the content is under "#shadow-root":
Ecco come risulta il DOM, negli strumenti di sviluppo di Chrome, con il contenuto inserito in "#shadow-root":

![](shadow-dom-say-hello.png)

First, the call to `elem.attachShadow({mode: …})` creates a shadow tree.
Inizialmente, la chiamata a `elem.attachShadow({mode: …})` crea uno Shadow tree.

There are two limitations:
1. We can create only one shadow root per element.
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.
Ci sono due limitazioni:
1. Possiamo creare solo una Shadow root per ogni elemento.
2. L'elemento `elem` deve essere, o un elemento personalizzato, o uno tra questi elementi: "article", "aside", "blockquote", "body", "div", "footer", "h1..h6", "header", "main" "nav", "p", "section", o "span". Altri elementi, come ad esempio, `<img>`, non possono contenere uno Shadow tree.

The `mode` option sets the encapsulation level. It must have any of two values:
- `"open"` -- the shadow root is available as `elem.shadowRoot`.
L'opzione `mode` imposta il livello di incapsulamento. Le opzioni possibili sono:
- `"open"` -- la Shadow root è disponibile tramite `elem.shadowRoot`.

Any code is able to access the shadow tree of `elem`.
- `"closed"` -- `elem.shadowRoot` is always `null`.
Lo Shadow tree di `elem` è accessibile da qualunque punto del codice.
- `"closed"` -- `elem.shadowRoot` è sempre `null`.

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.
Lo Shadow DOM è accessibile esclusivamente dal riferimento restituito da `attachShadow` (il quale, con ogni probabilità, sarà nascosto dentro una classe. Shadow tree nativi del browser, come `<input type="range">`, appartengono a questa categoria, e non c'è modo di accedervi.

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.
La [Shadow root](https://dom.spec.whatwg.org/#shadowroot), restituita con `attachShadow`, è come un elemento: possiamo usare `innerHTML` o i metodi DOM, come `append`, per popolarlo di elementi.

The element with a shadow root is called a "shadow tree host", and is available as the shadow root `host` property:
L'elemento con una Shadow root viene invece chiamato "Shadow tree host", ed è disponibile attraverso la proprietà `host` della Shadow root:

```js
// assuming {mode: "open"}, otherwise elem.shadowRoot is null
// supponiamo di avere {mode: "open"}, altrimenti elem.shadowRoot sarebbe null
alert(elem.shadowRoot.host === elem); // true
```

## Encapsulation
## Incapsulamento

Shadow DOM is strongly delimited from the main document:
Vi è una separazione marcata tra lo Shadow DOM ed il documento principale:

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.
2. Shadow DOM has own stylesheets. Style rules from the outer DOM don't get applied.
1. Gli elementi dello Shadow DOM non sono rilevabili tramite `querySelector` del light DOM. In particolare, gli id degli elementi dello Shadow DOM, potrebbero andare in conflitto con quelli dell'albero del light DOM.
2. Lo Shadow DOM ha i suoi fogli di stile e le regole di stile del DOM esterno non vengono applicate.

For example:
Per esempio:

```html run untrusted height=40
<style>
*!*
/* document style won't apply to the shadow tree inside #elem (1) */
/* lo stile del documento non viene applicato allo Shadow tree contenuto in #elem (1) */
*/!*
p { color: red; }
</style>
Expand All @@ -116,42 +116,42 @@ For example:
<script>
elem.attachShadow({mode: 'open'});
*!*
// shadow tree has its own style (2)
// Lo Shadow tree possiede un proprio stile (2)
*/!*
elem.shadowRoot.innerHTML = `
<style> p { font-weight: bold; } </style>
<p>Hello, John!</p>
`;

*!*
// <p> is only visible from queries inside the shadow tree (3)
// <p> e' visibile solamente da queries dentro lo Shadow tree (3)
*/!*
alert(document.querySelectorAll('p').length); // 0
alert(elem.shadowRoot.querySelectorAll('p').length); // 1
</script>
```

1. The style from the document does not affect the shadow tree.
2. ...But the style from the inside works.
3. To get elements in shadow tree, we must query from inside the tree.
1. Lo stile del documento non influenza lo Shadow tree.
2. ...ma lo stile all'interno sì.
3. Per avere gli elementi dentro lo Shadow tree, dobbiamo fare le query da dentro l'albero.

## References
## Riferimenti

- DOM: <https://dom.spec.whatwg.org/#shadow-trees>
- Compatibility: <https://caniuse.com/#feat=shadowdomv1>
- 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`.
- Compatibilità: <https://caniuse.com/#feat=shadowdomv1>
- Lo Shadow DOM viene menzionato in molte altre specifiche, ad esempio in [DOM Parsing](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin) specifica che la Shadow root possiede la proprietà `innerHTML`.


## Summary
## Riepilogo

Shadow DOM is a way to create a component-local DOM.
Lo "Shadow DOM" è una modalità di creazione di un componente DOM locale.

1. `shadowRoot = elem.attachShadow({mode: open|closed})` -- creates shadow DOM for `elem`. If `mode="open"`, then it's accessible as `elem.shadowRoot` property.
2. We can populate `shadowRoot` using `innerHTML` or other DOM methods.
1. Il comando `shadowRoot = elem.attachShadow({mode: open|closed})` crea uno Shadow DOM per `elem`. Se `mode="open"`, allora sarà possibile accedervi attraverso la proprietà `elem.shadowRoot`.
2. Possiamo popolare `shadowRoot` usando `innerHTML` o altri metodi DOM.

Shadow DOM elements:
- Have their own ids space,
- Invisible to JavaScript selectors from the main document, such as `querySelector`,
- Use styles only from the shadow tree, not from the main document.
Gli elementi dello Shadow DOM:
- Hanno la loro area per gli id
- Sono invisibili ai selettori JavaScript dal documento principale, se cercati con `querySelector`
- Usano gli stili dello Shadow tree, e non quelli del documento principale.

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.
Lo Shadow DOM, se esiste, viene renderizzato dal browser al posto del cosiddetto "light DOM" (normali nodi figli). Nel capitolo <info:slots-composition> vedremo come comporli.
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy