Skip to content

Commit ea8f513

Browse files
authored
Merge pull request #550 from joaquinelio/shave
Shadow DOM and events
2 parents 0b3902b + 3ca282b commit ea8f513

File tree

1 file changed

+45
-45
lines changed

1 file changed

+45
-45
lines changed

8-web-components/7-shadow-dom-events/article.md

Lines changed: 45 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# Shadow DOM and events
1+
# Shadow DOM y eventos
22

3-
The idea behind shadow tree is to encapsulate internal implementation details of a component.
3+
La idea detrás del shadow tree es encapsular los detalles internos de implementación de un componente.
44

5-
Let's say, a click event happens inside a shadow DOM of `<user-card>` component. But scripts in the main document have no idea about the shadow DOM internals, especially if the component comes from a 3rd-party library.
5+
Digamos que ocurre un evento click dentro de un shadow DOM del componente `<user-card>`. Pero los scripts en el documento principal no tienen idea acerca del interior del shadow DOM, especialmente si el componente es de una librería de terceros.
66

7-
So, to keep the details encapsulated, the browser *retargets* the event.
7+
Entonces, para mantener los detalles encapsulados, el navegador *redirige* el evento.
88

9-
**Events that happen in shadow DOM have the host element as the target, when caught outside of the component.**
9+
**Los eventos que ocurren en el shadow DOM tienen el elemento host como objetivo cuando son atrapados fuera del componente.**
1010

11-
Here's a simple example:
11+
Un ejemplo simple:
1212

1313
```html run autorun="no-epub" untrusted height=60
1414
<user-card></user-card>
@@ -30,16 +30,16 @@ document.onclick =
3030
</script>
3131
```
3232

33-
If you click on the button, the messages are:
33+
Si haces clic en el botón, los mensajes son:
3434

35-
1. Inner target: `BUTTON` -- internal event handler gets the correct target, the element inside shadow DOM.
36-
2. Outer target: `USER-CARD` -- document event handler gets shadow host as the target.
35+
1. Inner target: `BUTTON` -- el manejador de evento interno obtiene el objetivo correcto, el elemento dentro del shadow DOM.
36+
2. Outer target: `USER-CARD` -- el manejador de evento del documento obtiene el shadow host como objetivo.
3737

38-
Event retargeting is a great thing to have, because the outer document doesn't have to know about component internals. From its point of view, the event happened on `<user-card>`.
38+
Tener la "redirección de eventos" es muy bueno, porque el documento externo no necesita tener conocimiento acerca del interior del componente. Desde su punto de vista, el evento ocurrió sobre `<user-card>`.
3939

40-
**Retargeting does not occur if the event occurs on a slotted element, that physically lives in the light DOM.**
40+
**No hay redirección si el evento ocurre en un elemento eslotado (slot element), que físicamente se aloja en el "light DOM", el DOM visible.**
4141

42-
For example, if a user clicks on `<span slot="username">` in the example below, the event target is exactly this `span` element, for both shadow and light handlers:
42+
Por ejemplo, si un usuario hace clic en `<span slot="username">` en el ejemplo siguiente, el objetivo del evento es precisamente ese elemento `span` para ambos manejadores, shadow y light.
4343

4444
```html run autorun="no-epub" untrusted height=60
4545
<user-card id="userCard">
@@ -65,19 +65,19 @@ userCard.onclick = e => alert(`Outer target: ${e.target.tagName}`);
6565
</script>
6666
```
6767

68-
If a click happens on `"John Smith"`, for both inner and outer handlers the target is `<span slot="username">`. That's an element from the light DOM, so no retargeting.
68+
Si un clic ocurre en `"John Smith"`, el target es `<span slot="username">` para ambos manejadores: el interno y el externo. Es un elemento del light DOM, entonces no hay redirección.
6969

70-
On the other hand, if the click occurs on an element originating from shadow DOM, e.g. on `<b>Name</b>`, then, as it bubbles out of the shadow DOM, its `event.target` is reset to `<user-card>`.
70+
Por otro lado, si el clic ocurre en un elemento originalmente del shadow DOM, ej. en `<b>Name</b>`, entonces, como se propaga hacia fuera del shadow DOM, su `event.target` se reestablece a `<user-card>`.
7171

72-
## Bubbling, event.composedPath()
72+
## Propagación, event.composedPath()
7373

74-
For purposes of event bubbling, flattened DOM is used.
74+
Para el propósito de propagación de eventos, es usado un "flattened DOM" (DOM aplanado, fusión de light y shadow).
7575

76-
So, if we have a slotted element, and an event occurs somewhere inside it, then it bubbles up to the `<slot>` and upwards.
76+
Así, si tenemos un elemento eslotado y un evento ocurre dentro, entonces se propaga hacia arriba a `<slot>` y más allá.
7777

78-
The full path to the original event target, with all the shadow elements, can be obtained using `event.composedPath()`. As we can see from the name of the method, that path is taken after the composition.
78+
La ruta completa del destino original "event target", con todos sus elementos shadow, puede ser obtenida usando `event.composedPath()`. Como podemos ver del nombre del método, la ruta se toma despúes de la composición.
7979

80-
In the example above, the flattened DOM is:
80+
En el ejemplo de arriba, el "flattened DOM" es:
8181

8282
```html
8383
<user-card id="userCard">
@@ -92,45 +92,45 @@ In the example above, the flattened DOM is:
9292
```
9393

9494

95-
So, for a click on `<span slot="username">`, a call to `event.composedPath()` returns an array: [`span`, `slot`, `div`, `shadow-root`, `user-card`, `body`, `html`, `document`, `window`]. That's exactly the parent chain from the target element in the flattened DOM, after the composition.
95+
Entonces, para un clic sobre `<span slot="username">`, una llamada a `event.composedPath()` devuelve un array: [`span`, `slot`, `div`, `shadow-root`, `user-card`, `body`, `html`, `document`, `window`]. Que es precisamente la cadena de padres desde el elemento target en el flattened DOM, después de la composición.
9696

97-
```warn header="Shadow tree details are only provided for `{mode:'open'}` trees"
98-
If the shadow tree was created with `{mode: 'closed'}`, then the composed path starts from the host: `user-card` and upwards.
97+
```warn header="Los detalles del árbol Shadow solo son provistos en árboles con `{mode:'open'}`"
98+
Si el árbol shadow fue creado con `{mode: 'closed'}`, la ruta compuesta comienza desde el host: `user-card` en adelante.
9999

100-
That's the similar principle as for other methods that work with shadow DOM. Internals of closed trees are completely hidden.
100+
Este principio es similar a otros métodos que trabajan con el shadow DOM. El interior de árboles cerrados está completamente oculto.
101101
```
102102
103103
104104
## event.composed
105105
106-
Most events successfully bubble through a shadow DOM boundary. There are few events that do not.
106+
La mayoría de los eventos se propagan exitosamente a través de los límites de un shadow DOM. Hay unos pocos eventos que no.
107107
108-
This is governed by the `composed` event object property. If it's `true`, then the event does cross the boundary. Otherwise, it only can be caught from inside the shadow DOM.
108+
Esto está gobernado por la propiedad `composed` del objeto de evento. Si es `true`, el evento cruza los límites. Si no, solamente puede ser capturado dentro del shadow DOM.
109109
110-
If you take a look at [UI Events specification](https://www.w3.org/TR/uievents), most events have `composed: true`:
110+
Vemos en la [especificación UI Events](https://www.w3.org/TR/uievents) que la mayoría de los eventos tienen `composed: true`:
111111
112112
- `blur`, `focus`, `focusin`, `focusout`,
113113
- `click`, `dblclick`,
114114
- `mousedown`, `mouseup` `mousemove`, `mouseout`, `mouseover`,
115115
- `wheel`,
116116
- `beforeinput`, `input`, `keydown`, `keyup`.
117117
118-
All touch events and pointer events also have `composed: true`.
118+
Todos los eventos de toque y puntero también tienen `composed: true`.
119119
120-
There are some events that have `composed: false` though:
120+
Algunos eventos tienen `composed: false`:
121121
122-
- `mouseenter`, `mouseleave` (they do not bubble at all),
122+
- `mouseenter`, `mouseleave` (que no se propagan en absoluto),
123123
- `load`, `unload`, `abort`, `error`,
124124
- `select`,
125125
- `slotchange`.
126126
127-
These events can be caught only on elements within the same DOM, where the event target resides.
127+
Estos eventos solo pueden ser capturados dentro del mismo DOM, donde reside el evento target.
128128
129-
## Custom events
129+
## Eventos personalizados
130130
131-
When we dispatch custom events, we need to set both `bubbles` and `composed` properties to `true` for it to bubble up and out of the component.
131+
Cuando enviamos eventos personalizados, necesitamos establecer ambas propiedades `bubbles` y `composed` a `true` para que se propague hacia arriba y afuera del componente.
132132
133-
For example, here we create `div#inner` in the shadow DOM of `div#outer` and trigger two events on it. Only the one with `composed: true` makes it outside to the document:
133+
Por ejemplo, aquí creamos `div#inner` en el shadow DOM de `div#outer` y disparamos dos eventos en él. Solo el que tiene `composed: true` logra salir hacia el documento:
134134
135135
```html run untrusted height=0
136136
<div id="outer"></div>
@@ -167,26 +167,26 @@ inner.dispatchEvent(new CustomEvent('test', {
167167
</script>
168168
```
169169

170-
## Summary
170+
## Resumen
171171

172-
Events only cross shadow DOM boundaries if their `composed` flag is set to `true`.
172+
Los eventos solo cruzan los límites de shadow DOM si su bandera `composed` se establece como `true`.
173173

174-
Built-in events mostly have `composed: true`, as described in the relevant specifications:
174+
La mayoría de los eventos nativos tienen `composed: true`, tal como se describe en las especificaciones relevantes:
175175

176-
- UI Events <https://www.w3.org/TR/uievents>.
177-
- Touch Events <https://w3c.github.io/touch-events>.
178-
- Pointer Events <https://www.w3.org/TR/pointerevents>.
179-
- ...And so on.
176+
- Eventos UI <https://www.w3.org/TR/uievents>.
177+
- Eventos Touch <https://w3c.github.io/touch-events>.
178+
- Eventos Pointer <https://www.w3.org/TR/pointerevents>.
179+
- ...y así.
180180

181-
Some built-in events that have `composed: false`:
181+
Algunos eventos nativos que tienen `composed: false`:
182182

183-
- `mouseenter`, `mouseleave` (also do not bubble),
183+
- `mouseenter`, `mouseleave` (que tampoco se propagan),
184184
- `load`, `unload`, `abort`, `error`,
185185
- `select`,
186186
- `slotchange`.
187187

188-
These events can be caught only on elements within the same DOM.
188+
Estos eventos solo pueden ser capturados en elementos dentro del mismo DOM.
189189

190-
If we dispatch a `CustomEvent`, then we should explicitly set `composed: true`.
190+
Si enviamos un evento personalizado `CustomEvent`, debemos establecer explícitamente `composed: true`.
191191

192-
Please note that in case of nested components, one shadow DOM may be nested into another. In that case composed events bubble through all shadow DOM boundaries. So, if an event is intended only for the immediate enclosing component, we can also dispatch it on the shadow host and set `composed: false`. Then it's out of the component shadow DOM, but won't bubble up to higher-level DOM.
192+
Tenga en cuenta que en caso de componentes anidados, un shadow DOM puede estar anidado dentro de otro. En ese caso los eventos se propagan a través de los límites de todos los shadow DOM. Entonces, si se pretende que un evento sea solo para el componente inmediato que lo encierra, podemos enviarlo también en el shadow host y establecer `composed: false`. Entonces saldrá al shadow DOM del componente, pero no se propagará hacia un DOM de mayor nivel.

0 commit comments

Comments
 (0)