Загрузка данных
import { IChartApi, ISeriesApi, SeriesType } from 'lightweight-charts';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { DOMObject, DOMObjectParams } from '@core/DOMObject';
import { Hotkeys, Keys } from '@core/Hotkeys';
import { DrawingsNames } from '@src/constants';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { SettingsTab, SettingsValues, ToolbarSettingField } from '@src/types/settings';
import type { DrawingInteraction, ISeriesDrawing } from '@src/core/Drawings/SeriesDrawingBase';
interface DrawingParams extends DOMObjectParams {
drawingName: DrawingsNames;
lwcChart: IChartApi;
mainSeries: SeriesStrategies;
onDelete: (id: string) => void;
onCopy: () => void;
construct: (chart: IChartApi, series: ISeriesApi<SeriesType>, interaction: DrawingInteraction) => ISeriesDrawing;
selected$: Observable<boolean>;
isSelected: () => boolean;
select: () => void;
deselect: () => void;
isLocked?: boolean;
hotkeys: Hotkeys;
}
export class Drawing extends DOMObject {
private lwcDrawing: ISeriesDrawing;
private mainSeries: SeriesStrategies;
private drawingName: DrawingsNames;
private hotkeys: Hotkeys;
private lockedSubject: BehaviorSubject<boolean>;
private settingsSubject: BehaviorSubject<SettingsValues>;
private subscriptions = new Subscription();
private unregisterDeleteHotkey = () => {};
private unregisterCopyHotkey = () => {};
constructor({
lwcChart,
name,
mainSeries,
drawingName,
id,
onDelete,
onCopy,
zIndex,
moveUp,
moveDown,
construct,
selected$,
isSelected,
select,
deselect,
isLocked = false,
paneId,
hotkeys,
}: DrawingParams) {
super({
id,
name,
zIndex,
onDelete,
moveUp,
moveDown,
paneId,
});
this.hotkeys = hotkeys;
this.mainSeries = mainSeries;
this.drawingName = drawingName;
this.lockedSubject = new BehaviorSubject(isLocked);
const interaction: DrawingInteraction = {
selected$,
locked$: this.lockedSubject.asObservable(),
isSelected,
isLocked: () => this.lockedSubject.value,
select,
deselect,
};
this.lwcDrawing = construct(lwcChart, mainSeries, interaction);
this.settingsSubject = new BehaviorSubject(this.lwcDrawing.getSettings());
this.subscriptions.add(
this.lwcDrawing.subscribeSettings((settings) => {
this.settingsSubject.next(settings);
}),
);
this.subscriptions.add(
selected$.subscribe((isSelectedDrawing) => {
if (!isSelectedDrawing) {
this.unregisterSelectedDrawingHotkeys();
return;
}
this.unregisterDeleteHotkey = this.hotkeys.register({
keys: [Keys.delete],
callback: () => {
this.delete();
},
});
this.unregisterCopyHotkey = this.hotkeys.register({
keys: [Keys.mod, Keys.c],
callback: () => {
if (!this.isCreationPending()) {
onCopy();
}
},
});
}),
);
}
public getDrawingName(): DrawingsNames {
return this.drawingName;
}
public getSeriesDrawing(): ISeriesDrawing {
return this.lwcDrawing;
}
public show(): void {
this.lwcDrawing.show();
super.show();
}
public hide(): void {
this.lwcDrawing.hide();
super.hide();
}
public rebind = (nextMainSeries: SeriesStrategies): void => {
this.lwcDrawing.rebind(nextMainSeries);
this.mainSeries = nextMainSeries;
};
public isCreationPending(): boolean {
return this.lwcDrawing.isCreationPending();
}
public subscribeIsLocked(callback: (isLocked: boolean) => void): Subscription {
return this.lockedSubject.subscribe(callback);
}
public subscribeSettings(callback: (settings: SettingsValues) => void): Subscription {
return this.settingsSubject.subscribe(callback);
}
public isLocked(): boolean {
return this.lockedSubject.value;
}
public setLocked(isLocked: boolean): void {
if (this.lockedSubject.value === isLocked) {
return;
}
this.lockedSubject.next(isLocked);
}
public toggleLock(): void {
this.setLocked(!this.isLocked());
}
public waitForCreation(): Promise<void> {
return this.lwcDrawing.waitTillReady();
}
public shouldShowInObjectTree(): boolean {
return this.lwcDrawing.shouldShowInObjectTree();
}
public getState(): unknown {
return this.lwcDrawing.getState();
}
public setState(state: unknown): void {
this.lwcDrawing.setState(state);
this.settingsSubject.next(this.lwcDrawing.getSettings());
}
public getSettings(): SettingsValues {
return this.lwcDrawing.getSettings();
}
public updateSettings(settings: SettingsValues): void {
this.lwcDrawing.updateSettings(settings);
}
public getSettingsTabs(): SettingsTab[] {
return this.lwcDrawing.getSettingsTabs();
}
public getToolbarSettings(): ToolbarSettingField[] {
return this.getSettingsTabs()
.flatMap((tab) => tab.fields)
.filter((field): field is ToolbarSettingField => field.toolbar !== undefined);
}
public hasSettings(): boolean {
return this.getSettingsTabs().some((tab) => tab.fields.length > 0);
}
public destroy(): void {
this.subscriptions.unsubscribe();
this.unregisterSelectedDrawingHotkeys();
this.lockedSubject.complete();
this.settingsSubject.complete();
this.mainSeries.detachPrimitive(this.lwcDrawing);
this.lwcDrawing.destroy();
}
private unregisterSelectedDrawingHotkeys(): void {
this.unregisterDeleteHotkey();
this.unregisterCopyHotkey();
this.unregisterDeleteHotkey = () => {};
this.unregisterCopyHotkey = () => {};
}
}
import { IChartApi, ISeriesApi, MouseEventParams, SeriesType } from 'lightweight-charts';
import { cloneDeep, isEqual } from 'lodash-es';
import { BehaviorSubject, distinctUntilChanged, map, Observable, Subscription } from 'rxjs';
import { EventManager } from '@core';
import { DOMModel } from '@core/DOMModel';
import { Drawing } from '@core/Drawings';
import { Hotkeys } from '@core/Hotkeys';
import { EntitySettingsModal } from '@src/components/EntitySettingsModal';
import { drawingLabelById, drawingsMap, DrawingsNames } from '@src/constants';
import { ModalRenderer } from '@src/core/ModalRenderer';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { ActiveDrawingTool, DOMObjectSnapshot } from '@src/types';
import { Pane } from './Pane';
import type { DrawingInteraction } from '@src/core/Drawings/SeriesDrawingBase';
import type { SettingsValues } from '@src/types/settings';
interface DrawingsManagerParams {
eventManager: EventManager;
mainSeries$: Observable<SeriesStrategies | null>;
lwcChart: IChartApi;
DOM: DOMModel;
container: HTMLElement;
modalRenderer: ModalRenderer;
paneId: number;
hotkeys: Hotkeys;
pane: Pane;
setActiveTool: (name: ActiveDrawingTool) => void;
getActiveTool: () => ActiveDrawingTool;
getIsEndlessMode: () => boolean;
continueDrawing: (name: DrawingsNames) => void;
}
export interface DrawingSnapshotItem extends Partial<DOMObjectSnapshot> {
id: string;
drawingName: DrawingsNames;
state: unknown;
isLocked?: boolean;
zIndex?: number;
}
interface CreateDrawingOptions {
id?: string;
state?: unknown;
isLocked?: boolean;
zIndex?: number;
shouldUpdateDrawingsList?: boolean;
}
export type DrawingsManagerSnapshot = DrawingSnapshotItem[];
export class DrawingsManager {
private eventManager: EventManager;
private lwcChart: IChartApi;
private DOM: DOMModel;
private container: HTMLElement;
private modalRenderer: ModalRenderer;
private paneId: number;
private hotkeys: Hotkeys;
private mainSeries: SeriesStrategies | null = null;
private subscriptions = new Subscription();
private drawings$ = new BehaviorSubject<Drawing[]>([]);
private selectedDrawing$ = new BehaviorSubject<Drawing | null>(null); // todo: переместить в DrawingsManagerCollection
private pendingSnapshot: DrawingsManagerSnapshot | null = null;
private selectedDrawingSnapshot: DrawingSnapshotItem | null = null;
private pane: Pane;
private copyPasteBuffer: DrawingSnapshotItem | null = null;
private setActiveTool: (name: ActiveDrawingTool) => void;
private getActiveTool: () => ActiveDrawingTool;
private getIsEndlessMode: () => boolean;
private continueDrawing: (name: DrawingsNames) => void;
constructor({
eventManager,
mainSeries$,
lwcChart,
DOM,
container,
modalRenderer,
paneId,
hotkeys,
pane,
setActiveTool,
getActiveTool,
getIsEndlessMode,
continueDrawing,
}: DrawingsManagerParams) {
this.DOM = DOM;
this.eventManager = eventManager;
this.paneId = paneId;
this.pane = pane;
this.lwcChart = lwcChart;
this.container = container;
this.modalRenderer = modalRenderer;
this.hotkeys = hotkeys;
this.setActiveTool = setActiveTool;
this.getActiveTool = getActiveTool;
this.getIsEndlessMode = getIsEndlessMode;
this.continueDrawing = continueDrawing;
this.subscriptions.add(
mainSeries$.subscribe((series) => {
if (!series) {
return;
}
this.mainSeries = series;
this.drawings$.value.forEach((drawing) => drawing.rebind(series));
if (this.pendingSnapshot) {
const snapshot = this.pendingSnapshot;
this.pendingSnapshot = null;
doAfterPromise(() => this.setSnapshot(snapshot), this.pane.isReady());
}
}),
);
window.addEventListener('pointerup', this.handlePointerUp);
window.addEventListener('pointercancel', this.handlePointerUp);
this.container.addEventListener('click', this.handleClick);
this.container.addEventListener('pointerdown', this.handlePointerDown);
this.container.addEventListener('dblclick', this.handleDoubleClick);
this.container.addEventListener('contextmenu', this.handleContextMenu);
// todo: implement ctrl+v
// hotkeys.register({
// keys: [Keys.control, Keys.v],
// callback: () => {
// const bufferWithAppliedPosition = {
// ...this.copyPasteBuffer,
// state: {
// ...this.copyPasteBuffer?.state,
// startAnchor: {
// price: 73.36210252637723,
// time: 1783679170
// }
// }
// }
//
// this.setSnapshot([
// ...this.getSnapshot(),
// bufferWithAppliedPosition
// ])
// // hotkeys.unregister({ // todo: unregister all else ctrl+c's
// // keys: [Keys.control, Keys.c]
// // })
// }
// })
}
// TODO: handlePointerDown конфликтует с DrawingsManagerCollection.handlePaneClick
private handlePointerDown = (event: PointerEvent): void => {
if (!this.isEventInPane(event)) {
return;
}
this.selectedDrawingSnapshot = null;
if (event.button === 0) {
const drawings = this.drawings$.value;
const pendingDrawing = drawings.find((drawing) => drawing.isCreationPending());
if (!pendingDrawing && this.getActiveTool() !== 'crosshair') {
return;
}
const selectedDrawing = this.selectedDrawing$.value;
const drawing =
pendingDrawing ??
(selectedDrawing?.getSeriesDrawing().isHit(event) ? selectedDrawing : null) ??
this.findTopDrawing(event);
if (drawing && !drawing.isCreationPending()) {
this.selectedDrawingSnapshot = this.createDrawingSnapshot(drawing);
}
(drawing ?? selectedDrawing)?.getSeriesDrawing().pointerDown(event);
}
this.DOM.refreshEntities();
};
private handlePointerUp = (): void => {
const previousSnapshot = this.selectedDrawingSnapshot;
this.selectedDrawingSnapshot = null;
queueMicrotask(() => {
if (!previousSnapshot) {
return;
}
const drawing = this.findDrawing(previousSnapshot.id);
if (!drawing || drawing.isCreationPending()) {
return;
}
this.pushDrawingChange(previousSnapshot, this.createDrawingSnapshot(drawing));
});
this.DOM.refreshEntities();
};
private handleDoubleClick = (event: MouseEvent): void => {
if (!this.isEventInPane(event)) {
return;
}
const pendingDrawing = this.drawings$.value.find((drawing) => drawing.isCreationPending());
const drawing = pendingDrawing ?? this.findTopDrawing(event);
if (!drawing) {
return;
}
if (!drawing.isCreationPending() && drawing !== this.selectedDrawing$.value) {
this.selectedDrawing$.next(drawing);
}
drawing.getSeriesDrawing().doubleClick(event);
this.DOM.refreshEntities();
};
private handleContextMenu = (event: MouseEvent): void => {
if (!this.isEventInPane(event)) {
return;
}
const pendingDrawing = this.drawings$.value.find((drawing) => drawing.isCreationPending());
const drawing = pendingDrawing ?? this.findTopDrawing(event);
drawing?.getSeriesDrawing().contextMenu(event);
};
private handleClick = (event: MouseEvent): void => {
if (!this.isEventInPane(event)) {
return;
}
const pendingDrawing = this.drawings$.value.find((drawing) => drawing.isCreationPending());
pendingDrawing?.getSeriesDrawing().click(event);
this.DOM.refreshEntities();
};
private isEventInPane(event: MouseEvent): boolean {
const paneElement = this.pane.getHTMLElement();
return paneElement !== null && event.target instanceof Node && paneElement.contains(event.target);
}
private findTopDrawing(event: MouseEvent): Drawing | null {
let topDrawing: Drawing | null = null;
for (const drawing of this.drawings$.value) {
if (!drawing.getSeriesDrawing().isHit(event)) {
continue;
}
if (!topDrawing || drawing.zIndex > topDrawing.zIndex) {
topDrawing = drawing;
}
}
return topDrawing;
}
private findDrawing(id: string): Drawing | undefined {
return this.drawings$.value.find((drawing) => drawing.id === id);
}
private createDrawingSnapshot(drawing: Drawing): DrawingSnapshotItem {
return {
...drawing.getSnapshot(),
drawingName: drawing.getDrawingName(),
state: cloneDeep(drawing.getState()),
isLocked: drawing.isLocked(),
};
}
private updateDrawing(drawing: Drawing, update: () => void): void {
if (drawing.isCreationPending()) {
return;
}
const previousSnapshot = this.createDrawingSnapshot(drawing);
update();
this.pushDrawingChange(previousSnapshot, this.createDrawingSnapshot(drawing));
}
private pushDrawingChange(
previousSnapshot: DrawingSnapshotItem | null,
nextSnapshot: DrawingSnapshotItem | null,
): void {
if (isEqual(previousSnapshot, nextSnapshot)) {
return;
}
const previous = cloneDeep(previousSnapshot);
const next = cloneDeep(nextSnapshot);
// todo: объединять последовательные изменения одного дровинга в одну запись истории
this.eventManager.getUndoRedo().pushCommand({
undo: () => {
this.replaceDrawingSnapshot(next, previous);
},
redo: () => {
this.replaceDrawingSnapshot(previous, next);
},
});
}
private replaceDrawingSnapshot(
currentSnapshot: DrawingSnapshotItem | null,
nextSnapshot: DrawingSnapshotItem | null,
): void {
if (currentSnapshot && nextSnapshot && currentSnapshot.id === nextSnapshot.id) {
const drawing = this.findDrawing(nextSnapshot.id);
if (drawing) {
drawing.setState(cloneDeep(nextSnapshot.state));
drawing.setLocked(nextSnapshot.isLocked ?? false);
this.DOM.refreshEntities();
return;
}
}
if (currentSnapshot) {
this.removeDrawingInternal(currentSnapshot.id, false);
}
if (nextSnapshot) {
this.restoreDrawing(nextSnapshot);
}
this.setActiveTool('crosshair');
}
private restoreDrawing(snapshot: DrawingSnapshotItem): Drawing {
const existingDrawing = this.findDrawing(snapshot.id);
if (existingDrawing) {
existingDrawing.setState(cloneDeep(snapshot.state));
existingDrawing.setLocked(snapshot.isLocked ?? false);
if (snapshot.zIndex !== undefined) {
existingDrawing.setZIndex(snapshot.zIndex);
}
this.drawings$.next([...this.drawings$.value].sort((left, right) => left.zIndex - right.zIndex));
this.DOM.refreshEntities();
return existingDrawing;
}
return this.createDrawing({
name: snapshot.drawingName,
options: {
id: snapshot.id,
state: cloneDeep(snapshot.state),
isLocked: snapshot.isLocked,
zIndex: snapshot.zIndex,
},
});
}
private updateActiveTool(): void {
const hasPendingDrawing = this.drawings$.value.some((drawing) => drawing.isCreationPending());
if (hasPendingDrawing) {
return;
}
const activeTool = this.getActiveTool();
if (activeTool !== 'crosshair' && this.getIsEndlessMode()) {
this.continueDrawing(activeTool);
return;
}
this.setActiveTool('crosshair');
}
private removeDrawing = (id: string): void => {
const drawing = this.findDrawing(id);
if (!drawing) {
return;
}
if (drawing.isCreationPending()) {
this.removeDrawingInternal(id);
return;
}
const snapshot = this.createDrawingSnapshot(drawing);
this.removeDrawingInternal(id);
this.pushDrawingChange(snapshot, null);
};
private removeDrawingInternal(id: string, shouldUpdateTool = true): void {
const drawing = this.findDrawing(id);
if (!drawing) {
return;
}
this.removeDrawings([drawing], shouldUpdateTool);
}
private removePendingDrawings(shouldUpdateTool = true): void {
const drawingsToRemove = this.drawings$.value.filter((drawing) => drawing.isCreationPending());
this.removeDrawings(drawingsToRemove, shouldUpdateTool);
}
private removeDrawings(drawingsToRemove: Drawing[], shouldUpdateTool = true): void {
if (!drawingsToRemove.length) {
return;
}
const selectedDrawing = this.selectedDrawing$.value;
if (selectedDrawing && drawingsToRemove.includes(selectedDrawing)) {
this.selectedDrawing$.next(null);
}
drawingsToRemove.forEach((drawing) => {
drawing.destroy();
this.DOM.removeEntity(drawing);
});
this.drawings$.next(this.drawings$.value.filter((drawing) => !drawingsToRemove.includes(drawing)));
if (shouldUpdateTool) {
this.updateActiveTool();
}
this.DOM.refreshEntities();
}
public startDrawing = async (name: DrawingsNames, event?: MouseEventParams): Promise<void> => {
this.removePendingDrawings(false);
const previousDrawing = drawingsMap[name].singleInstance
? this.drawings$.value.find((drawing) => drawing.getDrawingName() === name)
: undefined;
const previousSnapshot = previousDrawing ? this.createDrawingSnapshot(previousDrawing) : null;
if (previousDrawing) {
this.removeDrawingInternal(previousDrawing.id, false);
}
if (this.selectedDrawing$.value) {
this.selectedDrawing$.next(null);
}
this.setActiveTool(name);
const drawing = this.createDrawing({
name,
event,
});
this.DOM.refreshEntities();
await drawing.waitForCreation();
if (!this.findDrawing(drawing.id)) {
if (previousSnapshot) {
this.restoreDrawing(previousSnapshot);
}
return;
}
this.pushDrawingChange(previousSnapshot, this.createDrawingSnapshot(drawing));
if (this.getActiveTool() === name) {
this.selectedDrawing$.next(drawing);
this.updateActiveTool();
}
this.DOM.refreshEntities();
};
private createDrawing({
name,
options = {},
event,
}: {
name: DrawingsNames;
options?: CreateDrawingOptions;
event?: MouseEventParams;
}): Drawing {
const { mainSeries } = this;
if (!mainSeries) {
throw new Error('[Drawings] main series is not defined');
}
const { id, state, isLocked = false, zIndex, shouldUpdateDrawingsList = true } = options;
const config = drawingsMap[name];
const drawingId = id ?? crypto.randomUUID();
let createdDrawing: Drawing | null = null;
const selected$ = this.selectedDrawing$.pipe(
map((drawing) => drawing?.id === drawingId),
distinctUntilChanged(),
);
const construct = (chart: IChartApi, series: ISeriesApi<SeriesType>, interaction: DrawingInteraction) => {
const paneElement = this.pane.getHTMLElement();
if (!paneElement) {
throw new Error('[Drawing Manager]: cannot place drawing, there is no pane');
}
const cells = paneElement.querySelectorAll<HTMLTableCellElement>(':scope > td');
const canvasElement = cells.item(1);
return config.construct({
chart,
series,
eventManager: this.eventManager,
container: canvasElement,
interaction,
removeSelf: () => this.removeDrawing(drawingId),
openSettings: () => {
if (createdDrawing) {
this.openSettings(createdDrawing);
}
},
initialEvent: event,
});
};
const drawingFactory = (entityZIndex: number, moveUp: (id: string) => void, moveDown: (id: string) => void) =>
new Drawing({
lwcChart: this.lwcChart,
mainSeries,
id: drawingId,
drawingName: name,
name: drawingLabelById()[name],
onDelete: this.removeDrawing,
onCopy: () => {
if (createdDrawing) {
this.copyPasteBuffer = this.createDrawingSnapshot(createdDrawing);
}
},
zIndex: entityZIndex,
moveDown,
moveUp,
construct,
selected$,
isSelected: () => this.selectedDrawing$.value?.id === drawingId,
select: () => {
if (!createdDrawing || createdDrawing.isCreationPending() || this.selectedDrawing$.value === createdDrawing) {
return;
}
this.selectedDrawing$.next(createdDrawing);
},
deselect: () => {
if (!createdDrawing || this.selectedDrawing$.value !== createdDrawing) {
return;
}
this.selectedDrawing$.next(null);
},
isLocked,
paneId: this.paneId,
hotkeys: this.hotkeys,
});
const entity = this.DOM.setEntity<Drawing>(drawingFactory, zIndex);
createdDrawing = entity;
if (state !== undefined) {
entity.setState(cloneDeep(state));
}
if (shouldUpdateDrawingsList) {
this.drawings$.next([...this.drawings$.value, entity].sort((left, right) => left.zIndex - right.zIndex));
}
return entity;
}
public getSnapshot(): DrawingsManagerSnapshot {
return this.drawings$.value
.filter((drawing) => !drawing.isCreationPending())
.map((drawing) => this.createDrawingSnapshot(drawing));
}
public setSnapshot(snapshot: DrawingsManagerSnapshot): void {
if (!Array.isArray(snapshot)) {
return;
}
if (!this.mainSeries) {
this.pendingSnapshot = cloneDeep(snapshot);
return;
}
this.selectedDrawingSnapshot = null;
this.removeDrawings(this.drawings$.value, false);
const restoredDrawings = snapshot.reduce<Drawing[]>((drawings, item) => {
if (!drawingsMap[item.drawingName]) {
return drawings;
}
drawings.push(
this.createDrawing({
name: item.drawingName,
options: {
id: item.id,
state: cloneDeep(item.state),
isLocked: item.isLocked,
zIndex: item.zIndex,
shouldUpdateDrawingsList: false,
},
}),
);
return drawings;
}, []);
this.drawings$.next(restoredDrawings.sort((left, right) => left.zIndex - right.zIndex));
this.setActiveTool('crosshair');
this.DOM.refreshEntities();
}
public cancelPendingDrawing(): void {
this.removePendingDrawings(false);
this.DOM.refreshEntities();
}
public entities(): Observable<Drawing[]> {
return this.drawings$.asObservable();
}
public selectedDrawing(): Observable<Drawing | null> {
return this.selectedDrawing$.asObservable();
}
public updateSelectedDrawingSettings = (settings: SettingsValues): void => {
const drawing = this.selectedDrawing$.value;
if (!drawing) {
return;
}
this.updateDrawing(drawing, () => {
drawing.updateSettings(settings);
});
};
public openSelectedDrawingSettings(): void {
const drawing = this.selectedDrawing$.value;
if (!drawing) {
return;
}
this.openSettings(drawing);
}
public deleteSelectedDrawing(): void {
const drawing = this.selectedDrawing$.value;
if (!drawing) {
return;
}
this.removeDrawing(drawing.id);
}
public toggleSelectedDrawingLock(): void {
const drawing = this.selectedDrawing$.value;
if (!drawing) {
return;
}
this.updateDrawing(drawing, () => {
drawing.toggleLock();
});
}
private openSettings = (drawing: Drawing): void => {
const tabs = drawing.getSettingsTabs();
if (!tabs.length || tabs.every((tab) => tab.fields.length === 0)) {
return;
}
let settings = drawing.getSettings();
this.modalRenderer.renderComponent(
<EntitySettingsModal
tabs={tabs}
values={settings}
onChange={(nextSettings) => {
settings = nextSettings;
}}
initialTabKey={tabs[0]?.key}
/>,
{
size: 'sm',
title: drawing.name,
onSave: () => {
if (!this.findDrawing(drawing.id)) {
return;
}
this.updateDrawing(drawing, () => {
drawing.updateSettings(settings);
});
},
},
);
};
public getDrawings(): Drawing[] {
return this.drawings$.value;
}
public hideAll(): void {
if (this.selectedDrawing$.value) {
this.selectedDrawing$.next(null);
}
this.drawings$.value.forEach((drawing) => drawing.hide());
this.DOM.refreshEntities();
}
public destroy(): void {
window.removeEventListener('pointerup', this.handlePointerUp);
window.removeEventListener('pointercancel', this.handlePointerUp);
this.container.removeEventListener('click', this.handleClick);
this.container.removeEventListener('pointerdown', this.handlePointerDown);
this.container.removeEventListener('dblclick', this.handleDoubleClick);
this.container.removeEventListener('contextmenu', this.handleContextMenu);
this.drawings$.value.forEach((drawing) => drawing.destroy());
this.selectedDrawingSnapshot = null;
this.copyPasteBuffer = null;
this.subscriptions.unsubscribe();
this.drawings$.complete();
this.selectedDrawing$.complete();
}
}
async function doAfterPromise(cb: () => void, waiter: Promise<void>) {
await waiter;
cb();
}
import { BehaviorSubject, Observable } from 'rxjs';
import { DrawingsNames } from '@src/constants';
import { DRAWING_KEYBOARD_SHORTCUTS, findDrawingPointerShortcut } from '@src/core/Drawings/shortcuts';
import { ActiveDrawingTool, SettingsValues } from '@src/types';
import { Drawing } from './Drawings';
import { DrawingsManager } from './DrawingsManager';
import { Hotkeys, Keys } from './Hotkeys';
import type { Pane } from './Pane';
import type { MouseEventParams } from 'lightweight-charts';
// todo: нужно дописывать класс)
export class DrawingsManagerCollection {
private managersMap: Map<number, DrawingsManager> = new Map();
private hotkeys: Hotkeys;
private activeTool$ = new BehaviorSubject<ActiveDrawingTool>('crosshair');
private endlessMode$ = new BehaviorSubject(false);
private isAwaitingDrawingStart = false;
private unregisterHotkeys: (() => void)[] = [];
constructor({ hotkeys }: { hotkeys: Hotkeys }) {
this.hotkeys = hotkeys;
for (const { keys, drawingName } of DRAWING_KEYBOARD_SHORTCUTS) {
this.unregisterHotkeys.push(
this.hotkeys.register({
keys,
callback: () => {
this.activateDrawingTool(drawingName);
},
}),
);
}
this.unregisterHotkeys.push(
this.hotkeys.register({
keys: [Keys.escape],
callback: this.activateCrosshair,
}),
);
}
public getIsEndlessMode(): boolean {
return this.endlessMode$.value;
}
public getActiveToolValue(): ActiveDrawingTool {
return this.activeTool$.value;
}
public setActiveTool(next: ActiveDrawingTool): void {
this.activeTool$.next(next);
if (next === 'crosshair') {
this.isAwaitingDrawingStart = false;
}
}
public removeDrawingManager(paneId: number): void {
this.managersMap.delete(paneId);
}
public addDrawingManager(manager: DrawingsManager, paneId: number): void {
this.managersMap.set(paneId, manager);
}
public activateDrawingTool = (name: DrawingsNames): void => {
this.cancelPendingDrawings();
this.setActiveTool(name);
this.isAwaitingDrawingStart = true;
};
public handlePaneClick(pane: Pane, event: MouseEventParams): void {
const activeTool = this.activeTool$.value;
if (activeTool === 'crosshair') {
const pointerShortcut = findDrawingPointerShortcut(event);
if (pointerShortcut) {
pane.getDrawingManager().startDrawing(pointerShortcut.drawingName, event);
}
return;
}
if (!this.isAwaitingDrawingStart) {
return;
}
this.isAwaitingDrawingStart = false;
pane.getDrawingManager().startDrawing(activeTool, event);
}
public setEndlessDrawingMode = (value: boolean): void => {
if (this.endlessMode$.value === value) {
return;
}
this.endlessMode$.next(value);
};
public isEndlessDrawingsMode(): Observable<boolean> {
return this.endlessMode$.asObservable();
}
public activateCrosshair = (): void => {
this.cancelPendingDrawings();
this.setActiveTool('crosshair');
};
public getActiveTool(): Observable<ActiveDrawingTool> {
return this.activeTool$.asObservable();
}
public selectedDrawing(): Observable<Drawing | null> {
return Array.from(this.managersMap.values())[0].selectedDrawing();
}
public updateSelectedDrawingSettings = (settings: SettingsValues): void => {
for (const manager of this.managersMap.values()) {
manager.updateSelectedDrawingSettings(settings);
}
};
public toggleSelectedDrawingLock = (): void => {
Array.from(this.managersMap.values())[0].toggleSelectedDrawingLock();
};
public openSelectedDrawingSettings = (): void => {
Array.from(this.managersMap.values())[0].openSelectedDrawingSettings();
};
public deleteSelectedDrawing = (): void => {
Array.from(this.managersMap.values())[0].deleteSelectedDrawing();
};
public destroy(): void {
for (const unregisterHotkey of this.unregisterHotkeys) {
unregisterHotkey();
}
this.unregisterHotkeys = [];
this.activeTool$.complete();
this.endlessMode$.complete();
}
private cancelPendingDrawings(): void {
for (const manager of this.managersMap.values()) {
manager.cancelPendingDrawing();
}
}
}
import {
AutoscaleInfo,
CrosshairMode,
IChartApi,
IPrimitivePaneView,
ISeriesApi,
ISeriesPrimitive,
ISeriesPrimitiveAxisView,
Logical,
MouseEventParams,
PrimitiveHoveredItem,
SeriesAttachedParameter,
SeriesOptionsMap,
SeriesType,
Time,
TouchMouseEventData,
} from 'lightweight-charts';
import { Observable, Subject, Subscription } from 'rxjs';
import { DrawingHandlesPrimitive } from '@core/Drawings/handles';
import { getPointerPoint as getPointerPointFromEvent, getRawPointerPoint } from '@core/Drawings/helpers';
import { AxisLabel, AxisSegment, Point, SeriesApi } from '@core/Drawings/types';
import { ChartOptionsModel, SettingsTab, SettingsValues } from '@src/types';
import type { DrawingHandle } from '@core/Drawings/handles';
export interface DrawingInteraction {
selected$: Observable<boolean>;
locked$: Observable<boolean>;
isSelected(): boolean;
isLocked(): boolean;
select(): void;
deselect(): void;
}
export interface ISeriesDrawing extends ISeriesPrimitive<Time> {
show(): void;
hide(): void;
rebind(series: ISeriesApi<SeriesType>): void;
destroy(): void;
waitTillReady(): Promise<void>;
isCreationPending(): boolean;
shouldShowInObjectTree(): boolean;
getState(): unknown;
setState(state: unknown): void;
getSettings(): SettingsValues;
getSettingsTabs(): SettingsTab[];
updateSettings(settings: SettingsValues): void;
subscribeSettings(callback: (settings: SettingsValues) => void): Subscription;
isHit(event: MouseEvent): boolean;
pointerDown(event: PointerEvent): void;
click(event: MouseEvent): void;
doubleClick(event: MouseEvent): void;
contextMenu(event: MouseEvent): void;
getRenderData(): unknown;
}
export type StartPoint = unknown;
interface SeriesDrawingBaseParams {
container: HTMLElement;
chart: IChartApi;
series: SeriesApi;
interaction: DrawingInteraction;
}
export interface BaseDrawingParams {
chart: IChartApi;
series: SeriesApi;
container: HTMLElement;
interaction: DrawingInteraction;
formatObservable?: Observable<ChartOptionsModel>;
removeSelf?: () => void;
openSettings?: () => void;
initialEvent?: MouseEventParams;
}
export abstract class SeriesDrawingBase<
TSettings extends SettingsValues = SettingsValues,
THandleId extends string = string,
> implements ISeriesDrawing
{
protected hidden = false;
protected chart: IChartApi;
protected series: SeriesApi;
protected subscriptions = new Subscription();
protected abstract mode: unknown; // todo: хочется иметь единый mode
protected abstract settings: TSettings;
protected readonly container: HTMLElement;
protected isBound = false;
private readonly interaction: DrawingInteraction;
private readonly settingsSubject = new Subject<SettingsValues>();
private readonly handlesPrimitive: DrawingHandlesPrimitive<THandleId>;
private isInteractionBound = false;
protected readyPromise: Promise<void> | null = null;
protected resolveReady: (() => void) | null = null;
protected requestUpdate: (() => void) | null = null;
constructor({ chart, series, container, interaction }: SeriesDrawingBaseParams) {
this.chart = chart;
this.series = series;
this.container = container;
this.interaction = interaction;
this.handlesPrimitive = new DrawingHandlesPrimitive(() => {
if (this.hidden || !this.shouldShowHandles()) {
return [];
}
return this.getDrawingHandles();
});
}
public subscribeSettings(callback: (settings: SettingsValues) => void): Subscription {
callback(this.getSettings());
return this.settingsSubject.subscribe(callback);
}
public show(): void {
this.hidden = false;
this.render();
}
public hide(): void {
this.hidden = true;
this.showCrosshair();
this.render();
}
public rebind(series: SeriesApi): void {
if (this.series === series) {
return;
}
this.showCrosshair();
this.unbindEvents();
this.series.detachPrimitive(this as unknown as ISeriesPrimitive<Time>);
this.series = series;
this.requestUpdate = null;
this.series.attachPrimitive(this as unknown as ISeriesPrimitive<Time>);
this.render();
}
public destroy(): void {
this.showCrosshair();
this.unbindEvents();
this.subscriptions.unsubscribe();
this.settingsSubject.complete();
this.series.detachPrimitive(this as unknown as ISeriesPrimitive<Time>);
this.requestUpdate = null;
this.resolveReady?.();
}
public waitTillReady(): Promise<void> {
if (this.mode === 'ready') {
return Promise.resolve();
}
if (!this.readyPromise) {
this.readyPromise = new Promise((resolve) => {
this.resolveReady = resolve;
});
}
return this.readyPromise;
}
public shouldShowInObjectTree(): boolean {
return this.mode !== 'idle';
}
public getSettings(): SettingsValues {
return { ...this.settings };
}
public updateSettings(settings: SettingsValues): void {
this.settings = {
...this.settings,
...settings,
};
this.settingsSubject.next(this.getSettings());
this.render();
}
public attached(param: SeriesAttachedParameter<Time, keyof SeriesOptionsMap>): void {
this.requestUpdate = param.requestUpdate;
this.series.attachPrimitive(this.handlesPrimitive);
this.bindInteraction();
this.bindEvents();
}
public detached(): void {
this.series.detachPrimitive(this.handlesPrimitive);
this.showCrosshair();
this.unbindEvents();
this.requestUpdate = null;
}
public autoscaleInfo(_start: Logical, _end: Logical): AutoscaleInfo | null {
return null;
}
public hitTest(x: number, y: number): PrimitiveHoveredItem | null {
const hoveredItem = this.getHoveredItem(x, y);
if (!hoveredItem || !this.isLocked()) {
return hoveredItem;
}
return {
...hoveredItem,
cursorStyle: 'pointer',
};
}
public isHit(event: MouseEvent): boolean {
if (!this.isEventInside(event)) {
return false;
}
const point = this.getEventPoint(event as PointerEvent);
return this.getHoveredItem(point.x, point.y) !== null;
}
public pointerDown(event: PointerEvent): void {
if (!this.isEventInside(event)) {
return;
}
if (!this.isLocked() || this.isCreationPending() || event.button !== 0) {
this.handlePointerDown(event);
return;
}
const point = this.getEventPoint(event);
if (this.getHoveredItem(point.x, point.y)) {
this.select();
return;
}
if (this.isSelected()) {
this.deselect();
}
}
public click(event: MouseEvent): void {
if (!this.isEventInside(event)) {
return;
}
this.handleClick(event);
}
public doubleClick(event: MouseEvent): void {
if (!this.isEventInside(event)) {
return;
}
this.handleDoubleClick(event);
}
public contextMenu(event: MouseEvent): void {
if (!this.isEventInside(event)) {
return;
}
this.handleContextMenu(event);
}
public abstract getRenderData(): unknown; // todo: make proper type
public abstract getState(): unknown;
public abstract getSettingsTabs(): SettingsTab[];
public abstract isCreationPending(): boolean;
public abstract setState(state: unknown): void;
public abstract updateAllViews(): void;
public abstract paneViews(): readonly IPrimitivePaneView[];
public abstract priceAxisPaneViews(): readonly IPrimitivePaneView[];
public abstract priceAxisViews(): readonly ISeriesPrimitiveAxisView[];
public abstract timeAxisPaneViews(): readonly IPrimitivePaneView[];
public abstract timeAxisViews(): readonly ISeriesPrimitiveAxisView[];
protected isSelected(): boolean {
return this.interaction.isSelected();
}
protected isLocked(): boolean {
return this.interaction.isLocked();
}
protected select(): void {
this.interaction.select();
}
protected deselect(): void {
this.interaction.deselect();
}
protected shouldShowHandles(): boolean {
return !this.isLocked() && (this.isSelected() || this.isCreationPending());
}
protected getDrawingHandles(): readonly DrawingHandle<THandleId>[] {
return [];
}
protected getDrawingHandleAtPoint(point: Point): DrawingHandle<THandleId> | null {
return this.handlesPrimitive.findHandle(point);
}
protected render(): void {
this.updateAllViews();
this.requestUpdate?.();
}
protected hideCrosshair(): void {
this.chart.applyOptions({
crosshair: {
mode: CrosshairMode.Hidden,
},
});
}
protected showCrosshair(): void {
this.chart.applyOptions({
crosshair: {
mode: CrosshairMode.Normal,
},
});
}
protected getEventPoint(event: PointerEvent | TouchMouseEventData): Point {
return getPointerPointFromEvent(this.container, event);
}
protected bindEvents(): void {
if (this.isBound) {
return;
}
this.isBound = true;
window.addEventListener('pointermove', this.handlePointerMove);
window.addEventListener('pointerup', this.handlePointerUp);
window.addEventListener('pointercancel', this.handlePointerUp);
}
protected unbindEvents(): void {
if (!this.isBound) {
return;
}
this.isBound = false;
window.removeEventListener('pointermove', this.handlePointerMove);
window.removeEventListener('pointerup', this.handlePointerUp);
window.removeEventListener('pointercancel', this.handlePointerUp);
}
// todo: хочется общую реализацию для каждой кнопки
protected handleClick(event: MouseEvent): void {}
protected handleContextMenu(event: MouseEvent): void {}
protected handleDoubleClick(event: MouseEvent): void {}
protected handlePointerMove(event: PointerEvent): void {}
protected handlePointerUp(event: PointerEvent): void {}
protected handlePointerDown(event: PointerEvent | TouchMouseEventData): void {}
protected abstract getHoveredItem(x: number, y: number): PrimitiveHoveredItem | null;
protected abstract getGeometry(): unknown; // todo: make proper type
protected abstract getTimeAxisSegments(): AxisSegment[];
protected abstract getPriceAxisSegments(): AxisSegment[];
protected abstract getTimeAxisLabel(kind: string): AxisLabel | null;
protected abstract getPriceAxisLabel(kind: string): AxisLabel | null;
private bindInteraction(): void {
if (this.isInteractionBound) {
return;
}
this.isInteractionBound = true;
this.subscriptions.add(
this.interaction.selected$.subscribe(() => {
this.render();
}),
);
this.subscriptions.add(
this.interaction.locked$.subscribe((isLocked) => {
if (isLocked) {
this.showCrosshair();
}
this.render();
}),
);
}
private isEventInside(event: MouseEvent): boolean {
if (event.target instanceof Node && this.container.contains(event.target)) {
return true;
}
return this.handlesPrimitive.isTimeAxisHit(getRawPointerPoint(this.container, event));
}
}
import { isNearPoint } from '@core/Drawings/helpers';
import { drawRoundedRect } from '@core/Drawings/utils';
import { getThemeStore } from '@src/theme';
import type { Point } from '@core/Drawings/types';
import type { CanvasRenderingTarget2D } from 'fancy-canvas';
import type {
IPrimitivePaneRenderer,
IPrimitivePaneView,
ISeriesPrimitive,
SeriesAttachedParameter,
Time,
} from 'lightweight-charts';
export type DrawingHandleShape = 'circle' | 'rounded';
export interface DrawingHandle<TId extends string = string> {
id: TId;
x: number;
y: number;
shape?: DrawingHandleShape;
size?: number;
borderWidth?: number;
strokeColor?: string;
}
const DEFAULT_HANDLE_SIZE = 12;
const DEFAULT_HANDLE_BORDER_WIDTH = 2;
const HANDLE_HIT_TOLERANCE = 8;
const HANDLE_RADIUS = 2;
export class DrawingHandlesPrimitive<TId extends string = string> implements ISeriesPrimitive<Time> {
private chart: SeriesAttachedParameter<Time>['chart'] | null = null;
private series: SeriesAttachedParameter<Time>['series'] | null = null;
private readonly paneRenderer: IPrimitivePaneRenderer = {
draw: (target) => this.drawPane(target),
};
private readonly timeAxisRenderer: IPrimitivePaneRenderer = {
draw: (target) => this.drawTimeAxis(target),
};
private readonly paneViewsList: readonly IPrimitivePaneView[] = [
{
renderer: () => this.paneRenderer,
zOrder: () => 'top',
},
];
private readonly timeAxisPaneViewsList: readonly IPrimitivePaneView[] = [
{
renderer: () => this.timeAxisRenderer,
zOrder: () => 'top',
},
];
constructor(private readonly getHandles: () => readonly DrawingHandle<TId>[]) {}
public attached({ chart, series }: SeriesAttachedParameter<Time>): void {
this.chart = chart;
this.series = series;
}
public detached(): void {
this.chart = null;
this.series = null;
}
public paneViews(): readonly IPrimitivePaneView[] {
return this.paneViewsList;
}
public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
return this.timeAxisPaneViewsList;
}
public findHandle(point: Point): DrawingHandle<TId> | null {
const handles = this.getHandles();
for (let index = handles.length - 1; index >= 0; index -= 1) {
const handle = handles[index];
if (isNearPoint(point, handle.x, handle.y, getHitTolerance(handle))) {
return handle;
}
}
return null;
}
public isTimeAxisHit(point: Point): boolean {
if (!this.isTimeAxisAdjacent()) {
return false;
}
const paneHeight = this.getPaneHeight();
if (paneHeight <= 0 || point.y < paneHeight) {
return false;
}
const handle = this.findHandle(point);
return handle !== null && intersectsTimeAxis(handle, paneHeight);
}
private drawPane(target: CanvasRenderingTarget2D): void {
const handles = this.getHandles();
if (!handles.length) {
return;
}
target.useBitmapCoordinateSpace(({ context, horizontalPixelRatio, verticalPixelRatio }) => {
for (const handle of handles) {
drawHandle(context, handle, horizontalPixelRatio, verticalPixelRatio);
}
});
}
private drawTimeAxis(target: CanvasRenderingTarget2D): void {
if (!this.isTimeAxisAdjacent()) {
return;
}
const paneHeight = this.getPaneHeight();
if (paneHeight <= 0) {
return;
}
const handles = this.getHandles();
if (!handles.length) {
return;
}
target.useBitmapCoordinateSpace(({ context, horizontalPixelRatio, verticalPixelRatio, bitmapSize }) => {
const axisHeight = bitmapSize.height / verticalPixelRatio;
for (const handle of handles) {
if (!intersectsTimeAxis(handle, paneHeight)) {
continue;
}
const axisY = handle.y - paneHeight;
const halfSize = getHandleSize(handle) / 2;
if (axisY + halfSize <= 0 || axisY - halfSize >= axisHeight) {
continue;
}
drawHandle(context, { ...handle, y: axisY }, horizontalPixelRatio, verticalPixelRatio);
}
});
}
private getPaneHeight(): number {
return this.series?.getPane().getHeight() ?? 0;
}
private isTimeAxisAdjacent(): boolean {
if (!this.chart || !this.series) {
return false;
}
return this.series.getPane().paneIndex() === this.chart.panes().length - 1;
}
}
function getHandleSize(handle: DrawingHandle): number {
return handle.size ?? DEFAULT_HANDLE_SIZE;
}
function getHitTolerance(handle: DrawingHandle): number {
return Math.max(HANDLE_HIT_TOLERANCE, getHandleSize(handle) / 2);
}
function intersectsTimeAxis(handle: DrawingHandle, paneHeight: number): boolean {
const halfSize = getHandleSize(handle) / 2;
return handle.y - halfSize < paneHeight && handle.y + halfSize > paneHeight;
}
function drawHandle(
context: CanvasRenderingContext2D,
handle: DrawingHandle,
horizontalPixelRatio: number,
verticalPixelRatio: number,
): void {
const size = getHandleSize(handle);
const shape = handle.shape ?? 'circle';
const pixelRatio = Math.max(horizontalPixelRatio, verticalPixelRatio);
const lineWidth = (handle.borderWidth ?? DEFAULT_HANDLE_BORDER_WIDTH) * pixelRatio;
const width = size * horizontalPixelRatio;
const height = size * verticalPixelRatio;
const x = handle.x * horizontalPixelRatio;
const y = handle.y * verticalPixelRatio;
const inset = lineWidth / 2;
const { colors } = getThemeStore();
context.save();
context.fillStyle = colors.chartBackground;
context.strokeStyle = handle.strokeColor ?? colors.chartLineColor;
context.lineWidth = lineWidth;
context.beginPath();
if (shape === 'circle') {
const radius = Math.max(Math.min(width, height) / 2 - inset, 0);
context.arc(x, y, radius, 0, Math.PI * 2);
} else {
const left = x - width / 2 + inset;
const top = y - height / 2 + inset;
const drawWidth = Math.max(width - lineWidth, 0);
const drawHeight = Math.max(height - lineWidth, 0);
drawRoundedRect(context, left, top, drawWidth, drawHeight, HANDLE_RADIUS * pixelRatio);
}
context.fill();
context.stroke();
context.restore();
}
import { CustomPriceAxisView, CustomTimeAxisView } from '@core/Drawings/axis';
import {
getPriceFromYCoordinate,
getTimeFromXCoordinate,
getXCoordinateFromTime,
getYCoordinateFromPrice,
} from '@core/Drawings/helpers';
import { updateViews } from '@core/Drawings/utils';
import { SeriesDrawingBase } from '@src/core/Drawings/SeriesDrawingBase';
import { getThemeStore } from '@src/theme';
import { Defaults } from '@src/types/defaults';
import { formatPrice } from '@src/utils';
import { formatDate } from '@src/utils/formatter';
import { AxisLinePaneView } from './paneView';
import {
AxisLineSettings,
AxisLineStyle,
AxisLineTextStyle,
createDefaultSettings,
getAxisLineSettingsTabs,
} from './settings';
import type { DrawingHandle } from '@core/Drawings/handles';
import type { AxisLabel, AxisSegment, Point } from '@core/Drawings/types';
import type { BaseDrawingParams, ISeriesDrawing } from '@src/core/Drawings/SeriesDrawingBase';
import type { ChartOptionsModel, SettingsTab } from '@src/types';
import type { IPrimitivePaneView, PrimitiveHoveredItem, Time, UTCTimestamp } from 'lightweight-charts';
export type AxisLineDirection = 'vertical' | 'horizontal';
type AxisLineMode = 'idle' | 'ready' | 'dragging';
type AxisLineHandleKey = 'main';
interface AxisLineParams extends BaseDrawingParams {
direction: AxisLineDirection;
}
interface AxisLineState {
hidden: boolean;
mode: AxisLineMode;
time: Time | null;
price: number | null;
settings: AxisLineSettings;
}
export interface AxisLineRenderData extends AxisLineStyle, AxisLineTextStyle {
direction: AxisLineDirection;
coordinate: number;
}
const LINE_HIT_TOLERANCE = 6;
export class AxisLine extends SeriesDrawingBase<AxisLineSettings, AxisLineHandleKey> implements ISeriesDrawing {
private readonly openSettings?: () => void;
protected settings: AxisLineSettings = createDefaultSettings();
protected mode: AxisLineMode = 'idle';
private readonly direction: AxisLineDirection;
private time: Time | null = null;
private price: number | null = null;
private dragPointerId: number | null = null;
private displayFormat: ChartOptionsModel = {
dateFormat: Defaults.dateFormat,
timeFormat: Defaults.timeFormat,
showTime: Defaults.showTime,
};
private readonly paneView: AxisLinePaneView;
private readonly timeAxisView: CustomTimeAxisView;
private readonly priceAxisView: CustomPriceAxisView;
constructor({
chart,
series,
direction,
container,
interaction,
formatObservable,
openSettings,
initialEvent,
}: AxisLineParams) {
super({ chart, series, container, interaction });
this.direction = direction;
this.openSettings = openSettings;
this.paneView = new AxisLinePaneView(this);
this.timeAxisView = new CustomTimeAxisView({
getAxisLabel: (kind) => this.getTimeAxisLabel(kind),
labelKind: 'main',
});
this.priceAxisView = new CustomPriceAxisView({
getAxisLabel: (kind) => this.getPriceAxisLabel(kind),
labelKind: 'main',
});
if (formatObservable) {
this.subscriptions.add(
formatObservable.subscribe((format) => {
this.displayFormat = format;
this.render();
}),
);
}
this.series.attachPrimitive(this);
if (initialEvent && initialEvent.sourceEvent) {
const point = this.getEventPoint(initialEvent.sourceEvent);
this.startDrawing(point);
}
}
public isCreationPending(): boolean {
return this.mode === 'idle';
}
public getState(): AxisLineState {
return {
hidden: this.hidden,
mode: this.mode,
time: this.time,
price: this.price,
settings: { ...this.settings },
};
}
public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
return [];
}
public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
return [];
}
public setState(state: unknown): void {
const nextState = state as Partial<AxisLineState>;
if ('hidden' in nextState && typeof nextState.hidden === 'boolean') {
this.hidden = nextState.hidden;
}
if ('mode' in nextState && nextState.mode) {
this.mode = nextState.mode;
}
if ('time' in nextState) {
this.time = nextState.time ?? null;
}
if ('price' in nextState) {
this.price = nextState.price ?? null;
}
if ('settings' in nextState && nextState.settings) {
this.settings = {
...createDefaultSettings(),
...nextState.settings,
};
}
this.render();
}
public getSettingsTabs(): SettingsTab[] {
return getAxisLineSettingsTabs(this.settings);
}
public updateAllViews(): void {
updateViews([this.paneView, this.timeAxisView, this.priceAxisView]);
}
public paneViews(): readonly IPrimitivePaneView[] {
return [this.paneView];
}
public timeAxisViews() {
return this.direction === 'vertical' ? [this.timeAxisView] : [];
}
public priceAxisViews() {
return this.direction === 'horizontal' ? [this.priceAxisView] : [];
}
public getRenderData(): AxisLineRenderData | null {
if (this.hidden) {
return null;
}
const coordinate = this.getCoordinate();
if (coordinate === null) {
return null;
}
return {
direction: this.direction,
coordinate,
...this.settings,
};
}
protected getDrawingHandles(): readonly DrawingHandle<AxisLineHandleKey>[] {
const coordinate = this.getCoordinate();
if (coordinate === null) {
return [];
}
const { width, height } = this.container.getBoundingClientRect();
return [
{
id: 'main',
x: this.direction === 'vertical' ? coordinate : width / 2,
y: this.direction === 'vertical' ? height / 2 : coordinate,
shape: 'rounded',
},
];
}
protected getHoveredItem(x: number, y: number): PrimitiveHoveredItem | null {
if (this.hidden || this.mode === 'idle') {
return null;
}
const point = { x, y };
const data = this.getRenderData();
if (!data) {
return null;
}
if (this.isSelected() && this.getDrawingHandleAtPoint(point)) {
return {
cursorStyle: this.getCursorStyle(),
externalId: 'axis-line',
zOrder: 'top',
};
}
if (!this.isPointNearLine(point, data.coordinate)) {
return null;
}
return {
cursorStyle: this.getCursorStyle(),
externalId: 'axis-line',
zOrder: 'top',
};
}
protected getTimeAxisLabel(kind: string): AxisLabel | null {
if (kind !== 'main' || this.direction !== 'vertical' || !this.isSelected() || this.time === null) {
return null;
}
const coordinate = getXCoordinateFromTime(this.chart, this.time, this.series);
if (coordinate === null || typeof this.time !== 'number') {
return null;
}
const { colors } = getThemeStore();
return {
coordinate,
text: formatDate(
this.time as UTCTimestamp,
this.displayFormat.dateFormat,
this.displayFormat.timeFormat,
this.displayFormat.showTime,
),
textColor: colors.chartPriceLineText,
backgroundColor: colors.axisMarkerLabelFill,
};
}
protected getPriceAxisLabel(kind: string): AxisLabel | null {
if (kind !== 'main' || this.direction !== 'horizontal' || !this.isSelected() || this.price === null) {
return null;
}
const coordinate = getYCoordinateFromPrice(this.series, this.price);
if (coordinate === null) {
return null;
}
const { colors } = getThemeStore();
return {
coordinate,
text: formatPrice(this.price) ?? '',
textColor: colors.chartPriceLineText,
backgroundColor: colors.axisMarkerLabelFill,
};
}
protected getTimeAxisSegments(): AxisSegment[] {
return [];
}
protected getPriceAxisSegments(): AxisSegment[] {
return [];
}
protected getGeometry(): null {
return null;
}
protected handleDoubleClick = (event: MouseEvent): void => {
if (this.hidden || this.mode !== 'ready') {
return;
}
const data = this.getRenderData();
if (!data) {
return;
}
const point = this.getEventPoint(event as PointerEvent);
const isNearHandle = this.isSelected() && Boolean(this.getDrawingHandleAtPoint(point));
const isNearLine = this.isPointNearLine(point, data.coordinate);
if (!isNearHandle && !isNearLine) {
return;
}
event.preventDefault();
event.stopPropagation();
this.openSettings?.();
};
protected handlePointerDown = (event: PointerEvent): void => {
if (this.hidden || event.button !== 0) {
return;
}
const point = this.getEventPoint(event);
if (this.mode === 'idle') {
event.preventDefault();
event.stopPropagation();
this.startDrawing(point);
return;
}
if (this.mode !== 'ready') {
return;
}
const data = this.getRenderData();
if (!data) {
return;
}
const isNearHandle = this.isSelected() && Boolean(this.getDrawingHandleAtPoint(point));
const isNearLine = this.isPointNearLine(point, data.coordinate);
if (!this.isSelected()) {
if (!isNearLine) {
return;
}
event.preventDefault();
event.stopPropagation();
this.select();
return;
}
if (!isNearHandle && !isNearLine) {
this.deselect();
return;
}
event.preventDefault();
event.stopPropagation();
this.mode = 'dragging';
this.dragPointerId = event.pointerId;
this.hideCrosshair();
this.render();
};
protected handlePointerMove = (event: PointerEvent): void => {
if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
return;
}
event.preventDefault();
event.stopPropagation();
this.updateLine(this.getEventPoint(event));
this.render();
};
protected handlePointerUp = (event: PointerEvent): void => {
if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
return;
}
this.mode = 'ready';
this.dragPointerId = null;
this.resolveReady?.();
this.showCrosshair();
this.render();
};
private startDrawing(point: Point): void {
this.updateLine(point);
this.mode = 'ready';
this.resolveReady?.();
this.render();
}
private updateLine(point: Point): void {
if (this.direction === 'vertical') {
this.time = getTimeFromXCoordinate(this.chart, point.x);
return;
}
this.price = getPriceFromYCoordinate(this.series, point.y);
}
private getCoordinate(): number | null {
if (this.direction === 'vertical') {
if (this.time === null) {
return null;
}
const coordinate = getXCoordinateFromTime(this.chart, this.time, this.series);
return coordinate === null ? null : Number(coordinate);
}
if (this.price === null) {
return null;
}
const coordinate = getYCoordinateFromPrice(this.series, this.price);
return coordinate === null ? null : Number(coordinate);
}
private isPointNearLine(point: Point, coordinate: number): boolean {
return this.direction === 'vertical'
? Math.abs(point.x - coordinate) <= LINE_HIT_TOLERANCE
: Math.abs(point.y - coordinate) <= LINE_HIT_TOLERANCE;
}
private getCursorStyle(): PrimitiveHoveredItem['cursorStyle'] {
return this.direction === 'vertical' ? 'ew-resize' : 'ns-resize';
}
}
import { CanvasRenderingTarget2D } from 'fancy-canvas';
import { IPrimitivePaneRenderer } from 'lightweight-charts';
import { AxisLine } from './axisLine';
const UI = {
lineWidth: 2,
textLineHeightMultiplier: 1.2,
textOffset: 4,
};
export class AxisLinePaneRenderer implements IPrimitivePaneRenderer {
private readonly axisLine: AxisLine;
constructor(axisLine: AxisLine) {
this.axisLine = axisLine;
}
public draw(target: CanvasRenderingTarget2D): void {
const data = this.axisLine.getRenderData();
if (!data) {
return;
}
target.useBitmapCoordinateSpace(({ context, bitmapSize, horizontalPixelRatio, verticalPixelRatio }) => {
const pixelRatio = Math.max(horizontalPixelRatio, verticalPixelRatio);
context.save();
context.fillStyle = data.lineColor;
if (data.direction === 'vertical') {
const x = Math.round(data.coordinate * horizontalPixelRatio);
const width = Math.max(1, UI.lineWidth * pixelRatio);
context.fillRect(x - width / 2, 0, width, bitmapSize.height);
}
if (data.direction === 'horizontal') {
const y = Math.round(data.coordinate * verticalPixelRatio);
const height = Math.max(1, UI.lineWidth * pixelRatio);
context.fillRect(0, y - height / 2, bitmapSize.width, height);
}
drawTextAlongAxisLine(context, {
direction: data.direction,
coordinate: data.coordinate,
text: data.text,
fontSize: data.fontSize,
isBold: data.isBold,
isItalic: data.isItalic,
textColor: data.textColor,
bitmapWidth: bitmapSize.width,
bitmapHeight: bitmapSize.height,
horizontalPixelRatio,
verticalPixelRatio,
});
context.restore();
});
}
}
function drawTextAlongAxisLine(
context: CanvasRenderingContext2D,
params: {
direction: 'vertical' | 'horizontal';
coordinate: number;
text: string;
fontSize: number;
isBold: boolean;
isItalic: boolean;
textColor: string;
bitmapWidth: number;
bitmapHeight: number;
horizontalPixelRatio: number;
verticalPixelRatio: number;
},
): void {
const {
direction,
coordinate,
text,
fontSize,
isBold,
isItalic,
textColor,
bitmapWidth,
bitmapHeight,
horizontalPixelRatio,
verticalPixelRatio,
} = params;
if (!text.trim()) {
return;
}
const lines = text.split('\n');
const safeFontSize = Math.max(1, fontSize);
const fontSizePx = safeFontSize * verticalPixelRatio;
const lineHeight = safeFontSize * UI.textLineHeightMultiplier * verticalPixelRatio;
const fontWeight = isBold ? '700 ' : '';
const fontStyle = isItalic ? 'italic ' : '';
const textOffset = UI.textOffset * Math.max(horizontalPixelRatio, verticalPixelRatio);
const x = direction === 'vertical' ? coordinate * horizontalPixelRatio : bitmapWidth / 2;
const y = direction === 'horizontal' ? coordinate * verticalPixelRatio : bitmapHeight / 2;
const angle = direction === 'vertical' ? -Math.PI / 2 : 0;
context.save();
context.translate(x, y);
context.rotate(angle);
context.font = `${fontStyle}${fontWeight}${fontSizePx}px Inter, sans-serif`;
context.fillStyle = textColor;
context.textAlign = 'center';
context.textBaseline = 'middle';
const blockHeight = lines.length * lineHeight;
const textCenterY = -(blockHeight / 2 + textOffset);
const startLineY = textCenterY - blockHeight / 2 + lineHeight / 2;
lines.forEach((line, index) => {
context.fillText(line, 0, startLineY + index * lineHeight);
});
context.restore();
}
import { round } from 'lodash-es';
import { skip } from 'rxjs';
import {
CustomPriceAxisPaneView,
CustomPriceAxisView,
CustomTimeAxisPaneView,
CustomTimeAxisView,
} from '@core/Drawings/axis';
import {
getPriceDelta as getPriceDeltaFromCoordinates,
getPriceFromYCoordinate,
getPriceRangeInContainer,
getTimeFromXCoordinate,
getXCoordinateFromTime,
getYCoordinateFromPrice,
isPointInBounds,
shiftTimeByPixels,
} from '@core/Drawings/helpers';
import { updateViews } from '@core/Drawings/utils';
import { SeriesDrawingBase } from '@src/core/Drawings/SeriesDrawingBase';
import { getThemeStore } from '@src/theme';
import { t } from '@src/translations';
import { Defaults } from '@src/types/defaults';
import { formatPercent, formatPrice, formatSignedNumber, getPercentPrecision, getPricePrecisionStep } from '@src/utils';
import { formatDate } from '@src/utils/formatter';
import { SliderPaneView } from './paneView';
import { createDefaultSettings, getSliderPositionSettingsTabs } from './settings';
import type { SliderPositionArguments, SliderPositionSettings, SliderPositionStyle } from './settings';
import type { DrawingHandle } from '@core/Drawings/handles';
import type { AxisLabel, AxisSegment, Bounds, Point } from '@core/Drawings/types';
import type { BaseDrawingParams, ISeriesDrawing } from '@src/core/Drawings/SeriesDrawingBase';
import type { ChartOptionsModel, SettingsTab, SettingsValues } from '@src/types';
import type {
IPrimitivePaneView,
MouseEventHandler,
MouseEventParams,
PrimitiveHoveredItem,
Time,
UTCTimestamp,
} from 'lightweight-charts';
import type { Observable } from 'rxjs';
type SliderSide = 'long' | 'short';
type SliderMode = 'idle' | 'ready' | 'dragging';
type DragTarget = 'body' | 'entry' | 'target' | 'stop' | 'end' | null;
type SliderHandleId = Exclude<DragTarget, 'body' | null>;
type TimeLabelKind = 'start' | 'end';
type PriceLabelKind = 'target' | 'entry' | 'stop';
interface SliderPositionParams extends BaseDrawingParams {
side: SliderSide;
resetTriggers?: Observable<unknown>[];
}
interface SliderPositionState {
hidden: boolean;
mode: SliderMode;
startTime: Time | null;
endTime: Time | null;
entryPrice: number | null;
stopPrice: number | null;
targetPrice: number | null;
riskRewardRatio: number;
amount: number;
settings: SliderPositionSettings;
}
interface PositionMetrics {
qty: number;
targetAmount: number;
stopAmount: number;
riskRewardRatio: number;
openPnl: number;
}
interface SliderGeometry {
startX: number;
endX: number;
leftX: number;
rightX: number;
entryY: number;
stopY: number;
targetY: number;
entryPrice: number;
stopPrice: number;
targetPrice: number;
profitTop: number;
profitBottom: number;
lossTop: number;
lossBottom: number;
}
export interface SliderRenderData extends SliderGeometry, SliderPositionStyle {
targetText: string;
centerText: string;
stopText: string;
centerBoxColor: string;
targetLabelDirection: 'up' | 'down';
stopLabelDirection: 'up' | 'down';
showLabels: boolean;
}
const HIT_TOLERANCE = 8;
const INITIAL_WIDTH_PX = 160;
const INITIAL_ZONE_OFFSET_PX = 60;
const DEFAULT_RISK_REWARD_RATIO = 1;
export class SliderPosition
extends SeriesDrawingBase<SliderPositionSettings, SliderHandleId>
implements ISeriesDrawing
{
protected settings: SliderPositionSettings = createDefaultSettings();
protected mode: SliderMode = 'idle';
private readonly side: SliderSide;
private readonly removeSelf?: () => void;
private readonly openSettings?: () => void;
private readonly clickHandler: MouseEventHandler<Time>;
private readonly paneView: SliderPaneView;
private readonly timeAxisPaneView: CustomTimeAxisPaneView;
private readonly priceAxisPaneView: CustomPriceAxisPaneView;
private readonly startTimeAxisView: CustomTimeAxisView;
private readonly endTimeAxisView: CustomTimeAxisView;
private readonly targetPriceAxisView: CustomPriceAxisView;
private readonly entryPriceAxisView: CustomPriceAxisView;
private readonly stopPriceAxisView: CustomPriceAxisView;
private displayFormat: ChartOptionsModel = {
dateFormat: Defaults.dateFormat,
timeFormat: Defaults.timeFormat,
showTime: Defaults.showTime,
};
private startTime: Time | null = null;
private endTime: Time | null = null;
private entryPrice: number | null = null;
private stopPrice: number | null = null;
private targetPrice: number | null = null;
private activeDragTarget: DragTarget = null;
private dragPointerId: number | null = null;
private dragStartPoint: Point | null = null;
private dragStateSnapshot: SliderPositionState | null = null;
constructor({
chart,
series,
side,
container,
interaction,
formatObservable,
resetTriggers = [],
removeSelf,
openSettings,
initialEvent,
}: SliderPositionParams) {
super({ chart, series, container, interaction });
this.side = side;
this.removeSelf = removeSelf;
this.openSettings = openSettings;
this.clickHandler = (params) => this.handleChartClick(params);
this.paneView = new SliderPaneView(this);
this.timeAxisPaneView = new CustomTimeAxisPaneView({
getAxisSegments: () => this.getTimeAxisSegments(),
zOrder: 'normal',
});
this.priceAxisPaneView = new CustomPriceAxisPaneView({
getAxisSegments: () => this.getPriceAxisSegments(),
zOrder: 'normal',
});
this.startTimeAxisView = new CustomTimeAxisView({
getAxisLabel: (kind) => this.getTimeAxisLabel(kind),
labelKind: 'start',
});
this.endTimeAxisView = new CustomTimeAxisView({
getAxisLabel: (kind) => this.getTimeAxisLabel(kind),
labelKind: 'end',
});
this.targetPriceAxisView = new CustomPriceAxisView({
getAxisLabel: (kind) => this.getPriceAxisLabel(kind),
labelKind: 'target',
});
this.entryPriceAxisView = new CustomPriceAxisView({
getAxisLabel: (kind) => this.getPriceAxisLabel(kind),
labelKind: 'entry',
});
this.stopPriceAxisView = new CustomPriceAxisView({
getAxisLabel: (kind) => this.getPriceAxisLabel(kind),
labelKind: 'stop',
});
if (formatObservable) {
this.subscriptions.add(
formatObservable.subscribe((format) => {
this.displayFormat = format;
this.render();
}),
);
}
resetTriggers.forEach((trigger) => {
this.subscriptions.add(
trigger.pipe(skip(1)).subscribe(() => {
this.removeSelf?.();
}),
);
});
this.series.attachPrimitive(this);
if (initialEvent) {
this.handleChartClick(initialEvent);
}
}
public isCreationPending(): boolean {
return this.mode === 'idle';
}
public getState(): SliderPositionState {
return {
hidden: this.hidden,
mode: this.mode,
startTime: this.startTime,
endTime: this.endTime,
entryPrice: this.entryPrice,
stopPrice: this.stopPrice,
targetPrice: this.targetPrice,
riskRewardRatio: this.getCurrentRiskRewardRatio(),
amount: this.settings.accountSize,
settings: { ...this.settings },
};
}
public setState(state: unknown): void {
if (!state || typeof state !== 'object') {
return;
}
const next = state as Partial<SliderPositionState>;
const {
hidden = this.hidden,
mode = this.mode,
startTime = this.startTime,
endTime = this.endTime,
entryPrice = this.entryPrice,
} = next;
this.hidden = hidden;
this.mode = mode;
this.startTime = startTime;
this.endTime = endTime;
this.entryPrice = entryPrice;
if (next.stopPrice !== undefined) {
this.stopPrice =
next.stopPrice === null || entryPrice === null
? next.stopPrice
: this.normalizeStop(entryPrice, next.stopPrice);
}
const targetPrice = this.resolveTargetPrice(next, entryPrice);
if (targetPrice !== undefined) {
this.targetPrice = targetPrice;
}
if (next.settings) {
this.settings = {
...createDefaultSettings(),
...next.settings,
};
}
if (typeof next.amount === 'number' && next.amount >= 0) {
this.settings.accountSize = next.amount;
}
this.render();
}
public getSettings(): SettingsValues {
return {
...this.settings,
...this.getPositionArguments(),
};
}
public updateSettings(values: SettingsValues): void {
const { entryPrice, targetPrice, stopPrice, ...settings } = values as Partial<
SliderPositionSettings & SliderPositionArguments
>;
this.applyPositionArguments({ entryPrice, targetPrice, stopPrice });
super.updateSettings(settings as SettingsValues);
}
public getSettingsTabs(): SettingsTab[] {
return getSliderPositionSettingsTabs(this.settings, this.getPositionArguments());
}
public updateAllViews(): void {
updateViews([
this.paneView,
this.timeAxisPaneView,
this.priceAxisPaneView,
this.startTimeAxisView,
this.endTimeAxisView,
this.targetPriceAxisView,
this.entryPriceAxisView,
this.stopPriceAxisView,
]);
}
public paneViews(): readonly IPrimitivePaneView[] {
return [this.paneView];
}
public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
return [this.timeAxisPaneView];
}
public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
return [this.priceAxisPaneView];
}
public timeAxisViews() {
return [this.startTimeAxisView, this.endTimeAxisView];
}
public priceAxisViews() {
return [this.targetPriceAxisView, this.entryPriceAxisView, this.stopPriceAxisView];
}
public getRenderData(): SliderRenderData | null {
if (this.hidden) {
return null;
}
const geometry = this.getGeometry();
if (!geometry) {
return null;
}
const metrics = this.getPositionMetrics(geometry, this.getPriceAtTime(this.endTime));
const { colors } = getThemeStore();
return {
...geometry,
targetText: this.getTargetText(geometry, metrics.targetAmount),
centerText: this.getCenterText(metrics),
stopText: this.getStopText(geometry, metrics.stopAmount),
centerBoxColor: metrics.openPnl >= 0 ? colors.chartCandleUp : colors.chartCandleDown,
targetLabelDirection: this.side === 'long' ? 'up' : 'down',
stopLabelDirection: this.side === 'long' ? 'down' : 'up',
showLabels: this.isSelected(),
...this.settings,
};
}
public getTimeBounds(): { left: number; right: number } | null {
const start = this.getTimeCoordinate('start');
const end = this.getTimeCoordinate('end');
if (start === null || end === null) {
return null;
}
return {
left: Math.min(start, end),
right: Math.max(start, end),
};
}
public getTimeCoordinate(kind: TimeLabelKind): number | null {
const time = kind === 'start' ? this.startTime : this.endTime;
if (time === null) {
return null;
}
const coordinate = getXCoordinateFromTime(this.chart, time, this.series);
return coordinate === null ? null : Number(coordinate);
}
public getTimeText(kind: TimeLabelKind): string {
const time = kind === 'start' ? this.startTime : this.endTime;
if (typeof time !== 'number') {
return '';
}
return formatDate(
time as UTCTimestamp,
this.displayFormat.dateFormat,
this.displayFormat.timeFormat,
this.displayFormat.showTime,
);
}
public getPriceCoordinate(kind: PriceLabelKind): number | null {
const geometry = this.getGeometry();
if (!geometry) {
return null;
}
switch (kind) {
case 'target':
return geometry.targetY;
case 'entry':
return geometry.entryY;
case 'stop':
return geometry.stopY;
default:
return null;
}
}
public getPriceText(kind: PriceLabelKind): string {
const geometry = this.getGeometry();
if (!geometry) {
return '';
}
switch (kind) {
case 'target':
return formatPrice(geometry.targetPrice) ?? '';
case 'entry':
return formatPrice(geometry.entryPrice) ?? '';
case 'stop':
return formatPrice(geometry.stopPrice) ?? '';
default:
return '';
}
}
protected getHoveredItem(x: number, y: number): PrimitiveHoveredItem | null {
const point = { x, y };
if (!this.isSelected()) {
if (!this.containsPoint(point)) {
return null;
}
return {
cursorStyle: 'pointer',
externalId: 'slider-position',
zOrder: 'top',
};
}
const dragTarget = this.getHandleTarget(point);
if (!dragTarget) {
return null;
}
let cursorStyle: PrimitiveHoveredItem['cursorStyle'] = 'grab';
if (dragTarget === 'target' || dragTarget === 'stop') {
cursorStyle = 'ns-resize';
} else if (dragTarget === 'end') {
cursorStyle = 'ew-resize';
}
return {
cursorStyle,
externalId: 'slider-position',
zOrder: 'top',
};
}
protected getTimeAxisSegments(): AxisSegment[] {
if (!this.isSelected()) {
return [];
}
const bounds = this.getTimeBounds();
if (!bounds) {
return [];
}
const { colors } = getThemeStore();
return [
{
from: bounds.left,
to: bounds.right,
color: colors.axisMarkerAreaFill,
},
];
}
protected getPriceAxisSegments(): AxisSegment[] {
if (!this.isSelected()) {
return [];
}
const geometry = this.getGeometry();
if (!geometry) {
return [];
}
const { colors } = getThemeStore();
return [
{
from: geometry.profitTop,
to: geometry.profitBottom,
color: colors.axisMarkerAreaFill,
},
{
from: geometry.lossTop,
to: geometry.lossBottom,
color: colors.axisMarkerAreaFill,
},
];
}
protected getTimeAxisLabel(kind: string): AxisLabel | null {
if (!this.isSelected() || (kind !== 'start' && kind !== 'end')) {
return null;
}
const labelKind = kind as TimeLabelKind;
const coordinate = this.getTimeCoordinate(labelKind);
const text = this.getTimeText(labelKind);
if (coordinate === null || !text) {
return null;
}
const { colors } = getThemeStore();
return {
coordinate,
text,
textColor: colors.chartPriceLineText,
backgroundColor: colors.axisMarkerLabelFill,
};
}
protected getPriceAxisLabel(kind: string): AxisLabel | null {
if (kind !== 'target' && kind !== 'entry' && kind !== 'stop') {
return null;
}
const labelKind = kind as PriceLabelKind;
const coordinate = this.getPriceCoordinate(labelKind);
const text = this.getPriceText(labelKind);
if (coordinate === null || !text) {
return null;
}
const { colors } = getThemeStore();
let backgroundColor = colors.axisMarkerLabelDefaultFill;
if (labelKind === 'target') {
backgroundColor = colors.axisMarkerLabelPositiveFill;
} else if (labelKind === 'stop') {
backgroundColor = colors.axisMarkerLabelNegativeFill;
}
return {
coordinate,
text,
textColor: colors.chartPriceLineText,
backgroundColor,
};
}
protected bindEvents(): void {
if (this.isBound) {
return;
}
super.bindEvents();
this.chart.subscribeClick(this.clickHandler);
}
protected unbindEvents(): void {
if (!this.isBound) {
return;
}
this.chart.unsubscribeClick(this.clickHandler);
super.unbindEvents();
}
protected handleDoubleClick = (event: MouseEvent): void => {
if (this.hidden || this.mode !== 'ready' || !this.isSelected()) {
return;
}
const point = this.getEventPoint(event as PointerEvent);
if (!this.containsPoint(point)) {
return;
}
event.preventDefault();
event.stopPropagation();
this.openSettings?.();
};
protected handlePointerDown = (event: PointerEvent): void => {
if (this.hidden || this.mode !== 'ready' || event.button !== 0) {
return;
}
const point = this.getEventPoint(event);
if (!this.isSelected()) {
if (!this.containsPoint(point)) {
return;
}
event.preventDefault();
event.stopPropagation();
this.select();
return;
}
const dragTarget = this.getHandleTarget(point);
if (!dragTarget) {
this.deselect();
return;
}
event.preventDefault();
event.stopPropagation();
this.activeDragTarget = dragTarget;
this.dragPointerId = event.pointerId;
this.dragStartPoint = point;
this.dragStateSnapshot = this.getState();
this.mode = 'dragging';
};
protected handlePointerMove = (event: PointerEvent): void => {
if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId || !this.dragStateSnapshot) {
return;
}
event.preventDefault();
this.applyDrag(this.getEventPoint(event));
this.render();
};
protected handlePointerUp = (event: PointerEvent): void => {
if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
return;
}
this.activeDragTarget = null;
this.dragPointerId = null;
this.dragStartPoint = null;
this.dragStateSnapshot = null;
this.mode = 'ready';
this.resolveReady?.();
this.render();
};
protected getDrawingHandles(): readonly DrawingHandle<SliderHandleId>[] {
const geometry = this.getGeometry();
if (!geometry) {
return [];
}
return [
{
id: 'target',
x: geometry.startX,
y: geometry.targetY,
},
{
id: 'stop',
x: geometry.startX,
y: geometry.stopY,
},
{
id: 'end',
x: geometry.endX,
y: geometry.entryY,
},
{
id: 'entry',
x: geometry.startX,
y: geometry.entryY,
shape: 'circle',
},
];
}
private resolveTargetPrice(
state: Partial<SliderPositionState>,
entryPrice: number | null,
): number | null | undefined {
if (state.targetPrice !== undefined) {
if (state.targetPrice === null || entryPrice === null) {
return state.targetPrice;
}
return this.normalizeTarget(entryPrice, state.targetPrice);
}
const ratio = state.riskRewardRatio;
if (entryPrice === null || this.stopPrice === null || typeof ratio !== 'number' || ratio < 0) {
return undefined;
}
const risk = Math.abs(entryPrice - this.stopPrice);
const direction = this.side === 'long' ? 1 : -1;
return this.normalizeTarget(entryPrice, entryPrice + risk * ratio * direction);
}
private handleChartClick(params: MouseEventParams<Time>): void {
// todo: привести к общему виду дровингов как handleChartClick => startDrawing
if (this.hidden || !params.point || this.mode !== 'idle') {
return;
}
const anchor = this.createAnchor(params);
if (!anchor) {
return;
}
const distance = this.getInitialZoneDistance(anchor.price, params.point.y);
if (distance === null) {
this.mode = 'ready';
this.resolveReady?.();
this.removeSelf?.();
return;
}
const stopDirection = this.side === 'long' ? -1 : 1;
const targetDirection = -stopDirection;
this.startTime = anchor.time;
this.endTime = this.shiftTime(anchor.time, INITIAL_WIDTH_PX) ?? anchor.time;
this.entryPrice = anchor.price;
this.stopPrice = this.normalizeStop(anchor.price, anchor.price + distance * stopDirection);
this.targetPrice = this.normalizeTarget(
anchor.price,
anchor.price + distance * targetDirection * DEFAULT_RISK_REWARD_RATIO,
);
this.mode = 'ready';
this.resolveReady?.();
this.render();
}
private applyDrag(point: Point): void {
const snapshot = this.dragStateSnapshot;
if (!snapshot) {
return;
}
switch (this.activeDragTarget) {
case 'body':
this.moveWhole(snapshot, point);
break;
case 'entry':
this.moveEntry(snapshot, point);
break;
case 'target':
this.moveTarget(snapshot, point);
break;
case 'stop':
this.moveStop(snapshot, point);
break;
case 'end':
this.resizeEnd(snapshot, point);
break;
default:
break;
}
}
private moveEntry(snapshot: SliderPositionState, point: Point): void {
if (snapshot.stopPrice === null || snapshot.targetPrice === null) {
return;
}
const nextPrice = getPriceFromYCoordinate(this.series, point.y);
if (nextPrice === null) {
return;
}
const minDistance = getPricePrecisionStep();
const minPrice = this.side === 'long' ? snapshot.stopPrice + minDistance : snapshot.targetPrice;
const maxPrice = this.side === 'long' ? snapshot.targetPrice : snapshot.stopPrice - minDistance;
if (minPrice > maxPrice) {
return;
}
this.entryPrice = Math.max(minPrice, Math.min(nextPrice, maxPrice));
}
private moveWhole(snapshot: SliderPositionState, point: Point): void {
if (snapshot.startTime === null || snapshot.endTime === null) {
return;
}
if (
snapshot.entryPrice === null ||
snapshot.stopPrice === null ||
snapshot.targetPrice === null ||
!this.dragStartPoint
) {
return;
}
const timeOffset = point.x - this.dragStartPoint.x;
const priceOffset = getPriceDeltaFromCoordinates(this.series, this.dragStartPoint.y, point.y);
const nextStartTime = this.shiftTime(snapshot.startTime, timeOffset);
const nextEndTime = this.shiftTime(snapshot.endTime, timeOffset);
if (nextStartTime === null || nextEndTime === null) {
return;
}
let nextEntryPrice = snapshot.entryPrice + priceOffset;
let nextStopPrice = snapshot.stopPrice + priceOffset;
let nextTargetPrice = snapshot.targetPrice + priceOffset;
const range = getPriceRangeInContainer(this.series, this.container);
if (range) {
const minValue = Math.min(nextEntryPrice, nextStopPrice, nextTargetPrice);
const maxValue = Math.max(nextEntryPrice, nextStopPrice, nextTargetPrice);
if (minValue < range.min) {
const shift = range.min - minValue;
nextEntryPrice += shift;
nextStopPrice += shift;
nextTargetPrice += shift;
}
if (maxValue > range.max) {
const shift = maxValue - range.max;
nextEntryPrice -= shift;
nextStopPrice -= shift;
nextTargetPrice -= shift;
}
}
this.startTime = nextStartTime;
this.endTime = nextEndTime;
this.entryPrice = nextEntryPrice;
this.stopPrice = nextStopPrice;
this.targetPrice = nextTargetPrice;
}
private moveStop(snapshot: SliderPositionState, point: Point): void {
if (snapshot.entryPrice === null) {
return;
}
const nextPrice = getPriceFromYCoordinate(this.series, point.y);
if (nextPrice === null) {
return;
}
this.stopPrice = this.normalizeStop(snapshot.entryPrice, this.clampPriceToRange(nextPrice));
}
private moveTarget(snapshot: SliderPositionState, point: Point): void {
if (snapshot.entryPrice === null) {
return;
}
const nextPrice = getPriceFromYCoordinate(this.series, point.y);
if (nextPrice === null) {
return;
}
this.targetPrice = this.normalizeTarget(snapshot.entryPrice, this.clampPriceToRange(nextPrice));
}
private resizeEnd(snapshot: SliderPositionState, point: Point): void {
const nextEndTime = getTimeFromXCoordinate(this.chart, point.x);
if (nextEndTime === null) {
return;
}
this.startTime = snapshot.startTime;
this.endTime = nextEndTime;
}
private createAnchor(params: MouseEventParams<Time>): { time: Time; price: number } | null {
if (!params.point || params.time === undefined) {
return null;
}
const price = getPriceFromYCoordinate(this.series, params.point.y);
if (price === null) {
return null;
}
return {
time: params.time,
price,
};
}
private normalizeStop(entryPrice: number, price: number): number {
const minDistance = getPricePrecisionStep();
return this.side === 'long' ? Math.min(price, entryPrice - minDistance) : Math.max(price, entryPrice + minDistance);
}
private normalizeTarget(entryPrice: number, price: number): number {
return this.side === 'long' ? Math.max(price, entryPrice) : Math.min(price, entryPrice);
}
private clampPriceToRange(price: number): number {
const range = getPriceRangeInContainer(this.series, this.container);
if (!range) {
return price;
}
return Math.max(range.min, Math.min(price, range.max));
}
private getInitialZoneDistance(entryPrice: number, entryY: number): number | null {
const { height } = this.container.getBoundingClientRect();
const availableOffset = Math.min(entryY, height - entryY) - HIT_TOLERANCE;
const offset = Math.min(INITIAL_ZONE_OFFSET_PX, availableOffset);
if (offset <= 0) {
return null;
}
const upperPrice = getPriceFromYCoordinate(this.series, entryY - offset);
const lowerPrice = getPriceFromYCoordinate(this.series, entryY + offset);
if (upperPrice === null || lowerPrice === null) {
return null;
}
const minPrice = Math.min(upperPrice, lowerPrice);
const maxPrice = Math.max(upperPrice, lowerPrice);
const stopDistance = this.side === 'long' ? entryPrice - minPrice : maxPrice - entryPrice;
const targetDistance = this.side === 'long' ? maxPrice - entryPrice : entryPrice - minPrice;
if (stopDistance <= 0 || targetDistance <= 0) {
return null;
}
const distance = Math.min(stopDistance, targetDistance / DEFAULT_RISK_REWARD_RATIO);
return distance >= getPricePrecisionStep() ? distance : null;
}
private shiftTime(time: Time, offsetX: number): Time | null {
return shiftTimeByPixels(this.chart, time, offsetX, this.series);
}
private getCurrentRiskRewardRatio(): number {
if (this.entryPrice === null || this.stopPrice === null || this.targetPrice === null) {
return DEFAULT_RISK_REWARD_RATIO;
}
const risk = Math.abs(this.entryPrice - this.stopPrice);
if (risk === 0) {
return 0;
}
return Math.abs(this.targetPrice - this.entryPrice) / risk;
}
private getPriceAtTime(time: Time | null): number | null {
if (typeof time !== 'number') {
return null;
}
const data = this.series.data() ?? [];
let lastPrice: number | null = null;
for (const item of data) {
if (typeof item.time !== 'number') {
continue;
}
if (item.time > time) {
break;
}
if ('close' in item && typeof item.close === 'number') {
lastPrice = item.close;
} else if ('value' in item && typeof item.value === 'number') {
lastPrice = item.value;
}
}
return lastPrice;
}
protected getGeometry(): SliderGeometry | null {
if (
this.startTime === null ||
this.endTime === null ||
this.entryPrice === null ||
this.stopPrice === null ||
this.targetPrice === null
) {
return null;
}
const startX = getXCoordinateFromTime(this.chart, this.startTime, this.series);
const endX = getXCoordinateFromTime(this.chart, this.endTime, this.series);
const entryY = getYCoordinateFromPrice(this.series, this.entryPrice);
const stopY = getYCoordinateFromPrice(this.series, this.stopPrice);
const targetY = getYCoordinateFromPrice(this.series, this.targetPrice);
if (startX === null || endX === null || entryY === null || stopY === null || targetY === null) {
return null;
}
const start = Number(startX);
const end = Number(endX);
const entry = Number(entryY);
const stop = Number(stopY);
const target = Number(targetY);
return {
startX: start,
endX: end,
leftX: Math.min(start, end),
rightX: Math.max(start, end),
entryY: entry,
stopY: stop,
targetY: target,
entryPrice: this.entryPrice,
stopPrice: this.stopPrice,
targetPrice: this.targetPrice,
profitTop: Math.min(target, entry),
profitBottom: Math.max(target, entry),
lossTop: Math.min(stop, entry),
lossBottom: Math.max(stop, entry),
};
}
private getPositionArguments(): SliderPositionArguments {
const entryPrice = this.entryPrice ?? 0;
return {
entryPrice,
targetPrice: this.targetPrice ?? entryPrice,
stopPrice: this.stopPrice ?? entryPrice,
};
}
private applyPositionArguments(values: Partial<SliderPositionArguments>): void {
if (typeof values.entryPrice === 'number') {
this.entryPrice = values.entryPrice;
}
if (this.entryPrice === null) {
return;
}
if (typeof values.targetPrice === 'number') {
this.targetPrice = this.normalizeTarget(this.entryPrice, values.targetPrice);
} else if (this.targetPrice !== null) {
this.targetPrice = this.normalizeTarget(this.entryPrice, this.targetPrice);
}
if (typeof values.stopPrice === 'number') {
this.stopPrice = this.normalizeStop(this.entryPrice, values.stopPrice);
} else if (this.stopPrice !== null) {
this.stopPrice = this.normalizeStop(this.entryPrice, this.stopPrice);
}
}
private getPositionMetrics(geometry: SliderGeometry, selectedPrice: number | null): PositionMetrics {
const riskDistance = Math.abs(geometry.entryPrice - geometry.stopPrice);
const rewardDistance = Math.abs(geometry.targetPrice - geometry.entryPrice);
const { accountSize, risk, lotSize, leverage, quantityPrecision } = this.settings;
if (riskDistance === 0 || geometry.entryPrice <= 0) {
return {
qty: 0,
targetAmount: accountSize,
stopAmount: accountSize,
riskRewardRatio: 0,
openPnl: this.getOpenPnl(geometry.entryPrice, selectedPrice),
};
}
const riskSize = (risk / 100) * accountSize;
const qtyRisk = riskSize / riskDistance / lotSize;
const qtyLeverage = (accountSize * leverage) / geometry.entryPrice / lotSize;
const qty = round(Math.min(qtyRisk, qtyLeverage), quantityPrecision);
const multiplier = lotSize;
return {
qty,
targetAmount: accountSize + rewardDistance * qty * multiplier,
stopAmount: accountSize - riskDistance * qty * multiplier,
riskRewardRatio: rewardDistance / riskDistance,
openPnl: this.getOpenPnl(geometry.entryPrice, selectedPrice),
};
}
private getOpenPnl(entryPrice: number, selectedPrice: number | null): number {
if (selectedPrice === null) {
return 0;
}
return this.side === 'long' ? selectedPrice - entryPrice : entryPrice - selectedPrice;
}
private getTargetText(geometry: SliderGeometry, amount: number): string {
const diff = Math.abs(geometry.targetPrice - geometry.entryPrice);
const percent = geometry.entryPrice !== 0 ? (diff / Math.abs(geometry.entryPrice)) * 100 : 0;
const formattedDiff = formatPrice(diff) ?? '0';
const formattedAmount = formatPrice(amount, 2) ?? '0';
return `${t('Target')}: ${formattedDiff} (${formatPercent(percent)}), ${t('Amount')}: ${formattedAmount}`;
}
private getCenterText(metrics: PositionMetrics): string {
const formattedQty = formatPrice(metrics.qty, this.settings.quantityPrecision) ?? '0';
const formattedRatio = formatPrice(metrics.riskRewardRatio, getPercentPrecision()) ?? '0';
return [
`${t('Open P&L')}: ${formatSignedNumber(metrics.openPnl)}, ${t('Qty')}: ${formattedQty}`,
`${t('Risk/Reward Ratio')}: ${formattedRatio}`,
].join('\n');
}
private getStopText(geometry: SliderGeometry, amount: number): string {
const diff = Math.abs(geometry.stopPrice - geometry.entryPrice);
const percent = geometry.entryPrice !== 0 ? (diff / Math.abs(geometry.entryPrice)) * 100 : 0;
const formattedDiff = formatPrice(diff) ?? '0';
const formattedAmount = formatPrice(amount, 2) ?? '0';
return `${t('Stop')}: ${formattedDiff} (${formatPercent(percent)}), ${t('Amount')}: ${formattedAmount}`;
}
private getHandleTarget(point: Point): DragTarget {
const geometry = this.getGeometry();
if (!geometry) {
return null;
}
const startHandle = this.getStartPriceHandleTarget(point, geometry);
if (startHandle) {
return startHandle;
}
const handle = this.getDrawingHandleAtPoint(point);
if (handle) {
return handle.id;
}
const bounds: Bounds = {
left: geometry.leftX,
right: geometry.rightX,
top: Math.min(geometry.targetY, geometry.stopY),
bottom: Math.max(geometry.targetY, geometry.stopY),
};
return isPointInBounds(point, bounds) ? 'body' : null;
}
private getStartPriceHandleTarget(point: Point, geometry: SliderGeometry): SliderHandleId | null {
if (Math.abs(point.x - geometry.startX) > HIT_TOLERANCE) {
return null;
}
const entryDistance = Math.abs(point.y - geometry.entryY);
if (entryDistance < 1) {
return 'entry';
}
const pointerSide = Math.sign(point.y - geometry.entryY);
const targetSide = Math.sign(geometry.targetY - geometry.entryY) || -Math.sign(geometry.stopY - geometry.entryY);
if (targetSide === 0) {
return entryDistance <= HIT_TOLERANCE ? 'entry' : null;
}
const isTargetSide = pointerSide === targetSide;
const handleY = isTargetSide ? geometry.targetY : geometry.stopY;
if (Math.abs(point.y - handleY) <= HIT_TOLERANCE) {
return isTargetSide ? 'target' : 'stop';
}
return entryDistance <= HIT_TOLERANCE ? 'entry' : null;
}
private containsPoint(point: Point): boolean {
const geometry = this.getGeometry();
if (!geometry) {
return false;
}
const bounds: Bounds = {
left: geometry.leftX,
right: geometry.rightX,
top: Math.min(geometry.targetY, geometry.stopY),
bottom: Math.max(geometry.targetY, geometry.stopY),
};
return isPointInBounds(point, bounds, HIT_TOLERANCE);
}
}
import { CanvasRenderingTarget2D } from 'fancy-canvas';
import { drawRoundedRect } from '@core/Drawings/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';
import type { SliderPositionStyle } from './settings';
import type { SliderPosition } from './sliderPosition';
import type { IPrimitivePaneRenderer } from 'lightweight-charts';
const UI = {
lineHeightMultiplier: 1.2,
mainBoxHeight: 28,
sideBoxHeight: 16,
padding: 4,
boxRadius: 4,
labelOffset: 10,
};
export class SliderPaneRenderer implements IPrimitivePaneRenderer {
private readonly slider: SliderPosition;
constructor(slider: SliderPosition) {
this.slider = slider;
}
public draw(target: CanvasRenderingTarget2D): void {
const data = this.slider.getRenderData();
if (!data) {
return;
}
target.useBitmapCoordinateSpace(({ context, horizontalPixelRatio, verticalPixelRatio, bitmapSize }) => {
const left = data.leftX * horizontalPixelRatio;
const right = data.rightX * horizontalPixelRatio;
const entryY = data.entryY * verticalPixelRatio;
const stopY = data.stopY * verticalPixelRatio;
const targetY = data.targetY * verticalPixelRatio;
const profitTop = data.profitTop * verticalPixelRatio;
const profitBottom = data.profitBottom * verticalPixelRatio;
const lossTop = data.lossTop * verticalPixelRatio;
const lossBottom = data.lossBottom * verticalPixelRatio;
const centerX = (left + right) / 2;
const labelOffset = UI.labelOffset * verticalPixelRatio;
const targetBoxHeight = getTextBoxHeight(data.targetText, data, UI.sideBoxHeight, verticalPixelRatio);
const centerBoxHeight = getTextBoxHeight(data.centerText, data, UI.mainBoxHeight, verticalPixelRatio);
const stopBoxHeight = getTextBoxHeight(data.stopText, data, UI.sideBoxHeight, verticalPixelRatio);
const targetLabelY = getOuterLabelCenterY(targetY, data.targetLabelDirection, targetBoxHeight, labelOffset);
const stopLabelY = getOuterLabelCenterY(stopY, data.stopLabelDirection, stopBoxHeight, labelOffset);
const centerLabelY = getCenterLabelCenterY(
entryY,
targetY,
stopY,
centerBoxHeight,
labelOffset,
bitmapSize.height,
);
context.save();
context.fillStyle = data.positiveFillColor;
context.fillRect(left, profitTop, right - left, profitBottom - profitTop);
context.fillStyle = data.negativeFillColor;
context.fillRect(left, lossTop, right - left, lossBottom - lossTop);
context.lineWidth = data.lineWidth * Math.max(horizontalPixelRatio, verticalPixelRatio);
drawHorizontalLine(context, left, right, targetY, removeAlphaFromHex(data.positiveFillColor));
drawHorizontalLine(context, left, right, entryY, data.lineColor);
drawHorizontalLine(context, left, right, stopY, removeAlphaFromHex(data.negativeFillColor));
if (data.showLabels) {
drawTextBox(
context,
centerX,
targetLabelY,
data.targetText,
data.positiveFillColor,
data,
horizontalPixelRatio,
verticalPixelRatio,
UI.sideBoxHeight,
);
drawTextBox(
context,
centerX,
centerLabelY,
data.centerText,
data.centerBoxColor,
data,
horizontalPixelRatio,
verticalPixelRatio,
UI.mainBoxHeight,
);
drawTextBox(
context,
centerX,
stopLabelY,
data.stopText,
data.negativeFillColor,
data,
horizontalPixelRatio,
verticalPixelRatio,
UI.sideBoxHeight,
);
}
context.restore();
});
}
}
function getOuterLabelCenterY(
coordinate: number,
direction: 'up' | 'down',
boxHeight: number,
labelOffset: number,
): number {
const offset = labelOffset + boxHeight / 2;
return direction === 'up' ? coordinate - offset : coordinate + offset;
}
function getCenterLabelCenterY(
entryY: number,
targetY: number,
stopY: number,
boxHeight: number,
labelOffset: number,
viewportHeight: number,
): number {
const targetSpace = Math.abs(targetY - entryY);
const stopSpace = Math.abs(stopY - entryY);
const requiredSpace = boxHeight + labelOffset * 2;
let referenceY = stopY;
if (stopSpace < requiredSpace && targetSpace >= requiredSpace) {
referenceY = targetY;
} else if (stopSpace < requiredSpace && targetSpace < requiredSpace) {
referenceY = targetSpace > stopSpace ? targetY : stopY;
}
const direction = referenceY < entryY ? -1 : 1;
return clampTextBoxCenter(entryY + direction * (labelOffset + boxHeight / 2), boxHeight, viewportHeight);
}
function clampTextBoxCenter(coordinate: number, boxHeight: number, viewportHeight: number): number {
if (viewportHeight <= boxHeight) {
return viewportHeight / 2;
}
const halfHeight = boxHeight / 2;
return Math.max(halfHeight, Math.min(coordinate, viewportHeight - halfHeight));
}
function drawHorizontalLine(
context: CanvasRenderingContext2D,
left: number,
right: number,
y: number,
color: string,
): void {
context.strokeStyle = color;
context.beginPath();
context.moveTo(left, y);
context.lineTo(right, y);
context.stroke();
}
function drawTextBox(
context: CanvasRenderingContext2D,
centerX: number,
centerY: number,
text: string,
fillColor: string,
style: SliderPositionStyle,
horizontalPixelRatio: number,
verticalPixelRatio: number,
fixedHeight: number,
): void {
context.save();
const lines = text.split('\n');
const fontSize = style.fontSize * verticalPixelRatio;
const lineHeight = Math.round(style.fontSize * UI.lineHeightMultiplier) * verticalPixelRatio;
const paddingX = UI.padding * horizontalPixelRatio;
const boxHeight = getTextBoxHeight(text, style, fixedHeight, verticalPixelRatio);
const radius = UI.boxRadius * Math.max(horizontalPixelRatio, verticalPixelRatio);
context.font = `${fontSize}px Inter, sans-serif`;
context.textAlign = 'center';
context.textBaseline = 'middle';
let maxTextWidth = 0;
for (const line of lines) {
maxTextWidth = Math.max(maxTextWidth, context.measureText(line).width);
}
const width = maxTextWidth + paddingX * 2;
const x = centerX - width / 2;
const y = centerY - boxHeight / 2;
context.fillStyle = fillColor;
context.beginPath();
drawRoundedRect(context, x, y, width, boxHeight, radius);
context.fill();
context.fillStyle = style.textColor;
if (lines.length === 1) {
context.fillText(lines[0], centerX, centerY);
context.restore();
return;
}
const textBlockHeight = lines.length * lineHeight;
const firstLineY = centerY - textBlockHeight / 2 + lineHeight / 2;
lines.forEach((line, index) => {
context.fillText(line, centerX, firstLineY + index * lineHeight);
});
context.restore();
}
function getTextBoxHeight(
text: string,
style: SliderPositionStyle,
fixedHeight: number,
verticalPixelRatio: number,
): number {
const linesCount = text.split('\n').length;
const lineHeight = Math.round(style.fontSize * UI.lineHeightMultiplier) * verticalPixelRatio;
const paddingY = UI.padding * verticalPixelRatio;
const minHeight = fixedHeight * verticalPixelRatio;
return Math.max(minHeight, linesCount * lineHeight + paddingY * 2);
}