MCPcopy Create free account
hub / github.com/adobe/react-spectrum / onKeyDown

Function onKeyDown

packages/react-aria/src/interactions/usePress.ts:391–455  ·  view source on GitHub ↗
(e)

Source from the content-addressed store, hash-verified

389 let state = ref.current;
390 let pressProps: DOMAttributes = {
391 onKeyDown(e) {
392 if (
393 isValidKeyboardEvent(e.nativeEvent, e.currentTarget as Element) &&
394 nodeContains(e.currentTarget as Element, getEventTarget(e) as Element)
395 ) {
396 // If the key's default behavior is allowed, the browser performs the element's
397 // activation behavior and fires its own click event. Enter does this on key down;
398 // Space does it on key up (see below).
399 state.defaultKeyboardClickEvent = e.key === 'Enter' ? e.nativeEvent : null;
400
401 if (shouldPreventDefaultKeyboard(getEventTarget(e) as Element, e)) {
402 e.preventDefault();
403 }
404
405 // If the event is repeating, it may have started on a different element
406 // after which focus moved to the current element. Ignore these events and
407 // only handle the first key down event.
408 let shouldStopPropagation = true;
409 if (!state.isPressed && !e.repeat) {
410 state.target = e.currentTarget;
411 state.isPressed = true;
412 state.pointerType = 'keyboard';
413 shouldStopPropagation = triggerPressStart(e, 'keyboard');
414 }
415
416 // Focus may move before the key up event, so register the event on the document
417 // instead of the same element where the key down event occurred. Make it capturing so that it will trigger
418 // before stopPropagation from useKeyboard on a child element may happen and thus we can still call triggerPress for the parent element.
419 let originalTarget = e.currentTarget;
420 let pressUp = e => {
421 if (
422 isValidKeyboardEvent(e, originalTarget) &&
423 !e.repeat &&
424 nodeContains(originalTarget, getEventTarget(e) as Element) &&
425 state.target
426 ) {
427 triggerPressUpEvent(createEvent(state.target, e), 'keyboard');
428 }
429 };
430
431 addGlobalListener(
432 getOwnerDocument(e.currentTarget),
433 'keyup',
434 chain(pressUp, onKeyUp),
435 true
436 );
437
438 if (shouldStopPropagation) {
439 e.stopPropagation();
440 }
441
442 // Keep track of the keydown events that occur while the Meta (e.g. Command) key is held.
443 // macOS has a bug where keyup events are not fired while the Meta key is down.
444 // When the Meta key itself is released we will get an event for that, and we'll act as if
445 // all of these other keys were released as well.
446 // https://bugs.chromium.org/p/chromium/issues/detail?id=1393524
447 // https://bugs.webkit.org/show_bug.cgi?id=55291
448 // https://bugzilla.mozilla.org/show_bug.cgi?id=1299553

Callers

nothing calls this directly

Calls 7

nodeContainsFunction · 0.90
getEventTargetFunction · 0.90
getOwnerDocumentFunction · 0.90
chainFunction · 0.90
isValidKeyboardEventFunction · 0.85
setMethod · 0.45

Tested by

no test coverage detected