UNPKG

react-native-debug-toolkit

Version:

A simple yet powerful debugging toolkit for React Native with a convenient floating UI for development

81 lines (65 loc) 2.35 kB
import AsyncStorage from '@react-native-async-storage/async-storage'; export type BaseEnvironmentConfig = { [key: string]: any; }; export class EnvironmentManager<T extends BaseEnvironmentConfig> { private static instance: EnvironmentManager<any>; private currentEnv: string; private environments: Record<string, T>; private listeners: ((env: T) => void)[] = []; static ENV_STORAGE_KEY = '@debug_toolkit_env'; protected constructor() { this.environments = {}; this.currentEnv = ''; } public static getInstance<T extends BaseEnvironmentConfig>(): EnvironmentManager<T> { if (!EnvironmentManager.instance) { EnvironmentManager.instance = new EnvironmentManager<T>(); } return EnvironmentManager.instance; } public async initialize(environments: Record<string, T>, defaultEnv: string): Promise<string> { if (!__DEV__) return defaultEnv; this.environments = environments; try { const savedEnv = await AsyncStorage.getItem(EnvironmentManager.ENV_STORAGE_KEY); this.currentEnv = savedEnv || defaultEnv; await AsyncStorage.setItem(EnvironmentManager.ENV_STORAGE_KEY, this.currentEnv); return this.currentEnv; } catch (error) { console.error('EnvironmentManager initialization error:', error); this.currentEnv = defaultEnv; return defaultEnv; } } public async changeEnvironment(newValue: string): Promise<void> { if (newValue === this.currentEnv) return; try { await AsyncStorage.setItem(EnvironmentManager.ENV_STORAGE_KEY, newValue); this.currentEnv = newValue; const envConfig = this.environments[newValue]; this.listeners.forEach(listener => listener(envConfig)); } catch (error) { console.error('Failed to change environment:', error); throw error; } } public getCurrentEnvironment(): string { return this.currentEnv; } public getEnvironmentConfig(): T { return this.environments[this.currentEnv]; } public getEnvironments(): Record<string, T> { return this.environments; } public onEnvironmentChange(listener: (env: T) => void): () => void { this.listeners.push(listener); return () => { this.listeners = this.listeners.filter(l => l !== listener); }; } public destroy(): void { this.listeners = []; } }