1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { unionize, ofType, UnionOf } from "common/unionize";
6 import { Dispatch } from "redux";
7 import { RootState } from "../store";
8 import { getUserUuid } from "common/getuser";
9 import { checkFavorite } from "./favorites-reducer";
10 import { snackbarActions, SnackbarKind } from "../snackbar/snackbar-actions";
11 import { ServiceRepository } from "services/services";
12 import { progressIndicatorActions } from "store/progress-indicator/progress-indicator-actions";
14 export const favoritesActions = unionize({
15 TOGGLE_FAVORITE: ofType<{ resourceUuid: string }>(),
16 CHECK_PRESENCE_IN_FAVORITES: ofType<string[]>(),
17 UPDATE_FAVORITES: ofType<Record<string, boolean>>()
20 export type FavoritesAction = UnionOf<typeof favoritesActions>;
22 export const toggleFavorite = (resource: { uuid: string; name: string }) =>
23 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
24 const userUuid = getUserUuid(getState());
26 return Promise.reject("No user");
28 dispatch(progressIndicatorActions.START_WORKING("toggleFavorite"));
29 dispatch(favoritesActions.TOGGLE_FAVORITE({ resourceUuid: resource.uuid }));
30 const isFavorite = checkFavorite(resource.uuid, getState().favorites);
31 dispatch(snackbarActions.OPEN_SNACKBAR({
33 ? "Removing from favorites..."
34 : "Adding to favorites...",
35 kind: SnackbarKind.INFO
38 const promise: any = isFavorite
39 ? services.favoriteService.delete({ userUuid, resourceUuid: resource.uuid })
40 : services.favoriteService.create({ userUuid, resource });
44 dispatch(favoritesActions.UPDATE_FAVORITES({ [resource.uuid]: !isFavorite }));
45 dispatch(snackbarActions.CLOSE_SNACKBAR());
46 dispatch(snackbarActions.OPEN_SNACKBAR({
48 ? "Removed from favorites"
49 : "Added to favorites",
51 kind: SnackbarKind.SUCCESS
53 dispatch(progressIndicatorActions.STOP_WORKING("toggleFavorite"));
56 dispatch(progressIndicatorActions.STOP_WORKING("toggleFavorite"));
61 export const updateFavorites = (resourceUuids: string[]) =>
62 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
63 const userUuid = getUserUuid(getState());
64 if (!userUuid) { return; }
65 dispatch(favoritesActions.CHECK_PRESENCE_IN_FAVORITES(resourceUuids));
66 services.favoriteService
67 .checkPresenceInFavorites(userUuid, resourceUuids)
68 .then((results: any) => {
69 dispatch(favoritesActions.UPDATE_FAVORITES(results));