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


  "Chart": "Chart",
  "Seasonality": "Seasonality",
  "Price": "Price",
  "Percent": "Percent",
  "Years": "Years",
  "From year": "From year",
  "To year": "To year",
  "Loading seasonality": "Loading seasonality…",
  "No seasonality data": "No data for the selected years",
  "Unable to load seasonality": "Unable to load seasonality",
  "Percentage requires a positive baseline": "Percentage change requires a positive yearly baseline price"


















import classNames from 'classnames';
import { useId, useRef, type ChangeEvent, type PointerEvent } from 'react';

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

interface CommonRangeFieldProps {
  label?: string;
  min?: number;
  max?: number;
  step?: number;
  color?: string;
  suffix?: string;
  size?: 'sm' | 'md';
  disabled?: boolean;
}

interface SingleRangeFieldProps extends CommonRangeFieldProps {
  mode?: 'single';
  value: number;
  onChange: (event: ChangeEvent<HTMLInputElement>) => void;
}

interface IntervalRangeFieldProps extends CommonRangeFieldProps {
  mode: 'range';
  value: readonly [number, number];
  startLabel: string;
  endLabel: string;
  onRangeChange: (value: [number, number]) => void;
}

type RangeFieldProps = SingleRangeFieldProps | IntervalRangeFieldProps;

export const RangeField = (props: RangeFieldProps) => {
  const {
    label,
    min = 0,
    max = 100,
    step = 1,
    color = 'var(--blue-1)',
    suffix = '%',
    size = 'md',
    disabled = false,
  } = props;
  const inputId = useId();
  const trackRef = useRef<HTMLDivElement>(null);
  const dragRef = useRef<{ startX: number; value: [number, number]; width: number } | null>(null);

  if (props.mode !== 'range') {
    return (
      <div className={classNames(styles.range, { [styles.range_sm]: size === 'sm' })}>
        {label && (
          <label htmlFor={inputId} className={styles.range_label}>
            {label}
          </label>
        )}
        <div className={styles.range_wrapper}>
          <input
            id={inputId}
            type="range"
            min={min}
            max={max}
            step={step}
            value={props.value}
            className={styles.range_input}
            style={{ ['--range-color' as string]: color }}
            onChange={props.onChange}
            disabled={disabled}
          />
          <span className={styles.range_value}>
            {props.value}
            {suffix}
          </span>
        </div>
      </div>
    );
  }

  const [from, to] = props.value;
  const span = max - min;
  const left = span > 0 ? ((from - min) / span) * 100 : 0;
  const right = span > 0 ? ((to - min) / span) * 100 : 0;
  const inactive = disabled || span <= 0;
  const stopDrag = () => {
    dragRef.current = null;
  };
  const startDrag = (event: PointerEvent<HTMLDivElement>) => {
    if (inactive || event.button !== 0 || !trackRef.current) return;
    const width = trackRef.current.getBoundingClientRect().width;
    if (width <= 0) return;
    event.preventDefault();
    event.currentTarget.setPointerCapture(event.pointerId);
    dragRef.current = { startX: event.clientX, value: [from, to], width };
  };
  const moveDrag = (event: PointerEvent<HTMLDivElement>) => {
    const drag = dragRef.current;
    if (!drag || inactive) return;
    const rawDelta = ((event.clientX - drag.startX) / drag.width) * span;
    const delta = Math.max(min - drag.value[0], Math.min(max - drag.value[1], Math.round(rawDelta / step) * step));
    props.onRangeChange([drag.value[0] + delta, drag.value[1] + delta]);
  };

  return (
    <div
      className={classNames(styles.range, intervalStyles.interval, { [styles.range_sm]: size === 'sm' })}
      role="group"
      aria-label={label}
      aria-disabled={inactive}
    >
      {label && <span className={styles.range_label}>{label}</span>}
      <div ref={trackRef} className={intervalStyles.track} style={{ ['--range-color' as string]: color }}>
        <div className={intervalStyles.rail} />
        <div
          className={intervalStyles.selection}
          style={{ left: `${left}%`, width: `${right - left}%` }}
          aria-hidden="true"
          onPointerDown={startDrag}
          onPointerMove={moveDrag}
          onPointerUp={stopDrag}
          onPointerCancel={stopDrag}
          onLostPointerCapture={stopDrag}
        />
        <input
          id={`${inputId}-from`}
          type="range"
          min={min}
          max={max}
          step={step}
          value={from}
          aria-label={props.startLabel}
          disabled={inactive}
          className={intervalStyles.input}
          style={{ zIndex: from === to && from === min ? 2 : 4 }}
          onChange={(event) => props.onRangeChange([Math.min(Number(event.currentTarget.value), to), to])}
        />
        <input
          id={`${inputId}-to`}
          type="range"
          min={min}
          max={max}
          step={step}
          value={to}
          aria-label={props.endLabel}
          disabled={inactive}
          className={intervalStyles.input}
          style={{ zIndex: 3 }}
          onChange={(event) => props.onRangeChange([from, Math.max(Number(event.currentTarget.value), from)])}
        />
      </div>
      <div className={intervalStyles.values}>
        <span>
          {from}
          {suffix}
        </span>
        <span>
          {to}
          {suffix}
        </span>
      </div>
    </div>
  );
};

















.interval {
  min-width: 0;

  &[aria-disabled='true'] {
    opacity: 0.5;
  }
}

.track {
  position: relative;
  height: var(--range-thumb-size);
  margin-inline: calc(var(--range-thumb-size) / 2);
  touch-action: none;
}

.rail,
.selection {
  position: absolute;
  top: 50%;
  height: var(--range-track-height);
  transform: translateY(-50%);
  border-radius: 999px;
}

.rail {
  inset-inline: 0;
  background: var(--neutral-9);
}

.selection {
  z-index: 1;
  background: var(--range-color);
  cursor: grab;
  touch-action: none;

  &:active {
    cursor: grabbing;
  }
}

.input {
  position: absolute;
  inset: 0;
  width: calc(100% + var(--range-thumb-size));
  height: var(--range-thumb-size);
  margin: 0;
  margin-left: calc(var(--range-thumb-size) / -2);
  appearance: none;
  background: transparent;
  pointer-events: none;

  &::-webkit-slider-runnable-track {
    height: var(--range-track-height);
    background: transparent;
  }

  &::-moz-range-track {
    height: var(--range-track-height);
    background: transparent;
  }

  &::-moz-range-progress {
    background: transparent;
  }

  &::-webkit-slider-thumb {
    width: var(--range-thumb-size);
    height: var(--range-thumb-size);
    margin-top: calc((var(--range-track-height) - var(--range-thumb-size)) / 2);
    appearance: none;
    border: 1px solid var(--color-field-border);
    border-radius: 50%;
    background: var(--neutral-panel);
    cursor: ew-resize;
    pointer-events: auto;
  }

  &::-moz-range-thumb {
    width: var(--range-thumb-size);
    height: var(--range-thumb-size);
    border: 1px solid var(--color-field-border);
    border-radius: 50%;
    background: var(--neutral-panel);
    cursor: ew-resize;
    pointer-events: auto;
  }

  &:focus-visible {
    outline: none;
  }

  &:focus-visible::-webkit-slider-thumb {
    outline: 2px solid var(--range-color);
    outline-offset: 2px;
  }

  &:focus-visible::-moz-range-thumb {
    outline: 2px solid var(--range-color);
    outline-offset: 2px;
  }

  &:disabled::-webkit-slider-thumb,
  &:disabled::-moz-range-thumb {
    pointer-events: none;
    cursor: default;
  }
}

.values {
  display: flex;
  justify-content: space-between;
  color: var(--neutral-12);
  font-size: var(--range-value-font-size);
}
















import { Divider } from 'exchange-elements/v2';
import { useEffect, useState } from 'react';

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

import { IndicatorsSelect } from '@components/IndicatorsSelect';

import { Button } from '@src/components/Button';
import { SeriesTypeIcon } from '@src/components/SeriesTypeIcon';
import { Tooltip } from '@src/components/Tooltip';
import { IndicatorsIds } from '@src/constants';
import { FullscreenController } from '@src/core/Fullscreen';
import { UndoRedo, type UndoRedoState } from '@src/core/UndoRedo';
import { createInitialSeasonalityState, type ChartView, type SeasonalityState } from '@src/core/Seasonality/types';
import { ChartViewMenu } from '@src/components/Menu/ChartViewMenu';
import { t } from '@src/translations';
import { ChartSeriesType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { useObservable } from '@src/utils';

import { Dropdown } from '../Dropdown';
import { BurgerMenuIcon, CameraIcon, FullscreenIcon, PlusCircleIcon, RedoIcon, SearchIcon, UndoIcon } from '../Icon';
import { SeriesMenu, SnapshotMenu, TimeframesMenu } from '../Menu';

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

const defaultUndoRedoState: UndoRedoState = {
  canUndo: false,
  canRedo: false,
};

const defaultUndoRedoState$ = of(defaultUndoRedoState);
const defaultSeasonalityState = createInitialSeasonalityState();
const defaultSeasonalityState$ = of(defaultSeasonalityState);

interface HeaderProps {
  timeframes: Timeframes[];
  selectedTimeframeObs: Observable<Timeframes>;
  setTimeframe: (value: Timeframes) => void;
  seriesTypes: ChartSeriesType[];
  setSelectedSeries: (next: ChartSeriesType) => void;
  selectedSeriesObs: Observable<ChartSeriesType>;
  showSettingsModal: (() => void) | undefined;
  addIndicatorToChart: (id: IndicatorsIds) => void;
  toggleToolbarVisible: () => boolean;
  showCompareButton: boolean;
  showSymbolSearchButton: boolean;
  undoRedo: UndoRedo | undefined;
  showMenuButton?: boolean;
  showFullscreenButton?: boolean;
  fullscreen: FullscreenController;
  openCompareModal?: () => void;
  openSymbolSearchModal?: () => void;
  copyImage?: () => Promise<void>;
  isMXT: boolean;
  seasonalityStateObs?: Observable<SeasonalityState>;
  setChartView?: (view: ChartView) => void;
}

export function Header({
  setTimeframe,
  selectedTimeframeObs,
  setSelectedSeries,
  selectedSeriesObs,
  timeframes,
  seriesTypes,
  showSettingsModal,
  addIndicatorToChart,
  toggleToolbarVisible,
  showCompareButton,
  showSymbolSearchButton,
  fullscreen,
  undoRedo,
  showFullscreenButton,
  showMenuButton,
  openCompareModal,
  openSymbolSearchModal,
  copyImage,
  isMXT,
  seasonalityStateObs,
  setChartView,
}: HeaderProps) {
  const [isToolbarOpen, setIsToolbarOpen] = useState(showMenuButton ?? false);
  const [isFullscreen, setIsFullscreen] = useState(fullscreen.isFullscreen);

  const undoRedoState = useObservable(undoRedo?.getState() ?? defaultUndoRedoState$, defaultUndoRedoState);

  useEffect(() => {
    const unsubscribe = fullscreen.onChange(() => {
      setIsFullscreen(fullscreen.isFullscreen);
    });

    return unsubscribe;
  }, [fullscreen]);

  const seasonalityState = useObservable(seasonalityStateObs ?? defaultSeasonalityState$, defaultSeasonalityState);
  const isSeasonality = seasonalityState.view === 'seasonality';
  const selectedTimeframe = useObservable(selectedTimeframeObs);
  const selectedSeries = useObservable(selectedSeriesObs);

  const handleOpenToolbar = (): void => {
    setIsToolbarOpen(toggleToolbarVisible());
  };

  return (
    <header className={styles.header}>
      <div className={styles.group}>
        {showMenuButton && !isSeasonality && (
          <Tooltip location="bottom" label={t(isToolbarOpen ? 'Hide drawing toolbar' : 'Show drawing toolbar')}>
            <Button pressed={isToolbarOpen} onClick={handleOpenToolbar} label={<BurgerMenuIcon />} />
          </Tooltip>
        )}

        {setChartView && (
          <Dropdown menuClassName={styles.menu} selectedValue={isSeasonality ? t('Seasonality') : t('Chart')}>
            <ChartViewMenu selectedView={seasonalityState.view} onClick={setChartView} />
          </Dropdown>
        )}

        {showSymbolSearchButton && !isSeasonality && (
          <Tooltip location="bottom" label={t('Symbol search')}>
            <Button onClick={openSymbolSearchModal} label={<SearchIcon />} />
          </Tooltip>
        )}

        {showCompareButton && !isSeasonality && (
          <Tooltip location="bottom" label={t('Compare symbols')}>
            <Button onClick={openCompareModal} label={<PlusCircleIcon />} />
          </Tooltip>
        )}
      </div>

      {!isSeasonality && (
        <>
          {(showMenuButton || showCompareButton || showSymbolSearchButton || setChartView) && (
            <Divider direction="vertical" pt={{ divider: { className: styles.divider } }} />
          )}

          <Tooltip location="bottom" label={t('Timeframe')}>
            <Dropdown
              menuClassName={styles.menu}
              selectedValue={selectedTimeframe ? t(selectedTimeframe) : selectedTimeframe}
            >
              <TimeframesMenu onClick={setTimeframe} {...{ selectedTimeframe, timeframes }} />
            </Dropdown>
          </Tooltip>

          <Divider direction="vertical" pt={{ divider: { className: styles.divider } }} />

          <div className={styles.group}>
            <IndicatorsSelect addIndicatorToChart={addIndicatorToChart} isMXT={isMXT} />

            {showSettingsModal && <Button onClick={showSettingsModal} label={t('Settings')} />}

            <Tooltip location="bottom" label={t('Chart type')}>
              <Dropdown menuClassName={styles.menu} selectedValue={<SeriesTypeIcon type={selectedSeries} />}>
                <SeriesMenu selectedType={selectedSeries} seriesTypes={seriesTypes} onClick={setSelectedSeries} />
              </Dropdown>
            </Tooltip>
          </div>

          {undoRedo && (
            <>
              <Divider direction="vertical" pt={{ divider: { className: styles.divider } }} />

              <div className={styles.group}>
                <Tooltip location="bottom" label={t('Undo')}>
                  <Button onClick={undoRedo.undo} disabled={!undoRedoState?.canUndo} label={<UndoIcon />} />
                </Tooltip>

                <Tooltip location="bottom" label={t('Redo')}>
                  <Button onClick={undoRedo.redo} disabled={!undoRedoState?.canRedo} label={<RedoIcon />} />
                </Tooltip>
              </div>
            </>
          )}
        </>
      )}

      {(copyImage || (!isSeasonality && showFullscreenButton)) && (
        <>
          <Divider direction="vertical" pt={{ divider: { className: styles.divider } }} />

          <div className={styles.group}>
            {copyImage && (!isSeasonality || seasonalityState.status === 'ready') && (
              <Tooltip location="bottom" label={t('Snapshot')}>
                <Dropdown menuClassName={styles.menu} selectedValue={<CameraIcon />}>
                  <SnapshotMenu onCopyImage={copyImage} />
                </Dropdown>
              </Tooltip>
            )}

            {showFullscreenButton && !isSeasonality && (
              <Tooltip location="bottom" label={t(isFullscreen ? 'Exit fullscreen' : 'Fullscreen')}>
                <Button pressed={isFullscreen} onClick={() => fullscreen.toggle()} label={<FullscreenIcon />} />
              </Tooltip>
            )}
          </div>
        </>
      )}
    </header>
  );
}

















import { MenuList, type MenuOption } from '@src/components/Menu/MenuList';
import type { ChartView } from '@src/core/Seasonality/types';
import { t } from '@src/translations';

interface ChartViewMenuProps {
  selectedView: ChartView;
  onClick: (view: ChartView) => void;
}

export function ChartViewMenu({ selectedView, onClick }: ChartViewMenuProps) {
  const options: MenuOption<ChartView>[] = [
    { value: 'chart', label: t('Chart') },
    { value: 'seasonality', label: t('Seasonality') },
  ];

  return <MenuList mode="single" value={selectedView} options={options} onClick={onClick} />;
}

















import { MenuList, type MenuOption } from '@src/components/Menu/MenuList';
import type { SeasonalityScale } from '@src/core/Seasonality/types';
import { t } from '@src/translations';

interface SeasonalityScaleMenuProps {
  selectedScale: SeasonalityScale;
  onClick: (scale: SeasonalityScale) => void;
}

export function SeasonalityScaleMenu({ selectedScale, onClick }: SeasonalityScaleMenuProps) {
  const options: MenuOption<SeasonalityScale>[] = [
    { value: 'absolute', label: t('Price') },
    { value: 'percentage', label: t('Percent') },
  ];

  return <MenuList mode="single" value={selectedScale} options={options} onClick={onClick} />;
}

















import type { Observable } from 'rxjs';

import { Dropdown } from '@src/components/Dropdown';
import { RangeField } from '@src/components/Fields/RangeField';
import { SeasonalityScaleMenu } from '@src/components/Menu/SeasonalityScaleMenu';
import type { SeasonalityRange, SeasonalityScale, SeasonalityState } from '@src/core/Seasonality/types';
import { t } from '@src/translations';
import { useObservable } from '@src/utils';

interface SeasonalityControlsProps {
  stateObs: Observable<SeasonalityState>;
  setScale: (scale: SeasonalityScale) => void;
  setRange: (range: SeasonalityRange) => void;
}

export function SeasonalityControls({ stateObs, setScale, setRange }: SeasonalityControlsProps) {
  const state = useObservable(stateObs);
  if (!state || state.view !== 'seasonality') return null;

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '16px', width: '100%', padding: '4px 8px' }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <RangeField
          mode="range"
          label={t('Years')}
          startLabel={t('From year')}
          endLabel={t('To year')}
          value={[state.fromYear, state.toYear]}
          min={state.minYear}
          max={state.maxYear}
          step={1}
          suffix=""
          size="sm"
          disabled={state.status === 'loading' || state.status === 'error'}
          onRangeChange={([fromYear, toYear]) => setRange({ fromYear, toYear })}
        />
      </div>
      <Dropdown menuClassName="" selectedValue={state.scale === 'absolute' ? t('Price') : t('Percent')}>
        <SeasonalityScaleMenu selectedScale={state.scale} onClick={setScale} />
      </Dropdown>
    </div>
  );
}
















import {
  createChart,
  CrosshairMode,
  LineSeries,
  PriceScaleMode,
  type IChartApi,
  type ISeriesApi,
  type LineData,
  type MouseEventParams,
  type Time,
  type WhitespaceData,
} from 'lightweight-charts';
import { BehaviorSubject, type Observable } from 'rxjs';

import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { getThemeStore } from '@src/theme/store';
import { getLocale, t } from '@src/translations';
import type { Candle } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { canvasToBlob, drawTextLayer, formatCompactNumber } from '@src/utils';

import {
  createInitialSeasonalityState,
  type DailyClose,
  type SeasonalityGetData,
  type SeasonalityRange,
  type SeasonalityScale,
  type SeasonalityState,
  type SeasonalityYear,
} from './types';

interface SeasonalityManagerParams {
  container: HTMLElement;
  getData: SeasonalityGetData;
  precision?: number;
  onOpen: () => void;
  onBack: () => void;
}

const DEFAULT_YEARS = 5;
const DAILY_TIMEFRAME = Timeframes['1d'];
const MAX_HISTORY_PAGES = 1000;
const CALENDAR = Array.from({ length: 366 }, (_, day) =>
  new Date(Date.UTC(2000, 0, day + 1)).toISOString().slice(0, 10),
);
type SeriesDatum = LineData<Time> | WhitespaceData<Time>;

export class SeasonalityManager {
  private readonly state = new BehaviorSubject<SeasonalityState>(createInitialSeasonalityState());
  private readonly chartContainer = document.createElement('div');
  private readonly legend = document.createElement('div');
  private readonly statusElement = document.createElement('div');
  private chart: IChartApi | null = null;
  private series: ISeriesApi<'Line'>[] = [];
  private allYears: SeasonalityYear[] = [];
  private data: SeasonalityYear[] = [];
  private requestId = 0;
  private renderFrame: number | null = null;
  private destroyed = false;

  constructor(private readonly params: SeasonalityManagerParams) {
    Object.assign(this.chartContainer.style, { position: 'absolute', inset: '0' });
    Object.assign(this.legend.style, {
      position: 'absolute',
      top: '8px',
      left: '8px',
      right: '70px',
      display: 'flex',
      flexWrap: 'wrap',
      gap: '6px 16px',
      pointerEvents: 'none',
      fontSize: '12px',
      zIndex: '2',
    });
    Object.assign(this.statusElement.style, {
      position: 'absolute',
      inset: '0',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '16px',
      textAlign: 'center',
      pointerEvents: 'none',
    });
    params.container.append(this.chartContainer, this.legend, this.statusElement);
  }

  public getState(): Observable<SeasonalityState> {
    return this.state.asObservable();
  }
  public isActive(): boolean {
    return this.state.value.view === 'seasonality';
  }

  public async show(symbolId: string, range?: SeasonalityRange): Promise<void> {
    if (this.destroyed) return;
    if (this.isActive() && this.state.value.symbolId === symbolId) {
      if (this.state.value.status === 'loading') return;
      if (this.allYears.length > 0) {
        if (range) this.setRange(range);
        return;
      }
    }
    const requestId = ++this.requestId;
    const isCurrent = () => !this.destroyed && requestId === this.requestId;
    if (!this.isActive()) this.params.onOpen();
    this.cancelRender();
    this.clearChart();
    this.allYears = [];
    this.showStatus(t('Loading seasonality'));
    this.state.next({ ...this.state.value, symbolId, view: 'seasonality', status: 'loading', error: null });
    try {
      if (!symbolId) throw new Error('Select an instrument');
      const rows = await this.loadHistory(symbolId, isCurrent);
      if (!isCurrent()) return;
      this.allYears = buildSeasonality(rows);
      if (this.allYears.length === 0) {
        this.showStatus(t('No seasonality data'));
        this.state.next({ ...this.state.value, status: 'empty' });
        return;
      }
      const minYear = this.allYears[0].year;
      const maxYear = this.allYears[this.allYears.length - 1].year;
      const selected = normalizeRange(
        range ?? {
          fromYear: Math.max(minYear, maxYear - DEFAULT_YEARS + 1),
          toYear: maxYear,
        },
        minYear,
        maxYear,
      );
      this.state.next({ ...this.state.value, ...selected, minYear, maxYear });
      this.renderRange();
    } catch (error) {
      if (!isCurrent()) return;
      this.clearChart();
      this.allYears = [];
      this.showStatus(t('Unable to load seasonality'));
      this.state.next({ ...this.state.value, status: 'error', error: String(error) });
      console.error('[Seasonality] History loading failed:', error);
    }
  }

  public setRange = (range: SeasonalityRange): void => {
    if (this.destroyed || !this.isActive() || this.allYears.length === 0) return;
    const state = this.state.value;
    const next = normalizeRange(range, state.minYear, state.maxYear);
    if (next.fromYear === state.fromYear && next.toYear === state.toYear) return;
    this.state.next({ ...state, ...next });
    if (this.renderFrame !== null) return;
    this.renderFrame = requestAnimationFrame(() => {
      this.renderFrame = null;
      if (!this.destroyed && this.isActive()) this.renderRange();
    });
  };

  public setScale = (scale: SeasonalityScale): void => {
    if (this.destroyed || !this.isActive() || this.state.value.scale === scale) return;
    this.state.next({ ...this.state.value, scale });
    if (this.chart) this.applyScale();
  };

  public back = (): void => {
    if (this.destroyed || !this.isActive()) return;
    this.requestId += 1;
    this.cancelRender();
    this.clearChart();
    this.allYears = [];
    this.statusElement.style.display = 'none';
    this.state.next({ ...this.state.value, view: 'chart', status: 'idle', error: null });
    this.params.onBack();
  };

  public updateTheme(): void {
    const { colors } = getThemeStore();
    this.params.container.style.background = colors.chartBackground;
    this.statusElement.style.color = colors.chartTextPrimary;
    this.chart?.applyOptions({
      layout: { background: { color: colors.chartBackground }, textColor: colors.chartTextPrimary },
      grid: { vertLines: { color: colors.chartGridLine }, horzLines: { color: colors.chartGridLine } },
    });
  }

  public async copyImage(): Promise<void> {
    if (!this.chart || this.state.value.status !== 'ready') return;
    const canvas = this.chart.takeScreenshot(true, false);
    drawTextLayer(canvas, this.legend, this.chart.chartElement());
    const blob = await canvasToBlob(canvas);
    await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
  }

  public destroy(): void {
    if (this.destroyed) return;
    this.destroyed = true;
    this.requestId += 1;
    this.cancelRender();
    this.clearChart();
    this.allYears = [];
    this.chartContainer.remove();
    this.legend.remove();
    this.statusElement.remove();
    this.state.complete();
  }

  private async loadHistory(symbolId: string, isCurrent: () => boolean): Promise<DailyClose[]> {
    const rows = new Map<string, DailyClose & { time: number }>();
    const loadPage = async (cursor?: Candle, page = 0): Promise<DailyClose[]> => {
      if (!isCurrent()) return [];
      if (page === MAX_HISTORY_PAGES) throw new Error('History page limit exceeded');
      const loaded = await this.params.getData(DAILY_TIMEFRAME, symbolId, cursor);
      if (!isCurrent()) return [];
      if (!loaded?.length) return [...rows.values()];
      let oldest = loaded[0];
      let oldestTime = Infinity;
      for (let index = loaded.length - 1; index >= 0; index -= 1) {
        const candle = loaded[index];
        if (!Number.isFinite(candle.time) || !Number.isFinite(candle.close)) throw new Error('Invalid daily candle');
        const time = Math.floor(candle.time > 1e10 ? candle.time / 1000 : candle.time);
        if (time < oldestTime) {
          oldest = candle;
          oldestTime = time;
        }
        const date = new Date(time * 1000).toISOString().slice(0, 10);
        const previous = rows.get(date);
        if (previous && previous.time !== time) throw new Error(`Multiple daily candles on ${date}`);
        if (!previous) rows.set(date, { date, close: candle.close, time });
      }
      if (cursor && oldestTime >= cursor.time) throw new Error('History pagination made no progress');
      return loadPage({ ...oldest, time: oldestTime }, page + 1);
    };
    return loadPage();
  }

  private renderRange(): void {
    const state = this.state.value;
    const visibleRange = this.chart?.timeScale().getVisibleLogicalRange();
    this.data = this.allYears.filter((year) => year.year >= state.fromYear && year.year <= state.toYear);
    if (this.data.length === 0) {
      this.clearChart();
      this.showStatus(t('No seasonality data'));
      this.state.next({ ...state, status: 'empty' });
      return;
    }
    if (!this.chart) {
      this.chart = createChart(this.chartContainer, {
        autoSize: true,
        rightPriceScale: { mode: PriceScaleMode.Normal, visible: true, borderVisible: false },
        leftPriceScale: { visible: false },
        crosshair: { mode: CrosshairMode.Normal },
        timeScale: {
          timeVisible: false,
          secondsVisible: false,
          rightOffset: 0,
          tickMarkFormatter: formatSeasonDate,
          lockVisibleTimeRangeOnResize: true,
        },
        localization: { locale: getLocale(), timeFormatter: formatSeasonDate },
      });
      this.updateTheme();
      this.chart.subscribeCrosshairMove(this.onCrosshairMove);
    }
    for (const series of this.series) this.chart.removeSeries(series);
    this.series = this.data.map((year) =>
      this.chart!.addSeries(LineSeries, {
        title: String(year.year),
        color: getYearColor(year.year),
        priceLineVisible: false,
        lastValueVisible: false,
      }),
    );
    this.legend.replaceChildren(
      ...this.data.map((year) => {
        const item = document.createElement('span');
        item.style.color = getYearColor(year.year);
        return item;
      }),
    );
    this.applyScale();
    if (visibleRange) this.chart.timeScale().setVisibleLogicalRange(visibleRange);
    else this.chart.timeScale().setVisibleRange({ from: '2000-01-01', to: '2000-12-31' });
    this.state.next({ ...this.state.value, status: 'ready' });
  }

  private applyScale(): void {
    const scale = this.state.value.scale;
    const visibleRange = this.chart?.timeScale().getVisibleLogicalRange();
    this.series.forEach((series, index) => {
      series.applyOptions({
        priceFormat: {
          type: 'custom',
          minMove: scale === 'percentage' ? 0.01 : 10 ** -(this.params.precision ?? 2),
          formatter:
            scale === 'percentage'
              ? (value: number) => `${value.toFixed(2)}%`
              : (value: number) => formatCompactNumber(value),
        },
      });
      series.setData(toSeriesData(this.data[index], scale));
    });
    if (visibleRange) this.chart?.timeScale().setVisibleLogicalRange(visibleRange);
    if (scale === 'percentage' && !this.data.some((year) => year.baselinePrice > 0)) {
      this.showStatus(t('Percentage requires a positive baseline'));
    } else this.statusElement.style.display = 'none';
    this.updateLegend();
  }

  private onCrosshairMove = (event: MouseEventParams): void => {
    this.updateLegend(event.time === undefined ? undefined : toDateKey(event.time));
  };

  private updateLegend(chartDate?: string): void {
    this.data.forEach((year, index) => {
      const point = chartDate
        ? year.points.find((item) => item.chartDate === chartDate)
        : year.points[year.points.length - 1];
      const value = this.state.value.scale === 'absolute' ? point?.price : point?.percentage;
      const item = this.legend.children[index];
      const formatted = value == null ? '—' : this.series[index].priceFormatter().format(value);
      item.textContent = `${year.year} · ${point?.date ?? '—'} · ${formatted}`;
    });
  }

  private showStatus(message: string): void {
    this.statusElement.textContent = message;
    this.statusElement.style.display = 'flex';
  }

  private cancelRender(): void {
    if (this.renderFrame !== null) cancelAnimationFrame(this.renderFrame);
    this.renderFrame = null;
  }

  private clearChart(): void {
    this.chart?.unsubscribeCrosshairMove(this.onCrosshairMove);
    this.chart?.remove();
    this.chart = null;
    this.series = [];
    this.data = [];
    this.legend.replaceChildren();
  }
}

export function normalizeRange(range: SeasonalityRange, minYear: number, maxYear: number): SeasonalityRange {
  if (!Number.isFinite(range.fromYear) || !Number.isFinite(range.toYear)) throw new Error('Invalid year range');
  const fromYear = Math.max(minYear, Math.min(maxYear, Math.round(range.fromYear)));
  const toYear = Math.max(fromYear, Math.min(maxYear, Math.round(range.toYear)));
  return { fromYear, toYear };
}

export function buildSeasonality(rows: readonly DailyClose[]): SeasonalityYear[] {
  const result: SeasonalityYear[] = [];
  for (const row of [...rows].sort((a, b) => a.date.localeCompare(b.date))) {
    const year = Number(row.date.slice(0, 4));
    let group = result[result.length - 1];
    if (!group || group.year !== year) {
      group = { year, baselineDate: row.date, baselinePrice: row.close, points: [] };
      result.push(group);
    }
    const percentage = group.baselinePrice > 0 ? (row.close / group.baselinePrice - 1) * 100 : null;
    if (percentage !== null && !Number.isFinite(percentage)) throw new Error('Invalid percentage');
    group.points.push({ date: row.date, chartDate: `2000-${row.date.slice(5)}`, price: row.close, percentage });
  }
  return result;
}

export function toSeriesData(year: SeasonalityYear, scale: SeasonalityScale): SeriesDatum[] {
  let index = 0;
  return CALENDAR.map((time) => {
    const point = year.points[index];
    if (point?.chartDate !== time) return { time };
    index += 1;
    const value = scale === 'absolute' ? point.price : point.percentage;
    return value === null ? { time } : { time, value };
  });
}

function toDateKey(time: Time): string {
  if (typeof time === 'string') return time;
  if (typeof time === 'number') return new Date(time * 1000).toISOString().slice(0, 10);
  return `${time.year}-${String(time.month).padStart(2, '0')}-${String(time.day).padStart(2, '0')}`;
}

function formatSeasonDate(time: Time): string {
  const date = toDateKey(time);
  return `${date.slice(8, 10)}.${date.slice(5, 7)}`;
}

function getYearColor(index: number): string {
  return COMPARE_COLOR_PALETTE[index % COMPARE_COLOR_PALETTE.length] ?? '#2962ff';
}

















import type { Candle } from '@src/types';
import type { Timeframes } from '@src/types/timeframes';

export type ChartView = 'chart' | 'seasonality';
export type SeasonalityScale = 'absolute' | 'percentage';

export interface SeasonalityRange {
  fromYear: number;
  toYear: number;
}

export interface SeasonalityState extends SeasonalityRange {
  view: ChartView;
  status: 'idle' | 'loading' | 'ready' | 'empty' | 'error';
  scale: SeasonalityScale;
  symbolId: string;
  minYear: number;
  maxYear: number;
  error: string | null;
}

export function createInitialSeasonalityState(): SeasonalityState {
  const year = new Date().getUTCFullYear();
  return {
    view: 'chart',
    status: 'idle',
    scale: 'absolute',
    symbolId: '',
    error: null,
    minYear: year - 4,
    maxYear: year,
    fromYear: year - 4,
    toYear: year,
  };
}

export interface SeasonalityPoint {
  date: string;
  chartDate: string;
  price: number;
  percentage: number | null;
}

export interface SeasonalityYear {
  year: number;
  baselineDate: string;
  baselinePrice: number;
  points: SeasonalityPoint[];
}

export interface DailyClose {
  date: string;
  close: number;
}

export type SeasonalityGetData = (timeframe: Timeframes, symbolId: string, until?: Candle) => Promise<Candle[] | null>;


















import dayjs from 'dayjs';

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

import { BehaviorSubject, combineLatest, defer, EMPTY, Observable, Subscription } from 'rxjs';
import { catchError, distinctUntilChanged, filter, ignoreElements, map, switchMap, tap } from 'rxjs/operators';

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

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

export enum Resize {
  Shrink,
  Expand,
}

const HISTORY_LOAD_THRESHOLD = 500;

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

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

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

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

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

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

  private isPointerDown = false;
  private didResetOnDrag = false;

  private subscriptions = new Subscription();

  private activeSymbolIds: string[] = [];

  private historyBatchRunning = false;

  private active = true;
  private savedViewport: {
    logicalRange: LogicalRange | null;
    timeRange: IRange<Time> | null;
    oldestTimes: (number | null)[];
    shiftVisibleRangeOnNewBar: boolean;
    allowShiftVisibleRangeOnWhitespaceReplacement: boolean;
  } | null = null;

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

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

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

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

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

    this.subscriptions.add(this.optionsSubscription);

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

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

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

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

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

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

    this.indicatorManager = new IndicatorManager({
      lwcChart: this.lwcChart,
      eventManager,
      dataSource: this.dataSource,
      paneManager: this.paneManager,
      initialIndicators: indicatorSnapshots,
      DOM: this.DOM,
      chartOptions: lwcChartConfig.chartOptions,
    });

    this.compareManager = new CompareManager({
      chart: this.lwcChart,
      eventManager,
      dataSource: this.dataSource,
      paneManager: this.paneManager,
      initialIndicators: compareSnapshots,
      indicatorManager: this.indicatorManager,
    });

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

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

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

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

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

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

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

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

  private onPointerDown = (event: PointerEvent) => {
    if (!this.active) return;
    if (event.composedPath().includes(this.lwcChart.chartElement())) {
      this.container.focus({ preventScroll: true });
    }

    this.isPointerDown = true;
    this.didResetOnDrag = false;
  };

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

    this.didResetOnDrag = true;

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

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

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

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

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

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

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

    this.paneManager.invalidate();
  }

  public setActive(active: boolean): void {
    if (this.active === active) return;
    this.active = active;
    this.isPointerDown = false;
    const timeScale = this.lwcChart.timeScale();
    if (!active) {
      const options = timeScale.options();
      this.savedViewport = {
        logicalRange: timeScale.getVisibleLogicalRange(),
        timeRange: timeScale.getVisibleRange(),
        oldestTimes: this.activeSymbolIds.map((symbolId) => this.dataSource.getOldestTime(symbolId)),
        shiftVisibleRangeOnNewBar: options.shiftVisibleRangeOnNewBar,
        allowShiftVisibleRangeOnWhitespaceReplacement: options.allowShiftVisibleRangeOnWhitespaceReplacement,
      };
      this.preserveInactiveTimeScale();
      return;
    }
    const saved = this.savedViewport;
    this.savedViewport = null;
    if (saved) {
      timeScale.applyOptions({
        shiftVisibleRangeOnNewBar: saved.shiftVisibleRangeOnNewBar,
        allowShiftVisibleRangeOnWhitespaceReplacement: saved.allowShiftVisibleRangeOnWhitespaceReplacement,
      });
      const historyChanged = this.activeSymbolIds.some(
        (symbolId, index) => this.dataSource.getOldestTime(symbolId) !== saved.oldestTimes[index],
      );
      if (historyChanged && saved.timeRange) {
        timeScale.setVisibleRange(saved.timeRange);
      } else if (saved.logicalRange) {
        timeScale.setVisibleLogicalRange(saved.logicalRange);
      }
    }
  }

  private preserveInactiveTimeScale(): void {
    if (this.active) return;
    this.lwcChart.timeScale().applyOptions({
      shiftVisibleRangeOnNewBar: false,
      allowShiftVisibleRangeOnWhitespaceReplacement: false,
    });
  }

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

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

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

  // todo: add/move to undo/redo model(eventManager)
  public scrollTimeScale = (direction: Direction) => {
    if (!this.active) return;
    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) => {
    if (!this.active) return;
    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 = () => {
    if (!this.active) return;
    this.eventManager.resetInterval({
      history: false,
    });

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

    this.paneManager.resetPriceScalesAutoScale();
  };

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

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

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

  public async copyImage(): Promise<void> {
    const canvas = this.lwcChart.takeScreenshot(true, false);
    const chartElement = this.lwcChart.chartElement();

    chartElement.querySelectorAll<HTMLElement>(`.${CHART_PANE_LEGEND_CONTAINER}`).forEach((legend) => {
      if (legend.hidden || window.getComputedStyle(legend).display === 'none') {
        return;
      }

      drawTextLayer(canvas, legend, chartElement);
    });

    const blob = await canvasToBlob(canvas);

    await navigator.clipboard.write([
      new ClipboardItem({
        'image/png': blob,
      }),
    ]);
  }

  private scheduleHistoryBatch(): void {
    if (!this.active || this.subscriptions.closed || this.historyBatchRunning || this.activeSymbolIds.length === 0) {
      return;
    }

    this.historyBatchRunning = true;

    requestAnimationFrame(() => {
      if (!this.active || this.subscriptions.closed) {
        this.historyBatchRunning = false;

        return;
      }

      const symbolIds = this.activeSymbolIds.slice();
      const timeframe = this.eventManager.getTimeframe();
      const oldestTimes = symbolIds.map((symbolId) => this.dataSource.getOldestTime(symbolId));

      Promise.all(symbolIds.map((symbolId) => this.dataSource.loadMoreHistory(symbolId)))
        .catch((error) => console.error('[Chart] History batch failed:', error))
        .finally(() => this.finishHistoryBatch(symbolIds, oldestTimes, timeframe));
    });
  }

  private finishHistoryBatch(
    symbolIds: string[],
    oldestTimes: (number | null)[],
    timeframe: ReturnType<EventManager['getTimeframe']>,
  ): void {
    this.historyBatchRunning = false;

    if (!this.active || this.subscriptions.closed) {
      return;
    }

    const contextChanged =
      timeframe !== this.eventManager.getTimeframe() || isUniqueSymbolId(symbolIds, this.activeSymbolIds);

    const hasProgress = this.hasHistoryProgress(symbolIds, oldestTimes);

    if (!contextChanged && !hasProgress) {
      return;
    }

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

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

  private hasHistoryProgress(symbolIds: string[], oldestTimes: (number | null)[]): boolean {
    return symbolIds.some((symbolId, index) => {
      if (!this.activeSymbolIds.includes(symbolId)) {
        return false;
      }

      const previousOldestTime = oldestTimes[index];
      const currentOldestTime = this.dataSource.getOldestTime(symbolId);

      return currentOldestTime !== null && (previousOldestTime === null || currentOldestTime < previousOldestTime);
    });
  }

  private async warmupSymbols(symbolIds: string[]): Promise<void> {
    const range = this.lwcChart.timeScale().getVisibleRange() as IRange<number> | null;

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

    await Promise.all(symbolIds.map((symbolId) => this.dataSource.loadTill(symbolId, range.from)));
  }

  private async loadIntervalRange(interval: Intervals, symbolIds: string[]): Promise<IRange<Time> | null> {
    if (interval === Intervals.All) {
      await Promise.all(symbolIds.map((symbolId) => this.dataSource.loadAllHistory(symbolId)));

      const firstTimes = symbolIds
        .map((symbolId) => this.dataSource.getOldestTime(symbolId))
        .filter((time): time is number => time !== null);

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

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

      return {
        from: Math.min(...firstTimes) as Time,
        to: Math.max(...lastTimes) as Time,
      };
    }

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

    await Promise.all(symbolIds.map((symbolId) => this.dataSource.loadTill(symbolId, from)));

    const hasData = symbolIds.some((symbolId) => this.dataSource.getOldestTime(symbolId) !== null);

    if (!hasData) {
      return null;
    }

    return {
      from: from as Time,
      to: to as Time,
    };
  }

  private setupDataSourceSubs(): void {
    let symbolsRegistered = false;

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

        return {
          mainSymbolId,
          symbolIds,
        };
      }),
      distinctUntilChanged(
        (previous, next) =>
          previous.mainSymbolId === next.mainSymbolId && !isUniqueSymbolId(previous.symbolIds, next.symbolIds),
      ),
    );

    this.subscriptions.add(
      combineLatest([this.eventManager.getInterval().pipe(distinctUntilChanged()), symbols$])
        .pipe(
          switchMap(([interval, { symbolIds }]) => {
            const previousSymbolIds = this.activeSymbolIds;
            const previousSymbolIdsSet = new Set(previousSymbolIds);
            const addedSymbolIds = symbolIds.filter((symbolId) => !previousSymbolIdsSet.has(symbolId));

            this.activeSymbolIds = symbolIds;

            if (!symbolsRegistered || isUniqueSymbolId(previousSymbolIds, symbolIds)) {
              symbolsRegistered = true;
              this.dataSource.setSymbols(symbolIds);
            }

            if (symbolIds.length === 0) {
              return EMPTY;
            }

            if (interval === null) {
              if (addedSymbolIds.length === 0) {
                return EMPTY;
              }

              return defer(() => this.warmupSymbols(addedSymbolIds)).pipe(
                ignoreElements(),
                catchError((error) => {
                  console.error('[Chart] Ошибка при прогреве символов:', error);

                  return EMPTY;
                }),
              );
            }

            return defer(() => this.loadIntervalRange(interval, symbolIds)).pipe(
              filter((range): range is IRange<Time> => range !== null),
              tap((range) => {
                if (this.active) this.lwcChart.timeScale().setVisibleRange(range);
              }),
              catchError((error) => {
                console.error('[Chart] Ошибка при применении интервала:', error);

                return EMPTY;
              }),
            );
          }),
        )
        .subscribe(),
    );
  }

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

      if (!logicalRange) return;

      const needsMoreData = logicalRange.from < HISTORY_LOAD_THRESHOLD;

      if (!needsMoreData) return;

      this.scheduleHistoryBatch();
    });
  }
}

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

  const nextSet = new Set(next);

  return previous.some((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,
  };
}

















import {
  CHART_DRAWING_TOOLBAR_CONTAINER,
  CHART_MODAL_CONTAINER_CLASSNAME,
  CHART_PANE_EMPTY_STATE_CONTAINER,
  CHART_PANE_LEGEND_CONTAINER,
  CHART_PANE_OVERLAY_CONTAINER,
  CHART_ROOT_CLASSNAME,
  CHART_SCROLLABLE_CLASSNAME,
} from '@src/constants';

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

enum ZIndex {
  Chart = '0',
  Base = '1',
  Legend = '2',
  Floating = '3',
  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.classList.add(CHART_SCROLLABLE_CLASSNAME);
    headerContainer.style.width = '100%';
    headerContainer.style.height = `${headerHeight}px`;
    headerContainer.style.overflow = 'auto hidden';

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

    const chartContainer = document.createElement('div');
    const chartViewContainer = document.createElement('div');
    Object.assign(chartViewContainer.style, {
      position: 'relative',
      display: 'grid',
      minWidth: '0',
      minHeight: '0',
    });
    chartContainer.style.gridArea = '1 / 1';

    const seasonalityContainer = document.createElement('div');
    Object.assign(seasonalityContainer.style, {
      position: 'relative',
      gridArea: '1 / 1',
      minWidth: '0',
      minHeight: '0',
      visibility: 'hidden',
      pointerEvents: 'none',
      zIndex: '1',
      overflow: 'hidden',
      display: 'grid',
      gridTemplateRows: '64px minmax(0, 1fr)',
      rowGap: '8px',
    });
    seasonalityContainer.tabIndex = -1;
    seasonalityContainer.inert = true;
    const seasonalityControlsContainer = document.createElement('div');
    const seasonalityPlotContainer = document.createElement('div');
    Object.assign(seasonalityPlotContainer.style, { position: 'relative', minWidth: '0', minHeight: '0' });
    seasonalityContainer.append(seasonalityControlsContainer, seasonalityPlotContainer);
    chartContainer.style.position = 'relative';
    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.outline = 'none';
    chartAreaContainer.tabIndex = -1;
    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.position = 'absolute';
    controlBarContainer.style.left = '50%';
    controlBarContainer.style.transform = 'translateX(-50%)';
    controlBarContainer.style.bottom = 'var(--space-2000)';
    controlBarContainer.style.zIndex = ZIndex.Floating;

    const drawingToolbarContainer = document.createElement('div');
    drawingToolbarContainer.classList.add(CHART_DRAWING_TOOLBAR_CONTAINER);
    drawingToolbarContainer.style.position = 'absolute';
    drawingToolbarContainer.style.inset = '0';
    drawingToolbarContainer.style.zIndex = ZIndex.Floating;
    drawingToolbarContainer.style.pointerEvents = 'none';
    drawingToolbarContainer.style.overflow = 'hidden';

    const modalContainer = document.createElement('div');
    modalContainer.classList.add(CHART_MODAL_CONTAINER_CLASSNAME);
    modalContainer.style.position = 'absolute';
    modalContainer.style.inset = '0';
    modalContainer.style.zIndex = ZIndex.Modal;
    modalContainer.hidden = true;

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

    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,
      seasonalityContainer,
      seasonalityControlsContainer,
      seasonalityPlotContainer,
      chartAreaContainer,
      toolBarContainer,
      modalContainer,
      controlBarContainer,
      drawingToolbarContainer,
      toggleToolbar,
    };
  }

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

  static createPaneContainers() {
    const legendContainer = document.createElement('div');

    legendContainer.classList.add(CHART_PANE_LEGEND_CONTAINER);

    legendContainer.style.position = 'absolute';
    legendContainer.style.top = '0';
    legendContainer.style.left = '0';
    legendContainer.style.zIndex = ZIndex.Legend;
    legendContainer.style.pointerEvents = 'none';

    const paneOverlayContainer = document.createElement('div');
    paneOverlayContainer.classList.add(CHART_PANE_OVERLAY_CONTAINER);
    paneOverlayContainer.style.position = 'absolute';
    paneOverlayContainer.style.inset = '0';
    paneOverlayContainer.style.zIndex = ZIndex.Base;
    paneOverlayContainer.style.pointerEvents = 'none';

    const paneEmptyStateContainer = document.createElement('div');
    paneEmptyStateContainer.classList.add(CHART_PANE_EMPTY_STATE_CONTAINER);
    paneEmptyStateContainer.hidden = true;

    return {
      legendContainer,
      paneOverlayContainer,
      paneEmptyStateContainer,
    };
  }
}
















export enum Keys {
  'escape' = 'escape',
  'delete' = 'delete',
  'tab' = 'tab',
  'shift' = 'shift',
  'control' = 'control',
  'meta' = 'meta',
  'mod' = 'mod',
  'alt' = 'alt',
  't' = 'keyt',
  'h' = 'keyh',
  'v' = 'keyv',
  'f' = 'keyf',
  'r' = 'keyr',
  'y' = 'keyy',
  'z' = 'keyz',
  'c' = 'keyc',
}

type HotkeyCallback = () => void | Promise<void>;
type UnregisterHotkey = () => void;

interface RegisterHotkeyParams {
  keys: readonly Keys[];
  callback: HotkeyCallback;
  enabled?: () => boolean;
}

interface HotkeyRegistration {
  callback: HotkeyCallback;
  enabled: () => boolean;
}

export interface IHotkeys {
  register(params: RegisterHotkeyParams): UnregisterHotkey;
  destroy(): void;
}

// todo: возможно можно сделать синглтоном и использовать импортируя экземпляр класса,
// там где это нужно вместо props drilling, как сейчас

export class Hotkeys implements IHotkeys {
  private registrations = new Map<string, HotkeyRegistration[]>();

  constructor(
    private readonly scope?: HTMLElement,
    private readonly enabled: () => boolean = () => true,
  ) {
    document.addEventListener('keydown', this.handleKeyDown);
  }

  public register({ keys, callback, enabled = this.enabled }: RegisterHotkeyParams): UnregisterHotkey {
    validateKeys(keys);

    const registration: HotkeyRegistration = {
      callback,
      enabled,
    };

    const shortcuts = getRegistrationShortcuts(keys);

    for (const shortcut of shortcuts) {
      const registrations = this.registrations.get(shortcut);

      if (registrations) {
        registrations.push(registration);
      } else {
        this.registrations.set(shortcut, [registration]);
      }
    }

    return () => {
      for (const shortcut of shortcuts) {
        const registrations = this.registrations.get(shortcut);

        if (!registrations) {
          continue;
        }

        const registrationIndex = registrations.lastIndexOf(registration);

        if (registrationIndex !== -1) {
          registrations.splice(registrationIndex, 1);
        }

        if (registrations.length === 0) {
          this.registrations.delete(shortcut);
        }
      }
    };
  }

  public destroy(): void {
    document.removeEventListener('keydown', this.handleKeyDown);
    this.registrations.clear();
  }

  private handleKeyDown = async (event: KeyboardEvent): Promise<void> => {
    if (event.defaultPrevented || event.isComposing || event.repeat || isEditableElement(event.target)) {
      return;
    }

    if (this.scope && !this.scope.contains(document.activeElement)) return;

    const registrations = this.registrations.get(getEventShortcut(event));
    const registration = registrations?.slice().reverse().find((item) => item.enabled());

    if (!registration) {
      return;
    }

    event.preventDefault();

    await registration.callback();
  };
}

function validateKeys(keys: readonly Keys[]): void {
  if (keys.length === 0) {
    throw new Error('[Hotkeys] попытка задать пустой хоткей');
  }

  let primaryKeysCount = 0;
  let hasMod = false;
  let hasControl = false;
  let hasMeta = false;

  for (const key of keys) {
    if (!isModifier(key)) {
      primaryKeysCount += 1;
    }

    if (key === Keys.mod) {
      hasMod = true;
    }

    if (key === Keys.control) {
      hasControl = true;
    }

    if (key === Keys.meta) {
      hasMeta = true;
    }
  }

  if (primaryKeysCount > 1) {
    throw new Error('[Hotkeys] хоткей может содержать только одну основную клавишу');
  }

  if (hasMod && (hasControl || hasMeta)) {
    throw new Error('[Hotkeys] mod нельзя использовать вместе с control или meta');
  }
}

function getRegistrationShortcuts(keys: readonly Keys[]): string[] {
  if (!keys.includes(Keys.mod)) {
    return [createShortcut(keys)];
  }

  const keysWithoutMod = keys.filter((key) => key !== Keys.mod);

  return [
    createShortcut([...keysWithoutMod, Keys.control]),
    createShortcut([...keysWithoutMod, Keys.meta]),
    createShortcut([...keysWithoutMod, Keys.control, Keys.meta]),
  ];
}

function getEventShortcut(event: KeyboardEvent): string {
  const key = normalizeCode(event.code);

  return buildShortcut(event.ctrlKey, event.metaKey, event.shiftKey, event.altKey, isModifier(key) ? '' : key);
}

function createShortcut(keys: readonly Keys[]): string {
  let control = false;
  let meta = false;
  let shift = false;
  let alt = false;
  let primaryKey: Keys | '' = '';

  for (const key of keys) {
    switch (key) {
      case Keys.control:
        control = true;
        break;
      case Keys.meta:
        meta = true;
        break;
      case Keys.shift:
        shift = true;
        break;
      case Keys.alt:
        alt = true;
        break;
      case Keys.mod:
        break;
      default:
        primaryKey = key;
    }
  }

  return buildShortcut(control, meta, shift, alt, primaryKey);
}

function buildShortcut(control: boolean, meta: boolean, shift: boolean, alt: boolean, primaryKey: Keys | ''): string {
  let shortcut = '';

  if (control) {
    shortcut = Keys.control;
  }
  if (meta) {
    shortcut += `${shortcut ? '+' : ''}${Keys.meta}`;
  }
  if (shift) {
    shortcut += `${shortcut ? '+' : ''}${Keys.shift}`;
  }
  if (alt) {
    shortcut += `${shortcut ? '+' : ''}${Keys.alt}`;
  }
  if (primaryKey) {
    shortcut += `${shortcut ? '+' : ''}${primaryKey}`;
  }

  return shortcut;
}

function isModifier(key: Keys): boolean {
  return key === Keys.mod || key === Keys.control || key === Keys.meta || key === Keys.shift || key === Keys.alt;
}

function normalizeCode(code: string): Keys {
  switch (code.toLowerCase()) {
    case 'controlleft':
    case 'controlright':
      return Keys.control;

    case 'metaleft':
    case 'metaright':
      return Keys.meta;

    case 'shiftleft':
    case 'shiftright':
      return Keys.shift;

    case 'altleft':
    case 'altright':
      return Keys.alt;

    default:
      return code.toLowerCase() as Keys;
  }
}

function isEditableElement(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) {
    return false;
  }

  return target.isContentEditable || target.closest('input, textarea, select, [contenteditable]') !== null;
}

















import { combineLatest, Subscription } from 'rxjs';

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

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

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

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

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

import { Chart } from './Chart';
import { ChartSettings, ChartSettingsSource } from './ChartSettings';
import { ContainerManager } from './ContainerManager';
import { EventManager } from './EventManager';
import { ReactRenderer } from './ReactRenderer';
import { TimeScaleHoverController } from './TimescaleHoverController';
import { UIRenderer } from './UIRenderer';
import { SeasonalityManager } from './Seasonality/SeasonalityManager';
import type { ChartView, SeasonalityRange } from './Seasonality/types';

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;
  showSnapshotButton?: boolean;
  /**
   * Дефолтная конфигурация тултипа - всегда показывается по умолчанию.
   * При добавлении/изменении полей в конфиге - они объединяются с дефолтными значениями.
   *
   * Полная кастомизация:
   * @example
   * ```typescript
   *    tooltipConfig: {
   *      time: { visible: true, label: 'Дата и время' },
   *      symbol: { visible: true, label: 'Инструмент' },
   *      close: { visible: true, label: 'Курс' },
   *      change: { visible: true, label: 'Изменение' },
   *      volume: { visible: true, label: 'Объем' },
   *      open: { visible: false },
   *      high: { visible: false },
   *      low: { visible: false }
   *    }
   *```
   */
  tooltipConfig?: TooltipConfig;

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

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

  container: HTMLElement;
  lwcInheritedChartOptions?: ChartTypeOptions;
}

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

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

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

  private subscriptions = new Subscription();

  private fullscreen!: FullscreenController;

  private chartCollectionPresetSettings!: ChartCollectionPreset;

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

  private setup = (config: IMoexChart) => {
    this.subscriptions = new Subscription();
    this.toolbarRenderer = undefined;
    this.controlBarRenderer = undefined;
    this.footerRenderer = undefined;
    this.inheritedChartOptions = config.lwcInheritedChartOptions;
    this.chartCollectionPresetSettings = config.chartCollectionPreset;

    setPricePrecision(config.chartCollectionPreset.ohlc.precision);

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

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

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

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

    this.rootContainer = config.container;

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

    const store = configureThemeStore(config.chartCollectionPreset);

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

    this.hotkeys = new Hotkeys(this.rootContainer, () => !this.seasonalityManager.isActive());

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

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

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

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

    this.modalRenderer = new ModalRenderer(modalContainer);

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

    const setSeasonalityVisible = (visible: boolean) => {
      chartContainer.style.visibility = visible ? 'hidden' : 'visible';
      chartContainer.inert = visible;
      footerContainer.style.visibility = visible ? 'hidden' : 'visible';
      footerContainer.inert = visible;
      seasonalityContainer.style.visibility = visible ? 'visible' : 'hidden';
      seasonalityContainer.style.pointerEvents = visible ? 'auto' : 'none';
      seasonalityContainer.inert = !visible;
    };
    this.seasonalityManager = new SeasonalityManager({
      container: seasonalityPlotContainer,
      getData: config.chartCollectionPreset.getDataSource,
      precision: config.chartCollectionPreset.ohlc.precision,
      onOpen: () => {
        this.chart.setActive(false);
        setSeasonalityVisible(true);
        seasonalityContainer.focus({ preventScroll: true });
      },
      onBack: () => {
        setSeasonalityVisible(false);
        this.chart.setActive(true);
        chartAreaContainer.focus({ preventScroll: true });
      },
    });
    this.seasonalityControlsRenderer = new ReactRenderer(seasonalityControlsContainer);
    this.seasonalityControlsRenderer.renderComponent(
      <SeasonalityControls
        stateObs={this.seasonalityManager.getState()}
        setScale={this.seasonalityManager.setScale}
        setRange={this.seasonalityManager.setRange}
      />,
    );
    this.subscriptions.add(
      this.hotkeys.register({
        keys: [Keys.escape],
        enabled: () => this.seasonalityManager.isActive() && modalContainer.hidden,
        callback: () => this.seasonalityManager.back(),
      }),
    );
    this.subscriptions.add(this.eventManager.symbolId().subscribe(() => this.seasonalityManager.back()));

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

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

    const realtimeParams = this.chart.getRealtimeApi();

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

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

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

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

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

    this.renderAttachments(config, toggleToolbar);
  };

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

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

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

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

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

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

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

    return res;
  }

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

  public clearSymbol(): void {
    this.seasonalityManager.back();
    this.eventManager.clearSymbol();
  }

  public showSeasonality(range?: SeasonalityRange): Promise<void> {
    return this.seasonalityManager.show(this.eventManager.exportChartSettings().symbolInfo.symbolId, range);
  }

  public backToChart = (): void => {
    this.seasonalityManager.back();
  };

  private setChartView = (view: ChartView): void => {
    if (view === 'chart') this.backToChart();
    else void this.showSeasonality();
  };

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

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

    this.headerRenderer.renderComponent(
      <Header
        seasonalityStateObs={this.seasonalityManager.getState()}
        setChartView={this.setChartView}
        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 })
        }
        copyImage={
          config.chartCollectionPreset.showSnapshotButton
            ? () => (this.seasonalityManager.isActive() ? this.seasonalityManager.copyImage() : this.chart.copyImage())
            : undefined
        }
        showMenuButton={!!config.chartCollectionPreset.showMenuButton}
        showFullscreenButton={!!config.chartCollectionPreset.showFullscreenButton}
        fullscreen={this.fullscreen}
        undoRedo={config.chartCollectionPreset.undoRedoEnabled ? this.eventManager.getUndoRedo() : undefined}
        toggleToolbarVisible={toggleToolbar}
        showCompareButton={!!config.chartCollectionPreset.showCompareButton}
        openCompareModal={
          config.chartCollectionPreset.openCompareModal ? config.chartCollectionPreset.openCompareModal : undefined
        }
        showSymbolSearchButton={!!config.chartCollectionPreset.openSymbolSearchModal}
        openSymbolSearchModal={config.chartCollectionPreset.openSymbolSearchModal}
        isMXT={config.chartCollectionPreset.theme === 'mxt'}
      />,
    );

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

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

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

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

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

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

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

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

    this.hotkeys.destroy();

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

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

    this.dataSource.destroy();

    ContainerManager.clearContainers(this.rootContainer);
  }
}

















import dayjs from 'dayjs';

import { BehaviorSubject, Observable, Subject } from 'rxjs';

import { Candle } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { normalizeSeriesData, parseTimeframe } from '@src/utils';

const FUTURE_WHITESPACES = 5000;

export interface SymbolSourceParams {
  symbol: string;
  getData: (timeframe: Timeframes, symbol: string, until?: Candle) => Promise<Candle[] | null>;
  getTimeframe: () => Timeframes;
}

export class SymbolSource {
  public readonly symbol: string;

  private readonly getData: SymbolSourceParams['getData'];
  private readonly getTimeframe: SymbolSourceParams['getTimeframe'];

  private readonly currentDataSubject = new BehaviorSubject<Candle[]>([]);
  private readonly realtimeSubject = new Subject<Candle>();
  private readonly lastCandleSubject = new BehaviorSubject<Candle | null>(null);
  private readonly isLoadingSubject = new BehaviorSubject<boolean>(false);
  private readonly isInitializedSubject = new BehaviorSubject<boolean>(false);

  private realtimeCache: Candle[] = [];
  private realtimeBuffer: Candle[] = [];

  private oldestCandle: Candle | null = null;
  private newestCandle: Candle | null = null;

  private loadSeq = 0;
  private loadingPromise: Promise<void> | null = null;

  private isEndOfData = false;

  constructor({ symbol, getData, getTimeframe }: SymbolSourceParams) {
    this.symbol = symbol;
    this.getData = getData;
    this.getTimeframe = getTimeframe;
  }

  public init(): void {
    this.reload(this.getTimeframe());
  }

  public data$(): Observable<Candle[]> {
    return this.currentDataSubject.asObservable();
  }

  public realtime$(): Observable<Candle> {
    return this.realtimeSubject.asObservable();
  }

  public lastCandle$(): Observable<Candle | null> {
    return this.lastCandleSubject.asObservable();
  }

  public isInitialized$(): Observable<boolean> {
    return this.isInitializedSubject.asObservable();
  }

  public waitUntilReady(): Promise<void> {
    if (this.isInitializedSubject.value) {
      return Promise.resolve();
    }

    const { loadingPromise } = this;

    if (!loadingPromise) {
      return Promise.resolve();
    }

    return loadingPromise.then(() => {
      if (this.isInitializedSubject.value) {
        return;
      }

      return this.waitUntilReady();
    });
  }

  public isLoadingValue(): boolean {
    return this.isLoadingSubject.value;
  }

  public getOldestTime(): number | null {
    return this.oldestCandle?.time ?? null;
  }

  public getLastValue(): Candle | null {
    return this.lastCandleSubject.value;
  }

  public destroy(): void {
    this.loadSeq += 1;
    this.loadingPromise = null;

    this.currentDataSubject.complete();
    this.realtimeSubject.complete();
    this.lastCandleSubject.complete();
    this.isLoadingSubject.complete();
    this.isInitializedSubject.complete();

    this.realtimeCache = [];
    this.realtimeBuffer = [];
    this.oldestCandle = null;
    this.newestCandle = null;
  }

  public pushRealtime(next: Candle): void {
    const candle = this.normalizeCandle(next);

    this.realtimeCache = this.normalizeList(this.realtimeCache.concat(candle));

    if (!this.newestCandle || candle.time >= this.newestCandle.time) {
      this.newestCandle = candle;
      this.lastCandleSubject.next(candle);
    }

    if (!this.isInitializedSubject.value) {
      this.realtimeBuffer.push(candle);
      return;
    }

    this.realtimeSubject.next(candle);
  }

  public saveRealtimeCache(): void {
    if (this.realtimeCache.length === 0) return;

    const timeframe = this.getTimeframe();

    const current = this.currentDataSubject.value.filter((candle) => candle.open !== undefined);
    const next = this.normalizeList(current.concat(this.realtimeCache));

    this.newestCandle = next[next.length - 1] ?? null;
    this.realtimeCache = [];

    this.currentDataSubject.next(applyWhitespacesToFuture(next, timeframe));
    this.lastCandleSubject.next(this.newestCandle);
  }

  public async loadMoreHistory(): Promise<void> {
    await this.waitUntilReady();

    if (this.isEndOfData) return;

    if (this.loadingPromise) {
      return this.loadingPromise;
    }

    if (!this.oldestCandle) return;

    const seq = ++this.loadSeq;
    const timeframe = this.getTimeframe();
    const oldestCandle = this.oldestCandle;

    const task = (async () => {
      this.isLoadingSubject.next(true);

      try {
        const olderData = await this.getData(timeframe, this.symbol, oldestCandle);
        if (seq !== this.loadSeq) return;

        if (olderData === null) {
          this.isEndOfData = true;
          return;
        }

        const older = this.normalizeList(olderData);

        if (older.length === 0) return;

        const current = this.currentDataSubject.value.filter((candle) => candle.open !== undefined);
        const combined = this.normalizeList(older.concat(current));

        const nextOldest = combined[0] ?? null;

        if (!nextOldest || !this.oldestCandle || nextOldest.time >= this.oldestCandle.time) {
          return;
        }

        this.oldestCandle = nextOldest;
        this.newestCandle = combined[combined.length - 1] ?? this.newestCandle;

        this.currentDataSubject.next(applyWhitespacesToFuture(combined, timeframe));
        this.lastCandleSubject.next(this.newestCandle);

        this.saveRealtimeCache();
      } catch (error) {
        console.error('[DataSource] Ошибка при догрузке истории:', error);
      } finally {
        if (seq === this.loadSeq) this.isLoadingSubject.next(false);
      }
    })();

    this.loadingPromise = task;

    task.finally(() => {
      if (this.loadingPromise === task) {
        this.loadingPromise = null;
      }
    });

    await task;
  }

  public async loadAllHistory(): Promise<void> {
    await this.waitUntilReady();

    if (this.isEndOfData) return;

    if (this.loadingPromise) {
      await this.loadingPromise;
    }

    const seq = ++this.loadSeq;
    const timeframe = this.getTimeframe();

    const task = (async () => {
      this.isLoadingSubject.next(true);

      try {
        let current = this.currentDataSubject.value.filter((candle) => candle.open !== undefined);
        let oldest = current[0] ?? null;

        if (!oldest) return;

        const seenOldestTimes = new Set<number>();

        while (oldest) {
          if (seq !== this.loadSeq) return;

          if (seenOldestTimes.has(oldest.time)) {
            break;
          }

          seenOldestTimes.add(oldest.time);

          // eslint-disable-next-line no-await-in-loop
          const olderData = await this.getData(timeframe, this.symbol, oldest);

          if (seq !== this.loadSeq) return;

          if (olderData === null) {
            this.isEndOfData = true;
            break;
          }

          const older = this.normalizeList(olderData);

          if (older.length === 0) break;

          const combined = this.normalizeList(older.concat(current));
          const nextOldest = combined[0] ?? null;

          if (!nextOldest || nextOldest.time >= oldest.time) {
            break;
          }

          oldest = nextOldest;
          current = combined;
        }

        this.oldestCandle = current[0] ?? null;
        this.newestCandle = current[current.length - 1] ?? null;

        this.currentDataSubject.next(applyWhitespacesToFuture(current, timeframe));
        this.lastCandleSubject.next(this.newestCandle);

        this.saveRealtimeCache();
      } catch (error) {
        console.error('[DataSource] Ошибка при полной загрузке истории:', error);
      } finally {
        if (seq === this.loadSeq) {
          this.isLoadingSubject.next(false);
        }
      }
    })();

    this.loadingPromise = task;

    task.finally(() => {
      if (this.loadingPromise === task) {
        this.loadingPromise = null;
      }
    });

    await task;
  }

  public async loadTill(time: number): Promise<void> {
    await this.waitUntilReady();

    while (this.oldestCandle && this.oldestCandle.time >= time) {
      const before = this.oldestCandle.time;

      // eslint-disable-next-line no-await-in-loop
      await this.loadMoreHistory();

      if (!this.oldestCandle) break;
      if (this.oldestCandle.time === before) break;
    }
  }

  public async reload(timeframe: Timeframes): Promise<void> {
    this.loadSeq += 1;

    const seq = this.loadSeq;

    this.isInitializedSubject.next(false);
    this.isLoadingSubject.next(true);

    this.currentDataSubject.next([]);
    this.realtimeCache = [];
    this.realtimeBuffer = [];
    this.oldestCandle = null;
    this.newestCandle = null;
    this.isEndOfData = false;
    this.lastCandleSubject.next(null);

    const task = (async () => {
      try {
        const loaded = (await this.getData(timeframe, this.symbol)) ?? [];

        if (seq !== this.loadSeq) return;

        const normalized = this.normalizeList(loaded);

        this.oldestCandle = normalized[0] ?? null;
        this.newestCandle = normalized[normalized.length - 1] ?? null;

        this.currentDataSubject.next(applyWhitespacesToFuture(normalized, timeframe));
        this.lastCandleSubject.next(this.newestCandle);

        this.isInitializedSubject.next(true);
        this.flushRealtimeBuffer();
      } catch (error) {
        console.error('[DataSource] Ошибка при загрузке данных:', error);
      } finally {
        if (seq === this.loadSeq) {
          this.isLoadingSubject.next(false);
        }
      }
    })();

    this.loadingPromise = task;

    task.finally(() => {
      if (this.loadingPromise === task) {
        this.loadingPromise = null;
      }
    });

    await task;
  }

  private flushRealtimeBuffer(): void {
    if (this.realtimeBuffer.length === 0) return;

    const newestTime = this.newestCandle?.time ?? Number.NEGATIVE_INFINITY;

    const bufferedCandles = this.normalizeList(this.realtimeBuffer.filter((candle) => candle.time >= newestTime));

    for (const candle of bufferedCandles) {
      this.realtimeSubject.next(candle);
    }

    this.realtimeBuffer = [];
  }

  private normalizeCandle(candle: Candle): Candle {
    const time = candle.time > 1e10 ? Math.floor(candle.time / 1000) : Math.floor(candle.time);

    if (time === candle.time) {
      return candle;
    }

    return {
      ...candle,
      time,
    };
  }

  private normalizeList(candles: Candle[]): Candle[] {
    return normalizeSeriesData(candles.map((candle) => this.normalizeCandle(candle)));
  }
}

export function applyWhitespacesToFuture(data: Candle[], timeframe: Timeframes): Candle[] {
  const lastCandle = data[data.length - 1];

  if (!lastCandle) {
    return data;
  }

  const { candleWidth, dayjsUnit } = parseTimeframe(timeframe);
  const startTime = dayjs.unix(lastCandle.time).utc();
  const result = data.slice();

  for (let index = 1; index <= FUTURE_WHITESPACES; index += 1) {
    result.push({
      time: startTime.add(candleWidth * index, dayjsUnit).unix(),
    } as Candle);
  }

  return result;
}