Files
blogflare/src/lib/components/admin/AnalyticsPanel.svelte
T
seahi dddd60671f
continuous-integration/drone/push Build is passing
style: 调整分析面板的网格布局比例与内边距
2026-09-25 21:02:44 +08:00

653 lines
15 KiB
Svelte

<script lang="ts">
/* eslint-disable @typescript-eslint/no-explicit-any */
let { analyticsPromise } = $props<{
analyticsPromise: Promise<any>;
}>();
let chartCanvas = $state<HTMLCanvasElement | undefined>(undefined);
let chartInstance: any = null;
let loading = $state(true);
let trafficData: any[] = $state([]);
let d1Data: any[] = $state([]);
let r2Data: any[] = $state([]);
let missingEnvVars = $state(false);
let error = $state('');
let totalRequests = $state(0);
let totalCached = $state(0);
let totalBytes = $state(0);
let hitRate = $state(0);
let totalPV = $state(0);
let totalUV = $state(0);
let d1RowsRead = $state(0);
let d1RowsWritten = $state(0);
let r2PayloadSize = $state(0);
let d1ReadDaily = $derived(d1Data.length > 0 ? d1RowsRead / 30 : 0);
let d1ReadPercent = $derived(d1Data.length > 0 ? (d1ReadDaily / 5000000) * 100 : 0);
let d1WriteDaily = $derived(d1Data.length > 0 ? d1RowsWritten / 30 : 0);
let d1WritePercent = $derived(d1Data.length > 0 ? (d1WriteDaily / 100000) * 100 : 0);
let r2Percent = $derived(
r2Data.length > 0 ? (r2PayloadSize / (10 * 1024 * 1024 * 1024)) * 100 : 0
);
$effect(() => {
analyticsPromise
.then((data: any) => {
if (data) {
trafficData = data.traffic || [];
d1Data = data.d1 || [];
r2Data = data.r2 || [];
missingEnvVars = data.missingEnvVars || false;
if (trafficData.length > 0) {
trafficData.forEach((day: any) => {
totalRequests += day.sum.requests || 0;
totalCached += day.sum.cachedRequests || 0;
totalBytes += day.sum.bytes || 0;
totalPV += day.sum.pageViews || 0;
totalUV += day.uniq?.uniques || 0;
});
hitRate = totalRequests > 0 ? (totalCached / totalRequests) * 100 : 0;
}
if (d1Data.length > 0) {
d1Data.forEach((row: any) => {
d1RowsRead += row.sum.rowsRead || 0;
d1RowsWritten += row.sum.rowsWritten || 0;
});
}
if (r2Data.length > 0) {
r2PayloadSize = r2Data[0]?.max?.payloadSize || 0;
}
if (data.errorMsg) {
error = data.errorMsg;
}
}
loading = false;
})
.catch((err: unknown) => {
console.error(err);
error = '获取数据失败,请检查 Cloudflare 环境变量配置。';
loading = false;
});
});
$effect(() => {
if (chartCanvas && trafficData && trafficData.length > 0) {
renderChart(trafficData);
}
});
async function renderChart(data: any[]) {
if (!chartCanvas) return;
const ChartJS = await import('chart.js/auto');
const Chart = ChartJS.default || ChartJS;
const labels = data.map((d: any) => d.dimensions.date);
const requests = data.map((d: any) => d.sum.requests);
const pvs = data.map((d: any) => d.sum.pageViews);
if (chartInstance) {
chartInstance.destroy();
}
chartInstance = new Chart(chartCanvas, {
type: 'line',
data: {
labels,
datasets: [
{
label: '总请求数',
data: requests,
borderColor: '#333',
backgroundColor: 'rgba(0,0,0,0.05)',
tension: 0.3,
fill: true,
yAxisID: 'y'
},
{
label: '页面浏览量 (PV)',
data: pvs,
borderColor: '#2196F3',
backgroundColor: 'rgba(33, 150, 243, 0.1)',
tension: 0.3,
fill: true,
yAxisID: 'y1'
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'index',
intersect: false
},
plugins: {
tooltip: {
mode: 'index',
intersect: false
}
},
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
beginAtZero: true
},
y1: {
type: 'linear',
display: true,
position: 'right',
beginAtZero: true,
grid: {
drawOnChartArea: false
}
}
}
}
});
}
function formatBytes(bytes: number) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function formatNumber(num: number) {
if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
return num.toString();
}
</script>
<div class="analytics-panel">
{#if loading}
<div class="loading-state">
<div class="spinner"></div>
<p>正在从 Cloudflare 获取最近 30 天流量数据...</p>
</div>
{:else if error}
<div class="error-state">
{error}
</div>
{:else if !trafficData || trafficData.length === 0}
<div class="empty-state">
没有获取到有效的流量数据,请确保 CF_API_TOKEN 和 CF_ZONE_ID 配置正确,且网站已有访问。
</div>
{:else}
<div class="section-title">30天访问流量</div>
<div class="dashboard-grid">
<div class="chart-container">
<div class="canvas-wrapper">
<canvas bind:this={chartCanvas}></canvas>
</div>
</div>
<div class="core-metrics">
<div class="metric-item">
<div class="metric-title">
<span class="metric-icon" style="color: #2196F3; background: rgba(33,150,243,0.1)">
<svg
viewBox="0 0 24 24"
width="14"
height="14"
stroke="currentColor"
stroke-width="2"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle
cx="12"
cy="12"
r="3"
></circle></svg
>
</span>
页面浏览 (PV)
</div>
<div class="metric-value" style="color: #2196F3">{totalPV.toLocaleString()}</div>
<div class="metric-subtitle">近 30 天累计访问量</div>
</div>
<div class="metric-item">
<div class="metric-title">
<span class="metric-icon">
<svg
viewBox="0 0 24 24"
width="14"
height="14"
stroke="currentColor"
stroke-width="2"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle
cx="12"
cy="7"
r="4"
></circle></svg
>
</span>
独立访客 (UV)
</div>
<div class="metric-value">{totalUV.toLocaleString()}</div>
<div class="metric-subtitle">近 30 天去重访客数</div>
</div>
<div class="metric-item">
<div class="metric-title">
<span class="metric-icon">
<svg
viewBox="0 0 24 24"
width="14"
height="14"
stroke="currentColor"
stroke-width="2"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
><rect x="2" y="2" width="20" height="8" rx="2" ry="2"></rect><rect
x="2"
y="14"
width="20"
height="8"
rx="2"
ry="2"
></rect><line x1="6" y1="6" x2="6.01" y2="6"></line><line
x1="6"
y1="18"
x2="6.01"
y2="18"
></line></svg
>
</span>
消耗总带宽
</div>
<div class="metric-value">{formatBytes(totalBytes)}</div>
<div class="metric-subtitle">包含网页及所有静态资源</div>
</div>
<div class="metric-item">
<div class="metric-title">
<span class="metric-icon" style="color: #4caf50; background: rgba(76,175,80,0.1)">
<svg
viewBox="0 0 24 24"
width="14"
height="14"
stroke="currentColor"
stroke-width="2"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg
>
</span>
缓存命中率
</div>
<div class="metric-value" style="color: #4caf50">{hitRate.toFixed(1)}%</div>
<div class="metric-subtitle">由 Cloudflare CDN 成功拦截</div>
</div>
</div>
</div>
<div class="section-title">Cloudflare 资源配额</div>
{#if missingEnvVars}
<div class="info-alert">
提示:如需正常获取 D1 和 R2 数据,请确保在环境变量中配置 <code>CF_ACCOUNT_ID</code>,
<code>CF_D1_ID</code>
和 <code>CF_R2_BUCKET</code>。
</div>
{/if}
<div class="quota-container">
<!-- D1 Read -->
<div class="quota-item">
<div class="quota-header">
<div class="quota-title">
D1 数据库日均读取 <span class="badge">基于近30天平均</span>
</div>
<div class="quota-numbers">
{d1Data.length > 0 ? formatNumber(d1ReadDaily) : '-'}
<span class="quota-max">/ 5M</span>
</div>
</div>
<div class="quota-bar-bg">
<div
class="quota-bar-fill {d1ReadPercent > 90
? 'danger'
: d1ReadPercent > 70
? 'warning'
: 'safe'}"
style="width: {Math.min(d1ReadPercent, 100)}%"
></div>
</div>
<div class="quota-footer">
<span>{d1ReadPercent < 1 ? '当前用量极低,非常健康' : '状态健康'}</span>
<span
>{d1ReadPercent < 0.01 && d1Data.length > 0
? '< 0.01'
: d1ReadPercent.toFixed(2)}%</span
>
</div>
</div>
<!-- D1 Write -->
<div class="quota-item">
<div class="quota-header">
<div class="quota-title">
D1 数据库日均写入 <span class="badge">基于近30天平均</span>
</div>
<div class="quota-numbers">
{d1Data.length > 0 ? formatNumber(d1WriteDaily) : '-'}
<span class="quota-max">/ 100K</span>
</div>
</div>
<div class="quota-bar-bg">
<div
class="quota-bar-fill {d1WritePercent > 90
? 'danger'
: d1WritePercent > 70
? 'warning'
: 'safe'}"
style="width: {Math.min(d1WritePercent, 100)}%"
></div>
</div>
<div class="quota-footer">
<span>{d1WritePercent < 1 ? '日常管理几乎不消耗额度' : '状态健康'}</span>
<span
>{d1WritePercent < 0.01 && d1Data.length > 0
? '< 0.01'
: d1WritePercent.toFixed(2)}%</span
>
</div>
</div>
<!-- R2 Storage -->
<div class="quota-item">
<div class="quota-header">
<div class="quota-title">R2 存储空间用量 <span class="badge">当前峰值</span></div>
<div class="quota-numbers">
{r2Data.length > 0 ? formatBytes(r2PayloadSize) : '-'}
<span class="quota-max">/ 10 GB</span>
</div>
</div>
<div class="quota-bar-bg">
<div
class="quota-bar-fill {r2Percent > 90 ? 'danger' : r2Percent > 70 ? 'warning' : 'safe'}"
style="width: {Math.min(r2Percent, 100)}%"
></div>
</div>
<div class="quota-footer">
<span>{r2Percent < 1 ? '距离10GB免费上限还有海量空间' : '状态健康'}</span>
<span>{r2Percent < 0.01 && r2Data.length > 0 ? '< 0.01' : r2Percent.toFixed(2)}%</span>
</div>
</div>
</div>
{/if}
</div>
<style>
.analytics-panel {
display: flex;
flex-direction: column;
gap: 30px;
}
.section-title {
font-size: 1.25rem;
font-weight: 700;
color: var(--text-color);
margin-bottom: -15px;
display: flex;
align-items: center;
gap: 8px;
}
.info-alert {
padding: 12px 16px;
background: rgba(33, 150, 243, 0.1);
border-left: 4px solid #2196f3;
border-radius: 4px;
font-size: 0.9rem;
color: var(--text-color);
margin-bottom: 5px;
}
.info-alert code {
background: rgba(0, 0, 0, 0.05);
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}
.dashboard-grid {
display: grid;
grid-template-columns: 7fr 3fr; /* 增加图表宽度,缩小右侧网格 */
gap: 0;
border: 2px solid var(--text-color, #000);
background: transparent;
}
@media (max-width: 900px) {
.dashboard-grid {
grid-template-columns: 1fr;
}
}
.chart-container {
padding: 20px;
display: flex;
flex-direction: column;
}
.canvas-wrapper {
position: relative;
flex: 1;
min-height: 250px;
width: 100%;
}
.core-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
border-left: 2px solid var(--text-color, #000);
}
@media (max-width: 900px) {
.core-metrics {
border-left: none;
border-top: 2px solid var(--text-color, #000);
}
}
.metric-item {
padding: 20px 16px; /* 减小内边距,适应更窄的宽度 */
display: flex;
flex-direction: column;
gap: 6px;
justify-content: center;
min-width: 0;
}
/* 为 2x2 网格绘制内部边框 */
.metric-item:nth-child(1),
.metric-item:nth-child(2) {
border-bottom: 2px solid var(--text-color, #000);
}
.metric-item:nth-child(1),
.metric-item:nth-child(3) {
border-right: 2px solid var(--text-color, #000);
}
@media (max-width: 600px) {
.core-metrics {
grid-template-columns: 1fr;
}
.metric-item:nth-child(1),
.metric-item:nth-child(3) {
border-right: none;
}
.metric-item:nth-child(1),
.metric-item:nth-child(2),
.metric-item:nth-child(3) {
border-bottom: 2px solid var(--text-color, #000);
}
}
.metric-title {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-muted, rgba(0, 0, 0, 0.6));
display: flex;
align-items: center;
}
.metric-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
background: rgba(0, 0, 0, 0.06);
border-radius: 4px;
margin-right: 6px;
color: var(--text-color, #000);
}
.metric-value {
font-size: 1.6rem;
font-weight: 800;
font-family: monospace;
}
.metric-subtitle {
font-size: 0.7rem;
color: var(--text-muted, rgba(0, 0, 0, 0.4));
margin-top: 2px;
}
.quota-container {
border: 2px solid var(--text-color, #000);
background: transparent;
display: flex;
flex-direction: column;
}
.quota-item {
padding: 24px;
border-bottom: 2px solid var(--text-color, #000);
}
.quota-item:last-child {
border-bottom: none;
}
.quota-header {
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: 12px;
}
.quota-title {
font-weight: 600;
font-size: 1rem;
display: flex;
align-items: center;
gap: 10px;
}
.badge {
font-size: 0.75rem;
font-weight: 400;
background: rgba(0, 0, 0, 0.05);
border: 1px solid var(--text-color, #000);
padding: 2px 8px;
border-radius: 12px;
color: var(--text-muted, rgba(0, 0, 0, 0.6));
}
.quota-numbers {
font-size: 1.1rem;
font-weight: 700;
font-family: monospace;
}
.quota-max {
color: var(--text-muted, rgba(0, 0, 0, 0.5));
font-weight: 500;
font-size: 0.9rem;
}
.quota-bar-bg {
width: 100%;
height: 10px;
background: rgba(0, 0, 0, 0.1);
border: 1px solid var(--text-color, #000);
border-radius: 6px;
overflow: hidden;
}
.quota-bar-fill {
height: 100%;
transition: width 1s ease-out;
}
.quota-bar-fill.safe {
background: #4caf50;
}
.quota-bar-fill.warning {
background: #ff9800;
}
.quota-bar-fill.danger {
background: #e53935;
}
.quota-footer {
display: flex;
justify-content: space-between;
margin-top: 8px;
font-size: 0.85rem;
color: var(--text-muted, rgba(0, 0, 0, 0.6));
}
.loading-state,
.error-state,
.empty-state {
padding: 40px;
text-align: center;
border: 2px dashed var(--border-color, rgba(0, 0, 0, 0.2));
font-weight: 500;
}
.error-state {
color: #e53935;
border-color: #e53935;
}
.spinner {
width: 30px;
height: 30px;
border: 3px solid rgba(0, 0, 0, 0.1);
border-top-color: var(--text-color, #000);
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 15px auto;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>