Merge pull request #10 from Maathias/voting

Voting
This commit was merged in pull request #10.
This commit is contained in:
Mateusz Pstrucha authored and GitHub committed 2021-09-13 21:46:38 +02:00
commit 7849cad09f
25 files changed
+466 -151

No files matched your search

+10
View File
@@ -6561,6 +6561,11 @@
}
}
},
"fast-average-color": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/fast-average-color/-/fast-average-color-6.4.2.tgz",
"integrity": "sha512-aVtrSOl5m9E3dSzJTQZtm4rgAtTjTILhlLDK8UB+nseLr4Ss+rtDUVESPEGERiQ/tNckWCECQtxGvo1ickd6yA=="
},
"fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -12540,6 +12545,11 @@
"resolved": "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.9.tgz",
"integrity": "sha512-nQTTcUu+ATDbrSD1BZHr5kgSD4oF8OFjxun8uAaL8RwPBacGBNPf/yAuVVdx17N8XNzRDMrZ9XcKZHCjPW+9ew=="
},
"react-ga": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/react-ga/-/react-ga-3.3.0.tgz",
"integrity": "sha512-o8RScHj6Lb8cwy3GMrVH6NJvL+y0zpJvKtc0+wmH7Bt23rszJmnqEQxRbyrqUzk9DTJIHoP42bfO5rswC9SWBQ=="
},
"react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+3 -1
View File
@@ -7,9 +7,11 @@
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"fast-average-color": "^6.4.2",
"ky": "^0.28.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-ga": "^3.3.0",
"react-router-dom": "^5.2.1",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
@@ -39,4 +41,4 @@
"last 1 safari version"
]
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

+16 -15
View File
@@ -1,25 +1,26 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"version": "1.3.0",
"short_name": "radio-rolnik",
"name": "Radio Rolnik Nysa",
"description": "",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
"src": "/media/icon_512.png",
"type": "image/png",
"sizes": "512x512",
"purpose": "maskable"
},
{
"src": "logo192.png",
"src": "/media/icon_256.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
"sizes": "256x256"
}
],
"start_url": ".",
"start_url": "/",
"scope": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
"orientation": "portrait",
"background_color": "#313131",
"theme_color": "#ca3e47",
"lang": "pl"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+88 -5
View File
@@ -2,17 +2,100 @@ import ky from 'ky'
var tracks = {}
class Track {
constructor(tdata) {
Object.assign(this, tdata)
this.stats = {
up: -1,
down: -1,
}
this.rank = -1
this.cast = ''
this.getVote()
}
get listen() {
return `https://open.spotify.com/track/${this.id}`
}
get share() {
return `https://${document.location.origin}/utwor/${this.id}`
}
setVote(value) {
return new Promise((resolve, reject) => {
if (value === this.cast) return
ky.patch(`/api/vote/${this.id}`, { json: { uid: 'mathias', value } })
.json()
.then((ok) => {
if (ok) {
this.cast = value
this.getStats()
}
resolve(ok)
})
.catch((err) => reject(err))
})
}
getVote() {
return new Promise((resolve, reject) => {
ky.get(`/api/vote/${this.id}/cast`, { searchParams: { uid: 'mathias' } })
.text()
.then((cast) => {
this.cast = cast
resolve(cast)
})
.catch((err) => {
console.error(err)
})
})
}
getStats() {
return new Promise((resolve, reject) => {
getStats(this.id)
.then((stats) => {
this.stats = stats
resolve(stats)
})
.catch((err) => {
console.error(err)
})
})
}
}
function getStats(id) {
return new Promise((resolve, reject) => {
ky.get(`/api/vote/${id}`)
.json()
.then((stats) => {
resolve(stats)
})
.catch((err) => reject(err))
})
}
function get(id) {
return new Promise((resolve, reject) => {
if (typeof tracks[id] === 'undefined') {
download(id).then((track) => resolve(track))
download(id)
.then((track) => resolve(track))
.catch((err) => reject(err))
} else resolve(tracks[id])
})
}
function getMultiple(ids) {
return new Promise((resolve, reject) => {
Promise.all(ids.map((id) => get(id))).then((tracks) => resolve(tracks))
Promise.all(ids.map((id) => get(id)))
.then((tracks) => resolve(tracks))
.catch((err) => {
console.error(err)
})
})
}
@@ -21,8 +104,8 @@ function download(id) {
ky.get('/api/track/' + id)
.json()
.then((track) => {
tracks[track.id] = track
resolve(track)
tracks[track.id] = new Track(track)
resolve(tracks[track.id])
})
.catch((err) => reject(err))
})
@@ -37,4 +120,4 @@ function search(query) {
})
}
export { tracks, get, getMultiple, search }
export { tracks, get, getMultiple, search, getStats }
+23
View File
@@ -0,0 +1,23 @@
import FastAverageColor from 'fast-average-color'
var fac = new FastAverageColor(),
def = document.documentElement.style.getPropertyValue('--deg')
function setColor(target, lvl) {
fac
.getColorAsync(target)
.then(({ value: [r, g, b] }) => {
let color =
Math.atan2(1.732050808 * (g - b), 2 * r - g - b) * 57.295779513
return color
})
.catch((err) => {
return def
})
.then((color) => {
document.documentElement.style.setProperty('--deg', color + 'deg')
})
}
export { setColor }
+11
View File
@@ -15,4 +15,15 @@
.history-section.now > .track {
background-color: var(--main);
box-shadow: 2px 2px 4px #6363637d;
color: #fffd;
}
.history-section.now > .track .track-artist,
.history-section.now > .track .track-timestamp {
color: #fffa;
}
.history-section.next > .track .track-timestamp,
.history-section.now > .track .track-timestamp {
font-size: 1.25em;
}
+3 -3
View File
@@ -14,13 +14,13 @@ function History({ next, tracks }) {
{next && (
<div className="history-section next">
<span>Następny:</span>
<Track {...next} timestamp=">" />
<Track track={next} timestamp=">" />
</div>
)}
<div className="history-section now">
<span>Gra teraz:</span>
<Track {...playing} timestamp="~" />
<Track track={playing} timestamp="~" />
</div>
<div className="history-section previous">
@@ -30,7 +30,7 @@ function History({ next, tracks }) {
? new Date(track.timestamp).toISOString().slice(11, 16)
: '-:-'
return <Track key={track.id} {...track} timestamp={time} />
return <Track key={track.id} track={track} timestamp={time} />
})}
</div>
</div>
-5
View File
@@ -1,5 +0,0 @@
function Home() {
return <div className="home"></div>
}
export default Home
+25 -3
View File
@@ -22,7 +22,6 @@
background: linear-gradient(180deg, white, transparent);
height: 100%;
padding: 1em;
padding-bottom: 6em;
box-shadow: 0 -1px 11px 2px #6b6b6b52;
}
@@ -36,10 +35,12 @@
font-size: 0.75em;
background-color: var(--light);
margin: 1em 0;
display: flex;
}
.info-balance > div {
display: inline-block;
min-width: 2em;
}
.info-balance > .up {
@@ -61,13 +62,34 @@
padding: 0;
}
.info-list > div > i {
.info-list > .buttons > i {
cursor: pointer;
width: 100%;
font-size: 1.5em;
padding: 0.25em;
}
.info-list > .buttons > i[data-set='true'] {
background-color: var(--light);
color: var(--main);
cursor: default;
}
.info-list > div > i:hover {
background-color: #cccc;
/* background-color: #cccc; */
color: var(--main);
}
.info-data {
text-align: left;
font-size: 0.7em;
color: #6666;
padding: 0.1em 0 0 0.5em;
user-select: all;
}
.info-meta {
padding-bottom: 0.3em;
font-size: 0.9em;
display: inline-block;
}
+128 -30
View File
@@ -1,28 +1,75 @@
import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { useContext, useEffect, useState } from 'react'
import { useParams, Redirect } from 'react-router-dom'
import { get } from '../../Cache'
import PlayingContext from '../../contexts/Playing'
import './Info.css'
var last
function Info() {
const { id } = useParams(),
[track, setTrack] = useState({
title: 'Tytuł',
votes: {},
title: '-',
stats: {},
album: {},
artists: ['Autor'],
})
artists: ['-'],
}),
[meta, setMeta] = useState('...'),
playing = useContext(PlayingContext)
if (!id) last = playing.id ?? ''
else last = id
useEffect(() => {
get(id).then((track) => {
setTrack(track)
})
}, [id])
setMeta(`Pobieranie... ${last}`)
get(last)
.then((track) => {
track
.getStats()
.then((stats) => {
track
.getVote()
.then(() => {
setTrack(track)
setMeta(false)
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
})
.catch((err) => {
setMeta(`Wystąpił błąd przy pobieraniu informacji o utworze`)
})
}, [last]) // eslint-disable-line
const percent = (track.votes.up / (track.votes.up + track.votes.down)) * 100
if (!id && last) return <Redirect to={`/utwor/${last}`} />
document.title = `${track.title} | radio-rolnik`
function vote(value) {
track
.setVote(value)
.then((ok) => {
track
.getStats()
.then(() => {
ok
? setMeta(`Zmieniono głos na ${{ up: '👍', down: '👎' }[value]}`)
: setMeta('Wystąpił bład przy zmienianiu głosu')
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
}
const total = track.stats.up + track.stats.down,
percent =
total > 0
? (track.stats.up / (track.stats.up + track.stats.down)) * 100
: 50
document.setTitle(track.title)
return (
<div className="wrapper info">
@@ -36,30 +83,81 @@ function Info() {
<span className="artist">{track.artists[0]}</span>
<div className="info-balance">
<div className="up" style={{ width: `${percent}%` }}>
{track.votes.up}&nbsp;
{track.stats.up}&nbsp;
</div>
<div className="down" style={{ width: `${100 - percent}%` }}>
{track.votes.down}
{track.stats.down}
</div>
</div>
<div className="info-list">
<div>
<i className="icon-thumbs-up"></i>
<i className="icon-thumbs-down"></i>
{meta && <span className="info-meta">{meta}</span>}
{track.id && (
<div className="info-list">
<div className="buttons">
<i
className="icon-thumbs-up"
data-set={track.cast === 'up'}
onClick={(e) => vote('up')}
></i>
<i
className="icon-thumbs-down"
data-set={track.cast === 'down'}
onClick={(e) => vote('down')}
></i>
</div>
<div className="buttons">
<i
className="icon-export"
onClick={(e) => {
if (navigator.share)
navigator.share({
url: track.share,
title: 'radio-rolnik',
text: `Sprawdź "${track.title}" na radio-rolnik`,
})
}}
></i>
<i
className="icon-music"
onClick={(e) => {
window.open(track.listen)
}}
></i>
<i
className="icon-flag"
onClick={(e) => {
window.confirm(`Napewno chcesz zgłosić ten utwór?`) &&
track.setVote('report')
}}
></i>
</div>
<div>
<span>{track.artists.join(', ')}</span>
</div>
<div>
<span>
{track.album.name ?? '-'} ({track.album.year ?? '-'})
</span>
</div>
<div>Liczba głosów: {total}</div>
<div>Miejsce: #{track.stats.rank}</div>
{track.banned && (
<div>
<span>
Utwór zablokowany <i className="icon-cancel-circled"></i>
</span>
</div>
)}
</div>
<div>
<i className="icon-export"></i>
<i className="icon-music"></i>
<i className="icon-flag"></i>
</div>
<div>{`${track.title} - ${track.artists.join(', ')} - ${
track.album.name
} (${track.album.year})`}</div>
<div>Liczba głosów: {track.votes.up + track.votes.down}</div>
<div>Miejsce: {track.votes.rank}</div>
<div>Zablokowane: {track.banned ? 'Tak' : 'Nie'}</div>
</div>
)}
</div>
<span className="info-data">{id}</span>
</div>
)
}
+2 -1
View File
@@ -5,7 +5,7 @@
justify-content: flex-end;
background-color: var(--light);
font-family: 'Quicksand';
overflow: hidden auto;
overflow: hidden;
}
.wrapper {
@@ -13,4 +13,5 @@
margin: auto;
box-sizing: border-box;
padding-bottom: 8em;
overflow-y: auto;
}
+74 -53
View File
@@ -5,7 +5,7 @@ import {
Redirect,
} from 'react-router-dom'
import { useEffect, useState } from 'react'
import ky from 'ky'
import ga from 'react-ga'
import Nav from '../Nav/Nav'
import History from '../History/History'
@@ -18,11 +18,21 @@ import { get, getMultiple } from '../../Cache'
import { addEvent } from '../../socket'
import PlayingContext from '../../contexts/Playing'
import GaContext from '../../contexts/Ga'
import './Main.css'
ga.initialize('UA-150749288-3')
document.setTitle = (prefix, suffix) => {
document.title = `${prefix} | ${suffix ?? 'radio-rolnik'}`
const title = `${prefix} | ${suffix ?? 'radio-rolnik'}`
// dont repeat same title
if (document.title === title) return
document.title = title
ga.pageview(document.location.pathname)
}
function Main() {
@@ -35,74 +45,85 @@ function Main() {
useEffect(() => {
addEvent('status', ({ trackid, progress, paused }) => {
get(trackid).then((track) => {
setPlaying(track)
setElapsed(progress)
setPaused(paused)
})
get(trackid)
.then((track) => {
setPlaying(track)
setElapsed(progress)
setPaused(paused)
})
.catch((err) => {
setPaused(true)
})
})
addEvent('next', ({ trackid }) => {
get(trackid).then((track) => {
setNext(track)
})
get(trackid)
.then((track) => {
setNext(track)
})
.catch((err) => console.error(err))
})
addEvent('previous', ({ trackids, timestamps }) => {
getMultiple(trackids).then((tracks) =>
// insert timestamps to tracks
setPrevious(
tracks.map((track, i) => ({ ...track, timestamp: timestamps[i] }))
)
)
getMultiple(trackids)
.then((tracks) => {
// insert timestamps to tracks
tracks.map((track, i) => (track.timestamp = timestamps[i]))
setPrevious(tracks)
})
.catch((err) => console.error(err))
})
addEvent('top', ({ trackids }) => {
getMultiple(trackids).then((tracks) => setTop(tracks))
getMultiple(trackids)
.then((tracks) => setTop(tracks))
.catch((err) => console.error(err))
})
}, [])
return (
<PlayingContext.Provider value={playing}>
<div className="main">
<Router>
<Switch>
<Route exact path="/">
<History next={next} tracks={previous} />
</Route>
<GaContext.Provider value={ga}>
<PlayingContext.Provider value={playing}>
<div className="main">
<Router>
<Switch>
<Route exact path="/">
<History next={next} tracks={previous} />
</Route>
<Route path="/utwor/:id">
<Info />
</Route>
<Route path="/utwor/:id?">
<Info />
</Route>
<Route path="/top">
<Top tracks={top} />
</Route>
<Route path="/top">
<Top tracks={top} />
</Route>
<Route path="/wyszukaj/:query?">
<Search />
</Route>
<Route path="/wyszukaj/:query?">
<Search />
</Route>
<Route render={() => <Redirect to="/" />} />
</Switch>
<Nav
buttons={[
{ label: 'Historia', to: '/', icon: 'align-left' },
{ label: 'Wyszukaj', to: '/wyszukaj', icon: 'search' },
{ label: 'Top', to: '/top', icon: 'list-numbered' },
{
label: 'Utwór',
path: '/utwor',
to: `/utwor/${playing.id}`,
icon: 'info',
},
{ label: 'Ustawienia', to: '/ustawienia', icon: 'cog-alt' },
]}
/>
<Status progress={elapsed} paused={paused} />
</Router>
</div>
</PlayingContext.Provider>
<Route render={() => <Redirect to="/" />} />
</Switch>
<Nav
buttons={[
{ label: 'Historia', to: '/', icon: 'align-left' },
{ label: 'Wyszukaj', to: '/wyszukaj', icon: 'search' },
{ label: 'Top', to: '/top', icon: 'list-numbered' },
{
label: 'Utwór',
path: '/utwor',
to: `/utwor`,
icon: 'info',
},
{ label: 'Ustawienia', to: '/ustawienia', icon: 'cog-alt' },
]}
/>
<Status progress={elapsed} paused={paused} />
</Router>
</div>
</PlayingContext.Provider>
</GaContext.Provider>
)
}
+1 -1
View File
@@ -46,7 +46,7 @@ function Nav({ buttons }) {
})()
// don't update for custom titles
label && (document.title = `${label} | radio-rolnik`)
label && document.setTitle(label)
}, [location]) // eslint-disable-line
return (
+1 -1
View File
@@ -74,7 +74,7 @@ function Search() {
</span>
)}
{results.map((track) => {
return <Track key={track.id} {...track} />
return <Track key={track.id} track={track} />
})}
</div>
</div>
+7 -1
View File
@@ -1,11 +1,13 @@
import { useContext, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { setColor } from '../../Color'
import PlayingContext from '../../contexts/Playing'
import './Status.css'
function Status({ progress, paused, onEnd }) {
function Status({ progress, paused }) {
const {
id,
title = '-',
@@ -18,6 +20,10 @@ function Status({ progress, paused, onEnd }) {
const step = 500,
tread = step / duration
useEffect(() => {
if (album.art) setColor(album.art, 1)
}, [album.art])
useEffect(() => {
setElapsed(progress ? progress / duration : 0)
}, [progress, duration])
+1 -1
View File
@@ -6,7 +6,7 @@ function Top(props) {
return (
<div className="wrapper top">
{props.tracks.map((track, rank) => {
return <Track key={track.id} rank={rank + 1} {...track} />
return <Track key={track.id} rank={rank + 1} track={track} />
})}
</div>
)
+17 -5
View File
@@ -29,6 +29,11 @@
user-select: none;
}
.track-timestamp {
font-size: 0.75em;
margin-left: -0.4em;
}
.track-section-b {
width: 100%;
overflow: hidden;
@@ -37,11 +42,12 @@
display: flex;
flex-direction: row;
align-items: center;
margin-right: 1em;
}
.track-timestamp {
font-size: 0.75em;
margin-left: -0.4em;
.track-section-a,
.track-section-b {
cursor: pointer;
}
.track-rank:before {
@@ -68,12 +74,12 @@
.track-icons {
float: right;
padding: 0 0.5em;
margin: auto;
}
.track-icons > i {
cursor: pointer;
padding: 0.5em;
}
.track-more {
@@ -84,7 +90,7 @@
top: 0;
border-radius: inherit;
background: hsl(12deg, 4%, 20%);
transition: 0.3s ease-in-out;
transition: 0.3s cubic-bezier(0.7, 0, 0.3, 1);
display: flex;
flex-direction: row;
@@ -112,6 +118,12 @@
width: 100%;
}
.track-more-button > i[data-set='true'] {
background-color: var(--dark);
color: var(--main);
cursor: default;
}
.track-more-button:hover {
background-color: #fff2;
}
+50 -25
View File
@@ -1,20 +1,36 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { Link, useHistory } from 'react-router-dom'
import './Track.css'
function Track({
id,
title = '-',
artists = ['-'],
album = {},
timestamp,
rank,
}) {
const [open, setOpen] = useState(false)
function Track({ track, timestamp, rank }) {
const [open, setOpen] = useState(false),
{
id,
title = '-',
artists = ['-'],
album = {},
votes = {},
cast = '',
} = track ?? {},
history = useHistory()
function vote(value) {
track
.setVote(value)
.then((ok) => ok && setOpen(false))
.catch((err) => console.error(err))
}
function info() {
history.push(`/utwor/${id}`)
}
return (
<div className={['track', open ? 'open' : ''].join(' ')}>
<div className={'track-section-a ' + (timestamp || rank ? '' : 'empty')}>
<div className={['track', open ? 'open' : ''].join(' ')} id={id}>
<div
className={'track-section-a ' + (timestamp || rank ? '' : 'empty')}
onClick={() => info()}
>
{timestamp && <span className="track-timestamp">{timestamp}</span>}
{rank && <span className="track-rank">{rank}</span>}
<img
@@ -24,10 +40,8 @@ function Track({
/>
</div>
<div className="track-section-b">
<Link to={`/utwor/${id}`} className="track-title">
{title}
</Link>
<div className="track-section-b" onClick={() => info()}>
<span className="track-title">{title}</span>
<span className="track-artist">{artists.join(', ')}</span>
</div>
@@ -41,21 +55,32 @@ function Track({
</div>
<div className="track-more">
<div className="track-more-button">
<i className="icon-thumbs-up"></i>
<i
className="icon-thumbs-up"
data-set={cast === 'up'}
onClick={(e) => vote('up')}
></i>
</div>
<div className="track-more-button">
<i className="icon-thumbs-down"></i>
<i
className="icon-thumbs-down"
data-set={cast === 'down'}
onClick={(e) => vote('down')}
></i>
</div>
<Link to={`/utwor/${id}`} className="track-more-button">
<i className="icon-info"></i>
</Link>
<div
className="track-more-button"
onClick={() => {
setOpen(false)
}}
>
<i className="icon-cancel-circled"></i>
<div className="track-more-button">
<i
className="icon-cancel-circled"
onClick={() => {
setOpen(false)
}}
></i>
</div>
</div>
</div>
+5
View File
@@ -0,0 +1,5 @@
import { createContext } from "react";
const GaContext = createContext('ga')
export default GaContext
+1 -1
View File
@@ -8,7 +8,7 @@ body {
}
:root {
--deg: 170deg;
--deg: 0deg;
--white: hsl(0, 0%, 100%);
--light: hsl(var(--deg) 50% 88%);
--main: hsl(var(--deg), 57%, 52%);