All files / app/layout/header header.component.ts

93% Statements 93/100
87.5% Branches 63/72
76.47% Functions 13/17
98.88% Lines 89/90

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 1723x 3x 3x 3x 3x 3x 3x 3x                       3x 3x 3x 3x                               3x 59x 59x 59x 59x 59x 59x 59x 59x 59x   59x   59x 59x 59x 59x   59x   59x 59x 62x 62x     59x 59x     59x 90x 90x 19x 19x         59x 63x 63x 63x 63x 1x 1x             1x                   21x 20x 20x   19x 19x   19x 19x 19x 19x       8x 8x 8x       11x 11x       4x 4x       15x 14x 14x 14x 6x 6x   8x 1x 1x     7x 7x 7x         3x 3x 3x 3x 3x 3x     3x 3x 3x 1x 2x 1x   1x   3x          
import { AccountDropdownComponent } from './account-dropdown/account-dropdown.component';
import { FontScaleControlComponent } from './font-scale-control/font-scale-control.component';
import { ThemeToggleComponent } from './theme-toggle/theme-toggle.component';
import { ARTICLE_TITLE_MAX_LENGTH, ArticleService } from '../../services/articles';
import { AuthService } from '../../services/auth/auth.service';
import { PageTitleStrategy } from '../../services/page-title.strategy';
import { HttpErrorResponse } from '@angular/common/http';
import {
    ChangeDetectionStrategy,
    Component,
    DestroyRef,
    ElementRef,
    computed,
    effect,
    inject,
    signal,
    untracked,
    viewChild,
} from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { DrawerService, LoggerService, NotificationService, WINDOW } from '@drevo-web/core';
import { IconButtonComponent, LineClampComponent, ModalService } from '@drevo-web/ui';
 
@Component({
    selector: 'app-header',
    imports: [
        AccountDropdownComponent,
        FontScaleControlComponent,
        LineClampComponent,
        ReactiveFormsModule,
        ThemeToggleComponent,
        IconButtonComponent,
    ],
    templateUrl: './header.component.html',
    styleUrl: './header.component.scss',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HeaderComponent {
    private readonly modalService = inject(ModalService);
    private readonly drawerService = inject(DrawerService);
    private readonly pageTitleStrategy = inject(PageTitleStrategy);
    private readonly destroyRef = inject(DestroyRef);
    private readonly window = inject(WINDOW);
    private readonly logger = inject(LoggerService).withContext('HeaderComponent');
    private readonly authService = inject(AuthService);
    private readonly articleService = inject(ArticleService);
    private readonly notificationService = inject(NotificationService);
 
    readonly pageTitle = this.pageTitleStrategy.pageTitle;
 
    private readonly _isEditingTitle = signal(false);
    private readonly _isSavingTitle = signal(false);
    private readonly _editingArticleId = signal<number | undefined>(undefined);
    readonly isEditingTitle = this._isEditingTitle.asReadonly();
 
    private readonly titleInputRef = viewChild<ElementRef<HTMLInputElement>>('titleInput');
 
    private readonly user = toSignal(this.authService.user$);
    readonly canRename = computed(() => {
        const ctx = this.pageTitleStrategy.titleContext();
        return !!ctx && (this.user()?.permissions.canModerate ?? false);
    });
 
    readonly titleControl = new FormControl('', { nonNullable: true });
    readonly titleMaxLength = ARTICLE_TITLE_MAX_LENGTH;
 
    constructor() {
        effect(() => {
            const el = this.titleInputRef()?.nativeElement;
            if (el) {
                el.focus();
                el.select();
            }
        });
 
        // Cancel in-progress edit when the user navigates to a different article.
        effect(() => {
            const currentArticleId = this.pageTitleStrategy.titleContext()?.articleId;
            untracked(() => {
                const editingId = this._editingArticleId();
                if (editingId !== undefined && editingId !== currentArticleId && !this._isSavingTitle()) {
                    this._isEditingTitle.set(false);
                    this._editingArticleId.set(undefined);
                }
            });
        });
    }
 
    toggleDrawer(): void {
        this.drawerService.toggle();
    }
 
    openSearch(): void {
        this.modalService.open(() => import('../../features/search/search.component').then(m => m.SearchComponent), {
            width: '600px',
        });
    }
 
    onTitleClick(): void {
        if (!this.canRename()) return;
        const selection = this.window?.getSelection();
        if (selection && !selection.isCollapsed) return;
 
        const ctx = this.pageTitleStrategy.titleContext();
        Iif (!ctx) return;
 
        this.titleControl.setValue(this.pageTitle());
        this._editingArticleId.set(ctx.articleId);
        this._isEditingTitle.set(true);
        this.logger.info('Title edit started', { articleId: ctx.articleId });
    }
 
    cancelTitleEdit(): void {
        Iif (this._isSavingTitle()) return;
        this._isEditingTitle.set(false);
        this._editingArticleId.set(undefined);
    }
 
    onTitleEnter(event: Event): void {
        event.preventDefault();
        this.saveTitleEdit();
    }
 
    onTitleBlur(): void {
        Iif (this._isSavingTitle()) return;
        this.saveTitleEdit();
    }
 
    saveTitleEdit(): void {
        if (!this._isEditingTitle() || this._isSavingTitle()) return;
        const value = this.titleControl.value.trim();
        const ctx = this.pageTitleStrategy.titleContext();
        if (!ctx || !value || value === ctx.title.trim()) {
            this.cancelTitleEdit();
            return;
        }
        if (value.length > ARTICLE_TITLE_MAX_LENGTH) {
            this.notificationService.error(`Название не может быть длиннее ${ARTICLE_TITLE_MAX_LENGTH} символов`);
            return;
        }
 
        this._isSavingTitle.set(true);
        this.titleControl.disable();
        this.articleService
            .renameArticle(ctx.articleId, value)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
                next: result => {
                    this._isSavingTitle.set(false);
                    this._isEditingTitle.set(false);
                    this._editingArticleId.set(undefined);
                    this.titleControl.enable();
                    this.pageTitleStrategy.updateArticleTitle(result.title);
                    this.notificationService.success('Статья переименована');
                },
                error: (err: unknown) => {
                    this._isSavingTitle.set(false);
                    this.titleControl.enable();
                    if (err instanceof HttpErrorResponse && err.error?.errorCode === 'TITLE_ALREADY_EXISTS') {
                        this.notificationService.error('Статья с таким названием уже существует');
                    } else if (err instanceof HttpErrorResponse && err.error?.errorCode === 'VALIDATION_ERROR') {
                        this.notificationService.error(err.error.error ?? 'Не удалось переименовать статью');
                    } else {
                        this.notificationService.error('Не удалось переименовать статью');
                    }
                    this.logger.error('Rename failed', err);
                },
            });
    }
}