FavoriteButton.tsx 1.78 KB
Newer Older
1
import * as React from 'react';
Andrew Hrdy's avatar
Andrew Hrdy committed
2
import * as classNames from 'classnames';
3
import { Tooltip } from '@material-ui/core';
4
5
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder';
import FavoriteIcon from '@material-ui/icons/Favorite';
Andrew Hrdy's avatar
Andrew Hrdy committed
6
7
import { trackPiwikEvent } from '../piwik/piwik';

8
9
10
11
12
13
interface FavoriteButtonProps {
    slug: string;
    initialState: boolean;
    addFavoriteFacility: (slug: string) => void;
    removeFavoriteFacility: (slug: string) => void;
}
14

15
16
export default ({slug, initialState, addFavoriteFacility, removeFavoriteFacility}: FavoriteButtonProps) => {
    const [isFavorite, setIsFavorite] = React.useState<boolean>(initialState);
17

18
    const handleClick = (event: React.MouseEvent) => {
19
        event.stopPropagation(); // Stops the card from being selected in the sidebar.
20
        event.preventDefault(); // Also stops the card from being selected in the sidebar.
21
22
23
24
25
26

        const newState = !isFavorite;

        setIsFavorite(newState);


27
        if (!newState) {
Andrew Hrdy's avatar
Andrew Hrdy committed
28
            trackPiwikEvent('card-action', 'un-favorite');
29

30
            setTimeout(() => {
31
                removeFavoriteFacility(slug);
32
33
            }, 0);
        } else {
Andrew Hrdy's avatar
Andrew Hrdy committed
34
            trackPiwikEvent('card-action', 'favorite');
35
36

            setTimeout(() => {
37
                addFavoriteFacility(slug);
38
39
            }, 0);
        }
40
    };
41

42
    if (isFavorite) {
43
        return (
44
45
46
            <Tooltip title="Remove Favorite">
                <FavoriteIcon onClick={handleClick}
                    className={classNames('favorite-button-heart', 'favorite-button-heart-favorited')} />
Matthew J Endries's avatar
Matthew J Endries committed
47
            </Tooltip>
48
49
50
        );
    }

51
52
53
54
55
56
57
    return (
        <Tooltip title="Add Favorite">
            <FavoriteBorderIcon onClick={handleClick}
                className={classNames('favorite-button-heart')} />
        </Tooltip>
    );
};