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";
13 import { loadFavoritesTree} from "store/side-panel-tree/side-panel-tree-actions";
15 export const favoritesActions = unionize({
16 TOGGLE_FAVORITE: ofType<{ resourceUuid: string }>(),
17 CHECK_PRESENCE_IN_FAVORITES: ofType<string[]>(),
18 UPDATE_FAVORITES: ofType<Record<string, boolean>>()
21 export type FavoritesAction = UnionOf<typeof favoritesActions>;
23 export const toggleFavorite = (resource: { uuid: string; name: string }) =>
24 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
25 const userUuid = getUserUuid(getState());
27 return Promise.reject("No user");
29 dispatch(progressIndicatorActions.START_WORKING("toggleFavorite"));
30 dispatch(favoritesActions.TOGGLE_FAVORITE({ resourceUuid: resource.uuid }));
31 const isFavorite = checkFavorite(resource.uuid, getState().favorites);
32 dispatch(snackbarActions.OPEN_SNACKBAR({
34 ? "Removing from favorites..."
35 : "Adding to favorites...",
36 kind: SnackbarKind.INFO
39 const promise: any = isFavorite
40 ? services.favoriteService.delete({ userUuid, resourceUuid: resource.uuid })
41 : services.favoriteService.create({ userUuid, resource });
45 dispatch(favoritesActions.UPDATE_FAVORITES({ [resource.uuid]: !isFavorite }));
46 dispatch(snackbarActions.CLOSE_SNACKBAR());
47 dispatch(snackbarActions.OPEN_SNACKBAR({
49 ? "Removed from favorites"
50 : "Added to favorites",
52 kind: SnackbarKind.SUCCESS
54 dispatch(progressIndicatorActions.STOP_WORKING("toggleFavorite"));
55 dispatch<any>(loadFavoritesTree())
58 dispatch(progressIndicatorActions.STOP_WORKING("toggleFavorite"));
63 export const updateFavorites = (resourceUuids: string[]) =>
64 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
65 const userUuid = getUserUuid(getState());
66 if (!userUuid) { return; }
67 dispatch(favoritesActions.CHECK_PRESENCE_IN_FAVORITES(resourceUuids));
68 services.favoriteService
69 .checkPresenceInFavorites(userUuid, resourceUuids)
70 .then((results: any) => {
71 dispatch(favoritesActions.UPDATE_FAVORITES(results));