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

89.53% Statements 248/277
77.22% Branches 156/202
88.13% Functions 52/59
92.12% Lines 234/254

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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 5441x 1x 1x 1x 1x 1x         1x     1x 1x 1x                       1x 1x 1x 1x   1x 1x 1x   1x 1x                                 1x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x   71x 71x   71x 71x     71x   71x 68x 68x     71x   71x 71x 71x     71x                 71x 71x 71x 71x   71x 71x 71x     71x 71x 71x 71x     71x 71x     71x 71x 71x 71x   71x 3x   71x     1x 1x                 71x     68x   64x           1x 1x                     71x 71x 71x 66x 65x 65x       71x 68x 68x 68x 68x     71x 89x 89x   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 1x   4x     1x 1x 1x           6x 6x 6x                       2x 2x   2x   2x 2x 1x           1x                   12x 12x   12x   12x   12x 1x 1x     11x 1x 1x     10x   10x                         10x 7x   3x           7x 7x         7x 7x 7x   7x   7x         7x 7x         6x 5x 5x 5x 1x 1x 1x   6x     1x 1x           8x 8x   8x                     8x 6x   6x           3x 2x 2x 1x 1x 1x   3x     3x 1x   2x   3x           1x 1x   1x                       1x       1x 1x       1x 1x     1x 1x                 3x       7x 7x     7x 7x                     11x             11x   3x 3x 3x 3x 3x   4x 4x 4x 4x 4x   4x 4x 4x 4x 4x     11x 11x     11x       3x 3x 3x       3x     8x   5x     5x 5x 1x   4x   5x       5x   3x 3x          
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 { PendingBannerComponent } from '../../components/pending-banner/pending-banner.component';
import {
    ReplaceFileDialogData,
    ReplaceFileDialogResult,
} from '../../components/replace-file-dialog/replace-file-dialog.component';
import { TITLE_MAX_LENGTH, TITLE_MIN_LENGTH } from '../../constants/picture.constants';
import { PendingAction } from '../../models/pending.model';
import { PictureResolveResult } from '../../resolvers/picture.resolver';
import { isPlatformBrowser } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
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, Router, RouterLink } from '@angular/router';
import { LoggerService, NotificationService, WINDOW } from '@drevo-web/core';
import { Picture, PictureArticle, PicturePending } from '@drevo-web/shared';
import { ConfirmationService, FormatDatePipe, ModalService, SpinnerComponent } from '@drevo-web/ui';
import { merge, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { catchError, filter, finalize, map, tap } from 'rxjs/operators';
 
const MAX_FILE_SIZE_BYTES = 500 * 1024;
const ALLOWED_FILE_TYPE = 'image/jpeg';
 
@Component({
    selector: 'app-picture-detail',
    imports: [
        ErrorComponent,
        ReactiveFormsModule,
        SidebarActionComponent,
        PendingBannerComponent,
        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 modalService = inject(ModalService);
    private readonly confirmationService = inject(ConfirmationService);
    private readonly router = inject(Router);
    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 fileInputRef = viewChild<ElementRef<HTMLInputElement>>('fileInput');
 
    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);
    readonly canModerate = computed(() => this.user()?.permissions.canModerate ?? false);
    readonly currentUserName = computed(() => this.user()?.name ?? '');
 
    // 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 ?? '');
 
    // File replacement
    private readonly _isUploading = signal(false);
    private readonly _imageOverride = signal<string | undefined>(undefined);
    readonly isUploading = this._isUploading.asReadonly();
    readonly displayImageUrl = computed(() => this._imageOverride() ?? this.picture()?.imageUrl ?? '');
 
    // Deletion
    private readonly _isDeleting = signal(false);
    readonly isDeleting = this._isDeleting.asReadonly();
 
    // Articles
    private readonly pictureId = computed(() => this.picture()?.id);
    private readonly _refreshPendingSubject = new Subject<void>();
    private readonly _pendingActionInProgress = signal<number | undefined>(undefined);
    readonly pendingActionInProgress = this._pendingActionInProgress.asReadonly();
 
    readonly pendingChanges = toSignal(
        merge(toObservable(this.pictureId), this._refreshPendingSubject.pipe(map(() => this.pictureId()))).pipe(
            switchMap(id =>
                id
                    ? this.pictureService.getPicturePending(id).pipe(
                          catchError((error: unknown) => {
                              this.logger.error('Failed to load picture pending changes', error);
                              return of([] as readonly PicturePending[]);
                          }),
                      )
                    : of([] as readonly PicturePending[]),
            ),
        ),
        { initialValue: [] as readonly PicturePending[] },
    );
 
    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);
    readonly canDelete = computed(() => {
        if (this._isDeleting() || this._isUploading() || this.articlesLoading()) return false;
        const articleList = this.articles();
        return articleList?.length === 0;
    });
 
    constructor() {
        effect(() => {
            this.picture(); // track picture changes
            this._titleOverride.set(undefined);
            this._imageOverride.set(undefined);
            this._isEditingTitle.set(false);
        });
 
        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.refreshPending();
                        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();
        Iif (!pic) return;
 
        this.logger.info('Opening lightbox from detail', { id: pic.id });
 
        const imageOverride = this._imageOverride();
        if (imageOverride) {
            this.lightboxService.openWithPicture({
                ...pic,
                title: this.displayTitle(),
                imageUrl: imageOverride,
            });
        } else {
            this.lightboxService.open(pic.id);
        }
    }
 
    editPicture(): void {
        if (this._isUploading()) return;
        this.fileInputRef()?.nativeElement.click();
    }
 
    onFileSelected(event: Event): void {
        const input = event.target as HTMLInputElement;
        const file = input.files?.[0];
        // Reset input so the same file can be re-selected
        input.value = '';
 
        Iif (!file) return;
 
        if (file.type !== ALLOWED_FILE_TYPE) {
            this.notificationService.error('Допустимый формат — только JPEG');
            return;
        }
 
        if (file.size > MAX_FILE_SIZE_BYTES) {
            this.notificationService.error('Максимальный размер файла — 500 КБ');
            return;
        }
 
        const previewUrl = URL.createObjectURL(file);
 
        this.modalService
            .open<ReplaceFileDialogData, ReplaceFileDialogResult>(
                () =>
                    import('../../components/replace-file-dialog/replace-file-dialog.component').then(
                        m => m.ReplaceFileDialogComponent,
                    ),
                {
                    data: { currentTitle: this.displayTitle(), previewUrl },
                    width: '500px',
                },
            )
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe(result => {
                if (result) {
                    this.uploadFile(file, result.title, previewUrl);
                } else {
                    URL.revokeObjectURL(previewUrl);
                }
            });
    }
 
    private uploadFile(file: File, title: string, previewUrl: string): void {
        const pic = this.picture();
        Iif (!pic) {
            URL.revokeObjectURL(previewUrl);
            return;
        }
 
        const formData = new FormData();
        formData.append('file', file);
        formData.append('pic_title', title);
 
        this._isUploading.set(true);
 
        this.pictureService
            .editPicture(pic.id, formData)
            .pipe(
                takeUntilDestroyed(this.destroyRef),
                finalize(() => {
                    this._isUploading.set(false);
                    URL.revokeObjectURL(previewUrl);
                }),
            )
            .subscribe({
                next: result => {
                    if (result.picture) {
                        this._titleOverride.set(result.picture.title);
                        this._imageOverride.set(result.picture.imageUrl);
                        this.notificationService.success('Файл заменён');
                    } else Eif (result.pending) {
                        this.refreshPending();
                        this.notificationService.info('Изменение отправлено на модерацию');
                    }
                    this.logger.info('File replacement submitted', { id: pic.id });
                },
                error: (err: unknown) => {
                    this.logger.error('Failed to replace file', err);
                    this.notificationService.error('Не удалось заменить файл');
                },
            });
    }
 
    deletePicture(): void {
        const pic = this.picture();
        Iif (!pic || !this.canDelete()) return;
 
        this.confirmationService
            .open({
                title: 'Удаление иллюстрации',
                message: 'Вы уверены, что хотите удалить эту иллюстрацию?',
                buttons: [
                    { key: 'cancel', label: 'Отмена' },
                    { key: 'confirm', label: 'Удалить', accent: 'danger' },
                ],
                disableClose: true,
            })
            .pipe(
                filter(result => result === 'confirm'),
                tap(() => this._isDeleting.set(true)),
                switchMap(() =>
                    this.pictureService.deletePicture(pic.id).pipe(finalize(() => this._isDeleting.set(false))),
                ),
                takeUntilDestroyed(this.destroyRef),
            )
            .subscribe({
                next: editResult => {
                    if (editResult.picture) {
                        this.notificationService.success('Иллюстрация удалена');
                        this.router.navigate(['/pictures']);
                    } else Eif (editResult.pending) {
                        this.refreshPending();
                        this.notificationService.info('Запрос на удаление отправлен на модерацию');
                    }
                    this.logger.info('Delete submitted', { id: pic.id });
                },
                error: (err: unknown) => {
                    if (err instanceof HttpErrorResponse && err.status === 409) {
                        this.notificationService.error('Иллюстрация используется в статьях и не может быть удалена');
                    } else {
                        this.notificationService.error('Не удалось удалить иллюстрацию');
                    }
                    this.logger.error('Failed to delete picture', err);
                },
            });
    }
 
    openPendingImage(pending: PicturePending): void {
        const picture = this.picture();
        Iif (!picture || !pending.pendingImageUrl) return;
 
        const lightboxPicture: Picture = {
            ...picture,
            id: pending.pictureId,
            title: pending.title ?? pending.currentTitle,
            user: pending.user,
            date: pending.date,
            width: pending.width ?? pending.currentWidth,
            height: pending.height ?? pending.currentHeight,
            imageUrl: pending.pendingImageUrl,
            thumbnailUrl: pending.pendingImageUrl,
        };
 
        this.lightboxService.openWithPicture(lightboxPicture);
    }
 
    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}`);
            });
    }
 
    private refreshPending(): void {
        this._refreshPendingSubject.next();
    }
 
    private reloadCurrentPage(): void {
        const currentUrl = this.router.url;
        this.router
            .navigateByUrl('/', { skipLocationChange: true })
            .then(success => {
                Eif (success) {
                    return this.router.navigateByUrl(currentUrl);
                }
                this.logger.error('Page reload: intermediate navigation was cancelled');
                return false;
            })
            .catch((error: unknown) => {
                this.logger.error('Page reload failed', error);
            });
    }
 
    runPendingAction(pending: PicturePending, pendingAction: PendingAction): void {
        Iif (this._pendingActionInProgress() === pending.id) return;
 
        let request$: Observable<void>;
        let successMessage: string;
        let errorMessage: string;
        let logMessage: string;
 
        switch (pendingAction) {
            case 'cancel':
                request$ = this.pictureService.cancelPending(pending.id);
                successMessage = 'Изменение отменено';
                errorMessage = 'Не удалось отменить изменение';
                logMessage = 'Pending cancellation submitted';
                break;
            case 'approve':
                request$ = this.pictureService.approvePending(pending.id);
                successMessage = 'Изменение одобрено';
                errorMessage = 'Не удалось одобрить изменение';
                logMessage = 'Pending approval submitted';
                break;
            case 'reject':
                request$ = this.pictureService.rejectPending(pending.id);
                successMessage = 'Изменение отклонено';
                errorMessage = 'Не удалось отклонить изменение';
                logMessage = 'Pending rejection submitted';
                break;
        }
 
        this._pendingActionInProgress.set(pending.id);
        request$
            .pipe(
                takeUntilDestroyed(this.destroyRef),
                finalize(() => this._pendingActionInProgress.set(undefined)),
            )
            .subscribe({
                next: () => {
                    this.notificationService.success(successMessage);
                    this.logger.info(logMessage, { pendingId: pending.id, pictureId: pending.pictureId });
                    Iif (pendingAction === 'approve' && pending.pendingType === 'delete') {
                        this.router.navigate(['/pictures']);
                        return;
                    }
                    this.reloadCurrentPage();
                },
                error: (error: unknown) => {
                    if (error instanceof HttpErrorResponse && error.status === 404) {
                        const notFoundMessage =
                            pendingAction === 'cancel'
                                ? 'Решение по этому предложению уже принято'
                                : 'Решение по этому предложению уже принято, либо пользователь отменил предложение';
                        this.notificationService.info(notFoundMessage);
                        if (pendingAction === 'approve' && pending.pendingType === 'delete') {
                            this.router.navigate(['/pictures']);
                        } else {
                            this.reloadCurrentPage();
                        }
                        this.logger.info('Pending action returned 404', {
                            pendingId: pending.id,
                            action: pendingAction,
                        });
                        return;
                    }
                    this.notificationService.error(errorMessage);
                    this.logger.error(logMessage, error);
                },
            });
    }
}