UNPKG

react-native-tvfocus

Version:

React Native tvOS and Android TV library to improve focus management with multiple screens.

76 lines (75 loc) 2.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFocusManager = exports.FocusManagerContext = exports.defaultFocusContext = void 0; const React = require("react"); const react_1 = require("react"); class FocusManager { constructor() { this.active = false; this.focusables = new Map(); this.lastfocused = null; this.nextfocus = null; this.firstitem = null; this.defaultitem = null; this.forceUpdate = null; } focus(focusable) { var _a, _b; const id = typeof focusable === 'number' ? focusable : focusable.id; this.nextfocus = id; (_a = this.forceUpdate) === null || _a === void 0 ? void 0 : _a.call(null); (_b = this.focusables.get(id)) === null || _b === void 0 ? void 0 : _b.forceUpdate(); } focusFirstIfNoDefault() { if (typeof this.defaultitem !== 'number' && typeof this.firstitem === 'number') { this.focus(this.firstitem); } } /** @internal */ shouldSetFocus(focusable, isDefault) { if (!this.active) return false; if (typeof this.lastfocused !== 'number' && typeof this.firstitem !== 'number') { this.firstitem = focusable.id; } if (typeof this.nextfocus === 'number' && this.nextfocus === focusable.id) { this.nextfocus = null; return true; } if (typeof this.lastfocused !== 'number' && isDefault) { this.defaultitem = focusable.id; return true; } return false; } /** @internal */ handleRemovedFocusable(focusable) { if (this.lastfocused === focusable.id) this.lastfocused = null; if (this.nextfocus === focusable.id) this.nextfocus = null; if (this.firstitem === focusable.id) this.firstitem = null; if (this.defaultitem === focusable.id) this.defaultitem = null; } /** @internal */ willBecomeActive() { this.nextfocus = this.lastfocused; } /** @internal */ willBecomeInactive() { // } } exports.default = FocusManager; exports.defaultFocusContext = Object.freeze({ focus: new FocusManager(), active: false, }); exports.FocusManagerContext = React.createContext(exports.defaultFocusContext); function useFocusManager() { const context = react_1.useContext(exports.FocusManagerContext); return context === exports.defaultFocusContext ? null : context.focus; } exports.useFocusManager = useFocusManager;