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


            );
          }),
        )
        .subscribe(),
    );
  }

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

      if (!logicalRange) return;

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

      const needsMoreData = logicalRange.from < HISTORY_LOAD_THRESHOLD;

      if (!needsMoreData) return;

      this.scheduleHistoryBatch();
    });
  }
}

function sameSymbolIds(previous: string[], next: string[]): boolean {
  if (previous.length !== next.length) {
    return false;
  }

  const nextSet = new Set(next);

  return previous.every((symbolId) => nextSet.has(symbolId));
}

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,
    defaultVisiblePriceScaleId: Direction.Right,
    layout: {
      background: {
        color: colors.chartBackground,
      },
      textColor: colors.chartTextPrimary,
      panes: {
        separatorColor: colors.chartPaneSeparator,
        separatorHoverColor: colors.chartPaneSeparator,
        enableResize: true,
      },
    },
    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: 10,
      shiftVisibleRangeOnNewBar: true,
      allowShiftVisibleRangeOnWhitespaceReplacement: true,
    },
    rightPriceScale: {
      minimumWidth: 60,
      borderVisible: false,
    },
    leftPriceScale: {
      minimumWidth: 60,
      borderVisible: false,
    },
    localization,
  };
}


















  it('не должен повторно регистрировать символы при смене только интервала', () => {
    const { chart, interval$, setSymbols } = createChartInternals({
      symbolId: 'SBER',
      compareSymbolIds: [],
      interval: Intervals['1Y'],
    });

    chart.setupDataSourceSubs();

    expect(setSymbols).toHaveBeenCalledTimes(1);

    interval$.next(Intervals.All);

    expect(setSymbols).toHaveBeenCalledTimes(1);
    expect(setSymbols).toHaveBeenCalledWith(['SBER']);

    chart.subscriptions.unsubscribe();
  });

  it('должен зарегистрировать новый основной символ и применить к нему активный интервал', async () => {
    const { chart, symbolId$, setSymbols, loadTill } = createChartInternals({
      symbolId: 'SBER',
      compareSymbolIds: [],
      interval: Intervals['1Y'],
    });

    chart.setupDataSourceSubs();

    await flushPromises();

    setSymbols.mockClear();
    loadTill.mockClear();

    symbolId$.next('GAZP');

    expect(setSymbols).toHaveBeenCalledTimes(1);
    expect(setSymbols).toHaveBeenCalledWith(['GAZP']);
    expect(loadTill).toHaveBeenCalledTimes(1);
    expect(loadTill).toHaveBeenCalledWith('GAZP', expect.any(Number));

    chart.subscriptions.unsubscribe();
  });

  it('должен загрузить всю историю для интервала All и применить общий диапазон', async () => {
    const { chart, loadAllHistory, getOldestTime, getLastCandle, setVisibleRange } = createChartInternals({
      symbolId: 'SBER',
      compareSymbolIds: ['GAZP'],
      interval: Intervals.All,
    });

    getOldestTime.mockImplementation((symbol: string) => (symbol === 'SBER' ? 100 : 50));
    getLastCandle.mockImplementation((symbol: string) => ({
      time: symbol === 'SBER' ? 200 : 300,
    }));

    chart.setupDataSourceSubs();

    expect(loadAllHistory).toHaveBeenCalledTimes(2);
    expect(loadAllHistory).toHaveBeenCalledWith('SBER');
    expect(loadAllHistory).toHaveBeenCalledWith('GAZP');

    await flushPromises();

    expect(setVisibleRange).toHaveBeenCalledTimes(1);
    expect(setVisibleRange).toHaveBeenCalledWith({
      from: 50,
      to: 300,
    });

    chart.subscriptions.unsubscribe();
  });

  it('должен прогреть добавленный символ при отсутствии активного интервала', async () => {
    const { chart, getVisibleRange, loadTill } = createChartInternals({
      symbolId: 'SBER',
      compareSymbolIds: [],
      interval: null,
    });

    getVisibleRange.mockReturnValue({
      from: 100,
      to: 200,
    });

    chart.setupDataSourceSubs();

    expect(loadTill).toHaveBeenCalledTimes(1);
    expect(loadTill).toHaveBeenCalledWith('SBER', 100);

    await flushPromises();

    chart.subscriptions.unsubscribe();
  });

  it('не должен применять интервал после отписки', async () => {
    const loading = createDeferred();

    const { chart, loadTill, setVisibleRange } = createChartInternals({
      symbolId: 'SBER',
      compareSymbolIds: [],
      interval: Intervals['1Y'],
    });

    loadTill.mockReturnValue(loading.promise);

    chart.setupDataSourceSubs();

    expect(loadTill).toHaveBeenCalledTimes(1);

    chart.subscriptions.unsubscribe();

    loading.resolve();

    await flushPromises();

    expect(setVisibleRange).not.toHaveBeenCalled();
  });
});