使用 ECharts 对 Statistic 界面魔改

前情提要:/post/2885718883 Hexo数据统计页面 | zhangxixi的博客

但是之前的界面比较粗糙,现在根据文档改了很多

文档入口:Documentation - Apache ECharts

主要改变

  1. 上方添加图表工具栏,支持转化、缩放、重置、查看数据、导出
  2. 对文章统计分类的旭日图进行更丰富的改变
  3. 增加文章发布热力图

效果对比

原先

Screenshot_3-7-2026_231149_zhangxixi2008.github.io

现在

Screenshot_3-7-2026_231459_localhost

更改

  1. 升级你的ECharts

由于我们使用的是api,所以在 _config.butterfly.yml 中改成:

1
- <script src="https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js"></script>
  1. 更改你的前端页面

打开 chartsindex.md

改为:

1
2
3
4
5
6
7
8
9
<!-- 文章发布时间统计图 -->
<div id="posts-chart" data-start="2021-10" style="border-radius: 8px; height: 600px; padding: 10px;"></div>
<!-- 文章标签统计图 -->
<div id="tags-chart" data-length="15" style="border-radius: 8px; height: 600px; padding: 10px;"></div>
<!-- 文章分类统计图 -->
<div id="categories-chart" data-parent="true" style="border-radius: 8px; height: 850px; width:100%; padding:10px 0;"></div>
<!-- 文章热力图 -->
<div id="calendar-chart" style="border-radius: 8px; height: 1020px; padding: 10px;"></div>

注意,height 可以根据情况设置。尤其是文章热力图,按照年份多少自行调控高度。(年份越多,生成的热力图越多)

  1. 更改后端js

\themes\butterfly\scripts\helpers\charts.js 中全部替换为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
/**
* Hexo Butterfly 主题 - 文章图表统计模块
*
* 本文件为 Hexo 博客 Butterfly 主题的辅助脚本,
* 用于在页面渲染完成后自动生成四种 ECharts 统计图表:
* 1. 文章发布统计图(时间折线图)
* 2. 标签统计图(柱状图)
* 3. 文章分类统计图(饼图/旭日图)
* 4. 文章发布热力图(日历热力图)
*
* 工作原理:
* - 注册 after_render:html 过滤器,在 HTML 渲染完成后注入图表脚本
* - 扫描页面中是否存在 #posts-chart、#tags-chart、#categories-chart、#calendar-chart 容器
* - 若存在对应容器,则生成相应的 ECharts 图表代码并插入页面
*/

// 引入 cheerio 用于解析和操作 HTML(类似 jQuery 的 Node.js 实现)
const cheerio = require('cheerio')
// 引入 moment 用于日期处理和格式化
const moment = require('moment')

/**
* 注册 Hexo 过滤器:after_render:html
* 在 HTML 渲染完成后执行,用于检测页面是否需要插入图表,并注入对应的 ECharts 脚本
*
* @param {string} locals - 渲染后的 HTML 字符串
* @returns {string} 处理后的 HTML 字符串
*/
hexo.extend.filter.register('after_render:html', function (locals) {
// 使用 cheerio 加载 HTML 内容
const $ = cheerio.load(locals)
// 查找页面中是否存在文章统计图容器
const post = $('#posts-chart')
// 查找页面中是否存在标签统计图容器
const tag = $('#tags-chart')
// 查找页面中是否存在分类统计图容器
const category = $('#categories-chart')
// 查找页面中是否存在文章发布热力图容器
const calendar = $('#calendar-chart')
// HTML 编码标记,用于处理某些情况下需要编码的场景
const htmlEncode = false

// 只要页面中存在任意一种图表容器,就执行图表注入逻辑
if (post.length > 0 || tag.length > 0 || category.length > 0 || calendar.length > 0) {
// 如果存在文章统计图容器且尚未注入脚本,则生成并插入文章统计图
if (post.length > 0 && $('#postsChart').length === 0) {
// 检查容器是否设置了 data-encode="true" 属性
if (post.attr('data-encode') === 'true') htmlEncode = true
// 在容器后插入文章统计图脚本,传入 data-start 属性指定的起始月份
post.after(postsChart(post.attr('data-start')))
}
// 如果存在标签统计图容器且尚未注入脚本,则生成并插入标签统计图
if (tag.length > 0 && $('#tagsChart').length === 0) {
// 检查容器是否设置了 data-encode="true" 属性
if (tag.attr('data-encode') === 'true') htmlEncode = true
// 在容器后插入标签统计图脚本,传入 data-length 属性指定的显示数量
tag.after(tagsChart(tag.attr('data-length')))
}
// 如果存在分类统计图容器且尚未注入脚本,则生成并插入分类统计图
if (category.length > 0 && $('#categoriesChart').length === 0) {
// 检查容器是否设置了 data-encode="true" 属性
if (category.attr('data-encode') === 'true') htmlEncode = true
// 在容器后插入分类统计图脚本,传入 data-parent 属性控制是否启用父级分类
category.after(categoriesChart(category.attr('data-parent')))
}
// 如果存在文章发布热力图容器且尚未注入脚本,则生成并插入文章发布热力图
if (calendar.length > 0 && $('#calendarChart').length === 0) {
// 检查容器是否设置了 data-encode="true" 属性
if (calendar.attr('data-encode') === 'true') htmlEncode = true
// 在容器后插入文章发布热力图脚本
calendar.after(calendarChart())
}

// 根据 htmlEncode 标记决定返回的 HTML 格式
if (htmlEncode) {
// 对特定字符进行编码处理(处理某些浏览器兼容性问题)
return $.root().html().replace(/&amp;#/g, '&#')
} else {
// 直接返回处理后的 HTML
return $.root().html()
}
} else {
// 页面中不存在任何图表容器,直接返回原始 HTML
return locals
}
}, 15)

/**
* 生成文章发布统计图表脚本
* 创建基于 ECharts 的时间折线图,展示从起始月份到当前月份的文章发布数量趋势
*
* @param {string} startMonth - 图表统计的起始月份,格式为 'YYYY-MM',默认为 '2020-01'
* @returns {string} 返回包含 ECharts 配置和初始化代码的 <script> 标签字符串
*/
function postsChart (startMonth) {
// 设置统计起始日期,若未传入则默认从 2020-01 开始
const startDate = moment(startMonth || '2020-01')
// 设置统计结束日期为当前时间
const endDate = moment()

// 使用 Map 存储每个月份对应的文章数量
const monthMap = new Map()
// 一天的毫秒数,用于按天递增遍历
const dayTime = 3600 * 24 * 1000
// 从起始日期遍历到结束日期,初始化每个月份的文章计数为 0
for (let time = startDate; time <= endDate; time += dayTime) {
const month = moment(time).format('YYYY-MM')
if (!monthMap.has(month)) {
monthMap.set(month, 0)
}
}
// 遍历 Hexo 本地的所有文章,统计每个月份的文章数量
hexo.locals.get('posts').forEach(function (post) {
const month = post.date.format('YYYY-MM')
if (monthMap.has(month)) {
monthMap.set(month, monthMap.get(month) + 1)
}
})
// 将月份数组和对应的文章数量数组序列化为 JSON 字符串,用于注入到 ECharts 配置中
const monthArr = JSON.stringify([...monthMap.keys()])
const monthValueArr = JSON.stringify([...monthMap.values()])

// 返回包含 ECharts 初始化代码的 script 标签
return `
<script id="postsChart">
// 根据当前主题(light/dark)动态设置文字颜色
var color = document.documentElement.getAttribute('data-theme') === 'light' ? '#4c4948' : 'rgba(255,255,255,0.7)'
// 初始化 ECharts 实例,绑定到 id 为 posts-chart 的容器
var postsChart = echarts.init(document.getElementById('posts-chart'), 'light');
// 配置文章统计图选项
var postsOption = {
title: {
text: '文章发布统计图',
x: 'center',
textStyle: {
color: color
}
},
animation : true,
animationDuration : 5000,
tooltip: {
trigger: 'axis'
},
// 工具箱配置,提供保存图片、数据视图、类型切换、区域缩放和还原功能
toolbox: {
show: true,
right: '5%',
// 工具箱图标颜色适配当前主题
iconStyle: {
borderColor: color
},
feature: {
// 保存为图片
saveAsImage: {
show: true,
title: '保存为图片',
pixelRatio: 2
},
// 数据视图,可查看原始数据
dataView: {
show: true,
title: '数据视图',
readOnly: true,
lang: ['数据视图', '关闭', '刷新']
},
// 动态类型切换,支持折线图与柱状图互换
magicType: {
show: true,
title: {
line: '切换为折线图',
bar: '切换为柱状图'
},
type: ['line', 'bar']
},
// 数据区域缩放,便于聚焦特定时间段
dataZoom: {
show: true,
title: {
zoom: '区域缩放',
back: '缩放还原'
}
},
// 还原初始状态
restore: {
show: true,
title: '还原'
}
}
},
xAxis: {
name: '日期',
type: 'category',
boundaryGap: false,
nameTextStyle: {
color: color
},
axisTick: {
show: false
},
axisLabel: {
show: true,
color: color
},
axisLine: {
show: true,
lineStyle: {
color: color
}
},
data: ${monthArr}
},
yAxis: {
name: '文章篇数',
type: 'value',
nameTextStyle: {
color: color
},
splitLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
show: true,
color: color
},
axisLine: {
show: true,
lineStyle: {
color: color
}
}
},
series: [{
name: '文章篇数',
type: 'line',
smooth: true,
lineStyle: {
width: 0
},
showSymbol: false,
itemStyle: {
opacity: 1,
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgba(128, 255, 165)'
},
{
offset: 1,
color: 'rgba(1, 191, 236)'
}])
},
areaStyle: {
opacity: 1,
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgba(128, 255, 165)'
}, {
offset: 1,
color: 'rgba(1, 191, 236)'
}])
},
data: ${monthValueArr},
markLine: {
data: [{
name: '平均值',
type: 'average',
label: {
color: color
}
}]
}
}]
};
postsChart.setOption(postsOption);
// 监听窗口大小变化,自动调整图表尺寸
window.addEventListener('resize', () => {
postsChart.resize();
});
// 监听图表点击事件,点击后跳转到对应月份的归档页面
postsChart.on('click', 'series', (event) => {
if (event.componentType === 'series') window.location.href = '/archives/' + event.name.replace('-', '/');
});
</script>`
}

/**
* 生成标签统计图表脚本
* 创建基于 ECharts 的柱状图,展示使用频率最高的标签及其对应的文章数量
*
* @param {number} len - 需要展示的标签数量,若未传入则展示所有标签
* @returns {string} 返回包含 ECharts 配置和初始化代码的 <script> 标签字符串
*/
function tagsChart (len) {
// 存储标签数据的临时数组
const tagArr = []
// 从 Hexo 本地获取所有标签信息
hexo.locals.get('tags').map(function (tag) {
tagArr.push({ name: tag.name, value: tag.length, path: tag.path })
})
// 按文章数量降序排序标签
tagArr.sort((a, b) => { return b.value - a.value })

// 确定需要展示的标签数量
const dataLength = Math.min(tagArr.length, len) || tagArr.length
// 提取展示的标签名称数组
const tagNameArr = []
for (let i = 0; i < dataLength; i++) {
tagNameArr.push(tagArr[i].name)
}
// 将数据序列化为 JSON 字符串
const tagNameArrJson = JSON.stringify(tagNameArr)
const tagArrJson = JSON.stringify(tagArr)

// 返回包含 ECharts 初始化代码的 script 标签
return `
<script id="tagsChart">
// 根据当前主题(light/dark)动态设置文字颜色
var color = document.documentElement.getAttribute('data-theme') === 'light' ? '#4c4948' : 'rgba(255,255,255,0.7)'
// 初始化 ECharts 实例,绑定到 id 为 tags-chart 的容器
var tagsChart = echarts.init(document.getElementById('tags-chart'), 'light');
// 配置标签统计图选项
var tagsOption = {
title: {
text: 'Top ${dataLength} 标签统计图',
x: 'center',
textStyle: {
color: color
}
},
animation : true,
animationDuration : 5000,
tooltip: {},
// 工具箱配置,提供保存图片、数据视图、类型切换和还原功能
toolbox: {
show: true,
right: '5%',
// 工具箱图标颜色适配当前主题
iconStyle: {
borderColor: color
},
feature: {
// 保存为图片
saveAsImage: {
show: true,
title: '保存为图片',
pixelRatio: 2
},
// 数据视图,可查看原始数据
dataView: {
show: true,
title: '数据视图',
readOnly: true,
lang: ['数据视图', '关闭', '刷新']
},
// 动态类型切换,支持柱状图与折线图互换
magicType: {
show: true,
title: {
bar: '切换为柱状图',
line: '切换为折线图'
},
type: ['bar', 'line']
},
// 还原初始状态
restore: {
show: true,
title: '还原'
}
}
},
xAxis: {
name: '标签',
type: 'category',
nameTextStyle: {
color: color
},
axisTick: {
show: false
},
axisLabel: {
show: true,
color: color,
interval: 0
},
axisLine: {
show: true,
lineStyle: {
color: color
}
},
data: ${tagNameArrJson}
},
yAxis: {
name: '文章篇数',
type: 'value',
splitLine: {
show: false
},
nameTextStyle: {
color: color
},
axisTick: {
show: false
},
axisLabel: {
show: true,
color: color
},
axisLine: {
show: true,
lineStyle: {
color: color
}
}
},
series: [{
name: '文章篇数',
type: 'bar',
data: ${tagArrJson},
itemStyle: {
borderRadius: [5, 5, 0, 0],
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgba(128, 255, 165)'
},
{
offset: 1,
color: 'rgba(1, 191, 236)'
}])
},
emphasis: {
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgba(128, 255, 195)'
},
{
offset: 1,
color: 'rgba(1, 211, 255)'
}])
}
},
markLine: {
data: [{
name: '平均值',
type: 'average',
label: {
color: color
}
}]
}
}]
};
tagsChart.setOption(tagsOption);
// 监听窗口大小变化,自动调整图表尺寸
window.addEventListener('resize', () => {
tagsChart.resize();
});
// 监听图表点击事件,点击后跳转到对应标签页面
tagsChart.on('click', 'series', (event) => {
if(event.data.path) window.location.href = '/' + event.data.path;
});
</script>`
}

/**
* 生成文章分类统计图表脚本
* 创建基于 ECharts 的饼图或旭日图,展示文章分类的分布情况
* 当存在父级分类且 dataParent 参数为 'true' 时,使用旭日图展示层级关系;
* 否则使用玫瑰饼图展示扁平化的分类分布
*
* @param {string} dataParent - 是否启用父级分类展示,'true' 启用旭日图,其他值使用饼图
* @returns {string} 返回包含 ECharts 配置和初始化代码的 <script> 标签字符串
*/
function categoriesChart (dataParent) {

// 存储分类数据的临时数组
const categoryArr = []
// 标记是否存在父级分类
let categoryParentFlag = false
// 从 Hexo 本地获取所有分类信息
hexo.locals.get('categories').map(function (category) {
// 如果分类存在 parent 属性,说明存在层级关系
if (category.parent) categoryParentFlag = true
categoryArr.push({
name: category.name,
value: category.length,
path: category.path,
id: category._id,
parentId: category.parent || '0'
})
})
// 判断是否启用父级分类展示:存在父级分类且传入参数为 'true'
categoryParentFlag = categoryParentFlag && dataParent === 'true'
// 按文章数量降序排序分类
categoryArr.sort((a, b) => { return b.value - a.value })

/**
* 将扁平的分类列表转换为树形结构
* 递归构建父子层级关系
*
* @param {Array} data - 分类数据数组
* @param {string} parent - 父级分类的 ID
* @returns {Array} 树形结构的分类数据
*/
function translateListToTree (data, parent) {
let tree = []
let temp
data.forEach((item, index) => {
if (data[index].parentId == parent) {
let obj = data[index];
temp = translateListToTree(data, data[index].id);
if (temp.length > 0) {
obj.children = temp
}
if (tree.indexOf(obj) === -1)
tree.push(obj)
}
})
return tree
}
// 将分类数据序列化为 JSON 字符串
const categoryNameJson = JSON.stringify(categoryArr.map(function (category) { return category.name }))
const categoryArrJson = JSON.stringify(categoryArr)
const categoryArrParentJson = JSON.stringify(translateListToTree(categoryArr, '0'))

// 返回包含 ECharts 初始化代码的 script 标签
return `
<script id="categoriesChart">
// 根据当前主题(light/dark)动态设置文字颜色
var color = document.documentElement.getAttribute('data-theme') === 'light' ? '#4c4948' : 'rgba(255,255,255,0.7)'
// 初始化 ECharts 实例,绑定到 id 为 categories-chart 的容器
var categoriesChart = echarts.init(document.getElementById('categories-chart'), 'light');
// 标记是否启用父级分类(旭日图)展示
var categoryParentFlag = ${categoryParentFlag}
// 配置分类统计图选项
var categoriesOption = {
title: {
text: '文章分类统计图',
x: 'center',
textStyle: {
color: color
}
},
animation : true,
animationDuration : 5000,
legend: {
top: 'bottom',
data: ${categoryNameJson},
textStyle: {
color: color
}
},
tooltip: {
trigger: 'item'
},
// 工具箱配置,提供保存图片、数据视图和还原功能(饼图/旭日图不支持类型切换和区域缩放)
toolbox: {
show: true,
right: '5%',
// 工具箱图标颜色适配当前主题
iconStyle: {
borderColor: color
},
feature: {
// 保存为图片
saveAsImage: {
show: true,
title: '保存为图片',
pixelRatio: 2
},
// 数据视图,可查看原始数据
dataView: {
show: true,
title: '数据视图',
readOnly: true,
lang: ['数据视图', '关闭', '刷新']
},
// 还原初始状态
restore: {
show: true,
title: '还原'
}
}
},
series: []
};
// 根据是否启用父级分类,选择插入旭日图或饼图配置
categoriesOption.series.push(
categoryParentFlag ?
{
nodeClick : false,
name: '文章篇数',
type: 'sunburst',
// radius: ['0%', '130%'],
center: ['50%', '50%'],
data: ${categoryArrParentJson},
levels: [
{},
{
r0: '15%',
r: '35%',
itemStyle: {
borderWidth: 2
},
label: {
align: 'center',
rotate: 'radial',
fontWeight: 'bolder',
minAngle: 5, // 扇区小于该角度不显示文字,避免拥挤
width: 100, // 文字宽度
overflow: 'truncate' // 文字过长截断
}
},
{
r0: '35%',
r: '70%',
label: {
align: 'center',
fontWeight: 'bold',
minAngle: 4, // 扇区小于该角度不显示文字,避免拥挤
width: 150, // 文字宽度
overflow: 'truncate' // 文字过长截断
}
},
{
r0: '70%',
r: '72%',
label: {
position: 'outside',
padding: 3,
silent: false,
minAngle: 1, // 扇区小于该角度不显示文字,避免拥挤
width: 100, // 文字宽度
overflow: 'truncate' // 文字过长截断
},
itemStyle: {
borderWidth: 3
}
}
],
sort: 'desc'
// itemStyle: {
// borderColor: '#fff',
// borderWidth: 2,
// emphasis: {
// focus: 'ancestor',
// shadowBlur: 10,
// shadowOffsetX: 0,
// shadowColor: 'rgba(255, 255, 255, 0.5)'
// }
// },
// label: {
// show: true, // 是否显示文字
// rotate: 'radial', // radial径向/ tangential切向/ 0不旋转
// fontSize: 12,
// color: '#333',
// minAngle: 4, // 扇区小于该角度不显示文字,避免拥挤
// width: 100, // 文字宽度
// overflow: 'truncate', // 文字过长截断
// align: 'center'
// }
}
:
{
// name: '文章篇数',
// type: 'pie',
// radius: [30, 80],
// roseType: 'area',
// label: {
// color: color,
// formatter: '{b} : {c} ({d}%)'
// },
// data: ${categoryArrJson},
// itemStyle: {
// emphasis: {
// shadowBlur: 10,
// shadowOffsetX: 0,
// shadowColor: 'rgba(255, 255, 255, 0.5)'
// }
// }
}
)
categoriesChart.setOption(categoriesOption);
// 监听窗口大小变化,自动调整图表尺寸
window.addEventListener('resize', () => {
categoriesChart.resize();
});
// 监听图表点击事件,点击后跳转到对应分类页面
categoriesChart.on('click', 'series', (event) => {
if(event.data.path) window.location.href = '/' + event.data.path;
});
</script>`
}

/**
* 生成文章发布热力图脚本
* 创建基于 ECharts 的日历热力图,展示每天的文章发布数量。
* 当文章跨越多个年份时,每年生成一个独立的 calendar 组件垂直排列。
* 使用 calendar 组件搭配 heatmap 系列,直观呈现全年发文频率分布。
*
* @returns {string} 返回包含 ECharts 配置和初始化代码的 <script> 标签字符串
*/
function calendarChart () {
// 使用 Map 存储每天对应的文章数量
const dayMap = new Map()
// 遍历 Hexo 本地的所有文章,统计每天的文章数量
hexo.locals.get('posts').forEach(function (post) {
const day = post.date.format('YYYY-MM-DD')
dayMap.set(day, (dayMap.get(day) || 0) + 1)
})

// 按年份分组数据:{ '2021': [['2021-10-01', 2], ...], '2022': [...] }
const yearDataMap = new Map()
dayMap.forEach((value, key) => {
const year = key.split('-')[0]
if (!yearDataMap.has(year)) {
yearDataMap.set(year, [])
}
yearDataMap.get(year).push([key, value])
})

// 获取年份列表,按降序排列(最近年份在前)
const years = [...yearDataMap.keys()].sort((a, b) => b - a)

// 如果没有任何文章,默认显示当前年份的空日历
if (years.length === 0) {
const currentYear = moment().format('YYYY')
years.push(currentYear)
yearDataMap.set(currentYear, [])
}

// 计算最大文章数,用于 visualMap 的 max
let maxCount = 0
dayMap.forEach((v) => { if (v > maxCount) maxCount = v })
if (maxCount === 0) maxCount = 1

// 将年份列表和按年分组的数据序列化为 JSON 字符串,注入到前端脚本中
const yearsJson = JSON.stringify(years)
const yearDataObj = {}
years.forEach(year => { yearDataObj[year] = yearDataMap.get(year) })
const yearDataJson = JSON.stringify(yearDataObj)

// 返回包含 ECharts 初始化代码的 script 标签
return `
<script id="calendarChart">
// 根据当前主题(light/dark)动态设置文字颜色
var color = document.documentElement.getAttribute('data-theme') === 'light' ? '#4c4948' : 'rgba(255,255,255,0.7)'
// 根据当前主题动态设置背景色,用于 calendar 分隔线
var bgColor = document.documentElement.getAttribute('data-theme') === 'light' ? '#fff' : '#1e1e1e'

// 注入的年份列表和对应数据
var years = ${yearsJson};
var yearData = ${yearDataJson};
var maxCount = ${maxCount};

// 根据年份数量动态调整容器高度(每个年份约需 180px 空间)
var container = document.getElementById('calendar-chart');
var neededHeight = 80 + years.length * 180 + (years.length > 1 ? 70 : 50);
container.style.height = Math.max(neededHeight, 320) + 'px';

// 初始化 ECharts 实例,变量名避免与 script id 冲突
var calChart = echarts.init(container, 'light');

// 动态构建 calendar 组件数组和 series 数组(每个年份一个)
var calendars = [];
var seriesList = [];
years.forEach(function(year, index) {
calendars.push({
top: index === 0 ? 80 : 80 + index * 180,
left: 50,
right: 50,
cellSize: ['auto', 16],
range: year, // 单一年份字符串,ECharts 支持
itemStyle: {
borderWidth: 0.5,
// borderColor: bgColor
},
splitLine: {
show: true,
lineStyle: {
color: '#cbd2ec',
width: 2
}
},
// 星期标签,使用中文缩写
dayLabel: {
color: color,
nameMap: 'cn'
},
// 月份标签,使用中文缩写
monthLabel: {
color: color,
nameMap: 'cn'
},
// 年份标签
yearLabel: {
color: color,
show: true
}
});

seriesList.push({
type: 'heatmap',
coordinateSystem: 'calendar',
calendarIndex: index,
data: yearData[year] || []
});
});

// 配置文章发布热力图选项
var calendarOption = {
title: {
text: '文章发布热力图',
x: 'center',
textStyle: {
color: color
}
},
animation : true,
animationDuration : 5000,
tooltip: {
formatter: function (params) {
return params.value[0] + '<br/>文章篇数:' + params.value[1]
}
},
// 工具箱配置,提供保存图片、数据视图和还原功能
toolbox: {
show: true,
right: '5%',
// 工具箱图标颜色适配当前主题
iconStyle: {
borderColor: color
},
feature: {
// 保存为图片
saveAsImage: {
show: true,
title: '保存为图片',
pixelRatio: 2
},
// 数据视图,可查看原始数据
dataView: {
show: true,
title: '数据视图',
readOnly: true,
lang: ['数据视图', '关闭', '刷新']
},
// 还原初始状态
restore: {
show: true,
title: '还原'
}
}
},
// 视觉映射组件,根据文章数量映射颜色深浅
visualMap: {
min: 0,
max: maxCount,
calculable: true,
orient: 'horizontal',
left: 'center',
bottom: years.length > 1 ? '0%' : '5%',
textStyle: {
color: color
},
inRange: {
color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
}
},
// 日历组件数组(多年份时多个 calendar 垂直排列)
calendar: calendars,
series: seriesList
};
calChart.setOption(calendarOption);
// 监听窗口大小变化,自动调整图表尺寸
window.addEventListener('resize', () => {
calChart.resize();
});
// 监听图表点击事件,点击后跳转到对应月份的归档页面
calChart.on('click', 'series', (event) => {
if (event.componentType === 'series') {
var date = event.value[0].split('-')
window.location.href = '/archives/' + date[0] + '/' + date[1] + '/'
}
});
</script>`
}