import { IPaneApi, IPriceScaleApi, PriceScaleMode, Time } from 'lightweight-charts';
import type { PriceScaleSide, PriceScaleSnapshot } from '@src/types/snapshot';
interface PriceScaleParams {
paneId: number;
side: PriceScaleSide;
pane: IPaneApi<Time>;
initialMode?: PriceScaleMode;
initialVisible: boolean;
hasVisibleSeriesData: () => boolean;
}
export class PriceScale {
public readonly paneId: number;
public readonly side: PriceScaleSide;
private readonly pane: IPaneApi<Time>;
private readonly hasVisibleSeriesDataCallback: () => boolean;
private mode: PriceScaleMode;
private visible: boolean;
constructor({
paneId,
side,
pane,
initialMode = PriceScaleMode.Normal,
initialVisible,
hasVisibleSeriesData,
}: PriceScaleParams) {
this.paneId = paneId;
this.side = side;
this.pane = pane;
this.mode = initialMode;
this.visible = initialVisible;
this.hasVisibleSeriesDataCallback = hasVisibleSeriesData;
const priceScale = this.getPriceScaleApi();
priceScale.applyOptions({
mode: this.mode,
autoScale: priceScale.options().autoScale ?? true,
visible: this.visible,
borderVisible: false,
});
}
public getMode(): PriceScaleMode {
return this.mode;
}
public setMode(mode: PriceScaleMode): void {
if (this.mode === mode) {
return;
}
const priceScale = this.getPriceScaleApi();
const autoScaleEnabled = priceScale.options().autoScale ?? true;
this.mode = mode;
priceScale.applyOptions({
mode,
autoScale: autoScaleEnabled,
});
}
public toggleLogarithmic(): void {
const nextMode =
this.mode === PriceScaleMode.Logarithmic
? PriceScaleMode.Normal
: PriceScaleMode.Logarithmic;
this.setMode(nextMode);
}
public isAutoScaleEnabled(): boolean {
return this.getPriceScaleApi().options().autoScale ?? true;
}
public toggleAutoScale(): void {
const priceScale = this.getPriceScaleApi();
const autoScaleEnabled = priceScale.options().autoScale ?? true;
priceScale.setAutoScale(!autoScaleEnabled);
}
public enableAutoScale(): void {
const priceScale = this.getPriceScaleApi();
if (priceScale.options().autoScale ?? true) {
return;
}
priceScale.setAutoScale(true);
}
public isVisible(): boolean {
return this.visible;
}
public setVisible(visible: boolean): void {
if (this.visible === visible) {
return;
}
this.visible = visible;
this.getPriceScaleApi().applyOptions({
visible,
borderVisible: false,
});
}
public hasVisibleSeriesData(): boolean {
return this.hasVisibleSeriesDataCallback();
}
public getSnapshot(): PriceScaleSnapshot {
return {
side: this.side,
mode: this.mode,
};
}
private getPriceScaleApi(): IPriceScaleApi {
return this.pane.priceScale(this.side);
}
}