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