WallpaperCard.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { useState, useEffect } from 'react'
  2. import { useQueryClient } from '@tanstack/react-query'
  3. import { Loader2, Check, X, Trash2, Download, Archive, AlertTriangle, RotateCw, Plus, FolderOpen, WifiOff } from 'lucide-react'
  4. import type { BackupProgressEvent, WallpaperMeta } from '@shared/types'
  5. import type { CardBorders } from '@shared/cardBorders'
  6. import type { CardBadges } from '@shared/cardBadges'
  7. import type { CardSteamState } from '../../hooks/useCardBorders'
  8. import clsx from 'clsx'
  9. import CompatBadge from '../common/CompatBadge'
  10. import { getPreviewSrc } from '../../utils/preview'
  11. import { hasBackup, hasDamagedFiles, progressVerb, verifyProblemLabel } from '../../utils/wallpaper'
  12. import { useToast } from '../common/Toast'
  13. import type { PreviewSize } from '../../hooks/usePreviewSize'
  14. import {
  15. CardAction,
  16. CardOverlay,
  17. CardPreview,
  18. CornerBadge,
  19. GridCard,
  20. LikeAction,
  21. PlayButton,
  22. ProgressBar,
  23. SteamAction
  24. } from '../common/GridCard'
  25. import { t, tagLabel } from '../../i18n'
  26. interface WallpaperCardProps {
  27. wallpaper: WallpaperMeta
  28. selected: boolean
  29. isDetailOpen: boolean
  30. lweInstalled: boolean
  31. steam: CardSteamState
  32. borders: CardBorders
  33. badges: CardBadges
  34. currentPlaylistId: string | null
  35. isInCurrentPlaylist: boolean
  36. previewSize: PreviewSize
  37. backupProgress: { percentage: number; status: 'copying' | 'verifying'; action?: BackupProgressEvent['action'] } | null
  38. onSelect: (e: React.MouseEvent) => void
  39. onContextMenu: (e: React.MouseEvent) => void
  40. }
  41. export default function WallpaperCard({
  42. wallpaper,
  43. selected,
  44. isDetailOpen,
  45. lweInstalled,
  46. steam,
  47. borders,
  48. badges,
  49. currentPlaylistId,
  50. isInCurrentPlaylist,
  51. previewSize,
  52. backupProgress,
  53. onSelect,
  54. onContextMenu
  55. }: WallpaperCardProps) {
  56. const { showToast } = useToast()
  57. const queryClient = useQueryClient()
  58. const [isApplying, setIsApplying] = useState(false)
  59. const [unsubState, setUnsubState] = useState<'idle' | 'confirm' | 'pending'>('idle')
  60. const [error, setError] = useState<string | null>(null)
  61. const [fpsInput, setFpsInput] = useState(wallpaper.fpsOverride != null ? String(wallpaper.fpsOverride) : '')
  62. const [isAddingToPlaylist, setIsAddingToPlaylist] = useState(false)
  63. const [isRedownloading, setIsRedownloading] = useState(false)
  64. const [downloadPercentage, setDownloadPercentage] = useState<number | null>(null)
  65. useEffect(() => {
  66. if (!wallpaper.downloading) return
  67. const off = window.electronAPI.on.downloadProgress((progress) => {
  68. if (progress.itemId !== wallpaper.id) return
  69. if (progress.status === 'downloading') {
  70. setDownloadPercentage(progress.percentage)
  71. } else {
  72. setDownloadPercentage(null)
  73. setIsRedownloading(false)
  74. }
  75. })
  76. return () => {
  77. off()
  78. setDownloadPercentage(null)
  79. }
  80. }, [wallpaper.downloading, wallpaper.id])
  81. function refreshLibrary() {
  82. queryClient.invalidateQueries({ queryKey: ['library'] })
  83. }
  84. async function handleRedownload(e: React.MouseEvent) {
  85. e.stopPropagation()
  86. if (isRedownloading) return
  87. setIsRedownloading(true)
  88. setError(null)
  89. try {
  90. await window.electronAPI.steam.redownload(wallpaper.id)
  91. refreshLibrary()
  92. } catch (err) {
  93. setError((err as Error).message)
  94. refreshLibrary()
  95. } finally {
  96. setIsRedownloading(false)
  97. }
  98. }
  99. async function handleApply() {
  100. setIsApplying(true)
  101. setError(null)
  102. try {
  103. await window.electronAPI.wallpaper.apply({ wallpaperId: wallpaper.id })
  104. refreshLibrary()
  105. } catch (err) {
  106. setError((err as Error).message)
  107. } finally {
  108. setIsApplying(false)
  109. }
  110. }
  111. function handleFpsBlur() {
  112. const trimmed = fpsInput.trim()
  113. const parsed = trimmed === '' ? undefined : parseInt(trimmed, 10)
  114. if (parsed !== undefined && (isNaN(parsed) || parsed < 1)) return
  115. const current = wallpaper.fpsOverride
  116. if ((parsed ?? undefined) === current) return
  117. window.electronAPI.library.update(wallpaper.id, { fpsOverride: parsed })
  118. }
  119. async function handleAddToPlaylist() {
  120. if (!currentPlaylistId || isAddingToPlaylist || isInCurrentPlaylist) return
  121. setIsAddingToPlaylist(true)
  122. setError(null)
  123. try {
  124. await window.electronAPI.playlist.addItems(currentPlaylistId, [wallpaper.id])
  125. showToast(t('playlist.addedToCurrent'))
  126. queryClient.invalidateQueries({ queryKey: ['playlists'] })
  127. } catch (err) {
  128. setError((err as Error).message)
  129. } finally {
  130. setIsAddingToPlaylist(false)
  131. }
  132. }
  133. async function handleUnsubscribeClick(e: React.MouseEvent) {
  134. e.stopPropagation()
  135. if (unsubState === 'idle') { setUnsubState('confirm'); return }
  136. if (unsubState !== 'confirm') return
  137. setUnsubState('pending')
  138. try {
  139. await window.electronAPI.steam.unsubscribe(wallpaper.id)
  140. refreshLibrary()
  141. queryClient.invalidateQueries({ queryKey: ['folders'] })
  142. } catch (err) {
  143. setError((err as Error).message)
  144. setUnsubState('idle')
  145. }
  146. }
  147. async function handleOpenLocally() {
  148. if (!wallpaper.localPath) return
  149. await window.electronAPI.shell.openPath(wallpaper.localPath)
  150. }
  151. const previewSrc = getPreviewSrc(wallpaper)
  152. const compact = previewSize !== 'big'
  153. const playBlocked = !lweInstalled || !!wallpaper.downloading || !!wallpaper.downloadFailed
  154. return (
  155. <GridCard
  156. data-wallpaper-id={wallpaper.id}
  157. selected={selected}
  158. isDetailOpen={isDetailOpen}
  159. steam={steam}
  160. borders={borders}
  161. draggable
  162. onDragStart={(e) => {
  163. e.dataTransfer.setData('text/wallpaper-id', wallpaper.id)
  164. e.dataTransfer.setData('text/wallpaper-selected', 'true')
  165. e.dataTransfer.effectAllowed = 'copy'
  166. }}
  167. onClick={onSelect}
  168. onContextMenu={onContextMenu}
  169. >
  170. <CardPreview src={previewSrc} alt={wallpaper.title}>
  171. {wallpaper.downloading && (
  172. <CardOverlay>
  173. <Download size={20} className="text-accent-400 animate-bounce" />
  174. <span className="text-xs text-gray-300">
  175. {downloadPercentage != null ? t('subscribe.downloadingPercent', { percent: downloadPercentage }) : t('subscribe.downloading')}
  176. </span>
  177. {downloadPercentage != null && (
  178. <ProgressBar percentage={downloadPercentage} className="h-1 w-full max-w-[140px] rounded-full bg-fg/10" />
  179. )}
  180. </CardOverlay>
  181. )}
  182. {wallpaper.downloadFailed && (
  183. <CardOverlay>
  184. <AlertTriangle size={20} className="text-red-400" />
  185. <span className="text-xs text-gray-300">{t('subscribe.downloadFailed')}</span>
  186. <button
  187. onClick={handleRedownload}
  188. disabled={isRedownloading}
  189. className="flex items-center gap-1 rounded bg-accent-600/80 px-2 py-1 text-xs text-white transition-colors hover:bg-accent-600 disabled:cursor-not-allowed disabled:opacity-50"
  190. >
  191. {isRedownloading ? <Loader2 size={11} className="animate-spin" /> : <RotateCw size={11} />}
  192. {t('subscribe.redownload')}
  193. </button>
  194. </CardOverlay>
  195. )}
  196. {hasDamagedFiles(wallpaper) && (
  197. <CardOverlay>
  198. <AlertTriangle size={20} className="text-amber-400" />
  199. <span className="text-xs text-gray-300">{verifyProblemLabel(wallpaper.verifyProblem!)}</span>
  200. <button
  201. onClick={handleRedownload}
  202. disabled={isRedownloading}
  203. className="flex items-center gap-1 rounded bg-accent-600/80 px-2 py-1 text-xs text-white transition-colors hover:bg-accent-600 disabled:cursor-not-allowed disabled:opacity-50"
  204. >
  205. {isRedownloading ? <Loader2 size={11} className="animate-spin" /> : <RotateCw size={11} />}
  206. {t('verify.repair')}
  207. </button>
  208. </CardOverlay>
  209. )}
  210. {backupProgress != null && (
  211. <CardOverlay>
  212. <Archive size={20} className="text-accent-400 animate-pulse" />
  213. <span className="text-xs text-gray-300">
  214. {backupProgress.status === 'verifying'
  215. ? t('backup.verifying', { percent: backupProgress.percentage })
  216. : t('backup.progress', { verb: progressVerb([backupProgress]), percent: backupProgress.percentage })}
  217. </span>
  218. <ProgressBar percentage={backupProgress.percentage} className="h-1 w-full max-w-[140px] rounded-full bg-fg/10" />
  219. </CardOverlay>
  220. )}
  221. {((badges.hdr && wallpaper.hdr) || (badges.hrtf && wallpaper.hrtf)) && (
  222. <div className="absolute right-2 top-2 flex gap-1">
  223. {badges.hdr && wallpaper.hdr && (
  224. <span
  225. className="rounded bg-black/70 px-1 py-0.5 text-[10px] font-semibold leading-none tracking-wide text-amber-300"
  226. title={wallpaper.type === 'video' ? t('hdr.video') : t('hdr.scene')}
  227. >
  228. HDR
  229. </span>
  230. )}
  231. {badges.hrtf && wallpaper.hrtf && (
  232. <span
  233. className="rounded bg-black/70 px-1 py-0.5 text-[10px] font-semibold leading-none tracking-wide text-sky-300"
  234. title={t('hrtf.badge')}
  235. >
  236. HRTF
  237. </span>
  238. )}
  239. </div>
  240. )}
  241. {backupProgress == null && hasBackup(wallpaper) && (
  242. <CornerBadge className="bottom-2 right-2 bg-black/60 text-accent-300" title={t('backup.badge')}>
  243. <Archive size={12} />
  244. </CornerBadge>
  245. )}
  246. {wallpaper.unavailable && (
  247. <CornerBadge
  248. className="bottom-2 left-2 bg-amber-600/80 text-white"
  249. title={t('library.unavailableBadge')}
  250. >
  251. <WifiOff size={12} />
  252. </CornerBadge>
  253. )}
  254. <CompatBadge
  255. compat={wallpaper.compat}
  256. className={clsx('absolute bottom-2', wallpaper.unavailable ? 'left-8' : 'left-2')}
  257. />
  258. </CardPreview>
  259. <div className="p-3">
  260. <h3 className="truncate text-sm font-medium text-gray-200" title={wallpaper.title}>
  261. {wallpaper.title}
  262. </h3>
  263. {wallpaper.tags.length > 0 && (
  264. <div className="mt-1 flex flex-wrap gap-1">
  265. {wallpaper.tags.slice(0, 3).map((tag) => (
  266. <span key={tag} className="rounded bg-fg/5 px-1.5 py-0.5 text-xs text-gray-400">
  267. {tagLabel(tag)}
  268. </span>
  269. ))}
  270. </div>
  271. )}
  272. <div className="mt-2 flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
  273. <span className="text-xs text-gray-500">{t('library.fps')}</span>
  274. <input
  275. type="number"
  276. min={1}
  277. max={360}
  278. placeholder={t('library.fpsDefault')}
  279. value={fpsInput}
  280. onChange={(e) => setFpsInput(e.target.value)}
  281. onBlur={handleFpsBlur}
  282. onKeyDown={(e) => { if (e.key === 'Enter') { e.currentTarget.blur() } }}
  283. className="w-16 rounded bg-fg/5 px-1.5 py-0.5 text-xs text-gray-300 outline-none focus:ring-1 focus:ring-accent-500 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  284. />
  285. </div>
  286. {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
  287. <div className={clsx('mt-2 flex items-center', compact ? 'gap-1' : 'gap-2')}>
  288. <LikeAction
  289. id={wallpaper.id}
  290. isLiked={steam.isLiked}
  291. unavailable={wallpaper.unavailable}
  292. compact={compact}
  293. onError={setError}
  294. />
  295. <CardAction
  296. icon={isInCurrentPlaylist ? Check : Plus}
  297. label={isInCurrentPlaylist ? t('playlist.added') : t('playlist.add')}
  298. busy={isAddingToPlaylist}
  299. compact={compact}
  300. tone={isInCurrentPlaylist ? 'active' : 'default'}
  301. disabled={!currentPlaylistId || isAddingToPlaylist || isInCurrentPlaylist}
  302. title={
  303. !currentPlaylistId
  304. ? t('playlist.noneActive')
  305. : isInCurrentPlaylist
  306. ? t('playlist.alreadyInCurrent')
  307. : t('playlist.addToCurrent')
  308. }
  309. onClick={handleAddToPlaylist}
  310. />
  311. {unsubState === 'confirm' ? (
  312. <div className="flex items-center gap-1">
  313. {!compact && <span className="text-xs text-gray-400">{t('common.sure')}</span>}
  314. <button
  315. onClick={handleUnsubscribeClick}
  316. title={t('subscribe.confirmUnsubscribe')}
  317. className={clsx('rounded bg-red-600/80 text-xs text-white hover:bg-red-600', compact ? 'p-1.5' : 'px-2 py-1')}
  318. >
  319. {compact ? <Check size={11} /> : t('common.yes')}
  320. </button>
  321. <button
  322. onClick={(e) => { e.stopPropagation(); setUnsubState('idle') }}
  323. title={t('common.cancel')}
  324. className={clsx('rounded bg-fg/5 text-xs text-gray-400 hover:bg-fg/10', compact ? 'p-1.5' : 'px-2 py-1')}
  325. >
  326. {compact ? <X size={11} /> : t('common.no')}
  327. </button>
  328. </div>
  329. ) : (
  330. <CardAction
  331. icon={Trash2}
  332. label={t('subscribe.unsubShort')}
  333. busy={unsubState === 'pending'}
  334. compact={compact}
  335. tone="danger"
  336. disabled={unsubState === 'pending'}
  337. title={t('subscribe.unsubscribeHint')}
  338. onClick={handleUnsubscribeClick}
  339. />
  340. )}
  341. <SteamAction id={wallpaper.id} compact={compact} />
  342. <CardAction
  343. icon={FolderOpen}
  344. label={t('common.open')}
  345. compact={compact}
  346. disabled={!wallpaper.localPath}
  347. title={wallpaper.localPath ? t('library.openFolder') : t('library.noLocalFiles')}
  348. onClick={handleOpenLocally}
  349. />
  350. </div>
  351. </div>
  352. <div className="absolute right-2 top-2">
  353. <PlayButton
  354. busy={isApplying}
  355. ready={!playBlocked}
  356. disabled={isApplying || playBlocked}
  357. title={
  358. wallpaper.downloading
  359. ? t('play.stillDownloading')
  360. : wallpaper.downloadFailed
  361. ? t('play.downloadFailed')
  362. : !lweInstalled
  363. ? t('play.installFirst')
  364. : t('play.wallpaper')
  365. }
  366. onClick={handleApply}
  367. />
  368. </div>
  369. </GridCard>
  370. )
  371. }