Skip to content

KeyboardEvent.keyCode is deprecated - should EUI switch to KeyboardEvent.key? #3512

@dimitropoulos

Description

@dimitropoulos

TLDR

This issue suggests removing usages of event.keyCode (since it's deprecated) in favor of event.key. Optionally, this can be enforced from that point forward with tooling.

Overview

Many are not aware that although all the latest versions of the browsers still support KeyboardEvent.keyCode, it's been deprecated: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

enter, KeyboardEvent.key: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

This event method is the heir apparent for keyboard management.

Is this a breaking change?

From my understanding of EUI's browser support level this should not be a breaking change.

Consider the following example from src/components/color_picker/saturation.tsx (of course, in practice a constant map could be used instead of 'ArrowDown' literals, although the literals can be type checked by TypeScript (thereby preventing typos) although they aren't by default):

- switch (e.keyCode) {
+ switch (e.key) {
-  case keyCodes.DOWN:
+  case 'ArrowDown':
    e.preventDefault();
    newTop = top < height ? top + heightScale : height;
    break;
-  case keyCodes.LEFT:
+  case 'ArrowLeft':
    e.preventDefault();
    newLeft = left > 0 ? left - widthScale : 0;
    break;
-  case keyCodes.UP:
+  case 'ArrowUp':
    e.preventDefault();
    newTop = top > 0 ? top - heightScale : 0;
    break;
-  case keyCodes.RIGHT:
+  case 'ArrowRight':
    e.preventDefault();
    newLeft = left < width ? left + widthScale : width;
    break;
  default:
    return;
}

30ish files in the codebase use a keyCodes map. Something similar could be trivially done to swap out the implementations for various places in the codebase.

I can verify that all of the constants in event.keyCode, at least, are covered by modern-day counterparts in event.key like F2, Enter, Tab, ArrowDown, etc.. Here's the official list of possible values: https://www.w3.org/TR/uievents-key/#named-key-attribute-values

Preventing in the future

This can (I think) be prevented in the future by overlaying the types using module augmentation.


Thoughts?

If there's interest I'm happy to contribute this change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions