feat: add annotation types management system

- Created annotation_types table with name, display_name, color, category, icon
- Implemented CRUD API endpoints for annotation types management
- Built annotation types management UI page at /annotation-types
- Updated Toolbox component to dynamically load and display annotation types
- Updated CandleChart component to use dynamic annotation types for markers
- Added seed functionality for default types (break_up, break_down, line)
- Cleaned up duplicate migration files
This commit is contained in:
Marko Djordjevic 2026-02-12 18:16:09 +01:00
parent 50229e2ccf
commit 974d9f5598
13 changed files with 942 additions and 79 deletions

View file

@ -0,0 +1,390 @@
'use client';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
type AnnotationType = {
id: number;
name: string;
display_name: string;
color: string;
category: string;
icon: string | null;
is_active: number;
created_at: number;
};
export default function AnnotationTypesPage() {
const [types, setTypes] = useState<AnnotationType[]>([]);
const [loading, setLoading] = useState(true);
const [editingId, setEditingId] = useState<number | null>(null);
const [showAddForm, setShowAddForm] = useState(false);
// Form state
const [formData, setFormData] = useState({
name: '',
display_name: '',
color: '#3b82f6',
category: 'marker',
icon: '',
});
const fetchTypes = async () => {
try {
const res = await fetch('/api/annotation-types');
if (res.ok) {
const data = await res.json();
setTypes(data);
}
} catch (error) {
console.error('Error fetching annotation types:', error);
} finally {
setLoading(false);
}
};
const seedDefaultTypes = async () => {
try {
const res = await fetch('/api/annotation-types', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'seed' }),
});
if (res.ok) {
fetchTypes();
}
} catch (error) {
console.error('Error seeding types:', error);
}
};
useEffect(() => {
fetchTypes();
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (editingId !== null) {
// Update existing type
const res = await fetch(`/api/annotation-types/${editingId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (res.ok) {
setEditingId(null);
resetForm();
fetchTypes();
} else {
const error = await res.json();
alert(error.error || 'Failed to update type');
}
} else {
// Create new type
const res = await fetch('/api/annotation-types', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (res.ok) {
setShowAddForm(false);
resetForm();
fetchTypes();
} else {
const error = await res.json();
alert(error.error || 'Failed to create type');
}
}
} catch (error) {
console.error('Error saving type:', error);
alert('Failed to save type');
}
};
const handleEdit = (type: AnnotationType) => {
setFormData({
name: type.name,
display_name: type.display_name,
color: type.color,
category: type.category,
icon: type.icon || '',
});
setEditingId(type.id);
setShowAddForm(true);
};
const handleDelete = async (id: number) => {
if (!confirm('Are you sure you want to delete this annotation type?')) {
return;
}
try {
const res = await fetch(`/api/annotation-types?id=${id}`, {
method: 'DELETE',
});
if (res.ok) {
fetchTypes();
} else {
const error = await res.json();
alert(error.error || 'Failed to delete type');
}
} catch (error) {
console.error('Error deleting type:', error);
alert('Failed to delete type');
}
};
const resetForm = () => {
setFormData({
name: '',
display_name: '',
color: '#3b82f6',
category: 'marker',
icon: '',
});
setEditingId(null);
};
const handleCancel = () => {
setShowAddForm(false);
resetForm();
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50 p-8">
<div className="max-w-6xl mx-auto">
<p>Loading...</p>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 p-8">
<div className="max-w-6xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Annotation Types</h1>
<p className="text-gray-600 mt-1">Manage annotation types for your charts</p>
</div>
<div className="flex gap-2">
<Button onClick={() => window.location.href = '/'} variant="outline">
Back to Chart
</Button>
{types.length === 0 && (
<Button onClick={seedDefaultTypes}>
Seed Default Types
</Button>
)}
{!showAddForm && (
<Button onClick={() => setShowAddForm(true)}>
Add New Type
</Button>
)}
</div>
</div>
{showAddForm && (
<div className="bg-white p-6 rounded-lg shadow mb-6">
<h2 className="text-xl font-semibold mb-4">
{editingId !== null ? 'Edit Annotation Type' : 'Add New Annotation Type'}
</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Internal Name *
</label>
<Input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="e.g., break_up"
required
disabled={editingId !== null}
/>
<p className="text-xs text-gray-500 mt-1">
Used internally (cannot be changed after creation)
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Display Name *
</label>
<Input
type="text"
value={formData.display_name}
onChange={(e) => setFormData({ ...formData, display_name: e.target.value })}
placeholder="e.g., Break Up"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Color *
</label>
<div className="flex gap-2">
<Input
type="color"
value={formData.color}
onChange={(e) => setFormData({ ...formData, color: e.target.value })}
className="w-20"
required
/>
<Input
type="text"
value={formData.color}
onChange={(e) => setFormData({ ...formData, color: e.target.value })}
placeholder="#3b82f6"
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Category *
</label>
<select
value={formData.category}
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-md"
required
>
<option value="marker">Marker</option>
<option value="line">Line</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Icon
</label>
<Input
type="text"
value={formData.icon}
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
placeholder="e.g., arrowUp"
/>
</div>
</div>
<div className="flex gap-2">
<Button type="submit">
{editingId !== null ? 'Update' : 'Create'}
</Button>
<Button type="button" variant="outline" onClick={handleCancel}>
Cancel
</Button>
</div>
</form>
</div>
)}
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Display Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Color
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Category
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Icon
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{types.length === 0 ? (
<tr>
<td colSpan={7} className="px-6 py-8 text-center text-gray-500">
No annotation types found. Click "Seed Default Types" to get started.
</td>
</tr>
) : (
types.map((type) => (
<tr key={type.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{type.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{type.display_name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center gap-2">
<div
className="w-6 h-6 rounded border border-gray-300"
style={{ backgroundColor: type.color }}
/>
<span className="text-gray-600">{type.color}</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
<span className="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
{type.category}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
{type.icon || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<span
className={`px-2 py-1 text-xs font-medium rounded-full ${
type.is_active
? 'bg-green-100 text-green-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{type.is_active ? 'Active' : 'Inactive'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div className="flex justify-end gap-2">
<Button
size="sm"
variant="outline"
onClick={() => handleEdit(type)}
>
Edit
</Button>
<Button
size="sm"
variant="outline"
onClick={() => handleDelete(type.id)}
>
Delete
</Button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { annotationTypes } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
type RouteContext = {
params: Promise<{ id: string }>;
};
// PATCH - Update annotation type
export async function PATCH(
request: NextRequest,
context: RouteContext
) {
try {
const { id } = await context.params;
const body = await request.json();
const { name, display_name, color, category, icon, is_active } = body;
const updateData: any = {};
if (name !== undefined) updateData.name = name;
if (display_name !== undefined) updateData.display_name = display_name;
if (color !== undefined) updateData.color = color;
if (category !== undefined) updateData.category = category;
if (icon !== undefined) updateData.icon = icon;
if (is_active !== undefined) updateData.is_active = is_active;
if (Object.keys(updateData).length === 0) {
return NextResponse.json(
{ error: 'No fields to update' },
{ status: 400 }
);
}
const result = await db
.update(annotationTypes)
.set(updateData)
.where(eq(annotationTypes.id, parseInt(id)))
.returning();
if (result.length === 0) {
return NextResponse.json(
{ error: 'Annotation type not found' },
{ status: 404 }
);
}
return NextResponse.json(result[0]);
} catch (error: any) {
console.error('Error updating annotation type:', error);
if (error.message?.includes('UNIQUE constraint failed')) {
return NextResponse.json(
{ error: 'Annotation type with this name already exists' },
{ status: 409 }
);
}
return NextResponse.json(
{ error: 'Failed to update annotation type' },
{ status: 500 }
);
}
}

View file

@ -0,0 +1,160 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { annotationTypes, annotations } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
// GET - List all annotation types
export async function GET() {
try {
const types = await db.select().from(annotationTypes);
return NextResponse.json(types);
} catch (error) {
console.error('Error fetching annotation types:', error);
return NextResponse.json(
{ error: 'Failed to fetch annotation types' },
{ status: 500 }
);
}
}
// POST - Create new annotation type or seed defaults
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// Special case: seed default types
if (body.action === 'seed') {
const existing = await db.select().from(annotationTypes);
if (existing.length > 0) {
return NextResponse.json({ message: 'Types already seeded' });
}
const now = Math.floor(Date.now() / 1000);
const defaultTypes = [
{
name: 'break_up',
display_name: 'Break Up',
color: '#10b981',
category: 'marker',
icon: 'arrowUp',
is_active: 1,
created_at: now,
},
{
name: 'break_down',
display_name: 'Break Down',
color: '#ef4444',
category: 'marker',
icon: 'arrowDown',
is_active: 1,
created_at: now,
},
{
name: 'line',
display_name: 'Line',
color: '#3b82f6',
category: 'line',
icon: 'line',
is_active: 1,
created_at: now,
},
];
await db.insert(annotationTypes).values(defaultTypes);
return NextResponse.json({ message: 'Default types seeded successfully' });
}
// Regular create
const { name, display_name, color, category, icon } = body;
if (!name || !display_name || !color || !category) {
return NextResponse.json(
{ error: 'name, display_name, color, and category are required' },
{ status: 400 }
);
}
const result = await db
.insert(annotationTypes)
.values({
name,
display_name,
color,
category,
icon: icon || null,
is_active: 1,
created_at: Math.floor(Date.now() / 1000),
})
.returning();
return NextResponse.json(result[0], { status: 201 });
} catch (error: any) {
console.error('Error creating annotation type:', error);
if (error.message?.includes('UNIQUE constraint failed')) {
return NextResponse.json(
{ error: 'Annotation type with this name already exists' },
{ status: 409 }
);
}
return NextResponse.json(
{ error: 'Failed to create annotation type' },
{ status: 500 }
);
}
}
// DELETE - Delete annotation type (only if no annotations use it)
export async function DELETE(request: NextRequest) {
try {
const { searchParams } = request.nextUrl;
const id = searchParams.get('id');
if (!id) {
return NextResponse.json(
{ error: 'id parameter is required' },
{ status: 400 }
);
}
// Check if the type exists
const type = await db
.select()
.from(annotationTypes)
.where(eq(annotationTypes.id, parseInt(id)))
.limit(1);
if (type.length === 0) {
return NextResponse.json(
{ error: 'Annotation type not found' },
{ status: 404 }
);
}
// Check if any annotations use this type
const existingAnnotations = await db
.select()
.from(annotations)
.where(eq(annotations.label_type, type[0].name))
.limit(1);
if (existingAnnotations.length > 0) {
return NextResponse.json(
{ error: 'Cannot delete annotation type: annotations exist with this type' },
{ status: 409 }
);
}
await db.delete(annotationTypes).where(eq(annotationTypes.id, parseInt(id)));
return NextResponse.json({ message: 'Annotation type deleted successfully' });
} catch (error) {
console.error('Error deleting annotation type:', error);
return NextResponse.json(
{ error: 'Failed to delete annotation type' },
{ status: 500 }
);
}
}

View file

@ -93,6 +93,12 @@ export default function Home() {
<div className="p-6 border-b border-border">
<h1 className="text-2xl font-semibold text-foreground">Candle Annotator</h1>
<p className="text-sm text-muted-foreground mt-1">Chart annotation tool</p>
<a
href="/annotation-types"
className="mt-3 inline-block text-sm text-blue-600 hover:text-blue-800 underline"
>
Manage Annotation Types
</a>
</div>
<div className="p-6">
<FileUpload onUploadSuccess={handleUploadSuccess} />

View file

@ -25,6 +25,16 @@ interface Annotation {
created_at: number;
}
type AnnotationType = {
id: number;
name: string;
display_name: string;
color: string;
category: string;
icon: string | null;
is_active: number;
};
interface CandleChartProps {
activeTool: string | null;
onAnnotationChange?: () => void;
@ -44,6 +54,7 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
const seriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
const [candles, setCandles] = useState<Candle[]>([]);
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [annotationTypes, setAnnotationTypes] = useState<AnnotationType[]>([]);
const [isEmpty, setIsEmpty] = useState(true);
// Fetch candles from API
@ -73,11 +84,25 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
}
};
// Fetch annotation types from API
const fetchAnnotationTypes = async () => {
try {
const response = await fetch('/api/annotation-types');
const data = await response.json();
setAnnotationTypes(data.filter((t: AnnotationType) => t.is_active === 1));
return data;
} catch (error) {
console.error('Failed to fetch annotation types:', error);
return [];
}
};
// Expose refresh method to parent
useImperativeHandle(ref, () => ({
refreshData: async () => {
await fetchCandles();
await fetchAnnotations();
await fetchAnnotationTypes();
},
}));
@ -154,30 +179,43 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
// Update markers from annotations
useEffect(() => {
if (!seriesRef.current) return;
if (!seriesRef.current || annotationTypes.length === 0) return;
const markerAnnotations = annotations.filter(
(a) => a.label_type === 'break_up' || a.label_type === 'break_down'
// Get marker type names
const markerTypeNames = annotationTypes
.filter((t) => t.category === 'marker')
.map((t) => t.name);
const markerAnnotations = annotations.filter((a) =>
markerTypeNames.includes(a.label_type)
);
const markers = markerAnnotations
.map((annotation) => {
const annotationType = annotationTypes.find((t) => t.name === annotation.label_type);
if (!annotationType) return null;
const isSelected = annotation.id === selectedLabelId;
// Determine marker shape and position based on icon
const isUpArrow = annotationType.icon === 'arrowUp';
return {
time: annotation.timestamp as Time,
position: annotation.label_type === 'break_up' ? ('belowBar' as const) : ('aboveBar' as const),
position: isUpArrow ? ('belowBar' as const) : ('aboveBar' as const),
color: isSelected
? (annotation.label_type === 'break_up' ? '#059669' : '#dc2626')
: (annotation.label_type === 'break_up' ? '#10b981' : '#ef4444'),
shape: annotation.label_type === 'break_up' ? ('arrowUp' as const) : ('arrowDown' as const),
text: annotation.label_type === 'break_up' ? 'Break Up' : 'Break Down',
? annotationType.color + 'CC' // Add slight transparency when selected
: annotationType.color,
shape: isUpArrow ? ('arrowUp' as const) : ('arrowDown' as const),
text: annotationType.display_name,
size: isSelected ? 2 : 1,
};
})
.sort((a, b) => (a.time as number) - (b.time as number));
.filter((m) => m !== null)
.sort((a, b) => (a!.time as number) - (b!.time as number));
seriesRef.current.setMarkers(markers);
}, [annotations, selectedLabelId]);
seriesRef.current.setMarkers(markers as any);
}, [annotations, selectedLabelId, annotationTypes]);
// Handle chart clicks for annotation
useEffect(() => {
@ -194,8 +232,12 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
if (time === null || price === null) return;
// For break_up and break_down, snap to nearest candle
if (activeTool === 'break_up' || activeTool === 'break_down') {
// Check if activeTool is a marker type
const markerType = annotationTypes.find(
(t) => t.category === 'marker' && t.name === activeTool
);
if (markerType) {
const timestamp = typeof time === 'string' ? Date.parse(time) / 1000 : (time as number);
// Find nearest candle
@ -228,12 +270,15 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
// For delete tool, find and delete marker at clicked position
if (activeTool === 'delete') {
const timestamp = typeof time === 'string' ? Date.parse(time) / 1000 : (time as number);
const markerTypeNames = annotationTypes
.filter((t) => t.category === 'marker')
.map((t) => t.name);
// Find annotation at this timestamp (within tolerance)
const tolerance = 60; // 60 seconds tolerance
const annotation = annotations.find(
(a) =>
(a.label_type === 'break_up' || a.label_type === 'break_down') &&
markerTypeNames.includes(a.label_type) &&
Math.abs(a.timestamp - timestamp) < tolerance
);
@ -254,14 +299,21 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
}
// Select/deselect label markers by clicking them
if (!activeTool || activeTool === 'break_up' || activeTool === 'break_down') {
const isMarkerTool = annotationTypes.find(
(t) => t.category === 'marker' && t.name === activeTool
);
if (!activeTool || isMarkerTool) {
const timestamp = typeof time === 'string' ? Date.parse(time) / 1000 : (time as number);
const markerTypeNames = annotationTypes
.filter((t) => t.category === 'marker')
.map((t) => t.name);
// Find annotation at this timestamp (within tolerance)
const tolerance = 60; // 60 seconds tolerance
const annotation = annotations.find(
(a) =>
(a.label_type === 'break_up' || a.label_type === 'break_down') &&
markerTypeNames.includes(a.label_type) &&
Math.abs(a.timestamp - timestamp) < tolerance
);
@ -276,12 +328,13 @@ const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
return () => {
chartRef.current?.unsubscribeClick(handleClick);
};
}, [activeTool, candles, annotations, onAnnotationChange]);
}, [activeTool, candles, annotations, annotationTypes, onAnnotationChange]);
// Fetch data on mount
useEffect(() => {
fetchCandles();
fetchAnnotations();
fetchAnnotationTypes();
}, []);
if (isEmpty) {

View file

@ -1,11 +1,21 @@
'use client';
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { ArrowUpCircle, ArrowDownCircle, TrendingUp, Trash2, Download, ChevronDown, ChevronUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
export type Tool = 'break_up' | 'break_down' | 'line' | 'delete' | null;
export type Tool = string | 'delete' | null;
type AnnotationType = {
id: number;
name: string;
display_name: string;
color: string;
category: string;
icon: string | null;
is_active: number;
};
interface Annotation {
id: number;
@ -40,7 +50,24 @@ export default function Toolbox({
}: ToolboxProps) {
const [labelsExpanded, setLabelsExpanded] = useState(true);
const [searchText, setSearchText] = useState('');
const [filterType, setFilterType] = useState<'all' | 'break_up' | 'break_down'>('all');
const [filterType, setFilterType] = useState<string>('all');
const [annotationTypes, setAnnotationTypes] = useState<AnnotationType[]>([]);
// Fetch annotation types on mount
useEffect(() => {
const fetchTypes = async () => {
try {
const res = await fetch('/api/annotation-types');
if (res.ok) {
const data = await res.json();
setAnnotationTypes(data.filter((t: AnnotationType) => t.is_active === 1));
}
} catch (error) {
console.error('Failed to fetch annotation types:', error);
}
};
fetchTypes();
}, []);
const handleToolClick = (tool: Tool) => {
// Toggle: if clicking the active tool, deactivate it
@ -51,9 +78,13 @@ export default function Toolbox({
}
};
// Get marker types (exclude line types)
const markerTypes = annotationTypes.filter((t) => t.category === 'marker');
const markerTypeNames = markerTypes.map((t) => t.name);
// Filter and sort annotations
const labelAnnotations = annotations
.filter((a) => a.label_type === 'break_up' || a.label_type === 'break_down')
.filter((a) => markerTypeNames.includes(a.label_type))
.filter((a) => (filterType === 'all' ? true : a.label_type === filterType))
.sort((a, b) => b.timestamp - a.timestamp);
@ -68,8 +99,11 @@ export default function Toolbox({
return formattedTime.toLowerCase().includes(searchText.toLowerCase());
});
const breakUpCount = labelAnnotations.filter((a) => a.label_type === 'break_up').length;
const breakDownCount = labelAnnotations.filter((a) => a.label_type === 'break_down').length;
// Count annotations per type
const typeCounts = markerTypes.reduce((acc, type) => {
acc[type.name] = labelAnnotations.filter((a) => a.label_type === type.name).length;
return acc;
}, {} as Record<string, number>);
const handleLabelDelete = async (id: number, e: React.MouseEvent) => {
e.stopPropagation();
@ -85,37 +119,51 @@ export default function Toolbox({
}
};
const getIconComponent = (iconName: string | null) => {
switch (iconName) {
case 'arrowUp':
return <ArrowUpCircle className="w-5 h-5" />;
case 'arrowDown':
return <ArrowDownCircle className="w-5 h-5" />;
case 'line':
return <TrendingUp className="w-5 h-5" />;
default:
return <ArrowUpCircle className="w-5 h-5" />;
}
};
return (
<div className="flex-1 flex flex-col gap-4 overflow-y-auto">
<h2 className="text-lg font-semibold text-foreground">Annotation Tools</h2>
<div className="flex flex-col gap-2">
<Button
variant={activeTool === 'break_up' ? 'default' : 'outline'}
className="justify-start gap-2"
onClick={() => handleToolClick('break_up')}
>
<ArrowUpCircle className="w-5 h-5" />
Label: Break Up
</Button>
{/* Marker type buttons */}
{markerTypes.map((type) => (
<Button
key={type.id}
variant={activeTool === type.name ? 'default' : 'outline'}
className="justify-start gap-2"
onClick={() => handleToolClick(type.name)}
>
{getIconComponent(type.icon)}
{type.display_name}
</Button>
))}
<Button
variant={activeTool === 'break_down' ? 'default' : 'outline'}
className="justify-start gap-2"
onClick={() => handleToolClick('break_down')}
>
<ArrowDownCircle className="w-5 h-5" />
Label: Break Down
</Button>
<Button
variant={activeTool === 'line' ? 'default' : 'outline'}
className="justify-start gap-2"
onClick={() => handleToolClick('line')}
>
<TrendingUp className="w-5 h-5" />
Draw Line
</Button>
{/* Line type buttons */}
{annotationTypes
.filter((t) => t.category === 'line')
.map((type) => (
<Button
key={type.id}
variant={activeTool === type.name ? 'default' : 'outline'}
className="justify-start gap-2"
onClick={() => handleToolClick(type.name)}
>
{getIconComponent(type.icon)}
{type.display_name}
</Button>
))}
{/* Color picker */}
<div className="flex gap-1 px-1">
@ -179,7 +227,12 @@ export default function Toolbox({
<div className="mt-3 space-y-2">
{/* Count display */}
<div className="text-xs text-muted-foreground px-2">
Break Up: {breakUpCount} | Break Down: {breakDownCount}
{markerTypes.map((type, idx) => (
<span key={type.id}>
{idx > 0 && ' | '}
{type.display_name}: {typeCounts[type.name] || 0}
</span>
))}
</div>
{/* Search input */}
@ -193,12 +246,15 @@ export default function Toolbox({
{/* Filter dropdown */}
<select
value={filterType}
onChange={(e) => setFilterType(e.target.value as 'all' | 'break_up' | 'break_down')}
onChange={(e) => setFilterType(e.target.value)}
className="w-full h-8 px-2 text-sm rounded border border-border bg-card"
>
<option value="all">All Types</option>
<option value="break_up">Break Up Only</option>
<option value="break_down">Break Down Only</option>
{markerTypes.map((type) => (
<option key={type.id} value={type.name}>
{type.display_name} Only
</option>
))}
</select>
{/* Labels list */}
@ -218,6 +274,7 @@ export default function Toolbox({
minute: '2-digit',
});
const isSelected = annotation.id === selectedLabelId;
const annotationType = annotationTypes.find((t) => t.name === annotation.label_type);
return (
<div
@ -234,13 +291,13 @@ export default function Toolbox({
<div className="font-medium text-foreground">{formattedTime}</div>
<div className="mt-1 flex items-center gap-2">
<span
className={`px-2 py-0.5 rounded text-xs font-medium ${
annotation.label_type === 'break_up'
? 'bg-emerald-100 text-emerald-700'
: 'bg-red-100 text-red-700'
}`}
className="px-2 py-0.5 rounded text-xs font-medium"
style={{
backgroundColor: annotationType ? `${annotationType.color}20` : '#e5e7eb',
color: annotationType?.color || '#374151',
}}
>
{annotation.label_type === 'break_up' ? 'Break Up' : 'Break Down'}
{annotationType?.display_name || annotation.label_type}
</span>
</div>
</div>

View file

@ -9,6 +9,17 @@ export const candles = sqliteTable('candles', {
close: real('close').notNull(),
});
export const annotationTypes = sqliteTable('annotation_types', {
id: integer('id').primaryKey({ autoIncrement: true }),
name: text('name').notNull().unique(), // internal name (e.g., 'break_up')
display_name: text('display_name').notNull(), // display name (e.g., 'Break Up')
color: text('color').notNull(), // hex color code
category: text('category').notNull(), // 'marker' or 'line'
icon: text('icon'), // icon name or symbol
is_active: integer('is_active').notNull().default(1), // 1 = active, 0 = inactive
created_at: integer('created_at').notNull(),
});
export const annotations = sqliteTable('annotations', {
id: integer('id').primaryKey({ autoIncrement: true }),
timestamp: integer('timestamp').notNull(),

View file

@ -0,0 +1,46 @@
import { db } from './index';
import { annotationTypes } from './schema';
export async function seedAnnotationTypes() {
const now = Math.floor(Date.now() / 1000);
const defaultTypes = [
{
name: 'break_up',
display_name: 'Break Up',
color: '#10b981',
category: 'marker',
icon: 'arrowUp',
is_active: 1,
created_at: now,
},
{
name: 'break_down',
display_name: 'Break Down',
color: '#ef4444',
category: 'marker',
icon: 'arrowDown',
is_active: 1,
created_at: now,
},
{
name: 'line',
display_name: 'Line',
color: '#3b82f6',
category: 'line',
icon: 'line',
is_active: 1,
created_at: now,
},
];
// Check if types already exist
const existing = await db.select().from(annotationTypes);
if (existing.length === 0) {
await db.insert(annotationTypes).values(defaultTypes);
console.log('Seeded default annotation types');
} else {
console.log('Annotation types already exist, skipping seed');
}
}