tag(功能):功能跑通

This commit is contained in:
OrangeRoll
2026-08-07 13:15:26 +08:00
parent 9e0387bf94
commit 3d1c6a6c76
19 changed files with 892 additions and 418 deletions
+245 -107
View File
@@ -1,121 +1,259 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import { useEffect, useRef, useState } from 'react'
import { Room, RoomEvent, Track } from 'livekit-client'
import './App.css'
function App() {
const [count, setCount] = useState(0)
type Role = 'host' | 'publisher' | 'viewer'
type TokenResponse = {
roomName: string
participantIdentity: string
participantName: string
livekitUrl: string
token: string
role: Role
}
type ScreenFeed = {
track: Track
label: string
}
function ScreenTrack({ track, label }: ScreenFeed) {
const mediaContainerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const mediaElement = track.attach()
mediaElement.autoplay = true
if (mediaElement instanceof HTMLVideoElement) {
// Local preview must be muted for browsers to allow autoplay.
mediaElement.muted = true
mediaElement.playsInline = true
void mediaElement.play().catch(() => {
// The user can still start playback manually if their browser blocks it.
})
}
mediaContainerRef.current?.append(mediaElement)
return () => {
mediaElement.remove()
}
}, [track])
return (
<>
<section id="center">
<div className="hero">
<img src={heroImg} className="base" width="170" height="179" alt="" />
<img src={reactLogo} className="framework" alt="React logo" />
<img src={viteLogo} className="vite" alt="Vite logo" />
</div>
<div>
<h1>Get started</h1>
<p>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
</p>
</div>
<button
type="button"
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
<figure className="screen-frame">
<figcaption>{label}</figcaption>
<div className="media-slot" ref={mediaContainerRef} />
</figure>
)
}
function App() {
const roomRef = useRef<Room | null>(null)
const [roomName, setRoomName] = useState('demo-room')
const [participantName, setParticipantName] = useState('')
const [role, setRole] = useState<Role>('publisher')
const [connectionState, setConnectionState] = useState<'idle' | 'connecting' | 'connected'>('idle')
const [isSharing, setIsSharing] = useState(false)
const [remoteCount, setRemoteCount] = useState(0)
const [localScreen, setLocalScreen] = useState<ScreenFeed | null>(null)
const [remoteScreens, setRemoteScreens] = useState<ScreenFeed[]>([])
const [error, setError] = useState('')
useEffect(() => {
return () => {
roomRef.current?.disconnect()
}
}, [])
function refreshRemoteCount(room: Room) {
setRemoteCount(room.remoteParticipants.size)
}
async function joinRoom() {
const normalizedRoom = roomName.trim()
const normalizedName = participantName.trim()
if (!/^[A-Za-z0-9_-]{3,64}$/.test(normalizedRoom)) {
setError('房间号只能包含 3–64 个字母、数字、下划线或连字符。')
return
}
if (!normalizedName) {
setError('请输入显示名称。')
return
}
setError('')
setConnectionState('connecting')
try {
const response = await fetch(`/api/rooms/${encodeURIComponent(normalizedRoom)}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ participantName: normalizedName, role }),
})
const payload = (await response.json()) as TokenResponse | { message: string }
if (!response.ok || !('token' in payload)) {
throw new Error('message' in payload ? payload.message : '无法获取房间凭证。')
}
roomRef.current?.disconnect()
setLocalScreen(null)
setRemoteScreens([])
const room = new Room()
room.on(RoomEvent.ParticipantConnected, () => refreshRemoteCount(room))
room.on(RoomEvent.ParticipantDisconnected, () => refreshRemoteCount(room))
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
if (track.kind === Track.Kind.Video && publication.source === Track.Source.ScreenShare) {
setRemoteScreens((screens) => [
...screens.filter((screen) => screen.track.sid !== track.sid),
{ track, label: `${participant.name || participant.identity} 的屏幕` },
])
}
})
room.on(RoomEvent.TrackUnsubscribed, (track) => {
setRemoteScreens((screens) => screens.filter((screen) => screen.track !== track))
})
room.on(RoomEvent.LocalTrackPublished, (publication) => {
if (publication.source === Track.Source.ScreenShare && publication.track) {
setLocalScreen({ track: publication.track, label: '你正在共享的屏幕' })
setIsSharing(true)
}
})
room.on(RoomEvent.LocalTrackUnpublished, (publication) => {
if (publication.source === Track.Source.ScreenShare) {
setLocalScreen(null)
setIsSharing(false)
}
})
room.on(RoomEvent.Disconnected, () => {
setConnectionState('idle')
setIsSharing(false)
setRemoteCount(0)
setLocalScreen(null)
setRemoteScreens([])
})
await room.connect(payload.livekitUrl, payload.token)
roomRef.current = room
refreshRemoteCount(room)
setConnectionState('connected')
} catch (cause) {
setConnectionState('idle')
setError(cause instanceof Error ? cause.message : '连接房间时发生未知错误。')
}
}
async function toggleScreenShare() {
const room = roomRef.current
if (!room) {
return
}
setError('')
try {
await room.localParticipant.setScreenShareEnabled(!isSharing)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '无法切换屏幕共享。')
}
}
function leaveRoom() {
roomRef.current?.disconnect()
roomRef.current = null
setConnectionState('idle')
setIsSharing(false)
setRemoteCount(0)
setLocalScreen(null)
setRemoteScreens([])
}
const connected = connectionState === 'connected'
const canShare = role === 'host' || role === 'publisher'
return (
<main className="app-shell">
<header>
<p className="eyebrow">LIVEKIT · </p>
<h1></h1>
<p className="subtitle"> LiveKitKtor 访</p>
</header>
<section className="join-panel" aria-label="加入房间">
<label>
<input
value={roomName}
onChange={(event) => setRoomName(event.target.value)}
disabled={connected}
maxLength={64}
/>
</label>
<label>
<input
value={participantName}
onChange={(event) => setParticipantName(event.target.value)}
disabled={connected}
maxLength={64}
placeholder="例如:张三"
/>
</label>
<label>
<select value={role} onChange={(event) => setRole(event.target.value as Role)} disabled={connected}>
<option value="host">Host</option>
<option value="publisher">Publisher</option>
<option value="viewer">Viewer</option>
</select>
</label>
{!connected ? (
<button type="button" className="primary" onClick={() => void joinRoom()} disabled={connectionState === 'connecting'}>
{connectionState === 'connecting' ? '正在连接…' : '加入房间'}
</button>
) : (
<button type="button" className="secondary" onClick={leaveRoom}></button>
)}
</section>
<div className="ticks"></div>
{error && <p className="error" role="alert">{error}</p>}
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
<section className="status-bar" aria-live="polite">
<span className={connected ? 'status online' : 'status'}>{connected ? '已连接' : '未连接'}</span>
<span>{remoteCount}</span>
{connected && (
<button type="button" className="share-button" onClick={() => void toggleScreenShare()} disabled={!canShare}>
{isSharing ? '停止共享屏幕' : '共享屏幕'}
</button>
)}
{connected && !canShare && <span className="hint">Viewer </span>}
</section>
<section className="screens">
<div className="screen-section">
<h2></h2>
<div className="video-stack">
{localScreen ? <ScreenTrack {...localScreen} /> : <p className="empty"></p>}
</div>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
<div className="screen-section">
<h2></h2>
<div className="video-stack">
{remoteScreens.length === 0
? <p className="empty"></p>
: remoteScreens.map((screen) => (
<ScreenTrack key={screen.track.sid} {...screen} />
))}
</div>
</div>
</section>
<div className="ticks"></div>
<section id="spacer"></section>
</>
<p className="development-note">
JWT
</p>
</main>
)
}