Files
openstapps/frontend/app/src/app/modules/data/elements/favorite-button.component.ts
2024-05-27 15:07:27 +02:00

75 lines
2.2 KiB
TypeScript

/*
* Copyright (C) 2022 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {ChangeDetectionStrategy, Component, Input} from '@angular/core';
import {SCIndexableThings} from '@openstapps/core';
import {FavoritesService} from '../../favorites/favorites.service';
import {Observable} from 'rxjs';
import {map, take} from 'rxjs/operators';
/**
* The button to add or remove a thing from favorites
*/
@Component({
selector: 'stapps-favorite-button',
templateUrl: './favorite-button.component.html',
styleUrls: ['./favorite-button.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FavoriteButtonComponent {
/**
* Item getter
*/
get item(): SCIndexableThings {
return this._item;
}
/**
* An item to show (setter is used as there were issues assigning the distance to the right place in a list)
*/
@Input() set item(item: SCIndexableThings) {
this._item = item;
this.isFavorite$ = this.favoritesService.get(this.item.uid).pipe(
map(favorite => {
return favorite !== undefined;
}),
);
}
/**
* An item to show
*/
private _item: SCIndexableThings;
/**
* The thing already in favorites or not
*/
isFavorite$: Observable<boolean>;
constructor(private favoritesService: FavoritesService) {}
/**
* Add or remove the thing from favorites (depending on its current status)
* @param event A click event
*/
async toggle(event: Event) {
// prevent additional effects e.g. router to be activated
event.stopPropagation();
this.isFavorite$.pipe(take(1)).subscribe(enabled => {
enabled ? this.favoritesService.delete(this.item) : this.favoritesService.put(this.item);
});
}
}