All files / app/features/picture/pages/picture-detail picture-detail.component.ts

90.69% Statements 117/129
76.13% Branches 67/88
88.88% Functions 24/27
91.52% Lines 108/118

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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 2291x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x                 1x 30x 30x 30x 30x 30x 30x 30x 30x 30x   30x   30x 30x     30x   30x 29x 29x     30x   30x     30x         30x 30x 30x 30x   30x 30x 30x     30x   30x     29x   26x           1x 1x                     30x 30x     30x   29x 29x 29x         30x 50x 50x   13x 13x 13x 13x           14x 13x 13x 13x 13x       3x 3x 3x       3x       3x 1x 1x   2x       8x   7x 7x 7x   7x 2x 2x     5x 5x         4x 4x 4x 3x 3x 1x 1x   4x     1x 1x 1x           6x 6x 6x                       1x 1x 1x 1x                 1x 1x       1x 1x     1x 1x                
import { AuthService } from '../../../../services/auth/auth.service';
import { PictureLightboxService } from '../../../../services/pictures/picture-lightbox.service';
import { PictureService } from '../../../../services/pictures/picture.service';
import { ErrorComponent } from '../../../../shared/components/error/error.component';
import { SidebarActionComponent } from '../../../../shared/components/sidebar-action/sidebar-action.component';
import { PictureResolveResult } from '../../resolvers/picture.resolver';
import { isPlatformBrowser } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, inject, PLATFORM_ID, signal, viewChild } from '@angular/core';
import { takeUntilDestroyed, toObservable, toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { LoggerService, NotificationService, WINDOW } from '@drevo-web/core';
import { PictureArticle } from '@drevo-web/shared';
import { FormatDatePipe, SpinnerComponent } from '@drevo-web/ui';
import { of, startWith, switchMap } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
 
const TITLE_MIN_LENGTH = 5;
const TITLE_MAX_LENGTH = 500;
 
@Component({
    selector: 'app-picture-detail',
    imports: [ErrorComponent, ReactiveFormsModule, SidebarActionComponent, FormatDatePipe, RouterLink, SpinnerComponent],
    templateUrl: './picture-detail.component.html',
    styleUrl: './picture-detail.component.scss',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PictureDetailComponent {
    private readonly route = inject(ActivatedRoute);
    private readonly authService = inject(AuthService);
    private readonly lightboxService = inject(PictureLightboxService);
    private readonly pictureService = inject(PictureService);
    private readonly notificationService = inject(NotificationService);
    private readonly logger = inject(LoggerService).withContext('PictureDetail');
    private readonly window = inject(WINDOW);
    private readonly platformId = inject(PLATFORM_ID);
    private readonly destroyRef = inject(DestroyRef);
 
    private readonly titleInputRef = viewChild<ElementRef<HTMLTextAreaElement>>('titleInput');
 
    private readonly resolveResult = toSignal(
        this.route.data.pipe(map(data => data['picture'] as PictureResolveResult)),
    );
 
    private readonly user = toSignal(this.authService.user$);
 
    readonly picture = computed(() => {
        const result = this.resolveResult();
        return typeof result === 'object' ? result : undefined;
    });
 
    readonly isLoadError = computed(() => this.resolveResult() === 'load-error');
 
    readonly canEdit = computed(() => this.user()?.permissions.canEdit ?? false);
 
    // Title inline editing
    readonly titleControl = new FormControl('', {
        nonNullable: true,
        validators: [Validators.required, Validators.minLength(TITLE_MIN_LENGTH), Validators.maxLength(TITLE_MAX_LENGTH)],
    });
 
    private readonly _isEditingTitle = signal(false);
    private readonly _isSavingTitle = signal(false);
    private readonly _titleOverride = signal<string | undefined>(undefined);
    private blurHandledByKeyboard = false;
 
    readonly isEditingTitle = this._isEditingTitle.asReadonly();
    readonly isSavingTitle = this._isSavingTitle.asReadonly();
    readonly displayTitle = computed(() => this._titleOverride() ?? this.picture()?.title ?? '');
 
    // Articles
    private readonly pictureId = computed(() => this.picture()?.id);
 
    private readonly articlesResult = toSignal(
        toObservable(this.pictureId).pipe(
            switchMap(id =>
                id
                    ? this.pictureService.getPictureArticles(id).pipe(
                          map(articles => ({ articles, loading: false as const })),
                          startWith({
                              articles: undefined as readonly PictureArticle[] | undefined,
                              loading: true as const,
                          }),
                          catchError((error: unknown) => {
                              this.logger.error('Failed to load articles', error);
                              return of({
                                  articles: undefined as readonly PictureArticle[] | undefined,
                                  loading: false as const,
                              });
                          }),
                      )
                    : of({ articles: undefined as readonly PictureArticle[] | undefined, loading: false as const }),
            ),
        ),
    );
 
    readonly articles = computed(() => this.articlesResult()?.articles);
    readonly articlesLoading = computed(() => this.articlesResult()?.loading ?? false);
 
    constructor() {
        effect(
            () => {
                this.picture(); // track picture changes
                this._titleOverride.set(undefined);
                this._isEditingTitle.set(false);
            },
            { allowSignalWrites: true },
        );
 
        effect(() => {
            const el = this.titleInputRef()?.nativeElement;
            if (el) {
                // Auto-size: shrink to 0, then expand to scrollHeight (min 4 rows via CSS)
                el.style.height = '0';
                el.style.height = `${el.scrollHeight}px`;
                el.focus();
                el.select();
            }
        });
    }
 
    startTitleEdit(): void {
        if (!this.canEdit() || this._isEditingTitle()) return;
        this.blurHandledByKeyboard = false;
        this.titleControl.setValue(this.displayTitle());
        this.titleControl.markAsPristine();
        this._isEditingTitle.set(true);
    }
 
    cancelTitleEdit(): void {
        Iif (this._isSavingTitle()) return;
        this.blurHandledByKeyboard = true;
        this._isEditingTitle.set(false);
    }
 
    onTitleBlur(): void {
        Iif (this.blurHandledByKeyboard) {
            this.blurHandledByKeyboard = false;
            return;
        }
        if (this.titleControl.invalid) {
            this._isEditingTitle.set(false);
            return;
        }
        this.saveTitleEdit();
    }
 
    saveTitleEdit(): void {
        if (this.titleControl.invalid || this._isSavingTitle()) return;
 
        const value = this.titleControl.value.trim();
        const pic = this.picture();
        Iif (!pic) return;
 
        if (value === this.displayTitle()) {
            this.cancelTitleEdit();
            return;
        }
 
        this._isSavingTitle.set(true);
        this.pictureService
            .updateTitle(pic.id, value)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
                next: result => {
                    this._isSavingTitle.set(false);
                    this._isEditingTitle.set(false);
                    if (result.picture) {
                        this._titleOverride.set(result.picture.title);
                        this.notificationService.success('Описание обновлено');
                    } else Eif (result.pending) {
                        this.notificationService.info('Изменение отправлено на модерацию');
                    }
                    this.logger.info('Title update submitted', { id: pic.id, title: value });
                },
                error: (err: unknown) => {
                    this._isSavingTitle.set(false);
                    this.logger.error('Failed to update title', err);
                    this.notificationService.error('Не удалось обновить описание');
                },
            });
    }
 
    onTitleEnter(event: Event): void {
        event.preventDefault();
        this.blurHandledByKeyboard = true;
        this.saveTitleEdit();
    }
 
    autoResizeTextarea(): void {
        const el = this.titleInputRef()?.nativeElement;
        if (el) {
            el.style.height = '0';
            el.style.height = `${el.scrollHeight}px`;
        }
    }
 
    onImageClick(): void {
        const pic = this.picture();
        Eif (pic) {
            this.logger.info('Opening lightbox from detail', { id: pic.id });
            this.lightboxService.open(pic.id);
        }
    }
 
    editPicture(): void {
        this.notificationService.info('Функция еще не реализована');
    }
 
    copyInsertCode(): void {
        const pic = this.picture();
        Iif (!pic || !isPlatformBrowser(this.platformId)) {
            return;
        }
 
        const code = `@${pic.id}@`;
        this.window?.navigator?.clipboard
            .writeText(code)
            .then(() => {
                this.notificationService.success('Код скопирован');
                this.logger.info('Insert code copied', { id: pic.id, code });
            })
            .catch((error: unknown) => {
                this.logger.error('Failed to copy insert code', error);
                this.notificationService.error(`Не удалось скопировать код ${code}`);
            });
    }
}