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


import { MismatchDirection, PriceScaleMode } from 'lightweight-charts';

import { Subscription } from 'rxjs';

import { Indicator } from '@core/Indicator';
import { IndicatorsIds, MAIN_PANE_INDEX } from '@src/constants';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { getThemeStore } from '@src/theme';
import { Direction } from '@src/types';
import { formatCompactNumber, formatPercent, formatPrice } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

import { PriceAxisLabelsPrimitive } from './PriceAxisLabelsPrimitive';
import { getAxisSideBySeries, getContrastTextColor } from './utils';

import type { PriceAxisLabel } from './types';

import type { IPriceLine, LogicalRange } from 'lightweight-charts';
import type { Observable } from 'rxjs';

type EntityCollection = 'compare' | 'indicator';
type SourceRole = 'main' | 'compare' | 'indicator' | 'volume';
type PriceAxisSide = Direction.Left | Direction.Right;

interface PriceAxisLabelsParams {
  mainSeries$: Observable<SeriesStrategies | null>;
  mainSymbol$: Observable<string>;
  compareEntities$: Observable<Indicator[]>;
  indicatorEntities$: Observable<Indicator[]>;
}

interface PriceLabelSource {
  id: string;
  role: SourceRole;
  series: SeriesStrategies;
  priority: number;
}

interface SourceDefaults {
  lastValueVisible: boolean;
  priceLineVisible: boolean;
  title: string;
}

interface AxisLabelsGroup {
  paneIndex: number;
  side: PriceAxisSide;
  labels: PriceAxisLabel[];
  reservedCoordinate: number | null;
}

interface AxisLayer {
  host: SeriesStrategies;
  primitive: PriceAxisLabelsPrimitive;
}

interface EntitySubscription {
  entity: Indicator;
  subscription: Subscription;
}

const SOURCE_PRIORITY: Record<SourceRole, number> = {
  main: 100,
  compare: 80,
  indicator: 60,
  volume: 40,
};

function getDataPrice(data: unknown): number | null {
  if (!data || typeof data !== 'object') {
    return null;
  }

  if ('close' in data && typeof data.close === 'number') {
    return data.close;
  }

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

  return null;
}

function getSeriesColor(series: SeriesStrategies, data: unknown): string {
  if (data && typeof data === 'object' && 'color' in data && typeof data.color === 'string') {
    return removeAlphaFromHex(data.color);
  }

  const options = series.options();

  if (
    data &&
    typeof data === 'object' &&
    'open' in data &&
    'close' in data &&
    typeof data.open === 'number' &&
    typeof data.close === 'number'
  ) {
    if (data.close >= data.open && 'upColor' in options && typeof options.upColor === 'string') {
      return removeAlphaFromHex(options.upColor);
    }

    if (data.close < data.open && 'downColor' in options && typeof options.downColor === 'string') {
      return removeAlphaFromHex(options.downColor);
    }
  }

  if ('color' in options && typeof options.color === 'string') {
    return removeAlphaFromHex(options.color);
  }

  if ('lineColor' in options && typeof options.lineColor === 'string') {
    return removeAlphaFromHex(options.lineColor);
  }

  if ('topLineColor' in options && typeof options.topLineColor === 'string') {
    return removeAlphaFromHex(options.topLineColor);
  }

  if ('bottomLineColor' in options && typeof options.bottomLineColor === 'string') {
    return removeAlphaFromHex(options.bottomLineColor);
  }

  return removeAlphaFromHex(getThemeStore().colors.chartLineColor);
}

function getAxisSide(source: PriceLabelSource): PriceAxisSide {
  if (source.role === 'volume') {
    return Direction.Right;
  }

  return getAxisSideBySeries(source.series);
}

export class PriceAxisLabels {
  private subscriptions = new Subscription();
  private entitySubscriptions = new Map<string, EntitySubscription>();
  private sourceDefaults = new WeakMap<SeriesStrategies, SourceDefaults>();
  private layers = new Map<string, AxisLayer>();

  private mainSeries: SeriesStrategies | null = null;
  private mainSeriesDataHandler: (() => void) | null = null;
  private compareEntities: Indicator[] = [];
  private indicatorEntities: Indicator[] = [];
  private visibleLogicalRange: LogicalRange | null = null;
  private currentPriceLine: IPriceLine | null = null;
  private currentPriceLineHost: SeriesStrategies | null = null;
  private mainSymbol = '';
  private isHistoryMode = false;
  private updateFrame: number | null = null;

  constructor({ mainSeries$, mainSymbol$, compareEntities$, indicatorEntities$ }: PriceAxisLabelsParams) {
    this.subscriptions.add(
      mainSymbol$.subscribe((symbol) => {
        this.mainSymbol = symbol;

        this.applyDisplayMode();
        this.scheduleUpdate();
      }),
    );

    this.subscriptions.add(
      mainSeries$.subscribe((series) => {
        this.setMainSeries(series);
      }),
    );

    this.subscriptions.add(
      compareEntities$.subscribe((entities) => {
        this.setEntities('compare', entities);
      }),
    );

    this.subscriptions.add(
      indicatorEntities$.subscribe((entities) => {
        this.setEntities('indicator', entities);
      }),
    );
  }

  public setVisibleLogicalRange(logicalRange: LogicalRange | null): void {
    this.visibleLogicalRange = logicalRange;

    this.refreshHistoryMode();
    this.scheduleUpdate();
  }

  public invalidate(): void {
    this.scheduleUpdate();
  }

  public destroy(): void {
    if (this.updateFrame !== null) {
      cancelAnimationFrame(this.updateFrame);
      this.updateFrame = null;
    }

    this.unsubscribeMainSeries();
    this.subscriptions.unsubscribe();

    this.entitySubscriptions.forEach(({ subscription }) => {
      subscription.unsubscribe();
    });

    this.getSources().forEach(({ series }) => {
      this.restoreSourceOptions(series);
    });

    this.layers.forEach(({ host, primitive }) => {
      try {
        host.detachPrimitive(primitive);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    });

    this.entitySubscriptions.clear();
    this.layers.clear();
    this.removeCurrentPriceLine();
  }

  private setMainSeries(series: SeriesStrategies | null): void {
    if (this.mainSeries === series) {
      return;
    }

    const previousSeries = this.mainSeries;

    this.unsubscribeMainSeries();

    if (previousSeries) {
      this.restoreSourceOptions(previousSeries);
    }

    this.mainSeries = series;

    if (series) {
      this.ensureSourceDefaults(series);

      this.mainSeriesDataHandler = () => {
        this.refreshHistoryMode();
        this.scheduleUpdate();
      };

      series.subscribeDataChanged(this.mainSeriesDataHandler);
    }

    if (this.currentPriceLineHost && this.currentPriceLineHost !== series) {
      this.removeCurrentPriceLine();
    }

    this.refreshHistoryMode();
    this.applyDisplayMode();
    this.scheduleUpdate();
  }

  private unsubscribeMainSeries(): void {
    if (!this.mainSeries || !this.mainSeriesDataHandler) {
      this.mainSeriesDataHandler = null;
      return;
    }

    try {
      this.mainSeries.unsubscribeDataChanged(this.mainSeriesDataHandler);
    } catch {
      // Серия могла быть удалена раньше объекта PriceAxisLabels.
    }

    this.mainSeriesDataHandler = null;
  }

  private setEntities(collection: EntityCollection, entities: Indicator[]): void {
    if (collection === 'compare') {
      this.compareEntities = entities;
    } else {
      this.indicatorEntities = entities;
    }

    const activeKeys = new Set(entities.map((entity) => `${collection}:${entity.getId()}`));

    this.entitySubscriptions.forEach((entry, key) => {
      if (!key.startsWith(`${collection}:`) || activeKeys.has(key)) {
        return;
      }

      entry.entity.getSeriesMap().forEach((series) => {
        this.restoreSourceOptions(series);
      });

      entry.subscription.unsubscribe();
      this.entitySubscriptions.delete(key);
    });

    entities.forEach((entity) => {
      const key = `${collection}:${entity.getId()}`;
      const current = this.entitySubscriptions.get(key);

      if (current?.entity === entity) {
        return;
      }

      if (current) {
        current.entity.getSeriesMap().forEach((series) => {
          this.restoreSourceOptions(series);
        });

        current.subscription.unsubscribe();
      }

      const subscription = entity.subscribeDataChange(() => {
        this.applyDisplayModeToSources(this.getEntitySources(collection, entity));

        this.scheduleUpdate();
      });

      this.entitySubscriptions.set(key, {
        entity,
        subscription,
      });

      this.applyDisplayModeToSources(this.getEntitySources(collection, entity));
    });

    this.applyDisplayMode();
    this.scheduleUpdate();
  }

  private getSources(): PriceLabelSource[] {
    const sources: PriceLabelSource[] = [];

    if (this.mainSeries) {
      sources.push({
        id: 'main',
        role: 'main',
        series: this.mainSeries,
        priority: SOURCE_PRIORITY.main,
      });
    }

    this.compareEntities.forEach((entity) => {
      sources.push(...this.getEntitySources('compare', entity));
    });

    this.indicatorEntities.forEach((entity) => {
      sources.push(...this.getEntitySources('indicator', entity));
    });

    return sources;
  }

  private getEntitySources(collection: EntityCollection, entity: Indicator): PriceLabelSource[] {
    let role: SourceRole = 'indicator';

    if (collection === 'compare') {
      role = 'compare';
    } else if (entity.getType() === IndicatorsIds.Volume) {
      role = 'volume';
    }

    return Array.from(entity.getSeriesMap().entries(), ([seriesId, series]) => ({
      id: `${collection}:${entity.getId()}:${seriesId}`,
      role,
      series,
      priority: SOURCE_PRIORITY[role],
    }));
  }

  private ensureSourceDefaults(series: SeriesStrategies): SourceDefaults {
    const savedDefaults = this.sourceDefaults.get(series);

    if (savedDefaults) {
      return savedDefaults;
    }

    const options = series.options();

    const defaults = {
      lastValueVisible: options.lastValueVisible,
      priceLineVisible: options.priceLineVisible,
      title: options.title ?? '',
    };

    this.sourceDefaults.set(series, defaults);

    return defaults;
  }

  private restoreSourceOptions(series: SeriesStrategies): void {
    const defaults = this.sourceDefaults.get(series);

    if (!defaults) {
      return;
    }

    try {
      series.applyOptions(defaults);
    } catch {
      // Серия могла быть удалена раньше объекта PriceAxisLabels.
    }
  }

  private applyDisplayMode(): void {
    this.applyDisplayModeToSources(this.getSources());

    if (!this.isHistoryMode) {
      this.hideCurrentPriceLine();
    }
  }

  private applyDisplayModeToSources(sources: PriceLabelSource[]): void {
    sources.forEach((source) => {
      const defaults = this.ensureSourceDefaults(source.series);

      try {
        if (source.role === 'volume') {
          source.series.applyOptions({
            lastValueVisible: false,
            priceLineVisible: false,
          });

          return;
        }

        if (source.role === 'main') {
          source.series.applyOptions({
            lastValueVisible: this.isHistoryMode ? false : defaults.lastValueVisible,
            title: this.isHistoryMode ? '' : this.mainSymbol || defaults.title,
          });

          return;
        }

        source.series.applyOptions({
          lastValueVisible: this.isHistoryMode ? false : defaults.lastValueVisible,
        });
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    });
  }

  private refreshHistoryMode(): void {
    const barsInfo =
      this.visibleLogicalRange && this.mainSeries ? this.mainSeries.barsInLogicalRange(this.visibleLogicalRange) : null;

    const nextHistoryMode = (barsInfo?.barsAfter ?? 0) > 0;

    if (nextHistoryMode === this.isHistoryMode) {
      return;
    }

    this.isHistoryMode = nextHistoryMode;
    this.applyDisplayMode();
  }

  private scheduleUpdate(): void {
    if (this.updateFrame !== null) {
      return;
    }

    this.updateFrame = requestAnimationFrame(() => {
      this.updateFrame = null;
      this.update();
    });
  }

  private update(): void {
    const sources = this.getSources();

    this.updateCurrentPriceLine(sources);
    this.updateAxisLayers(this.collectAxisGroups(sources), sources);
  }

  private collectAxisGroups(sources: PriceLabelSource[]): Map<string, AxisLabelsGroup> {
    const groups = new Map<string, AxisLabelsGroup>();

    sources.forEach((source) => {
      if (!source.series.isVisible() || (source.role !== 'volume' && !this.isHistoryMode)) {
        return;
      }

      const label = this.createLabel(source);

      if (!label) {
        return;
      }

      const paneIndex = source.series.getPane().paneIndex();

      const side = getAxisSide(source);
      const key = `${paneIndex}:${side}`;
      const group = groups.get(key);

      if (group) {
        group.labels.push(label);
        return;
      }

      groups.set(key, {
        paneIndex,
        side,
        labels: [label],
        reservedCoordinate: null,
      });
    });

    const mainSource = sources.find((source) => source.role === 'main');

    if (!mainSource) {
      return groups;
    }

    const showRealtimeLabel = this.isHistoryMode || this.ensureSourceDefaults(mainSource.series).lastValueVisible;

    if (!showRealtimeLabel) {
      return groups;
    }

    const reservedCoordinate = this.getCurrentMainPriceCoordinate();

    if (reservedCoordinate === null) {
      return groups;
    }

    const paneIndex = mainSource.series.getPane().paneIndex();

    const side = getAxisSide(mainSource);
    const group = groups.get(`${paneIndex}:${side}`);

    if (group) {
      group.reservedCoordinate = reservedCoordinate;
    }

    return groups;
  }

  private createLabel(source: PriceLabelSource): PriceAxisLabel | null {
    const data = this.getSourceData(source);
    const price = getDataPrice(data);

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

    const coordinate = source.series.priceToCoordinate(price);

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

    return {
      id: source.id,
      desiredCoordinate: coordinate,
      text: source.role === 'volume' ? formatCompactNumber(price) : this.formatValue(source.series, price),
      color: getSeriesColor(source.series, data),
      style: this.isHistoryMode ? 'outlined' : 'filled',
      priority: source.priority,
    };
  }

  private getSourceData(source: PriceLabelSource): unknown {
    if (this.isHistoryMode && this.visibleLogicalRange) {
      return source.series.dataByIndex(Math.floor(this.visibleLogicalRange.to), MismatchDirection.NearestLeft);
    }

    const data = source.series.data();

    return data[data.length - 1] ?? null;
  }

  private updateAxisLayers(groups: Map<string, AxisLabelsGroup>, sources: PriceLabelSource[]): void {
    const activeKeys = new Set<string>();

    groups.forEach((group, key) => {
      const host = this.getAxisHost(group.paneIndex, group.side, sources);

      if (!host) {
        return;
      }

      activeKeys.add(key);

      this.getOrCreateLayer(key, host).primitive.setLabels(group.labels, group.reservedCoordinate);
    });

    this.layers.forEach((layer, key) => {
      if (activeKeys.has(key)) {
        return;
      }

      try {
        layer.host.detachPrimitive(layer.primitive);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }

      this.layers.delete(key);
    });
  }

  private getAxisHost(paneIndex: number, side: PriceAxisSide, sources: PriceLabelSource[]): SeriesStrategies | null {
    if (paneIndex === MAIN_PANE_INDEX && side === Direction.Right && this.mainSeries) {
      return this.mainSeries;
    }

    const regularSource = sources.find(
      (source) =>
        source.role !== 'volume' && source.series.getPane().paneIndex() === paneIndex && getAxisSide(source) === side,
    );

    if (regularSource) {
      return regularSource.series;
    }

    return (
      sources.find((source) => source.series.getPane().paneIndex() === paneIndex && getAxisSide(source) === side)
        ?.series ?? null
    );
  }

  private getOrCreateLayer(key: string, host: SeriesStrategies): AxisLayer {
    const currentLayer = this.layers.get(key);

    if (currentLayer?.host === host) {
      return currentLayer;
    }

    if (currentLayer) {
      try {
        currentLayer.host.detachPrimitive(currentLayer.primitive);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    }

    const layer = {
      host,
      primitive: new PriceAxisLabelsPrimitive(),
    };

    host.attachPrimitive(layer.primitive);
    this.layers.set(key, layer);

    return layer;
  }

  private updateCurrentPriceLine(sources: PriceLabelSource[]): void {
    const mainSource = sources.find((source) => source.role === 'main');

    if (!this.isHistoryMode || !mainSource || !mainSource.series.isVisible()) {
      this.hideCurrentPriceLine();
      return;
    }

    const data = mainSource.series.data();
    const lastData = data[data.length - 1];
    const price = getDataPrice(lastData);

    if (price === null) {
      this.hideCurrentPriceLine();
      return;
    }

    const color = getSeriesColor(mainSource.series, lastData);

    this.getCurrentPriceLine(mainSource.series, color).applyOptions({
      price,
      color,
      lineVisible: false,
      axisLabelVisible: true,
      axisLabelColor: color,
      axisLabelTextColor: getContrastTextColor(color),
      title: this.mainSymbol,
    });
  }

  private getCurrentMainPriceCoordinate(): number | null {
    if (!this.mainSeries) {
      return null;
    }

    const data = this.mainSeries.data();
    const price = getDataPrice(data[data.length - 1]);

    return price === null ? null : this.mainSeries.priceToCoordinate(price);
  }

  private getCurrentPriceLine(series: SeriesStrategies, color: string): IPriceLine {
    if (this.currentPriceLine && this.currentPriceLineHost === series) {
      return this.currentPriceLine;
    }

    this.removeCurrentPriceLine();

    this.currentPriceLine = series.createPriceLine({
      price: 0,
      color,
      lineVisible: false,
      axisLabelVisible: false,
      title: '',
    });

    this.currentPriceLineHost = series;

    return this.currentPriceLine;
  }

  private hideCurrentPriceLine(): void {
    this.currentPriceLine?.applyOptions({
      lineVisible: false,
      axisLabelVisible: false,
      title: '',
    });
  }

  private removeCurrentPriceLine(): void {
    if (this.currentPriceLine && this.currentPriceLineHost) {
      try {
        this.currentPriceLineHost.removePriceLine(this.currentPriceLine);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    }

    this.currentPriceLine = null;
    this.currentPriceLineHost = null;
  }

  private formatValue(series: SeriesStrategies, price: number): string {
    const { mode } = series.priceScale().options();

    const formattedPrice = formatPrice(price) ?? series.priceFormatter().format(price);

    if (mode !== PriceScaleMode.Percentage && mode !== PriceScaleMode.IndexedTo100) {
      return formattedPrice;
    }

    if (!this.visibleLogicalRange) {
      return formattedPrice;
    }

    const firstVisiblePrice = getDataPrice(
      series.dataByIndex(Math.ceil(this.visibleLogicalRange.from), MismatchDirection.NearestRight),
    );

    if (firstVisiblePrice === null || firstVisiblePrice === 0) {
      return formattedPrice;
    }

    if (mode === PriceScaleMode.Percentage) {
      return formatPercent(((price - firstVisiblePrice) / firstVisiblePrice) * 100);
    }

    const indexedValue = (price / firstVisiblePrice) * 100;

    return formatPrice(indexedValue) ?? String(indexedValue);
  }
}



import type { LaidOutPriceAxisLabel, MeasuredPriceAxisLabel, PriceAxisLabelsLayoutOptions } from './types';

const DEFAULT_GAP = 3;

function compareLabels(left: MeasuredPriceAxisLabel, right: MeasuredPriceAxisLabel): number {
  if (left.desiredCoordinate !== right.desiredCoordinate) {
    return left.desiredCoordinate - right.desiredCoordinate;
  }

  if (left.priority !== right.priority) {
    return right.priority - left.priority;
  }

  return left.id.localeCompare(right.id);
}

function layoutRange(
  labels: MeasuredPriceAxisLabel[],
  minCoordinate: number,
  maxCoordinate: number,
  gap: number,
  overflowAlignment: 'start' | 'center' | 'end',
): LaidOutPriceAxisLabel[] {
  const sortedLabels = [...labels].sort(compareLabels);

  if (sortedLabels.length === 0) {
    return [];
  }

  const availableHeight = Math.max(0, maxCoordinate - minCoordinate);
  const stackHeight =
    sortedLabels.reduce((height, label) => height + label.height, 0) + gap * Math.max(0, sortedLabels.length - 1);

  if (stackHeight > availableHeight) {
    let top = minCoordinate;

    if (overflowAlignment === 'end') {
      top = maxCoordinate - stackHeight;
    } else if (overflowAlignment === 'center') {
      top = minCoordinate + (availableHeight - stackHeight) / 2;
    }

    return sortedLabels.map((label) => {
      const coordinate = top + label.height / 2;

      top += label.height + gap;

      return {
        ...label,
        coordinate,
      };
    });
  }

  const result = sortedLabels.map((label) => ({
    ...label,
    coordinate: Math.min(
      Math.max(label.desiredCoordinate, minCoordinate + label.height / 2),
      maxCoordinate - label.height / 2,
    ),
  }));

  for (let index = 1; index < result.length; index += 1) {
    const previousLabel = result[index - 1];
    const currentLabel = result[index];

    currentLabel.coordinate = Math.max(
      currentLabel.coordinate,
      previousLabel.coordinate + previousLabel.height / 2 + currentLabel.height / 2 + gap,
    );
  }

  const lastLabel = result[result.length - 1];
  const maximumLastCoordinate = maxCoordinate - lastLabel.height / 2;

  if (lastLabel.coordinate > maximumLastCoordinate) {
    const offset = lastLabel.coordinate - maximumLastCoordinate;

    result.forEach((label) => {
      label.coordinate -= offset;
    });
  }

  for (let index = result.length - 2; index >= 0; index -= 1) {
    const currentLabel = result[index];
    const nextLabel = result[index + 1];

    currentLabel.coordinate = Math.min(
      currentLabel.coordinate,
      nextLabel.coordinate - nextLabel.height / 2 - currentLabel.height / 2 - gap,
    );
  }

  const firstLabel = result[0];
  const minimumFirstCoordinate = minCoordinate + firstLabel.height / 2;

  if (firstLabel.coordinate < minimumFirstCoordinate) {
    const offset = minimumFirstCoordinate - firstLabel.coordinate;

    result.forEach((label) => {
      label.coordinate += offset;
    });
  }

  return result;
}

export function layoutPriceAxisLabels(
  labels: MeasuredPriceAxisLabel[],
  axisHeight: number,
  options: PriceAxisLabelsLayoutOptions = {},
): LaidOutPriceAxisLabel[] {
  if (axisHeight <= 0 || labels.length === 0) {
    return [];
  }

  const { gap = DEFAULT_GAP, reservedCoordinate, reservedHeight } = options;

  if (reservedCoordinate === undefined || reservedHeight === undefined) {
    return layoutRange(labels, 0, axisHeight, gap, 'center');
  }

  const coordinate = Math.min(Math.max(reservedCoordinate, 0), axisHeight);
  const height = Math.max(0, reservedHeight);
  const reservedTop = Math.max(0, coordinate - height / 2);
  const reservedBottom = Math.min(axisHeight, coordinate + height / 2);
  const labelsAbove = labels.filter((label) => label.desiredCoordinate <= coordinate);
  const labelsBelow = labels.filter((label) => label.desiredCoordinate > coordinate);

  return [
    ...layoutRange(labelsAbove, 0, Math.max(0, reservedTop - gap), gap, 'end'),
    ...layoutRange(labelsBelow, Math.min(axisHeight, reservedBottom + gap), axisHeight, gap, 'start'),
  ].sort((left, right) => {
    if (left.priority !== right.priority) {
      return left.priority - right.priority;
    }

    return left.id.localeCompare(right.id);
  });
}


import { getThemeStore } from '@src/theme';
import { Direction } from '@src/types';

import { layoutPriceAxisLabels } from './PriceAxisLabelsLayout';
import { getAxisSideBySeries, getContrastTextColor } from './utils';

import type { LaidOutPriceAxisLabel, MeasuredPriceAxisLabel, PriceAxisLabel, PriceAxisSide } from './types';

import type { CanvasRenderingTarget2D } from 'fancy-canvas';
import type {
  ChartOptions,
  IPrimitivePaneRenderer,
  IPrimitivePaneView,
  ISeriesPrimitive,
  PrimitivePaneViewZOrder,
  SeriesAttachedParameter,
  Time,
} from 'lightweight-charts';

type ChartLayoutOptions = Readonly<ChartOptions['layout']>;

interface PriceAxisLabelsRenderState {
  labels: PriceAxisLabel[];
  reservedCoordinate: number | null;
  chart: SeriesAttachedParameter<Time>['chart'] | null;
  series: SeriesAttachedParameter<Time>['series'] | null;
}

interface LabelGeometry {
  label: LaidOutPriceAxisLabel;
  left: number;
  top: number;
  textX: number;
  textY: number;
}

const HORIZONTAL_PADDING_RATIO = 7.25 / 12;
const VERTICAL_PADDING_RATIO = 3.75 / 12;
const TEXT_VERTICAL_OFFSET_RATIO = 0.5 / 12;
const LABEL_EDGE_GAP = 1;

function getFont(layout: ChartLayoutOptions): string {
  return `${layout.fontSize}px ${layout.fontFamily}`;
}

function getLabelTextColor(label: PriceAxisLabel): string {
  if (label.style === 'outlined') {
    return label.color;
  }

  return getContrastTextColor(label.color);
}

function areLabelsEqual(currentLabels: PriceAxisLabel[], nextLabels: PriceAxisLabel[]): boolean {
  return (
    currentLabels.length === nextLabels.length &&
    currentLabels.every((currentLabel, index) => {
      const nextLabel = nextLabels[index];

      return (
        currentLabel.id === nextLabel.id &&
        currentLabel.desiredCoordinate === nextLabel.desiredCoordinate &&
        currentLabel.text === nextLabel.text &&
        currentLabel.color === nextLabel.color &&
        currentLabel.style === nextLabel.style &&
        currentLabel.priority === nextLabel.priority
      );
    })
  );
}

function measureLabels(
  context: CanvasRenderingContext2D,
  labels: PriceAxisLabel[],
  layout: ChartLayoutOptions,
): MeasuredPriceAxisLabel[] {
  const horizontalPadding = layout.fontSize * HORIZONTAL_PADDING_RATIO;
  const verticalPadding = layout.fontSize * VERTICAL_PADDING_RATIO;

  return labels.map((label) => {
    const textMetrics = context.measureText(label.text);
    const textHeight = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent || layout.fontSize;

    return {
      ...label,
      width: Math.ceil(textMetrics.width) + horizontalPadding * 2,
      height: textHeight + verticalPadding * 2,
    };
  });
}

function createLabelGeometries(
  labels: MeasuredPriceAxisLabel[],
  axisWidth: number,
  axisHeight: number,
  side: PriceAxisSide,
  layout: ChartLayoutOptions,
  reservedCoordinate: number | null,
): LabelGeometry[] {
  const reservedHeight = labels.reduce(
    (maximumHeight, label) => Math.max(maximumHeight, label.height),
    layout.fontSize + layout.fontSize * VERTICAL_PADDING_RATIO * 2,
  );

  const laidOutLabels =
    reservedCoordinate === null
      ? layoutPriceAxisLabels(labels, axisHeight)
      : layoutPriceAxisLabels(labels, axisHeight, {
          reservedCoordinate,
          reservedHeight,
        });

  return laidOutLabels.map((label) => {
    const left =
      side === Direction.Right ? LABEL_EDGE_GAP : Math.max(LABEL_EDGE_GAP, axisWidth - label.width - LABEL_EDGE_GAP);

    return {
      label,
      left,
      top: label.coordinate - label.height / 2,
      textX: left + label.width / 2,
      textY: label.coordinate + layout.fontSize * TEXT_VERTICAL_OFFSET_RATIO,
    };
  });
}

function drawLabelBackgrounds(target: CanvasRenderingTarget2D, geometries: LabelGeometry[]): void {
  target.useBitmapCoordinateSpace(({ context, horizontalPixelRatio, verticalPixelRatio }) => {
    const { colors } = getThemeStore();

    context.save();

    geometries.forEach(({ label, left, top }) => {
      const bitmapLeft = Math.round(left * horizontalPixelRatio);
      const bitmapTop = Math.round(top * verticalPixelRatio);
      const bitmapWidth = Math.round(label.width * horizontalPixelRatio);
      const bitmapHeight = Math.round(label.height * verticalPixelRatio);

      context.fillStyle = label.style === 'outlined' ? colors.chartBackground : label.color;
      context.fillRect(bitmapLeft, bitmapTop, bitmapWidth, bitmapHeight);

      if (label.style !== 'outlined') {
        return;
      }

      const borderWidth = Math.max(1, Math.floor(Math.min(horizontalPixelRatio, verticalPixelRatio)));

      context.strokeStyle = label.color;
      context.lineWidth = borderWidth;
      context.strokeRect(
        bitmapLeft + borderWidth / 2,
        bitmapTop + borderWidth / 2,
        Math.max(0, bitmapWidth - borderWidth),
        Math.max(0, bitmapHeight - borderWidth),
      );
    });

    context.restore();
  });
}

function drawLabelTexts(
  target: CanvasRenderingTarget2D,
  geometries: LabelGeometry[],
  layout: ChartLayoutOptions,
): void {
  target.useMediaCoordinateSpace(({ context }) => {
    context.save();
    context.font = getFont(layout);
    context.textAlign = 'center';
    context.textBaseline = 'middle';

    geometries.forEach(({ label, textX, textY }) => {
      context.fillStyle = getLabelTextColor(label);
      context.fillText(label.text, textX, textY);
    });

    context.restore();
  });
}

class PriceAxisLabelsRenderer implements IPrimitivePaneRenderer {
  constructor(private readonly state: PriceAxisLabelsRenderState) {}

  public draw(target: CanvasRenderingTarget2D): void {
    const { labels, chart, series, reservedCoordinate } = this.state;
    const layout = chart?.options().layout;

    if (!layout || labels.length === 0) {
      return;
    }

    let geometries: LabelGeometry[] = [];

    target.useMediaCoordinateSpace(({ context, mediaSize }) => {
      if (mediaSize.width <= 0 || mediaSize.height <= 0) {
        return;
      }

      context.save();
      context.font = getFont(layout);

      const measuredLabels = measureLabels(context, labels, layout);

      geometries = createLabelGeometries(
        measuredLabels,
        mediaSize.width,
        mediaSize.height,
        getAxisSideBySeries(series),
        layout,
        reservedCoordinate,
      );

      context.restore();
    });

    if (geometries.length === 0) {
      return;
    }

    drawLabelBackgrounds(target, geometries);
    drawLabelTexts(target, geometries, layout);
  }
}

class PriceAxisLabelsPaneView implements IPrimitivePaneView {
  private readonly rendererInstance: PriceAxisLabelsRenderer;

  constructor(private readonly state: PriceAxisLabelsRenderState) {
    this.rendererInstance = new PriceAxisLabelsRenderer(state);
  }

  public renderer(): IPrimitivePaneRenderer | null {
    return this.state.labels.length > 0 ? this.rendererInstance : null;
  }

  public zOrder(): PrimitivePaneViewZOrder {
    return 'top';
  }
}

export class PriceAxisLabelsPrimitive implements ISeriesPrimitive<Time> {
  private readonly state: PriceAxisLabelsRenderState = {
    labels: [],
    reservedCoordinate: null,
    chart: null,
    series: null,
  };

  private readonly priceAxisPaneView = new PriceAxisLabelsPaneView(this.state);
  private readonly priceAxisPaneViewList: IPrimitivePaneView[] = [this.priceAxisPaneView];
  private requestUpdate: (() => void) | null = null;

  public attached({ chart, series, requestUpdate }: SeriesAttachedParameter<Time>): void {
    this.state.chart = chart;
    this.state.series = series;
    this.requestUpdate = requestUpdate;
    this.requestUpdate();
  }

  public detached(): void {
    this.state.chart = null;
    this.state.series = null;
    this.state.labels = [];
    this.state.reservedCoordinate = null;
    this.requestUpdate = null;
  }

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

  public updateAllViews(): void {}

  public setLabels(labels: PriceAxisLabel[], reservedCoordinate: number | null = null): void {
    if (areLabelsEqual(this.state.labels, labels) && this.state.reservedCoordinate === reservedCoordinate) {
      return;
    }

    this.state.labels = labels;
    this.state.reservedCoordinate = reservedCoordinate;
    this.requestUpdate?.();
  }

  public clear(): void {
    if (this.state.labels.length === 0 && this.state.reservedCoordinate === null) {
      return;
    }

    this.state.labels = [];
    this.state.reservedCoordinate = null;
    this.requestUpdate?.();
  }
}


import { Direction } from '@src/types';

export type PriceAxisLabelStyle = 'filled' | 'outlined';
export type PriceAxisSide = Direction.Left | Direction.Right;

export interface PriceAxisLabel {
  id: string;
  desiredCoordinate: number;
  text: string;
  color: string;
  style: PriceAxisLabelStyle;
  priority: number;
}

export interface MeasuredPriceAxisLabel extends PriceAxisLabel {
  width: number;
  height: number;
}

export interface LaidOutPriceAxisLabel extends MeasuredPriceAxisLabel {
  coordinate: number;
}

export interface PriceAxisLabelsLayoutOptions {
  gap?: number;
  reservedCoordinate?: number;
  reservedHeight?: number;
}



import { SeriesAttachedParameter, Time } from 'lightweight-charts';

import { Direction } from '@src/types';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

import { PriceAxisSide } from './types';

export function getContrastTextColor(color: string): string {
  const hex = removeAlphaFromHex(color).replace('#', '');
  const red = Number.parseInt(hex.slice(0, 2), 16);
  const green = Number.parseInt(hex.slice(2, 4), 16);
  const blue = Number.parseInt(hex.slice(4, 6), 16);
  const brightness = 0.199 * red + 0.687 * green + 0.114 * blue;

  return brightness > 160 ? '#000000' : '#FFFFFF';
}

export function getAxisSideBySeries(series: SeriesAttachedParameter<Time>['series'] | null): PriceAxisSide {
  return series?.options().priceScaleId === Direction.Left ? Direction.Left : Direction.Right;
}


import { IPaneApi, IPriceScaleApi, PriceScaleMode, Time } from 'lightweight-charts';

import type { PriceScaleSide, PriceScaleSnapshot } from '@src/types/snapshot';

interface PriceScaleParams {
  paneId: number;
  side: PriceScaleSide;
  pane: IPaneApi<Time>;
  initialMode?: PriceScaleMode;
  initialVisible: boolean;
  hasVisibleSeriesData: () => boolean;
}

export class PriceScale {
  public readonly paneId: number;
  public readonly side: PriceScaleSide;

  private readonly pane: IPaneApi<Time>;
  private readonly hasVisibleSeriesDataCallback: () => boolean;

  private mode: PriceScaleMode;
  private visible: boolean;

  constructor({
    paneId,
    side,
    pane,
    initialMode = PriceScaleMode.Normal,
    initialVisible,
    hasVisibleSeriesData,
  }: PriceScaleParams) {
    this.paneId = paneId;
    this.side = side;
    this.pane = pane;
    this.mode = initialMode;
    this.visible = initialVisible;
    this.hasVisibleSeriesDataCallback = hasVisibleSeriesData;

    const priceScale = this.getPriceScaleApi();

    priceScale.applyOptions({
      mode: this.mode,
      autoScale: priceScale.options().autoScale ?? true,
      visible: this.visible,
      borderVisible: false,
    });
  }

  public getMode(): PriceScaleMode {
    return this.mode;
  }

  public setMode(mode: PriceScaleMode): void {
    if (this.mode === mode) {
      return;
    }

    this.mode = mode;

    this.getPriceScaleApi().applyOptions({
      mode,
    });
  }

  public toggleLogarithmic(): void {
    const nextMode = this.mode === PriceScaleMode.Logarithmic ? PriceScaleMode.Normal : PriceScaleMode.Logarithmic;

    this.setMode(nextMode);
  }

  public isAutoScaleEnabled(): boolean {
    return this.getPriceScaleApi().options().autoScale ?? true;
  }

  public toggleAutoScale(): void {
    const priceScale = this.getPriceScaleApi();
    const autoScaleEnabled = priceScale.options().autoScale ?? true;

    priceScale.setAutoScale(!autoScaleEnabled);
  }

  public enableAutoScale(): void {
    const priceScale = this.getPriceScaleApi();

    if (priceScale.options().autoScale ?? true) {
      return;
    }

    priceScale.setAutoScale(true);
  }

  public isVisible(): boolean {
    return this.visible;
  }

  public setVisible(visible: boolean): void {
    if (this.visible === visible) {
      return;
    }

    this.visible = visible;

    this.getPriceScaleApi().applyOptions({
      visible,
      borderVisible: false,
    });
  }

  public hasVisibleSeriesData(): boolean {
    return this.hasVisibleSeriesDataCallback();
  }

  public getSnapshot(): PriceScaleSnapshot {
    return {
      side: this.side,
      mode: this.mode,
    };
  }

  private getPriceScaleApi(): IPriceScaleApi {
    return this.pane.priceScale(this.side);
  }
}


import { PriceScaleMode } from 'lightweight-charts';

import { PriceScaleControls as PriceScaleControlsView } from '@components/PriceScaleControls';
import { ReactRenderer } from '@core/ReactRenderer';
import { CHART_PRICE_SCALE_CONTROLS, CHART_PRICE_SCALE_CONTROLS_VISIBLE } from '@src/constants';
import { Direction } from '@src/types';

import { PriceScale } from './PriceScale';

interface PriceScaleControlsParams {
  leftPriceScale: PriceScale;
  rightPriceScale: PriceScale;
  onPriceScaleChange: () => void;
}

interface PriceScaleElements {
  left: HTMLTableCellElement;
  right: HTMLTableCellElement;
}

export class PriceScaleControls {
  private readonly leftPriceScale: PriceScale;
  private readonly rightPriceScale: PriceScale;
  private readonly onPriceScaleChange: () => void;
  private readonly container: HTMLElement;
  private readonly renderer: ReactRenderer;

  private paneElement: HTMLElement | null = null;
  private leftPriceScaleElement: HTMLTableCellElement | null = null;
  private rightPriceScaleElement: HTMLTableCellElement | null = null;
  private hoveredPriceScale: PriceScale | null = null;
  private renderedAutoScaleEnabled: boolean | null = null;

  constructor({ leftPriceScale, rightPriceScale, onPriceScaleChange }: PriceScaleControlsParams) {
    this.leftPriceScale = leftPriceScale;
    this.rightPriceScale = rightPriceScale;
    this.onPriceScaleChange = onPriceScaleChange;

    this.container = document.createElement('div');
    this.container.classList.add(CHART_PRICE_SCALE_CONTROLS);
    this.renderer = new ReactRenderer(this.container);
  }

  public mount(paneElement: HTMLElement): void {
    const priceScaleElements = this.getPriceScaleElements(paneElement);

    if (!priceScaleElements) {
      this.unmount();
      return;
    }

    if (this.paneElement !== paneElement) {
      this.unmount();

      this.paneElement = paneElement;
      this.paneElement.addEventListener('pointermove', this.handlePointerMove);
      this.paneElement.addEventListener('pointerleave', this.handlePointerLeave);
    }

    this.leftPriceScaleElement = priceScaleElements.left;
    this.rightPriceScaleElement = priceScaleElements.right;

    this.leftPriceScaleElement.style.position = 'relative';
    this.rightPriceScaleElement.style.position = 'relative';

    this.refresh();
  }

  public refresh(): void {
    if (!this.hoveredPriceScale) {
      this.hide();
      return;
    }

    this.render(this.hoveredPriceScale);
  }

  public destroy(): void {
    this.unmount();
    this.renderer.destroy();
  }

  private handlePointerMove = (event: PointerEvent): void => {
    const nextPriceScale = this.getHoveredPriceScale(event.clientX);

    if (this.hoveredPriceScale !== nextPriceScale) {
      this.hoveredPriceScale = nextPriceScale;
      this.refresh();
      return;
    }

    if (!nextPriceScale || event.buttons === 0) {
      return;
    }

    const isAutoScaleEnabled = nextPriceScale.isAutoScaleEnabled();

    if (this.renderedAutoScaleEnabled === isAutoScaleEnabled) {
      return;
    }

    this.render(nextPriceScale);
  };

  private handlePointerLeave = (): void => {
    this.hoveredPriceScale = null;
    this.refresh();
  };

  private render(priceScale: PriceScale): void {
    const priceScaleElement = this.getPriceScaleElement(priceScale);

    if (!priceScaleElement || !this.canShowControls(priceScale, priceScaleElement)) {
      this.hide();
      return;
    }

    if (this.container.parentElement !== priceScaleElement) {
      priceScaleElement.appendChild(this.container);
    }

    const isAutoScaleEnabled = priceScale.isAutoScaleEnabled();
    this.renderedAutoScaleEnabled = isAutoScaleEnabled;

    this.renderer.renderComponent(
      <PriceScaleControlsView
        isAutoScale={isAutoScaleEnabled}
        isLogarithmic={priceScale.getMode() === PriceScaleMode.Logarithmic}
        onToggleAutoScale={() => {
          priceScale.toggleAutoScale();
          this.refresh();
          this.onPriceScaleChange();
        }}
        onToggleLogarithmic={() => {
          priceScale.toggleLogarithmic();
          this.refresh();
          this.onPriceScaleChange();
        }}
      />,
    );

    this.container.classList.add(CHART_PRICE_SCALE_CONTROLS_VISIBLE);
  }

  private hide(): void {
    this.renderedAutoScaleEnabled = null;
    this.container.classList.remove(CHART_PRICE_SCALE_CONTROLS_VISIBLE);
  }

  private getHoveredPriceScale(clientX: number): PriceScale | null {
    if (this.isPointerInsidePriceScale(this.leftPriceScale, clientX)) {
      return this.leftPriceScale;
    }

    if (this.isPointerInsidePriceScale(this.rightPriceScale, clientX)) {
      return this.rightPriceScale;
    }

    return null;
  }

  private isPointerInsidePriceScale(priceScale: PriceScale, clientX: number): boolean {
    const priceScaleElement = this.getPriceScaleElement(priceScale);

    if (!priceScaleElement || !this.canShowControls(priceScale, priceScaleElement)) {
      return false;
    }

    const priceScaleRect = priceScaleElement.getBoundingClientRect();

    return clientX >= priceScaleRect.left && clientX <= priceScaleRect.right;
  }

  private canShowControls(priceScale: PriceScale, priceScaleElement: HTMLTableCellElement): boolean {
    return priceScale.isVisible() && priceScale.hasVisibleSeriesData() && priceScaleElement.clientWidth > 0;
  }

  private getPriceScaleElement(priceScale: PriceScale): HTMLTableCellElement | null {
    return priceScale.side === Direction.Left ? this.leftPriceScaleElement : this.rightPriceScaleElement;
  }

  private getPriceScaleElements(paneElement: HTMLElement): PriceScaleElements | null {
    if (paneElement.children.length < 3) {
      return null;
    }

    const leftPriceScaleElement = paneElement.children.item(0);
    const rightPriceScaleElement = paneElement.children.item(paneElement.children.length - 1);

    if (
      !(leftPriceScaleElement instanceof HTMLTableCellElement) ||
      !(rightPriceScaleElement instanceof HTMLTableCellElement)
    ) {
      return null;
    }

    return {
      left: leftPriceScaleElement,
      right: rightPriceScaleElement,
    };
  }

  private unmount(): void {
    if (this.paneElement) {
      this.paneElement.removeEventListener('pointermove', this.handlePointerMove);
      this.paneElement.removeEventListener('pointerleave', this.handlePointerLeave);
    }

    this.paneElement = null;
    this.leftPriceScaleElement = null;
    this.rightPriceScaleElement = null;
    this.hoveredPriceScale = null;

    this.container.remove();
    this.hide();
  }
}



import classNames from 'classnames';
import { Button, Tooltip } from 'exchange-elements/v2';

import { CHART_PRICE_SCALE_CONTROLS_CONTENT } from '@src/constants';
import { t } from '@src/translations';

import styles from './index.module.scss';

import type { SyntheticEvent } from 'react';

interface PriceScaleControlsProps {
  isAutoScale: boolean;
  isLogarithmic: boolean;
  onToggleAutoScale: () => void;
  onToggleLogarithmic: () => void;
}

export function PriceScaleControls({
  isAutoScale,
  isLogarithmic,
  onToggleAutoScale,
  onToggleLogarithmic,
}: PriceScaleControlsProps) {
  const stopPropagation = (event: SyntheticEvent) => {
    event.stopPropagation();
  };

  return (
    <section
      className={classNames(styles.root, CHART_PRICE_SCALE_CONTROLS_CONTENT)}
      onPointerDown={stopPropagation}
      onMouseDown={stopPropagation}
      onClick={stopPropagation}
    >
      <Tooltip
        tooltipClassName={styles.tooltip}
        label={t('AutoScale')}
      >
        <Button
          size="sm"
          className={classNames(styles.button, {
            [styles.pressed]: isAutoScale,
          })}
          onClick={onToggleAutoScale}
          label="A"
        />
      </Tooltip>

      <Tooltip
        tooltipClassName={styles.tooltip}
        label={t('Logarithmic')}
      >
        <Button
          size="sm"
          className={classNames(styles.button, {
            [styles.pressed]: isLogarithmic,
          })}
          onClick={onToggleLogarithmic}
          label="L"
        />
      </Tooltip>
    </section>
  );
}


@use '../../theme/mixins' as m;

.tooltip {
  @include m.tooltipHint;
}

.root {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-0250);
  padding: var(--space-0250);
  background-color: var(--neutral-0);
  pointer-events: none;

  .button {
    @include m.buttonBase;

    min-width: var(--space-1500);
    width: var(--space-1500);
    height: var(--space-1500);
    flex-shrink: 0;
    pointer-events: auto;
  }
}