addons/isl-server/src/PageFocusTracker.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type {PageVisibility} from 'isl/src/types';
b69ab319
b69ab3110/**
b69ab3111 * Aggregates if any ISL page has focus or visibility.
b69ab3112 */
b69ab3113export class PageFocusTracker {
b69ab3114 private focusedPages = new Set();
b69ab3115 private visiblePages = new Set();
b69ab3116
b69ab3117 private onChangeHandlers = new Set<(state: PageVisibility) => unknown>();
b69ab3118
b69ab3119 setState(page: string, state: PageVisibility) {
b69ab3120 switch (state) {
b69ab3121 case 'focused':
b69ab3122 this.focusedPages.add(page);
b69ab3123 this.visiblePages.add(page);
b69ab3124 break;
b69ab3125 case 'visible':
b69ab3126 this.focusedPages.delete(page);
b69ab3127 this.visiblePages.add(page);
b69ab3128 break;
b69ab3129 case 'hidden':
b69ab3130 this.focusedPages.delete(page);
b69ab3131 this.visiblePages.delete(page);
b69ab3132 break;
b69ab3133 }
b69ab3134 for (const handler of this.onChangeHandlers) {
b69ab3135 handler(state);
b69ab3136 }
b69ab3137 }
b69ab3138
b69ab3139 public disposePage(page: string) {
b69ab3140 this.focusedPages.delete(page);
b69ab3141 this.visiblePages.delete(page);
b69ab3142 }
b69ab3143
b69ab3144 public hasPageWithFocus() {
b69ab3145 return this.focusedPages.size > 0;
b69ab3146 }
b69ab3147 public hasVisiblePage() {
b69ab3148 return this.visiblePages.size > 0;
b69ab3149 }
b69ab3150
b69ab3151 public onChange(callback: () => unknown): () => void {
b69ab3152 this.onChangeHandlers.add(callback);
b69ab3153 return () => this.onChangeHandlers.delete(callback);
b69ab3154 }
b69ab3155}