Spaces:
Paused
Paused
Download src/mv/MvApp.tsx from Ethscriptions/video: direct link, hf CLI and curl.
- Browser
- Download file 33.3 kB
-
https://huggingface.co/spaces/Ethscriptions/video/resolve/main/src/mv/MvApp.tsx
- Command line
-
hf download hf://spaces/Ethscriptions/video/src/mv/MvApp.tsx
-
curl -L -o MvApp.tsx https://huggingface.co/spaces/Ethscriptions/video/resolve/main/src/mv/MvApp.tsx
33.3 kB
| import { useCallback, useEffect, useMemo, useRef, useState } from 'react' | |
| import { zipSync } from 'fflate' | |
| import './styles.css' | |
| import { DURATION } from './engine/audio' | |
| import { Renderer } from './engine/renderer' | |
| import { SCENES, sceneAt } from './engine/timeline' | |
| import { AUDIO_URL, ensureLyricFont, loadFonts } from './fonts' | |
| import { exportMp4, exportRenderer, webCodecsSupported, type ExportResult } from './export/exportMp4' | |
| import { DESIGNS, RATIOS, RATIO_SIZE, renderCover, type CoverItem, type Ratio } from './covers/covers' | |
| import { PLATFORMS, countChars, formatTags } from './copy/platforms' | |
| import { getLyricOffset, loadSavedLyrics, lyricCount, parseLrc, setLyricOffset, setLyrics } from './engine/lyrics' | |
| import { bus } from './playerBus' | |
| type Orient = 'landscape' | 'portrait' | |
| const fmt = (t: number) => { | |
| const m = Math.floor(t / 60) | |
| const s = Math.floor(t % 60) | |
| return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` | |
| } | |
| function useToast() { | |
| const [msg, setMsg] = useState<string | null>(null) | |
| const timer = useRef<number>(0) | |
| const show = useCallback((m: string) => { | |
| setMsg(m) | |
| window.clearTimeout(timer.current) | |
| timer.current = window.setTimeout(() => setMsg(null), 1600) | |
| }, []) | |
| return { msg, show } | |
| } | |
| async function copyText(text: string): Promise<boolean> { | |
| try { | |
| await navigator.clipboard.writeText(text) | |
| return true | |
| } catch { | |
| const ta = document.createElement('textarea') | |
| ta.value = text | |
| ta.style.position = 'fixed' | |
| ta.style.opacity = '0' | |
| document.body.appendChild(ta) | |
| ta.select() | |
| let ok = false | |
| try { | |
| ok = document.execCommand('copy') | |
| } catch { | |
| ok = false | |
| } | |
| document.body.removeChild(ta) | |
| return ok | |
| } | |
| } | |
| function download(url: string, name: string) { | |
| const a = document.createElement('a') | |
| a.href = url | |
| a.download = name | |
| document.body.appendChild(a) | |
| a.click() | |
| a.remove() | |
| } | |
| // ====================================================================== App | |
| export default function MvApp() { | |
| const [ready, setReady] = useState(false) | |
| // landscape 16:9 only (portrait was dropped on request) | |
| const orient: Orient = 'landscape' | |
| const setOrient = (_o: Orient) => {} | |
| const toast = useToast() | |
| useEffect(() => { | |
| loadFonts().then(() => setReady(true)) | |
| // debug / QA hook: render a single frame offscreen | |
| ;(window as unknown as { __mvSnap: unknown }).__mvSnap = async (t: number, w: number, h: number) => { | |
| await loadFonts() | |
| const r = exportRenderer() | |
| r.setSize(w, h) | |
| const t0 = performance.now() | |
| r.render(t) | |
| const ms = performance.now() - t0 | |
| return { url: r.out.toDataURL('image/jpeg', 0.85), ms, webgl: r.webgl } | |
| } | |
| ;(window as unknown as { __mvExport: unknown }).__mvExport = exportMp4 | |
| ;(window as unknown as { __mvSetLyrics: unknown }).__mvSetLyrics = async (src: string) => { | |
| const n = setLyrics(src, false) | |
| await ensureLyricFont() | |
| return n | |
| } | |
| ;(window as unknown as { __mvSheet: unknown }).__mvSheet = async (which: string, w: number, h: number) => { | |
| const H = await import('./engine/hero') | |
| const c = document.createElement('canvas') | |
| c.width = w | |
| c.height = h | |
| const g = c.getContext('2d')! | |
| g.fillStyle = '#8a96a6' | |
| g.fillRect(0, 0, w, h) | |
| const s = Math.min(w, h) | |
| if (which === 'walk') H.heroWalk(g, w / 2, h * 0.95, h * 0.9, 0.2, { t: 1 }) | |
| if (which === 'back') H.heroBack(g, w / 2, h * 0.95, h * 0.9, 0, { t: 1 }) | |
| if (which === 'bike') H.bike(g, w / 2, h * 0.85, s * 0.62, { t: 1, parked: true }) | |
| if (which === 'ride') H.heroRide(g, w / 2, h * 0.95, s * 0.6, { t: 1, smile: true, tuck: 0 }) | |
| if (which === 'rear') H.heroRideRear(g, w / 2, h * 0.98, h * 0.9, 0, 1) | |
| if (which === 'sit') { | |
| H.bike(g, w * 0.62, h * 0.95, (h * 0.75) / H.HERO_H, { facing: -1, light: 0, parked: true }) | |
| H.heroSit(g, w * 0.36, h * 0.95, h * 0.75, 1, { fire: 0 }) | |
| } | |
| if (which === 'push') H.heroPush(g, w * 0.5, h * 0.95, (h * 0.85) / H.HERO_H, 0.2, { t: 1, light: 1 }) | |
| if (which === 'face') H.heroPortrait(g, w / 2, h * 0.42, h * 0.22, { t: 1, tear: 0.5 }) | |
| return c.toDataURL('image/png') | |
| } | |
| }, []) | |
| return ( | |
| <div className="mv-root"> | |
| <header className="mv-header"> | |
| <div className="mv-brand"> | |
| <span className="mv-logo">黑街</span> | |
| <div> | |
| <div className="mv-brand-en">BLACK STREET · MV</div> | |
| <div className="mv-brand-sub">陈雅雯《黑街》 · 浏览器实时渲染</div> | |
| </div> | |
| </div> | |
| <nav className="mv-nav"> | |
| <a href="#player">播放</a> | |
| <a href="#lyrics">歌词</a> | |
| <a href="#export">导出</a> | |
| <a href="#copy">文案</a> | |
| <a href="#covers">封面</a> | |
| </nav> | |
| </header> | |
| <Player ready={ready} orient={orient} setOrient={setOrient} /> | |
| <LyricsPanel toast={toast.show} /> | |
| <ExportPanel orient={orient} ready={ready} /> | |
| <CopyPanel toast={toast.show} /> | |
| <CoverPanel ready={ready} toast={toast.show} /> | |
| <footer className="mv-footer"> | |
| 画面为原创程序化动画(Canvas 2D + WebGL),所有渲染、导出都在你的浏览器本地完成,不上传任何数据。 | |
| <br /> | |
| 音乐《黑街》原唱陈雅雯,DJ 版 DJ鐘董,版权归原作者所有。 | |
| </footer> | |
| {toast.msg && <div className="mv-toast">{toast.msg}</div>} | |
| </div> | |
| ) | |
| } | |
| // ====================================================================== Player | |
| function Player({ ready, orient, setOrient }: { ready: boolean; orient: Orient; setOrient: (o: Orient) => void }) { | |
| const canvasRef = useRef<HTMLCanvasElement>(null) | |
| const audioRef = useRef<HTMLAudioElement>(null) | |
| const wrapRef = useRef<HTMLDivElement>(null) | |
| const rendererRef = useRef<Renderer | null>(null) | |
| const tRef = useRef(0) | |
| const dirty = useRef(true) | |
| const [playing, setPlaying] = useState(false) | |
| const [time, setTime] = useState(0) | |
| const [theater, setTheater] = useState(false) | |
| const [started, setStarted] = useState(false) | |
| const [fps, setFps] = useState(0) | |
| useEffect(() => { | |
| if (!canvasRef.current) return | |
| rendererRef.current = new Renderer(canvasRef.current) | |
| // the master peaks above 0 dBFS (+0.49 dB): leave ~1 dB headroom so the browser doesn't clip it | |
| if (audioRef.current) audioRef.current.volume = 0.89 | |
| }, []) | |
| useEffect(() => { | |
| const r = rendererRef.current | |
| if (!r) return | |
| const hi = window.devicePixelRatio > 1.5 && Math.max(window.innerWidth, window.innerHeight) > 1100 | |
| const [w, h] = hi ? [1600, 900] : [1280, 720] | |
| if (orient === 'landscape') r.setSize(w, h) | |
| else r.setSize(h, w) | |
| dirty.current = true | |
| }, [orient]) | |
| useEffect(() => { | |
| if (ready) dirty.current = true | |
| }, [ready]) | |
| useEffect(() => { | |
| let raf = 0 | |
| let last = performance.now() | |
| let frames = 0 | |
| let lastUi = 0 | |
| const loop = (now: number) => { | |
| raf = requestAnimationFrame(loop) | |
| const a = audioRef.current | |
| const r = rendererRef.current | |
| if (!r || !a) return | |
| const isPlaying = !a.paused && !a.ended | |
| if (isPlaying) { | |
| tRef.current = a.currentTime | |
| dirty.current = true | |
| } | |
| if (dirty.current) { | |
| r.render(tRef.current) | |
| dirty.current = false | |
| frames++ | |
| } | |
| if (now - lastUi > 120) { | |
| setTime(tRef.current) | |
| lastUi = now | |
| } | |
| if (now - last > 1000) { | |
| setFps(isPlaying ? Math.round((frames * 1000) / (now - last)) : 0) | |
| frames = 0 | |
| last = now | |
| } | |
| } | |
| raf = requestAnimationFrame(loop) | |
| return () => cancelAnimationFrame(raf) | |
| }, []) | |
| const toggle = useCallback(() => { | |
| const a = audioRef.current | |
| if (!a) return | |
| setStarted(true) | |
| if (a.paused) { | |
| if (a.ended || a.currentTime >= DURATION - 0.05) a.currentTime = 0 | |
| a.play().catch(() => {}) | |
| } else a.pause() | |
| }, []) | |
| const seek = useCallback((t: number) => { | |
| const a = audioRef.current | |
| const v = Math.max(0, Math.min(DURATION, t)) | |
| tRef.current = v | |
| if (a) a.currentTime = v | |
| dirty.current = true | |
| setTime(v) | |
| }, []) | |
| useEffect(() => { | |
| bus.time = () => audioRef.current?.currentTime ?? tRef.current | |
| bus.seek = seek | |
| bus.play = () => { | |
| setStarted(true) | |
| audioRef.current?.play().catch(() => {}) | |
| } | |
| bus.pause = () => audioRef.current?.pause() | |
| const onLyrics = () => (dirty.current = true) | |
| window.addEventListener('mv-lyrics', onLyrics) | |
| return () => window.removeEventListener('mv-lyrics', onLyrics) | |
| }, [seek]) | |
| useEffect(() => { | |
| const onKey = (e: KeyboardEvent) => { | |
| if ((e.target as HTMLElement)?.closest('input,textarea')) return | |
| if (e.code === 'Space') { | |
| e.preventDefault() | |
| toggle() | |
| } else if (e.code === 'ArrowRight') seek(tRef.current + 5) | |
| else if (e.code === 'ArrowLeft') seek(tRef.current - 5) | |
| else if (e.code === 'Escape') setTheater(false) | |
| } | |
| window.addEventListener('keydown', onKey) | |
| return () => window.removeEventListener('keydown', onKey) | |
| }, [toggle, seek]) | |
| const fullscreen = () => { | |
| const el = wrapRef.current as (HTMLDivElement & { webkitRequestFullscreen?: () => void }) | null | |
| if (!el) return | |
| if (document.fullscreenElement) { | |
| document.exitFullscreen().catch(() => {}) | |
| return | |
| } | |
| if (el.requestFullscreen) el.requestFullscreen().catch(() => setTheater(true)) | |
| else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen() | |
| else setTheater(true) | |
| } | |
| const scene = sceneAt(time) | |
| return ( | |
| <section id="player" className="mv-section"> | |
| <div className="mv-player-head"> | |
| <h2> | |
| <span className="mv-h-idx">01</span> 在线观看 | |
| </h2> | |
| <span className="mv-badge">16:9 · 1080P</span> | |
| </div> | |
| <div ref={wrapRef} className={`mv-stage-wrap ${orient} ${theater ? 'theater' : ''}`}> | |
| <div className={`mv-stage ${orient}`} onClick={toggle}> | |
| <canvas ref={canvasRef} className="mv-canvas" /> | |
| {!playing && ( | |
| <button className="mv-bigplay" aria-label="播放"> | |
| <svg viewBox="0 0 24 24" width="38" height="38"> | |
| <path d="M8 5v14l11-7z" fill="currentColor" /> | |
| </svg> | |
| {!started && <span>{ready ? '点击播放(建议戴耳机)' : '加载字体中…'}</span>} | |
| </button> | |
| )} | |
| </div> | |
| <div className="mv-controls"> | |
| <button className="mv-ctrl" onClick={toggle} aria-label={playing ? '暂停' : '播放'}> | |
| {playing ? ( | |
| <svg viewBox="0 0 24 24" width="22" height="22"> | |
| <path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor" /> | |
| </svg> | |
| ) : ( | |
| <svg viewBox="0 0 24 24" width="22" height="22"> | |
| <path d="M8 5v14l11-7z" fill="currentColor" /> | |
| </svg> | |
| )} | |
| </button> | |
| <span className="mv-time"> | |
| {fmt(time)} / {fmt(DURATION)} | |
| </span> | |
| <div className="mv-track"> | |
| <div className="mv-track-segs"> | |
| {SCENES.map((s) => ( | |
| <div key={s.id} className="mv-track-seg" style={{ width: `${((s.end - s.start) / DURATION) * 100}%`, background: s.color }} title={s.name} /> | |
| ))} | |
| </div> | |
| <div className="mv-track-fill" style={{ width: `${(time / DURATION) * 100}%` }} /> | |
| <input type="range" min={0} max={DURATION} step={0.01} value={time} onChange={(e) => seek(parseFloat(e.target.value))} aria-label="进度" /> | |
| </div> | |
| <span className="mv-fps">{fps ? `${fps} fps` : ''}</span> | |
| <button className="mv-ctrl" onClick={fullscreen} aria-label="全屏"> | |
| <svg viewBox="0 0 24 24" width="20" height="20"> | |
| <path d="M4 9V4h5v2H6v3zm10-5h6v5h-2V6h-4zM4 15h2v3h3v2H4zm14 3v-3h2v5h-6v-2z" fill="currentColor" /> | |
| </svg> | |
| </button> | |
| {theater && ( | |
| <button className="mv-ctrl" onClick={() => setTheater(false)}> | |
| ✕ | |
| </button> | |
| )} | |
| </div> | |
| </div> | |
| <div className="mv-chips"> | |
| {SCENES.map((s, i) => ( | |
| <button key={s.id} className={`mv-chip ${scene.id === s.id ? 'on' : ''}`} onClick={() => seek(s.start + 0.02)}> | |
| <i style={{ background: s.color }} /> | |
| <b>{String(i + 1).padStart(2, '0')}</b> {s.name} | |
| <em>{fmt(s.start)}</em> | |
| </button> | |
| ))} | |
| </div> | |
| <audio | |
| ref={audioRef} | |
| src={AUDIO_URL} | |
| preload="auto" | |
| onPlay={() => setPlaying(true)} | |
| onPause={() => setPlaying(false)} | |
| onEnded={() => { | |
| setPlaying(false) | |
| dirty.current = true | |
| }} | |
| /> | |
| </section> | |
| ) | |
| } | |
| // ====================================================================== Export | |
| function ExportPanel({ orient, ready }: { orient: Orient; ready: boolean }) { | |
| const o: Orient = orient | |
| const [res, setRes] = useState<'1080' | '720'>('1080') | |
| const [fps, setFps] = useState<24 | 30 | 60>(30) | |
| const [state, setState] = useState<'idle' | 'running' | 'done' | 'error'>('idle') | |
| const [prog, setProg] = useState({ stage: '', progress: 0, eta: 0, frame: 0, total: 0 }) | |
| const [result, setResult] = useState<(ExportResult & { url: string; name: string }) | null>(null) | |
| const [err, setErr] = useState('') | |
| const ctrl = useRef<AbortController | null>(null) | |
| const supported = useMemo(() => (typeof window !== 'undefined' ? webCodecsSupported() : true), []) | |
| const size = useMemo(() => { | |
| const [a, b] = res === '1080' ? [1920, 1080] : [1280, 720] | |
| return o === 'landscape' ? [a, b] : [b, a] | |
| }, [o, res]) | |
| const start = async () => { | |
| if (!ready) return | |
| ctrl.current = new AbortController() | |
| setState('running') | |
| setErr('') | |
| if (result) URL.revokeObjectURL(result.url) | |
| setResult(null) | |
| try { | |
| const r = await exportMp4({ | |
| width: size[0], | |
| height: size[1], | |
| fps, | |
| signal: ctrl.current.signal, | |
| onProgress: (p) => setProg((prev) => ({ ...prev, ...p, eta: p.eta ?? prev.eta, frame: p.frame ?? prev.frame, total: p.total ?? prev.total })), | |
| }) | |
| const url = URL.createObjectURL(r.blob) | |
| const name = `黑街_BLACK-STREET_${size[0]}x${size[1]}_${fps}fps.${r.ext}` | |
| setResult({ ...r, url, name }) | |
| setState('done') | |
| download(url, name) | |
| } catch (e) { | |
| if ((e as Error).name === 'AbortError') setState('idle') | |
| else { | |
| setErr((e as Error).message || String(e)) | |
| setState('error') | |
| } | |
| } | |
| } | |
| const frames = Math.ceil(DURATION * fps) | |
| return ( | |
| <section id="export" className="mv-section"> | |
| <h2> | |
| <span className="mv-h-idx">03</span> 导出 MP4 <small>浏览器本地渲染 · 不上传</small> | |
| </h2> | |
| <div className="mv-card mv-export"> | |
| <div className="mv-opt"> | |
| <label>分辨率</label> | |
| <div className="mv-seg"> | |
| <button className={res === '1080' ? 'on' : ''} onClick={() => setRes('1080')} disabled={state === 'running'}> | |
| 1080P | |
| </button> | |
| <button className={res === '720' ? 'on' : ''} onClick={() => setRes('720')} disabled={state === 'running'}> | |
| 720P(更快) | |
| </button> | |
| </div> | |
| </div> | |
| <div className="mv-opt"> | |
| <label>帧率</label> | |
| <div className="mv-seg"> | |
| {([24, 30, 60] as const).map((f) => ( | |
| <button key={f} className={fps === f ? 'on' : ''} onClick={() => setFps(f)} disabled={state === 'running'}> | |
| {f} fps | |
| </button> | |
| ))} | |
| </div> | |
| </div> | |
| <div className="mv-export-meta"> | |
| 输出:{size[0]}×{size[1]} · {fps}fps · H.264 + AAC · 共 {frames.toLocaleString()} 帧 · 时长 {fmt(DURATION)} | |
| {!supported && <div className="mv-warn">当前浏览器不支持 WebCodecs 快速编码,将使用实时录制(需要约 2.5 分钟)。推荐使用最新版 Chrome / Edge。</div>} | |
| </div> | |
| {state !== 'running' ? ( | |
| <button className="mv-primary" onClick={start} disabled={!ready}> | |
| {ready ? '开始导出 MP4' : '准备中…'} | |
| </button> | |
| ) : ( | |
| <div className="mv-progress"> | |
| <div className="mv-progress-bar"> | |
| <div style={{ width: `${(prog.progress * 100).toFixed(1)}%` }} /> | |
| </div> | |
| <div className="mv-progress-info"> | |
| <span> | |
| {prog.stage} {(prog.progress * 100).toFixed(1)}% | |
| {prog.total ? ` · ${prog.frame}/${prog.total} 帧` : ''} | |
| </span> | |
| <span>{prog.eta ? `预计剩余 ${fmt(prog.eta)}` : ''}</span> | |
| </div> | |
| <button className="mv-ghost" onClick={() => ctrl.current?.abort()}> | |
| 取消 | |
| </button> | |
| <p className="mv-hint">导出期间请保持本页面在前台,切到后台会变慢。</p> | |
| </div> | |
| )} | |
| {state === 'error' && <div className="mv-warn">导出失败:{err}</div>} | |
| {state === 'done' && result && ( | |
| <div className="mv-result"> | |
| <video src={result.url} controls playsInline className={o} /> | |
| <div> | |
| <a className="mv-primary" href={result.url} download={result.name}> | |
| 再次下载 {result.ext.toUpperCase()}({(result.blob.size / 1024 / 1024).toFixed(1)} MB) | |
| </a> | |
| {result.note && <p className="mv-hint">{result.note}</p>} | |
| </div> | |
| </div> | |
| )} | |
| </div> | |
| </section> | |
| ) | |
| } | |
| // ====================================================================== Copy | |
| function CopyPanel({ toast }: { toast: (m: string) => void }) { | |
| const [pid, setPid] = useState(PLATFORMS[0].id) | |
| const p = PLATFORMS.find((x) => x.id === pid)! | |
| const [titles, setTitles] = useState<Record<string, string>>(() => Object.fromEntries(PLATFORMS.map((x) => [x.id, x.titles[0]]))) | |
| const [descs, setDescs] = useState<Record<string, string>>(() => Object.fromEntries(PLATFORMS.map((x) => [x.id, x.desc]))) | |
| const [tags, setTags] = useState<Record<string, string[]>>(() => Object.fromEntries(PLATFORMS.map((x) => [x.id, [...x.tags]]))) | |
| const [newTag, setNewTag] = useState('') | |
| const title = titles[pid] | |
| const tcount = countChars(title) | |
| const myTags = tags[pid] | |
| const allTags = useMemo(() => Array.from(new Set([...p.tags, ...myTags])), [p, myTags]) | |
| const overTitle = tcount > p.titleLimit | |
| const overTags = p.tagLimit != null && myTags.length > p.tagLimit | |
| const doCopy = async (text: string, what: string) => { | |
| const ok = await copyText(text) | |
| toast(ok ? `已复制${what}` : '复制失败,请手动选择文本') | |
| } | |
| const toggleTag = (t: string) => setTags((prev) => ({ ...prev, [pid]: prev[pid].includes(t) ? prev[pid].filter((x) => x !== t) : [...prev[pid], t] })) | |
| const addTag = () => { | |
| const t = newTag.replace(/^#/, '').trim() | |
| if (!t) return | |
| setTags((prev) => ({ ...prev, [pid]: prev[pid].includes(t) ? prev[pid] : [...prev[pid], t] })) | |
| setNewTag('') | |
| } | |
| const tagText = formatTags(p, myTags) | |
| return ( | |
| <section id="copy" className="mv-section"> | |
| <h2> | |
| <span className="mv-h-idx">04</span> 发布文案 <small>标题 · 描述 · 话题,一键复制</small> | |
| </h2> | |
| <div className="mv-tabs"> | |
| {PLATFORMS.map((x) => ( | |
| <button key={x.id} className={x.id === pid ? 'on' : ''} onClick={() => setPid(x.id)} style={{ ['--pc' as string]: x.color }}> | |
| {x.name} | |
| </button> | |
| ))} | |
| </div> | |
| <div className="mv-card mv-copy" style={{ ['--pc' as string]: p.color }}> | |
| <div className="mv-copy-tip">{p.tip}</div> | |
| <div className="mv-field"> | |
| <div className="mv-field-head"> | |
| <label>标题</label> | |
| <span className={overTitle ? 'bad' : 'good'}> | |
| {tcount}/{p.titleLimit} 字 | |
| </span> | |
| <button className="mv-copybtn" onClick={() => doCopy(title, '标题')}> | |
| 复制标题 | |
| </button> | |
| </div> | |
| <input className="mv-input" value={title} onChange={(e) => setTitles((prev) => ({ ...prev, [pid]: e.target.value }))} /> | |
| <div className="mv-alts"> | |
| {p.titles.map((t) => ( | |
| <button key={t} className={t === title ? 'on' : ''} onClick={() => setTitles((prev) => ({ ...prev, [pid]: t }))}> | |
| {t} <em>{countChars(t)}字</em> | |
| </button> | |
| ))} | |
| </div> | |
| </div> | |
| <div className="mv-field"> | |
| <div className="mv-field-head"> | |
| <label>描述</label> | |
| <span className="good">{countChars(descs[pid])} 字</span> | |
| <button className="mv-copybtn" onClick={() => doCopy(descs[pid], '描述')}> | |
| 复制描述 | |
| </button> | |
| </div> | |
| <textarea className="mv-input" rows={p.id === 'bili' ? 12 : 6} value={descs[pid]} onChange={(e) => setDescs((prev) => ({ ...prev, [pid]: e.target.value }))} /> | |
| </div> | |
| <div className="mv-field"> | |
| <div className="mv-field-head"> | |
| <label>{p.tagStyle === 'comma' ? '标签' : '话题'}</label> | |
| <span className={overTags ? 'bad' : 'good'}> | |
| {myTags.length} | |
| {p.tagLimit != null ? `/${p.tagLimit}` : ''} 个{p.tagLimit == null ? '(不限)' : ''} | |
| </span> | |
| <button className="mv-copybtn" onClick={() => doCopy(tagText, p.tagStyle === 'comma' ? '标签' : '话题')}> | |
| 复制{p.tagStyle === 'comma' ? '标签' : '话题'} | |
| </button> | |
| </div> | |
| <div className="mv-tags"> | |
| {allTags.map((t) => ( | |
| <button key={t} className={myTags.includes(t) ? 'on' : ''} onClick={() => toggleTag(t)}> | |
| #{t} | |
| </button> | |
| ))} | |
| <span className="mv-addtag"> | |
| <input value={newTag} placeholder="添加话题" onChange={(e) => setNewTag(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && addTag()} /> | |
| <button onClick={addTag}>+</button> | |
| </span> | |
| </div> | |
| <pre className="mv-tagtext">{tagText}</pre> | |
| </div> | |
| <button className="mv-primary" onClick={() => doCopy(`${title}\n\n${descs[pid]}\n\n${tagText}`, '全部内容')}> | |
| 一键复制全部({p.name}) | |
| </button> | |
| {(overTitle || overTags) && <div className="mv-warn">有内容超出 {p.name} 的限制,请调整后再发布。</div>} | |
| </div> | |
| </section> | |
| ) | |
| } | |
| // ====================================================================== Covers | |
| function CoverPanel({ ready, toast }: { ready: boolean; toast: (m: string) => void }) { | |
| const [items, setItems] = useState<CoverItem[]>([]) | |
| const [sel, setSel] = useState<Set<string>>(new Set()) | |
| const [filter, setFilter] = useState<Ratio | 'all'>('all') | |
| const [busy, setBusy] = useState(false) | |
| const [view, setView] = useState<CoverItem | null>(null) | |
| const started = useRef(false) | |
| useEffect(() => { | |
| if (!ready || started.current) return | |
| started.current = true | |
| let cancelled = false | |
| ;(async () => { | |
| setBusy(true) | |
| for (const ratio of RATIOS) { | |
| for (const d of DESIGNS) { | |
| if (cancelled) return | |
| await new Promise((r) => setTimeout(r, 30)) | |
| try { | |
| const it = await renderCover(ratio, d) | |
| setItems((prev) => [...prev, it]) | |
| } catch (e) { | |
| console.warn('cover failed', e) | |
| } | |
| } | |
| } | |
| setBusy(false) | |
| })() | |
| return () => { | |
| cancelled = true | |
| } | |
| }, [ready]) | |
| const shown = items.filter((i) => filter === 'all' || i.ratio === filter) | |
| const toggle = (k: string) => | |
| setSel((prev) => { | |
| const n = new Set(prev) | |
| if (n.has(k)) n.delete(k) | |
| else n.add(k) | |
| return n | |
| }) | |
| const selected = items.filter((i) => sel.has(i.key)) | |
| const fileName = (i: CoverItem) => `黑街封面_${i.ratio.replace(':', 'x')}_${i.design.name}_${i.width}x${i.height}.jpg` | |
| const downloadSel = async () => { | |
| for (const i of selected) { | |
| download(i.url, fileName(i)) | |
| await new Promise((r) => setTimeout(r, 350)) | |
| } | |
| toast(`已下载 ${selected.length} 张封面`) | |
| } | |
| const zipSel = async () => { | |
| const files: Record<string, Uint8Array> = {} | |
| for (const i of selected) files[fileName(i)] = new Uint8Array(await i.blob.arrayBuffer()) | |
| const z = zipSync(files, { level: 0 }) | |
| const url = URL.createObjectURL(new Blob([z], { type: 'application/zip' })) | |
| download(url, `黑街封面_${selected.length}张.zip`) | |
| setTimeout(() => URL.revokeObjectURL(url), 5000) | |
| toast('ZIP 已生成') | |
| } | |
| return ( | |
| <section id="covers" className="mv-section"> | |
| <h2> | |
| <span className="mv-h-idx">05</span> 封面 <small>16:9 · 4:3 · 3:4 · 每种比例 {DESIGNS.length} 款,可多选</small> | |
| </h2> | |
| <div className="mv-cover-bar"> | |
| <div className="mv-seg"> | |
| {(['all', ...RATIOS] as const).map((r) => ( | |
| <button key={r} className={filter === r ? 'on' : ''} onClick={() => setFilter(r)}> | |
| {r === 'all' ? '全部' : `${r}(${RATIO_SIZE[r].join('×')})`} | |
| </button> | |
| ))} | |
| </div> | |
| <div className="mv-cover-actions"> | |
| <button className="mv-ghost" onClick={() => setSel(new Set([...sel, ...shown.map((i) => i.key)]))}> | |
| 全选{filter === 'all' ? '' : ' ' + filter} | |
| </button> | |
| <button className="mv-ghost" onClick={() => setSel(new Set())}> | |
| 清空 | |
| </button> | |
| <button className="mv-primary sm" disabled={!selected.length} onClick={downloadSel}> | |
| 下载选中({selected.length}) | |
| </button> | |
| <button className="mv-primary sm alt" disabled={!selected.length} onClick={zipSel}> | |
| 打包 ZIP | |
| </button> | |
| </div> | |
| </div> | |
| {busy && <div className="mv-hint">正在生成封面… {items.length}/{RATIOS.length * DESIGNS.length}</div>} | |
| <div className="mv-cover-grid"> | |
| {shown.map((i) => ( | |
| <div key={i.key} className={`mv-cover ${sel.has(i.key) ? 'on' : ''} r${i.ratio.replace(':', '')}`} onClick={() => toggle(i.key)}> | |
| <img src={i.url} alt={i.design.name} loading="lazy" /> | |
| <div className="mv-cover-check">{sel.has(i.key) ? '✓' : ''}</div> | |
| <div className="mv-cover-meta"> | |
| <b>{i.design.name}</b> | |
| <span>{i.ratio}</span> | |
| <button | |
| onClick={(e) => { | |
| e.stopPropagation() | |
| setView(i) | |
| }} | |
| > | |
| 大图 | |
| </button> | |
| </div> | |
| </div> | |
| ))} | |
| </div> | |
| {view && ( | |
| <div className="mv-lightbox" onClick={() => setView(null)}> | |
| <img src={view.url} alt={view.design.name} /> | |
| <div className="mv-lightbox-bar" onClick={(e) => e.stopPropagation()}> | |
| <span> | |
| {view.design.name} · {view.ratio} · {view.width}×{view.height} | |
| </span> | |
| <button className="mv-primary sm" onClick={() => download(view.url, fileName(view))}> | |
| 下载 | |
| </button> | |
| <button className="mv-ghost" onClick={() => setView(null)}> | |
| 关闭 | |
| </button> | |
| </div> | |
| </div> | |
| )} | |
| </section> | |
| ) | |
| } | |
| // ====================================================================== Lyrics | |
| const fmtLrc = (t: number) => { | |
| const m = Math.floor(t / 60) | |
| const sec = t - m * 60 | |
| return `[${String(m).padStart(2, '0')}:${sec.toFixed(2).padStart(5, '0')}]` | |
| } | |
| function LyricsPanel({ toast }: { toast: (m: string) => void }) { | |
| const [text, setText] = useState('') | |
| const [count, setCount] = useState(0) | |
| const [offset, setOffset] = useState(0) | |
| const [tap, setTap] = useState<{ lines: string[]; times: number[] } | null>(null) | |
| useEffect(() => { | |
| const saved = loadSavedLyrics() | |
| setText(saved) | |
| setCount(lyricCount()) | |
| if (lyricCount()) ensureLyricFont() | |
| }, []) | |
| const notify = () => window.dispatchEvent(new Event('mv-lyrics')) | |
| const apply = (src = text) => { | |
| const n = setLyrics(src) | |
| setCount(n) | |
| notify() | |
| if (n) ensureLyricFont() | |
| toast(n ? `已应用 ${n} 句歌词` : '没有识别到时间轴,请用「打轴」逐句标记') | |
| } | |
| const plainLines = () => | |
| text | |
| .split(/\r?\n/) | |
| .map((l) => l.replace(/\[[^\]]*\]/g, '').trim()) | |
| .filter(Boolean) | |
| const startTap = () => { | |
| const ls = plainLines() | |
| if (!ls.length) { | |
| toast('请先粘贴歌词文本') | |
| return | |
| } | |
| setTap({ lines: ls, times: [] }) | |
| bus.seek(0) | |
| bus.play() | |
| } | |
| const stamp = useCallback(() => { | |
| setTap((cur) => { | |
| if (!cur) return cur | |
| const times = [...cur.times, bus.time()] | |
| if (times.length >= cur.lines.length) { | |
| const lrc = cur.lines.map((l, i) => fmtLrc(times[i]) + l).join('\n') | |
| setText(lrc) | |
| const n = setLyrics(lrc) | |
| setCount(n) | |
| notify() | |
| ensureLyricFont() | |
| bus.pause() | |
| toast(`打轴完成:${n} 句`) | |
| return null | |
| } | |
| return { ...cur, times } | |
| }) | |
| }, [toast]) | |
| useEffect(() => { | |
| if (!tap) return | |
| const onKey = (e: KeyboardEvent) => { | |
| if (e.code === 'Enter' || e.code === 'KeyJ') { | |
| e.preventDefault() | |
| stamp() | |
| } | |
| } | |
| window.addEventListener('keydown', onKey) | |
| return () => window.removeEventListener('keydown', onKey) | |
| }, [tap, stamp]) | |
| const nudge = (d: number) => { | |
| const v = Math.round((getLyricOffset() + d) * 10) / 10 | |
| setLyricOffset(v) | |
| setOffset(v) | |
| notify() | |
| } | |
| const copyLrc = async () => { | |
| const ok = await copyText(text) | |
| toast(ok ? '已复制 LRC' : '复制失败') | |
| } | |
| const preview = parseLrc(text).length | |
| return ( | |
| <section id="lyrics" className="mv-section"> | |
| <h2> | |
| <span className="mv-h-idx">02</span> 歌词 <small>逐字弹出 · 卡拉OK 填色 · 跟随鼓点跳动 · 会一起导出到 MP4</small> | |
| </h2> | |
| <div className="mv-card mv-lyrics"> | |
| <p className="mv-hint"> | |
| 粘贴带时间轴的 LRC 歌词(音乐平台一般都能下载),或者粘贴纯文本歌词后点「打轴」:音乐会从头播放,每唱到一句按一下 Enter(或 J 键 / 下方按钮),就会自动生成时间轴。 | |
| </p> | |
| {!tap ? ( | |
| <> | |
| <textarea className="mv-input" rows={8} value={text} placeholder={'[00:12.30]第一句歌词\n[00:16.80]第二句歌词\n……'} onChange={(e) => setText(e.target.value)} /> | |
| <div className="mv-lyrics-bar"> | |
| <button className="mv-primary sm" onClick={() => apply()}> | |
| 应用歌词{preview ? `(${preview} 句)` : ''} | |
| </button> | |
| <button className="mv-ghost" onClick={startTap}> | |
| 打轴(边听边按) | |
| </button> | |
| <button className="mv-ghost" onClick={copyLrc} disabled={!text}> | |
| 复制 LRC | |
| </button> | |
| <button | |
| className="mv-ghost" | |
| onClick={() => { | |
| setText('') | |
| apply('') | |
| }} | |
| > | |
| 清空 | |
| </button> | |
| <span className="mv-lyrics-offset"> | |
| 时间微调 | |
| <button className="mv-ghost" onClick={() => nudge(-0.1)}> | |
| −0.1s | |
| </button> | |
| <b>{offset >= 0 ? '+' : ''}{offset.toFixed(1)}s</b> | |
| <button className="mv-ghost" onClick={() => nudge(0.1)}> | |
| +0.1s | |
| </button> | |
| </span> | |
| <span className="mv-hint">当前已应用 {count} 句</span> | |
| </div> | |
| </> | |
| ) : ( | |
| <div className="mv-tap"> | |
| <div className="mv-tap-prog"> | |
| 第 {tap.times.length + 1} / {tap.lines.length} 句 | |
| </div> | |
| <div className="mv-tap-now">{tap.lines[tap.times.length]}</div> | |
| <div className="mv-tap-next">{tap.lines[tap.times.length + 1] ?? '(最后一句)'}</div> | |
| <div className="mv-lyrics-bar"> | |
| <button className="mv-primary" onClick={stamp}> | |
| 唱到这一句了(Enter) | |
| </button> | |
| <button className="mv-ghost" onClick={() => setTap((c) => (c && c.times.length ? { ...c, times: c.times.slice(0, -1) } : c))}> | |
| 撤销上一句 | |
| </button> | |
| <button | |
| className="mv-ghost" | |
| onClick={() => { | |
| setTap(null) | |
| bus.pause() | |
| }} | |
| > | |
| 退出打轴 | |
| </button> | |
| </div> | |
| </div> | |
| )} | |
| </div> | |
| </section> | |
| ) | |
| } | |