chore: archive line-rectangle-annotations change and sync specs

- Archived change to openspec/changes/archive/2026-02-17-line-rectangle-annotations/
- Updated annotation-tools spec: added rectangle tool mode, TrendLine plugin rendering, line hit testing, line selection handles; updated line drawing and delete requirements; removed SVG overlay rendering
- Created new rectangle-annotation spec with full requirements for rectangle drawing, rendering, hit testing, selection, deletion, and database storage

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Marko Djordjevic 2026-02-17 18:16:49 +01:00
parent d1557a3846
commit 0e8dcc6707
8 changed files with 522 additions and 8 deletions

View file

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-02-15

View file

@ -0,0 +1,92 @@
## Context
The candle annotator uses lightweight-charts for rendering candlestick data and currently has two rendering layers for annotations:
1. **Canvas-based (ISeriesPrimitive)**: Used by `SpanRectanglePrimitive.ts` for span annotations. These are attached to the series via `series.attachPrimitive()` and render natively within the chart canvas. They support `hitTest()`, autoscaling, and z-ordering.
2. **SVG overlay**: Used by `SvgOverlay.tsx` for line annotations. An absolutely-positioned SVG element sits on top of the chart with `zIndex: 1111`, intercepting pointer events when the line or delete tool is active. It duplicates coordinate conversion logic and manages its own interaction state.
The existing `src/plugins/trend-line.ts` already implements a `TrendLine` class using `ISeriesPrimitive<Time>` but is not wired into the interactive drawing flow. The Toolbox component manages tool modes — line drawing is triggered by annotation types with `category: 'line'`.
## Goals / Non-Goals
**Goals:**
- Replace SVG overlay line rendering with the existing `TrendLine` plugin (canvas-based)
- Add interactive drawing for lines using chart's native click/crosshair events instead of SVG pointer events
- Add a rectangle annotation tool using a new `RectangleDrawingPrimitive` plugin
- Maintain all existing line behaviors: two-click drawing, preview, selection, endpoint dragging, deletion
- Use the same database schema and API endpoints — rectangles stored as `label_type: "rectangle"` with geometry JSON
- Keep rendering approach consistent with `SpanRectanglePrimitive` patterns
**Non-Goals:**
- Changing span annotation implementation (already uses ISeriesPrimitive)
- Adding axis labels or price/time markers to lines or rectangles
- Multi-select or group operations on annotations
- Undo/redo functionality
- Toolbar UI for the rectangle drawing tool from the upstream example (we use our own Toolbox)
## Decisions
### 1. Remove SVG overlay entirely
**Decision**: Delete `SvgOverlay.tsx` and move all line rendering to the `TrendLine` plugin.
**Rationale**: The SVG overlay creates a layering problem — it must intercept pointer events by sitting above the chart, which blocks chart interactions (zoom, pan, crosshair) when the line tool is active. The plugin system renders within the chart canvas and can coexist with native chart interactions. `SpanRectanglePrimitive` already demonstrates this approach works well.
**Alternative considered**: Keep SVG for interactive drawing (preview), use plugin only for saved lines. Rejected because it still requires maintaining two rendering systems and the coordinate conversion duplication.
### 2. Manage drawing interaction in CandleChart via chart events
**Decision**: Use `chart.subscribeClick()` and `chart.subscribeCrosshairMove()` in `CandleChart.tsx` to handle the two-click drawing flow for both lines and rectangles.
**Rationale**: The chart API provides native click and crosshair events that include time/price data coordinates directly, eliminating the need for manual pixel-to-data conversion. This matches how the upstream `RectangleDrawingTool` example works. `CandleChart.tsx` already owns the chart and series references.
**Alternative considered**: Create a separate `DrawingManager` component. Rejected for this scope — CandleChart already manages span primitives, so adding line/rectangle primitive management follows the existing pattern. Extraction can happen later if complexity warrants it.
### 3. Enhance TrendLine plugin with hit testing and selection
**Decision**: Add `hitTest()` and `setSelected()` methods to the existing `TrendLine` class, following the `SpanRectanglePrimitive` pattern.
**Rationale**: `hitTest()` enables the chart's built-in click handling to detect which primitive was clicked, eliminating the need for manual distance-to-line-segment calculation in the overlay. Selection state changes line appearance (thicker stroke, handles).
**Implementation**: Hit testing for lines uses perpendicular distance to the line segment (same algorithm currently in `SvgOverlay`, moved into the renderer's coordinate space).
### 4. Create RectangleDrawingPrimitive following SpanRectanglePrimitive patterns
**Decision**: Create a new `src/plugins/rectangle-drawing.ts` that implements `ISeriesPrimitive<Time>` directly (not extending a base class), storing two corner points `{time, price}` and rendering a filled rectangle.
**Rationale**: The upstream `RectangleDrawingTool` example is complex (multiple axis views, toolbar UI, PluginBase class) — most of that complexity is unnecessary since we have our own Toolbox and don't need axis highlighting. Our `SpanRectanglePrimitive` already demonstrates a simpler rectangle rendering approach. The new plugin adapts that pattern but uses two arbitrary corner points instead of candle-range-derived bounds.
**Differences from SpanRectanglePrimitive**: Span rectangles are defined by candle ranges (start_time/end_time → compute min_low/max_high from candle data). Rectangle annotations are freeform — two arbitrary {time, price} corners, no dependency on candle data.
### 5. Preview primitives for drawing feedback
**Decision**: Create temporary "preview" instances of `TrendLine` and `RectangleDrawingPrimitive` during the two-click drawing flow. Update endpoint on crosshair move. Remove and replace with permanent instance on second click.
**Rationale**: This is the same approach used in the upstream `RectangleDrawingTool` example (`PreviewRectangle` class). A preview primitive with dashed/semi-transparent styling gives visual feedback without requiring a separate rendering layer. Attach on first click, update on move, detach and replace on second click.
### 6. Endpoint dragging via primitive update
**Decision**: When a line is selected and the user drags a handle, call `trendLine.updatePoints(p1, p2)` and `requestUpdate()` to re-render at new coordinates. On mouse up, persist via PATCH API.
**Rationale**: The `TrendLine` class already has `updatePoints()`. Drag detection uses crosshair move events. This replaces the SVG-based drag handling that manipulated DOM elements directly.
**Handle rendering**: Draw small circles at endpoints when selected, as part of the `TrendLinePaneRenderer.draw()` method (no separate SVG elements needed).
### 7. Database and API — no changes
**Decision**: Rectangles use the existing `annotations` table with `label_type: "rectangle"` and `geometry: {"startTime", "startPrice", "endTime", "endPrice"}` — identical schema to lines.
**Rationale**: The geometry format is the same (two points). No migration needed. The API endpoints (`POST/PATCH/DELETE /api/annotations`) already handle arbitrary `label_type` and `geometry` values.
## Risks / Trade-offs
**[Risk] Line hit testing accuracy in canvas coordinates** → The distance-to-line-segment algorithm needs to work in bitmap coordinate space. Mitigation: Port the existing algorithm from SvgOverlay, test with various zoom levels. Use a tolerance of ~10 CSS pixels (scaled by pixel ratio).
**[Risk] Breaking existing saved line annotations** → Existing lines in the database use the same geometry format, so they should render identically with the plugin. Mitigation: No data migration needed; verify rendering parity before removing SVG overlay.
**[Risk] Pointer event handling conflicts** → Chart's native click events fire for both annotation tools and regular chart interaction. Mitigation: Only handle annotation clicks when `activeTool` is set to a drawing/delete tool. When no tool is active, clicks pass through to normal chart behavior (zoom, crosshair, etc.).
**[Risk] Performance with many primitives** → Each line/rectangle is a separate `ISeriesPrimitive` instance. Mitigation: This is the same approach used for spans, and the number of annotations per chart is typically small (tens, not thousands).
**[Trade-off] No PluginBase class** → We implement `ISeriesPrimitive` directly rather than using the upstream `PluginBase` abstraction. This means slightly more boilerplate per plugin but avoids adding a dependency/abstraction for just two plugin types.

View file

@ -0,0 +1,29 @@
## Why
The current line drawing implementation uses an SVG overlay (`SvgOverlay.tsx`) positioned on top of the lightweight-charts canvas. This creates a disconnect — lines don't participate in chart autoscaling, coordinate conversion is duplicated outside the chart library, and the rendering layer is split between SVG and canvas. Lightweight-charts natively supports drawing primitives via the `ISeriesPrimitive` API, and the project already has a `TrendLine` plugin in `src/plugins/trend-line.ts` (unused) and uses `SpanRectanglePrimitive` for span annotations. Migrating line drawing to the native plugin system and adding rectangle annotations will unify the rendering approach, improve performance, and enable consistent interaction patterns.
## What Changes
- **BREAKING**: Remove SVG overlay line drawing (`SvgOverlay.tsx`) and replace with lightweight-charts `TrendLine` plugin-based rendering
- Implement interactive two-click line drawing using chart's native `subscribeClick()` and `subscribeCrosshairMove()` events instead of SVG pointer events
- Add a new rectangle annotation tool based on the lightweight-charts `RectangleDrawingTool` plugin pattern (two-click to define opposite corners)
- Add "rectangle" tool mode to the Toolbox alongside existing line/span/label tools
- Store rectangle annotations in the database with `label_type: "rectangle"` and geometry containing `{startTime, startPrice, endTime, endPrice}`
- Update line editing (drag endpoints) and deletion to work through the plugin system instead of SVG hit detection
- Add preview rendering during drawing for both lines and rectangles (using crosshair move events)
## Capabilities
### New Capabilities
- `rectangle-annotation`: Two-click rectangle drawing tool using lightweight-charts ISeriesPrimitive, with preview during drawing, persistence, editing, and deletion
### Modified Capabilities
- `annotation-tools`: Line drawing changes from SVG overlay to lightweight-charts TrendLine plugin; line tool mode interaction moves from SVG events to chart subscribeClick/subscribeCrosshairMove; line editing and deletion use plugin-based hit detection instead of SVG proximity calculation
## Impact
- **Frontend components**: `SvgOverlay.tsx` removed or gutted; `CandleChart.tsx` updated to manage TrendLine primitives; `Toolbox.tsx` gains rectangle tool button
- **Plugins**: `src/plugins/trend-line.ts` enhanced with interactive drawing support (click handlers, preview); new `src/plugins/rectangle-drawing.ts` added
- **API**: Existing annotation endpoints used as-is; rectangle annotations use the same `annotations` table with `label_type: "rectangle"` and `geometry` JSON
- **Database**: No schema changes — rectangles use the existing `geometry` column pattern (same as lines)
- **Dependencies**: No new dependencies — uses lightweight-charts APIs already in use

View file

@ -0,0 +1,83 @@
## ADDED Requirements
### Requirement: Active tool includes rectangle mode
The system SHALL add "rectangle" to the available tool modes alongside "select", "break_up", "break_down", "line", "span", and "delete". Only one tool SHALL be active at a time.
#### Scenario: Rectangle tool in tool list
- **WHEN** the Toolbox renders
- **THEN** a rectangle tool button is available alongside the existing tool buttons
### Requirement: Line rendering via TrendLine plugin
The system SHALL render saved line annotations using the `TrendLine` class (implementing `ISeriesPrimitive<Time>`) instead of SVG `<line>` elements. Each line annotation SHALL have one `TrendLine` primitive instance attached to the candlestick series via `series.attachPrimitive()`. The `SvgOverlay` component SHALL be removed.
#### Scenario: Saved lines render as canvas primitives
- **WHEN** line annotations exist for the active chart
- **THEN** each line renders via a TrendLine primitive on the chart canvas (not SVG overlay)
#### Scenario: Lines participate in autoscaling
- **WHEN** a line annotation's price range extends beyond visible candle data
- **THEN** the chart autoscale includes the line's price range via `autoscaleInfo()`
#### Scenario: Lines update on zoom/pan
- **WHEN** user zooms or pans the chart
- **THEN** line primitives automatically reposition via the ISeriesPrimitive lifecycle
### Requirement: Line hit testing
The `TrendLine` class SHALL implement `hitTest(x, y)` to detect clicks near the line. Hit testing SHALL calculate the perpendicular distance from the click point to the line segment and return a hit if within 10 CSS pixels (scaled by device pixel ratio).
#### Scenario: Click near line detected
- **WHEN** user clicks within 10 CSS pixels of a line segment
- **THEN** `hitTest()` returns a `PrimitiveHoveredItem` with the annotation ID as `externalId`
#### Scenario: Click far from line not detected
- **WHEN** user clicks more than 10 CSS pixels from any line segment
- **THEN** `hitTest()` returns null
### Requirement: Line selection handles via plugin
When a line is selected, the `TrendLine` renderer SHALL draw circular endpoint handles (radius 6px) at both endpoints of the line. The handles SHALL be rendered as part of the canvas draw call, not as separate SVG elements.
#### Scenario: Handles appear on selection
- **WHEN** a line is selected (via click with line tool active)
- **THEN** circular handles render at both endpoints of the line on the canvas
#### Scenario: Handles disappear on deselection
- **WHEN** the selected line is deselected (Escape key or clicking elsewhere)
- **THEN** the endpoint handles no longer render
## MODIFIED Requirements
### Requirement: Two-click line drawing
When the "line" tool is active, the system SHALL implement a two-click drawing interaction using `chart.subscribeClick()` for click detection and `chart.subscribeCrosshairMove()` for preview updates. The first click sets the start point (time, price). The second click sets the end point (time, price). After the second click, the system SHALL save an annotation with `label_type: "line"` and `geometry` containing JSON: `{"startTime": <unix>, "startPrice": <float>, "endTime": <unix>, "endPrice": <float>}`. The line SHALL render immediately as a TrendLine primitive attached to the candlestick series.
#### Scenario: Draw a trend line
- **WHEN** "line" tool is active and user clicks two points on the chart
- **THEN** system saves a line annotation with start/end coordinates and renders the line as a TrendLine primitive
#### Scenario: Visual feedback during line drawing
- **WHEN** "line" tool is active and user has clicked the first point but not the second
- **THEN** system displays a preview TrendLine primitive (dashed or semi-transparent) from the first point to the current crosshair position, updating via `subscribeCrosshairMove()`
#### Scenario: Cancel line drawing
- **WHEN** user presses Escape during a two-click line drawing (after first click)
- **THEN** system cancels the line drawing, detaches the preview primitive, and clears the drawing state without saving
### Requirement: Delete annotation
When the "delete" tool is active and the user clicks on or near an existing annotation (marker, line, or rectangle), the system SHALL remove that annotation from the database and update the chart display immediately. Line and rectangle hit detection SHALL use the primitive's `hitTest()` method instead of SVG proximity calculation.
#### Scenario: Delete a marker annotation
- **WHEN** "delete" tool is active and user clicks on a candle that has a marker annotation
- **THEN** system removes the annotation from the database and the marker disappears from the chart
#### Scenario: Delete a line annotation
- **WHEN** "delete" tool is active and user clicks near an existing line
- **THEN** system detects the hit via `TrendLine.hitTest()`, sends DELETE /api/annotations/{id}, detaches the primitive from the series, and updates the annotation list
#### Scenario: Delete a rectangle annotation
- **WHEN** "delete" tool is active and user clicks within a rectangle
- **THEN** system detects the hit via `RectangleDrawingPrimitive.hitTest()`, sends DELETE /api/annotations/{id}, detaches the primitive, and updates the annotation list
## REMOVED Requirements
### Requirement: SVG overlay rendering
**Reason**: Replaced by TrendLine plugin rendering. Line annotations now render via `ISeriesPrimitive` on the chart canvas instead of SVG `<line>` elements in an overlay. All coordinate conversion, hit detection, and interaction handling moves to the plugin system and chart native events.
**Migration**: Remove `SvgOverlay.tsx` component. Remove its usage from `CandleChart.tsx`. Line annotation data in the database is unchanged — the same geometry format is used by the TrendLine plugin.

View file

@ -0,0 +1,105 @@
## ADDED Requirements
### Requirement: Rectangle tool mode
The Toolbox SHALL include a "rectangle" tool button. When activated, the chart enters rectangle drawing mode. Only one tool SHALL be active at a time — activating the rectangle tool deactivates any other active tool.
#### Scenario: Activate rectangle tool
- **WHEN** user clicks the rectangle tool button in the Toolbox
- **THEN** the rectangle tool becomes active, the button appears visually selected, and the chart cursor changes to crosshair
#### Scenario: Deactivate rectangle tool
- **WHEN** user clicks the already-active rectangle tool button
- **THEN** the tool deactivates, the mode returns to "select", and the cursor returns to default
#### Scenario: Rectangle tool deactivates other tools
- **WHEN** the "line" tool is active and user clicks the rectangle tool button
- **THEN** the line tool deactivates and the rectangle tool becomes active
### Requirement: Two-click rectangle drawing
When the "rectangle" tool is active, the system SHALL implement a two-click interaction to define a rectangle. The first click sets one corner point (time, price). The second click sets the opposite corner point (time, price). The rectangle is defined by these two arbitrary data-coordinate corners — it is NOT constrained to candle boundaries.
#### Scenario: Draw a rectangle
- **WHEN** "rectangle" tool is active and user clicks two points on the chart
- **THEN** the system saves a rectangle annotation with the two corner coordinates and renders a filled semi-transparent rectangle on the chart
#### Scenario: First click registers corner
- **WHEN** "rectangle" tool is active and user clicks on the chart
- **THEN** the system records the click position as {time, price} for the first corner
#### Scenario: Second click completes rectangle
- **WHEN** user has set the first corner and clicks a second position
- **THEN** the system saves a rectangle annotation via POST /api/annotations with `label_type: "rectangle"` and `geometry: {"startTime", "startPrice", "endTime", "endPrice"}`
### Requirement: Rectangle preview during drawing
After the first click, the system SHALL display a preview rectangle that stretches from the first corner to the current cursor position. The preview SHALL have a dashed border and reduced opacity to distinguish it from saved rectangles.
#### Scenario: Preview follows cursor
- **WHEN** user has clicked the first corner and moves the mouse
- **THEN** a semi-transparent preview rectangle renders from the first corner to the cursor position, updating in real-time via crosshair move events
#### Scenario: Preview disappears on cancel
- **WHEN** user presses Escape during rectangle drawing (after first click)
- **THEN** the preview rectangle disappears and the drawing is cancelled without saving
### Requirement: Rectangle rendering via ISeriesPrimitive
The system SHALL render saved rectangle annotations using a `RectangleDrawingPrimitive` class that implements `ISeriesPrimitive<Time>`. Each rectangle annotation SHALL have one primitive instance attached to the candlestick series via `series.attachPrimitive()`.
#### Scenario: Rectangle renders for saved annotation
- **WHEN** a rectangle annotation exists for the active chart
- **THEN** a semi-transparent filled rectangle renders on the chart canvas at the stored corner coordinates
#### Scenario: Rectangle uses annotation color
- **WHEN** a rectangle annotation has a color value
- **THEN** the rectangle renders with that color as fill (at reduced opacity) and border
#### Scenario: Rectangle updates on zoom/pan
- **WHEN** user zooms or pans the chart
- **THEN** rectangle primitives automatically reposition via the ISeriesPrimitive lifecycle (coordinate conversion in paneView.update())
#### Scenario: Rectangle z-order
- **WHEN** rectangle annotations render on the chart
- **THEN** they SHALL render at "bottom" z-order (behind candlesticks), consistent with span rectangles
### Requirement: Rectangle hit testing
The `RectangleDrawingPrimitive` SHALL implement `hitTest(x, y)` to detect clicks within the rectangle bounds. Hit testing SHALL convert pixel coordinates to data coordinates and check if the point falls within the rectangle's time/price range.
#### Scenario: Click inside rectangle detected
- **WHEN** user clicks at a position inside a rectangle's bounds
- **THEN** `hitTest()` returns a `PrimitiveHoveredItem` with the annotation ID as `externalId`
#### Scenario: Click outside rectangle not detected
- **WHEN** user clicks at a position outside all rectangle bounds
- **THEN** `hitTest()` returns null
### Requirement: Rectangle selection
The system SHALL allow users to select a rectangle annotation by clicking within its bounds when the "rectangle" or "select" tool is active.
#### Scenario: Click to select rectangle
- **WHEN** user clicks within a rectangle annotation
- **THEN** the rectangle appears selected (thicker border or increased opacity)
#### Scenario: Click to deselect rectangle
- **WHEN** user clicks outside all rectangle annotations while one is selected
- **THEN** the selection is cleared
### Requirement: Rectangle deletion
The system SHALL allow users to delete rectangle annotations via the delete tool.
#### Scenario: Delete rectangle with delete tool
- **WHEN** the "delete" tool is active and user clicks within a rectangle
- **THEN** the system sends DELETE /api/annotations/{id}, removes the primitive from the chart, and updates the annotation list
#### Scenario: Delete selected rectangle with keyboard
- **WHEN** a rectangle is selected and user presses Delete or Backspace
- **THEN** the system deletes the rectangle annotation and removes it from the chart
### Requirement: Rectangle database storage
Rectangle annotations SHALL be stored in the existing `annotations` table with `label_type: "rectangle"` and `geometry` containing JSON: `{"startTime": <unix>, "startPrice": <float>, "endTime": <float>, "endPrice": <float>}`. The `startTime/startPrice` represents one corner, `endTime/endPrice` the opposite corner.
#### Scenario: Rectangle annotation persisted
- **WHEN** user completes a two-click rectangle drawing
- **THEN** the system sends POST /api/annotations with label_type "rectangle", the active chart_id, selected color, and geometry JSON with the two corner coordinates
#### Scenario: Rectangle annotation loaded on chart switch
- **WHEN** user switches to a chart that has rectangle annotations
- **THEN** the system fetches annotations, creates RectangleDrawingPrimitive instances for each rectangle annotation, and attaches them to the series

View file

@ -0,0 +1,57 @@
## 1. Enhance TrendLine Plugin
- [x] 1.1 Add `hitTest(x, y)` method to `TrendLine` class — calculate perpendicular distance from click point to line segment in pixel coordinates, return `PrimitiveHoveredItem` with annotation ID if within 10px tolerance
- [x] 1.2 Add `setSelected(isSelected)` method and selection state to `TrendLine` — when selected, renderer draws thicker line and circular endpoint handles (radius 6px, white fill, colored stroke)
- [x] 1.3 Add `attached()/detached()` lifecycle methods to `TrendLine` to store `SeriesAttachedParameter` reference (needed for hitTest coordinate conversion)
- [x] 1.4 Add preview line support — dashed stroke style and reduced opacity when an `isPreview` option is set
## 2. Create RectangleDrawingPrimitive Plugin
- [x] 2.1 Create `src/plugins/rectangle-drawing.ts` implementing `ISeriesPrimitive<Time>` with renderer, pane view, and data model for two corner points `{time, price}`
- [x] 2.2 Implement `RectangleDrawingPaneRenderer.draw()` — filled semi-transparent rectangle with border, using `useBitmapCoordinateSpace` for HiDPI scaling
- [x] 2.3 Implement `hitTest(x, y)` — convert pixel to data coordinates, check if within rectangle time/price bounds
- [x] 2.4 Add `setSelected(isSelected)` and selection visual feedback (thicker border, increased opacity)
- [x] 2.5 Add preview mode support — dashed border and reduced opacity for preview rectangles during drawing
- [x] 2.6 Add `autoscaleInfo()` to include rectangle price range in chart scaling
- [x] 2.7 Set z-order to "bottom" so rectangles render behind candlesticks
## 3. Wire Up Drawing Interaction in CandleChart
- [x] 3.1 Add state for drawing mode: `drawingState: {tool: 'line'|'rectangle', firstPoint: {time, price}} | null` and `previewPrimitive: TrendLine | RectangleDrawingPrimitive | null`
- [x] 3.2 Subscribe to `chart.subscribeClick()` — on first click when line/rectangle tool active, record first point and attach preview primitive; on second click, save annotation via API, detach preview, attach permanent primitive
- [x] 3.3 Subscribe to `chart.subscribeCrosshairMove()` — when drawing in progress, update preview primitive's endpoint via `updatePoints()` or equivalent
- [x] 3.4 Handle Escape key — detach preview primitive and clear drawing state
- [x] 3.5 Manage TrendLine primitives for saved line annotations — create/attach on load, detach on delete, update on edit
## 4. Wire Up Rectangle Primitives in CandleChart
- [x] 4.1 On annotation fetch, create `RectangleDrawingPrimitive` instances for `label_type: "rectangle"` annotations and attach to series
- [x] 4.2 On chart switch, detach old rectangle primitives and create new ones for the new chart's annotations
- [x] 4.3 Handle rectangle selection — on click hit detected via primitive `hitTest()`, call `setSelected()` and track selected annotation ID
- [x] 4.4 Handle rectangle deletion — when delete tool active and hit detected, send DELETE API call, detach primitive, refresh annotations
## 5. Update Toolbox
- [x] 5.1 Add "rectangle" tool button to Toolbox (using existing `RectangleHorizontal` lucide icon import, which is already present)
- [x] 5.2 Wire rectangle button to `onToolChange('rectangle')` with same toggle behavior as other tools
## 6. Remove SVG Overlay
- [x] 6.1 Remove `SvgOverlay` import and JSX from `CandleChart.tsx`
- [x] 6.2 Delete `src/components/SvgOverlay.tsx`
- [x] 6.3 Move line annotation primitive management into CandleChart (replace what SvgOverlay was doing — loading saved lines, managing line primitives on annotation fetch/delete)
## 7. Line Endpoint Dragging
- [x] 7.1 Implement drag detection — when a selected line's endpoint handle is clicked (via hitTest near endpoint), enter drag mode
- [x] 7.2 On crosshair move during drag, call `trendLine.updatePoints()` to reposition the dragged endpoint in real-time
- [x] 7.3 On click to release drag, persist updated geometry via PATCH /api/annotations/{id}
## 8. Verification
- [x] 8.1 Verify existing saved line annotations render correctly with TrendLine plugin (visual parity with old SVG rendering)
- [x] 8.2 Verify line drawing, preview, selection, dragging, and deletion all work end-to-end
- [x] 8.3 Verify rectangle drawing, preview, selection, and deletion work end-to-end
- [x] 8.4 Verify chart zoom/pan correctly repositions both line and rectangle primitives
- [x] 8.5 Verify tool switching between line, rectangle, span, label, and delete modes works correctly
- [x] 8.6 Verify annotations persist and reload correctly on chart switch

View file

@ -1,7 +1,7 @@
## ADDED Requirements
### Requirement: Active tool mode
The system SHALL maintain an "active tool" state that determines what happens when the user clicks on the chart. Available tool modes are: "select" (default, no action on click), "break_up" (label Break Up), "break_down" (label Break Down), "line" (draw trend line), and "delete" (remove annotation). Only one tool SHALL be active at a time.
The system SHALL maintain an "active tool" state that determines what happens when the user clicks on the chart. Available tool modes are: "select" (default, no action on click), "break_up" (label Break Up), "break_down" (label Break Down), "line" (draw trend line), "rectangle" (draw rectangle annotation), and "delete" (remove annotation). Only one tool SHALL be active at a time.
#### Scenario: Tool activation
- **WHEN** user clicks a tool button in the sidebar
@ -30,30 +30,71 @@ When the "break_down" tool is active and the user clicks on the chart, the syste
- **THEN** system saves a "break_down" annotation for that candle's timestamp and displays a red arrow marker below the bar
### Requirement: Two-click line drawing
When the "line" tool is active, the system SHALL implement a two-click drawing interaction. The first click sets the start point (time, price). The second click sets the end point (time, price). After the second click, the system SHALL save an annotation with `label_type: "line"` and `geometry` containing JSON: `{"startTime": <unix>, "startPrice": <float>, "endTime": <unix>, "endPrice": <float>}`. The line SHALL render immediately on the SVG overlay.
When the "line" tool is active, the system SHALL implement a two-click drawing interaction using `chart.subscribeClick()` for click detection and `chart.subscribeCrosshairMove()` for preview updates. The first click sets the start point (time, price). The second click sets the end point (time, price). After the second click, the system SHALL save an annotation with `label_type: "line"` and `geometry` containing JSON: `{"startTime": <unix>, "startPrice": <float>, "endTime": <unix>, "endPrice": <float>}`. The line SHALL render immediately as a TrendLine primitive attached to the candlestick series.
#### Scenario: Draw a trend line
- **WHEN** "line" tool is active and user clicks two points on the chart
- **THEN** system saves a line annotation with start/end coordinates and renders the line on the overlay
- **THEN** system saves a line annotation with start/end coordinates and renders the line as a TrendLine primitive
#### Scenario: Visual feedback during line drawing
- **WHEN** "line" tool is active and user has clicked the first point but not the second
- **THEN** system displays a preview line from the first point to the current cursor position
- **THEN** system displays a preview TrendLine primitive (dashed or semi-transparent) from the first point to the current crosshair position, updating via `subscribeCrosshairMove()`
#### Scenario: Cancel line drawing
- **WHEN** user presses Escape during a two-click line drawing (after first click)
- **THEN** system cancels the line drawing and clears the preview without saving
- **THEN** system cancels the line drawing, detaches the preview primitive, and clears the drawing state without saving
### Requirement: Line rendering via TrendLine plugin
The system SHALL render saved line annotations using the `TrendLine` class (implementing `ISeriesPrimitive<Time>`) instead of SVG `<line>` elements. Each line annotation SHALL have one `TrendLine` primitive instance attached to the candlestick series via `series.attachPrimitive()`. The `SvgOverlay` component SHALL be removed.
#### Scenario: Saved lines render as canvas primitives
- **WHEN** line annotations exist for the active chart
- **THEN** each line renders via a TrendLine primitive on the chart canvas (not SVG overlay)
#### Scenario: Lines participate in autoscaling
- **WHEN** a line annotation's price range extends beyond visible candle data
- **THEN** the chart autoscale includes the line's price range via `autoscaleInfo()`
#### Scenario: Lines update on zoom/pan
- **WHEN** user zooms or pans the chart
- **THEN** line primitives automatically reposition via the ISeriesPrimitive lifecycle
### Requirement: Line hit testing
The `TrendLine` class SHALL implement `hitTest(x, y)` to detect clicks near the line. Hit testing SHALL calculate the perpendicular distance from the click point to the line segment and return a hit if within 10 CSS pixels (scaled by device pixel ratio).
#### Scenario: Click near line detected
- **WHEN** user clicks within 10 CSS pixels of a line segment
- **THEN** `hitTest()` returns a `PrimitiveHoveredItem` with the annotation ID as `externalId`
#### Scenario: Click far from line not detected
- **WHEN** user clicks more than 10 CSS pixels from any line segment
- **THEN** `hitTest()` returns null
### Requirement: Line selection handles via plugin
When a line is selected, the `TrendLine` renderer SHALL draw circular endpoint handles (radius 6px) at both endpoints of the line. The handles SHALL be rendered as part of the canvas draw call, not as separate SVG elements.
#### Scenario: Handles appear on selection
- **WHEN** a line is selected (via click with line tool active)
- **THEN** circular handles render at both endpoints of the line on the canvas
#### Scenario: Handles disappear on deselection
- **WHEN** the selected line is deselected (Escape key or clicking elsewhere)
- **THEN** the endpoint handles no longer render
### Requirement: Delete annotation
When the "delete" tool is active and the user clicks on or near an existing annotation (marker or line), the system SHALL remove that annotation from the database and update the chart display immediately.
When the "delete" tool is active and the user clicks on or near an existing annotation (marker, line, or rectangle), the system SHALL remove that annotation from the database and update the chart display immediately. Line and rectangle hit detection SHALL use the primitive's `hitTest()` method instead of SVG proximity calculation.
#### Scenario: Delete a marker annotation
- **WHEN** "delete" tool is active and user clicks on a candle that has a marker annotation
- **THEN** system removes the annotation from the database and the marker disappears from the chart
#### Scenario: Delete a line annotation
- **WHEN** "delete" tool is active and user clicks near an existing line on the overlay
- **THEN** system removes the line annotation from the database and the line disappears from the overlay
- **WHEN** "delete" tool is active and user clicks near an existing line
- **THEN** system detects the hit via `TrendLine.hitTest()`, sends DELETE /api/annotations/{id}, detaches the primitive from the series, and updates the annotation list
#### Scenario: Delete a rectangle annotation
- **WHEN** "delete" tool is active and user clicks within a rectangle
- **THEN** system detects the hit via `RectangleDrawingPrimitive.hitTest()`, sends DELETE /api/annotations/{id}, detaches the primitive, and updates the annotation list
### Requirement: Coordinate mapping
The system SHALL convert mouse click pixel coordinates to chart data coordinates (time and price) using the lightweight-charts API: `chart.timeScale().coordinateToTime(x)` for time and `series.coordinateToPrice(y)` for price. For point annotations, the time SHALL be snapped to the nearest candle timestamp.

View file

@ -0,0 +1,105 @@
## ADDED Requirements
### Requirement: Rectangle tool mode
The Toolbox SHALL include a "rectangle" tool button. When activated, the chart enters rectangle drawing mode. Only one tool SHALL be active at a time — activating the rectangle tool deactivates any other active tool.
#### Scenario: Activate rectangle tool
- **WHEN** user clicks the rectangle tool button in the Toolbox
- **THEN** the rectangle tool becomes active, the button appears visually selected, and the chart cursor changes to crosshair
#### Scenario: Deactivate rectangle tool
- **WHEN** user clicks the already-active rectangle tool button
- **THEN** the tool deactivates, the mode returns to "select", and the cursor returns to default
#### Scenario: Rectangle tool deactivates other tools
- **WHEN** the "line" tool is active and user clicks the rectangle tool button
- **THEN** the line tool deactivates and the rectangle tool becomes active
### Requirement: Two-click rectangle drawing
When the "rectangle" tool is active, the system SHALL implement a two-click interaction to define a rectangle. The first click sets one corner point (time, price). The second click sets the opposite corner point (time, price). The rectangle is defined by these two arbitrary data-coordinate corners — it is NOT constrained to candle boundaries.
#### Scenario: Draw a rectangle
- **WHEN** "rectangle" tool is active and user clicks two points on the chart
- **THEN** the system saves a rectangle annotation with the two corner coordinates and renders a filled semi-transparent rectangle on the chart
#### Scenario: First click registers corner
- **WHEN** "rectangle" tool is active and user clicks on the chart
- **THEN** the system records the click position as {time, price} for the first corner
#### Scenario: Second click completes rectangle
- **WHEN** user has set the first corner and clicks a second position
- **THEN** the system saves a rectangle annotation via POST /api/annotations with `label_type: "rectangle"` and `geometry: {"startTime", "startPrice", "endTime", "endPrice"}`
### Requirement: Rectangle preview during drawing
After the first click, the system SHALL display a preview rectangle that stretches from the first corner to the current cursor position. The preview SHALL have a dashed border and reduced opacity to distinguish it from saved rectangles.
#### Scenario: Preview follows cursor
- **WHEN** user has clicked the first corner and moves the mouse
- **THEN** a semi-transparent preview rectangle renders from the first corner to the cursor position, updating in real-time via crosshair move events
#### Scenario: Preview disappears on cancel
- **WHEN** user presses Escape during rectangle drawing (after first click)
- **THEN** the preview rectangle disappears and the drawing is cancelled without saving
### Requirement: Rectangle rendering via ISeriesPrimitive
The system SHALL render saved rectangle annotations using a `RectangleDrawingPrimitive` class that implements `ISeriesPrimitive<Time>`. Each rectangle annotation SHALL have one primitive instance attached to the candlestick series via `series.attachPrimitive()`.
#### Scenario: Rectangle renders for saved annotation
- **WHEN** a rectangle annotation exists for the active chart
- **THEN** a semi-transparent filled rectangle renders on the chart canvas at the stored corner coordinates
#### Scenario: Rectangle uses annotation color
- **WHEN** a rectangle annotation has a color value
- **THEN** the rectangle renders with that color as fill (at reduced opacity) and border
#### Scenario: Rectangle updates on zoom/pan
- **WHEN** user zooms or pans the chart
- **THEN** rectangle primitives automatically reposition via the ISeriesPrimitive lifecycle (coordinate conversion in paneView.update())
#### Scenario: Rectangle z-order
- **WHEN** rectangle annotations render on the chart
- **THEN** they SHALL render at "bottom" z-order (behind candlesticks), consistent with span rectangles
### Requirement: Rectangle hit testing
The `RectangleDrawingPrimitive` SHALL implement `hitTest(x, y)` to detect clicks within the rectangle bounds. Hit testing SHALL convert pixel coordinates to data coordinates and check if the point falls within the rectangle's time/price range.
#### Scenario: Click inside rectangle detected
- **WHEN** user clicks at a position inside a rectangle's bounds
- **THEN** `hitTest()` returns a `PrimitiveHoveredItem` with the annotation ID as `externalId`
#### Scenario: Click outside rectangle not detected
- **WHEN** user clicks at a position outside all rectangle bounds
- **THEN** `hitTest()` returns null
### Requirement: Rectangle selection
The system SHALL allow users to select a rectangle annotation by clicking within its bounds when the "rectangle" or "select" tool is active.
#### Scenario: Click to select rectangle
- **WHEN** user clicks within a rectangle annotation
- **THEN** the rectangle appears selected (thicker border or increased opacity)
#### Scenario: Click to deselect rectangle
- **WHEN** user clicks outside all rectangle annotations while one is selected
- **THEN** the selection is cleared
### Requirement: Rectangle deletion
The system SHALL allow users to delete rectangle annotations via the delete tool.
#### Scenario: Delete rectangle with delete tool
- **WHEN** the "delete" tool is active and user clicks within a rectangle
- **THEN** the system sends DELETE /api/annotations/{id}, removes the primitive from the chart, and updates the annotation list
#### Scenario: Delete selected rectangle with keyboard
- **WHEN** a rectangle is selected and user presses Delete or Backspace
- **THEN** the system deletes the rectangle annotation and removes it from the chart
### Requirement: Rectangle database storage
Rectangle annotations SHALL be stored in the existing `annotations` table with `label_type: "rectangle"` and `geometry` containing JSON: `{"startTime": <unix>, "startPrice": <float>, "endTime": <float>, "endPrice": <float>}`. The `startTime/startPrice` represents one corner, `endTime/endPrice` the opposite corner.
#### Scenario: Rectangle annotation persisted
- **WHEN** user completes a two-click rectangle drawing
- **THEN** the system sends POST /api/annotations with label_type "rectangle", the active chart_id, selected color, and geometry JSON with the two corner coordinates
#### Scenario: Rectangle annotation loaded on chart switch
- **WHEN** user switches to a chart that has rectangle annotations
- **THEN** the system fetches annotations, creates RectangleDrawingPrimitive instances for each rectangle annotation, and attaches them to the series