All files / app/services/pictures picture-lightbox.service.ts

97.46% Statements 77/79
85.71% Branches 12/14
93.33% Functions 14/15
97.4% Lines 75/77

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 16112x 12x 12x 12x 12x   12x   12x         12x 123x 123x 123x 123x 123x   123x 123x 123x 123x   123x 123x 123x 123x     123x   123x     123x 123x       15x   15x   15x 15x 15x 15x   15x 15x 15x                 5x   5x   5x 5x 5x 5x   5x 5x       123x     15x   1x 1x 1x 1x             9x 1x   8x 8x         18x                       18x 1x     17x 17x 17x 17x 17x   17x 4x 4x 4x           2x         20x 20x   20x 3x   17x         123x       123x     39x 13x 13x          
import { PictureService } from './picture.service';
import { Location } from '@angular/common';
import { DestroyRef, inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { LoggerService, WINDOW } from '@drevo-web/core';
import { Picture } from '@drevo-web/shared';
import { catchError, EMPTY, fromEvent, Subject, switchMap } from 'rxjs';
 
const HASH_PREFIX = '#picture=';
 
@Injectable({
    providedIn: 'root',
})
export class PictureLightboxService {
    private readonly pictureService = inject(PictureService);
    private readonly location = inject(Location);
    private readonly window = inject(WINDOW);
    private readonly destroyRef = inject(DestroyRef);
    private readonly logger = inject(LoggerService).withContext('PictureLightbox');
 
    private readonly _isOpen = signal(false);
    private readonly _currentPicture = signal<Picture | undefined>(undefined);
    private readonly _isLoading = signal(false);
    private readonly _isZoomed = signal(false);
 
    readonly isOpen = this._isOpen.asReadonly();
    readonly currentPicture = this._currentPicture.asReadonly();
    readonly isLoading = this._isLoading.asReadonly();
    readonly isZoomed = this._isZoomed.asReadonly();
 
    /** Whether we pushed a hash entry that needs to be cleaned up on close */
    private hashPushed = false;
 
    private readonly _openSubject = new Subject<number>();
 
    constructor() {
        this.listenPopstate();
        this.listenOpen();
    }
 
    open(pictureId: number): void {
        this.logger.info('Opening lightbox', { pictureId });
 
        const wasOpen = this._isOpen();
 
        this._isOpen.set(true);
        this._isLoading.set(true);
        this._isZoomed.set(false);
        this._currentPicture.set(undefined);
 
        this.updateHash(pictureId, wasOpen);
        this.hashPushed = true;
        this._openSubject.next(pictureId);
    }
 
    /**
     * Open lightbox with a pre-loaded picture (skips API fetch).
     * Useful when the caller already has the up-to-date picture data
     * (e.g. after file replacement with cache-busted URL).
     */
    openWithPicture(picture: Picture): void {
        this.logger.info('Opening lightbox with preloaded picture', { pictureId: picture.id });
 
        const wasOpen = this._isOpen();
 
        this._isOpen.set(true);
        this._isLoading.set(false);
        this._isZoomed.set(false);
        this._currentPicture.set(picture);
 
        this.updateHash(picture.id, wasOpen);
        this.hashPushed = true;
    }
 
    private listenOpen(): void {
        this._openSubject
            .pipe(
                switchMap(pictureId =>
                    this.pictureService.getPicture(pictureId).pipe(
                        catchError(error => {
                            this.logger.error('Failed to load picture', error);
                            this._isLoading.set(false);
                            this.close();
                            return EMPTY;
                        })
                    )
                ),
                takeUntilDestroyed(this.destroyRef)
            )
            .subscribe(picture => {
                if (!this._isOpen()) {
                    return;
                }
                this._currentPicture.set(picture);
                this._isLoading.set(false);
            });
    }
 
    close(): void {
        this.closeInternal(true);
    }
 
    /**
     * Close without navigating back in history.
     * Use when the caller handles navigation itself (e.g. routerLink).
     */
    closeWithoutNavigation(): void {
        this.closeInternal(false);
    }
 
    private closeInternal(navigateBack: boolean): void {
        if (!this._isOpen()) {
            return;
        }
 
        this.logger.info('Closing lightbox');
        this._isOpen.set(false);
        this._currentPicture.set(undefined);
        this._isLoading.set(false);
        this._isZoomed.set(false);
 
        if (this.hashPushed) {
            this.hashPushed = false;
            Eif (navigateBack) {
                this.location.back();
            }
        }
    }
 
    toggleZoom(): void {
        this._isZoomed.update(v => !v);
    }
 
    /** Push or replace the hash depending on whether the lightbox is already open */
    private updateHash(pictureId: number, replace: boolean): void {
        const currentPath = this.location.path(false);
        const url = `${currentPath}${HASH_PREFIX}${pictureId}`;
 
        if (replace) {
            this.location.replaceState(url);
        } else {
            this.location.go(url);
        }
    }
 
    private listenPopstate(): void {
        Iif (!this.window) {
            return;
        }
 
        fromEvent(this.window, 'popstate')
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe(() => {
                if (this._isOpen()) {
                    this.hashPushed = false;
                    this.close();
                }
            });
    }
}