Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various fixes and features #7

Merged
merged 7 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,440 changes: 165 additions & 3,275 deletions package-lock.json

Large diffs are not rendered by default.

68 changes: 60 additions & 8 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import React from 'react';
import { combinePlaylists, getPlaylistInfo, getPaginatedSpotifyData, TrackState } from './utils';
import { GET_PLAYLISTS_URL, LS_KEY } from './constants';
import { CREATE_NEW_PLAYLIST_IDENTIFIER, CREATE_PLAYLIST_URL, GET_PLAYLISTS_URL, LS_KEY } from './constants';
import type { CombinedPlaylist, SpotifyPlaylist, InitialPlaylistForm } from './types';

import './assets/css/styles.scss';
import { Card } from './components/Card';
import { SpicetifySvgIcon } from './components/SpicetifySvgIcon';
import { AddPlaylistCard } from './components/AddPlaylistCard';
import { PlaylistForm } from './components/AddPlaylistForm';
import { AddPlaylistCard } from './components/AddPlaylistCard';
import { Card } from './components/Card';
import { ImportExportModal } from './components/ImportExportModal';

export interface State {
playlists: SpotifyPlaylist[];
Expand Down Expand Up @@ -41,23 +42,52 @@ class App extends React.Component<Record<string, unknown>, State> {
async componentDidMount() {
const playlists = await getPaginatedSpotifyData<SpotifyPlaylist>(GET_PLAYLISTS_URL);
const combinedPlaylists = this.combinedPlaylistsLs.map((combinedPlaylist) => this.getMostRecentPlaylistFromData(combinedPlaylist, playlists));
const checkedCombinedPlaylists = this.checkIfPlaylistsAreStillValid(combinedPlaylists);

this.setState({
playlists,
combinedPlaylists
combinedPlaylists: checkedCombinedPlaylists
});
}

checkIfPlaylistsAreStillValid(combinedPlaylists: CombinedPlaylist[]) {
const validPlaylists = combinedPlaylists.filter(({ target }) => target?.id);

if (validPlaylists.length !== combinedPlaylists.length) {
this.combinedPlaylistsLs = validPlaylists;
}

return validPlaylists;
}

@TrackState('isLoading')
async createNewCombinedPlaylist(formData: InitialPlaylistForm) {
const sourcePlaylists = formData.sources.map((source) => this.findPlaylist(source));
const targetPlaylist = this.findPlaylist(formData.target);
const targetPlaylist = formData.target === CREATE_NEW_PLAYLIST_IDENTIFIER
? await this.createPlaylist(formData.sources)
: this.findPlaylist(formData.target);

await combinePlaylists(sourcePlaylists, targetPlaylist);
this.saveCombinedPlaylist(sourcePlaylists, targetPlaylist);

Spicetify.PopupModal.hide();
}

async createPlaylist(sources: string[]) {
const { username }: { username: string } = await Spicetify.Platform.UserAPI.getUser();
const sourcePlaylistNames = sources.map((source) => this.findPlaylist(source).name);

const newPlaylist = await Spicetify.CosmosAsync.post(CREATE_PLAYLIST_URL(username), {
name: 'Combined Playlist',
description: `Combined playlist from ${sourcePlaylistNames.join(', ')}.`,
public: false,
});

this.setState((state) => ({ playlists: [...state.playlists, newPlaylist ] }));

return newPlaylist;
}

/**
* Save combined playlist to localstorage and state. Making sure not to create a duplicate
*/
Expand Down Expand Up @@ -87,6 +117,7 @@ class App extends React.Component<Record<string, unknown>, State> {
@TrackState('isLoading')
async syncPlaylist(id: string) {
const playlistToSync = this.findPlaylist(id);
Spicetify.showNotification(`Synchronizing playlist: ${playlistToSync.name}`);
const { sources } = this.state.combinedPlaylists.find((combinedPlaylist) => combinedPlaylist.target.id === playlistToSync.id) as CombinedPlaylist;
const sourcePlaylists = sources.map((sourcePlaylist) => this.findPlaylist(sourcePlaylist.id));

Expand Down Expand Up @@ -133,26 +164,47 @@ class App extends React.Component<Record<string, unknown>, State> {
});
}

openImportExportModal() {
const importCombinedPlaylists = (combinedPlaylistsData: string) => {
const combinedPlaylists = JSON.parse(combinedPlaylistsData);
const safeCombinedPlaylists = this.checkIfPlaylistsAreStillValid(combinedPlaylists.map((combinedPlaylist: CombinedPlaylist) => this.getMostRecentPlaylistFromData(combinedPlaylist, this.state.playlists)));

this.setState({ combinedPlaylists: safeCombinedPlaylists });

this.combinedPlaylistsLs = safeCombinedPlaylists;

Spicetify.showNotification('Imported combined playlists successfully!');
Spicetify.PopupModal.hide();
};

Spicetify.PopupModal.display({
title: 'Import / export combined playlists',
content: <ImportExportModal combinedPlaylists={this.state.combinedPlaylists} importCombinedPlaylists={importCombinedPlaylists} />,
isLarge: true,
});
}

render() {
return (
<div id="combined-playlists--wrapper" className="contentSpacing">
<header>
<h1>Playlist combiner</h1>
<button onClick={() => this.openImportExportModal()}><SpicetifySvgIcon iconName="external-link" /></button>
<button onClick={() => this.showAddPlaylistModal()}><SpicetifySvgIcon iconName="plus2px" /></button>
</header>

{!this.state.isInitializing && <div id="combined-playlists--grid" className="main-gridContainer-gridContainer">
{this.state.combinedPlaylists.map((combinedPlaylist) => {
{this.state.combinedPlaylists.map((combinedPlaylist, i) => {
const playlist = this.findPlaylist(combinedPlaylist.target.id);

return <Card
key={playlist.id}
playlist={playlist}
onClick={() => this.openEditPlaylistModal(combinedPlaylist)}
onClick={() => !this.state.isLoading && this.openEditPlaylistModal(combinedPlaylist)}
onClickAction={() => !this.state.isLoading && this.syncPlaylist(playlist.id)}
/>;
})}
<AddPlaylistCard onClick={() => this.showAddPlaylistModal()} />
<AddPlaylistCard onClick={() => !this.state.isLoading && this.showAddPlaylistModal()} />
</div>}
</div>
);
Expand Down
74 changes: 74 additions & 0 deletions src/assets/css/styles.scss
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
@mixin button {
border-radius: 500px;
padding: 16px;
font-weight: bold;
font-size: 1rem;
transition: transform 0.2s ease-out;

&:hover {
cursor: pointer;
transform: scale(1.025);
}
}

#combined-playlists-wrapper {
display: flex;
flex-direction: column;
Expand Down Expand Up @@ -58,6 +71,7 @@
display: flex;
justify-content: center;
align-items: center;
margin-left: 1rem;

&:hover {
background-color: var(--spice-tab-active);
Expand Down Expand Up @@ -136,6 +150,7 @@
display: flex;
gap: 1em;
padding: 8px 0;
align-items: center;

button {
display: flex;
Expand All @@ -161,9 +176,68 @@
background-color: var(--spice-button);
color: black;
flex-grow: 1;
border: none;

@include button;

&:active {
background-color: var(--spice-button-active);
}
}
}

.btn {
&__add-playlist {
@include button;
background-color: var(--spice-player);
border: 1px solid var(--spice-misc);
color: var(--spice-text);

&:hover {
border-color: var(--spice-text);
}
}

&__remove-playlist {
@include button;
background-color: var(--spice-player);
border: 1px solid var(--spice-misc);
padding: 8px 16px;

&:hover {
border-color: var(--spice-text);
}
}

&__import-export {
@include button;
background-color: var(--spice-player);
border: 1px solid var(--spice-misc);
padding: 8px 16px;

&:hover {
border-color: var(--spice-text);
}
}
}

#import-export-modal {
.export-form {
margin-top: 0.5em;
margin-bottom: 1em;
}

.import-form {
display: flex;
flex-direction: column;
gap: 1em;

textarea {
border-radius: 6px;
resize: vertical;
color: var(--spice-text);
background-color: var(--spice-misc);
padding: 1em;
}
}
}
13 changes: 9 additions & 4 deletions src/components/AddPlaylistForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { FieldArrayRenderProps } from 'formik';
import React from 'react';
import { SpicetifySvgIcon } from './SpicetifySvgIcon';
import type { InitialPlaylistForm } from '../types/initial-playlist-form';
import { CREATE_NEW_PLAYLIST_IDENTIFIER } from '../constants';

interface Props {
playlists: SpotifyApi.PlaylistObjectSimplified[];
Expand All @@ -13,7 +14,7 @@ interface Props {
export type SubmitEventHandler = (form : InitialPlaylistForm) => void

const initialPlaylistForm: InitialPlaylistForm = {
target: '',
target: CREATE_NEW_PLAYLIST_IDENTIFIER,
sources: ['', '']
};

Expand Down Expand Up @@ -58,9 +59,13 @@ export function PlaylistForm({ playlists, onSubmit, initialForm = initialPlaylis
</Field>

{values.sources.length > 1 && <button
className='main-buttons-button main-button-outlined'
className='main-buttons-button main-button-outlined btn__remove-playlist'
type="button"
onClick={() => arrayHelpers.remove(index)}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
arrayHelpers.remove(index);
}}
name="Remove playlist"
>
<SpicetifySvgIcon iconName="x" size={16} />
Expand All @@ -81,7 +86,7 @@ export function PlaylistForm({ playlists, onSubmit, initialForm = initialPlaylis
id="target-select-field"
className="main-dropDown-dropDown"
>
<option value="">Select target playlist</option>
<option value={CREATE_NEW_PLAYLIST_IDENTIFIER}>Create new playlist</option>
{ playlists.map(({ id, name }) => (
<option key={id} value={id}>{name}</option>
)) }
Expand Down
2 changes: 1 addition & 1 deletion src/components/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function Card({ playlist, onClick, onClickAction }: CardProps) {
<div className="main-card-draggable" draggable="true">
<div className="main-card-imageContainer">
<div className="main-cardImage-imageWrapper">
<div className=""><img aria-hidden="false" draggable="false" loading="lazy" src={playlist.images[0].url} alt="" className="main-image-image main-cardImage-image" /></div>
<div className=""><img aria-hidden="false" draggable="false" loading="lazy" src={playlist.images[0]?.url} alt="" className="main-image-image main-cardImage-image" /></div>
</div>

<div onClick={handleActionClick} className="main-card-PlayButtonContainer">
Expand Down
34 changes: 34 additions & 0 deletions src/components/ImportExportModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React, { useRef } from 'react';
import type { CombinedPlaylist } from '../types/combined-playlist';

export interface ImportExportModalProps {
combinedPlaylists: CombinedPlaylist[];
importCombinedPlaylists: (combinedPlaylistsData: string) => void;
}

export function ImportExportModal({ combinedPlaylists, importCombinedPlaylists }: ImportExportModalProps) {
const importInput = useRef<HTMLTextAreaElement>(null);

function exportCombinedPlaylists() {
// Copy combinedPlaylists to clipboard
navigator.clipboard.writeText(JSON.stringify(combinedPlaylists));
Spicetify.PopupModal.hide();
Spicetify.showNotification('Combined playlists copied to clipboard');
}

return (
<section id="import-export-modal">
<h3>Export</h3>
<div className="export-form">
<button className="btn__import-export" onClick={exportCombinedPlaylists}>Export combined playlists</button>
</div>

<h3>Import</h3>
<div className="import-form">
<p>Paste the exported code here</p>
<textarea ref={importInput} cols={30} rows={5}></textarea>
<button className="btn__import-export" onClick={() => importCombinedPlaylists((importInput.current as HTMLTextAreaElement).value)}>Import</button>
</div>
</section>
);
}
4 changes: 4 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ export const TRACKS_FROM_PLAYLIST_URL_FILTER = '?fields=items(track(uri)),next';
export const ADD_TRACKS_TO_PLAYLIST_URL = (id: string) => `https://api.spotify.com/v1/playlists/${id}/tracks`;

export const LS_KEY = 'combined-playlists';

export const CREATE_PLAYLIST_URL = (userId: string) => `https://api.spotify.com/v1/users/${userId}/playlists`;

export const CREATE_NEW_PLAYLIST_IDENTIFIER = 'CREATE_NEW_PLAYLIST_IDENTIFIER';