import { Theme, ThemeManager, DEFAULT_THEME } from './theme-protocol'; import { Component, Value, Autowired, Optional, Prioritizeable, PostConstruct } from '@celljs/core'; import { BehaviorSubject } from 'rxjs'; @Component(ThemeManager) export class ThemeManagerImpl implements ThemeManager { protected readonly themeStorageKey = 'cell:theme'; @Value('cell.themes') protected readonly themesForConfig: { [id: string]: Theme }; @Autowired(Theme) @Optional() protected readonly themes: Theme[]; protected prioritized: Theme[]; currentSubject = new BehaviorSubject | undefined>(undefined); @PostConstruct() init() { const themeStr = localStorage.getItem(this.themeStorageKey); if (themeStr) { this.currentSubject.next(JSON.parse(themeStr)); } else { if (this.themesForConfig) { this.currentSubject.next(this.themesForConfig[DEFAULT_THEME]); } } this.currentSubject.subscribe(theme => { if (theme) { localStorage.setItem(this.themeStorageKey, JSON.stringify(theme)); } else { localStorage.removeItem(this.themeStorageKey); } }); } async get(): Promise[]> { if (!this.prioritized) { const parsedThemesForConfig = Object.keys(this.themesForConfig || {}).map(id => { const theme = { ...this.themesForConfig[id] }; theme.id = id; theme.priority = theme.priority || 500; return theme; }); this.prioritized = Prioritizeable.prioritizeAllSync([ ...parsedThemesForConfig, ...this.themes ]).map(p => p.value); } return this.prioritized; } }