common-ui/src/lib/users/components/initials-avatar/initials-avatar.component.ts
2024-12-10 17:02:25 +02:00

58 lines
3.0 KiB
TypeScript

import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatTooltip } from '@angular/material/tooltip';
import { TranslateService } from '@ngx-translate/core';
import { IqserUser } from '../../iqser-user.model';
import { NamePipe } from '../../name.pipe';
import { IqserUserService } from '../../services/iqser-user.service';
import { NamePipeOptions } from '../../types/name-pipe-options';
import { IIqserUser } from '../../types/user.response';
@Component({
selector: 'iqser-initials-avatar',
templateUrl: './initials-avatar.component.html',
styleUrls: ['./initials-avatar.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NamePipe, MatTooltip],
})
export class InitialsAvatarComponent<
Interface extends IIqserUser = IIqserUser,
Class extends IqserUser & Interface = IqserUser & Interface,
> {
readonly #userService = inject<IqserUserService<Interface, Class>>(IqserUserService);
readonly #translateService = inject(TranslateService);
readonly #users = toSignal(this.#userService.all$);
readonly color = input('lightgray');
readonly size = input<'small' | 'large' | 'extra-small'>('small');
readonly withName = input(false);
readonly showYou = input(false);
readonly tooltipPosition = input<'below' | 'above'>('above');
readonly defaultValue = input<string>(this.#translateService.instant('initials-avatar.unassigned'));
readonly showTooltip = input(true);
readonly user = input.required<Class | string>();
readonly showBorderCondition = input<<T extends Class = Class>(user: T) => boolean>(user => user.isSpecial);
readonly _user = computed(() => {
const user = this.user();
if (typeof user === 'string') {
if (user?.toLowerCase() === 'system') return this.#userService.newSystemUser();
if (!user) return undefined;
return this.#users()?.find(u => u.id === user) ?? this.#userService.newDeletedUser();
}
return user;
});
readonly #isSystemUser = computed(() => this._user()?.id?.toLowerCase() === 'system');
readonly isCurrentUser = computed(() => this.#userService.currentUser?.id === this._user()?.id);
readonly hasBorder = computed(() => !!this._user() && !this.isCurrentUser() && this.showBorderCondition()(this._user()!));
readonly disabled = computed(() => !!this._user() && !this.#isSystemUser() && !this._user()?.hasAnyRole);
readonly colorClass = computed(() => {
if (this.isCurrentUser()) return 'primary-white';
if (this.disabled()) return 'inactive';
if (this.color().includes('-')) return this.color();
if (this.#isSystemUser()) return 'primary-white primary';
return `${this.color()}-dark`;
});
readonly namePipeOptions = computed<NamePipeOptions>(
() => ({ showYou: this.showYou(), defaultValue: this.defaultValue() }) as NamePipeOptions,
);
}