| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599 |
- import { useMemo, useState } from 'react'
- import Toggle from '../common/Toggle'
- import ResizableWidth from '../common/ResizableWidth'
- import { Reorderable, useReorder } from '../common/Reorderable'
- import { useQueryClient } from '@tanstack/react-query'
- import {
- ListVideo,
- Plus,
- Pencil,
- Trash2,
- Play,
- Pause,
- Square,
- SkipForward,
- SkipBack,
- Shuffle,
- Film,
- Heart,
- ArrowDownWideNarrow,
- CalendarClock
- } from 'lucide-react'
- import clsx from 'clsx'
- import type { PlaylistMode, PlaylistSettings, ScreenTarget } from '@shared/types'
- import PlaylistItemRow from './PlaylistItemRow'
- import WallpaperPickerModal from './WallpaperPickerModal'
- import DetailSidebar from '../common/DetailSidebar'
- import WallpaperContextMenu from '../common/WallpaperContextMenu'
- import { useAllWallpapers, usePlaybackStates, usePlaylists } from '../../hooks/queries'
- import { useFavoriteIds } from '../../hooks/useFavorites'
- import { useApplyWallpaper, useSubscribe, useUnsubscribe } from '../../hooks/useWallpaperActions'
- import { detailSidebarProps } from '../../utils/wallpaper'
- import ScreenSelect from '../common/ScreenSelect'
- import { useDisplayTargets } from '../../hooks/useDisplayTargets'
- import { screenLabel } from '../../utils/screens'
- import { t } from '../../i18n'
- import type { MessageKey } from '@shared/i18n'
- const MODE_OPTIONS: { value: PlaylistMode; label: MessageKey }[] = [
- { value: 'timer', label: 'playlist.modeTimer' },
- { value: 'daytime', label: 'playlist.modeDaytime' },
- { value: 'dayofweek', label: 'playlist.modeDayOfWeek' },
- { value: 'logon', label: 'playlist.modeLogon' }
- ]
- const MODE_HINTS: Record<Exclude<PlaylistMode, 'timer'>, MessageKey> = {
- daytime: 'playlist.modeDaytimeHint',
- dayofweek: 'playlist.modeDayOfWeekHint',
- logon: 'playlist.modeLogonHint'
- }
- const SORT_OPTIONS: { value: PlaylistSettings['sortBy']; label: MessageKey }[] = [
- { value: 'manual', label: 'playlist.sortManual' },
- { value: 'title', label: 'playlist.sortTitle' },
- { value: 'createdAt', label: 'playlist.sortAdded' }
- ]
- interface PlaylistsViewProps {
- onBrowseCreator?: (creatorSteamId: string) => void
- }
- export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
- const queryClient = useQueryClient()
- const [activePlaylistId, setActivePlaylistId] = useState<string | null>(null)
- const [creating, setCreating] = useState(false)
- const [newTitle, setNewTitle] = useState('')
- const [renamingId, setRenamingId] = useState<string | null>(null)
- const [renameValue, setRenameValue] = useState('')
- const [pickerOpen, setPickerOpen] = useState(false)
- const [dragIndex, setDragIndex] = useState<number | null>(null)
- const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)
- const [error, setError] = useState<string | null>(null)
- const [detailId, setDetailId] = useState<string | null>(null)
- const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number; wallpaperId: string } | null>(null)
- const savedPlaylists = usePlaylists()
- const playlistOrder = useReorder('we-playlist-order', savedPlaylists.map((p) => p.id))
- const playlists = useMemo(
- () => playlistOrder.sortItems(savedPlaylists, (p) => p.id),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [savedPlaylists, playlistOrder.order]
- )
- const wallpapers = useAllWallpapers()
- const wallpaperById = useMemo(() => new Map(wallpapers.map((w) => [w.id, w])), [wallpapers])
- const playbackStates = usePlaybackStates()
- const { targets, perScreen } = useDisplayTargets()
- const [screen, setScreen] = useState<ScreenTarget>('*')
- const applyWallpaper = useApplyWallpaper()
- const subscribe = useSubscribe()
- const unsubscribe = useUnsubscribe()
- const activePlaylist = playlists.find((p) => p.id === activePlaylistId) ?? null
- const mode: PlaylistMode = activePlaylist?.settings.mode ?? 'timer'
- const favoriteIds = useFavoriteIds()
- const favoriteCount = activePlaylist?.items.filter((i) => favoriteIds.has(i.wallpaperId)).length ?? 0
- function invalidatePlaylists() {
- void queryClient.invalidateQueries({ queryKey: ['playlists'] })
- }
- async function handleCreate() {
- if (!newTitle.trim()) {
- setCreating(false)
- return
- }
- const playlist = await window.electronAPI.playlist.create(newTitle.trim())
- setNewTitle('')
- setCreating(false)
- invalidatePlaylists()
- setActivePlaylistId(playlist.id)
- }
- async function handleRename(id: string) {
- if (!renameValue.trim()) {
- setRenamingId(null)
- return
- }
- await window.electronAPI.playlist.rename(id, renameValue.trim())
- setRenamingId(null)
- invalidatePlaylists()
- }
- async function handleDelete(id: string) {
- await window.electronAPI.playlist.delete(id)
- if (activePlaylistId === id) setActivePlaylistId(null)
- invalidatePlaylists()
- void queryClient.invalidateQueries({ queryKey: ['playlist-playback-state'] })
- }
- async function updateSettings(patch: Partial<PlaylistSettings>) {
- if (!activePlaylist) return
- await window.electronAPI.playlist.updateSettings(activePlaylist.id, patch)
- invalidatePlaylists()
- }
- async function handleAddWallpapers(wallpaperIds: string[]) {
- if (!activePlaylist) return
- await window.electronAPI.playlist.addItems(activePlaylist.id, wallpaperIds)
- setPickerOpen(false)
- invalidatePlaylists()
- }
- async function handleRemoveItem(wallpaperId: string) {
- if (!activePlaylist) return
- await window.electronAPI.playlist.removeItems(activePlaylist.id, [wallpaperId])
- invalidatePlaylists()
- }
- async function handleUpdateItem(
- wallpaperId: string,
- patch: { volume?: number; durationSec?: number; endMinute?: number }
- ) {
- if (!activePlaylist) return
- await window.electronAPI.playlist.updateItem(activePlaylist.id, wallpaperId, patch)
- invalidatePlaylists()
- }
- function openItemCtxMenu(e: React.MouseEvent, wallpaperId: string) {
- e.preventDefault()
- setCtxMenu({ x: e.clientX, y: e.clientY, wallpaperId })
- }
- function handleDragStart(index: number) {
- setDragIndex(index)
- }
- function handleDragOver(index: number) {
- setDragOverIndex(index)
- }
- async function handleDrop() {
- if (!activePlaylist || dragIndex === null || dragOverIndex === null || dragIndex === dragOverIndex) {
- setDragIndex(null)
- setDragOverIndex(null)
- return
- }
- const order = activePlaylist.items.map((i) => i.wallpaperId)
- const [moved] = order.splice(dragIndex, 1)
- order.splice(dragOverIndex, 0, moved)
- setDragIndex(null)
- setDragOverIndex(null)
- await window.electronAPI.playlist.reorderItems(activePlaylist.id, order)
- invalidatePlaylists()
- }
- async function handlePlay() {
- if (!activePlaylist) return
- setError(null)
- try {
- await window.electronAPI.playlist.start(activePlaylist.id, screen)
- void queryClient.invalidateQueries({ queryKey: ['playlist-playback-state'] })
- } catch (err) {
- setError((err as Error).message)
- }
- }
- async function handlePlayItem(wallpaperId: string) {
- if (!activePlaylist) return
- const playingIt = thisStates.filter((s) => s.isPlaying && s.currentItemId === wallpaperId)
- if (playingIt.length > 0) {
- for (const s of playingIt) await window.electronAPI.playlist.pause(s.screen)
- void queryClient.invalidateQueries({ queryKey: ['playlist-playback-state'] })
- return
- }
- setError(null)
- try {
- await window.electronAPI.playlist.playItem(activePlaylist.id, wallpaperId, isThisPlaylistActive ? undefined : screen)
- void queryClient.invalidateQueries({ queryKey: ['playlist-playback-state'] })
- } catch (err) {
- setError((err as Error).message)
- }
- }
- // controls act on every screen this playlist plays on, narrowed down by the screen picker
- async function forEachScreen(action: (screen: ScreenTarget) => Promise<unknown>) {
- for (const s of thisStates) await action(s.screen)
- void queryClient.invalidateQueries({ queryKey: ['playlist-playback-state'] })
- }
- const handlePauseResume = () =>
- forEachScreen((s) => (isPlaying ? window.electronAPI.playlist.pause(s) : window.electronAPI.playlist.resume(s)))
- const handleStop = () => forEachScreen((s) => window.electronAPI.playlist.stop(s))
- const handleNext = () => forEachScreen((s) => window.electronAPI.playlist.next(s))
- const handlePrevious = () => forEachScreen((s) => window.electronAPI.playlist.previous(s))
- const thisStates = playbackStates.filter(
- (s) => s.playlistId === activePlaylist?.id && (screen === '*' || s.screen === screen)
- )
- const isThisPlaylistActive = thisStates.length > 0
- const isPlaying = thisStates.some((s) => s.isPlaying)
- const currentItemIds = new Set(thisStates.map((s) => s.currentItemId))
- const ctxWallpaper = ctxMenu ? wallpaperById.get(ctxMenu.wallpaperId) : undefined
- const detailWallpaper = detailId ? wallpaperById.get(detailId) : undefined
- const existingIds = useMemo(
- () => new Set(activePlaylist?.items.map((i) => i.wallpaperId) ?? []),
- [activePlaylist]
- )
- return (
- <div className="flex h-full">
- <ResizableWidth storageKey="we-playlist-panel-width" defaultWidth={224} min={160} max={400} edge="right">
- <div className="flex w-full flex-col border-r border-fg/5 overflow-y-auto">
- <div className="flex items-center justify-between px-3 pt-3 pb-1">
- <span className="text-[10px] font-semibold uppercase tracking-wide text-gray-600">
- {t('nav.playlists')}
- </span>
- <button
- onClick={() => {
- setCreating(true)
- setNewTitle('')
- }}
- title={t('playlist.create')}
- className="rounded p-0.5 text-gray-600 hover:text-gray-300"
- >
- <Plus size={14} />
- </button>
- </div>
- {creating && (
- <div className="flex items-center gap-1 px-3 py-1.5">
- <ListVideo size={14} className="shrink-0 text-gray-500" />
- <input
- autoFocus
- value={newTitle}
- onChange={(e) => { setNewTitle(e.target.value) }}
- onBlur={() => void handleCreate()}
- onKeyDown={(e) => {
- if (e.key === 'Enter') void handleCreate()
- if (e.key === 'Escape') setCreating(false)
- }}
- placeholder={t('playlist.namePlaceholder')}
- className="flex-1 bg-transparent text-sm text-gray-200 outline-none placeholder-gray-600"
- />
- </div>
- )}
- {playlists.length === 0 && !creating && (
- <p className="px-3 py-4 text-xs text-gray-600">
- {t('playlist.noneYet')}
- </p>
- )}
- {playlists.map((p) => (
- <Reorderable
- key={p.id}
- group="we-playlist-order"
- id={p.id}
- onMove={playlistOrder.move}
- disabled={renamingId === p.id}
- >
- <button
- onClick={() => { setActivePlaylistId(p.id) }}
- className={clsx(
- 'group flex items-center gap-2 px-3 py-2 text-sm',
- activePlaylistId === p.id
- ? 'bg-fg/5 text-fg'
- : 'text-gray-400 hover:bg-fg/5 hover:text-gray-200'
- )}
- >
- <ListVideo
- size={14}
- className={clsx(
- 'shrink-0',
- playbackStates.some((s) => s.playlistId === p.id) ? 'text-accent-400' : 'text-gray-600'
- )}
- />
- {renamingId === p.id ? (
- <input
- autoFocus
- value={renameValue}
- onChange={(e) => { setRenameValue(e.target.value) }}
- onBlur={() => void handleRename(p.id)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') void handleRename(p.id)
- if (e.key === 'Escape') setRenamingId(null)
- }}
- onClick={(e) => { e.stopPropagation() }}
- className="flex-1 bg-transparent text-sm text-gray-200 outline-none"
- />
- ) : (
- <span className="flex-1 truncate text-left">{p.title}</span>
- )}
- <span className="text-xs text-gray-600">{p.items.length}</span>
- <span
- onClick={(e) => {
- e.stopPropagation()
- setRenamingId(p.id)
- setRenameValue(p.title)
- }}
- className="hidden rounded p-0.5 text-gray-600 hover:text-gray-300 group-hover:block"
- >
- <Pencil size={11} />
- </span>
- <span
- onClick={(e) => {
- e.stopPropagation()
- void handleDelete(p.id)
- }}
- className="hidden rounded p-0.5 text-gray-600 hover:text-red-400 group-hover:block"
- >
- <Trash2 size={11} />
- </span>
- </button>
- </Reorderable>
- ))}
- </div>
- </ResizableWidth>
- <div className="flex flex-1 overflow-hidden">
- <div className="flex flex-1 flex-col overflow-hidden">
- {!activePlaylist ? (
- <div className="flex h-full items-center justify-center text-gray-600">
- <p>{t('playlist.selectOrCreate')}</p>
- </div>
- ) : (
- <>
- <div className="border-b border-fg/5 px-4 py-3">
- <div className="flex items-center justify-between">
- <h2 className="text-lg font-semibold text-gray-100">{activePlaylist.title}</h2>
- <div className="flex items-center gap-2">
- {perScreen && (
- <ScreenSelect targets={targets} value={screen} onChange={setScreen} title={t('playlist.whichScreen')} />
- )}
- {isThisPlaylistActive ? (
- <>
- <button
- onClick={() => void handlePrevious()}
- title={t('playlist.previous')}
- className="rounded-lg bg-fg/5 p-2 text-gray-300 hover:bg-fg/10"
- >
- <SkipBack size={14} />
- </button>
- <button
- onClick={() => void handlePauseResume()}
- title={isPlaying ? t('common.pause') : t('common.resume')}
- className="rounded-lg bg-accent-600 p-2 text-white hover:bg-accent-500"
- >
- {isPlaying ? <Pause size={14} /> : <Play size={14} />}
- </button>
- <button
- onClick={() => void handleNext()}
- title={t('common.next')}
- className="rounded-lg bg-fg/5 p-2 text-gray-300 hover:bg-fg/10"
- >
- <SkipForward size={14} />
- </button>
- <button
- onClick={() => void handleStop()}
- title={t('playlist.stop')}
- className="rounded-lg bg-fg/5 p-2 text-gray-300 hover:bg-red-500/20 hover:text-red-400"
- >
- <Square size={14} />
- </button>
- </>
- ) : (
- <button
- onClick={() => void handlePlay()}
- disabled={activePlaylist.items.length === 0}
- className="flex items-center gap-2 rounded-lg bg-accent-600 px-4 py-2 text-sm font-medium text-white hover:bg-accent-500 disabled:opacity-50"
- >
- <Play size={14} />
- {t('playlist.play')}
- </button>
- )}
- </div>
- </div>
- {error && <p className="mt-2 text-xs text-red-400">{error}</p>}
- {perScreen && isThisPlaylistActive && (
- <p className="mt-1 text-xs text-gray-500">
- {t('playlist.playingOn', { screens: thisStates.map((s) => screenLabel(s.screen)).join(', ') })}
- </p>
- )}
- <div className="mt-3 flex flex-wrap items-center gap-4">
- <label className="flex items-center gap-2 text-xs text-gray-400">
- <CalendarClock size={12} />
- {t('playlist.mode')}
- <select
- value={mode}
- onChange={(e) => void updateSettings({ mode: e.target.value as PlaylistMode })}
- className="rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
- >
- {MODE_OPTIONS.map((o) => (
- <option key={o.value} value={o.value}>
- {t(o.label)}
- </option>
- ))}
- </select>
- </label>
- {mode !== 'timer' && (
- <p className="basis-full text-xs text-gray-600">{t(MODE_HINTS[mode])}</p>
- )}
- {mode === 'timer' && (
- <>
- <label className="flex items-center gap-2 text-xs text-gray-400">
- <Toggle on={activePlaylist.settings.randomize} onClick={() => void updateSettings({ randomize: !activePlaylist.settings.randomize })} />
- <Shuffle size={12} />
- {t('playlist.randomize')}
- </label>
- {!activePlaylist.settings.randomize && (
- <label className="flex items-center gap-2 text-xs text-gray-400">
- <ArrowDownWideNarrow size={12} />
- {t('playlist.sortBy')}
- <select
- value={activePlaylist.settings.sortBy}
- onChange={(e) =>
- void updateSettings({ sortBy: e.target.value as PlaylistSettings['sortBy'] })
- }
- className="rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
- >
- {SORT_OPTIONS.map((o) => (
- <option key={o.value} value={o.value}>
- {t(o.label)}
- </option>
- ))}
- </select>
- </label>
- )}
- <label className="flex items-center gap-2 text-xs text-gray-400">
- {t('playlist.duration')}
- <input
- type="number"
- min={1}
- value={activePlaylist.settings.defaultDurationSec}
- onChange={(e) =>
- void updateSettings({ defaultDurationSec: Math.max(1, Number(e.target.value)) })
- }
- className="w-20 rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
- />
- {t('playlist.seconds')}
- </label>
- <label
- className="flex items-center gap-2 text-xs text-gray-400"
- title={t('playlist.finishVideosHint')}
- >
- <Toggle on={!!activePlaylist.settings.finishVideos} onClick={() => void updateSettings({ finishVideos: !activePlaylist.settings.finishVideos })} />
- <Film size={12} />
- {t('playlist.finishVideos')}
- </label>
- </>
- )}
- <label
- className="flex items-center gap-2 text-xs text-gray-400"
- title={t('playlist.favoritesOnlyHint')}
- >
- <Toggle on={!!activePlaylist.settings.favoritesOnly} onClick={() => void updateSettings({ favoritesOnly: !activePlaylist.settings.favoritesOnly })} />
- <Heart size={12} />
- {t('playlist.favoritesOnly')}
- {activePlaylist.settings.favoritesOnly && (
- <span className={favoriteCount === 0 ? 'text-amber-400' : 'text-gray-600'}>
- {favoriteCount === 0
- ? t('playlist.favoritesOnlyNone')
- : t('playlist.favoritesOnlyCount', { favorites: favoriteCount, total: activePlaylist.items.length })}
- </span>
- )}
- </label>
- <label className="flex items-center gap-2 text-xs text-gray-400">
- {t('playlist.defaultVolume')}
- <input
- type="range"
- min={0}
- max={100}
- value={activePlaylist.settings.defaultVolume}
- onChange={(e) => void updateSettings({ defaultVolume: Number(e.target.value) })}
- className="w-24 accent-accent-500"
- />
- <span className="w-8 text-gray-300">{activePlaylist.settings.defaultVolume}</span>
- </label>
- </div>
- </div>
- <div className="flex items-center justify-between px-4 pt-3">
- <span className="text-xs text-gray-600">
- {t('playlist.count', { count: activePlaylist.items.length })}
- </span>
- <button
- onClick={() => { setPickerOpen(true) }}
- className="flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-1.5 text-xs text-gray-300 hover:bg-fg/10"
- >
- <Plus size={12} />
- {t('playlist.addWallpapers')}
- </button>
- </div>
- <div className="flex-1 overflow-y-auto p-4 space-y-2">
- {activePlaylist.items.length === 0 && (
- <div className="flex h-32 items-center justify-center text-sm text-gray-600">
- {t('playlist.empty')}
- </div>
- )}
- {activePlaylist.items.map((item, index, items) => (
- <PlaylistItemRow
- key={item.wallpaperId}
- item={item}
- earlierEnd={items.slice(0, index).reduce((end, other) => Math.max(end, other.endMinute ?? 0), 0)}
- isLast={index === items.length - 1}
- wallpaper={wallpaperById.get(item.wallpaperId)}
- index={index}
- isPlaying={isPlaying}
- isCurrent={currentItemIds.has(item.wallpaperId)}
- onDragStart={handleDragStart}
- onDragOver={handleDragOver}
- onDrop={() => void handleDrop()}
- onPlay={() => void handlePlayItem(item.wallpaperId)}
- onRemove={() => void handleRemoveItem(item.wallpaperId)}
- onUpdate={(patch) => void handleUpdateItem(item.wallpaperId, patch)}
- onContextMenu={(e) => { openItemCtxMenu(e, item.wallpaperId) }}
- onOpenDetail={() => { setDetailId(item.wallpaperId) }}
- defaultDurationSec={activePlaylist.settings.defaultDurationSec}
- mode={mode}
- defaultVolume={activePlaylist.settings.defaultVolume}
- />
- ))}
- </div>
- </>
- )}
- </div>
- {detailWallpaper && (
- <DetailSidebar
- id={detailWallpaper.id}
- {...detailSidebarProps(detailWallpaper)}
- onClose={() => { setDetailId(null) }}
- onSubscribe={() => void subscribe(detailWallpaper.id)}
- onUnsubscribe={() => unsubscribe([detailWallpaper.id])}
- onPlay={(target) => applyWallpaper(detailWallpaper.id, target)}
- onBrowseCreator={onBrowseCreator}
- />
- )}
- </div>
- {pickerOpen && activePlaylist && (
- <WallpaperPickerModal
- excludeIds={existingIds}
- onAdd={(wallpaperIds) => void handleAddWallpapers(wallpaperIds)}
- onClose={() => { setPickerOpen(false) }}
- />
- )}
- {ctxMenu && (
- <WallpaperContextMenu
- x={ctxMenu.x}
- y={ctxMenu.y}
- ids={[ctxMenu.wallpaperId]}
- wallpapers={ctxWallpaper ? [ctxWallpaper] : []}
- onClose={() => { setCtxMenu(null) }}
- onBrowseCreator={onBrowseCreator}
- />
- )}
- </div>
- )
- }
|