All files / services drawer.service.ts

91.66% Statements 22/24
75% Branches 6/8
100% Functions 8/8
90.47% Lines 19/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 491x 1x 1x   1x 1x         1x 13x 13x   13x 13x     4x 4x       4x       3x       3x       3x     3x       4x     4x      
import { StorageService } from './storage.service';
import { isPlatformBrowser } from '@angular/common';
import { inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
 
const DRAWER_STORAGE_KEY = 'drevo-sidebar-open';
const DEFAULT_OPEN = true;
 
@Injectable({
    providedIn: 'root',
})
export class DrawerService {
    private readonly storage = inject(StorageService);
    private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
 
    private readonly _isOpen = signal(false);
    readonly isOpen = this._isOpen.asReadonly();
 
    toggle(): void {
        this._isOpen.update(v => !v);
        this.save(this._isOpen());
    }
 
    open(): void {
        this._isOpen.set(true);
    }
 
    close(): void {
        this._isOpen.set(false);
    }
 
    restoreSaved(): void {
        this._isOpen.set(this.loadSaved());
    }
 
    private loadSaved(): boolean {
        Iif (!this.isBrowser) {
            return DEFAULT_OPEN;
        }
        return this.storage.get<boolean>(DRAWER_STORAGE_KEY) ?? DEFAULT_OPEN;
    }
 
    private save(isOpen: boolean): void {
        Iif (!this.isBrowser) {
            return;
        }
        this.storage.set(DRAWER_STORAGE_KEY, isOpen);
    }
}