Carrusel
Una fila de elementos visuales que se desplaza hacia los lados en torno a un elemento en primer plano, cada uno de los cuales abre lo que muestra. Una fila destacada puede no tener fin, mostrar su posición con puntos y avanzar por sí sola.
- Categoría
- Contención
- Tokens
comp.carousel- Nivel
- Base
- Web
tanrei-carouselschedule - SwiftUI
TanreiCarouselschedule - Jetpack Compose
TanreiCarouselschedule - Flutter
TanreiCarouselschedule - React Native
Carouselschedule
Generado a partir de docs/status/status.json, specs/carousel.spec.json
Una especificación revisada, todavía no en todas las plataformas
Esta página describe el carrusel tal como lo define ahora la especificación. Varias elecciones independientes (dónde se sitúa el elemento principal, anchos fluidos o fijos, escala, ajuste, bucle) sustituyen a la propiedad layout, y una fila destacada puede mostrar puntos y avanzar por sí sola. Ahora el elemento principal se sitúa en el centro de forma predeterminada, y los elementos vecinos quedan a una separación de distancia en cualquier posición del desplazamiento. El componente web ya hace todo esto, y también las demostraciones. SwiftUI, Compose, Flutter y React Native aparecen arriba como rezagadas: hasta que se pongan al día ofrecen la revisión anterior, con layout y sin bucle, puntos, reproducción automática ni controles anterior y siguiente. Consulta El elemento principal está en el centro de forma predeterminada y Migrar desde layout.
El valor predeterminado: el elemento principal en el centro y un elemento pequeño a su lado
Un carrusel tiene un solo tipo de elemento, item. Cada plataforma recibe los elementos como recibe cualquier conjunto de hijos repetidos: hijos <tanrei-carousel-item> en la web, vistas TanreiCarouselItem en un constructor de vistas en SwiftUI, llamadas a TanreiCarouselItem desde una lambda de elemento en Compose, widgets TanreiCarouselItem en children en Flutter e hijos CarouselItem en React Native.
Cada elemento es una sola acción. Contiene tu contenido, normalmente una imagen, y emite click cuando la persona lo activa (action, onClick, onTap u onPress, según la plataforma). Su label es su nombre accesible: di qué muestra el contenido, por ejemplo «Sendero costero, 12 fotos». El contenido en sí queda oculto para la tecnología de apoyo, y no debe incluir ningún control propio.
La fila se organiza en torno a un elemento en primer plano, el elemento principal (hero). Unas pocas propiedades independientes dicen cómo, y cada una tiene un valor predeterminado adecuado para una fila que se explora: el elemento principal en el centro, los elementos de al lado más estrechos y una fila que se asienta en un elemento entero. itemWidth es el ancho del elemento principal; déjalo sin definir para tomar el valor predeterminado del sistema de diseño. Una fila destacada puede añadir loop, los puntos (indicator) y autoplay. Sin autoplay, el carrusel no tiene ningún valor que controlar: se desplaza cuando la persona lo desplaza o mueve el foco.
Sobre los extremos de la fila, un control anterior y uno siguiente la mueven elemento a elemento. De forma predeterminada se dibujan para un ratón o un panel táctil, y aparecen mientras el puntero está sobre el carrusel o el foco está dentro de él. Dales un previousLabel y un nextLabel en el idioma de tu producto. Consulta Los controles anterior y siguiente.
Los ejemplos de Web y React muestran la especificación actual. Los ejemplos de SwiftUI, Compose, Flutter y React Native muestran la revisión anterior, que es la que ofrecen esas plataformas: layout (varios elementos en una fila de forma predeterminada, hero o uncontained) e itemWidth, sin bucle, puntos ni reproducción automática.
<tanrei-carousel previous-label="Paseo anterior" next-label="Paseo siguiente" label="Paseos cerca de ti">
<tanrei-carousel-item label="Sendero costero, 12 fotos"><img src="coast.jpg" alt="" /></tanrei-carousel-item>
<tanrei-carousel-item label="Casco antiguo, 8 fotos"><img src="town.jpg" alt="" /></tanrei-carousel-item>
<tanrei-carousel-item label="Circuito del bosque, 20 fotos"><img src="forest.jpg" alt="" /></tanrei-carousel-item>
</tanrei-carousel>
<!-- Una fila destacada: sin fin, con puntos, que avanza por sí sola. El elemento principal está en el centro de forma predeterminada. -->
<tanrei-carousel previous-label="Paseo anterior" next-label="Paseo siguiente" label="Paseos destacados" loop indicator autoplay
play-label="Reproducir presentación" pause-label="Pausar presentación">…</tanrei-carousel>
<!-- Una fila sencilla desde el borde de inicio: cada elemento mide 120 de ancho (un número de píxeles CSS) y la fila
reposa donde termine el desplazamiento. fixed-width y free-scroll son los inversos de fluidWidth y snap, que son true de forma predeterminada. -->
<tanrei-carousel previous-label="Paseo anterior" next-label="Paseo siguiente" label="Vistos recientemente" hero-alignment="start" fixed-width free-scroll item-width="120">…</tanrei-carousel>
<script type="module">
import '@tanrei/web/components/carousel';
for (const item of document.querySelectorAll('tanrei-carousel-item')) {
item.addEventListener('click', () => openWalk(item.label));
}
// Solo lo emite el control de reproducción, no las pausas temporales, ni tampoco cuando defines paused.
document.querySelector('[label="Paseos destacados"]').addEventListener('pausedchange', (e) => savePaused(e.detail.paused));
</script>import { Carousel, CarouselItem } from '@tanrei/react';
<Carousel label="Vistos recientemente" itemWidth={120} fluidWidth={false} snap={false}>
{walks.map((walk) => (
<CarouselItem key={walk.id} label={walk.label} onClick={() => openWalk(walk)}>
<img src={walk.image} alt="" />
</CarouselItem>
))}
</Carousel>
<Carousel label="Paseos destacados" loop indicator autoplay paused={paused}
onPausedChange={(e) => setPaused(e.detail.paused)}
previousLabel="Paseo anterior" nextLabel="Paseo siguiente"
playLabel="Reproducir presentación" pauseLabel="Pausar presentación">
{featured.map((walk) => <CarouselItem key={walk.id} label={walk.label} onClick={() => openWalk(walk)}><img src={walk.image} alt="" /></CarouselItem>)}
</Carousel>import Tanrei
// La revisión anterior: layout elige la disposición. .hero es un elemento destacado cada vez.
TanreiCarousel("Paseos destacados", layout: .hero) {
ForEach(walks) { walk in
TanreiCarouselItem(walk.label, action: { open(walk) }) {
WalkImage(walk)
}
}
}import androidx.compose.ui.unit.dp
import io.github.chnotchy.tanrei.components.TanreiCarousel
import io.github.chnotchy.tanrei.components.TanreiCarouselItem
import io.github.chnotchy.tanrei.components.TanreiCarouselLayout
// La revisión anterior. Una lambda de elemento, como la que reciben los carruseles de Material. itemWidth es un Dp, o null para usar el token.
// Uncontained es una fila sencilla: todos los elementos del mismo ancho, cortados en el borde.
TanreiCarousel(
itemCount = walks.size,
contentDescription = "Vistos recientemente",
layout = TanreiCarouselLayout.Uncontained,
itemWidth = 120.dp,
) { index ->
val walk = walks[index]
TanreiCarouselItem(label = walk.label, onClick = { open(walk) }) {
WalkImage(walk)
}
}import 'package:tanrei/tanrei.dart';
// La revisión anterior: layout elige la disposición.
TanreiCarousel(
semanticLabel: 'Paseos destacados',
layout: TanreiCarouselLayout.hero,
children: [
for (final Walk walk in walks)
TanreiCarouselItem(label: walk.label, onTap: () => open(walk), child: WalkImage(walk)),
],
),import { Image } from 'react-native';
import { Carousel, CarouselItem } from '@tanrei/react-native';
// El layout predeterminado de la revisión anterior: varios elementos en una fila.
<Carousel accessibilityLabel="Paseos cerca de ti">
{walks.map((walk) => (
<CarouselItem key={walk.id} label={walk.label} onPress={() => openWalk(walk)}>
<Image source={walk.image} style={{ flex: 1 }} />
</CarouselItem>
))}
</Carousel>Un elemento principal tan ancho como puede ser, y anchos fijos que se desplazan libremente desde el borde de inicio
Organizar la fila: anchos fijos, escala, bucle y contenido hacia el elemento principal
fixed-width free-scrollfixed-width scale-others looploopitem-width=“120” content-alignment=“toward-hero” loopPuntos, reproducción automática, progreso, en pausa y el control de reproducción solo
indicatorindicator autoplayautoplay-progresspausedLa reproducción automática nunca se ejecuta donde el ajuste de reducir movimiento está activado: ahí las demostraciones de reproducción automática permanecen quietas, sin el control de reproducción ni el progreso.
Anatomía
| Parte | Descripción |
|---|---|
1 row | The row of items: as wide as the carousel, scrolling sideways, padded at its start and end. Items scroll under the padding to its edges, every two neighbours the same gap apart. |
2 item | One item of the row (an item of the item kind). The item in focus is the hero, in the middle of the row unless heroAlignment puts it at the start; with fluid widths the others narrow as they move away from it, and with scaleOthers they are drawn smaller. |
3 item.container | The item's rounded box. It clips the item's content, fills what the content leaves uncovered, and carries hover, focus and press. |
4 item.content | What the product puts in the item (an image, a poster). The carousel lays it out at the hero's width and aligns it in the container (centred, or toward the hero), so a narrower item shows part of it. |
5 focus-ring · opcional | Gap-then-ring indicator for keyboard focus: inside an item's container, which the row would otherwise clip, and around the indicator's or the playback control's container. |
6 previous · opcional | The previous control: an icon-only Button over the row's inline start, centred on the row's height, that moves the row back by one resting position. Drawn as navigation says, while there are at least two resting positions (CRL-41). |
7 next · opcional | The next control: an icon-only Button over the row's inline end, centred on the row's height, that moves the row on by one resting position. Drawn as navigation says, while there are at least two resting positions (CRL-41). |
8 controls · opcional | The controls row directly below the items, drawn while the indicator or the playback control is. It does not scroll. |
9 indicator · opcional | The dots, centred in the controls row: one per resting position, the current one stretched, the stretch following the scroll. One control (a slider) whose container carries hover, focus and press. |
10 indicator.dot | One dot: a pill of the dot size, stretched toward the active width as the row nears its position; the current dot may fill to show the time until autoplay moves on. |
11 playback · opcional | The playback control at the end of the controls row, drawn while autoplay is on: an icon-only button, a circle, that pauses and plays. |
12 playback.icon | The glyph of the icon set: `pause` while autoplay is playing, `play_arrow` while it is paused. Never mirrored. |
Propiedades
| Propiedad | Tipo | Valor predeterminado | Descripción |
|---|---|---|---|
heroAlignment | start | center | "center" | Where the item in focus (the hero) sits: in the middle, with items on both sides (the default), or at the inner start edge (the left in a left-to-right language), with items after it only. Not a token axis: geometry, read from the same tokens. |
itemWidth | number | null | The width the hero is laid out at, in the platform's unit (CSS px, pt, dp, logical pixels); null takes comp.carousel.container.large-width. With fixed widths every item is this wide (at most the inner width); with fluid widths the hero is kept between a floor and a cap that leave room for the others (CRL-9). Choose it from the content's shape: a product's posters and thumbnails differ. |
fluidWidth | boolean | true | Whether item widths change fluidly: true narrows the items beside the hero (on both sides of a hero in the centre) to a medium and a small width, each width following the scroll; false makes every item the hero's width, the ones that do not fit cut by the carousel's edges. |
contentAlignment | center | toward-hero | "center" | With fluid widths, where a narrowed item's content is anchored: center shows its middle; toward-hero aligns the items after the hero to their start and the items before it to their end, so each shows the side nearest the hero. Ignored while fluidWidth is false. |
scaleOthers | boolean | false | Whether the items other than the hero are drawn smaller, down to comp.carousel.container.min-scale, the scale following the scroll and the gap between drawn items staying the same. It applies with fluid or fixed widths. |
snap | boolean | true | Whether the row settles at an item when a scroll ends; false lets it rest wherever the scroll ends. |
loop | boolean | false | Whether the row is endless: scrolling past the last item continues to the first, and back. Takes effect only with two or more items; with fewer it is ignored. |
navigation | auto | always | none | "auto" | Whether the previous and next controls are drawn over the ends of the row (CRL-41, CRL-42). auto draws them where the primary pointer is fine and can hover — a mouse or a trackpad, where no finger swipes the row — and shows them while the pointer is over the carousel or focus is within it; always draws them on every device and shows them at all times; none draws neither. Keep auto wherever you can: without the controls a person with a mouse moves the row only with Shift and the wheel, or with the indicator where it is drawn, and never with a single press (WCAG 2.5.7). |
indicator | boolean | false | Whether the dots are drawn below the items: one per resting position, the current one stretched. For a short featured row; a long row to browse needs none. |
autoplay | boolean | false | Whether the row advances by itself, one item every autoplayInterval. It holds while the carousel is hovered, has focus within, is pressed or is hidden, and never runs where motion is reduced (CRL-32 to CRL-34). |
autoplayInterval | number | null | How long the row rests at an item before autoplay moves on, in milliseconds; null takes comp.carousel.autoplay.interval. Give text-heavy items more time than images. |
paused | boolean | false | Whether autoplay is paused, by the person (with the playback control) or by the product. The playback control changes it and emits pausedChange; a product that sets it emits nothing. |
playbackControl | boolean | true | Whether the playback control is drawn while autoplay is on. A product may hide it, but should keep it wherever it can: on touch there is no hover, and without it a person cannot stop the motion (WCAG 2.2.2). |
autoplayProgress | boolean | false | Whether the current dot fills to show the time until autoplay moves on. Needs indicator; ignored while autoplay is off or paused. |
playLabel | string | "" | The playback control's accessible name while autoplay is paused ("Play the slideshow"). Required while the control can be drawn. |
pauseLabel | string | "" | The playback control's accessible name while autoplay is playing ("Pause the slideshow"). Required while the control can be drawn. |
previousLabel | string | "" | The previous control's accessible name ("Previous walk"). Required while the control can be drawn. |
nextLabel | string | "" | The next control's accessible name ("Next walk"). Required while the control can be drawn. |
label | string | "" | Names the carousel's list, and its indicator, for assistive technology ("Recently played"). Required. |
Eventos
| Evento | Descripción |
|---|---|
pausedChange | The person paused or played autoplay with the playback control; carries the new paused value. Not emitted when the product sets paused, nor for the holds of CRL-33. |
Elementos
Los tipos de elemento que el componente repite. Un fixture enumera sus elementos en orden; cada plataforma nombra cada tipo según su propio estilo.
item
One item of the row: the product's content in a rounded box, one action named by its label.
| Propiedad | Tipo | Valor predeterminado | Descripción |
|---|---|---|---|
label | string | "" | The item's accessible name: what its content shows ("Coast path, 12 photos"). Required; the content itself is not read. It is also the indicator's value text while the item is in focus. |
| Slot | Descripción |
|---|---|
default | The item's content. A fixture item's content is the name of a glyph: the harness draws it centred in the content box (the hero's width, the row's height) at sys.icon.medium through the icon helper, with the family and fill of an unselected icon, in the item's content color, on the item's container color. |
| Evento | Descripción |
|---|---|
click | The item was activated by pointer, touch, keyboard or assistive technology. |
| Especificación | Web | SwiftUI | Jetpack Compose | Flutter | React Native |
|---|---|---|---|---|---|
| Elemento | tanrei-carousel-item | TanreiCarouselItem | TanreiCarouselItem | TanreiCarouselItem | CarouselItem |
label · Propiedad | label | label | label | label | label |
click · Evento | click | action | onClick | onTap | onPress |
| Notas | A <tanrei-carousel-item> child; its content is its default slot. | TanreiCarouselItem(_ label: String, action: @escaping () -> Void) { content }. | TanreiCarouselItem(label, onClick) { content }, called from the carousel's item lambda. | TanreiCarouselItem(label:, onTap:, child:), one of the carousel's children. | <CarouselItem label onPress>{content}</CarouselItem>, a child of Carousel. |
Estados
Comportamiento
Requisitos en formato EARS. Cada implementación de plataforma se prueba contra estos identificadores. El texto de los requisitos se muestra tal como está en la especificación, en inglés.
| ID | Requisito |
|---|---|
CRL-1 | WHEN the user activates an item by pointer, touch, Enter or Space THE carousel SHALL emit that item's click exactly once; a press that turns into a scroll (a drag beyond the platform's touch slop, a fling) SHALL NOT activate the item it started on. |
CRL-2 | WHILE an item, the indicator or the playback control is hovered, keyboard-focused or pressed THE carousel SHALL render that part's container, content color and opacity, and an item's shape, from the component tokens of its highest-precedence active state, with precedence pressed over focused over hovered; focus gained by pointer or touch SHALL NOT select the focused state. |
CRL-3 | WHEN an item, the indicator or the playback control receives keyboard focus THE carousel SHALL show the focus ring without animation, inside an item's container, which the row would otherwise clip, and around the indicator's or the playback control's container; focus gained by pointer or touch SHALL NOT show it. |
CRL-4 | THE carousel SHALL make each item's hit area its drawn container with half of comp.carousel.layout.gap on each side, which for a small item at comp.carousel.container.small-min-width is sys.target.touch wide with the default tokens, and SHALL NOT let the hit area of an item that fills a slot fall below sys.target.pointer wide for a fine pointer or sys.target.touch for touch; a system whose widths give less SHALL still extend the hit area without changing the drawn item, and the row's height SHALL NOT be below the target either. An item on its way between the last slot and an edge slot (CRL-12) is narrower than any slot: its hit area SHALL be its drawn container with half of the gap on each side and no wider, so that it never covers its neighbour's. |
CRL-5 | WHEN a carousel item or the playback control is pressed by pointer, touch, Enter or Space, or the indicator by pointer or touch, THE carousel SHALL show that part's pressed state without delay and SHALL keep it visible for at least sys.motion.duration.press-hold, even when the press ends sooner; the indicator's SHALL last as long as the press does. |
CRL-6 | WHILE a carousel item, the indicator or the playback control is pressed THE carousel SHALL answer as sys.behavior.pressed-feedback names: overlay applies the pressed tokens to the whole container at once; ripple grows the pressed state layer from the point of contact (from the center for keyboard activation); dim applies the pressed opacity to the whole control and draws no state layer; none draws no answer to the press. Under ripple and dim only the container color stays with the state under the press; content color, opacity and shape still come from the pressed tokens. Under none every part stays with the state under the press. The ripple grows over comp.carousel.motion.feedback-duration with comp.carousel.motion.state-easing, fades over comp.carousel.motion.state-duration with comp.carousel.motion.state-easing once the press has ended and press-hold has passed, and appears whole where motion is reduced. |
CRL-7 | THE carousel SHALL ease the corners of its items' containers, the indicator's container and the playback control by sys.shape.corner-smoothing (0 is a quarter circle, 0.6 the iOS continuous corner; a platform with only the OS curve draws it for any amount above 0) and show keyboard focus as sys.behavior.focus-style names (ring or glow); a platform that cannot draw a choice SHALL fall back to the first value and state that in its README. |
CRL-8 | THE carousel SHALL be as wide as its parent; its row of items SHALL be comp.carousel.layout.height tall unless the product sizes the carousel through the platform's own sizing, in which case the row takes that height less the controls row (CRL-28), and every item SHALL be as tall as the row. It SHALL lay its items out in one row in the order given, comp.carousel.layout.gap apart (g), inside comp.carousel.layout.padding-inline at its start and its end: the inner width W is the carousel's width less that padding twice. Items SHALL scroll under the padding to the carousel's edges and be clipped there. |
CRL-9 | THE carousel SHALL take L from itemWidth, or from comp.carousel.container.large-width while itemWidth is null, and SHALL make the hero slot H wide. WHILE fluidWidth is false H SHALL be L, at most W. WHILE fluidWidth is true H SHALL be L kept between a floor and a cap: WHILE heroAlignment is center, the floor (W − 4 × g − 2 × comp.carousel.container.small-max-width) / 3 and the cap W − 2 × (g + comp.carousel.container.small-max-width); WHILE heroAlignment is start, the floor (W − 2 × g − comp.carousel.container.small-max-width) / 2 and the cap W − g − comp.carousel.container.small-max-width. IF fluidWidth is true and that cap is less than comp.carousel.container.small-max-width THE carousel SHALL lay the row out as it does with fixed widths (CRL-13), H being W. |
CRL-10 | WHILE fluidWidth is true THE carousel SHALL fill the width E that the hero slot leaves on each side where items follow it (on both sides, E = (W − H) / 2 − g, WHILE heroAlignment is center; after it, E = W − H − g, WHILE heroAlignment is start) with slots g apart, going outward from the hero: IF E − g is less than 2 × comp.carousel.container.small-min-width, one small slot E wide; otherwise a medium slot M wide and then a small slot S wide, where S is (E − g) / 3 kept between comp.carousel.container.small-min-width and comp.carousel.container.small-max-width and M = E − g − S. IF M is then greater than H, M SHALL be H and S SHALL be E − g − H. Widths SHALL NOT be rounded before the items are placed; CRL-40 says where a platform that draws on whole device pixels puts the rounding. |
CRL-11 | THE carousel SHALL place the hero slot, where the item in focus sits, WHILE heroAlignment is center with its middle at the middle of the inner width (its start h at (W − H) / 2), and WHILE heroAlignment is start at the inner start edge (h is 0); and SHALL place the other slots of CRL-10, on both sides of it at the centre and after it at the start, each one g beyond the slot before it going outward, measured between the slots' drawn edges. |
CRL-12 | THE carousel SHALL place its items by a scroll position p, a number of items that advances by one for every H + g the row is scrolled. WHILE loop is not in effect (CRL-27) p SHALL run from 0 to N − 1 (N the number of items), except where CRL-13 ends the range sooner for a hero at the start; the resting positions are the whole numbers in the range and, where the range ends at a fraction, its end, D of them in all, so D is N wherever the range is not ended sooner. Item i, counted from 0, sits at slot position s = i − p. Slot 0 is the hero slot and slots 1, 2 and on follow it toward the end; WHILE heroAlignment is center slots −1, −2 and on precede it toward the start, and WHILE heroAlignment is start no slot precedes it (CRL-10, CRL-11, CRL-13). WHILE fluidWidth is true, beyond the last slot on each side lies an edge slot of no width, g beyond that slot — before a hero at the start, g before the hero slot itself — so that at a whole p nothing is drawn beyond the last slots; an item at or beyond an edge slot SHALL NOT be drawn. An item's start and width SHALL be the linear interpolation between those of the two slots around s. So at p = 0 the first item is the hero and nothing is drawn before it, and as p grows each item moves toward the start, growing from nothing at the edge slot to H as it reaches slot 0 and narrowing again to nothing as it leaves, a hero at the start narrowing against the inner start edge; at the end of the range the last item is the hero and the slots after it are empty. |
CRL-13 | WHILE fluidWidth is false THE carousel SHALL make every slot H wide, slot k starting at h + k × (H + g), h being the hero slot's start (CRL-11), with no edge slot: the slots go on beyond the carousel's edges, where the items are clipped (CRL-8), so that CRL-12's interpolation starts item i at h + s × (H + g). WHILE scaleOthers is also true the slots other than the hero's take the widths and the places CRL-26 gives them. WHILE heroAlignment is start, scaleOthers is false and loop is not in effect, the range of p SHALL end where the last item ends at the inner end edge, at the greater of 0 and (N × (H + g) − g − W) / (H + g), so that WHILE every item fits in W the row does not scroll. |
CRL-14 | WHEN the user scrolls the carousel by touch, pen, trackpad, a horizontal wheel or Shift with a vertical wheel THE carousel SHALL follow the scroll; WHILE snap is true, WHEN the scroll ends (a drag released, a wheel or trackpad gesture over) THE carousel SHALL settle at a resting position: the next one in the direction of a fling, or else the nearest one, over comp.carousel.motion.scroll-duration with comp.carousel.motion.scroll-easing, at once where motion is reduced; WHILE snap is false it SHALL come to rest wherever the scroll ends. A fling is a release faster than the platform's minimum fling velocity (Android's ViewConfiguration.getScaledMinimumFlingVelocity, Flutter's kMinFlingVelocity) or, where the platform names none (the web, SwiftUI, React Native), 0.5 points per millisecond. A release's velocity is the pointer's over its last moves: WHERE the pointer has not moved for longer than the time after which the platform's velocity tracker takes a pointer as stopped (40 milliseconds in Android's VelocityTracker, Jetpack Compose's VelocityTracker and Flutter's VelocityTracker) or, where the platform names none (the web, SwiftUI, React Native), 40 milliseconds before the release THE carousel SHALL take the release as having no velocity, so that a drag that stops where it is wanted and is let go there is no fling, however fast it moved before it stopped. A horizontal wheel, a trackpad and Shift with a vertical wheel are physical in every layout direction: THE carousel SHALL move the row the way the platform's own scrolling containers move for that input and SHALL NOT reverse it in a right-to-left layout, so that Shift with a wheel turned down, which brings into view what lies further to the right, moves toward later items in left-to-right and toward earlier items in right-to-left. |
CRL-15 | THE carousel SHALL lay each item's content out H wide and as tall as the row, and SHALL clip it to the item's container and its comp.carousel.container.shape corners; WHILE fluidWidth is false or contentAlignment is center the content SHALL be centred on the container, and WHILE fluidWidth is true and contentAlignment is toward-hero an item after the hero (s above 0) SHALL align the content's start edge with its container's start edge and an item before it (s below 0) the content's end edge with its container's end edge, so that a narrowed item shows the side of its content nearest the hero and the content glides inside the item as it widens and narrows. |
CRL-16 | THE carousel SHALL fill each item's container with comp.carousel.item.container.color at rest, under its content, whatever the item's state, and SHALL hand the content comp.carousel.item.content.color as the platform's inherited foreground (the web's inherited color, SwiftUI's foreground style, Compose's content color, Flutter's default text and icon style, React Native's Tanrei text context). Because an item's content usually covers it (an image), the carousel SHALL draw the state layer over the content: comp.carousel.item.state-layer.color at sys.state.hover-state-layer-opacity, sys.state.focus-state-layer-opacity or sys.state.pressed-state-layer-opacity for the item's highest-precedence state, and the ripple of CRL-6 in the same layer, so hover, focus and press show on any content; the container color under the content is the resting fill only. |
CRL-17 | THE carousel SHALL be at most five Tab stops, in this order: the playback control while it is drawn (CRL-35), so that the motion can be stopped before anything else is reached; the previous and then the next control while they are drawn (CRL-41), before the items, so that a person can move the row before reading it; the items, as one stop, at the item that last had keyboard focus in it or else at the resting item (the item at slot 0 while fluidWidth is true, heroAlignment is center or snap is true, and otherwise the first item wholly in view); and the indicator while it is drawn (CRL-29). WHILE an item has keyboard focus Right Arrow and Left Arrow SHALL move focus to the next and previous item, from the last to the first and the first to the last WHILE loop is in effect and otherwise without wrapping, and Home and End to the first and last item; in a right-to-left layout Left Arrow SHALL move to the next item and Right Arrow to the previous. |
CRL-18 | WHEN an item receives keyboard focus or assistive-technology focus THE carousel SHALL scroll, over comp.carousel.motion.scroll-duration with comp.carousel.motion.scroll-easing (at once where motion is reduced), so that WHILE fluidWidth is true, heroAlignment is center or snap is true the item sits at slot 0 or, where the range ends first, at the resting position nearest it, going the shorter way round WHILE loop is in effect; and otherwise so that the whole item is in view, scrolling as little as that needs. |
CRL-19 | THE carousel SHALL expose its items as a list named by label, and each item as one element with the button role, named by its label, with its position among the items and their number; it SHALL hide each item's content from assistive technology (the label names the item), and SHALL keep items that are out of view exposed, in order, so that a screen reader reaches every item (CRL-18 brings it into view). The indicator (CRL-31), the playback control (CRL-35) and the previous and next controls (CRL-41) SHALL be outside the list and SHALL NOT be counted among its items. |
CRL-20 | WHILE an item's label is empty THE carousel SHALL still render it, and in debug builds report that it has no accessible name; WHILE the carousel's label is empty it SHALL report that the list and the indicator have no name; WHILE autoplay and playbackControl are true and playLabel or pauseLabel is empty it SHALL report the missing name; WHILE the previous and next controls are drawn (CRL-41) and previousLabel or nextLabel is empty it SHALL report the missing name; and WHILE indicator is true and the dots do not fit (CRL-29) it SHALL report that they are not drawn. An item's content SHALL contain no interactive element; a platform that can inspect it (the web, on every slot change) SHALL report one in debug builds, and a platform that cannot SHALL state the rule in its README. |
CRL-21 | WHEN the carousel's width or its items change THE carousel SHALL arrange its slots again and keep the resting item (CRL-17) where it was, as far as the new range allows, without motion; WHEN the number of items falls below two it SHALL stop looping (CRL-27) and advancing (CRL-32), and no longer draw the indicator, the playback control or the previous and next controls. |
CRL-22 | WHEN the colors of an item, the indicator or the playback control change between states THE carousel SHALL animate them over comp.carousel.motion.state-duration with comp.carousel.motion.state-easing, and SHALL change them at once where motion is reduced. |
CRL-23 | WHEN the layout direction is right-to-left THE carousel SHALL mirror its row and its controls row: the inner start edge at the right, items moving toward the right as p grows, the padding, the scroll direction, the start and end sides of contentAlignment, the order of the dots, the playback control's side and the sides of the previous and next controls (the previous control at the right) all mirrored; it SHALL grow a ripple from the point of contact as in left-to-right, and SHALL NOT mirror an item's content or the pause and play_arrow glyphs. The chevron_left and chevron_right glyphs of the previous and next controls SHALL be drawn mirrored exactly when the system's icon set marks the name as mirrored, by the Button's own icon helper; THE carousel SHALL NOT mirror a glyph itself. |
CRL-24 | WHEN heroAlignment, contentAlignment or navigation names a value the carousel does not define THE carousel SHALL render with that prop's default value, and in debug builds report the unknown value; WHEN itemWidth or autoplayInterval is not a positive number THE carousel SHALL treat it as null and in debug builds report it. |
CRL-25 | WHILE the text size is enlarged THE carousel SHALL keep its height, slots and items as they are: it holds no text of its own, and an item's content follows the text size itself. |
CRL-26 | WHILE scaleOthers is true THE carousel SHALL give the hero slot the scale 1 and every other slot the scale comp.carousel.container.min-scale, and SHALL draw each item's container at the scale interpolated between the two slots around s, which is 1 − (1 − comp.carousel.container.min-scale) × the lesser of 1 and |s|: as tall as the row times that scale, centred on the row's height, with its content drawn at that scale. WHILE fluidWidth is false a slot SHALL also be H times its scale wide, and the slots SHALL be placed g apart from drawn edge to drawn edge going outward from the hero slot, so that the smaller items close up to their neighbours; WHILE fluidWidth is true the slots keep the widths of CRL-10, which already fill the row, and only the height and the content take the scale. The corners of a scaled container SHALL stay the radius of comp.carousel.container.shape (or of its state's shape token) and SHALL NOT be multiplied by the scale; the item's focus ring SHALL be drawn at its own width inside the drawn container, and the item's hit area (CRL-4) SHALL follow the drawn container. The scale SHALL follow the scroll where motion is reduced as well, because the person's own scroll drives it. |
CRL-27 | WHILE loop is true and there are at least two items THE carousel SHALL scroll without end in both directions: p SHALL take any value, every whole number SHALL be a resting position, and item i SHALL sit at the one slot position s that differs from i − p by a whole multiple of N and lies above −N / 2 and at most N / 2 WHILE heroAlignment is center, or above −1 and at most N − 1 WHILE heroAlignment is start, so that scrolling past the last item continues to the first and before the first to the last. Each item SHALL be drawn once: with fluid widths and enough items for every slot and both edge slots an item passes from one side to the other at the edge slots, where it has no width, and with fewer items, or with fixed widths and too few items to reach beyond both edges, a slot stays empty and an item that passes to the other side may appear there at once. WHILE there are fewer than two items THE carousel SHALL ignore loop; loop is in effect only while both conditions hold. |
CRL-28 | WHILE the indicator (CRL-29) or the playback control (CRL-35) is drawn THE carousel SHALL draw, directly below its row of items, a controls row as wide as the carousel and comp.carousel.controls.height tall that does not scroll, with the indicator's container centred on the carousel's width and the playback control at its inline end, its end edge at the inner end edge, both centred on the row's height; WHILE neither is drawn there SHALL be no controls row. The indicator SHALL stay centred whether or not the playback control is drawn. |
CRL-29 | WHILE indicator is true and there are at least two resting positions THE carousel SHALL draw the indicator: D dots in reading order, comp.carousel.dot.gap apart, each comp.carousel.dot.size tall with round ends, inside a container that reaches comp.carousel.controls.indicator-padding-inline beyond the first and last dot, is comp.carousel.controls.button-size tall and has comp.carousel.controls.shape corners. The indicator's position q follows p: between resting positions j and j + 1 it runs linearly from j to j + 1, and WHILE loop is in effect q is p less a whole multiple of N, from 0 up to N, its distance to a dot measured around the ring. Dot j SHALL be comp.carousel.dot.size + (comp.carousel.dot.active-width − comp.carousel.dot.size) × w wide, w being the greater of 0 and 1 − the distance from q to j, and SHALL be drawn in comp.carousel.dot.color with a fill of comp.carousel.indicator.content.color over it at opacity w, across its whole width unless CRL-36 says otherwise, so that the current dot is stretched and in the active color and the stretch and the color pass to the next dot as the row scrolls. IF the container would be wider than W − 2 × (sys.target.touch + g) THE carousel SHALL NOT draw the indicator. |
CRL-30 | WHEN the person presses the indicator by pointer or touch anywhere in its hit area THE carousel SHALL move the row to the resting position of the dot nearest the press and, while the press moves along the dots, to the dot nearest it, each move over comp.carousel.motion.scroll-duration with comp.carousel.motion.scroll-easing (at once where motion is reduced); WHILE the indicator has keyboard focus Right Arrow and Left Arrow SHALL move the row to the next and previous resting position (wrapping WHILE loop is in effect, and otherwise not), Home and End to the first and last, mirrored in a right-to-left layout; WHEN assistive technology increments or decrements the indicator it SHALL move by one resting position. Focus SHALL stay on the indicator, and the items' Tab stop (CRL-17) SHALL become the resting item the move brings. |
CRL-31 | THE carousel SHALL expose the indicator as one slider (the adjustable trait on Apple platforms), named by label, horizontal, with the lowest value 1, the highest D and the value of the resting position nearest q counted from 1, and SHALL give it as value text the label of the item that position brings to slot 0 or, where the range ends first, the resting item there; its dots SHALL NOT be exposed one by one. |
CRL-32 | WHILE autoplay is true, paused is false, there are at least two resting positions, motion is not reduced (CRL-34) and no hold of CRL-33 is in effect THE carousel SHALL advance to the next resting position each time autoplayInterval (or comp.carousel.autoplay.interval while it is null) has passed with the row at rest, scrolling over comp.carousel.motion.autoplay-duration with comp.carousel.motion.autoplay-easing; from the last resting position it SHALL go on to the first, forward WHILE loop is in effect and otherwise back across the row over the same duration. An advance SHALL NOT move focus, change the items' Tab stop, or make an announcement. |
CRL-33 | WHILE a pointer is over the carousel (its row or its controls row), focus is anywhere within it however it came there, the person is pressing or dragging the row or the indicator, or the platform reports the carousel's window or document hidden, THE carousel SHALL NOT advance and SHALL hold the time that has passed; WHEN the last hold ends it SHALL continue from the time it held. WHEN the person moves the row (a scroll, a key, the indicator, the previous or the next control) the time SHALL start again from zero once the row comes to rest. WHEN the person activates the playback control to play, the hover and focus holds in effect at that moment SHALL end, and each SHALL apply again only once the pointer or focus has left the carousel and entered it again. |
CRL-34 | WHILE motion is reduced THE carousel SHALL NOT advance by itself, whatever autoplay and paused say, and SHALL NOT draw the playback control or the autoplay progress; WHEN motion stops being reduced it SHALL start autoplay again (paused permitting) with the time from zero. Where motion is reduced the width, the scale and the dots SHALL still follow a scroll the person makes. |
CRL-35 | WHILE autoplay is true, playbackControl is true, there are at least two resting positions and motion is not reduced THE carousel SHALL draw the playback control in the controls row: an icon-only button, a comp.carousel.controls.button-size square with comp.carousel.controls.shape corners, filled with comp.carousel.playback.container.color, holding the icon set's pause glyph while paused is false and play_arrow while paused is true, comp.carousel.controls.icon.size, in comp.carousel.playback.content.color, with the family and fill of an unselected icon, sys.icon.weight and its optical size clamped to sys.icon.optical-size.min and sys.icon.optical-size.max. It SHALL be exposed with the button role, named by pauseLabel while paused is false and by playLabel while paused is true, with no pressed or selected state. WHEN the person activates it THE carousel SHALL toggle paused, emit pausedChange with the new value and keep focus on it, and on play the time SHALL start from zero; WHEN the product sets paused THE carousel SHALL emit nothing. |
CRL-36 | WHILE autoplayProgress is true, the indicator is drawn, autoplay is true, paused is false and motion is not reduced THE carousel SHALL draw the fill of CRL-29 only on the dot of the resting position the row last came to rest at, from that dot's start edge across the part of its width that the time passed (CRL-33) is of the interval, growing with the time and stopping while a hold is in effect, and on no other dot, so that the dot stands in comp.carousel.dot.color and fills with comp.carousel.indicator.content.color until the row moves on, the fill fading as the dot narrows. |
CRL-37 | THE carousel SHALL give the playback control a hit area centred on it of at least sys.target.touch for touch and sys.target.pointer for a fine pointer, and the indicator a hit area as tall as the controls row and as wide as its container, at least sys.target.touch wide; with the default tokens both fit inside the controls row, and CRL-29 keeps them apart. |
CRL-38 | WHILE the icon set's font has not loaded THE carousel SHALL keep the playback control's glyph box and draw nothing in it, never the glyph's name as text. |
CRL-39 | THE carousel SHALL take its layout direction from where it is used — the direction of the nearest ancestor that sets one, and the platform's own where none does — and SHALL have no direction setting of its own; WHEN that direction changes while the carousel is shown THE carousel SHALL draw itself for the new direction at once, without a motion of its own, keeping the item at rest (the same item in reading order, not the same scroll offset), its playback and its focus. |
CRL-40 | THE carousel SHALL keep the distance from the drawn end edge of an item's container to the drawn start edge of the next item's container equal to comp.carousel.layout.gap, for every two neighbouring items that are both drawn, at every scroll position: at rest and at every moment of a drag, a fling, a settle, an advance and a move by the keys or the dots, in every combination of heroAlignment, fluidWidth, scaleOthers, contentAlignment, snap and loop, and in both layout directions. The edges are those of the container as it is drawn, after any scale (CRL-26), not those of a box laid out before the scale. THE carousel SHALL place every item it draws in a frame from the same scroll position p, and SHALL NOT ease, delay or animate an item's start, width or scale apart from p. A platform that draws on whole device pixels SHALL round each item's start edge and take its end edge from the next item's rounded start edge less the gap as that platform rounds it, so that the rounding falls on an item's width and never on a gap, and no two gaps in view differ. |
CRL-41 | WHILE navigation is auto or always and there are at least two resting positions THE carousel SHALL draw a previous control over the inline start of its row and a next control over its inline end, above the items: the previous control's start edge at the inner start edge and the next control's end edge at the inner end edge, both centred on the row's height. They SHALL be icon-only Buttons of the medium size in the variant comp.carousel.navigation.button.variant names, given through the channel a Button reads from the component that places it and otherwise unrestyled, showing the icon set's chevron_left and chevron_right glyphs and named by previousLabel and nextLabel. WHILE navigation is auto THE carousel SHALL draw them only where the primary pointer is fine and can hover; WHILE navigation is none, or there are fewer than two resting positions, it SHALL draw neither. |
CRL-42 | WHILE navigation is auto THE carousel SHALL show the previous and next controls only while a pointer is over the carousel (its row or its controls row) or focus is within it, however it came there, fading them in and out over comp.carousel.motion.state-duration with comp.carousel.motion.state-easing, at once where motion is reduced; hidden, they SHALL keep their place in the Tab order (CRL-17) and stay exposed to assistive technology with their names and states, so that a keyboard reaches them and focus shows them. WHILE navigation is always THE carousel SHALL show them at all times. |
CRL-43 | WHEN the person activates the previous or the next control THE carousel SHALL move the row to the resting position before or after the one it is at — while it is moving, the one it is moving to; between two resting positions, the nearest one before or after where it is — over comp.carousel.motion.scroll-duration with comp.carousel.motion.scroll-easing (at once where motion is reduced), from the first to the last and from the last to the first WHILE loop is in effect. Focus SHALL stay on the control, and the items' Tab stop (CRL-17) SHALL become the resting item the move brings. WHILE loop is not in effect THE carousel SHALL disable the previous control while the row is at, or moving to, the first resting position, and the next control at the last: drawn and exposed as disabled and refusing activation, but kept in the Tab order and keeping focus, so that the stops do not change as the row moves and focus is never lost when a control reaches its end. |
Correspondencia de nombres por plataforma
Paridad no significa API idénticas. Cada plataforma expresa el mismo contrato con su propio estilo.
| Especificación | Web | SwiftUI | Jetpack Compose | Flutter | React Native |
|---|---|---|---|---|---|
| Componente | tanrei-carousel | TanreiCarousel | TanreiCarousel | TanreiCarousel | Carousel |
heroAlignment · Propiedad | heroAlignment | heroAlignment | heroAlignment | heroAlignment | heroAlignment |
itemWidth · Propiedad | itemWidth | itemWidth | itemWidth | itemWidth | itemWidth |
fluidWidth · Propiedad | fluidWidth | fluidWidth | fluidWidth | fluidWidth | fluidWidth |
contentAlignment · Propiedad | contentAlignment | contentAlignment | contentAlignment | contentAlignment | contentAlignment |
scaleOthers · Propiedad | scaleOthers | scaleOthers | scaleOthers | scaleOthers | scaleOthers |
snap · Propiedad | snap | snap | snap | snap | snap |
loop · Propiedad | loop | loop | loop | loop | loop |
navigation · Propiedad | navigation | navigation | navigation | navigation | navigation |
indicator · Propiedad | indicator | showsIndicator | indicator | indicator | indicator |
autoplay · Propiedad | autoplay | autoplay | autoplay | autoplay | autoplay |
autoplayInterval · Propiedad | autoplayInterval | autoplayInterval | autoplayInterval | autoplayInterval | autoplayInterval |
paused · Propiedad | paused | isPaused | paused | paused | paused |
playbackControl · Propiedad | playbackControl | showsPlaybackControl | playbackControl | playbackControl | playbackControl |
autoplayProgress · Propiedad | autoplayProgress | showsAutoplayProgress | autoplayProgress | autoplayProgress | autoplayProgress |
playLabel · Propiedad | playLabel | playLabel | playLabel | playLabel | playLabel |
pauseLabel · Propiedad | pauseLabel | pauseLabel | pauseLabel | pauseLabel | pauseLabel |
previousLabel · Propiedad | previousLabel | previousLabel | previousLabel | previousLabel | previousLabel |
nextLabel · Propiedad | nextLabel | nextLabel | nextLabel | nextLabel | nextLabel |
label · Propiedad | label | label | contentDescription | semanticLabel | accessibilityLabel |
pausedChange · Evento | pausedchange | isPaused | onPausedChange | onPausedChanged | onPausedChange |
| Notas | Attributes: hero-alignment, item-width (a number of CSS pixels; without it the property is null), content-alignment, scale-others, loop, indicator, autoplay, autoplay-interval (milliseconds), paused, autoplay-progress, play-label, pause-label, navigation (reflected), previous-label, next-label. fluidWidth, snap and playbackControl are boolean properties that default to true; their attributes are the inverses fixed-width, free-scroll and no-playback-control (an HTML boolean attribute cannot default to true). pausedchange is a CustomEvent whose detail.paused is the new value. Built on a native horizontal scroller (so wheel, trackpad and touch scroll as the platform does) whose track is as long as the scroll range; the items are placed from its scroll offset (CRL-12), and the settle animates the scroll offset over comp.carousel.motion.scroll-duration and scroll-easing once the scroll ends (scrollend, or 100 ms without a scroll event, because not every engine sends scrollend after a wheel), since a smooth scrollTo cannot follow the tokens. Fling 0.5 px/ms, measured from the finger's last touch moves over their own time stamps; after a fling the settle starts at the release, and the browser's momentum is held until it ends. While loop is in effect the track is several turns long and the offset is moved by a whole number of turns (N × (H + g)) when the row rests near either end, which draws nothing new. Autoplay reads prefers-reduced-motion and document.visibilityState when it would advance and listens for their changes; the hover hold is pointerenter / pointerleave on the host, the focus hold focusin / focusout. The items are placed from one scroll position in one pass, each start rounded to a device pixel and each end taken from the next start (CRL-40). The previous and next controls are <tanrei-button> elements with focusable-when-disabled, given their variant through the Button's group-item channel; auto draws them under (hover: hover) and (pointer: fine) and shows them while the host matches :hover or :focus-within. Snapshot harness: a 400 × 200 stage (the carousel fills it: W 368), or 400 × 248 for the fixtures with a controls row, on a surface page, scrolled to its start, the pointer outside, motion not reduced and the autoplay clock stopped at the start of its interval. | Lagging: ships an earlier revision of this spec, with layout and its three values, and no loop, dots or autoplay, and so owes the hero centred by default, the edge slots of no width, the scaled slots closed up and the constant gap as well (CRL-9 to CRL-13, CRL-26, CRL-40), and the previous and next controls with their props navigation, previousLabel and nextLabel (CRL-41 to CRL-43). Target API: TanreiCarousel(_ label: String, heroAlignment: .center, itemWidth: CGFloat? = nil, fluidWidth: true, contentAlignment: .center, scaleOthers: false, snap: true, loop: false, showsIndicator: false, autoplay: false, autoplayInterval: Duration? = nil, isPaused: Binding<Bool>, showsPlaybackControl: true, showsAutoplayProgress: false, playLabel:, pauseLabel:) { TanreiCarouselItem(…) { … } }; pausedChange is the isPaused binding, set only by the control. A horizontal ScrollView whose content is a track as long as the scroll range, the items placed from the scroll offset by a custom Layout (read from scrollPosition and the track's geometry), settled by a custom ScrollTargetBehavior (iOS 17). The list is an accessibilityElement(children: .contain) named by label, and each item a button. SwiftUI has no position-in-set property for a custom container, so VoiceOver's own count of the container's elements stands in; the README says so. Autoplay reads accessibilityReduceMotion and scenePhase. Snapshot harness: a 400 × 200 frame (400 × 248 with a controls row) on a surface page. | Lagging: ships an earlier revision of this spec, with layout and its three values, and no loop, dots or autoplay, and so owes the hero centred by default, the edge slots of no width, the scaled slots closed up and the constant gap as well (CRL-9 to CRL-13, CRL-26, CRL-40), and the previous and next controls with their props navigation, previousLabel and nextLabel (CRL-41 to CRL-43). Target API: TanreiCarousel(itemCount, contentDescription, heroAlignment, itemWidth: Dp? = null, fluidWidth = true, contentAlignment, scaleOthers = false, snap = true, loop = false, indicator = false, autoplay = false, autoplayInterval: Duration? = null, paused = false, onPausedChange, playbackControl = true, autoplayProgress = false, playLabel, pauseLabel) { index -> TanreiCarouselItem(…) { … } }, as Material's carousels take an item lambda; built on Modifier.scrollable and a custom Layout, not Material's carousel (the package does not depend on Material). Settling uses a SnapFlingBehavior whose fling threshold is ViewConfiguration's. No list role: collectionInfo on the row and collectionItemInfo with Role.Button on each item. Autoplay reads the animator duration scale (0 is reduced motion) and the lifecycle's resumed state. Snapshot harness: a 400 × 200 dp box (400 × 248 with a controls row) on a surface page. | Lagging: ships an earlier revision of this spec, with layout and its three values, and no loop, dots or autoplay, and so owes the hero centred by default, the edge slots of no width, the scaled slots closed up and the constant gap as well (CRL-9 to CRL-13, CRL-26, CRL-40), and the previous and next controls with their props navigation, previousLabel and nextLabel (CRL-41 to CRL-43). Target API: TanreiCarousel(semanticLabel:, heroAlignment: TanreiCarouselHeroAlignment.center, itemWidth: null, fluidWidth: true, contentAlignment: TanreiCarouselContentAlignment.center, scaleOthers: false, snap: true, loop: false, indicator: false, autoplay: false, autoplayInterval: null, paused: false, onPausedChanged:, playbackControl: true, autoplayProgress: false, playLabel:, pauseLabel:, children: [...]), built on the widgets library's Scrollable with a custom layout and ScrollPhysics that settle (CRL-14), not Material's CarouselView. Each item is Semantics(button: true, label:) inside IndexedSemantics, and the scrollable reports semanticChildCount, so the position and the number of items are read; the whole is a Semantics(label:, explicitChildNodes: true) container. Autoplay reads MediaQuery.disableAnimationsOf and the app lifecycle. Snapshot harness: a golden of a 400 × 200 surface (400 × 248 with a controls row) on a surface page. | Lagging: ships an earlier revision of this spec, with layout and its three values, and no loop, dots or autoplay, and so owes the hero centred by default, the edge slots of no width, the scaled slots closed up and the constant gap as well (CRL-9 to CRL-13, CRL-26, CRL-40), and the previous and next controls with their props navigation, previousLabel and nextLabel (CRL-41 to CRL-43). Target API: <Carousel accessibilityLabel heroAlignment itemWidth fluidWidth contentAlignment scaleOthers snap loop indicator autoplay autoplayInterval paused onPausedChange playbackControl autoplayProgress playLabel pauseLabel>{items}</Carousel>: a horizontal ScrollView whose content is as long as the scroll range, the items placed from an Animated value of its offset; it settles with scrollTo after the drag or momentum ends (fling 0.5 pt/ms). The carousel has role="list" and each item the button role. React Native has no position-in-set property, so an item's position and the number of items are left to the screen reader's own count of the list; the README says so. Autoplay reads AccessibilityInfo.isReduceMotionEnabled and AppState. No virtualization. Snapshot harness: a 400 × 200 view (400 × 248 with a controls row) on a surface page. |
Tokens
| Token | Alias de | Valor resuelto (claro) |
|---|---|---|
--tanrei-comp-carousel-autoplay-interval | — | 5000ms |
--tanrei-comp-carousel-container-large-width | — | 200px |
--tanrei-comp-carousel-container-min-scale | — | 0.85 |
--tanrei-comp-carousel-container-shape | sys.shape.corner.large | 12px |
--tanrei-comp-carousel-container-small-max-width | — | 56px |
--tanrei-comp-carousel-container-small-min-width | — | 40px |
--tanrei-comp-carousel-controls-button-size | — | 40px |
--tanrei-comp-carousel-controls-height | sys.target.touch | 48px |
--tanrei-comp-carousel-controls-icon-size | sys.icon.medium | 24px |
--tanrei-comp-carousel-controls-indicator-padding-inline | sys.space.space150 | 12px |
--tanrei-comp-carousel-controls-shape | sys.shape.corner.full | 9999px |
--tanrei-comp-carousel-dot-active-width | — | 24px |
--tanrei-comp-carousel-dot-color | sys.color.outline | |
--tanrei-comp-carousel-dot-gap | sys.space.space100 | 8px |
--tanrei-comp-carousel-dot-size | — | 8px |
--tanrei-comp-carousel-focused-container-shape | — | 12px |
--tanrei-comp-carousel-focused-opacity | — | 1 |
--tanrei-comp-carousel-hovered-container-shape | — | 12px |
--tanrei-comp-carousel-hovered-opacity | — | 1 |
--tanrei-comp-carousel-indicator-container-color | — | |
--tanrei-comp-carousel-indicator-content-color | sys.color.primary | |
--tanrei-comp-carousel-indicator-focused-container-color | — | |
--tanrei-comp-carousel-indicator-focused-content-color | — | |
--tanrei-comp-carousel-indicator-focused-state-layer-color | — | |
--tanrei-comp-carousel-indicator-hovered-container-color | — | |
--tanrei-comp-carousel-indicator-hovered-content-color | — | |
--tanrei-comp-carousel-indicator-hovered-state-layer-color | — | |
--tanrei-comp-carousel-indicator-pressed-container-color | — | |
--tanrei-comp-carousel-indicator-pressed-content-color | — | |
--tanrei-comp-carousel-indicator-pressed-state-layer-color | — | |
--tanrei-comp-carousel-indicator-state-layer-color | comp.carousel.indicator.content.color | |
--tanrei-comp-carousel-item-container-color | sys.color.surface-container-highest | |
--tanrei-comp-carousel-item-content-color | sys.color.on-surface | |
--tanrei-comp-carousel-item-focused-container-color | — | |
--tanrei-comp-carousel-item-focused-content-color | — | |
--tanrei-comp-carousel-item-focused-state-layer-color | — | |
--tanrei-comp-carousel-item-hovered-container-color | — | |
--tanrei-comp-carousel-item-hovered-content-color | — | |
--tanrei-comp-carousel-item-hovered-state-layer-color | — | |
--tanrei-comp-carousel-item-pressed-container-color | — | |
--tanrei-comp-carousel-item-pressed-content-color | — | |
--tanrei-comp-carousel-item-pressed-state-layer-color | — | |
--tanrei-comp-carousel-item-state-layer-color | comp.carousel.item.content.color | |
--tanrei-comp-carousel-layout-gap | sys.space.space100 | 8px |
--tanrei-comp-carousel-layout-height | — | 200px |
--tanrei-comp-carousel-layout-padding-inline | sys.space.space200 | 16px |
--tanrei-comp-carousel-motion-autoplay-duration | sys.motion.duration.long2 | 500ms |
--tanrei-comp-carousel-motion-autoplay-easing | sys.motion.easing.standard | cubic-bezier(0.2, 0, 0, 1) |
--tanrei-comp-carousel-motion-feedback-duration | sys.motion.role.feedback | 450ms |
--tanrei-comp-carousel-motion-scroll-duration | sys.motion.duration.medium2 | 300ms |
--tanrei-comp-carousel-motion-scroll-easing | sys.motion.easing.emphasized-decelerate | cubic-bezier(0.05, 0.7, 0.1, 1) |
--tanrei-comp-carousel-motion-state-duration | sys.motion.role.state.large | 250ms |
--tanrei-comp-carousel-motion-state-easing | sys.motion.easing.state | cubic-bezier(0.2, 0, 0, 1) |
--tanrei-comp-carousel-navigation-button-variant | — | 2 |
--tanrei-comp-carousel-playback-container-color | — | |
--tanrei-comp-carousel-playback-content-color | sys.color.on-surface-variant | |
--tanrei-comp-carousel-playback-focused-container-color | — | |
--tanrei-comp-carousel-playback-focused-content-color | — | |
--tanrei-comp-carousel-playback-focused-state-layer-color | — | |
--tanrei-comp-carousel-playback-hovered-container-color | — | |
--tanrei-comp-carousel-playback-hovered-content-color | — | |
--tanrei-comp-carousel-playback-hovered-state-layer-color | — | |
--tanrei-comp-carousel-playback-pressed-container-color | — | |
--tanrei-comp-carousel-playback-pressed-content-color | — | |
--tanrei-comp-carousel-playback-pressed-state-layer-color | — | |
--tanrei-comp-carousel-playback-state-layer-color | comp.carousel.playback.content.color | |
--tanrei-comp-carousel-pressed-container-shape | — | 12px |
--tanrei-comp-carousel-pressed-opacity | — | 1 |
Fixtures
Representaciones canónicas. Todas las plataformas capturan cada fixture con el mismo identificador para poder comparar los resultados.
centered
previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 5 fixed-width
fluidWidth: false snap: false previousLabel: Previous walk nextLabel: Next walk label: Walks near you items: 5 scaled
fluidWidth: false scaleOthers: true loop: true previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 5 loop
loop: true previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 5 content-toward-hero
itemWidth: 120 contentAlignment: toward-hero loop: true previousLabel: Previous walk nextLabel: Next walk label: Walks near you items: 6 navigation
navigation: always previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 5 indicator
indicator: true previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 6 autoplay
indicator: true autoplay: true playLabel: Play the slideshow pauseLabel: Pause the slideshow previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 6 autoplay-progress
indicator: true autoplay: true autoplayProgress: true playLabel: Play the slideshow pauseLabel: Pause the slideshow previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 6 autoplay-paused
indicator: true autoplay: true paused: true autoplayProgress: true playLabel: Play the slideshow pauseLabel: Pause the slideshow previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 6 playback-control
autoplay: true playLabel: Play the slideshow pauseLabel: Pause the slideshow previousLabel: Previous walk nextLabel: Next walk label: Featured walks items: 4 Generado a partir de specs/carousel.spec.json, tokens/comp/carousel.tokens.json, design/tokens/
Usa un carrusel para una fila de elementos visuales que las personas exploran y abren de uno en uno: álbumes, lugares, productos, episodios. Muestra que siguen más elementos sin ocupar la altura de una cuadrícula, y da más espacio a los elementos que están a la vista que a los que están a punto de llegar.
Usa una lista cuando los elementos sean sobre todo texto, o cuando las personas los comparen o elijan entre ellos. Usa tarjetas en una cuadrícula cuando cada elemento necesite su propio texto y sus propias acciones. Haz que un carrusel avance por sí solo únicamente en una fila destacada corta, y conserva su control de reproducción.
Cada propiedad responde a una pregunta, y se combinan libremente.
| Propiedad | Valor predeterminado | Qué decide |
|---|---|---|
heroAlignment |
center |
Dónde se sitúa el elemento en primer plano: en el centro (center), con elementos a ambos lados, o en el borde interior de inicio (start), con elementos solo después de él. |
itemWidth |
El del sistema de diseño | El ancho del elemento principal. Con anchos fijos, el ancho de todos los elementos. |
fluidWidth |
true |
Con true, los elementos situados junto al elemento principal se estrechan a un ancho mediano y a uno pequeño, y cada ancho sigue al desplazamiento. Con false, todos los elementos tienen el ancho del elemento principal, y el último que está a la vista queda cortado por el borde. |
contentAlignment |
center |
Con anchos fluidos, qué parte del contenido de un elemento estrechado se muestra: su centro, o el lado más cercano al elemento principal (toward-hero). |
scaleOthers |
false |
Dibuja más pequeños los elementos que no son el principal, siguiendo al desplazamiento, con anchos fluidos o fijos. La separación entre elementos no cambia: con anchos fijos, los elementos más pequeños se acercan a sus vecinos. |
snap |
true |
La fila se asienta en un elemento entero cuando termina un desplazamiento, o reposa donde este termine. |
loop |
false |
Hace que la fila no tenga fin: después del último elemento viene el primero. Solo con dos elementos o más. |
En la web, fluidWidth es fixed-width y snap es free-scroll, por ser los inversos de propiedades que son true de forma predeterminada.
Algunas filas habituales:
| Para | Define |
|---|---|
| Explorar muchos elementos: álbumes, lugares | Nada: los valores predeterminados. |
| Un elemento destacado cada vez, con un asomo del siguiente | Un itemWidth al menos tan ancho como el carrusel. El elemento principal toma el mayor ancho que puede tener. |
| Una fila destacada con elementos a ambos lados | Nada más: el elemento principal está en el centro de forma predeterminada. A menudo con loop, para que ambos lados estén siempre llenos. |
| Una fila que empieza en el borde, con el elemento principal primero | heroAlignment start. |
| Una fila sencilla que se desplaza, como los elementos vistos recientemente | heroAlignment start, fluidWidth false y snap false. |
Elige itemWidth según la forma de tu contenido: las portadas cuadradas, los carteles altos y las miniaturas anchas piden anchos distintos, incluso dentro de un mismo producto. Con anchos fluidos, el elemento principal deja sitio a los demás: nunca crece más allá del ancho que deja un elemento pequeño a cada lado donde siguen elementos, y nunca se encoge por debajo del ancho que mantiene al elemento siguiente no más ancho que él. En una fila demasiado estrecha para eso, el carrusel muestra un elemento cada vez, tan ancho como la fila.
Dos cosas difieren de la revisión anterior. Hasta que las demás plataformas se pongan al día, este es el comportamiento de la web.
- El valor predeterminado de
heroAlignmentes ahoracenter. Antes erastart. Los dos valores se mantienen. - Los elementos vecinos quedan a una separación de distancia en cualquier posición del desplazamiento, no solo en reposo. Antes, la separación crecía cuando un elemento pasaba por el borde de la fila, y un elemento a escala reducida dejaba espacio de más a su alrededor.
| Tenías | Ahora |
|---|---|
Ningún heroAlignment |
El elemento principal está en el centro, con un elemento más estrecho a cada lado. Para mantener la fila como estaba, define heroAlignment como start (hero-alignment="start" en la web). |
heroAlignment start |
Nada que cambiar. |
heroAlignment center |
Nada que cambiar. Puedes quitar la propiedad. |
scaleOthers con anchos fijos |
Los elementos más pequeños quedan ahora a una separación de sus vecinos, más cerca que antes. Nada que cambiar. |
Un itemWidth más ancho que la fila, sin heroAlignment |
El elemento principal es más estrecho que antes, porque queda un elemento pequeño a cada lado. Define heroAlignment como start para obtener el elemento principal más ancho. |
Con anchos fluidos, un elemento entra ahora en la fila desde la nada en el borde y crece a medida que entra, en lugar de deslizarse hacia dentro con todo su ancho. En reposo, la fila se ve como antes.
La propiedad layout de la revisión anterior se ha eliminado. Cada uno de sus valores es ahora una combinación de las propiedades anteriores:
layout anterior |
Ahora |
|---|---|
| Con su valor predeterminado | heroAlignment start. En una fila no más ancha que un teléfono, la imagen es la misma. En una fila más ancha, el elemento principal crece hasta su límite. |
hero |
heroAlignment start y un itemWidth al menos tan ancho como el carrusel, para que el elemento principal tome el mayor ancho que puede tener. La misma imagen. |
uncontained |
heroAlignment start, fluidWidth false y snap false (hero-alignment="start" fixed-width free-scroll en la web). La misma imagen. |
- Puntos.
indicatordibuja un punto por cada posición de reposo, en una fila debajo de los elementos, centrada respecto al carrusel. El punto actual está estirado, y el estiramiento pasa de un punto al siguiente a medida que la fila se desplaza. Los puntos son un solo control: pulsa o arrastra en cualquier lugar sobre ellos para mover la fila. Úsalos en una fila destacada corta. Si hay demasiados para caber junto al control de reproducción, no se dibujan, y las compilaciones de depuración lo indican. - Reproducción automática.
autoplayhace avanzar la fila un elemento cadaautoplayIntervalmilisegundos (5 segundos en el sistema predeterminado). Da más tiempo a los elementos con mucho texto que a las imágenes. Sinloop, vuelve al primer elemento después del último. Nunca mueve el foco y no anuncia nada. - Pausas temporales. La reproducción automática se detiene temporalmente mientras el puntero está sobre el carrusel, mientras el foco está en cualquier lugar dentro de él, mientras se pulsa o se arrastra y mientras la ventana está oculta. Cuando termina la última pausa temporal, continúa donde se detuvo; después de que la persona mueva la fila, el intervalo empieza de nuevo.
- Reducir movimiento. Donde el ajuste de reducir movimiento de la plataforma está activado, la reproducción automática nunca se ejecuta, y el control de reproducción y el progreso no se dibujan. Los anchos, la escala y los puntos siguen acompañando al desplazamiento de la propia persona.
- El control de reproducción. Mientras la reproducción automática está activada, un botón redondo al final de la fila de los puntos la pausa y la reanuda, mostrando
pauseoplay_arrow. Recibe su nombre depauseLabelo deplayLabel, según lo que vaya a hacer. Cambiapausedy emitepausedChange(pausedchangeen la web); tu código también puede definirpaused, lo cual no emite nada. - Progreso. Con
autoplayProgress, el punto actual se llena a medida que pasa el tiempo que falta hasta el elemento siguiente.
Mantén la reproducción bajo control. Un producto puede ocultar el control de reproducción con playbackControl en false, pero debería conservarlo siempre que pueda. Las pausas temporales no son una forma de detener el movimiento: en una pantalla táctil no hay cursor que pasar por encima, un dedo retiene la fila solo mientras descansa sobre ella, y un lector de pantalla que lee sin mover el foco no la retiene en absoluto. Sin el control, una persona con un teléfono solo puede detener un carrusel con reproducción automática mediante el ajuste de reducir movimiento del sistema. Ocúltalo solo donde tu producto ofrezca otra forma de detener el movimiento, como una pausa para todo el contenido en movimiento de la página (WCAG 2.2.2).
Una fila sin barra de desplazamiento no le da al ratón ninguna pulsación única que la mueva: solo Mayús con la rueda, o los puntos donde se dibujan. Por eso el carrusel dibuja un control anterior y uno siguiente sobre los extremos de su fila. Son Buttons solo de icono con galones, en la variante que nombra el sistema de diseño (elevated en el sistema predeterminado), y cada uno mueve la fila un elemento atrás o adelante, como hacen los puntos y las teclas de flecha.
navigation |
Se dibujan | Se muestran |
|---|---|---|
auto (predeterminado) |
Donde el puntero principal es un ratón o un panel táctil, que puede pasar por encima | Mientras el puntero está sobre el carrusel o el foco está dentro de él |
always |
En todos los dispositivos, también los táctiles | Siempre |
none |
Nunca | Nunca |
- Por qué no en pantallas táctiles de forma predeterminada. El dedo desliza la fila, y en un teléfono los controles quedarían sobre los elementos todo el tiempo. Elige
alwaysdonde tus usuarios también los necesiten en pantallas táctiles. - En los extremos. Sin
loop, el control anterior se desactiva en el primer elemento y el siguiente en el último. Un control desactivado conserva el foco y su lugar en el orden de tabulación, así que pulsar siguiente una y otra vez nunca hace perder el foco. Conloop, dan la vuelta. - Las pulsaciones se suman. Una pulsación mientras la fila se mueve cuenta desde donde va, así que dos pulsaciones rápidas mueven dos elementos.
- Reproducción automática. Una pulsación es un movimiento de la propia persona: el intervalo vuelve a empezar cuando la fila se detiene. Mientras el puntero está sobre los controles, o el foco está en ellos, la reproducción automática se detiene temporalmente, como en cualquier otro lugar del carrusel.
- Nombres.
previousLabelynextLabellos nombran para las tecnologías de apoyo, por ejemplo «Paseo anterior» y «Paseo siguiente». Las compilaciones de depuración notifican si falta alguno.
Mantén auto siempre que puedas. Elige none solo donde tu página le dé al ratón otra forma de mover la fila, como los puntos.
- El contenido se dispone con el ancho del elemento principal. Todos los elementos disponen su contenido con el ancho del elemento principal, de modo que un elemento estrechado muestra el centro de su imagen, o el lado más cercano al elemento principal con
contentAlignmenttoward-hero, y la imagen se desliza dentro del elemento a medida que este crece y se encoge. Proporciona una imagen que se entienda bien a partir de la parte que se muestra. - Sin texto sobre el elemento. El elemento no dibuja ninguna leyenda, porque no se puede garantizar ningún contraste para un texto sobre una imagen. Pon una leyenda en tu contenido, sobre un velo propio, o muéstrala fuera del carrusel.
- Una sola acción por elemento. Un elemento abre lo que muestra. Mantén los botones, los enlaces y otros controles fuera de su contenido.
- Ningún elemento deshabilitado. Una fila para explorar no tiene nada que se muestre pero no esté disponible. Deja fuera un elemento así.
- Los elementos vacíos también se ven. El contenedor del elemento se rellena, bajo su contenido, con su color de reposo, sea cual sea el estado del elemento, de modo que un elemento cuya imagen todavía no se ha cargado sigue siendo visible.
- Los estados se muestran sobre el contenido. El paso del cursor, el foco y la pulsación se dibujan como una capa sobre el contenido, con la onda en esa misma capa, así que se ven sobre cualquier imagen.
Las personas desplazan la fila con el tacto, un lápiz, un panel táctil, una rueda horizontal o Mayús con una rueda vertical. Con snap, la fila se asienta en un elemento entero cuando termina el desplazamiento: un lanzamiento avanza hasta el elemento siguiente en su dirección, y al soltar más despacio va al más cercano. Un lanzamiento es soltar a una velocidad mayor que la velocidad mínima de lanzamiento de la plataforma, o que 0.5 puntos por milisegundo donde la plataforma no indica ninguna. Sin loop, al final del recorrido el último elemento es el principal, y los huecos que le siguen quedan vacíos. Con loop, cada elemento se dibuja una sola vez, en el lugar que le corresponda alrededor del elemento principal, y la fila da vueltas sin fin. Cuando el movimiento está reducido, todo movimiento que el propio carrusel inicia ocurre de inmediato. Con un ratón, los controles anterior y siguiente la mueven elemento a elemento.
Cuando cambian el ancho del carrusel o sus elementos, este vuelve a organizar sus huecos y mantiene donde estaba el elemento que se encontraba en primer plano, sin movimiento.
- Etiqueta cada elemento con lo que muestra su contenido, en el idioma de tu producto.
- Elige
itemWidthde modo que se ajuste a la forma del contenido. - Dale al carrusel un
labelque dé nombre a la fila, como «Reproducido recientemente». - Conserva el control de reproducción siempre que el carrusel avance por sí solo, y dale un
playLabely unpauseLabel.
- No pongas controles dentro del contenido de un elemento. El elemento ya es un botón.
- No uses un carrusel para contenido que las personas deben ver entero, como unos pasos o unas condiciones. Los elementos que no están a la vista pasan inadvertidos con facilidad.
- No actives la reproducción automática en una fila larga para explorar. Es adecuada para una fila destacada corta, con puntos.
- No ocultes el control de reproducción salvo que tu producto ofrezca otra forma de detener el movimiento.
- Rol
list- Etiquetado
- The items are a list named by label. Each item is one button named by its label, with its position and the number of items; its content is not read. The indicator is one slider named by label, whose value text is the current item's label. The playback control is a button named by pauseLabel while playing and by playLabel while paused. Items out of view are still reachable, and focusing one scrolls it into place. The previous and next controls are buttons named by previousLabel and nextLabel, disabled at the ends of a row that does not loop.
- Objetivo mínimo
- El área de pulsación cumple el tamaño mínimo de objetivo aunque el tamaño visual sea menor. minimum 32px · pointer 44px · spacing 8px · touch 48px
Teclado
| Teclas | Acción |
|---|---|
| Tab / Shift+Tab | Moves through the carousel's stops: the playback control (while it is drawn), the previous and next controls (while they are drawn), then the items as one stop (the item that last had focus, or else the resting item), then the indicator (while it is drawn), and on out (CRL-17). |
| Right Arrow / Left Arrow | On an item: moves focus to the next or previous item and brings it into place. On the indicator: moves the row to the next or previous position. Both wrap only while the carousel loops, and are mirrored in right-to-left layouts. |
| Home / End | On an item: moves focus to the first or last item and brings it into place. On the indicator: moves the row to the first or last position. |
| Enter / Space | On an item: activates it (its click). On the playback control: pauses or plays autoplay. On the previous or the next control: moves the row back or on by one position (CRL-43). |
Notas
- Scrolling is never the only way to reach an item (WCAG 2.5.7, 2.1.1): the previous and next controls move the row one position with a single press of a mouse — drawn by default wherever the primary pointer is fine and can hover —, and the arrow keys, the indicator and screen-reader focus move through every item and bring it into place. The row draws no scroll bar, so without the controls a mouse could move the row only with Shift and the wheel.
- Where the previous and next controls are, and when. They stand over the ends of the row, as the arrows of Ant Design's and Mantine's carousels and the overlay layouts of Fluent 2's do, not in the controls row, which exists only for a featured row with dots or autoplay. By default (auto) they are drawn only for a pointer that is fine and can hover, and shown while it is over the carousel or focus is within it: a touch screen moves the row with the finger's own swipe, and there the controls would stand over the items for good. A product whose people need them on touch as well sets always. Their place in the Tab sequence is the WAI-ARIA carousel example's: the playback control, then previous and next, then the slides.
- A previous or next control at the end of a row that does not loop is disabled but keeps focus and its place in the Tab order (the Button's focusableWhenDisabled), so that pressing next again and again never drops focus to the page, and the number of stops does not change with the scroll.
- An item entering or leaving at an edge of a row with fluid widths is, between resting positions, narrower than a touch target (CRL-4, CRL-12). A row that snaps never rests there; a row that does not snap can, and the arrow keys, the indicator and a further scroll all bring that item to a slot, where it has its whole target.
- Autoplay (WCAG 2.2.2 Pause, Stop, Hide). A carousel that advances by itself holds while it is hovered, while focus is anywhere in it, while it is pressed and while it is hidden, and it never advances where the platform's reduced-motion setting is on (CRL-33, CRL-34). While autoplay is on, the playback control is drawn by default and is the first Tab stop, so a keyboard user reaches it before the items (CRL-17).
- Keep playback controllable. A product may hide the playback control (playbackControl false), but it should keep it wherever it can. The holds are not a way to stop the motion: on touch there is no hover, a finger on the carousel holds it only while it stays there, and a screen reader that reads without moving focus does not hold it at all. Without the control, a person on a phone can stop an autoplaying carousel only through the system's reduced-motion setting. Hide it only where the product gives the person another way to stop the motion, such as a pause for all moving content on the page.
- Autoplay makes no announcement and never moves focus (CRL-32). A person who wants to know what changed finds the current item as the indicator's value.
- Loop keeps the arrow keys and the indicator going round, but Home and End still go to the first and last item, so a person can always find the ends of an endless row.
- The indicator is one slider, not a row of unlabelled buttons: one Tab stop, the arrow keys to move, the current item's label as its value. Its hit area is the whole container and the controls row's height, so the dots need no target of their own.
- The current dot is told apart by its stretched shape, not by color alone (WCAG 1.4.1), and the other dots use the functional outline role (3:1 against the surface).
- Web: the host has no role; a shadow element with role list, named by label, holds the item slot, so the slotted `<tanrei-carousel-item>` elements (role listitem, around a shadow element with role button and tabindex, roving: 0 on the Tab stop, -1 on the others) are its items, as the interactive card draws its button. The indicator is a shadow element with role slider and tabindex 0, and the playback control a native `<button>`; both sit after the list, outside it. Compose has no list role: the row gives `collectionInfo` and each item `collectionItemInfo` with `Role.Button`; the indicator is a `progressBarRangeInfo` with `setProgress`. Flutter reads each item's position through `IndexedSemantics`, and the indicator is a `Semantics(slider: true)` with increase and decrease actions. SwiftUI's indicator is `accessibilityAdjustableAction`, React Native's the adjustable role with increment and decrement actions. SwiftUI and React Native have no position-in-set property for a custom container, so there the screen reader's own count of the items stands in for CRL-19's position and number; their READMEs say so.
- How a state looks is a value decision of the active design system; components read the state's tokens and never compute the effect themselves.
Generado a partir de specs/carousel.spec.json, tokens/sys/measure.tokens.json
- El carrusel es una lista que recibe su nombre de
label. Cada elemento es un solo botón que recibe su nombre de su etiqueta, con su posición entre los elementos y el número de estos. Su contenido queda oculto para la tecnología de apoyo. - Los elementos que no están a la vista siguen expuestos, en orden, de modo que un lector de pantalla llega a todos. Al mover el foco del lector de pantalla a un elemento, este se desplaza hasta su lugar.
- Paradas de tabulación. El carrusel tiene hasta cinco: el control de reproducción, mientras se dibuja; los controles anterior y siguiente, mientras se dibujan; los elementos, como una sola parada; y los puntos, mientras se dibujan. El control de reproducción va primero, antes de los elementos, para que quien usa el teclado pueda detener el movimiento antes de llegar a cualquier otra cosa. Los controles anterior y siguiente van antes de los elementos, como en el ejemplo de carrusel de WAI-ARIA. A los elementos se entra por el último que tuvo el foco del teclado o, si no lo hay, por el elemento que reposa en el lugar del elemento principal.
- Flecha derecha y Flecha izquierda mueven el foco al elemento siguiente y al anterior. Se detienen en los extremos, y dan la vuelta solo mientras el carrusel esté en bucle. Inicio y Fin van al primer y al último elemento, incluso en una fila en bucle. En un diseño de derecha a izquierda, Flecha izquierda va al elemento siguiente.
- Al mover el foco, el elemento con foco pasa al lugar del elemento principal, tan cerca como lo permita el final del recorrido, y por el camino más corto en una fila en bucle. En una fila con anchos fijos y desplazamiento libre desde el inicio, simplemente trae el elemento entero a la vista.
- Enter y Espacio activan el elemento con foco. Una pulsación que se convierte en un desplazamiento no activa el elemento sobre el que empezó.
- Los puntos son un solo control deslizante que recibe su nombre de
labely cuyo valor es la etiqueta del elemento actual. Las teclas de flecha, Inicio y Fin, y las acciones de incrementar y disminuir de la plataforma mueven la fila una posición. El punto actual se distingue por su forma estirada, no solo por el color. - El control de reproducción es un botón que recibe su nombre de
pauseLabelmientras reproduce y deplayLabelmientras está en pausa. No tiene estado pulsado, así que nunca se lee como «Pausar, pulsado». Al activarlo, el foco permanece en él. Sus glifos de pausa y de reproducción no se reflejan, y antes de que se haya cargado la fuente de iconos no se dibuja como texto el nombre de ningún glifo. - Los controles anterior y siguiente son botones que reciben su nombre de
previousLabelynextLabel. Al activar uno, el foco permanece en él. En los extremos de una fila que no da la vuelta, el control se desactiva, pero conserva el foco y sigue en el orden de tabulación. Ocultos conauto, la tabulación los sigue alcanzando y el lector de pantalla los lee, y el foco los muestra. En un diseño de derecha a izquierda, el control anterior queda a la derecha y los galones se reflejan donde el conjunto de iconos lo indica. - La reproducción automática se detiene temporalmente mientras el foco está en cualquier lugar del carrusel, nunca mueve el foco, no anuncia nada y nunca se ejecuta cuando el movimiento está reducido.
- El anillo de foco se dibuja dentro del elemento, donde la fila no puede recortarlo, y alrededor de los puntos y del control de reproducción. Se muestra solo para el foco del teclado.
- El área de pulsación de cada elemento es su contenedor más la mitad de la separación a cada lado, y nunca es menor que el objetivo mínimo, ni siquiera en un elemento pequeño. Un elemento que todavía está entrando o saliendo por el borde es más estrecho que eso, y su área de pulsación nunca cubre la de su vecino. El área de pulsación del control de reproducción es el objetivo táctil, y la de los puntos es todo su contenedor y la altura de la fila.
- El desplazamiento nunca es la única forma de llegar a un elemento: los controles anterior y siguiente mueven la fila con una sola pulsación del ratón (WCAG 2.5.7), y las teclas de flecha, los puntos y el foco del lector de pantalla llegan a todos.
- El carrusel conserva su altura y sus elementos con tamaños de texto mayores. No contiene ningún texto propio, y tu contenido sigue por sí mismo el tamaño del texto.
- Las compilaciones de depuración notifican un elemento sin etiqueta, un carrusel sin
label, un control de reproducción sinplayLabelopauseLabel, unos controles anterior y siguiente sinpreviousLabelonextLabel, unos puntos que no caben, unheroAlignment, uncontentAlignmento unnavigationdesconocidos, y unitemWidtho unautoplayIntervalque no es un número positivo. La web notifica además un elemento interactivo dentro del contenido de un elemento.
Carencias conocidas por plataforma:
- SwiftUI y React Native no tienen una propiedad de posición en el conjunto para un contenedor personalizado, así que el recuento de elementos del propio lector de pantalla hace las veces de la posición de cada elemento y del número de elementos. SwiftUI tampoco tiene rol de lista: el carrusel es un contenedor que recibe su nombre de
label. - Compose no tiene rol de lista. La fila proporciona el tamaño de su colección y cada elemento su posición, con el rol de botón, así que TalkBack anuncia una colección y no una lista.
- Solo la web puede inspeccionar el contenido de un elemento, así que solo la web notifica un control dentro de él. En las demás plataformas, cumplir la regla te corresponde a ti.
- Web: la parada de tabulación pasa a cualquier elemento que reciba el foco, incluido el de un clic, mientras que la especificación indica el elemento que tuvo por última vez el foco del teclado. Un lanzamiento con el lápiz se asienta en el elemento más cercano, no en el siguiente. El cursor virtual de un lector de pantalla que no mueve el foco desplaza la fila como lo hace el navegador, sin llevar el elemento al lugar del elemento principal.
- SwiftUI: el carrusel siempre es tan alto como su token de altura, porque SwiftUI no puede distinguir un marco de la propuesta de una pila. Dale tamaño mediante los tokens de una capa. El asentamiento se mueve con la desaceleración propia de la vista de desplazamiento, no con el movimiento de desplazamiento del carrusel, y no de inmediato cuando el movimiento está reducido. Construye todos los elementos y vuelve a colocar cada uno en cada fotograma del desplazamiento. Las teclas de flecha, la parada de tabulación y el foco de VoiceOver se prueban como reglas, no con un teclado ni con VoiceOver en un dispositivo.
- Compose compone y dispone todos los elementos, incluidos los que no están a la vista. Una rueda, que no produce lanzamientos, se asienta en el elemento más cercano. El desplazamiento solo se ha verificado con Robolectric, no en un dispositivo.
- Flutter asienta un carrusel con ajuste después de cada evento de la rueda del ratón, no cuando termina el gesto de la rueda. Todavía no se ha comprobado con TalkBack y VoiceOver en un dispositivo.
- React Native vuelve a disponer todos los elementos en el hilo de JavaScript en cada fotograma del desplazamiento, y renderiza todos los elementos. Las teclas de flecha solo funcionan donde los eventos de un teclado físico llegan a la aplicación. La colocación guiada por el desplazamiento, el asentamiento, la diseño de derecha a izquierda y el foco del lector de pantalla solo se han verificado en Jest, nunca en un dispositivo.
- Con
m3-like, los elementos conservan el relleno predeterminado donde el carrusel de Material usa el color de la superficie, a propósito, para que un elemento cuya imagen no se ha cargado siga viéndose.
- Dale al carrusel un
label, y a cada elemento una etiqueta que diga qué muestra su contenido. El contenido no se lee. - Con reproducción automática, dale al control de reproducción un
playLabely unpauseLabelque digan qué hace, y mantenlo dibujado. - Dales a los controles anterior y siguiente un
previousLabely unnextLabel, y dejanavigationenautosalvo que tu página le dé al ratón otra forma de mover la fila. - Mantén los controles fuera del contenido de los elementos.
- Si el contenido transmite un significado que su etiqueta no recoge, como un precio en un cartel, ponlo en la etiqueta.
- En SwiftUI, Compose y React Native, mantén moderado el número de elementos: ahí el carrusel construye todos los elementos, incluidos los que no están a la vista.