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


import dayjs from 'dayjs';

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

import flatten from 'lodash-es/flatten';
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 { DrawingsManager } from '@core/DrawingsManager';
import { EventManager } from '@core/EventManager';
import { IndicatorManager } from '@core/IndicatorManager';
import { ModalRenderer } from '@core/ModalRenderer';
import { PaneManager } from '@core/PaneManager';
import { PriceAxisLabelsController } from '@core/PriceAxisLabels';
import { CompareManager } from '@src/core/CompareManager';
import { PriceScaleModeController, PriceScaleModeSnapshot } from '@src/core/PriceScale';
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, 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 = 50;

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

/**
 * Абстракция над библиотекой для построения графиков
 */
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 priceAxisLabelsController: PriceAxisLabelsController;
  private priceScaleModeController: PriceScaleModeController;
  private optionsSubscription: Subscription;
  private dataSource: DataSource;
  private chartConfig: Omit<ChartConfig, 'theme' | 'mode'>;
  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 activeSymbols: string[] = [];

  private historyBatchRunning = false;

  constructor({ params, lwcChartConfig }: ChartParams) {
    const {
      eventManager,
      dataSource,
      modalRenderer,
      ohlcConfig,
      tooltipConfig,
      panes: panesSnapshot,
      priceScaleModes = [],
    } = 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 }) => {
        const configToApply = { ...lwcChartConfig, dateFormat, timeFormat, showTime };

        this.lwcChart.applyOptions({
          ...getOptions(configToApply),
          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.priceScaleModeController = new PriceScaleModeController({
      getPaneById: (paneId) => this.paneManager?.getPaneById(paneId),
      initialModes: priceScaleModes,
      onChange: () => {
        this.priceAxisLabelsController?.invalidate();
        this.paneManager?.updatePriceScaleControls();
      },
    });

    this.paneManager = new PaneManager({
      eventManager: this.eventManager,
      panesSnapshot,
      lwcChart: this.lwcChart,
      dataSource,
      DOM: this.DOM,
      ohlcConfig,
      subscribeChartEvent: this.subscribeChartEvent,
      chartContainer: this.container,
      tooltipConfig,
      modalRenderer,
      getPriceScaleMode: (target) => this.priceScaleModeController.getActiveMode(target),
      togglePriceScaleMode: (target, mode) => this.priceScaleModeController.toggleSavedMode(target, mode),
    });

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

    this.indicatorManager = new IndicatorManager({
      eventManager,
      initialIndicators: flatten(
        panesSnapshot.map((pane) => pane.indicators.map((ind) => ({ ...ind, paneId: pane.id }))),
      ),
      DOM: this.DOM,
      dataSource: this.dataSource,
      lwcChart: this.lwcChart,
      paneManager: this.paneManager,
      chartOptions: lwcChartConfig.chartOptions,
    });

    this.compareManager = new CompareManager({
      chart: this.lwcChart,
      initialIndicators: flatten(
        panesSnapshot.map((pane) => pane.indicators.map((ind) => ({ ...ind, paneId: pane.id }))),
      ),
      eventManager: this.eventManager,
      dataSource: this.dataSource,
      indicatorManager: this.indicatorManager,
      paneManager: this.paneManager,
      priceScaleModeController: this.priceScaleModeController,
    });

    this.priceAxisLabelsController = new PriceAxisLabelsController({
      mainSeries$: this.paneManager.getMainPane().getMainSerie().asObservable(),
      mainSymbol$: this.eventManager.symbol(),
      compareEntities$: this.compareManager.entities(),
      indicatorEntities$: this.indicatorManager.entities(),
    });

    this.priceAxisLabelsController.setVisibleLogicalRange(this.lwcChart.timeScale().getVisibleLogicalRange());
    this.priceScaleModeController.applyAll();
    this.paneManager.updatePriceScaleControls();

    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 getDrawingsManager = (): DrawingsManager => {
    return this.paneManager.getDrawingsManager();
  };

  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.lwcChart.applyOptions(getOptions({ ...this.chartConfig, theme, mode }));
    this.priceAxisLabelsController.invalidate();
  }

  public destroy(): void {
    this.priceAxisLabelsController.destroy();
    this.priceScaleModeController.destroy();
    this.mouseEvents.destroy();
    this.compareManager.clear();
    this.subscriptions.unsubscribe();
    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.activeSymbols,
      update: (symbol: string, candle: Candle) => {
        this.dataSource.updateRealtime(symbol, candle);
      },
    };
  }

  public getSnapshot(): ChartSnapshot {
    return {
      panes: this.paneManager.getSnapshot(),
      chartSeriesType: this.eventManager.exportChartSettings().seriesSelected,
      timeframe: this.eventManager.exportChartSettings().timeframe,
      symbol: this.activeSymbols[0],
      priceScaleModes: this.priceScaleModeController.getSnapshot(),
    };
  }

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

    this.historyBatchRunning = true;

    requestAnimationFrame(() => {
      const symbols = this.activeSymbols.slice();

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

        const range = this.lwcChart.timeScale().getVisibleLogicalRange();
        if (range && range.from < HISTORY_LOAD_THRESHOLD) {
          this.scheduleHistoryBatch();
        }
      });
    });
  };

  private setupDataSourceSubs() {
    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 as number;
    };

    const warmupSymbols = (symbols: string[]) => {
      if (!symbols.length) return;

      const from = getWarmupFrom();
      if (!from) return;

      Promise.all(symbols.map((symbol) => this.dataSource.loadTill(symbol, from))).catch((error) => {
        console.error('[Chart] Ошибка при прогреве символов:', error);
      });
    };
    const symbols$ = combineLatest([this.eventManager.symbol(), this.compareManager.itemsObs()]).pipe(
      map(([main, items]) => Array.from(new Set([main, ...items.map((i) => i.symbol)]))),
    );

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

          if (!interval) return;

          if (interval === Intervals.All) {
            Promise.all(symbols.map((s) => this.dataSource.loadAllHistory(s)))
              .then(() => {
                requestAnimationFrame(() => this.lwcChart.timeScale().fitContent());
              })
              .catch((error) => console.error('[Chart] Ошибка при загрузке всей истории:', error));

            return;
          }

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

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

    this.subscriptions.add(
      symbols$.subscribe((symbols) => {
        const prevSymbols = this.activeSymbols;
        this.activeSymbols = symbols;

        this.dataSource.setSymbols(symbols);

        const prevSet = new Set(prevSymbols);
        const added: string[] = [];

        for (let i = 0; i < symbols.length; i += 1) {
          const s = symbols[i];
          if (!s) continue;
          if (prevSet.has(s)) continue;
          added.push(s);
        }

        if (added.length) {
          warmupSymbols(added);
        }
      }),
    );
  }

  private setupHistoricalDataLoading(): void {
    // todo (не)вызвать loadMoreHistory после проверки на необходимость дозагрузки после смены таймфрейма
    this.mouseEvents.subscribe('visibleLogicalRangeChange', (logicalRange: LogicalRange | null) => {
      this.priceAxisLabelsController.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,
    },
    rightPriceScale: {
      textColor: colors.chartTextPrimary,
      borderVisible: false,
    },
    localization,
  };
}



import { IChartApi, IPaneApi, IPriceScaleApi, 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 { Indicator } from '@core/Indicator';
import { Legend } from '@core/Legend';
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 { PriceScaleControlsController, PriceScaleTarget } from '@src/core/PriceScale';
import { SeriesFactory, SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { t } from '@src/translations';
import { Direction, OHLCConfig, TooltipConfig } from '@src/types';
import { DOMObjectSnapshot, IndicatorSnapshot, ISerializable, PaneSnapshot } 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;
  getPriceScaleMode: (target: PriceScaleTarget) => PriceScaleMode;
  togglePriceScaleMode: (target: PriceScaleTarget, mode: PriceScaleMode) => 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 isMain: boolean;
  private mainSeries: BehaviorSubject<SeriesStrategies | null> = new BehaviorSubject<SeriesStrategies | null>(null); // Main Series. Exists in a single copy
  private legend!: Legend;
  private tooltip: TooltipService | undefined;

  private indicatorsMap: BehaviorSubject<Map<string, Indicator>> = new BehaviorSubject<Map<string, Indicator>>(
    new Map(),
  );

  private lwcPane: IPaneApi<Time>;
  private lwcChart: IChartApi;

  private eventManager: EventManager;
  private drawingsManager: DrawingsManager;

  private legendContainer!: HTMLElement;
  private paneOverlayContainer!: HTMLElement;
  private legendRenderer!: UIRenderer;
  private tooltipRenderer: UIRenderer | undefined;
  private modalRenderer: ModalRenderer;

  private priceScaleControlsController!: PriceScaleControlsController;

  private mainSerieSub!: Subscription;
  private subscribeChartEvent: ChartMouseEvents['subscribe'];
  private onDelete: () => void;
  private subscriptions = new Subscription();
  private paneContainerSyncFrameId: number | null = null;

  constructor({
    lwcChart,
    eventManager,
    dataSource,
    DOM,
    isMainPane,
    ohlcConfig,
    id,
    basedOn,
    subscribeChartEvent,
    tooltipConfig,
    onDelete,
    chartContainer,
    modalRenderer,
    getPriceScaleMode,
    togglePriceScaleMode,
  }: PaneParams) {
    this.onDelete = onDelete;
    this.eventManager = eventManager;
    this.lwcChart = lwcChart;
    this.modalRenderer = modalRenderer;
    this.subscribeChartEvent = subscribeChartEvent;
    this.isMain = isMainPane ?? false;
    this.id = id;

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

    this.priceScaleControlsController = new PriceScaleControlsController({
      chartContainer,
      getPaneElement: () => this.lwcPane.getHTMLElement(),
      getPriceScale: (priceScaleId) => this.getPriceScale(priceScaleId),
      getPriceScaleTarget: (priceScaleId) => this.getPriceScaleTarget(priceScaleId),
      hasPriceScaleSeries: (priceScaleId) => this.hasPriceScaleSeries(priceScaleId),
      getPriceScaleMode,
      togglePriceScaleMode,
    });

    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();
    } else {
      console.error('[Pane]: There is no any mainSerie for new pane');
    }

    this.drawingsManager = new DrawingsManager({
      // todo: менеджер дровингов должен быть один на чарт, не на пейн
      eventManager,
      DOM,
      mainSeries$: this.mainSeries.asObservable(),
      lwcChart,
      container: chartContainer,
      modalRenderer: this.modalRenderer,
      paneId: 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 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 paneIndex = () => {
    return this.lwcPane.paneIndex();
  };

  public getPriceScale(priceScaleId: string): IPriceScaleApi {
    return this.lwcChart.priceScale(priceScaleId, this.paneIndex());
  }

  public getPriceScaleTarget(priceScaleId: string): PriceScaleTarget {
    return {
      paneId: this.id,
      priceScaleId,
    };
  }

  public hasPriceScaleSeries(priceScaleId: Direction): boolean {
    if (priceScaleId === Direction.Right && this.mainSeries.value) {
      return true;
    }

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

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

      for (let j = 0; j < series.length; j += 1) {
        if (this.isSeriesOnPriceScale(series[j], priceScaleId)) {
          return true;
        }
      }
    }

    return false;
  }

  private isSeriesOnPriceScale(series: SeriesStrategies, priceScaleId: Direction): boolean {
    const options = series.options();
    const seriesPriceScaleId = options.priceScaleId ?? Direction.Right;

    return options.visible !== false && seriesPriceScaleId === priceScaleId;
  }

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

    map.set(indicatorId, indicator);

    this.indicatorsMap.next(map);
  }

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

    map.delete(indicatorId);

    this.indicatorsMap.next(map);

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

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

  private initializeLegend({ ohlcConfig }: { ohlcConfig: OHLCConfig }) {
    const { legendContainer, paneOverlayContainer } = ContainerManager.createPaneContainers();
    this.legendContainer = legendContainer;
    this.paneOverlayContainer = paneOverlayContainer;
    this.legendRenderer = new ReactRenderer(legendContainer);

    this.schedulePaneContainerSync();

    // todo: переписать код ниже под логику пейнов
    // /*
    //   Внутри lightweight-chart DOM построен как таблица из 3 td
    //   [0] left priceScale, [1] center chart, [2] right priceScale
    //   Кладём легенду в td[1] и тогда легенда сама будет адаптироваться при изменении ширины шкал
    // */
    // requestAnimationFrame(() => {
    //   const root = chartAreaContainer.querySelector('.tv-lightweight-charts');
    //   console.log(root)
    //   const table = root?.querySelector('table');
    //   console.log(table)
    //
    //   const htmlCollectionOfPanes = table?.getElementsByTagName('td')
    //   console.log(htmlCollectionOfPanes)
    //
    //   const centerId = htmlCollectionOfPanes?.[1];
    //   console.log(centerId)
    //
    //   if (centerId && legendContainer && legendContainer.parentElement !== centerId) {
    //     centerId.appendChild(legendContainer);
    //   }
    // });
    // /*
    //   Внутри lightweight-chart DOM построен как таблица из 3 td
    //   [0] left priceScale, [1] center chart, [2] right priceScale
    //   Кладём легенду в td[1] и тогда легенда сама будет адаптироваться при изменении ширины шкал
    // */
    // requestAnimationFrame(() => {
    //   const root = chartAreaContainer.querySelector('.tv-lightweight-charts');
    //   const table = root?.querySelector('table');
    //   const centerId = table?.getElementsByTagName('td')?.[1];
    //
    //   if (centerId && legendContainer && legendContainer.parentElement !== centerId) {
    //     centerId.appendChild(legendContainer);
    //   }
    // });

    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.getSettings();

        this.modalRenderer.renderComponent(
          <EntitySettingsModal
            tabs={[{ key: 'arguments', label: t('Arguments'), fields: indicator.getSettingsConfig() }]}
            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 initializeMainSerie({ lwcChart, dataSource }: { lwcChart: IChartApi; dataSource: DataSource }) {
    this.mainSerieSub = this.eventManager.subscribeSeriesSelected((nextSeries) => {
      this.mainSeries.value?.destroy();

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

      this.mainSeries.next(next);
    });
  }

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

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

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

    lwcPaneElement.style.position = 'relative';

    lwcPaneElement.appendChild(this.legendContainer);
    lwcPaneElement.appendChild(this.paneOverlayContainer);

    this.priceScaleControlsController.mount();
  }

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

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

    const snap = {
      isMain: this.isMain,
      id: this.id,
      indicators,
      drawings: this.getDrawingsSnapshot(),
    };

    return snap;
  }

  public updatePriceScaleControls(): void {
    this.priceScaleControlsController.update();
  }

  public resetPriceScalesAutoScale(): void {
    this.priceScaleControlsController.resetAutoScale();
  }

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

    this.subscriptions.unsubscribe();
    this.tooltip?.destroy();
    this.legend?.destroy();
    this.legendRenderer.destroy();

    this.tooltipRenderer?.destroy();
    this.legendContainer.remove();
    this.paneOverlayContainer.remove();
    this.priceScaleControlsController.destroy();
    this.indicatorsMap.complete();

    this.mainSerieSub?.unsubscribe();

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

    const paneIndex = this.paneIndex();

    if (paneIndex >= 0) {
      try {
        this.lwcChart.removePane(paneIndex);
      } catch (e) {
        console.log(e);
      }
    }
  }
}


import { DataSource } from '@core/DataSource';
import { DrawingsManager, DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { Pane, PaneParams } from '@core/Pane';
import { ISerializable, PaneSnapshot } from '@src/types/snapshot';

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

// todo: PaneManager, регулирует порядок пейнов. Знает про MainPane.
// todo: Также перекинуть соответствующие/необходимые свойства из чарта, и из чарта удалить
// todo: в CompareManage, при создании нового пейна для сравнения - инициализируем новый dataSource, принадлежащий только конкретному пейну. Убираем возможность добавлять индикаторы на такие пейны
// todo: на каждый символ свой DataSource (учитывать что есть MainPane и "главный" DataSource, который инициализиурется во время старта moexChart)
// todo: сделать два разных представления для compare, в зависимости от отображения на главном пейне или на второстепенном

export class PaneManager implements ISerializable<PaneSnapshot[]> {
  private mainPane: Pane;
  private paneChartInheritedParams: PaneManagerParams & { isMainPane: boolean };
  private panesMap: Map<number, Pane> = new Map<number, Pane>();
  private nextPaneId = 0;

  constructor(params: PaneManagerParams) {
    this.paneChartInheritedParams = { ...params, isMainPane: false };

    this.mainPane = new Pane({ ...params, isMainPane: true, id: 0, onDelete: () => {} });

    this.panesMap.set(this.nextPaneId++, this.mainPane);
    this.setup(params.panesSnapshot);
  }

  private setup(panesSnapshot: PaneSnapshot[]) {
    panesSnapshot.forEach((paneSnap: PaneSnapshot) => {
      const { isMain, id, drawings } = paneSnap;

      this.destroyPane(id, false);

      if (isMain) {
        this.mainPane = new Pane({ ...this.paneChartInheritedParams, isMainPane: true, id: 0, onDelete: () => {} });

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

        this.mainPane.setDrawingsSnapshot(drawings);
      } else {
        const pane = this.addPane(undefined, id);
        pane.setDrawingsSnapshot(drawings);
      }
    });

    this.syncPaneContainers();
  }

  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() {
    return this.panesMap;
  }

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

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

    if (!pane) {
      return;
    }

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

    if (syncAfter) {
      this.syncPaneContainers();
    }
  }

  public addPane(dataSource?: DataSource, paneId?: number): Pane {
    const id = paneId ?? this.nextPaneId++;
    this.nextPaneId = Math.max(this.nextPaneId, id + 1);

    const newPane = new Pane({
      ...this.paneChartInheritedParams,
      id,
      dataSource: dataSource ?? null,
      basedOn: dataSource ? undefined : this.mainPane,
      onDelete: () => this.destroyPane(id),
    });

    this.panesMap.set(id, newPane);
    this.syncPaneContainers();

    return newPane;
  }

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

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

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

    this.updatePriceScaleControls();
  }

  public getDrawingsManager(): DrawingsManager {
    // todo: temp
    return this.mainPane.getDrawingManager();
  }

  public getSnapshot(): PaneSnapshot[] {
    const res: PaneSnapshot[] = [];
    this.panesMap.forEach((pane) => {
      res.push(pane.getSnapshot());
    });

    return res;
  }
}



import { PriceScaleMode } from 'lightweight-charts';

import type { Pane } from '@core/Pane';

export interface PriceScaleTarget {
  paneId: number;
  priceScaleId: string;
}

export interface PriceScaleModeSnapshot extends PriceScaleTarget {
  mode: PriceScaleMode;
}

interface PriceScaleModeControllerParams {
  getPaneById: (paneId: number) => Pane | undefined;
  initialModes?: PriceScaleModeSnapshot[];
  onChange?: () => void;
}

export class PriceScaleModeController {
  private readonly getPaneById: (paneId: number) => Pane | undefined;
  private readonly onChange?: () => void;
  private readonly savedModes = new Map<number, Map<string, PriceScaleMode>>();
  private readonly overrideModes = new Map<number, Map<string, PriceScaleMode>>();

  constructor({ getPaneById, initialModes = [], onChange }: PriceScaleModeControllerParams) {
    this.getPaneById = getPaneById;
    this.onChange = onChange;
    this.setSnapshot(initialModes);
  }

  public getActiveMode(target: PriceScaleTarget): PriceScaleMode {
    return this.getOverrideMode(target) ?? this.getSavedMode(target);
  }

  public getSavedMode(target: PriceScaleTarget): PriceScaleMode {
    return this.savedModes.get(target.paneId)?.get(target.priceScaleId) ?? PriceScaleMode.Normal;
  }

  public setSavedMode(target: PriceScaleTarget, mode: PriceScaleMode): void {
    const savedModeChanged = this.getSavedMode(target) !== mode;
    const hasOverrideMode = this.getOverrideMode(target) !== undefined;

    if (!savedModeChanged && !hasOverrideMode) {
      return;
    }

    this.setMode(this.savedModes, target, mode);
    this.removeMode(this.overrideModes, target);
    this.applyMode(target);
    this.onChange?.();
  }

  public toggleSavedMode(target: PriceScaleTarget, mode: PriceScaleMode): void {
    const nextMode = this.getActiveMode(target) === mode ? PriceScaleMode.Normal : mode;

    this.setSavedMode(target, nextMode);
  }

  public setOverrideMode(target: PriceScaleTarget, mode: PriceScaleMode): void {
    if (mode === PriceScaleMode.Normal) {
      this.clearOverrideMode(target);
      return;
    }

    if (this.getOverrideMode(target) === mode) {
      return;
    }

    this.setMode(this.overrideModes, target, mode);
    this.applyMode(target);
    this.onChange?.();
  }

  public clearOverrideMode(target: PriceScaleTarget): void {
    if (this.getOverrideMode(target) === undefined) {
      return;
    }

    this.removeMode(this.overrideModes, target);
    this.applyMode(target);
    this.onChange?.();
  }

  public applyAll(): void {
    this.getTargets(this.savedModes).forEach((target) => this.applyMode(target));
    this.getTargets(this.overrideModes).forEach((target) => this.applyMode(target));
  }

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

    this.savedModes.forEach((paneModes, paneId) => {
      if (!this.getPaneById(paneId)) {
        return;
      }

      paneModes.forEach((mode, priceScaleId) => {
        snapshot.push({
          paneId,
          priceScaleId,
          mode,
        });
      });
    });

    return snapshot;
  }

  public setSnapshot(snapshot: PriceScaleModeSnapshot[]): void {
    this.savedModes.clear();

    snapshot.forEach(({ paneId, priceScaleId, mode }) => {
      this.setMode(this.savedModes, { paneId, priceScaleId }, mode);
    });
  }

  public destroy(): void {
    this.savedModes.clear();
    this.overrideModes.clear();
  }

  private getOverrideMode(target: PriceScaleTarget): PriceScaleMode | undefined {
    return this.overrideModes.get(target.paneId)?.get(target.priceScaleId);
  }

  private setMode(
    modes: Map<number, Map<string, PriceScaleMode>>,
    target: PriceScaleTarget,
    mode: PriceScaleMode,
  ): void {
    if (mode === PriceScaleMode.Normal) {
      this.removeMode(modes, target);
      return;
    }

    const paneModes = modes.get(target.paneId) ?? new Map<string, PriceScaleMode>();

    paneModes.set(target.priceScaleId, mode);
    modes.set(target.paneId, paneModes);
  }

  private removeMode(modes: Map<number, Map<string, PriceScaleMode>>, target: PriceScaleTarget): void {
    const paneModes = modes.get(target.paneId);

    paneModes?.delete(target.priceScaleId);

    if (paneModes?.size === 0) {
      modes.delete(target.paneId);
    }
  }

  private getTargets(modes: Map<number, Map<string, PriceScaleMode>>): PriceScaleTarget[] {
    const targets: PriceScaleTarget[] = [];

    modes.forEach((paneModes, paneId) => {
      paneModes.forEach((_, priceScaleId) => {
        targets.push({ paneId, priceScaleId });
      });
    });

    return targets;
  }

  private applyMode(target: PriceScaleTarget): void {
    const pane = this.getPaneById(target.paneId);

    if (!pane) {
      return;
    }

    const priceScale = pane.getPriceScale(target.priceScaleId);
    const { autoScale } = priceScale.options();

    priceScale.applyOptions({
      mode: this.getActiveMode(target),
      autoScale,
    });
  }
}



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

import { PriceScaleControls } from '@components/PriceScaleControls';
import { ReactRenderer } from '@core/ReactRenderer';
import { Direction } from '@src/types';

import type { PriceScaleTarget } from './controller';

interface PriceScaleControlsControllerParams {
  chartContainer: HTMLElement;
  getPaneElement: () => HTMLElement | null;
  getPriceScale: (priceScaleId: Direction) => IPriceScaleApi;
  getPriceScaleTarget: (priceScaleId: Direction) => PriceScaleTarget;
  hasPriceScaleSeries: (priceScaleId: Direction) => boolean;
  getPriceScaleMode: (target: PriceScaleTarget) => PriceScaleMode;
  togglePriceScaleMode: (target: PriceScaleTarget, mode: PriceScaleMode) => void;
}

export class PriceScaleControlsController {
  private readonly chartContainer: HTMLElement;
  private readonly getPaneElement: () => HTMLElement | null;
  private readonly getPriceScale: (priceScaleId: Direction) => IPriceScaleApi;
  private readonly getPriceScaleTarget: (priceScaleId: Direction) => PriceScaleTarget;
  private readonly hasPriceScaleSeries: (priceScaleId: Direction) => boolean;
  private readonly getPriceScaleMode: (target: PriceScaleTarget) => PriceScaleMode;
  private readonly togglePriceScaleMode: (target: PriceScaleTarget, mode: PriceScaleMode) => void;

  private readonly container: HTMLElement;
  private readonly renderer: ReactRenderer;

  private paneElement: HTMLElement | null = null;
  private hoveredPriceScaleId: Direction | null = null;

  constructor({
    chartContainer,
    getPaneElement,
    getPriceScale,
    getPriceScaleTarget,
    hasPriceScaleSeries,
    getPriceScaleMode,
    togglePriceScaleMode,
  }: PriceScaleControlsControllerParams) {
    this.chartContainer = chartContainer;
    this.getPaneElement = getPaneElement;
    this.getPriceScale = getPriceScale;
    this.getPriceScaleTarget = getPriceScaleTarget;
    this.hasPriceScaleSeries = hasPriceScaleSeries;
    this.getPriceScaleMode = getPriceScaleMode;
    this.togglePriceScaleMode = togglePriceScaleMode;

    this.container = document.createElement('div');
    this.container.className = 'moex-price-scale-controls';
    this.container.style.position = 'absolute';
    this.container.style.zIndex = '10';
    this.container.style.pointerEvents = 'none';

    this.renderer = new ReactRenderer(this.container);
  }

  public mount(): void {
    const paneElement = this.getPaneElement();

    if (!paneElement) {
      return;
    }

    if (this.paneElement === paneElement && this.container.parentElement === this.chartContainer) {
      this.update();
      return;
    }

    this.unmount();

    this.paneElement = paneElement;

    this.chartContainer.appendChild(this.container);
    this.chartContainer.addEventListener('pointermove', this.handlePointerMove);
    this.chartContainer.addEventListener('pointerleave', this.handlePointerLeave);

    this.update();
  }

  public update(): void {
    if (!this.hoveredPriceScaleId) {
      this.hide();
      return;
    }

    this.render(this.hoveredPriceScaleId);
  }

  public resetAutoScale(): void {
    this.setAutoScale(Direction.Left, true);
    this.setAutoScale(Direction.Right, true);
    this.update();
  }

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

  private handlePointerMove = (event: PointerEvent): void => {
    if (!this.paneElement) {
      return;
    }

    const chartRect = this.chartContainer.getBoundingClientRect();
    const paneRect = this.paneElement.getBoundingClientRect();

    const isInsidePane = event.clientY >= paneRect.top && event.clientY < paneRect.bottom;

    const nextPriceScaleId = isInsidePane
      ? this.getHoveredPriceScaleId(event.clientX - chartRect.left, chartRect.width)
      : null;

    if (this.hoveredPriceScaleId === nextPriceScaleId) {
      if (nextPriceScaleId) {
        this.updatePosition(nextPriceScaleId);
      }

      return;
    }

    this.hoveredPriceScaleId = nextPriceScaleId;
    this.update();
  };

  private handlePointerLeave = (): void => {
    this.hoveredPriceScaleId = null;
    this.update();
  };

  private render(priceScaleId: Direction): void {
    if (!this.isPriceScaleAvailable(priceScaleId)) {
      this.hide();
      return;
    }

    this.updatePosition(priceScaleId);

    const target = this.getPriceScaleTarget(priceScaleId);
    const priceScaleMode = this.getPriceScaleMode(target);

    this.renderer.renderComponent(
      <PriceScaleControls
        isAutoScale={this.isAutoScale(priceScaleId)}
        isLogarithmic={priceScaleMode === PriceScaleMode.Logarithmic}
        onToggleAutoScale={() => {
          this.toggleAutoScale(priceScaleId);
          this.update();
        }}
        onToggleLogarithmic={() => {
          this.togglePriceScaleMode(target, PriceScaleMode.Logarithmic);
          this.update();
        }}
      />,
    );

    this.container.classList.add('moex-price-scale-controls_visible');
  }

  private hide(): void {
    this.container.classList.remove('moex-price-scale-controls_visible');
  }

  private getHoveredPriceScaleId(pointerX: number, chartWidth: number): Direction | null {
    const leftWidth = this.getPriceScaleWidth(Direction.Left);
    const rightWidth = this.getPriceScaleWidth(Direction.Right);

    if (this.isPriceScaleAvailable(Direction.Left) && pointerX >= 0 && pointerX <= leftWidth) {
      return Direction.Left;
    }

    if (this.isPriceScaleAvailable(Direction.Right) && pointerX >= chartWidth - rightWidth && pointerX <= chartWidth) {
      return Direction.Right;
    }

    return null;
  }

  private updatePosition(priceScaleId: Direction): void {
    if (!this.paneElement) {
      return;
    }

    const chartRect = this.chartContainer.getBoundingClientRect();
    const paneRect = this.paneElement.getBoundingClientRect();

    const bottomOffset = Math.max(0, chartRect.bottom - paneRect.bottom);

    this.container.style.width = `${this.getPriceScaleWidth(priceScaleId)}px`;
    this.container.style.bottom = `${bottomOffset}px`;

    if (priceScaleId === Direction.Left) {
      this.container.style.left = '0';
      this.container.style.right = '';
      return;
    }

    this.container.style.left = '';
    this.container.style.right = '0';
  }

  private toggleAutoScale(priceScaleId: Direction): void {
    this.setAutoScale(priceScaleId, !this.isAutoScale(priceScaleId));
  }

  private setAutoScale(priceScaleId: Direction, autoScale: boolean): void {
    this.getPriceScale(priceScaleId).setAutoScale(autoScale);
  }

  private isAutoScale(priceScaleId: Direction): boolean {
    return this.getPriceScale(priceScaleId).options().autoScale ?? true;
  }

  private isPriceScaleAvailable(priceScaleId: Direction): boolean {
    const priceScale = this.getPriceScale(priceScaleId);
    const options = priceScale.options();

    return options.visible !== false && priceScale.width() > 0 && this.hasPriceScaleSeries(priceScaleId);
  }

  private getPriceScaleWidth(priceScaleId: Direction): number {
    return this.getPriceScale(priceScaleId).width();
  }

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

    this.paneElement = null;
    this.hoveredPriceScaleId = null;
    this.hide();
  }
}


export { PriceScaleModeController } from './controller';
export type { PriceScaleModeSnapshot, PriceScaleTarget } from './controller';
export { PriceScaleControlsController } from './controls';



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

import { Indicator } from '@core/Indicator';
import { IndicatorsIds, MAIN_PANE_INDEX } from '@src/constants';

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

import { PriceAxisLabelsPrimitive } from './primitive';
import { 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 PriceAxisLabelsControllerOptions {
  mainSeries$: Observable<SeriesStrategies | null>;
  mainSymbol$: Observable<string>;
  compareEntities$: Observable<Indicator[]>;
  indicatorEntities$: Observable<Indicator[]>;
}

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

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

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

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

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 PriceAxisLabelsController {
  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$ }: PriceAxisLabelsControllerOptions) {
    this.subscriptions.add(
      mainSymbol$.subscribe((symbol) => {
        const symbolParts = symbol.split(':');

        this.mainSymbol = symbolParts[symbolParts.length - 1] || symbol;
        this.applyDisplayMode();
        this.scheduleUpdate();
      }),
    );

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

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

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

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

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

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

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

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

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

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

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

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

    const previousSeries = this.mainSeries;

    this.unsubscribeMainSeries();

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

    this.mainSeries = series;

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

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

      series.subscribeDataChanged(this.mainSeriesDataHandler);
    }

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

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

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

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

    this.mainSeriesDataHandler = null;
  }

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

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

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

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

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

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

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

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

        current.subscription.unsubscribe();
      }

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

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

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

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

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

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

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

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

    return sources;
  }

  private getEntitySources(collection: EntityCollection, entity: Indicator): PriceLabelSource[] {
    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 {
      // Серия могла быть удалена раньше контроллера.
    }
  }

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

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

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

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

    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 './layout';
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 state: PriceAxisLabelsRenderState,
    private setMinimumWidth: (width: number) => void,
  ) {}

  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);
      const minimumWidth = measuredLabels.reduce(
        (maximumWidth, label) => Math.max(maximumWidth, label.width + LABEL_EDGE_GAP * 2),
        0,
      );

      this.setMinimumWidth(minimumWidth);

      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 rendererInstance: PriceAxisLabelsRenderer;

  constructor(
    private state: PriceAxisLabelsRenderState,
    setMinimumWidth: (width: number) => void,
  ) {
    this.rendererInstance = new PriceAxisLabelsRenderer(state, setMinimumWidth);
  }

  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 state: PriceAxisLabelsRenderState = {
    labels: [],
    reservedCoordinate: null,
    chart: null,
    series: null,
  };

  private priceAxisPaneView: PriceAxisLabelsPaneView;
  private priceAxisPaneViewList: IPrimitivePaneView[];
  private requestUpdate: (() => void) | null = null;
  private initialMinimumWidth = 0;
  private minimumWidth = 0;
  private pendingMinimumWidth: number | null = null;
  private minimumWidthFrame: number | null = null;

  constructor() {
    this.priceAxisPaneView = new PriceAxisLabelsPaneView(this.state, (width) => {
      this.scheduleMinimumWidth(width);
    });

    this.priceAxisPaneViewList = [this.priceAxisPaneView];
  }

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

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

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

  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;

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

    this.requestUpdate?.();
  }

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

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

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

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

    this.pendingMinimumWidth = minimumWidth;

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

    this.minimumWidthFrame = requestAnimationFrame(() => {
      const { pendingMinimumWidth } = this;

      this.minimumWidthFrame = null;
      this.pendingMinimumWidth = null;

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

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

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

    this.minimumWidth = minimumWidth;
  }

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

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



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

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

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

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

export interface LaidOutPriceAxisLabel extends MeasuredPriceAxisLabel {
  coordinate: number;
}

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


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

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

import { PriceAxisSide } from './types';

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

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

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



export { PriceAxisLabelsController } from './controller';
export { layoutPriceAxisLabels } from './layout';
export { PriceAxisLabelsPrimitive } from './primitive';
export type {
  LaidOutPriceAxisLabel,
  MeasuredPriceAxisLabel,
  PriceAxisLabel,
  PriceAxisLabelsLayoutOptions,
  PriceAxisLabelStyle,
} from './types';


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

import { flatten } from 'lodash-es';
import { BehaviorSubject, distinctUntilChanged, map, Observable } 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 { PriceScaleModeController } from '@src/core/PriceScale';

import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { CompareItem, CompareMode, Direction, IndicatorConfig } from '@src/types';
import { IndicatorSnapshot } from '@src/types/snapshot';
import { createFallbackColor, normalizeColor, normalizeSymbol } from '@src/utils';

import type { PriceScaleTarget } from '@src/core/PriceScale';

interface CompareEntry {
  key: string;
  symbol: string;
  mode: CompareMode;
  paneIndex: number;
  symbol$: BehaviorSubject<string>;
  entity: Indicator;
}

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

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 priceScaleModeController: PriceScaleModeController;

  private readonly entries = new Map<string, CompareEntry>();
  private readonly itemsSubject = new BehaviorSubject<CompareItem[]>([]);
  private readonly entitiesSubject = new BehaviorSubject<Indicator[]>([]);

  private hasPercentageComparison = false;

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

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

    if (!initialIndicators) {
      return;
    }

    this.setup(initialIndicators);
  }

  private async setup(initialIndicators: IndicatorSnapshot[]) {
    for (const indicator of initialIndicators) {
      if (indicator.indicatorType !== undefined) {
        continue;
      }

      if (indicator.config && indicator.config.label) {
        const serie = indicator.config.series[0];

        const compareMode =
          serie.seriesOptions?.priceScaleId === Direction.Left
            ? CompareMode.NewScale
            : indicator.config.newPane
              ? CompareMode.NewPane
              : CompareMode.Percentage;

        // eslint-disable-next-line no-await-in-loop
        await this.setSymbolMode(serie.name, indicator.config.label, compareMode, indicator.paneId);
      }
    }
  }

  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 i = 0; i < keys.length; i += 1) {
      this.removeByKey(keys[i]);
    }
    this.applyPolicy();
    this.publish();
  }

  public async setSymbolMode(
    seriesType: SeriesType,
    symbolRaw: string,
    mode: CompareMode,
    paneId?: number,
  ): Promise<void> {
    const symbol = normalizeSymbol(symbolRaw);
    if (!symbol) return;

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

    const key = makeKey(symbol, mode);
    if (this.entries.has(key)) return;

    const symbol$ = new BehaviorSubject(symbol);

    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
        (ind) => ind.getConfig().series?.[0]?.seriesOptions?.color,
      );
      const existIndicators = Array.from(this.indicatorManager.getIndicators().value.values());
      const usedColorsByIndicatorsRaw = existIndicators.map((ind) =>
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        ind.config?.series?.map((serie) => serie.seriesOptions?.color),
      );
      const usedColorsByIndicators = flatten(usedColorsByIndicatorsRaw).filter((color) => color !== undefined);
      const usedColors = usedColorsByCompare.concat(usedColorsByIndicators);

      const config = getDefaultCompareIndicatorConfig(symbol, 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,
        mainSymbol$: symbol$,
        dataSource: this.dataSource,
        associatedPane,
        config: {
          ...config,
          series: [
            {
              ...config.series[0],
              seriesOptions: {
                ...config.series[0]?.seriesOptions,
                priceScaleId: mode === CompareMode.NewScale ? Direction.Left : Direction.Right,
              },
            },
          ],
          newPane: mode === CompareMode.NewPane,
        },
        zIndex,
        onDelete: () => this.removeByKey(key),
        moveUp,
        moveDown,
        paneId: associatedPane.getId(),
      });
    });

    this.entries.set(key, {
      key,
      symbol,
      mode,
      paneIndex: entity.getPane().getId(),
      symbol$,
      entity,
    });

    this.applyPolicy();
    this.publish();

    await this.dataSource.isReady(symbol);
  }

  public removeSymbolMode(symbolRaw: string, mode: CompareMode): void {
    const symbol = normalizeSymbol(symbolRaw);
    if (!symbol) return;

    this.removeByKey(makeKey(symbol, mode));
    this.applyPolicy();
    this.publish();
  }

  public removeSymbol(symbolRaw: string): void {
    const symbol = normalizeSymbol(symbolRaw);
    if (!symbol) return;

    const all = Array.from(this.entries.entries());
    for (let i = 0; i < all.length; i += 1) {
      const [key, entry] = all[i];

      if (entry.symbol === symbol) {
        this.removeByKey(key);
      }
    }

    this.applyPolicy();
    this.publish();
  }

  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(({ symbol, entity, mode }) => ({
      symbol,
      entity,
      mode,
    }));
  }

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

  private removeByKey(key: string): void {
    const entry = this.entries.get(key);
    if (!entry) return;

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

    this.applyPolicy();
    this.publish();
  }

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

    const items: CompareItem[] = [];
    const entities: Indicator[] = [];

    for (let i = 0; i < values.length; i += 1) {
      items.push({
        symbol: values[i].symbol,
        mode: values[i].mode,
      });

      entities.push(values[i].entity);
    }

    this.itemsSubject.next(items);
    this.entitiesSubject.next(entities);
  }

  private syncPercentageMode(target: PriceScaleTarget, hasPercentageComparison: boolean): void {
    if (this.hasPercentageComparison === hasPercentageComparison) {
      return;
    }

    this.hasPercentageComparison = hasPercentageComparison;

    if (hasPercentageComparison) {
      this.priceScaleModeController.setOverrideMode(target, PriceScaleMode.Percentage);
      return;
    }

    this.priceScaleModeController.clearOverrideMode(target);
  }

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

    let hasPercentageComparison = false;

    const leftScalePaneIds = new Set<number>();
    const additionalPaneIds = new Set<number>();

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

      if (entry.mode === CompareMode.Percentage) {
        hasPercentageComparison = true;
      }

      if (entry.mode === CompareMode.NewScale) {
        leftScalePaneIds.add(pane.getId());
      }

      if (!pane.isMainPane()) {
        additionalPaneIds.add(pane.getId());
      }
    }

    const mainLeftScaleVisible = leftScalePaneIds.has(mainPane.getId());

    this.chart.applyOptions({
      leftPriceScale: {
        visible: mainLeftScaleVisible,
        borderVisible: false,
      },
    });

    this.chart.priceScale(Direction.Right, mainPane.paneIndex()).applyOptions({
      visible: true,
    });

    this.chart.priceScale(Direction.Left, mainPane.paneIndex()).applyOptions({
      visible: mainLeftScaleVisible,
      borderVisible: false,
    });

    const mainRightPriceScaleTarget = mainPane.getPriceScaleTarget(Direction.Right);

    this.syncPercentageMode(mainRightPriceScaleTarget, hasPercentageComparison);

    const additionalPaneIdsList = Array.from(additionalPaneIds.values());

    for (let i = 0; i < additionalPaneIdsList.length; i += 1) {
      const pane = this.paneManager.getPaneById(additionalPaneIdsList[i]);

      if (!pane) {
        continue;
      }

      this.chart.priceScale(Direction.Right, pane.paneIndex()).applyOptions({
        visible: true,
      });

      this.chart.priceScale(Direction.Left, pane.paneIndex()).applyOptions({
        visible: leftScalePaneIds.has(pane.getId()),
        borderVisible: false,
      });
    }

    for (let i = 0; i < list.length; i += 1) {
      const entry = list[i];

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

      if (!pane.isMainPane()) {
        serie.applyOptions({
          priceScaleId: Direction.Right,
        });

        continue;
      }

      serie.applyOptions({
        priceScaleId: entry.mode === CompareMode.NewScale ? Direction.Left : Direction.Right,
      });
    }

    this.paneManager.updatePriceScaleControls();
  }
}

function makeKey(symbol: string, mode: CompareMode): string {
  return `${symbol}|${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);
}

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

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



import { IChartApi } from 'lightweight-charts';
import { BehaviorSubject, map, 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 { 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 baseConfig = snap.config ?? (indicatorsConfigMap()[snap.indicatorType] as IndicatorConfig);

    const config = snap.config
      ? baseConfig
      : applyNextIndicatorColors(baseConfig, this.getUsedIndicatorColorsByType(snap.indicatorType));

    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,

          mainSymbol$: this.eventManager.getSymbol(),
          lwcChart: this.lwcChart,
          dataSource: this.dataSource,
          associatedPane,
          config,
          type: snap.indicatorType,
          chartOptions: this.chartOptions,
        });
      },
    );

    indicatorsMap.set(id, indicatorToSet);

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

  private getUsedIndicatorColorsByType(indicatorType: IndicatorSnapshot['indicatorType']): string[] {
    const colors: string[] = [];

    this.indicatorsMap$.value.forEach((indicator) => {
      if (indicator.getIndicatorType() !== indicatorType) {
        return;
      }

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

    return colors;
  }

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



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

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

interface CreateContainersOptions {
  parentContainer: HTMLElement;
  showBottomPanel?: boolean;
  showMenuButton?: boolean;
}

enum ZIndex {
  Chart = '0',
  Base = '10',
  Modal = '1000',
}

const ContainerLayoutConfig = {
  headerHeight: 36,
  footerHeight: 32,
  toolbarWidth: 42,
  verticalGap: 8,
};

/**
 * Утилита для создания DOM контейнеров
 */
export class ContainerManager {
  private static injectFont(): void {
    const existingLink = document.querySelector('link[href*="fonts.googleapis.com"]');
    if (existingLink) return;

    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,100..900&display=swap';
    document.head.appendChild(link);
  }

  /**
   * Создание контейнеров для графика и UI компонентов
   */
  static createContainers({ parentContainer, showBottomPanel, showMenuButton }: CreateContainersOptions) {
    this.injectFont();

    const { headerHeight, footerHeight, toolbarWidth, verticalGap } = ContainerLayoutConfig;

    parentContainer.innerHTML = '';
    parentContainer.classList.add(CHART_ROOT_CLASSNAME);
    parentContainer.style.height = '100%';
    parentContainer.style.width = '100%';
    parentContainer.style.padding = 'var(--space-1000)';
    parentContainer.style.backgroundColor = 'var(--neutral-0)';
    parentContainer.style.borderRadius = 'var(--space-0500)';

    parentContainer.style.display = 'grid';
    parentContainer.style.rowGap = `${verticalGap}px`;
    parentContainer.style.gridTemplateRows = showBottomPanel
      ? `${headerHeight}px minmax(0, 1fr) ${footerHeight}px`
      : `${headerHeight}px minmax(0, 1fr)`;

    const headerContainer = document.createElement('div');
    headerContainer.style.width = '100%';
    headerContainer.style.height = `${headerHeight}px`;
    headerContainer.style.overflow = 'auto hidden';
    headerContainer.className = styles.scrollableBox;

    const footerContainer = document.createElement('div');
    footerContainer.style.width = '100%';
    footerContainer.style.height = `${footerHeight}px`;

    const chartContainer = document.createElement('div');
    chartContainer.style.height = '100%';
    chartContainer.style.width = '100%';
    chartContainer.style.minWidth = '0';
    chartContainer.style.minHeight = '0';
    chartContainer.style.display = 'grid';
    chartContainer.style.columnGap = 'var(--space-0500)';
    chartContainer.style.gridTemplateColumns = 'minmax(0, 1fr)';

    const chartAreaContainer = document.createElement('div');
    chartAreaContainer.style.position = 'relative';
    chartAreaContainer.style.height = '100%';
    chartAreaContainer.style.minHeight = '0';
    chartAreaContainer.style.minWidth = '0';
    chartAreaContainer.style.cursor = 'crosshair';

    const toolBarContainer = document.createElement('div');
    toolBarContainer.style.height = '100%';
    toolBarContainer.style.minHeight = '0';
    toolBarContainer.style.overflow = 'hidden';

    const controlBarContainer = document.createElement('div');
    controlBarContainer.style.width = '250px';
    controlBarContainer.style.position = 'absolute';
    controlBarContainer.style.left = '50%';
    controlBarContainer.style.transform = 'translateX(-50%)';
    controlBarContainer.style.bottom = 'var(--space-2000)';
    controlBarContainer.style.zIndex = ZIndex.Base;

    const modalContainer = document.createElement('div');
    modalContainer.className = 'moex-chart-modal-container';
    modalContainer.style.position = 'absolute';
    modalContainer.style.width = '100%';
    modalContainer.style.height = '100%';
    modalContainer.style.maxWidth = '100%';
    modalContainer.style.maxHeight = '100%';
    modalContainer.style.zIndex = ZIndex.Modal;
    modalContainer.style.pointerEvents = 'none';

    chartAreaContainer.append(controlBarContainer, modalContainer);
    chartContainer.append(chartAreaContainer);
    parentContainer.append(headerContainer, chartContainer);

    if (showBottomPanel) {
      parentContainer.append(footerContainer);
    }

    const toggleToolbar = () => {
      const mounted = toolBarContainer.isConnected;

      if (mounted) {
        toolBarContainer.remove();
        chartContainer.style.gridTemplateColumns = 'minmax(0, 1fr)';
        return false;
      }

      chartContainer.insertBefore(toolBarContainer, chartAreaContainer);
      chartContainer.style.gridTemplateColumns = `${toolbarWidth}px minmax(0, 1fr)`;
      return true;
    };

    chartContainer.insertBefore(toolBarContainer, chartAreaContainer);
    chartContainer.style.gridTemplateColumns = `${toolbarWidth}px minmax(0, 1fr)`;

    if (!showMenuButton) {
      toggleToolbar();
    }

    return {
      headerContainer,
      footerContainer,

      chartContainer,
      chartAreaContainer,
      toolBarContainer,

      modalContainer,
      controlBarContainer,

      toggleToolbar,
    };
  }

  /**
   * Очистка контейнеров
   */
  static clearContainers(parentContainer: HTMLElement): void {
    parentContainer.innerHTML = '';
  }

  static createPaneContainers() {
    const legendContainer = document.createElement('div');
    legendContainer.style.width = '80%';
    legendContainer.style.position = 'absolute';
    legendContainer.style.top = '0';
    legendContainer.style.left = '0';
    legendContainer.style.zIndex = ZIndex.Base;
    legendContainer.style.pointerEvents = 'none';

    const paneOverlayContainer = document.createElement('div');
    paneOverlayContainer.className = 'moex-chart-pane-overlay-container';
    paneOverlayContainer.style.position = 'absolute';
    paneOverlayContainer.style.inset = '0';
    paneOverlayContainer.style.zIndex = ZIndex.Base;
    paneOverlayContainer.style.pointerEvents = 'none';

    return {
      legendContainer,
      paneOverlayContainer,
    };
  }
}



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

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

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

import type { SyntheticEvent } from 'react';

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

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

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

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



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

.tooltip {
  @include m.tooltipHint;
}

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

  .button {
    @include m.buttonBase;

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



import { DataSource } from '@core/DataSource';
import { DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { ChartSeriesType, IndicatorsIds, Timeframes } from '@lib';
import { PriceScaleModeSnapshot } from '@src/core/PriceScale';
import { IndicatorConfig } from '@src/types/indicator';

export interface ISerializable<T extends object> {
  getSnapshot: () => T;
}

export type InitialSnapshot = {
  timeframe: Timeframes; // todo: move to snap
  chartSeriesType: ChartSeriesType; // todo: move to snap
  symbol: string; // todo: move to snap
};

export type MoexChartSnapshot = {
  // settings: ChartSettingsSnapshot;
  charts: ChartSnapshot[];
};

export type ChartSnapshot = {
  timeframe: Timeframes;
  chartSeriesType: ChartSeriesType;
  symbol: string;
  panes: PaneSnapshot[];
  priceScaleModes?: PriceScaleModeSnapshot[];
};

export type PaneSnapshot = {
  isMain: boolean;
  id: number;
  indicators: IndicatorSnapshot[];
  drawings: DrawingsManagerSnapshot;
};

export type IndicatorSnapshot = Partial<DOMObjectSnapshot> & {
  dataSource?: DataSource;
  indicatorType: IndicatorsIds | undefined; // if indicatorType is undefined, then its compareIndicator
  config?: IndicatorConfig;
};

// todo: move DrawingsManagerSnapshot here

export type DOMObjectSnapshot = {
  id: string;
  name: string;
  zIndex: number;
  hidden: boolean;
  paneId: number;
};



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 { ModalRenderer } from '@core/ModalRenderer';
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, TooltipConfig } from '@src/types';
import { ISerializable, MoexChartSnapshot } 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: (symbol: 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: MoexChartSnapshot;
  chartCollectionPreset: ChartCollectionPreset;

  container: HTMLElement;
  lwcInheritedChartOptions?: ChartTypeOptions;
}

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

  private headerRenderer!: UIRenderer;
  private modalRenderer!: ModalRenderer;
  private toolbarRenderer: UIRenderer | undefined;
  private controlBarRenderer?: UIRenderer;
  private footerRenderer?: 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);

    this.eventManager = new EventManager({
      initialTimeframe: config.snapshot.charts[0].timeframe,
      initialSeries: config.snapshot.charts[0].chartSeriesType,
      initialSymbol: config.snapshot.charts[0].symbol,
      initialChartOptions: config.lwcInheritedChartOptions,
    });

    // 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,
      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.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,
      },
      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);

    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(snap: MoexChartSnapshot) {
    const configConstructorLike: IMoexChart = {
      snapshot: snap,
      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(symbol: string): void {
    if (!symbol) return;

    this.eventManager.setSymbol(symbol);
  }

  private renderAttachments(config: IMoexChart, toggleToolbar: () => boolean) {
    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) {
      this.toolbarRenderer.renderComponent(
        <Toolbar
          toggleDOM={this.chart.getDom().toggleDOM}
          addDrawing={(name) => {
            // todo: deal with new panes logic
            this.chart.getDrawingsManager().addDrawingForce(name);
          }}
          setEndlessDrawingsMode={this.chart.getDrawingsManager().setEndlessDrawingMode}
          isEndlessDrawingsMode$={this.chart.getDrawingsManager().isEndlessDrawingsMode()}
          activateCrosshair={() => this.chart.getDrawingsManager().activateCrosshair()}
          activeTool$={this.chart.getDrawingsManager().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.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();
    }

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

    this.dataSource.destroy();

    ContainerManager.clearContainers(this.rootContainer);
  }
}



{
  "name": "moex-chart",
  "version": "0.1.0",
  "description": "",
  "type": "module",
  "main": "dist/index.cjs",
  "types": "types/index.d.ts",
  "files": [
    "dist",
    "types"
  ],
  "sideEffects": [
    "**/*css",
    "**/*.scss"
  ],
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs",
      "types": "./types/index.d.ts"
    },
    "./package.json": "./package.json",
    "./dist/styles.css": {
      "import": "./dist/styles.css",
      "require": "./dist/styles.css"
    }
  },
  "scripts": {
    "postbuild:storybook": "sed -i 's#<head>#<head>\\n<base href='/storybook/'>#' ./storybook-static/index.html ./storybook-static/iframe.html",
    "clean:dist": "powershell -NoProfile -Command \"if (Test-Path dist) { Remove-Item -Recurse -Force dist }\"",
    "clean:types": "powershell -NoProfile -Command \"if (Test-Path types) { Remove-Item -Recurse -Force types }\"",
    "build:lib:js": "webpack --config webpack.lib.config.cjs",
    "build:lib:types": "tsc --project tsconfig.types.json && tsc-alias -p tsconfig.types.json",
    "build:lib": "npm run clean:dist && npm run clean:types && npm run build:lib:js && npm run build:lib:types",
    "test": "jest",
    "coverage": "jest --coverage",
    "lint:fix": "npx prettier src --write && npx eslint src --fix",
    "lint": "npx eslint src",
    "prettier-check": "npx prettier src --check",
    "prettier-fix": "npx prettier src --write",
    "prepare": "husky",
    "storybook": "storybook dev -p 6006",
    "storybook-local": "cross-env buildType=local storybook dev -p 6006",
    "start": "npm run storybook-local",
    "build-storybook": "storybook build",
    "build-storybook-local": "cross-env buildType=local storybook build",
    "typecheck": "npx tsc -p tsconfig.json --noEmit",
    "typecheck:watch": "npx tsc -p tsconfig.json --noEmit -w"
  },
  "keywords": [],
  "author": "MOEX",
  "license": "UNLICENSED",
  "devDependencies": {
    "@babel/core": "^7.21.0",
    "@babel/preset-env": "^7.28.3",
    "@babel/preset-react": "^7.27.1",
    "@babel/preset-typescript": "^7.27.1",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.10",
    "@storybook/addon-actions": "^7.6.13",
    "@storybook/addon-controls": "^7.6.13",
    "@storybook/addon-docs": "^7.6.13",
    "@storybook/addon-essentials": "^7.6.13",
    "@storybook/addon-interactions": "^7.6.13",
    "@storybook/addon-links": "^7.6.13",
    "@storybook/builder-webpack5": "^7.6.13",
    "@storybook/components": "^7.6.13",
    "@storybook/manager-webpack5": "^6.5.16",
    "@storybook/preset-scss": "^1.0.3",
    "@storybook/react": "^7.6.13",
    "@storybook/react-webpack5": "^7.6.13",
    "@storybook/testing-library": "^0.0.13",
    "@testing-library/dom": "^9.3.4",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@types/jest": "^27.5.2",
    "@types/lodash-es": "^4.17.12",
    "@types/markdown-it": "^14.0.1",
    "@types/markdown-it-link-attributes": "^3.0.5",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.10",
    "@types/react-window": "^1.8.5",
    "@types/sanitize-html": "^2.11.0",
    "@typescript-eslint/eslint-plugin": "^5.52.0",
    "@typescript-eslint/parser": "^5.52.0",
    "autoprefixer": "^10.4.21",
    "babel-loader": "^8.3.0",
    "copy-webpack-plugin": "^11.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^6.7.3",
    "css-minimizer-webpack-plugin": "^3.4.1",
    "dotenv-webpack": "^8.0.1",
    "eslint": "^8.34.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.6.0",
    "eslint-import-resolver-typescript": "^3.10.1",
    "eslint-import-resolver-webpack": "^0.13.2",
    "eslint-plugin-eslint-comments": "^3.2.0",
    "eslint-plugin-import": "^2.31.0",
    "eslint-plugin-jest": "^25.7.0",
    "eslint-plugin-jsx-a11y": "^6.7.1",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.0",
    "husky": "^9.1.5",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.5.0",
    "json5": "^2.2.3",
    "mini-css-extract-plugin": "^2.7.2",
    "postcss": "^8.5.6",
    "postcss-loader": "^4.3.0",
    "prettier": "^3.3.3",
    "react": "^18.2.0",
    "react-docgen-typescript-plugin": "^0.5.1",
    "react-dom": "^18.2.0",
    "react-refresh": "^0.14.0",
    "react-refresh-typescript": "^2.0.8",
    "sass": "^1.58.1",
    "sass-loader": "^13.2.0",
    "storybook": "^7.6.13",
    "storybook-addon-sass-postcss": "^0.1.3",
    "style-loader": "^3.3.1",
    "terser-webpack-plugin": "^5.3.6",
    "ts-jest": "^29.1.5",
    "ts-loader": "^9.4.2",
    "ts-node": "10.9.1",
    "tsc-alias": "^1.8.16",
    "type-fest": "^3.6.1",
    "typescript": "^5.5.3",
    "typescript-plugin-css-modules": "^4.1.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.11.1"
  },
  "dependencies": {
    "@dnd-kit/core": "^6.1.0",
    "@dnd-kit/modifiers": "^7.0.0",
    "@dnd-kit/sortable": "^8.0.0",
    "@dnd-kit/utilities": "^3.2.2",
    "@stomp/stompjs": "^7.1.1",
    "classnames": "^2.3.2",
    "dayjs": "^1.11.7",
    "dotenv": "^16.4.7",
    "exchange-elements": "^0.0.257",
    "fancy-canvas": "2.1.0",
    "lightweight-charts": "^5.0.8",
    "lodash-es": "^4.17.21",
    "rxjs": "^7.8.2",
    "uuid": "^11.0.3"
  },
  "peerDependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "overrides": {
    "@storybook/mdx2-csf": "1.0.0"
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx,css,scss,md,html}": [
      "npm run lint:fix"
    ]
  }
}