A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
// SPDX-License-Identifier: AGPL-3.0-or-later
import Navigation from '@app/features/navigation/state/Navigation';
import {getAppStorageScope} from '@app/features/platform/state/PersistentStorage';
import {makePersistent} from '@app/features/platform/utils/MobXPersistence';
import {initializeStore} from '@app/features/platform/utils/StoreInitialization';
import {ME} from '@fluxer/constants/src/AppConstants';
import {makeAutoObservable, reaction} from 'mobx';
const FAVORITES_ROUTE_ID = '@favorites';
class SelectedGuild {
lastSelectedGuildId: string | null = null;
selectedGuildId: string | null = null;
selectionNonce: number = 0;
private selectedGuildScope: string | null = null;
private navigationDisposer: (() => void) | null = null;
constructor() {
makeAutoObservable(this, {}, {autoBind: true});
initializeStore(this, () => this.initPersistence());
}
private async initPersistence(): Promise<void> {
await makePersistent(this, 'SelectedGuild', ['lastSelectedGuildId']);
this.setupNavigationReaction();
}
private setupNavigationReaction(): void {
this.navigationDisposer?.();
this.navigationDisposer = reaction(
() => Navigation.guildId,
(guildId) => {
const normalized = this.normalizeGuildFromNavigation(guildId);
if (normalized) {
this.applyNavigationGuild(normalized);
} else {
this.clearSelection();
}
},
{
fireImmediately: true,
},
);
}
private normalizeGuildFromNavigation(guildId: string | null): string | null {
if (!guildId || guildId === ME || guildId === FAVORITES_ROUTE_ID) {
return null;
}
return guildId;
}
private applyNavigationGuild(guildId: string): void {
this.setGuild(guildId);
}
private setGuild(
guildId: string,
options?: {
forceNonce?: boolean;
},
): void {
const hasChanged = guildId !== this.selectedGuildId;
if (hasChanged) {
this.rememberSelectedGuild();
this.selectedGuildId = guildId;
this.selectedGuildScope = getAppStorageScope();
this.bumpNonce();
return;
}
if (options?.forceNonce) {
this.bumpNonce();
}
}
private clearSelection(): void {
if (this.selectedGuildId == null) {
return;
}
this.rememberSelectedGuild();
this.selectedGuildId = null;
this.selectedGuildScope = null;
this.bumpNonce();
}
private rememberSelectedGuild(): void {
if (this.selectedGuildScope === getAppStorageScope()) {
this.lastSelectedGuildId = this.selectedGuildId;
}
}
private bumpNonce(): void {
this.selectionNonce++;
}
}
export default new SelectedGuild();