feat: 添加主题切换功能,优化图表布局设置

This commit is contained in:
2025-12-20 04:16:15 +07:00
parent b7a2c04532
commit f23c691d69

View File

@@ -1,5 +1,6 @@
import type { Awaitable } from "@vueuse/core";
import type { ChartOptions, DeepPartial, IChartApi, ISeriesApi, OhlcData, SeriesType } from "lightweight-charts";
import type { ChartOptions, DeepPartial, IChartApi, ISeriesApi, LayoutOptions, OhlcData, SeriesType } from "lightweight-charts";
import type { ThemeMode } from "./useTheme";
import { AreaSeries, BarSeries, BaselineSeries, CandlestickSeries, ColorType, createChart, HistogramSeries, LineSeries } from "lightweight-charts";
import { mergeWith } from "lodash-es";
@@ -12,13 +13,23 @@ export type WeightChartOptions = DeepPartial<ChartOptions>;
export type TradingViewData = (() => Awaitable<TData[]>) | MaybeRefOrGetter<TData[]>;
export interface TradingViewOptions<T = Series> {
theme?: "light" | "dark";
theme?: ThemeMode;
type?: T;
data?: TradingViewData;
weightChartOptions?: MaybeRefOrGetter<WeightChartOptions>;
autosize?: boolean;
}
const lightThemeLayout: Partial<LayoutOptions> = {
textColor: "black",
background: { type: ColorType.Solid, color: "#fff" },
};
const darkThemeLayout: Partial<LayoutOptions> = {
textColor: "white",
background: { type: ColorType.Solid, color: "#000" },
};
const initializeOptions: Required<TradingViewOptions> = {
theme: "dark",
type: "Candlestick",
@@ -26,10 +37,6 @@ const initializeOptions: Required<TradingViewOptions> = {
weightChartOptions: {
width: 400,
height: 300,
layout: {
textColor: "black",
background: { type: ColorType.Solid, color: "#fff" },
},
},
autosize: true,
};
@@ -53,6 +60,8 @@ function getChartSeriesDefinition(type: Series) {
}
}
const { isDark } = useTheme();
export function useTradingView(target: MaybeRefOrGetter<HTMLElement | null>, options?: TradingViewOptions) {
const opts: Required<TradingViewOptions> = mergeWith(initializeOptions, options);
const chart = ref<IChartApi | null>(null);
@@ -94,6 +103,13 @@ export function useTradingView(target: MaybeRefOrGetter<HTMLElement | null>, opt
}
}
function changeTheme(theme: ThemeMode) {
if (!chart.value)
return;
const layout = theme === "dark" ? darkThemeLayout : lightThemeLayout;
chart.value.applyOptions({ layout });
}
tryOnMounted(() => {
const el = unrefElement(target);
if (!el)
@@ -101,6 +117,9 @@ export function useTradingView(target: MaybeRefOrGetter<HTMLElement | null>, opt
chartEl.value = el;
chart.value = createChart(el, toValue(opts.weightChartOptions));
series.value = chart.value.addSeries(chartSeriesDefinition);
watch(isDark, (dark) => {
changeTheme(dark ? "dark" : "light");
}, { immediate: true });
setData(opts.data);
fitContent();