Загрузка данных
import { type LineData, PriceScaleMode, type WhitespaceData } from 'lightweight-charts';
import type {
DailyClose,
SeasonalityChange,
SeasonalityRange,
SeasonalityScale,
SeasonalityTableRow,
SeasonalityYear,
} from '@src/types';
type SeriesDatum = LineData | WhitespaceData;
const CALENDAR = Array.from({ length: 366 }, (_, day) =>
new Date(Date.UTC(2000, 0, day + 1)).toISOString().slice(0, 10),
);
const ISO_DATE_MONTH_START = 5;
const ISO_DATE_MONTH_END = 7;
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 years: SeasonalityYear[] = [];
const sorted = [...rows].sort((a, b) => a.date.localeCompare(b.date));
for (const row of sorted) {
const year = Number(row.date.slice(0, 4));
let current = years[years.length - 1];
if (!current || current.year !== year) {
current = {
year,
baselineDate: row.date,
baselinePrice: row.close,
points: [],
};
years.push(current);
}
if (current.points[current.points.length - 1]?.date === row.date) {
throw new Error(`Multiple daily candles on ${row.date}`);
}
const percentage = current.baselinePrice > 0 ? (row.close / current.baselinePrice - 1) * 100 : null;
if (percentage !== null && !Number.isFinite(percentage)) {
throw new Error('Invalid percentage');
}
current.points.push({
date: row.date,
chartDate: `2000-${row.date.slice(5)}`,
price: row.close,
percentage,
});
}
return years;
}
export function toSeriesData(year: SeasonalityYear, scale: SeasonalityScale): SeriesDatum[] {
const isPercentage = scale === PriceScaleMode.Percentage;
let index = 0;
return CALENDAR.map((time) => {
const point = year.points[index];
if (point?.chartDate !== time) {
return { time };
}
index += 1;
const value = isPercentage ? point.percentage : point.price;
return value === null ? { time } : { time, value };
});
}
export function buildSeasonalityAverage(years: readonly SeasonalityYear[], scale: SeasonalityScale): SeriesDatum[] {
const values = new Map<string, number[]>();
const isPercentage = scale === PriceScaleMode.Percentage;
for (const year of years) {
for (const point of year.points) {
const value = isPercentage ? point.percentage : point.price;
if (value === null) {
continue;
}
const dailyValues = values.get(point.chartDate) ?? [];
dailyValues.push(value);
values.set(point.chartDate, dailyValues);
}
}
return CALENDAR.map((time) => {
const value = calculateAverage(values.get(time) ?? []);
return value === null ? { time } : { time, value };
});
}
export function buildSeasonalityTable(years: readonly SeasonalityYear[]): SeasonalityTableRow[] {
const closes = new Map<number, number>();
for (const year of years) {
for (const point of year.points) {
const month = Number(point.date.slice(ISO_DATE_MONTH_START, ISO_DATE_MONTH_END)) - 1;
closes.set(year.year * 12 + month, point.price);
}
}
return years
.map((year) => {
const firstMonth = year.year * 12;
const baselineMonth = Number(year.baselineDate.slice(ISO_DATE_MONTH_START, ISO_DATE_MONTH_END)) - 1;
const lastPoint = year.points[year.points.length - 1];
const baselinePrice = closes.get(firstMonth - 1) ?? year.baselinePrice;
return {
year: year.year,
months: Array.from({ length: 12 }, (_, month) => {
const key = firstMonth + month;
const fromPrice = closes.get(key - 1) ?? (month === baselineMonth ? year.baselinePrice : undefined);
return calculateChange(fromPrice, closes.get(key));
}),
total: calculateChange(baselinePrice, lastPoint.price),
};
})
.reverse();
}
function calculateChange(from: number | undefined, to: number | undefined): SeasonalityChange | null {
if (from === undefined || to === undefined) {
return null;
}
return {
absolute: to - from,
percentage: from > 0 ? (to / from - 1) * 100 : null,
};
}
export function buildSeasonalityTableAverage(
rows: readonly SeasonalityTableRow[],
): Pick<SeasonalityTableRow, 'months' | 'total'> | null {
if (rows.length === 0) {
return null;
}
return {
months: Array.from({ length: 12 }, (_, month) => averageChanges(rows.map((row) => row.months[month]))),
total: averageChanges(rows.map((row) => row.total)),
};
}
function averageChanges(changes: readonly (SeasonalityChange | null | undefined)[]): SeasonalityChange | null {
const available = changes.filter((change): change is SeasonalityChange => change !== null && change !== undefined);
if (available.length === 0) {
return null;
}
return {
absolute: available.reduce((sum, change) => sum + change.absolute, 0) / available.length,
percentage: calculateAverage(available.map((change) => change.percentage)),
};
}
function calculateAverage(values: readonly (number | null)[]): number | null {
let sum = 0;
let count = 0;
for (const value of values) {
if (value !== null) {
sum += value;
count += 1;
}
}
return count === 0 ? null : sum / count;
}
import dayjs from 'dayjs';
import {
ColorType,
createChart,
createSeriesMarkers,
CrosshairMode,
type IChartApi,
type ISeriesApi,
type ISeriesMarkersPluginApi,
LineSeries,
LineStyle,
type MouseEventParams,
PriceScaleMode,
type Time,
} from 'lightweight-charts';
import { BehaviorSubject } from 'rxjs';
import { createInitialSeasonalityState, DEFAULT_SEASONALITY_YEARS } from '@src/constants';
import { ZIndex } from '@src/core/ContainerManager';
import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { getThemeStore } from '@src/theme/store';
import { getLocale, t } from '@src/translations';
import { SeasonalityViewType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import {
buildSeasonality,
buildSeasonalityTable,
canvasToBlob,
drawTextLayer,
formatCompactNumber,
formatPercent,
getPercentPrecisionStep,
getPricePrecisionStep,
normalizeRange,
toSeriesData,
} from '@src/utils';
import { buildSeasonalityAverage } from '@src/utils/seasonality';
import type { DataSourceParams } from '@src/core/DataSource';
import type {
Candle,
DailyClose,
SeasonalityRange,
SeasonalityScale,
SeasonalityTableRow,
SeasonalityYear,
} from '@src/types';
interface SeasonalityManagerParams {
container: HTMLElement;
getData: DataSourceParams['getData'];
}
interface SeasonalityPlot {
year: SeasonalityYear;
series: ISeriesApi<'Line'>;
legend: HTMLSpanElement;
legendValue: HTMLSpanElement;
markers?: ISeriesMarkersPluginApi<Time>;
}
interface SeasonalityAveragePlot {
series: ISeriesApi<'Line'>;
legend: HTMLSpanElement;
legendValue: HTMLSpanElement;
data: ReturnType<typeof buildSeasonalityAverage>;
}
export class SeasonalityManager {
private readonly currentYear = dayjs().year();
private readonly state = new BehaviorSubject(createInitialSeasonalityState());
private readonly chartContainer: HTMLDivElement;
private readonly legend: HTMLDivElement;
private readonly statusElement: HTMLDivElement;
private readonly plots = new Map<number, SeasonalityPlot>();
private chart: IChartApi | null = null;
private averagePlot: SeasonalityAveragePlot | null = null;
private allYears: SeasonalityYear[] = [];
private tableRows: SeasonalityTableRow[] = [];
private requestId = 0;
private renderFrame: number | null = null;
private destroyed = false;
constructor(private readonly params: SeasonalityManagerParams) {
const { chartContainer, legend, statusElement } = createSeasonalityElements(params.container);
this.chartContainer = chartContainer;
this.legend = legend;
this.statusElement = statusElement;
this.updateTheme();
}
public getState() {
return this.state.asObservable();
}
public async show(symbolId: string, range?: SeasonalityRange): Promise<void> {
if (this.destroyed || this.reuseHistory(symbolId, range)) {
return;
}
const requestId = ++this.requestId;
this.reset();
this.showStatus(t('Loading seasonality'));
this.state.next({
...this.state.value,
symbolId,
status: 'loading',
tableRows: [],
error: null,
});
try {
if (!symbolId) {
throw new Error('Select an instrument');
}
const rows = await this.loadHistory(symbolId, requestId);
if (!this.isCurrent(requestId)) {
return;
}
this.allYears = buildSeasonality(rows);
this.tableRows = buildSeasonalityTable(this.allYears);
this.setInitialRange(range);
} catch (error) {
if (!this.isCurrent(requestId)) {
return;
}
this.reset();
this.showStatus(t('Unable to load seasonality'));
this.state.next({
...this.state.value,
status: 'error',
tableRows: [],
error: String(error),
});
console.error('[Seasonality] History loading failed:', error);
}
}
public setRange = (range: SeasonalityRange): void => {
if (this.destroyed || 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.allYears.length > 0) {
this.renderRange();
}
});
};
public setDisplayMode = (displayMode: SeasonalityViewType): void => {
if (this.destroyed || this.state.value.displayMode === displayMode) {
return;
}
this.state.next({ ...this.state.value, displayMode });
};
public setAverageVisible = (showAverage: boolean): void => {
if (this.destroyed || this.state.value.showAverage === showAverage) {
return;
}
this.state.next({ ...this.state.value, showAverage });
this.updateAveragePlot(this.getSelectedYears());
this.renderLegend();
this.updateLegend();
};
public setScale = (scale: SeasonalityScale): void => {
if (this.destroyed || this.state.value.scale === scale) {
return;
}
this.state.next({ ...this.state.value, scale });
if (!this.chart) {
return;
}
this.plots.forEach((plot) => this.updateSeries(plot));
this.updateAveragePlot(this.getSelectedYears());
this.fitCalendar();
this.updateStatus();
this.updateLegend();
};
public clear = (): void => {
if (this.destroyed) {
return;
}
this.requestId += 1;
this.reset();
this.state.next({
...this.state.value,
status: 'idle',
tableRows: [],
error: null,
});
};
public updateTheme(): void {
const { colors } = getThemeStore();
Object.assign(this.params.container.style, {
backgroundColor: colors.chartBackground,
});
Object.assign(this.statusElement.style, {
color: colors.chartTextPrimary,
});
this.legend.style.color = colors.chartTextPrimary;
this.chart?.applyOptions(getThemeOptions());
if (this.averagePlot) {
this.averagePlot.series.applyOptions({ color: colors.chartTextPrimary });
this.averagePlot.legendValue.style.color = colors.chartTextPrimary;
}
}
public async copyImage(): Promise<void> {
if (
!this.chart ||
this.state.value.status !== 'ready' ||
this.state.value.displayMode !== SeasonalityViewType.Chart
) {
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.reset();
this.chartContainer.remove();
this.legend.remove();
this.statusElement.remove();
this.state.complete();
}
private isCurrent(requestId: number): boolean {
return !this.destroyed && requestId === this.requestId;
}
private reuseHistory(symbolId: string, range?: SeasonalityRange): boolean {
const state = this.state.value;
if (state.symbolId !== symbolId) {
return false;
}
if (state.status === 'loading') {
return true;
}
if (this.allYears.length === 0) {
return false;
}
if (range) {
this.setRange(range);
}
return true;
}
private async loadHistory(symbolId: string, requestId: number): Promise<DailyClose[]> {
const candles = new Map<number, Candle>();
const loadPage = async (cursor?: Candle): Promise<void> => {
if (!this.isCurrent(requestId)) {
return;
}
const loaded = await this.params.getData(Timeframes['1d'], symbolId, cursor);
if (!this.isCurrent(requestId) || !loaded?.length) {
return;
}
const { oldest, newestTime } = mergeHistoryPage(loaded, candles);
if (cursor && oldest.time >= cursor.time) {
const isBoundaryOnly = oldest.time === cursor.time && newestTime === cursor.time;
if (isBoundaryOnly) {
return;
}
throw new Error(
`History pagination made no progress: cursor=${cursor.time}, ` +
`oldest=${oldest.time}, newest=${newestTime}, count=${loaded.length}`,
);
}
return loadPage(oldest);
};
await loadPage();
if (!this.isCurrent(requestId)) {
return [];
}
return Array.from(candles.values(), (candle) => ({
date: dayjs.unix(candle.time).format('YYYY-MM-DD'),
close: candle.close,
}));
}
private setInitialRange(range?: SeasonalityRange): void {
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: maxYear - DEFAULT_SEASONALITY_YEARS + 1,
toYear: maxYear,
},
minYear,
maxYear,
);
this.state.next({
...this.state.value,
...selected,
minYear,
maxYear,
});
this.renderRange();
}
private createChart(): IChartApi {
const chart = createChart(this.chartContainer, {
...getThemeOptions(),
autoSize: true,
handleScroll: false,
handleScale: false,
kineticScroll: {
mouse: false,
touch: false,
},
rightPriceScale: {
mode: PriceScaleMode.Normal,
autoScale: true,
alignLabels: true,
visible: true,
borderVisible: false,
},
leftPriceScale: {
visible: false,
},
timeScale: {
timeVisible: false,
secondsVisible: false,
borderVisible: false,
allowBoldLabels: false,
rightOffset: 0,
tickMarkFormatter: formatSeasonDate,
lockVisibleTimeRangeOnResize: true,
},
localization: {
locale: getLocale(),
timeFormatter: formatSeasonDate,
},
});
chart.subscribeCrosshairMove(this.onCrosshairMove);
this.chart = chart;
return chart;
}
private renderRange(): void {
const chart = this.chart ?? this.createChart();
const { fromYear, toYear } = this.state.value;
const years = this.getSelectedYears();
this.plots.forEach((plot, year) => {
if (year < fromYear || year > toYear) {
plot.markers?.detach();
chart.removeSeries(plot.series);
this.plots.delete(year);
}
});
const plots = years.map((year) => {
const existing = this.plots.get(year.year);
if (existing) {
return existing;
}
const plot = this.createPlot(chart, year);
this.plots.set(year.year, plot);
return plot;
});
this.updateAveragePlot(years);
this.renderLegend();
if (plots.length > 0) {
this.fitCalendar();
}
this.updateStatus();
this.updateLegend();
this.state.next({
...this.state.value,
status: plots.length > 0 ? 'ready' : 'empty',
tableRows: this.tableRows.filter((row) => row.year >= fromYear && row.year <= toYear),
});
}
private getSelectedYears(): SeasonalityYear[] {
const { fromYear, toYear } = this.state.value;
return this.allYears.filter((year) => year.year >= fromYear && year.year <= toYear);
}
private renderLegend(): void {
const plots = [...this.plots.values()].sort((a, b) => a.year.year - b.year.year);
const elements = plots.flatMap((plot) => [plot.legend, plot.legendValue]);
if (this.averagePlot) {
elements.push(this.averagePlot.legend, this.averagePlot.legendValue);
}
this.legend.replaceChildren(...elements);
}
private updateAveragePlot(years: readonly SeasonalityYear[]): void {
if (!this.chart) {
return;
}
if (!this.state.value.showAverage || years.length === 0) {
if (this.averagePlot) {
this.chart.removeSeries(this.averagePlot.series);
this.averagePlot = null;
}
return;
}
if (!this.averagePlot) {
const legend = document.createElement('span');
const legendValue = document.createElement('span');
const color = getThemeStore().colors.chartTextPrimary;
legend.textContent = t('Avg');
Object.assign(legendValue.style, { color, textAlign: 'right' });
this.averagePlot = {
legend,
legendValue,
data: [],
series: this.chart.addSeries(LineSeries, {
title: t('Avg'),
color,
lineStyle: LineStyle.Dashed,
lineWidth: 2,
priceLineVisible: false,
lastValueVisible: true,
pointMarkersVisible: false,
crosshairMarkerVisible: true,
}),
};
}
this.updatePriceFormat(this.averagePlot.series);
this.averagePlot.data = buildSeasonalityAverage(years, this.state.value.scale);
this.averagePlot.series.setData(this.averagePlot.data);
}
private fitCalendar(): void {
this.chart?.timeScale().setVisibleRange({
from: '2000-01-01',
to: '2000-12-31',
});
}
private createPlot(chart: IChartApi, year: SeasonalityYear): SeasonalityPlot {
const color = getYearColor(year.year);
const legend = document.createElement('span');
const legendValue = document.createElement('span');
legend.textContent = String(year.year);
Object.assign(legendValue.style, {
color,
textAlign: 'right',
});
const plot: SeasonalityPlot = {
year,
legend,
legendValue,
series: chart.addSeries(LineSeries, {
title: String(year.year),
color,
priceLineVisible: false,
lastValueVisible: true,
lineWidth: year.year === this.currentYear ? 3 : 1,
pointMarkersVisible: false,
crosshairMarkerVisible: true,
}),
};
if (year.year === this.currentYear) {
plot.markers = createSeriesMarkers(plot.series, [], {
autoScale: false,
});
}
this.updateSeries(plot);
return plot;
}
private updateSeries({ series, year, markers }: SeasonalityPlot): void {
const { scale } = this.state.value;
const isPercentage = scale === PriceScaleMode.Percentage;
this.updatePriceFormat(series);
series.setData(toSeriesData(year, scale));
if (markers) {
const lastPoint = year.points[year.points.length - 1];
const value = isPercentage ? lastPoint.percentage : lastPoint.price;
markers.setMarkers(
value === null
? []
: [
{
time: lastPoint.chartDate,
position: 'inBar',
shape: 'circle',
color: getYearColor(year.year),
size: 1,
},
],
);
}
}
private updatePriceFormat(series: ISeriesApi<'Line'>): void {
const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;
series.applyOptions({
priceFormat: {
type: 'custom',
minMove: isPercentage ? getPercentPrecisionStep() : getPricePrecisionStep(),
formatter: (value: number) => (isPercentage ? formatPercent(value) : formatCompactNumber(value)),
},
});
}
private updateStatus(): void {
if (this.plots.size === 0) {
this.showStatus(t('No seasonality data'));
return;
}
const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;
const hasBaseline = Array.from(this.plots.values()).some((plot) => plot.year.baselinePrice > 0);
if (isPercentage && !hasBaseline) {
this.showStatus(t('Percentage requires a positive baseline'));
return;
}
this.statusElement.style.display = 'none';
}
private onCrosshairMove = (event: MouseEventParams): void => {
this.updateLegend(event);
};
private updateLegend(event?: MouseEventParams): void {
const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;
this.plots.forEach(({ year, series, legendValue }) => {
const lastPoint = year.points[year.points.length - 1];
let value = isPercentage ? lastPoint.percentage : lastPoint.price;
if (event?.time !== undefined) {
value = getCrosshairValue(event, series);
}
legendValue.textContent = value === null ? '—' : series.priceFormatter().format(value);
});
this.updateAverageLegend(event);
}
private updateAverageLegend(event?: MouseEventParams): void {
const average = this.averagePlot;
if (!average) {
return;
}
let value: number | null = null;
if (event?.time !== undefined) {
value = getCrosshairValue(event, average.series);
} else {
for (const point of average.data) {
if ('value' in point) {
value = point.value;
}
}
}
average.legend.textContent = t('Avg');
average.legendValue.textContent = value === null ? '—' : average.series.priceFormatter().format(value);
}
private showStatus(message: string): void {
this.statusElement.textContent = message;
this.statusElement.style.display = 'flex';
}
private reset(): void {
if (this.renderFrame !== null) {
cancelAnimationFrame(this.renderFrame);
this.renderFrame = null;
}
this.chart?.unsubscribeCrosshairMove(this.onCrosshairMove);
this.plots.forEach((plot) => plot.markers?.detach());
this.chart?.remove();
this.chart = null;
this.averagePlot = null;
this.allYears = [];
this.tableRows = [];
this.plots.clear();
this.legend.replaceChildren();
this.statusElement.style.display = 'none';
}
}
function getCrosshairValue(event: MouseEventParams, series: ISeriesApi<'Line'>): number | null {
const point = event.seriesData.get(series);
return point && 'value' in point && typeof point.value === 'number' ? point.value : null;
}
function mergeHistoryPage(loaded: Candle[], candles: Map<number, Candle>): { oldest: Candle; newestTime: number } {
let oldest = loaded[0];
let oldestTime = Infinity;
let newestTime = -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);
const normalized = time === candle.time ? candle : { ...candle, time };
newestTime = Math.max(newestTime, time);
if (time < oldestTime) {
oldest = normalized;
oldestTime = time;
}
if (!candles.has(time)) {
candles.set(time, normalized);
}
}
return { oldest, newestTime };
}
function getThemeOptions() {
const { colors } = getThemeStore();
return {
layout: {
background: {
type: ColorType.Solid,
color: colors.chartBackground,
},
textColor: colors.chartTextPrimary,
panes: {
separatorColor: colors.chartPaneSeparator,
separatorHoverColor: colors.chartPaneSeparator,
enableResize: false,
},
},
grid: {
vertLines: {
color: colors.chartGridLine,
},
horzLines: {
color: colors.chartGridLine,
},
},
crosshair: {
mode: CrosshairMode.Normal,
vertLine: {
color: colors.chartCrosshairLine,
labelBackgroundColor: colors.chartCrosshairLabel,
style: LineStyle.Solid,
},
horzLine: {
color: colors.chartCrosshairLine,
labelBackgroundColor: colors.chartCrosshairLabel,
style: LineStyle.Dashed,
},
},
};
}
function formatSeasonDate(time: Time): string {
if (typeof time === 'object') {
const day = String(time.day).padStart(2, '0');
const month = String(time.month).padStart(2, '0');
return `${day}.${month}`;
}
const date = typeof time === 'number' ? new Date(time * 1000).toISOString() : time;
return `${date.slice(8, 10)}.${date.slice(5, 7)}`;
}
function getYearColor(year: number): string {
return COMPARE_COLOR_PALETTE[year % COMPARE_COLOR_PALETTE.length];
}
function createSeasonalityElements(container: HTMLElement) {
const chartContainer = document.createElement('div');
const legend = document.createElement('div');
const statusElement = document.createElement('div');
Object.assign(chartContainer.style, {
position: 'absolute',
inset: 0,
});
Object.assign(legend.style, {
width: 'max-content',
position: 'absolute',
top: 0,
left: 0,
display: 'grid',
gridTemplateColumns: 'max-content max-content',
justifyContent: 'start',
alignItems: 'center',
gap: 'var(--space-0125) var(--space-0500)',
fontSize: 'var(--space-0750)',
lineHeight: 'var(--space-1000)',
fontVariantNumeric: 'tabular-nums',
pointerEvents: 'none',
zIndex: ZIndex.Legend,
});
Object.assign(statusElement.style, {
position: 'absolute',
inset: 0,
display: 'none',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
pointerEvents: 'none',
});
container.append(chartContainer, legend, statusElement);
return { chartContainer, legend, statusElement };
}
import { PriceScaleMode } from 'lightweight-charts';
import {
buildSeasonality,
buildSeasonalityAverage,
buildSeasonalityTable,
buildSeasonalityTableAverage,
normalizeRange,
toSeriesData,
} from '@src/utils/seasonality';
import type { SeasonalityTableRow } from '@src/types';
describe('normalizeRange', () => {
it.each([
[
{ fromYear: 2010, toYear: 2040 },
{ fromYear: 2020, toYear: 2025 },
],
[
{ fromYear: 2022.6, toYear: 2024.4 },
{ fromYear: 2023, toYear: 2024 },
],
[
{ fromYear: 2024, toYear: 2021 },
{ fromYear: 2024, toYear: 2024 },
],
[
{ fromYear: 2010, toYear: 2011 },
{ fromYear: 2020, toYear: 2020 },
],
])('должен ограничивать и упорядочивать диапазон %j', (input, expected) => {
expect(normalizeRange(input, 2020, 2025)).toEqual(expected);
});
it.each([NaN, Infinity, -Infinity])('должен отклонять некорректную границу %s', (value) => {
expect(() => normalizeRange({ fromYear: value, toYear: 2024 }, 2020, 2025)).toThrow('Invalid year range');
expect(() => normalizeRange({ fromYear: 2020, toYear: value }, 2020, 2025)).toThrow('Invalid year range');
});
});
describe('buildSeasonality', () => {
it('должен возвращать пустой результат для пустой истории', () => {
expect(buildSeasonality([])).toEqual([]);
});
it('должен сортировать данные без изменения исходного массива и выбирать базу отдельно для каждого года', () => {
const rows = [
{ date: '2024-01-03', close: 125 },
{ date: '2023-12-31', close: 50 },
{ date: '2024-01-02', close: 100 },
];
const snapshot = rows.map((row) => ({ ...row }));
const years = buildSeasonality(rows);
expect(rows).toEqual(snapshot);
expect(years.map(({ year, baselinePrice }) => [year, baselinePrice])).toEqual([
[2023, 50],
[2024, 100],
]);
expect(years[1].baselineDate).toBe('2024-01-02');
expect(years[1].points.map(({ percentage }) => percentage)).toEqual([0, 25]);
expect(years[1].points[0].chartDate).toBe('2000-01-02');
});
it('должен рассчитывать отрицательную доходность', () => {
const [year] = buildSeasonality([
{ date: '2024-01-01', close: 100 },
{ date: '2024-01-02', close: 75 },
]);
expect(year.points[1].percentage).toBe(-25);
});
it.each([0, -10])('должен сохранять цены без процентов при неположительной базе %s', (close) => {
const [year] = buildSeasonality([
{ date: '2024-01-01', close },
{ date: '2024-01-02', close: 10 },
]);
expect(year.points.map((point) => point.percentage)).toEqual([null, null]);
expect(year.points[1].price).toBe(10);
});
it('должен отклонять повторяющиеся даты независимо от порядка данных', () => {
expect(() =>
buildSeasonality([
{ date: '2024-01-01', close: 100 },
{ date: '2023-01-01', close: 90 },
{ date: '2024-01-01', close: 101 },
]),
).toThrow('Multiple daily candles');
});
it('должен отклонять переполнение при расчёте доходности', () => {
expect(() =>
buildSeasonality([
{ date: '2024-01-01', close: Number.MIN_VALUE },
{ date: '2024-01-02', close: Number.MAX_VALUE },
]),
).toThrow('Invalid percentage');
});
});
describe('toSeriesData', () => {
it('должен совмещать годы по високосному календарю и сохранять пропуски торговых дней', () => {
const [year] = buildSeasonality([
{ date: '2023-02-28', close: 100 },
{ date: '2023-03-01', close: 110 },
]);
const data = toSeriesData(year, PriceScaleMode.Normal);
expect(data).toHaveLength(366);
expect(data[0]).toEqual({ time: '2000-01-01' });
expect(data[data.length - 1]).toEqual({ time: '2000-12-31' });
expect(data.find((point) => point.time === '2000-02-28')).toEqual({
time: '2000-02-28',
value: 100,
});
expect(data.find((point) => point.time === '2000-02-29')).toEqual({
time: '2000-02-29',
});
expect(data.find((point) => point.time === '2000-03-01')).toEqual({
time: '2000-03-01',
value: 110,
});
});
it('должен сохранять 29 февраля и рассчитывать процентные значения', () => {
const [year] = buildSeasonality([
{ date: '2024-02-29', close: 10 },
{ date: '2024-03-01', close: 15 },
]);
const data = toSeriesData(year, PriceScaleMode.Percentage);
expect(data.find((point) => point.time === '2000-02-29')).toEqual({
time: '2000-02-29',
value: 0,
});
expect(data.find((point) => point.time === '2000-03-01')).toEqual({
time: '2000-03-01',
value: 50,
});
});
it('должен оставлять пропуски вместо процентов при отсутствии положительной базы', () => {
const [year] = buildSeasonality([{ date: '2024-01-01', close: 0 }]);
expect(toSeriesData(year, PriceScaleMode.Percentage)[0]).toEqual({
time: '2000-01-01',
});
expect(toSeriesData(year, PriceScaleMode.Normal)[0]).toEqual({
time: '2000-01-01',
value: 0,
});
});
});
describe('buildSeasonalityTable', () => {
it('должен возвращать пустую таблицу без истории', () => {
expect(buildSeasonalityTable([])).toEqual([]);
});
it('должен использовать последние закрытия месяцев и предыдущий декабрь', () => {
const years = buildSeasonality([
{ date: '2024-02-29', close: 121 },
{ date: '2024-01-31', close: 110 },
{ date: '2023-12-29', close: 100 },
{ date: '2024-01-02', close: 105 },
]);
const [row] = buildSeasonalityTable(years);
expect(buildSeasonalityTable(years).map((item) => item.year)).toEqual([2024, 2023]);
expect(row.months).toHaveLength(12);
expect(row.months[0]?.absolute).toBe(10);
expect(row.months[0]?.percentage).toBeCloseTo(10, 10);
expect(row.months[1]?.absolute).toBe(11);
expect(row.months[1]?.percentage).toBeCloseTo(10, 10);
expect(row.total?.absolute).toBe(21);
expect(row.total?.percentage).toBeCloseTo(21, 10);
expect(row.months.slice(2)).toEqual(Array(10).fill(null));
});
it('должен рассчитывать первый неполный месяц и год от первой доступной цены', () => {
const years = buildSeasonality([
{ date: '2021-10-15', close: 100 },
{ date: '2021-10-29', close: 101 },
{ date: '2021-11-30', close: 105 },
{ date: '2021-12-30', close: 106 },
]);
const [row] = buildSeasonalityTable(years);
expect(row.months.slice(0, 9)).toEqual(Array(9).fill(null));
expect(row.months[9]?.absolute).toBe(1);
expect(row.months[9]?.percentage).toBeCloseTo(1, 10);
expect(row.months[10]?.absolute).toBe(4);
expect(row.months[11]?.absolute).toBe(1);
expect(row.total?.absolute).toBe(6);
expect(row.total?.percentage).toBeCloseTo(6, 10);
});
it('должен сохранять пропуски внутри года и рассчитывать итог по доступным ценам', () => {
const years = buildSeasonality([
{ date: '2024-01-02', close: 100 },
{ date: '2024-01-31', close: 110 },
{ date: '2024-03-15', close: 120 },
{ date: '2024-03-29', close: 132 },
{ date: '2024-04-30', close: 132 },
]);
const [row] = buildSeasonalityTable(years);
expect(row.months[1]).toBeNull();
expect(row.months[2]).toBeNull();
expect(row.months[3]).toEqual({
absolute: 0,
percentage: 0,
});
expect(row.total?.absolute).toBe(32);
expect(row.total?.percentage).toBeCloseTo(32, 10);
});
it.each([0, -10])('должен сохранять неположительную базу предыдущего декабря %s', (baseline) => {
const years = buildSeasonality([
{ date: '2023-12-29', close: baseline },
{ date: '2024-01-02', close: 50 },
{ date: '2024-01-31', close: 100 },
]);
const [row] = buildSeasonalityTable(years);
expect(row.months[0]).toEqual({
absolute: 100 - baseline,
percentage: null,
});
expect(row.total).toEqual({
absolute: 100 - baseline,
percentage: null,
});
});
it('должен использовать первую цену года при отсутствии предыдущего декабря', () => {
const years = buildSeasonality([
{ date: '2023-11-30', close: 80 },
{ date: '2024-01-02', close: 100 },
{ date: '2024-01-31', close: 110 },
]);
const [row] = buildSeasonalityTable(years);
expect(row.months[0]?.absolute).toBe(10);
expect(row.months[0]?.percentage).toBeCloseTo(10, 10);
expect(row.total?.absolute).toBe(10);
expect(row.total?.percentage).toBeCloseTo(10, 10);
});
it('должен сохранять точность и рассчитывать отрицательный годовой итог', () => {
const years = buildSeasonality([
{ date: '2023-12-29', close: 100 },
{ date: '2024-01-31', close: 90 },
{ date: '2024-02-29', close: 99.0044 },
]);
const [row] = buildSeasonalityTable(years);
expect(row.months[0]?.percentage).toBeCloseTo(-10, 10);
expect(row.months[1]?.absolute).toBeCloseTo(9.0044, 10);
expect(row.total?.absolute).toBeCloseTo(-0.9956, 10);
expect(row.total?.percentage).toBeCloseTo(-0.9956, 10);
});
});
describe('buildSeasonalityAverage', () => {
it('должен возвращать календарь без значений для пустой истории', () => {
const data = buildSeasonalityAverage([], PriceScaleMode.Normal);
expect(data).toHaveLength(366);
expect(data[0]).toEqual({ time: '2000-01-01' });
expect(data[data.length - 1]).toEqual({ time: '2000-12-31' });
expect(data.every((point) => !('value' in point))).toBe(true);
});
it('должен усреднять только доступные цены, включая нули', () => {
const years = buildSeasonality([
{ date: '2023-01-01', close: 100 },
{ date: '2023-01-02', close: 200 },
{ date: '2024-01-01', close: 200 },
{ date: '2024-01-02', close: 200 },
{ date: '2025-01-01', close: 0 },
{ date: '2025-01-03', close: 20 },
]);
const data = buildSeasonalityAverage(years, PriceScaleMode.Normal);
expect(data[0]).toEqual({ time: '2000-01-01', value: 100 });
expect(data[1]).toEqual({ time: '2000-01-02', value: 200 });
expect(data[2]).toEqual({ time: '2000-01-03', value: 20 });
expect(data[3]).toEqual({ time: '2000-01-04' });
});
it('должен усреднять проценты каждого года и исключать отсутствующую базу', () => {
const years = buildSeasonality([
{ date: '2023-01-01', close: 100 },
{ date: '2023-01-02', close: 200 },
{ date: '2024-01-01', close: 200 },
{ date: '2024-01-02', close: 200 },
{ date: '2025-01-01', close: 0 },
{ date: '2025-01-03', close: 20 },
]);
const data = buildSeasonalityAverage(years, PriceScaleMode.Percentage);
expect(data[0]).toEqual({ time: '2000-01-01', value: 0 });
expect(data[1]).toEqual({ time: '2000-01-02', value: 50 });
expect(data[2]).toEqual({ time: '2000-01-03' });
});
it('должен сохранять нулевое среднее отрицательных и положительных процентов', () => {
const years = buildSeasonality([
{ date: '2023-01-01', close: 100 },
{ date: '2023-01-02', close: 0 },
{ date: '2024-01-01', close: 100 },
{ date: '2024-01-02', close: 200 },
]);
expect(buildSeasonalityAverage(years, PriceScaleMode.Percentage)[1]).toEqual({
time: '2000-01-02',
value: 0,
});
});
it('должен учитывать 29 февраля без заполнения отсутствующих дат', () => {
const years = buildSeasonality([
{ date: '2023-02-28', close: 100 },
{ date: '2024-02-29', close: 200 },
]);
const data = buildSeasonalityAverage(years, PriceScaleMode.Normal);
expect(data.find((point) => point.time === '2000-02-28')).toEqual({
time: '2000-02-28',
value: 100,
});
expect(data.find((point) => point.time === '2000-02-29')).toEqual({
time: '2000-02-29',
value: 200,
});
expect(data.find((point) => point.time === '2000-03-01')).toEqual({
time: '2000-03-01',
});
});
it('должен сохранять точность и не изменять исходные годы', () => {
const years = buildSeasonality([
{ date: '2023-01-01', close: 3.123456 },
{ date: '2024-01-01', close: 7.987654 },
]);
const snapshot = JSON.parse(JSON.stringify(years));
const [point] = buildSeasonalityAverage(years, PriceScaleMode.Normal);
expect('value' in point && point.value).toBeCloseTo(5.555555, 10);
expect(years).toEqual(snapshot);
});
it('должен усреднять доступные проценты после первого года без положительной базы', () => {
const years = buildSeasonality([
{ date: '2023-01-01', close: 0 },
{ date: '2023-01-02', close: 10 },
{ date: '2024-01-01', close: 100 },
{ date: '2024-01-02', close: 50 },
{ date: '2025-01-01', close: 200 },
{ date: '2025-01-02', close: 300 },
]);
const data = buildSeasonalityAverage(years, PriceScaleMode.Percentage);
expect(data[0]).toEqual({ time: '2000-01-01', value: 0 });
expect(data[1]).toEqual({ time: '2000-01-02', value: 0 });
});
it('должен оставлять весь календарь пустым при отсутствии процентной базы у всех лет', () => {
const years = buildSeasonality([
{ date: '2023-01-01', close: 0 },
{ date: '2023-01-02', close: 10 },
{ date: '2024-01-01', close: -100 },
{ date: '2024-01-02', close: 50 },
]);
const data = buildSeasonalityAverage(years, PriceScaleMode.Percentage);
expect(data).toHaveLength(366);
expect(data.every((point) => !('value' in point))).toBe(true);
});
});
describe('buildSeasonalityTableAverage', () => {
it('должен возвращать null без строк', () => {
expect(buildSeasonalityTableAverage([])).toBeNull();
});
it('должен отдельно усреднять месяцы и годовые итоги с учётом нулей и пропусков', () => {
const rows: SeasonalityTableRow[] = [
{
year: 2023,
months: [{ absolute: 10, percentage: 10 }, null, { absolute: 0, percentage: 0 }],
total: { absolute: 30, percentage: 30 },
},
{
year: 2024,
months: [
{ absolute: 20, percentage: null },
{ absolute: -5, percentage: -5 },
],
total: { absolute: -10, percentage: -10 },
},
{
year: 2025,
months: [{ absolute: 0, percentage: 0 }],
total: null,
},
];
const snapshot = JSON.parse(JSON.stringify(rows));
const average = buildSeasonalityTableAverage(rows)!;
expect(average.months).toHaveLength(12);
expect(average.months[0]).toEqual({ absolute: 10, percentage: 5 });
expect(average.months[1]).toEqual({ absolute: -5, percentage: -5 });
expect(average.months[2]).toEqual({ absolute: 0, percentage: 0 });
expect(average.months.slice(3)).toEqual(Array(9).fill(null));
expect(average.total).toEqual({ absolute: 10, percentage: 10 });
expect(rows).toEqual(snapshot);
});
it('должен сохранять абсолютное среднее при отсутствии процентных значений', () => {
const average = buildSeasonalityTableAverage([
{
year: 2024,
months: [{ absolute: 0, percentage: null }],
total: { absolute: -2, percentage: null },
},
])!;
expect(average.months[0]).toEqual({ absolute: 0, percentage: null });
expect(average.total).toEqual({ absolute: -2, percentage: null });
});
it('должен возвращать пропуски для полностью пустых колонок и итогов', () => {
expect(buildSeasonalityTableAverage([{ year: 2024, months: [], total: null }])).toEqual({
months: Array(12).fill(null),
total: null,
});
});
it('не должен округлять средние значения до точности отображения', () => {
const average = buildSeasonalityTableAverage([
{ year: 2023, months: [], total: { absolute: 3.123456, percentage: 1.123456 } },
{ year: 2024, months: [], total: { absolute: 7.987654, percentage: 2.987654 } },
])!;
expect(average.total?.absolute).toBeCloseTo(5.555555, 10);
expect(average.total?.percentage).toBeCloseTo(2.055555, 10);
});
});
import { createChart, createSeriesMarkers, LineStyle, PriceScaleMode } from 'lightweight-charts';
import { SeasonalityManager } from '@core/SeasonalityManager';
import { createInitialSeasonalityState } from '@src/constants';
import { getThemeStore } from '@src/theme/store';
import { SeasonalityViewType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { canvasToBlob, drawTextLayer } from '@src/utils';
import { setPricePrecision } from '@src/utils/precision';
import type { Candle } from '@src/types';
import type { ChartOptions, DeepPartial, LineData, LineSeriesPartialOptions, WhitespaceData } from 'lightweight-charts';
interface SeriesTestContext {
options: LineSeriesPartialOptions;
applyOptions: jest.Mock;
setData: jest.Mock;
priceFormatter: () => {
format: (value: number) => string;
};
}
interface ChartTestContext {
options: DeepPartial<ChartOptions>;
series: SeriesTestContext[];
addSeries: jest.Mock;
applyOptions: jest.Mock;
removeSeries: jest.Mock;
remove: jest.Mock;
timeScale: () => {
setVisibleRange: jest.Mock;
};
subscribeCrosshairMove: jest.Mock;
unsubscribeCrosshairMove: jest.Mock;
takeScreenshot: jest.Mock;
chartElement: () => HTMLElement;
}
interface MarkersTestContext {
setMarkers: jest.Mock;
detach: jest.Mock;
}
const mocks = {
charts: [] as ChartTestContext[],
markers: [] as MarkersTestContext[],
};
function createSeriesContext(options: LineSeriesPartialOptions): SeriesTestContext {
return {
options,
applyOptions: jest.fn(),
setData: jest.fn(),
priceFormatter: () => ({
format: (value: number) => value.toFixed(2),
}),
};
}
function createChartContext(container: HTMLElement, options: DeepPartial<ChartOptions>): ChartTestContext {
const timeScale = {
setVisibleRange: jest.fn(),
};
const series: SeriesTestContext[] = [];
return {
options,
series,
addSeries: jest.fn((_type: unknown, seriesOptions: LineSeriesPartialOptions) => {
const item = createSeriesContext(seriesOptions);
series.push(item);
return item;
}),
applyOptions: jest.fn(),
removeSeries: jest.fn(),
remove: jest.fn(),
timeScale: () => timeScale,
subscribeCrosshairMove: jest.fn(),
unsubscribeCrosshairMove: jest.fn(),
takeScreenshot: jest.fn(() => document.createElement('canvas')),
chartElement: () => container,
};
}
jest.mock('lightweight-charts', () => ({
...jest.requireActual('lightweight-charts'),
createChart: jest.fn(),
createSeriesMarkers: jest.fn(),
}));
jest.mock('@src/theme/store', () => ({
getThemeStore: jest.fn(),
}));
jest.mock('@src/translations', () => ({
t: (key: string) => key,
getLocale: () => 'en',
}));
jest.mock('@src/utils', () => ({
...jest.requireActual('@src/utils/seasonality'),
...jest.requireActual('@src/utils/precision'),
formatCompactNumber: (value: number) => String(value),
formatPercent: (value: number) => `${value.toFixed(2)}%`,
canvasToBlob: jest.fn(),
drawTextLayer: jest.fn(),
}));
function getLastCall(mock: jest.Mock) {
return mock.mock.calls[mock.mock.calls.length - 1];
}
function getLegendValue(label: string): string | null {
const element = [...container.querySelectorAll('span')].find((item) => item.textContent === label);
return element?.nextElementSibling?.textContent ?? null;
}
function createCandle(date: string, close = 100, milliseconds = false): Candle {
return {
time: Date.parse(`${date}T12:00:00Z`) / (milliseconds ? 1 : 1000),
open: close,
high: close,
low: close,
close,
volume: 1,
};
}
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
let container: HTMLDivElement;
let manager: SeasonalityManager;
let getData: jest.Mock;
let state: ReturnType<typeof createInitialSeasonalityState>;
let frames: Map<number, FrameRequestCallback>;
let nextFrame: number;
let clipboardDescriptor: PropertyDescriptor | undefined;
let clipboardItemDescriptor: PropertyDescriptor | undefined;
const colors = {
chartBackground: '#ffffff',
chartTextPrimary: '#111111',
chartPaneSeparator: '#222222',
chartGridLine: '#333333',
chartCrosshairLine: '#444444',
chartCrosshairLabel: '#555555',
};
function createManager() {
manager = new SeasonalityManager({
container,
getData,
});
manager.getState().subscribe((value) => {
state = value;
});
}
function flushAnimationFrames() {
const callbacks = [...frames.values()];
frames.clear();
callbacks.forEach((callback) => callback(0));
}
async function loadSampleHistory() {
getData
.mockResolvedValueOnce([
createCandle('2020-01-01'),
createCandle('2023-01-01'),
createCandle('2025-01-01'),
createCandle('2025-01-02', 125),
])
.mockResolvedValueOnce(null);
await manager.show('AAA', {
fromYear: 2020,
toYear: 2025,
});
}
beforeEach(() => {
clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
clipboardItemDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'ClipboardItem');
jest.useFakeTimers();
jest.setSystemTime(new Date('2025-06-01T12:00:00Z'));
setPricePrecision(3);
jest.spyOn(console, 'error').mockImplementation(() => {});
mocks.charts.length = 0;
mocks.markers.length = 0;
(createChart as jest.Mock).mockImplementation((element: HTMLElement, options: DeepPartial<ChartOptions>) => {
const chart = createChartContext(element, options);
mocks.charts.push(chart);
return chart;
});
(createSeriesMarkers as jest.Mock).mockImplementation(() => {
const markers = {
setMarkers: jest.fn(),
detach: jest.fn(),
};
mocks.markers.push(markers);
return markers;
});
frames = new Map();
nextFrame = 0;
jest.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
frames.set(++nextFrame, callback);
return nextFrame;
});
jest.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => {
frames.delete(id);
});
jest.mocked(getThemeStore).mockReturnValue({
colors,
} as ReturnType<typeof getThemeStore>);
getData = jest.fn();
container = document.createElement('div');
document.body.append(container);
state = createInitialSeasonalityState();
createManager();
});
afterEach(() => {
manager.destroy();
container.remove();
setPricePrecision();
if (clipboardDescriptor) {
Object.defineProperty(navigator, 'clipboard', clipboardDescriptor);
} else {
Reflect.deleteProperty(navigator, 'clipboard');
}
if (clipboardItemDescriptor) {
Object.defineProperty(globalThis, 'ClipboardItem', clipboardItemDescriptor);
} else {
Reflect.deleteProperty(globalThis, 'ClipboardItem');
}
jest.restoreAllMocks();
jest.clearAllMocks();
jest.useRealTimers();
});
describe('SeasonalityManager: загрузка истории', () => {
it('должен загружать дневные страницы, нормализовать время и удалять граничные дубликаты', async () => {
const boundary = createCandle('2025-01-02', 125);
getData
.mockResolvedValueOnce([boundary, createCandle('2025-01-03', 150, true)])
.mockResolvedValueOnce([createCandle('2025-01-01', 100), boundary])
.mockResolvedValueOnce(null);
await manager.show('AAA');
expect(state.status).toBe('ready');
expect(getData.mock.calls.map((args) => args.slice(0, 2))).toEqual(Array(3).fill([Timeframes['1d'], 'AAA']));
expect(getData.mock.calls[1][2].time).toBe(boundary.time);
manager.setScale(PriceScaleMode.Normal);
const data = getLastCall(mocks.charts[0].series[0].setData)[0];
expect(data.filter((point: LineData | WhitespaceData) => 'value' in point)).toEqual([
{ time: '2000-01-01', value: 100 },
{ time: '2000-01-02', value: 125 },
{ time: '2000-01-03', value: 150 },
]);
});
it('должен завершать загрузку при повторении только граничной свечи', async () => {
const first = createCandle('2025-01-01');
getData.mockResolvedValueOnce([first]).mockResolvedValueOnce([first]);
await manager.show('AAA');
expect(state.status).toBe('ready');
expect(getData).toHaveBeenCalledTimes(2);
});
it('должен показывать ошибку при отсутствии прогресса пагинации', async () => {
getData.mockResolvedValueOnce([createCandle('2025-01-01')]).mockResolvedValueOnce([createCandle('2025-01-02')]);
await manager.show('AAA');
expect(state.status).toBe('error');
expect(state.error).toContain('made no progress');
});
it.each([{ page: null }, { page: [] }])('должен показывать пустое состояние для страницы $page', async ({ page }) => {
getData.mockResolvedValueOnce(page);
await manager.show('AAA');
expect(state.status).toBe('empty');
expect(mocks.charts).toHaveLength(0);
expect(container.textContent).toContain('No seasonality data');
});
it('не должен запрашивать историю без выбранного инструмента', async () => {
await manager.show('');
expect(state.status).toBe('error');
expect(getData).not.toHaveBeenCalled();
});
it.each(['time', 'close'] as const)('должен отклонять некорректное поле %s', async (field) => {
getData.mockResolvedValueOnce([
{
...createCandle('2025-01-01'),
[field]: NaN,
},
]);
await manager.show('AAA');
expect(state.status).toBe('error');
expect(state.error).toContain('Invalid daily candle');
});
it('должен повторно загружать историю после ошибки', async () => {
getData.mockRejectedValueOnce(new Error('network'));
await manager.show('AAA');
expect(state.status).toBe('error');
await loadSampleHistory();
expect(state.status).toBe('ready');
expect(state.error).toBeNull();
});
it('не должен применять ответ после очистки сезонности', async () => {
const request = createDeferred<Candle[]>();
getData.mockReturnValueOnce(request.promise);
const loading = manager.show('AAA');
expect(state.status).toBe('loading');
manager.clear();
request.resolve([createCandle('2025-01-01')]);
await loading;
expect(state.status).toBe('idle');
expect(state.tableRows).toEqual([]);
expect(mocks.charts).toHaveLength(0);
});
it('не должен применять ошибку предыдущего инструмента', async () => {
const old = createDeferred<Candle[]>();
getData.mockReturnValueOnce(old.promise);
const loading = manager.show('OLD');
getData.mockResolvedValueOnce([createCandle('2025-01-01')]).mockResolvedValueOnce(null);
await manager.show('NEW');
old.reject(new Error('late failure'));
await loading;
expect(state.symbolId).toBe('NEW');
expect(state.status).toBe('ready');
expect(state.tableRows.map((row) => row.year)).toEqual([2025]);
expect(console.error).not.toHaveBeenCalled();
});
it('не должен применять данные предыдущего инструмента', async () => {
const old = createDeferred<Candle[]>();
getData.mockReturnValueOnce(old.promise);
const loading = manager.show('OLD');
getData.mockResolvedValueOnce([createCandle('2025-01-01')]).mockResolvedValueOnce(null);
await manager.show('NEW');
old.resolve([createCandle('2020-01-01')]);
await loading;
expect(state.symbolId).toBe('NEW');
expect(state.minYear).toBe(2025);
expect(state.tableRows.map((row) => row.year)).toEqual([2025]);
expect(mocks.charts).toHaveLength(1);
});
it('не должен повторно запрашивать загружаемый инструмент', async () => {
const request = createDeferred<Candle[]>();
getData.mockReturnValueOnce(request.promise);
const loading = manager.show('AAA');
await manager.show('AAA');
expect(getData).toHaveBeenCalledTimes(1);
request.resolve([]);
await loading;
});
it('должен использовать загруженную историю при изменении диапазона', async () => {
await loadSampleHistory();
const count = getData.mock.calls.length;
await manager.show('AAA', {
fromYear: 2025,
toYear: 2025,
});
flushAnimationFrames();
expect(getData).toHaveBeenCalledTimes(count);
expect(state.fromYear).toBe(2025);
expect(mocks.charts[0].removeSeries).toHaveBeenCalledTimes(2);
});
it('должен выбирать последние пять календарных лет по умолчанию', async () => {
getData.mockResolvedValueOnce([createCandle('2020-01-01'), createCandle('2025-01-01')]).mockResolvedValueOnce(null);
await manager.show('AAA');
expect(state.fromYear).toBe(2021);
expect(state.toYear).toBe(2025);
});
});
describe('SeasonalityManager: отображение и очистка', () => {
it('должен объединять изменения диапазона в один кадр и применять последнее значение', async () => {
await loadSampleHistory();
manager.setRange({
fromYear: 2020,
toYear: 2023,
});
manager.setRange({
fromYear: 2023,
toYear: 2023,
});
expect(frames.size).toBe(1);
flushAnimationFrames();
expect(state.status).toBe('ready');
expect(container.textContent).toContain('2023');
expect(container.textContent).not.toContain('2025');
expect(mocks.markers[0].detach).toHaveBeenCalledTimes(1);
});
it('не должен перерисовывать прежний диапазон и должен поддерживать диапазон без данных', async () => {
await loadSampleHistory();
manager.setRange({
fromYear: 2020,
toYear: 2025,
});
expect(frames.size).toBe(0);
manager.setRange({
fromYear: 2021,
toYear: 2022,
});
flushAnimationFrames();
expect(state.status).toBe('empty');
expect(container.textContent).toContain('No seasonality data');
});
it('должен переключать формат значений без пересоздания графика', async () => {
await loadSampleHistory();
manager.setScale(PriceScaleMode.Normal);
manager.setScale(PriceScaleMode.Percentage);
const series = mocks.charts[0].series[mocks.charts[0].series.length - 1];
const { priceFormat } = getLastCall(series.applyOptions)[0];
expect(priceFormat.formatter(12.5)).toBe('12.50%');
expect(priceFormat.minMove).toBe(0.01);
manager.setScale(PriceScaleMode.Normal);
expect(getLastCall(series.applyOptions)[0].priceFormat.minMove).toBe(0.001);
expect(mocks.charts).toHaveLength(1);
expect(mocks.charts[0].timeScale().setVisibleRange).toHaveBeenCalledWith({
from: '2000-01-01',
to: '2000-12-31',
});
expect(getLastCall(mocks.markers[0].setMarkers)[0][0].time).toBe('2000-01-02');
});
it.each([0, 6])('должен брать шаг цены из общей точности %s', async (precision) => {
await loadSampleHistory();
const series = mocks.charts[0].series[mocks.charts[0].series.length - 1];
const count = getData.mock.calls.length;
setPricePrecision(precision);
manager.setScale(PriceScaleMode.Percentage);
manager.setScale(PriceScaleMode.Normal);
expect(getLastCall(series.applyOptions)[0].priceFormat.minMove).toBe(10 ** -precision);
manager.setScale(PriceScaleMode.Percentage);
const { priceFormat } = getLastCall(series.applyOptions)[0];
expect(priceFormat.minMove).toBe(0.01);
expect(priceFormat.formatter(12.5)).toBe('12.50%');
expect(getData).toHaveBeenCalledTimes(count);
expect(mocks.charts).toHaveLength(1);
});
it('должен показывать предупреждение о базе только для процентной шкалы', async () => {
getData.mockResolvedValueOnce([createCandle('2025-01-01', 0)]).mockResolvedValueOnce(null);
await manager.show('AAA');
manager.setScale(PriceScaleMode.Percentage);
expect(container.textContent).toContain('Percentage requires a positive baseline');
expect(getLastCall(mocks.markers[0].setMarkers)[0]).toEqual([]);
manager.setScale(PriceScaleMode.Normal);
expect((container.lastElementChild as HTMLElement).style.display).toBe('none');
});
it('должен применять актуальные цвета темы при создании и обновлении графика', async () => {
await loadSampleHistory();
expect(mocks.charts[0].options.crosshair).toMatchObject({
vertLine: {
color: colors.chartCrosshairLine,
labelBackgroundColor: colors.chartCrosshairLabel,
},
horzLine: {
color: colors.chartCrosshairLine,
labelBackgroundColor: colors.chartCrosshairLabel,
},
});
jest.mocked(getThemeStore).mockReturnValue({
colors: {
...colors,
chartTextPrimary: '#999999',
chartCrosshairLine: '#aabbcc',
chartCrosshairLabel: '#ddeeff',
},
} as ReturnType<typeof getThemeStore>);
manager.updateTheme();
expect(getLastCall(mocks.charts[0].applyOptions)[0]).toMatchObject({
layout: {
textColor: '#999999',
},
crosshair: {
vertLine: {
color: '#aabbcc',
labelBackgroundColor: '#ddeeff',
},
horzLine: {
color: '#aabbcc',
labelBackgroundColor: '#ddeeff',
},
},
});
});
it('должен форматировать все варианты времени как день и месяц', async () => {
await loadSampleHistory();
const formatter = mocks.charts[0].options.localization?.timeFormatter;
if (typeof formatter !== 'function') {
throw new Error('Time formatter is not configured');
}
expect(
formatter({
year: 2000,
month: 2,
day: 9,
}),
).toBe('09.02');
expect(formatter('2000-02-09')).toBe('09.02');
expect(formatter(Date.UTC(2000, 1, 9) / 1000)).toBe('09.02');
});
it('должен обновлять легенду по перекрестию и обозначать отсутствующие значения', async () => {
await loadSampleHistory();
const chart = mocks.charts[0];
const listener = chart.subscribeCrosshairMove.mock.calls[0][0];
listener({
time: '2000-01-01',
seriesData: new Map([[chart.series[0], { value: 42 }]]),
});
expect(container.textContent).toContain('42.00');
expect(container.textContent).toContain('—');
listener({
time: undefined,
seriesData: new Map(),
});
expect(container.textContent).not.toContain('—');
});
it('должен копировать готовый график вместе с легендой', async () => {
const blob = new Blob(['image'], {
type: 'image/png',
});
const write = jest.fn().mockResolvedValue(undefined);
jest.mocked(canvasToBlob).mockResolvedValueOnce(blob);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { write },
});
Object.defineProperty(globalThis, 'ClipboardItem', {
configurable: true,
value: class {
constructor(public data: Record<string, Blob>) {}
},
});
await manager.copyImage();
expect(write).not.toHaveBeenCalled();
await loadSampleHistory();
await manager.copyImage();
expect(mocks.charts[0].takeScreenshot).toHaveBeenCalledWith(true, false);
expect(drawTextLayer).toHaveBeenCalledTimes(1);
expect(canvasToBlob).toHaveBeenCalledTimes(1);
expect(write).toHaveBeenCalledTimes(1);
const items = write.mock.calls[0][0];
expect(items[0].data['image/png']).toBe(blob);
});
it('должен отменять кадры и освобождать ресурсы при очистке сезонности', async () => {
await loadSampleHistory();
manager.setRange({
fromYear: 2023,
toYear: 2025,
});
const chart = mocks.charts[0];
manager.clear();
manager.clear();
expect(frames.size).toBe(0);
expect(state.status).toBe('idle');
flushAnimationFrames();
expect(mocks.charts).toHaveLength(1);
expect(chart.remove).toHaveBeenCalledTimes(1);
expect(chart.unsubscribeCrosshairMove).toHaveBeenCalledWith(chart.subscribeCrosshairMove.mock.calls[0][0]);
expect(mocks.markers[0].detach).toHaveBeenCalledTimes(1);
});
it('должен завершать состояние и игнорировать ответ после уничтожения', async () => {
const complete = jest.fn();
manager.getState().subscribe({ complete });
const request = createDeferred<Candle[]>();
getData.mockReturnValueOnce(request.promise);
const loading = manager.show('AAA');
manager.destroy();
manager.destroy();
manager.clear();
request.resolve([createCandle('2025-01-01')]);
await loading;
await manager.show('BBB');
manager.setRange({
fromYear: 2020,
toYear: 2025,
});
manager.setScale(PriceScaleMode.Normal);
manager.setScale(PriceScaleMode.Percentage);
manager.setDisplayMode(SeasonalityViewType.Table);
expect(complete).toHaveBeenCalledTimes(1);
expect(state.displayMode).toBe(SeasonalityViewType.Chart);
expect(state.scale).toBe(PriceScaleMode.Normal);
expect(state.tableRows).toEqual([]);
expect(container.children).toHaveLength(0);
expect(mocks.charts).toHaveLength(0);
expect(getData).toHaveBeenCalledTimes(1);
});
it('не должен изменять диапазон без загруженной истории', () => {
const initial = state;
manager.setRange({
fromYear: 2020,
toYear: 2025,
});
manager.setScale(PriceScaleMode.Normal);
expect(state).toBe(initial);
expect(frames.size).toBe(0);
});
it('должен применять шкалу, выбранную во время загрузки', async () => {
const request = createDeferred<Candle[]>();
getData.mockReturnValueOnce(request.promise).mockResolvedValueOnce(null);
const loading = manager.show('AAA');
manager.setScale(PriceScaleMode.Percentage);
request.resolve([createCandle('2025-01-01'), createCandle('2025-01-02', 125)]);
await loading;
const data = getLastCall(mocks.charts[0].series[0].setData)[0];
expect(state.scale).toBe(PriceScaleMode.Percentage);
expect(data.filter((point: LineData | WhitespaceData) => 'value' in point)).toEqual([
{ time: '2000-01-01', value: 0 },
{ time: '2000-01-02', value: 25 },
]);
});
it('должен восстанавливать отображение после выбора пустого диапазона', async () => {
await loadSampleHistory();
const count = getData.mock.calls.length;
manager.setRange({
fromYear: 2021,
toYear: 2022,
});
flushAnimationFrames();
expect(state.status).toBe('empty');
manager.setRange({
fromYear: 2023,
toYear: 2025,
});
flushAnimationFrames();
expect(state.status).toBe('ready');
expect(getData).toHaveBeenCalledTimes(count);
expect(mocks.charts).toHaveLength(1);
expect((container.lastElementChild as HTMLElement).style.display).toBe('none');
});
it('должен сбрасывать статус и повторно загружать инструмент после очистки', async () => {
await loadSampleHistory();
manager.setScale(PriceScaleMode.Percentage);
manager.setDisplayMode(SeasonalityViewType.Table);
manager.clear();
expect(state.status).toBe('idle');
expect(state.error).toBeNull();
expect(state.scale).toBe(PriceScaleMode.Percentage);
expect(state.displayMode).toBe(SeasonalityViewType.Table);
expect(state.tableRows).toEqual([]);
const count = getData.mock.calls.length;
await loadSampleHistory();
expect(getData).toHaveBeenCalledTimes(count + 2);
expect(state.status).toBe('ready');
expect(state.tableRows.map((row) => row.year)).toEqual([2025, 2023, 2020]);
expect(mocks.charts).toHaveLength(2);
});
});
describe('SeasonalityManager: табличный режим', () => {
it('должен сохранять строки и состояние при повторном открытии загруженного инструмента', async () => {
await loadSampleHistory();
manager.setDisplayMode(SeasonalityViewType.Table);
const previous = state;
const count = getData.mock.calls.length;
await manager.show('AAA');
expect(state).toBe(previous);
expect(state.tableRows).toBe(previous.tableRows);
expect(getData).toHaveBeenCalledTimes(count);
expect(mocks.charts).toHaveLength(1);
});
it('не должен повторно отправлять состояние при выборе текущего вида', () => {
const next = jest.fn();
const subscription = manager.getState().subscribe(next);
next.mockClear();
manager.setDisplayMode(SeasonalityViewType.Chart);
expect(next).not.toHaveBeenCalled();
manager.setDisplayMode(SeasonalityViewType.Table);
const previous = state;
manager.setDisplayMode(SeasonalityViewType.Table);
expect(next).toHaveBeenCalledTimes(1);
expect(state).toBe(previous);
expect(state.displayMode).toBe(SeasonalityViewType.Table);
subscription.unsubscribe();
});
it('должен показывать изменение первого неполного месяца и годовой итог', async () => {
getData
.mockResolvedValueOnce([
createCandle('2021-10-15', 100),
createCandle('2021-10-29', 101),
createCandle('2021-11-30', 105),
createCandle('2021-12-30', 106),
])
.mockResolvedValueOnce(null);
await manager.show('AAA');
const [row] = state.tableRows;
expect(row.months.slice(0, 9)).toEqual(Array(9).fill(null));
expect(row.months[9]?.absolute).toBe(1);
expect(row.months[9]?.percentage).toBeCloseTo(1, 10);
expect(row.total?.absolute).toBe(6);
expect(row.total?.percentage).toBeCloseTo(6, 10);
});
it('должен использовать декабрь с предыдущей страницы за пределами выбранного диапазона', async () => {
getData
.mockResolvedValueOnce([
createCandle('2024-01-02', 105),
createCandle('2024-01-31', 110),
createCandle('2024-02-29', 121),
])
.mockResolvedValueOnce([createCandle('2023-12-29', 100)])
.mockResolvedValueOnce(null);
await manager.show('AAA', {
fromYear: 2024,
toYear: 2024,
});
expect(state.tableRows).toHaveLength(1);
const [row] = state.tableRows;
expect(row.year).toBe(2024);
expect(row.months[0]?.absolute).toBe(10);
expect(row.months[0]?.percentage).toBeCloseTo(10, 10);
expect(row.total?.absolute).toBe(21);
expect(row.total?.percentage).toBeCloseTo(21, 10);
expect(getData).toHaveBeenCalledTimes(3);
});
it('должен рассчитывать месячные и годовые изменения по загруженной истории', async () => {
getData
.mockResolvedValueOnce([
createCandle('2023-12-29', 100),
createCandle('2024-01-02', 104),
createCandle('2024-01-31', 110),
createCandle('2024-02-29', 121),
createCandle('2024-12-31', 120),
createCandle('2025-01-31', 132),
])
.mockResolvedValueOnce(null);
await manager.show('AAA', {
fromYear: 2024,
toYear: 2025,
});
expect(state.tableRows.map((row) => row.year)).toEqual([2025, 2024]);
const row = state.tableRows[1];
expect(row.months).toHaveLength(12);
expect(row.months[0]?.absolute).toBe(10);
expect(row.months[0]?.percentage).toBeCloseTo(10);
expect(row.months[1]?.absolute).toBe(11);
expect(row.months[1]?.percentage).toBeCloseTo(10);
expect(row.total?.absolute).toBe(20);
expect(row.total?.percentage).toBeCloseTo(20);
const count = getData.mock.calls.length;
manager.setDisplayMode(SeasonalityViewType.Table);
manager.setRange({
fromYear: 2025,
toYear: 2025,
});
flushAnimationFrames();
expect(state.tableRows).toHaveLength(1);
expect(state.tableRows[0].year).toBe(2025);
expect(state.tableRows[0].months[0]?.absolute).toBe(12);
expect(state.tableRows[0].months[0]?.percentage).toBeCloseTo(10);
expect(state.tableRows[0].total?.absolute).toBe(12);
expect(state.tableRows[0].total?.percentage).toBeCloseTo(10);
expect(getData).toHaveBeenCalledTimes(count);
});
it('должен отличать отсутствующую базу, пропущенный месяц и нулевое изменение', async () => {
getData
.mockResolvedValueOnce([
createCandle('2024-01-31', 0),
createCandle('2024-02-29', 10),
createCandle('2024-04-30', 15),
createCandle('2024-05-31', 15),
])
.mockResolvedValueOnce(null);
await manager.show('AAA');
const row = state.tableRows[0];
expect(row.months[0]).toEqual({
absolute: 0,
percentage: null,
});
expect(row.months[1]).toEqual({
absolute: 10,
percentage: null,
});
expect(row.months[2]).toBeNull();
expect(row.months[3]).toBeNull();
expect(row.months[4]).toEqual({
absolute: 0,
percentage: 0,
});
expect(row.months.slice(5)).toEqual(Array(7).fill(null));
expect(row.total).toEqual({
absolute: 15,
percentage: null,
});
});
it('должен переключать вид без повторной загрузки и пересоздания графика', async () => {
await loadSampleHistory();
const count = getData.mock.calls.length;
const chart = mocks.charts[0];
const rows = state.tableRows;
manager.setDisplayMode(SeasonalityViewType.Table);
expect(state.displayMode).toBe(SeasonalityViewType.Table);
expect(state.status).toBe('ready');
expect(state.tableRows).toBe(rows);
manager.setScale(PriceScaleMode.Percentage);
manager.setDisplayMode(SeasonalityViewType.Chart);
expect(state.displayMode).toBe(SeasonalityViewType.Chart);
expect(state.scale).toBe(PriceScaleMode.Percentage);
expect(state.fromYear).toBe(2020);
expect(state.toYear).toBe(2025);
expect(state.tableRows).toBe(rows);
expect(getData).toHaveBeenCalledTimes(count);
expect(mocks.charts).toHaveLength(1);
expect(chart.remove).not.toHaveBeenCalled();
});
it('должен сохранять вид и шкалу, выбранные во время загрузки', async () => {
const request = createDeferred<Candle[]>();
getData.mockReturnValueOnce(request.promise).mockResolvedValueOnce(null);
const loading = manager.show('AAA');
manager.setDisplayMode(SeasonalityViewType.Table);
manager.setScale(PriceScaleMode.Percentage);
expect(state.status).toBe('loading');
expect(state.tableRows).toEqual([]);
request.resolve([createCandle('2024-12-31', 100), createCandle('2025-01-31', 125)]);
await loading;
expect(state.status).toBe('ready');
expect(state.displayMode).toBe(SeasonalityViewType.Table);
expect(state.scale).toBe(PriceScaleMode.Percentage);
expect(state.tableRows[0].months[0]).toEqual({
absolute: 25,
percentage: 25,
});
expect(state.tableRows[0].total).toEqual({
absolute: 25,
percentage: 25,
});
});
it('не должен копировать снимок графика в табличном режиме', async () => {
await loadSampleHistory();
manager.setDisplayMode(SeasonalityViewType.Table);
await manager.copyImage();
expect(mocks.charts[0].takeScreenshot).not.toHaveBeenCalled();
expect(drawTextLayer).not.toHaveBeenCalled();
expect(canvasToBlob).not.toHaveBeenCalled();
});
it('должен очищать строки при загрузке нового инструмента и ошибке запроса', async () => {
await loadSampleHistory();
manager.setDisplayMode(SeasonalityViewType.Table);
const request = createDeferred<Candle[]>();
getData.mockReturnValueOnce(request.promise);
const loading = manager.show('NEW');
expect(state.symbolId).toBe('NEW');
expect(state.status).toBe('loading');
expect(state.tableRows).toEqual([]);
request.reject(new Error('network'));
await loading;
expect(state.status).toBe('error');
expect(state.displayMode).toBe(SeasonalityViewType.Table);
expect(state.tableRows).toEqual([]);
});
it('должен восстанавливать строки после выбора пустого диапазона', async () => {
await loadSampleHistory();
const count = getData.mock.calls.length;
manager.setDisplayMode(SeasonalityViewType.Table);
manager.setRange({
fromYear: 2021,
toYear: 2022,
});
flushAnimationFrames();
expect(state.status).toBe('empty');
expect(state.tableRows).toEqual([]);
manager.setRange({
fromYear: 2023,
toYear: 2025,
});
flushAnimationFrames();
expect(state.status).toBe('ready');
expect(state.displayMode).toBe(SeasonalityViewType.Table);
expect(state.tableRows.map((row) => row.year)).toEqual([2025, 2023]);
expect(getData).toHaveBeenCalledTimes(count);
});
});
describe('SeasonalityManager: среднее', () => {
it('должен добавлять среднюю серию по запросу и удалять её без загрузки истории', async () => {
await loadSampleHistory();
const chart = mocks.charts[0];
expect(chart.series).toHaveLength(3);
expect(state.showAverage).toBe(false);
manager.setAverageVisible(true);
const average = chart.series[3];
expect(state.showAverage).toBe(true);
expect(average.options).toEqual(expect.objectContaining({
title: 'Avg',
color: colors.chartTextPrimary,
lineStyle: LineStyle.Dashed,
lineWidth: 2,
priceLineVisible: false,
}));
expect(getLastCall(average.setData)[0][0]).toEqual({ time: '2000-01-01', value: 100 });
expect(getLastCall(average.setData)[0][1]).toEqual({ time: '2000-01-02', value: 125 });
expect(container.textContent).toContain('Avg');
manager.setAverageVisible(true);
expect(chart.series).toHaveLength(4);
expect(average.setData).toHaveBeenCalledTimes(1);
manager.setAverageVisible(false);
expect(state.showAverage).toBe(false);
expect(chart.removeSeries).toHaveBeenCalledWith(average);
expect(container.textContent).not.toContain('Avg');
expect(getData).toHaveBeenCalledTimes(2);
expect(createChart).toHaveBeenCalledTimes(1);
});
it('должен пересчитывать среднее при изменении шкалы и диапазона', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const average = chart.series[3];
manager.setScale(PriceScaleMode.Percentage);
expect(getLastCall(average.setData)[0][0]).toEqual({ time: '2000-01-01', value: 0 });
expect(getLastCall(average.setData)[0][1]).toEqual({ time: '2000-01-02', value: 25 });
expect(getLastCall(average.applyOptions)[0].priceFormat.minMove).toBe(0.01);
expect(getLastCall(average.applyOptions)[0].priceFormat.formatter(25)).toBe('25.00%');
manager.setRange({ fromYear: 2020, toYear: 2023 });
flushAnimationFrames();
expect(getLastCall(average.setData)[0][1]).toEqual({ time: '2000-01-02' });
manager.setScale(PriceScaleMode.Normal);
expect(getLastCall(average.setData)[0][0]).toEqual({ time: '2000-01-01', value: 100 });
expect(getLastCall(average.applyOptions)[0].priceFormat.minMove).toBe(0.001);
expect(chart.series.filter((series) => series.options.title === 'Avg')).toHaveLength(1);
expect(getData).toHaveBeenCalledTimes(2);
});
it('должен обновлять среднее в легенде по курсору и показывать пропуски', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const average = chart.series[3];
const onCrosshairMove = getLastCall(chart.subscribeCrosshairMove)[0];
const label = [...container.querySelectorAll('span')].find((element) => element.textContent === 'Avg')!;
const value = label.nextElementSibling!;
expect(value.textContent).toBe('125.00');
onCrosshairMove({
time: '2000-01-01',
seriesData: new Map([[average, { value: 0 }]]),
});
expect(value.textContent).toBe('0.00');
onCrosshairMove({ time: '2000-01-02', seriesData: new Map() });
expect(value.textContent).toBe('—');
onCrosshairMove({});
expect(value.textContent).toBe('125.00');
});
it('должен сохранять среднее между видами и при повторной загрузке после очистки', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
manager.setDisplayMode(SeasonalityViewType.Table);
manager.setDisplayMode(SeasonalityViewType.Chart);
expect(state.showAverage).toBe(true);
expect(chart.series).toHaveLength(4);
expect(getData).toHaveBeenCalledTimes(2);
manager.clear();
expect(state.showAverage).toBe(true);
expect(chart.remove).toHaveBeenCalledTimes(1);
expect(container.textContent).not.toContain('Avg');
await loadSampleHistory();
expect(mocks.charts[1].series.some((series) => series.options.title === 'Avg')).toBe(true);
expect(container.textContent).toContain('Avg');
});
it('должен удалять среднее для пустого диапазона и восстанавливать при выборе данных', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const average = chart.series[3];
manager.setRange({ fromYear: 2021, toYear: 2022 });
flushAnimationFrames();
expect(state.status).toBe('empty');
expect(state.showAverage).toBe(true);
expect(chart.removeSeries).toHaveBeenCalledWith(average);
expect(container.textContent).not.toContain('Avg');
manager.setRange({ fromYear: 2025, toYear: 2025 });
flushAnimationFrames();
expect(state.status).toBe('ready');
expect(chart.series[chart.series.length - 1].options.title).toBe('Avg');
expect(container.textContent).toContain('Avg');
expect(getData).toHaveBeenCalledTimes(2);
});
it('должен применять выбранное среднее после загрузки истории', async () => {
manager.setAverageVisible(true);
expect(createChart).not.toHaveBeenCalled();
await loadSampleHistory();
expect(state.showAverage).toBe(true);
expect(mocks.charts[0].series[3].options.title).toBe('Avg');
});
it('должен обновлять цвет средней линии и её значения из темы', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const average = mocks.charts[0].series[3];
jest.mocked(getThemeStore).mockReturnValue({
colors: { ...colors, chartTextPrimary: '#abcdef' },
} as ReturnType<typeof getThemeStore>);
manager.updateTheme();
expect(average.applyOptions).toHaveBeenLastCalledWith({ color: '#abcdef' });
const label = [...container.querySelectorAll('span')].find((element) => element.textContent === 'Avg')!;
expect((label.nextElementSibling as HTMLElement).style.color).toBe('rgb(171, 205, 239)');
});
it('не должен создавать среднюю серию после уничтожения менеджера', async () => {
await loadSampleHistory();
const chart = mocks.charts[0];
manager.destroy();
manager.setAverageVisible(true);
expect(chart.series).toHaveLength(3);
expect(chart.remove).toHaveBeenCalledTimes(1);
});
});
describe('SeasonalityManager: значения легенды', () => {
it.each([
{ point: { time: '2000-01-01' } },
{ point: { value: '42' } },
{ point: { value: null } },
{ point: { open: 10, high: 20, low: 5, close: 15 } },
])('должен показывать пропуск для неподходящей точки %j', async ({ point }) => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const onCrosshairMove = getLastCall(chart.subscribeCrosshairMove)[0];
onCrosshairMove({
time: '2000-01-01',
seriesData: new Map<SeriesTestContext, unknown>([
[chart.series[0], point],
[chart.series[3], point],
]),
});
expect(getLegendValue('2020')).toBe('—');
expect(getLegendValue('Avg')).toBe('—');
});
it('должен форматировать нулевое и отрицательное значения форматтером соответствующей серии', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const year = chart.series[0];
const average = chart.series[3];
const onCrosshairMove = getLastCall(chart.subscribeCrosshairMove)[0];
jest.spyOn(year, 'priceFormatter').mockReturnValue({
format: (value: number) => `year:${value}`,
});
jest.spyOn(average, 'priceFormatter').mockReturnValue({
format: (value: number) => `average:${value}`,
});
onCrosshairMove({
time: '2000-01-01',
seriesData: new Map([
[year, { value: 0 }],
[average, { value: -12.5 }],
]),
});
expect(getLegendValue('2020')).toBe('year:0');
expect(getLegendValue('Avg')).toBe('average:-12.5');
});
it.each([
[PriceScaleMode.Normal, '100.00', '125.00'],
[PriceScaleMode.Percentage, '0.00', '25.00'],
] as const)(
'должен восстанавливать последние значения без времени курсора для шкалы %s',
async (scale, yearValue, averageValue) => {
await loadSampleHistory();
manager.setScale(scale);
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const onCrosshairMove = getLastCall(chart.subscribeCrosshairMove)[0];
const seriesData = new Map([
[chart.series[0], { value: 999 }],
[chart.series[3], { value: 999 }],
]);
onCrosshairMove({ time: '2000-01-01', seriesData });
expect(getLegendValue('2020')).toBe('999.00');
expect(getLegendValue('Avg')).toBe('999.00');
onCrosshairMove({ time: undefined, seriesData });
expect(getLegendValue('2020')).toBe(yearValue);
expect(getLegendValue('Avg')).toBe(averageValue);
},
);
it('должен показывать пропуск для среднего без доступных процентных значений', async () => {
getData
.mockResolvedValueOnce([createCandle('2025-01-01', 0), createCandle('2025-01-02', 10)])
.mockResolvedValueOnce(null);
await manager.show('AAA');
manager.setScale(PriceScaleMode.Percentage);
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const onCrosshairMove = getLastCall(chart.subscribeCrosshairMove)[0];
expect(getLegendValue('2025')).toBe('—');
expect(getLegendValue('Avg')).toBe('—');
onCrosshairMove({ time: '2000-01-02', seriesData: new Map() });
onCrosshairMove({});
expect(getLegendValue('Avg')).toBe('—');
});
it('должен обновлять годовую легенду после отключения среднего', async () => {
await loadSampleHistory();
manager.setAverageVisible(true);
const chart = mocks.charts[0];
const onCrosshairMove = getLastCall(chart.subscribeCrosshairMove)[0];
manager.setAverageVisible(false);
onCrosshairMove({
time: '2000-01-01',
seriesData: new Map([[chart.series[0], { value: 0 }]]),
});
expect(getLegendValue('2020')).toBe('0.00');
expect(getLegendValue('Avg')).toBeNull();
});
});