diff --git a/2-ui/3-event-details/6-pointer-events/article.md b/2-ui/3-event-details/6-pointer-events/article.md index 658465d39..63c1743d7 100644 --- a/2-ui/3-event-details/6-pointer-events/article.md +++ b/2-ui/3-event-details/6-pointer-events/article.md @@ -1,30 +1,30 @@ -# Pointer events +# Eventos de puntero -Pointer events is a modern way to handle input from a variety of pointing devices, such as a mouse, a pen/stylus, a touchscreen and so on. +Los eventos de puntero son una forma moderna de manejar la entrada de una variedad de dispositivos señaladores, como un mouse, un lápiz, una pantalla táctil, etc. -## The brief history +## Una breve historia -Let's make a small overview, so that you understand the general picture and the place of Pointer Events among other event types. +Hagamos una pequeña descripción general para que comprenda la imagen general y el lugar de los Eventos de Puntero entre otros tipos de eventos. -- Long ago, in the past, there existed only mouse events. +- Hace mucho tiempo, en el pasado, solo existían eventos de mouse. - Then touch devices appeared. For the old code to work, they also generate mouse events. For instance, tapping generates `mousedown`. But mouse events were not good enough, as touch devices are more powerful in many aspects. For example, it's possible to touch multiple points at once, and mouse events don't have any properties for that. + Luego aparecieron los dispositivos táctiles. Para que el código antiguo funcione, también generan eventos de mouse. Por ejemplo, tocar genera `mousedown`. Pero los eventos del mouse no eran adecuados porque los dispositivos táctiles son más poderosos en muchos aspectos. Por ejemplo, es posible tocar varios puntos a la vez, y los eventos del mouse no tienen propiedades para eso. -- So touch events were introduced, such as `touchstart`, `touchend`, `touchmove`, that have touch-specific properties (we don't cover them in detail here, because pointer events are even better). +- Por lo tanto, se introdujeron eventos táctiles, como `touchstart`,`touchend`, `touchmove`, que tienen propiedades específicas de toque (no los cubrimos en detalle aquí, porque los eventos de puntero son aún mejores). - Still, it wasn't enough, as there are many other devices, such as pens, that have their own features. Also, writing a code that listens both touch and mouse events was cumbersome. + Aún así no fue suficiente, ya que hay muchos otros dispositivos, como los lápices, que tienen sus propias funciones. Además, escribir un código que escuchara ambos eventos, los táctiles y los del mouse era engorroso. -- To solve these issues, the new standard Pointer Events was introduced. It provides a single set of events for all kinds of pointing devices. +- Para resolver estos problemas, se introdujo el nuevo estándar: *Pointer Events*. Este proporciona un conjunto único de eventos para todo tipo de dispositivos señaladores. -As of now, [Pointer Events Level 2](https://www.w3.org/TR/pointerevents2/) specification is supported in all major browsers, while the [Pointer Events Level 3](https://w3c.github.io/pointerevents/) is in the works. Unless you code for Internet Explorer 10 or Safari 12 and below, there's no point in using mouse or touch events any more. We can switch to pointer events. +Al momento la especificación [Pointer Events Level 2](https://www.w3.org/TR/pointerevents2/) es compatible con todos los principales navegadores, mientras que [Pointer Events Level 3](https://w3c.github.io/pointerevents/) está en proceso. A menos que codifique para Internet Explorer 10 o Safari 12 y versiones anteriores, ya no tiene sentido usar el mouse o los eventos táctiles. Podemos cambiar a eventos de puntero. -That said, there are important peculiarities, one should know them to use them correctly and avoid extra surprises. We'll pay attention to them in this article. +Dicho esto, hay peculiaridades importantes, uno debe saber usarlas correctamente y evitar sorpresas adicionales. Les prestaremos atención en este artículo. -## Pointer event types +## Tipos de eventos de puntero -Pointer events are named similar to mouse events: +Los eventos de puntero se llaman de forma similar a los eventos del mouse: -| Pointer Event | Mouse event | +| Eventos de puntero | Eventos de mouse | |---------------|-------------| | `pointerdown` | `mousedown` | | `pointerup` | `mouseup` | @@ -37,193 +37,193 @@ Pointer events are named similar to mouse events: | `gotpointercapture` | - | | `lostpointercapture` | - | -As we can see, for every `mouse`, there's a `pointer` that plays a similar role. Also there are 3 additional pointer events that don't have a corresponding `mouse...` counterpart, we'll soon explain about them. +Como podemos ver, para cada `mouse`, hay un `pointer` que juega un papel similar. También hay 3 eventos de puntero adicionales que no tienen una contraparte correspondiente de `mouse ...`, pronto hablaremos sobre ellos. -```smart header="Replacing `mouse` with `pointer` in our code" -We can replace `mouse` events with `pointer` in our code and expect things to continue working fine with mouse. +```smart header="Remplazando *mouse* con *pointer* en nuestro código" +Podemos reemplazar los eventos `mouse` con `pointer` en nuestro código y esperar que las cosas sigan funcionando bien con el mouse. -The support for touch devices will also "magically" improve, but we'll probably need to add `touch-action: none` rule in CSS. See the details below in the section about `pointercancel`. +El soporte para dispositivos táctiles también mejorará "mágicamente", pero probablemente necesitemos agregar la regla `touch-action: none` en CSS. Vea los detalles a continuación en la sección sobre `pointercancel`. ``` -## Pointer event properties +## Propiedades de los eventos de puntero -Pointer events have the same properties as mouse events, such as `clientX/Y`, `target` etc, plus some extra: +Los eventos de puntero tienen las mismas propiedades que los eventos del mouse, como `clientX/Y`, `target`, etc., más algunos adicionales: -- `pointerId` - the unique identifier of the pointer causing the event. +- `pointerId` - el identificador único del puntero que causa el evento. - Allows to handle multiple pointers, such as a touchscreen with stylus and multi-touch (explained below). -- `pointerType` - the pointing device type, must be a string, one of: "mouse", "pen" or "touch". + Permite manejar múltiples punteros, como una pantalla táctil con lápiz y multitáctil (explicado a continuación). +- `pointerType` - el tipo de dispositivo señalador debe ser una cadena, uno de los siguientes: "mouse", "pen" o "touch". - We can use this property to react differently on various pointer types. -- `isPrimary` - `true` for the primary pointer (the first finger in multi-touch). + Podemos usar esta propiedad para reaccionar de manera diferente en varios tipos de punteros. +- `isPrimary` - `true` para el puntero principal (el primer dedo en multitáctil). -For pointers that measure a contact area and pressure, e.g. a finger on the touchscreen, the additional properties can be useful: +Para punteros que miden un área de contacto y presión, p. Ej. un dedo en la pantalla táctil, las propiedades adicionales pueden ser útiles: -- `width` - the width of of the area where the pointer touches the device. Where unsupported, e.g. for mouse it's always `1`. -- `height` - the height of of the area where the pointer touches the device. Where unsupported, always `1`. -- `pressure` - the pressure of the pointer tip, in range from 0 to 1. For devices that don't support pressure must be either `0.5` (pressed) or `0`. -- `tangentialPressure` - the normalized tangential pressure. -- `tiltX`, `tiltY`, `twist` - pen-specific properties that describe how the pen is positioned relative the surface. +- `width` - el ancho del área donde el puntero toca el dispositivo. Donde no sea compatible, como en el mouse, siempre es `1`. +- `height` - el alto del área donde el puntero toca el dispositivo. Donde no sea compatible, siempre es `1`. +- `pressure` - la presión de la punta del puntero, en el rango de 0 a 1. Para dispositivos que no soportan presión, debe ser `0.5` (presionada) o `0`. +- `tangentialPressure` - la presión tangencial normalizada. +- `tiltX`, `tiltY`, `twist` - propiedades específicas del lápiz que describen cómo se lo coloca en relación con la superficie. -These properties aren't very well supported across devices, so they are rarely used. You can find the details in the [specification](https://w3c.github.io/pointerevents/#pointerevent-interface) if needed. +Estas propiedades no son muy compatibles en todos los dispositivos, por lo que rara vez se utilizan. Puede encontrar los detalles en la [especificación](https://w3c.github.io/pointerevents/#pointerevent-interface) si lo necesita. -## Multi-touch +## Multi-touch (Multitáctil) -One of the things that mouse events totally don't support is multi-touch: a user can touch them in several places at once at their phone or tablet, perform special gestures. +Una de las cosas con las que los eventos del mouse no son compatibles es la propiedad multitáctil: un usuario puede tocarlos en varios lugares a la vez en su teléfono o tableta, realizar gestos especiales. -Pointer Events allow to handle multi-touch with the help of `pointerId` and `isPrimary` properties. +Los eventos de puntero permiten manejar multitáctiles con la ayuda de las propiedades `pointerId` e `isPrimary`. -Here's what happens when a user touches a screen at one place, and then puts another finger somewhere else on it: +Esto es lo que sucede cuando un usuario toca una pantalla en un lugar y luego coloca otro dedo en otro lugar: -1. At the first touch: - - `pointerdown` with `isPrimary=true` and some `pointerId`. -2. For the second finger and further touches: - - `pointerdown` with `isPrimary=false` and a different `pointerId` for every finger. +1. En el primer toque: + - `pointerdown` with `isPrimary=true` y algún `pointerId`. +2. Para el segundo dedo y toques posteriores: + - `pointerdown` con `isPrimary=false` y un diferente `pointerId` por cada dedo. -Please note: there `pointerId` is assigned not to the whole device, but for each touching finger. If we use 5 fingers to simultaneously touch the screen, we have 5 `pointerdown` events with respective coordinates and different `pointerId`. +Tenga en cuenta: el `pointerId` no se asigna a todo el dispositivo, sino a cada dedo que se toca. Si usamos 5 dedos para tocar simultáneamente la pantalla, tenemos 5 eventos `pointerdown` con coordenadas respectivas y diferentes `pointerId`. -The events associated with the first finger always have `isPrimary=true`. +Los eventos asociados con el primer dedo siempre tienen `isPrimary = true`. -We can track multiple touching fingers using their `pointerId`. When the user moves move and then detouches a finger, we get `pointermove` and `pointerup` events with the same `pointerId` as we had in `pointerdown`. +Podemos rastrear el toque de varios dedos usando sus `pointerId`. Cuando el usuario mueve y luego levanta un dedo, obtenemos los eventos `pointermove` y `pointerup` con el mismo `pointerId` que teníamos en `pointerdown`. ```online -Here's the demo that logs `pointerdown` and `pointerup` events: +Aquí está la demostración que registra los eventos `pointerdown` y `pointerup`: [iframe src="multitouch" edit height=200] -Please note: you must be using a touchscreen device, such as a phone or a tablet to actually see the difference. For single-touch devices, such as a mouse, there'll be always same `pointerId` with `isPrimary=true`, for all pointer events. +Tenga en cuenta que debe utilizar un dispositivo con pantalla táctil, como un teléfono o una tableta, para ver realmente la diferencia. Para dispositivos de un solo toque, como el de un mouse, siempre será el mismo `pointerId` con `isPrimary=true` para todos los eventos de puntero. ``` -## Event: pointercancel +## Evento: pointercancel -We've mentioned the importance of `touch-action: none` before. Now let's explain why, as skipping this may cause our interfaces to malfunction. +Ya hemos mencionado la importancia de `touch-action: none`. Ahora expliquemos por qué, ya que omitir esto puede hacer que nuestras interfaces funcionen mal. -The `pointercancel` event fires when there's an ongoing pointer interaction, and then something happens that causes it to be aborted, so that no more pointer events are generated. +El evento `pointercancel` se dispara cuando hay una interacción de puntero en curso, y luego sucede algo que hace que se anule, de modo que no se generan más eventos de puntero. -Such causes are: -- The pointer device hardware was disabled. -- The device orientation changed (tablet rotated). -- The browser decided to handle the interaction on its own, considering it a mouse gesture or zoom-and-pan action or something else. +Algunos causas son: +- Se deshabilitó el hardware del dispositivo de puntero. +- La orientación del dispositivo cambió (tableta rotada). +- El navegador decidió manejar la interacción por sí solo, considerándolo un gesto del mouse o una acción de zoom y panorámica u otra cosa. -We'll demonstrate `pointercancel` on a practical example to see how it affects us. +Demostraremos `pointercancel` en un ejemplo práctico para ver cómo nos afecta. -Let's say we're impelementing drag'n'drop for a ball, just as in the beginning of the article . +Digamos que estamos implementando arrastrar y soltar (drag'n'drop) en una pelota, como al principio del artículo . -Here are the flow of user actions and corresponding events: +A continuación, se muestra el flujo de acciones del usuario y los eventos correspondientes: -1) The user presses the mouse button on an image, to start dragging - - `pointerdown` event fires -2) Then they start dragging the image - - `pointermove` fires, maybe several times -3) Surprise! The browser has native drag'n'drop support for images, that kicks in and takes over the drag'n'drop process, thus generating `pointercancel` event. - - The browser now handles drag'n'drop of the image on its own. The user may even drag the ball image out of the browser, into their Mail program or a File Manager. - - No more `pointermove` events for us. +1) El usuario presiona el botón del mouse sobre una imagen para comenzar a arrastrar + - `pointerdown` el evento se dispara +2) Luego comienzan a arrastrar la imagen + - `pointermove` se dispara, tal vez varias veces +3) ¡Sorpresa! El navegador tiene soporte nativo de arrastrar y soltar para imágenes, que se dispara y se hace cargo del proceso de arrastrar y soltar, generando así el evento `pointercancel`. + - El navegador ahora maneja arrastrar y soltar la imagen por sí solo. El usuario puede incluso arrastrar la imagen de la bola fuera del navegador, a su programa de correo o al administrador de archivos. + - No más eventos `pointermove` para nosotros. -So the issue is that the browser "hijacks" the interaction: `pointercancel` fires and no more `pointermove` events are generated. +Así que el problema es que el navegador "secuestra" la interacción: `pointercancel` se dispara y no se generan más eventos de `pointermove`. ```online -Here's the demo with pointer events (only `up/down`, `move` and `cancel`) logged in the textarea: +Aquí está la demostración con eventos de puntero (solo `arriba / abajo`, `mover` y `cancelar`) registrados en el área de texto: [iframe src="ball" height=240 edit] ``` -We'd like to implement our own drag'n'drop, so let's tell the browser not to take it over. +Nos gustaría implementar nuestro propio arrastrar y soltar, así que digámosle al navegador que no se haga cargo. -**Prevent default browser actions to avoid `pointercancel`.** +**Evitar las acciones predeterminadas del navegador para prevenir `pointercancel`.** -We need to do two things: +Necesitaremos dos cosas: -1. Prevent native drag'n'drop from happening: - - Can do it by setting `ball.ondragstart = () => false`, just as described in the article . - - That works well for mouse events. -2. For touch devices, there are also touch-related browser actions. We'll have problems with them too. - - We can prevent them by setting `#ball { touch-action: none }` in CSS. - - Then our code will start working on touch devices. +1. Evitar que suceda la función nativa de arrastrar y soltar: + - Puede hacerlo configurando `ball.ondragstart = () => false`, tal como se describe en el artículo . + - Eso funciona bien para eventos de mouse. +2. Para los dispositivos táctiles, también existen acciones del navegador relacionadas con el tacto. También tendremos problemas con ellos. + - Podemos prevenirlos configurando `#ball{touch-action: none}` en CSS. + - Entonces nuestro código comenzará a funcionar en dispositivos táctiles. -After we do that, the events will work as intended, the browser won't hijack the process and emit no `pointercancel`. +Después de hacer eso, los eventos funcionarán según lo previsto, el navegador no secuestrará el proceso y no emitirá ningún `pointercancel`. ```online -This demo adds these lines: +Esta demostración agrega estas líneas: [iframe src="ball-2" height=240 edit] -As you can see, there's no `pointercancel` any more. +Como puede ver, ya no hay `pointercancel`. ``` -Now we can add the code to actually move the ball, and our drag'n'drop will work for mouse devices and touch devices. +Ahora podemos agregar el código para mover realmente la bola, y nuestro método de arrastrar y soltar funcionará en dispositivos de mouse y dispositivos táctiles. -## Pointer capturing +## Captura del puntero -Pointer capturing is a special feature of pointer events. +La captura de puntero es una característica especial de los eventos de puntero. -The idea is that we can "bind" all events with a particular `pointerId` to a given element. Then all subsequent events with the same `pointerId` will be retargeted to the same element. That is: the browser sets that element as the target and trigger associated handlers, no matter where it actually happened. +La idea es que podemos "vincular" todos los eventos con un `pointerId` particular a un elemento dado. Luego, todos los eventos posteriores con el mismo `pointerId` se redireccionarán al mismo elemento. Es decir: el navegador establece ese elemento como destino y dispara los controladores asociados, sin importar dónde sucedió realmente. -The related methods are: -- `elem.setPointerCapture(pointerId)` - binds the given `pointerId` to `elem`. -- `elem.releasePointerCapture(pointerId)` - unbinds the given `pointerId` from `elem`. +Los métodos relacionados son: +- `elem.setPointerCapture(pointerId)` - vincula el `pointerId` dado a `elem`. +- `elem.releasePointerCapture(pointerId)` - desvincula el `pointerId` dado del `elem`. -Such binding doesn't hold long. It's automatically removed after `pointerup` or `pointercancel` events, or when the target `elem` is removed from the document. +Tal unión no dura mucho. Se elimina automáticamente después de los eventos `pointerup` o `pointercancel`, o cuando el `elem` de destino se elimina del documento. -Now when do we need this? +Ahora, ¿cuándo necesitamos esto? -**Pointer capturing is used to simplify drag'n'drop kind of interactions.** +**La captura de puntero se utiliza para simplificar el tipo de interacciones de arrastrar y soltar.** -Let's recall the problem we met while making a custom slider in the article . +Recordemos el problema que encontramos al hacer un control deslizante personalizado en el artículo . -1) First, the user presses `pointerdown` on the slider thumb to start dragging it. -2) ...But then, as they move the pointer, it may leave the slider: go below or over it. +1) Primero, el usuario presiona `pointerdown` en el control deslizante para comenzar a arrastrarlo. +2) ...Pero luego, a medida que mueven el puntero, puede salirse del control deslizante: que vaya por debajo o por encima de él. -But we continue tracking track `pointermove` events and move the thumb until `pointerup`, even though the pointer is not on the slider any more. +Pero continuamos rastreando los eventos de la pista `pointermove` y movemos el pulgar hasta `pointerup`, aunque el puntero ya no esté en el control deslizante. -[Previously](info:mouse-drag-and-drop), to handle `pointermove` events that happen outside of the slider, we listened for `pointermove` events on the whole `document`. +[Anteriormente](info: mouse-drag-and-drop), para manejar los eventos `pointermove` que ocurrían fuera del control deslizante, escuchábamos los eventos `pointermove` en todo el `document`. -Pointer capturing provides an alternative solution: we can call `thumb.setPointerCapture(event.pointerId)` in `pointerdown` handler, and then all future pointer events until `pointerup` will be retargeted to `thumb`. +La captura de puntero proporciona una solución alternativa: podemos llamar a `thumb.setPointerCapture(event.pointerId)` en el controlador `pointerdown`, y luego a todos los eventos de puntero futuros hasta que `pointerup` se redireccione a `thumb`. -That is: events handlers on `thumb` will be called, and `event.target` will always be `thumb`, even if the user moves their pointer around the whole document. So we can listen at `thumb` for `pointermove`, no matter where it happens. +Es decir: se llamará a los controladores de eventos en `thumb` y `event.target` siempre será `thumb`, incluso si el usuario mueve el puntero por todo el documento. Así que podemos escuchar en `thumb` desde `pointermove`, sin importar dónde suceda. -Here's the essential code: +Aquí está el código esencial: ```js thumb.onpointerdown = function(event) { - // retarget all pointer events (until pointerup) to me + // reorienta todos los eventos de puntero (hasta pointerup) a mí thumb.setPointerCapture(event.pointerId); }; thumb.onpointermove = function(event) { - // move the slider: listen at thumb, as all events are retargeted to it + // mueve el control deslizante: escucha con thumb, ya que todos los eventos se redireccionan a él let newLeft = event.clientX - slider.getBoundingClientRect().left; thumb.style.left = newLeft + 'px'; }; -// note: no need to call thumb.releasePointerCapture, -// it happens on pointerup automatically +// nota: no es necesario llamar a thumb.releasePointerCapture, +// esto sucede con el pointerup automáticamente ``` ```online -The full demo: +La demostración completa: [iframe src="slider" height=100 edit] ``` -**As a summary: the code becomes cleaner as we don't need to add/remove handlers on the whole `document` any more. That's what pointer capturing does.** +**Como resumen: el código se vuelve más limpio ya que ya no necesitamos agregar o eliminar controladores en todo el `document`. Eso es lo que hace la captura de punteros.** -There are two associated pointer events: +Hay dos eventos de puntero asociados: -- `gotpointercapture` fires when an element uses `setPointerCapture` to enable capturing. -- `lostpointercapture` fires when the capture is released: either explicitly with `releasePointerCapture` call, or automatically on `pointerup`/`pointercancel`. +- `gotpointercapture` se dispara cuando un elemento usa `setPointerCapture` para permitir la captura. +- `lostpointercapture` se dispara cuando se libera la captura: ya sea explícitamente con la llamada a `releasePointerCapture`, o automáticamente con `pointerup`/`pointercancel`. -## Summary +## Resumen -Pointer events allow to handle mouse, touch and pen events simultaneously. +Los eventos de puntero permiten manejar eventos de mouse, toque y lápiz simultáneamente. -Pointer events extend mouse events. We can replace `mouse` with `pointer` in event names and expect our code to continue working for mouse, with better support for other device types. +Los eventos de puntero extienden los eventos del mouse. Podemos reemplazar `mouse` con `pointer` en los nombres de los eventos y esperar que nuestro código continúe funcionando para el mouse, con mejor soporte para otros tipos de dispositivos. -Remember to set `touch-events: none` in CSS for elements that we engage, otherwise the browser hijacks many types of touch interactions and pointer events won't be generated. +Recuerde establecer `touch-events: none` en CSS para los elementos que involucramos, de lo contrario, el navegador secuestra muchos tipos de interacciones táctiles y no se generarán eventos de puntero. -Additional abilities of Pointer events are: +Las habilidades adicionales de los eventos Pointer son: -- Multi-touch support using `pointerId` and `isPrimary`. -- Device-specific properties, such as `pressure`, `width/height` and others. -- Pointer capturing: we can retarget all pointer events to a specific element until `pointerup`/`pointercancel`. +- Soporte multitáctil usando `pointerId` y `isPrimary`. +- Propiedades específicas del dispositivo, como `pressure`, `width/height` y otras. +- Captura de puntero: podemos redirigir todos los eventos de puntero a un elemento específico hasta `pointerup`/`pointercancel`. -As of now, pointer events are supported in all major browsers, so we can safely switch to them, if IE10- and Safari 12- are not needed. And even with those browsers, there are polyfills that enable the support of pointer events. \ No newline at end of file +Al momento los eventos de puntero son compatibles con todos los navegadores principales, por lo que podemos cambiarlos de forma segura si no se necesitan IE10 y Safari 12. E incluso con esos navegadores, existen polyfills que permiten la compatibilidad con eventos de puntero.