-
-
Notifications
You must be signed in to change notification settings - Fork 209
/
UserPins.tsx
415 lines (372 loc) · 11.9 KB
/
UserPins.tsx
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/* eslint-disable jsx-a11y/anchor-is-valid */
import * as ReactDOM from "react-dom";
import * as React from "react";
import { get } from "lodash";
import { Integrations } from "@sentry/tracing";
import * as Sentry from "@sentry/react";
import ErrorBoundary from "../utils/ErrorBoundary";
import GlobalAppContext, { GlobalAppContextT } from "../utils/GlobalAppContext";
import {
WithAlertNotificationsInjectedProps,
withAlertNotifications,
} from "../notifications/AlertNotificationsHOC";
import APIServiceClass from "../utils/APIService";
import BrainzPlayer from "../brainzplayer/BrainzPlayer";
import Loader from "../components/Loader";
import PinnedRecordingCard from "./PinnedRecordingCard";
import { getPageProps, getListenablePin } from "../utils/utils";
export type UserPinsProps = {
user: ListenBrainzUser;
pins: PinnedRecording[];
totalCount: number;
profileUrl?: string;
} & WithAlertNotificationsInjectedProps;
export type UserPinsState = {
pins: PinnedRecording[];
page: number;
maxPage: number;
loading: boolean;
recordingFeedbackMap: RecordingFeedbackMap;
};
export default class UserPins extends React.Component<
UserPinsProps,
UserPinsState
> {
static contextType = GlobalAppContext;
declare context: React.ContextType<typeof GlobalAppContext>;
private DEFAULT_PINS_PER_PAGE = 25;
constructor(props: UserPinsProps) {
super(props);
const { totalCount } = this.props;
this.state = {
maxPage: Math.ceil(totalCount / this.DEFAULT_PINS_PER_PAGE),
page: 1,
pins: props.pins || [],
loading: false,
recordingFeedbackMap: {},
};
}
async componentDidMount(): Promise<void> {
const { currentUser } = this.context;
// Listen to browser previous/next events and load page accordingly
window.addEventListener("popstate", this.handleURLChange);
this.handleURLChange();
this.loadFeedback();
}
componentWillUnmount() {
window.removeEventListener("popstate", this.handleURLChange);
}
// pagination functions
handleURLChange = async (): Promise<void> => {
const { page, maxPage } = this.state;
const url = new URL(window.location.href);
if (url.searchParams.get("page")) {
let newPage = Number(url.searchParams.get("page"));
if (newPage === page) {
// page didn't change
return;
}
newPage = Math.max(newPage, 1);
newPage = Math.min(newPage, maxPage);
await this.getPinsFromAPI(newPage, false);
} else if (page !== 1) {
// occurs on back + forward history
await this.getPinsFromAPI(1, false);
}
};
handleClickOlder = async (event?: React.MouseEvent) => {
const { page, maxPage } = this.state;
if (event) {
event.preventDefault();
}
if (page >= maxPage) {
return;
}
await this.getPinsFromAPI(page + 1);
};
handleClickNewer = async (event?: React.MouseEvent) => {
const { page } = this.state;
if (event) {
event.preventDefault();
}
if (page === 1) {
return;
}
await this.getPinsFromAPI(page - 1);
};
getPinsFromAPI = async (page: number, pushHistory: boolean = true) => {
const { newAlert, user } = this.props;
const { APIService } = this.context;
this.setState({ loading: true });
try {
const limit = (page - 1) * this.DEFAULT_PINS_PER_PAGE;
const count = this.DEFAULT_PINS_PER_PAGE;
const newPins = await APIService.getPinsForUser(user.name, limit, count);
if (!newPins.pinned_recordings.length) {
// No pins were fetched
this.setState({ loading: false });
return;
}
const totalCount = parseInt(newPins.total_count, 10);
this.setState(
{
loading: false,
page,
maxPage: Math.ceil(totalCount / this.DEFAULT_PINS_PER_PAGE),
pins: newPins.pinned_recordings,
},
this.loadFeedback
);
if (pushHistory) {
window.history.pushState(null, "", `?page=${[page]}`);
}
// Scroll window back to the top of the events container element
const eventContainerElement = document.querySelector(
"#pinned-recordings"
);
if (eventContainerElement) {
eventContainerElement.scrollIntoView({ behavior: "smooth" });
}
} catch (error) {
newAlert(
"warning",
"Could not load pin history",
<>
Something went wrong when we tried to load your pinned recordings,
please try again or contact us if the problem persists.
<br />
<strong>
{error.name}: {error.message}
</strong>
</>
);
this.setState({ loading: false });
}
};
getFeedback = async () => {
const { pins, newAlert } = this.props;
const { APIService, currentUser } = this.context;
let recordings = "";
if (pins && currentUser?.name) {
pins.forEach((pin) => {
const recordingMsid = pin.recording_msid;
if (recordingMsid) {
recordings += `${recordingMsid},`;
}
});
try {
const data = await APIService.getFeedbackForUserForRecordings(
currentUser.name,
recordings
);
return data.feedback;
} catch (error) {
if (newAlert) {
newAlert(
"danger",
"We could not load love/hate feedback",
typeof error === "object" ? error.message : error
);
}
}
}
return [];
};
loadFeedback = async () => {
const feedback = await this.getFeedback();
if (!feedback) {
return;
}
const recordingFeedbackMap: RecordingFeedbackMap = {};
feedback.forEach((fb: FeedbackResponse) => {
recordingFeedbackMap[fb.recording_msid] = fb.score;
});
this.setState({ recordingFeedbackMap });
};
updateFeedback = (
recordingMsid: string,
score: ListenFeedBack | RecommendationFeedBack
) => {
const { recordingFeedbackMap } = this.state;
const newFeedbackMap = {
...recordingFeedbackMap,
[recordingMsid]: score as ListenFeedBack,
};
this.setState({ recordingFeedbackMap: newFeedbackMap });
};
getFeedbackForRecordingMsid = (
recordingMsid?: string | null
): ListenFeedBack => {
const { recordingFeedbackMap } = this.state;
return recordingMsid ? get(recordingFeedbackMap, recordingMsid, 0) : 0;
};
// BrainzPlayer functions
removePinFromPinsList = (pin: PinnedRecording) => {
const { pins } = this.state;
const index = pins.indexOf(pin);
pins.splice(index, 1);
this.setState({ pins });
};
render() {
const { user, profileUrl, newAlert } = this.props;
const { pins, page, loading, maxPage } = this.state;
const { currentUser, APIService } = this.context;
const isNewerButtonDisabled = page === 1;
const isOlderButtonDisabled = page >= maxPage;
const pinsAsListens = pins.map((pin) => {
return getListenablePin(pin);
});
return (
<div role="main">
<div className="row">
<div className="col-md-8 col-md-offset-2">
<h3>Pinned Recordings</h3>
{pins.length === 0 && (
<>
<div className="lead text-center">No pins yet</div>
{user.name === currentUser.name && (
<>
Pin one of your
<a href={`${profileUrl}`}> recent Listens!</a>
</>
)}
</>
)}
{pins.length > 0 && (
<div>
<div
style={{
height: 0,
position: "sticky",
top: "50%",
zIndex: 1,
}}
>
<Loader isLoading={loading} />
</div>
<div
id="pinned-recordings"
style={{ opacity: loading ? "0.4" : "1" }}
>
{pins?.map((pin) => {
return (
<PinnedRecordingCard
key={pin.created}
userName={user.name}
pinnedRecording={pin}
isCurrentUser={currentUser?.name === user?.name}
removePinFromPinsList={this.removePinFromPinsList}
newAlert={newAlert}
currentFeedback={this.getFeedbackForRecordingMsid(
pin.recording_msid
)}
updateFeedbackCallback={this.updateFeedback}
/>
);
})}
{pins.length < this.DEFAULT_PINS_PER_PAGE && (
<h5 className="text-center">No more pins to show.</h5>
)}
</div>
<ul
className="pager"
id="navigation"
style={{ marginRight: "-1em", marginLeft: "1.5em" }}
>
<li
className={`previous ${
isNewerButtonDisabled ? "disabled" : ""
}`}
>
<a
role="button"
onClick={this.handleClickNewer}
onKeyDown={(e) => {
if (e.key === "Enter") this.handleClickNewer();
}}
tabIndex={0}
href={
isNewerButtonDisabled ? undefined : `?page=${page - 1}`
}
>
← Newer
</a>
</li>
<li
className={`next ${
isOlderButtonDisabled ? "disabled" : ""
}`}
style={{ marginLeft: "auto" }}
>
<a
role="button"
onClick={this.handleClickOlder}
onKeyDown={(e) => {
if (e.key === "Enter") this.handleClickOlder();
}}
tabIndex={0}
href={
isOlderButtonDisabled ? undefined : `?page=${page + 1}`
}
>
Older →
</a>
</li>
</ul>
</div>
)}
</div>
</div>
<BrainzPlayer
listens={pinsAsListens}
newAlert={newAlert}
listenBrainzAPIBaseURI={APIService.APIBaseURI}
refreshSpotifyToken={APIService.refreshSpotifyToken}
refreshYoutubeToken={APIService.refreshYoutubeToken}
/>
</div>
);
}
}
document.addEventListener("DOMContentLoaded", () => {
const { domContainer, reactProps, globalReactProps } = getPageProps();
const {
api_url,
current_user,
spotify,
youtube,
sentry_dsn,
sentry_traces_sample_rate,
} = globalReactProps;
const { user, pins, total_count, profile_url } = reactProps;
const apiService = new APIServiceClass(
api_url || `${window.location.origin}/1`
);
if (sentry_dsn) {
Sentry.init({
dsn: sentry_dsn,
integrations: [new Integrations.BrowserTracing()],
tracesSampleRate: sentry_traces_sample_rate,
});
}
const UserPinsWithAlertNotifications = withAlertNotifications(UserPins);
const globalProps: GlobalAppContextT = {
APIService: apiService,
currentUser: current_user,
spotifyAuth: spotify,
youtubeAuth: youtube,
};
ReactDOM.render(
<ErrorBoundary>
<GlobalAppContext.Provider value={globalProps}>
<UserPinsWithAlertNotifications
user={user}
pins={pins}
totalCount={total_count}
profileUrl={profile_url}
/>
</GlobalAppContext.Provider>
</ErrorBoundary>,
domContainer
);
});