# VChart Component Guide for TikTok Analytics
Complete guide for implementing and deploying the custom VChart component for TikTok analytics visualization in Lark aPaaS.
## Table of Contents
- [Overview](#overview)
- [Prerequisites](#prerequisites)
- [Architecture](#architecture)
- [Development Setup](#development-setup)
- [Component API](#component-api)
- [Data Format Requirements](#data-format-requirements)
- [Deployment Steps](#deployment-steps)
- [Usage in aPaaS](#usage-in-apaas)
- [Customization](#customization)
- [Troubleshooting](#troubleshooting)
## Overview
This custom component provides interactive TikTok analytics visualizations using the VChart library from ByteDance. It supports multiple chart types and real-time data updates from Bitable tables.
### Features
- **Multiple Chart Types**: Line, Bar, Pie, and combined Dashboard views
- **Real-time Updates**: Auto-refresh capability with configurable intervals
- **Responsive Design**: Automatically adapts to container size
- **Interactive**: Click events, tooltips, and hover effects
- **Export**: Export charts as PNG, SVG, or JPEG images
- **Error Handling**: Graceful error states with retry functionality
- **TikTok Branding**: Uses official TikTok color scheme
### Supported Visualizations
1. **Line Chart**: Views over time trend analysis
2. **Bar Chart**: Top 10 videos by views (horizontal bars)
3. **Pie Chart**: Engagement breakdown (Likes/Comments/Shares)
4. **Dashboard**: Combined multi-chart layout
## Prerequisites
### Required Dependencies
```json
{
"@visactor/vchart": "^1.11.0",
"@visactor/lark-vchart": "^1.0.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0"
}
```
### Installation
```bash
npm install --save @visactor/vchart @visactor/lark-vchart react react-dom
npm install --save-dev @types/react @types/react-dom
```
### Development Tools
- Node.js >= 16.0.0
- TypeScript >= 5.0.0
- npm >= 8.0.0
## Architecture
### Directory Structure
```
src/vchart-component/
├── index.tsx # Main component
├── specs/ # Chart specifications
│ ├── line-chart.ts # Line chart spec
│ ├── bar-chart.ts # Bar chart spec
│ ├── pie-chart.ts # Pie chart spec
│ ├── dashboard.ts # Dashboard spec
│ └── index.ts # Exports
└── component/
└── tiktok-dashboard/ # aPaaS component
├── index.meta.json # Component metadata
├── meta.ts # Type definitions
├── model.ts # Data model
└── index.tsx # Component entry
```
### Component Hierarchy
```
TikTokDashboard (aPaaS Component)
└── VChartComponent (React Component)
└── ChartContainer (Base Container)
└── VChart Instance (VChart Library)
```
## Development Setup
### 1. Clone and Install
```bash
cd /Users/mdch/hype-dash
npm install
```
### 2. Configure TypeScript
Ensure your `tsconfig.json` includes:
```json
{
"compilerOptions": {
"jsx": "react",
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}
```
### 3. Build Component
```bash
npm run build
```
## Component API
### TikTokDashboard Props
```typescript
interface TikTokDashboardProps {
/** Bitable table ID containing TikTok video data */
tableId: string;
/** Type of chart to display */
chartType?: 'line' | 'bar' | 'pie' | 'dashboard';
/** Auto-refresh interval in seconds (0 = no auto-refresh) */
refreshInterval?: number;
/** Chart height in pixels */
height?: number;
/** Custom CSS class name */
className?: string;
/** Event handlers */
onChartClick?: (data: ChartClickData) => void;
onDataLoad?: (data: DataLoadEvent) => void;
onError?: (error: ErrorEvent) => void;
}
```
### Default Values
```typescript
{
chartType: 'dashboard',
refreshInterval: 0,
height: 600
}
```
### Events
#### onChartClick
Triggered when a chart element is clicked.
```typescript
interface ChartClickData {
videoId: string;
title: string;
value: number;
type: string;
}
```
#### onDataLoad
Triggered when data is successfully loaded.
```typescript
interface DataLoadEvent {
recordCount: number;
timestamp: string;
}
```
#### onError
Triggered when an error occurs.
```typescript
interface ErrorEvent {
message: string;
code: string;
}
```
### Methods
The component exposes methods via React ref:
```typescript
const dashboardRef = useRef();
// Refresh data manually
await dashboardRef.current.refresh();
// Export chart as image
const imageData = await dashboardRef.current.exportImage('png');
// Get current data
const data = dashboardRef.current.getData();
```
## Data Format Requirements
### Bitable Table Structure
Required fields in your Bitable table:
| Field Name | Type | Required | Description |
|-----------|------|----------|-------------|
| Video ID | Text | Yes | Unique video identifier |
| Title | Text | Yes | Video title |
| Views | Number | Yes | View count |
| Likes | Number | No | Like count |
| Comments | Number | No | Comment count |
| Shares | Number | No | Share count |
| Watch % | Number | No | Watch completion percentage |
| Date published | Date | Yes | Publication date |
| Duration | Number | No | Video duration in seconds |
### Example Record
```json
{
"record_id": "recXXXXXX",
"fields": {
"Video ID": "7409731702890827041",
"Title": "Amazing TikTok Video",
"Views": 1500000,
"Likes": 125000,
"Comments": 8500,
"Shares": 3200,
"Watch %": 75.5,
"Date published": 1701388800000,
"Duration": 45
}
}
```
### Data Transformation
The component automatically transforms Bitable records to the internal format:
```typescript
interface TikTokVideoData {
videoId: string;
title: string;
views: number;
likes: number;
comments: number;
shares: number;
watchPercent: number;
datePublished: string; // ISO 8601
duration: number;
}
```
## Deployment Steps
### 1. Build the Component
```bash
./scripts/deploy-vchart-component.sh
```
This script will:
- Check prerequisites
- Install dependencies
- Compile TypeScript
- Bundle component
- Create deployment package
### 2. Locate the Package
The deployment package will be created at:
```
dist/vchart-component/component/tiktok-analytics-dashboard.zip
```
### 3. Upload to Lark aPaaS
1. **Open Developer Console**
- Navigate to: https://open.feishu.cn/app
- Select your app
2. **Navigate to Custom Components**
- Click on "Custom Components" in the sidebar
- Click "Upload Component"
3. **Upload Package**
- Select the `.zip` file from step 2
- Component ID: `tiktok-analytics-dashboard`
- Version: `1.0.0`
4. **Configure Settings**
- Enable in production: Yes
- Set permissions as needed
5. **Publish**
- Click "Publish" to make the component available
### 4. Verify Deployment
- Check component appears in the component library
- Test in a development environment first
- Verify all props and events work correctly
## Usage in aPaaS
### Basic Usage
```typescript
import { TikTokDashboard } from '@components/tiktok-analytics-dashboard';
function MyApp() {
return (
<TikTokDashboard
tableId="tblG4uuUvbwfvI9Z"
chartType="dashboard"
height={600}
/>
);
}
```
### With Event Handlers
```typescript
function MyApp() {
const handleChartClick = (data) => {
console.log('Clicked:', data);
// Navigate to video details, etc.
};
const handleDataLoad = (event) => {
console.log(`Loaded ${event.recordCount} videos`);
};
const handleError = (error) => {
console.error('Error:', error.message);
// Show error notification
};
return (
<TikTokDashboard
tableId="tblG4uuUvbwfI9Z"
chartType="dashboard"
height={600}
onChartClick={handleChartClick}
onDataLoad={handleDataLoad}
onError={handleError}
/>
);
}
```
### With Auto-Refresh
```typescript
function MyApp() {
return (
<TikTokDashboard
tableId="tblG4uuUvbwfvI9Z"
chartType="line"
refreshInterval={60} // Refresh every 60 seconds
height={400}
/>
);
}
```
### With Ref for Manual Control
```typescript
function MyApp() {
const dashboardRef = useRef();
const handleRefresh = async () => {
const data = await dashboardRef.current.refresh();
console.log('Refreshed with', data.length, 'records');
};
const handleExport = async () => {
const imageData = await dashboardRef.current.exportImage('png');
// Download or display image
};
return (
<>
<button onClick={handleRefresh}>Refresh</button>
<button onClick={handleExport}>Export PNG</button>
<TikTokDashboard
ref={dashboardRef}
tableId="tblG4uuUvbwfvI9Z"
chartType="dashboard"
/>
</>
);
}
```
## Customization
### Custom Colors
Modify `src/vchart-component/index.tsx`:
```typescript
export const TIKTOK_COLORS = {
primary: '#YOUR_COLOR',
secondary: '#YOUR_COLOR',
// ... etc
};
```
### Custom Chart Specs
Edit individual spec files in `src/vchart-component/specs/`:
- `line-chart.ts` - Customize line chart appearance
- `bar-chart.ts` - Customize bar chart layout
- `pie-chart.ts` - Customize pie chart segments
- `dashboard.ts` - Customize dashboard layout
### Adding New Chart Types
1. Create new spec file in `specs/`
2. Export from `specs/index.ts`
3. Add case in `VChartComponent` switch statement
4. Update type definitions in `meta.ts`
## Troubleshooting
### Common Issues
#### 1. Component Not Loading
**Problem**: Component doesn't render or shows blank screen
**Solutions**:
- Verify VChart dependencies are installed
- Check browser console for errors
- Ensure Bitable SDK is available in aPaaS environment
- Verify table ID is correct
#### 2. Data Not Displaying
**Problem**: Chart shows "No data available"
**Solutions**:
- Check Bitable table has records
- Verify field names match exactly (case-sensitive)
- Ensure required fields (Video ID, Title, Views) are present
- Check date fields are in millisecond timestamp format
#### 3. Chart Rendering Errors
**Problem**: Chart fails to render with error
**Solutions**:
- Verify data format is correct
- Check for null/undefined values in data
- Ensure numeric fields contain valid numbers
- Review browser console for VChart errors
#### 4. Performance Issues
**Problem**: Slow rendering with large datasets
**Solutions**:
- Limit records fetched (adjust `pageSize` in model.ts)
- Use pagination for large datasets
- Disable auto-refresh or increase interval
- Consider data aggregation on backend
#### 5. Export Not Working
**Problem**: Image export fails
**Solutions**:
- Ensure chart is fully rendered before export
- Check browser permissions for download
- Try different export formats
- Verify VChart instance is available
### Debug Mode
Enable debug logging:
```typescript
// In component/tiktok-dashboard/model.ts
const DEBUG = true;
if (DEBUG) {
console.log('Fetched data:', data);
console.log('Transformed:', transformedData);
}
```
### Getting Help
1. Check VChart documentation: https://visactor.io/vchart
2. Review Lark aPaaS docs: https://open.feishu.cn/document
3. Check component logs in browser console
4. Verify Bitable API responses
## Best Practices
### Performance
- Use `refreshInterval` wisely (recommended: 60-300 seconds)
- Limit data fetched to necessary fields
- Implement pagination for large datasets
- Cache transformed data when possible
### User Experience
- Always handle loading and error states
- Provide clear error messages
- Add retry functionality for failed requests
- Show data update timestamps
### Maintenance
- Keep VChart library updated
- Monitor component performance
- Log errors for debugging
- Test with production data volumes
### Security
- Validate table IDs before fetching
- Sanitize user input
- Handle sensitive data appropriately
- Use proper error messages (don't expose internals)
## Chart Specifications Reference
### Line Chart Features
- Time-series visualization
- Trend analysis
- Smooth animations
- Interactive tooltips
- Responsive axis labels
- Formatted number labels (K, M notation)
### Bar Chart Features
- Horizontal layout for better readability
- Gradient fill colors
- Top 10 filtering
- Title truncation for long text
- Value labels on bars
- Click interactions
### Pie Chart Features
- Donut style (inner radius)
- Percentage calculations
- Legend with values
- Color-coded segments
- Hover effects
- Outside labels
### Dashboard Features
- Grid layout (2x2)
- Multiple synchronized charts
- Shared color scheme
- Consistent styling
- Comprehensive data overview
- Single data fetch for all charts
## Version History
### v1.0.0 (2025-12-09)
- Initial release
- Support for 4 chart types
- Auto-refresh capability
- Export functionality
- Event handling
- Error recovery
- Responsive design
## License
MIT License - See LICENSE file for details
## Support
For issues or questions:
- GitHub: https://github.com/hypelab/hype-dash
- Email: dev@hypelab.com