Загрузка данных
import { IChartApi, ISeriesApi, SeriesType } from 'lightweight-charts';
import { cloneDeep } from 'lodash-es';
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 '@core/Drawings/common';
type IDrawing = DOMObject;
interface DrawingParams extends DOMObjectParams {
drawingName: DrawingsNames;
lwcChart: IChartApi;
mainSeries: SeriesStrategies;
onDelete: (id: string) => void;
onChange: (previousState: unknown, nextState: unknown) => 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;
resetActiveTool: () => void;
}
export class Drawing extends DOMObject implements IDrawing {
private lwcDrawing: ISeriesDrawing;
private mainSeries: SeriesStrategies;
private drawingName: DrawingsNames;
private hotkeys: Hotkeys;
private onChange: DrawingParams['onChange'];
private lockedSubject: BehaviorSubject<boolean>;
private settingsSubject: BehaviorSubject<SettingsValues>;
private subscriptions = new Subscription();
private escapeUnregisterHash: string | null = null;
private deleteUnregisterHash: string | null = null;
private copyUnregisterHash: string | null = null;
constructor({
lwcChart,
name,
mainSeries,
drawingName,
id,
onDelete,
onChange,
onCopy,
zIndex,
moveUp,
moveDown,
construct,
selected$,
isSelected,
select,
deselect,
isLocked = false,
paneId,
hotkeys,
resetActiveTool,
}: DrawingParams) {
super({
id,
name,
zIndex,
onDelete,
moveUp,
moveDown,
paneId,
});
this.hotkeys = hotkeys;
this.mainSeries = mainSeries;
this.drawingName = drawingName;
this.onChange = onChange;
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.escapeUnregisterHash = hotkeys.register({
keys: [Keys.escape],
callback: () => {
this.delete();
resetActiveTool();
},
});
this.subscriptions.add(
selected$.subscribe((isSelectedDrawing) => {
if (isSelectedDrawing) {
this.deleteUnregisterHash = hotkeys.register({
keys: [Keys.delete],
callback: () => {
this.delete();
},
});
this.copyUnregisterHash = hotkeys.register({
keys: [Keys.mod, Keys.c],
callback: () => {
if (!this.isCreationPending()) {
onCopy();
}
},
});
return;
}
this.unregisterSelectedDrawingHotkeys();
}),
);
this.afterCreation(() => {
hotkeys.unregister({
keys: [Keys.escape],
hash: this.escapeUnregisterHash,
});
this.escapeUnregisterHash = null;
});
}
public delete(): void {
super.delete();
}
public getDrawingName(): DrawingsNames {
return this.drawingName;
}
public getLwcDrawing(): 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 async 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 {
const previousState = cloneDeep(this.getState());
this.lwcDrawing.updateSettings(settings);
this.onChange(
previousState,
cloneDeep(this.getState()),
);
}
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.hotkeys.unregister({
keys: [Keys.escape],
hash: this.escapeUnregisterHash,
});
this.escapeUnregisterHash = null;
this.lockedSubject.complete();
this.settingsSubject.complete();
this.mainSeries.detachPrimitive(this.lwcDrawing);
this.lwcDrawing.destroy();
}
private unregisterSelectedDrawingHotkeys(): void {
this.hotkeys.unregister({
keys: [Keys.delete],
hash: this.deleteUnregisterHash,
});
this.hotkeys.unregister({
keys: [Keys.mod, Keys.c],
hash: this.copyUnregisterHash,
});
this.deleteUnregisterHash = null;
this.copyUnregisterHash = null;
}
private async afterCreation(callback: () => void): Promise<void> {
await this.lwcDrawing.waitTillReady();
callback();
}
}
import { IChartApi, ISeriesApi, 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, Keys } 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 } from '@src/types';
import type { DrawingInteraction } from '@src/core/Drawings/common';
interface DrawingsManagerParams {
eventManager: EventManager;
mainSeries$: Observable<SeriesStrategies | null>;
lwcChart: IChartApi;
DOM: DOMModel;
container: HTMLElement;
modalRenderer: ModalRenderer;
paneId: number;
hotkeys: Hotkeys;
}
export interface DrawingSnapshotItem {
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 mainSeries: SeriesStrategies | null = null;
private subscriptions = new Subscription();
private drawings$ = new BehaviorSubject<Drawing[]>([]);
private selectedDrawing$ = new BehaviorSubject<Drawing | null>(null);
private activeTool$ = new BehaviorSubject<ActiveDrawingTool>('crosshair');
private endlessMode$ = new BehaviorSubject(false);
private recreateScheduled = false;
private pendingSnapshot: DrawingsManagerSnapshot | null = null;
private pointerDownSnapshot: DrawingsManagerSnapshot | null = null;
private paneId: number;
private hotkeys: Hotkeys;
private copyPasteBuffer: DrawingSnapshotItem | null = null;
private escapeUnregisterHash: string | null = null;
constructor({
eventManager,
mainSeries$,
lwcChart,
DOM,
container,
modalRenderer,
paneId,
hotkeys,
}: DrawingsManagerParams) {
this.DOM = DOM;
this.eventManager = eventManager;
this.paneId = paneId;
this.lwcChart = lwcChart;
this.container = container;
this.modalRenderer = modalRenderer;
this.hotkeys = hotkeys;
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;
this.setSnapshot(snapshot);
}
}),
);
window.addEventListener('pointerup', this.handlePointerUp);
window.addEventListener('pointercancel', this.handlePointerUp);
this.container.addEventListener('click', this.handleClick);
this.container.addEventListener('pointerdown', this.handlePointerDown);
// 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]
// // })
// }
// })
}
private handlePointerDown = (): void => {
this.pointerDownSnapshot = this.getSnapshot();
this.DOM.refreshEntities();
};
private handlePointerUp = (): void => {
const previousSnapshot = this.pointerDownSnapshot;
this.pointerDownSnapshot = null;
queueMicrotask(() => {
if (!previousSnapshot) {
return;
}
const nextSnapshot = new Map(
this.getSnapshot().map((drawing) => [
drawing.id,
drawing,
]),
);
this.eventManager.getUndoRedo().group(() => {
previousSnapshot.forEach((previousDrawing) => {
const nextDrawing = nextSnapshot.get(previousDrawing.id);
if (nextDrawing) {
this.pushDrawingChange(previousDrawing, nextDrawing);
}
});
});
});
this.DOM.refreshEntities();
this.updateActiveTool();
};
private handleClick = (): void => {
this.DOM.refreshEntities();
this.updateActiveTool();
};
private findDrawing(id: string): Drawing | undefined {
return this.drawings$.value.find((drawing) => drawing.id === id);
}
private createDrawingSnapshot(
drawing: Drawing,
state: unknown = drawing.getState(),
): DrawingSnapshotItem {
return {
id: drawing.id,
drawingName: drawing.getDrawingName(),
state: cloneDeep(state),
isLocked: drawing.isLocked(),
zIndex: drawing.zIndex,
};
}
private pushDrawingChange(
previousSnapshot: DrawingSnapshotItem | null,
nextSnapshot: DrawingSnapshotItem | null,
): void {
if (isEqual(previousSnapshot, nextSnapshot)) {
return;
}
const previous = cloneDeep(previousSnapshot);
const next = cloneDeep(nextSnapshot);
this.eventManager.getUndoRedo().pushCommand({
undo: () => {
this.applyDrawingChange(next, previous);
},
redo: () => {
this.applyDrawingChange(previous, next);
},
});
}
private applyDrawingChange(
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);
if (nextSnapshot.zIndex !== undefined) {
drawing.setZIndex(nextSnapshot.zIndex);
}
this.drawings$.next(
[...this.drawings$.value].sort(
(left, right) => left.zIndex - right.zIndex,
),
);
this.DOM.refreshEntities();
return;
}
}
if (currentSnapshot) {
this.removeDrawingInternal(currentSnapshot.id, false);
}
if (nextSnapshot) {
this.restoreDrawing(nextSnapshot);
}
this.activeTool$.next('crosshair');
this.DOM.refreshEntities();
}
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.DOM.refreshEntities();
return existingDrawing;
}
return this.createDrawing(snapshot.drawingName, {
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.activeTool$.value;
const isSingleInstanceTool = activeTool !== 'crosshair' && drawingsMap[activeTool]?.singleInstance;
if (activeTool !== 'crosshair' && this.endlessMode$.value && !isSingleInstanceTool) {
if (this.recreateScheduled) {
return;
}
this.recreateScheduled = true;
queueMicrotask(() => {
this.recreateScheduled = false;
const currentTool = this.activeTool$.value;
const hasPendingAfterTick = this.drawings$.value.some((drawing) => drawing.isCreationPending());
if (currentTool === 'crosshair') {
return;
}
if (!this.endlessMode$.value) {
return;
}
if (drawingsMap[currentTool]?.singleInstance) {
return;
}
if (hasPendingAfterTick) {
return;
}
void this.addDrawingForce(currentTool);
});
return;
}
this.activeTool$.next('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 addDrawingForce = async (name: DrawingsNames): 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);
}
this.activeTool$.next(name);
const drawing = this.createDrawing(name);
this.DOM.refreshEntities();
await drawing.waitForCreation();
if (!this.findDrawing(drawing.id)) {
if (previousSnapshot) {
this.restoreDrawing(previousSnapshot);
}
return;
}
this.pushDrawingChange(
previousSnapshot,
this.createDrawingSnapshot(drawing),
);
};
private createDrawing(
name: DrawingsNames,
options: CreateDrawingOptions = {},
): Drawing {
if (!this.mainSeries) {
throw new Error('[Drawings] main series is not defined');
}
const {
id,
state,
isLocked = false,
zIndex,
shouldUpdateDrawingsList = true,
} = options;
const shouldSelectAfterCreation = state === undefined;
if (
shouldSelectAfterCreation &&
this.selectedDrawing$.value
) {
this.selectedDrawing$.next(null);
}
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 = series.getPane().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);
}
},
});
};
const drawingFactory = (
entityZIndex: number,
moveUp: (id: string) => void,
moveDown: (id: string) => void,
) =>
new Drawing({
lwcChart: this.lwcChart,
mainSeries: this.mainSeries as SeriesStrategies,
id: drawingId,
drawingName: name,
name: drawingLabelById()[name],
onDelete: this.removeDrawing,
onChange: (previousState, nextState) => {
if (!createdDrawing) {
return;
}
this.pushDrawingChange(
this.createDrawingSnapshot(createdDrawing, previousState),
this.createDrawingSnapshot(createdDrawing, nextState),
);
},
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,
resetActiveTool: () => {
this.activeTool$.next('crosshair');
},
});
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,
),
);
}
if (shouldSelectAfterCreation) {
entity.waitForCreation().then(() => {
if (!this.drawings$.value.includes(entity)) {
return;
}
this.selectedDrawing$.next(entity);
this.updateActiveTool();
this.DOM.refreshEntities();
});
}
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.pointerDownSnapshot = null;
this.removeDrawings(this.drawings$.value, false);
const restoredDrawings = snapshot.reduce<Drawing[]>((drawings, item) => {
if (!drawingsMap[item.drawingName]) {
return drawings;
}
drawings.push(
this.createDrawing(item.drawingName, {
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.activeTool$.next('crosshair');
this.DOM.refreshEntities();
}
public setEndlessDrawingMode = (value: boolean): void => {
if (value) {
this.escapeUnregisterHash = this.hotkeys.register({
keys: [Keys.escape],
callback: () => {
this.setEndlessDrawingMode(false);
},
});
} else {
this.hotkeys.unregister({
keys: [Keys.escape],
hash: this.escapeUnregisterHash,
});
this.escapeUnregisterHash = null;
}
this.endlessMode$.next(value);
};
public isEndlessDrawingsMode(): Observable<boolean> {
return this.endlessMode$.asObservable();
}
public getActiveTool(): Observable<ActiveDrawingTool> {
return this.activeTool$.asObservable();
}
public activateCrosshair(): void {
this.removePendingDrawings(false);
this.activeTool$.next('crosshair');
this.DOM.refreshEntities();
}
public entities(): Observable<Drawing[]> {
return this.drawings$.asObservable();
}
public selectedDrawing(): Observable<Drawing | null> {
return this.selectedDrawing$.asObservable();
}
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;
}
const previousSnapshot = this.createDrawingSnapshot(drawing);
drawing.toggleLock();
this.pushDrawingChange(
previousSnapshot,
this.createDrawingSnapshot(drawing),
);
}
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)) {
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 {
this.hotkeys.unregister({
keys: [Keys.escape],
hash: this.escapeUnregisterHash,
});
window.removeEventListener('pointerup', this.handlePointerUp);
window.removeEventListener('pointercancel', this.handlePointerUp);
this.container.removeEventListener('click', this.handleClick);
this.container.removeEventListener('pointerdown', this.handlePointerDown);
this.drawings$.value.forEach((drawing) => drawing.destroy());
this.pointerDownSnapshot = null;
this.copyPasteBuffer = null;
this.subscriptions.unsubscribe();
this.drawings$.complete();
this.selectedDrawing$.complete();
this.activeTool$.complete();
this.endlessMode$.complete();
}
}
import { BehaviorSubject, map, Observable } from 'rxjs';
import { DOM } from '@components/DOM';
import { IDOMObject } from '@core/DOMObject';
import { ModalRenderer } from '@core/ModalRenderer';
import { t } from '@src/translations';
interface DOMModelParams {
modalRenderer: ModalRenderer;
}
/**
* Абстракция над библиотекой для построения графиков
*/
export class DOMModel {
// ∈ symbol&pane
private modalRenderer: ModalRenderer;
private lastZIndex = 0;
private entities: BehaviorSubject<IDOMObject[]> = new BehaviorSubject<IDOMObject[]>([]); // drawings/indicators/series
// private panes: Panes[]; // todo: пока что на каждый пейн будет один objectTree
constructor({ modalRenderer }: DOMModelParams) {
this.modalRenderer = modalRenderer;
}
public removeEntity = <T extends IDOMObject>(entity: T): void => {
this.entities.next(this.entities.value.filter((item) => item.id !== entity.id));
};
public setEntity = <T extends IDOMObject>(
callback: (
zIndex: number,
moveUp: (id: string) => void,
moveDown: (id: string) => void,
) => T,
zIndex?: number,
): T => {
const entityZIndex = zIndex ?? this.lastZIndex;
this.lastZIndex = Math.max(
this.lastZIndex,
entityZIndex + 1,
);
const entity = callback(
entityZIndex,
this.moveUp,
this.moveDown,
);
this.entities.next(
[...this.entities.value, entity].sort(
(left, right) => left.zIndex - right.zIndex,
),
);
return entity;
};
private moveUp = (id: string): void => {
const entities = this.entities.value;
const current = entities.find((entity) => entity.id === id);
if (!current) {
return;
}
const next = entities.find((entity) => entity.zIndex === current.zIndex + 1);
if (!next) {
return;
}
const nextEntities = entities.filter(
(entity) =>
entity.id !== id &&
entity.zIndex !== current.zIndex + 1,
);
const currentZIndex = current.zIndex;
current.setZIndex(next.zIndex);
next.setZIndex(currentZIndex);
this.entities.next(
[...nextEntities, current, next].sort(
(left, right) => left.zIndex - right.zIndex,
),
);
};
private moveDown = (id: string): void => {
const entities = this.entities.value;
const current = entities.find((entity) => entity.id === id);
if (!current) {
return;
}
const previous = entities.find((entity) => entity.zIndex === current.zIndex - 1);
if (!previous) {
return;
}
const nextEntities = entities.filter(
(entity) =>
entity.id !== id &&
entity.zIndex !== current.zIndex - 1,
);
const currentZIndex = current.zIndex;
current.setZIndex(previous.zIndex);
previous.setZIndex(currentZIndex);
this.entities.next(
[...nextEntities, current, previous].sort(
(left, right) => left.zIndex - right.zIndex,
),
);
};
public getEntities = (): Observable<IDOMObject[]> => {
return this.entities.pipe(
map((entities) =>
entities.filter((entity) =>
entity.shouldShowInObjectTree(),
),
),
);
};
public refreshEntities = (): void => {
this.entities.next(
[...this.entities.value].sort(
(left, right) => left.zIndex - right.zIndex,
),
);
};
public toggleDOM = () => {
this.modalRenderer.renderComponent(
<DOM elementsObs={this.getEntities()} />,
{
title: t('DOM tree'),
onSave: () => console.warn('dom state saved'),
acceptLabel: '',
rejectLabel: '',
},
);
};
public destroy(): void {
// todo implement
}
}
import classNames from 'classnames';
import { Button, Tooltip } from 'exchange-elements/v2';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { GearIcon, LockIcon, LockOpenIcon, TrashIcon } from '@src/components/Icon';
import { ToolbarColorControl } from '@src/components/ToolbarColorControl';
import { t } from '@src/translations';
import styles from './index.module.scss';
import type { Drawing } from '@core/Drawings';
import type { SettingsValues } from '@src/types/settings';
import type { PointerEvent, SyntheticEvent } from 'react';
import type { Observable } from 'rxjs';
interface FloatingDrawingToolbarProps {
selectedDrawing$: Observable<Drawing | null>;
onToggleLock: () => void;
onOpenSettings: () => void;
onDelete: () => void;
}
interface Position {
x: number;
y: number;
}
interface DragState {
pointerId: number;
startX: number;
startY: number;
initialX: number;
initialY: number;
}
const TOOLBAR_TOP_OFFSET = 12;
export function FloatingDrawingToolbar({
selectedDrawing$,
onToggleLock,
onOpenSettings,
onDelete,
}: FloatingDrawingToolbarProps) {
const toolbarRef = useRef<HTMLDivElement | null>(null);
const dragStateRef = useRef<DragState | null>(null);
const positionRef = useRef<Position | null>(null);
const [selectedDrawing, setSelectedDrawing] = useState<Drawing | null>(null);
const [settings, setSettings] = useState<SettingsValues>({});
const [isLocked, setIsLocked] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [position, setPosition] = useState<Position | null>(null);
const shouldShowToolbar = selectedDrawing?.hasSettings() ?? false;
useEffect(() => {
const subscription = selectedDrawing$.subscribe(setSelectedDrawing);
return () => {
subscription.unsubscribe();
};
}, [selectedDrawing$]);
useEffect(() => {
if (!selectedDrawing || !shouldShowToolbar) {
setIsLocked(false);
return;
}
const subscription = selectedDrawing.subscribeIsLocked(setIsLocked);
return () => {
subscription.unsubscribe();
};
}, [selectedDrawing, shouldShowToolbar]);
useEffect(() => {
if (!selectedDrawing || !shouldShowToolbar) {
setSettings({});
return;
}
const subscription = selectedDrawing.subscribeSettings(setSettings);
return () => {
subscription.unsubscribe();
};
}, [selectedDrawing, shouldShowToolbar]);
useLayoutEffect(() => {
if (!selectedDrawing || !shouldShowToolbar) {
return;
}
const toolbar = toolbarRef.current;
const container = toolbar?.parentElement;
if (!toolbar || !container) {
return;
}
const currentPosition = positionRef.current;
if (currentPosition) {
updatePosition(
clampPosition(
currentPosition.x,
currentPosition.y,
toolbar,
container,
),
);
return;
}
updatePosition({
x: Math.round(
(container.clientWidth - toolbar.offsetWidth) / 2,
),
y: TOOLBAR_TOP_OFFSET,
});
}, [selectedDrawing, shouldShowToolbar]);
const handleDragStart = (
event: PointerEvent<HTMLButtonElement>,
): void => {
const currentPosition = positionRef.current;
if (event.button !== 0 || !currentPosition) {
return;
}
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
dragStateRef.current = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
initialX: currentPosition.x,
initialY: currentPosition.y,
};
setIsDragging(true);
};
const handleDrag = (
event: PointerEvent<HTMLButtonElement>,
): void => {
const dragState = dragStateRef.current;
const toolbar = toolbarRef.current;
const container = toolbar?.parentElement;
if (
!dragState ||
dragState.pointerId !== event.pointerId ||
!toolbar ||
!container
) {
return;
}
event.preventDefault();
updatePosition(
clampPosition(
dragState.initialX + event.clientX - dragState.startX,
dragState.initialY + event.clientY - dragState.startY,
toolbar,
container,
),
);
};
const handleDragEnd = (
event: PointerEvent<HTMLButtonElement>,
): void => {
if (dragStateRef.current?.pointerId !== event.pointerId) {
return;
}
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
dragStateRef.current = null;
setIsDragging(false);
};
const stopPropagation = (event: SyntheticEvent): void => {
event.stopPropagation();
};
function updatePosition(nextPosition: Position): void {
positionRef.current = nextPosition;
setPosition((currentPosition) => {
if (
currentPosition?.x === nextPosition.x &&
currentPosition.y === nextPosition.y
) {
return currentPosition;
}
return nextPosition;
});
}
if (!selectedDrawing || !shouldShowToolbar) {
return null;
}
const toolbarSettings = selectedDrawing.getToolbarSettings();
const lockLabel = isLocked ? t('Unlock') : t('Lock');
return (
<div
ref={toolbarRef}
className={styles.toolbar}
style={{
visibility: position ? 'visible' : 'hidden',
transform: `translate3d(${position?.x ?? 0}px, ${position?.y ?? 0}px, 0)`,
}}
onPointerDown={stopPropagation}
onClick={stopPropagation}
onDoubleClick={stopPropagation}
onContextMenu={stopPropagation}
>
<button
type="button"
className={classNames(styles.toolbar_handle, {
[styles.dragging]: isDragging,
})}
onPointerDown={handleDragStart}
onPointerMove={handleDrag}
onPointerUp={handleDragEnd}
onPointerCancel={handleDragEnd}
>
<span />
<span />
<span />
<span />
<span />
<span />
</button>
{toolbarSettings.map((field) => {
if (
field.type !== 'color' ||
field.toolbar.control !== 'color'
) {
return null;
}
return (
<ToolbarColorControl
key={field.key}
role={field.toolbar.role}
value={String(
settings[field.key] ??
field.defaultValue,
)}
onChange={(value) => {
selectedDrawing.updateSettings({
[field.key]: value,
});
}}
/>
);
})}
<Tooltip
tooltipClassName={styles.toolbar_tooltip}
showMessageOnFocus
label={t('Settings')}
location="top"
>
<Button
size="sm"
className={styles.button}
onClick={onOpenSettings}
label={<GearIcon />}
/>
</Tooltip>
<Tooltip
tooltipClassName={styles.toolbar_tooltip}
showMessageOnFocus
label={lockLabel}
location="top"
>
<Button
size="sm"
className={classNames(styles.button, {
[styles.pressed]: isLocked,
})}
onClick={onToggleLock}
label={isLocked ? <LockIcon /> : <LockOpenIcon />}
/>
</Tooltip>
<Tooltip
tooltipClassName={styles.toolbar_tooltip}
showMessageOnFocus
label={t('Remove')}
location="top"
>
<Button
size="sm"
className={styles.button}
onClick={onDelete}
label={<TrashIcon />}
/>
</Tooltip>
</div>
);
}
function clampPosition(
x: number,
y: number,
toolbar: HTMLElement,
container: HTMLElement,
): Position {
return {
x: Math.max(
0,
Math.min(
Math.round(x),
container.clientWidth - toolbar.offsetWidth,
),
),
y: Math.max(
0,
Math.min(
Math.round(y),
container.clientHeight - toolbar.offsetHeight,
),
),
};
}
export enum Keys {
'escape' = 'escape',
'delete' = 'delete',
'tab' = 'tab',
'shift' = 'shift',
'control' = 'control',
'meta' = 'meta',
'mod' = 'mod',
'alt' = 'alt',
't' = 'keyt',
'h' = 'keyh',
'v' = 'keyv',
'f' = 'keyf',
'z' = 'keyz',
'y' = 'keyy',
'c' = 'keyc',
'mousedown' = 'mousedown',
}
type HotkeyCallback = () => void | Promise<void>;
interface RegisterHotkeyParams {
keys: Keys[];
callback: HotkeyCallback;
}
interface UnregisterHotkeyParams {
keys: Keys[];
hash?: string | null;
}
interface HotkeyRegistration {
keys: Keys[];
callback: HotkeyCallback;
}
export interface IHotkeys {
register(params: RegisterHotkeyParams): string | null;
unregister(params: UnregisterHotkeyParams): void;
}
// todo: возможно можно сделать синглтоном и использовать импортируя эк земпляр класса,
// там где это нужно вместо props drilling, как сейчас
export class Hotkeys implements IHotkeys {
private registrations = new Map<string, HotkeyRegistration>();
constructor() {
document.addEventListener('keydown', this.handleKeyDown);
}
public register({
keys,
callback,
}: RegisterHotkeyParams): string | null {
if (keys.length === 0) {
console.error('[Hotkeys] попытка задать пустой хоткей');
return null;
}
const hash = `hotkeyCallback-${crypto.randomUUID()}`;
this.registrations.set(hash, {
keys,
callback,
});
return hash;
}
public unregister({
hash,
}: UnregisterHotkeyParams): void {
if (!hash) {
return;
}
this.registrations.delete(hash);
}
public destroy(): void {
document.removeEventListener('keydown', this.handleKeyDown);
this.registrations.clear();
}
private handleKeyDown = async (
event: KeyboardEvent,
): Promise<void> => {
if (
event.repeat ||
isEditableElement(event.target)
) {
return;
}
const callbacks = [...this.registrations.values()]
.filter(({ keys }) => matchesHotkey(event, keys))
.map(({ callback }) => callback)
.reverse();
if (callbacks.length === 0) {
return;
}
event.preventDefault();
for (const callback of callbacks) {
// eslint-disable-next-line no-await-in-loop
await callback();
}
};
}
function matchesHotkey(
event: KeyboardEvent,
keys: Keys[],
): boolean {
const eventKey = normalizeCode(event.code);
const primaryKeys = keys.filter(
(key) => !isModifier(key),
);
if (
primaryKeys.length !== 1 ||
primaryKeys[0] !== eventKey
) {
return false;
}
if (keys.includes(Keys.mod)) {
if (!event.ctrlKey && !event.metaKey) {
return false;
}
} else if (
event.ctrlKey !== keys.includes(Keys.control) ||
event.metaKey !== keys.includes(Keys.meta)
) {
return false;
}
return (
event.shiftKey === keys.includes(Keys.shift) &&
event.altKey === keys.includes(Keys.alt)
);
}
function isModifier(key: Keys): boolean {
return (
key === Keys.mod ||
key === Keys.control ||
key === Keys.meta ||
key === Keys.shift ||
key === Keys.alt
);
}
function normalizeCode(code: string): Keys {
switch (code.toLowerCase()) {
case 'controlleft':
case 'controlright':
return Keys.control;
case 'metaleft':
case 'metaright':
return Keys.meta;
case 'shiftleft':
case 'shiftright':
return Keys.shift;
case 'altleft':
case 'altright':
return Keys.alt;
default:
return code.toLowerCase() as Keys;
}
}
function isEditableElement(
target: EventTarget | null,
): boolean {
if (!(target instanceof HTMLElement)) {
return false;
}
return (
target.isContentEditable ||
target.closest(
'input, textarea, select, [contenteditable]',
) !== null
);
}
const drawingsManager = this.chart.getDrawingsManager();
this.drawingToolbarRenderer.renderComponent(
<FloatingDrawingToolbar
selectedDrawing$={drawingsManager.selectedDrawing()}
onToggleLock={() => drawingsManager.toggleSelectedDrawingLock()}
onOpenSettings={() => drawingsManager.openSelectedDrawingSettings()}
onDelete={() => drawingsManager.deleteSelectedDrawing()}
/>,
);
this.hotkeys = new Hotkeys();
if (config.chartCollectionPreset.undoRedoEnabled) {
const undoRedo = this.eventManager.getUndoRedo();
this.hotkeys.register({
keys: [Keys.mod, Keys.z],
callback: undoRedo.undo,
});
this.hotkeys.register({
keys: [Keys.mod, Keys.shift, Keys.z],
callback: undoRedo.redo,
});
this.hotkeys.register({
keys: [Keys.mod, Keys.y],
callback: undoRedo.redo,
});
}
this.modalRenderer = new ModalRenderer(modalContainer);