feat: complete candle annotator implementation
- Created CandleChart component with lightweight-charts integration - Implemented SvgOverlay component for line drawing - Integrated all components in main page - Fixed TypeScript and Tailwind CSS compatibility issues - Added comprehensive README.md with project documentation - Created DEPLOYMENT.md with setup and troubleshooting guide - Downgraded to stable versions (Tailwind v3, lightweight-charts v4) - All 59 tasks from OpenSpec completed
This commit is contained in:
parent
8d1e72579e
commit
23f18f405a
11 changed files with 8166 additions and 24 deletions
|
|
@ -5,10 +5,11 @@ import { eq } from 'drizzle-orm';
|
|||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id);
|
||||
const { id: idParam } = await params;
|
||||
const id = parseInt(idParam);
|
||||
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import Papa from 'papaparse';
|
|||
import { db } from '@/lib/db';
|
||||
import { candles } from '@/lib/db/schema';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
export async function POST(request: NextRequest): Promise<NextResponse> {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File;
|
||||
|
|
@ -17,7 +17,7 @@ export async function POST(request: NextRequest) {
|
|||
|
||||
const text = await file.text();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
return new Promise<NextResponse>((resolve) => {
|
||||
Papa.parse(text, {
|
||||
header: true,
|
||||
dynamicTyping: true,
|
||||
|
|
@ -115,7 +115,7 @@ export async function POST(request: NextRequest) {
|
|||
);
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
error: (error: any) => {
|
||||
resolve(
|
||||
NextResponse.json(
|
||||
{ error: `CSV parsing error: ${error.message}` },
|
||||
|
|
|
|||
|
|
@ -1,19 +1,26 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useRef } from 'react';
|
||||
import Toolbox, { Tool } from '@/components/Toolbox';
|
||||
import FileUpload from '@/components/FileUpload';
|
||||
import CandleChart, { CandleChartHandle } from '@/components/CandleChart';
|
||||
|
||||
export default function Home() {
|
||||
const [activeTool, setActiveTool] = useState<Tool>(null);
|
||||
const chartRef = useRef<CandleChartHandle>(null);
|
||||
|
||||
const handleExport = () => {
|
||||
window.location.href = '/api/export';
|
||||
};
|
||||
|
||||
const handleUploadSuccess = () => {
|
||||
// TODO: Trigger chart refresh
|
||||
console.log('Upload successful - refresh chart');
|
||||
// Refresh chart data after successful upload
|
||||
chartRef.current?.refreshData();
|
||||
};
|
||||
|
||||
const handleAnnotationChange = () => {
|
||||
// Refresh chart when annotations change
|
||||
chartRef.current?.refreshData();
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
@ -34,11 +41,12 @@ export default function Home() {
|
|||
</aside>
|
||||
|
||||
{/* Main chart area */}
|
||||
<main className="flex-1 flex items-center justify-center bg-background">
|
||||
<div className="text-muted-foreground text-center">
|
||||
<p className="text-lg">Upload a CSV file to view the candlestick chart</p>
|
||||
<p className="text-sm mt-2">CSV format: time, open, high, low, close</p>
|
||||
</div>
|
||||
<main className="flex-1 relative">
|
||||
<CandleChart
|
||||
ref={chartRef}
|
||||
activeTool={activeTool}
|
||||
onAnnotationChange={handleAnnotationChange}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
284
src/components/CandleChart.tsx
Normal file
284
src/components/CandleChart.tsx
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
|
||||
import { createChart, IChartApi, ISeriesApi, CandlestickData, Time } from 'lightweight-charts';
|
||||
import SvgOverlay from './SvgOverlay';
|
||||
|
||||
interface Candle {
|
||||
time: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
}
|
||||
|
||||
interface Annotation {
|
||||
id: number;
|
||||
timestamp: number;
|
||||
label_type: string;
|
||||
geometry: {
|
||||
startTime?: number;
|
||||
startPrice?: number;
|
||||
endTime?: number;
|
||||
endPrice?: number;
|
||||
} | null;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
interface CandleChartProps {
|
||||
activeTool: string | null;
|
||||
onAnnotationChange?: () => void;
|
||||
}
|
||||
|
||||
export interface CandleChartHandle {
|
||||
refreshData: () => Promise<void>;
|
||||
}
|
||||
|
||||
const CandleChart = forwardRef<CandleChartHandle, CandleChartProps>(
|
||||
({ activeTool, onAnnotationChange }, ref) => {
|
||||
const chartContainerRef = useRef<HTMLDivElement>(null);
|
||||
const chartRef = useRef<IChartApi | null>(null);
|
||||
const seriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
|
||||
const [candles, setCandles] = useState<Candle[]>([]);
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([]);
|
||||
const [isEmpty, setIsEmpty] = useState(true);
|
||||
|
||||
// Fetch candles from API
|
||||
const fetchCandles = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/candles');
|
||||
const data = await response.json();
|
||||
setCandles(data);
|
||||
setIsEmpty(data.length === 0);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch candles:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch annotations from API
|
||||
const fetchAnnotations = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/annotations');
|
||||
const data = await response.json();
|
||||
setAnnotations(data);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch annotations:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// Expose refresh method to parent
|
||||
useImperativeHandle(ref, () => ({
|
||||
refreshData: async () => {
|
||||
await fetchCandles();
|
||||
await fetchAnnotations();
|
||||
},
|
||||
}));
|
||||
|
||||
// Initialize chart
|
||||
useEffect(() => {
|
||||
if (!chartContainerRef.current || isEmpty) return;
|
||||
|
||||
const chart = createChart(chartContainerRef.current, {
|
||||
width: chartContainerRef.current.clientWidth,
|
||||
height: chartContainerRef.current.clientHeight,
|
||||
layout: {
|
||||
background: { color: '#0f172a' }, // Slate-900
|
||||
textColor: '#e2e8f0', // Slate-200
|
||||
},
|
||||
grid: {
|
||||
vertLines: { color: '#1e293b' }, // Subtle grid
|
||||
horzLines: { color: '#1e293b' },
|
||||
},
|
||||
crosshair: {
|
||||
mode: 1,
|
||||
},
|
||||
timeScale: {
|
||||
timeVisible: true,
|
||||
secondsVisible: false,
|
||||
borderColor: '#334155',
|
||||
},
|
||||
rightPriceScale: {
|
||||
borderColor: '#334155',
|
||||
},
|
||||
});
|
||||
|
||||
const candlestickSeries = chart.addCandlestickSeries({
|
||||
upColor: '#22c55e', // Green
|
||||
downColor: '#ef4444', // Red
|
||||
borderVisible: false,
|
||||
wickUpColor: '#22c55e',
|
||||
wickDownColor: '#ef4444',
|
||||
});
|
||||
|
||||
chartRef.current = chart;
|
||||
seriesRef.current = candlestickSeries;
|
||||
|
||||
// Handle resize
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
if (entries.length === 0 || !chartContainerRef.current) return;
|
||||
const { width, height } = entries[0].contentRect;
|
||||
chart.applyOptions({ width, height });
|
||||
});
|
||||
|
||||
resizeObserver.observe(chartContainerRef.current);
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
chart.remove();
|
||||
};
|
||||
}, [isEmpty]);
|
||||
|
||||
// Load candle data into chart
|
||||
useEffect(() => {
|
||||
if (!seriesRef.current || candles.length === 0) return;
|
||||
|
||||
const chartData: CandlestickData[] = candles.map((candle) => ({
|
||||
time: candle.time as Time,
|
||||
open: candle.open,
|
||||
high: candle.high,
|
||||
low: candle.low,
|
||||
close: candle.close,
|
||||
}));
|
||||
|
||||
seriesRef.current.setData(chartData);
|
||||
}, [candles]);
|
||||
|
||||
// Update markers from annotations
|
||||
useEffect(() => {
|
||||
if (!seriesRef.current) return;
|
||||
|
||||
const markerAnnotations = annotations.filter(
|
||||
(a) => a.label_type === 'break_up' || a.label_type === 'break_down'
|
||||
);
|
||||
|
||||
const markers = markerAnnotations.map((annotation) => ({
|
||||
time: annotation.timestamp as Time,
|
||||
position: annotation.label_type === 'break_up' ? ('belowBar' as const) : ('aboveBar' as const),
|
||||
color: annotation.label_type === 'break_up' ? '#22c55e' : '#ef4444',
|
||||
shape: annotation.label_type === 'break_up' ? ('arrowUp' as const) : ('arrowDown' as const),
|
||||
text: annotation.label_type === 'break_up' ? 'Break Up' : 'Break Down',
|
||||
}));
|
||||
|
||||
seriesRef.current.setMarkers(markers);
|
||||
}, [annotations]);
|
||||
|
||||
// Handle chart clicks for annotation
|
||||
useEffect(() => {
|
||||
if (!chartRef.current || !seriesRef.current) return;
|
||||
|
||||
const handleClick = async (param: any) => {
|
||||
if (!param.point || !activeTool) return;
|
||||
|
||||
const timeCoordinate = param.point.x;
|
||||
const priceCoordinate = param.point.y;
|
||||
|
||||
const time = chartRef.current!.timeScale().coordinateToTime(timeCoordinate);
|
||||
const price = seriesRef.current!.coordinateToPrice(priceCoordinate);
|
||||
|
||||
if (time === null || price === null) return;
|
||||
|
||||
// For break_up and break_down, snap to nearest candle
|
||||
if (activeTool === 'break_up' || activeTool === 'break_down') {
|
||||
const timestamp = typeof time === 'string' ? Date.parse(time) / 1000 : (time as number);
|
||||
|
||||
// Find nearest candle
|
||||
const nearestCandle = candles.reduce((prev, curr) => {
|
||||
return Math.abs(curr.time - timestamp) < Math.abs(prev.time - timestamp) ? curr : prev;
|
||||
}, candles[0]);
|
||||
|
||||
if (!nearestCandle) return;
|
||||
|
||||
// Create annotation
|
||||
try {
|
||||
const response = await fetch('/api/annotations', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
timestamp: nearestCandle.time,
|
||||
label_type: activeTool,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
await fetchAnnotations();
|
||||
onAnnotationChange?.();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to create annotation:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
// 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') &&
|
||||
Math.abs(a.timestamp - timestamp) < tolerance
|
||||
);
|
||||
|
||||
if (annotation) {
|
||||
try {
|
||||
const response = await fetch(`/api/annotations/${annotation.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
await fetchAnnotations();
|
||||
onAnnotationChange?.();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to delete annotation:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
chartRef.current.subscribeClick(handleClick);
|
||||
|
||||
return () => {
|
||||
chartRef.current?.unsubscribeClick(handleClick);
|
||||
};
|
||||
}, [activeTool, candles, annotations, onAnnotationChange]);
|
||||
|
||||
// Fetch data on mount
|
||||
useEffect(() => {
|
||||
fetchCandles();
|
||||
fetchAnnotations();
|
||||
}, []);
|
||||
|
||||
if (isEmpty) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center bg-background">
|
||||
<div className="text-muted-foreground text-center">
|
||||
<p className="text-lg">Upload a CSV file to view the candlestick chart</p>
|
||||
<p className="text-sm mt-2">CSV format: time, open, high, low, close</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 relative">
|
||||
<div ref={chartContainerRef} className="absolute inset-0" />
|
||||
<SvgOverlay
|
||||
chart={chartRef.current}
|
||||
series={seriesRef.current}
|
||||
activeTool={activeTool}
|
||||
onAnnotationChange={onAnnotationChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
CandleChart.displayName = 'CandleChart';
|
||||
|
||||
export default CandleChart;
|
||||
357
src/components/SvgOverlay.tsx
Normal file
357
src/components/SvgOverlay.tsx
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { IChartApi, ISeriesApi } from 'lightweight-charts';
|
||||
|
||||
interface Annotation {
|
||||
id: number;
|
||||
timestamp: number;
|
||||
label_type: string;
|
||||
geometry: {
|
||||
startTime?: number;
|
||||
startPrice?: number;
|
||||
endTime?: number;
|
||||
endPrice?: number;
|
||||
} | null;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
interface SvgOverlayProps {
|
||||
chart: IChartApi | null;
|
||||
series: ISeriesApi<'Candlestick'> | null;
|
||||
activeTool: string | null;
|
||||
onAnnotationChange?: () => void;
|
||||
}
|
||||
|
||||
interface Point {
|
||||
time: number;
|
||||
price: number;
|
||||
}
|
||||
|
||||
export default function SvgOverlay({
|
||||
chart,
|
||||
series,
|
||||
activeTool,
|
||||
onAnnotationChange,
|
||||
}: SvgOverlayProps) {
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([]);
|
||||
const [drawingLine, setDrawingLine] = useState<{ start: Point; current: Point } | null>(null);
|
||||
const [mousePosition, setMousePosition] = useState<{ x: number; y: number } | null>(null);
|
||||
|
||||
// Fetch annotations
|
||||
const fetchAnnotations = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/annotations');
|
||||
const data = await response.json();
|
||||
setAnnotations(data);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch annotations:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Update dimensions when chart resizes
|
||||
useEffect(() => {
|
||||
if (!chart) return;
|
||||
|
||||
const updateDimensions = () => {
|
||||
const container = chart.chartElement();
|
||||
if (container) {
|
||||
setDimensions({
|
||||
width: container.clientWidth,
|
||||
height: container.clientHeight,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
updateDimensions();
|
||||
|
||||
const resizeObserver = new ResizeObserver(updateDimensions);
|
||||
const container = chart.chartElement();
|
||||
if (container) {
|
||||
resizeObserver.observe(container);
|
||||
}
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [chart]);
|
||||
|
||||
// Subscribe to visible range changes (zoom/pan)
|
||||
useEffect(() => {
|
||||
if (!chart) return;
|
||||
|
||||
const handleVisibleRangeChange = () => {
|
||||
// Force re-render by updating state
|
||||
setAnnotations((prev) => [...prev]);
|
||||
};
|
||||
|
||||
chart.timeScale().subscribeVisibleTimeRangeChange(handleVisibleRangeChange);
|
||||
|
||||
return () => {
|
||||
chart.timeScale().unsubscribeVisibleTimeRangeChange(handleVisibleRangeChange);
|
||||
};
|
||||
}, [chart]);
|
||||
|
||||
// Fetch annotations on mount and when notified
|
||||
useEffect(() => {
|
||||
fetchAnnotations();
|
||||
}, [onAnnotationChange]);
|
||||
|
||||
// Convert data coordinates to pixel coordinates
|
||||
const dataToPixel = (time: number, price: number): { x: number; y: number } | null => {
|
||||
if (!chart || !series) return null;
|
||||
|
||||
const x = chart.timeScale().timeToCoordinate(time as any);
|
||||
const y = series.priceToCoordinate(price);
|
||||
|
||||
if (x === null || y === null) return null;
|
||||
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
// Convert pixel coordinates to data coordinates
|
||||
const pixelToData = (x: number, y: number): Point | null => {
|
||||
if (!chart || !series) return null;
|
||||
|
||||
const time = chart.timeScale().coordinateToTime(x);
|
||||
const price = series.coordinateToPrice(y);
|
||||
|
||||
if (time === null || price === null) return null;
|
||||
|
||||
return {
|
||||
time: typeof time === 'string' ? Date.parse(time) / 1000 : (time as number),
|
||||
price,
|
||||
};
|
||||
};
|
||||
|
||||
// Handle mouse move
|
||||
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
|
||||
if (!svgRef.current) return;
|
||||
|
||||
const rect = svgRef.current.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const y = e.clientY - rect.top;
|
||||
|
||||
setMousePosition({ x, y });
|
||||
|
||||
if (drawingLine && activeTool === 'line') {
|
||||
const dataPoint = pixelToData(x, y);
|
||||
if (dataPoint) {
|
||||
setDrawingLine((prev) => (prev ? { ...prev, current: dataPoint } : null));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle click
|
||||
const handleClick = async (e: React.MouseEvent<SVGSVGElement>) => {
|
||||
if (!svgRef.current || !chart || !series) return;
|
||||
|
||||
const rect = svgRef.current.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const y = e.clientY - rect.top;
|
||||
|
||||
const dataPoint = pixelToData(x, y);
|
||||
if (!dataPoint) return;
|
||||
|
||||
// Line drawing mode
|
||||
if (activeTool === 'line') {
|
||||
if (!drawingLine) {
|
||||
// First click - start line
|
||||
setDrawingLine({
|
||||
start: dataPoint,
|
||||
current: dataPoint,
|
||||
});
|
||||
} else {
|
||||
// Second click - save line
|
||||
try {
|
||||
const response = await fetch('/api/annotations', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
timestamp: drawingLine.start.time,
|
||||
label_type: 'line',
|
||||
geometry: {
|
||||
startTime: drawingLine.start.time,
|
||||
startPrice: drawingLine.start.price,
|
||||
endTime: dataPoint.time,
|
||||
endPrice: dataPoint.price,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
await fetchAnnotations();
|
||||
onAnnotationChange?.();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to create line annotation:', error);
|
||||
}
|
||||
|
||||
setDrawingLine(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete mode - delete line
|
||||
if (activeTool === 'delete') {
|
||||
// Find line annotation near click point
|
||||
const lineAnnotations = annotations.filter((a) => a.label_type === 'line' && a.geometry);
|
||||
|
||||
for (const annotation of lineAnnotations) {
|
||||
if (!annotation.geometry) continue;
|
||||
|
||||
const start = dataToPixel(
|
||||
annotation.geometry.startTime!,
|
||||
annotation.geometry.startPrice!
|
||||
);
|
||||
const end = dataToPixel(annotation.geometry.endTime!, annotation.geometry.endPrice!);
|
||||
|
||||
if (!start || !end) continue;
|
||||
|
||||
// Calculate distance from point to line segment
|
||||
const distance = distanceToLineSegment({ x, y }, start, end);
|
||||
|
||||
if (distance < 10) {
|
||||
// Within 10 pixels
|
||||
try {
|
||||
const response = await fetch(`/api/annotations/${annotation.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
await fetchAnnotations();
|
||||
onAnnotationChange?.();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to delete annotation:', error);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Calculate distance from point to line segment
|
||||
const distanceToLineSegment = (
|
||||
point: { x: number; y: number },
|
||||
lineStart: { x: number; y: number },
|
||||
lineEnd: { x: number; y: number }
|
||||
): number => {
|
||||
const A = point.x - lineStart.x;
|
||||
const B = point.y - lineStart.y;
|
||||
const C = lineEnd.x - lineStart.x;
|
||||
const D = lineEnd.y - lineStart.y;
|
||||
|
||||
const dot = A * C + B * D;
|
||||
const lenSq = C * C + D * D;
|
||||
let param = -1;
|
||||
|
||||
if (lenSq !== 0) param = dot / lenSq;
|
||||
|
||||
let xx, yy;
|
||||
|
||||
if (param < 0) {
|
||||
xx = lineStart.x;
|
||||
yy = lineStart.y;
|
||||
} else if (param > 1) {
|
||||
xx = lineEnd.x;
|
||||
yy = lineEnd.y;
|
||||
} else {
|
||||
xx = lineStart.x + param * C;
|
||||
yy = lineStart.y + param * D;
|
||||
}
|
||||
|
||||
const dx = point.x - xx;
|
||||
const dy = point.y - yy;
|
||||
|
||||
return Math.sqrt(dx * dx + dy * dy);
|
||||
};
|
||||
|
||||
// Handle Escape key to cancel line drawing
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && drawingLine) {
|
||||
setDrawingLine(null);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [drawingLine]);
|
||||
|
||||
// Render line annotations
|
||||
const renderLines = () => {
|
||||
const lineAnnotations = annotations.filter((a) => a.label_type === 'line' && a.geometry);
|
||||
|
||||
return lineAnnotations.map((annotation) => {
|
||||
if (!annotation.geometry) return null;
|
||||
|
||||
const start = dataToPixel(
|
||||
annotation.geometry.startTime!,
|
||||
annotation.geometry.startPrice!
|
||||
);
|
||||
const end = dataToPixel(annotation.geometry.endTime!, annotation.geometry.endPrice!);
|
||||
|
||||
if (!start || !end) return null;
|
||||
|
||||
return (
|
||||
<line
|
||||
key={annotation.id}
|
||||
x1={start.x}
|
||||
y1={start.y}
|
||||
x2={end.x}
|
||||
y2={end.y}
|
||||
stroke="#3b82f6"
|
||||
strokeWidth="2"
|
||||
style={{ cursor: activeTool === 'delete' ? 'pointer' : 'default' }}
|
||||
/>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
// Render preview line while drawing
|
||||
const renderPreviewLine = () => {
|
||||
if (!drawingLine) return null;
|
||||
|
||||
const start = dataToPixel(drawingLine.start.time, drawingLine.start.price);
|
||||
const end = dataToPixel(drawingLine.current.time, drawingLine.current.price);
|
||||
|
||||
if (!start || !end) return null;
|
||||
|
||||
return (
|
||||
<line
|
||||
x1={start.x}
|
||||
y1={start.y}
|
||||
x2={end.x}
|
||||
y2={end.y}
|
||||
stroke="#3b82f6"
|
||||
strokeWidth="2"
|
||||
strokeDasharray="5,5"
|
||||
opacity="0.6"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
if (!chart || !series) return null;
|
||||
|
||||
return (
|
||||
<svg
|
||||
ref={svgRef}
|
||||
width={dimensions.width}
|
||||
height={dimensions.height}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
pointerEvents: activeTool === 'line' || activeTool === 'delete' ? 'auto' : 'none',
|
||||
cursor: activeTool === 'line' ? 'crosshair' : activeTool === 'delete' ? 'pointer' : 'default',
|
||||
}}
|
||||
onMouseMove={handleMouseMove}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{renderLines()}
|
||||
{renderPreviewLine()}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue