All files / Rindu/components/RemoveTracksModal RemoveTracksModal.tsx

11.42% Statements 8/70
0% Branches 0/25
0% Functions 0/15
11.94% Lines 8/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 24319x   19x   19x 19x 19x 19x             19x 19x                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import { ReactElement, ReactNode, useEffect, useState } from "react";
 
import { List, ListRowProps } from "react-virtualized";
 
import { Button, CardTrack, Heading, LoadingSpinner } from "components";
import { CardType } from "components/CardTrack/CardTrack";
import { useSpotify, useToast, useTranslations } from "hooks";
import { AsType } from "types/heading";
import { IPageDetails, ITrack } from "types/spotify";
import {
  analyzePlaylist,
  divideArray,
  getIdFromUri,
  templateReplace,
} from "utils";
import { removeTracksFromLibrary } from "utils/spotifyCalls";
 
interface RemoveTracksModalProps {
  isLibrary: boolean;
}
 
function renderListRow({
  style,
  key,
  index,
  tracksToRemove,
  pageDetails,
}: ListRowProps & {
  tracksToRemove: ITrack[];
  pageDetails: IPageDetails | null;
}): ReactElement {
  return (
    <div style={{ ...style, width: "100%" }} key={key}>
      <CardTrack
        isTrackInLibrary={false}
        track={tracksToRemove[index]}
        playlistUri={pageDetails?.uri ?? ""}
        type={CardType.Album}
        position={tracksToRemove[index].position}
      />
    </div>
  );
}
 
export default function RemoveTracksModal({
  isLibrary,
}: Readonly<RemoveTracksModalProps>): ReactElement {
  const { removeTracks, pageDetails, setAllTracks } = useSpotify();
  const [isLoadingComplete, setIsLoadingComplete] = useState(false);
  const { addToast } = useToast();
  const [duplicateTracksIdx, setDuplicateTracksIdx] = useState<number[]>([]);
  const [corruptedSongsIdx, setCorruptedSongsIdx] = useState<number[]>([]);
  const [tracksToRemove, setTracksToRemove] = useState<ITrack[]>([]);
  const { translations } = useTranslations();
  const [title, setTitle] = useState<string | ReactNode[]>(
    translations.removeTracksModal.analyzingPlaylist
  );
 
  useEffect(() => {
    Iif (!pageDetails) return;
    setIsLoadingComplete(false);
 
    analyzePlaylist(
      getIdFromUri(pageDetails?.uri, "id"),
      pageDetails.tracks?.total,
      isLibrary,
      translations
    ).then((res) => {
      Iif (!res) return;
 
      setAllTracks(res.tracks);
      setDuplicateTracksIdx(res.duplicateTracksIndexes);
      setCorruptedSongsIdx(res.corruptedSongsIndexes);
      setTracksToRemove(res.tracksToRemove);
      setTitle(res.summary);
      setIsLoadingComplete(true);
    });
  }, [isLibrary, pageDetails, setAllTracks, translations]);
 
  async function handleRemoveTracksFromLibrary() {
    const ids = tracksToRemove
      .map(({ id }) => id)
      .filter((id) => id) as string[];
 
    const idChunks = divideArray(ids, 50);
    const promises = idChunks.map((ids) => removeTracksFromLibrary(ids));
    try {
      await Promise.all(promises);
      setAllTracks((tracks) => {
        return tracks.filter((track) => {
          Iif (ids.includes(track.id ?? "")) {
            return false;
          }
          return true;
        });
      });
      setTracksToRemove([]);
      setTitle("Tracks removed from library");
      addToast({
        variant: "success",
        message: templateReplace(translations.toastMessages.typeRemovedFrom, [
          translations.contentType.items,
          translations.contentType.library,
        ]),
      });
    } catch (error) {
      addToast({
        variant: "error",
        message: templateReplace(
          translations.toastMessages.couldNotRemoveFrom,
          [translations.contentType.library]
        ),
      });
      console.error(error);
    }
  }
 
  async function handleRemoveTracksFromPlaylist() {
    const indexes = [...new Set([...corruptedSongsIdx, ...duplicateTracksIdx])];
    try {
      await removeTracks(
        getIdFromUri(pageDetails?.uri, "id"),
        indexes,
        pageDetails?.snapshot_id
      );
      setAllTracks((tracks) => {
        return tracks.filter((_, i) => {
          Iif (indexes.includes(i)) {
            return false;
          }
          return true;
        });
      });
      setTracksToRemove([]);
      const itemsRemovedFromPlaylist = templateReplace(
        translations.toastMessages.typeRemovedFrom,
        [translations.contentType.items, translations.contentType.playlist]
      );
      setTitle(itemsRemovedFromPlaylist);
      addToast({
        variant: "success",
        message: itemsRemovedFromPlaylist,
      });
    } catch (error) {
      addToast({
        variant: "error",
        message: templateReplace(
          translations.toastMessages.couldNotRemoveFrom,
          [translations.contentType.playlist]
        ),
      });
      console.error(error);
    }
  }
 
  return (
    <div>
      {!isLoadingComplete ? (
        <div className="loading-message">
          <LoadingSpinner />
        </div>
      ) : null}
      <div className="tracks">
        {tracksToRemove.length === 0 ? (
          <div className={tracksToRemove.length === 0 ? "loading-message" : ""}>
            <Heading number={4} textAlign="center" as={AsType.P}>
              {title}
            </Heading>
          </div>
        ) : null}
        {tracksToRemove.length > 0 ? (
          <>
            <List
              height={
                tracksToRemove.length > 5 ? 400 : 65 * tracksToRemove.length
              }
              width={800}
              overscanRowCount={2}
              rowCount={tracksToRemove.length}
              rowHeight={65}
              rowRenderer={(listRowProps) =>
                renderListRow({
                  ...listRowProps,
                  tracksToRemove,
                  pageDetails,
                })
              }
            />
            <div
              className={tracksToRemove.length === 0 ? "loading-message" : ""}
            >
              <Heading number={4} textAlign="center" as={AsType.P}>
                {title}
              </Heading>
            </div>
            <div className="popupContainer_buttons">
              <Button
                type="button"
                tabIndex={0}
                onClick={async (e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  Iif (isLibrary) {
                    await handleRemoveTracksFromLibrary();
                    return;
                  }
                  await handleRemoveTracksFromPlaylist();
                }}
              >
                {translations.removeTracksModal.cleanPlaylist}
              </Button>
            </div>
          </>
        ) : null}
        <style jsx>{`
          .tracks {
            overflow-y: hidden;
            overflow-x: hidden;
            max-height: calc((var(--vh, 1vh) * 100) - 300px);
            margin-top: 30px;
          }
          .loading-message {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
          }
          p {
            margin: 0;
            font-size: 14px;
          }
          .popupContainer_buttons {
            display: flex;
            margin-top: 24px;
            justify-content: center;
            flex-wrap: wrap;
          }
        `}</style>
      </div>
    </div>
  );
}