# Lark Block Framework Guide
**Complete Developer Guide for Creating Chart Widgets in Lark**
---
## Overview
The Lark Block Framework enables developers to create custom, embeddable chart widgets that can be inserted into Lark Documents, Wikis, and Base dashboards. This SDK provides a TypeScript implementation that uses VChart for rendering and integrates seamlessly with Bitable data sources.
## Table of Contents
1. [Quick Start](#quick-start)
2. [Architecture](#architecture)
3. [Block Framework API](#block-framework-api)
4. [Chart Types](#chart-types)
5. [Data Integration](#data-integration)
6. [Custom Extensions](#custom-extensions)
7. [Deployment](#deployment)
8. [Examples](#examples)
9. [Troubleshooting](#troubleshooting)
---
## Quick Start
### Installation
```bash
npm install @hypelab/lark-dashboard-sdk
# or
pnpm add @hypelab/lark-dashboard-sdk
```
### Basic Usage
```typescript
import { createChartBlockCreator, createQuickChartConfig } from '@hypelab/lark-dashboard-sdk/block';
// Create the block creator configuration
const creator = createChartBlockCreator({
apiKey: process.env.LARK_API_KEY,
defaultChartType: 'bar',
debug: true,
});
// In Lark Block environment
Creator(creator);
```
### Quick Chart Configuration
```typescript
const config = createQuickChartConfig({
type: 'line',
appToken: 'IZ3cbKvLsakfGZsZgjvl38ifgwg',
tableId: 'tblkVYEcPh410eFw',
xAxisField: 'Date',
yAxisField: ['Views', 'Likes'],
title: 'TikTok Performance',
});
```
---
## Architecture
### Component Structure
```
lark-dashboard-sdk/
├── src/
│ ├── block/ # Block Framework
│ │ ├── ChartBlockCreator.ts # Main Creator implementation
│ │ ├── types.ts # TypeScript definitions
│ │ ├── index.ts # Public exports
│ │ ├── block.config.json # Block metadata
│ │ └── views/
│ │ └── chart-block.ttml # TTML template
│ ├── apaas/ # aPaaS utilities
│ └── vchart-component/ # Standalone VChart
```
### Data Flow
```
┌─────────────────┐ ┌────────────────┐ ┌─────────────┐
│ Bitable Table │────▶│ ChartBlockCreator │────▶│ VChart │
│ (Data Source) │ │ (Data Transform) │ │ (Rendering) │
└─────────────────┘ └────────────────┘ └─────────────┘
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ tt.request│ │ setData │ │ renderSync│
└───────────┘ └───────────┘ └───────────┘
```
---
## Block Framework API
### Creator Pattern
The Block Framework uses a Creator pattern for widget registration:
```typescript
interface CreatorConfig {
data: Record<string, any>; // Initial state
onLoad?: (options: LifecycleOptions) => void; // Block loaded
onReady?: () => void; // DOM ready
onDestroy?: () => void; // Cleanup
onShow?: () => void; // Block visible
onHide?: () => void; // Block hidden
methods?: Record<string, Function>; // Exposed methods
}
```
### Lifecycle Events
| Event | Description | Use Case |
|-------|-------------|----------|
| `onLoad` | Block initialized | Restore settings, fetch initial data |
| `onReady` | DOM rendered | Initialize chart instance |
| `onDestroy` | Block removed | Cleanup timers, release resources |
| `onShow` | Block visible | Resume data refresh |
| `onHide` | Block hidden | Pause refresh to save resources |
### tt API (Lark Environment)
```typescript
interface TtApi {
setBlockInfo: (info: { sourceMeta: BlockSourceMeta }) => void;
cancel: () => void;
request: <T>(options: RequestOptions<T>) => void;
showToast: (options: { title: string; icon?: 'success' | 'error' | 'none' }) => void;
showLoading: (options: { title: string }) => void;
hideLoading: () => void;
}
```
---
## Chart Types
### Supported Types
| Type | Icon | Description | Best For |
|------|------|-------------|----------|
| `bar` | 📊 | Bar chart | Category comparison |
| `line` | 📈 | Line chart | Trends over time |
| `pie` | 🥧 | Pie chart | Proportions |
| `area` | 📉 | Area chart | Cumulative trends |
| `scatter` | ⚫ | Scatter plot | Correlations |
| `funnel` | 🔻 | Funnel chart | Conversion flows |
| `radar` | 🎯 | Radar chart | Multi-variable analysis |
### Chart Configuration
```typescript
interface ChartConfig {
chartType: ChartType;
title?: string;
dataSource: DataSource;
options?: ChartOptions;
}
interface ChartOptions {
colors?: string[];
showLegend?: boolean;
showDataLabels?: boolean;
animation?: boolean;
stacked?: boolean;
}
```
---
## Data Integration
### Bitable Data Source
```typescript
interface DataSource {
appToken: string; // Bitable app token
tableId: string; // Table ID
viewId?: string; // Optional view ID
fields: {
xAxis: string; // X-axis field name
yAxis: string | string[]; // Y-axis field(s)
series?: string; // Optional grouping field
};
filters?: FilterCondition[];
}
```
### Example: TikTok Analytics
```typescript
const tiktokConfig: ChartConfig = {
chartType: 'bar',
title: 'Video Performance by Platform',
dataSource: {
appToken: 'IZ3cbKvLsakfGZsZgjvl38ifgwg',
tableId: 'tblkVYEcPh410eFw',
fields: {
xAxis: 'Platform',
yAxis: ['Views', 'Likes', 'Comments'],
series: 'Sentiment'
}
},
options: {
showLegend: true,
colors: ['#3370FF', '#34C759', '#FF3B30']
}
};
```
### Data Transformation
The SDK automatically transforms Bitable records:
```typescript
// Input: Bitable records
[
{ fields: { Platform: 'TikTok', Views: 15000, Likes: 1200 } },
{ fields: { Platform: 'Facebook', Views: 8500, Likes: 650 } }
]
// Output: VChart data points
[
{ x: 'TikTok', y: 15000, y2: 1200 },
{ x: 'Facebook', y: 8500, y2: 650 }
]
```
---
## Custom Extensions
### Base Dashboard Extensions
Lark Base dashboards support custom extensions via service URLs:
1. **Navigate to Extensions**: In your Base dashboard, click "Add Extension"
2. **Select Custom**: Choose "Add Custom" option
3. **Enter Service URL**: Input your deployed block service URL
4. **Authorize Access**: Grant necessary permissions
### Extension Types Available
| Extension | Description | Use Case |
|-----------|-------------|----------|
| Countdown | Time-based display | Events, launches |
| Map | Location visualization | Check-ins, addresses |
| Heatmap | Color-coded density | Trends, activity |
| Milestone | Date tracking | Project deadlines |
| **Custom** | Your block widget | Charts, analytics |
---
## Deployment
### 1. Build the Block
```bash
pnpm build:block
```
### 2. Deploy to Hosting
Deploy the built assets to your hosting service:
```bash
# Vercel
vercel --prod
# Cloudflare Workers
wrangler deploy
```
### 3. Register in Lark
1. Go to [Lark Open Platform](https://open.larksuite.com)
2. Create a new Block application
3. Configure the service URL
4. Set required permissions
5. Publish the block
### Block Manifest (block.config.json)
```json
{
"name": "Chart Block",
"version": "1.0.0",
"capabilities": ["data-binding", "bitable-integration"],
"permissions": {
"read": ["bitable.records"],
"write": ["block.create"]
}
}
```
---
## Examples
### Example 1: Sentiment Pie Chart
```typescript
import { createChartBlockCreator, createQuickChartConfig } from '@hypelab/lark-dashboard-sdk/block';
const sentimentPieConfig = createQuickChartConfig({
type: 'pie',
appToken: 'IZ3cbKvLsakfGZsZgjvl38ifgwg',
tableId: 'tblkVYEcPh410eFw',
xAxisField: 'Sentiment',
yAxisField: 'Count',
title: 'Sentiment Distribution'
});
const creator = createChartBlockCreator();
creator.methods.createBlock(sentimentPieConfig);
```
### Example 2: Time Series Line Chart
```typescript
const timeSeriesConfig: ChartConfig = {
chartType: 'line',
title: 'Views Over Time',
dataSource: {
appToken: 'YOUR_APP_TOKEN',
tableId: 'YOUR_TABLE_ID',
fields: {
xAxis: 'Date',
yAxis: ['Views', 'Likes', 'Comments']
}
},
options: {
showLegend: true,
animation: true,
colors: ['#1890ff', '#52c41a', '#faad14']
}
};
```
### Example 3: Stacked Bar Chart
```typescript
const stackedBarConfig: ChartConfig = {
chartType: 'bar',
title: 'Engagement by Platform',
dataSource: {
appToken: 'YOUR_APP_TOKEN',
tableId: 'YOUR_TABLE_ID',
fields: {
xAxis: 'Platform',
yAxis: 'Engagement',
series: 'Type' // Creates stacked bars by Type
}
},
options: {
stacked: true,
showDataLabels: true
}
};
```
---
## Troubleshooting
### Common Issues
#### 1. "Chart container not found"
**Cause**: The DOM element isn't ready when renderChart is called.
**Solution**: Ensure chart rendering happens in `onReady` callback.
#### 2. "Failed to load data"
**Cause**: API authentication failed or incorrect table/app tokens.
**Solution**: Verify your `apiKey` and `appToken` are correct.
#### 3. Charts not updating
**Cause**: Data refresh timer not started.
**Solution**: Call `startRefresh()` in `onShow` callback.
### Debug Mode
Enable debug logging:
```typescript
const creator = createChartBlockCreator({
debug: true, // Logs all lifecycle events
});
```
### VChart Debugging
Check the browser console for VChart errors:
```javascript
// In browser console
window.vchart_debug = true;
```
---
## API Limitations
### What's NOT Possible via API
| Feature | API Support | Alternative |
|---------|-------------|-------------|
| Create Dashboard View | No | Manual UI |
| Add Chart to Dashboard | No | Custom Extension |
| Native Dashboard Blocks | No | Block Framework |
### Supported View Types (via API)
- `grid` - Table view
- `kanban` - Board view
- `gallery` - Card gallery
- `gantt` - Timeline view
- `form` - Form input
Dashboard view type is **NOT** supported via API.
---
## Resources
### Documentation
- [Lark Open Platform](https://open.larksuite.com)
- [Bitable API Reference](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/bitable-v1/app-table-record/search)
- [VChart Documentation](https://visactor.io/vchart)
- [Block Framework Introduction](https://open.larksuite.com/document/uAjLw4CM/uYjL24iN/docs-add-on/docs-add-on-introduction)
### Related Files in SDK
- `/src/block/ChartBlockCreator.ts` - Main implementation
- `/src/block/types.ts` - TypeScript definitions
- `/src/block/views/chart-block.ttml` - TTML template
- `/examples/chart-block-example.ts` - Usage examples
- `/docs/API_LIMITATIONS.md` - API constraints
---
**Last Updated**: 2025-12-09
**Version**: 1.0.0