♻️ 重构祈愿图表 close#166

* Initial plan

* Refactor wish calendar - split charts into separate components with scrollbar support

Co-authored-by: BTMuli <72692909+BTMuli@users.noreply.github.com>

* Address code review feedback - improve error handling and comments

Co-authored-by: BTMuli <72692909+BTMuli@users.noreply.github.com>

* Move chart logic to components and remove v-if guards

Co-authored-by: BTMuli <72692909+BTMuli@users.noreply.github.com>

* Fix UID switching reactivity, add scrollbar spacing, and fix download functionality

Co-authored-by: BTMuli <72692909+BTMuli@users.noreply.github.com>

* Use proper ECharts ComposeOption type declarations

Co-authored-by: BTMuli <72692909+BTMuli@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: BTMuli <72692909+BTMuli@users.noreply.github.com>
This commit is contained in:
Copilot
2025-11-22 00:11:37 +08:00
committed by GitHub
parent 45ff02b998
commit 586b506fca
4 changed files with 429 additions and 195 deletions

View File

@@ -0,0 +1,155 @@
<!-- 祈愿日历图表组件 -->
<template>
<v-chart
class="gro-chart-calendar"
:option="chartOptions"
autoresize
:theme="echartsTheme"
:init-options="{ locale: 'ZH' }"
:style="{ height: chartHeight }"
/>
</template>
<script lang="ts" setup>
import TSUserGacha from "@Sqlm/userGacha.js";
import useAppStore from "@store/app.js";
import type { HeatmapSeriesOption } from "echarts/charts.js";
import { HeatmapChart } from "echarts/charts.js";
import type {
CalendarComponentOption,
ToolboxComponentOption,
TooltipComponentOption,
VisualMapComponentOption,
} from "echarts/components.js";
import {
CalendarComponent,
ToolboxComponent,
TooltipComponent,
VisualMapComponent,
} from "echarts/components.js";
import type { ComposeOption } from "echarts/core.js";
import { use } from "echarts/core.js";
import { LabelLayout } from "echarts/features.js";
import { CanvasRenderer } from "echarts/renderers.js";
import { storeToRefs } from "pinia";
import { computed, onMounted, shallowRef, watch } from "vue";
import VChart from "vue-echarts";
use([
LabelLayout,
CanvasRenderer,
HeatmapChart,
CalendarComponent,
ToolboxComponent,
TooltipComponent,
VisualMapComponent,
]);
type GachaChartCalendarProps = { uid: string; gachaType?: string };
type EChartsOption = ComposeOption<
| CalendarComponentOption
| TooltipComponentOption
| VisualMapComponentOption
| ToolboxComponentOption
| HeatmapSeriesOption
>;
const props = defineProps<GachaChartCalendarProps>();
const { theme } = storeToRefs(useAppStore());
const chartOptions = shallowRef<EChartsOption>({});
const yearCount = shallowRef<number>(1); // 默认至少1年避免高度为0
const echartsTheme = computed<"dark" | "light">(() => (theme.value === "dark" ? "dark" : "light"));
// 根据年份数量动态计算高度每个日历约160px加上顶部空间
const chartHeight = computed<string>(() => {
const baseHeight = 120; // 顶部工具栏和 visualMap 的空间
const perYearHeight = 160; // 每个年份的日历高度
const totalHeight = baseHeight + yearCount.value * perYearHeight;
return `${totalHeight}px`;
});
/**
* @description 获取日历图表配置
* @returns {EChartsOption}
*/
async function getCalendarOptions(): Promise<EChartsOption> {
const records = await TSUserGacha.getGachaRecordsGroupByDate(props.uid, props.gachaType);
// 获取最大长度
const maxLen = Math.max(...Object.values(records).map((v) => v.length));
// 获取年份
const yearsSet = new Set(Object.keys(records).map((v) => v.split("-")[0]));
function getYearData(year: string): [string, number][] {
const res: [string, number][] = [];
for (const key in records) {
if (key.startsWith(year)) res.push([key, records[key].length]);
}
return res;
}
return {
tooltip: { position: "top" },
toolbox: {
show: true,
feature: {
restore: {},
saveAsImage: { pixelRatio: 2 },
},
},
visualMap: {
min: 0,
max: maxLen,
calculable: true,
orient: "horizontal",
left: "center",
top: "top",
},
calendar: Array.from(yearsSet).map((year, index) => ({
range: year,
cellSize: ["auto", 15],
top: 150 * index + 80,
right: 12,
})),
series: Array.from(yearsSet).map((year, index) => ({
type: "heatmap",
coordinateSystem: "calendar",
calendarIndex: index,
data: getYearData(year),
})),
};
}
async function loadChartData(): Promise<void> {
try {
const options = await getCalendarOptions();
chartOptions.value = options;
// 获取年份数量
if (options.calendar && Array.isArray(options.calendar)) {
yearCount.value = options.calendar.length || 1;
}
} catch (error) {
console.error("Failed to load calendar chart:", error);
// 保持默认值,显示基础高度
}
}
onMounted(async () => {
await loadChartData();
});
// 监听 uid 和 gachaType 变化,重新加载数据
watch(
() => [props.uid, props.gachaType],
async () => {
await loadChartData();
},
);
</script>
<style lang="css" scoped>
.gro-chart-calendar {
width: 100%;
min-height: 400px;
}
</style>

View File

@@ -0,0 +1,231 @@
<!-- 祈愿分析图表组件 -->
<template>
<v-chart
class="gro-chart-overview"
:option="chartOptions"
autoresize
:theme="echartsTheme"
:init-options="{ locale: 'ZH' }"
/>
</template>
<script lang="ts" setup>
import TSUserGacha from "@Sqlm/userGacha.js";
import useAppStore from "@store/app.js";
import type { PieSeriesOption } from "echarts/charts.js";
import { BarChart, PieChart } from "echarts/charts.js";
import type {
GridComponentOption,
LegendComponentOption,
TitleComponentOption,
ToolboxComponentOption,
TooltipComponentOption,
} from "echarts/components.js";
import {
GridComponent,
LegendComponent,
TitleComponent,
ToolboxComponent,
TooltipComponent,
} from "echarts/components.js";
import type { ComposeOption } from "echarts/core.js";
import { use } from "echarts/core.js";
import { LabelLayout } from "echarts/features.js";
import { CanvasRenderer } from "echarts/renderers.js";
import { storeToRefs } from "pinia";
import { computed, onMounted, shallowRef, watch } from "vue";
import VChart from "vue-echarts";
use([
LabelLayout,
CanvasRenderer,
BarChart,
PieChart,
GridComponent,
LegendComponent,
TitleComponent,
ToolboxComponent,
TooltipComponent,
]);
type GachaChartOverviewProps = { uid: string };
type EChartsOption = ComposeOption<
| TitleComponentOption
| TooltipComponentOption
| LegendComponentOption
| ToolboxComponentOption
| GridComponentOption
| PieSeriesOption
>;
const props = defineProps<GachaChartOverviewProps>();
const { theme } = storeToRefs(useAppStore());
const chartOptions = shallowRef<EChartsOption>({});
const echartsTheme = computed<"dark" | "light">(() => (theme.value === "dark" ? "dark" : "light"));
/**
* @description 获取整体祈愿图表配置
* @returns {EChartsOption}
*/
async function getOverviewOptions(): Promise<EChartsOption> {
const records = await TSUserGacha.getGachaRecords(props.uid);
const data: EChartsOption = {
title: [
{ text: ">> 祈愿系统大数据分析 <<", left: "center", top: "5%" },
{ text: "卡池分布", left: "17%", top: "45%" },
{ text: "星级分布", left: "17%", top: "90%" },
{ text: "角色池分布", left: "45%", bottom: "10%" },
{ text: "武器池分布", right: "5%", bottom: "10%" },
],
tooltip: { trigger: "item" },
legend: { type: "scroll", orient: "vertical", left: 10, top: 20, bottom: 20 },
toolbox: {
show: true,
feature: {
restore: {},
saveAsImage: { pixelRatio: 2 },
},
},
series: [
{
name: "卡池分布",
type: "pie",
radius: "50%",
data: [],
emphasis: {
itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgba(0, 0, 0, 0.5)" },
},
right: "60%",
top: 0,
bottom: "50%",
},
{
name: "星级分布",
type: "pie",
radius: "50%",
data: [],
right: "60%",
top: "50%",
bottom: "0",
},
{
name: "角色池分布",
type: "pie",
radius: [30, 150],
center: ["50%", "50%"],
roseType: "area",
itemStyle: { borderRadius: [2, 10] },
data: [],
datasetIndex: 3,
},
{
name: "武器池分布",
type: "pie",
radius: [30, 100],
itemStyle: { borderRadius: [3, 10] },
data: [],
left: "70%",
},
],
};
if (data.title !== undefined && Array.isArray(data.title)) {
data.title[0].subtext = `${records.length} 条数据`;
}
if (data.series !== undefined && Array.isArray(data.series)) {
data.series[0].data = [
{
value: records.filter((item) => item.uigfType === "100").length,
name: "新手祈愿",
},
{
value: records.filter((item) => item.uigfType === "200").length,
name: "常驻祈愿",
},
{
value: records.filter((item) => item.uigfType === "301").length,
name: "角色活动祈愿",
},
{
value: records.filter((item) => item.uigfType === "302").length,
name: "武器活动祈愿",
},
{
value: records.filter((item) => item.uigfType === "500").length,
name: "集录祈愿",
},
];
data.series[1].data = [
{ value: records.filter((item) => item.rank === "3").length, name: "3星" },
{ value: records.filter((item) => item.rank === "4").length, name: "4星" },
{ value: records.filter((item) => item.rank === "5").length, name: "5星" },
];
}
const tempSet = new Set<string>();
const tempRecord = new Map<string, number>();
// 角色池分析
let tempList = records.filter((item) => item.uigfType === "301");
let star3 = tempList.filter((item) => item.rank === "3").length;
if (data.title !== undefined && Array.isArray(data.title)) {
data.title[3].subtext = `${tempList.length} 条数据, 其中三星武器 ${star3}`;
}
tempList
.filter((item) => item.rank !== "3")
.forEach((item) => {
if (tempSet.has(item.name)) {
tempRecord.set(item.name, (tempRecord.get(item.name) ?? 0) + 1);
} else {
tempSet.add(item.name);
tempRecord.set(item.name, 1);
}
});
if (data.series !== undefined && Array.isArray(data.series)) {
data.series[2].data = Array.from(tempRecord).map((item) => ({ value: item[1], name: item[0] }));
}
tempSet.clear();
tempRecord.clear();
// 武器池分析
tempList = records.filter((item) => item.uigfType === "302");
star3 = tempList.filter((item) => item.rank === "3").length;
if (data.title !== undefined && Array.isArray(data.title)) {
data.title[4].subtext = `${tempList.length} 条数据,其中三星武器 ${star3}`;
}
tempList
.filter((item) => item.rank !== "3")
.forEach((item) => {
if (tempSet.has(item.name)) {
tempRecord.set(item.name, (tempRecord.get(item.name) ?? 0) + 1);
} else {
tempSet.add(item.name);
tempRecord.set(item.name, 1);
}
});
if (data.series !== undefined && Array.isArray(data.series)) {
data.series[3].data = Array.from(tempRecord).map((item) => ({ value: item[1], name: item[0] }));
}
return data;
}
async function loadChartData(): Promise<void> {
chartOptions.value = await getOverviewOptions();
}
onMounted(async () => {
await loadChartData();
});
// 监听 uid 变化,重新加载数据
watch(
() => props.uid,
async () => {
await loadChartData();
},
);
</script>
<style lang="css" scoped>
.gro-chart-overview {
width: 100%;
height: 100%;
min-height: 600px;
}
</style>

View File

@@ -0,0 +1,165 @@
<!-- 祈愿柱状图组件 -->
<template>
<v-chart
class="gro-chart-stackbar"
:option="chartOptions"
autoresize
:theme="echartsTheme"
:init-options="{ locale: 'ZH' }"
/>
</template>
<script lang="ts" setup>
import TSUserGacha from "@Sqlm/userGacha.js";
import useAppStore from "@store/app.js";
import type { BarSeriesOption } from "echarts/charts.js";
import { BarChart } from "echarts/charts.js";
import type {
DataZoomComponentOption,
GridComponentOption,
LegendComponentOption,
ToolboxComponentOption,
TooltipComponentOption,
} from "echarts/components.js";
import {
DataZoomComponent,
GridComponent,
LegendComponent,
ToolboxComponent,
TooltipComponent,
} from "echarts/components.js";
import type { ComposeOption } from "echarts/core.js";
import { use } from "echarts/core.js";
import { LabelLayout } from "echarts/features.js";
import { CanvasRenderer } from "echarts/renderers.js";
import { storeToRefs } from "pinia";
import { computed, onMounted, shallowRef, watch } from "vue";
import VChart from "vue-echarts";
use([
LabelLayout,
CanvasRenderer,
BarChart,
DataZoomComponent,
GridComponent,
LegendComponent,
ToolboxComponent,
TooltipComponent,
]);
type GachaChartStackBarProps = { uid: string; gachaType?: string };
type EChartsOption = ComposeOption<
| BarSeriesOption
| TooltipComponentOption
| ToolboxComponentOption
| LegendComponentOption
| GridComponentOption
| DataZoomComponentOption
>;
const props = defineProps<GachaChartStackBarProps>();
const { theme } = storeToRefs(useAppStore());
const chartOptions = shallowRef<EChartsOption>({});
const echartsTheme = computed<"dark" | "light">(() => (theme.value === "dark" ? "dark" : "light"));
/**
* @description 堆叠柱状图
* @returns {EChartsOption}
*/
async function getStackBarOptions(): Promise<EChartsOption> {
const records = await TSUserGacha.getGachaRecordsGroupByDate(props.uid, props.gachaType);
const dataCount = Object.keys(records).length;
const xAxis = {
type: <const>"category",
data: Object.keys(records),
axisTick: { alignWithLabel: true },
axisLine: { show: true, lineStyle: { color: "#000" } },
axisLabel: {
rotate: 45,
interval: 4,
fontSize: 12,
fontFamily: "var(--font-title)",
},
axisPointer: { type: <const>"shadow" },
};
const temp5 = [];
const temp4 = [];
const temp3 = [];
for (const key in records) {
const gachaLogs = records[key];
const star5 = gachaLogs.filter((r) => r.rank === "5").length;
const star4 = gachaLogs.filter((r) => r.rank === "4").length;
const star3 = gachaLogs.filter((r) => r.rank === "3").length;
temp5.push(star5);
temp4.push(star4);
temp3.push(star3);
}
const series: BarSeriesOption[] = [
{ data: temp5, type: "bar", stack: "a", name: "五星数量" },
{ data: temp4, type: "bar", stack: "a", name: "四星数量" },
{ data: temp3, type: "bar", stack: "a", name: "三星数量" },
];
// 添加 dataZoom 组件以支持数据量大时的缩放和滚动
const dataZoom =
dataCount > 100
? [
{
type: <const>"slider",
show: true,
xAxisIndex: [0],
start: Math.max(0, ((dataCount - 100) / dataCount) * 100),
end: 100,
bottom: "5%",
},
{
type: <const>"inside",
xAxisIndex: [0],
start: Math.max(0, ((dataCount - 100) / dataCount) * 100),
end: 100,
},
]
: undefined;
return {
tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
toolbox: {
show: true,
feature: {
restore: {},
saveAsImage: { pixelRatio: 2 },
},
},
legend: { data: ["三星数量", "四星数量", "五星数量"] },
xAxis,
yAxis: { type: "value" },
series,
dataZoom,
grid: { left: "3%", right: "3%", bottom: dataZoom ? "15%" : "3%", top: "10%" },
};
}
async function loadChartData(): Promise<void> {
chartOptions.value = await getStackBarOptions();
}
onMounted(async () => {
await loadChartData();
});
// 监听 uid 和 gachaType 变化,重新加载数据
watch(
() => [props.uid, props.gachaType],
async () => {
await loadChartData();
},
);
</script>
<style lang="css" scoped>
.gro-chart-stackbar {
width: 100%;
height: 100%;
min-height: 500px;
}
</style>

View File

@@ -1,4 +1,3 @@
<!-- TODO组件拆分 -->
<template>
<div class="gro-chart">
<div class="gro-chart-options">
@@ -15,66 +14,25 @@
width="200px"
/>
</div>
<v-chart
class="gro-chart-box"
:option="chartOptions"
autoresize
:theme="echartsTheme"
:init-options="{ locale: 'ZH' }"
v-if="chartOptions"
/>
<div class="gro-chart-container">
<gro-chart-overview v-if="curChartType === 'overview'" :uid="uid" />
<gro-chart-calendar v-if="curChartType === 'calendar'" :uid="uid" :gacha-type="gachaType" />
<gro-chart-stackbar v-if="curChartType === 'stackBar'" :uid="uid" :gacha-type="gachaType" />
</div>
</div>
</template>
<script lang="ts" setup>
// TODO: 类型声明
// about import err,see:https://github.com/apache/echarts/issues/19992
import showLoading from "@comp/func/loading.js";
import useAppStore from "@store/app.js";
import TGachaCharts from "@utils/gachaCharts.js";
import { BarChart, HeatmapChart, PieChart } from "echarts/charts.js";
import {
CalendarComponent,
DataZoomComponent,
GridComponent,
LegendComponent,
TitleComponent,
ToolboxComponent,
TooltipComponent,
VisualMapComponent,
} from "echarts/components.js";
import { use } from "echarts/core.js";
import { LabelLayout } from "echarts/features.js";
import { CanvasRenderer } from "echarts/renderers.js";
import type { EChartsOption } from "echarts/types/dist/shared.js";
import { storeToRefs } from "pinia";
import { computed, ref, shallowRef, watch } from "vue";
import VChart from "vue-echarts";
// echarts
use([
LabelLayout,
CanvasRenderer,
BarChart,
HeatmapChart,
PieChart,
CalendarComponent,
DataZoomComponent,
GridComponent,
LegendComponent,
TitleComponent,
ToolboxComponent,
TooltipComponent,
VisualMapComponent,
]);
import GroChartCalendar from "@comp/userGacha/gro-chart-calendar.vue";
import GroChartOverview from "@comp/userGacha/gro-chart-overview.vue";
import GroChartStackbar from "@comp/userGacha/gro-chart-stackbar.vue";
import { ref } from "vue";
type GachaOverviewEchartsProps = { uid: string; gachaType?: string };
type ChartsType = "overview" | "calendar" | "stackBar";
type ChartItem = { label: string; value: ChartsType };
const props = defineProps<GachaOverviewEchartsProps>();
const { theme } = storeToRefs(useAppStore());
defineProps<GachaOverviewEchartsProps>();
const chartTypes: Array<ChartItem> = [
{ label: "祈愿分析", value: "overview" },
{ label: "祈愿日历", value: "calendar" },
@@ -82,32 +40,6 @@ const chartTypes: Array<ChartItem> = [
];
const curChartType = ref<ChartsType>("overview");
const chartOptions = shallowRef<EChartsOption>();
const echartsTheme = computed<"dark" | "light">(() => (theme.value === "dark" ? "dark" : "light"));
watch(
() => curChartType.value,
() => {
getOptions();
},
{ immediate: true },
);
async function getOptions(): Promise<void> {
await showLoading.start("加载中...");
switch (curChartType.value) {
case "overview":
chartOptions.value = await TGachaCharts.overview(props.uid);
break;
case "calendar":
chartOptions.value = await TGachaCharts.calendar(props.uid, props.gachaType);
break;
case "stackBar":
chartOptions.value = await TGachaCharts.stackBar(props.uid, props.gachaType);
break;
}
await showLoading.end();
}
</script>
<style lang="css" scoped>
.gro-chart {
@@ -119,12 +51,12 @@ async function getOptions(): Promise<void> {
align-items: flex-start;
justify-content: flex-start;
gap: 10px;
overflow-y: auto;
}
.gro-chart-options {
position: relative;
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
margin-right: auto;
@@ -137,9 +69,9 @@ async function getOptions(): Promise<void> {
font-family: var(--font-title);
}
.gro-chart-box {
width: calc(100% - 8px);
height: calc(100% - 64px);
min-height: 300px;
.gro-chart-container {
width: 100%;
flex: 1;
overflow: hidden auto;
}
</style>