Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
2.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import * as ModalCommands from '@app/features/ui/commands/ModalCommands';
import * as PopoutCommands from '@app/features/ui/commands/PopoutCommands';
import {getActivePortalHost} from '@app/features/ui/overlay/PortalHostContext';
import type {PopoutKey} from '@app/features/ui/popover';

export const LayerType = Object.freeze({
	CONTEXT_MENU: 'contextmenu',
	MODAL: 'modal',
	POPOUT: 'popout',
} as const);

export type LayerType = (typeof LayerType)[keyof typeof LayerType];

interface Layer {
	type: LayerType;
	key: string | PopoutKey;
	onClose?: () => void;
	ownerDocument: Document;
}

class LayerManager {
	private layers: Array<Layer> = [];
	private isInitialized = false;

	init() {
		if (this.isInitialized) return;
		this.isInitialized = true;
		document.addEventListener('keydown', this.handleGlobalEscape, {capture: true});
	}

	observeDocument(childDocument: Document): () => void {
		childDocument.addEventListener('keydown', this.handleGlobalEscape, {capture: true});
		return () => childDocument.removeEventListener('keydown', this.handleGlobalEscape, {capture: true});
	}

	private handleGlobalEscape = (event: KeyboardEvent) => {
		if (event.key !== 'Escape') return;
		const eventDocument = event.currentTarget as Document;
		const topLayer = this.layers.findLast((layer) => layer.ownerDocument === eventDocument);
		if (!topLayer) return;
		if (topLayer.type !== 'popout' && !topLayer.onClose) return;
		event.preventDefault();
		event.stopImmediatePropagation();
		if (topLayer.type === 'popout') {
			topLayer.onClose?.();
			this.removeLayer('popout', topLayer.key);
			PopoutCommands.close(topLayer.key);
			return;
		}
		topLayer.onClose?.();
	};

	addLayer(
		type: LayerType,
		key: string | PopoutKey,
		onClose?: () => void,
		ownerDocument: Document = getActivePortalHost()?.ownerDocument ?? document,
	) {
		this.removeLayer(type, key);
		this.layers.push({
			type,
			key,
			onClose,
			ownerDocument,
		});
	}

	removeLayer(type: LayerType, key: string | PopoutKey) {
		this.layers = this.layers.filter((layer) => !(layer.type === type && layer.key === key));
	}

	private getTopLayer(): Layer | undefined {
		return this.layers.length > 0 ? this.layers[this.layers.length - 1] : undefined;
	}

	isTopLayer(type: LayerType, key: string | PopoutKey): boolean {
		const topLayer = this.getTopLayer();
		return topLayer?.type === type && topLayer?.key === key;
	}

	hasType(type: LayerType): boolean {
		return this.layers.some((l) => l.type === type);
	}

	closeAll(): void {
		ModalCommands.popAll();
		PopoutCommands.closeAll();
		this.layers = [];
	}
}

export default new LayerManager();