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


import { type BehaviorSubject, distinctUntilChanged, type Observable, Subscription } from 'rxjs';

import { MAIN_PANE_INDEX } from '@src/constants';

import { type Candle, Direction } from '@src/types';

import { formatPrice, getPricePrecisionStep, isBarData, isLineData, normalizeSeriesData } from '@src/utils';

import type { DataSource } from '@core/DataSource';
import type { Indicator } from '@core/Indicator';
import type { ChartTypeToCandleData, IndicatorDataFormatter } from '@core/Indicators';
import type { Ohlc } from '@core/Legend';
import type { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';

import type {
  BarData,
  BarPrice,
  BarsInfo,
  Coordinate,
  CreatePriceLineOptions,
  CustomData,
  DataChangedHandler,
  DeepPartial,
  HistogramData,
  IChartApi,
  IPaneApi,
  IPriceFormatter,
  IPriceLine,
  IPriceScaleApi,
  IRange,
  ISeriesApi,
  ISeriesPrimitive,
  LineData,
  MismatchDirection,
  MouseEventParams,
  PriceScaleOptions,
  SeriesDataItemTypeMap,
  SeriesDefinition,
  SeriesOptionsMap,
  SeriesPartialOptionsMap,
  SeriesType,
  Time,
} from 'lightweight-charts';

export interface SerieData {
  time: Time;
  customValues: Candle;
}

export interface CreateSeriesParams<TSeries extends SeriesType> {
  chart: IChartApi;
  seriesOptions?: SeriesPartialOptionsMap[TSeries];
  paneIndex?: number;
  priceScaleOptions?: DeepPartial<PriceScaleOptions>;
}

export interface IBaseSeries<TSeries extends SeriesType> extends ISeriesApi<TSeries> {
  getLwcSeries: () => ISeriesApi<TSeries>;
  getLegendData: (param?: MouseEventParams) => Partial<
    Record<
      keyof Ohlc,
      {
        value: number | string | Time;
        color: string;
        name: string;
      }
    >
  >;
}

export interface BaseSeriesParams<TSeries extends SeriesType = SeriesType> {
  lwcChart: IChartApi;
  dataSource: DataSource;
  mainSymbol$: Observable<string>;
  mainSerie$: BehaviorSubject<SeriesStrategies | null>;
  customFormatter?: (params: IndicatorDataFormatter<TSeries>) => SeriesDataItemTypeMap<Time>[TSeries][];
  seriesOptions?: SeriesPartialOptionsMap[TSeries];
  priceScaleOptions?: DeepPartial<PriceScaleOptions>;
  showSymbolLabel?: boolean;
  paneIndex?: number;
  indicatorReference?: Indicator;
}

function applyMoscowTimezone(candles: Candle[]): ChartTypeToCandleData['Candlestick'][] {
  // todo this approach is too slow, for timezones impl we should shift timeScale instead of mutating the data
  const offsetMinutes = -180; // utc.time - moscow.time in minutes
  const secondsInMinute = 60;

  return candles.flatMap((candle) => {
    if (typeof candle.time !== 'number' || !Number.isFinite(candle.time)) {
      return [];
    }

    return [
      {
        ...candle,
        time: candle.time - offsetMinutes * secondsInMinute,
      },
    ];
  });
}

export abstract class BaseSeries<TSeries extends SeriesType> implements IBaseSeries<TSeries> {
  protected lwcSeries: ISeriesApi<TSeries>;

  protected customFormatter:
    | ((params: IndicatorDataFormatter<TSeries>) => SeriesDataItemTypeMap<Time>[TSeries][])
    | undefined;

  protected lwcChart: IChartApi;

  protected mainSymbol$: Observable<string>;

  protected mainSerie$: BehaviorSubject<SeriesStrategies | null>;

  protected paneIndex: number | null = null;

  protected indicatorReference: Indicator | null = null;

  protected showSymbolLabel: boolean;

  private subscriptions = new Subscription();

  private dataSub: Subscription | null = null;

  private realtimeSub: Subscription | null = null;

  constructor({
    lwcChart,
    mainSymbol$,
    mainSerie$,
    customFormatter,
    seriesOptions,
    priceScaleOptions,
    showSymbolLabel = true,
    paneIndex,
    indicatorReference,
  }: BaseSeriesParams<TSeries>) {
    this.lwcSeries = this.createSeries({
      chart: lwcChart,
      seriesOptions,
      paneIndex,
      priceScaleOptions,
    });

    this.lwcChart = lwcChart;
    this.customFormatter = customFormatter;
    this.mainSymbol$ = mainSymbol$;
    this.mainSerie$ = mainSerie$;
    this.showSymbolLabel = showSymbolLabel;
    this.indicatorReference = indicatorReference ?? null;
  }

  public getLegendData = (
    param?: MouseEventParams,
  ): Partial<
    Record<
      keyof Ohlc,
      {
        value: number | string | Time;
        color: string;
        name: string;
      }
    >
  > => {
    if (!param) {
      const seriesData = this.data();
      const currentBar = seriesData.at(-1);

      if (!currentBar) {
        return {};
      }

      return this.formatLegendValues(currentBar, seriesData.at(-2) ?? null);
    }

    const currentBar = param.seriesData.get(this.lwcSeries) ?? null;

    const previousBar = param.logical === null ? null : this.dataByIndex(param.logical! - 1);

    return this.formatLegendValues(currentBar, previousBar);
  };

  public show(): void {
    this.lwcSeries.applyOptions({
      visible: true,
    });
  }

  public hide(): void {
    this.lwcSeries.applyOptions({
      visible: false,
    });
  }

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

  public destroy(): void {
    this.dataSub?.unsubscribe();
    this.realtimeSub?.unsubscribe();
    this.subscriptions.unsubscribe();
    this.lwcChart.removeSeries(this.lwcSeries);
  }

  public getLwcSeries(): ISeriesApi<TSeries> {
    return this.lwcSeries;
  }

  public applyOptions(options: SeriesPartialOptionsMap[TSeries]): void {
    this.lwcSeries.applyOptions(options);
  }

  public attachPrimitive(primitive: ISeriesPrimitive<Time>): void {
    this.lwcSeries.attachPrimitive(primitive);
  }

  public barsInLogicalRange(range: IRange<number>): BarsInfo<Time> | null {
    return this.lwcSeries.barsInLogicalRange(range);
  }

  public coordinateToPrice(coordinate: number): BarPrice | null {
    return this.lwcSeries.coordinateToPrice(coordinate);
  }

  public createPriceLine(options: CreatePriceLineOptions): IPriceLine {
    return this.lwcSeries.createPriceLine(options);
  }

  public data(): readonly SeriesDataItemTypeMap<Time>[TSeries][] {
    return this.lwcSeries.data();
  }

  public dataByIndex(
    logicalIndex: number,
    mismatchDirection?: MismatchDirection,
  ): SeriesDataItemTypeMap<Time>[TSeries] | null {
    return this.lwcSeries.dataByIndex(logicalIndex, mismatchDirection);
  }

  public detachPrimitive(primitive: ISeriesPrimitive<Time>): void {
    this.lwcSeries.detachPrimitive(primitive);
  }

  public getPane(): IPaneApi<Time> {
    return this.lwcSeries.getPane();
  }

  public moveToPane(paneIndex: number): void {
    this.lwcSeries.moveToPane(paneIndex);
  }

  public options(): Readonly<SeriesOptionsMap[TSeries]> {
    return this.lwcSeries.options();
  }

  public priceFormatter(): IPriceFormatter {
    return this.lwcSeries.priceFormatter();
  }

  public priceLines(): IPriceLine[] {
    return this.lwcSeries.priceLines();
  }

  public priceScale(): IPriceScaleApi {
    return this.lwcSeries.priceScale();
  }

  public priceToCoordinate(price: number): Coordinate | null {
    return this.lwcSeries.priceToCoordinate(price);
  }

  public removePriceLine(line: IPriceLine): void {
    this.lwcSeries.removePriceLine(line);
  }

  public seriesOrder(): number {
    return this.lwcSeries.seriesOrder();
  }

  public seriesType(): TSeries {
    return this.lwcSeries.seriesType();
  }

  public setData(data: SeriesDataItemTypeMap<Time>[TSeries][]): void {
    this.lwcSeries.setData(normalizeSeriesData(data));
  }

  public setSeriesOrder(order: number): void {
    this.lwcSeries.setSeriesOrder(order);
  }

  public subscribeDataChanged(handler: DataChangedHandler): void {
    this.lwcSeries.subscribeDataChanged(handler);
  }

  public unsubscribeDataChanged(handler: DataChangedHandler): void {
    this.lwcSeries.unsubscribeDataChanged(handler);
  }

  public update(bar: SeriesDataItemTypeMap<Time>[TSeries], historicalUpdate?: boolean): void {
    const lastBar = this.lwcSeries.data().at(-1);

    if (!lastBar) {
      this.lwcSeries.update(bar, false);

      return;
    }

    const isHistoricalUpdate =
      historicalUpdate ?? (typeof lastBar.time === 'number' && typeof bar.time === 'number' && bar.time < lastBar.time);

    this.lwcSeries.update(bar, isHistoricalUpdate);
  }

  protected createSeries({
    chart,
    seriesOptions,
    paneIndex = MAIN_PANE_INDEX,
    priceScaleOptions = {},
  }: CreateSeriesParams<TSeries>): ISeriesApi<TSeries> {
    this.paneIndex = paneIndex;

    const options = {
      ...this.getDefaultOptions(),
      ...seriesOptions,
    };

    const series = chart.addSeries<TSeries>(this.seriesDefinition(), options, paneIndex);

    chart.priceScale(options.priceScaleId ?? Direction.Right, paneIndex).applyOptions(priceScaleOptions);

    return series;
  }

  protected abstract dataSourceSubscription(next: Candle[]): void;

  protected abstract seriesDefinition(): SeriesDefinition<TSeries>;

  protected abstract dataSourceRealtimeSubscription(next: Candle): void;

  protected abstract getDefaultOptions(): SeriesPartialOptionsMap[TSeries];

  protected abstract formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>[TSeries][];

  protected abstract formatLegendValues(
    currentBar: BarData | LineData | HistogramData | CustomData | null,
    prevBar: BarData | LineData | HistogramData | CustomData | null,
  ): Partial<
    Record<
      keyof Ohlc,
      {
        value: number | string | Time;
        color: string;
        name: string;
      }
    >
  >;

  protected applyTimezone(data: Candle[]): Candle[] {
    return applyMoscowTimezone(data);
  }

  protected formatData(inputData: Candle[]): SeriesDataItemTypeMap<Time>[TSeries][] {
    const data = this.applyTimezone(inputData);

    if (!this.customFormatter) {
      return this.formatMainSerie(data);
    }

    const mainSeriesData = (this.mainSerie$.value?.data() ?? []) as unknown as SerieData[];

    const selfData = this.data() as unknown as ChartTypeToCandleData[TSeries][];

    if (data.length !== 1) {
      return this.customFormatter({
        mainSeriesData,
        selfData,
        indicatorReference: this.indicatorReference ?? undefined,
      });
    }

    const candle = this.formatMainSerie(data)[0];

    if (!candle) {
      return [];
    }

    return this.customFormatter({
      mainSeriesData,
      selfData,
      candle: candle as unknown as SerieData,
      indicatorReference: this.indicatorReference ?? undefined,
    });
  }

  protected subscribeDataSource = (dataSource: DataSource): void => {
    const minMove = getPricePrecisionStep();

    this.subscriptions.add(
      this.mainSymbol$.pipe(distinctUntilChanged()).subscribe((symbol) => {
        this.lwcSeries.applyOptions({
          // todo: на каждый апдейт dataSource сеттим options. Не оптимально
          title: this.showSymbolLabel ? symbol : '',
          priceFormat: {
            type: 'custom',
            minMove,
            formatter: (price: number) => formatPrice(price) ?? String(price),
          },
        });

        this.dataSub?.unsubscribe();
        this.realtimeSub?.unsubscribe();

        this.dataSub = dataSource.subscribe(symbol, (next) => {
          this.dataSourceSubscription(next);
        });

        this.realtimeSub = dataSource.subscribeRealtime(symbol, (next: Candle) => {
          this.dataSourceRealtimeSubscription(next);
        });
      }),
    );
  };
}

export function calcCandleChange(
  prev: BarData | LineData | HistogramData | CustomData | null,
  current: BarData | LineData | HistogramData | CustomData | null,
):
  | (Ohlc & {
      customValues?: Record<string, unknown>;
    })
  | null {
  if (!current) {
    return null;
  }

  if (!prev) {
    return current;
  }

  if (isBarData(prev) && isBarData(current)) {
    const absoluteChange = current.close - prev.close;

    const percentageChange = ((current.close - prev.close) / prev.close) * 100;

    return {
      ...current,
      absoluteChange,
      percentageChange,
    };
  }

  if (isLineData(prev) && isLineData(current)) {
    const absoluteChange = current.value - prev.value;

    const percentageChange = ((current.value - prev.value) / prev.value) * 100;

    const high = current.customValues?.high;
    const low = current.customValues?.low;

    return {
      time: current.time,
      value: current.value,
      high: typeof high === 'number' ? high : current.value,
      low: typeof low === 'number' ? low : current.value,
      absoluteChange,
      percentageChange,
      customValues: current.customValues,
    };
  }

  return null;
}



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 './primitive';

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 PriceAxisLabelsControllerOptions {
  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;
}

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

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 toOpaqueColor(color: string): string {
  return /^#[0-9a-fA-F]{8}$/.test(color) ? removeAlphaFromHex(color) : color;
}

function getSeriesColor(series: SeriesStrategies, data: unknown): string {
  if (data && typeof data === 'object' && 'color' in data && typeof data.color === 'string') {
    return toOpaqueColor(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 toOpaqueColor(options.upColor);
    }

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

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

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

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

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

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

function getContrastTextColor(color: string): string {
  const hex = toOpaqueColor(color).replace('#', '');

  if (hex.length !== 6) {
    return '#FFFFFF';
  }

  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);

  if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
    return '#FFFFFF';
  }

  const brightness = 0.199 * red + 0.687 * green + 0.114 * blue;

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

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

  return source.series.options().priceScaleId === Direction.Left ? Direction.Left : Direction.Right;
}

export class PriceAxisLabelsController {
  private readonly subscriptions = new Subscription();

  private readonly entitySubscriptions = new Map<
    string,
    {
      entity: Indicator;
      subscription: Subscription;
    }
  >();

  private readonly sourceDefaults = new WeakMap<SeriesStrategies, SourceDefaults>();

  private readonly 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$ }: PriceAxisLabelsControllerOptions) {
    this.subscriptions.add(
      mainSymbol$.subscribe((symbol) => {
        this.mainSymbol = symbol.split(':').at(-1) || 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 {
        // Серия могла быть удалена раньше контроллера.
      }
    });

    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 {
      // Серия могла быть удалена раньше контроллера.
    }

    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[] {
    const isVolume = collection === 'indicator' && entity.getType() === IndicatorsIds.Volume;
    const role: SourceRole = collection === 'compare' ? 'compare' : isVolume ? 'volume' : 'indicator';

    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 {
      // Серия могла быть удалена раньше контроллера.
    }
  }

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

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

  private applyDisplayModeToSources(sources: readonly 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 {
        // Серия могла быть удалена раньше контроллера.
      }
    });
  }

  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: readonly 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);
    }

    return source.series.data().at(-1) ?? null;
  }

  private updateAxisLayers(groups: Map<string, AxisLabelsGroup>, sources: readonly 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 {
        // Серия могла быть удалена раньше контроллера.
      }

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

  private getAxisHost(
    paneIndex: number,
    side: PriceAxisSide,
    sources: readonly 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 {
        // Серия могла быть удалена раньше контроллера.
      }
    }

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

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

    return layer;
  }

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

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

      return;
    }

    const lastData = mainSource.series.data().at(-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 price = getDataPrice(this.mainSeries.data().at(-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 {
        // Серия могла быть удалена раньше контроллера.
      }
    }

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

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

    if (mode !== PriceScaleMode.Percentage && mode !== PriceScaleMode.IndexedTo100) {
      return formatPrice(price) ?? series.priceFormatter().format(price);
    }

    const logicalRange = this.visibleLogicalRange;

    if (!logicalRange) {
      return formatPrice(price) ?? series.priceFormatter().format(price);
    }

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

    if (firstVisiblePrice === null || firstVisiblePrice === 0) {
      return formatPrice(price) ?? series.priceFormatter().format(price);
    }

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

    const indexedValue = (price / firstVisiblePrice) * 100;

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



export { PriceAxisLabelsController } from './controller';
export { layoutPriceAxisLabels } from './layout';
export { PriceAxisLabelsPrimitive } from './primitive';

export type {
  LaidOutPriceAxisLabel,
  MeasuredPriceAxisLabel,
  PriceAxisLabel,
  PriceAxisLabelsLayoutOptions,
  PriceAxisLabelStyle,
} from './types';



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

type StackAlignment = 'start' | 'center' | 'end';

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 createLabel(label: MeasuredPriceAxisLabel, coordinate: number): LaidOutPriceAxisLabel {
  return {
    ...label,
    coordinate,
  };
}

function getStackHeight(labels: readonly MeasuredPriceAxisLabel[], gap: number): number {
  const labelsHeight = labels.reduce((height, label) => height + label.height, 0);

  return labelsHeight + gap * Math.max(0, labels.length - 1);
}

function placeStack(labels: readonly MeasuredPriceAxisLabel[], top: number, gap: number): LaidOutPriceAxisLabel[] {
  let currentTop = top;

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

    currentTop += label.height + gap;

    return createLabel(label, coordinate);
  });
}

function placeOverflowingStack(
  labels: readonly MeasuredPriceAxisLabel[],
  minCoordinate: number,
  maxCoordinate: number,
  gap: number,
  alignment: StackAlignment,
): LaidOutPriceAxisLabel[] {
  const stackHeight = getStackHeight(labels, gap);
  const availableHeight = Math.max(0, maxCoordinate - minCoordinate);

  let top = minCoordinate;

  if (alignment === 'end') {
    top = maxCoordinate - stackHeight;
  }

  if (alignment === 'center') {
    top = minCoordinate + (availableHeight - stackHeight) / 2;
  }

  return placeStack(labels, top, gap);
}

function layoutRange(
  labels: readonly MeasuredPriceAxisLabel[],
  minCoordinate: number,
  maxCoordinate: number,
  gap: number,
  overflowAlignment: StackAlignment,
): LaidOutPriceAxisLabel[] {
  const sortedLabels = [...labels].sort(compareLabels);

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

  const availableHeight = Math.max(0, maxCoordinate - minCoordinate);
  const stackHeight = getStackHeight(sortedLabels, gap);

  if (stackHeight > availableHeight) {
    return placeOverflowingStack(sortedLabels, minCoordinate, maxCoordinate, gap, overflowAlignment);
  }

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

    return createLabel(label, coordinate);
  });

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

    const minimumCoordinate = previousLabel.coordinate + previousLabel.height / 2 + currentLabel.height / 2 + gap;

    currentLabel.coordinate = Math.max(currentLabel.coordinate, minimumCoordinate);
  }

  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];

    const maximumCoordinate = nextLabel.coordinate - nextLabel.height / 2 - currentLabel.height / 2 - gap;

    currentLabel.coordinate = Math.min(currentLabel.coordinate, maximumCoordinate);
  }

  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: readonly MeasuredPriceAxisLabel[],
  axisHeight: number,
  options: PriceAxisLabelsLayoutOptions = {},
): LaidOutPriceAxisLabel[] {
  if (axisHeight <= 0 || labels.length === 0) {
    return [];
  }

  const gap = options.gap ?? DEFAULT_GAP;
  const validLabels = labels.filter((label) => Number.isFinite(label.desiredCoordinate));

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

  const reservedCoordinate = Math.min(Math.max(options.reservedCoordinate, 0), axisHeight);

  const reservedHeight = Math.max(0, options.reservedHeight);

  const reservedTop = reservedCoordinate - reservedHeight / 2;

  const reservedBottom = reservedCoordinate + reservedHeight / 2;

  const labelsAbove = validLabels.filter((label) => label.desiredCoordinate <= reservedCoordinate);

  const labelsBelow = validLabels.filter((label) => label.desiredCoordinate > reservedCoordinate);

  const result = [
    ...layoutRange(labelsAbove, 0, reservedTop - gap, gap, 'end'),
    ...layoutRange(labelsBelow, reservedBottom + gap, axisHeight, gap, 'start'),
  ];

  return result.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 { layoutPriceAxisLabels } from './layout';

import type { LaidOutPriceAxisLabel, MeasuredPriceAxisLabel, PriceAxisLabel } from './types';
import type { CanvasRenderingTarget2D } from 'fancy-canvas';
import type {
  ChartOptions,
  IPrimitivePaneRenderer,
  IPrimitivePaneView,
  ISeriesPrimitive,
  PrimitivePaneViewZOrder,
  SeriesAttachedParameter,
  Time,
} from 'lightweight-charts';

type PriceAxisSide = 'left' | 'right';
type ChartLayoutOptions = Readonly<ChartOptions['layout']>;

interface MeasuredLabel extends MeasuredPriceAxisLabel {
  width: number;
}

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

const HORIZONTAL_PADDING_RATIO = 7.25 / 12;
const VERTICAL_PADDING_RATIO = 3 / 12;
const TEXT_VERTICAL_OFFSET_RATIO = 1 / 12;
const LABEL_EDGE_GAP = 1;
const CONTRAST_THRESHOLD = 160;

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

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

  const hex = label.color.replace('#', '').slice(0, 6);

  if (hex.length !== 6) {
    return '#FFFFFF';
  }

  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);

  if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
    return '#FFFFFF';
  }

  const brightness = 0.199 * red + 0.687 * green + 0.114 * blue;

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

function areLabelsEqual(currentLabels: readonly PriceAxisLabel[], nextLabels: readonly PriceAxisLabel[]): boolean {
  if (currentLabels.length !== nextLabels.length) {
    return false;
  }

  return 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: readonly PriceAxisLabel[],
  layout: ChartLayoutOptions,
): MeasuredLabel[] {
  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 measuredTextHeight = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent;

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

function createLabelGeometries(
  labels: readonly MeasuredLabel[],
  axisWidth: number,
  axisHeight: number,
  side: PriceAxisSide,
  layout: ChartLayoutOptions,
  reservedCoordinate: number | null,
): LabelGeometry[] {
  const labelsById = new Map<string, MeasuredLabel>();

  labels.forEach((label) => {
    labelsById.set(label.id, label);
  });

  const reservedHeight = labels.reduce(
    (maximumHeight, label) => Math.max(maximumHeight, label.height),
    layout.fontSize + layout.fontSize * VERTICAL_PADDING_RATIO * 2,
  );

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

  return laidOutLabels.flatMap((label) => {
    const measuredLabel = labelsById.get(label.id);

    if (!measuredLabel) {
      return [];
    }

    const left =
      side === 'right' ? LABEL_EDGE_GAP : Math.max(LABEL_EDGE_GAP, axisWidth - measuredLabel.width - LABEL_EDGE_GAP);

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

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

    context.save();

    geometries.forEach(({ label, left, top, width }) => {
      const bitmapLeft = Math.round(left * horizontalPixelRatio);
      const bitmapTop = Math.round(top * verticalPixelRatio);
      const bitmapWidth = Math.round(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: readonly 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 getLabels: () => readonly PriceAxisLabel[],
    private readonly getLayout: () => ChartLayoutOptions | null,
    private readonly getSide: () => PriceAxisSide,
    private readonly getReservedCoordinate: () => number | null,
    private readonly setMinimumWidth: (width: number) => void,
  ) {}

  public draw(target: CanvasRenderingTarget2D): void {
    const labels = this.getLabels();
    const layout = this.getLayout();

    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);

      this.setMinimumWidth(
        measuredLabels.reduce((maximumWidth, label) => Math.max(maximumWidth, label.width + LABEL_EDGE_GAP * 2), 0),
      );

      geometries = createLabelGeometries(
        measuredLabels,
        mediaSize.width,
        mediaSize.height,
        this.getSide(),
        layout,
        this.getReservedCoordinate(),
      );

      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 getLabels: () => readonly PriceAxisLabel[],
    getLayout: () => ChartLayoutOptions | null,
    getSide: () => PriceAxisSide,
    getReservedCoordinate: () => number | null,
    setMinimumWidth: (width: number) => void,
  ) {
    this.rendererInstance = new PriceAxisLabelsRenderer(
      getLabels,
      getLayout,
      getSide,
      getReservedCoordinate,
      setMinimumWidth,
    );
  }

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

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

export class PriceAxisLabelsPrimitive implements ISeriesPrimitive<Time> {
  private readonly priceAxisPaneView: PriceAxisLabelsPaneView;

  private readonly priceAxisPaneViewList: readonly IPrimitivePaneView[];

  private labels: readonly PriceAxisLabel[] = [];

  private reservedCoordinate: number | null = null;

  private chart: SeriesAttachedParameter<Time>['chart'] | null = null;

  private series: SeriesAttachedParameter<Time>['series'] | null = null;

  private requestUpdate: (() => void) | null = null;

  private initialMinimumWidth = 0;

  private minimumWidth = 0;

  private pendingMinimumWidth: number | null = null;

  private minimumWidthFrame: number | null = null;

  constructor() {
    this.priceAxisPaneView = new PriceAxisLabelsPaneView(
      () => this.labels,
      () => this.chart?.options().layout ?? null,
      () => (this.series?.options().priceScaleId === 'left' ? 'left' : 'right'),
      () => this.reservedCoordinate,
      (width) => {
        this.scheduleMinimumWidth(width);
      },
    );

    this.priceAxisPaneViewList = [this.priceAxisPaneView];
  }

  public attached({ chart, series, requestUpdate }: SeriesAttachedParameter<Time>): void {
    this.chart = chart;
    this.series = series;
    this.requestUpdate = requestUpdate;
    this.initialMinimumWidth = series.priceScale().options().minimumWidth ?? 0;
    this.minimumWidth = this.initialMinimumWidth;
    this.requestUpdate();
  }

  public detached(): void {
    this.cancelMinimumWidthUpdate();
    this.applyMinimumWidth(this.initialMinimumWidth);

    this.chart = null;
    this.series = null;
    this.requestUpdate = null;
    this.labels = [];
    this.reservedCoordinate = null;
    this.initialMinimumWidth = 0;
    this.minimumWidth = 0;
  }

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

  public updateAllViews(): void {}

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

    this.labels = labels;
    this.reservedCoordinate = reservedCoordinate;

    if (labels.length === 0) {
      this.scheduleMinimumWidth(0);
    }

    this.requestUpdate?.();
  }

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

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

  private scheduleMinimumWidth(width: number): void {
    const minimumWidth = Math.max(this.initialMinimumWidth, Math.ceil(width));

    if (minimumWidth === this.minimumWidth || minimumWidth === this.pendingMinimumWidth) {
      return;
    }

    this.pendingMinimumWidth = minimumWidth;

    if (this.minimumWidthFrame !== null) {
      return;
    }

    this.minimumWidthFrame = requestAnimationFrame(() => {
      this.minimumWidthFrame = null;

      if (this.pendingMinimumWidth !== null) {
        this.applyMinimumWidth(this.pendingMinimumWidth);
      }

      this.pendingMinimumWidth = null;
    });
  }

  private applyMinimumWidth(minimumWidth: number): void {
    if (!this.series || minimumWidth === this.minimumWidth) {
      return;
    }

    this.series.priceScale().applyOptions({
      minimumWidth,
    });

    this.minimumWidth = minimumWidth;
  }

  private cancelMinimumWidthUpdate(): void {
    if (this.minimumWidthFrame === null) {
      return;
    }

    cancelAnimationFrame(this.minimumWidthFrame);
    this.minimumWidthFrame = null;
    this.pendingMinimumWidth = null;
  }
}


export type PriceAxisLabelStyle = 'filled' | 'outlined';

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

export interface MeasuredPriceAxisLabel extends PriceAxisLabel {
  height: number;
}

export interface LaidOutPriceAxisLabel extends MeasuredPriceAxisLabel {
  coordinate: number;
}

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