-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1535 lines (1283 loc) · 48.7 KB
/
script.js
File metadata and controls
1535 lines (1283 loc) · 48.7 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
/* =========================================================
GitHub Issue Tracker
功能:
- 自动拉取用户有权限的 GitHub Project
- 直接从 GitHub Project 拉取 Issue(不本地保存)
- 过滤已关闭的 Issue
- 统计:状态、优先级、里程碑、分配人、Estimation
- 多条件同时过滤(AND 逻辑)
- 只有点击刷新按钮才更新数据
========================================================= */
const STORAGE_KEYS = {
TOKEN: "github_token",
PROJECTS: "my_projects",
SELECTED_PROJECT: "selected_project",
CACHED_ISSUES: "cached_issues",
LAST_FETCH_TIME: "last_fetch_time"
};
const GITHUB_GRAPHQL = "https://api.github.com/graphql";
const ASSIGNEE_PAGE_SIZE = 10;
const PAGE_SIZE = 100;
const MAX_CONCURRENT = 6; // 最大并发数
// 全局状态
let cachedIssues = [];
let filters = {
state: null,
priority: null,
milestone: null,
assignee: null,
team: null,
hasEstimation: null
};
let assigneePage = 0;
// 当前请求的 AbortController
let currentAbortController = null;
// 缓存 Chart 实例
const chartInstances = new Map();
// DOM 元素缓存(仅缓存静态元素)
const staticDomCache = new Map();
/* ---------------- 工具函数 ---------------- */
/**
* 获取 DOM 元素(带缓存,仅用于静态元素)
*/
const STATIC_ELEMENTS = new Set([
"loading-container", "loading-text", "loading-percent",
"loading-bar-fill", "loading-detail", "fetch-btn",
"token-status", "token-input", "project-select", "last-fetch-time"
]);
function getElement(id, useCache = true) {
const canCache = useCache && STATIC_ELEMENTS.has(id);
if (canCache && staticDomCache.has(id)) {
return staticDomCache.get(id);
}
const el = document.getElementById(id);
if (canCache && el) {
staticDomCache.set(id, el);
}
return el;
}
/**
* 安全地设置元素文本
*/
function setText(el, text) {
if (el) el.textContent = text;
}
/**
* 安全地设置元素 HTML
*/
function setHTML(el, html) {
if (el) el.innerHTML = html;
}
/**
* 防抖函数
*/
function debounce(fn, delay) {
let timer = null;
return function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
/**
* 按值排序对象
*/
function sortObjectByValue(obj, desc = true) {
return Object.entries(obj)
.sort((a, b) => desc ? b[1] - a[1] : a[1] - b[1])
.reduce((acc, [k, v]) => { acc[k] = v; return acc; }, {});
}
/**
* 获取优先级样式类
*/
function getPriorityClass(priority) {
if (!priority) return "none";
const lower = priority.toLowerCase();
if (/p0|high|critical/.test(lower)) return "high";
if (/p1|medium/.test(lower)) return "medium";
if (/p2|low/.test(lower)) return "low";
return "none";
}
/**
* 格式化日期
*/
function formatDate(dateStr) {
if (!dateStr) return "未知";
try {
return new Date(dateStr).toLocaleString();
} catch {
return "未知";
}
}
/**
* 生成安全的 ID
*/
function safeId(str) {
return String(str || "").replace(/[^a-zA-Z0-9]/g, "_");
}
/* ---------------- 页面初始化 ---------------- */
document.addEventListener("DOMContentLoaded", () => {
initTabs();
initEventDelegation();
updateTokenStatus();
loadProjectSelect();
updateLastFetchTime();
loadCachedData();
});
/* ---------------- Tab 切换 ---------------- */
function initTabs() {
const navTabs = document.querySelectorAll(".nav-tab");
const tabContents = document.querySelectorAll(".tab-content");
navTabs.forEach(tab => {
tab.addEventListener("click", () => {
const targetTab = tab.dataset.tab;
requestAnimationFrame(() => {
// 更新 Tab 状态
navTabs.forEach(t => t.classList.toggle("active", t === tab));
// 更新内容区域
tabContents.forEach(content => {
content.classList.toggle("active", content.id === `tab-${targetTab}`);
});
});
});
});
}
/* ---------------- 事件委托 ---------------- */
function initEventDelegation() {
document.addEventListener("click", handleGlobalClick);
}
function handleGlobalClick(e) {
const target = e.target;
// 处理展开/折叠子 Issue
const toggleArrow = target.closest(".toggle-arrow");
if (toggleArrow) {
e.preventDefault();
const toggleId = toggleArrow.dataset.toggle;
if (toggleId) toggleChildren(toggleId);
return;
}
// 处理标签点击过滤
const labelTag = target.closest(".label-tag");
if (labelTag && labelTag.dataset.filterType) {
e.preventDefault();
handleLabelFilter(labelTag);
return;
}
// 处理分页按钮
const paginationBtn = target.closest(".pagination-btn");
if (paginationBtn && !paginationBtn.disabled) {
e.preventDefault();
const delta = paginationBtn.dataset.delta;
const type = paginationBtn.dataset.type;
if (delta && type) handlePageChange(parseInt(delta), type);
return;
}
}
/**
* 处理标签过滤点击
*/
function handleLabelFilter(labelTag) {
const filterType = labelTag.dataset.filterType;
const filterValue = labelTag.dataset.filterValue;
const isWorkload = labelTag.dataset.isWorkload === "true";
// 重置分配人分页
assigneePage = 0;
if (isWorkload) {
handleWorkloadFilter(filterValue);
} else {
handleNormalFilter(filterType, filterValue);
}
// 添加这行:刷新统计界面
refreshStats();
}
function handleWorkloadFilter(filterValue) {
if (filterValue === "all") {
filters.team = null;
filters.hasEstimation = null;
} else if (filterValue === "no-estimation") {
filters.hasEstimation = filters.hasEstimation === false ? null : false;
if (filters.hasEstimation === false) filters.team = null;
} else {
if (filters.team === filterValue && filters.hasEstimation === true) {
filters.team = null;
filters.hasEstimation = null;
} else {
filters.team = filterValue;
filters.hasEstimation = true;
}
}
}
function handleNormalFilter(filterType, filterValue) {
if (filterValue === "all") {
filters[filterType] = null;
} else if (filters[filterType] === filterValue) {
filters[filterType] = null;
} else {
filters[filterType] = filterValue;
}
}
/**
* 处理分页变化
*/
function handlePageChange(delta, type) {
assigneePage = Math.max(0, assigneePage + delta);
// 只更新分配人标签区域
const container = document.getElementById(`labels-${type}`);
if (container) {
// 使用当前过滤后的数据重新计算
const filteredIssues = applyFilters(cachedIssues);
const stats = getStatsData(filteredIssues);
const category = {
type,
data: stats.assigneeStats,
colors: getAssigneeColors(),
paginated: true
};
renderPaginatedLabels(category, container);
}
}
/* ---------------- Loading Progress ---------------- */
function showLoading(text = "正在加载...", detail = "") {
requestAnimationFrame(() => {
const container = getElement("loading-container");
const textEl = getElement("loading-text");
const percentEl = getElement("loading-percent");
const fillEl = getElement("loading-bar-fill");
const detailEl = getElement("loading-detail");
const btn = getElement("fetch-btn");
if (container) container.classList.remove("hidden");
setText(textEl, text);
setText(percentEl, "0%");
if (fillEl) fillEl.style.width = "0%";
setText(detailEl, detail);
if (btn) btn.classList.add("loading");
});
}
function updateLoading(percent, text = null, detail = null) {
requestAnimationFrame(() => {
const percentEl = getElement("loading-percent");
const fillEl = getElement("loading-bar-fill");
setText(percentEl, `${Math.round(percent)}%`);
if (fillEl) fillEl.style.width = `${percent}%`;
if (text !== null) setText(getElement("loading-text"), text);
if (detail !== null) setText(getElement("loading-detail"), detail);
});
}
function hideLoading() {
requestAnimationFrame(() => {
const container = getElement("loading-container");
const btn = getElement("fetch-btn");
if (container) container.classList.add("hidden");
if (btn) btn.classList.remove("loading");
});
}
// 精简 Token 管理
/* ---------------- Token 管理 ---------------- */
const loadToken = () => localStorage.getItem(STORAGE_KEYS.TOKEN) || "";
function saveToken() {
const token = getElement("token-input")?.value?.trim();
if (!token) return alert("请输入有效的 Token");
localStorage.setItem(STORAGE_KEYS.TOKEN, token);
getElement("token-input").value = "";
updateTokenStatus();
fetchProjects();
}
function clearToken() {
localStorage.removeItem(STORAGE_KEYS.TOKEN);
updateTokenStatus();
}
function updateTokenStatus() {
const el = getElement("token-status");
if (!el) return;
const token = loadToken();
el.className = `token-status ${token ? "success" : "error"}`;
el.textContent = token ? `✓ Token 已配置(${token.slice(0, 8)}...)` : "✗ 未配置 Token";
}
/* ---------------- 缓存管理 ---------------- */
function loadCachedData() {
try {
const cached = localStorage.getItem(STORAGE_KEYS.CACHED_ISSUES);
if (cached) {
cachedIssues = JSON.parse(cached);
if (cachedIssues.length > 0) {
// 延迟渲染,优先显示页面框架
if ("requestIdleCallback" in window) {
requestIdleCallback(() => refreshStats(), { timeout: 500 });
} else {
setTimeout(refreshStats, 100);
}
}
}
} catch (e) {
console.error("加载缓存失败:", e);
cachedIssues = [];
}
}
const saveCachedIssues = debounce(() => {
try {
localStorage.setItem(STORAGE_KEYS.CACHED_ISSUES, JSON.stringify(cachedIssues));
} catch (e) {
console.error("保存缓存失败:", e);
// 如果存储失败(可能是存储已满),尝试清理旧数据
try {
localStorage.removeItem(STORAGE_KEYS.CACHED_ISSUES);
} catch {}
}
}, 300);
function updateLastFetchTime() {
const timeEl = getElement("last-fetch-time");
const lastFetch = localStorage.getItem(STORAGE_KEYS.LAST_FETCH_TIME);
if (timeEl && lastFetch) {
const date = new Date(parseInt(lastFetch));
timeEl.textContent = `上次更新: ${date.toLocaleString()}`;
}
}
/* ---------------- 项目管理 ---------------- */
function loadProjectSelect() {
const select = getElement("project-select");
if (!select) return;
const saved = localStorage.getItem(STORAGE_KEYS.PROJECTS);
const selectedProject = localStorage.getItem(STORAGE_KEYS.SELECTED_PROJECT);
// 使用 DocumentFragment 批量操作
const fragment = document.createDocumentFragment();
const defaultOpt = document.createElement("option");
defaultOpt.value = "";
defaultOpt.textContent = "-- 请选择 --";
fragment.appendChild(defaultOpt);
if (saved) {
try {
const projects = JSON.parse(saved);
projects.forEach(p => {
const opt = document.createElement("option");
const value = JSON.stringify(p);
opt.value = value;
opt.textContent = `${p.owner} / ${p.title}`;
opt.selected = selectedProject === value;
fragment.appendChild(opt);
});
} catch (e) {
console.error("加载项目列表失败:", e);
}
}
select.innerHTML = "";
select.appendChild(fragment);
}
function saveSelectedProject() {
const select = getElement("project-select");
if (select?.value) {
localStorage.setItem(STORAGE_KEYS.SELECTED_PROJECT, select.value);
}
}
/* ---------------- 获取项目列表 ---------------- */
async function fetchProjects() {
const token = loadToken();
if (!token) {
alert("请先配置 Token");
return;
}
showLoading("正在获取项目列表...");
const query = `
query {
viewer {
login
projectsV2(first: 50) {
nodes { title number owner { ... on Organization { login } ... on User { login } } }
}
organizations(first: 20) {
nodes {
login
projectsV2(first: 50) {
nodes { title number owner { ... on Organization { login } ... on User { login } } }
}
}
}
}
}`;
try {
const res = await fetch(GITHUB_GRAPHQL, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ query })
});
const json = await res.json();
if (json.errors) {
hideLoading();
alert("获取项目失败:" + json.errors[0].message);
return;
}
const projects = [];
const viewer = json.data?.viewer;
if (!viewer) {
hideLoading();
alert("无法获取用户信息,请检查 Token");
return;
}
// 用户项目
viewer.projectsV2?.nodes?.forEach(p => {
if (p?.title && p?.number && p?.owner?.login) {
projects.push({
title: p.title,
number: p.number,
owner: p.owner.login,
ownerType: "User"
});
}
});
// 组织项目
viewer.organizations?.nodes?.forEach(org => {
org?.projectsV2?.nodes?.forEach(p => {
if (p?.title && p?.number && p?.owner?.login) {
projects.push({
title: p.title,
number: p.number,
owner: p.owner.login,
ownerType: "Organization"
});
}
});
});
localStorage.setItem(STORAGE_KEYS.PROJECTS, JSON.stringify(projects));
loadProjectSelect();
hideLoading();
if (projects.length === 0) {
alert("未找到任何项目,请确认您有权限访问 GitHub Projects");
}
} catch (err) {
hideLoading();
console.error("获取项目失败:", err);
alert("网络错误:" + err.message);
}
}
/* ---------------- 拉取并刷新 ---------------- */
async function fetchAndRefresh() {
const issues = await fetchProjectIssues();
if (issues) {
cachedIssues = issues;
saveCachedIssues();
localStorage.setItem(STORAGE_KEYS.LAST_FETCH_TIME, Date.now().toString());
updateLastFetchTime();
// 重置过滤器和分页
resetFilters();
refreshStats();
}
}
function resetFilters() {
filters = {
state: null,
priority: null,
milestone: null,
assignee: null,
team: null,
hasEstimation: null
};
assigneePage = 0;
}
/* ---------------- 从 Project 拉取 Issue(优化版) ---------------- */
async function fetchProjectIssues() {
const select = getElement("project-select");
if (!select?.value) return alert("请先选择一个项目"), null;
const token = loadToken();
if (!token) return alert("请先配置 GitHub Token"), null;
let project;
try {
project = JSON.parse(select.value);
} catch {
return alert("项目数据格式错误"), null;
}
saveSelectedProject();
showLoading("正在获取 Issue 列表...", `项目: ${project.title}`);
const ownerQuery = project.ownerType === "Organization" ? "organization" : "user";
const query = buildQuery(ownerQuery);
try {
// 取消之前的请求
if (currentAbortController) {
currentAbortController.abort();
}
currentAbortController = new AbortController();
const signal = currentAbortController.signal;
// 获取第一页和总数
const first = await fetchPage(token, query, project.owner, project.number, null, signal);
if (!first.ok) return hideLoading(), alert(first.error), null;
let allItems = first.items;
const { totalCount, projectTitle } = first;
updateLoading(15, null, `已获取 ${allItems.length} / ${totalCount} 条`);
// 并发获取剩余页面
if (first.hasNext) {
const remaining = await fetchAllPages(token, query, project.owner, project.number, first.cursor, totalCount, allItems.length);
allItems = allItems.concat(remaining);
}
updateLoading(90, "正在处理数据...", `共 ${allItems.length} 条`);
const issues = processItems(allItems, projectTitle);
updateLoading(100, "加载完成!", `共 ${issues.length} 个有效 Issue`);
setTimeout(hideLoading, 200);
return issues;
} catch (err) {
console.error("获取 Issue 失败:", err);
hideLoading();
return alert("请求错误:" + err.message), null;
}
}
/**
* 构建 GraphQL 查询
*/
function buildQuery(ownerQuery) {
return `query($owner:String!,$number:Int!,$cursor:String){${ownerQuery}(login:$owner){projectV2(number:$number){title items(first:${PAGE_SIZE},after:$cursor){totalCount pageInfo{hasNextPage endCursor}nodes{content{...on Issue{id number title state url updatedAt milestone{title}labels(first:10){nodes{name}}assignees(first:5){nodes{login}}repository{name owner{login}}parent{id}}}fieldValues(first:15){nodes{...on ProjectV2ItemFieldSingleSelectValue{field{...on ProjectV2SingleSelectField{name}}name}...on ProjectV2ItemFieldNumberValue{field{...on ProjectV2FieldCommon{name}}number}}}}}}}}`;
}
/**
* 获取单页数据
*/
async function fetchPage(token, query, owner, number, cursor, signal = null) {
const options = {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
"GraphQL-Features": "sub_issues"
},
body: JSON.stringify({ query, variables: { owner, number, cursor } })
};
if (signal) options.signal = signal;
const res = await fetch(GITHUB_GRAPHQL, options);
if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
const json = await res.json();
if (json.errors) return { ok: false, error: json.errors[0].message };
const proj = json.data?.[Object.keys(json.data)[0]]?.projectV2;
if (!proj) return { ok: false, error: "无法找到该 Project" };
const items = proj.items;
return {
ok: true,
items: items.nodes || [],
totalCount: items.totalCount || 0,
hasNext: items.pageInfo?.hasNextPage,
cursor: items.pageInfo?.endCursor,
projectTitle: proj.title
};
}
/**
* 并发获取所有剩余页面
*/
async function fetchAllPages(token, query, owner, number, startCursor, totalCount, fetched) {
const results = [];
let cursor = startCursor;
while (cursor) {
const res = await fetchPage(token, query, owner, number, cursor);
if (!res.ok) {
console.error("获取页面失败:", res.error);
break;
}
results.push(...res.items);
cursor = res.hasNext ? res.cursor : null;
const progress = Math.min(15 + ((fetched + results.length) / totalCount) * 70, 85);
updateLoading(progress, null, `已获取 ${fetched + results.length} / ${totalCount} 条`);
}
return results;
}
/**
* 处理 Issue 数据
*/
function processItems(items, projectTitle) {
const issues = [];
const issueMap = new Map();
for (let i = 0, len = items.length; i < len; i++) {
const content = items[i]?.content;
if (!content?.url || content.state === "CLOSED") continue;
const fields = items[i].fieldValues?.nodes;
let status, priority, estimation, team, funcType;
if (fields) {
for (const f of fields) {
const name = f?.field?.name?.toLowerCase();
if (!name) continue;
const val = f.name ?? f.number;
if (name === FIELD_NAMES.STATUS) status = val;
else if (name === FIELD_NAMES.PRIORITY) priority = val;
else if (name === "estimation") estimation = val;
else if (name === "team") team = val;
else if (name === "functiontype") funcType = val;
}
}
const issue = {
id: content.id,
owner: content.repository?.owner?.login || "",
repo: content.repository?.name || "",
number: content.number,
url: content.url,
title: content.title || "",
state: status || "未知",
issueState: content.state,
milestone: content.milestone?.title || null,
updated_at: content.updatedAt,
labels: content.labels?.nodes?.map(n => n.name) || [],
priority: priority || "未设置",
project_name: projectTitle,
FunctionType: funcType || "",
assignees: content.assignees?.nodes?.map(a => a.login) || [],
estimation: typeof estimation === "number" ? estimation : null,
team: team || "未设置",
parentId: content.parent?.id || null,
childIds: []
};
issues.push(issue);
issueMap.set(issue.id, issue);
}
// 建立父子关系
for (const issue of issues) {
if (issue.parentId) {
issueMap.get(issue.parentId)?.childIds.push(issue.id);
}
}
return issues;
}
/* ---------------- 统计相关函数 ---------------- */
/**
* 获取用于统计的 Issue(排除在列表中有父 Issue 的子 Issue)
*/
function getIssuesForStats(issues) {
const issueIdSet = new Set(issues.map(i => i.id));
return issues.filter(issue => !issue.parentId || !issueIdSet.has(issue.parentId));
}
/**
* 生成统计数据(带缓存)
*/
function getStatsData(issues) {
const statsIssues = getIssuesForStats(issues);
const stats = {
stateStats: {},
priorityStats: {},
milestoneStats: {},
assigneeStats: {},
teamWorkloadStats: {},
noEstimationCount: 0,
statsIssueCount: statsIssues.length,
totalIssueCount: issues.length
};
for (const issue of statsIssues) {
const {
state = "未知",
priority = "未设置",
milestone,
team = "未设置",
estimation,
assignees
} = issue;
stats.stateStats[state] = (stats.stateStats[state] || 0) + 1;
stats.priorityStats[priority] = (stats.priorityStats[priority] || 0) + 1;
stats.milestoneStats[milestone || "未设置"] = (stats.milestoneStats[milestone || "未设置"] || 0) + 1;
if (estimation > 0) {
stats.teamWorkloadStats[team] = (stats.teamWorkloadStats[team] || 0) + estimation;
} else {
stats.noEstimationCount++;
}
if (assignees?.length > 0) {
for (const assignee of assignees) {
stats.assigneeStats[assignee] = (stats.assigneeStats[assignee] || 0) + 1;
}
} else {
stats.assigneeStats["未分配"] = (stats.assigneeStats["未分配"] || 0) + 1;
}
}
stats.assigneeStats = sortObjectByValue(stats.assigneeStats);
stats.teamWorkloadStats = sortObjectByValue(stats.teamWorkloadStats);
return stats;
}
/**
* 检查是否有激活的过滤器
*/
const hasActiveFilters = () => !!(filters.state || filters.priority || filters.milestone || filters.assignee || filters.team || filters.hasEstimation !== null);
/**
* 应用过滤器
*/
function applyFilters(issues) {
if (!hasActiveFilters()) return issues;
const { state, priority, milestone, assignee, team, hasEstimation } = filters;
return issues.filter(issue => {
if (state && issue.state !== state) return false;
if (priority && issue.priority !== priority) return false;
if (milestone && (issue.milestone || "未设置") !== milestone) return false;
if (assignee) {
if (assignee === "未分配" ? issue.assignees?.length : !issue.assignees?.includes(assignee)) return false;
}
if (team && (issue.team || "未设置") !== team) return false;
// 修改:更明确的 estimation 判断
if (hasEstimation === true && !(issue.estimation > 0)) return false; // 必须有且 > 0
if (hasEstimation === false && issue.estimation > 0) return false; // 必须无或 = 0
return true;
});
}
/**
* 清除所有过滤器
*/
function clearAllFilters() {
resetFilters();
refreshStats();
}
/* ---------------- 颜色配置 ---------------- */
function getStateColors() {
return ["#2da44e", "#cf222e", "#57606a", "#0969da", "#8250df", "#bf8700"];
}
function getPriorityColors() {
return ["#cf222e", "#bf8700", "#2da44e", "#6e7781"];
}
function getMilestoneColors() {
return ["#0969da", "#6f42c1", "#fd7e14", "#20c997", "#e83e8c", "#17a2b8"];
}
function getWorkloadColors() {
return ["#8250df", "#0969da", "#2da44e", "#bf8700", "#cf222e", "#fd7e14", "#e83e8c", "#17a2b8", "#6e7781"];
}
function getAssigneeColors() {
return ["#0969da", "#6f42c1", "#fd7e14", "#20c997", "#e83e8c", "#17a2b8", "#2da44e", "#cf222e"];
}
/* ---------------- 刷新统计界面 ---------------- */
function refreshStats() {
const container = getElement("stats-container", false);
if (!container) return;
destroyAllCharts();
const filteredIssues = applyFilters(cachedIssues);
const stats = getStatsData(filteredIssues);
// 移除这行,缓存逻辑有问题
// cachedStats = stats;
// 构建 DOM
const fragment = document.createDocumentFragment();
// 统计说明
fragment.appendChild(createStatsInfo(stats));
// 过滤条件显示
if (hasActiveFilters()) {
fragment.appendChild(createFilterInfo());
}
// 图表区域
const chartsRow = document.createElement("div");
chartsRow.className = "charts-row";
const categories = getChartCategories(stats);
categories.forEach(category => {
chartsRow.appendChild(createChartWrapper(category));
});
fragment.appendChild(chartsRow);
// 一次性更新 DOM
container.innerHTML = "";
container.appendChild(fragment);
// 延迟渲染图表
requestAnimationFrame(() => {
categories.forEach(category => {
renderPieChart(`chart-${category.type}`, category);
});
});
// 渲染 Issue 列表
loadFilteredIssues();
}
function destroyAllCharts() {
chartInstances.forEach(chart => {
try {
chart.destroy();
} catch (e) {
console.warn("销毁图表失败:", e);
}
});
chartInstances.clear();
}
function createStatsInfo(stats) {
const div = document.createElement("div");
div.className = "stats-info";
const { statsIssueCount, totalIssueCount } = stats;
const excluded = totalIssueCount - statsIssueCount;
div.innerHTML = excluded > 0
? `<span class="stats-note">📊 统计基于 ${statsIssueCount} 个顶层 Issue(已排除 ${excluded} 个子 Issue)</span>`
: `<span class="stats-note">📊 统计基于 ${statsIssueCount} 个 Issue</span>`;
return div;
}
function createFilterInfo() {
const div = document.createElement("div");
div.className = "filter-info";
const activeFilters = [];
if (filters.state) activeFilters.push(`状态: ${filters.state}`);
if (filters.priority) activeFilters.push(`优先级: ${filters.priority}`);
if (filters.milestone) activeFilters.push(`里程碑: ${filters.milestone}`);
if (filters.assignee) activeFilters.push(`分配人: ${filters.assignee}`);
if (filters.team) activeFilters.push(`Team: ${filters.team}`);
if (filters.hasEstimation === true) activeFilters.push(`工作量: 有`);
if (filters.hasEstimation === false) activeFilters.push(`工作量: 未设置`);
div.innerHTML = `
<span class="filter-label">当前过滤:${activeFilters.join(" + ")}</span>
<button class="btn btn-small btn-secondary" onclick="clearAllFilters()">清除全部</button>
`;
return div;
}
function getChartCategories(stats) {
const workloadData = { ...stats.teamWorkloadStats };
if (stats.noEstimationCount > 0) {
workloadData["未设置"] = stats.noEstimationCount;
}
return [
{ title: "状态", data: stats.stateStats, type: "state", colors: getStateColors() },
{ title: "优先级", data: stats.priorityStats, type: "priority", colors: getPriorityColors() },
{ title: "里程碑", data: stats.milestoneStats, type: "milestone", colors: getMilestoneColors() },
{ title: "工作量", data: workloadData, type: "workload", colors: getWorkloadColors(), isWorkload: true },
{ title: "分配人", data: stats.assigneeStats, type: "assignee", colors: getAssigneeColors(), paginated: true }
];
}
/* ---------------- 图表组件 ---------------- */
function createChartWrapper(category) {
const wrapper = document.createElement("div");
wrapper.className = "chart-wrapper";
// 标题
wrapper.appendChild(createChartTitle(category));
// Canvas
const canvasContainer = document.createElement("div");
canvasContainer.className = "canvas-container";
const canvas = document.createElement("canvas");
canvas.id = `chart-${category.type}`;
canvasContainer.appendChild(canvas);
wrapper.appendChild(canvasContainer);
// 标签
const labelsContainer = document.createElement("div");
labelsContainer.className = "chart-labels";
labelsContainer.id = `labels-${category.type}`;
if (category.paginated) {
renderPaginatedLabels(category, labelsContainer);