karaoke(app): port single-device playlist from partiverse + tests

点歌单本地管理 — 添加/上移/下移/置顶/删除 + 10 秒撤销倒计时 + YouTube 一键
搜,无 room / 无 ws。删掉了 partiverse 那套 yopu 和弦抓取 / LLM 聊天点歌 /
QR 码(依赖后端,对单机无意义)。logic 全 immutable,21 个 vitest 覆盖
边界(首位上移 noop / 末位下移 noop / 缺失 id / 不变性)。
This commit is contained in:
Fam Zheng
2026-05-14 15:32:22 +01:00
parent 78f84d4225
commit fbd6e3cb9c
8 changed files with 3414 additions and 0 deletions
+179
View File
@@ -0,0 +1,179 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import AddSongModal from './components/AddSongModal.vue'
import { addSong, deleteSong, moveSong, youtubeSearchUrl, type Song } from './logic/playlist'
import { loadState, saveState } from './logic/storage'
const playlist = ref<Song[]>([])
const showAdd = ref(false)
const pendingDeletes = ref<Record<number, number>>({}) // songId -> timeoutId
const DELETE_DELAY_MS = 10_000
onMounted(() => {
playlist.value = loadState().playlist
})
watch(playlist, () => saveState({ playlist: playlist.value }), { deep: true })
onUnmounted(() => {
for (const id of Object.values(pendingDeletes.value)) clearTimeout(id)
})
function onAdd(payload: { singer: string; title: string }) {
playlist.value = addSong(playlist.value, payload.singer, payload.title)
showAdd.value = false
}
function onMove(songId: number, direction: 'up' | 'down' | 'first') {
playlist.value = moveSong(playlist.value, songId, direction)
}
function startDelete(songId: number) {
pendingDeletes.value[songId] = window.setTimeout(() => {
playlist.value = deleteSong(playlist.value, songId)
delete pendingDeletes.value[songId]
}, DELETE_DELAY_MS)
}
function cancelDelete(songId: number) {
const t = pendingDeletes.value[songId]
if (t !== undefined) {
clearTimeout(t)
delete pendingDeletes.value[songId]
}
}
function isPending(songId: number): boolean {
return pendingDeletes.value[songId] !== undefined
}
</script>
<template>
<main>
<header class="topbar">
<h1>🎤 Karaoke 点歌</h1>
<button class="primary" @click="showAdd = true">+ 添加歌曲</button>
</header>
<section v-if="playlist.length === 0" class="empty">
<p>点歌单空空如也</p>
<p class="dim">点击 "添加歌曲" 把歌排进队</p>
</section>
<section v-else class="list">
<article
v-for="(song, idx) in playlist"
:key="song.id"
:class="['item', { pending: isPending(song.id) }]"
>
<div class="meta">
<span class="idx">{{ idx + 1 }}</span>
<div class="text">
<div class="title">{{ song.title }}</div>
<div class="singer">{{ song.singer }}</div>
</div>
</div>
<div class="actions">
<a
:href="youtubeSearchUrl(song)"
target="_blank"
rel="noopener noreferrer"
class="action yt"
title="在 YouTube 搜索"
>YT</a>
<button class="action" :disabled="idx === 0 || isPending(song.id)" @click="onMove(song.id, 'first')" title="置顶"></button>
<button class="action" :disabled="idx === 0 || isPending(song.id)" @click="onMove(song.id, 'up')" title="上移"></button>
<button class="action" :disabled="idx === playlist.length - 1 || isPending(song.id)" @click="onMove(song.id, 'down')" title="下移"></button>
<button v-if="!isPending(song.id)" class="action danger" @click="startDelete(song.id)" title="删除"></button>
<button v-else class="action cancel-delete" @click="cancelDelete(song.id)">撤销</button>
</div>
<div v-if="isPending(song.id)" class="progress">
<div class="bar" />
</div>
</article>
</section>
<AddSongModal :show="showAdd" @close="showAdd = false" @add="onAdd" />
</main>
</template>
<style scoped>
main {
max-width: 720px;
margin: 0 auto;
padding: 16px 16px 40px;
}
.topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
h1 { margin: 0; font-size: 1.5rem; background: linear-gradient(135deg, #fff, var(--accent)); -webkit-background-clip: text; background-clip: text; color: transparent; }
button.primary { background: var(--accent); border: none; color: white; padding: 10px 16px; border-radius: 8px; font-weight: bold; }
.empty {
text-align: center;
background: var(--bg-soft);
border-radius: 12px;
padding: 60px 20px;
color: var(--fg-dim);
}
.empty .dim { font-size: 0.9rem; opacity: 0.7; margin-top: 6px; }
.list { display: flex; flex-direction: column; gap: 8px; }
.item {
position: relative;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 10px;
padding: 12px 14px;
display: flex;
flex-direction: column;
gap: 8px;
}
.item.pending { opacity: 0.55; background: rgba(239, 68, 68, 0.1); }
.meta { display: flex; align-items: center; gap: 12px; min-width: 0; }
.idx {
flex-shrink: 0;
width: 28px;
height: 28px;
border-radius: 50%;
background: rgba(236, 72, 153, 0.2);
color: var(--accent);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 0.85rem;
}
.text { min-width: 0; flex: 1; }
.title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.singer { color: var(--fg-dim); font-size: 0.85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.actions { display: flex; gap: 6px; flex-wrap: wrap; }
.action {
min-width: 36px;
height: 36px;
border: 1px solid var(--border);
background: var(--bg-soft);
color: var(--fg);
border-radius: 6px;
display: inline-flex;
align-items: center;
justify-content: center;
font-weight: bold;
padding: 0 8px;
text-decoration: none;
font-size: 0.9rem;
}
.action.yt { color: #ff4d4d; }
.action.danger { color: var(--danger); border-color: rgba(239, 68, 68, 0.4); }
.action.cancel-delete { background: var(--accent-2); border-color: var(--accent-2); color: #000; font-size: 0.8rem; }
.progress { height: 3px; background: rgba(239, 68, 68, 0.2); border-radius: 2px; overflow: hidden; }
.bar {
height: 100%;
background: var(--danger);
animation: shrink 10s linear forwards;
}
@keyframes shrink { from { width: 100%; } to { width: 0; } }
@media (max-width: 500px) {
.actions { gap: 4px; }
.action { min-width: 32px; height: 32px; font-size: 0.85rem; }
}
</style>
@@ -0,0 +1,139 @@
import { describe, expect, it } from 'vitest'
import {
addSong,
deleteSong,
moveSong,
nextId,
youtubeSearchUrl,
type Song,
} from '../logic/playlist'
const sample = (): Song[] => [
{ id: 1, singer: '周杰伦', title: '七里香' },
{ id: 2, singer: '林俊杰', title: '江南' },
{ id: 3, singer: '陶喆', title: '小镇姑娘' },
]
describe('nextId', () => {
it('returns 1 for empty playlist', () => {
expect(nextId([])).toBe(1)
})
it('returns max + 1', () => {
expect(nextId(sample())).toBe(4)
})
it('handles gaps correctly', () => {
expect(nextId([{ id: 7, singer: 'a', title: 'b' }])).toBe(8)
})
})
describe('addSong', () => {
it('appends to the end with next id', () => {
const out = addSong(sample(), '邓紫棋', '泡沫')
expect(out).toHaveLength(4)
expect(out[3]).toEqual({ id: 4, singer: '邓紫棋', title: '泡沫' })
})
it('trims whitespace', () => {
const out = addSong([], ' Adele ', ' Hello ')
expect(out[0]).toEqual({ id: 1, singer: 'Adele', title: 'Hello' })
})
it('rejects empty singer or title (returns unchanged)', () => {
const list = sample()
expect(addSong(list, '', 'Hello')).toBe(list)
expect(addSong(list, 'Adele', '')).toBe(list)
expect(addSong(list, ' ', ' ')).toBe(list)
})
it('does not mutate input', () => {
const list = sample()
addSong(list, 'a', 'b')
expect(list).toHaveLength(3)
})
})
describe('deleteSong', () => {
it('removes by id', () => {
const out = deleteSong(sample(), 2)
expect(out).toHaveLength(2)
expect(out.map((s) => s.id)).toEqual([1, 3])
})
it('is noop for missing id', () => {
const out = deleteSong(sample(), 999)
expect(out).toHaveLength(3)
})
it('does not mutate input', () => {
const list = sample()
deleteSong(list, 1)
expect(list).toHaveLength(3)
})
})
describe('moveSong', () => {
it("moves 'up'", () => {
const out = moveSong(sample(), 2, 'up')
expect(out.map((s) => s.id)).toEqual([2, 1, 3])
})
it("moves 'down'", () => {
const out = moveSong(sample(), 2, 'down')
expect(out.map((s) => s.id)).toEqual([1, 3, 2])
})
it("moves 'first'", () => {
const out = moveSong(sample(), 3, 'first')
expect(out.map((s) => s.id)).toEqual([3, 1, 2])
})
it("'up' on first item is noop", () => {
const out = moveSong(sample(), 1, 'up')
expect(out.map((s) => s.id)).toEqual([1, 2, 3])
})
it("'down' on last item is noop", () => {
const out = moveSong(sample(), 3, 'down')
expect(out.map((s) => s.id)).toEqual([1, 2, 3])
})
it("'first' on first item is noop", () => {
const out = moveSong(sample(), 1, 'first')
expect(out.map((s) => s.id)).toEqual([1, 2, 3])
})
it('handles missing id', () => {
const out = moveSong(sample(), 999, 'up')
expect(out.map((s) => s.id)).toEqual([1, 2, 3])
})
it('preserves the song count', () => {
for (const dir of ['up', 'down', 'first'] as const) {
for (const id of [1, 2, 3]) {
const out = moveSong(sample(), id, dir)
expect(out).toHaveLength(3)
expect(out.map((s) => s.id).sort()).toEqual([1, 2, 3])
}
}
})
it('does not mutate input', () => {
const list = sample()
moveSong(list, 2, 'up')
expect(list.map((s) => s.id)).toEqual([1, 2, 3])
})
})
describe('youtubeSearchUrl', () => {
it('builds an encoded search URL', () => {
const url = youtubeSearchUrl({ id: 1, singer: '周杰伦', title: '七里香' })
expect(url.startsWith('https://www.youtube.com/results?search_query=')).toBe(true)
expect(url).toContain(encodeURIComponent('周杰伦 七里香'))
})
it('encodes special characters', () => {
const url = youtubeSearchUrl({ id: 1, singer: 'A&B', title: 'C/D' })
expect(url).toContain('A%26B')
expect(url).toContain('C%2FD')
})
})
@@ -0,0 +1,89 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
const props = defineProps<{
show: boolean
}>()
const emit = defineEmits<{
close: []
add: [{ singer: string; title: string }]
}>()
const singer = ref('')
const title = ref('')
watch(
() => props.show,
(s) => {
if (s) {
singer.value = ''
title.value = ''
}
},
)
const canAdd = () => singer.value.trim() !== '' && title.value.trim() !== ''
function submit() {
if (!canAdd()) return
emit('add', { singer: singer.value.trim(), title: title.value.trim() })
}
</script>
<template>
<div v-if="show" class="overlay" @click.self="$emit('close')">
<div class="modal">
<header>
<h2>添加歌曲</h2>
<button class="x" @click="$emit('close')"></button>
</header>
<section>
<label>歌手</label>
<input v-model="singer" type="text" placeholder="周杰伦" @keydown.enter="submit" />
</section>
<section>
<label>歌名</label>
<input v-model="title" type="text" placeholder="七里香" @keydown.enter="submit" />
</section>
<footer>
<button class="cancel" @click="$emit('close')">取消</button>
<button class="ok" :disabled="!canAdd()" @click="submit">添加</button>
</footer>
</div>
</div>
</template>
<style scoped>
.overlay {
position: fixed; inset: 0;
background: rgba(0, 0, 0, 0.75);
display: flex; align-items: center; justify-content: center;
z-index: 1500; padding: 16px;
}
.modal {
background: #232336;
border: 1px solid var(--border);
border-radius: 12px;
width: 100%; max-width: 480px;
padding: 16px;
}
header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
h2 { margin: 0; font-size: 1.3rem; }
section { margin-bottom: 16px; }
label { display: block; margin-bottom: 6px; color: var(--fg-dim); font-weight: 500; font-size: 0.9rem; }
input {
width: 100%;
padding: 12px 14px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--bg-soft);
color: var(--fg);
font-size: 1rem;
}
input:focus { outline: 2px solid var(--accent); }
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 12px; border-top: 1px solid var(--border); }
button.x { width: 32px; height: 32px; border-radius: 6px; background: transparent; color: var(--fg-dim); border: 1px solid var(--border); }
button.cancel { background: var(--bg-soft); border: 1px solid var(--border); color: var(--fg); padding: 10px 18px; border-radius: 8px; }
button.ok { background: var(--accent); border: none; color: white; padding: 10px 18px; border-radius: 8px; font-weight: bold; }
</style>
@@ -0,0 +1,49 @@
// Playlist 不可变操作。所有函数纯,返回新数组。
export interface Song {
id: number
singer: string
title: string
}
export type Direction = 'up' | 'down' | 'first'
export function nextId(playlist: Song[]): number {
let max = 0
for (const s of playlist) if (s.id > max) max = s.id
return max + 1
}
export function addSong(playlist: Song[], singer: string, title: string): Song[] {
const s = singer.trim()
const t = title.trim()
if (!s || !t) return playlist
return [...playlist, { id: nextId(playlist), singer: s, title: t }]
}
export function deleteSong(playlist: Song[], songId: number): Song[] {
return playlist.filter((s) => s.id !== songId)
}
export function moveSong(playlist: Song[], songId: number, direction: Direction): Song[] {
const idx = playlist.findIndex((s) => s.id === songId)
if (idx === -1) return playlist
const next = [...playlist]
const [song] = next.splice(idx, 1)
if (direction === 'first') {
next.unshift(song)
} else if (direction === 'up') {
next.splice(Math.max(0, idx - 1), 0, song)
} else {
// 'down': insert at idx + 1 of original. After splice, original idx + 1
// becomes position idx in `next`. So inserting at idx puts the song before
// the element that *was* at idx + 1 — we want *after* it, hence idx + 1.
next.splice(Math.min(next.length, idx + 1), 0, song)
}
return next
}
export function youtubeSearchUrl(song: Song): string {
const q = encodeURIComponent(`${song.singer} ${song.title}`)
return `https://www.youtube.com/results?search_query=${q}`
}
@@ -0,0 +1,32 @@
import type { Song } from './playlist'
interface PersistedState {
playlist: Song[]
}
const KEY = 'karaoke:v1'
function isBrowser(): boolean {
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'
}
export function loadState(): PersistedState {
if (!isBrowser()) return { playlist: [] }
try {
const raw = window.localStorage.getItem(KEY)
if (!raw) return { playlist: [] }
const parsed = JSON.parse(raw) as Partial<PersistedState>
return { playlist: parsed.playlist ?? [] }
} catch {
return { playlist: [] }
}
}
export function saveState(state: PersistedState): void {
if (!isBrowser()) return
try {
window.localStorage.setItem(KEY, JSON.stringify(state))
} catch {
// ignore
}
}
+5
View File
@@ -0,0 +1,5 @@
import { createApp } from 'vue'
import App from './App.vue'
import './style.css'
createApp(App).mount('#app')
+23
View File
@@ -0,0 +1,23 @@
:root {
color-scheme: dark;
--bg: #1a1a2e;
--bg-soft: rgba(255, 255, 255, 0.06);
--bg-card: rgba(255, 255, 255, 0.08);
--border: rgba(255, 255, 255, 0.15);
--fg: rgba(255, 255, 255, 0.92);
--fg-dim: rgba(255, 255, 255, 0.6);
--accent: #ec4899;
--accent-2: #f59e0b;
--danger: #ef4444;
--ok: #4caf50;
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif;
}
* { box-sizing: border-box; }
html, body, #app {
margin: 0; padding: 0; min-height: 100vh;
background: var(--bg);
color: var(--fg);
-webkit-tap-highlight-color: transparent;
}
button { font: inherit; cursor: pointer; }
button:disabled { opacity: 0.5; cursor: not-allowed; }