feat: added user search to various components

This commit is contained in:
2025-06-01 17:44:48 +02:00
parent 94702834b4
commit ca6037d405
9 changed files with 171 additions and 80 deletions

View File

@@ -8,7 +8,7 @@
</mat-chip-listbox> </mat-chip-listbox>
<button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button> <button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button>
</div> </div>
<mat-spinner *ngIf="loading"></mat-spinner> <mat-spinner *ngIf="loading" color="accent"></mat-spinner>
<table mat-table [dataSource]="keys"> <table mat-table [dataSource]="keys">
<div matColumnDef="room"> <div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef>Sala</th> <th mat-header-cell *matHeaderCellDef>Sala</th>

View File

@@ -1,6 +1,6 @@
<mat-dialog-content> <mat-dialog-content>
<form (ngSubmit)="send()" [formGroup]="form"> <form (ngSubmit)="send()" [formGroup]="form">
<mat-form-field> <mat-form-field color="accent">
<mat-label>Sala</mat-label> <mat-label>Sala</mat-label>
<mat-select formControlName="room" required> <mat-select formControlName="room" required>
@for (item of rooms; track $index) { @for (item of rooms; track $index) {
@@ -9,17 +9,9 @@
</mat-select> </mat-select>
<mat-error *ngIf="form.controls['room'].hasError('required')">Wymagane</mat-error> <mat-error *ngIf="form.controls['room'].hasError('required')">Wymagane</mat-error>
</mat-form-field> </mat-form-field>
<mat-form-field> <mat-form-field color="accent">
<mat-label>Wypożyczający</mat-label> <mat-label>Wypożyczający</mat-label>
<!-- TODO: Add user selector --> <app-user-search formControlName="user" required/>
<input matInput placeholder="Nazwa użytkownika" formControlName="user" required>
<!-- <input #input matInput placeholder="Nazwa użytkownika" formControlName="user" required [matAutocomplete]="auto" (input)="filter()">
<mat-autocomplete requireSelection #auto="matAutocomplete">
@for (item of unames; track item) {
<mat-option [value]="item">{{item}}</mat-option>
}
</mat-autocomplete> -->
<mat-error *ngIf="form.controls['user'].hasError('unf')">Zła nazwa użytkownika</mat-error>
<mat-error *ngIf="form.controls['user'].hasError('required')">Wymagane</mat-error> <mat-error *ngIf="form.controls['user'].hasError('required')">Wymagane</mat-error>
</mat-form-field> </mat-form-field>
<button mat-button>Wyślij</button> <button mat-button>Wyślij</button>

View File

@@ -1,8 +1,8 @@
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { AdminCommService } from '../../admin-comm.service'; import { AdminCommService } from '../../admin-comm.service';
import { MatDialogRef } from '@angular/material/dialog'; import { MatDialogRef } from '@angular/material/dialog';
import { FormControl, FormGroup } from '@angular/forms'; import { FormControl, FormGroup } from '@angular/forms';
import { startWith } from 'rxjs'; import { UserSearchResult } from 'src/app/commonComponents/user-search/user-search.component';
@Component({ @Component({
selector: 'app-new-key', selector: 'app-new-key',
@@ -10,11 +10,10 @@ import { startWith } from 'rxjs';
styleUrl: './new-key.component.scss' styleUrl: './new-key.component.scss'
}) })
export class NewKeyComponent implements OnInit { export class NewKeyComponent implements OnInit {
// @ViewChild('input') input!: ElementRef<HTMLInputElement>
rooms: string[] = [] rooms: string[] = []
form = new FormGroup({ form = new FormGroup({
room: new FormControl<string>(""), room: new FormControl<string>(""),
user: new FormControl<string>("") user: new FormControl<UserSearchResult | null>(null)
}) })
unames: any[] = [] unames: any[] = []
constructor ( private ac: AdminCommService, public dialogRef: MatDialogRef<NewKeyComponent> ) {} constructor ( private ac: AdminCommService, public dialogRef: MatDialogRef<NewKeyComponent> ) {}
@@ -24,26 +23,11 @@ export class NewKeyComponent implements OnInit {
this.rooms = v this.rooms = v
}) })
} }
// filter() {
// const v = this.input.nativeElement.value
// console.log(v);
// if (v) {
// this.ac.userFilter(v.toLowerCase()).subscribe((v) => {
// this.unames = v
// })
// } else {
// this.unames = []
// }
// }
send() { send() {
if (this.form.valid) { if (this.form.valid) {
this.dialogRef.close(this.form.value) this.dialogRef.close(this.form.value)
} else { }
this.form.controls['user'].setErrors({unf: true})
}
} }
} }

View File

@@ -1,10 +1,10 @@
<form [formGroup]="form" (ngSubmit)="submit()"> <form [formGroup]="form" (ngSubmit)="submit()">
<div formGroupName="recp"> <div formGroupName="recp">
<mat-radio-group formControlName="type"> <mat-radio-group formControlName="type">
<mat-radio-button value="uname"> <mat-radio-button value="uid">
<mat-form-field> <mat-form-field>
<mat-label>Nazwa użytkownika</mat-label> <mat-label>Użytkownik</mat-label>
<input matInput type="text" formControlName="uname"> <app-user-search formControlName="uid" required/>
</mat-form-field> </mat-form-field>
</mat-radio-button> </mat-radio-button>
<mat-radio-button value="room"> <mat-radio-button value="room">

View File

@@ -6,6 +6,7 @@ import { Group } from 'src/app/types/group';
import { LocalStorageService } from 'src/app/services/local-storage.service'; import { LocalStorageService } from 'src/app/services/local-storage.service';
import { ToolbarService } from '../toolbar/toolbar.service'; import { ToolbarService } from '../toolbar/toolbar.service';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { UserSearchResult } from 'src/app/commonComponents/user-search/user-search.component';
@Component({ @Component({
selector: 'app-notifications', selector: 'app-notifications',
@@ -44,9 +45,9 @@ export class NotificationsComponent implements OnInit, OnDestroy {
success?: { sent: number; possible: number; }; success?: { sent: number; possible: number; };
form = new FormGroup<NotificationForm>({ form = new FormGroup({
recp: new FormGroup({ recp: new FormGroup({
uname: new FormControl<string>(''), uid: new FormControl<UserSearchResult | null>(null),
room: new FormControl<string|null>(null), room: new FormControl<string|null>(null),
group: new FormControl<string>(''), group: new FormControl<string>(''),
type: new FormControl<"room" | "uname" | "group">('uname', {nonNullable: true}) type: new FormControl<"room" | "uname" | "group">('uname', {nonNullable: true})
@@ -56,19 +57,8 @@ export class NotificationsComponent implements OnInit, OnDestroy {
}) })
submit() { submit() {
this.acs.notif.send(this.form.value as Notification).subscribe((data) => { this.acs.notif.send({...this.form.value, recp: {...this.form.get("recp")?.value, uid: this.form.controls['recp'].controls['uid'].value?._id}} as Notification).subscribe((data) => {
this.success = data this.success = data
}) })
} }
} }
interface NotificationForm {
body: FormControl<string>;
title: FormControl<string>;
recp: FormGroup<{
uname: FormControl<string | null>;
room: FormControl<string | null>;
group: FormControl<string | null>;
type: FormControl<"room" | "uname" | "group">;
}>
}

View File

@@ -1,16 +1,15 @@
<mat-form-field> <div role="group" class="app-user-search-container" (focusin)="onFocusIn($event)" (focusout)="onFocusOut($event)">
<mat-label *ngIf="label">{{label}}</mat-label> <input type="text" [matAutocomplete]="ac" [formControl]="control" #inputComponent class="input-element">
<input matInput type="text" [matAutocomplete]="ac" [formControl]="control" #inputComponent> <mat-spinner color="accent" diameter="16" *ngIf="loading" matSuffix></mat-spinner>
</mat-form-field> <mat-autocomplete #ac="matAutocomplete" autoActiveFirstOption (optionSelected)="saveValue($event)" [displayWith]="displayFn">
<mat-spinner color="accent" diameter="32" *ngIf="loading"></mat-spinner> @for (item of list; track $index) {
<mat-autocomplete #ac="matAutocomplete" autoActiveFirstOption (optionSelected)="saveValue($event)" [displayWith]="displayFn"> <mat-option [value]="item">
@for (item of list; track $index) { @if (item.fname) {
<mat-option [value]="item"> {{item.fname}} {{item.surname}} <span *ngIf="item.room" class="room">({{item.room}})</span>
@if (item.fname) { } @else {
{{item.fname}} {{item.surname}} <span *ngIf="item.room" class="room">({{item.room}})</span> {{item.uname}}
} @else { }
{{item.uname}} </mat-option>
} }
</mat-option> </mat-autocomplete>
} </div>
</mat-autocomplete>

View File

@@ -6,4 +6,13 @@
.room { .room {
color: gray; color: gray;
}
input {
border: none;
background: none;
padding: 0;
outline: 0;
font: inherit;
color: currentColor;
} }

View File

@@ -1,10 +1,12 @@
import { Component, EventEmitter, forwardRef, Input, Output, ViewChild } from '@angular/core'; import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Component, DoCheck, ElementRef, HostBinding, Input, OnDestroy, Optional, Self } from '@angular/core';
import { ControlValueAccessor, FormControl, FormGroupDirective, NgControl, NgForm } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatInput } from '@angular/material/input'; import { MatFormFieldControl } from '@angular/material/form-field';
import { Subject } from 'rxjs';
import { AdminCommService } from 'src/app/admin-view/admin-comm.service'; import { AdminCommService } from 'src/app/admin-view/admin-comm.service';
interface UserSearchResult { export interface UserSearchResult {
_id: string; _id: string;
fname: string; fname: string;
surname: string; surname: string;
@@ -18,26 +20,120 @@ interface UserSearchResult {
styleUrl: './user-search.component.scss', styleUrl: './user-search.component.scss',
providers: [ providers: [
{ {
provide: NG_VALUE_ACCESSOR, provide: MatFormFieldControl,
useExisting: forwardRef(() => UserSearchComponent), useExisting: UserSearchComponent
multi: true
} }
], ],
host: { host: {
'(blur)': '_onTouched()' '(blur)': '_onTouched()'
} }
}) })
export class UserSearchComponent implements ControlValueAccessor { export class UserSearchComponent implements ControlValueAccessor, MatFormFieldControl<UserSearchResult>, OnDestroy, DoCheck {
protected loading: boolean = false protected loading: boolean = false
@Input() label?: boolean
control: FormControl = new FormControl(); control: FormControl = new FormControl();
protected list: UserSearchResult[] = [] protected list: UserSearchResult[] = []
private timeout?: NodeJS.Timeout private timeout?: NodeJS.Timeout
private _onChange!: (_: UserSearchResult) => void private _onChange!: (_: UserSearchResult) => void
private _onTouched!: any private _onTouched!: any
constructor(readonly acu: AdminCommService) { static nextId = 0;
@Input()
public get value(): UserSearchResult | null {
return this.control.value;
}
public set value(value: UserSearchResult | null) {
this.control.setValue(value)
this.stateChanges.next()
}
touched = false
stateChanges = new Subject<void>();
@HostBinding() id: string = `app-user-search-${UserSearchComponent.nextId++}`;
private _placeholder: string = "";
@Input()
public get placeholder(): string {
return this._placeholder;
}
public set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next()
}
focused: boolean = false;
onFocusIn(event: FocusEvent) {
if (!this.focused) {
this.focused = true;
this.stateChanges.next();
}
}
onFocusOut(event: FocusEvent) {
if (!this._elementRef.nativeElement.contains(event.relatedTarget as Element)) {
this.touched = true
this.focused = false;
this._onTouched();
this.stateChanges.next();
}
}
get empty(): boolean {
return !this.control.value
}
@HostBinding('class.floating')
get shouldLabelFloat(): boolean {
return this.focused || !this.empty
}
private _required: boolean = false;
@Input()
public get required(): boolean {
return this._required;
}
public set required(value: BooleanInput) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next()
}
private _disabled: boolean = false;
@Input()
public get disabled(): boolean {
return this._disabled;
}
public set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
this._disabled ? this.control.disable() : this.control.enable()
this.stateChanges.next()
}
errorState: boolean = false
controlType?: string | undefined = "app-user-search";
autofilled?: boolean | undefined;
@Input('aria-describedby') userAriaDescribedBy?: string;
setDescribedByIds(ids: string[]): void {
const controlElement = this._elementRef.nativeElement.querySelector('.app-user-search-container')!;
controlElement.setAttribute('aria-describedby', ids.join(' '))
}
onContainerClick(event: MouseEvent): void {
if ((event.target as Element).tagName.toLowerCase() != 'input') {
this._elementRef.nativeElement.querySelector('input').focus()
}
}
constructor(
readonly acu: AdminCommService,
@Optional() @Self() public ngControl: NgControl,
@Optional() private _parentForm: NgForm,
@Optional() private _parentFormGroup: FormGroupDirective,
private _elementRef: ElementRef
) {
if (this.ngControl != null) {
(this.ngControl as NgControl).valueAccessor = this
}
this.control.valueChanges.subscribe(() => { this.control.valueChanges.subscribe(() => {
if (typeof this.control.value == "object") return;
this.loading = true this.loading = true
if (this.timeout) clearTimeout(this.timeout) if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => { this.timeout = setTimeout(() => {
@@ -48,9 +144,28 @@ export class UserSearchComponent implements ControlValueAccessor {
}, 500) }, 500)
}) })
} }
ngDoCheck(): void {
if (this.ngControl) {
this.updateErrorState()
}
}
private updateErrorState() {
const parent = this._parentFormGroup || this._parentForm
writeValue(obj: string): void { const oldState = this.errorState;
this.control.setValue(obj) const newState = (this.ngControl?.invalid || this.control.invalid) && (this.touched || parent.submitted);
if (oldState !== newState) {
this.errorState = newState
this.stateChanges.next()
}
}
ngOnDestroy(): void {
this.stateChanges.complete()
}
writeValue(obj: UserSearchResult): void {
this.value = obj
} }
registerOnChange(fn: (_: UserSearchResult) => void): void { registerOnChange(fn: (_: UserSearchResult) => void): void {
@@ -62,7 +177,7 @@ export class UserSearchComponent implements ControlValueAccessor {
} }
setDisabledState?(isDisabled: boolean): void { setDisabledState?(isDisabled: boolean): void {
isDisabled ? this.control.disable() : this.control.enable() this.disabled = isDisabled
} }
protected displayFn(u: UserSearchResult): string { protected displayFn(u: UserSearchResult): string {
@@ -71,6 +186,8 @@ export class UserSearchComponent implements ControlValueAccessor {
} }
protected saveValue(e: MatAutocompleteSelectedEvent) { protected saveValue(e: MatAutocompleteSelectedEvent) {
this._onChange(this.control.value) this.autofilled = true
this.value = e.option.value
this._onChange(this.value!)
} }
} }

View File

@@ -2,7 +2,7 @@ export interface Notification {
body: string; body: string;
title: string; title: string;
recp: { recp: {
uname: string | null; uid: string | null;
room: string | null; room: string | null;
type: "all" | "room" | "uname" type: "all" | "room" | "uname"
} }