fork/replay-manager-for-slippi

git clone https://git.julia.blue/fork/replay-manager-for-slippi

Nicoletdisallow copy of incomplete filece3c214

2.4.1
17.0 KiB566 linesraw
1import {
2  Alert,
3  Avatar,
4  Box,
5  Checkbox,
6  Chip,
7  createTheme,
8  IconButton,
9  List,
10  ListItemButton,
11  Stack,
12  ThemeProvider,
13  Tooltip,
14} from '@mui/material';
15import {
16  EmojiEventsOutlined,
17  EmojiEvents,
18  HideSource,
19} from '@mui/icons-material';
20import { ForwardedRef, forwardRef, RefObject, useCallback, JSX } from 'react';
21import styled from '@emotion/styled';
22import { format } from 'date-fns';
23import { UTCDate } from '@date-fns/utc';
24import { Id, PlayerOverrides, Replay } from '../common/types';
25import {
26  characterNames,
27  frameMsDivisor,
28  isValidCharacter,
29  shortStageNames,
30  stageNames,
31} from '../common/constants';
32import { DroppableChip } from './DragAndDrop';
33import getCharacterIcon from './getCharacterIcon';
34
35const PlayersRow = styled.div`
36  display: flex;
37`;
38
39const QuarterSegment = styled.div`
40  align-items: center;
41  box-sizing: border-box;
42  display: flex;
43  padding-left: 4px;
44  min-width: 25%;
45`;
46
47const ReplayContent = styled.div`
48  display: flex;
49  flex-direction: column;
50  flex-grow: 1;
51`;
52
53const chipStyle = {
54  width: '25%',
55};
56
57export function SkewReplay({ replay }: { replay: Replay }) {
58  const time = format(replay.startAt, 'h:mmaaa');
59  const dateShort = format(replay.startAt, 'yyyy MMM dd');
60  const duration =
61    replay.lastFrame > -124
62      ? format(
63          new UTCDate((replay.lastFrame + 124) / frameMsDivisor),
64          "m'm'ss's'",
65        )
66      : '?m??s';
67  const shortStageName =
68    shortStageNames.get(replay.stageId) || replay.stageId.toString();
69  return (
70    <Stack width="275px">
71      <Stack direction="row">
72        <ThemeProvider
73          theme={createTheme({
74            components: {
75              MuiChip: {
76                styleOverrides: {
77                  label: {
78                    alignItems: 'center',
79                    display: 'flex',
80                    flexGrow: 1,
81                  },
82                },
83              },
84            },
85          })}
86        >
87          {replay.players.map((player) =>
88            player.playerType === 0 || player.playerType === 1 ? (
89              <Chip
90                key={player.port}
91                icon={
92                  isValidCharacter(player.externalCharacterId) ? (
93                    <Avatar
94                      alt={characterNames.get(player.externalCharacterId)}
95                      src={getCharacterIcon(
96                        player.externalCharacterId,
97                        player.costumeIndex,
98                      )}
99                      style={{ height: '24px', width: '24px' }}
100                      variant="square"
101                    />
102                  ) : undefined
103                }
104                style={{ width: '25%' }}
105                variant="outlined"
106              />
107            ) : (
108              <Chip
109                key={player.port}
110                icon={<HideSource />}
111                style={{ width: '25%' }}
112              />
113            ),
114          )}
115        </ThemeProvider>
116      </Stack>
117      <Stack direction="row" typography="caption">
118        <Box width="50%">
119          {dateShort}, {time}
120        </Box>
121        <Box width="25%">{shortStageName}</Box>
122        <Box width="25%">{duration}</Box>
123      </Stack>
124    </Stack>
125  );
126}
127
128const ReplayListItem = forwardRef(
129  (
130    {
131      index,
132      numAvailablePlayers,
133      replay,
134      selectedChipData,
135      findOtherPlayer,
136      onClick,
137      onOverride,
138      resetSelectedChipData,
139      elevateChips,
140      elevateNames,
141    }: {
142      index: number;
143      numAvailablePlayers: number;
144      replay: Replay;
145      selectedChipData: PlayerOverrides;
146      findOtherPlayer: (entrantId: Id, participantId: Id) => PlayerOverrides;
147      onClick: (index: number) => void;
148      onOverride: () => void;
149      resetSelectedChipData: () => void;
150      elevateChips: boolean;
151      elevateNames: boolean;
152    },
153    ref: ForwardedRef<HTMLDivElement> | undefined,
154  ) => {
155    const onClickCallback = useCallback(() => {
156      onClick(index);
157    }, [index, onClick]);
158
159    const dateShort = format(replay.startAt, 'yyyy MMM dd');
160    const time = format(replay.startAt, 'h:mmaaa');
161    const duration =
162      replay.lastFrame > -124
163        ? format(
164            new UTCDate((replay.lastFrame + 124) / frameMsDivisor),
165            "m'm'ss's'",
166          )
167        : '?m??s';
168    const stageName =
169      stageNames.get(replay.stageId) || replay.stageId.toString();
170
171    const displayNamesToShow = replay.players.map((player) => {
172      const key = player.port;
173      const displayName =
174        player.playerOverrides.displayName ||
175        (player.playerType === 0 && player.displayName) ||
176        '';
177      let trophy: JSX.Element | undefined;
178      if (displayName) {
179        if (player.isWinner) {
180          if (replay.timeout) {
181            trophy = (
182              <Tooltip arrow placement="top" title="Unset as winner (timeout)">
183                <Stack
184                  direction="row"
185                  typography="caption"
186                  style={{
187                    alignItems: 'center',
188                    cursor: 'pointer',
189                    overflow: 'hidden',
190                    textWrap: 'nowrap',
191                    backgroundColor: elevateNames ? 'white' : undefined,
192                  }}
193                  sx={{
194                    zIndex: (theme) =>
195                      elevateNames ? theme.zIndex.drawer + 2 : undefined,
196                  }}
197                  onClick={(event) => {
198                    event.stopPropagation();
199                    player.isWinner = false;
200                    onOverride();
201                  }}
202                >
203                  <EmojiEvents />
204                  {` ${displayName.slice(0, 15)}`}
205                </Stack>
206              </Tooltip>
207            );
208          } else {
209            trophy = (
210              <Tooltip arrow placement="top" title="Winner">
211                <Stack
212                  direction="row"
213                  typography="caption"
214                  style={{
215                    alignItems: 'center',
216                    overflow: 'hidden',
217                    textWrap: 'nowrap',
218                    backgroundColor: elevateNames ? 'white' : undefined,
219                  }}
220                  sx={{
221                    zIndex: (theme) =>
222                      elevateNames ? theme.zIndex.drawer + 2 : undefined,
223                  }}
224                >
225                  <EmojiEvents />
226                  {` ${displayName.slice(0, 15)}`}
227                </Stack>
228              </Tooltip>
229            );
230          }
231        } else if (player.playerType === 0 || player.playerType === 1) {
232          trophy = (
233            <Tooltip arrow placement="top" title="Set as winner">
234              <Stack
235                direction="row"
236                typography="caption"
237                style={{
238                  alignItems: 'center',
239                  cursor: 'pointer',
240                  overflow: 'hidden',
241                  textWrap: 'nowrap',
242                  backgroundColor: elevateNames ? 'white' : undefined,
243                }}
244                sx={{
245                  zIndex: (theme) =>
246                    elevateNames ? theme.zIndex.drawer + 2 : undefined,
247                }}
248                onClick={(event) => {
249                  event.stopPropagation();
250                  replay.players.forEach((innerPlayer) => {
251                    innerPlayer.isWinner = false;
252                  });
253                  player.isWinner = true;
254                  onOverride();
255                }}
256              >
257                <EmojiEventsOutlined />
258                {` ${displayName.slice(0, 15)}`}
259              </Stack>
260            </Tooltip>
261          );
262        }
263      } else if (player.isWinner) {
264        if (replay.timeout) {
265          trophy = (
266            <Stack
267              direction="row"
268              typography="caption"
269              style={{
270                alignItems: 'center',
271                cursor: 'pointer',
272                backgroundColor: elevateNames ? 'white' : undefined,
273              }}
274              sx={{
275                zIndex: (theme) =>
276                  elevateNames ? theme.zIndex.drawer + 2 : undefined,
277              }}
278              onClick={(event) => {
279                event.stopPropagation();
280                player.isWinner = false;
281                onOverride();
282              }}
283            >
284              <EmojiEvents /> Unset as winner
285            </Stack>
286          );
287        } else {
288          trophy = (
289            <Stack
290              direction="row"
291              typography="caption"
292              style={{
293                alignItems: 'center',
294                backgroundColor: elevateNames ? 'white' : undefined,
295              }}
296              sx={{
297                zIndex: (theme) =>
298                  elevateNames ? theme.zIndex.drawer + 2 : undefined,
299              }}
300            >
301              <EmojiEvents /> Winner
302            </Stack>
303          );
304        }
305      } else if (player.playerType === 0 || player.playerType === 1) {
306        trophy = (
307          <Stack
308            direction="row"
309            typography="caption"
310            style={{
311              alignItems: 'center',
312              cursor: 'pointer',
313              backgroundColor: elevateNames ? 'white' : undefined,
314            }}
315            sx={{
316              zIndex: (theme) =>
317                elevateNames ? theme.zIndex.drawer + 2 : undefined,
318            }}
319            onClick={(event) => {
320              event.stopPropagation();
321              replay.players.forEach((innerPlayer) => {
322                innerPlayer.isWinner = false;
323              });
324              player.isWinner = true;
325              onOverride();
326            }}
327          >
328            <EmojiEventsOutlined /> Set as winner
329          </Stack>
330        );
331      }
332      return <QuarterSegment key={key}>{trophy}</QuarterSegment>;
333    });
334
335    const playerChips = replay.players.map((player) => {
336      const key = player.port;
337      if (player.playerType !== 0 && player.playerType !== 1) {
338        return <Chip key={key} icon={<HideSource />} style={chipStyle} />;
339      }
340
341      const avatar = isValidCharacter(player.externalCharacterId) ? (
342        <Avatar
343          alt={characterNames.get(player.externalCharacterId)}
344          src={getCharacterIcon(
345            player.externalCharacterId,
346            player.costumeIndex,
347          )}
348          style={{ height: '24px', width: '24px' }}
349          variant="square"
350        />
351      ) : undefined;
352      const avatarButton = (player.externalCharacterId === 18 ||
353        player.externalCharacterId === 19) && (
354        <IconButton
355          onClick={(event) => {
356            event.preventDefault();
357            event.stopPropagation();
358            if (player.externalCharacterId === 18) {
359              player.externalCharacterId = 19;
360            } else {
361              player.externalCharacterId = 18;
362            }
363            onOverride();
364          }}
365        >
366          {avatar}
367        </IconButton>
368      );
369      const name =
370        player.playerType === 0
371          ? player.connectCode || player.nametag || `P${key}`
372          : 'CPU';
373      const onClickOrDrop = (
374        displayName: string,
375        entrantId: Id,
376        participantId: Id,
377        prefix: string,
378        pronouns: string,
379      ) => {
380        player.playerOverrides = {
381          displayName,
382          entrantId,
383          participantId,
384          prefix,
385          pronouns,
386        };
387        const validPlayers = replay.players.filter(
388          (otherPlayer) =>
389            otherPlayer.playerType === 0 || otherPlayer.playerType === 1,
390        );
391        validPlayers.forEach((otherPlayer) => {
392          if (
393            otherPlayer.port !== player.port &&
394            otherPlayer.playerOverrides.entrantId === entrantId &&
395            otherPlayer.playerOverrides.participantId === participantId
396          ) {
397            otherPlayer.playerOverrides.displayName = '';
398            otherPlayer.playerOverrides.entrantId = 0;
399            otherPlayer.playerOverrides.participantId = 0;
400            otherPlayer.playerOverrides.prefix = '';
401            otherPlayer.playerOverrides.pronouns = '';
402          }
403        });
404
405        // pigeonhole remaining player if possible
406        if (numAvailablePlayers === validPlayers.length) {
407          const { teamId } = player;
408          const isTeams = numAvailablePlayers === 4 && teamId !== -1;
409
410          // find if there's exactly one hole to pigeon
411          const playersToCheck = validPlayers.filter(
412            (validPlayer) =>
413              (!isTeams || validPlayer.teamId === teamId) &&
414              validPlayer.playerOverrides.participantId !== participantId,
415          );
416          if (playersToCheck.length === 1) {
417            const otherPlayer = findOtherPlayer(entrantId, participantId);
418            if (otherPlayer.entrantId && otherPlayer.participantId) {
419              replay.players[playersToCheck[0].port - 1].playerOverrides =
420                otherPlayer;
421              replay.players.forEach((replayPlayer) => {
422                if (
423                  replayPlayer.port !== playersToCheck[0].port &&
424                  replayPlayer.playerOverrides.entrantId ===
425                    otherPlayer.entrantId &&
426                  replayPlayer.playerOverrides.participantId ===
427                    otherPlayer.participantId
428                ) {
429                  replayPlayer.playerOverrides.displayName = '';
430                  replayPlayer.playerOverrides.entrantId = 0;
431                  replayPlayer.playerOverrides.participantId = 0;
432                  replayPlayer.playerOverrides.prefix = '';
433                  replayPlayer.playerOverrides.pronouns = '';
434                }
435              });
436            }
437          }
438        }
439
440        onOverride();
441        resetSelectedChipData();
442      };
443
444      return (
445        <DroppableChip
446          active={replay.selected}
447          avatar={avatarButton || avatar}
448          key={key}
449          label={name}
450          outlined
451          selectedChipData={selectedChipData}
452          style={chipStyle}
453          onClickOrDrop={onClickOrDrop}
454          elevate={elevateChips}
455        />
456      );
457    });
458
459    const replayListItemInner = (
460      <ListItemButton
461        disabled={replay.lastFrame < -123}
462        disableGutters
463        ref={ref}
464        style={
465          replay.invalidReasons.length === 0 ||
466          (selectedChipData.entrantId && selectedChipData.participantId) ||
467          elevateChips ||
468          elevateNames
469            ? {}
470            : { opacity: '50%' }
471        }
472        selected={replay.selected}
473        onClick={onClickCallback}
474      >
475        <Checkbox checked={replay.selected} />
476        <ReplayContent>
477          <Stack direction="row" sx={{ typography: 'caption' }}>
478            {displayNamesToShow}
479          </Stack>
480          <PlayersRow>{playerChips}</PlayersRow>
481          <Stack direction="row" sx={{ typography: 'caption' }}>
482            <QuarterSegment>{time}</QuarterSegment>
483            <QuarterSegment>{stageName}</QuarterSegment>
484            <QuarterSegment>
485              {duration}
486              {replay.timeout && ' (timeout)'}
487            </QuarterSegment>
488          </Stack>
489          <Stack direction="row" sx={{ typography: 'caption' }}>
490            <QuarterSegment>{dateShort}</QuarterSegment>
491            <QuarterSegment>{replay.fileName}</QuarterSegment>
492          </Stack>
493        </ReplayContent>
494      </ListItemButton>
495    );
496
497    return replay.invalidReasons.length === 0 || replay.selected ? (
498      replayListItemInner
499    ) : (
500      <Tooltip arrow title={replay.invalidReasons.join(' ')}>
501        <div>{replayListItemInner}</div>
502      </Tooltip>
503    );
504  },
505);
506
507export default function ReplayList({
508  dirInit,
509  numAvailablePlayers,
510  replays,
511  replayRefs,
512  selectedChipData,
513  findOtherPlayer,
514  onClick,
515  onOverride,
516  resetSelectedChipData,
517  elevate,
518  elevateChips,
519  elevateNames,
520}: {
521  dirInit: boolean;
522  numAvailablePlayers: number;
523  replays: Replay[];
524  replayRefs: RefObject<HTMLDivElement>[];
525  selectedChipData: PlayerOverrides;
526  findOtherPlayer: (entrantId: Id, participantId: Id) => PlayerOverrides;
527  onClick: (index: number) => void;
528  onOverride: () => void;
529  resetSelectedChipData: () => void;
530  elevate: boolean;
531  elevateChips: boolean;
532  elevateNames: boolean;
533}) {
534  return (
535    <List
536      disablePadding
537      style={{ backgroundColor: 'white' }}
538      sx={{
539        zIndex: (theme) => (elevate ? theme.zIndex.drawer + 2 : undefined),
540      }}
541    >
542      {replays.length === 0 ? (
543        <Alert severity="warning" sx={{ mb: '8px', mt: '8px', pl: '10px' }}>
544          {dirInit ? 'Click refresh replays!' : 'No replays in folder.'}
545        </Alert>
546      ) : (
547        replays.map((replay, index) => (
548          <ReplayListItem
549            key={replay.filePath}
550            ref={replayRefs[index]}
551            index={index}
552            findOtherPlayer={findOtherPlayer}
553            numAvailablePlayers={numAvailablePlayers}
554            replay={replay}
555            selectedChipData={selectedChipData}
556            onClick={onClick}
557            onOverride={onOverride}
558            resetSelectedChipData={resetSelectedChipData}
559            elevateChips={elevateChips}
560            elevateNames={elevateNames}
561          />
562        ))
563      )}
564    </List>
565  );
566}