Compare commits

...

4 Commits

Author SHA1 Message Date
hexin-codex-bot 2c7b81981c fix: preserve continuous drawer and heart exit animations
Build and deploy Docker / deploy (push) Failing after 6m29s
2026-10-08 16:12:33 +08:00
hexin-codex-bot c0b752da3a feat: add true gesture-driven full-viewport video feed and polished motion 2026-10-08 16:09:57 +08:00
hexin-codex-bot 693990d9fb fix: enable mobile swipe through playback layer and sound control 2026-10-08 15:20:27 +08:00
hexin-codex-bot c9606a6d0f feat: add generated local videos and portable build setup
Build and deploy Docker / deploy (push) Failing after 7m7s
2026-10-08 14:18:38 +08:00
19 changed files with 560 additions and 215 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ RUN pnpm install --frozen-lockfile --ignore-scripts
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm typecheck && pnpm build
RUN pnpm typecheck && pnpm test && pnpm build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0
+5 -2
View File
@@ -12,11 +12,14 @@ pnpm install --frozen-lockfile
pnpm dev
```
浏览器打开 http://localhost:3000 。手机与电脑自适应:手机全屏触摸上下切换,电脑宽屏播放,支持滚轮、上下方向键及右侧切换按钮。空格暂停,M 切换声音。
浏览器打开 http://localhost:3000 。页面直接铺满浏览器宽度,没有侧栏或固定宽度的播放器外框。手机保留底部导航,电脑使用浮层控制。
上下拖动时,上下两条视频会随鼠标或手指一起移动;轻拖后松开回弹,超过约 19% 屏幕高度或快速甩动则翻页。三条真实页面循环复用,避免切换时闪屏。电脑也支持滚轮、上下方向键及右侧切换按钮。空格暂停,M 切换声音,斜杠搜索。
## 交互
- 三段本地 MP4 无限循环切换,单击暂停、双击点赞、拖动进度、静音/开启声音、桌面全屏。
- 三段本地 MP4 无限循环切换,单击暂停、双击位置爱心与粒子、拖动进度、静音/开启声音、桌面全屏。
- 点赞收藏弹性反馈,评论面板滑入滑出,手机评论面板可拖动顶部把手向下关闭;系统减少动态效果设置受到尊重。
- 点赞、收藏、关注按视频保存在本机 localStorage,无需账号。
- 搜索默认数据、标签搜索、分享视频专属链接、评论抽屉及本次会话评论。
- 其他导航提供演示提示,不包含其他业务页面。
+119
View File
@@ -0,0 +1,119 @@
import { Children, forwardRef, useEffect, useImperativeHandle, useRef, type ReactNode, type PointerEvent, type WheelEvent } from 'react';
import { flushSync } from 'react-dom';
import { swipeDirection } from '../lib/gestures';
export type SwipeFeedHandle = { next: (direction: number) => void };
type Props = { children: ReactNode; onChange: (direction: number) => void; disabled: boolean };
/** Three live pages share one moving track, so adjacent videos stay visible during a gesture. */
export const SwipeFeed = forwardRef<SwipeFeedHandle, Props>(function SwipeFeed({ children, onChange, disabled }, ref) {
const viewport = useRef<HTMLDivElement>(null);
const track = useRef<HTMLDivElement>(null);
const gesture = useRef({ active: false, startY: 0, lastY: 0, lastTime: 0, velocity: 0, moved: false });
const offset = useRef(0);
const settling = useRef(false);
const suppressClickUntil = useRef(0);
const wheelTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const wheelCooldown = useRef(0);
const finishTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => () => {
if (wheelTimer.current) clearTimeout(wheelTimer.current);
if (finishTimer.current) clearTimeout(finishTimer.current);
}, []);
function move(y: number) {
const height = viewport.current?.clientHeight || 1;
offset.current = Math.max(-height, Math.min(height, y));
if (track.current) track.current.style.transform = `translate3d(0, ${offset.current}px, 0)`;
}
function settle(direction: number) {
const node = track.current;
if (!node || settling.current) return;
settling.current = true;
gesture.current.active = false;
const height = viewport.current?.clientHeight || 1;
const target = -direction * height;
const distance = Math.abs(target - offset.current);
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const duration = reduced ? 0 : Math.min(460, Math.max(240, distance / height * 420));
node.style.transition = `transform ${duration}ms cubic-bezier(.22,.72,.18,1)`;
// Flush the drag position before applying the landing position.
node.getBoundingClientRect();
move(target);
viewport.current?.setAttribute('data-moving', 'true');
const finish = () => {
node.removeEventListener('transitionend', ended);
if (finishTimer.current) clearTimeout(finishTimer.current);
node.style.transition = 'none';
// Update slide positions and reset the shared track in the same paint.
if (direction) flushSync(() => onChange(direction));
move(0);
settling.current = false;
wheelCooldown.current = performance.now() + 160;
viewport.current?.removeAttribute('data-moving');
};
const ended = (event: TransitionEvent) => { if (event.target === node) finish(); };
node.addEventListener('transitionend', ended);
finishTimer.current = setTimeout(finish, duration + 50);
}
useImperativeHandle(ref, () => ({ next(direction) { if (!disabled) settle(Math.sign(direction)); } }));
function pointerDown(event: PointerEvent<HTMLDivElement>) {
if (disabled || settling.current || event.button !== 0 || (event.target as HTMLElement).closest('button:not(.video-hit),input,a')) return;
if (wheelTimer.current) clearTimeout(wheelTimer.current);
gesture.current = { active: true, startY: event.clientY - offset.current, lastY: event.clientY, lastTime: performance.now(), velocity: 0, moved: false };
(event.target as HTMLElement).setPointerCapture(event.pointerId);
}
function pointerMove(event: PointerEvent<HTMLDivElement>) {
const state = gesture.current;
if (!state.active) return;
const now = performance.now();
const elapsed = now - state.lastTime;
if (elapsed > 0) state.velocity = state.velocity * .35 + (event.clientY - state.lastY) / elapsed * .65;
state.lastY = event.clientY;
state.lastTime = now;
const dy = event.clientY - state.startY;
if (Math.abs(dy) > 5) state.moved = true;
if (state.moved) {
event.preventDefault();
suppressClickUntil.current = performance.now() + 350;
viewport.current?.setAttribute('data-moving', 'true');
move(dy);
}
}
function pointerUp(event: PointerEvent<HTMLDivElement>) {
const state = gesture.current;
if (!state.active) return;
state.active = false;
if (!state.moved) return;
event.preventDefault();
suppressClickUntil.current = performance.now() + 400;
const height = viewport.current?.clientHeight || 1;
const velocity = performance.now() - state.lastTime < 100 ? state.velocity : 0;
settle(swipeDirection(offset.current, velocity, height));
}
function wheel(event: WheelEvent<HTMLDivElement>) {
if (disabled || event.ctrlKey || Math.abs(event.deltaY) < Math.abs(event.deltaX)) return;
if (settling.current || performance.now() < wheelCooldown.current) return;
const unit = event.deltaMode === 1 ? 20 : event.deltaMode === 2 ? (viewport.current?.clientHeight || 800) : 1;
viewport.current?.setAttribute('data-moving', 'true');
move(offset.current - event.deltaY * unit);
if (wheelTimer.current) clearTimeout(wheelTimer.current);
wheelTimer.current = setTimeout(() => settle(Math.abs(offset.current) > 35 ? (offset.current < 0 ? 1 : -1) : 0), 90);
}
return <div ref={viewport} className="feed-viewport" aria-label="上下滑动视频流"
onPointerDown={pointerDown} onPointerMove={pointerMove} onPointerUp={pointerUp}
onPointerCancel={() => { if (gesture.current.active) { gesture.current.active = false; settle(0); } }}
onWheel={wheel}
onClickCapture={event => { if (performance.now() < suppressClickUntil.current || settling.current) { event.preventDefault(); event.stopPropagation(); } }}>
<div ref={track} className="feed-track">{Children.toArray(children)}</div>
</div>;
});
+81
View File
@@ -0,0 +1,81 @@
import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { Heart, MessageCircle, Bookmark, Share2, Plus, Play, Pause, Volume2, VolumeX, Music2, Maximize, Check, MapPin } from 'lucide-react';
import { compact, type VideoItem } from '../lib/videos';
export type Reaction = { liked?: boolean; saved?: boolean; followed?: boolean };
type Props = {
item: VideoItem; position: number; active: boolean; muted: boolean; playing: boolean;
reaction: Reaction; commentCount: number;
setPlaying: (value: boolean) => void; toggleMuted: () => void;
onReact: (field: keyof Reaction, force?: boolean) => void;
onComment: () => void; onShare: () => void; onTag: (tag: string) => void;
};
export function VideoCard({ item, position, active, muted, playing, reaction, commentCount, setPlaying, toggleMuted, onReact, onComment, onShare, onTag }: Props) {
const video = useRef<HTMLVideoElement>(null);
const card = useRef<HTMLElement>(null);
const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [progress, setProgress] = useState(0);
const [duration, setDuration] = useState(8);
const [failed, setFailed] = useState(false);
const [hearts, setHearts] = useState<{ id: number; x: number; y: number }[]>([]);
useEffect(() => {
const element = video.current;
if (!element) return;
let cancelled = false;
if (active && playing) element.play().catch(() => { if (!cancelled) setPlaying(false); });
else element.pause();
if (!active) { element.currentTime = 0; setProgress(0); }
return () => { cancelled = true; };
}, [active, playing, setPlaying]);
useEffect(() => () => { if (clickTimer.current) clearTimeout(clickTimer.current); }, []);
const time = (seconds: number) => `00:${Math.floor(seconds).toString().padStart(2, '0')}`;
return <article ref={card} className={`video-page scene-${item.id} ${active ? 'is-active' : ''}`}
style={{ transform: `translate3d(0, ${position * 100}%, 0)` }} aria-hidden={!active} inert={!active} aria-label={item.title}>
<video ref={video} className="video" src={item.src} poster={item.poster} loop playsInline
muted={!active || muted} preload="auto" onTimeUpdate={event => { if (active) setProgress(event.currentTarget.currentTime); }}
onLoadedMetadata={event => setDuration(event.currentTarget.duration)} onError={() => setFailed(true)} />
<div className="scrim" />
<button className="video-hit" aria-label={playing ? '暂停视频' : '播放视频'}
onClick={() => { if (clickTimer.current) clearTimeout(clickTimer.current); clickTimer.current = setTimeout(() => setPlaying(!playing), 220); }}
onDoubleClick={event => {
if (clickTimer.current) clearTimeout(clickTimer.current);
onReact('liked', true);
const bounds = card.current!.getBoundingClientRect();
setHearts(previous => [...previous.slice(-4), { id: Date.now(), x: event.clientX - bounds.left, y: event.clientY - bounds.top }]);
}} />
<div className="scene-copy" aria-hidden="true"><span>{item.label}</span><strong>{item.subtitle}</strong><i>THE LITTLE THINGS. THE BIG FEELINGS.</i></div>
{active && !playing && !failed && <span className="paused"><Play size={58} fill="currentColor" /></span>}
{hearts.map(heart => <span key={heart.id} className="heart-burst" style={{ left: heart.x, top: heart.y }} onAnimationEnd={event => { if (event.target === event.currentTarget) setHearts(previous => previous.filter(h => h.id !== heart.id)); }}><Heart size={112} fill="currentColor" /><i /><i /><i /><i /></span>)}
{failed && <div className="video-error">视频暂时无法加载<button onClick={() => { setFailed(false); video.current?.load(); setPlaying(true); }}>重新加载</button></div>}
<div className="video-info"><span className="location"><MapPin size={13} />{item.location}<span>·</span>精选风景</span>
<h2>@{item.author}<span className="verified"><Check size={11} /></span></h2>
<h3>{item.title}</h3><p>{item.description}</p>
<div className="tags">{item.tags.map(tag => <button key={tag} onClick={() => onTag(tag)}>#{tag}</button>)}</div>
<div className="music"><Music2 size={15} /><span>{item.music}</span><span className={`music-bars ${active && playing ? 'playing' : ''}`}><i /><i /><i /><i /></span></div>
</div>
<div className="actions">
<button className={`avatar ${reaction.followed ? 'following' : ''}`} style={{ background: item.color }} aria-label={reaction.followed ? '取消关注作者' : '关注作者'} aria-pressed={!!reaction.followed} onClick={() => onReact('followed')}>
{item.avatar}<span key={String(reaction.followed)}>{reaction.followed ? <Check size={13} /> : <Plus size={13} />}</span>
</button>
<button className={`action ${reaction.liked ? 'liked' : ''}`} aria-label="点赞" aria-pressed={!!reaction.liked} onClick={() => onReact('liked')}><Heart fill="currentColor" /><span key={String(reaction.liked)}>{compact(item.likes + (reaction.liked ? 1 : 0))}</span></button>
<button className="action" aria-label="查看评论" onClick={onComment}><MessageCircle fill="currentColor" /><span>{item.comments + commentCount}</span></button>
<button className={`action ${reaction.saved ? 'saved' : ''}`} aria-label="收藏" aria-pressed={!!reaction.saved} onClick={() => onReact('saved')}><Bookmark fill="currentColor" /><span key={String(reaction.saved)}>{compact(item.saves + (reaction.saved ? 1 : 0))}</span></button>
<button className="action" aria-label="分享视频" onClick={onShare}><Share2 fill="currentColor" /><span>分享</span></button>
<span className={`record ${active && playing ? 'spinning' : ''}`}><span style={{ background: item.color }}><Music2 size={17} /></span></span>
</div>
<div className="player-controls">
<input className="progress" type="range" aria-label="播放进度" min="0" max={duration || 8} step="0.05" value={progress}
style={{ '--progress': `${progress / (duration || 8) * 100}%` } as CSSProperties}
onChange={event => { const value = Number(event.target.value); if (video.current) video.current.currentTime = value; setProgress(value); }} />
<div className="control-row"><button aria-label={playing ? '暂停' : '播放'} onClick={() => setPlaying(!playing)}>{playing ? <Pause size={18} fill="currentColor" /> : <Play size={18} fill="currentColor" />}</button>
<span className="time">{time(progress)} <span>/ {time(duration)}</span></span><span className="control-hint">上下拖动或滚动,发现下一个瞬间</span>
<span className="quality">高清 <small>HD</small></span>
<button aria-label={muted ? '开启声音' : '静音'} onClick={toggleMuted}>{muted ? <VolumeX size={20} /> : <Volume2 size={20} />}</button>
<button aria-label="全屏" onClick={() => { if (document.fullscreenElement) document.exitFullscreen(); else document.documentElement.requestFullscreen?.().catch(() => {}); }}><Maximize size={19} /></button>
</div>
</div>
</article>;
}
+12
View File
@@ -0,0 +1,12 @@
/** Positive movement means pulling the previous page down; negative means pushing to the next. */
export function swipeDirection(distance: number, velocity: number, height: number): -1 | 0 | 1 {
if (height <= 0) return 0;
const committed = Math.abs(distance) > height * .19 || (Math.abs(velocity) > .4 && Math.abs(distance) > 20);
return committed ? (distance < 0 ? 1 : -1) : 0;
}
/** Three unique videos are kept mounted and repositioned around the active page. */
export function pagePosition(videoIndex: number, activeIndex: number): -1 | 0 | 1 {
const relative = (videoIndex - activeIndex + 3) % 3;
return relative === 2 ? -1 : relative as 0 | 1;
}
+1 -1
View File
@@ -1,3 +1,3 @@
import type { NextConfig } from 'next';
const config: NextConfig = { output: 'standalone', poweredByHeader: false, reactStrictMode: true };
const config: NextConfig = { output: process.platform === 'win32' ? undefined : 'standalone', poweredByHeader: false, reactStrictMode: true };
export default config;
+26 -5
View File
@@ -1,7 +1,28 @@
{
"name": "tiktok-ui", "version": "1.0.0", "private": true,
"scripts": {"dev":"next dev --hostname 0.0.0.0", "build":"next build", "start":"next start --hostname 0.0.0.0", "typecheck":"tsc --noEmit", "generate:videos":"node scripts/generate-videos.mjs"},
"dependencies": {"next":"^15.5.0", "react":"^19.1.0", "react-dom":"^19.1.0", "lucide-react":"^0.468.0"},
"devDependencies": {"typescript":"^5.9.0", "@types/node":"^22.0.0", "@types/react":"^19.0.0", "@types/react-dom":"^19.0.0", "@napi-rs/canvas":"^0.1.80", "ffmpeg-static":"^5.2.0"},
"packageManager":"pnpm@10.28.2"
"name": "tiktok-ui",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev --hostname 0.0.0.0",
"build": "next build",
"start": "next start --hostname 0.0.0.0",
"typecheck": "tsc --noEmit",
"test": "node --test tests/gestures.test.mjs",
"generate:videos": "node scripts/generate-videos.mjs"
},
"dependencies": {
"lucide-react": "^0.468.0",
"next": "^15.5.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@ffmpeg-installer/ffmpeg": "^1.1.0",
"@napi-rs/canvas": "^0.1.80",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"typescript": "^5.9.0"
},
"packageManager": "pnpm@10.28.2"
}
+156 -43
View File
@@ -1,46 +1,159 @@
import Head from 'next/head';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Heart, MessageCircle, Bookmark, Share2, Plus, Play, Pause, Volume2, VolumeX, ChevronUp, ChevronDown, Search, Home, Compass, Users, Music2, Maximize, X, Check, MapPin, Send, ArrowUpRight, TvMinimal, Ellipsis, UserRound } from 'lucide-react';
import { videos, compact } from '../lib/videos';
type Reaction = { liked?:boolean; saved?:boolean; followed?:boolean };
type Comment = {name:string; text:string};
const initialComments:Comment[]=[{name:'小岛同学',text:'这一刻,连时间都慢下来了。'},{name:'今天也要开心',text:'好喜欢这个氛围 ✨'},{name:'路过人间',text:'收藏了,留给忙碌的一天。'}];
export default function Feed(){
const [index,setIndex]=useState(0),[playing,setPlaying]=useState(true),[muted,setMuted]=useState(true),[progress,setProgress]=useState(0),[duration,setDuration]=useState(8),[reactions,setReactions]=useState<Record<string,Reaction>>({}),[ready,setReady]=useState(false),[panel,setPanel]=useState<'comments'|'search'|null>(null),[toast,setToast]=useState(''),[burst,setBurst]=useState(false),[query,setQuery]=useState(''),[draft,setDraft]=useState(''),[comments,setComments]=useState<Record<string,Comment[]>>({}),[tab,setTab]=useState('推荐'),[error,setError]=useState(false);
const video=useRef<HTMLVideoElement>(null),stage=useRef<HTMLElement>(null),touch=useRef({x:0,y:0}),lastScroll=useRef(0),clickTimer=useRef<ReturnType<typeof setTimeout>|null>(null),toastTimer=useRef<ReturnType<typeof setTimeout>|null>(null),burstTimer=useRef<ReturnType<typeof setTimeout>|null>(null);
const item=videos[index],reaction=reactions[item.id]||{};
const notify=useCallback((text:string)=>{setToast(text);if(toastTimer.current)clearTimeout(toastTimer.current);toastTimer.current=setTimeout(()=>setToast(''),2400);},[]);
useEffect(()=>{try{const data=JSON.parse(localStorage.getItem('flow-reactions')||'{}');if(data && typeof data==='object' && !Array.isArray(data))setReactions(data);}catch{}setReady(true);const id=new URLSearchParams(location.search).get('video');const found=videos.findIndex(v=>v.id===id);if(found>=0)setIndex(found);return()=>{if(clickTimer.current)clearTimeout(clickTimer.current);if(toastTimer.current)clearTimeout(toastTimer.current);if(burstTimer.current)clearTimeout(burstTimer.current);};},[]);
useEffect(()=>{if(ready)try{localStorage.setItem('flow-reactions',JSON.stringify(reactions));}catch{}},[reactions,ready]);
const next=useCallback((direction:number)=>{setIndex(i=>(i+direction+videos.length)%videos.length);setProgress(0);setPlaying(true);setError(false);setBurst(false);setDraft('');if(clickTimer.current)clearTimeout(clickTimer.current);},[]);
useEffect(()=>{const el=video.current;if(!el)return;if(playing){el.play().catch(()=>setPlaying(false));}else el.pause();},[index,playing]);
useEffect(()=>{function key(e:KeyboardEvent){if((e.target as HTMLElement).closest('input,textarea,button')||panel)return;if(e.code==='ArrowDown'||e.code==='ArrowUp'){e.preventDefault();next(e.code==='ArrowDown'?1:-1);}if(e.code==='Space'){e.preventDefault();setPlaying(p=>!p);}if(e.code==='KeyM')setMuted(m=>!m);}window.addEventListener('keydown',key);return()=>window.removeEventListener('keydown',key);},[next,panel]);
useEffect(()=>{const el=stage.current;if(!el)return;const wheel=(e:WheelEvent)=>{if(panel||Math.abs(e.deltaY)<12||e.ctrlKey)return;e.preventDefault();if(Date.now()-lastScroll.current<750)return;lastScroll.current=Date.now();next(e.deltaY>0?1:-1);};el.addEventListener('wheel',wheel,{passive:false});return()=>el.removeEventListener('wheel',wheel);},[next,panel]);
useEffect(()=>{if(!panel)return;const before=document.activeElement as HTMLElement;const dialog=document.querySelector<HTMLElement>('[role="dialog"]');dialog?.querySelector<HTMLElement>('button,input')?.focus();const key=(e:KeyboardEvent)=>{if(e.key==='Escape')setPanel(null);if(e.key==='Tab'){const list=dialog?.querySelectorAll<HTMLElement>('button,input,[tabindex="0"]');if(!list?.length)return;const first=list[0],last=list[list.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}}};document.addEventListener('keydown',key);return()=>{document.removeEventListener('keydown',key);before?.focus();};},[panel]);
function toggle(field:keyof Reaction){setReactions(r=>({...r,[item.id]:{...r[item.id],[field]:!r[item.id]?.[field]}}));}
function like(){setReactions(r=>({...r,[item.id]:{...r[item.id],liked:true}}));setBurst(true);if(burstTimer.current)clearTimeout(burstTimer.current);burstTimer.current=setTimeout(()=>setBurst(false),800);}
async function share(){const url=`${location.origin}/?video=${item.id}`;try{if(navigator.share){await navigator.share({title:item.title,url});}else{await navigator.clipboard.writeText(url);notify('视频链接已复制');}}catch(e){if((e as Error).name!=='AbortError')notify('请复制地址栏链接进行分享');}}
const time=(s:number)=>`00:${Math.floor(s).toString().padStart(2,'0')}`;
const results=videos.filter(v=>`${v.title}${v.author}${v.tags.join('')}`.includes(query.trim()));
return <><Head><title>瞬间 FLOW · 发现生活的另一面</title><meta name="description" content="沉浸式短视频体验,记录每一个值得停留的瞬间。"/><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"/><meta name="theme-color" content="#0b0b0e"/></Head>
<div className="app-shell">
<aside className="sidebar"><a className="brand" href="/" aria-label="瞬间首页"><span className="brand-mark"><Music2 size={28}/></span>瞬间<span className="brand-en">FLOW</span></a><button className="search-box" onClick={()=>setPanel('search')}><Search size={19}/><span>搜索感兴趣的内容</span><kbd>/</kbd></button><nav>{[{name:'推荐',icon:Home},{name:'发现',icon:Compass},{name:'关注',icon:Users}].map(({name,icon:Icon})=><button key={name} className={`nav-item ${tab===name?'active':''}`} onClick={()=>{setTab(name);if(name==='发现')setPanel('search');if(name==='关注')notify('关注作者后,关注标记会保存在此设备');}}><Icon size={23}/>{name}{name==='推荐'&&<span className="active-dot"/>}</button>)}</nav><div className="sidebar-line"/><p className="sidebar-label">精选频道</p>{['生活的浪漫','自然放映厅','城市漫游'].map((label,i)=><button key={label} className="channel" onClick={()=>{setIndex(i);setProgress(0);setPlaying(true);setError(false);}}><span className={`channel-dot dot-${i}`}/>{label}<ArrowUpRight size={14}/></button>)}<div className="sidebar-bottom"><div className="mini-brand">每一刻,都值得被看见<span>MAKE EVERY MOMENT COUNT.</span></div><p>关于瞬间 · 使用指南 · 联系我们</p><p>© 2026 瞬间 FLOW</p><span className="demo-pill"><span/>本地演示 · 无需登录</span></div></aside>
<main className="main"><header className="desktop-header"><div><span className="eyebrow">FOR YOU</span><h1>发现生活的另一面<span>精选推荐</span></h1></div><span className="header-note"><span/> 偶遇一个好瞬间</span></header>
<section ref={stage} className={`stage scene-${item.id}`} aria-label="短视频播放器" onTouchStart={e=>{touch.current={x:e.touches[0].clientX,y:e.touches[0].clientY};}} onTouchEnd={e=>{if(panel||(e.target as HTMLElement).closest('button,input'))return;const dy=e.changedTouches[0].clientY-touch.current.y,dx=e.changedTouches[0].clientX-touch.current.x;if(Math.abs(dy)>55&&Math.abs(dy)>Math.abs(dx))next(dy<0?1:-1);}}>
<video key={item.id} ref={video} className="video" src={item.src} poster={item.poster} loop playsInline muted={muted} autoPlay preload="auto" onTimeUpdate={e=>setProgress(e.currentTarget.currentTime)} onLoadedMetadata={e=>setDuration(e.currentTarget.duration)} onPlay={()=>setPlaying(true)} onPause={()=>setPlaying(false)} onError={()=>{setError(true);setPlaying(false);}}/>
<div className="scrim"/><button className="video-hit" aria-label={playing?'暂停视频':'播放视频'} onClick={()=>{if(clickTimer.current)clearTimeout(clickTimer.current);clickTimer.current=setTimeout(()=>setPlaying(p=>!p),220);}} onDoubleClick={()=>{if(clickTimer.current)clearTimeout(clickTimer.current);like();}}/>
<div className="mobile-top"><TvMinimal size={23}/><div><button onClick={()=>notify('点击作者头像即可关注')}>关注</button><button className="selected" onClick={()=>setTab('推荐')}>推荐</button></div><button aria-label="搜索视频" onClick={()=>setPanel('search')}><Search size={24}/></button></div>
<div className="stage-top"><span className="curated"><span/> 今日精选</span><span className="location"><MapPin size={14}/>{item.location}</span><button aria-label={muted?'开启声音':'静音'} className="sound-top" onClick={()=>setMuted(m=>!m)}>{muted?<VolumeX size={19}/>:<Volume2 size={19}/>}</button></div>
<div className="scene-copy" aria-hidden="true"><span>{item.label}</span><strong>{item.subtitle}</strong><i>THE LITTLE THINGS. THE BIG FEELINGS.</i></div>
{!playing&&!error&&<span className="paused"><Play size={54} fill="currentColor"/></span>}{burst&&<span className="heart-burst"><Heart size={110} fill="currentColor"/></span>}{error&&<div className="video-error">视频暂时无法加载<button onClick={()=>{setError(false);video.current?.load();setPlaying(true);}}>重新加载</button></div>}
<div className="video-info"><span className="editor-label">瞬间精选 <span>·</span> 风景与生活</span><h2>@{item.author}<span className="verified"><Check size={11}/></span></h2><h3>{item.title}</h3><p>{item.description}</p><div className="tags">{item.tags.map(t=><button key={t} onClick={()=>{setQuery(t);setPanel('search');}}>#{t}</button>)}</div><div className="music"><Music2 size={15}/><span>{item.music}</span><span className="music-bars">▂ ▅ ▃ ▆ ▂</span></div></div>
<div className="actions"><button className="avatar" style={{background:item.color}} aria-label={reaction.followed?'取消关注作者':'关注作者'} aria-pressed={!!reaction.followed} onClick={()=>toggle('followed')}>{item.avatar}<span>{reaction.followed?<Check size={13}/>:<Plus size={13}/>}</span></button><button className={`action ${reaction.liked?'liked':''}`} aria-label="点赞" aria-pressed={!!reaction.liked} onClick={()=>toggle('liked')}><Heart fill="currentColor"/><span>{compact(item.likes+(reaction.liked?1:0))}</span></button><button className="action" aria-label="查看评论" onClick={()=>setPanel('comments')}><MessageCircle fill="currentColor"/><span>{item.comments+(comments[item.id]?.length||0)}</span></button><button className={`action ${reaction.saved?'saved':''}`} aria-label="收藏" aria-pressed={!!reaction.saved} onClick={()=>toggle('saved')}><Bookmark fill="currentColor"/><span>{compact(item.saves+(reaction.saved?1:0))}</span></button><button className="action" aria-label="分享视频" onClick={share}><Share2 fill="currentColor"/><span>分享</span></button><span className={`record ${playing?'spinning':''}`}><span style={{background:item.color}}><Music2 size={16}/></span></span></div>
<div className="player-controls"><input className="progress" type="range" aria-label="播放进度" min="0" max={duration||8} step="0.05" value={progress} style={{'--progress':`${progress/(duration||8)*100}%`} as React.CSSProperties} onChange={e=>{const value=Number(e.target.value);if(video.current)video.current.currentTime=value;setProgress(value);}}/><div className="control-row"><button aria-label={playing?'暂停':'播放'} onClick={()=>setPlaying(p=>!p)}>{playing?<Pause size={18} fill="currentColor"/>:<Play size={18} fill="currentColor"/>}</button><span className="time">{time(progress)} <span>/ {time(duration)}</span></span><span className="control-hint">滚动发现更多精彩</span><button className="quality" onClick={()=>notify('当前为本地生成的高清演示视频')}>高清 <span>HD</span></button><button aria-label={muted?'开启声音':'静音'} onClick={()=>setMuted(m=>!m)}>{muted?<VolumeX size={20}/>:<Volume2 size={20}/>}</button><button aria-label="全屏" onClick={()=>{if(document.fullscreenElement)document.exitFullscreen();else stage.current?.requestFullscreen?.().catch(()=>notify('此浏览器暂不支持全屏'));}}><Maximize size={18}/></button></div></div>
</section><div className="desktop-footer"><span><span className="key">↑</span><span className="key">↓</span> 切换视频 <span className="footer-divider"/> <span className="key space">Space</span> 暂停 / 播放</span><span><span className="current-number">0{index+1}</span> / 0{videos.length} <span className="footer-divider"/> 好风景,循环看</span></div>
<div className="next-controls"><button aria-label="上一个视频" onClick={()=>next(-1)}><ChevronUp/></button><span/ ><button aria-label="下一个视频" onClick={()=>next(1)}><ChevronDown/></button></div>
</main><nav className="mobile-bottom"><button className="selected" onClick={()=>{setTab('推荐');setPanel(null);}}><Home fill="currentColor"/>首页</button><button onClick={()=>setPanel('search')}><Compass/>发现</button><button className="create" aria-label="发布提示" onClick={()=>notify('当前为浏览演示,暂未开放发布')}><Plus/></button><button onClick={()=>setPanel('comments')}><MessageCircle/>消息</button><button onClick={()=>notify('无需登录,点赞与收藏保存在此设备')}><UserRound/>我</button></nav>
</div>
{panel&&<div className="modal-backdrop" onClick={()=>setPanel(null)}><section className="panel" role="dialog" aria-modal="true" aria-labelledby="panel-title" onClick={e=>e.stopPropagation()}><header><h2 id="panel-title">{panel==='comments'?`评论 · ${item.comments+(comments[item.id]?.length||0)}`:'发现好瞬间'}</h2><button aria-label="关闭" onClick={()=>setPanel(null)}><X/></button></header>{panel==='comments'?<><p className="panel-note">演示评论 · 新评论仅在本次浏览中保留</p><div className="comments">{[...initialComments,...comments[item.id]||[]].map((c,i)=><article key={i}><span className="comment-avatar">{c.name[0]}</span><div><strong>{c.name}</strong><p>{c.text}</p><small>刚刚 · 回复</small></div><Heart size={15}/></article>)}</div><form onSubmit={e=>{e.preventDefault();if(!draft.trim())return;setComments(c=>({...c,[item.id]:[...c[item.id]||[],{name:'访客',text:draft.trim()}]}));setDraft('');}}><input aria-label="评论内容" placeholder="留下你的心情…" value={draft} maxLength={200} onChange={e=>setDraft(e.target.value)}/><button aria-label="发送评论" disabled={!draft.trim()}><Send size={20}/></button></form></>:<><div className="search-input"><Search size={20}/><input aria-label="搜索内容" placeholder="搜索标题、作者或标签" value={query} onChange={e=>setQuery(e.target.value)}/></div><div className="search-results">{results.map(v=><button key={v.id} onClick={()=>{setIndex(videos.findIndex(x=>x.id===v.id));setPlaying(true);setProgress(0);setError(false);setPanel(null);}}><img src={v.poster} alt=""/><span><strong>{v.title}</strong><small>@{v.author} · {v.tags[0]}</small></span><Play size={18}/></button>)}{results.length===0&&<p>还没有找到,试试“日落”或“海”。</p>}</div></>}</section></div>}
<div className={`toast ${toast?'visible':''}`} role="status">{toast}</div>
</>;
import { ChevronUp, ChevronDown, Search, Home, Compass, Music2, X, Send, UserRound, Plus, MessageCircle, Heart, Play, VolumeX, Volume2 } from 'lucide-react';
import { videos } from '../lib/videos';
import { SwipeFeed, type SwipeFeedHandle } from '../components/SwipeFeed';
import { VideoCard, type Reaction } from '../components/VideoCard';
import { pagePosition } from '../lib/gestures';
type Comment = { name: string; text: string };
const initialComments: Comment[] = [
{ name: '小岛同学', text: '这一刻,连时间都慢下来了。' },
{ name: '今天也要开心', text: '好喜欢这个氛围 ✨' },
{ name: '路过人间', text: '收藏了,留给忙碌的一天。' },
];
export default function Feed() {
const [index, setIndex] = useState(0);
const [playing, setPlaying] = useState(true);
const [muted, setMuted] = useState(true);
const [reactions, setReactions] = useState<Record<string, Reaction>>({});
const [ready, setReady] = useState(false);
const [panel, setPanel] = useState<'comments' | 'search' | 'share' | null>(null);
const [closing, setClosing] = useState(false);
const [toast, setToast] = useState('');
const [query, setQuery] = useState('');
const [draft, setDraft] = useState('');
const [comments, setComments] = useState<Record<string, Comment[]>>({});
const [shareUrl, setShareUrl] = useState('');
const feed = useRef<SwipeFeedHandle>(null);
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const drawer = useRef<HTMLElement>(null);
const sheetGesture = useRef<{ startY: number; dy: number } | null>(null);
const item = videos[index];
const notify = useCallback((text: string) => {
setToast(text);
if (toastTimer.current) clearTimeout(toastTimer.current);
toastTimer.current = setTimeout(() => setToast(''), 2400);
}, []);
const closePanel = useCallback(() => {
setClosing(true);
if (closeTimer.current) clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(() => { setPanel(null); setClosing(false); }, 240);
}, []);
useEffect(() => {
try {
const data = JSON.parse(localStorage.getItem('flow-reactions') || '{}');
if (data && typeof data === 'object' && !Array.isArray(data)) setReactions(data);
} catch {}
setReady(true);
const id = new URLSearchParams(location.search).get('video');
const found = videos.findIndex(video => video.id === id);
if (found >= 0) setIndex(found);
return () => {
if (toastTimer.current) clearTimeout(toastTimer.current);
if (closeTimer.current) clearTimeout(closeTimer.current);
};
}, []);
useEffect(() => {
if (ready) try { localStorage.setItem('flow-reactions', JSON.stringify(reactions)); } catch {}
}, [reactions, ready]);
const change = useCallback((direction: number) => {
setIndex(value => (value + direction + videos.length) % videos.length);
setPlaying(true);
setDraft('');
}, []);
useEffect(() => {
const key = (event: KeyboardEvent) => {
if ((event.target as HTMLElement).closest('input,textarea') || panel) return;
if (event.code === 'ArrowDown' || event.code === 'ArrowUp') {
event.preventDefault(); feed.current?.next(event.code === 'ArrowDown' ? 1 : -1);
}
if (event.code === 'Space' && !(event.target as HTMLElement).closest('button')) { event.preventDefault(); setPlaying(value => !value); }
if (event.code === 'KeyM') setMuted(value => !value);
if (event.code === 'Slash') { event.preventDefault(); setPanel('search'); }
};
window.addEventListener('keydown', key);
return () => window.removeEventListener('keydown', key);
}, [panel]);
useEffect(() => {
if (!panel) return;
const before = document.activeElement as HTMLElement;
const element = drawer.current;
element?.querySelector<HTMLElement>('button,input')?.focus();
const key = (event: KeyboardEvent) => {
if (event.key === 'Escape') closePanel();
if (event.key !== 'Tab') return;
const elements = element?.querySelectorAll<HTMLElement>('button:not(:disabled),input,[tabindex="0"]');
if (!elements?.length) return;
const first = elements[0], last = elements[elements.length - 1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
};
document.addEventListener('keydown', key);
return () => { document.removeEventListener('keydown', key); before?.focus(); };
}, [panel, closePanel]);
function react(id: string, field: keyof Reaction, force?: boolean) {
setReactions(previous => ({ ...previous, [id]: { ...previous[id], [field]: force ?? !previous[id]?.[field] } }));
}
async function share() {
const url = `${location.origin}/?video=${item.id}`;
setShareUrl(url);
try {
if (navigator.share) await navigator.share({ title: item.title, url });
else if (navigator.clipboard) { await navigator.clipboard.writeText(url); notify('视频链接已复制'); }
else setPanel('share');
} catch (error) { if ((error as Error).name !== 'AbortError') setPanel('share'); }
}
const results = videos.filter(video => `${video.title}${video.author}${video.tags.join('')}`.includes(query.trim()));
return <>
<Head><title>瞬间 FLOW · 发现生活的另一面</title><meta name="description" content="沉浸式短视频体验,记录每一个值得停留的瞬间。" /><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /><meta name="theme-color" content="#08080b" /></Head>
<div className="app-shell" inert={!!panel}>
<main className="main">
<SwipeFeed ref={feed} onChange={change} disabled={!!panel}>
{videos.map((video, videoIndex) => {
return <VideoCard key={video.id} item={video} position={pagePosition(videoIndex, index)} active={videoIndex === index}
playing={playing} muted={muted} reaction={reactions[video.id] || {}} commentCount={comments[video.id]?.length || 0}
setPlaying={setPlaying} toggleMuted={() => setMuted(value => !value)} onReact={(field, force) => react(video.id, field, force)}
onComment={() => setPanel('comments')} onShare={share} onTag={tag => { setQuery(tag); setPanel('search'); }} />;
})}
</SwipeFeed>
<header className="feed-header">
<a className="brand" href="/" aria-label="瞬间首页"><Music2 /><strong>瞬间</strong><span>FLOW</span></a>
<button className="mobile-sound" aria-label={muted ? '开启声音' : '静音'} onClick={() => setMuted(value => !value)}>{muted ? <VolumeX /> : <Volume2 />}</button>
<nav className="feed-tabs"><button onClick={() => notify('点击作者头像即可关注')}>关注</button><button className="selected">推荐</button></nav>
<button className="search-trigger" aria-label="搜索视频" onClick={() => setPanel('search')}><Search /><span>搜索你感兴趣的内容</span><kbd>/</kbd></button>
</header>
<div className="next-controls"><button aria-label="上一个视频" onClick={() => feed.current?.next(-1)}><ChevronUp /></button><span /><button aria-label="下一个视频" onClick={() => feed.current?.next(1)}><ChevronDown /></button></div>
<div className="feed-position" aria-hidden="true">{videos.map((video, i) => <i key={video.id} className={i === index ? 'active' : ''} />)}</div>
</main>
<nav className="mobile-bottom"><button className="selected" onClick={() => notify('正在浏览推荐视频')}><Home fill="currentColor" />首页</button><button onClick={() => setPanel('search')}><Compass />发现</button><button className="create" aria-label="发布提示" onClick={() => notify('当前为浏览演示,暂未开放发布')}><Plus /></button><button onClick={() => setPanel('comments')}><MessageCircle />消息</button><button onClick={() => notify('无需登录,点赞与收藏保存在此设备')}><UserRound />我</button></nav>
</div>
{panel && <div className={`modal-backdrop ${closing ? 'closing' : ''}`} onClick={closePanel}>
<section ref={drawer} className="panel" role="dialog" aria-modal="true" aria-labelledby="panel-title" onClick={event => event.stopPropagation()}>
<div className="sheet-grip" onPointerDown={event => { sheetGesture.current = { startY: event.clientY, dy: 0 }; if (drawer.current) drawer.current.style.transition = 'none'; event.currentTarget.setPointerCapture(event.pointerId); }}
onPointerMove={event => { if (!sheetGesture.current || !drawer.current) return; const dy = Math.max(0, event.clientY - sheetGesture.current.startY); sheetGesture.current.dy = dy; drawer.current.style.transform = `translateY(${dy}px)`; }}
onPointerUp={() => { if (!sheetGesture.current || !drawer.current) return; drawer.current.style.transition = ''; if (sheetGesture.current.dy > 90) closePanel(); else drawer.current.style.transform = ''; sheetGesture.current = null; }}
onPointerCancel={() => { if (drawer.current) { drawer.current.style.transition = ''; drawer.current.style.transform = ''; } sheetGesture.current = null; }}><span /></div>
<header><h2 id="panel-title">{panel === 'comments' ? `评论 · ${item.comments + (comments[item.id]?.length || 0)}` : panel === 'search' ? '发现好瞬间' : '分享这一刻'}</h2><button aria-label="关闭" onClick={closePanel}><X /></button></header>
{panel === 'comments' ? <>
<p className="panel-note">演示评论 · 新评论仅在本次浏览中保留</p>
<div className="comments">{[...initialComments, ...comments[item.id] || []].map((comment, i) => <article key={`${i}-${comment.text}`}><span className="comment-avatar">{comment.name[0]}</span><div><strong>{comment.name}</strong><p>{comment.text}</p><small>刚刚 · 回复</small></div><Heart size={15} /></article>)}</div>
<form onSubmit={event => { event.preventDefault(); if (!draft.trim()) return; setComments(previous => ({ ...previous, [item.id]: [...previous[item.id] || [], { name: '访客', text: draft.trim() }] })); setDraft(''); }}><input aria-label="评论内容" placeholder="留下你的心情…" value={draft} maxLength={200} onChange={event => setDraft(event.target.value)} /><button aria-label="发送评论" disabled={!draft.trim()}><Send size={20} /></button></form>
</> : panel === 'search' ? <>
<div className="search-input"><Search size={20} /><input aria-label="搜索内容" placeholder="搜索标题、作者或标签" value={query} onChange={event => setQuery(event.target.value)} /></div>
<div className="search-results">{results.map(video => <button key={video.id} onClick={() => { setIndex(videos.findIndex(v => v.id === video.id)); setPlaying(true); closePanel(); }}><img src={video.poster} alt="" /><span><strong>{video.title}</strong><small>@{video.author} · {video.tags[0]}</small></span><Play size={18} /></button>)}{!results.length && <p>还没有找到,试试“日落”或“海”。</p>}</div>
</> : <><p className="panel-note">复制下面的链接,即可分享当前视频。</p><input className="share-link" aria-label="视频链接" readOnly value={shareUrl} onFocus={event => event.target.select()} /></>}
</section>
</div>}
<div className={`toast ${toast ? 'visible' : ''}`} role="status">{toast}</div>
</>;
}
+81 -153
View File
@@ -21,6 +21,9 @@ importers:
specifier: ^19.1.0
version: 19.3.0(react@19.3.0)
devDependencies:
'@ffmpeg-installer/ffmpeg':
specifier: ^1.1.0
version: 1.1.0
'@napi-rs/canvas':
specifier: ^0.1.80
version: 0.1.100
@@ -33,22 +36,58 @@ importers:
'@types/react-dom':
specifier: ^19.0.0
version: 19.3.0(@types/react@19.3.0)
ffmpeg-static:
specifier: ^5.2.0
version: 5.3.0
typescript:
specifier: ^5.9.0
version: 5.9.3
packages:
'@derhuerst/http-basic@8.2.4':
resolution: {integrity: sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==}
engines: {node: '>=6.0.0'}
'@emnapi/runtime@1.11.3':
resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
'@ffmpeg-installer/darwin-arm64@4.1.5':
resolution: {integrity: sha512-hYqTiP63mXz7wSQfuqfFwfLOfwwFChUedeCVKkBtl/cliaTM7/ePI9bVzfZ2c+dWu3TqCwLDRWNSJ5pqZl8otA==}
cpu: [arm64]
os: [darwin]
'@ffmpeg-installer/darwin-x64@4.1.0':
resolution: {integrity: sha512-Z4EyG3cIFjdhlY8wI9aLUXuH8nVt7E9SlMVZtWvSPnm2sm37/yC2CwjUzyCQbJbySnef1tQwGG2Sx+uWhd9IAw==}
cpu: [x64]
os: [darwin]
'@ffmpeg-installer/ffmpeg@1.1.0':
resolution: {integrity: sha512-Uq4rmwkdGxIa9A6Bd/VqqYbT7zqh1GrT5/rFwCwKM70b42W5gIjWeVETq6SdcL0zXqDtY081Ws/iJWhr1+xvQg==}
'@ffmpeg-installer/linux-arm64@4.1.4':
resolution: {integrity: sha512-dljEqAOD0oIM6O6DxBW9US/FkvqvQwgJ2lGHOwHDDwu/pX8+V0YsDL1xqHbj1DMX/+nP9rxw7G7gcUvGspSoKg==}
cpu: [arm64]
os: [linux]
'@ffmpeg-installer/linux-arm@4.1.3':
resolution: {integrity: sha512-NDf5V6l8AfzZ8WzUGZ5mV8O/xMzRag2ETR6+TlGIsMHp81agx51cqpPItXPib/nAZYmo55Bl2L6/WOMI3A5YRg==}
cpu: [arm]
os: [linux]
'@ffmpeg-installer/linux-ia32@4.1.0':
resolution: {integrity: sha512-0LWyFQnPf+Ij9GQGD034hS6A90URNu9HCtQ5cTqo5MxOEc7Rd8gLXrJvn++UmxhU0J5RyRE9KRYstdCVUjkNOQ==}
cpu: [ia32]
os: [linux]
'@ffmpeg-installer/linux-x64@4.1.0':
resolution: {integrity: sha512-Y5BWhGLU/WpQjOArNIgXD3z5mxxdV8c41C+U15nsE5yF8tVcdCGet5zPs5Zy3Ta6bU7haGpIzryutqCGQA/W8A==}
cpu: [x64]
os: [linux]
'@ffmpeg-installer/win32-ia32@4.1.0':
resolution: {integrity: sha512-FV2D7RlaZv/lrtdhaQ4oETwoFUsUjlUiasiZLDxhEUPdNDWcH1OU9K1xTvqz+OXLdsmYelUDuBS/zkMOTtlUAw==}
cpu: [ia32]
os: [win32]
'@ffmpeg-installer/win32-x64@4.1.0':
resolution: {integrity: sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg==}
cpu: [x64]
os: [win32]
'@img/colour@1.1.0':
resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
engines: {node: '>=18'}
@@ -344,9 +383,6 @@ packages:
'@swc/helpers@0.5.15':
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
'@types/node@10.17.60':
resolution: {integrity: sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==}
'@types/node@22.20.5':
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
@@ -358,68 +394,24 @@ packages:
'@types/react@19.3.0':
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
agent-base@6.0.2:
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
buffer-from@1.1.2:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
caniuse-lite@1.0.30001815:
resolution: {integrity: sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==}
caseless@0.12.0:
resolution: {integrity: sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==}
client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
concat-stream@2.0.0:
resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==}
engines: {'0': node >= 6.0}
csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
debug@4.4.3:
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
detect-libc@2.1.2:
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
env-paths@2.2.1:
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
ffmpeg-static@5.3.0:
resolution: {integrity: sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==}
engines: {node: '>=16'}
http-response-object@3.0.2:
resolution: {integrity: sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==}
https-proxy-agent@5.0.1:
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
lucide-react@0.468.0:
resolution: {integrity: sha512-6koYRhnM2N0GGZIdXzSeiNwguv1gt/FAjZOiPl76roBi3xKEXa4WmfpxgQwTTL4KipXjefrnf3oV4IsYhi4JFA==}
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
nanoid@3.3.20:
resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -446,9 +438,6 @@ packages:
sass:
optional: true
parse-cache-control@1.0.1:
resolution: {integrity: sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==}
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -456,10 +445,6 @@ packages:
resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==}
engines: {node: ^10 || ^12 || >=14}
progress@2.0.3:
resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
engines: {node: '>=0.4.0'}
react-dom@19.3.0:
resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==}
peerDependencies:
@@ -469,13 +454,6 @@ packages:
resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==}
engines: {node: '>=0.10.0'}
readable-stream@3.6.2:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
scheduler@0.28.0:
resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}
@@ -497,9 +475,6 @@ packages:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
string_decoder@1.3.0:
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
styled-jsx@5.1.6:
resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}
engines: {node: '>= 12.0.0'}
@@ -516,9 +491,6 @@ packages:
tslib@2.8.1:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
typedarray@0.0.6:
resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==}
typescript@5.9.3:
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
@@ -527,23 +499,48 @@ packages:
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
snapshots:
'@derhuerst/http-basic@8.2.4':
dependencies:
caseless: 0.12.0
concat-stream: 2.0.0
http-response-object: 3.0.2
parse-cache-control: 1.0.1
'@emnapi/runtime@1.11.3':
dependencies:
tslib: 2.8.1
optional: true
'@ffmpeg-installer/darwin-arm64@4.1.5':
optional: true
'@ffmpeg-installer/darwin-x64@4.1.0':
optional: true
'@ffmpeg-installer/ffmpeg@1.1.0':
optionalDependencies:
'@ffmpeg-installer/darwin-arm64': 4.1.5
'@ffmpeg-installer/darwin-x64': 4.1.0
'@ffmpeg-installer/linux-arm': 4.1.3
'@ffmpeg-installer/linux-arm64': 4.1.4
'@ffmpeg-installer/linux-ia32': 4.1.0
'@ffmpeg-installer/linux-x64': 4.1.0
'@ffmpeg-installer/win32-ia32': 4.1.0
'@ffmpeg-installer/win32-x64': 4.1.0
'@ffmpeg-installer/linux-arm64@4.1.4':
optional: true
'@ffmpeg-installer/linux-arm@4.1.3':
optional: true
'@ffmpeg-installer/linux-ia32@4.1.0':
optional: true
'@ffmpeg-installer/linux-x64@4.1.0':
optional: true
'@ffmpeg-installer/win32-ia32@4.1.0':
optional: true
'@ffmpeg-installer/win32-x64@4.1.0':
optional: true
'@img/colour@1.1.0':
optional: true
@@ -728,8 +725,6 @@ snapshots:
dependencies:
tslib: 2.8.1
'@types/node@10.17.60': {}
'@types/node@22.20.5':
dependencies:
undici-types: 6.21.0
@@ -742,66 +737,19 @@ snapshots:
dependencies:
csstype: 3.2.3
agent-base@6.0.2:
dependencies:
debug: 4.4.3
transitivePeerDependencies:
- supports-color
buffer-from@1.1.2: {}
caniuse-lite@1.0.30001815: {}
caseless@0.12.0: {}
client-only@0.0.1: {}
concat-stream@2.0.0:
dependencies:
buffer-from: 1.1.2
inherits: 2.0.4
readable-stream: 3.6.2
typedarray: 0.0.6
csstype@3.2.3: {}
debug@4.4.3:
dependencies:
ms: 2.1.3
detect-libc@2.1.2:
optional: true
env-paths@2.2.1: {}
ffmpeg-static@5.3.0:
dependencies:
'@derhuerst/http-basic': 8.2.4
env-paths: 2.2.1
https-proxy-agent: 5.0.1
progress: 2.0.3
transitivePeerDependencies:
- supports-color
http-response-object@3.0.2:
dependencies:
'@types/node': 10.17.60
https-proxy-agent@5.0.1:
dependencies:
agent-base: 6.0.2
debug: 4.4.3
transitivePeerDependencies:
- supports-color
inherits@2.0.4: {}
lucide-react@0.468.0(react@19.3.0):
dependencies:
react: 19.3.0
ms@2.1.3: {}
nanoid@3.3.20: {}
next@15.5.27(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0):
@@ -828,8 +776,6 @@ snapshots:
- '@types/node'
- babel-plugin-macros
parse-cache-control@1.0.1: {}
picocolors@1.1.1: {}
postcss@8.4.31:
@@ -838,8 +784,6 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.2
progress@2.0.3: {}
react-dom@19.3.0(react@19.3.0):
dependencies:
react: 19.3.0
@@ -847,14 +791,6 @@ snapshots:
react@19.3.0: {}
readable-stream@3.6.2:
dependencies:
inherits: 2.0.4
string_decoder: 1.3.0
util-deprecate: 1.0.2
safe-buffer@5.2.1: {}
scheduler@0.28.0: {}
semver@7.8.5:
@@ -896,10 +832,6 @@ snapshots:
source-map-js@1.2.2: {}
string_decoder@1.3.0:
dependencies:
safe-buffer: 5.2.1
styled-jsx@5.1.6(react@19.3.0):
dependencies:
client-only: 0.0.1
@@ -907,10 +839,6 @@ snapshots:
tslib@2.8.1: {}
typedarray@0.0.6: {}
typescript@5.9.3: {}
undici-types@6.21.0: {}
util-deprecate@1.0.2: {}
+1 -2
View File
@@ -1,2 +1 @@
onlyBuiltDependencies:
- ffmpeg-static
onlyBuiltDependencies: []
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.
+2 -1
View File
@@ -1,8 +1,9 @@
import { createCanvas } from '@napi-rs/canvas';
import ffmpeg from 'ffmpeg-static';
import installer from '@ffmpeg-installer/ffmpeg';
import { spawn } from 'node:child_process';
import { mkdir, writeFile } from 'node:fs/promises';
import { once } from 'node:events';
const ffmpeg=installer.path;
const W=960,H=960,FPS=24,SECONDS=8;
await mkdir('public/videos',{recursive:true});
const canvas=createCanvas(W,H), c=canvas.getContext('2d');
+25 -7
View File
File diff suppressed because one or more lines are too long
+50
View File
@@ -0,0 +1,50 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import ts from 'typescript';
const source = readFileSync(new URL('../lib/gestures.ts', import.meta.url), 'utf8');
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } });
const exports = {};
vm.runInNewContext(compiled.outputText, { exports });
const { swipeDirection, pagePosition } = exports;
test('short slow drags spring back in both directions', () => {
assert.equal(swipeDirection(-100, -.1, 800), 0);
assert.equal(swipeDirection(100, .1, 800), 0);
});
test('long drags land on the adjacent page', () => {
assert.equal(swipeDirection(-180, 0, 800), 1);
assert.equal(swipeDirection(180, 0, 800), -1);
});
test('quick flicks commit without requiring a long drag', () => {
assert.equal(swipeDirection(-45, -.6, 800), 1);
assert.equal(swipeDirection(45, .6, 800), -1);
});
test('tiny pointer jitter never changes videos', () => {
assert.equal(swipeDirection(-6, -2, 800), 0);
assert.equal(swipeDirection(0, 2, 800), 0);
});
test('threshold adapts to viewport height', () => {
assert.equal(swipeDirection(-130, 0, 600), 1);
assert.equal(swipeDirection(-130, 0, 1000), 0);
assert.equal(swipeDirection(-130, 0, 0), 0);
});
test('every active page has exactly one previous and one next page', () => {
for (let active = 0; active < 3; active++) {
assert.equal(pagePosition(active, active), 0);
assert.equal(pagePosition((active + 1) % 3, active), 1);
assert.equal(pagePosition((active + 2) % 3, active), -1);
}
});
test('recycling at the loop seam preserves the on-screen landing position', () => {
for (let active = 0; active < 3; active++) {
for (const direction of [-1, 1]) {
const next = (active + direction + 3) % 3;
// A dragged neighbor reaches y=0 before recycling; it stays at y=0 after.
assert.equal(pagePosition(next, active) - direction, 0);
assert.equal(pagePosition(next, next), 0);
}
}
});