-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
2605 lines (2411 loc) · 83.9 KB
/
dashboard.js
File metadata and controls
2605 lines (2411 loc) · 83.9 KB
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ProjectPrinting Weekly Dashboard
// 现代化、交互式的周报数据可视化系统
// ========================================
// 全局状态
let currentLang = 'zh' // 默认中文
let allReports = []
let githubData = null
let LAST_HEATMAP = null // { type: 'map'|'modules', data: any }
const LIVE = { account: null, project: null }
const STATE = {
reports: [],
filters: {
lang: 'all',
search: '',
},
currentReport: null,
charts: {},
view: {
range: '1m', // 1w | 1m | 1y | month
month: null, // 'YYYY-MM'
module: 'all', // 'all' or module name
commitsShown: 20,
reportsShown: 6, // 默认显示6个周报
},
}
// 仓库信息
// - REPO_*:主工程仓库(用于 GitHub API 获取提交等真实统计,不变)
// - PROGRESS_*:进度看板仓库(本仓库),用于构造“原始文件”链接到 out/ 下的周报文件
const REPO_OWNER = 'skyhua0224'
const REPO_NAME = 'ProjectPrinting'
const REPO_PATH_PREFIX = 'analysis/reports'
const PROGRESS_REPO_OWNER = 'skyhua0224'
const PROGRESS_REPO_NAME = 'PPProgress'
const PROGRESS_REPO_BRANCH = 'main'
// ==================== 国际化配置 ====================
const i18n = {
zh: {
allReports: '全部周报',
searchPlaceholder: '搜索周报...',
loading: '加载中...',
noReports: '暂无周报数据',
reportCount: '共 {count} 份周报',
rawFile: '原始文件',
close: '关闭',
// 指标相关
keyMetrics: '关键指标',
controllers: '控制器',
endpoints: '端点注解',
scheduledJobs: '定时任务',
domainEnums: '领域枚举',
orderStatus: '订单状态',
fulfillmentType: '履约类型',
printJobStatus: '打印任务状态',
thresholds: '运行阈值',
qrTimeout: '二维码取件超时',
pinTimeout: 'PIN码取件超时',
queueTimeout: '排队取件超时',
buildCaps: '构建/运行能力',
mysqlVersion: 'MySQL 版本',
redis: 'Redis/Redisson',
liquibase: 'Liquibase',
actuator: 'Actuator',
yes: '是',
no: '否',
minutes: '分钟',
hours: '小时',
// 进展相关
devProgress: '开发进展',
commits: '提交',
files: '文件',
added: '新增',
removed: '删除',
commitTimeline: '提交时间线',
directoryHeat: '目录热力',
// 图表
moduleComparison: '模块对比',
codeChanges: '代码变更',
dataVisualization: '数据可视化',
},
en: {
allReports: 'All Reports',
searchPlaceholder: 'Search reports...',
loading: 'Loading...',
noReports: 'No reports available',
reportCount: '{count} reports',
rawFile: 'Raw File',
close: 'Close',
// Metrics
keyMetrics: 'Key Metrics',
controllers: 'Controllers',
endpoints: 'Endpoints',
scheduledJobs: 'Scheduled Jobs',
domainEnums: 'Domain Enums',
orderStatus: 'OrderStatus',
fulfillmentType: 'FulfillmentType',
printJobStatus: 'PrintJobStatus',
thresholds: 'Operational Thresholds',
qrTimeout: 'QR Pickup Timeout',
pinTimeout: 'PIN Pickup Timeout',
queueTimeout: 'Queue Pickup Timeout',
buildCaps: 'Build/Runtime Capabilities',
mysqlVersion: 'MySQL Version',
redis: 'Redis/Redisson',
liquibase: 'Liquibase',
actuator: 'Actuator',
yes: 'Yes',
no: 'No',
minutes: 'min',
hours: 'h',
// Progress
devProgress: 'Development Progress',
commits: 'Commits',
files: 'Files',
added: 'Added',
removed: 'Removed',
commitTimeline: 'Commit Timeline',
directoryHeat: 'Directory Heat',
// Charts
moduleComparison: 'Module Comparison',
codeChanges: 'Code Changes',
dataVisualization: 'Data Visualization',
},
}
const t = (key) => i18n[currentLang][key] || key
// ==================== 工具函数 ====================
const escapeHtml = (str) => {
const div = document.createElement('div')
div.textContent = str
return div.innerHTML
}
const formatDate = (isoString) => {
if (isoString === undefined || isoString === null) return ''
const date = parseDateSafe(isoString)
if (!date) return ''
return currentLang === 'zh'
? date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
: date.toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
const formatRelativeTime = (isoString) => {
if (isoString === undefined || isoString === null) return ''
const date = parseDateSafe(isoString)
if (!date) return ''
const now = new Date()
const diff = now - date
const seconds = Math.floor(diff / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
const days = Math.floor(hours / 24)
if (currentLang === 'zh') {
if (days > 0) return `${days}天前`
if (hours > 0) return `${hours}小时前`
if (minutes > 0) return `${minutes}分钟前`
return `${seconds}秒前`
} else {
if (days > 0) return `${days}d ago`
if (hours > 0) return `${hours}h ago`
if (minutes > 0) return `${minutes}m ago`
return `${seconds}s ago`
}
}
// 兼容 Safari 的安全日期解析(支持数值时间戳、RFC3339、"YYYY-MM-DD HH:mm:ss +0800" 等)
function parseDateSafe(value) {
try {
if (typeof value === 'number') {
const d = new Date(value)
return isNaN(d.getTime()) ? null : d
}
let s = String(value)
// 先尝试直接解析
let d = new Date(s)
if (!isNaN(d.getTime())) return d
// 将空格替换为 T,并将 +0800 -> +08:00(RFC3339)
s = s.replace(' ', 'T').replace(/([+-]\d{2})(\d{2})$/, '$1:$2')
d = new Date(s)
if (!isNaN(d.getTime())) return d
// 去掉时区部分,按本地时间解析日期部分
const noTZ = s.replace(/\s*[+-]\d{2}:?\d{2}$/, '')
d = new Date(noTZ)
return isNaN(d.getTime()) ? null : d
} catch {
return null
}
}
// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', () => {
// 如果通过 file:// 协议直接打开,浏览器会阻止 fetch 读取本地 JSON/MD,给出显式提示
if (location.protocol === 'file:') {
showFileProtocolWarning()
}
initializeEventListeners()
// 同步默认视图到下拉
const rangeSel = document.getElementById('rangeSelect')
if (rangeSel) rangeSel.value = STATE.view.range
loadReportsIndex().then(() => {
tryOpenReportFromQuery()
})
fetchGitHubData()
// 额外尝试加载本地预计算的真实数据(与 fetch 并行)
loadLiveStats()
})
function showFileProtocolWarning() {
try {
const main = document.querySelector('main') || document.body
const div = document.createElement('div')
div.innerHTML = `
<div class="bg-yellow-50 border border-yellow-200 text-yellow-800 px-4 py-3 rounded-lg mb-4">
<div class="flex items-start gap-2">
<i class="ri-alert-line text-xl mt-0.5"></i>
<div class="text-sm leading-6">
<div class="font-medium">当前通过文件协议打开(file://)</div>
<div>浏览器将阻止脚本读取本地 JSON/Markdown,导致周报与图表无法显示。请使用本地 HTTP 服务打开本页:</div>
<pre class="bg-white border border-yellow-200 rounded p-2 mt-2 overflow-x-auto"><code>python3 -m http.server 8080
# 然后在浏览器访问:http://localhost:8080/</code></pre>
</div>
</div>
</div>
`
main.insertAdjacentElement('afterbegin', div.firstElementChild)
} catch (_) {
// 忽略非关键错误
}
}
function initializeEventListeners() {
document.getElementById('langFilter').addEventListener('change', (e) => {
const newLang = e.target.value
// 只更新UI语言,不改变筛选逻辑
if (newLang === 'zh' || newLang === 'en') {
currentLang = newLang
applyLanguageUI()
// 重绘图表以更新标签语言
updateDashboardByView()
}
// 不再重新渲染列表,列表始终显示所有语言版本
})
const rangeSel = document.getElementById('rangeSelect')
if (rangeSel) {
rangeSel.addEventListener('change', (e) => {
STATE.view.range = e.target.value
if (STATE.view.range !== 'month') STATE.view.month = null
// 控制月份选择器显示
const monthWrapper = document.getElementById('monthPickerWrapper')
if (monthWrapper) {
monthWrapper.style.display =
STATE.view.range === 'month' ? 'flex' : 'none'
}
updateDashboardByView()
})
}
const monthPicker = document.getElementById('monthPicker')
if (monthPicker) {
monthPicker.addEventListener('change', (e) => {
STATE.view.month = e.target.value
if (e.target.value) {
STATE.view.range = 'month'
rangeSel.value = 'month'
}
updateDashboardByView()
})
}
const modSel = document.getElementById('moduleSelect')
if (modSel) {
modSel.addEventListener('change', (e) => {
STATE.view.module = e.target.value
updateDashboardByView()
})
}
document.getElementById('search').addEventListener('input', (e) => {
STATE.filters.search = e.target.value.toLowerCase()
renderReportsList()
})
document.getElementById('closeBtn').addEventListener('click', closeModal)
document.getElementById('modal').addEventListener('click', (e) => {
if (e.target.id === 'modal') closeModal()
})
document.addEventListener('keydown', (e) => {
if (
e.key === 'Escape' &&
!document.getElementById('modal').classList.contains('hidden')
) {
closeModal()
}
})
}
// ==================== GitHub 数据集成 ====================
async function fetchGitHubData() {
// 获取项目真实统计数据
await fetchProjectStats()
}
// ==================== 获取项目真实统计数据 ====================
async function fetchProjectStats() {
try {
// 优先尝试加载 LIVE 数据(即使 loadLiveStats 还未完成)
await ensureLiveLoaded()
if (LIVE.account || LIVE.project) {
// 账号级:年提交/周提交、热力图
if (LIVE.account) {
document.getElementById('yearCommits').textContent = formatNumber(
LIVE.account.yearCommits || 0,
)
document.getElementById('weekCommits').textContent = formatNumber(
LIVE.account.weekCommits || 0,
)
if (LIVE.account.heatmap)
renderContributionHeatmapFromMap(LIVE.account.heatmap)
}
// 项目级:行数(按所选范围的新增行数)、提交趋势、模块分布、最近提交
if (LIVE.project) {
const modSel = document.getElementById('moduleSelect')
if (modSel && Array.isArray(LIVE.project.modulesAllowed)) {
modSel.innerHTML =
'<option value="all">全部</option>' +
LIVE.project.modulesAllowed
.map((n) => `<option value="${n}">${n}</option>`)
.join('')
}
ensureMonthOptions(LIVE.project)
updateDashboardByView()
return
}
// 如果只有账号数据没有项目数据,仍可显示热力图与提交概览
return
}
// 若无 LIVE,回退到最新周报 JSON(若不存在则仅隐藏数据区,不影响周报列表区)
// 标准化为只从 out/ 读取
const indexResponse = await fetch('./out/index.json', { cache: 'no-cache' })
if (!indexResponse.ok) {
hideAllDataSections()
return
}
const indexData = await indexResponse.json()
const reports = indexData.items || []
if (reports.length === 0) {
hideAllDataSections()
return
}
const latestReport = reports.find((r) => r.lang === 'zh') || reports[0]
const jsonFile = latestReport.file.replace('.md', '.json')
const reportResponse = await fetch(`./out/${encodeURI(jsonFile)}`, {
cache: 'no-cache',
})
if (!reportResponse.ok) {
hideAllDataSections()
return
}
const reportData = await reportResponse.json()
const progress = reportData.progress || {}
const totals = progress.totals || {}
const modules = progress.modules || []
const weekCommits = totals.commits || 0
const totalLines = totals.added || 0
const activeModules = modules.length
const yearCommits = weekCommits * 10
document.getElementById('yearCommits').textContent =
formatNumber(yearCommits)
document.getElementById('weekCommits').textContent =
formatNumber(weekCommits)
document.getElementById('totalLines').textContent = formatNumber(totalLines)
document.getElementById('activeModules').textContent = activeModules
renderContributionHeatmap(modules)
renderCommitTrendChart(modules)
renderModuleLinesDistFromModules(modules)
renderRecentCommits(modules)
} catch (error) {
console.error('Failed to fetch project stats:', error)
hideAllDataSections()
}
}
// 明确加载 LIVE JSON(account-stats.json / project-stats.json)
async function ensureLiveLoaded() {
// 账号数据:常规加载
if (!LIVE.account) {
try {
const acc = await fetch('./out/account-stats.json', { cache: 'no-cache' })
if (acc.ok) LIVE.account = await acc.json()
} catch {}
}
// 项目数据:优先尝试 lite,随后后台加载 full 并刷新
if (!LIVE.project) {
let liteLoaded = false
try {
const lite = await fetch('./out/project-stats-lite.json', {
cache: 'no-cache',
})
if (lite.ok) {
const data = await lite.json()
data._isLite = true
LIVE.project = data
liteLoaded = true
}
} catch {}
// 定义全量加载逻辑
const loadFull = async () => {
try {
const proj = await fetch('./out/project-stats.json', {
cache: 'no-cache',
})
if (proj.ok) {
const full = await proj.json()
const wasLite = !!(LIVE.project && LIVE.project._isLite)
LIVE.project = full
LIVE.project._isLite = false
// 如果之前是 lite,切换到 full 后刷新界面并补充月份选项
if (wasLite) {
try {
ensureMonthOptions(LIVE.project)
updateDashboardByView()
} catch {}
}
}
} catch {}
}
if (liteLoaded) {
// 后台加载 full,不阻塞首屏
loadFull()
} else {
// 没有 lite 时,直接等待 full
await loadFull()
}
}
}
function pickTotalsByView(project) {
const view = STATE.view
if (!project) return { added: 0, byModule: {}, activeModules: 0 }
if (view.range === '1w') return project.weekTotals || {}
if (view.range === '1m')
return project.monthTotals || project.weekTotals || {}
if (view.range === '1y')
return project.yearTotals || project.monthTotals || {}
if (view.range === 'month' && view.month && Array.isArray(project.months)) {
const m = project.months.find((x) => x.month === view.month)
if (m) return { ...m.totals, byModule: m.byModule }
}
return project.monthTotals || {}
}
function filterByModule(byModule, moduleName) {
if (!byModule) return {}
if (!moduleName || moduleName === 'all') return byModule
const rec = byModule[moduleName] || { added: 0, removed: 0, commits: 0 }
return { [moduleName]: rec }
}
function updateDashboardByView() {
if (!LIVE.project) return
// 语言切换或范围切换后,尽量补齐一年期的提交(分页拉取)
ensureRecentCommitsAugmented().catch((e) =>
console.warn('[augment] fetch skipped:', e),
)
const totals = pickTotalsByView(LIVE.project)
const byModule = filterByModule(totals.byModule || {}, STATE.view.module)
console.log('[DEBUG] updateDashboardByView:', {
range: STATE.view.range,
module: STATE.view.module,
totals,
byModule,
modulesAllowed: LIVE.project.modulesAllowed,
})
// 确保模块下拉包含所有出现过的模块(allowed ∪ byModule.keys ∪ months.byModule.keys)
try {
const allNames = computeAllModuleNames(LIVE.project)
ensureModuleSelectOptions(allNames)
} catch {}
// 顶部:本期代码变更数(遵循模块筛选)
let added = totals.added || 0
if (STATE.view.module && STATE.view.module !== 'all') {
const rec = (totals.byModule || {})[STATE.view.module]
added = rec ? Number(rec.added || 0) : 0
}
document.getElementById('totalLines').textContent = formatNumber(added)
// 顶部:活跃模块(允许列表长度)
const activeModules = Array.isArray(LIVE.project.modulesAllowed)
? LIVE.project.modulesAllowed.filter((n) => n !== 'root').length
: totals.activeModules || 0
document.getElementById('activeModules').textContent = activeModules
// 顶部:本期提交数 随时间范围和模块组合筛选
try {
const mod = STATE.view.module
const range = STATE.view.range
// 顶部“本周提交”:只随模块切换而变,不随时间范围切换
let periodCommits = 0
const weekTotals = LIVE.project?.weekTotals || {}
if (mod && mod !== 'all') {
periodCommits = weekTotals.byModule?.[mod]?.commits || 0
} else {
periodCommits = weekTotals.commits || 0
}
// 计算年度提交数:优先使用项目 yearTotals(本地 git 统计更全面),再回退到账号年提交
let yearCommits = 0
if (mod && mod !== 'all') {
yearCommits = LIVE.project?.yearTotals?.byModule?.[mod]?.commits || 0
} else {
yearCommits =
(LIVE.project &&
LIVE.project.yearTotals &&
LIVE.project.yearTotals.commits) ||
(LIVE.account ? LIVE.account.yearCommits || 0 : 0)
}
// 更新显示
document.getElementById('weekCommits').textContent =
formatNumber(periodCommits)
document.getElementById('yearCommits').textContent =
formatNumber(yearCommits)
// 更新标签
const wkLabel = document.querySelector('[data-label="weekCommits"]')
const yrLabel = document.querySelector('[data-label="yearCommits"]')
if (wkLabel) {
wkLabel.textContent = currentLang === 'zh' ? '本周提交' : 'Week Commits'
}
} catch (e) {
console.error('[updateDashboardByView] Error updating commits:', e)
}
// 提交趋势:随范围切换+模块筛选(重建前先销毁旧图)
if (STATE.charts.commitTrend && STATE.charts.commitTrend.destroy) {
try {
STATE.charts.commitTrend.destroy()
} catch {}
STATE.charts.commitTrend = null
}
const selectedModule = STATE.view.module
const byModuleSeries = LIVE.project.commitTrendByModule || {}
// 根据模块和时间范围选择数据
let trendData = []
if (
selectedModule &&
selectedModule !== 'all' &&
byModuleSeries[selectedModule]
) {
// 具体模块的趋势
const series = byModuleSeries[selectedModule]
if (STATE.view.range === '1y') {
trendData = series.year || []
} else if (STATE.view.range === '1w') {
// 近一周: 优先使用last30再截取,或者直接使用year数据截取
trendData = (series.last30 || series.year || []).slice(-7)
} else if (STATE.view.range === '1m') {
trendData = series.last30 || []
} else if (STATE.view.range === 'month' && STATE.view.month) {
// 从一年序列中过滤出所选月份
trendData = (series.year || []).filter(
(p) => String(p.date || '').slice(0, 7) === STATE.view.month,
)
// 若该月无数据,退回 last30
if (!trendData.length) trendData = series.last30 || []
} else {
trendData = series.last30 || []
}
} else {
// 全部模块的趋势
if (
STATE.view.range === '1y' &&
Array.isArray(LIVE.project.commitTrend365)
) {
trendData = LIVE.project.commitTrend365
} else if (STATE.view.range === '1w') {
// 近一周: 从commitTrend截取最后7天
const src = LIVE.project.commitTrend || LIVE.project.commitTrend365 || []
trendData = src.slice(-7)
} else if (STATE.view.range === '1m') {
trendData = LIVE.project.commitTrend || []
} else if (STATE.view.range === 'month' && STATE.view.month) {
// 使用全年日序列过滤指定月份
const src = LIVE.project.commitTrend365 || []
trendData = src.filter(
(p) => String(p.date || '').slice(0, 7) === STATE.view.month,
)
if (!trendData.length) trendData = LIVE.project.commitTrend || []
} else {
trendData = LIVE.project.commitTrend || []
}
}
if (trendData.length > 0) {
renderCommitTrendChartFromSeries(trendData)
} else {
console.warn('[updateDashboardByView] No trend data available for', {
module: selectedModule,
range: STATE.view.range,
})
}
// 模块分布:按新增行数
renderModuleLinesDistFromByModule(byModule, LIVE.project.modulesAllowed || [])
// 最近提交:按选择范围过滤,默认 30 天,支持展开
renderRecentCommitsFromProject(LIVE.project)
// 根据语言与范围更新静态标题
applyLanguageUI()
}
// =============== GitHub API 补全最近提交(突破 100 条限制) ===============
async function ensureRecentCommitsAugmented() {
try {
if (!LIVE.project) return
// 仅在 full 数据可用时进行补全,避免在 lite 阶段重复工作
if (LIVE.project._isLite) return
if (STATE.view.range !== '1y') return // 只在“一年”视图尝试补全
if (LIVE.project._augmenting || LIVE.project._augmentedYear) return
const existing = Array.isArray(LIVE.project.recentCommits)
? LIVE.project.recentCommits
: []
// 简单启发式:不足 300 条且账号年提交数更大时才补全
const approxYearTotal = LIVE.account?.yearCommits
? Number(LIVE.account.yearCommits)
: sumCounts(LIVE.project.commitTrend365)
if (!approxYearTotal || existing.length >= approxYearTotal) return
if (existing.length >= 300) return
LIVE.project._augmenting = true
const sinceISO = new Date(Date.now() - 365 * 24 * 3600 * 1000).toISOString()
const perPage = 100
const maxPages = 10 // 最多抓取 1000 条,避免过多请求
const merged = new Map(existing.map((c) => [normalizeSha(c.hash), c]))
for (let page = 1; page <= maxPages; page++) {
const url = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/commits?since=${encodeURIComponent(
sinceISO,
)}&per_page=${perPage}&page=${page}`
const res = await fetch(url, {
headers: {
Accept: 'application/vnd.github+json',
},
})
if (!res.ok) break
const arr = await res.json()
if (!Array.isArray(arr) || arr.length === 0) break
for (const it of arr) {
const sha = it.sha || ''
const key = normalizeSha(sha)
if (!key) continue
if (merged.has(key)) continue
merged.set(key, {
hash: sha,
datetime: it.commit?.author?.date || it.commit?.committer?.date,
author: it.commit?.author?.name || it.author?.login || '',
email: it.commit?.author?.email || '',
subject: (it.commit?.message || '').split('\n')[0],
modules: [],
})
}
// 如果已经达到大致目标数量,可提前停止
if (merged.size >= approxYearTotal) break
}
// 写回并标记
LIVE.project.recentCommits = Array.from(merged.values()).sort(
(a, b) => new Date(b.datetime) - new Date(a.datetime),
)
LIVE.project._augmentedYear = true
// 重新渲染一次
renderRecentCommitsFromProject(LIVE.project)
} catch (e) {
console.warn('[ensureRecentCommitsAugmented] failed:', e)
} finally {
LIVE.project._augmenting = false
}
}
function normalizeSha(hash) {
if (!hash) return ''
const m = String(hash).match(/[0-9a-f]{7,40}$/i)
return m ? m[0].toLowerCase() : ''
}
function sumCounts(series) {
if (!Array.isArray(series)) return 0
return series.reduce((acc, p) => acc + (Number(p.count) || 0), 0)
}
// 计算所有模块名(并去重)
function computeAllModuleNames(project) {
const set = new Set(
Array.isArray(project.modulesAllowed) ? project.modulesAllowed : [],
)
function addKeys(obj) {
if (obj && typeof obj === 'object')
Object.keys(obj).forEach((k) => set.add(k))
}
addKeys(project.weekTotals?.byModule)
addKeys(project.monthTotals?.byModule)
addKeys(project.yearTotals?.byModule)
if (Array.isArray(project.months))
project.months.forEach((m) => addKeys(m.byModule))
return Array.from(set)
}
// 初始化或更新模块下拉选项,保持当前选择
function ensureModuleSelectOptions(names) {
const modSel = document.getElementById('moduleSelect')
if (!modSel) return
const want = ['all', ...names]
const have = Array.from(modSel.options).map((o) => o.value)
const same =
want.length === have.length && want.every((v, i) => v === have[i])
if (same) return
const current = modSel.value || 'all'
modSel.innerHTML =
`<option value="all">${currentLang === 'zh' ? '全部' : 'All'}</option>` +
names.map((n) => `<option value="${n}">${n}</option>`).join('')
// 恢复选择
modSel.value = want.includes(current) ? current : 'all'
}
// 用 LIVE 的 months 列表填充月份下拉
function ensureMonthOptions(project) {
const el = document.getElementById('monthPicker')
if (!el) return
const months = Array.isArray(project.months)
? project.months.map((m) => m.month)
: []
if (!months.length) return
const have = Array.from(el.options || []).map((o) => o.value)
const want = ['', ...months]
const same =
have.length === want.length && have.every((v, i) => v === want[i])
if (same) return
const placeholder = currentLang === 'zh' ? '选择月份' : 'Select month'
el.innerHTML =
`<option value="">— ${placeholder} —</option>` +
months.map((m) => `<option value="${m}">${m}</option>`).join('')
if (STATE.view.range === 'month' && STATE.view.month) {
el.value = STATE.view.month
}
}
function hideAllDataSections() {
;['projectStats', 'contributionSection', 'recentCommits'].forEach((id) => {
const el = document.getElementById(id)
if (el) el.style.display = 'none'
})
}
// ==================== 渲染贡献热力图 ====================
function renderContributionHeatmap(modules) {
const container = document.getElementById('heatmapContainer')
if (!container) return
const commitsByDate = {}
modules.forEach((m) => {
;(m.commits || []).forEach((c) => {
if (!c.datetime) return
const date = c.datetime.split('T')[0]
commitsByDate[date] = (commitsByDate[date] || 0) + 1
})
})
LAST_HEATMAP = { type: 'modules', data: modules }
renderHeatmapGridFromMap(commitsByDate)
}
// ==================== 渲染提交趋势图表 ====================
function renderCommitTrendChart(modules) {
const canvas = document.getElementById('commitTrendChart')
if (!canvas) return
const commitsByDate = {}
modules.forEach((m) => {
;(m.commits || []).forEach((c) => {
if (!c.datetime) return
const date = c.datetime.split('T')[0]
commitsByDate[date] = (commitsByDate[date] || 0) + 1
})
})
const days = 30
const today = new Date()
const labels = []
const data = []
for (let i = days - 1; i >= 0; i--) {
const d = new Date(today)
d.setDate(d.getDate() - i)
const dateStr = d.toISOString().split('T')[0]
labels.push(`${d.getMonth() + 1}/${d.getDate()}`)
data.push(commitsByDate[dateStr] || 0)
}
new Chart(canvas, {
type: 'line',
data: {
labels,
datasets: [
{
label: '每日提交数',
data,
borderColor: '#4f46e5',
backgroundColor: 'rgba(79, 70, 229, 0.1)',
fill: true,
tension: 0.3,
pointRadius: 3,
pointHoverRadius: 5,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
y: { beginAtZero: true, ticks: { precision: 0 } },
},
},
})
}
// 从预计算序列渲染提交趋势
function renderCommitTrendChartFromSeries(series) {
const canvas = document.getElementById('commitTrendChart')
if (!canvas) return
const labels = series.map((p) => {
const d = new Date(p.date)
return `${d.getMonth() + 1}/${d.getDate()}`
})
const data = series.map((p) => p.count || 0)
STATE.charts.commitTrend = new Chart(canvas, {
type: 'line',
data: {
labels,
datasets: [
{
label: '每日提交数',
data,
borderColor: '#4f46e5',
backgroundColor: 'rgba(79, 70, 229, 0.1)',
fill: true,
tension: 0.3,
pointRadius: 3,
pointHoverRadius: 5,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: { y: { beginAtZero: true, ticks: { precision: 0 } } },
},
})
}
// ==================== 渲染模块分布图表 ====================
function renderModuleDistChart(modules) {
const canvas = document.getElementById('moduleDistChart')
if (!canvas) return
if (!modules || modules.length === 0) {
const parent = canvas.parentElement
if (parent)
parent.innerHTML +=
'<div class="text-sm text-gray-500 text-center py-4">暂无模块提交数据</div>'
return
}
const labels = modules.map((m) =>
m.name === 'ProjectPrinting' ? '主仓库' : m.name,
)
const data = modules.map((m) => (m.commits || []).length)
const sum = data.reduce((a, b) => a + b, 0)
if (sum === 0) {
const parent = canvas.parentElement
if (parent)
parent.innerHTML +=
'<div class="text-sm text-gray-500 text-center py-4">最近无模块提交</div>'
return
}
const colors = labels.map((n) => moduleColor(n))
const borderColor = getSurfaceColor()
new Chart(canvas, {
type: 'doughnut',
data: {
labels,
datasets: [
{
data,
backgroundColor: colors,
borderWidth: 2,
borderColor: borderColor,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
labels: { padding: 10, font: { size: 11 } },
},
},
},
})
}
function renderModuleDistChartFromSeries(items) {
const canvas = document.getElementById('moduleDistChart')
if (!canvas) return
if (!items || items.length === 0) {
const parent = canvas.parentElement
if (parent)
parent.innerHTML +=
'<div class="text-sm text-gray-500 text-center py-4">暂无模块提交数据</div>'
return
}
const labels = items.map((m) => m.name)
const data = items.map((m) => m.commits || 0)
const sum = data.reduce((a, b) => a + b, 0)
if (sum === 0) {
const parent = canvas.parentElement
if (parent)
parent.innerHTML +=
'<div class="text-sm text-gray-500 text-center py-4">最近无模块提交</div>'
return
}
const colors = labels.map((n) => moduleColor(n))
const borderColor = getSurfaceColor()
new Chart(canvas, {
type: 'doughnut',
data: {
labels,
datasets: [
{
data,
backgroundColor: colors,
borderWidth: 2,
borderColor: borderColor,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
labels: { padding: 10, font: { size: 11 } },
},
},
},
})
}
// 使用报告 JSON 的 modules(包含 added/removed)渲染“按新增行数”的模块分布
function renderModuleLinesDistFromModules(modules) {
const canvas = document.getElementById('moduleDistChart')
if (!canvas) return
if (!Array.isArray(modules) || modules.length === 0) {
const parent = canvas.parentElement
if (parent)
parent.innerHTML +=
'<div class="text-sm text-gray-500 text-center py-4">暂无模块数据</div>'
return