forked from lichess-org/lichobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RelatedCtrl.ts
76 lines (63 loc) · 2.11 KB
/
RelatedCtrl.ts
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
import redraw from '../../../utils/redraw'
import * as xhr from '../userXhr'
import { handleXhrError } from '../../../utils'
import socket from '../../../socket'
import { Related } from '../../../lichess/interfaces/user'
import { Paginator } from '../../../lichess/interfaces'
import challengeForm from '../../challengeForm'
export default class RelatedCtrl {
currentTab: number
isLoadingNextPage = false
followers?: readonly Related[]
followersPaginator?: Paginator<Related>
following?: readonly Related[]
followingPaginator?: Paginator<Related>
constructor(readonly userId: string, readonly defaultTab?: number) {
this.currentTab = defaultTab || 0
socket.createDefault()
this.getData(this.userId, 1)
.then(redraw)
.catch(handleXhrError)
}
public loadNextPage = (page: number) => {
this.isLoadingNextPage = true
this.getData(this.userId, page)
.then(() => {
this.isLoadingNextPage = false
redraw()
})
.catch(handleXhrError)
redraw()
}
public toggleFollowing = (obj: Related) => {
if (obj.relation) xhr.unfollow(obj.user).then(d => this.setNewUserState(obj, d))
else xhr.follow(obj.user).then(d => this.setNewUserState(obj, d))
}
public challenge = (id: string) => {
challengeForm.open(id)
}
public onTabChange = (tabIndex: number) => {
const loc = window.location.search.replace(/\?tab=\w+$/, '')
try {
window.history.replaceState(window.history.state, '', loc + '?tab=' + tabIndex)
} catch (e) { console.error(e) }
this.currentTab = tabIndex
if ((this.currentTab === 0 && !this.followers) ||
(this.currentTab === 1 && !this.following)) {
this.getData(this.userId, 1)
.then(redraw)
}
redraw()
}
private getData(userId: string, page: number): Promise<void> {
return xhr.following(userId, page)
.then(d => {
this.following = (this.following || []).concat(d.paginator.currentPageResults)
this.followingPaginator = d.paginator
})
}
private setNewUserState(obj: Related, newData: xhr.RelationActionResult) {
obj.relation = newData.following
redraw()
}
}