Загрузка данных
import { BehaviorSubject, combineLatest, map, Observable, Subscription } from 'rxjs';
import { ChartOptionsModel, ChartSeriesType, Intervals, TimeFormat } from '@src/types';
import { Defaults } from '@src/types/defaults';
import { Timeframes } from '@src/types/timeframes';
import { DateFormat, getTimeframeByInterval, shouldShowTime } from '@src/utils';
import { ChartSettings, ChartSettingsSource, parseChartSettings } from './ChartSettings';
import { UndoKey, UndoRedo } from './UndoRedo';
interface EventManagerParams {
initialTimeframe: Timeframes;
initialSeries: ChartSeriesType;
initialSymbol: string;
initialSymbolName?: string;
initialSymbolTicker?: string;
initialTimeFormat?: TimeFormat;
initialDateFormat?: DateFormat;
initialInterval?: Intervals | null;
}
interface SetWithHistoryOptions {
history?: boolean;
}
/**
* Менеджер (настроек)*, которые меняются во время использование
* Отвечает за централизованное управление (настроек)
* * имеются в виду настройки, которые пользователь применяет к графику
*/
export class EventManager {
private timeframe$: BehaviorSubject<Timeframes>;
private seriesSelected$: BehaviorSubject<ChartSeriesType>;
private symbol$: BehaviorSubject<string>;
private symbolName$: BehaviorSubject<string>;
private symbolTicker$: BehaviorSubject<string>;
private timeFormat$: BehaviorSubject<TimeFormat>;
private dateFormat$: BehaviorSubject<DateFormat>;
private interval$: BehaviorSubject<Intervals | null>;
private controlBarVisible$ = new BehaviorSubject<boolean>(false); // todo: move to render
private undoRedo: UndoRedo;
constructor({
initialTimeframe,
initialSeries,
initialSymbol,
initialSymbolName,
initialSymbolTicker,
initialTimeFormat,
initialDateFormat,
initialInterval = null,
}: EventManagerParams) {
this.timeframe$ = new BehaviorSubject<Timeframes>(initialTimeframe);
this.interval$ = new BehaviorSubject<Intervals | null>(initialInterval);
this.seriesSelected$ = new BehaviorSubject<ChartSeriesType>(initialSeries);
this.symbol$ = new BehaviorSubject<string>(initialSymbol);
this.symbolName$ = new BehaviorSubject<string>(initialSymbolName ?? initialSymbol);
this.symbolTicker$ = new BehaviorSubject<string>(initialSymbolTicker ?? initialSymbol);
this.timeFormat$ = new BehaviorSubject<TimeFormat>(initialTimeFormat ?? Defaults.timeFormat);
this.dateFormat$ = new BehaviorSubject<DateFormat>(initialDateFormat ?? Defaults.dateFormat);
this.undoRedo = new UndoRedo({
timeframe: (value) => this.timeframe$.next(value),
seriesSelected: (value) => this.seriesSelected$.next(value),
symbol: (value) => this.symbol$.next(value),
timeFormat: (value) => this.timeFormat$.next(value),
dateFormat: (value) => this.dateFormat$.next(value),
interval: (value) => this.interval$.next(value),
});
}
private setWithHistory<K extends UndoKey, V>(
key: K,
subject: BehaviorSubject<V>,
next: V,
options?: SetWithHistoryOptions,
): void {
const prev = subject.getValue();
if (Object.is(prev, next)) {
return;
}
subject.next(next);
const historyEnabled = options?.history ?? true;
if (historyEnabled) {
this.undoRedo.push(key, prev, next);
}
}
public getUndoRedo(): UndoRedo {
return this.undoRedo;
}
public getTimeframe(): Timeframes {
return this.timeframe$.value;
}
public setInterval = (next: Intervals, options?: SetWithHistoryOptions) => {
const timeframe = getTimeframeByInterval(next);
this.undoRedo.group(() => {
this.setWithHistory('timeframe', this.timeframe$, timeframe, options);
this.setWithHistory('interval', this.interval$, next, options);
});
};
public resetInterval = (options?: SetWithHistoryOptions) =>
this.setWithHistory('interval', this.interval$, null, options);
public getInterval(): Observable<Intervals | null> {
return this.interval$.asObservable();
}
public setSymbol = (symbol: string, options?: SetWithHistoryOptions): void => {
this.setInstrument(symbol, symbol, symbol, options);
};
public getSymbol(): Observable<string> {
return this.symbol$.asObservable();
}
public setInstrument(
symbol: string,
symbolName: string,
symbolTicker?: string,
options?: SetWithHistoryOptions,
): void {
const nextSymbolTicker = symbolTicker ?? symbol;
this.setWithHistory('symbol', this.symbol$, symbol, options);
if (this.symbolName$.value !== symbolName) {
this.symbolName$.next(symbolName);
}
if (this.symbolTicker$.value !== nextSymbolTicker) {
this.symbolTicker$.next(nextSymbolTicker);
}
}
public symbolName(): Observable<string> {
return this.symbolName$.asObservable();
}
public getSymbolName(): string {
return this.symbolName$.value;
}
public symbolTicker(): Observable<string> {
return this.symbolTicker$.asObservable();
}
public getSymbolTicker(): string {
return this.symbolTicker$.value;
}
public setTimeFormat = (next: TimeFormat, options?: SetWithHistoryOptions): void =>
this.setWithHistory('timeFormat', this.timeFormat$, next, options);
public setDateFormat = (next: DateFormat, options?: SetWithHistoryOptions): void =>
this.setWithHistory('dateFormat', this.dateFormat$, next, options);
public getChartOptionsModel(): Observable<ChartOptionsModel> {
// todo: подумать - стоит ли унести это в чарт
return combineLatest([this.timeFormat$, this.dateFormat$, this.timeframe$]).pipe(
map(([timeFormat, dateFormat, timeframe]) => ({
timeFormat,
dateFormat,
showTime: shouldShowTime(timeframe),
})),
);
}
public setTimeframe = (next: Timeframes, options?: SetWithHistoryOptions) =>
this.undoRedo.group(() => {
this.resetInterval(options);
this.setWithHistory('timeframe', this.timeframe$, next, options);
});
public symbol(): Observable<string> {
return this.symbol$.asObservable();
}
public timeframe(): Observable<Timeframes> {
return this.timeframe$.asObservable();
}
public subscribeTimeframe(callback: (format: Timeframes) => void): Subscription {
return this.timeframe$.subscribe(callback);
}
public getTimeframeObs(): Observable<Timeframes> {
return this.timeframe$.asObservable();
}
public setSeriesSelected = (next: ChartSeriesType, options?: SetWithHistoryOptions) =>
this.setWithHistory('seriesSelected', this.seriesSelected$, next, options);
public getSelectedSeries(): Observable<ChartSeriesType> {
return this.seriesSelected$.asObservable();
}
public subscribeSeriesSelected(callback: (next: ChartSeriesType) => void): Subscription {
return this.seriesSelected$.subscribe(callback);
}
public setControlBarVisible(visible: boolean): void {
this.controlBarVisible$.next(visible);
}
public getControlBarVisible(): Observable<boolean> {
return this.controlBarVisible$.asObservable();
}
public exportChartSettings(): ChartSettings {
return {
timeframe: this.timeframe$.value,
seriesSelected: this.seriesSelected$.value,
symbol: this.symbol$.value,
timeFormat: this.timeFormat$.value,
dateFormat: this.dateFormat$.value,
interval: this.interval$.value,
};
}
public importChartSettings(settings: ChartSettingsSource): void {
const { symbol, seriesSelected, timeframe, timeFormat, dateFormat, interval } = parseChartSettings(settings);
const setOptions = { history: false };
if (symbol) {
this.setSymbol(symbol, setOptions);
}
if (seriesSelected) {
this.setSeriesSelected(seriesSelected, setOptions);
}
if (timeFormat) {
this.setTimeFormat(timeFormat, setOptions);
}
if (dateFormat) {
this.setDateFormat(dateFormat, setOptions);
}
if (interval != null) {
this.setInterval(interval, setOptions);
return;
}
if (timeframe) {
this.setTimeframe(timeframe, setOptions);
}
if (interval === null) {
this.resetInterval(setOptions);
}
}
public destroy(): void {
this.timeFormat$.complete();
this.dateFormat$.complete();
this.timeframe$.complete();
this.controlBarVisible$.complete();
this.interval$.complete();
this.symbol$.complete();
this.symbolName$.complete();
this.symbolTicker$.complete();
this.seriesSelected$.complete();
}
}
import { combineLatest, Subscription } from 'rxjs';
import { ControlBar } from '@components/ControlBar';
import { Footer } from '@components/Footer';
import { Header } from '@components/Header';
import { DataSource, DataSourceParams } from '@core/DataSource';
import { Hotkeys } from '@core/Hotkeys';
import { ModalRenderer } from '@core/ModalRenderer';
import { SettingsModal } from '@src/components/SettingsModal';
import Toolbar from '@src/components/Toolbar';
import { IndicatorsIds } from '@src/constants';
import { CompareManager } from '@src/core/CompareManager';
import { FullscreenController } from '@src/core/Fullscreen';
import { configureThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { Locale, setLocale, t } from '@src/translations';
import { Candle, ChartSeriesType, ChartTypeOptions, OHLCConfig, TooltipConfig } from '@src/types';
import { ISerializable, MoexChartSnapshot } from '@src/types/snapshot';
import { Timeframes } from '@src/types/timeframes';
import { setPricePrecision } from '@src/utils';
import { Chart } from './Chart';
import { ChartSettings, ChartSettingsSource } from './ChartSettings';
import { ContainerManager } from './ContainerManager';
import { EventManager } from './EventManager';
import { ReactRenderer } from './ReactRenderer';
import { TimeScaleHoverController } from './TimescaleHoverController';
import { UIRenderer } from './UIRenderer';
import 'exchange-elements/dist/fonts/inter/font.css';
import 'exchange-elements/dist/style.css';
import 'exchange-elements/dist/tokens/moex.css';
import '../styles/global.scss';
// todo: forbid @lib in /src
export interface ChartCollectionPreset {
undoRedoEnabled?: boolean;
showMenuButton?: boolean;
showBottomPanel?: boolean;
showControlBar?: boolean;
showFullscreenButton?: boolean;
showSettingsButton?: boolean;
showCompareButton?: boolean;
showSymbolSearchButton?: boolean;
/**
* Дефолтная конфигурация тултипа - всегда показывается по умолчанию.
* При добавлении/изменении полей в конфиге - они объединяются с дефолтными значениями.
*
* Полная кастомизация:
* @example
* ```typescript
* tooltipConfig: {
* time: { visible: true, label: 'Дата и время' },
* symbol: { visible: true, label: 'Инструмент' },
* close: { visible: true, label: 'Курс' },
* change: { visible: true, label: 'Изменение' },
* volume: { visible: true, label: 'Объем' },
* open: { visible: false },
* high: { visible: false },
* low: { visible: false }
* }
*```
*/
tooltipConfig?: TooltipConfig;
size?:
| {
width: number;
height: number;
}
| false;
supportedTimeframes: Timeframes[];
supportedChartSeriesTypes: ChartSeriesType[];
getDataSource: DataSourceParams['getData'];
startRealtime: (
getSymbols: () => string[],
getTimeframe: () => Timeframes,
update: (symbol: string, candle: Candle) => void,
periodMs?: number,
) => () => void;
theme: ThemeKey; // 'mb' | 'mxt' | 'tr'
ohlc: OHLCConfig;
locale: Locale;
mode?: ThemeMode; // 'light' | 'dark'
openCompareModal?: () => void;
openSymbolSearchModal?: () => void;
}
export interface IMoexChart {
snapshot: MoexChartSnapshot;
chartCollectionPreset: ChartCollectionPreset;
container: HTMLElement;
lwcInheritedChartOptions?: ChartTypeOptions;
}
export class MoexChart implements ISerializable<MoexChartSnapshot> {
private chart!: Chart;
private resizeObserver?: ResizeObserver;
private eventManager!: EventManager;
private hotkeys!: Hotkeys;
private rootContainer!: HTMLElement;
private headerRenderer!: UIRenderer;
private modalRenderer!: ModalRenderer;
private toolbarRenderer: UIRenderer | undefined;
private controlBarRenderer?: UIRenderer;
private footerRenderer?: UIRenderer;
private timeScaleHoverController!: TimeScaleHoverController;
private dataSource!: DataSource;
private subscriptions = new Subscription();
private fullscreen!: FullscreenController;
private chartCollectionPresetSettings!: ChartCollectionPreset;
constructor(config: IMoexChart) {
setLocale(config.chartCollectionPreset.locale);
this.setup(config);
}
private setup = (config: IMoexChart) => {
this.chartCollectionPresetSettings = config.chartCollectionPreset;
setPricePrecision(config.chartCollectionPreset.ohlc.precision);
const { chartSeriesType, symbol, symbolName, symbolTicker, timeframe, interval, dateFormat, timeFormat } =
config.snapshot.charts[0];
this.eventManager = new EventManager({
initialTimeframe: timeframe,
initialSeries: chartSeriesType,
initialSymbol: symbol,
initialSymbolName: symbolName,
initialSymbolTicker: symbolTicker,
initialTimeFormat: timeFormat,
initialDateFormat: dateFormat,
initialInterval: interval,
});
// todo: сюда прокидывается не подходящий под сигнатуру интерфейс. Функция не работает
// if (config.lwcInheritedChartOptions) {
// this.setSettings(config.lwcInheritedChartOptions);
// }
this.dataSource = new DataSource({
getData: config.chartCollectionPreset.getDataSource,
eventManager: this.eventManager,
});
this.rootContainer = config.container;
this.fullscreen = new FullscreenController(this.rootContainer);
const store = configureThemeStore(config.chartCollectionPreset);
const {
chartAreaContainer,
toolBarContainer,
headerContainer,
modalContainer,
controlBarContainer,
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.modalRenderer = new ModalRenderer(modalContainer);
this.chart = new Chart({
params: {
dataSource: this.dataSource,
eventManager: this.eventManager,
modalRenderer: this.modalRenderer,
ohlcConfig: config.chartCollectionPreset.ohlc, // todo: omptimize
tooltipConfig: config.chartCollectionPreset.tooltipConfig ?? {},
panes: config.snapshot.charts[0].panes,
hotkeys: this.hotkeys,
},
lwcChartConfig: {
container: chartAreaContainer,
seriesTypes: config.chartCollectionPreset.supportedChartSeriesTypes,
theme: store.theme,
mode: store.mode,
chartOptions: config.lwcInheritedChartOptions, // todo: remove, use only model from eventManager
},
});
this.subscriptions.add(
combineLatest([store.theme$, store.mode$]).subscribe(([theme, mode]) => {
this.chart.updateTheme(theme, mode);
document.documentElement.dataset.theme = theme;
document.documentElement.dataset.mode = mode;
}),
);
const realtimeParams = this.chart.getRealtimeApi();
this.subscriptions.add(
config.chartCollectionPreset.startRealtime(
realtimeParams.getSymbols,
realtimeParams.getTimeframe,
realtimeParams.update,
),
);
this.headerRenderer = new ReactRenderer(headerContainer);
this.toolbarRenderer = new ReactRenderer(toolBarContainer);
if (config.chartCollectionPreset.showControlBar) {
this.controlBarRenderer = new ReactRenderer(controlBarContainer);
}
if (config.chartCollectionPreset.showBottomPanel) {
this.footerRenderer = new ReactRenderer(footerContainer);
}
this.timeScaleHoverController = new TimeScaleHoverController({
eventManager: this.eventManager,
controlBarContainer,
chartContainer: chartAreaContainer,
});
this.renderAttachments(config, toggleToolbar);
};
public setSettings(settings: ChartSettingsSource): void {
this.eventManager.importChartSettings(settings);
}
public getSettings(): ChartSettings {
return this.eventManager.exportChartSettings();
}
// todo: описать подробнее в доке. Точно ли public?
public getRealtimeApi() {
return this.chart.getRealtimeApi();
}
// todo: описать подробнее в доке
public getCompareManager(): CompareManager {
return this.chart.getCompareManager();
}
public setSnapshot(snap: MoexChartSnapshot) {
const configConstructorLike: IMoexChart = {
snapshot: snap,
chartCollectionPreset: this.chartCollectionPresetSettings,
container: this.rootContainer,
};
this.destroy();
this.setup(configConstructorLike);
}
// todo: описать в доке
public getSnapshot(): MoexChartSnapshot {
const res = {
settings: this.getSettings(),
charts: [this.chart.getSnapshot()], // todo: в будущем может быть несколько инстансов чартов
};
return res;
}
public setSymbol(symbol: string, symbolName?: string, symbolTicker?: string): void {
if (!symbol) return;
this.eventManager.setInstrument(symbol, symbolName ?? symbol, symbolTicker ?? symbol);
}
private renderAttachments(config: IMoexChart, toggleToolbar: () => boolean) {
this.headerRenderer.renderComponent(
<Header
timeframes={config.chartCollectionPreset.supportedTimeframes}
selectedTimeframeObs={this.eventManager.getTimeframeObs()}
setTimeframe={(value) => {
this.eventManager.setTimeframe(value);
}}
seriesTypes={config.chartCollectionPreset.supportedChartSeriesTypes}
selectedSeriesObs={this.eventManager.getSelectedSeries()}
setSelectedSeries={(value) => {
this.eventManager.setSeriesSelected(value);
}}
showSettingsModal={
config.chartCollectionPreset.showSettingsButton
? () =>
this.modalRenderer.renderComponent(
<SettingsModal
// todo: deal with onSave
changeTimeFormat={(format) => this.eventManager.setTimeFormat(format)}
changeDateFormat={(format) => this.eventManager.setDateFormat(format)}
chartDateTimeFormatObs={this.eventManager.getChartOptionsModel()}
/>,
{ title: t('Settings') },
)
: undefined
}
addIndicatorToChart={(indicatorType: IndicatorsIds) =>
this.chart.getIndicatorManager().addIndicator({ indicatorType })
}
showMenuButton={!!config.chartCollectionPreset.showMenuButton}
showFullscreenButton={!!config.chartCollectionPreset.showFullscreenButton}
fullscreen={this.fullscreen}
undoRedo={config.chartCollectionPreset.undoRedoEnabled ? this.eventManager.getUndoRedo() : undefined}
toggleToolbarVisible={toggleToolbar}
showCompareButton={!!config.chartCollectionPreset.showCompareButton}
openCompareModal={
config.chartCollectionPreset.openCompareModal ? config.chartCollectionPreset.openCompareModal : undefined
}
showSymbolSearchButton={!!config.chartCollectionPreset.openSymbolSearchModal}
openSymbolSearchModal={config.chartCollectionPreset.openSymbolSearchModal}
isMXT={config.chartCollectionPreset.theme === 'mxt'}
/>,
);
if (this.toolbarRenderer && config.chartCollectionPreset.showMenuButton) {
this.toolbarRenderer.renderComponent(
<Toolbar
toggleDOM={this.chart.getDom().toggleDOM}
addDrawing={this.chart.getDrawingsManager().addDrawingForce} // todo: deal with new panes logic
setEndlessDrawingsMode={this.chart.getDrawingsManager().setEndlessDrawingMode}
isEndlessDrawingsMode$={this.chart.getDrawingsManager().isEndlessDrawingsMode()}
activateCrosshair={() => this.chart.getDrawingsManager().activateCrosshair()}
activeTool$={this.chart.getDrawingsManager().getActiveTool()}
hotkeys={this.hotkeys}
/>,
);
}
if (this.controlBarRenderer && config.chartCollectionPreset.showControlBar) {
this.controlBarRenderer.renderComponent(
<ControlBar
scroll={this.chart.scrollTimeScale}
zoom={this.chart.zoomTimeScale}
reset={this.chart.resetZoom}
visible={this.eventManager.getControlBarVisible()}
/>,
);
}
if (this.footerRenderer && config.chartCollectionPreset.showBottomPanel) {
this.footerRenderer.renderComponent(
<Footer
supportedTimeframes={config.chartCollectionPreset.supportedTimeframes}
setInterval={this.eventManager.setInterval}
intervalObs={this.eventManager.getInterval()}
/>,
);
}
}
/**
* Уничтожение графика и очистка ресурсов
* @returns void
*/
destroy(): void {
this.headerRenderer.destroy();
this.subscriptions.unsubscribe();
this.timeScaleHoverController.destroy();
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = undefined;
}
if (this.controlBarRenderer) {
this.controlBarRenderer.destroy();
}
if (this.footerRenderer) {
this.footerRenderer.destroy();
}
if (this.chart) {
this.chart.destroy();
}
if (this.eventManager) {
this.eventManager.destroy();
}
this.dataSource.destroy();
ContainerManager.clearContainers(this.rootContainer);
}
}