mastoradio/src/store.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-01-16 20:10:40 +01:00
import { writable, derived, get } from 'svelte/store'
2020-01-20 03:26:18 +01:00
import { writableLocalStorage } from '/services/svelte.js'
import { hashtagIterator } from '/services/mastodon.js'
import { mkTracksIterator } from '/services/misc.js'
2020-01-16 20:10:40 +01:00
export const domain = writableLocalStorage('domain', 'eldritch.cafe')
export const hashtags = writableLocalStorage('hashtags', [
'np',
'nowplaying',
'tootradio',
'pouetradio'
])
2020-01-20 04:49:38 +01:00
const tracksIterator = mkTracksIterator(hashtagIterator(get(domain), get(hashtags)[0]))
2020-01-18 05:13:38 +01:00
export const paused = writable(true)
2020-01-16 20:10:40 +01:00
export const muted = writableLocalStorage('muted', false)
export const volume = writableLocalStorage('volume', 100)
2020-01-20 04:49:38 +01:00
export const next = writable(null)
2020-01-16 20:10:40 +01:00
export const enqueueing = writable(false)
2020-01-20 04:49:38 +01:00
export const queue = writable([])
export const index = writable(null)
2020-01-16 20:10:40 +01:00
export const current = derived([queue, index], ([$queue, $index]) => $queue[$index])
2020-01-20 04:49:38 +01:00
export const canPrevious = derived([index, queue], ([$index, $queue]) => $index !== null && $index < $queue.length - 1)
export const canNext = derived([index, next], ([$index, $next]) => $index !== null && ($index > 0 || $next !== null))
2020-01-16 20:10:40 +01:00
export const loading = writable(false)
2020-01-20 04:49:38 +01:00
next.subscribe(async $next => {
if ($next === null) {
if (!get(enqueueing)) {
enqueueing.set(true)
2020-01-16 20:10:40 +01:00
2020-01-20 04:49:38 +01:00
const { value: newTrack } = await tracksIterator.next()
2020-01-16 20:10:40 +01:00
2020-01-20 04:49:38 +01:00
if (newTrack) {
next.set(newTrack)
}
2020-01-20 03:26:18 +01:00
2020-01-20 04:49:38 +01:00
enqueueing.set(false)
}
}
})
2020-01-16 20:10:40 +01:00
2020-01-20 04:49:38 +01:00
export const selectPrevious = () => {
if (get(canPrevious)) {
index.update($index => $index + 1)
}
}
2020-01-20 03:26:18 +01:00
2020-01-20 04:49:38 +01:00
export const selectNext = () => {
if (get(canNext)) {
const $index = get(index)
2020-01-16 20:10:40 +01:00
2020-01-20 04:49:38 +01:00
if ($index === 0) {
queue.update($queue => {
const $next = get(next)
next.set(null)
2020-01-16 20:10:40 +01:00
2020-01-20 04:49:38 +01:00
return [$next, ...$queue]
})
} else {
index.update($index => $index - 1)
2020-01-16 20:10:40 +01:00
}
}
}