# Keyboard Map

## Draft Community Group Report, 1 January 1970

This version:
  https://wicg.github.io/keyboard-map/
Editors:
  Gary Kacmarcik (Google)
Explainer:
  Keyboard Map Explainer

Copyright © 1970 the Contributors to the Keyboard Map Specification, published by the Web Platform Incubator Community Group under the W3C Community Contributor License Agreement (CLA). A human-readable summary is available.

## Abstract

This specification defines an API that allows websites to convert from a given `code` value to a valid `key` value that can be shown to the user to identify the given key. The conversion from `code` to `key` is based on the user’s currently selected keyboard layout. It is intended to be used by web applications that want to treat the keyboard as a set of buttons and need to describe those buttons to the user.

## Status of this document

This specification was published by the Web Platform Incubator Community Group. It is not a W3C Standard nor is it on the W3C Standards Track. Please note that under the W3C Community Contributor License Agreement (CLA) there is a limited opt-out and other conditions apply. Learn more about W3C Community and Business Groups.

This document is an editor’s draft proposed as a First Public Working Draft.

## 1. Introduction

On a `KeyboardEvent`, the `code` attribute encodes a value that represents the physical location of the key that was pressed. This value ignores the current locale (e.g., "en-US"), layout (e.g., "dvorak") and modifier state (e.g., "Shift + Control"), so it is ideally suited for applications (like games) that want to use the keyboard as a set of generic buttons. The idea behind the `code` attribute is that it provides a platform-neutral scancode for each physical key.

The `key` attribute, on the other hand, contains the value that is generated by the key press, accounting for the locale, layout, and modifier keys. Almost every Unicode character is a valid `key` attribute, along with a number of special named values (see `KeyboardEvent` key attribute values), so there are thousands of possible `key` values.

Because most users have a physical keyboard that matches their locale and layout, we can reasonably assume that the `key` value is a good stand-in for the glyph printed on the keycap. While this does not hold true when the user has selected a different layout, in that case the user is well-aware of the mismatch between the glyph on the keycap and the character generated by a key press.

The API described in this document provides a simple way of obtaining this basic `code` to `key` mapping.

## 2. Keyboard Map API

### 2.1. Navigator Interface

    [Exposed=Window]
    partial interface Navigator {
      [SecureContext, SameObject] readonly attribute Keyboard keyboard;
    };

#### 2.1.1. keyboard

The keyboard attribute must return the `Navigator`'s `Keyboard` object.

Note: The keyboard object is also defined in the Keyboard Lock specification. These two definitions will be reconciled once we decide on a final home for these specifications.

### 2.2. KeyboardLayoutMap Interface

    [Exposed=Window]
    interface KeyboardLayoutMap {
      readonly maplike<DOMString, DOMString>;
    };

The `KeyboardLayoutMap` is a readonly collection of mappings from `code` values to `key` values.

### 2.3. Keyboard Interface

    [SecureContext, Exposed=Window] interface Keyboard {
      Promise<KeyboardLayoutMap> getLayoutMap();
    };

#### 2.3.1. getLayoutMap()

When getLayoutMap() is called, the user agent must run the following steps:

1. Let p be a new `Promise`.

2. If not currently executing in the currently active top-level browsing context, then

   1. Reject p with an "`InvalidStateError`" `DOMException`.

3. Run the following steps in parallel:

   1. Let map be a new `KeyboardLayoutMap` that is initially empty.

   2. For each value code in the "KeyboardEvent code" column of the Writing System Keys table

      1. Let layout be the highest priority ASCII-capable keyboard layout, or the highest priority keyboard layout if none of the available layouts are ASCII-capable.

      2. If code is not a valid key in the layout, then continue

      3. Let key be the `key` value that would be generated by layout if the key identified by code was pressed with no modifiers.

      4. If key is a dead key, then

         1. Set key to the standalone character that corresponds to the dead key, as defined in the Standalone Equivalents for Dead Keys table.

      5. Create a map entry e from the pair < code, key >

      6. Add e to map.

   3. Resolve p with map.

4. Return p.

User agents may choose to cache the map and return the cached value as long as the cache is updated (or invalidated) whenever the keyboard layout changes.

To show instructions about which key to press in a game:

    navigator.keyboard.getLayoutMap().then(function(map) {
      var keyUp = map.get("KeyW");
      showUserDialog("Press " + keyUp + " to move up.");
    });

On a "US International" keyboard where the single-quote (') key is a dead key that adds an acute accent to the following character. The keyboard map would contain an entry mapping Quote (the `code` for this key) to "'" (the single-quote character U+0027).

### 2.4. Dead Keys and Combining Characters

Since the intent of the keyboard map API is to provide human-readable descriptions for keys on the user’s keyboard, dead keys or combining characters need to be converted into standalone forms so that they can be used directly.

The following table defines how to map from common dead keys and combining characters into standalone characters.

Table 1: Standalone Equivalents for Dead Keys
Dead Key Name | Unicode Combining | Standalone Character | Unicode Standalone
--- | --- | --- | ---
Grave | U+0300 | "`" | U+0060
Acute | U+0301 | "'" | U+0027
Circumflex | U+0302 | "^" | U+005e
Tilde | U+0303 | "~" | U+007e
Diaeresis | U+0308 | "¨" | U+00a8

### 2.5. ASCII-Capable Keyboard Layouts

An ASCII-capable keyboard layout is one that:

- Is capable of producing all of the basic ASCII characters "A" - "Z" without requiring the use of any modifier keys.

- Produces a valid, printable character for all the common writing system keys.

The common writing system keys are those that are common to all keyboard layouts, as shown in blue in Figure 13 of the [UIEvents-Code] specification.

## 3. Keyboard Events

### 3.1. The layoutchange Event

The layoutchange event fires on the keyboard object whenever the current keyboard layout is changed. A layout change can occur when the user selects a new layout, or it may happen automatically when the user performs an action (e.g., switching to an application that has a preferred layout).

Note the following:

- Modifying the set of available layouts does not trigger a layoutchange event, unless the modification changes the current layout.

- Adding or removing a physical keyboard does not trigger an event unless the system has functionality to change the current layout based on adding or removing a physical keyboard. But note that it is the layout change that triggers this event, not the act of adding or removing the physical keyboard.

- The event will be fired whenever the current layout changes, even if the highest priority ASCII-capable layout remains the same.

If the keyboard layout changes while the user agent is not the foreground application, then the layoutchange event MUST fire when the user agent regains focus.

To handle this event:

    navigator.keyboard.addEventListener("layoutchange", function() {
      // Update user keyboard map settings
      updateGameControlSettingsPage();
    });

## 4. Mobile Device Considerations

Since this is a keyboard-focused API and mobile devices do not commonly have physical keyboards, this API will not typically be present or supported on mobile devices.

However, mobile devices may choose to support this API if they allow physical keyboards to be connected. In this case, they may return a subset of the Writing System Keys that are appropriate for the platform.

Mobile platforms that require the user to configure their physical keyboard layout (and don’t provide a reasonable default), may support this API by returning a layout map that contains no entries.

## 5. Security Considerations

This API returns static data and does not change any system state, so there are no special security concerns.

## 6. Privacy Considerations

As with all APIs that return information about the current device state, there is a risk of using this API to create a larger "fingerprint" of the user than if this API was not available.

By returning info from the highest priority ASCII-capable keyboard layout instead of the active layout, the value of this information for fingerprinting is reduced since users are more likely to share the same values.

Note the following situations where this layout information might be used to identify individuals:

- Users who use uncommon ASCII layouts (like Dvorak or Colemak)

- Users who use an ASCII layout that doesn’t match the default for the region that they are in. For example, a user in the US with an active UK or French layout.

Without this API, similar fingerprinting can still be attempted, but it is more difficult since it would require the user to interact with the page by typing characters and analyze the resulting `KeyboardEvent`s.

### 6.1. Privacy Mitigations

As a first line of defense for the user, this specification requires that the API is only available from secure contexts and can only be called from the currently active top-level browsing context.

User agents that are concerned about the privacy impact of providing this keyboard mapping information can also consider the following mitigations:

- Having a user prompt to ask for permission whenever a site attempts to use this API.

- Always return a "standard" mapping. Although note that the standard mapping would need to vary for different parts of the world. For example, a user agent that had a "privacy mode" that always returned a US-QWERTY layout mapping would actually be providing more identifying information for users in the UK than the actual mapping would (since most users in the UK do not use a US layout).

### 6.2. Privacy Mode

If a user agent provides an "incognito" or "privacy mode", then this API should act the same as it does outside of "privacy mode". The reason for this is that there is no universal neutral value that can be returned to ensure the user’s privacy.

User agents may choose to give the user the option to specify what value should be returned when in this mode, although care must be taken to ensure that the user does not get a false sense of security since this value would need to be updated when if they travel outside their home region.

## 7. Acknowledgements

Thanks to the following people for the discussions that lead to the creation of this proposal:

Hadley Beeman (W3C TAG), Joe Downing (Google), Masayuki Nakano (Mozilla), Julien Wajsberg (Mozilla)

## 8. Glossary

scancode

  A value that the keyboard hardware assigns to each key so that it can be identified uniquely. See https://en.wikipedia.org/wiki/Scancode for additional information.

## Conformance

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with `class="example"`, like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with `class="note"`, like this:

Note, this is an informative note.

## Index

### Terms defined by this specification

- ASCII-capable, in §2.5
- common writing system keys, in §2.5
- getLayoutMap()
  - dfn for Keyboard, in §2.3.1
  - method for Keyboard, in §2.3
- Keyboard, in §2.3
- keyboard
  - attribute for Navigator, in §2.1
  - dfn for Navigator, in §2.1.1
- KeyboardLayoutMap, in §2.2
- layoutchange, in §3.1
- scancode, in §8

https://html.spec.whatwg.org/multipage/system-state.html#navigator Referenced in:

- 2.1. Navigator Interface
- 2.1.1. keyboard

https://html.spec.whatwg.org/multipage/infrastructure.html#in-parallel Referenced in:

- 2.3.1. getLayoutMap()

https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context Referenced in:

- 2.3.1. getLayoutMap()
- 6.1. Privacy Mitigations

https://w3c.github.io/webappsec-secure-contexts/#secure-contexts Referenced in:

- 6.1. Privacy Mitigations

https://www.w3.org/TR/uievents/#keyboardevent Referenced in:

- 1. Introduction (2)
- 6. Privacy Considerations

https://www.w3.org/TR/uievents/#dom-keyboardevent-code Referenced in:

- Unnumbered Section (2)
- 1. Introduction (2) (3)
- 2.2. KeyboardLayoutMap Interface
- 2.3.1. getLayoutMap()

http://www.w3.org/TR/uievents/#dead-key Referenced in:

- 2.3.1. getLayoutMap() (2) (3)
- 2.4. Dead Keys and Combining Characters (2)

https://www.w3.org/TR/uievents/#dom-keyboardevent-key Referenced in:

- Unnumbered Section (2)
- 1. Introduction (2) (3) (4)
- 2.2. KeyboardLayoutMap Interface
- 2.3.1. getLayoutMap()

http://www.w3.org/TR/uievents-code/#code-quote Referenced in:

- 2.3.1. getLayoutMap()

http://www.w3.org/TR/uievents-code/#writing-system-keys Referenced in:

- 2.3.1. getLayoutMap()
- 4. Mobile Device Considerations

http://www.w3.org/TR/uievents-key/#key-attribute-value Referenced in:

- 1. Introduction

https://heycam.github.io/webidl/#idl-DOMException Referenced in:

- 2.3.1. getLayoutMap()

https://heycam.github.io/webidl/#idl-DOMString Referenced in:

- 2.2. KeyboardLayoutMap Interface (2)

https://heycam.github.io/webidl/#Exposed Referenced in:

- 2.1. Navigator Interface
- 2.2. KeyboardLayoutMap Interface
- 2.3. Keyboard Interface

https://heycam.github.io/webidl/#invalidstateerror Referenced in:

- 2.3.1. getLayoutMap()

https://heycam.github.io/webidl/#idl-promise Referenced in:

- 2.3.1. getLayoutMap()

https://heycam.github.io/webidl/#SameObject Referenced in:

- 2.1. Navigator Interface

https://heycam.github.io/webidl/#SecureContext Referenced in:

- 2.1. Navigator Interface
- 2.3. Keyboard Interface

### Terms defined by reference

- [HTML] defines the following terms:
  - Navigator
  - in parallel
  - top-level browsing context
- [secure-contexts] defines the following terms:
  - secure contexts
- [uievents] defines the following terms:
  - KeyboardEvent
  - code
  - dead key
  - key
- [UIEvents-Code] defines the following terms:
  - quote
  - writing system keys
- [uievents-key] defines the following terms:
  - key attribute value
- [WebIDL] defines the following terms:
  - DOMException
  - DOMString
  - Exposed
  - InvalidStateError
  - Promise
  - SameObject
  - SecureContext

## References

### Normative References

[HTML]
  Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[RFC2119]
  S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[SECURE-CONTEXTS]
  Mike West. Secure Contexts. 15 September 2016. CR. URL: https://www.w3.org/TR/secure-contexts/
[UIEVENTS]
  Gary Kacmarcik; Travis Leithead; Doug Schepers. UI Events. 30 May 2019. WD. URL: https://www.w3.org/TR/uievents/
[UIEvents-Code]
  Gary Kacmarcik; Travis Leithead. UI Events KeyboardEvent code Values. 1 June 2017. CR. URL: https://www.w3.org/TR/uievents-code/
[UIEVENTS-KEY]
  Gary Kacmarcik; Travis Leithead. UI Events KeyboardEvent key Values. 1 June 2017. CR. URL: https://www.w3.org/TR/uievents-key/
[WebIDL]
  Boris Zbarsky. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/

## IDL Index

    [Exposed=Window]
    partial interface Navigator {
      [SecureContext, SameObject] readonly attribute Keyboard keyboard;
    };

    [Exposed=Window]
    interface KeyboardLayoutMap {
      readonly maplike<DOMString, DOMString>;
    };

    [SecureContext, Exposed=Window] interface Keyboard {
      Promise<KeyboardLayoutMap> getLayoutMap();
    };

#navigator-keyboard Referenced in:

- 2.1.1. keyboard
- 2.1. Navigator Interface
- 3.1. The layoutchange Event

#keyboardlayoutmap Referenced in:

- 2.2. KeyboardLayoutMap Interface
- 2.3. Keyboard Interface
- 2.3.1. getLayoutMap()

#keyboard Referenced in:

- 2.1. Navigator Interface
- 2.1.1. keyboard

#keyboard-getlayoutmap Referenced in:

- 2.3.1. getLayoutMap()

#ascii-capable Referenced in:

- 2.3.1. getLayoutMap() (2)

#common-writing-system-keys Referenced in:

- 2.5. ASCII-Capable Keyboard Layouts

#layoutchange Referenced in:

- 3.1. The layoutchange Event (2) (3)

#scancode Referenced in:

- 1. Introduction