Files
start-os/web/projects/ui/src/app/services/theme-switcher.service.ts
2024-08-15 12:40:49 +04:00

37 lines
1016 B
TypeScript

import { Inject, Injectable } from '@angular/core'
import { WA_WINDOW } from '@ng-web-apis/common'
import { PatchDB } from 'patch-db-client'
import { filter, take, BehaviorSubject } from 'rxjs'
import { ApiService } from './api/embassy-api.service'
import { DataModel } from './patch-db/data-model'
@Injectable({
providedIn: 'root',
})
export class ThemeSwitcherService extends BehaviorSubject<string> {
constructor(
private readonly patch: PatchDB<DataModel>,
private readonly embassyApi: ApiService,
@Inject(WA_WINDOW) private readonly windowRef: Window,
) {
super('Dark')
this.patch
.watch$('ui', 'theme')
.pipe(take(1), filter(Boolean))
.subscribe(theme => {
this.updateTheme(theme)
})
}
override next(theme: string): void {
this.embassyApi.setDbValue(['theme'], theme)
this.updateTheme(theme)
}
private updateTheme(theme: string): void {
this.windowRef.document.body.setAttribute('data-theme', theme)
super.next(theme)
}
}