Загрузка данных


import {
  CustomPriceAxisPaneView,
  CustomPriceAxisView,
  CustomTimeAxisPaneView,
  CustomTimeAxisView,
} from '@core/Drawings/axis';
import { DrawingBase } from '@core/Drawings/DrawingBase';
import {
  getTimeFromXCoordinate,
  getXCoordinateFromTime,
  getYCoordinateFromPrice,
} from '@core/Drawings/helpers';
import { getDistanceToSegment, updateViews } from '@core/Drawings/utils';

import { Defaults } from '@src/types/defaults';
import { formatPrice } from '@src/utils';
import { formatDate } from '@src/utils/formatter';

import { RegressionTrendPaneView } from './paneView';
import {
  createDefaultSettings,
  getRegressionTrendSettingsTabs,
  RegressionTrendSettings,
  RegressionTrendStyle,
} from './settings';

import type { DrawingHandle } from '@core/Drawings/handles';
import type { AxisLabel, AxisSegment, Point } from '@core/Drawings/types';
import type { BaseDrawingParams, ISeriesDrawing } from '@core/Drawings/DrawingBase';
import type { ChartOptionsModel, SettingsTab } from '@src/types';
import type { IPrimitivePaneView, PrimitiveHoveredItem, Time, UTCTimestamp } from 'lightweight-charts';

type RegressionTrendMode = 'idle' | 'drawing' | 'ready' | 'dragging';
type DragTarget = 'start' | 'end' | 'body' | null;
type RegressionTrendHandleKey = Exclude<DragTarget, 'body' | null>;
type TimeLabelKind = 'start' | 'end';
type PriceLabelKind = 'start' | 'end';

type RegressionTrendParams = BaseDrawingParams;

interface RegressionTrendState {
  hidden: boolean;
  mode: RegressionTrendMode;
  startTime: Time | null;
  endTime: Time | null;
  settings: RegressionTrendSettings;
}

interface RegressionSeriesData {
  time: Time;
  close?: number;
  value?: number;
}

interface RegressionResult {
  baseStartPrice: number;
  baseEndPrice: number;
  upperStartPrice: number;
  upperEndPrice: number;
  lowerStartPrice: number;
  lowerEndPrice: number;
  correlation: number;
}

interface RegressionTrendGeometry {
  baseStartPoint: Point;
  baseEndPoint: Point;
  upperStartPoint: Point;
  upperEndPoint: Point;
  lowerStartPoint: Point;
  lowerEndPoint: Point;
  baseStartPrice: number;
  baseEndPrice: number;
  correlation: number;
  left: number;
  right: number;
  top: number;
  bottom: number;
}

export interface RegressionTrendRenderData
  extends RegressionTrendGeometry,
    RegressionTrendStyle {
  showChannel: boolean;
}

const LINE_HIT_TOLERANCE = 8;
const MIN_BAR_DISTANCE = 1;
const REGRESSION_DEVIATION = 2;

export class RegressionTrend
  extends DrawingBase<RegressionTrendSettings, RegressionTrendHandleKey>
  implements ISeriesDrawing
{
  private openSettings?: () => void;

  protected settings: RegressionTrendSettings = createDefaultSettings();
  protected mode: RegressionTrendMode = 'idle';

  private startTime: Time | null = null;
  private endTime: Time | null = null;

  private activeDragTarget: DragTarget = null;
  private dragPointerId: number | null = null;
  private dragStartPoint: Point | null = null;
  private dragStateSnapshot: RegressionTrendState | null = null;

  private displayFormat: ChartOptionsModel = {
    dateFormat: Defaults.dateFormat,
    timeFormat: Defaults.timeFormat,
    showTime: Defaults.showTime,
  };

  private readonly paneView: RegressionTrendPaneView;
  private readonly timeAxisPaneView: CustomTimeAxisPaneView;
  private readonly priceAxisPaneView: CustomPriceAxisPaneView;
  private readonly startTimeAxisView: CustomTimeAxisView;
  private readonly endTimeAxisView: CustomTimeAxisView;
  private readonly startPriceAxisView: CustomPriceAxisView;
  private readonly endPriceAxisView: CustomPriceAxisView;

  constructor({
    chart,
    series,
    container,
    interaction,
    formatObservable,
    openSettings,
    initialEvent,
  }: RegressionTrendParams) {
    super({ chart, series, container, interaction });

    this.openSettings = openSettings;

    this.paneView = new RegressionTrendPaneView(this);
    this.timeAxisPaneView = this.createTimeAxisPaneView();
    this.priceAxisPaneView = this.createPriceAxisPaneView();
    this.startTimeAxisView = this.createTimeAxisView('start');
    this.endTimeAxisView = this.createTimeAxisView('end');
    this.startPriceAxisView = this.createPriceAxisView('start');
    this.endPriceAxisView = this.createPriceAxisView('end');

    this.subscribeFormat(formatObservable, (format) => {
      this.displayFormat = format;
    });

    this.series.attachPrimitive(this);

    if (initialEvent?.sourceEvent) {
      this.startDrawing(this.getEventPoint(initialEvent.sourceEvent));
    }
  }

  public isCreationPending(): boolean {
    return this.mode === 'idle' || this.mode === 'drawing';
  }

  public getState(): RegressionTrendState {
    return {
      hidden: this.hidden,
      mode: this.mode,
      startTime: this.startTime,
      endTime: this.endTime,
      settings: { ...this.settings },
    };
  }

  public setState(state: unknown): void {
    if (!state || typeof state !== 'object') {
      return;
    }

    const nextState = state as Partial<RegressionTrendState>;

    this.hidden = nextState.hidden ?? this.hidden;

    if (nextState.mode) {
      this.mode = nextState.mode === 'dragging' ? 'ready' : nextState.mode;
    }

    if ('startTime' in nextState) {
      this.startTime = nextState.startTime ?? null;
    }

    if ('endTime' in nextState) {
      this.endTime = nextState.endTime ?? null;
    }

    if (nextState.settings) {
      this.settings = {
        ...createDefaultSettings(),
        ...nextState.settings,
      };
    }

    this.render();
  }

  public getSettingsTabs(): SettingsTab[] {
    return getRegressionTrendSettingsTabs(this.settings);
  }

  public updateAllViews(): void {
    updateViews([
      this.paneView,
      this.timeAxisPaneView,
      this.priceAxisPaneView,
      this.startTimeAxisView,
      this.endTimeAxisView,
      this.startPriceAxisView,
      this.endPriceAxisView,
    ]);
  }

  public paneViews(): readonly IPrimitivePaneView[] {
    return [this.paneView];
  }

  public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
    return [this.timeAxisPaneView];
  }

  public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
    return [this.priceAxisPaneView];
  }

  public timeAxisViews() {
    return [this.startTimeAxisView, this.endTimeAxisView];
  }

  public priceAxisViews() {
    return [this.startPriceAxisView, this.endPriceAxisView];
  }

  public getRenderData(): RegressionTrendRenderData | null {
    if (this.hidden) {
      return null;
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return null;
    }

    return {
      ...geometry,
      ...this.settings,
      showChannel: this.mode === 'ready' || this.mode === 'dragging',
    };
  }

  protected getDrawingHandles(): readonly DrawingHandle<RegressionTrendHandleKey>[] {
    const geometry = this.getGeometry();

    if (!geometry) {
      return [];
    }

    return [
      {
        id: 'start',
        ...geometry.baseStartPoint,
        shape: 'circle',
      },
      {
        id: 'end',
        ...geometry.baseEndPoint,
        shape: 'circle',
      },
    ];
  }

  protected getHoveredItem(x: number, y: number): PrimitiveHoveredItem | null {
    if (this.hidden || this.mode !== 'ready') {
      return null;
    }

    const point = { x, y };

    if (!this.isSelected()) {
      if (!this.containsPoint(point)) {
        return null;
      }

      return {
        cursorStyle: 'pointer',
        externalId: 'regression-trend',
        zOrder: 'top',
      };
    }

    const dragTarget = this.getDragTarget(point);

    if (!dragTarget) {
      return null;
    }

    return {
      cursorStyle: dragTarget === 'body' ? 'grab' : 'ew-resize',
      externalId: 'regression-trend',
      zOrder: 'top',
    };
  }

  protected getTimeAxisSegments(): AxisSegment[] {
    if (!this.shouldShowInteractiveAxis()) {
      return [];
    }

    const geometry = this.getGeometry();

    return geometry ? [this.createAxisSegment(geometry.left, geometry.right)] : [];
  }

  protected getPriceAxisSegments(): AxisSegment[] {
    if (!this.shouldShowInteractiveAxis()) {
      return [];
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return [];
    }

    return [
      this.createAxisSegment(
        Math.min(geometry.baseStartPoint.y, geometry.baseEndPoint.y),
        Math.max(geometry.baseStartPoint.y, geometry.baseEndPoint.y),
      ),
    ];
  }

  protected getTimeAxisLabel(kind: string): AxisLabel | null {
    if (!this.shouldShowInteractiveAxis() || (kind !== 'start' && kind !== 'end')) {
      return null;
    }

    const labelKind = kind as TimeLabelKind;
    const time = labelKind === 'start' ? this.startTime : this.endTime;

    if (typeof time !== 'number') {
      return null;
    }

    const coordinate = getXCoordinateFromTime(this.chart, time, this.series);

    return this.createAxisLabel(
      coordinate === null ? null : Number(coordinate),
      this.formatTime(time),
    );
  }

  protected getPriceAxisLabel(kind: string): AxisLabel | null {
    if (!this.shouldShowInteractiveAxis() || (kind !== 'start' && kind !== 'end')) {
      return null;
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return null;
    }

    const price =
      kind === 'start'
        ? geometry.baseStartPrice
        : geometry.baseEndPrice;

    const coordinate = getYCoordinateFromPrice(this.series, price);

    return this.createAxisLabel(
      coordinate === null ? null : Number(coordinate),
      formatPrice(price) ?? '',
    );
  }

  protected handleDoubleClick = (event: MouseEvent): void => {
    if (this.hidden || this.mode !== 'ready' || !this.isSelected()) {
      return;
    }

    const point = this.getEventPoint(event as PointerEvent);

    if (!this.containsPoint(point) && !this.getDrawingHandleAtPoint(point)) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();
    this.openSettings?.();
  };

  protected handlePointerDown = (event: PointerEvent): void => {
    if (this.hidden || event.button !== 0) {
      return;
    }

    const point = this.getEventPoint(event);

    if (this.mode === 'idle') {
      event.preventDefault();
      event.stopPropagation();
      this.startDrawing(point);
      return;
    }

    if (this.mode === 'drawing') {
      const time = this.getBarTime(point.x);

      if (time === null) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();

      this.endTime = time;

      if (!this.hasValidRange()) {
        this.render();
        return;
      }

      this.mode = 'ready';
      this.resolveReady?.();
      this.render();
      return;
    }

    if (this.mode !== 'ready') {
      return;
    }

    if (!this.isSelected()) {
      if (!this.containsPoint(point)) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();
      this.select();
      return;
    }

    const dragTarget = this.getDragTarget(point);

    if (!dragTarget) {
      this.deselect();
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.activeDragTarget = dragTarget;
    this.dragPointerId = event.pointerId;
    this.dragStartPoint = point;
    this.dragStateSnapshot = this.getState();
    this.mode = 'dragging';

    this.hideCrosshair();
    this.render();
  };

  protected handlePointerMove = (event: PointerEvent): void => {
    const point = this.getEventPoint(event);

    if (this.mode === 'drawing') {
      const time = this.getBarTime(point.x);

      if (time !== null) {
        this.endTime = time;
        this.render();
      }

      return;
    }

    if (
      this.mode !== 'dragging' ||
      this.dragPointerId !== event.pointerId ||
      !this.dragStateSnapshot
    ) {
      return;
    }

    event.preventDefault();

    this.applyDrag(point);
    this.render();
  };

  protected handlePointerUp = (event: PointerEvent): void => {
    if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
      return;
    }

    this.activeDragTarget = null;
    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragStateSnapshot = null;
    this.mode = 'ready';

    this.showCrosshair();
    this.render();
  };

  protected getGeometry(): RegressionTrendGeometry | null {
    if (this.startTime === null || this.endTime === null) {
      return null;
    }

    const regression = this.getRegression();

    if (!regression) {
      return null;
    }

    const baseStartPoint = this.getPoint(this.startTime, regression.baseStartPrice);
    const baseEndPoint = this.getPoint(this.endTime, regression.baseEndPrice);
    const upperStartPoint = this.getPoint(this.startTime, regression.upperStartPrice);
    const upperEndPoint = this.getPoint(this.endTime, regression.upperEndPrice);
    const lowerStartPoint = this.getPoint(this.startTime, regression.lowerStartPrice);
    const lowerEndPoint = this.getPoint(this.endTime, regression.lowerEndPrice);

    if (
      !baseStartPoint ||
      !baseEndPoint ||
      !upperStartPoint ||
      !upperEndPoint ||
      !lowerStartPoint ||
      !lowerEndPoint
    ) {
      return null;
    }

    const points = [
      upperStartPoint,
      upperEndPoint,
      lowerStartPoint,
      lowerEndPoint,
    ];

    return {
      baseStartPoint,
      baseEndPoint,
      upperStartPoint,
      upperEndPoint,
      lowerStartPoint,
      lowerEndPoint,
      baseStartPrice: regression.baseStartPrice,
      baseEndPrice: regression.baseEndPrice,
      correlation: regression.correlation,
      left: Math.min(...points.map((point) => point.x)),
      right: Math.max(...points.map((point) => point.x)),
      top: Math.min(...points.map((point) => point.y)),
      bottom: Math.max(...points.map((point) => point.y)),
    };
  }

  private startDrawing(point: Point): void {
    const time = this.getBarTime(point.x);

    if (time === null) {
      return;
    }

    this.startTime = time;
    this.endTime = time;
    this.mode = 'drawing';
    this.render();
  }

  private applyDrag(point: Point): void {
    const snapshot = this.dragStateSnapshot;

    if (!snapshot || snapshot.startTime === null || snapshot.endTime === null) {
      return;
    }

    switch (this.activeDragTarget) {
      case 'start':
        this.moveEdge('start', point);
        break;
      case 'end':
        this.moveEdge('end', point);
        break;
      case 'body':
        this.moveWhole(snapshot, point);
        break;
      default:
        break;
    }
  }

  private moveEdge(kind: TimeLabelKind, point: Point): void {
    const time = this.getBarTime(point.x);

    if (time === null) {
      return;
    }

    const previousTime = kind === 'start' ? this.startTime : this.endTime;

    if (kind === 'start') {
      this.startTime = time;
    } else {
      this.endTime = time;
    }

    if (this.hasValidRange()) {
      return;
    }

    if (kind === 'start') {
      this.startTime = previousTime;
    } else {
      this.endTime = previousTime;
    }
  }

  private moveWhole(snapshot: RegressionTrendState, point: Point): void {
    if (!this.dragStartPoint || snapshot.startTime === null || snapshot.endTime === null) {
      return;
    }

    const data = this.getSeriesData();

    const dragStartIndex = this.getBarIndexByX(this.dragStartPoint.x, data);
    const currentIndex = this.getBarIndexByX(point.x, data);
    const startIndex = this.getBarIndex(snapshot.startTime, data);
    const endIndex = this.getBarIndex(snapshot.endTime, data);

    if (
      dragStartIndex === null ||
      currentIndex === null ||
      startIndex === null ||
      endIndex === null
    ) {
      return;
    }

    const rawOffset = currentIndex - dragStartIndex;
    const minIndex = Math.min(startIndex, endIndex);
    const maxIndex = Math.max(startIndex, endIndex);
    const minOffset = -minIndex;
    const maxOffset = data.length - 1 - maxIndex;
    const offset = Math.max(minOffset, Math.min(rawOffset, maxOffset));

    this.startTime = data[startIndex + offset].time;
    this.endTime = data[endIndex + offset].time;
  }

  private getRegression(): RegressionResult | null {
    const data = this.getSeriesData();
    const range = this.getBarRange(data);

    if (!range) {
      return null;
    }

    const values: number[] = [];

    for (let index = range.left; index <= range.right; index += 1) {
      const value = getSeriesValue(data[index]);

      if (value !== null) {
        values.push(value);
      }
    }

    if (values.length < 2) {
      return null;
    }

    const regression = calculateRegression(values);
    const offset = regression.deviation * REGRESSION_DEVIATION;

    const baseStartPrice = range.reversed
      ? regression.endValue
      : regression.startValue;

    const baseEndPrice = range.reversed
      ? regression.startValue
      : regression.endValue;

    return {
      baseStartPrice,
      baseEndPrice,
      upperStartPrice: baseStartPrice + offset,
      upperEndPrice: baseEndPrice + offset,
      lowerStartPrice: baseStartPrice - offset,
      lowerEndPrice: baseEndPrice - offset,
      correlation: regression.correlation,
    };
  }

  private getBarRange(
    data = this.getSeriesData(),
  ): {
    left: number;
    right: number;
    reversed: boolean;
  } | null {
    if (this.startTime === null || this.endTime === null) {
      return null;
    }

    const startIndex = this.getBarIndex(this.startTime, data);
    const endIndex = this.getBarIndex(this.endTime, data);

    if (startIndex === null || endIndex === null) {
      return null;
    }

    return {
      left: Math.min(startIndex, endIndex),
      right: Math.max(startIndex, endIndex),
      reversed: startIndex > endIndex,
    };
  }

  private hasValidRange(): boolean {
    const range = this.getBarRange();

    return range !== null && range.right - range.left >= MIN_BAR_DISTANCE;
  }

  private getBarTime(x: number): Time | null {
    const time = getTimeFromXCoordinate(this.chart, x);

    if (typeof time !== 'number') {
      return null;
    }

    const data = this.getSeriesData();
    const index = findNearestBarIndex(data, time);

    return index === null ? null : data[index].time;
  }

  private getBarIndexByX(
    x: number,
    data: readonly RegressionSeriesData[],
  ): number | null {
    const time = getTimeFromXCoordinate(this.chart, x);

    return typeof time === 'number'
      ? findNearestBarIndex(data, time)
      : null;
  }

  private getBarIndex(
    time: Time,
    data: readonly RegressionSeriesData[],
  ): number | null {
    return typeof time === 'number'
      ? findNearestBarIndex(data, time)
      : null;
  }

  private getSeriesData(): readonly RegressionSeriesData[] {
    return this.series.data() as readonly RegressionSeriesData[];
  }

  private getPoint(time: Time, price: number): Point | null {
    const x = getXCoordinateFromTime(this.chart, time, this.series);
    const y = getYCoordinateFromPrice(this.series, price);

    if (x === null || y === null) {
      return null;
    }

    return {
      x: Number(x),
      y: Number(y),
    };
  }

  private getDragTarget(point: Point): DragTarget {
    const handle = this.getDrawingHandleAtPoint(point);

    if (handle) {
      return handle.id;
    }

    return this.containsPoint(point) ? 'body' : null;
  }

  private containsPoint(point: Point): boolean {
    const geometry = this.getGeometry();

    if (!geometry) {
      return false;
    }

    if (
      getDistanceToSegment(
        point,
        geometry.upperStartPoint,
        geometry.upperEndPoint,
      ) <= LINE_HIT_TOLERANCE
    ) {
      return true;
    }

    if (
      getDistanceToSegment(
        point,
        geometry.lowerStartPoint,
        geometry.lowerEndPoint,
      ) <= LINE_HIT_TOLERANCE
    ) {
      return true;
    }

    if (
      getDistanceToSegment(
        point,
        geometry.baseStartPoint,
        geometry.baseEndPoint,
      ) <= LINE_HIT_TOLERANCE
    ) {
      return true;
    }

    return isPointInPolygon(point, [
      geometry.upperStartPoint,
      geometry.upperEndPoint,
      geometry.lowerEndPoint,
      geometry.lowerStartPoint,
    ]);
  }

  private formatTime(time: number): string {
    return formatDate(
      time as UTCTimestamp,
      this.displayFormat.dateFormat,
      this.displayFormat.timeFormat,
      this.displayFormat.showTime,
    );
  }
}

function calculateRegression(values: readonly number[]): {
  startValue: number;
  endValue: number;
  deviation: number;
  correlation: number;
} {
  const count = values.length;
  const meanX = (count - 1) / 2;
  const meanY = values.reduce((sum, value) => sum + value, 0) / count;

  let sumXX = 0;
  let sumXY = 0;
  let sumYY = 0;

  for (let index = 0; index < count; index += 1) {
    const x = index - meanX;
    const y = values[index] - meanY;

    sumXX += x * x;
    sumXY += x * y;
    sumYY += y * y;
  }

  const slope = sumXX === 0 ? 0 : sumXY / sumXX;
  const intercept = meanY - slope * meanX;

  let residualSum = 0;

  for (let index = 0; index < count; index += 1) {
    const expected = intercept + slope * index;
    const residual = values[index] - expected;

    residualSum += residual * residual;
  }

  const denominator = Math.sqrt(sumXX * sumYY);

  return {
    startValue: intercept,
    endValue: intercept + slope * (count - 1),
    deviation: Math.sqrt(residualSum / count),
    correlation: denominator === 0 ? 0 : sumXY / denominator,
  };
}

function getSeriesValue(data: RegressionSeriesData): number | null {
  if (typeof data.close === 'number' && Number.isFinite(data.close)) {
    return data.close;
  }

  if (typeof data.value === 'number' && Number.isFinite(data.value)) {
    return data.value;
  }

  return null;
}

function findNearestBarIndex(
  data: readonly RegressionSeriesData[],
  targetTime: number,
): number | null {
  if (!data.length) {
    return null;
  }

  let left = 0;
  let right = data.length - 1;

  while (left <= right) {
    const middle = Math.floor((left + right) / 2);
    const { time } = data[middle];

    if (typeof time !== 'number') {
      return findNearestBarIndexLinear(data, targetTime);
    }

    if (time === targetTime) {
      return middle;
    }

    if (time < targetTime) {
      left = middle + 1;
    } else {
      right = middle - 1;
    }
  }

  const nextIndex = Math.min(left, data.length - 1);
  const previousIndex = Math.max(0, nextIndex - 1);
  const nextTime = data[nextIndex].time;
  const previousTime = data[previousIndex].time;

  if (typeof nextTime !== 'number' || typeof previousTime !== 'number') {
    return findNearestBarIndexLinear(data, targetTime);
  }

  return Math.abs(previousTime - targetTime) <= Math.abs(nextTime - targetTime)
    ? previousIndex
    : nextIndex;
}

function findNearestBarIndexLinear(
  data: readonly RegressionSeriesData[],
  targetTime: number,
): number | null {
  let result: number | null = null;
  let minDistance = Number.POSITIVE_INFINITY;

  data.forEach((item, index) => {
    if (typeof item.time !== 'number') {
      return;
    }

    const distance = Math.abs(item.time - targetTime);

    if (distance >= minDistance) {
      return;
    }

    minDistance = distance;
    result = index;
  });

  return result;
}

function isPointInPolygon(point: Point, polygon: Point[]): boolean {
  let inside = false;

  for (
    let index = 0, previousIndex = polygon.length - 1;
    index < polygon.length;
    previousIndex = index, index += 1
  ) {
    const current = polygon[index];
    const previous = polygon[previousIndex];

    const intersects =
      current.y > point.y !== previous.y > point.y &&
      point.x <
        ((previous.x - current.x) * (point.y - current.y)) /
          (previous.y - current.y) +
          current.x;

    if (intersects) {
      inside = !inside;
    }
  }

  return inside;
}

















import { clamp } from 'lodash-es';

import { DrawingBase } from '@core/Drawings/DrawingBase';
import {
  clampPointToContainer as clampPointToContainerInElement,
  getContainerSize as getElementContainerSize,
  getPriceDelta,
  shiftTimeByPixels,
} from '@core/Drawings/helpers';

import type {
  Anchor,
  Bounds,
  ContainerSize,
  Point,
} from '@core/Drawings/types';
import type { SettingsValues } from '@src/types';

export type TwoPointAnchorKind = 'start' | 'end';

export interface TwoPointGeometry extends Bounds {
  startPoint: Point;
  endPoint: Point;
}

export abstract class TwoPointDrawingBase<
  TSettings extends SettingsValues = SettingsValues,
  THandleId extends string = string,
> extends DrawingBase<TSettings, THandleId> {
  protected startAnchor: Anchor | null = null;
  protected endAnchor: Anchor | null = null;

  protected getAnchor(kind: TwoPointAnchorKind): Anchor | null {
    return kind === 'start' ? this.startAnchor : this.endAnchor;
  }

  protected setAnchor(kind: TwoPointAnchorKind, anchor: Anchor | null): void {
    if (kind === 'start') {
      this.startAnchor = anchor;
      return;
    }

    this.endAnchor = anchor;
  }

  protected setAnchors(
    startAnchor: Anchor | null,
    endAnchor: Anchor | null,
  ): void {
    this.startAnchor = startAnchor;
    this.endAnchor = endAnchor;
  }

  protected createAnchor(point: Point): Anchor | null {
    return this.createAnchorFromPoint(point);
  }

  protected setAnchorFromPoint(
    kind: TwoPointAnchorKind,
    point: Point,
  ): boolean {
    const anchor = this.createAnchor(point);

    if (!anchor) {
      return false;
    }

    this.setAnchor(kind, anchor);

    return true;
  }

  protected setAnchorsFromPoints(
    startPoint: Point,
    endPoint: Point,
  ): boolean {
    const startAnchor = this.createAnchor(startPoint);
    const endAnchor = this.createAnchor(endPoint);

    if (!startAnchor || !endAnchor) {
      return false;
    }

    this.setAnchors(startAnchor, endAnchor);

    return true;
  }

  protected getAnchorTimeCoordinate(kind: TwoPointAnchorKind): number | null {
    const point = this.getPointFromAnchor(this.getAnchor(kind));

    return point?.x ?? null;
  }

  protected getAnchorPriceCoordinate(kind: TwoPointAnchorKind): number | null {
    const point = this.getPointFromAnchor(this.getAnchor(kind));

    return point?.y ?? null;
  }

  protected moveAnchorsByPixels(
    startAnchor: Anchor | null,
    endAnchor: Anchor | null,
    dragStartPoint: Point | null,
    point: Point,
  ): boolean {
    if (!dragStartPoint) {
      return false;
    }

    const offsetX = point.x - dragStartPoint.x;
    const priceOffset = getPriceDelta(
      this.series,
      dragStartPoint.y,
      point.y,
    );

    return this.moveAnchors(
      startAnchor,
      endAnchor,
      offsetX,
      priceOffset,
    );
  }

  protected moveAnchorsWithinContainer(
    startAnchor: Anchor | null,
    endAnchor: Anchor | null,
    dragStartPoint: Point | null,
    point: Point,
    bounds: Bounds,
  ): boolean {
    if (!dragStartPoint) {
      return false;
    }

    const { width, height } = this.getContainerSize();
    const rawOffsetX = point.x - dragStartPoint.x;
    const rawOffsetY = point.y - dragStartPoint.y;
    const offsetX = clamp(rawOffsetX, -bounds.left, width - bounds.right);
    const offsetY = clamp(rawOffsetY, -bounds.top, height - bounds.bottom);
    const priceOffset = getPriceDelta(
      this.series,
      dragStartPoint.y,
      dragStartPoint.y + offsetY,
    );

    return this.moveAnchors(
      startAnchor,
      endAnchor,
      offsetX,
      priceOffset,
    );
  }

  protected getContainerSize(): ContainerSize {
    return getElementContainerSize(this.container);
  }

  protected clampPointToContainer(point: Point): Point {
    return clampPointToContainerInElement(point, this.container);
  }

  protected getTwoPointGeometry(): TwoPointGeometry | null {
    const startPoint = this.getPointFromAnchor(this.startAnchor);
    const endPoint = this.getPointFromAnchor(this.endAnchor);

    if (!startPoint || !endPoint) {
      return null;
    }

    return {
      startPoint,
      endPoint,
      left: Math.min(startPoint.x, endPoint.x),
      right: Math.max(startPoint.x, endPoint.x),
      top: Math.min(startPoint.y, endPoint.y),
      bottom: Math.max(startPoint.y, endPoint.y),
    };
  }

  private moveAnchors(
    startAnchor: Anchor | null,
    endAnchor: Anchor | null,
    offsetX: number,
    priceOffset: number,
  ): boolean {
    if (!startAnchor || !endAnchor) {
      return false;
    }

    const nextStartTime = shiftTimeByPixels(
      this.chart,
      startAnchor.time,
      offsetX,
      this.series,
    );

    const nextEndTime = shiftTimeByPixels(
      this.chart,
      endAnchor.time,
      offsetX,
      this.series,
    );

    if (nextStartTime === null || nextEndTime === null) {
      return false;
    }

    this.startAnchor = {
      time: nextStartTime,
      price: startAnchor.price + priceOffset,
    };

    this.endAnchor = {
      time: nextEndTime,
      price: endAnchor.price + priceOffset,
    };

    return true;
  }
}

















import { clamp } from 'lodash-es';
import {
  IPrimitivePaneView,
  PrimitiveHoveredItem,
  UTCTimestamp,
} from 'lightweight-charts';

import {
  CustomPriceAxisView,
  CustomTimeAxisView,
} from '@core/Drawings/axis';
import { DrawingBase } from '@core/Drawings/DrawingBase';
import {
  clampPointToContainer,
  getContainerSize,
  getXCoordinateFromTime,
  getYCoordinateFromPrice,
  isPointInBounds,
} from '@core/Drawings/helpers';
import { updateViews } from '@core/Drawings/utils';

import { SettingsTab } from '@src/types';
import { Defaults } from '@src/types/defaults';
import { formatDate, formatPrice } from '@src/utils';

import { TextPaneView } from './paneView';
import {
  createDefaultSettings,
  getTextSettingsTabs,
  TextContentStyle,
  TextSettings,
  TextStyle,
} from './settings';

import type {
  Anchor,
  AxisLabel,
  AxisSegment,
  Point,
} from '@core/Drawings/types';
import type {
  BaseDrawingParams,
  ISeriesDrawing,
} from '@core/Drawings/DrawingBase';
import type { ChartOptionsModel } from '@src/types';

type TextMode = 'idle' | 'dragging' | 'ready';

export interface TextState {
  hidden: boolean;
  mode: TextMode;
  point: Anchor | null;
  settings: TextSettings;
}

interface TextGeometry {
  point: Point;
  left: number;
  right: number;
  top: number;
  bottom: number;
  width: number;
  height: number;
  lines: string[];
  font: string;
  lineHeight: number;
}

export interface TextRenderData
  extends TextGeometry,
    TextStyle,
    TextContentStyle {
  showSelectionBorder: boolean;
}

type TextParams = BaseDrawingParams;

const UI = {
  padding: 6,
};

let measureCanvas: HTMLCanvasElement | null = null;

export class Text extends DrawingBase<TextSettings> implements ISeriesDrawing {
  private readonly openSettings?: () => void;

  protected mode: TextMode = 'idle';
  protected settings: TextSettings = createDefaultSettings();

  private point: Anchor | null = null;
  private dragPointerId: number | null = null;
  private dragStartPoint: Point | null = null;
  private dragGeometrySnapshot: TextGeometry | null = null;

  private displayFormat: ChartOptionsModel = {
    dateFormat: Defaults.dateFormat,
    timeFormat: Defaults.timeFormat,
    showTime: Defaults.showTime,
  };

  private readonly paneView: TextPaneView;
  private readonly timeAxisView: CustomTimeAxisView;
  private readonly priceAxisView: CustomPriceAxisView;

  constructor({
    chart,
    series,
    formatObservable,
    openSettings,
    container,
    interaction,
    initialEvent,
  }: TextParams) {
    super({
      chart,
      series,
      container,
      interaction,
    });

    this.openSettings = openSettings;

    this.paneView = new TextPaneView(this);
    this.timeAxisView = this.createTimeAxisView('main');
    this.priceAxisView = this.createPriceAxisView('main');

    this.subscribeFormat(formatObservable, (format) => {
      this.displayFormat = format;
    });

    this.series.attachPrimitive(this);

    if (initialEvent?.sourceEvent) {
      this.startDrawing(
        this.getEventPoint(initialEvent.sourceEvent),
      );
    }
  }

  public isCreationPending(): boolean {
    return this.mode === 'idle';
  }

  public getSettingsTabs(): SettingsTab[] {
    return getTextSettingsTabs(this.settings);
  }

  public getState(): TextState {
    return {
      hidden: this.hidden,
      mode: this.mode,
      point: this.point,
      settings: { ...this.settings },
    };
  }

  public setState(state: unknown): void {
    if (!state || typeof state !== 'object') {
      return;
    }

    const nextState = state as Partial<TextState>;

    this.hidden =
      typeof nextState.hidden === 'boolean'
        ? nextState.hidden
        : this.hidden;

    this.mode = nextState.mode ?? this.mode;

    if ('point' in nextState) {
      this.point = nextState.point ?? null;
    }

    if (nextState.settings) {
      this.settings = {
        ...createDefaultSettings(),
        ...nextState.settings,
      };
    }

    this.render();
  }

  public updateAllViews(): void {
    updateViews([
      this.paneView,
      this.timeAxisView,
      this.priceAxisView,
    ]);
  }

  public paneViews(): readonly IPrimitivePaneView[] {
    return [this.paneView];
  }

  public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
    return [];
  }

  public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
    return [];
  }

  public timeAxisViews() {
    return [this.timeAxisView];
  }

  public priceAxisViews() {
    return [this.priceAxisView];
  }

  public getRenderData(): TextRenderData | null {
    if (this.hidden) {
      return null;
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return null;
    }

    return {
      ...geometry,
      ...this.settings,
      showSelectionBorder: this.isSelected(),
    };
  }

  protected getHoveredItem(
    x: number,
    y: number,
  ): PrimitiveHoveredItem | null {
    if (
      this.hidden ||
      this.mode === 'idle' ||
      !this.containsPoint({ x, y })
    ) {
      return null;
    }

    return {
      cursorStyle: 'move',
      externalId: 'text',
      zOrder: 'top',
    };
  }

  protected getTimeAxisLabel(kind: string): AxisLabel | null {
    if (
      !this.isAxisLabelAvailable() ||
      kind !== 'main' ||
      !this.isSelected() ||
      !this.point ||
      typeof this.point.time !== 'number'
    ) {
      return null;
    }

    const coordinate = getXCoordinateFromTime(
      this.chart,
      this.point.time,
      this.series,
    );

    return this.createAxisLabel(
      coordinate === null
        ? null
        : Number(coordinate),
      formatDate(
        this.point.time as UTCTimestamp,
        this.displayFormat.dateFormat,
        this.displayFormat.timeFormat,
        this.displayFormat.showTime,
      ),
    );
  }

  protected getPriceAxisLabel(kind: string): AxisLabel | null {
    if (
      !this.isAxisLabelAvailable() ||
      kind !== 'main' ||
      !this.isSelected() ||
      !this.point
    ) {
      return null;
    }

    const coordinate = getYCoordinateFromPrice(
      this.series,
      this.point.price,
    );

    return this.createAxisLabel(
      coordinate === null
        ? null
        : Number(coordinate),
      formatPrice(this.point.price) ?? '',
    );
  }

  protected getPriceAxisSegments(): AxisSegment[] {
    return [];
  }

  protected getTimeAxisSegments(): AxisSegment[] {
    return [];
  }

  protected handlePointerDown = (event: PointerEvent): void => {
    if (this.hidden || event.button !== 0) {
      return;
    }

    const point = this.getEventPoint(event);

    if (this.mode === 'idle') {
      event.preventDefault();
      event.stopPropagation();

      this.startDrawing(point);
      return;
    }

    if (this.mode !== 'ready') {
      return;
    }

    const containsPoint = this.containsPoint(point);

    if (!this.isSelected()) {
      if (!containsPoint) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();

      this.select();
      return;
    }

    if (containsPoint) {
      event.preventDefault();
      event.stopPropagation();

      this.startDragging(
        point,
        event.pointerId,
      );
      return;
    }

    this.deselect();
  };

  protected handleDoubleClick = (event: MouseEvent): void => {
    if (
      this.hidden ||
      this.mode !== 'ready' ||
      !this.isSelected()
    ) {
      return;
    }

    const point = this.getEventPoint(
      event as PointerEvent,
    );

    if (!this.containsPoint(point)) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.openSettings?.();
  };

  protected handlePointerMove = (event: PointerEvent): void => {
    if (
      this.dragPointerId !== event.pointerId ||
      this.mode !== 'dragging'
    ) {
      return;
    }

    event.preventDefault();

    this.movePoint(
      this.getEventPoint(event),
    );
    this.render();
  };

  protected handlePointerUp = (event: PointerEvent): void => {
    if (
      this.dragPointerId !== event.pointerId ||
      this.mode !== 'dragging'
    ) {
      return;
    }

    this.finishDragging();
  };

  private startDrawing(point: Point): void {
    // todo: вынести в абстрактный класс абстрактным методом (и в соседних классах)
    const anchor = this.createAnchorFromPoint(
      clampPointToContainer(
        point,
        this.container,
      ),
    );

    if (!anchor) {
      return;
    }

    this.point = anchor;
    this.mode = 'ready';
    this.resolveReady?.();

    this.render();
  }

  private startDragging(
    point: Point,
    pointerId: number,
  ): void {
    this.mode = 'dragging';
    this.dragPointerId = pointerId;
    this.dragStartPoint = point;
    this.dragGeometrySnapshot = this.getGeometry();

    this.hideCrosshair();
    this.render();
  }

  private finishDragging(): void {
    this.mode = 'ready';
    this.resolveReady?.();

    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragGeometrySnapshot = null;

    this.showCrosshair();
    this.render();
  }

  private movePoint(eventPoint: Point): void {
    const geometry = this.dragGeometrySnapshot;
    const dragStartPoint = this.dragStartPoint;

    if (!geometry || !dragStartPoint) {
      return;
    }

    const { width, height } =
      getContainerSize(this.container);

    const offsetX =
      eventPoint.x - dragStartPoint.x;

    const offsetY =
      eventPoint.y - dragStartPoint.y;

    const nextLeft = clamp(
      geometry.left + offsetX,
      0,
      Math.max(
        0,
        width - geometry.width,
      ),
    );

    const nextTop = clamp(
      geometry.top + offsetY,
      0,
      Math.max(
        0,
        height - geometry.height,
      ),
    );

    const anchor = this.createAnchorFromPoint({
      x: nextLeft,
      y: nextTop,
    });

    if (!anchor) {
      return;
    }

    this.point = anchor;
  }

  protected getGeometry(): TextGeometry | null {
    const projectedPoint =
      this.getPointFromAnchor(this.point);

    if (!projectedPoint) {
      return null;
    }

    const {
      width: containerWidth,
      height: containerHeight,
    } = getContainerSize(this.container);

    const anchorPoint: Point = {
      x: clamp(
        Math.round(projectedPoint.x),
        0,
        containerWidth,
      ),
      y: clamp(
        Math.round(projectedPoint.y),
        0,
        containerHeight,
      ),
    };

    const lines =
      getTextLines(this.settings.text);

    const font =
      getFont(this.settings);

    const lineHeight =
      this.settings.fontSize;

    const measured =
      measureTextBlock(
        lines,
        font,
        lineHeight,
      );

    const width = Math.min(
      containerWidth,
      measured.width + UI.padding * 2,
    );

    const height = Math.min(
      containerHeight,
      measured.height + UI.padding * 2,
    );

    const left = clamp(
      anchorPoint.x,
      0,
      Math.max(
        0,
        containerWidth - width,
      ),
    );

    const top = clamp(
      anchorPoint.y,
      0,
      Math.max(
        0,
        containerHeight - height,
      ),
    );

    return {
      point: {
        x: left,
        y: top,
      },
      left,
      right: left + width,
      top,
      bottom: top + height,
      width,
      height,
      lines,
      font,
      lineHeight,
    };
  }

  private containsPoint(point: Point): boolean {
    const geometry = this.getGeometry();

    return (
      geometry !== null &&
      isPointInBounds(
        point,
        geometry,
        2,
      )
    );
  }
}

function getTextLines(text: string): string[] {
  const lines = text.split('\n');

  return lines.length
    ? lines
    : [''];
}

function getFont(settings: TextSettings): string {
  const italic =
    settings.isItalic
      ? 'italic '
      : '';

  const bold =
    settings.isBold
      ? '700 '
      : '';

  return `${italic}${bold}${settings.fontSize}px Inter, sans-serif`;
}

function measureTextBlock(
  lines: string[],
  font: string,
  lineHeight: number,
): {
  width: number;
  height: number;
} {
  const context = getMeasureContext();

  if (!context) {
    const estimatedWidth =
      Math.max(
        ...lines.map((line) =>
          Math.max(
            1,
            line.length,
          ),
        ),
      ) * 8;

    return {
      width: estimatedWidth,
      height: lines.length * lineHeight,
    };
  }

  context.font = font;

  const width = lines.reduce(
    (maxWidth, line) => {
      return Math.max(
        maxWidth,
        context.measureText(
          line || ' ',
        ).width,
      );
    },
    0,
  );

  return {
    width: Math.ceil(width),
    height: lines.length * lineHeight,
  };
}

function getMeasureContext(): CanvasRenderingContext2D | null {
  if (!measureCanvas) {
    measureCanvas =
      document.createElement('canvas');
  }

  return measureCanvas.getContext('2d');
}

















import { clamp } from 'lodash-es';
import {
  IPrimitivePaneView,
  PrimitiveHoveredItem,
} from 'lightweight-charts';

import {
  CustomPriceAxisPaneView,
  CustomTimeAxisPaneView,
} from '@core/Drawings/axis';
import { DrawingBase } from '@core/Drawings/DrawingBase';
import {
  clampPointToContainer,
  getContainerSize,
  isNearPoint,
} from '@core/Drawings/helpers';
import {
  getDistanceToSegment,
  updateViews,
} from '@core/Drawings/utils';

import { TraectoryPaneView } from './paneView';
import {
  createDefaultSettings,
  getTraectorySettingsTabs,
  TraectorySettings,
  TraectoryStyle,
} from './settings';

import type { DrawingHandle } from '@core/Drawings/handles';
import type {
  Anchor,
  AxisLabel,
  AxisSegment,
  Point,
} from '@core/Drawings/types';
import type {
  BaseDrawingParams,
  ISeriesDrawing,
} from '@core/Drawings/DrawingBase';
import type { SettingsTab } from '@src/types';

type TraectoryMode =
  | 'idle'
  | 'drawing'
  | 'ready'
  | 'dragging-point'
  | 'dragging-body';

type TraectoryHandleId = `${number}`;
type TraectoryParams = BaseDrawingParams;

export interface TraectoryState {
  hidden: boolean;
  mode: TraectoryMode;
  points: Anchor[];
  settings: TraectorySettings;
}

interface TraectoryGeometry {
  points: Point[];
  left: number;
  right: number;
  top: number;
  bottom: number;
}

export interface TraectoryRenderData
  extends TraectoryGeometry,
    TraectoryStyle {
  previewPoint: Point | null;
  showArrow: boolean;
}

const POINT_HIT_TOLERANCE = 8;
const SEGMENT_HIT_TOLERANCE = 6;
const MIN_POINTS_COUNT = 2;

export class Traectory
  extends DrawingBase<
    TraectorySettings,
    TraectoryHandleId
  >
  implements ISeriesDrawing
{
  private removeSelf?: () => void;
  private openSettings?: () => void;

  protected settings: TraectorySettings =
    createDefaultSettings();

  protected mode: TraectoryMode = 'idle';

  private points: Anchor[] = [];
  private previewAnchor: Anchor | null = null;

  private dragPointerId: number | null = null;
  private dragStartPoint: Point | null = null;
  private dragPointIndex: number | null = null;
  private dragGeometrySnapshot: TraectoryGeometry | null = null;

  private readonly paneView: TraectoryPaneView;
  private readonly timeAxisPaneView: CustomTimeAxisPaneView;
  private readonly priceAxisPaneView: CustomPriceAxisPaneView;

  constructor({
    chart,
    series,
    container,
    interaction,
    removeSelf,
    openSettings,
    initialEvent,
  }: TraectoryParams) {
    super({
      chart,
      series,
      container,
      interaction,
    });

    this.removeSelf = removeSelf;
    this.openSettings = openSettings;

    this.paneView =
      new TraectoryPaneView(this);

    this.timeAxisPaneView =
      this.createTimeAxisPaneView();

    this.priceAxisPaneView =
      this.createPriceAxisPaneView();

    this.series.attachPrimitive(this);

    if (initialEvent?.sourceEvent) {
      this.startDrawing(
        this.getEventPoint(
          initialEvent.sourceEvent,
        ),
      );
    }
  }

  public isCreationPending(): boolean {
    return (
      this.mode === 'idle' ||
      this.mode === 'drawing'
    );
  }

  public getState(): TraectoryState {
    return {
      hidden: this.hidden,
      mode: this.mode,
      points: this.points,
      settings: {
        ...this.settings,
      },
    };
  }

  public setState(state: unknown): void {
    if (
      !state ||
      typeof state !== 'object'
    ) {
      return;
    }

    const nextState =
      state as Partial<TraectoryState>;

    this.hidden =
      typeof nextState.hidden === 'boolean'
        ? nextState.hidden
        : this.hidden;

    this.mode =
      nextState.mode ??
      this.mode;

    this.points =
      Array.isArray(nextState.points)
        ? nextState.points
        : this.points;

    if (
      'settings' in nextState &&
      nextState.settings
    ) {
      this.settings = {
        ...createDefaultSettings(),
        ...nextState.settings,
      };
    }

    this.render();
  }

  public getSettingsTabs(): SettingsTab[] {
    return getTraectorySettingsTabs(
      this.settings,
    );
  }

  public updateAllViews(): void {
    updateViews([
      this.paneView,
      this.timeAxisPaneView,
      this.priceAxisPaneView,
    ]);
  }

  public paneViews():
    readonly IPrimitivePaneView[] {
    return [
      this.paneView,
    ];
  }

  public timeAxisPaneViews():
    readonly IPrimitivePaneView[] {
    return [
      this.timeAxisPaneView,
    ];
  }

  public priceAxisPaneViews():
    readonly IPrimitivePaneView[] {
    return [
      this.priceAxisPaneView,
    ];
  }

  public timeAxisViews() {
    return [];
  }

  public priceAxisViews() {
    return [];
  }

  public getRenderData():
    TraectoryRenderData | null {
    if (this.hidden) {
      return null;
    }

    const geometry =
      this.getGeometry();

    if (!geometry) {
      return null;
    }

    return {
      ...geometry,
      previewPoint:
        this.getPreviewPoint(),
      showArrow:
        this.mode !== 'drawing' &&
        geometry.points.length > 1,
      ...this.settings,
    };
  }

  protected getDrawingHandles():
    readonly DrawingHandle<TraectoryHandleId>[] {
    const geometry =
      this.getGeometry();

    if (!geometry) {
      return [];
    }

    return geometry.points
      .map<
        DrawingHandle<TraectoryHandleId>
      >((point, index) => ({
        id: `${index}`,
        ...point,
        shape: 'circle',
      }))
      .reverse();
  }

  protected getHoveredItem(
    x: number,
    y: number,
  ): PrimitiveHoveredItem | null {
    if (
      this.hidden ||
      this.mode === 'idle' ||
      this.mode === 'drawing'
    ) {
      return null;
    }

    const point = {
      x,
      y,
    };

    if (!this.isSelected()) {
      if (
        !this.isPointNearTraectory(
          point,
        )
      ) {
        return null;
      }

      return {
        cursorStyle: 'move',
        externalId: 'traectory',
        zOrder: 'top',
      };
    }

    if (
      this.getPointIndexAt(
        point,
      ) !== null
    ) {
      return {
        cursorStyle: 'move',
        externalId: 'traectory',
        zOrder: 'top',
      };
    }

    if (
      !this.isPointNearTraectory(
        point,
      )
    ) {
      return null;
    }

    return {
      cursorStyle: 'move',
      externalId: 'traectory',
      zOrder: 'top',
    };
  }

  protected getTimeAxisSegments():
    AxisSegment[] {
    if (
      !this.shouldShowInteractiveAxis()
    ) {
      return [];
    }

    const geometry =
      this.getGeometry();

    if (!geometry) {
      return [];
    }

    return [
      this.createAxisSegment(
        geometry.left,
        geometry.right,
      ),
    ];
  }

  protected getPriceAxisSegments():
    AxisSegment[] {
    if (
      !this.shouldShowInteractiveAxis()
    ) {
      return [];
    }

    const geometry =
      this.getGeometry();

    if (!geometry) {
      return [];
    }

    return [
      this.createAxisSegment(
        geometry.top,
        geometry.bottom,
      ),
    ];
  }

  protected getPriceAxisLabel(
    _kind: string,
  ): AxisLabel | null {
    return null;
  }

  protected getTimeAxisLabel(
    _kind: string,
  ): AxisLabel | null {
    return null;
  }

  protected handleClick = (
    event: MouseEvent,
  ): void => {
    if (
      this.hidden ||
      this.mode !== 'drawing' ||
      event.detail !== 1
    ) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.appendPoint(
      this.getEventPoint(
        event as PointerEvent,
      ),
    );
  };

  protected handleDoubleClick = (
    event: MouseEvent,
  ): void => {
    if (this.hidden) {
      return;
    }

    if (
      this.mode === 'drawing'
    ) {
      event.preventDefault();
      event.stopPropagation();

      this.finishDrawing();
      return;
    }

    if (
      this.mode !== 'ready' ||
      !this.isSelected()
    ) {
      return;
    }

    const point =
      this.getEventPoint(
        event as PointerEvent,
      );

    if (
      this.getPointIndexAt(
        point,
      ) === null &&
      !this.isPointNearTraectory(
        point,
      )
    ) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.openSettings?.();
  };

  protected handleContextMenu = (
    event: MouseEvent,
  ): void => {
    if (
      this.hidden ||
      this.mode !== 'drawing'
    ) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.finishDrawing();
  };

  protected handlePointerDown = (
    event: PointerEvent,
  ): void => {
    if (
      this.hidden ||
      event.button !== 0
    ) {
      return;
    }

    const point =
      this.getEventPoint(event);

    if (this.mode === 'idle') {
      event.preventDefault();
      event.stopPropagation();

      this.startDrawing(point);
      return;
    }

    if (
      this.mode === 'drawing'
    ) {
      return;
    }

    if (
      this.mode !== 'ready'
    ) {
      return;
    }

    if (!this.isSelected()) {
      if (
        !this.isPointNearTraectory(
          point,
        )
      ) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();

      this.select();
      return;
    }

    const pointIndex =
      this.getPointIndexAt(point);

    if (pointIndex !== null) {
      event.preventDefault();
      event.stopPropagation();

      this.startDraggingPoint(
        point,
        event.pointerId,
        pointIndex,
      );
      return;
    }

    if (
      !this.isPointNearTraectory(
        point,
      )
    ) {
      this.deselect();
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.startDraggingBody(
      point,
      event.pointerId,
    );
  };

  protected handlePointerMove = (
    event: PointerEvent,
  ): void => {
    const point =
      this.getEventPoint(event);

    if (
      this.mode === 'drawing'
    ) {
      this.updatePreview(point);
      return;
    }

    if (
      this.dragPointerId !==
      event.pointerId
    ) {
      return;
    }

    if (
      this.mode ===
      'dragging-point'
    ) {
      event.preventDefault();

      this.movePoint(point);
      this.render();
      return;
    }

    if (
      this.mode ===
      'dragging-body'
    ) {
      event.preventDefault();

      this.moveBody(point);
      this.render();
    }
  };

  protected handlePointerUp = (
    event: PointerEvent,
  ): void => {
    if (
      this.dragPointerId !==
      event.pointerId
    ) {
      return;
    }

    if (
      this.mode ===
        'dragging-point' ||
      this.mode ===
        'dragging-body'
    ) {
      this.finishDragging();
    }
  };

  private startDrawing(
    point: Point,
  ): void {
    const anchor =
      this.createAnchorFromPoint(
        clampPointToContainer(
          point,
          this.container,
        ),
      );

    if (!anchor) {
      return;
    }

    this.points = [
      anchor,
    ];

    this.previewAnchor =
      anchor;

    this.mode = 'drawing';

    this.render();
  }

  private appendPoint(
    point: Point,
  ): void {
    const anchor =
      this.createAnchorFromPoint(
        clampPointToContainer(
          point,
          this.container,
        ),
      );

    if (!anchor) {
      return;
    }

    const lastPoint =
      this.points[
        this.points.length - 1
      ];

    if (
      lastPoint &&
      Number(lastPoint.time) ===
        Number(anchor.time) &&
      lastPoint.price ===
        anchor.price
    ) {
      this.previewAnchor =
        anchor;

      this.render();
      return;
    }

    this.points = [
      ...this.points,
      anchor,
    ];

    this.previewAnchor =
      anchor;

    this.render();
  }

  private updatePreview(
    point: Point,
  ): void {
    const anchor =
      this.createAnchorFromPoint(
        clampPointToContainer(
          point,
          this.container,
        ),
      );

    if (!anchor) {
      return;
    }

    this.previewAnchor =
      anchor;

    this.render();
  }

  private finishDrawing(): void {
    if (
      this.points.length <
      MIN_POINTS_COUNT
    ) {
      if (this.removeSelf) {
        this.removeSelf();
        return;
      }

      this.resetToIdle();
      return;
    }

    this.previewAnchor = null;
    this.mode = 'ready';
    this.resolveReady?.();

    this.render();
  }

  private startDraggingPoint(
    point: Point,
    pointerId: number,
    pointIndex: number,
  ): void {
    this.mode =
      'dragging-point';

    this.dragPointerId =
      pointerId;

    this.dragStartPoint =
      point;

    this.dragPointIndex =
      pointIndex;

    this.dragGeometrySnapshot =
      this.getGeometry();

    this.hideCrosshair();
    this.render();
  }

  private startDraggingBody(
    point: Point,
    pointerId: number,
  ): void {
    this.mode =
      'dragging-body';

    this.dragPointerId =
      pointerId;

    this.dragStartPoint =
      point;

    this.dragPointIndex = null;

    this.dragGeometrySnapshot =
      this.getGeometry();

    this.hideCrosshair();
    this.render();
  }

  private finishDragging(): void {
    this.mode = 'ready';
    this.resolveReady?.();

    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragPointIndex = null;
    this.dragGeometrySnapshot = null;

    this.showCrosshair();
    this.render();
  }

  private resetToIdle(): void {
    this.mode = 'idle';

    this.points = [];
    this.previewAnchor = null;
    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragPointIndex = null;
    this.dragGeometrySnapshot = null;

    this.showCrosshair();
    this.render();
  }

  private movePoint(
    point: Point,
  ): void {
    const geometry =
      this.dragGeometrySnapshot;

    const pointIndex =
      this.dragPointIndex;

    if (
      !geometry ||
      pointIndex === null
    ) {
      return;
    }

    const nextPoints = [
      ...geometry.points,
    ];

    nextPoints[pointIndex] =
      clampPointToContainer(
        point,
        this.container,
      );

    this.setAnchorsFromPoints(
      nextPoints,
    );
  }

  private moveBody(
    point: Point,
  ): void {
    const geometry =
      this.dragGeometrySnapshot;

    const dragStartPoint =
      this.dragStartPoint;

    if (
      !geometry ||
      !dragStartPoint
    ) {
      return;
    }

    const { width, height } =
      getContainerSize(
        this.container,
      );

    const rawOffsetX =
      point.x -
      dragStartPoint.x;

    const rawOffsetY =
      point.y -
      dragStartPoint.y;

    const offsetX = clamp(
      rawOffsetX,
      -geometry.left,
      width - geometry.right,
    );

    const offsetY = clamp(
      rawOffsetY,
      -geometry.top,
      height - geometry.bottom,
    );

    const nextPoints =
      geometry.points.map(
        (item) => {
          return clampPointToContainer(
            {
              x:
                item.x +
                offsetX,
              y:
                item.y +
                offsetY,
            },
            this.container,
          );
        },
      );

    this.setAnchorsFromPoints(
      nextPoints,
    );
  }

  private setAnchorsFromPoints(
    points: Point[],
  ): void {
    const nextAnchors:
      Anchor[] = [];

    for (const point of points) {
      const anchor =
        this.createAnchorFromPoint(
          point,
        );

      if (!anchor) {
        return;
      }

      nextAnchors.push(
        anchor,
      );
    }

    this.points =
      nextAnchors;
  }

  protected getGeometry():
    TraectoryGeometry | null {
    if (!this.points.length) {
      return null;
    }

    const { width, height } =
      getContainerSize(
        this.container,
      );

    const screenPoints:
      Point[] = [];

    for (
      const anchor of this.points
    ) {
      const point =
        this.getPointFromAnchor(
          anchor,
        );

      if (!point) {
        return null;
      }

      screenPoints.push({
        x: clamp(
          point.x,
          0,
          width,
        ),
        y: clamp(
          point.y,
          0,
          height,
        ),
      });
    }

    return {
      points: screenPoints,
      left: Math.min(
        ...screenPoints.map(
          (point) => point.x,
        ),
      ),
      right: Math.max(
        ...screenPoints.map(
          (point) => point.x,
        ),
      ),
      top: Math.min(
        ...screenPoints.map(
          (point) => point.y,
        ),
      ),
      bottom: Math.max(
        ...screenPoints.map(
          (point) => point.y,
        ),
      ),
    };
  }

  private getPreviewPoint():
    Point | null {
    if (
      this.mode !== 'drawing' ||
      !this.previewAnchor
    ) {
      return null;
    }

    const point =
      this.getPointFromAnchor(
        this.previewAnchor,
      );

    if (!point) {
      return null;
    }

    const { width, height } =
      getContainerSize(
        this.container,
      );

    return {
      x: clamp(
        point.x,
        0,
        width,
      ),
      y: clamp(
        point.y,
        0,
        height,
      ),
    };
  }

  private getPointIndexAt(
    point: Point,
  ): number | null {
    const handle =
      this.getDrawingHandleAtPoint(
        point,
      );

    return handle
      ? Number(handle.id)
      : null;
  }

  private isPointNearTraectory(
    point: Point,
  ): boolean {
    const geometry =
      this.getGeometry();

    if (!geometry) {
      return false;
    }

    if (
      geometry.points.length === 1
    ) {
      const firstPoint =
        geometry.points[0];

      return isNearPoint(
        point,
        firstPoint.x,
        firstPoint.y,
        POINT_HIT_TOLERANCE,
      );
    }

    for (
      let index = 0;
      index <
      geometry.points.length - 1;
      index += 1
    ) {
      const startPoint =
        geometry.points[index];

      const endPoint =
        geometry.points[
          index + 1
        ];

      if (
        getDistanceToSegment(
          point,
          startPoint,
          endPoint,
        ) <=
        SEGMENT_HIT_TOLERANCE
      ) {
        return true;
      }
    }

    return false;
  }
}