feat: implement sections 6-7 - span selection, preview, and label assignment popover
This commit is contained in:
parent
c9d2cbfc4b
commit
586f02ed69
11 changed files with 647 additions and 22483 deletions
347
src/components/SpanAnnotationManager.tsx
Normal file
347
src/components/SpanAnnotationManager.tsx
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { IChartApi, ISeriesApi, Time } from 'lightweight-charts';
|
||||
import { SpanRectanglePrimitive, SpanData } from './SpanRectanglePrimitive';
|
||||
import SpanPopover from './SpanPopover';
|
||||
|
||||
interface Candle {
|
||||
time: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
}
|
||||
|
||||
interface SpanAnnotation {
|
||||
id: number;
|
||||
chart_id: number;
|
||||
start_time: number;
|
||||
end_time: number;
|
||||
label: string;
|
||||
confidence: number | null;
|
||||
outcome: string | null;
|
||||
notes: string | null;
|
||||
sub_spans: any;
|
||||
color: string;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
interface SpanLabelType {
|
||||
id: number;
|
||||
name: string;
|
||||
display_name: string;
|
||||
color: string;
|
||||
hotkey: string | null;
|
||||
is_active: number;
|
||||
sort_order: number;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
interface SpanAnnotationManagerProps {
|
||||
chart: IChartApi | null;
|
||||
series: ISeriesApi<'Candlestick'> | null;
|
||||
activeTool: string | null;
|
||||
candles: Candle[];
|
||||
spanAnnotations: SpanAnnotation[];
|
||||
spanLabelTypes: SpanLabelType[];
|
||||
selectedSpanId: number | null;
|
||||
onSpanAnnotationsChange: () => void;
|
||||
onSelectedSpanChange: (spanId: number | null) => void;
|
||||
activeChartId: number | null;
|
||||
}
|
||||
|
||||
type InteractionState = 'idle' | 'first-click-done' | 'popover-open';
|
||||
|
||||
export default function SpanAnnotationManager({
|
||||
chart,
|
||||
series,
|
||||
activeTool,
|
||||
candles,
|
||||
spanAnnotations,
|
||||
spanLabelTypes,
|
||||
selectedSpanId,
|
||||
onSpanAnnotationsChange,
|
||||
onSelectedSpanChange,
|
||||
activeChartId,
|
||||
}: SpanAnnotationManagerProps) {
|
||||
const [interactionState, setInteractionState] = useState<InteractionState>('idle');
|
||||
const [startCandle, setStartCandle] = useState<Candle | null>(null);
|
||||
const [endCandle, setEndCandle] = useState<Candle | null>(null);
|
||||
const [previewPrimitive, setPreviewPrimitive] = useState<SpanRectanglePrimitive | null>(null);
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
const primitivesRef = useRef<Map<number, SpanRectanglePrimitive>>(new Map());
|
||||
|
||||
// Find nearest candle to a timestamp
|
||||
const findNearestCandle = (timestamp: number): Candle | null => {
|
||||
if (candles.length === 0) return null;
|
||||
return candles.reduce((prev, curr) => {
|
||||
return Math.abs(curr.time - timestamp) < Math.abs(prev.time - timestamp) ? curr : prev;
|
||||
});
|
||||
};
|
||||
|
||||
// Calculate price range for candles in a span
|
||||
const calculatePriceRange = (start: Candle, end: Candle): { max_high: number; min_low: number } => {
|
||||
const startIdx = candles.findIndex((c) => c.time === start.time);
|
||||
const endIdx = candles.findIndex((c) => c.time === end.time);
|
||||
|
||||
if (startIdx === -1 || endIdx === -1) {
|
||||
return { max_high: Math.max(start.high, end.high), min_low: Math.min(start.low, end.low) };
|
||||
}
|
||||
|
||||
const [minIdx, maxIdx] = [Math.min(startIdx, endIdx), Math.max(startIdx, endIdx)];
|
||||
const spanCandles = candles.slice(minIdx, maxIdx + 1);
|
||||
|
||||
const max_high = Math.max(...spanCandles.map((c) => c.high));
|
||||
const min_low = Math.min(...spanCandles.map((c) => c.low));
|
||||
|
||||
return { max_high, min_low };
|
||||
};
|
||||
|
||||
// Render span annotations as primitives
|
||||
useEffect(() => {
|
||||
if (!series || !chart) return;
|
||||
|
||||
// Clear existing primitives
|
||||
primitivesRef.current.forEach((primitive) => {
|
||||
series.detachPrimitive(primitive);
|
||||
});
|
||||
primitivesRef.current.clear();
|
||||
|
||||
// Create primitives for each span annotation
|
||||
spanAnnotations.forEach((span) => {
|
||||
const { max_high, min_low } = calculatePriceRange(
|
||||
{ time: span.start_time, open: 0, high: 0, low: 0, close: 0 },
|
||||
{ time: span.end_time, open: 0, high: 0, low: 0, close: 0 }
|
||||
);
|
||||
|
||||
// If we can't calculate price range from candles, use sensible defaults
|
||||
const spanData: SpanData = {
|
||||
id: span.id,
|
||||
start_time: span.start_time,
|
||||
end_time: span.end_time,
|
||||
label: span.label,
|
||||
color: span.color,
|
||||
max_high: max_high,
|
||||
min_low: min_low,
|
||||
};
|
||||
|
||||
const primitive = new SpanRectanglePrimitive({
|
||||
data: spanData,
|
||||
isSelected: span.id === selectedSpanId,
|
||||
});
|
||||
|
||||
series.attachPrimitive(primitive);
|
||||
primitivesRef.current.set(span.id, primitive);
|
||||
});
|
||||
|
||||
// Request chart update
|
||||
chart.timeScale().fitContent();
|
||||
}, [spanAnnotations, selectedSpanId, series, chart, candles]);
|
||||
|
||||
// Handle clicks on chart for span tool
|
||||
useEffect(() => {
|
||||
if (!chart || !series || activeTool !== 'span') {
|
||||
// Clean up preview if tool changes
|
||||
if (previewPrimitive && series) {
|
||||
series.detachPrimitive(previewPrimitive);
|
||||
setPreviewPrimitive(null);
|
||||
}
|
||||
setInteractionState('idle');
|
||||
setStartCandle(null);
|
||||
setEndCandle(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const handleClick = (param: any) => {
|
||||
if (!param.point) return;
|
||||
|
||||
const time = chart.timeScale().coordinateToTime(param.point.x);
|
||||
if (!time) return;
|
||||
|
||||
const timestamp = typeof time === 'string' ? Date.parse(time) / 1000 : (time as number);
|
||||
const nearestCandle = findNearestCandle(timestamp);
|
||||
|
||||
if (!nearestCandle) return;
|
||||
|
||||
if (interactionState === 'idle') {
|
||||
// First click: set start candle
|
||||
setStartCandle(nearestCandle);
|
||||
setInteractionState('first-click-done');
|
||||
} else if (interactionState === 'first-click-done') {
|
||||
// Second click: set end candle and open popover
|
||||
setEndCandle(nearestCandle);
|
||||
setInteractionState('popover-open');
|
||||
setPopoverOpen(true);
|
||||
|
||||
// Clean up preview primitive
|
||||
if (previewPrimitive) {
|
||||
series.detachPrimitive(previewPrimitive);
|
||||
setPreviewPrimitive(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
chart.subscribeClick(handleClick);
|
||||
|
||||
return () => {
|
||||
chart.unsubscribeClick(handleClick);
|
||||
};
|
||||
}, [chart, series, activeTool, interactionState, candles, previewPrimitive]);
|
||||
|
||||
// Handle mouse move for preview
|
||||
useEffect(() => {
|
||||
if (!chart || !series || activeTool !== 'span' || interactionState !== 'first-click-done' || !startCandle) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleMouseMove = (param: any) => {
|
||||
if (!param.point) return;
|
||||
|
||||
const time = chart.timeScale().coordinateToTime(param.point.x);
|
||||
if (!time) return;
|
||||
|
||||
const timestamp = typeof time === 'string' ? Date.parse(time) / 1000 : (time as number);
|
||||
const cursorCandle = findNearestCandle(timestamp);
|
||||
|
||||
if (!cursorCandle) return;
|
||||
|
||||
// Calculate price range for preview
|
||||
const { max_high, min_low } = calculatePriceRange(startCandle, cursorCandle);
|
||||
|
||||
// Swap if end < start
|
||||
const [start_time, end_time] =
|
||||
startCandle.time <= cursorCandle.time
|
||||
? [startCandle.time, cursorCandle.time]
|
||||
: [cursorCandle.time, startCandle.time];
|
||||
|
||||
const previewData: SpanData = {
|
||||
id: -1, // Preview ID
|
||||
start_time,
|
||||
end_time,
|
||||
label: 'PREVIEW',
|
||||
color: '#888888',
|
||||
max_high,
|
||||
min_low,
|
||||
};
|
||||
|
||||
// Remove old preview primitive
|
||||
if (previewPrimitive) {
|
||||
series.detachPrimitive(previewPrimitive);
|
||||
}
|
||||
|
||||
// Create new preview primitive
|
||||
const newPreview = new SpanRectanglePrimitive({
|
||||
data: previewData,
|
||||
isSelected: false,
|
||||
});
|
||||
|
||||
series.attachPrimitive(newPreview);
|
||||
setPreviewPrimitive(newPreview);
|
||||
};
|
||||
|
||||
chart.subscribeCrosshairMove(handleMouseMove);
|
||||
|
||||
return () => {
|
||||
chart.unsubscribeCrosshairMove(handleMouseMove);
|
||||
};
|
||||
}, [chart, series, activeTool, interactionState, startCandle, candles, previewPrimitive]);
|
||||
|
||||
// Handle Escape key to cancel span selection
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && activeTool === 'span') {
|
||||
if (interactionState === 'first-click-done') {
|
||||
// Cancel span selection
|
||||
setInteractionState('idle');
|
||||
setStartCandle(null);
|
||||
setEndCandle(null);
|
||||
|
||||
// Clean up preview
|
||||
if (previewPrimitive && series) {
|
||||
series.detachPrimitive(previewPrimitive);
|
||||
setPreviewPrimitive(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [activeTool, interactionState, previewPrimitive, series]);
|
||||
|
||||
// Handle popover save
|
||||
const handlePopoverSave = async (data: {
|
||||
label: string;
|
||||
confidence: number | null;
|
||||
outcome: string | null;
|
||||
notes: string | null;
|
||||
}) => {
|
||||
if (!startCandle || !endCandle || !activeChartId) return;
|
||||
|
||||
// Swap if end < start
|
||||
const [start_time, end_time] =
|
||||
startCandle.time <= endCandle.time
|
||||
? [startCandle.time, endCandle.time]
|
||||
: [endCandle.time, startCandle.time];
|
||||
|
||||
// Find label type color
|
||||
const labelType = spanLabelTypes.find((t) => t.name === data.label);
|
||||
const color = labelType?.color || '#2196F3';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/span-annotations', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
chart_id: activeChartId,
|
||||
start_time,
|
||||
end_time,
|
||||
label: data.label,
|
||||
confidence: data.confidence,
|
||||
outcome: data.outcome,
|
||||
notes: data.notes,
|
||||
color,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
onSpanAnnotationsChange();
|
||||
setPopoverOpen(false);
|
||||
setInteractionState('idle');
|
||||
setStartCandle(null);
|
||||
setEndCandle(null);
|
||||
} else {
|
||||
console.error('Failed to create span annotation');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating span annotation:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle popover cancel
|
||||
const handlePopoverCancel = () => {
|
||||
setPopoverOpen(false);
|
||||
setInteractionState('idle');
|
||||
setStartCandle(null);
|
||||
setEndCandle(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<SpanPopover
|
||||
open={popoverOpen}
|
||||
onOpenChange={setPopoverOpen}
|
||||
spanLabelTypes={spanLabelTypes}
|
||||
initialData={
|
||||
startCandle && endCandle
|
||||
? {
|
||||
start_time: Math.min(startCandle.time, endCandle.time),
|
||||
end_time: Math.max(startCandle.time, endCandle.time),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onSave={handlePopoverSave}
|
||||
onCancel={handlePopoverCancel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue