-
Notifications
You must be signed in to change notification settings - Fork 199
/
LobbyWidget.jsx
582 lines (542 loc) · 17 KB
/
LobbyWidget.jsx
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
import React, { useEffect } from 'react';
import { Modal } from 'react-bootstrap';
import _ from 'lodash';
import copy from 'copy-to-clipboard';
import moment from 'moment';
import { useDispatch, useSelector } from 'react-redux';
import Gon from 'gon';
import classnames from 'classnames';
import * as lobbyMiddlewares from '../middlewares/Lobby';
import gameStateCodes from '../config/gameStateCodes';
import { actions } from '../slices';
import * as selectors from '../selectors';
import Loading from '../components/Loading';
// import GamesHeatmap from '../components/GamesHeatmap';
// import Card from '../components/Card';
import UserInfo from './UserInfo';
import {
makeGameUrl,
getSignInGithubUrl,
getLobbyUrl,
} from '../utils/urlBuilders';
import i18n from '../../i18n';
// import StartGamePanel from '../components/StartGamePanel';
import CompletedGames from '../components/Game/CompletedGames';
import CreateGameDialog from '../components/Game/CreateGameDialog';
import Leaderboard from '../components/Leaderboard';
import Announcement from '../components/Announcement';
import GameLevelBadge from '../components/GameLevelBadge';
import LobbyChat from './LobbyChat';
import levelRatio from '../config/levelRatio';
import PlayerLoading from '../components/PlayerLoading';
import hashLinkNames from '../config/hashLinkNames';
import { fetchCompletedGames, loadNextPage } from '../slices/completedGames';
const isActiveGame = game => [gameStateCodes.playing, gameStateCodes.waitingOpponent].includes(game.state);
const Players = ({ players }) => {
if (players.length === 1) {
return (
<td className="p-3 align-middle text-nowrap" colSpan={2}>
<div className="d-flex align-items-center">
<UserInfo user={players[0]} />
</div>
</td>
);
}
const getPregressbarWidth = player => `${
(player.checkResult?.successCount / player.checkResult?.assertsCount)
* 100
}%`;
const getPregressbarClass = player => classnames('cb-check-result-bar', player.checkResult.status);
return (
<>
<td className="p-3 align-middle text-nowrap cb-username-td text-truncate">
<div className="d-flex flex-column position-relative">
<UserInfo
user={players[0]}
hideOnlineIndicator
loading={players[0].checkResult.status === 'started'}
/>
<div className={getPregressbarClass(players[0])}>
<div
className="cb-asserts-progress"
style={{ width: getPregressbarWidth(players[0]) }}
/>
</div>
<PlayerLoading
show={players[0].checkResult.status === 'started'}
small
/>
</div>
</td>
<td className="p-3 align-middle text-nowrap cb-username-td text-truncate">
<div className="d-flex flex-column position-relative">
<UserInfo
user={players[1]}
hideOnlineIndicator
loading={players[1].checkResult.status === 'started'}
/>
<div className={getPregressbarClass(players[1])}>
<div
className="cb-asserts-progress"
style={{ width: getPregressbarWidth(players[1]), right: 0 }}
/>
</div>
<PlayerLoading
show={players[1].checkResult.status === 'started'}
small
/>
</div>
</td>
</>
);
};
const isPlayer = (user, game) => !_.isEmpty(_.find(game.players, { id: user.id }));
const ShowButton = ({ url }) => (
<a type="button" className="btn btn-outline-orange btn-sm" href={url}>
Show
</a>
);
const ContinueButton = ({ url }) => (
<a type="button" className="btn btn-outline-success btn-sm" href={url}>
Continue
</a>
);
const renderButton = (url, type) => {
const buttons = {
show: ShowButton,
continue: ContinueButton,
};
const ButtonType = buttons[type];
return <ButtonType url={url} />;
};
const GameActionButton = ({ game }) => {
const gameUrl = makeGameUrl(game.id);
const gameUrlJoin = makeGameUrl(game.id, 'join');
const currentUser = Gon.getAsset('current_user');
const gameState = game.state;
const signInUrl = getSignInGithubUrl();
if (gameState === gameStateCodes.playing) {
const type = isPlayer(currentUser, game) ? 'continue' : 'show';
return renderButton(gameUrl, type);
}
if (gameState === gameStateCodes.waitingOpponent) {
if (isPlayer(currentUser, game)) {
return (
<div className="d-flex justify-content-center">
<div className="btn-group ml-5">
<ContinueButton url={gameUrl} />
<button
type="button"
className="btn btn-sm"
onClick={() => copy(`${window.location}${gameUrl}`)}
data-toggle="tooltip"
data-placement="right"
title="Copy link"
>
<i className="far fa-copy" />
</button>
</div>
<button
type="button"
className="btn btn-hover btn-sm"
onClick={lobbyMiddlewares.cancelGame(game.id)}
data-toggle="tooltip"
data-placement="right"
title="Cancel game"
>
<i className="fas fa-times" />
</button>
</div>
);
}
if (currentUser.isGuest) {
return (
<button
type="button"
className="btn btn-outline-success btn-sm"
data-method="get"
data-to={signInUrl}
>
{i18n.t('Sign in with %{name}', { name: 'Github' })}
</button>
);
}
return (
<div className="btn-group">
<button
type="button"
className="btn btn-outline-orange btn-sm"
data-method="post"
data-csrf={window.csrf_token}
data-to={gameUrlJoin}
>
{i18n.t('Fight')}
</button>
</div>
);
}
return null;
};
const LiveTournaments = ({ tournaments }) => {
if (_.isEmpty(tournaments)) {
return (
<div className="text-center">
<h3 className="mb-0 mt-3">There are no active tournaments right now</h3>
<a href="/tournaments/#create">
<u>You may want to create one</u>
</a>
</div>
);
}
return (
<div className="table-responsive">
<h2 className="text-center mt-3">Live tournaments</h2>
<table className="table table-striped">
<thead className="">
<tr>
<th className="p-3 border-0">Title</th>
<th className="p-3 border-0">Starts_at</th>
<th className="p-3 border-0">Creator</th>
<th className="p-3 border-0">Actions</th>
</tr>
</thead>
<tbody className="">
{_.orderBy(tournaments, 'startsAt', 'desc').map(tournament => (
<tr key={tournament.id}>
<td className="p-3 align-middle">{tournament.name}</td>
<td className="p-3 align-middle text-nowrap">
{moment
.utc(tournament.startsAt)
.local()
.format('YYYY-MM-DD HH:mm')}
</td>
<td className="p-3 align-middle text-nowrap">
<UserInfo user={tournament.creator} />
</td>
<td className="p-3 align-middle">
<ShowButton url={`/tournaments/${tournament.id}/`} />
</td>
</tr>
))}
</tbody>
</table>
<div className="text-center mt-5">
<a href="/tournaments">
<u>Tournamets Info</u>
</a>
</div>
</div>
);
};
const CompletedTournaments = ({ tournaments }) => {
if (_.isEmpty(tournaments)) {
return null;
}
return (
<div className="table-responsive">
<h2 className="text-center mt-3">Completed tournaments</h2>
<table className="table table-striped">
<thead className="">
<tr>
<th className="p-3 border-0">Title</th>
<th className="p-3 border-0">Type</th>
<th className="p-3 border-0">Starts_at</th>
<th className="p-3 border-0">Creator</th>
<th className="p-3 border-0">Actions</th>
</tr>
</thead>
<tbody className="">
{_.orderBy(tournaments, 'startsAt', 'desc').map(tournament => (
<tr key={tournament.id}>
<td className="p-3 align-middle">{tournament.name}</td>
<td className="p-3 align-middle">{tournament.type}</td>
<td className="p-3 align-middle text-nowrap">
{moment
.utc(tournament.startsAt)
.local()
.format('YYYY-MM-DD HH:mm')}
</td>
<td className="p-3 align-middle text-nowrap">
<UserInfo user={tournament.creator} />
</td>
<td className="p-3 align-middle">
<ShowButton url={`/tournaments/${tournament.id}/`} />
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
const ActiveGames = ({ games }) => {
if (!games) {
return null;
}
const currentUser = Gon.getAsset('current_user');
const filterGames = game => {
if (game.visibilityType === 'hidden') {
return !!_.find(game.players, { id: currentUser.id });
}
return true;
};
const filtetedGames = games.filter(filterGames);
if (_.isEmpty(filtetedGames)) {
return <p className="text-center">There are no active games right now.</p>;
}
const gamesSortByLevel = _.sortBy(filtetedGames, [
game => levelRatio[game.level],
]);
const {
gamesWithCurrentUser = [],
gamesWithActiveUsers = [],
gamesWithBots = [],
} = _.groupBy(gamesSortByLevel, game => {
const isCurrentUserPlay = game.players.some(
({ id }) => id === currentUser.id,
);
if (isCurrentUserPlay) {
return 'gamesWithCurrentUser';
}
if (!game.isBot) {
return 'gamesWithActiveUsers';
}
return 'gamesWithBots';
});
const sortedGames = [
...gamesWithCurrentUser,
...gamesWithActiveUsers,
...gamesWithBots,
];
return (
<div className="table-responsive">
<table className="table table-striped border-gray border-top-0 mb-0">
<thead className="text-center">
<tr>
<th className="p-3 border-0">Level</th>
<th className="p-3 border-0">State</th>
<th className="p-3 border-0 text-center" colSpan={2}>
Players
</th>
<th className="p-3 border-0">Actions</th>
</tr>
</thead>
<tbody>
{sortedGames.map(
game => isActiveGame(game) && (
<tr key={game.id} className="text-dark game-item">
<td className="p-3 align-middle text-nowrap">
<GameLevelBadge level={game.level} />
</td>
<td className="p-3 align-middle text-center text-nowrap">
<img
alt={game.state}
title={game.state}
src={
game.state === 'playing'
? '/assets/images/playing.svg'
: '/assets/images/waitingOpponent.svg'
}
/>
</td>
<Players players={game.players} />
<td className="p-3 align-middle text-center">
<GameActionButton game={game} />
</td>
</tr>
),
)}
</tbody>
</table>
</div>
);
};
const tabLinkClassName = (...hash) => {
const url = new URL(window.location);
return classnames(
'nav-item nav-link text-uppercase rounded-0 text-black font-weight-bold p-3',
{ active: hash.includes(url.hash) },
);
};
const tabContentClassName = hash => {
const url = new URL(window.location);
return classnames({
'tab-pane': true,
fade: true,
active: hash.includes(url.hash),
show: hash.includes(url.hash),
});
};
const tabLinkHandler = hash => () => {
window.location.hash = hash;
};
const GameContainers = ({
activeGames,
completedGames,
liveTournaments,
completedTournaments,
totalGames,
}) => {
useEffect(() => {
if (!window.location.hash) {
tabLinkHandler(hashLinkNames.default)();
window.scrollTo({ top: 0 });
}
}, []);
return (
<div className="p-0">
<nav>
<div className="nav nav-tabs bg-gray" id="nav-tab" role="tablist">
<a
className={tabLinkClassName(
hashLinkNames.lobby,
hashLinkNames.default,
)}
id="lobby-tab"
data-toggle="tab"
href="#lobby"
role="tab"
aria-controls="lobby"
aria-selected="true"
onClick={tabLinkHandler(hashLinkNames.lobby)}
>
Lobby
</a>
<a
className={tabLinkClassName(hashLinkNames.tournaments)}
id="tournaments-tab"
data-toggle="tab"
href="#tournaments"
role="tab"
aria-controls="tournaments"
aria-selected="false"
onClick={tabLinkHandler(hashLinkNames.tournaments)}
>
Tournaments
</a>
<a
className={tabLinkClassName(hashLinkNames.completedGames)}
id="completedGames-tab"
data-toggle="tab"
href="#completedGames"
role="tab"
aria-controls="completedGames"
aria-selected="false"
onClick={tabLinkHandler(hashLinkNames.completedGames)}
>
Completed Games
</a>
</div>
</nav>
<div className="tab-content" id="nav-tabContent">
<div
className={tabContentClassName(
hashLinkNames.lobby,
hashLinkNames.default,
)}
id="lobby"
role="tabpanel"
aria-labelledby="lobby-tab"
>
<ActiveGames games={activeGames} />
</div>
<div
className={tabContentClassName(hashLinkNames.tournaments)}
id="tournaments"
role="tabpanel"
aria-labelledby="tournaments-tab"
>
<LiveTournaments tournaments={liveTournaments} />
<CompletedTournaments tournaments={completedTournaments} />
</div>
<div
className={tabContentClassName(hashLinkNames.completedGames)}
id="completedGames"
role="tabpanel"
aria-labelledby="completedGames-tab"
>
<CompletedGames games={completedGames} loadNextPage={loadNextPage} totalGames={totalGames} />
</div>
</div>
</div>
);
};
const renderModal = (show, handleCloseModal) => (
<Modal show={show} onHide={handleCloseModal}>
<Modal.Header closeButton>
<Modal.Title>Create a game</Modal.Title>
</Modal.Header>
<Modal.Body>
<CreateGameDialog hideModal={handleCloseModal} />
</Modal.Body>
</Modal>
);
const CreateGameButton = ({ handleClick }) => (
<button
type="button"
className="btn btn-success text-uppercase font-weight-bold py-3 mb-3"
onClick={handleClick}
>
Create a Game
</button>
);
const LobbyWidget = () => {
const currentUser = Gon.getAsset('current_user');
const currentOpponent = Gon.getAsset('opponent');
const isModalShow = useSelector(selectors.isModalShow);
const dispatch = useDispatch();
const handleShowModal = () => dispatch(actions.showCreateGameModal());
const handleCloseModal = () => dispatch(actions.closeCreateGameModal());
useEffect(() => {
dispatch(actions.setCurrentUser({ user: { ...currentUser } }));
dispatch(lobbyMiddlewares.fetchState());
if (currentOpponent) {
window.history.replaceState({}, document.title, getLobbyUrl());
dispatch(
actions.showCreateGameInviteModal({
opponentInfo: { id: currentOpponent.id, name: currentOpponent.name },
}),
);
}
}, [currentUser, dispatch]);
useEffect(() => {
dispatch(fetchCompletedGames());
}, [dispatch]);
const {
loaded,
activeGames,
liveTournaments,
completedTournaments,
} = useSelector(selectors.lobbyDataSelector);
const { completedGames, totalGames } = useSelector(selectors.completedGamesData);
if (!loaded) {
return <Loading />;
}
return (
<div className="container-lg">
{renderModal(isModalShow, handleCloseModal)}
<div className="row">
<div className="col-lg-8 col-md-12 p-0 mb-2 pr-lg-2 pb-3">
<GameContainers
activeGames={activeGames}
completedGames={completedGames}
liveTournaments={liveTournaments}
completedTournaments={completedTournaments}
totalGames={totalGames}
/>
<LobbyChat />
</div>
<div className="d-flex flex-column col-lg-4 col-md-12 p-0">
<CreateGameButton handleClick={handleShowModal} />
<div className="mt-2">
<Announcement />
</div>
<div className="mt-2">
<Leaderboard />
</div>
</div>
</div>
</div>
);
};
export default LobbyWidget;