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


import { IChartApi, PriceScaleMode, SeriesType } from 'lightweight-charts';

import { flatten } from 'lodash-es';
import { BehaviorSubject, distinctUntilChanged, map, Observable, of, Subscription } from 'rxjs';

import { DataSource } from '@core/DataSource';
import { EventManager } from '@core/EventManager';
import { Indicator } from '@core/Indicator';
import { IndicatorManager } from '@core/IndicatorManager';
import { PaneManager } from '@core/PaneManager';
import { PriceScale } from '@core/PriceScale';
import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { CompareItem, CompareMode, Direction, IndicatorConfig, SymbolInfo, SymbolInfoInput } from '@src/types';
import { CompareSnapshot } from '@src/types/snapshot';
import { createFallbackColor, normalizeColor, normalizeSymbol, normalizeSymbolInfo } from '@src/utils';

interface CompareEntry extends CompareItem {
  key: string;
  entity: Indicator;
}

interface CompareManagerParams {
  chart: IChartApi;
  eventManager: EventManager;
  dataSource: DataSource;
  indicatorManager: IndicatorManager;
  paneManager: PaneManager;
  initialIndicators?: CompareSnapshot[];
}

export class CompareManager {
  private readonly chart: IChartApi;
  private readonly eventManager: EventManager;
  private readonly dataSource: DataSource;
  private readonly indicatorManager: IndicatorManager;
  private readonly paneManager: PaneManager;
  private readonly entries = new Map<string, CompareEntry>();
  private readonly itemsSubject = new BehaviorSubject<CompareItem[]>([]);
  private readonly entitiesSubject = new BehaviorSubject<Indicator[]>([]);
  private readonly subscriptions = new Subscription();

  private percentageComparisonActive = false;
  private restoringInitialIndicators = false;

  constructor({
    chart,
    eventManager,
    dataSource,
    indicatorManager,
    paneManager,
    initialIndicators = [],
  }: CompareManagerParams) {
    this.chart = chart;
    this.eventManager = eventManager;
    this.dataSource = dataSource;
    this.indicatorManager = indicatorManager;
    this.paneManager = paneManager;

    this.subscriptions.add(
      this.eventManager.timeframe().subscribe(() => {
        this.applyPolicy();
      }),
    );

    this.setup(initialIndicators);
  }

  public itemsObs(): Observable<CompareItem[]> {
    return this.itemsSubject.asObservable();
  }

  public entities(): Observable<Indicator[]> {
    return this.entitiesSubject.asObservable();
  }

  public clear(): void {
    const keys = Array.from(this.entries.keys());

    for (let index = 0; index < keys.length; index += 1) {
      this.removeEntry(keys[index]);
    }

    this.commitEntriesChange();
  }

  public async setSymbolMode(
    seriesType: SeriesType,
    symbolInfoInput: SymbolInfoInput,
    mode: CompareMode,
    paneId?: number,
  ): Promise<void> {
    const symbolInfo = normalizeSymbolInfo(symbolInfoInput);

    if (!symbolInfo) {
      return;
    }

    const { symbolId, symbol, symbolName } = symbolInfo;

    if (mode === CompareMode.NewScale && this.isNewScaleDisabled() && !this.restoringInitialIndicators) {
      return;
    }

    const key = makeKey(symbolId, mode);

    if (this.entries.has(key)) {
      return;
    }

    const entity = this.indicatorManager.addEntity<Indicator>((zIndex, moveUp, moveDown) => {
      const usedColorsByCompare = this.entitiesSubject.value.map(
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        (indicator) => indicator.getConfig().series?.[0]?.seriesOptions?.color,
      );

      const existingIndicators = Array.from(this.indicatorManager.getIndicators().value.values());

      const usedColorsByIndicatorsRaw = existingIndicators.map((indicator) =>
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        indicator.config?.series?.map((series) => series.seriesOptions?.color),
      );

      const usedColorsByIndicators = flatten(usedColorsByIndicatorsRaw).filter((color) => color !== undefined);
      const usedColors = usedColorsByCompare.concat(usedColorsByIndicators);

      const config = getDefaultCompareIndicatorConfig(symbolInfo, usedColors);

      const associatedPane =
        mode === CompareMode.NewPane
          ? paneId !== undefined
            ? (this.paneManager.getPaneById(paneId) ?? this.paneManager.addPane())
            : this.paneManager.addPane()
          : this.paneManager.getMainPane();

      return new Indicator({
        id: key,
        lwcChart: this.chart,
        mainSymbolId$: of(symbolId),
        mainSymbol$: of(symbol),
        dataSource: this.dataSource,
        associatedPane,
        config: {
          ...config,
          series: [
            {
              ...config.series[0],
              actLikeMainSerie: true,
              seriesOptions: {
                ...config.series[0]?.seriesOptions,
                priceScaleId: mode === CompareMode.NewScale ? Direction.Left : Direction.Right,
              },
            },
          ],
          newPane: mode === CompareMode.NewPane,
        },
        zIndex,
        onDelete: () => {
          if (this.removeEntry(key)) {
            this.commitEntriesChange();
          }
        },
        moveUp,
        moveDown,
        paneId: associatedPane.getId(),
      });
    });

    this.entries.set(key, {
      key,
      symbolId,
      symbol,
      symbolName,
      mode,
      entity,
    });

    this.commitEntriesChange();

    await this.dataSource.isReady(symbolId);
  }

  public removeSymbolMode(symbolIdRaw: string, mode: CompareMode): void {
    const symbolId = normalizeSymbol(symbolIdRaw);

    if (!symbolId) {
      return;
    }

    if (this.removeEntry(makeKey(symbolId, mode))) {
      this.commitEntriesChange();
    }
  }

  public removeSymbol(symbolIdRaw: string): void {
    const symbolId = normalizeSymbol(symbolIdRaw);

    if (!symbolId) {
      return;
    }

    const entries = Array.from(this.entries.entries());
    let removed = false;

    for (let index = 0; index < entries.length; index += 1) {
      const [key, entry] = entries[index];

      if (entry.symbolId !== symbolId) {
        continue;
      }

      removed = this.removeEntry(key) || removed;
    }

    if (removed) {
      this.commitEntriesChange();
    }
  }

  public isNewScaleDisabled(): boolean {
    return this.itemsSubject.value.length > 0;
  }

  public isNewScaleDisabledObservable(): Observable<boolean> {
    return this.itemsSubject.pipe(
      map((items) => items.length > 0),
      distinctUntilChanged(),
    );
  }

  public getAllEntities() {
    return Array.from(this.entries.values()).map(({ symbolId, symbol, symbolName, entity, mode }) => ({
      symbolId,
      symbol,
      symbolName,
      entity,
      mode,
    }));
  }

  public destroy(): void {
    this.subscriptions.unsubscribe();
    this.clear();
    this.itemsSubject.complete();
    this.entitiesSubject.complete();
  }

  private setup = async (compareIndicators: CompareSnapshot[]): Promise<void> => {
    this.restoringInitialIndicators = true;

    try {
      for (const compareIndicator of compareIndicators) {
        const { scale, symbolInfo, seriesName, paneId } = compareIndicator;

        const symbolInfoNormalized = normalizeSymbolInfo(symbolInfo);

        if (!symbolInfoNormalized) {
          continue;
        }

        if (this.paneManager.getMainPane().getId() !== paneId && scale === Direction.Left) {
          throw new Error('[CompareManager]: несколько шкал на второстеменном пейне не поддерживаются');
        }

        const compareMode =
          scale === Direction.Left
            ? CompareMode.NewScale
            : this.paneManager.getMainPane().getId() === paneId
              ? CompareMode.Percentage
              : CompareMode.NewPane;

        // eslint-disable-next-line no-await-in-loop
        await this.setSymbolMode(seriesName, symbolInfoNormalized, compareMode, paneId!);
      }
    } finally {
      this.restoringInitialIndicators = false;
    }
  };

  private removeEntry(key: string): boolean {
    const entry = this.entries.get(key);

    if (!entry) {
      return false;
    }

    this.entries.delete(key);
    this.indicatorManager.removeEntity(entry.entity);
    entry.entity.destroy();

    return true;
  }

  private commitEntriesChange(): void {
    this.applyPolicy();
    this.publish();
  }

  private publish(): void {
    const entries = Array.from(this.entries.values());

    this.itemsSubject.next(
      entries.map(({ symbolId, symbol, symbolName, mode }) => ({
        symbolId,
        symbol,
        symbolName,
        mode,
      })),
    );

    this.entitiesSubject.next(entries.map(({ entity }) => entity));
  }

  private syncPercentageMode(priceScale: PriceScale, shouldEnablePercentageMode: boolean): void {
    if (this.restoringInitialIndicators) {
      this.percentageComparisonActive = shouldEnablePercentageMode;
      return;
    }

    if (this.percentageComparisonActive === shouldEnablePercentageMode) {
      return;
    }

    this.percentageComparisonActive = shouldEnablePercentageMode;

    if (shouldEnablePercentageMode) {
      priceScale.setMode(PriceScaleMode.Percentage);
      return;
    }

    if (priceScale.getMode() === PriceScaleMode.Percentage) {
      priceScale.setMode(PriceScaleMode.Normal);
    }
  }

  private applyPolicy(): void {
    const entries = Array.from(this.entries.values());

    let percentageComparisonActive = false;
    let newScaleComparisonActive = false;

    for (let index = 0; index < entries.length; index += 1) {
      if (entries[index].mode === CompareMode.Percentage) {
        percentageComparisonActive = true;
      }

      if (entries[index].mode === CompareMode.NewScale) {
        newScaleComparisonActive = true;
      }
    }

    for (let index = 0; index < entries.length; index += 1) {
      const entry = entries[index];
      const pane = entry.entity.getPane();

      // [0 - в индикаторах compare сущности может быть только одна серия] [1 - entry]
      const series = Array.from(entry.entity.getSeriesMap().values())[0];

      if (!series) {
        continue;
      }

      series.applyOptions({
        priceScaleId: pane.isMainPane() && entry.mode === CompareMode.NewScale ? Direction.Left : Direction.Right,
      });
    }

    this.paneManager.setPriceScaleSideVisible(Direction.Left, newScaleComparisonActive);
    this.paneManager.setPriceScaleSideVisible(Direction.Right, true);

    const mainRightPriceScale = this.paneManager.getMainPane().getPriceScale(Direction.Right);

    this.syncPercentageMode(mainRightPriceScale, percentageComparisonActive);

    this.paneManager.invalidate();
  }
}

function makeKey(symbolId: string, mode: CompareMode): string {
  return `${symbolId}|${mode}`;
}

function getPaletteColorFromIndex(usedColors: Set<string>, startIndex: number): string {
  for (let offset = 0; offset < COMPARE_COLOR_PALETTE.length; offset += 1) {
    const color = COMPARE_COLOR_PALETTE[(startIndex + offset) % COMPARE_COLOR_PALETTE.length];

    if (!usedColors.has(normalizeColor(color))) {
      return color;
    }
  }

  return createFallbackColor(usedColors.size);
}

function getDefaultCompareIndicatorConfig(symbolInfo: SymbolInfo, usedColors: string[]): IndicatorConfig {
  const reservedColors = new Set(usedColors.map(normalizeColor));

  return {
    symbolInfo,
    newPane: true,
    label: symbolInfo.symbolName,
    series: [
      {
        name: 'Line', // todo: change with enum
        id: `compare-${crypto.randomUUID()}`,
        seriesOptions: {
          visible: true,
          color: getPaletteColorFromIndex(reservedColors, 0),
        },
      },
    ],
  };
}


import dayjs from 'dayjs';

import {
  BarPrice,
  ChartOptions,
  createChart,
  CrosshairMode,
  DeepPartial,
  IChartApi,
  IRange,
  LocalizationOptionsBase,
  LogicalRange,
  Time,
  UTCTimestamp,
} from 'lightweight-charts';

import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs';
import { map, withLatestFrom } from 'rxjs/operators';

import { ChartMouseEvents } from '@core/ChartMouseEvents';
import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { DrawingsManagerCollection } from '@core/DrawingsManagerCollection';
import { EventManager } from '@core/EventManager';
import { Hotkeys } from '@core/Hotkeys';
import { IndicatorManager } from '@core/IndicatorManager';
import { ModalRenderer } from '@core/ModalRenderer';
import { PaneManager } from '@core/PaneManager';
import { CompareManager } from '@src/core/CompareManager';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { getThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { getLocale } from '@src/translations';
import {
  Candle,
  ChartOptionsModel,
  ChartSeriesType,
  ChartTypeOptions,
  Direction,
  OHLCConfig,
  TooltipConfig,
} from '@src/types';
import { Defaults } from '@src/types/defaults';
import { DayjsOffset, Intervals, intervalsToDayjs } from '@src/types/intervals';
import { ChartSnapshot, CompareSnapshot, IndicatorSnapshot, ISerializable, PaneSnapshot } from '@src/types/snapshot';
import { formatCompactNumber } from '@src/utils';
import { createTickMarkFormatter, formatDate } from '@src/utils/formatter';

export interface ChartConfig extends Partial<ChartOptionsModel> {
  container: HTMLElement;
  seriesTypes: ChartSeriesType[];
  theme: ThemeKey;
  mode?: ThemeMode;
  chartOptions?: ChartTypeOptions;
  localization?: LocalizationOptionsBase;
}

export enum Resize {
  Shrink,
  Expand,
}

const HISTORY_LOAD_THRESHOLD = 500;

interface ChartParams {
  params: {
    dataSource: DataSource;
    eventManager: EventManager;
    modalRenderer: ModalRenderer;
    ohlcConfig: OHLCConfig;
    tooltipConfig: TooltipConfig;
    panes: PaneSnapshot[];
    hotkeys: Hotkeys;
  };
  lwcChartConfig: ChartConfig;
}

function splitIndicatorSnapshots(panes: PaneSnapshot[]): {
  compareSnapshots: CompareSnapshot[];
  indicatorSnapshots: IndicatorSnapshot[];
} {
  const snapshots = panes.flatMap(({ id, indicators }) =>
    indicators.map((indicator) => ({
      ...indicator,
      paneId: id,
    })),
  );

  function isIndicatorSnapshot(
    input: (IndicatorSnapshot | CompareSnapshot) & { indicatorType?: unknown },
  ): input is IndicatorSnapshot {
    return input.indicatorType !== undefined;
  }
  function isCompareSnapshot(
    input: (IndicatorSnapshot | CompareSnapshot) & { indicatorType?: unknown },
  ): input is CompareSnapshot {
    return input.indicatorType === undefined;
  }

  return {
    indicatorSnapshots: snapshots.filter((x) => isIndicatorSnapshot(x)),
    compareSnapshots: snapshots.filter((x) => isCompareSnapshot(x)),
  };
}

/**
 * Абстракция над библиотекой для построения графиков
 */
export class Chart implements ISerializable<ChartSnapshot> {
  private lwcChart!: IChartApi;
  private container: HTMLElement;
  private eventManager: EventManager;
  private paneManager!: PaneManager;
  private compareManager: CompareManager;
  private mouseEvents: ChartMouseEvents;
  private indicatorManager: IndicatorManager;
  private optionsSubscription: Subscription;
  private dataSource: DataSource;
  private chartConfig: ChartConfig;
  private mainSeries: BehaviorSubject<SeriesStrategies | null>; // Main Series. Exists in a single copy
  private DOM: DOMModel;

  private isPointerDown = false;
  private didResetOnDrag = false;

  private subscriptions = new Subscription();

  private currentInterval: Intervals | null = null;

  private activeSymbolIds: string[] = [];

  private historyBatchRunning = false;

  constructor({ params, lwcChartConfig }: ChartParams) {
    const { eventManager, dataSource, modalRenderer, ohlcConfig, tooltipConfig, panes: panesSnapshot } = params;

    this.eventManager = eventManager;
    this.dataSource = dataSource;
    this.container = lwcChartConfig.container;
    this.chartConfig = lwcChartConfig;

    this.lwcChart = createChart(this.container, getOptions(lwcChartConfig));

    this.optionsSubscription = this.eventManager
      .getChartOptionsModel()
      .subscribe(({ dateFormat, timeFormat, showTime }) => {
        this.chartConfig = {
          ...this.chartConfig,
          dateFormat,
          timeFormat,
          showTime,
        };

        this.lwcChart.applyOptions({
          ...getOptions(this.chartConfig),
          localization: {
            timeFormatter: (time: UTCTimestamp) => formatDate(time, dateFormat, timeFormat, showTime),
          },
        });
      });

    this.subscriptions.add(this.optionsSubscription);

    this.mouseEvents = new ChartMouseEvents({
      lwcChart: this.lwcChart,
      container: this.container,
    });

    this.mouseEvents.subscribe('wheel', this.onWheel);
    this.mouseEvents.subscribe('pointerDown', this.onPointerDown);
    this.mouseEvents.subscribe('pointerMove', this.onPointerMove);
    this.mouseEvents.subscribe('pointerUp', this.onPointerUp);
    this.mouseEvents.subscribe('pointerCancel', this.onPointerUp);

    this.DOM = new DOMModel({
      modalRenderer,
    });

    this.paneManager = new PaneManager({
      eventManager: this.eventManager,
      panesSnapshot,
      lwcChart: this.lwcChart,
      dataSource,
      DOM: this.DOM,
      ohlcConfig,
      subscribeChartEvent: this.subscribeChartEvent,
      chartContainer: this.container,
      tooltipConfig,
      modalRenderer,
      hotkeys: params.hotkeys,
    });

    this.mainSeries = this.paneManager.getMainPane().getMainSerie();

    const { indicatorSnapshots, compareSnapshots } = splitIndicatorSnapshots(panesSnapshot);

    this.indicatorManager = new IndicatorManager({
      lwcChart: this.lwcChart,
      eventManager,
      dataSource: this.dataSource,
      paneManager: this.paneManager,

      initialIndicators: indicatorSnapshots,
      DOM: this.DOM,
      chartOptions: lwcChartConfig.chartOptions,
    });

    this.compareManager = new CompareManager({
      chart: this.lwcChart,
      eventManager,
      dataSource: this.dataSource,
      paneManager: this.paneManager,

      initialIndicators: compareSnapshots,
      indicatorManager: this.indicatorManager,
    });

    this.paneManager.start({
      compareEntities$: this.compareManager.entities(),
      indicatorEntities$: this.indicatorManager.entities(),
    });

    this.paneManager.setVisibleLogicalRange(this.lwcChart.timeScale().getVisibleLogicalRange());
    this.paneManager.invalidate();

    this.setupDataSourceSubs();
    this.setupHistoricalDataLoading();
  }

  public getPriceScaleWidth(direction: Direction): number {
    try {
      const priceScale = this.lwcChart.priceScale(direction);

      return priceScale ? priceScale.width() : 0;
    } catch {
      return 0;
    }
  }

  public getDrawingsCollectionManager = (): DrawingsManagerCollection => {
    return this.paneManager.getDrawingsCollectionManager();
  };

  public getIndicatorManager = (): IndicatorManager => {
    return this.indicatorManager;
  };

  private onWheel = () => {
    this.eventManager.resetInterval({
      history: false,
    });
  };

  private onPointerDown = () => {
    this.isPointerDown = true;
    this.didResetOnDrag = false;
  };

  private onPointerMove = () => {
    if (!this.isPointerDown) return;
    if (this.didResetOnDrag) return;

    this.didResetOnDrag = true;

    this.eventManager.resetInterval({
      history: false,
    });
  };

  private onPointerUp = () => {
    this.isPointerDown = false;
  };

  public getDom(): DOMModel {
    return this.DOM;
  }

  public getMainSeries(): Observable<SeriesStrategies | null> {
    return this.mainSeries.asObservable();
  }

  public getCompareManager(): CompareManager {
    return this.compareManager;
  }

  public updateTheme(theme: ThemeKey, mode: ThemeMode) {
    this.chartConfig = {
      ...this.chartConfig,
      theme,
      mode,
    };

    this.lwcChart.applyOptions(getOptions(this.chartConfig));

    this.paneManager.invalidate();
  }

  public destroy(): void {
    this.subscriptions.unsubscribe();
    this.mouseEvents.destroy();
    this.compareManager.destroy();
    this.paneManager.destroy();
    this.lwcChart.remove();
  }

  public subscribeChartEvent: ChartMouseEvents['subscribe'] = (event, callback) =>
    this.mouseEvents.subscribe(event, callback);

  public unsubscribeChartEvent: ChartMouseEvents['unsubscribe'] = (event, callback) => {
    this.mouseEvents.unsubscribe(event, callback);
  };

  // todo: add/move to undo/redo model(eventManager)
  public scrollTimeScale = (direction: Direction) => {
    this.eventManager.resetInterval({
      history: false,
    });

    const diff = direction === Direction.Left ? -2 : 2;
    const currentPosition = this.lwcChart.timeScale().scrollPosition();
    this.lwcChart.timeScale().scrollToPosition(currentPosition + diff, false);
  };

  // todo: add/move to undo/redo model(eventManager)
  public zoomTimeScale = (resize: Resize) => {
    this.eventManager.resetInterval({
      history: false,
    });

    const diff = resize === Resize.Shrink ? -1 : 1;

    const currentRange = this.lwcChart.timeScale().getVisibleRange();

    if (!currentRange) return;

    const { from, to } = currentRange as IRange<number>;

    if (!from || !to) return;

    const next: IRange<Time> = {
      from: (from + (to - from) * 0.1 * diff) as Time,
      to: to as Time,
    };

    this.lwcChart.timeScale().setVisibleRange(next);
  };

  // todo: add to undo/redo model(eventManager)
  public resetZoom = () => {
    this.eventManager.resetInterval({
      history: false,
    });

    this.lwcChart.timeScale().resetTimeScale();

    this.paneManager.resetPriceScalesAutoScale();
  };

  public getRealtimeApi() {
    return {
      getTimeframe: () => this.eventManager.getTimeframe(),
      getSymbols: () => this.activeSymbolIds,
      update: (symbolId: string, candle: Candle) => {
        this.dataSource.updateRealtime(symbolId, candle);
      },
    };
  }

  public getSnapshot(): ChartSnapshot {
    const { seriesSelected, timeframe, dateFormat, timeFormat, interval, symbolInfo } =
      this.eventManager.exportChartSettings();

    return {
      panes: this.paneManager.getSnapshot(),
      chartSeriesType: seriesSelected,
      timeframe,
      dateFormat,
      timeFormat,
      interval,
      ...symbolInfo,
    };
  }

  private scheduleHistoryBatch = () => {
    if (this.historyBatchRunning) return;

    this.historyBatchRunning = true;

    requestAnimationFrame(() => {
      const symbolIds = this.activeSymbolIds.slice();

      Promise.all(symbolIds.map((symbolId) => this.dataSource.loadMoreHistory(symbolId))).finally(() => {
        this.historyBatchRunning = false;

        const range = this.lwcChart.timeScale().getVisibleLogicalRange();

        if (range && range.from < HISTORY_LOAD_THRESHOLD) {
          this.scheduleHistoryBatch();
        }
      });
    });
  };

  private setupDataSourceSubs(): void {
    const getWarmupFrom = (): number => {
      if (this.currentInterval && this.currentInterval !== Intervals.All) {
        return getIntervalRange(this.currentInterval).from;
      }

      const range = this.lwcChart.timeScale().getVisibleRange();

      if (!range) return 0;

      const { from } = range as IRange<number>;

      return from;
    };

    const warmupSymbolIds = (symbolIds: string[]): void => {
      const from = getWarmupFrom();

      if (!from) return;

      Promise.all(symbolIds.map((symbolId) => this.dataSource.loadTill(symbolId, from))).catch((error) => {
        console.error('[Chart] Ошибка при прогреве символов:', error);
      });
    };

    const symbolIds$ = combineLatest([this.eventManager.symbolId(), this.compareManager.itemsObs()]).pipe(
      map(([mainSymbolId, items]) => Array.from(new Set([mainSymbolId, ...items.map(({ symbolId }) => symbolId)]))),
    );

    this.subscriptions.add(
      this.eventManager
        .getInterval()
        .pipe(withLatestFrom(symbolIds$))
        .subscribe(([interval, symbolIds]) => {
          this.currentInterval = interval;

          if (!interval) return;

          if (interval === Intervals.All) {
            Promise.all(symbolIds.map((symbolId) => this.dataSource.loadAllHistory(symbolId)))
              .then(() => {
                const firstTimes = symbolIds
                  .map((symbolId) => this.dataSource.getOldestTime(symbolId))
                  .filter((time): time is number => time !== null);

                const lastTimes = symbolIds
                  .map((symbolId) => this.dataSource.getLastCandle(symbolId)?.time)
                  .filter((time): time is number => time !== undefined);

                if (firstTimes.length === 0 || lastTimes.length === 0) {
                  return;
                }

                requestAnimationFrame(() => {
                  this.lwcChart.timeScale().setVisibleRange({
                    from: Math.min(...firstTimes) as Time,
                    to: Math.max(...lastTimes) as Time,
                  });
                });
              })
              .catch((error) => console.error('[Chart] Ошибка при загрузке всей истории:', error));

            return;
          }

          const { from, to } = getIntervalRange(interval);

          Promise.all(symbolIds.map((symbolId) => this.dataSource.loadTill(symbolId, from)))
            .then(() => {
              this.lwcChart.timeScale().setVisibleRange({
                from: from as Time,
                to: to as Time,
              });
            })
            .catch((error) => {
              console.error('[Chart] Ошибка при применении интервала:', error);
            });
        }),
    );

    this.subscriptions.add(
      symbolIds$.subscribe((symbolIds) => {
        const previousSymbolIds = new Set(this.activeSymbolIds);

        this.activeSymbolIds = symbolIds;
        this.dataSource.setSymbols(symbolIds);

        const addedSymbolIds = symbolIds.filter((symbolId) => !previousSymbolIds.has(symbolId));

        if (addedSymbolIds.length) {
          warmupSymbolIds(addedSymbolIds);
        }
      }),
    );
  }

  private setupHistoricalDataLoading(): void {
    // todo (не)вызвать loadMoreHistory после проверки на необходимость дозагрузки после смены таймфрейма
    this.mouseEvents.subscribe('visibleLogicalRangeChange', (logicalRange: LogicalRange | null) => {
      this.paneManager.setVisibleLogicalRange(logicalRange);

      if (!logicalRange) return;

      if (this.currentInterval === Intervals.All) {
        return;
      }

      const needsMoreData = logicalRange.from < HISTORY_LOAD_THRESHOLD;

      if (!needsMoreData) return;

      this.scheduleHistoryBatch();
    });
  }
}

function getIntervalRange(interval: Intervals): {
  from: number;
  to: number;
} {
  const { value, unit } = intervalsToDayjs[interval] as DayjsOffset;

  const from = Math.floor(dayjs().subtract(value, unit).valueOf() / 1000);
  const to = Math.floor(dayjs().valueOf() / 1000);

  return {
    from,
    to,
  };
}

function getOptions(config: ChartConfig): DeepPartial<ChartOptions> {
  const timeFormat = config.timeFormat ?? Defaults.timeFormat;
  const showTime = config.showTime ?? Defaults.showTime;

  const use12HourFormat = timeFormat === '12h';
  const timeFormatString = use12HourFormat ? 'h:mm A' : 'HH:mm';

  const { colors } = getThemeStore();

  const localization: LocalizationOptionsBase = {
    locale: getLocale(),
    priceFormatter: (priceValue: BarPrice) => {
      return formatCompactNumber(priceValue);
    },
  };

  return {
    width: config.container.clientWidth,
    height: config.container.clientHeight,
    autoSize: true,
    layout: {
      background: {
        color: colors.chartBackground,
      },
      textColor: colors.chartTextPrimary,
    },
    grid: {
      vertLines: {
        color: colors.chartGridLine,
      },
      horzLines: {
        color: colors.chartGridLine,
      },
    },
    crosshair: {
      mode: CrosshairMode.Normal,
      vertLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: 0,
      },
      horzLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: 2,
      },
    },
    timeScale: {
      timeVisible: showTime,
      secondsVisible: false,
      tickMarkFormatter: createTickMarkFormatter(timeFormatString),
      borderVisible: false,
      allowBoldLabels: false,
      rightOffset: 25,
      shiftVisibleRangeOnNewBar: true,
      allowShiftVisibleRangeOnWhitespaceReplacement: true,
    },
    rightPriceScale: {
      textColor: colors.chartTextPrimary,
      borderVisible: false,
    },
    localization,
  };
}


import { combineLatest, Subscription } from 'rxjs';

import { ControlBar } from '@components/ControlBar';
import { Footer } from '@components/Footer';

import { Header } from '@components/Header';
import { DataSource, DataSourceParams } from '@core/DataSource';
import { Hotkeys, Keys } from '@core/Hotkeys';
import { ModalRenderer } from '@core/ModalRenderer';
import { FloatingDrawingToolbar } from '@src/components/FloatingToolbar';
import { SettingsModal } from '@src/components/SettingsModal';

import Toolbar from '@src/components/Toolbar';
import { IndicatorsIds } from '@src/constants';
import { CompareManager } from '@src/core/CompareManager';
import { FullscreenController } from '@src/core/Fullscreen';

import { configureThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { Locale, setLocale, t } from '@src/translations';
import { Candle, ChartSeriesType, ChartTypeOptions, OHLCConfig, SymbolInfoInput, TooltipConfig } from '@src/types';
import { ISerializable, MoexChartSnapshot, MoexChartSnapshotInput } from '@src/types/snapshot';
import { Timeframes } from '@src/types/timeframes';

import { setPricePrecision } from '@src/utils';

import { Chart } from './Chart';
import { ChartSettings, ChartSettingsSource } from './ChartSettings';
import { ContainerManager } from './ContainerManager';
import { EventManager } from './EventManager';
import { ReactRenderer } from './ReactRenderer';
import { TimeScaleHoverController } from './TimescaleHoverController';
import { UIRenderer } from './UIRenderer';

import 'exchange-elements/dist/fonts/inter/font.css';
import 'exchange-elements/dist/style.css';
import 'exchange-elements/dist/tokens/moex.css';
import '../styles/global.scss';

// todo: forbid @lib in /src
export interface ChartCollectionPreset {
  undoRedoEnabled?: boolean;
  showMenuButton?: boolean;
  showBottomPanel?: boolean;
  showControlBar?: boolean;
  showFullscreenButton?: boolean;
  showSettingsButton?: boolean;
  showCompareButton?: boolean;
  showSymbolSearchButton?: boolean;
  /**
   * Дефолтная конфигурация тултипа - всегда показывается по умолчанию.
   * При добавлении/изменении полей в конфиге - они объединяются с дефолтными значениями.
   *
   * Полная кастомизация:
   * @example
   * ```typescript
   *    tooltipConfig: {
   *      time: { visible: true, label: 'Дата и время' },
   *      symbol: { visible: true, label: 'Инструмент' },
   *      close: { visible: true, label: 'Курс' },
   *      change: { visible: true, label: 'Изменение' },
   *      volume: { visible: true, label: 'Объем' },
   *      open: { visible: false },
   *      high: { visible: false },
   *      low: { visible: false }
   *    }
   *```
   */
  tooltipConfig?: TooltipConfig;

  size?:
    | {
        width: number;
        height: number;
      }
    | false;
  supportedTimeframes: Timeframes[];
  supportedChartSeriesTypes: ChartSeriesType[];
  getDataSource: DataSourceParams['getData'];
  startRealtime: (
    getSymbols: () => string[],
    getTimeframe: () => Timeframes,
    update: (symbolId: string, candle: Candle) => void,
    periodMs?: number,
  ) => () => void;
  theme: ThemeKey; // 'mb' | 'mxt' | 'tr'
  ohlc: OHLCConfig;
  locale: Locale;
  mode?: ThemeMode; // 'light' | 'dark'
  openCompareModal?: () => void;
  openSymbolSearchModal?: () => void;
}

export interface IMoexChart {
  snapshot: MoexChartSnapshotInput;
  chartCollectionPreset: ChartCollectionPreset;

  container: HTMLElement;
  lwcInheritedChartOptions?: ChartTypeOptions;
}

export class MoexChart implements ISerializable<MoexChartSnapshot> {
  private chart!: Chart;
  private resizeObserver?: ResizeObserver;
  private eventManager!: EventManager;
  private hotkeys!: Hotkeys;
  private rootContainer!: HTMLElement;

  private headerRenderer!: UIRenderer;
  private modalRenderer!: ModalRenderer;
  private toolbarRenderer: UIRenderer | undefined;
  private controlBarRenderer?: UIRenderer;
  private footerRenderer?: UIRenderer;
  private drawingToolbarRenderer!: UIRenderer;

  private timeScaleHoverController!: TimeScaleHoverController;
  private dataSource!: DataSource;

  private subscriptions = new Subscription();

  private fullscreen!: FullscreenController;

  private chartCollectionPresetSettings!: ChartCollectionPreset;

  constructor(config: IMoexChart) {
    setLocale(config.chartCollectionPreset.locale);
    this.setup(config);
  }

  private setup = (config: IMoexChart) => {
    this.chartCollectionPresetSettings = config.chartCollectionPreset;

    setPricePrecision(config.chartCollectionPreset.ohlc.precision);

    const { chartSeriesType, symbolId, symbol, symbolName, timeframe, interval, dateFormat, timeFormat } =
      config.snapshot.charts[0];

    this.eventManager = new EventManager({
      initialTimeframe: timeframe,
      initialSeries: chartSeriesType,
      initialSymbolInfo: {
        symbolId,
        symbol,
        symbolName,
      },
      initialTimeFormat: timeFormat,
      initialDateFormat: dateFormat,
      initialInterval: interval,
    });

    // todo: сюда прокидывается не подходящий под сигнатуру интерфейс. Функция не работает
    // if (config.lwcInheritedChartOptions) {
    //   this.setSettings(config.lwcInheritedChartOptions);
    // }

    this.dataSource = new DataSource({
      getData: config.chartCollectionPreset.getDataSource,
      eventManager: this.eventManager,
    });

    this.rootContainer = config.container;

    this.fullscreen = new FullscreenController(this.rootContainer);

    const store = configureThemeStore(config.chartCollectionPreset);

    const {
      chartAreaContainer,
      toolBarContainer,
      headerContainer,
      modalContainer,
      controlBarContainer,
      drawingToolbarContainer,
      footerContainer,
      toggleToolbar, // todo: move this function to toolbarModel
    } = ContainerManager.createContainers({
      parentContainer: this.rootContainer,
      showBottomPanel: config.chartCollectionPreset.showBottomPanel, // todo: apply config.showBottomPanel in FullscreenController
      showMenuButton: config.chartCollectionPreset.showMenuButton,
    });

    this.hotkeys = new Hotkeys();

    if (config.chartCollectionPreset.undoRedoEnabled) {
      const undoRedo = this.eventManager.getUndoRedo();

      this.hotkeys.register({
        keys: [Keys.mod, Keys.z],
        callback: undoRedo.undo,
      });

      this.hotkeys.register({
        keys: [Keys.mod, Keys.y],
        callback: undoRedo.redo,
      });

      this.hotkeys.register({
        keys: [Keys.mod, Keys.shift, Keys.z],
        callback: undoRedo.redo,
      });
    }

    this.modalRenderer = new ModalRenderer(modalContainer);

    this.chart = new Chart({
      params: {
        dataSource: this.dataSource,
        eventManager: this.eventManager,
        modalRenderer: this.modalRenderer,
        ohlcConfig: config.chartCollectionPreset.ohlc, // todo: omptimize
        tooltipConfig: config.chartCollectionPreset.tooltipConfig ?? {},
        panes: config.snapshot.charts[0].panes,
        hotkeys: this.hotkeys,
      },
      lwcChartConfig: {
        container: chartAreaContainer,
        seriesTypes: config.chartCollectionPreset.supportedChartSeriesTypes,
        theme: store.theme,
        mode: store.mode,
        chartOptions: config.lwcInheritedChartOptions, // todo: remove, use only model from eventManager
      },
    });

    this.subscriptions.add(
      combineLatest([store.theme$, store.mode$]).subscribe(([theme, mode]) => {
        this.chart.updateTheme(theme, mode);

        document.documentElement.dataset.theme = theme;
        document.documentElement.dataset.mode = mode;
      }),
    );

    const realtimeParams = this.chart.getRealtimeApi();

    this.subscriptions.add(
      config.chartCollectionPreset.startRealtime(
        realtimeParams.getSymbols,
        realtimeParams.getTimeframe,
        realtimeParams.update,
      ),
    );

    this.headerRenderer = new ReactRenderer(headerContainer);
    this.toolbarRenderer = new ReactRenderer(toolBarContainer);
    this.drawingToolbarRenderer = new ReactRenderer(drawingToolbarContainer);

    if (config.chartCollectionPreset.showControlBar) {
      this.controlBarRenderer = new ReactRenderer(controlBarContainer);
    }

    if (config.chartCollectionPreset.showBottomPanel) {
      this.footerRenderer = new ReactRenderer(footerContainer);
    }

    this.timeScaleHoverController = new TimeScaleHoverController({
      eventManager: this.eventManager,
      controlBarContainer,
      chartContainer: chartAreaContainer,
    });

    this.renderAttachments(config, toggleToolbar);
  };

  public setSettings(settings: ChartSettingsSource): void {
    this.eventManager.importChartSettings(settings);
  }

  public getSettings(): ChartSettings {
    return this.eventManager.exportChartSettings();
  }

  // todo: описать подробнее в доке. Точно ли public?
  public getRealtimeApi() {
    return this.chart.getRealtimeApi();
  }

  // todo: описать подробнее в доке
  public getCompareManager(): CompareManager {
    return this.chart.getCompareManager();
  }

  public setSnapshot(snapshot: MoexChartSnapshotInput) {
    const configConstructorLike: IMoexChart = {
      snapshot,
      chartCollectionPreset: this.chartCollectionPresetSettings,
      container: this.rootContainer,
    };

    this.destroy();
    this.setup(configConstructorLike);
  }

  // todo: описать в доке
  public getSnapshot(): MoexChartSnapshot {
    const res = {
      settings: this.getSettings(),
      charts: [this.chart.getSnapshot()], // todo: в будущем может быть несколько инстансов чартов
    };

    return res;
  }

  public setSymbol(symbolInfo: SymbolInfoInput): void {
    this.eventManager.setSymbol(symbolInfo);
  }

  private renderAttachments(config: IMoexChart, toggleToolbar: () => boolean) {
    const drawingsCollectionManager = this.chart.getDrawingsCollectionManager();

    this.drawingToolbarRenderer.renderComponent(
      // этот тулбар к drawingManger бы прибить, сильно на него завязан
      <FloatingDrawingToolbar
        selectedDrawing$={drawingsCollectionManager.selectedDrawing()}
        onUpdateSettings={drawingsCollectionManager.updateSelectedDrawingSettings}
        onToggleLock={() => drawingsCollectionManager.toggleSelectedDrawingLock()}
        onOpenSettings={() => drawingsCollectionManager.openSelectedDrawingSettings()}
        onDelete={() => drawingsCollectionManager.deleteSelectedDrawing()}
      />,
    );

    this.headerRenderer.renderComponent(
      <Header
        timeframes={config.chartCollectionPreset.supportedTimeframes}
        selectedTimeframeObs={this.eventManager.getTimeframeObs()}
        setTimeframe={(value) => {
          this.eventManager.setTimeframe(value);
        }}
        seriesTypes={config.chartCollectionPreset.supportedChartSeriesTypes}
        selectedSeriesObs={this.eventManager.getSelectedSeries()}
        setSelectedSeries={(value) => {
          this.eventManager.setSeriesSelected(value);
        }}
        showSettingsModal={
          config.chartCollectionPreset.showSettingsButton
            ? () =>
                this.modalRenderer.renderComponent(
                  <SettingsModal
                    // todo: deal with onSave
                    changeTimeFormat={(format) => this.eventManager.setTimeFormat(format)}
                    changeDateFormat={(format) => this.eventManager.setDateFormat(format)}
                    chartDateTimeFormatObs={this.eventManager.getChartOptionsModel()}
                  />,
                  { title: t('Settings') },
                )
            : undefined
        }
        addIndicatorToChart={(indicatorType: IndicatorsIds) =>
          this.chart.getIndicatorManager().addIndicator({ indicatorType })
        }
        showMenuButton={!!config.chartCollectionPreset.showMenuButton}
        showFullscreenButton={!!config.chartCollectionPreset.showFullscreenButton}
        fullscreen={this.fullscreen}
        undoRedo={config.chartCollectionPreset.undoRedoEnabled ? this.eventManager.getUndoRedo() : undefined}
        toggleToolbarVisible={toggleToolbar}
        showCompareButton={!!config.chartCollectionPreset.showCompareButton}
        openCompareModal={
          config.chartCollectionPreset.openCompareModal ? config.chartCollectionPreset.openCompareModal : undefined
        }
        showSymbolSearchButton={!!config.chartCollectionPreset.openSymbolSearchModal}
        openSymbolSearchModal={config.chartCollectionPreset.openSymbolSearchModal}
        isMXT={config.chartCollectionPreset.theme === 'mxt'}
      />,
    );

    if (this.toolbarRenderer && config.chartCollectionPreset.showMenuButton) {
      const drawingCollection = this.chart.getDrawingsCollectionManager();
      this.toolbarRenderer.renderComponent(
        <Toolbar
          toggleDOM={this.chart.getDom().toggleDOM}
          addDrawing={drawingCollection.activateDrawingTool}
          setEndlessDrawingsMode={drawingCollection.setEndlessDrawingMode}
          isEndlessDrawingsMode$={drawingCollection.isEndlessDrawingsMode()}
          activateCrosshair={() => drawingCollection.activateCrosshair()}
          activeTool$={drawingCollection.getActiveTool()}
        />,
      );
    }

    if (this.controlBarRenderer && config.chartCollectionPreset.showControlBar) {
      this.controlBarRenderer.renderComponent(
        <ControlBar
          scroll={this.chart.scrollTimeScale}
          zoom={this.chart.zoomTimeScale}
          reset={this.chart.resetZoom}
          visible={this.eventManager.getControlBarVisible()}
        />,
      );
    }

    if (this.footerRenderer && config.chartCollectionPreset.showBottomPanel) {
      this.footerRenderer.renderComponent(
        <Footer
          supportedTimeframes={config.chartCollectionPreset.supportedTimeframes}
          setInterval={this.eventManager.setInterval}
          intervalObs={this.eventManager.getInterval()}
        />,
      );
    }
  }

  /**
   * Уничтожение графика и очистка ресурсов
   * @returns void
   */
  destroy(): void {
    this.headerRenderer.destroy();
    this.drawingToolbarRenderer.destroy();
    this.subscriptions.unsubscribe();
    this.timeScaleHoverController.destroy();

    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = undefined;
    }

    if (this.controlBarRenderer) {
      this.controlBarRenderer.destroy();
    }

    if (this.footerRenderer) {
      this.footerRenderer.destroy();
    }

    if (this.chart) {
      this.chart.destroy();
    }

    this.hotkeys.destroy();

    if (this.eventManager) {
      this.eventManager.destroy();
    }

    if (this.toolbarRenderer) {
      this.toolbarRenderer.destroy();
    }

    this.dataSource.destroy();

    ContainerManager.clearContainers(this.rootContainer);
  }
}
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;
  mainSymbolId$: Observable<string>;
  mainSymbol$: Observable<string>;
  mainSerie$: BehaviorSubject<SeriesStrategies | null>;
  actLikeMainSerie?: boolean;
  customFormatter?: (params: IndicatorDataFormatter<TSeries>) => SeriesDataItemTypeMap<Time>[TSeries][];
  seriesOptions?: SeriesPartialOptionsMap[TSeries];
  priceScaleOptions?: DeepPartial<PriceScaleOptions>;
  showSymbolLabel?: boolean;
  paneIndex?: number;
  indicatorReference?: Indicator;
}

export abstract class BaseSeries<TSeries extends SeriesType> implements IBaseSeries<TSeries> {
  protected lwcSeries: ISeriesApi<TSeries>;
  protected customFormatter?: (params: IndicatorDataFormatter<TSeries>) => SeriesDataItemTypeMap<Time>[TSeries][];

  protected lwcChart: IChartApi;
  protected mainSymbolId$: Observable<string>;
  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;
  public actLikeMainSerie = false;

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

    this.lwcChart = lwcChart;
    this.customFormatter = customFormatter;
    this.mainSymbolId$ = mainSymbolId$;
    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[seriesData.length - 1];

      if (!currentBar) {
        return {};
      }

      return this.formatLegendValues(currentBar, seriesData[seriesData.length - 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 data = this.lwcSeries.data();
    const lastBar = data[data.length - 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 formatData(inputData: Candle[]): SeriesDataItemTypeMap<Time>[TSeries][] {
    if (!this.customFormatter) {
      return this.formatMainSerie(inputData);
    }

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

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

    const candle = this.formatMainSerie(inputData)[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.lwcSeries.applyOptions({
      priceFormat: {
        type: 'custom',
        minMove,
        formatter: (price: number) => formatPrice(price) ?? String(price),
      },
    });

    this.subscriptions.add(
      this.mainSymbol$.pipe(distinctUntilChanged()).subscribe((symbol) => {
        this.lwcSeries.applyOptions({
          title: this.showSymbolLabel ? symbol : '',
        });
      }),
    );

    this.subscriptions.add(
      this.mainSymbolId$.pipe(distinctUntilChanged()).subscribe((symbolId) => {
        this.dataSub?.unsubscribe();
        this.realtimeSub?.unsubscribe();

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

        this.realtimeSub = dataSource.subscribeRealtime(symbolId, (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: Number.isNaN(percentageChange) ? 0 : 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: Number.isNaN(percentageChange) ? 0 : percentageChange,
      customValues: current.customValues,
    };
  }

  return null;
}


import {
  BarData,
  BarSeries,
  CustomData,
  HistogramData,
  LineData,
  SeriesDataItemTypeMap,
  SeriesDefinition,
  SeriesPartialOptionsMap,
  Time,
} from 'lightweight-charts';

import { Ohlc } from '@core/Legend';

import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@src/core/Series/BaseSeries';
import { ISeries } from '@src/modules/series-strategies';
import { getThemeStore } from '@src/theme';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isBarData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

export class BarSeriesStrategy extends BaseSeries<'Bar'> implements ISeries<'Bar'> {
  constructor(params: BaseSeriesParams<'Bar'>) {
    super(params);
    this.subscribeDataSource(params.dataSource);
  }

  protected seriesDefinition(): SeriesDefinition<'Bar'> {
    return BarSeries;
  }

  getDefaultOptions(): SeriesPartialOptionsMap['Bar'] {
    const { colors } = getThemeStore();

    return {
      upColor: colors.chartCandleUp,
      downColor: colors.chartCandleDown,
    };
  }

  getTypeName(): string {
    return 'Bar';
  }

  public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
    if (!Array.isArray(data)) {
      return false;
    }

    return data.every((point) => typeof point.time === 'number');
  }

  protected dataSourceSubscription = (dataToSet: Candle[]): void => {
    if (!this.validateData(dataToSet)) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    this.setData(this.formatData(dataToSet));
  };

  protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
    if (!this.validateData([dataToSet])) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    const formattedData = this.formatData([dataToSet]);
    this.update(formattedData[0], true);
  };

  protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Bar'][] {
    return inputData.map((point) => ({
      time: point.time as Time,
      open: point.open,
      high: point.high,
      low: point.low,
      close: point.close,
      customValues: point as unknown as Record<string, unknown>,
    }));
  }

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

    const { colors } = getThemeStore();

    const color = removeAlphaFromHex(
      currentBar.close < currentBar.open ? colors.chartCandleWickDown : colors.chartCandleWickUp,
    );

    const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));

    return {
      open: {
        value: formatCompactNumber(currentBar.open) ?? '',
        name: t('Open'),
        color,
      },
      high: {
        value: formatCompactNumber(currentBar.high) ?? '',
        name: t('High'),
        color,
      },
      low: {
        value: formatCompactNumber(currentBar.low) ?? '',
        name: t('Low'),
        color,
      },
      close: {
        value: formatCompactNumber(currentBar.close) ?? '',
        name: t('Close'),
        color,
      },
      absoluteChange: {
        value: formatCompactNumber(absoluteChange ?? 0),
        name: t('Change'),
        color,
      },
      percentageChange: {
        value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
        name: t('Change'),
        color,
      },
      time: {
        value: time,
        name: t('Time'),
        color,
      },
    };
  }
}


import {
  BarData,
  CandlestickSeries,
  CustomData,
  HistogramData,
  LineData,
  SeriesDataItemTypeMap,
  SeriesDefinition,
  SeriesPartialOptionsMap,
  Time,
} from 'lightweight-charts';

import { Ohlc } from '@core/Legend';

import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@core/Series/BaseSeries';

import { ISeries } from '@src/modules/series-strategies';

import { getThemeStore } from '@src/theme/store';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isBarData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

export class CandlestickSeriesStrategy extends BaseSeries<'Candlestick'> implements ISeries<'Candlestick'> {
  constructor(params: BaseSeriesParams<'Candlestick'>) {
    super(params);
    this.subscribeDataSource(params.dataSource);
  }

  protected seriesDefinition(): SeriesDefinition<'Candlestick'> {
    return CandlestickSeries;
  }

  public getDefaultOptions(): SeriesPartialOptionsMap['Candlestick'] {
    const { colors } = getThemeStore();

    return {
      upColor: colors.chartCandleUp,
      downColor: colors.chartCandleDown,
      borderVisible: false,
      wickUpColor: colors.chartCandleWickUp,
      wickDownColor: colors.chartCandleWickDown,
    };
  }

  public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
    // todo: should be private
    if (!Array.isArray(data)) {
      return false;
    }

    return data.every((point) => {
      if (!point) {
        return false;
      }
      // Проверяем обязательные поля
      if (typeof point.time !== 'number') {
        return false;
      }

      // Если указаны OHLC, проверяем их корректность
      if (
        point.open !== undefined &&
        point.high !== undefined &&
        point.low !== undefined &&
        point.close !== undefined
      ) {
        return point.high >= Math.max(point.open, point.close) && point.low <= Math.min(point.open, point.close);
      }

      return true;
    });
  }

  public getTypeName(): string {
    return 'Candlestick';
  }

  protected dataSourceSubscription = (dataToSet: Candle[]): void => {
    if (!this.validateData(dataToSet)) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    this.setData(this.formatData(dataToSet));
  };

  protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
    if (!this.validateData([dataToSet])) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    const formattedData = this.formatData([dataToSet]);
    this.update(formattedData[0], true);
  };

  protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Candlestick'][] {
    return inputData.map((point) => ({
      time: point.time as Time,
      open: point.open,
      high: point.high,
      low: point.low,
      close: point.close,
      customValues: point as unknown as Record<string, unknown>,
    }));
  }

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

    const { colors } = getThemeStore();

    const color = removeAlphaFromHex(
      currentBar.close < currentBar.open ? colors.chartCandleWickDown : colors.chartCandleWickUp,
    );

    const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));

    return {
      open: {
        value: formatCompactNumber(currentBar.open) ?? '',
        name: t('Open'),
        color,
      },
      high: {
        value: formatCompactNumber(currentBar.high) ?? '',
        name: t('High'),
        color,
      },
      low: {
        value: formatCompactNumber(currentBar.low) ?? '',
        name: t('Low'),
        color,
      },
      close: {
        value: formatCompactNumber(currentBar.close) ?? '',
        name: t('Close'),
        color,
      },
      absoluteChange: {
        value: formatCompactNumber(absoluteChange ?? 0),
        name: t('Change'),
        color,
      },
      percentageChange: {
        value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
        name: t('Change'),
        color,
      },
      time: {
        value: time,
        name: t('Time'),
        color,
      },
    };
  }
}


import {
  BarData,
  CustomData,
  HistogramData,
  HistogramSeries,
  LineData,
  SeriesDataItemTypeMap,
  SeriesDefinition,
  SeriesPartialOptionsMap,
  Time,
} from 'lightweight-charts';

import { Ohlc } from '@core/Legend';

import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@core/Series/BaseSeries';

import { ISeries } from '@src/modules/series-strategies';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isHistogramData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

export class HistogramSeriesStrategy extends BaseSeries<'Histogram'> implements ISeries<'Histogram'> {
  constructor(params: BaseSeriesParams<'Histogram'>) {
    super(params);
    this.subscribeDataSource(params.dataSource);
  }

  protected seriesDefinition(): SeriesDefinition<'Histogram'> {
    return HistogramSeries;
  }

  protected getDefaultOptions(): SeriesPartialOptionsMap['Histogram'] {
    return {};
  }

  public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
    if (!Array.isArray(data)) {
      return false;
    }

    return data.every((point) => typeof point.time === 'number');
  }

  public getTypeName(): string {
    return 'Histogram';
  }

  protected dataSourceSubscription = (dataToSet: Candle[]): void => {
    if (!this.validateData(dataToSet)) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    this.setData(this.formatData(dataToSet));
  };

  protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
    if (!this.validateData([dataToSet])) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    const formattedData = this.formatData([dataToSet]);
    this.update(formattedData[0], true);
  };

  protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Histogram'][] {
    return inputData.map((point) => ({
      time: point.time as Time,
      value: point.close,
      customValues: point as unknown as Record<string, unknown>,
    }));
  }

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

    const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));

    const color = currentBar.color ? removeAlphaFromHex(currentBar.color) : this.options().color;

    return {
      value: {
        value: formatCompactNumber(currentBar.value) ?? '',
        name: '',
        color,
      },
      absoluteChange: {
        value: formatCompactNumber(absoluteChange ?? 0),
        name: t('Change'),
        color,
      },
      percentageChange: {
        value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
        name: t('Change'),
        color,
      },
      time: {
        value: time,
        name: t('Time'),
        color,
      },
    };
  }
}


import {
  BarData,
  CustomData,
  HistogramData,
  LineData,
  LineSeries,
  LineStyle,
  SeriesDataItemTypeMap,
  SeriesDefinition,
  SeriesPartialOptionsMap,
  Time,
} from 'lightweight-charts';

import { Ohlc } from '@core/Legend';

import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@core/Series/BaseSeries';

import { ISeries } from '@src/modules/series-strategies';

import { getThemeStore } from '@src/theme/store';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isLineData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

export class LineSeriesStrategy extends BaseSeries<'Line'> implements ISeries<'Line'> {
  constructor(params: BaseSeriesParams<'Line'>) {
    super(params);
    this.subscribeDataSource(params.dataSource);
  }

  protected seriesDefinition(): SeriesDefinition<'Line'> {
    return LineSeries;
  }

  protected getDefaultOptions(): SeriesPartialOptionsMap['Line'] {
    const { colors } = getThemeStore();

    return {
      color: colors.chartLineColor,
      lineWidth: 2,
      lineStyle: LineStyle.Solid,
    };
  }

  public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
    if (!Array.isArray(data)) {
      return false;
    }

    return data.every((point) => typeof point.time === 'number');
  }

  public getTypeName(): string {
    return 'Line';
  }

  protected dataSourceSubscription = (dataToSet: Candle[]): void => {
    if (!this.validateData(dataToSet)) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    this.setData(this.formatData(dataToSet));
  };

  protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
    if (!this.validateData([dataToSet])) {
      console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
      return;
    }

    const formattedData = this.formatData([dataToSet]);
    this.update(formattedData[0], true);
  };

  protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Line'][] {
    return inputData.map((point) => ({
      time: point.time as Time,
      value: point.close, // Для line графика используем close как value
      customValues: point as unknown as Record<string, unknown>,
    }));
  }

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

    const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));

    const color = currentBar.color ? removeAlphaFromHex(currentBar.color) : this.options().color;

    return {
      value: {
        value: formatCompactNumber(currentBar.value) ?? '',
        name: '',
        color,
      },
      absoluteChange: {
        value: formatCompactNumber(absoluteChange ?? 0),
        name: t('Change'),
        color,
      },
      percentageChange: {
        value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
        name: t('Change'),
        color,
      },
      time: {
        value: time,
        name: t('Time'),
        color,
      },
    };
  }
}


import { SymbolInfo } from '@src/types/symbol';

export enum CompareMode {
  Percentage = 'PCT',
  NewScale = 'SCALE',
  NewPane = 'PANE',
}

export interface CompareItem extends SymbolInfo {
  mode: CompareMode;
}


export interface SymbolInfo {
  symbolId: string;
  symbol: string;
  symbolName: string;
}

export interface SymbolInfoInput {
  symbolId: string;
  symbol?: string;
  symbolName?: string;
}


import { useEffect, useRef, useState } from 'react';

import { createPortal } from 'react-dom';

import { CompareManager } from '@core/CompareManager';
import { DateFormat, IMoexChart, Locale, MoexChart, Timeframes } from '@lib';
import { IndicatorsIds } from '@lib/constants';
import { CompareMode, Direction, SymbolInfoInput } from '@lib/types';

// import { argTypes } from '../argTypes';

import { dataSourceProvider } from '../common';

import { activate } from '../worker';

import type { Meta, StoryObj } from '@storybook/react';

/**
 * ## TradeRadar story
 * describes an entry point of MoexChart for TR user
 */

type TRProps = Omit<IMoexChart, 'container'>;
activate();
const TREntry = (props: TRProps) => {
  const [isCompareOpen, setIsCompareOpen] = useState(false);
  const [moexChart, setMoexChart] = useState<MoexChart | undefined>();
  const [snap, setSnap] = useState<any>();

  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const container = containerRef.current;

    if (!container) {
      return;
    }

    const chart = new MoexChart({
      ...props,
      container,
      chartCollectionPreset: {
        ...props.chartCollectionPreset,
        openCompareModal: () => setIsCompareOpen(true),
      },
    });

    setMoexChart(chart);

    return () => {
      chart.destroy();
    };
  }, [props]);

  return (
    <div
      style={{
        width: '100%',
        height: '100dvh',
        display: 'grid',
        gridTemplateRows: 'auto auto minmax(0, 1fr)',
        gap: 10,
        padding: 20,
        boxSizing: 'border-box',
      }}
    >
      <h3
        style={{
          margin: 0,
        }}
      >
        TradeRadar usage
      </h3>

      <div>
        <button
          type="button"
          onClick={() => {
            setSnap(moexChart?.getSnapshot());
          }}
        >
          Сохранить стейт
        </button>

        <button
          type="button"
          onClick={() => {
            if (snap) {
              moexChart?.setSnapshot(snap);
            }
          }}
        >
          Применить стейт
        </button>
      </div>

      <div ref={containerRef} />

      {isCompareOpen &&
        createPortal(
          <Modal
            onClose={() => setIsCompareOpen(false)}
            compareManager={moexChart?.getCompareManager() ?? null}
          />,
          document.body,
        )}
    </div>
  );
};

const meta: Meta<TRProps> = {
  title: 'TradeRadar',
  component: TREntry,
  // argTypes, // todo: пофиксить вместе с переписыванием доки
  parameters: {
    layout: 'fullscreen',
    docs: {
      description: {
        component: `## TradeRadar story
  describes an entry point of MoexChart for TR user`,
      },
    },
  },
};

export default meta;

type Story = StoryObj<typeof meta>;

const args: TRProps = {
  snapshot: {
    charts: [
      {
        timeframe: Timeframes['10s'],
        chartSeriesType: 'Candlestick',
        symbolId: 'appl',
        panes: [
          {
            // empty panes deletes automatically
            isMain: true, // Be careful. There is only one main pane can be present
            id: 0,
            indicators: [
              {
                indicatorType: IndicatorsIds.Volume, // if indicatorType is undefined, then its compareIndicator
              },
              {
                indicatorType: IndicatorsIds.EMA,
              },
              {
                symbolInfo: { symbolId: 'TQBR:SBER' },
                scale: Direction.Right,
                seriesName: 'Line',
              },
            ],
            drawings: [],
          },
          {
            isMain: false,
            id: 1,
            indicators: [
              {
                indicatorType: IndicatorsIds.MACD,
              },
            ],
            drawings: [],
          },
        ],
      },
    ],
  },
  chartCollectionPreset: {
    undoRedoEnabled: true,
    showMenuButton: true,
    showBottomPanel: true,
    showControlBar: true,
    showFullscreenButton: true,
    showSettingsButton: true,
    showCompareButton: true,
    tooltipConfig: {
      showTooltip: false,
      time: { visible: true, label: 'Время' },
      close: { visible: true, label: 'Закр.' },
      change: { visible: true, label: 'Изм.' },
      volume: { visible: true, label: 'Объем' },
      open: { visible: true, label: 'Откр.' },
      high: { visible: true, label: 'Макс.' },
      low: { visible: true, label: 'Мин.' },
    },

    supportedTimeframes: [
      Timeframes['1s'],
      Timeframes['5s'],
      Timeframes['10s'],
      Timeframes['1m'],
      Timeframes['2m'],
      Timeframes['30m'],
      Timeframes['1h'],
      Timeframes['2h'],
      Timeframes['3h'],
      Timeframes['4h'],
      Timeframes['1d'],
      Timeframes['1w'],
    ],
    supportedChartSeriesTypes: ['Candlestick', 'Line', 'Bar'],
    getDataSource: dataSourceProvider.generateCandles.bind(dataSourceProvider),
    startRealtime: (getSymbols, getTimeframe, update) =>
      dataSourceProvider.startRealtime(getSymbols, getTimeframe, update), // should return unsub
    theme: 'tr',
    ohlc: {
      show: true,
      precision: 2,
    },
    mode: 'dark',
    locale: Locale.eng,
  },

  lwcInheritedChartOptions: {
    timeVisible: true,
    secondsVisible: false,
    timeFormat: '24h',
    dateFormat: DateFormat.DD_MM_YYYY_HH_mm_ss,
  },
};

export const TradeRadar: Story = {
  args,
  parameters: {
    controls: {
      expanded: true, // отвечает за расширение колонок(+Description, +Default) в табе controls
    },
  },
};

const COMPARE_ITEMS: SymbolInfoInput[] = [
  { symbolId: 'TQBR:SBER', symbol: 'SBER', symbolName: 'Sberbank' },
  { symbolId: 'APAX' },
  { symbolId: 'SOL' },
];

const Modal = ({ onClose, compareManager }: { onClose: () => void; compareManager: CompareManager | null }) => {
  const [isNewScaleDisabled, setIsNewScaleDisabled] = useState(false);

  useEffect(() => {
    if (!compareManager) {
      setIsNewScaleDisabled(false);
      return;
    }

    setIsNewScaleDisabled(compareManager.isNewScaleDisabled());

    const subscription = compareManager.isNewScaleDisabledObservable().subscribe(setIsNewScaleDisabled);

    return () => subscription.unsubscribe();
  }, [compareManager]);

  return (
    <div
      onClick={onClose}
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#0000004D',
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: 999,
        cursor: 'pointer',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          display: 'grid',
          gap: 16,
          padding: 16,
          backgroundColor: 'white',
        }}
      >
        {COMPARE_ITEMS.map((symbolInfo) => (
          <div
            key={symbolInfo.symbolId}
            style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}
          >
            <span>{symbolInfo.symbolName ?? symbolInfo.symbol ?? symbolInfo.symbolId}</span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button
                onClick={() => compareManager?.setSymbolMode('Line', symbolInfo, CompareMode.Percentage)}
                style={{ backgroundColor: 'lightgray', padding: '2px 8px' }}
                type="button"
              >
                %
              </button>
              <button
                onClick={() => compareManager?.setSymbolMode('Line', symbolInfo, CompareMode.NewScale)}
                style={{
                  backgroundColor: isNewScaleDisabled ? 'darkgray' : 'lightgray',
                  padding: '2px 8px',
                  cursor: isNewScaleDisabled ? 'not-allowed' : 'cursor',
                }}
                disabled={isNewScaleDisabled}
                type="button"
              >
                Новая шкала
              </button>
              <button
                onClick={() => compareManager?.setSymbolMode('Line', symbolInfo, CompareMode.NewPane)}
                style={{ backgroundColor: 'lightgray', padding: '2px 8px' }}
                type="button"
              >
                Новая панель
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
import { IChartApi } from 'lightweight-charts';
import { BehaviorSubject, Observable } from 'rxjs';

import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { EventManager } from '@core/EventManager';
import { Indicator } from '@core/Indicator';
import { PaneManager } from '@core/PaneManager';
import { IndicatorsIds } from '@src/constants';
import { DOMObject } from '@src/core/DOMObject';
import { indicatorsMap as indicatorsConfigMap } from '@src/core/Indicators';
import { ChartTypeOptions, IndicatorConfig } from '@src/types';
import { IndicatorSnapshot } from '@src/types/snapshot';
import { applyNextIndicatorColors, getIndicatorColors } from '@src/utils';

interface SeriesParams {
  eventManager: EventManager;
  dataSource: DataSource;
  lwcChart: IChartApi;
  paneManager: PaneManager;
  DOM: DOMModel;
  initialIndicators?: IndicatorSnapshot[];
  chartOptions?: ChartTypeOptions;
}

export class IndicatorManager {
  private eventManager: EventManager;
  private lwcChart: IChartApi;
  private chartOptions?: ChartTypeOptions;

  private entities$: BehaviorSubject<Indicator[]> = new BehaviorSubject<Indicator[]>([]);
  private indicatorsMap$: BehaviorSubject<Map<string, Indicator>> = new BehaviorSubject(new Map()); // todo: заменить IndicatorsIds ключ на уникальный id индикатора
  private DOM: DOMModel;
  private dataSource: DataSource;
  private paneManager: PaneManager;

  constructor({ eventManager, dataSource, lwcChart, DOM, chartOptions, initialIndicators, paneManager }: SeriesParams) {
    this.eventManager = eventManager;
    this.lwcChart = lwcChart;
    this.chartOptions = chartOptions;
    this.DOM = DOM;
    this.dataSource = dataSource;
    this.paneManager = paneManager;

    this.indicatorsMap$ = new BehaviorSubject<Map<string, Indicator>>(new Map());

    initialIndicators?.forEach((ind) => {
      this.addIndicator(ind);
    });
  }

  public addEntity<T extends Indicator>(
    factory: (zIndex: number, moveUp: (id: string) => void, moveDown: (id: string) => void) => T,
  ): T {
    return this.DOM.setEntity(factory);
  }

  public addIndicator(snap: Partial<IndicatorSnapshot>): void {
    if (!snap.indicatorType) {
      console.error('[IndicatorManager] Не был получен тип индиктора');
      return;
    }
    const indicatorsMap = new Map(this.indicatorsMap$.value);

    const id = snap.id ?? `${snap.indicatorType}-${crypto.randomUUID()}`;

    const config = getConfigByIndicatorType({
      indicatorType: snap.indicatorType,
      existedIndicators: this.indicatorsMap$.value,
    });

    const associatedPane =
      snap.paneId !== undefined
        ? (this.paneManager.getPaneById(snap.paneId) ?? this.paneManager.addPane())
        : config?.newPane
          ? this.paneManager.addPane()
          : this.paneManager.getMainPane();

    const indicatorToSet = this.addEntity<Indicator>(
      (zIndex: number, moveUp: (id: string) => void, moveDown: (id: string) => void) => {
        return new Indicator({
          id,
          paneId: associatedPane.getId(),
          zIndex,
          onDelete: this.deleteIndicator,
          moveUp,
          moveDown,
          mainSymbolId$: this.eventManager.symbolId(),
          mainSymbol$: this.eventManager.symbol(),
          lwcChart: this.lwcChart,
          dataSource: this.dataSource,
          associatedPane,
          config,
          settings: snap.settings,
          type: snap.indicatorType,
          chartOptions: this.chartOptions,
        });
      },
    );

    indicatorsMap.set(id, indicatorToSet);

    this.indicatorsMap$.next(indicatorsMap);
    this.entities$.next(Array.from(indicatorsMap.values()));
  }

  public getIndicators() {
    return this.indicatorsMap$;
  }

  public removeEntity(entity: DOMObject): void {
    this.DOM.removeEntity(entity);
  }

  public deleteIndicator = (id: string) => {
    const indicatorsMap = new Map(this.indicatorsMap$.value);
    const entity = indicatorsMap.get(id);

    if (!entity) {
      return;
    }

    this.removeEntity(entity);
    entity.destroy();
    indicatorsMap.delete(id);

    this.indicatorsMap$.next(indicatorsMap);
    this.entities$.next(Array.from(indicatorsMap.values()));
  };

  public entities(): Observable<Indicator[]> {
    return this.entities$.asObservable();
  }
}

function getConfigByIndicatorType({
  indicatorType,
  existedIndicators,
}: {
  indicatorType: IndicatorsIds;
  existedIndicators: Map<string, Indicator>;
}): IndicatorConfig {
  const configWithAppliesSettings = indicatorsConfigMap()[indicatorType] as IndicatorConfig;
  const usedColors = getUsedIndicatorColorsByType({ indicatorType, existedIndicators });

  return applyNextIndicatorColors(configWithAppliesSettings, usedColors);
}

function getUsedIndicatorColorsByType({
  indicatorType,
  existedIndicators,
}: {
  indicatorType: IndicatorSnapshot['indicatorType'];
  existedIndicators: Map<string, Indicator>;
}): string[] {
  const colors: string[] = [];

  existedIndicators.forEach((indicator) => {
    if (indicator.getIndicatorType() !== indicatorType) {
      return;
    }

    colors.push(...getIndicatorColors(indicator.getConfig()));
  });

  return colors;
}

import { IChartApi } from 'lightweight-charts';
import { Observable, Subscription } from 'rxjs';

import { DataSource } from '@core/DataSource';
import { DOMObject, DOMObjectParams } from '@core/DOMObject';
import { Pane } from '@core/Pane';

import { indicatorLabelById, indicatorSeriesLabelById, IndicatorsIds } from '@src/constants';
import { SeriesFactory, SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { ChartTypeOptions, Direction, IndicatorConfig, SettingsValues } from '@src/types';
import { CompareSnapshot, DOMObjectSnapshot, IndicatorSnapshot, ISerializable } from '@src/types/snapshot';

type IIndicator = DOMObject;

export interface IndicatorParams extends DOMObjectParams {
  mainSymbolId$: Observable<string>;
  mainSymbol$: Observable<string>;
  lwcChart: IChartApi;
  dataSource: DataSource;
  associatedPane: Pane;
  config: IndicatorConfig;
  settings?: SettingsValues;
  type?: IndicatorsIds;
  chartOptions?: ChartTypeOptions;
}

// todo: сделать отдельно представление для Compare, и попобовать убрать CompareManager из Chart
export class Indicator extends DOMObject implements ISerializable<IndicatorSnapshot | CompareSnapshot> {
  private indicatorType?: IndicatorsIds;
  private series: SeriesStrategies[] = [];
  private seriesMap: Map<string, SeriesStrategies> = new Map();
  private lwcChart: IChartApi;
  private dataSource: DataSource;
  private mainSymbolId$: Observable<string>;
  private mainSymbol$: Observable<string>;
  private associatedPane: Pane;
  private config: IndicatorConfig;
  private settings: SettingsValues = {};

  private dataChangeHandlers = new Set<() => void>();
  private seriesSubscriptions = new Subscription();

  constructor({
    id,
    type,
    lwcChart,
    dataSource,
    zIndex,
    onDelete,
    moveUp,
    moveDown,
    mainSymbolId$,
    mainSymbol$,
    associatedPane,
    paneId,
    config,
    settings,
  }: IndicatorParams) {
    super({ id, name: config?.label ?? id, zIndex, onDelete, moveUp, moveDown, paneId });
    this.lwcChart = lwcChart;
    this.dataSource = dataSource;
    this.mainSymbolId$ = mainSymbolId$;
    this.mainSymbol$ = mainSymbol$;
    this.indicatorType = type;
    this.config = config;
    this.name = this.getLabel();

    this.settings = { ...this.getDefaultSettings(), ...settings };

    this.associatedPane = associatedPane;

    this.createSeries();

    this.associatedPane.setIndicator(this.id, this);
  }

  public recreateSeries() {
    this.destroySeries();
    this.createSeries();
  }

  public subscribeDataChange(handler: () => void): Subscription {
    this.dataChangeHandlers.add(handler);

    return new Subscription(() => {
      this.dataChangeHandlers.delete(handler);
    });
  }

  public getLabel = () => {
    if (this.config.label) {
      return this.config.label;
    }

    if (this.indicatorType) {
      return indicatorLabelById()[this.indicatorType];
    }

    return this.id;
  };

  public getSeriesLabel(serieName: string): string | undefined {
    if (this.config.seriesLabels?.[serieName]) {
      return this.config.seriesLabels[serieName];
    }

    if (this.indicatorType) {
      return indicatorSeriesLabelById[this.indicatorType]?.[serieName];
    }

    return undefined;
  }

  public getId(): string {
    return this.id;
  }

  public getType(): IndicatorsIds | undefined {
    return this.indicatorType;
  }

  public getPane(): Pane {
    return this.associatedPane;
  }

  public getSeriesMap(): Map<string, SeriesStrategies> {
    return this.seriesMap;
  }

  public getConfig(): IndicatorConfig {
    return this.config;
  }

  public getIndicatorType(): IndicatorSnapshot['indicatorType'] | undefined {
    return this.indicatorType;
  }

  public getSettingsValues(): SettingsValues {
    return { ...this.settings };
  }

  public getSettingsFields() {
    return this.config.settings ?? [];
  }

  public hasSettings(): boolean {
    return Boolean(this.config.settings?.length);
  }

  public updateSettings(settings: SettingsValues): void {
    this.settings = settings;

    // todo: обновлять данные серий без удаления и повторного создания
    this.recreateSeries();

    this.notifyDataChanged();
  }

  public show() {
    this.series.forEach((s) => {
      s.show();
    });
    super.show();
  }

  public hide() {
    this.series.forEach((s) => {
      s.hide();
    });
    super.hide();
  }

  public override getSnapshot(): DOMObjectSnapshot & (IndicatorSnapshot | CompareSnapshot) {
    const domSnap = super.getSnapshot();

    if (this.indicatorType) {
      return {
        ...domSnap,
        indicatorType: this.indicatorType,
        settings: this.getSettingsValues(),
      };
    }

    const seriesName = this.config.series[0]?.name;
    const scale = this.config.series[0]?.seriesOptions?.priceScaleId as Direction;
    if (!scale || !seriesName) {
      throw new Error('[Indicator]: невозможно сохранить состояние compare индикатора');
    }
    return {
      ...domSnap,
      symbolInfo: this.config.symbolInfo!,
      seriesName,
      scale,
    };
  }

  public setSnapshot(snap: IndicatorSnapshot): void {}

  // destroy и delete принципиально отличаются!
  // delete вызовет destroy в конце концов. По сути - это destroy с сайд-эффектом в eventManager
  public delete() {
    super.delete();
  }

  // destroy и delete принципиально отличаются!
  public destroy() {
    this.destroySeries();
    this.dataChangeHandlers.clear();
    this.associatedPane.removeIndicator(this.id);
  }

  private createSeries(): void {
    this.config.series.forEach(
      ({ name, id: serieId, dataFormatter, seriesOptions, priceScaleOptions, actLikeMainSerie }) => {
        const serie = SeriesFactory.create(name!)({
          lwcChart: this.lwcChart,
          dataSource: this.dataSource,
          customFormatter: dataFormatter
            ? (params) =>
                dataFormatter({
                  ...params,
                  settings: this.settings,
                  indicatorReference: this,
                })
            : undefined,
          seriesOptions,
          priceScaleOptions,
          mainSymbolId$: this.mainSymbolId$,
          mainSymbol$: this.mainSymbol$,
          mainSerie$: this.associatedPane.getMainSerie(),
          showSymbolLabel: false,
          paneIndex: this.associatedPane.paneIndex(),
          indicatorReference: this,
          actLikeMainSerie,
        });

        const handleDataChanged = () => {
          this.notifyDataChanged();
        };

        serie.subscribeDataChanged(handleDataChanged);

        this.seriesSubscriptions.add(() => {
          serie.unsubscribeDataChanged(handleDataChanged);
        });

        this.seriesMap.set(serieId, serie);

        this.series.push(serie);
      },
    );

    if (!this.associatedPane.getLocalMainSeries()) {
      const mainSeriesCandidates = this.series.filter((serie) => serie.actLikeMainSerie);
      if (mainSeriesCandidates.length < 1) {
        throw new Error('[Indicator]: there is no mainSerie in this indicator');
      }
      this.associatedPane.setLocalMainSeries(mainSeriesCandidates[0]);
    }
  }

  private destroySeries(): void {
    this.seriesSubscriptions.unsubscribe();
    this.seriesSubscriptions = new Subscription();

    this.series.forEach((s) => {
      s.destroy();
    });

    this.series = [];
    this.seriesMap.clear();
  }

  private notifyDataChanged(): void {
    this.dataChangeHandlers.forEach((handler) => {
      handler();
    });
  }

  private getDefaultSettings(): SettingsValues {
    const settings: SettingsValues = {};

    this.config.settings?.forEach((field) => {
      settings[field.key] = field.defaultValue;
    });

    return settings;
  }
}


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

import { BehaviorSubject, Subscription } from 'rxjs';

import { ChartTooltip } from '@components/ChartTooltip';
import { LegendComponent } from '@components/Legend';
import { ChartMouseEvents } from '@core/ChartMouseEvents';
import { ContainerManager } from '@core/ContainerManager';
import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { DrawingsManager, DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { EventManager } from '@core/EventManager';
import { Hotkeys } from '@core/Hotkeys';
import { Indicator } from '@core/Indicator';
import { Legend } from '@core/Legend';
import { PriceScale, PriceScaleControls } from '@core/PriceScale';
import { ReactRenderer } from '@core/ReactRenderer';
import { TooltipService } from '@core/Tooltip';
import { UIRenderer } from '@core/UIRenderer';
import { EntitySettingsModal } from '@src/components/EntitySettingsModal';
import { DrawingsNames, indicatorLabelById, MAIN_PANE_INDEX } from '@src/constants';
import { ModalRenderer } from '@src/core/ModalRenderer';
import { SeriesFactory, SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { t } from '@src/translations';
import { ActiveDrawingTool, Direction, OHLCConfig, TooltipConfig } from '@src/types';
import {
  CompareSnapshot,
  DOMObjectSnapshot,
  IndicatorSnapshot,
  ISerializable,
  PaneSnapshot,
  PriceScaleSide,
  PriceScaleSnapshot,
} from '@src/types/snapshot';
import { ensureDefined } from '@src/utils';

export interface PaneParams {
  id: number;
  lwcChart: IChartApi;
  eventManager: EventManager;
  DOM: DOMModel;
  isMainPane: boolean;
  ohlcConfig: OHLCConfig;
  dataSource: DataSource | null; // todo: deal with dataSource. На каких то пейнах он нужен, на каких то нет
  basedOn?: Pane; // Pane на котором находится главная серия, или серия, по которой строятся серии на текущем пейне
  subscribeChartEvent: ChartMouseEvents['subscribe'];
  tooltipConfig: TooltipConfig;
  onDelete: () => void;
  chartContainer: HTMLElement;
  modalRenderer: ModalRenderer;
  initialPriceScales?: PriceScaleSnapshot[];
  onPriceScaleStateChange: () => void;
  leftPriceScaleVisible: boolean;
  rightPriceScaleVisible: boolean;
  hotkeys: Hotkeys;
  addDrawingManager: (manager: DrawingsManager, paneId: number) => void;
  removeDrawingManager: (paneId: number) => void;
  setActiveTool: (name: ActiveDrawingTool) => void;
  getActiveTool: () => ActiveDrawingTool;
  getIsEndlessMode: () => boolean;
  continueDrawing: (name: DrawingsNames) => void;
}

// todo: Pane, ему должна принадлежать mainSerie, а также IndicatorManager и drawingsManager, mouseEvents. Также перекинуть соответствующие/необходимые свойства из чарта, и из чарта удалить
// todo: Учитывать, что есть линейка, которая рисуется одна для всех пейнов
// todo: в CompareManage, при создании нового пейна для сравнения - инициализируем новый dataSource, принадлежащий только конкретному пейну. Убираем возможность добавлять индикаторы на такие пейны
// todo: на каждый символ свой DataSource (учитывать что есть MainPane и "главный" DataSource, который инициализиурется во время старта moexChart)
// todo: сделать два разных представления для compare, в зависимости от отображения на главном пейне или на второстепенном
export class Pane implements ISerializable<PaneSnapshot> {
  private readonly id: number;
  private readonly isMain: boolean;
  private mainSeries = new BehaviorSubject<SeriesStrategies | null>(null); // Main Series. Exists in a single copy

  // todo: Отвратительный нейминг. Нужно оставить главной только эту серию и переименовать её localMainSeries => mainSerie
  // Если вдруг понадобится главная серия главного пейна, то брать из КоллекцииПейнов(-сейчас PaneManager)
  // serie to attach drawings
  private localMainSeries = new BehaviorSubject<SeriesStrategies | null>(null);
  private legend!: Legend;
  private tooltip: TooltipService | undefined;
  private readonly indicatorsMap = new BehaviorSubject<Map<string, Indicator>>(new Map());
  private readonly lwcPane: IPaneApi<Time>;
  private readonly lwcChart: IChartApi;
  private readonly eventManager: EventManager;
  private readonly drawingsManager: DrawingsManager;
  private legendContainer!: HTMLElement;
  private paneOverlayContainer!: HTMLElement;
  private legendRenderer!: UIRenderer;
  private tooltipRenderer: UIRenderer | undefined;
  private readonly modalRenderer: ModalRenderer;
  private readonly leftPriceScale: PriceScale;
  private readonly rightPriceScale: PriceScale;
  private readonly priceScaleControls: PriceScaleControls;
  private mainSerieSub?: Subscription;
  private readonly subscribeChartEvent: ChartMouseEvents['subscribe'];
  private readonly onDelete: () => void;
  private readonly onPriceScaleStateChange: () => void;
  private readonly subscriptions = new Subscription();
  private paneContainerSyncFrameId: number | null = null;

  constructor({
    lwcChart,
    eventManager,
    dataSource,
    DOM,
    isMainPane,
    ohlcConfig,
    id,
    basedOn,
    subscribeChartEvent,
    tooltipConfig,
    onDelete,
    chartContainer,
    modalRenderer,
    initialPriceScales = [],
    onPriceScaleStateChange,
    leftPriceScaleVisible,
    rightPriceScaleVisible,
    hotkeys,
    addDrawingManager,
    removeDrawingManager,
    setActiveTool,
    getActiveTool,
    getIsEndlessMode,
    continueDrawing,
  }: PaneParams) {
    this.onDelete = onDelete;
    this.onPriceScaleStateChange = onPriceScaleStateChange;
    this.eventManager = eventManager;
    this.lwcChart = lwcChart;
    this.modalRenderer = modalRenderer;
    this.subscribeChartEvent = subscribeChartEvent;
    this.isMain = isMainPane;
    this.id = id;

    if (isMainPane) {
      this.lwcPane = this.lwcChart.panes()[MAIN_PANE_INDEX];
    } else {
      this.lwcPane = this.lwcChart.addPane(true);
    }

    this.leftPriceScale = this.createPriceScale(Direction.Left, initialPriceScales, leftPriceScaleVisible);
    this.rightPriceScale = this.createPriceScale(Direction.Right, initialPriceScales, rightPriceScaleVisible);

    // TODO: Перенести PriceScaleControls внутрь PriceScale, чтобы каждая шкала владела собственными контролами, а PriceScaleControls работал только с одной шкалой.
    this.priceScaleControls = new PriceScaleControls({
      leftPriceScale: this.leftPriceScale,
      rightPriceScale: this.rightPriceScale,
      onPriceScaleChange: this.handlePriceScaleStateChange,
    });

    this.initializeLegend({ ohlcConfig });

    this.tooltip = new TooltipService({
      config: tooltipConfig,
      legend: this.legend,
      paneOverlayContainer: this.paneOverlayContainer,
    });

    this.tooltipRenderer = new ReactRenderer(this.paneOverlayContainer);

    this.tooltipRenderer.renderComponent(
      <ChartTooltip
        formatObs={this.eventManager.getChartOptionsModel()}
        timeframeObs={this.eventManager.getTimeframeObs()}
        viewModel={this.tooltip.getTooltipViewModel()}
        // ohlcConfig={this.legend.getConfig()}
        ohlcConfig={ohlcConfig}
        tooltipConfig={this.tooltip.getConfig()}
      />,
    );

    if (dataSource) {
      this.initializeMainSerie({ lwcChart, dataSource });
    } else if (basedOn) {
      this.mainSeries = basedOn.getMainSerie();
      this.mainSeries.subscribe(() => {
        this.rebindIndicators();
      });
    } else {
      console.error('[Pane]: There is no any mainSerie for new pane');
    }

    this.drawingsManager = new DrawingsManager({
      // todo: менеджер дровингов должен быть один на чарт, не на пейн
      pane: this,
      eventManager,
      DOM,
      mainSeries$: this.localMainSeries.asObservable(),
      lwcChart,
      container: chartContainer,
      modalRenderer: this.modalRenderer,
      paneId: this.id,
      hotkeys,
      setActiveTool,
      getActiveTool,
      getIsEndlessMode,
      continueDrawing,
    });

    addDrawingManager(this.drawingsManager, this.id);

    this.subscriptions.add(() => removeDrawingManager(this.id));
    this.subscriptions.add(
      this.drawingsManager.entities().subscribe((drawings) => {
        const hasRuler = drawings.some((drawing) => drawing.getDrawingName() === DrawingsNames.ruler);

        this.legendContainer.style.display = hasRuler ? 'none' : '';
      }),
    );
  }

  public getLocalMainSeries = () => {
    return this.localMainSeries.value;
  };

  public setLocalMainSeries = (next: SeriesStrategies) => {
    if (!this.isMain) {
      this.localMainSeries.next(next);
    }
  };

  public isMainPane = () => {
    return this.isMain;
  };

  public getDrawingsSnapshot(): DrawingsManagerSnapshot {
    return this.drawingsManager.getSnapshot();
  }

  public setDrawingsSnapshot(snapshot: DrawingsManagerSnapshot): void {
    this.drawingsManager.setSnapshot(snapshot);
  }

  public getMainSerie = () => {
    return this.mainSeries;
  };

  public getId = () => {
    return this.id;
  };

  public isReady = async (interval = 50): Promise<void> => {
    return new Promise((resolve) => {
      const check = () => {
        if (this.lwcPane.getHTMLElement() === null) {
          setTimeout(check, interval);
        } else {
          resolve();
        }
      };

      check();
    });
  };

  public getHTMLElement = () => {
    return this.lwcPane.getHTMLElement();
  };

  public paneIndex = () => {
    return this.lwcPane.paneIndex();
  };

  public getPriceScale(side: PriceScaleSide): PriceScale {
    return side === Direction.Left ? this.leftPriceScale : this.rightPriceScale;
  }

  public setIndicator(indicatorId: string, indicator: Indicator): void {
    const map = this.indicatorsMap.value;

    map.set(indicatorId, indicator);
    this.indicatorsMap.next(map);
    this.priceScaleControls.refresh();
  }

  public removeIndicator(indicatorId: string): void {
    const map = this.indicatorsMap.value;

    map.delete(indicatorId);
    this.indicatorsMap.next(map);
    this.priceScaleControls.refresh();

    if (map.size === 0 && !this.isMain) {
      this.onDelete();
    }
  }

  public getDrawingManager(): DrawingsManager {
    return this.drawingsManager;
  }

  public schedulePaneContainerSync(): void {
    if (this.paneContainerSyncFrameId !== null) {
      return;
    }

    this.paneContainerSyncFrameId = requestAnimationFrame(() => {
      this.paneContainerSyncFrameId = null;
      this.syncPaneContainers();
    });
  }

  public refreshPriceScaleControls(): void {
    this.priceScaleControls.refresh();
  }

  public resetPriceScalesAutoScale(): void {
    this.leftPriceScale.enableAutoScale();
    this.rightPriceScale.enableAutoScale();
    this.handlePriceScaleStateChange();
  }

  public getSnapshot(): PaneSnapshot {
    const indicators: (DOMObjectSnapshot & (IndicatorSnapshot | CompareSnapshot))[] = [];

    this.indicatorsMap.value.forEach((indicator) => {
      indicators.push(indicator.getSnapshot());
    });

    return {
      isMain: this.isMain,
      id: this.id,
      indicators,
      drawings: this.getDrawingsSnapshot(),
      priceScales: [this.leftPriceScale.getSnapshot(), this.rightPriceScale.getSnapshot()],
    };
  }

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

    this.drawingsManager.destroy();

    this.subscriptions.unsubscribe();
    this.tooltip?.destroy();
    this.legend?.destroy();
    this.legendRenderer.destroy();
    this.tooltipRenderer?.destroy();
    this.priceScaleControls.destroy();
    this.legendContainer.remove();
    this.paneOverlayContainer.remove();
    this.indicatorsMap.complete();
    this.mainSerieSub?.unsubscribe();
    this.localMainSeries.complete();

    if (this.isMain) {
      this.mainSeries.value?.destroy();
      this.mainSeries.complete();
    }
  }

  private createPriceScale(
    side: PriceScaleSide,
    initialPriceScales: PriceScaleSnapshot[],
    initialVisible: boolean,
  ): PriceScale {
    const initialMode =
      initialPriceScales.find((priceScaleSnapshot) => priceScaleSnapshot.side === side)?.mode ?? PriceScaleMode.Normal;

    return new PriceScale({
      paneId: this.id,
      side,
      pane: this.lwcPane,
      initialMode,
      initialVisible,
      hasVisibleSeriesData: () => this.hasVisibleSeriesData(side),
    });
  }

  private hasVisibleSeriesData(side: PriceScaleSide): boolean {
    const mainSeries = this.mainSeries.value;

    if (this.isMain && side === Direction.Right && mainSeries?.isVisible() && mainSeries.data().length > 0) {
      return true;
    }

    const indicators = Array.from(this.indicatorsMap.value.values());

    for (let indicatorIndex = 0; indicatorIndex < indicators.length; indicatorIndex += 1) {
      const series = Array.from(indicators[indicatorIndex].getSeriesMap().values());

      for (let seriesIndex = 0; seriesIndex < series.length; seriesIndex += 1) {
        const currentSeries = series[seriesIndex];
        const options = currentSeries.options();
        const seriesPriceScaleSide = options.priceScaleId ?? Direction.Right;

        if (currentSeries.isVisible() && currentSeries.data().length > 0 && seriesPriceScaleSide === side) {
          return true;
        }
      }
    }

    return false;
  }

  private handlePriceScaleStateChange = (): void => {
    this.priceScaleControls.refresh();
    this.onPriceScaleStateChange();
  };

  private initializeLegend({ ohlcConfig }: { ohlcConfig: OHLCConfig }): void {
    const { legendContainer, paneOverlayContainer } = ContainerManager.createPaneContainers();

    this.legendContainer = legendContainer;
    this.paneOverlayContainer = paneOverlayContainer;
    this.legendRenderer = new ReactRenderer(legendContainer);

    this.schedulePaneContainerSync();

    this.legend = new Legend({
      config: ohlcConfig,
      indicators: this.indicatorsMap,
      eventManager: this.eventManager,
      subscribeChartEvent: this.subscribeChartEvent,
      mainSeries: this.isMain ? this.mainSeries : null,
      paneId: this.id,
      paneIndex: this.paneIndex,
      openIndicatorSettings: (indicatorId, indicator) => {
        let settings = indicator.getSettingsValues();

        this.modalRenderer.renderComponent(
          <EntitySettingsModal
            tabs={[
              {
                key: 'arguments',
                label: t('Arguments'),
                fields: indicator.getSettingsFields(),
              },
            ]}
            values={settings}
            onChange={(nextSettings) => {
              settings = nextSettings;
            }}
            initialTabKey="arguments"
          />,
          {
            size: 'sm',
            title: indicatorLabelById()[indicatorId],
            onSave: () => indicator.updateSettings(settings),
          },
        );
      },
      // todo: throw isMainPane
    });

    this.legendRenderer.renderComponent(
      <LegendComponent
        ohlcConfig={this.legend.getConfig()}
        viewModel={this.legend.getLegendViewModel()}
      />,
    );
  }

  private rebindIndicators(): void {
    for (const indicator of this.indicatorsMap.value.values()) {
      indicator.recreateSeries();
    }
  }

  private initializeMainSerie({ lwcChart, dataSource }: { lwcChart: IChartApi; dataSource: DataSource }): void {
    this.localMainSeries = this.mainSeries;
    this.mainSerieSub = this.eventManager.subscribeSeriesSelected((nextSeries) => {
      this.mainSeries.value?.destroy();

      const next = ensureDefined(SeriesFactory.create(nextSeries))({
        lwcChart,
        dataSource,
        mainSymbolId$: this.eventManager.symbolId(),
        mainSymbol$: this.eventManager.symbol(),
        mainSerie$: this.mainSeries,
      });

      this.mainSeries.next(next);
      this.rebindIndicators();

      this.priceScaleControls.refresh();
    });
  }

  private syncPaneContainers(): void {
    const lwcPaneElement = this.lwcPane.getHTMLElement();

    if (!lwcPaneElement) {
      this.schedulePaneContainerSync();

      return;
    }

    /*
      Внутри lightweight-chart DOM построен как таблица из 3 td
      [0] left priceScale, [1] center chart, [2] right priceScale
      Кладём легенду в td[1] и тогда легенда сама будет адаптироваться при изменении ширины шкал
    */
    const cells = lwcPaneElement.querySelectorAll<HTMLTableCellElement>(':scope > td');
    const chartCell = cells.item(1);

    if (!chartCell) {
      this.schedulePaneContainerSync();
      return;
    }

    chartCell.style.position = 'relative';
    chartCell.appendChild(this.legendContainer);
    chartCell.appendChild(this.paneOverlayContainer);

    this.priceScaleControls.mount(lwcPaneElement);
  }
}


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

import { DataSource } from '@core/DataSource';
import { DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { DrawingsManagerCollection } from '@core/DrawingsManagerCollection';
import { Pane, PaneParams } from '@core/Pane';
import { PriceAxisLabels } from '@core/PriceAxisLabels';
import { DrawingsNames } from '@src/constants';
import { ActiveDrawingTool, Direction } from '@src/types';
import { ISerializable, PaneSnapshot, PriceScaleSide, PriceScaleSnapshot } from '@src/types/snapshot';

import type { Indicator } from '@core/Indicator';
import type { IChartApi, LogicalRange, MouseEventParams } from 'lightweight-charts';

interface PaneManagerParams
  extends Omit<
    PaneParams,
    'id' | 'isMainPane' | 'basedOn' | 'onDelete' | 'initialPriceScales' | CollectionDependencies
  > {
  panesSnapshot: PaneSnapshot[];
}

type CollectionDependencies =
  | 'onPriceScaleStateChange'
  | 'leftPriceScaleVisible'
  | 'rightPriceScaleVisible'
  | 'addDrawingManager'
  | 'removeDrawingManager'
  | 'setActiveTool'
  | 'getActiveTool'
  | 'getIsEndlessMode'
  | 'continueDrawing';

interface PaneManagerStartParams {
  compareEntities$: Observable<Indicator[]>;
  indicatorEntities$: Observable<Indicator[]>;
}

type SharedPaneParams = Omit<PaneManagerParams, 'panesSnapshot'>;

// todo: PaneManager, регулирует порядок пейнов. Знает про MainPane.
// todo: Также перекинуть соответствующие/необходимые свойства из чарта, и из чарта удалить
// todo: в CompareManage, при создании нового пейна для сравнения - инициализируем новый dataSource, принадлежащий только конкретному пейну. Убираем возможность добавлять индикаторы на такие пейны
// todo: на каждый символ свой DataSource (учитывать что есть MainPane и "главный" DataSource, который инициализиурется во время старта moexChart)
// todo: сделать два разных представления для compare, в зависимости от отображения на главном пейне или на второстепенном
export class PaneManager implements ISerializable<PaneSnapshot[]> {
  private readonly sharedPaneParams: SharedPaneParams;
  private readonly lwcChart: IChartApi;
  private readonly panesMap = new Map<number, Pane>();

  private mainPane: Pane;
  private nextPaneId: number;
  private priceAxisLabels: PriceAxisLabels | null = null;
  private leftPriceScaleVisible = false;
  private rightPriceScaleVisible = true;
  private drawingsManagerCollection: DrawingsManagerCollection;
  private readonly subscriptions = new Subscription();

  constructor({ panesSnapshot, ...sharedPaneParams }: PaneManagerParams) {
    this.sharedPaneParams = {
      ...sharedPaneParams,
    };
    this.lwcChart = sharedPaneParams.lwcChart;

    const mainPaneSnapshot = panesSnapshot.find((paneSnapshot) => paneSnapshot.isMain);
    const mainPaneId = mainPaneSnapshot?.id ?? 0;

    this.drawingsManagerCollection = new DrawingsManagerCollection({
      hotkeys: sharedPaneParams.hotkeys,
    });

    this.mainPane = new Pane({
      ...this.sharedPaneParams,
      ...this.getCollectionDependencies(),
      id: mainPaneId,
      isMainPane: true,
      onDelete: () => {},
      initialPriceScales: mainPaneSnapshot?.priceScales, // todo: add to sharedParams?
    });

    this.panesMap.set(mainPaneId, this.mainPane);

    if (mainPaneSnapshot) {
      this.mainPane.setDrawingsSnapshot(mainPaneSnapshot.drawings);
    }

    const greatestPaneId = panesSnapshot.reduce(
      (greatestId, paneSnapshot) => Math.max(greatestId, paneSnapshot.id),
      mainPaneId,
    );

    this.nextPaneId = greatestPaneId + 1;

    panesSnapshot.forEach((paneSnapshot) => {
      if (paneSnapshot.isMain) {
        return;
      }

      const pane = this.addPane(undefined, paneSnapshot.id, paneSnapshot.priceScales);

      pane.setDrawingsSnapshot(paneSnapshot.drawings);
    });

    this.initClickListener();

    this.syncPaneContainers();
  }

  public start({ compareEntities$, indicatorEntities$ }: PaneManagerStartParams): void {
    this.priceAxisLabels?.destroy();

    this.priceAxisLabels = new PriceAxisLabels({
      mainSeries$: this.mainPane.getMainSerie().asObservable(),
      mainSymbol$: this.sharedPaneParams.eventManager.symbol(),
      compareEntities$,
      indicatorEntities$,
    });
  }

  public getDrawingsCollectionManager(): DrawingsManagerCollection {
    return this.drawingsManagerCollection;
  }

  public setVisibleLogicalRange(logicalRange: LogicalRange | null): void {
    this.priceAxisLabels?.setVisibleLogicalRange(logicalRange);
  }

  public invalidate(): void {
    this.priceAxisLabels?.invalidate();
    this.refreshPriceScaleControls();
  }

  public setPriceScaleSideVisible(side: PriceScaleSide, visible: boolean): void {
    if (side === Direction.Left) {
      this.leftPriceScaleVisible = visible;
    } else {
      this.rightPriceScaleVisible = visible;
    }

    this.panesMap.forEach((pane) => {
      pane.getPriceScale(side).setVisible(visible);
    });
  }

  public getPaneByIndex(index: number): Pane | undefined {
    for (const pane of this.panesMap.values()) {
      if (pane.paneIndex() === index) {
        return pane;
      }
    }

    return undefined;
  }

  public getPaneById(id: number): Pane | undefined {
    return this.panesMap.get(id);
  }

  public getDrawingsSnapshot(): DrawingsManagerSnapshot {
    return this.mainPane.getDrawingsSnapshot();
  }

  public setDrawingsSnapshot(snapshot: DrawingsManagerSnapshot): void {
    this.mainPane.setDrawingsSnapshot(snapshot);
  }

  public getPanes(): Map<number, Pane> {
    return this.panesMap;
  }

  public getMainPane = (): Pane => {
    return this.mainPane;
  };

  public addPane(dataSource?: DataSource, paneId?: number, initialPriceScales?: PriceScaleSnapshot[]): Pane {
    const id = paneId ?? this.nextPaneId++;

    this.nextPaneId = Math.max(this.nextPaneId, id + 1);

    const pane = new Pane({
      ...this.sharedPaneParams,
      ...this.getCollectionDependencies(),
      id,
      isMainPane: false,
      dataSource: dataSource ?? null,
      basedOn: dataSource ? undefined : this.mainPane,
      onDelete: () => this.destroyPane(id),
      initialPriceScales,
    });

    this.panesMap.set(id, pane);
    this.syncPaneContainers();
    this.priceAxisLabels?.invalidate();

    return pane;
  }

  public resetPriceScalesAutoScale(): void {
    this.panesMap.forEach((pane) => {
      pane.resetPriceScalesAutoScale();
    });
  }

  public getSnapshot(): PaneSnapshot[] {
    const snapshot: PaneSnapshot[] = [];

    this.panesMap.forEach((pane) => {
      snapshot.push(pane.getSnapshot());
    });

    return snapshot;
  }

  public destroy(): void {
    this.priceAxisLabels?.destroy();
    this.priceAxisLabels = null;
    this.subscriptions.unsubscribe();

    this.panesMap.forEach((pane) => {
      pane.destroy();
    });

    this.drawingsManagerCollection.destroy();

    this.panesMap.clear();
  }

  private initClickListener(): void {
    const handler = (param: MouseEventParams) => {
      if (param.paneIndex === undefined) {
        return;
      }

      const clickedPane = this.getPaneByIndex(param.paneIndex);

      if (!clickedPane) {
        return;
      }

      this.drawingsManagerCollection.handlePaneClick(clickedPane, param);
    };

    this.lwcChart.subscribeClick(handler);
    this.subscriptions.add(() => this.lwcChart.unsubscribeClick(handler));
  }

  private refreshPriceScaleControls(): void {
    this.panesMap.forEach((pane) => {
      pane.refreshPriceScaleControls();
    });
  }

  private destroyPane(id: number): void {
    const pane = this.panesMap.get(id);

    if (!pane) {
      return;
    }

    const paneIndex = pane.paneIndex();

    this.panesMap.delete(id);
    pane.destroy();

    if (paneIndex >= 0) {
      this.sharedPaneParams.lwcChart.removePane(paneIndex);
    }

    this.syncPaneContainers();
    this.priceAxisLabels?.invalidate();
  }

  private syncPaneContainers(): void {
    this.panesMap.forEach((pane) => {
      pane.schedulePaneContainerSync();
    });
  }

  private getCollectionDependencies(): Pick<PaneParams, CollectionDependencies> {
    return {
      onPriceScaleStateChange: this.handlePriceScaleStateChange,
      leftPriceScaleVisible: this.leftPriceScaleVisible,
      rightPriceScaleVisible: this.rightPriceScaleVisible,
      addDrawingManager: (manager, paneId) => this.drawingsManagerCollection.addDrawingManager(manager, paneId),
      removeDrawingManager: (paneId: number) => this.drawingsManagerCollection.removeDrawingManager(paneId),
      setActiveTool: (name: ActiveDrawingTool) => this.drawingsManagerCollection.setActiveTool(name),
      getActiveTool: () => this.drawingsManagerCollection.getActiveToolValue(),
      getIsEndlessMode: () => this.drawingsManagerCollection.getIsEndlessMode(),
      continueDrawing: (name: DrawingsNames) => this.drawingsManagerCollection.activateDrawingTool(name),
    };
  }

  private handlePriceScaleStateChange = (): void => {
    this.priceAxisLabels?.invalidate();
  };
}


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 { 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 { 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?.();
  }
}