| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import type {PageVisibility} from 'isl/src/types'; |
| b69ab31 | | | 9 | |
| b69ab31 | | | 10 | /** |
| b69ab31 | | | 11 | * Aggregates if any ISL page has focus or visibility. |
| b69ab31 | | | 12 | */ |
| b69ab31 | | | 13 | export class PageFocusTracker { |
| b69ab31 | | | 14 | private focusedPages = new Set(); |
| b69ab31 | | | 15 | private visiblePages = new Set(); |
| b69ab31 | | | 16 | |
| b69ab31 | | | 17 | private onChangeHandlers = new Set<(state: PageVisibility) => unknown>(); |
| b69ab31 | | | 18 | |
| b69ab31 | | | 19 | setState(page: string, state: PageVisibility) { |
| b69ab31 | | | 20 | switch (state) { |
| b69ab31 | | | 21 | case 'focused': |
| b69ab31 | | | 22 | this.focusedPages.add(page); |
| b69ab31 | | | 23 | this.visiblePages.add(page); |
| b69ab31 | | | 24 | break; |
| b69ab31 | | | 25 | case 'visible': |
| b69ab31 | | | 26 | this.focusedPages.delete(page); |
| b69ab31 | | | 27 | this.visiblePages.add(page); |
| b69ab31 | | | 28 | break; |
| b69ab31 | | | 29 | case 'hidden': |
| b69ab31 | | | 30 | this.focusedPages.delete(page); |
| b69ab31 | | | 31 | this.visiblePages.delete(page); |
| b69ab31 | | | 32 | break; |
| b69ab31 | | | 33 | } |
| b69ab31 | | | 34 | for (const handler of this.onChangeHandlers) { |
| b69ab31 | | | 35 | handler(state); |
| b69ab31 | | | 36 | } |
| b69ab31 | | | 37 | } |
| b69ab31 | | | 38 | |
| b69ab31 | | | 39 | public disposePage(page: string) { |
| b69ab31 | | | 40 | this.focusedPages.delete(page); |
| b69ab31 | | | 41 | this.visiblePages.delete(page); |
| b69ab31 | | | 42 | } |
| b69ab31 | | | 43 | |
| b69ab31 | | | 44 | public hasPageWithFocus() { |
| b69ab31 | | | 45 | return this.focusedPages.size > 0; |
| b69ab31 | | | 46 | } |
| b69ab31 | | | 47 | public hasVisiblePage() { |
| b69ab31 | | | 48 | return this.visiblePages.size > 0; |
| b69ab31 | | | 49 | } |
| b69ab31 | | | 50 | |
| b69ab31 | | | 51 | public onChange(callback: () => unknown): () => void { |
| b69ab31 | | | 52 | this.onChangeHandlers.add(callback); |
| b69ab31 | | | 53 | return () => this.onChangeHandlers.delete(callback); |
| b69ab31 | | | 54 | } |
| b69ab31 | | | 55 | } |