Saltar al contenido
menumenu tanreiexpand_morecontrasttranslate
tanreiexpand_more
Primeros pasosWebReactSwiftUIJetpack ComposeFlutterReact NativePreajustesTu propio sistema de diseñoUsar Tanrei con agentes de IAMarcaTokens de diseñoSistemas de diseño y personalizaciónTheme StudioColorTipografíaIconosFormaElevaciónMovimientoEstados de interacciónComportamientoDiseño de páginaAccesibilidadTextosTokens de colorTokens de la escala tipográficaTokens de formaTokens de elevaciónTokens de movimientoTokens de estadoTokens de espacio y de medidaComponentesBotónBotón de acción principalBotón segmentadoGrupo de botonesBotón con menúBarra de herramientasBotón de copiarCasilla de verificaciónBotón de opciónInterruptorChipMenúControl deslizanteCampo de control deslizanteCalendarioDateTimePickerGrupo de camposGrupo de botones de opciónGrupo de casillas de verificaciónSelectCampo de selecciónBarra de menúsSubida de archivosSelector de archivos AvanzadoZona de soltar archivosEntrada de texto AvanzadoCampo de textoCampo de chipsCampoCuadro combinado AvanzadoCampo de cuadro combinadoEntrada numérica AvanzadoCampo numéricoEntrada de color AvanzadoCampo de colorEntrada de código de un solo uso AvanzadoCampo de código de un solo usoEntrada de texto incrustada AvanzadoCuadro de redacción de chatTarjetaDivisorCapa modal AvanzadoDiálogoListaFila de listaHoja inferiorHoja lateralCarruselBloque de códigoTablaPopoverPasosAcordeónLista de descripcionesFiguraEstructura de la aplicaciónCabecera de páginaVista de árbolLínea de tiempoVista previa de imágenesTirador de tamañoMarco redimensionableÁrea de desplazamientoInsigniaIndicador de progresoMedidorContador animadoIndicador de cargaSnackbarTooltipAtajo de tecladoTagCódigo en líneaCalloutAvatarEstado vacíoGrupo de tagsEsqueletoElemento de archivoMuestraTexto en marquesinaPestañasVista de pestañasBarra de la aplicaciónBarra de navegaciónPanel de navegaciónBúsquedaEnlacePaginaciónEnlaces anterior y siguienteIndicador de pasosRuta de navegaciónTabla de contenidoTarjeta de enlaceMenú FABEstadoCómo se construye TanreiCómo contribuirLicencia y atribución
InicioComponentesAtajo de teclado

Atajo de teclado

Muestra las teclas que ejecutan un comando, como teclas o como texto, con los símbolos y los nombres de modificadores del teclado que la persona está usando, y las lee en voz alta por su nombre.

content_copyVer en Markdown
Categoría
Comunicación
Tokens
comp.keyboard-shortcut
Nivel
Base

Descripción general

Web
tanrei-keyboard-shortcut
schedule
SwiftUI
TanreiKeyboardShortcut
radio_button_unchecked
Jetpack Compose
TanreiKeyboardShortcut
radio_button_unchecked
Flutter
TanreiKeyboardShortcut
radio_button_unchecked
React Native
KeyboardShortcut
radio_button_unchecked

Generado a partir de docs/status/status.json, specs/keyboard-shortcut.spec.json

Un atajo de teclado muestra las teclas que ejecutan un comando: dibujadas como capuchones de tecla, o como texto simple junto al nombre de un comando, en tamaño pequeño o mediano. Las teclas se escriben con nombres neutros (mod, shift, k) y se dibujan según la convención del teclado que la persona está usando: los símbolos de Apple (⇧⌘K) o los nombres estándar (Ctrl+Shift+K). Un producto puede definir la convención para una región, o dejársela a la plataforma. Un atajo formado por varias combinaciones seguidas (Ctrl+K Ctrl+C) es una sola secuencia.

Capuchones de tecla, una secuencia de dos combinaciones y la forma simple, para el teclado que estás usando

Sus teclas se dibujan solo para la vista: la tecnología de apoyo lee el label que da el producto (el atajo dicho con tus propias palabras) y, si no hay ninguno, la notación de aria-keyshortcuts (Meta+Shift+K). Tanrei no tiene nombres para las teclas en ningún idioma. Muestra las teclas y nada más: no recibe foco ni entrada, y no hace que las teclas funcionen. Es tu producto quien las vincula.

Tres componentes dibujan un atajo con él, a partir de una propiedad shortcut propia: el menú al final de la fila de un elemento, un tooltip simple después de su texto, y la búsqueda como una pista en su barra o en su activador. Ahí usa esas propiedades, no un elemento tuyo: el anfitrión dibuja las teclas con su propio estilo de texto y las expone como el atajo de teclado del control.

Uso

keys contiene una combinación por cadena, y las combinaciones se pulsan en orden. Una combinación consta de nombres de teclas unidos por +, y los nombres no distinguen mayúsculas de minúsculas.

  • Modificadores: mod (Comando en las plataformas de Apple, Control en las demás), ctrl, alt, shift.
  • Teclas con nombre: enter, escape, tab, backspace, delete, space, arrow-up, arrow-down, arrow-left, arrow-right, home, end, page-up, page-down, caps-lock, de f1 a f24, y plus para la tecla +.
  • Cualquier otro carácter suelto es la tecla de ese carácter: k, /, ,.

En la web, el atributo keys contiene las combinaciones separadas por espacios (keys="mod+k mod+c"), y la propiedad es un array. SwiftUI, Compose, Flutter y React Native todavía no han implementado el componente. Hasta que lo hagan, sus menús escriben un atajo en el texto final del elemento, como muestra la página del menú.

<!-- El tamaño small cabe en una línea de texto de cuerpo sin hacerla más alta. -->
<p>Busca con <tanrei-keyboard-shortcut keys="mod+k" label="Comando o Control y K" size="small"></tanrei-keyboard-shortcut>.</p>

<!-- Dos combinaciones pulsadas una después de la otra. -->
<tanrei-keyboard-shortcut keys="mod+k mod+c" label="Comando o Control y K, después Comando o Control y C"></tanrei-keyboard-shortcut>

<!-- Texto simple, leído en el idioma de tu producto. -->
<tanrei-keyboard-shortcut keys="mod+shift+k" variant="plain" label="Befehl Umschalt K"></tanrei-keyboard-shortcut>

<!-- Una región escrita para un solo teclado, sea cual sea la plataforma de la persona. -->
<section data-tanrei-keyboard-convention="standard">
  <tanrei-keyboard-shortcut keys="mod+s" label="Control S"></tanrei-keyboard-shortcut>
</section>

<script type="module">
  import '@tanrei/web/components/keyboard-shortcut';
  // El elemento solo muestra las teclas. Vincúlalas tú y decláralo en el control al que pertenecen.
  const shown = document.querySelector('tanrei-keyboard-shortcut');
  searchButton.setAttribute('aria-keyshortcuts', shown.ariaKeyShortcuts); // "Meta+K" o "Control+K"
</script>
import { KeyboardShortcut } from '@tanrei/react';

<p>Busca con <KeyboardShortcut keys={['mod+k']} label="Comando o Control y K" size="small" />.</p>

<KeyboardShortcut keys={['mod+k', 'mod+c']} label="Comando o Control y K, después Comando o Control y C" />

<KeyboardShortcut keys={['mod+shift+k']} variant="plain" label="Befehl Umschalt K" />

// Una región escrita para un solo teclado, sea cual sea la plataforma de la persona.
<section data-tanrei-keyboard-convention="standard">
  <KeyboardShortcut keys={['mod+s']} label="Control S" />
</section>

Especificaciones

Las mismas teclas para un teclado de Apple y para uno estándar; small dentro de una frase; teclas con nombre; deshabilitado

Pulsa para buscar, o desde cualquier lugar de la página.

Anatomía

Anatomía

Dibujado sobre el fixture keycap-apple, tal como lo dibuja el paquete web.
Parte Descripción
1 container One key's cap, in the keycap form: a small rounded square that widens with its legend, with a faint fill and, in the default system, no edge. A layer that wants keys with an edge, or with a deeper edge at the bottom, gives the edge its widths. The plain form draws no cap.
2 label A key's legend: a modifier's symbol or name (⌘, Ctrl), a named key's symbol or name (↩, Enter), or a character (K). It is text, drawn in the component's text style.
3 separator · opcional The + between two keys of a chord where the keyboard's convention writes one (Ctrl+K). Apple platforms write none (⌘K).
4 chord The keys pressed together: the modifiers, in the convention's order, then one other key.
5 sequence · opcional Chords pressed one after the other (Ctrl+K, then Ctrl+C), a wider gap apart. Most shortcuts are one chord.

Medidas

Medidas

Longitud Token Valor (px)
container padding-inline tanrei.comp.keyboard-shortcut.container.padding-inline.medium 6
container height tanrei.comp.keyboard-shortcut.container.height.medium 24
Dibujado sobre el fixture keycap-apple, tal como lo dibuja el paquete web.

Propiedades

Propiedad Tipo Valor predeterminado Descripción
keys strings The shortcut: one chord per string, pressed in order. A chord is key names joined by + ("mod+shift+k"). Modifiers: mod (Command on Apple platforms, Control elsewhere), ctrl, alt, shift. Named keys: enter, escape, tab, backspace, delete, space, arrow-up, arrow-down, arrow-left, arrow-right, home, end, page-up, page-down, caps-lock, f1 to f24, plus. Any other single character is that character's key. Names ignore case.
variant keycap | plain "keycap" How the keys are drawn: keycap puts each key in its own cap; plain writes the shortcut as a line of text, as a menu or a tooltip writes it. A design system may add values.
size small | medium "medium" Small (20 caps, 12 text) sits in a line of body text or a menu row without making it taller; medium (24 caps, 14 text) sits beside larger text or on its own. A design system may add values.
convention auto | apple | standard "auto" Whose keyboard the keys are written for. apple: the symbols of macOS, iOS, iPadOS and visionOS (⌃ ⌥ ⇧ ⌘, no separator). standard: the names of Windows, Linux, ChromeOS and Android (Ctrl, Alt, Shift, joined by +). auto: the convention an ancestor sets, else the one of the platform the app runs on.
label string "" What assistive technology reads in place of the drawn keys: the shortcut in the product's language ("Shift Command K", "Befehl Umschalt K"). The product's: Tanrei has no names for keys. Empty exposes the shortcut in the form of the platform's keyboard shortcut property (KBS-12), which is a standard's notation and not a sentence, and is reported (KBS-11).
disabled boolean false Fades the legends, for the shortcut of a command that is unavailable. The keys still show; the shortcut takes no input either way.

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
KBS-1 THE keyboard shortcut SHALL read keys as a sequence of chords pressed one after the other, each chord being the key names of one string joined by + and compared without case: mod, ctrl, alt and shift as modifiers, the named keys enter, escape, tab, backspace, delete, space, arrow-up, arrow-down, arrow-left, arrow-right, home, end, page-up, page-down, caps-lock, f1 to f24 and plus, and any other single character as that character's key.
KBS-2 WHILE convention is auto THE keyboard shortcut SHALL use the convention its nearest ancestor sets, and without one SHALL use apple on macOS, iOS, iPadOS and visionOS and standard on every other platform; it SHALL NOT choose the convention by the design system, because the keys follow the keyboard a person presses, not the look of the product.
KBS-3 WHILE the convention is apple THE keyboard shortcut SHALL write mod as ⌘, ctrl as ⌃, alt as ⌥ and shift as ⇧, in the order ⌃ ⌥ ⇧ ⌘ whatever order keys gives, followed by the chord's other key, with no separator; and SHALL write enter as ↩, escape as ⎋, tab as ⇥, backspace as ⌫, delete as ⌦, space as Space, the arrows as ↑ ↓ ← →, home as ↖, end as ↘, page-up as ⇞, page-down as ⇟, caps-lock as ⇪, a function key as F1 to F24 and plus as +.
KBS-4 WHILE the convention is standard THE keyboard shortcut SHALL write mod and ctrl as Ctrl, alt as Alt and shift as Shift, in the order Ctrl, Alt, Shift whatever order keys gives, followed by the chord's other key, each joined to the next by +; and SHALL write enter as Enter, escape as Esc, tab as Tab, backspace as Backspace, delete as Delete, space as Space, the arrows as ↑ ↓ ← →, home as Home, end as End, page-up as PgUp, page-down as PgDn, caps-lock as Caps Lock, a function key as F1 to F24 and plus as +.
KBS-5 THE keyboard shortcut SHALL write a letter key as its capital letter in both conventions and any other character key as given, and SHALL NOT add shift for a capital letter: shift is drawn only where keys names it, so mod+k and mod+K both draw ⌘K and mod+shift+k draws ⇧⌘K.
KBS-6 WHILE variant is keycap THE keyboard shortcut SHALL draw each key of a chord in its own cap: at least its size's container height tall and at least as wide as it is tall, its legend centered with its size's container padding on each side, corners of its size's container shape eased by sys.shape.corner-smoothing, filled with comp.keyboard-shortcut.container.color, and edged in comp.keyboard-shortcut.outline.color, comp.keyboard-shortcut.outline.width on its top and sides and comp.keyboard-shortcut.outline.bottom-width at its bottom, both inside the cap's size, a width of 0 (both, in the default system) drawing no edge on those sides, so that the cap is its fill alone; the legend SHALL be in its size's label typescale and comp.keyboard-shortcut.keycap.label.color, and two caps of one chord SHALL be its size's chord gap apart, or, where the convention has a separator, the separator in the legend's style and color with the chord gap on each side of it.
KBS-7 WHILE variant is plain THE keyboard shortcut SHALL write each chord as one run of text in its size's label typescale and comp.keyboard-shortcut.plain.label.color, the Apple symbols with no separator (⌥⌘⎋) and the standard names joined by + with no spaces (Ctrl+Alt+Delete), and SHALL draw no cap, fill or edge.
KBS-8 WHILE keys holds more than one chord THE keyboard shortcut SHALL draw the chords in order, its size's sequence gap apart, in both forms, and SHALL draw nothing else between them.
KBS-9 WHILE disabled is true THE keyboard shortcut SHALL draw its legends and separators from the disabled component tokens of its variant, SHALL keep its caps' fill and edges at rest, and SHALL NOT expose a disabled state of its own: it is not a control, and the command it belongs to exposes whether it is available.
KBS-10 THE keyboard shortcut SHALL hide its caps, legends and separators from assistive technology and SHALL expose in their place one text, read where the shortcut sits: label where it is not empty, which is the shortcut in the product's own words ("Shift Command K"), and otherwise the text KBS-11 gives. It SHALL NOT expose the symbols themselves, which a screen reader reads by the names of their characters.
KBS-11 WHILE label is empty THE keyboard shortcut SHALL have no names for keys of its own and SHALL NOT spell its keys out in the words of any language: it SHALL expose as its text the shortcut in the form of the platform's keyboard shortcut property (KBS-12) — Meta+Shift+K; Control+K Control+C — which is a standard's notation for keys, the same in every language, and in debug builds SHALL report once that the shortcut has no words. The legends it draws (KBS-3 to KBS-5) are the engravings of the two keyboard conventions, what the keys themselves carry, and are not words of Tanrei's; a keyboard engraved otherwise is a convention of its own, and a proposal of its own.
KBS-12 THE keyboard shortcut SHALL give a component that hosts it the shortcut in the form of the platform's keyboard shortcut property, which the web writes as aria-keyshortcuts does: each chord's modifiers then its key joined by +, with mod as Meta under apple and Control under standard, ctrl as Control, alt as Alt and shift as Shift, and the chords separated by spaces (Meta+Shift+K; Control+K Control+C).
KBS-13 WHERE a component draws the keyboard shortcut in one of its own parts THE keyboard shortcut SHALL draw its legends and separators in that part's text style and color from the host's tokens instead of its own label typescale and label color, SHALL keep its own caps, sizes and gaps, and SHALL expose nothing to assistive technology, because the host exposes the shortcut as its own (a menu item's keyboard shortcut).
KBS-14 THE keyboard shortcut SHALL NOT listen for, register or perform the keys it shows, SHALL NOT take focus, and SHALL NOT take pointer, touch or keyboard input of its own: it shows the keys, and the product makes them work.
KBS-15 THE keyboard shortcut SHALL lay itself out inline with the text around it, align the baseline of its legends with that text's baseline, never break a line inside a chord, and break a sequence only between chords; WHILE the text size is enlarged THE keyboard shortcut SHALL grow its caps with their legends, keeping container height as a minimum.
KBS-16 WHERE the layout direction is right-to-left THE keyboard shortcut SHALL keep the keys of a chord and the chords of a sequence in left-to-right order, isolated from the surrounding direction, as keyboards and the platforms' own menus write them.
KBS-17 WHERE the font of its text style has no glyph for a symbol it writes (⌘, ⌥, ⎋) THE keyboard shortcut SHALL draw that symbol from the platform's system font at the same size and baseline, and SHALL NOT draw a missing-glyph box.
KBS-18 IF keys is empty THE keyboard shortcut SHALL draw nothing and expose nothing; IF a chord is empty, holds no key other than modifiers, holds more than one key other than modifiers, names a key twice once the convention has written it (ctrl+mod under standard), or names an unknown key of more than one character THE keyboard shortcut SHALL draw what it can (each key once, an unknown name as given, in order) and in debug builds SHALL report the chord.
KBS-19 THE keyboard shortcut 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 keyboard shortcut is shown THE keyboard shortcut SHALL draw itself for the new direction at once, without a motion of its own, keeping what it shows and its state.

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-keyboard-shortcut TanreiKeyboardShortcut TanreiKeyboardShortcut TanreiKeyboardShortcut KeyboardShortcut
keys · Propiedad keys keys keys keys keys
variant · Propiedad variant variant variant variant variant
size · Propiedad size size size size size
convention · Propiedad convention convention convention convention convention
label · Propiedad label label contentDescription semanticLabel accessibilityLabel
disabled · Propiedad disabled disabled enabled enabled disabled
Notas The keys attribute holds the chords separated by spaces (keys="mod+k mod+c"); the property is an array. The shadow root draws a <kbd> per chord holding a <kbd> per key, as HTML nests keys that are pressed together, all aria-hidden, beside one visually hidden text (KBS-10). Under auto the convention is the nearest ancestor's data-tanrei-keyboard-convention attribute (apple or standard), read when the element connects and when that attribute changes, else apple where navigator.userAgentData.platform or navigator.platform names macOS, iOS or iPadOS. The read-only ariaKeyShortcuts property is KBS-12's form, which the menu sets on its item. The small caps line up with text through vertical-align: baseline on an inline-flex host (KBS-15). Words: the element has no names for keys; without label its text for assistive technology is ariaKeyShortcuts. TanreiKeyboardShortcut(_ keys: [String], …), with an initializer that takes SwiftUI's own KeyboardShortcut (its key and modifiers, .command as mod), so a product that already registers a shortcut shows the same one. auto reads the \.tanreiKeyboardConvention environment value, else apple. disabled follows SwiftUI's .disabled(_:) environment. The shortcut's text is the view's accessibilityLabel, on an element that combines its children. TanreiKeyboardShortcut(keys: List<String>, …). Compose idiom is the inverse flag enabled. auto reads LocalTanreiKeyboardConvention, else standard (Android and ChromeOS write Ctrl). The shortcut's text is the contentDescription of semantics merged over the drawn keys, which are cleared. TanreiKeyboardShortcut(keys: [...]), with a .fromActivator(SingleActivator) constructor so a product that binds Shortcuts shows the same keys (meta on Apple targets and control elsewhere read as mod). A widget that takes no press has no onPressed to null, so the flag is the inverse enabled, as in Compose. auto reads the TanreiKeyboardConvention inherited widget, else apple where defaultTargetPlatform is macOS or iOS. The drawn keys are excluded from semantics under one Semantics(label:). <KeyboardShortcut keys={['mod+k']} />. auto reads the KeyboardConventionProvider context, else apple where Platform.OS is ios (and macos under React Native macOS). The drawn keys are one accessible element with accessibilityRole="text" and the shortcut's accessibilityLabel.

Tokens

Token Alias de Valor resuelto (claro)
--tanrei-comp-keyboard-shortcut-chord-gap-medium sys.space.space50 4px
--tanrei-comp-keyboard-shortcut-chord-gap-small sys.space.space25 2px
--tanrei-comp-keyboard-shortcut-container-color sys.color.surface-container-highest #eeeeee
--tanrei-comp-keyboard-shortcut-container-height-medium — 24px
--tanrei-comp-keyboard-shortcut-container-height-small — 20px
--tanrei-comp-keyboard-shortcut-container-padding-inline-medium sys.space.space75 6px
--tanrei-comp-keyboard-shortcut-container-padding-inline-small sys.space.space50 4px
--tanrei-comp-keyboard-shortcut-container-shape-medium sys.shape.corner.small 6px
--tanrei-comp-keyboard-shortcut-container-shape-small sys.shape.corner.extra-small 3px
--tanrei-comp-keyboard-shortcut-keycap-disabled-label-color — #1b1b1b · 38%
--tanrei-comp-keyboard-shortcut-keycap-label-color sys.color.on-surface-variant #4b4b4b
--tanrei-comp-keyboard-shortcut-outline-bottom-width sys.space.space0 0px
--tanrei-comp-keyboard-shortcut-outline-color sys.color.outline-variant #000000 · 8%
--tanrei-comp-keyboard-shortcut-outline-width sys.space.space0 0px
--tanrei-comp-keyboard-shortcut-plain-disabled-label-color — #1b1b1b · 38%
--tanrei-comp-keyboard-shortcut-plain-label-color sys.color.on-surface-variant #4b4b4b
--tanrei-comp-keyboard-shortcut-sequence-gap-medium sys.space.space150 12px
--tanrei-comp-keyboard-shortcut-sequence-gap-small sys.space.space100 8px
--tanrei-comp-keyboard-shortcut-label-typescale-medium sys.typescale.label 500 14px/1.4286
--tanrei-comp-keyboard-shortcut-label-typescale-small sys.typescale.label-small 500 12px/1.3333

Fixtures

Representaciones canónicas. Todas las plataformas capturan cada fixture con el mismo identificador para poder comparar los resultados.

Generado a partir de specs/keyboard-shortcut.spec.json, tokens/comp/keyboard-shortcut.tokens.json, design/tokens/

Pautas

Cuándo usarlo

Usa un atajo de teclado dondequiera que tu producto le diga a una persona qué teclas ejecutan un comando: en una frase de ayuda, en una lista de atajos, en un estado vacío, junto al nombre de un comando en una paleta.

En un elemento de menú, un tooltip simple o una búsqueda, usa en su lugar la propiedad shortcut de ese componente. No uses el capuchón de tecla para texto que una persona escribe, como un comando o un nombre de archivo: un capuchón significa una tecla que hay que pulsar.

Capuchón o texto simple, pequeño o mediano

Opción Qué dibuja Úsala para
keycap (predeterminada) Cada tecla en su propio capuchón, con un + entre los capuchones en la convención estándar. La ayuda y la documentación, donde las teclas son el tema.
plain El atajo como un solo tramo de texto: ⌥⌘⎋, o Ctrl+Alt+Delete. Sin capuchón, relleno ni borde. Junto al nombre de un comando, donde una fila de capuchones competiría con él: como lo escribe un menú.
medium (predeterminada) Capuchones de 24 con texto de 14. Solo, o junto a un texto más grande.
small Capuchones de 20 con texto de 12. En una línea de texto de cuerpo o en una fila densa, sin hacer la línea más alta.

En el sistema predeterminado, un capuchón es un relleno tenue sin borde, y su leyenda tiene el color de texto discreto. Un sistema de diseño puede dar a los capuchones un borde, con la parte inferior más gruesa, y puede añadir variantes y tamaños.

Cómo escribir las teclas

  • Escribe mod para el modificador principal, no ctrl: es Comando en un teclado de Apple y Control en los demás. Escribe ctrl solo para un atajo que sea Control en todos los teclados.
  • En cualquier orden. El componente escribe los modificadores en el orden propio del teclado: ⌃ ⌥ ⇧ ⌘ para Apple, y Ctrl, Alt, Shift para los nombres estándar.
  • Una letra se dibuja en mayúscula, y no añade Shift: mod+k y mod+K dibujan ambos ⌘K. Shift solo se dibuja donde lo nombras.
  • Una tecla por combinación, además de sus modificadores. Una combinación sin tecla, o con dos, se dibuja como se pueda, y las compilaciones de depuración lo notifican.
  • Una secuencia son varias combinaciones: mod+k y luego mod+c. Se dibujan con una separación entre ellas, sin nada en medio.
  • Las teclas con nombre también siguen al teclado. enter es ↩ en un teclado de Apple y Enter en uno estándar; escape es ⎋ o Esc; backspace es ⌫ o Backspace; page-down es ⇟ o PgDn. Las flechas son ↑ ↓ ← → en ambos.

La convención

convention dice para qué teclado están escritas las teclas. Déjala en auto: el componente usa entonces la convención que define un ancestro y, si no hay ninguna, la de la plataforma: la de Apple en macOS, iOS, iPadOS y visionOS, y los nombres estándar en todas las demás.

Defínela para una región cuando tu producto sepa más que la plataforma: un ajuste que deja elegir a la persona, una documentación que muestra los dos teclados uno al lado del otro, una sesión remota en otro sistema. En la web es el atributo data-tanrei-keyboard-convention (apple o standard) en cualquier ancestro; los menús, los tooltips y las búsquedas que haya dentro también lo siguen. Define convention en un solo atajo únicamente para una excepción.

La convención nunca procede del sistema de diseño. Las teclas siguen al teclado que la persona pulsa, no al aspecto del producto.

Recomendado

  • Muestra el atajo que funciona de verdad. Vincula las teclas en tu producto y mantén ambas cosas sincronizadas.
  • Da un label a cada atajo que se lea en voz alta: el atajo dicho con las palabras de tu producto («Mayúsculas Comando K»). Sin él, un lector de pantalla lee la notación Meta+Shift+K.
  • Con convention="auto", las teclas dibujadas siguen al teclado de la persona, y un label que has escrito tú no puede hacerlo. Escribe uno que sea cierto en los dos teclados («Comando o Control, Mayúsculas, K»), como hacen los ejemplos de esta página, o define el label cuando ya conozcas el teclado.
  • Usa disabled para el atajo de un comando que ahora no está disponible, junto a ese comando. Las teclas se siguen mostrando, atenuadas.
  • Mantén un atajo en una sola línea. Una combinación nunca se parte; una secuencia puede saltar de línea entre combinaciones.

Evita

  • No escribas tú los símbolos (⌘K en el texto). Serían incorrectos en otro teclado, y un lector de pantalla puede leer un símbolo por el nombre de su carácter.
  • No hagas de un atajo la única forma de llegar a un comando. Es un acelerador de algo a lo que la persona también puede llegar con el puntero y con el foco.
  • No coloques tu propio elemento de atajo de teclado dentro de un elemento de menú o de un tooltip. Usa la propiedad shortcut del anfitrión.
  • No elijas la convención según la marca o el tema.

Accesibilidad

Rol
none
Etiquetado
The keyboard shortcut has no role of its own: it is text, read where it sits. Its symbols are hidden; what is read is label, the shortcut in the product's words ("Shift Command K"), or, without one, the notation of KBS-12 (Meta+Shift+K), so a screen reader never says "place of interest sign" for ⌘. Hosted in another component (a menu item), it is hidden entirely, and the host exposes the shortcut as its keyboard shortcut property.
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

Notas

  • Not interactive: it takes no focus and no input (KBS-14), so there is no target to size. minimumTarget holds trivially.
  • Showing a shortcut does not make it work, and does not tell assistive technology that it works. A control that really answers the keys exposes that itself (aria-keyshortcuts on the web, the platform's keyboard shortcut on the others); a host such as the menu does it with the form KBS-12 gives.
  • The keyboard shortcut has no names for keys in any language: a shortcut that should be read as words is given them in label. A table of key names a product sets once, and names taken from the platform, are not built.
  • Contrast: the legend's color on the cap's fill is text on a surface and is held to 4.5:1 in the default system (7:1 in its high-contrast schemes); there it is sys.color.on-surface-variant on sys.color.surface-container-highest, 7.52:1 light and 6.09:1 dark at standard contrast. The cap's fill is decorative and is not held to a ratio against what is behind it: the legend alone carries the meaning, and a cap that cannot be told from its background is still a readable legend.

Generado a partir de specs/keyboard-shortcut.spec.json, tokens/sys/measure.tokens.json

De qué se encarga el componente

  • Los capuchones, las leyendas y los separadores quedan ocultos para la tecnología de apoyo. En su lugar se lee un único texto, allí donde está el atajo: label, de modo que ⇧⌘K se lee «Mayúsculas Comando K» y nunca los nombres de carácter de los símbolos. Sin un label, es el atajo en la notación de aria-keyshortcuts (Meta+Shift+K, o Control+K Control+C para una secuencia), que pertenece a un estándar y es la misma en todos los idiomas, y el componente lo notifica una vez en desarrollo.
  • El componente no tiene nombres para las teclas: no escribe con su nombre un modificador, una flecha ni una tecla de puntuación en ningún idioma. Un lector de pantalla puede saltarse un carácter suelto, como una coma, y esa es una razón más para escribir el label.
  • No tiene rol, no recibe foco ni entrada, y no es un objetivo: es texto.
  • Dentro de un anfitrión (un elemento de menú, un tooltip simple, una búsqueda) no expone nada por sí mismo. El anfitrión expone el atajo como el atajo de teclado de su control: aria-keyshortcuts en la web.
  • disabled atenúa las leyendas y no expone ningún estado. El comando al que pertenece el atajo dice si está disponible.
  • Las teclas conservan el orden de izquierda a derecha en un diseño de derecha a izquierda, aisladas del texto que las rodea, como las escriben los teclados y los menús de las propias plataformas.
  • Se apoya en la línea base del texto que lo rodea y crece con el texto ampliado; la altura del capuchón es un mínimo.
  • Un símbolo que le falta al tipo de letra del producto (⌘, ⎋) se dibuja con una fuente del sistema al mismo tamaño, nunca como un recuadro de glifo ausente.
  • En el sistema predeterminado, la leyenda sobre el capuchón cumple el contraste exigido al texto. El relleno del capuchón es decorativo: solo la leyenda transmite el significado.
  • Las compilaciones de depuración notifican una combinación vacía, una combinación solo de modificadores, una combinación con dos teclas, una tecla nombrada dos veces una vez escrita (ctrl+mod en la convención estándar), un nombre de tecla desconocido y una convención desconocida.

Carencias conocidas por plataforma:

  • SwiftUI, Compose, Flutter y React Native no han implementado el atajo de teclado.
  • Web: es probable que una comprobación automática de contraste señale un atajo deshabilitado que está solo, fuera de un comando que a su vez se exponga como deshabilitado: su leyenda está atenuada, y el elemento no expone ningún estado deshabilitado propio.

Qué debes hacer tú

  • Haz que las teclas funcionen: el componente solo las muestra.
  • En el control al que pertenecen las teclas, exponlas como su atajo de teclado. En la web, define aria-keyshortcuts a partir de la propiedad de solo lectura ariaKeyShortcuts del elemento, que da la forma que admite ese atributo.
  • Pasa label, el atajo dicho con las palabras de tu producto, dondequiera que el atajo se lea en voz alta. Tanrei no incluye textos propios ni nombres para las teclas.
  • Mantén todos los comandos accesibles sin su atajo.