UNPKG

@awsui/components-react

Version:

AWS UI is a collection of [React](https://reactjs.org/) components that help create intuitive, responsive, and accessible user experiences for web applications. It is developed by Amazon Web Services (AWS). This work is available under the terms of the [A

62 lines (61 loc) 2.35 kB
import { useEffect, useState } from 'react'; import { KeyCode } from '../../keycode'; import { unstable_batchedUpdates } from 'react-dom'; var ControlTracker = (function () { function ControlTracker(root) { var _this = this; this.root = root; this.listeners = new Set(); this.isKeyboard = false; this.handleMousedown = function () { _this.isKeyboard = false; _this.notify(); }; this.handleKeydown = function (event) { var isSpecialKey = [KeyCode.shift, KeyCode.alt, KeyCode.control, KeyCode.meta].indexOf(event.keyCode) > -1; if (!isSpecialKey) { _this.isKeyboard = true; _this.notify(); } }; } ControlTracker.prototype.addDocumentListeners = function () { this.root.addEventListener('mousedown', this.handleMousedown); this.root.addEventListener('keydown', this.handleKeydown); }; ControlTracker.prototype.removeDocumentListeners = function () { this.root.removeEventListener('mousedown', this.handleMousedown); this.root.removeEventListener('keydown', this.handleKeydown); }; ControlTracker.prototype.notify = function () { var _this = this; unstable_batchedUpdates(function () { _this.listeners.forEach(function (listener) { return listener(_this.isKeyboard); }); }); }; ControlTracker.prototype.subscribe = function (callback) { var _this = this; if (this.listeners.size === 0) { this.addDocumentListeners(); } this.listeners.add(callback); callback(this.isKeyboard); return function () { _this.listeners["delete"](callback); if (_this.listeners.size === 0) { _this.removeDocumentListeners(); } }; }; return ControlTracker; }()); var tracker = typeof document !== 'undefined' && new ControlTracker(document); export default function useFocusVisible() { var _a = useState(false), visible = _a[0], setVisible = _a[1]; useEffect(function () { if (tracker) { return tracker.subscribe(function (isKeyboard) { return setVisible(isKeyboard); }); } }, []); return visible ? { 'data-awsui-focus-visible': visible } : {}; }