File size: 2,121 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { useTranslate } from 'i18n-calypso';
import PropTypes from 'prop-types';
import { useState } from 'react';
import useSafe from '../helpers/use-safe';
import { bumpStat } from '../rest-client/bump-stat';
import { wpcom } from '../rest-client/wpcom';
import Gridicon from './gridicons';

const followStatTypes = {
	comment: 'note_commented_post',
	comment_like: 'note_liked_comment',
	like: 'note_liked_post',
	follow: 'note_followed',
	reblog: 'note_reblog_post',
};

export const FollowLink = ( { site, noteType, isFollowing: initialIsFollowing } ) => {
	const translate = useTranslate();

	const [ isRequestRunning, setIsRequestRunning ] = useState( false );
	const [ isFollowing, setIsFollowing ] = useState( initialIsFollowing );

	const safeSetIsFollowing = useSafe( setIsFollowing );
	const safeSetIsRequestRunning = useSafe( setIsRequestRunning );

	function toggleFollowStatus() {
		if ( isRequestRunning ) {
			return;
		}

		const follower = wpcom().site( site ).follow();
		setIsRequestRunning( true );

		// optimistically update local state
		const previousState = isFollowing;
		setIsFollowing( ! isFollowing );

		const updateState = ( error, data ) => {
			safeSetIsRequestRunning( false );
			if ( error ) {
				safeSetIsFollowing( previousState );
				throw error;
			}
			safeSetIsFollowing( data.is_following );
		};

		if ( isFollowing ) {
			follower.del( updateState );
			bumpStat( 'notes-click-action', 'unfollow' );
		} else {
			follower.add( updateState );

			const stats = { 'notes-click-action': 'follow' };
			stats.follow_source = followStatTypes[ noteType ];
			bumpStat( stats );
		}
	}

	const icon = isFollowing ? 'reader-following' : 'reader-follow';
	const linkText = isFollowing
		? translate( 'Subscribed', { context: 'you are subscribing' } )
		: translate( 'Subscribe', { context: 'verb: imperative' } );

	return (
		<button className="follow-link" onClick={ toggleFollowStatus }>
			<Gridicon icon={ icon } size={ 18 } />
			{ linkText }
		</button>
	);
};

FollowLink.propTypes = {
	site: PropTypes.number,
	isFollowing: PropTypes.bool,
};

export default FollowLink;