mono/reference/tiktok/player/README.md
2026-01-29 18:35:51 +01:00

305 lines
7.8 KiB
Markdown

# TikTok Video Player
A complete TikTok-style video player built from deobfuscated TikTok source code. Features infinite scroll, video controls, comments system, and privacy compliance - all with just React and Tailwind CSS.
## 🚀 Features
### Core Video Player
-**HTML5 Video Player** with custom controls
-**Infinite Scroll** with snap-to-video behavior
-**Auto-play/Pause** based on viewport visibility
-**Keyboard Navigation** (Space, Arrow keys, M for mute)
-**Progress Bar** with click-to-seek
-**Volume Control** and mute functionality
-**WebVTT Subtitles** support with parsing
-**Video Preloading** and memory management
### UI Components
-**Action Bar** (Like, Comment, Share, Bookmark, Follow)
-**Video Metadata** with hashtag/mention parsing
-**User Avatars** with verification badges
-**Loading States** and error handling
-**Navigation Indicators** (side dots)
-**Responsive Design** for mobile and desktop
### Advanced Features
-**Mock Data System** for testing
-**Analytics Tracking** hooks
-**Comment System** (placeholder implementation)
-**Share Functionality** with clipboard copy
-**Performance Optimized** with throttled scroll events
-**Accessibility** with ARIA labels and keyboard support
## 📦 Installation
```bash
# Install dependencies
npm install
# Start development playground
npm run playground
# Build the library
npm run build
# Preview the built library
npm run preview
```
## 🎮 Playground
The playground demonstrates all features with mocked video data:
```bash
npm run playground
```
Open [http://localhost:3000](http://localhost:3000) to see the player in action.
### Keyboard Shortcuts
- **Space**: Play/Pause current video
- **↑/↓**: Navigate between videos
- **M**: Mute/Unmute audio
## 🔧 Usage
### Basic Implementation
```tsx
import React from 'react';
import { VideoFeed, generateMockVideos } from 'tiktok-video-player';
function App() {
const videos = generateMockVideos(20);
return (
<VideoFeed
videos={videos}
onLoadMore={() => {
// Load more videos from your API
}}
onVideoChange={(index) => {
// Track video views
console.log('Video changed to:', index);
}}
onLike={(videoId) => {
// Handle like action
console.log('Liked video:', videoId);
}}
/>
);
}
```
### With Mux Integration
```tsx
import { VideoFeed } from 'tiktok-video-player';
import { VideoItem } from 'tiktok-video-player/types';
// Convert Mux data to VideoItem format
const convertMuxToVideoItem = (muxAsset: any): VideoItem => ({
id: muxAsset.id,
video: {
playAddr: `https://stream.mux.com/${muxAsset.playback_ids[0].id}.m3u8`,
duration: muxAsset.duration,
width: 720,
height: 1280,
ratio: '9:16'
},
author: {
// Your user data
},
stats: {
// Your video stats
},
// ... other properties
});
function MuxVideoFeed({ muxAssets }: { muxAssets: any[] }) {
const videos = muxAssets.map(convertMuxToVideoItem);
return <VideoFeed videos={videos} />;
}
```
### Custom Video Source
```tsx
import { VideoFeed } from 'tiktok-video-player';
const customVideos = [
{
id: 'video_1',
video: {
playAddr: 'https://your-cdn.com/video1.mp4',
duration: 30,
width: 720,
height: 1280
},
author: {
nickname: 'Creator Name',
uniqueId: 'creator_username',
avatarThumb: 'https://your-cdn.com/avatar.jpg'
},
stats: {
diggCount: 1200,
commentCount: 45,
shareCount: 23
},
desc: 'Check out this amazing video! #awesome #content'
}
];
<VideoFeed videos={customVideos} />
```
## 🏗️ Architecture
Based on deobfuscated TikTok source code, the player uses:
### State Management
- **Video Detail Atom**: Central video state management
- **Swiper Mode State**: Navigation and interaction state
- **Comment State**: Comment system with ML preloading
- **Privacy State**: Cookie consent and network monitoring
### Core Hooks
- `useVideoPlayer`: Video playback control and state
- `useInfiniteScroll`: Infinite scroll with preloading
- Custom hooks for analytics and privacy compliance
### Components
- `VideoFeed`: Main container with infinite scroll
- `VideoPlayer`: HTML5 video with custom controls
- `VideoActionBar`: Like, comment, share buttons
- `VideoMetadata`: Author info and description parsing
## 🎨 Styling
Built with Tailwind CSS and includes TikTok's design system:
```css
/* TikTok brand colors */
--tiktok-red: #FE2C55;
--tiktok-blue: #25F4EE;
--tiktok-dark: #161823;
/* Custom animations */
.animate-spin-slow: 3s linear infinite;
.backdrop-blur-xs: blur(2px);
```
## 📱 Mobile Support
- Touch gestures for navigation
- Responsive design for all screen sizes
- iOS/Android video playback optimization
- PWA-ready with proper meta tags
## 🔒 Privacy & Security
Implements TikTok's Privacy and Network Security (PNS) system:
- Cookie consent management
- Network request interception
- Web API monitoring (geolocation, camera, etc.)
- GDPR/CCPA compliance features
## 🧪 Testing
The playground includes:
- 50+ mock videos with realistic data
- Simulated API loading delays
- Error state demonstrations
- Analytics event logging
- Performance monitoring
## 📊 Analytics Integration
Built-in hooks for tracking:
```tsx
const handleVideoChange = (index: number) => {
// Track video views
analytics.track('video_view', {
video_id: videos[index].id,
video_index: index,
timestamp: Date.now()
});
};
const handleLike = (videoId: string) => {
// Track engagement
analytics.track('video_like', {
video_id: videoId,
timestamp: Date.now()
});
};
```
## 🔧 Configuration
### Video Player Options
```tsx
interface VideoPlayerOptions {
autoplay?: boolean; // Auto-play videos (default: true)
muted?: boolean; // Start muted (default: true)
loop?: boolean; // Loop individual videos (default: true)
preload?: 'none' | 'metadata' | 'auto';
controls?: boolean; // Show native controls (default: false)
}
```
### Infinite Scroll Options
```tsx
interface InfiniteScrollOptions {
threshold?: number; // Load more threshold (default: 0.8)
preloadDistance?: number; // Videos to preload (default: 6)
hasMore?: boolean; // More content available
}
```
## 🚀 Performance
Optimizations based on TikTok's implementation:
- **Sparse Loading**: Only loads visible videos
- **Memory Management**: Cleans up off-screen videos
- **Throttled Events**: 100ms scroll event throttling
- **Preloading Strategy**: Smart content preloading
- **Video Optimization**: Metadata preloading only
## 📝 TypeScript Support
Full TypeScript support with comprehensive type definitions:
```tsx
import {
VideoItem,
VideoPlayerProps,
UseVideoPlayerReturn,
CommentItem
} from 'tiktok-video-player/types';
```
## 🤝 Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## 📄 License
MIT License - see [LICENSE](LICENSE) file for details.
## 🙏 Acknowledgments
Built from deobfuscated TikTok source code analysis. This implementation replicates TikTok's sophisticated video player architecture while being completely independent and open-source.
---
**Note**: This is a reverse-engineered implementation for educational purposes. All TikTok trademarks belong to ByteDance Ltd.