formatting head

This commit is contained in:
Acid
2025-12-27 15:33:48 -05:00
commit 6f3bdd61d4
63 changed files with 6935 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import CreateRoomPage from './components/CreateRoomPage';
import JoinRoomPage from './components/JoinRomPage';
import HomePage from './components/HomePage';
import Room from './components/Room';
import './css/create.css';
import { useEffect, useState } from 'react';
function App() {
const [roomCode, setRoomCode] = useState<string | null>();
useEffect(() => {
fetch('/api/user-in-room/', {
credentials: 'include',
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log('User in room response:', data);
setRoomCode(data.code);
})
.catch((err) => {
console.error('error fetching backend', err);
});
}, []);
return (
<div className="center">
<Router>
<Routes>
{roomCode ? (
<>
<Route path="/" element={<Navigate to={`/room/${roomCode}`} replace />} />
<Route path="/home" element={<Navigate to={`/room/${roomCode}`} replace />} />
</>
) : (
<>
<Route path="/" element={<HomePage />} />
<Route path="/home" element={<HomePage />} />
</>
)}
<Route path="/join" element={<JoinRoomPage />} />
<Route
path="/create"
element={<CreateRoomPage votes_to_skip={2} update={false} allowPause={true} roomCode={null} />}
/>
<Route path="/room/:roomCode" element={<Room />} />
</Routes>
</Router>
</div>
);
}
export default App;
@@ -0,0 +1,63 @@
import * as React from 'react';
import { useState } from 'react';
import Snackbar, { type SnackbarCloseReason } from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';
import '../css/AlertComponent.css';
interface IncomingProps {
message: string;
severity: 'ok' | 'error';
}
function AlertComponent(props: IncomingProps) {
const { message, severity } = props;
const [open, setOpen] = useState(true);
const handleClose = (_event?: React.SyntheticEvent | Event, reason?: SnackbarCloseReason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
if (severity === 'ok') {
return (
<div className="AlertComponent">
<Snackbar
open={open}
autoHideDuration={6000}
onClose={handleClose}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
>
<Alert
onClose={handleClose}
severity="success"
variant="filled"
sx={{
width: '100%',
}}
>
{message}
</Alert>
</Snackbar>
</div>
);
} else if (severity === 'error') {
return (
<div>
<Snackbar
open={open}
autoHideDuration={6000}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
onClose={handleClose}
>
<Alert onClose={handleClose} severity="error" variant="filled" sx={{ width: '100%' }}>
{message}
</Alert>
</Snackbar>
</div>
);
}
}
export default AlertComponent;
+189
View File
@@ -0,0 +1,189 @@
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import FormHelperText from '@mui/material/FormHelperText';
import FormControl from '@mui/material/FormControl';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import { Link, useNavigate } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import AlertComponent from './AlertComponent';
interface PassedProps {
votes_to_skip: number;
update: boolean;
allowPause: boolean;
roomCode: string | null;
}
function CreateRoomPage(props: PassedProps) {
//default props destructured
const { votes_to_skip = 2, allowPause = false, update = false, roomCode = null } = props;
const [votes, setvotes] = useState<number>(votes_to_skip);
let guestCanPause = useRef<boolean>(allowPause);
const navigate = useNavigate();
const [responseMessage, setResponseMessage] = useState<'Error' | 'Succsess' | null>(null);
//helper funcs
function handleGuestCanPause(e: React.ChangeEvent<HTMLInputElement>) {
guestCanPause.current = e.target.value === 'true' ? true : false;
}
function handleVotesToSkip(e: React.ChangeEvent<HTMLInputElement>) {
setvotes(() => parseInt(e.target.value, 10) || 2);
}
function handleCreateRoom() {
const requestOptions: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
votes_to_skip: votes,
guest_can_pause: guestCanPause.current,
}),
};
fetch('/api/create-room/', requestOptions).then((response) =>
response.json().then((data) => {
navigate('/room/' + data.code);
console.log('data:', data);
}),
);
console.log('guestCanPause:', guestCanPause);
console.log('votes:', votes);
}
function handleUpdateRoom() {
const requestOptions: RequestInit = {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
votes_to_skip: votes,
guest_can_pause: guestCanPause.current,
code: roomCode,
}),
};
fetch('/api/update-room/', requestOptions)
.then((response) => {
if (response.ok) {
setResponseMessage('Succsess');
} else {
setResponseMessage('Error');
}
})
.catch((err) => {
setResponseMessage('Error');
console.error('error on HandleUpdateRoom', err);
});
console.log('## UpdateRoomBUtton##');
console.log('guestCanPause:', guestCanPause);
console.log('votes:', votes);
console.log('roomCode:', roomCode);
console.log('Message:', responseMessage);
return <Grid size={{ xs: 12 }} alignItems="center"></Grid>;
}
useEffect(() => {
if (responseMessage !== null) {
console.log('Message set to:', responseMessage);
// Set timer to clear message after 2 seconds
const timer = setTimeout(() => {
setResponseMessage(null);
}, 2000);
// Cleanup function - clears timer if component unmounts or message changes
return () => {
clearTimeout(timer);
};
}
}, [responseMessage]);
const title = update ? 'Update Room ' : 'Create Room';
function renderCreateButton() {
return (
<Grid container spacing={1}>
<Grid size={{ xs: 12 }} alignItems="center">
<Button color="primary" variant="contained" onClick={handleCreateRoom}>
Create Room
</Button>
</Grid>
<Grid size={{ xs: 12 }} alignItems="center">
<Button color="secondary" variant="contained" component={Link} to="/">
Back
</Button>
</Grid>
</Grid>
);
}
function renderUpdateButton() {
return (
<Grid container spacing={1}>
<Grid size={{ xs: 12 }} alignItems="center">
<Button color="primary" variant="contained" onClick={handleUpdateRoom}>
Update Room
</Button>
</Grid>
</Grid>
);
}
return (
<>
<Grid container spacing={1}>
<Grid size={{ xs: 12 }} alignItems="center"></Grid>
<Typography component="h4" variant="h4">
{title}
</Typography>
<Grid size={{ xs: 12 }} alignItems="center">
<FormControl component="fieldset">
<FormHelperText sx={{ textAlign: 'center' }}>Guest Control Of Playback State</FormHelperText>
<RadioGroup row defaultValue={guestCanPause.current} onChange={handleGuestCanPause}>
<FormControlLabel
value="true"
control={<Radio color="primary" />}
label="Play/Pause"
labelPlacement="bottom"
/>
<FormControlLabel
value="false"
control={<Radio color="secondary" />}
label="No Control"
labelPlacement="bottom"
/>
</RadioGroup>
</FormControl>
</Grid>
<Grid size={{ xs: 12 }} alignItems="center">
<FormControl>
<TextField required={true} type="number" defaultValue={votes} onChange={handleVotesToSkip} />
<FormHelperText sx={{ textAlign: 'center' }}>Votes Required to Skip Song</FormHelperText>
</FormControl>
</Grid>
{update ? renderUpdateButton() : renderCreateButton()}
{responseMessage === 'Succsess' ? <AlertComponent message="Updated settings" severity="ok" /> : null}
{responseMessage === 'Error' ? <AlertComponent message="Error from server" severity="error" /> : null}
</Grid>
</>
);
}
export default CreateRoomPage;
+28
View File
@@ -0,0 +1,28 @@
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import ButtonGroup from '@mui/material/ButtonGroup';
import { Link } from 'react-router-dom';
function HomePage() {
return (
<Grid container spacing={5} alignContent="center" alignItems="center">
<Grid alignItems="center">
<Typography variant="h3">House Party</Typography>
<Grid alignContent="center">
<ButtonGroup disableElevation variant="contained" color="primary">
<Button color="primary" component={Link} to="/join">
Join a Room
</Button>
<Button color="secondary" component={Link} to="/create">
Create Room
</Button>
</ButtonGroup>
</Grid>
</Grid>
</Grid>
);
}
export default HomePage;
+65
View File
@@ -0,0 +1,65 @@
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import { Link, useNavigate } from 'react-router-dom';
import { useState } from 'react';
function JoinRoomPage() {
const [roomCode, setRoomCode] = useState<string>('');
const [errorCode, setErrorcode] = useState<string>('');
const navigate = useNavigate();
function joinButton() {
const requestOptions: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ code: roomCode }),
};
fetch('/api/join-room/', requestOptions)
.then((response) => {
console.log('The response:', response);
if (response.ok) {
navigate(`/room/${roomCode}`);
} else {
setErrorcode('Room not found');
}
})
.catch((err) => console.log('fetch error:', err));
console.log('code :', roomCode);
}
return (
<Grid container spacing={1}>
<Grid size={12} alignItems="center">
<Typography variant="h4" component="h4">
Join a Room
</Typography>
<Grid size={12} alignItems="center">
<TextField
label="Code"
placeholder="Enter Room Code"
value={roomCode}
onChange={(e) => setRoomCode(e.target.value)}
helperText={errorCode}
variant="outlined"
/>
</Grid>
<Grid>
<Button variant="contained" color="primary" onClick={joinButton}>
Join
</Button>
<Button variant="contained" color="secondary" component={Link} to="/">
Back
</Button>
</Grid>
</Grid>
</Grid>
);
}
export default JoinRoomPage;
+98
View File
@@ -0,0 +1,98 @@
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Card from '@mui/material/Card';
import IconButton from '@mui/material/IconButton';
import LinearProgress from '@mui/material/LinearProgress';
import { PlayArrow, SkipNext, Pause } from '@mui/icons-material';
import type { PlayerProps } from '../interfaces';
import AlertComponent from './AlertComponent';
import { useState } from 'react';
function Player(props: PlayerProps) {
const [alert, setAlert] = useState<string | null>(null);
let songProgress: number = (props.time / props.duration) * 100;
function pause() {
const requestOptions: RequestInit = {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
};
fetch('/spotify/pause', requestOptions)
.then((data) => data.json())
.then((response) => {
if (response.error) {
console.error('you got loicence to pause ?:', response);
setAlert(response.error.message);
}
setTimeout(() => setAlert(null), 3000);
});
}
function play() {
const requestOptions: RequestInit = {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
};
fetch('/spotify/play', requestOptions)
.then((data) => data.json())
.then((response) => {
if (response.error) {
console.error('you got loicence to play ?:', response);
setAlert(response.error.message);
}
setTimeout(() => setAlert(null), 3000);
});
}
return (
<>
<Card>
<Grid container alignItems="center">
<Grid alignItems="center" size={4}>
<img src={props.image_url} height="100%" width="100%" />
</Grid>
<Grid alignItems="center" size={8}>
<Typography component="h5" variant="h5">
{props.title}
</Typography>
<Typography color="textSecondary" variant="subtitle1">
{props.artist}
</Typography>
<div>
<IconButton
onClick={() => {
props.is_playing ? pause() : play();
}}
>
{props.is_playing ? <Pause /> : <PlayArrow />}
</IconButton>
<IconButton>
<SkipNext />
</IconButton>
</div>
</Grid>
</Grid>
<LinearProgress variant="determinate" value={songProgress} color="primary" />
</Card>
{props.id ? (
<iframe
data-testid="embed-iframe"
src={`https://open.spotify.com/embed/track/${props.id}?utm_source=generator`}
width="100%"
height="152"
frameBorder="0"
allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
loading="lazy"
/>
) : null}
{alert ? <AlertComponent message={alert} severity="error" /> : null}
</>
);
}
export default Player;
+207
View File
@@ -0,0 +1,207 @@
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import type { PlayerProps, roomData, SpotifyAuthResponse } from '../interfaces';
import CreateRoomPage from './CreateRoomPage';
import Player from './Player';
import { Stack } from '@mui/material';
function Room() {
let { roomCode } = useParams<{ roomCode: string }>();
const [votesToSkip, setVotesToSkip] = useState<number>(2);
const [guestCanPause, setGuestCanPause] = useState<boolean>(false);
const [isHost, setIsHost] = useState<boolean>(false);
const [error, setError] = useState<string>('');
const [settings, setSettigs] = useState<boolean>(false);
const [isSpotifyAuth, setIsSpotifyAuth] = useState(false);
const [playing, setPlaying] = useState<PlayerProps>();
const navigate = useNavigate();
function LeaveRoom() {
const requestOptions: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
};
fetch('/api/leave-room/', requestOptions)
.then((response) => response.json())
.then((data) => {
if (data.message) {
console.log('leaving room ', data);
navigate('/');
}
});
}
function checkAuth() {
const requestOptions: RequestInit = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
};
fetch('/spotify/is-auth', requestOptions)
.then((response) => response.json())
.then((data) => {
if (data.status) {
setIsSpotifyAuth(true);
console.log('is-auth response', data.status);
}
});
}
function renderSettingsButton() {
return (
<Grid size={12} alignContent="center">
<Button variant="contained" color="primary" onClick={() => setSettigs(true)}>
Settings
</Button>
<Button variant="contained" color="warning" onClick={() => authenticateSpotify()}>
Login To Spotify
</Button>
</Grid>
);
}
function renderSerrings() {
return (
<Grid container spacing={1}>
<Grid size={12} alignContent="center">
<CreateRoomPage
update={true}
votes_to_skip={votesToSkip}
allowPause={guestCanPause}
roomCode={roomCode || null}
/>
</Grid>
<Grid size={12} alignContent="center">
<Button variant="contained" color="secondary" onClick={() => setSettigs(false)}>
Exit settings
</Button>
</Grid>
</Grid>
);
}
// on maunt and settings change
useEffect(() => {
if (!roomCode) {
setError('No room code provided');
return;
}
fetch('/api/get-room/?code=' + roomCode, {
credentials: 'include',
})
.then((response) => {
if (!response.ok) {
navigate('/home');
}
roomCode = undefined;
return response.json();
})
.then((data: roomData) => {
console.log('data:', data);
setVotesToSkip(data.votes_to_skip);
setGuestCanPause(data.guest_can_pause);
console.log('data.isHost', data.isHost);
setIsHost(data.isHost);
})
.catch((err) => {
setError(err.message);
});
}, [settings]);
///get playing song
useEffect(() => {
function getSong() {
fetch('/spotify/current-song', {
credentials: 'include',
})
.then((response) => response.json())
.then((data) => {
console.log('📡 fetchData called : ', data);
setPlaying(data);
})
.catch((err) => {
console.log('❌ Error fetching data:', err);
});
}
checkAuth();
if (isSpotifyAuth === true) {
getSong();
const intervalID = setInterval(() => {
getSong();
}, 1000);
return () => {
clearInterval(intervalID);
};
}
console.log('isSpotifyAuth ', isSpotifyAuth);
}, [isSpotifyAuth]);
function authenticateSpotify() {
if (isHost && !isSpotifyAuth) {
setIsSpotifyAuth(true);
console.log('isSpotifyAuth.current:', isSpotifyAuth);
fetch('/spotify/is-auth', {
credentials: 'include',
})
.then((response) => response.json())
.then((data: SpotifyAuthResponse) => {
// isSpotifyAuth.current = data.status;
if (!data.status) {
fetch(`/spotify/get-auth-url?state=${roomCode}`, {
credentials: 'include',
}).then((response) =>
response.json().then((data) => {
//redirect to spotify upstream auth
window.location.replace(data.url);
return;
}),
);
}
});
} else {
console.log('Clicked Utenticate button ');
console.log('isSpotifyAuth:', isSpotifyAuth);
return;
}
}
if (error) {
return <div>Error: {error}</div>;
}
if (settings) {
console.log('rendering settings', settings);
return renderSerrings();
} else {
return (
<Stack spacing={2} sx={{ maxWidth: 600, mx: 'auto', p: 2 }}>
<Typography variant="h4">Room: {roomCode}</Typography>
{playing ? <Player {...playing} /> : <Typography variant="h4">Nothing playing</Typography>}
<Typography variant="h6">Votes to Skip: {votesToSkip}</Typography>
<Typography variant="h6">Guest Can Pause: {guestCanPause ? 'Yes' : 'No'}</Typography>
<Typography variant="h6">Is Host: {isHost ? 'Yes' : 'No'}</Typography>
{isHost ? renderSettingsButton() : null}
<Button variant="contained" color="secondary" onClick={LeaveRoom}>
Leave Room
</Button>
</Stack>
);
}
}
export default Room;
+18
View File
@@ -0,0 +1,18 @@
export function getCookie(name: string): string | null {
const cookies = document.cookie.split('; ');
for (const cookie of cookies) {
const [key, value] = cookie.split('=');
if (key === name) return decodeURIComponent(value);
}
return null;
}
// Usage
//const session = getCookie("sessionid");
export function deleteCookie(name: string): void {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
// Usage
// deleteCookie("sessionid");
+11
View File
@@ -0,0 +1,11 @@
.AlertComponent {
all: revert;
/* or: all: initial; */
position: fixed;
left: 50%;
bottom: max(16px, env(safe-area-inset-bottom));
/* iOS safe area friendly */
transform: translateX(-50%);
display: inline-block;
z-index: 9999;
}
+6
View File
@@ -0,0 +1,6 @@
.center {
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
}
+24
View File
@@ -0,0 +1,24 @@
export interface roomData {
code: number;
created_at: string;
guest_can_pause: boolean;
host: string;
id: number;
isHost: boolean;
votes_to_skip: number;
}
export type SpotifyAuthResponse = {
status: boolean;
};
export interface PlayerProps {
title: string;
artist: string;
duration: number;
time: number;
image_url: string;
is_playing: boolean;
votes: number;
id: string;
}
+9
View File
@@ -0,0 +1,9 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
+68
View File
@@ -0,0 +1,68 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />