github-overview 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/index.html CHANGED
@@ -4,6 +4,7 @@
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
6
  <title>github-overview</title>
7
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%230f1115'/%3E%3Cpath d='M4 11V6l4-2 4 2v5' fill='none' stroke='%234f8cff' stroke-width='1.6' stroke-linejoin='round'/%3E%3C/svg%3E">
7
8
  <style>
8
9
  :root[data-theme="dark"] {
9
10
  --bg-base: #0f1115;
@@ -62,7 +63,11 @@
62
63
  .repo { font-size: 16px; font-weight: 600; white-space: nowrap; }
63
64
  .repo span { color: var(--label-secondary); font-weight: 400; }
64
65
  .caret { color: var(--label-secondary); font-weight: 400; }
65
- .repo-wrap { position: relative; }
66
+ .repo-wrap { position: relative; display: flex; align-items: center; gap: 4px; }
67
+ .repo-open { display: inline-flex; width: 20px; height: 20px; align-items: center; justify-content: center;
68
+ border-radius: 6px; color: var(--label-secondary); }
69
+ .repo-open:hover { background: var(--border-l1); color: var(--label-primary); }
70
+ .repo-open[hidden] { display: none; }
66
71
  .repo-wrap > .repo { border: 0; background: none; padding: 0; font: inherit; font-weight: 600; color: var(--label-primary); cursor: pointer; }
67
72
  .repo-wrap > .repo:hover { color: var(--label-secondary); }
68
73
  .repo-menu { position: absolute; top: 26px; left: -8px; z-index: 20; min-width: 200px; max-height: 260px; overflow: auto;
@@ -73,12 +78,26 @@
73
78
  .spacer { flex: 1; }
74
79
  .seg { display: inline-flex; border: 1px solid var(--border-l2); border-radius: 8px; overflow: hidden; height: 28px; }
75
80
  .seg button { border: 0; border-radius: 0; height: 26px; margin: 1px; padding: 0 10px; color: var(--label-secondary); }
76
- .seg button.on { background: var(--bg-layer-2); color: var(--label-primary); }
81
+ .seg button.on { background: var(--bg-layer-2); color: var(--label-primary); font-weight: 600; }
82
+ [data-theme="light"] .seg button.on { box-shadow: inset 0 0 0 1px var(--border-l2); }
77
83
 
78
84
  .kpis { display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px 28px; padding: 18px 0 2px; }
79
85
  .kpi-label { font-size: 12px; color: var(--label-secondary); }
80
86
  .kpi-value { font-size: 24px; font-weight: 600; letter-spacing: -.02em; line-height: 1.35; }
81
87
  .kpi-sub { font-size: 12px; color: var(--label-secondary); }
88
+ .head-note { font-size: 12px; font-weight: 400; color: var(--label-secondary); margin-left: 6px; }
89
+ #sec-top { margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border-l1); }
90
+ #fork-stats { grid-template-columns: 1fr 1fr; }
91
+ #fork-list { margin-top: 10px; }
92
+ #fork-list td:first-child { font-size: 13px; font-weight: 400; }
93
+ .leaders { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px 28px; padding: 14px 0 4px; }
94
+ .lead { min-width: 0; }
95
+ .lead-label { font-size: 12px; color: var(--label-secondary); }
96
+ .lead-name { font-size: 12px; color: var(--label-primary); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
97
+ .lead-value { font-size: 24px; font-weight: 600; letter-spacing: -.02em; line-height: 1.35; font-variant-numeric: tabular-nums; }
98
+ .lead-sub { font-size: 12px; color: var(--label-secondary); }
99
+ .lead[data-key] { cursor: pointer; }
100
+ .lead[data-key]:hover .lead-name { color: var(--brand); }
82
101
  .up { color: var(--success); }
83
102
 
84
103
  .cols { display: grid; grid-template-columns: minmax(0, 1fr) 318px; min-width: 0; gap: 30px; margin-top: 20px; align-items: start; }
@@ -118,10 +137,39 @@
118
137
  .ranks .track { height: 6px; border-radius: 2px; background: var(--bg-layer-2); overflow: hidden; }
119
138
  .ranks .track i { display: block; height: 100%; background: var(--brand); border-radius: 2px; }
120
139
  .ranks .v { text-align: right; font-variant-numeric: tabular-nums; }
140
+ .stats em a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
141
+ .cmp ul { list-style: none; margin: 0; padding: 0 6px 0 0; display: grid; gap: 7px; }
142
+ .cmp li { display: grid; grid-template-columns: 172px 148px 1fr 60px; gap: 12px; align-items: baseline; font-size: 16px; cursor: pointer; }
143
+ .cmp li:hover .k { color: var(--label-primary); }
144
+ .cmp .k { color: var(--label-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
145
+ .cmp .ver { font-size: 12px; color: var(--label-secondary); font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
146
+ .cmp .v { text-align: right; font-variant-numeric: tabular-nums; }
147
+ .cmp .d { text-align: right; font-size: 12px; color: var(--label-secondary); font-variant-numeric: tabular-nums; }
148
+ .repo-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 0 28px; }
149
+ .repo-grid ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; min-width: 0; }
150
+ .repo-grid li.muted { grid-template-columns: 1fr; font-size: 13px; }
151
+ .cmp li.muted { grid-template-columns: 1fr; font-size: 13px; }
152
+ @media (max-width: 560px) {
153
+ .cmp li { grid-template-columns: 1fr auto; gap: 2px 12px; font-size: 15px; padding: 6px 0; }
154
+ .cmp .k { grid-column: 1; grid-row: 1; }
155
+ .cmp .d { grid-column: 2; grid-row: 1; }
156
+ .cmp .ver { grid-column: 1; grid-row: 2; }
157
+ .cmp .v { grid-column: 2; grid-row: 2; }
158
+ }
159
+ /* 名字列给上限而不是固定宽,窗口窄下来整行才收得住,不会顶出容器 */
160
+ .repo-grid li { display: grid; grid-template-columns: minmax(0, 168px) minmax(0, 1fr) 56px; align-items: center; gap: 10px; font-size: 16px; cursor: pointer; }
161
+ .repo-grid li:hover .k { color: var(--label-primary); }
162
+ .repo-grid .k { color: var(--label-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
163
+ .repo-grid .track { height: 6px; border-radius: 2px; background: var(--bg-layer-2); overflow: hidden; }
164
+ .repo-grid .track i { display: block; height: 100%; background: var(--brand); border-radius: 2px; }
165
+ .repo-grid .v { text-align: right; font-variant-numeric: tabular-nums; }
166
+ @media (max-width: 900px) { .repo-grid { grid-template-columns: 1fr; } }
121
167
  .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-top: 12px; }
122
168
  .stats div { display: flex; flex-direction: column; gap: 2px; }
123
169
  .stats span { font-size: 12px; color: var(--label-secondary); }
124
170
  .stats b { font-size: 24px; font-weight: 600; font-variant-numeric: tabular-nums; }
171
+ /* 对比区间两行放,一行会把中间日期折断 */
172
+ #impact-cover { font-size: 13px; white-space: pre-line; line-height: 1.6; }
125
173
  .stats em { font-size: 12px; font-style: normal; color: var(--label-secondary); }
126
174
  .note { margin: 12px 0 0; font-size: 12px; line-height: 1.65; color: var(--label-secondary); }
127
175
 
@@ -145,8 +193,34 @@
145
193
  .cfg-row { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--label-secondary); margin-top: 8px; }
146
194
  .cfg-row label { width: 56px; flex: none; }
147
195
  .cfg { display: none; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border-l1); }
196
+ /* 绑定页:全屏盖住看板,只有一条主路径 */
197
+ .gate { position: fixed; inset: 0; z-index: 60; display: none; place-items: center; background: var(--bg-base); }
198
+ .gate.on { display: grid; }
199
+ body.gated { overflow: hidden; }
200
+ .gate-card { width: min(360px, calc(100vw - 40px)); text-align: left; }
201
+ .gate-card h1 { font-size: 15px; font-weight: 600; color: var(--label-primary); margin: 0 0 6px; }
202
+ .gate-card p { font-size: 12px; line-height: 1.6; color: var(--label-secondary); margin: 0 0 16px; }
203
+ .gate-card button.primary { width: 100%; height: 34px; border: 0; border-radius: 8px; background: var(--brand); color: #fff;
204
+ font-size: 13px; font-weight: 500; cursor: pointer; }
205
+ .gate-card button.primary:disabled { opacity: .55; cursor: default; }
206
+ .gate-alt { display: block; margin-top: 14px; }
207
+ /* 自己的分隔线,别借用页头那根 .sep(那是 1px 竖线,会把这里挤成一列字) */
208
+ .gate-alt.sep-top { padding-top: 14px; border-top: 1px solid var(--border-l1); }
209
+ .gate-alt input { width: 100%; height: 30px; background: var(--bg-layer-1); border: 1px solid var(--border-l1); border-radius: 8px;
210
+ color: var(--label-primary); font: inherit; font-size: 12px; padding: 0 10px; }
211
+ .gate-alt a { color: var(--brand); text-decoration: none; }
212
+ .gate-card a { color: var(--brand); text-decoration: none; }
213
+ .gate-card a:hover { text-decoration: underline; text-underline-offset: 2px; }
214
+ .gate-card p.gate-code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 15px; letter-spacing: .1em;
215
+ color: var(--label-primary); margin: 0 0 2px; }
216
+ .gate-out { font-size: 12px; color: var(--label-secondary); margin-top: 10px; min-height: 16px; }
217
+ .gate-code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 15px; letter-spacing: .1em; color: var(--label-primary); margin: 8px 0; }
148
218
  .cfg.open { display: block; }
149
- .foot { display: flex; justify-content: space-between; font-size: 12px; color: var(--label-secondary); margin-top: 12px; }
219
+ .ask-out { margin: 8px 0 0; font-size: 12px; line-height: 1.55; color: var(--label-secondary); }
220
+ .ask-out a { color: var(--brand); text-decoration: none; }
221
+ .ask-out a:hover { text-decoration: underline; }
222
+ .foot { display: flex; align-items: baseline; gap: 8px; font-size: 12px; color: var(--label-secondary); margin-top: 12px; }
223
+ #sum-src { margin-right: auto; }
150
224
  .link { color: var(--label-secondary); border: 0; height: auto; padding: 0; background: none; text-decoration: underline; text-underline-offset: 2px; }
151
225
  .link:hover { color: var(--label-primary); background: none; }
152
226
  .rowline { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--label-secondary); }
@@ -164,22 +238,29 @@
164
238
  }
165
239
  @media (max-width: 980px) {
166
240
  .kpis { grid-template-columns: repeat(2, 1fr); row-gap: 14px; }
241
+ .leaders { grid-template-columns: repeat(2, 1fr); gap: 14px 20px; }
167
242
  .kpi:nth-child(odd) { border-left: none; padding-left: 0; }
168
243
  .kpi:nth-child(even) { border-left: 1px solid var(--border-l1); padding-left: 14px; }
169
244
  }
170
245
  @media (max-width: 620px) {
171
246
  .wrap { padding: 14px 16px 28px; }
172
247
  header { flex-wrap: wrap; row-gap: 8px; }
173
- .repo { flex: 1 0 100%; order: -1; }
248
+ .repo-wrap { min-width: 0; max-width: 100%; }
249
+ .repo-wrap > .repo { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 4px; order: -1; }
250
+ .repo-wrap > .repo #repo-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
251
+ .repo-wrap > .repo-note { font-size: 12px; color: var(--label-secondary); white-space: nowrap; }
174
252
  .spacer { display: none; }
175
253
  .seg { margin-left: auto; }
176
254
  .kpi-value { font-size: 24px; }
177
255
  .kpi:last-child { grid-column: 1 / -1; border-left: none; padding-left: 0; }
178
256
  .split { grid-template-columns: 1fr; gap: 20px; }
179
257
  .donut { flex-direction: row; align-items: center; gap: 16px; }
180
- .donut svg { margin: 0; flex: none; }
181
- .donut-legend { flex: 1; min-width: 0; }
182
- .donut-legend span { overflow: hidden; text-overflow: ellipsis; }
258
+ .donut { width: 100%; max-width: 100%; overflow: hidden; }
259
+ .donut svg { margin: 0; flex: none; width: 84px; height: 84px; }
260
+ .donut-legend { flex: 1; min-width: 0; overflow: hidden; }
261
+ .donut-legend div { min-width: 0; }
262
+ .donut-legend span { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
263
+ .donut-legend b { flex: none; }
183
264
  .stats { grid-template-columns: 1fr 1fr; gap: 14px; }
184
265
  .stats b { font-size: 18px; }
185
266
  thead th:nth-child(3), tbody td:nth-child(3) { display: none; }
@@ -194,10 +275,15 @@
194
275
  <span class="sep"></span>
195
276
  <div class="repo-wrap">
196
277
  <button class="repo" id="repo-pick" aria-haspopup="true" aria-expanded="false"><span id="repo-owner"></span><span id="repo-name">全部仓库</span> <span class="caret">▾</span></button>
278
+ <a class="repo-open" id="repo-open" target="_blank" rel="noopener" aria-label="在 GitHub 打开" hidden>
279
+ <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path d="M6.5 3.5h6v6M12.5 3.5 5 11" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
280
+ </a>
197
281
  <div class="repo-menu" id="repo-menu" hidden></div>
282
+ <span class="repo-note" id="repo-note" hidden></span>
198
283
  </div>
199
284
  <div class="spacer"></div>
200
285
  <div class="seg" id="seg">
286
+ <button data-r="1">1 天</button>
201
287
  <button data-r="7" class="on">7 天</button>
202
288
  <button data-r="30">30 天</button>
203
289
  <button data-r="90">90 天</button>
@@ -213,38 +299,43 @@
213
299
 
214
300
  <section class="kpis">
215
301
  <div class="kpi">
216
- <div class="kpi-label">访客</div>
217
- <div class="kpi-value" id="k-uniq">341</div>
218
- <div class="kpi-sub" id="k-views-sub">424 次浏览</div>
302
+ <div class="kpi-label">浏览</div>
303
+ <div class="kpi-value" id="k-uniq">—</div>
304
+ <div class="kpi-sub" id="k-views-sub"></div>
219
305
  </div>
220
306
  <div class="kpi">
221
307
  <div class="kpi-label">外部贡献</div>
222
308
  <div class="kpi-value" id="k-contrib">2</div>
223
- <div class="kpi-sub" id="k-contrib-sub">1 issue、1 PR</div>
309
+ <div class="kpi-sub" id="k-contrib-sub">—</div>
224
310
  </div>
225
311
  <div class="kpi">
226
312
  <div class="kpi-label">npm 下载</div>
227
- <div class="kpi-value" id="k-npm">10,527</div>
228
- <div class="kpi-sub">周汇总</div>
313
+ <div class="kpi-value" id="k-npm">—</div>
314
+ <div class="kpi-sub" id="k-npm-sub">近 7 天</div>
229
315
  </div>
230
316
  <div class="kpi">
231
317
  <div class="kpi-label">stars</div>
232
318
  <div class="kpi-value" id="k-stars">9</div>
233
- <div class="kpi-sub" id="k-forks">2 forks</div>
319
+ <div class="kpi-sub" id="k-forks"></div>
234
320
  </div>
235
321
  <div class="kpi">
236
322
  <div class="kpi-label">发版</div>
237
323
  <div class="kpi-value" id="k-rel">4</div>
238
- <div class="kpi-sub" id="k-rel-sub">0.6.11 → 0.6.14</div>
324
+ <div class="kpi-sub" id="k-rel-sub"></div>
239
325
  </div>
240
326
  </section>
241
327
 
328
+ <section class="sec" id="sec-top" hidden>
329
+ <div class="head"><h2>各仓之最<span class="head-note" id="top-note"></span></h2></div>
330
+ <div class="leaders" id="leaders"></div>
331
+ </section>
332
+
242
333
  <div class="cols">
243
334
  <main>
244
335
  <section class="sec">
245
336
  <div class="head">
246
337
  <h2>流量</h2>
247
- <span class="note" id="range-note">10-26 → 11-01</span>
338
+ <span class="note" id="range-note"></span>
248
339
  <div class="spacer"></div>
249
340
  <span class="key"><i style="background:var(--brand)"></i>浏览</span>
250
341
  <span class="key"><i style="background:var(--machine)"></i>克隆</span>
@@ -258,25 +349,69 @@
258
349
  <h2>下载</h2>
259
350
  <div class="srcs">
260
351
  <span class="src on">npm</span>
261
- <span class="src off">PyPI</span>
262
- <span class="src off">Docker</span>
263
- <span class="src off">+ 添加</span>
264
352
  </div>
265
353
  </div>
266
354
  <div class="chart" id="c-npm"></div>
267
355
  </section>
268
356
 
269
357
  <section class="sec">
270
- <div class="head"><h2>贡献</h2></div>
358
+ <div class="head"><h2>贡献</h2><span class="src" id="contrib-range"></span><span class="head-note" id="contrib-fresh"></span></div>
359
+ <div class="stats">
360
+ <div><span>issue</span><b id="s-issues">—</b><em id="s-issues-sub"></em></div>
361
+ <div><span>PR</span><b id="s-prs">—</b><em id="s-prs-sub"></em></div>
362
+ <div><span>安全告警 · 快照</span><b id="s-alerts">关闭</b><em id="s-alerts-sub">无数据</em></div>
363
+ </div>
364
+ </section>
365
+
366
+ <section class="sec" id="sec-forks" hidden>
367
+ <div class="head"><h2>Fork<span class="src" id="fork-range"></span><span class="head-note" id="fork-fresh"></span></div>
368
+ <div class="stats" id="fork-stats">
369
+ <div><span>新增</span><b id="f-new">—</b><em id="f-new-sub"></em></div>
370
+ <div><span>最近</span><b id="f-last">—</b><em id="f-last-sub"></em></div>
371
+ </div>
372
+ <div class="note" id="fork-note" hidden></div>
373
+ <div id="fork-list"></div>
374
+ </section>
375
+
376
+ <section class="sec" id="sec-impact" hidden>
377
+ <div class="head">
378
+ <h2>发版效果</h2>
379
+ <span class="src" id="impact-ver"></span>
380
+ </div>
381
+ <div class="stats">
382
+ <div><span>浏览日均</span><b id="impact-views">—</b><em id="impact-views-sub"></em></div>
383
+ <div><span>下载日均</span><b id="impact-npm">—</b><em id="impact-npm-sub"></em></div>
384
+ <div><span>对比区间</span><b id="impact-cover">—</b><em id="impact-cover-sub"></em></div>
385
+ </div>
386
+ </section>
387
+
388
+ <section class="sec" id="sec-cmp" hidden>
389
+ <div class="head"><h2>发版前后 · 浏览/天<span class="head-note" id="rel-note"></span></h2></div>
390
+ <div class="cmp"><ul id="cmp-list"></ul></div>
391
+ </section>
392
+
393
+ <section class="sec" id="sec-funnel" hidden>
394
+ <div class="head"><h2>漏斗</h2></div>
271
395
  <div class="stats">
272
- <div><span>issue</span><b id="s-issues">1 个</b><em id="s-issues-sub">已关闭</em></div>
273
- <div><span>PR</span><b id="s-prs">1 个</b><em id="s-prs-sub">已合并,+118 −5</em></div>
274
- <div><span>安全告警</span><b id="s-alerts">未开启</b><em id="s-alerts-sub">无数据</em></div>
396
+ <div><span>浏览</span><b id="f-views">—</b><em id="f-views-sub"></em></div>
397
+ <div><span>仓库主页</span><b id="f-home">—</b><em id="f-home-sub"></em></div>
398
+ <div><span>npm 下载</span><b id="f-npm">—</b><em id="f-npm-sub"></em></div>
275
399
  </div>
276
400
  </section>
277
401
 
402
+ <section class="sec" id="sec-repos" hidden>
403
+ <div class="head">
404
+ <h2>项目<span class="head-note" id="proj-note"></span></h2>
405
+ <div class="srcs" id="ov-sort">
406
+ <span class="src on" data-sort="u">访客</span>
407
+ <span class="src off" data-sort="n">下载</span>
408
+ </div>
409
+ </div>
410
+ <div class="repo-grid" id="repo-list"></div>
411
+ </section>
412
+
278
413
  <section class="sec">
279
- <div class="head"><h2>构成</h2></div>
414
+ <div class="head"><h2>构成<span class="head-note" id="comp-note">· 各仓最近一次快照</span></h2></div>
280
415
  <div class="split">
281
416
  <div class="donut" id="donut"></div>
282
417
  <div class="ranks" id="ranks"></div>
@@ -287,20 +422,22 @@
287
422
 
288
423
  <aside>
289
424
  <div class="panel ai">
290
- <h3>摘要<span id="sum-at">11-02 09:14</span></h3>
291
- <p id="sum-1">近 7 天约 <b>341</b> 人来看过仓库。</p>
292
- <p id="sum-2">外部提了 1 个 issue、1 个 PR。</p>
293
- <p id="sum-3">Star 涨到 <b>9</b>,npm 周下载 1.05 万。</p>
425
+ <h3>摘要<span id="sum-at"></span></h3>
426
+ <p id="sum-1">摘要正在生成。</p>
427
+ <p id="sum-2" hidden></p>
428
+ <p id="sum-3" hidden></p>
294
429
 
295
430
  <div class="ask">
296
- <input placeholder="问这个仓库">
431
+ <input id="ask-q" placeholder="问全部仓库">
297
432
  <button class="mini">问</button>
298
433
  </div>
299
- <div class="foot"><span>deepseek-v4</span><button class="link" id="cfg-toggle">配置</button></div>
434
+ <p class="ask-out" id="ask-out" hidden></p>
435
+ <div class="foot"><span id="ai-model">—</span><span id="sum-src"></span><button class="link" id="cfg-toggle">配置</button></div>
300
436
 
301
437
  <div class="cfg" id="cfg">
302
- <div class="cfg-row"><label>Base URL</label><input value="https://api.deepseek.com/v1" spellcheck="false"></div>
303
- <div class="cfg-row"><label>API Key</label><input type="password" placeholder="sk-…" spellcheck="false"></div>
438
+ <div class="cfg-row"><label>Base URL</label><input id="cfg-base" placeholder="https://…/v1" spellcheck="false"></div>
439
+ <div class="cfg-row"><label>API Key</label><input id="cfg-key" type="password" placeholder="sk-…" spellcheck="false"></div>
440
+ <div class="cfg-row"><label>模型</label><input id="cfg-model" placeholder="模型名" spellcheck="false"></div>
304
441
  <div class="cfg-row" style="justify-content:flex-end;gap:6px">
305
442
  <button class="mini ghost">取消</button>
306
443
  <button class="mini" id="cfg-save">保存</button>
@@ -309,8 +446,9 @@
309
446
  </div>
310
447
 
311
448
  <div class="panel">
312
- <h3>刷新<span>每天 21:00</span></h3>
313
- <div class="rowline"><span>上次</span><b id="r-last">3 分钟前</b></div>
449
+ <h3>刷新<span id="r-interval">—</span></h3>
450
+ <div class="rowline"><span>上次</span><b id="r-last">—</b></div>
451
+ <div class="rowline" id="r-contrib-row" hidden><span>贡献</span><b id="r-contrib">—</b></div>
314
452
  <div class="rowline"><span>已存</span><b id="r-days">8 天</b></div>
315
453
  <div class="rowline" style="margin-top:10px"><span>数据源</span><b>GitHub · npm</b></div>
316
454
  </div>
@@ -318,6 +456,19 @@
318
456
  </div>
319
457
  </div>
320
458
 
459
+ <div class="gate" id="gate">
460
+ <div class="gate-card">
461
+ <h1>把看板接到你的 GitHub</h1>
462
+ <p id="gate-lead">登录你自己的账号,数据只存在这台电脑上。</p>
463
+ <div id="gate-main"></div>
464
+ <div class="gate-alt">
465
+ <p id="gate-alt-lead" style="margin:0 0 8px">改用访问令牌</p>
466
+ <input id="gate-token" type="password" placeholder="ghp_… 或 github_pat_…" spellcheck="false" autocomplete="off">
467
+ <p style="margin:8px 0 0"><a id="gate-new" target="_blank" rel="noopener">在新标签页生成</a></p>
468
+ </div>
469
+ <div class="gate-out" id="gate-out"></div>
470
+ </div>
471
+ </div>
321
472
  <script>
322
473
  let DATA = [
323
474
  { d: "10-26", v: 1, u: 1, c: 81, cu: 34, n: 1240 },
@@ -330,7 +481,7 @@ let DATA = [
330
481
  ];
331
482
  let RELEASE = { "10-29": 1, "10-30": 1, "10-31": 1, "11-01": 1 };
332
483
  const NS = "http://www.w3.org/2000/svg";
333
- const fmt = v => new Intl.NumberFormat("en").format(Math.round(v));
484
+ const fmt = v => (v > 0 && v < 10 ? Math.round(v * 10) / 10 : Math.round(v)).toLocaleString("en");
334
485
 
335
486
  const theme = () => document.documentElement.dataset.theme;
336
487
  function C() {
@@ -345,6 +496,19 @@ function el(tag, attrs, text) {
345
496
  if (text != null) n.textContent = text;
346
497
  return n;
347
498
  }
499
+ // 窄屏放不下就少标几个日期,但末日一定标上,也别和前一个挤成一条
500
+ function axisIdx(n, iw) {
501
+ const fit = Math.max(3, Math.floor(iw / 64));
502
+ const step = Math.max(1, Math.ceil(n / fit));
503
+ const out = [];
504
+ for (let i = 0; i < n; i += step) out.push(i);
505
+ if (out[out.length - 1] !== n - 1) {
506
+ if (n - 1 - out[out.length - 1] < step / 2) out.pop();
507
+ out.push(n - 1);
508
+ }
509
+ return out;
510
+ }
511
+
348
512
  function scale(max, ticks) {
349
513
  const rough = max / ticks, p = Math.pow(10, Math.floor(Math.log10(rough))), m = rough / p;
350
514
  const step = (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p;
@@ -373,7 +537,7 @@ function flowChart(node, days) {
373
537
  if (!DATA.some(r => (r.v || 0) > 0 || (r.c || 0) > 0)) return emptyInto(node, "还没有流量数据");
374
538
  const L = scale(Math.max(...DATA.map(r => r.v)) * 1.06, ticks);
375
539
  const R = scale(Math.max(...DATA.map(r => r.c)) * 1.06, ticks);
376
- const x = i => P.l + (i * iw) / (dom.length - 1);
540
+ const x = i => (dom.length === 1 ? P.l + iw / 2 : P.l + (i * iw) / (dom.length - 1));
377
541
  const yl = v => P.t + ih - (v / L.max) * ih;
378
542
  const yr = v => P.t + ih - (v / R.max) * ih;
379
543
 
@@ -391,35 +555,60 @@ function flowChart(node, days) {
391
555
  if (firstIdx > 0) {
392
556
  svg.appendChild(el("rect", { x: P.l, y: P.t, width: x(firstIdx) - P.l, height: ih, fill: c.zero }));
393
557
  svg.appendChild(el("line", { x1: x(firstIdx), x2: x(firstIdx), y1: P.t, y2: P.t + ih, stroke: c.grid, "stroke-dasharray": "3 4" }));
394
- svg.appendChild(el("text", { x: x(firstIdx) + 7, y: P.t + 13, class: "tick-label" }, "10-26 起"));
558
+ svg.appendChild(el("text", { x: x(firstIdx) + 7, y: P.t + 13, class: "tick-label" }, `${dom[firstIdx]?.label ?? ""} 起有数据`));
395
559
  }
396
560
 
397
561
  dom.forEach((d, i) => {
398
- if (d.rec && RELEASE[d.label]) {
562
+ if (dom.length > 1 && d.rec && RELEASE[d.label]) {
399
563
  svg.appendChild(el("line", { x1: x(i), x2: x(i), y1: P.t - 3, y2: P.t + ih, stroke: c.event, "stroke-width": 1, "stroke-dasharray": "2 4", opacity: .5 }));
400
564
  }
401
565
  });
402
566
 
403
- const vp = dom.map((d, i) => d.rec ? `${x(i)},${yl(d.rec.v)}` : null);
404
- const f = vp.findIndex(Boolean), l = vp.length - 1 - [...vp].reverse().findIndex(Boolean);
567
+ const vp = dom.map((d, i) => (d.rec ? { i, pt: `${x(i)},${yl(d.rec.v)}`, v: d.rec.v } : null)).filter(Boolean);
568
+ // 末尾连续 0 = 当天还没采集到:实线停在最后有数的一天,后面用虚线
569
+ const recs = dom.filter((d) => d.rec);
570
+ const avgV = recs.length ? recs.reduce((a, d) => a + (d.rec.v || 0), 0) / recs.length : 0;
571
+ let cut = dom.length;
572
+ while (cut > 0 && dom[cut - 1].rec && (dom[cut - 1].rec.v || 0) === 0 && avgV >= 20) cut--;
573
+ const solidLen = Math.max(1, vp.filter((p) => p.i < cut).length);
574
+ const solid = vp.slice(0, solidLen), tail = vp.slice(solidLen);
575
+
576
+ if (dom.length === 1 && dom[0].rec) {
577
+ const bw2 = Math.min(26, iw * 0.16), cv = dom[0].rec.c || 0;
578
+ svg.appendChild(el("rect", { x: x(0) + Math.min(46, iw * 0.3) / 2 + 6, y: yr(cv), width: bw2, height: yr(0) - yr(cv), fill: c.machine, opacity: .3, rx: 3 }));
579
+ } else {
580
+ const cp = dom.slice(0, cut).map((d, i) => d.rec ? `${x(i)},${yr(d.rec.c)}` : null).filter(Boolean).join(" ");
581
+ svg.appendChild(el("polyline", { points: cp, fill: "none", stroke: c.machine, "stroke-width": 1.5, opacity: .9 }));
582
+ }
583
+
584
+ const lastSolid = solid[solid.length - 1], firstSolid = solid[0];
405
585
  svg.appendChild(el("path", {
406
- d: `M${x(f)},${yl(0)} L` + vp.filter(Boolean).join(" L") + ` L${x(l)},${yl(0)} Z`,
586
+ d: `M${firstSolid.pt} L` + solid.map((p) => p.pt).join(" L") + ` L${x(lastSolid.i)},${yl(0)} L${x(firstSolid.i)},${yl(0)} Z`,
407
587
  fill: c.human, opacity: .14
408
588
  }));
409
-
410
- const cp = dom.map((d, i) => d.rec ? `${x(i)},${yr(d.rec.c)}` : null).filter(Boolean).join(" ");
411
- svg.appendChild(el("polyline", { points: cp, fill: "none", stroke: c.machine, "stroke-width": 1.5, opacity: .9 }));
412
-
413
- svg.appendChild(el("polyline", { points: vp.filter(Boolean).join(" "), fill: "none", stroke: c.human, "stroke-width": 2, "stroke-linejoin": "round" }));
589
+ svg.appendChild(el("polyline", { points: solid.map((p) => p.pt).join(" "), fill: "none", stroke: c.human, "stroke-width": 2, "stroke-linejoin": "round" }));
590
+ // 单天没有折线可看,改成一个站直的柱子
591
+ if (dom.length === 1 && dom[0].rec) {
592
+ const bw = Math.min(46, iw * 0.3), v = dom[0].rec.v || 0;
593
+ svg.appendChild(el("rect", { x: x(0) - bw / 2, y: yl(v), width: bw, height: yl(0) - yl(v), fill: c.human, opacity: .18, rx: 3 }));
594
+ svg.appendChild(el("circle", { cx: x(0), cy: yl(v), r: 3.4, fill: c.human }));
595
+ }
596
+ if (tail.length) {
597
+ // 末尾没采集到的 0 不连成斜线,否则看起来像浏览真的掉到 0
598
+ const tpts = [lastSolid.pt, ...tail.map((p) => p.pt)];
599
+ if ((tail[tail.length - 1].v || 0) === 0) tpts.pop();
600
+ if (tpts.length > 1) svg.appendChild(el("polyline", { points: tpts.join(" "), fill: "none", stroke: c.human, "stroke-width": 1.5, "stroke-dasharray": "3 4", opacity: .55 }));
601
+ const cutLabel = dom[cut]?.label ?? "";
602
+ // 贴右轴会压住末端的刻度数字,改放在未采集灰区的左下
603
+ svg.appendChild(el("text", { x: x(cut) - 8, y: P.t + 12, "text-anchor": "end", class: "tick-label", fill: c.human, opacity: .75 }, cutLabel ? `${cutLabel} 未采集` : "未采集"));
604
+ }
414
605
 
415
606
  const peak = DATA.reduce((a, b) => b.v > a.v ? b : a);
416
607
  const pi = dom.findIndex(d => d.rec === peak);
417
608
  svg.appendChild(el("text", { x: x(pi), y: yl(peak.v) - 8, "text-anchor": "middle", class: "val-label" }, fmt(peak.v)));
418
609
 
419
- const step = Math.max(1, Math.ceil(dom.length / 6));
420
- dom.forEach((d, i) => {
421
- if (i % step && i !== dom.length - 1) return;
422
- svg.appendChild(el("text", { x: x(i), y: H - 4, "text-anchor": "middle", class: "tick-label" }, d.label));
610
+ axisIdx(dom.length, iw).forEach((i) => {
611
+ svg.appendChild(el("text", { x: x(i), y: H - 4, "text-anchor": "middle", class: "tick-label" }, dom[i].label));
423
612
  });
424
613
  node.appendChild(svg);
425
614
  }
@@ -444,6 +633,13 @@ function npmChart(node, days) {
444
633
  svg.appendChild(el("line", { x1: P.l, x2: W - P.r, y1: yy, y2: yy, stroke: c.grid }));
445
634
  svg.appendChild(el("text", { x: P.l - 8, y: yy + 4, "text-anchor": "end", class: "tick-label" }, fmt(S.step * t)));
446
635
  }
636
+ // npm 下载比浏览晚几天才有数,开头空白要说明是哪天开始有数
637
+ const firstN = dom.findIndex((d) => d.rec && d.rec.n > 0);
638
+ if (firstN > 0) {
639
+ svg.appendChild(el("rect", { x: P.l, y: P.t, width: cx(firstN) - bw / 2 - P.l, height: ih, fill: c.zero }));
640
+ svg.appendChild(el("line", { x1: cx(firstN) - bw / 2, x2: cx(firstN) - bw / 2, y1: P.t, y2: P.t + ih, stroke: c.grid, "stroke-dasharray": "3 4" }));
641
+ svg.appendChild(el("text", { x: P.l + 6, y: P.t + 12, class: "tick-label" }, `${dom[firstN].label} 起有数据`));
642
+ }
447
643
  dom.forEach((d, i) => {
448
644
  if (!d.rec) return;
449
645
  const v = d.rec.n;
@@ -457,10 +653,13 @@ function npmChart(node, days) {
457
653
  svg.appendChild(el("rect", { x: cx(i) - bw / 2, y: y(v), width: bw, height: Math.max(2, P.t + ih - y(v)), rx: 2, fill: c.human, opacity: .85 }));
458
654
  if (v > 0 && bw > 12 && (iw / dom.length > 46 || v === NMAX)) svg.appendChild(el("text", { x: cx(i), y: y(v) - 6, "text-anchor": "middle", class: "val-label" }, fmt(v)));
459
655
  });
460
- const step = Math.max(1, Math.ceil(dom.length / 6));
461
- dom.forEach((d, i) => {
462
- if (i % step && i !== dom.length - 1) return;
463
- svg.appendChild(el("text", { x: cx(i), y: H - 4, "text-anchor": "middle", class: "tick-label" }, d.label));
656
+ // 末尾两根柱还没采到数,标出从哪天起是空的,别让人以为是零下载
657
+ const cutAt = dom.findIndex((d, i) => i >= dom.length - 2 && (!d.rec || d.rec.n == null || d.rec.n === 0));
658
+ if (cutAt >= 0 && dom[cutAt]?.label) {
659
+ svg.appendChild(el("text", { x: W - P.r - 6, y: P.t + 14, "text-anchor": "end", class: "tick-label", fill: c.machine, opacity: .75 }, `${dom[cutAt].label} 未采集`));
660
+ }
661
+ axisIdx(dom.length, iw).forEach((i) => {
662
+ svg.appendChild(el("text", { x: cx(i), y: H - 4, "text-anchor": "middle", class: "tick-label" }, dom[i].label));
464
663
  });
465
664
  node.appendChild(svg);
466
665
  }
@@ -471,6 +670,8 @@ let RANKS = [
471
670
  let PATHS = null;
472
671
  let FIRST = null;
473
672
  let LIVE_SET = false;
673
+ // 实时数据:拿不到就继续用内置样例,页面始终能看
674
+ const LIVE = { totals: {}, range: { days: 7, storedDays: 0 }, repo: {}, contributions: { issues: [], pulls: [], open: null }, releases: [], paths: [], npmVersions: [], updatedAt: null };
474
675
 
475
676
  const emptyInto = (node, text) => {
476
677
  node.textContent = "";
@@ -498,7 +699,10 @@ function donut(node) {
498
699
  let parts = PATHS ? PATHS : [];
499
700
  if (!parts.length && !LIVE_SET) parts = [["0.6.14", 320, "--brand"], ["旧版本", 1137, "--machine"]];
500
701
  if (!parts.length) return emptyInto(node, "还没有页面数据");
702
+ // 占比只在这份热门榜内部算:页面榜是各仓最近一次同步拿到的前几个,
703
+ // 拿 14 天总浏览当分母会把两段时间混在一起,还会凭空补出一个「其他页面」
501
704
  const total = parts.reduce((s, p) => s + p[1], 0);
705
+ if (!total) return emptyInto(node, "还没有页面数据");
502
706
  const R = 40, ST = 13, CIRC = 2 * Math.PI * R;
503
707
  const svg = el("svg", { viewBox: "0 0 104 104", role: "img", "aria-label": "页面访问占比" });
504
708
  svg.appendChild(el("circle", { cx: 52, cy: 52, r: R, fill: "none", stroke: cs.getPropertyValue("--border-l1").trim(), "stroke-width": ST }));
@@ -542,10 +746,11 @@ function ranks(node) {
542
746
  // 只有一两个来源时别把数字推到半屏外
543
747
  const thin = RANKS.length === 1 && RANKS[0][1].length <= 2;
544
748
  node.style.maxWidth = thin ? "320px" : "";
545
- RANKS.forEach(([group, rows]) => {
749
+ RANKS.forEach(([group, rows, note]) => {
546
750
  const box = document.createElement("div");
547
751
  const h3 = document.createElement("h3");
548
- h3.textContent = group;
752
+ h3.textContent = group + " · 最近一次快照";
753
+ if (note) { const sp = document.createElement("span"); sp.className = "head-note"; sp.textContent = "· " + note; h3.appendChild(sp); }
549
754
  box.appendChild(h3);
550
755
  const ul = document.createElement("ul");
551
756
  const max = Math.max(...rows.map(r => r[1]), 1);
@@ -577,15 +782,21 @@ function ranks(node) {
577
782
  });
578
783
  }
579
784
 
785
+ // 有的 tag 写 v 有的不写,同一列里统一省掉前缀,版本号本身不变
786
+ const bareTag = (t) => String(t ?? "").trim().replace(/^[vV](?=\d)/, "");
787
+
580
788
  const kUniq = document.getElementById("k-uniq");
581
789
  const kViewsSub = document.getElementById("k-views-sub");
582
790
 
583
791
 
584
792
  const rangeNote = document.getElementById("range-note");
585
- let currentRange = 7;
793
+ let currentRange = [1, 7, 30, 90].includes(Number(new URLSearchParams(location.search).get("days"))) ? Number(new URLSearchParams(location.search).get("days")) : 7;
586
794
 
587
795
  function render(days) {
588
796
  currentRange = days;
797
+ const u = new URL(location.href);
798
+ if (days === 7) u.searchParams.delete("days"); else u.searchParams.set("days", String(days));
799
+ history.replaceState(null, "", u);
589
800
  const dom = domain(days);
590
801
  const recs = dom.filter(d => d.rec).map(d => d.rec);
591
802
  const tv = recs.reduce((s, r) => s + r.v, 0);
@@ -593,22 +804,41 @@ function render(days) {
593
804
  // 访客只能用 API 窗口去重值;超过 14 天没有该值就退回日均
594
805
  // 7 天取 API 去重值,更长范围按覆盖期逐日合计
595
806
  let uniq = LIVE.totals.uniques != null ? LIVE.totals.uniques : null;
807
+ // 1 天时 totals.uniques 是 14 天窗口去重值,换成当天去重才不误导
808
+ if (days === 1 && recs.length) uniq = recs[recs.length - 1].u;
596
809
  if (uniq == null) uniq = recs.length ? tu : null;
597
- kUniq.textContent = uniq == null ? "—" : fmt(uniq);
810
+ // 主数用窗口内浏览(逐日可加,跟着范围变);访客是 GitHub 的 14 天去重值,只能放副标说清口径
598
811
  const covered = LIVE.range && LIVE.range.covered;
599
- kViewsSub.textContent = fmt(tv) + " 次浏览" + (covered && covered < days ? `,覆盖 ${covered} 天` : "");
812
+ const covN = covered || recs.length;
813
+ kUniq.textContent = recs.length ? fmt(tv) : "—";
814
+ kViewsSub.textContent = uniq == null
815
+ ? "访客 —"
816
+ : days === 1
817
+ ? `访客 ${fmt(uniq)} · ${DATA[DATA.length - 1]?.d || ""}`
818
+ // 去重访客只有 GitHub 的 14 天窗口,比所选范围长时它会比上面的浏览还大;
819
+ // 窗口写在最前面,才不会被读成「这段里来了这么多人」
820
+ : Math.min(covN, 14) > days
821
+ ? `近 ${Math.min(covN, 14)} 天去重访客 ${fmt(uniq)}`
822
+ : `访客 ${fmt(uniq)} · 近 ${Math.min(covN, 14)} 天去重`;
600
823
  rangeNote.textContent = dom[0].label + " → " + dom[dom.length - 1].label;
824
+ // issue/PR 数跟着所选窗口走,标题要说清是哪段
825
+ const cSpan = LIVE.starGrowth?.span;
826
+ document.getElementById("contrib-range").textContent = days === 1 && LIVE.range?.to
827
+ ? label(LIVE.range.to)
828
+ : cSpan ? `近 ${cSpan} 天` : `近 ${days} 天`;
601
829
  flowChart(document.getElementById("c-flow"), days);
602
830
  npmChart(document.getElementById("c-npm"), days);
603
831
  donut(document.getElementById("donut"));
604
832
  ranks(document.getElementById("ranks"));
833
+ // 切范围后 fork 的窗口标题也得跟着变,不能停在上一段
834
+ renderForks(LIVE, days);
605
835
  }
606
836
 
607
837
  document.getElementById("seg").addEventListener("click", e => {
608
838
  const b = e.target.closest("button");
609
839
  if (!b) return;
610
840
  [...e.currentTarget.children].forEach(x => x.classList.toggle("on", x === b));
611
- render(+b.dataset.r);
841
+ // 先 render 会拿上一段范围的数据去填新范围的标题,等这次请求回来再一起重画
612
842
  pull(+b.dataset.r);
613
843
  });
614
844
 
@@ -621,22 +851,67 @@ document.getElementById("theme").addEventListener("click", () => {
621
851
  render(currentRange);
622
852
  });
623
853
 
624
- document.getElementById("cfg-toggle").addEventListener("click", () => document.getElementById("cfg").classList.toggle("open"));
625
- document.getElementById("cfg-save").addEventListener("click", () => {
626
- document.getElementById("cfg").classList.remove("open");
627
- document.getElementById("cfg-toggle").textContent = "已配置";
854
+ const postJson = (path, obj, opts = {}) =>
855
+ fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(obj), ...opts });
856
+ const cfgPanel = document.getElementById("cfg");
857
+ async function loadCfg() {
858
+ try {
859
+ const r = await fetch("/api/config", { cache: "no-store" });
860
+ const c = await r.json();
861
+ document.getElementById("cfg-base").value = c.baseurl || "";
862
+ document.getElementById("cfg-model").value = c.model || "";
863
+ document.getElementById("ai-model").textContent = c.model || "deepseek-chat";
864
+ if (c.apikey) document.getElementById("cfg-key").placeholder = "已保存";
865
+ } catch {}
866
+ }
867
+ document.getElementById("cfg-toggle").addEventListener("click", () => {
868
+ const open = cfgPanel.classList.toggle("open");
869
+ if (open) loadCfg();
870
+ });
871
+ document.getElementById("cfg-save").addEventListener("click", async () => {
872
+ const base = document.getElementById("cfg-base").value.trim();
873
+ if (!base) { document.getElementById("cfg-base").focus(); return; }
874
+ const btn = document.getElementById("cfg-save");
875
+ btn.disabled = true;
876
+ try {
877
+ const r = await postJson("/api/config", { baseurl: base, apikey: document.getElementById("cfg-key").value.trim(), model: document.getElementById("cfg-model").value.trim() });
878
+ if (!r.ok) throw new Error("save");
879
+ const c = await r.json();
880
+ document.getElementById("ai-model").textContent = c.model || "deepseek-chat";
881
+ document.getElementById("cfg-key").value = "";
882
+ document.getElementById("cfg-toggle").textContent = "已保存";
883
+ document.getElementById("ask-out").hidden = true;
884
+ cfgPanel.classList.remove("open");
885
+ loadSummary(currentRange);
886
+ } catch {
887
+ document.getElementById("cfg-toggle").textContent = "保存失败";
888
+ }
889
+ btn.disabled = false;
628
890
  });
629
891
 
630
892
  const rb = document.getElementById("refresh");
631
893
  rb.addEventListener("click", async () => {
632
894
  const keep = rb.innerHTML;
633
- rb.textContent = "刷新中…";
895
+ rb.disabled = true;
896
+ rb.textContent = "同步中…";
897
+ // 31 个仓库要几十秒,显示到第几个,不然只能盯着一个不动的按钮
898
+ const tick = setInterval(async () => {
899
+ try {
900
+ const r = await fetch("/api/progress");
901
+ const st = await r.json();
902
+ if (st.total) rb.textContent = `同步 ${st.done}/${st.total}`;
903
+ } catch { /* 下一次还会再问 */ }
904
+ }, 700);
634
905
  try {
635
- await fetch("/api/sync", { method: "POST" });
906
+ const res = await fetch("/api/sync", { method: "POST" });
907
+ const j = await res.json().catch(() => ({}));
636
908
  await pull(currentRange, true);
637
- rb.textContent = "刚更新";
909
+ rb.textContent = j.cached ? "已是最新" : "刚更新";
638
910
  } catch (e) {
639
911
  rb.textContent = "刷新失败";
912
+ } finally {
913
+ clearInterval(tick);
914
+ rb.disabled = false;
640
915
  }
641
916
  setTimeout(() => { rb.innerHTML = keep; }, 1600);
642
917
  });
@@ -647,10 +922,323 @@ try {
647
922
  if (saved === "light") document.getElementById("theme").click();
648
923
  } catch (e) {}
649
924
  // 实时数据:拿不到就继续用内置样例,页面始终能看
650
- const LIVE = { totals: {}, range: { days: 7, storedDays: 0 }, repo: {}, contributions: { issues: [], pulls: [] }, releases: [], paths: [], npmVersions: [], updatedAt: null };
651
925
  const label = iso => String(iso).slice(5, 10);
652
926
  const mmdd = iso => label(iso);
653
927
 
928
+ function renderImpact(it) {
929
+ const sec = document.getElementById("sec-impact");
930
+ if (!it) {
931
+ sec.hidden = true;
932
+ return;
933
+ }
934
+ sec.hidden = false;
935
+ const pct = (v) => pctText(v);
936
+ // 日均保留一位小数,四位数以上加千分位
937
+ const num = (v) => (v == null ? "—" : (Math.round(v * 10) / 10).toLocaleString("en"));
938
+ const show = (k, id, sub) => {
939
+ const b = it.before?.[k]?.avg;
940
+ const a = it.after?.[k]?.avg;
941
+ document.getElementById(id).textContent = b === null || b === undefined ? "—" : `${num(b)} → ${num(a)}`;
942
+ document.getElementById(sub).textContent = pct(it.delta?.[k]) || "";
943
+ };
944
+ // 全局视图主卡不止一个仓,版本号前面要带仓名,不然不知道说的是谁
945
+ document.getElementById("impact-ver").textContent = `${it.name ? it.name + " " : ""}${bareTag(it.version)} · ${String(it.at).slice(5)}${it.limited ? " · 数据不足" : ""}`;
946
+ show("views", "impact-views", "impact-views-sub");
947
+ // 这个仓没有 npm 包时整格不出现,别留一个「—」让人以为数据丢了
948
+ const npmCell = document.getElementById("impact-npm").parentElement;
949
+ const hasNpm = it.before?.npm?.avg != null || it.after?.npm?.avg != null;
950
+ // 用行内 display 而不是 hidden:.stats div 的 flex 会盖掉 [hidden]
951
+ if (npmCell) npmCell.style.display = hasNpm ? "" : "none";
952
+ if (hasNpm) show("npm", "impact-npm", "impact-npm-sub");
953
+ const spanTxt = (o) => (o?.from && o?.to ? `${String(o.from).slice(5)} – ${String(o.to).slice(5)}` : null);
954
+ const bSpan = spanTxt(it.before?.views), aSpan = spanTxt(it.after?.views);
955
+ document.getElementById("impact-cover").textContent = bSpan && aSpan
956
+ ? `前 ${bSpan}\n后 ${aSpan}`
957
+ : `前 ${it.before?.views?.days ?? 0} 天\n后 ${it.after?.views?.days ?? 0} 天`;
958
+ document.getElementById("impact-cover-sub").textContent = `前 ${it.before?.views?.days ?? 0} 天 · 后 ${it.after?.views?.days ?? 0} 天`;
959
+ }
960
+
961
+ let OVERVIEW = [];
962
+ let OV_SORT = "u";
963
+
964
+ let TOP_SIG = "";
965
+ function renderTop() {
966
+ const sec = document.getElementById("sec-top");
967
+ if (!sec) return;
968
+ const rows = OVERVIEW.filter((r) => r && r.key);
969
+ sec.hidden = !rows.length;
970
+ if (!rows.length) return;
971
+ // 请求的范围超过已存天数时,标题按实际覆盖的天数说,别把 90 天写成 90 天
972
+ const covSpan = Math.min(currentRange, LIVE.range?.covered || currentRange);
973
+ const span = currentRange === 1 ? (DATA[DATA.length - 1]?.d || "") : `近 ${covSpan} 天`;
974
+ const sig = span + "|" + rows.map((r) => `${r.key}:${r.views}:${r.npm}:${r.npmWeek}:${r.uniques}:${r.starDelta}`).join(",");
975
+ if (sig === TOP_SIG) return;
976
+ TOP_SIG = sig;
977
+ document.getElementById("top-note").textContent = `· ${span}`;
978
+ const node = document.getElementById("leaders");
979
+ node.textContent = "";
980
+ const sum = (f) => rows.reduce((a, r) => a + (Number(f(r)) || 0), 0);
981
+ // npm 当天数据要晚一两天才到,窗口里全空时不能把「还没采集」写成 0
982
+ const hasNpm = DATA.some((r) => r.n != null);
983
+ const metrics = [
984
+ { label: "浏览最多", k: "views", total: sum((r) => r.views), empty: "没有浏览" },
985
+ { label: "访客最多", k: "uniques", total: sum((r) => r.uniques), empty: "没有访客", note: currentRange === 1 ? "当天访客" : "14 天去重" },
986
+ { label: "涨星最多", k: "starDelta", total: sum((r) => r.starDelta), empty: "没有新增" },
987
+ { label: "下载最多", k: "npm", total: sum((r) => r.npm), empty: hasNpm ? "没有下载" : "还没采集到", emptyVal: hasNpm ? "0" : "—" },
988
+ ];
989
+ for (const m of metrics) {
990
+ const best = [...rows].sort((a, b) => (b[m.k] ?? -1) - (a[m.k] ?? -1))[0];
991
+ const val = best?.[m.k];
992
+ const tile = document.createElement("div");
993
+ tile.className = "lead";
994
+ const label = document.createElement("div");
995
+ label.className = "lead-label";
996
+ label.textContent = m.label;
997
+ const name = document.createElement("div");
998
+ name.className = "lead-name";
999
+ const value = document.createElement("div");
1000
+ value.className = "lead-value";
1001
+ const sub = document.createElement("div");
1002
+ sub.className = "lead-sub";
1003
+ if (!best || !(val > 0)) {
1004
+ name.textContent = "—";
1005
+ value.textContent = m.emptyVal || "0";
1006
+ sub.textContent = m.empty;
1007
+ } else {
1008
+ name.textContent = best.name;
1009
+ name.title = best.key;
1010
+ value.textContent = (m.k === "starDelta" ? "+" : "") + fmt(val);
1011
+ const pct = m.total > 0 ? Math.round((val / m.total) * 100) : null;
1012
+ const bits = [];
1013
+ if (m.note) bits.push(m.note);
1014
+ if (pct != null) bits.push(`占全部仓库 ${pct}%`);
1015
+ sub.textContent = bits.join(" · ");
1016
+ tile.dataset.key = best.key;
1017
+ tile.title = `${best.key} · 点击查看`;
1018
+ tile.addEventListener("click", () => switchRepo(best.key));
1019
+ }
1020
+ tile.append(label, name, value, sub);
1021
+ node.appendChild(tile);
1022
+ }
1023
+ }
1024
+
1025
+ function drawOverview() {
1026
+ document.getElementById("sec-repos").hidden = !OVERVIEW.length;
1027
+ const node = document.getElementById("repo-list");
1028
+ node.textContent = "";
1029
+ if (!OVERVIEW.length) return;
1030
+ const k = OV_SORT === "u" ? "uniques" : "npm";
1031
+ const projNote = document.getElementById("proj-note");
1032
+ if (projNote) {
1033
+ // 访客只有 GitHub 的 14 天去重值,下载才是这段窗口的逐日合计:
1034
+ // 两个长度不同的数不能挂在一个「近 N 天」后面,各自把口径说全
1035
+ const day = DATA[DATA.length - 1]?.d || "";
1036
+ projNote.textContent = currentRange === 1
1037
+ ? `· 访客和下载都取自 ${day} 当天`
1038
+ : `· 访客近 14 天去重 · 下载近 ${Math.min(currentRange, LIVE.range?.covered || currentRange)} 天`;
1039
+ }
1040
+ const emptyWord = OV_SORT === "u" ? "没有访客" : "没有下载";
1041
+ const all = [...OVERVIEW].sort((a, b) => (b[k] ?? 0) - (a[k] ?? 0));
1042
+ // 零访客的仓不占行,折成一句
1043
+ const used = all.filter((r) => (r[k] ?? 0) > 0);
1044
+ const rest = all.length - used.length;
1045
+ const rows = used.length ? used : all.slice(0, 6);
1046
+ const max = Math.max(...rows.map((r) => r[k] ?? 0), 1);
1047
+ const cols = 2;
1048
+ const per = Math.ceil(rows.length / cols);
1049
+ for (let c = 0; c < cols; c++) {
1050
+ const ul = document.createElement("ul");
1051
+ for (const r of rows.slice(c * per, (c + 1) * per)) {
1052
+ const li = document.createElement("li");
1053
+ const name = document.createElement("span");
1054
+ name.className = "k";
1055
+ name.textContent = r.name;
1056
+ const track = document.createElement("span");
1057
+ track.className = "track";
1058
+ const bar = document.createElement("i");
1059
+ bar.style.width = Math.max(2, ((r[k] ?? 0) / max) * 100) + "%";
1060
+ track.appendChild(bar);
1061
+ const v = document.createElement("span");
1062
+ v.className = "v";
1063
+ v.textContent = r[k] == null ? "—" : fmt(r[k]);
1064
+ li.title = r.key;
1065
+ li.append(name, track, v);
1066
+ li.addEventListener("click", () => switchRepo(r.key));
1067
+ ul.appendChild(li);
1068
+ }
1069
+ if (c === cols - 1 && rest) {
1070
+ const li = document.createElement("li");
1071
+ li.className = "muted";
1072
+ li.style.cursor = "default";
1073
+ const sp = document.createElement("span");
1074
+ sp.className = "k";
1075
+ sp.textContent = `另有 ${rest} 个${emptyWord}`;
1076
+ li.appendChild(sp);
1077
+ ul.appendChild(li);
1078
+ }
1079
+ node.appendChild(ul);
1080
+ }
1081
+ }
1082
+
1083
+ document.getElementById("ov-sort").addEventListener("click", (e) => {
1084
+ const b = e.target.closest("[data-sort]");
1085
+ if (!b) return;
1086
+ OV_SORT = b.dataset.sort;
1087
+ [...document.getElementById("ov-sort").children].forEach((x) => x.classList.toggle("on", x === b));
1088
+ drawOverview();
1089
+ });
1090
+
1091
+ // 统一成倍数:+795% 和 ×38 混排没法一眼比大小
1092
+ // 倍数带方向:单看 ×0.7 看不出是降了一半还是涨了
1093
+ function pctText(d) {
1094
+ if (d === null || d === undefined) return "";
1095
+ const r = 1 + d / 100;
1096
+ // 显示的倍数四舍五入到 ×1.0 时就是持平,别配上升箭头
1097
+ if (Number(r.toFixed(1)) === 1) return "持平";
1098
+ const arrow = r >= 1 ? "↑ " : "↓ ";
1099
+ if (r >= 10) return arrow + "×" + Math.round(r);
1100
+ if (r >= 0.1) return arrow + "×" + r.toFixed(1);
1101
+ return arrow + "×" + r.toFixed(2);
1102
+ }
1103
+
1104
+ function renderImpacts(list) {
1105
+ const all = (list || []).filter((i) => !i.limited && i.before?.views?.avg != null && i.after?.views?.avg != null);
1106
+ // 日均不到 5 次浏览的仓,倍数只是噪声(0.3 → 12 也是 ×39),排在最前面反而看不懂
1107
+ const solid = all.filter((i) => (i.before?.views?.avg ?? 0) >= 5);
1108
+ const rows = solid.length ? solid : all;
1109
+ document.getElementById("sec-cmp").hidden = !rows.length;
1110
+ const node = document.getElementById("cmp-list");
1111
+ node.textContent = "";
1112
+ // 上面那张主卡就是这个列表里最靠前的那条,列表里再出现一次只是重复
1113
+ const main = LIVE.impact;
1114
+ const sameAsMain = (r) => main && ((r.url && main.url && r.url === main.url) || (String(r.at) === String(main.at) && r.version === main.version));
1115
+ const rest = main ? rows.filter((r) => !sameAsMain(r)) : rows;
1116
+ const relNote = document.getElementById("rel-note");
1117
+ // 这行说的是能算出前后对比的仓,不是有发版的仓,别写成「有发版」
1118
+ // 这里数的是「最新一版落在所选范围里」的仓,前后对比各用自己那 90 天,窗口要说清
1119
+ if (relNote) relNote.textContent = rows.length ? ` · 范围内 ${rows.length} 个仓可对比` : "";
1120
+ const rank = [...rest].sort((a, b) => (b.delta?.views ?? -1e9) - (a.delta?.views ?? -1e9)).slice(0, 8);
1121
+ for (const r of rank) {
1122
+ const li = document.createElement("li");
1123
+ li.title = `${r.key} · 下载日均 ${r.before?.npm?.avg ?? "—"} → ${r.after?.npm?.avg ?? "—"}`;
1124
+ const k = document.createElement("span"); k.className = "k"; k.textContent = r.name;
1125
+ const ver = document.createElement("span"); ver.className = "ver"; ver.textContent = `${bareTag(r.version)} · ${String(r.at).slice(5)}`;
1126
+ const v = document.createElement("span"); v.className = "v"; v.textContent = `${fmt(r.before.views.avg)} → ${fmt(r.after.views.avg)}`;
1127
+ const d = document.createElement("span"); d.className = "d"; d.textContent = pctText(r.delta?.views);
1128
+ li.append(k, ver, v, d);
1129
+ li.addEventListener("click", () => switchRepo(r.key));
1130
+ node.appendChild(li);
1131
+ }
1132
+ if (rest.length > rank.length) {
1133
+ const li = document.createElement("li");
1134
+ li.className = "muted";
1135
+ li.style.cursor = "default";
1136
+ const sp = document.createElement("span"); sp.className = "k"; sp.textContent = `另有 ${rest.length - rank.length} 个仓未列出`;
1137
+ li.appendChild(sp);
1138
+ node.appendChild(li);
1139
+ }
1140
+ }
1141
+
1142
+ function renderForks(json, days) {
1143
+ const sec = document.getElementById("sec-forks");
1144
+ const f = json.forks;
1145
+ if (!f || f.total == null) { sec.hidden = true; return; }
1146
+ sec.hidden = false;
1147
+ const all = json.repo?.fullName === "全部仓库";
1148
+ const items = f.items || [];
1149
+ const note = document.getElementById("fork-note");
1150
+ note.hidden = true;
1151
+ note.textContent = "";
1152
+ // 标签必须写实际取到的窗口:1 天视图是最近一个完整日,90 天也可能只有 29 天数据
1153
+ const span = f.from && f.to ? Math.round((Date.parse(f.to) - Date.parse(f.from)) / 86400000) + 1 : days;
1154
+ document.getElementById("fork-range").textContent = span === 1 ? "今天" : `近 ${span} 天`;
1155
+ document.getElementById("fork-fresh").textContent = f.at ? `${label(f.at)} 更新` : "";
1156
+ // 卡片只报这一窗口里的 fork:总数是全生命周期的量,混在窗口卡片里会被读成窗口数
1157
+ const inWin = f.inWindow || 0;
1158
+ document.getElementById("f-new").textContent = inWin.toLocaleString("en");
1159
+ const reposWith = (json.repos || []).filter((r) => (r.newForks || 0) > 0).length;
1160
+ document.getElementById("f-new-sub").textContent = !items.length
1161
+ ? "没有新 fork"
1162
+ : all
1163
+ ? `${reposWith} 个仓库`
1164
+ : "";
1165
+ // 窗口里没有的时候,最近那个只当「上次」写进子标,别放在「最近」上被读成本窗口
1166
+ const inItem = items[0];
1167
+ const past = f.latest || items[0];
1168
+ document.getElementById("f-last").textContent = inItem ? inItem.login : "—";
1169
+ const short = (x) => (all && x.repo ? x.repo.split("/").slice(-1)[0] + " · " : "");
1170
+ document.getElementById("f-last-sub").textContent = inItem
1171
+ ? short(inItem) + label(inItem.at)
1172
+ : past
1173
+ ? "上次 " + label(past.at) + (all && past.repo ? " · " + past.repo.split("/").slice(-1)[0] : "")
1174
+ : "";
1175
+ const list = document.getElementById("fork-list");
1176
+ list.textContent = "";
1177
+ if (!items.length) return;
1178
+ if (all) {
1179
+ if (items.length >= 100) {
1180
+ note.hidden = false;
1181
+ note.textContent = "只统计最近 100 个 fork";
1182
+ }
1183
+ const rows = (json.repos || []).filter((r) => (r.newForks || 0) > 0)
1184
+ // 同分时按窗口里最近那个 fork 排:累计 fork 是全生命周期的量,不该决定这张表的顺序
1185
+ .sort((a, b) => (b.newForks || 0) - (a.newForks || 0)
1186
+ || Date.parse(b.lastFork?.at || 0) - Date.parse(a.lastFork?.at || 0));
1187
+ if (!rows.length) return;
1188
+ const table = document.createElement("table");
1189
+ // 表里只放这一段窗口的量:累计 fork 是全生命周期的数,放进来会被当成窗口结果
1190
+ table.innerHTML = "<thead><tr><th>仓库</th><th>新增</th><th>最近</th></tr></thead>";
1191
+ const body = document.createElement("tbody");
1192
+ for (const r of rows) {
1193
+ const tr = document.createElement("tr");
1194
+ tr.innerHTML = `<td>${r.name}</td><td>${(r.newForks || 0).toLocaleString("en")}</td><td>${r.lastFork ? label(r.lastFork.at) : "—"}</td>`;
1195
+ body.appendChild(tr);
1196
+ }
1197
+ table.appendChild(body);
1198
+ list.appendChild(table);
1199
+ return;
1200
+ }
1201
+ if (items.length > 20) {
1202
+ note.hidden = false;
1203
+ note.textContent = `只列最近 20 个,另有 ${Math.max(items.length, inWin) - 20} 个`;
1204
+ }
1205
+ const table = document.createElement("table");
1206
+ table.innerHTML = "<thead><tr><th>谁</th><th>时间</th></tr></thead>";
1207
+ const body = document.createElement("tbody");
1208
+ for (const x of items.slice(0, 20)) {
1209
+ const tr = document.createElement("tr");
1210
+ const who = document.createElement("td");
1211
+ const a = document.createElement("a");
1212
+ a.href = x.url;
1213
+ a.target = "_blank";
1214
+ a.rel = "noreferrer";
1215
+ a.textContent = x.login;
1216
+ who.appendChild(a);
1217
+ const when = document.createElement("td");
1218
+ when.textContent = label(x.at);
1219
+ tr.append(who, when);
1220
+ body.appendChild(tr);
1221
+ }
1222
+ table.appendChild(body);
1223
+ list.appendChild(table);
1224
+ }
1225
+
1226
+ function renderFunnel(f) {
1227
+ const sec = document.getElementById("sec-funnel");
1228
+ if (!f || f.views == null) { sec.hidden = true; return; }
1229
+ sec.hidden = false;
1230
+ document.getElementById("f-views").textContent = fmt(f.views);
1231
+ // 漏斗固定取最近 14 个完整日,和上面选的范围无关,窗口写在数字下面而不是标题上
1232
+ document.getElementById("f-views-sub").textContent = `近 ${Math.min(LIVE.range?.covered || 14, 14)} 天`;
1233
+ document.getElementById("f-home").textContent = f.home == null ? "—" : fmt(f.home);
1234
+ document.getElementById("f-home-sub").textContent = f.home == null ? "" : Math.round((f.home / f.views) * 100) + "% 浏览";
1235
+ const fNoPkg = LIVE.repo && LIVE.repo.fullName !== "全部仓库" && !LIVE.repo.npmPkg;
1236
+ document.getElementById("f-npm").textContent = f.npm == null || fNoPkg ? "—" : fmt(f.npm);
1237
+ // 下载和浏览取同一段 14 天,只给日均,不跨窗口算倍数
1238
+ const fDays = Math.min(LIVE.range?.covered || 14, 14);
1239
+ document.getElementById("f-npm-sub").textContent = f.npm == null || fNoPkg ? "" : `日均 ${fmt(Math.round(f.npm / fDays))} 次`;
1240
+ }
1241
+
654
1242
  function applyLive(json) {
655
1243
  Object.assign(LIVE, json);
656
1244
  LIVE_SET = true;
@@ -673,50 +1261,177 @@ function applyLive(json) {
673
1261
  const rows = [...merged.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
674
1262
  const rest = [...merged.values()].reduce((s, n) => s + n, 0) - rows.reduce((s, r) => s + r[1], 0);
675
1263
  PATHS = rows.map(([k, n], i) => [k, n, i === 0 ? "--brand" : i === 1 ? "--machine" : "--event"]);
676
- if (rest > 0) PATHS.push(["其他页面", rest, "--border-l2"]);
1264
+ if (rest > 0) PATHS.push(["其他页面", rest, "--label-secondary"]);
677
1265
  }
678
1266
  if (Array.isArray(json.referrers) && json.referrers.length) {
679
- RANKS = [["从哪来", json.referrers.slice(0, 4).map(r => [r.from.replace(/^www\./, ""), r.n])]];
1267
+ const refTotal = json.referrers.reduce((a, r) => a + r.n, 0);
1268
+ const refTop = json.referrers.slice(0, 4);
1269
+ const refShown = refTop.reduce((a, r) => a + r.n, 0);
1270
+ const refRest = refTotal - refShown;
1271
+ // GitHub 只回前几个来源,写「有来源 N 次」会被读成全部推荐流量的总数
1272
+ const refNote = refTotal
1273
+ ? `前 ${refTop.length} 个 ${refShown.toLocaleString("en-US")} 次${refRest > 0 ? ` · 另有 ${refRest.toLocaleString("en-US")} 次来自其他来源` : ""}`
1274
+ : "";
1275
+ RANKS = [["从哪来", refTop.map(r => [r.from.replace(/^www\./, ""), r.n]), refNote]];
680
1276
  }
681
1277
  const repo = json.repo || {};
682
1278
  const ownerEl = document.getElementById("repo-owner");
683
1279
  const nameEl = document.getElementById("repo-name");
1280
+ const askQ = document.getElementById("ask-q");
1281
+ if (askQ) askQ.placeholder = repo.fullName === "全部仓库" ? "问全部仓库" : "问这个仓库";
684
1282
  if (repo.fullName === "全部仓库") {
685
1283
  ownerEl.textContent = "";
686
1284
  nameEl.textContent = "全部仓库";
1285
+ setRepoLink(null);
687
1286
  } else {
688
1287
  ownerEl.textContent = repo.owner ? repo.owner + " /" : "";
689
1288
  nameEl.textContent = repo.name || "";
1289
+ setRepoLink(repo.fullName);
690
1290
  }
691
1291
  const c = json.contributions || { issues: [], pulls: [] };
692
1292
  const ic = c.issues.length, pc = c.pulls.length;
693
1293
  document.getElementById("k-contrib").textContent = ic + pc;
694
- document.getElementById("k-contrib-sub").textContent = ic + " issue、" + pc + " PR";
1294
+ // 1 天视图报的是最近一个完整日,不是今天
1295
+ const dayLbl = json.range && json.range.to ? label(json.range.to) : "今天";
1296
+ // 子标要说清是哪几类反馈,别只给一个合计
1297
+ // 多天窗口里数据不够长时,写实际有数据的天数:90 天的选择只有 19 天数据,不能当成 90 天
1298
+ // 口径和摘要一致:min(图上选的天数, 实际覆盖天数),today 没采集到不算一天
1299
+ const rg = json.range || {}, asked = rg.days;
1300
+ const spanDays = asked && rg.covered ? Math.min(asked, rg.covered) : null;
1301
+ const covLbl = spanDays && asked && spanDays < asked ? spanDays + " 天 · " : "";
1302
+ document.getElementById("k-contrib-sub").textContent = currentRange === 1
1303
+ ? (ic + pc ? dayLbl + " 新开 " + ic + " issue、" + pc + " PR" : dayLbl + " 没有新开 issue 或 PR")
1304
+ : covLbl + ic + " issue、" + pc + " PR";
695
1305
  document.getElementById("k-stars").textContent = repo.stars ?? "—";
696
- document.getElementById("k-forks").textContent = (repo.forks ?? 0) + " forks";
1306
+ // 星标增长只报真实覆盖区间:1 天报当天,多天报有数据的跨度
1307
+ const sg = json.starGrowth;
1308
+ const gTxt = sg && Number.isFinite(sg.delta) && sg.span
1309
+ ? (sg.span === 1 ? label(sg.to) : "近 " + sg.span + " 天") + " " + (sg.delta > 0 ? "+" + sg.delta : sg.delta === 0 ? "±0" : String(sg.delta))
1310
+ : "";
1311
+ // 星标卡下面报的 fork 也要是这一窗口的,跟左边的星标增量对齐
1312
+ const forkWin = json.forks ? json.forks.inWindow || 0 : 0;
1313
+ document.getElementById("k-forks").textContent = (gTxt ? gTxt + " · " : "")
1314
+ + (forkWin ? "新增 " + forkWin + " 个 fork" : "没有新 fork")
1315
+ + (repo.fullName === "全部仓库" && repo.count ? " · " + repo.count + " 个仓" : "");
697
1316
  const rels = (json.releases || []).filter(r => DATA.some(x => x.d === label(r.at)));
698
- document.getElementById("k-rel").textContent = rels.length;
1317
+ // 后端对发版列表有硬上限(全局 120、单仓 200):只有真的取满上限,数字才是下限
1318
+ const relCap = repo.fullName === "全部仓库" ? 120 : 200;
1319
+ const relCapped = rels.length >= relCap;
1320
+ document.getElementById("k-rel").textContent = relCapped ? rels.length + "+" : rels.length;
1321
+ const relSpan = repo.fullName === "全部仓库"
1322
+ ? (() => { const first = label(rels[rels.length - 1].at), last = label(rels[0].at); return first === last ? last : first + " → " + last; })()
1323
+ : (() => { const first = bareTag(rels[rels.length - 1].tag), last = bareTag(rels[0].tag); return first === last ? last : first + " → " + last; })();
1324
+ // 截断时说清这个区间只是最近若干个,别让人把 11-07 当成窗口起点
699
1325
  document.getElementById("k-rel-sub").textContent = rels.length
700
- ? (repo.fullName === "全部仓库" ? "最近 " + label(rels[0].at) : rels[rels.length - 1].tag + " → " + rels[0].tag)
1326
+ ? (relCapped ? "最近 " + rels.length + " 个 · " + relSpan : relSpan)
701
1327
  : "本窗口无发版";
702
- const iss = c.issues[0];
1328
+ const pending = c.open ? c.open.issues : c.issues.filter((x) => x.state === "open");
703
1329
  document.getElementById("s-issues").textContent = ic + " 个";
704
- document.getElementById("s-issues-sub").textContent = iss
705
- ? (iss.state === "closed" ? "已关闭," : "开着,") + "来自 " + iss.author
706
- : "没有外部 issue";
707
- const pr = c.pulls[0];
1330
+ const issub = document.getElementById("s-issues-sub");
1331
+ issub.textContent = "";
1332
+ // 一个都别藏:没有 hover 的触屏上 tooltip 等于不存在,每条都做成链接
1333
+ const addLinks = (parent, rows) => {
1334
+ rows.forEach((x, i) => {
1335
+ if (i) parent.appendChild(document.createTextNode("、"));
1336
+ const a = document.createElement("a");
1337
+ a.href = x.url;
1338
+ a.target = "_blank";
1339
+ a.rel = "noreferrer";
1340
+ a.textContent = `${(x.repo || "").split("/")[1] || ""} #${x.number}`.trim();
1341
+ parent.appendChild(a);
1342
+ });
1343
+ };
1344
+ if (!pending.length) {
1345
+ // 没有还开着的,不等于「都回复过」:关掉的也可能是没人理的
1346
+ issub.textContent = ic ? `窗口内 ${ic} 个都已关闭` : "没有外部 issue";
1347
+ } else {
1348
+ const replied = pending.some((x) => (x.comments ?? 0) > 0);
1349
+ issub.textContent = (ic ? "" : "窗口内没有新的;") + (pending.length === 1 ? (replied ? "还开着:" : "没回:") : `${replied ? "还开着" : "没回"} ${pending.length} 个:`);
1350
+ addLinks(issub, pending);
1351
+ }
708
1352
  document.getElementById("s-prs").textContent = pc + " 个";
709
- document.getElementById("s-prs-sub").textContent = pr
710
- ? (pr.merged ? "已合并" : "没合并") + (pr.additions != null ? ",+" + pr.additions + " −" + pr.deletions : ",来自 " + pr.author)
711
- : "没有外部 PR";
1353
+ const prSub = document.getElementById("s-prs-sub");
1354
+ const prMerged = c.pulls.filter((x) => x.merged).length;
1355
+ const openPrs = c.open ? c.open.pulls : c.pulls.filter((x) => !x.merged);
1356
+ prSub.textContent = "";
1357
+ if (openPrs.length) {
1358
+ prSub.textContent = (prMerged ? `已合并 ${prMerged} 个 · ` : "") + (pc ? "" : "窗口内没有新的;")
1359
+ + (openPrs.length === 1 ? "待合:" : `待合 ${openPrs.length} 个:`);
1360
+ addLinks(prSub, openPrs);
1361
+ } else if (!pc) {
1362
+ prSub.textContent = "没有外部 PR";
1363
+ } else {
1364
+ prSub.textContent = `窗口内 ${pc} 个都已处理`;
1365
+ }
1366
+ const fresh = document.getElementById("contrib-fresh");
1367
+ if (fresh) {
1368
+ const d = c.at ? new Date(c.at) : null;
1369
+ fresh.textContent = d && !Number.isNaN(d.getTime()) ? `· ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")} 更新` : "";
1370
+ }
712
1371
  const al = c.alerts;
713
1372
  const opened = al ? ["dependabot", "codeScanning", "secretScanning"].filter(k => al[k]?.available) : [];
714
1373
  const total = al ? opened.reduce((s, k) => s + (al[k].open || 0), 0) : null;
715
- document.getElementById("s-alerts").textContent = !al || !opened.length ? "未开启" : total ? total + " 条" : "无";
716
- document.getElementById("s-alerts-sub").textContent = !al || !opened.length ? "无数据" : total ? "待处理" : "已开启";
1374
+ renderImpact(json.impact);
1375
+ renderImpacts(json.impacts);
1376
+ renderFunnel(json.funnel);
1377
+ // 这里还没拿到 render(days) 的参数:用当前窗口,切范围时 render 会再刷一次
1378
+ renderForks(json, json.range?.days || currentRange);
1379
+ OVERVIEW = json.repos || [];
1380
+ drawOverview();
1381
+ renderTop();
1382
+ const atype = { dependabot: "依赖漏洞", codeScanning: "代码扫描", secretScanning: "密钥泄漏" };
1383
+ const asub = document.getElementById("s-alerts-sub");
1384
+ const aval = document.getElementById("s-alerts");
1385
+ const blocked = !!al && ["dependabot", "codeScanning", "secretScanning"].every((k) => al[k] && !al[k].available && al[k].blocked);
1386
+ aval.textContent = blocked ? "缺权限" : !al || !opened.length ? "关闭" : (total || 0) + " 条";
1387
+ asub.textContent = "";
1388
+ asub.removeAttribute("title");
1389
+ if (blocked) {
1390
+ asub.textContent = "重新授权 GitHub";
1391
+ } else if (!al || !opened.length) {
1392
+ asub.textContent = "无数据";
1393
+ } else if (!total) {
1394
+ // 0 条要说清零的含义,不能拿「功能已开启」当解释
1395
+ asub.textContent = json.repo && json.repo.fullName === "全部仓库" ? "全部仓库都没有待处理" : "没有待处理";
1396
+ } else if (Array.isArray(json.repos)) {
1397
+ const flat = opened.flatMap((k) => (al[k].repos || []).filter((r) => r.open > 0).map((r) => ({ type: k, ...r })));
1398
+ flat.sort((x, y) => y.open - x.open);
1399
+ const top = flat[0];
1400
+ if (top) {
1401
+ const a = document.createElement("a");
1402
+ a.href = `https://github.com/${top.key}/security/${top.type === "dependabot" ? "dependabot" : top.type === "codeScanning" ? "code-scanning" : "secret-scanning"}`;
1403
+ a.target = "_blank";
1404
+ a.rel = "noreferrer";
1405
+ a.textContent = `${top.key.split("/")[1]} ${top.open} 条`;
1406
+ // 主数是全部仓库合计,子标只点了最大的一仓,得说清这两件事
1407
+ asub.textContent = json.repo && json.repo.fullName === "全部仓库" ? "全部仓库合计 · 最多 " : "最多 ";
1408
+ asub.appendChild(a);
1409
+ asub.append(` · ${atype[top.type]}`);
1410
+ asub.title = flat.map((r) => `${r.key.split("/")[1]} ${atype[r.type]} ${r.open}`).join("\n");
1411
+ } else {
1412
+ asub.textContent = "待处理";
1413
+ }
1414
+ } else {
1415
+ const parts = opened.filter((k) => al[k].open > 0).map((k) => `${atype[k]} ${al[k].open}`);
1416
+ const a = document.createElement("a");
1417
+ a.href = `https://github.com/${json.repo.fullName}/security`;
1418
+ a.target = "_blank";
1419
+ a.rel = "noreferrer";
1420
+ asub.append(a);
1421
+ const txt = parts.length ? parts.join("、") : "待处理";
1422
+ a.textContent = txt;
1423
+ asub.title = "依赖漏洞 / 代码扫描 / 密钥泄漏";
1424
+ }
717
1425
  const t = json.totals || {};
718
- if (t.npmWeek != null) {
719
- document.getElementById("k-npm").textContent = fmt(t.npmWeek);
1426
+ // 逐日下载是按窗口存的,跟 npmWeek 那个固定 7 天滚动值不是一回事:这里只报窗口合计
1427
+ const npmWin = t.npm;
1428
+ document.getElementById("k-npm").textContent = npmWin != null ? fmt(npmWin) : "—";
1429
+ const npmSub = document.getElementById("k-npm-sub");
1430
+ if (npmSub) {
1431
+ const span = currentRange === 1 ? "当天" : `近 ${Math.min(currentRange, LIVE.range?.covered || currentRange)} 天`;
1432
+ const noPkg = repo.fullName !== "全部仓库" && LIVE.repo && !LIVE.repo.npmPkg;
1433
+ npmSub.textContent = noPkg ? "没有关联 npm 包" : npmWin == null ? "还没采集到"
1434
+ : (repo.fullName === "全部仓库" && repo.count ? repo.count + " 个仓 · " : "") + span;
720
1435
  }
721
1436
  const days = json.range?.storedDays || 0;
722
1437
  document.getElementById("r-days").textContent = days + " 天";
@@ -727,7 +1442,15 @@ function applyLive(json) {
727
1442
  }
728
1443
 
729
1444
  let REPOS = [];
730
- let currentRepo = "all";
1445
+ let currentRepo = new URLSearchParams(location.search).get("repo") || "all";
1446
+ function setRepoLink(fullName) {
1447
+ const a = document.getElementById("repo-open");
1448
+ if (!a) return;
1449
+ const owner = REPOS[0] ? REPOS[0].key.split("/")[0] : "";
1450
+ const url = fullName ? "https://github.com/" + fullName : owner ? "https://github.com/" + owner : "";
1451
+ if (url) { a.href = url; a.hidden = false; } else a.hidden = true;
1452
+ }
1453
+
731
1454
  const PICK = document.getElementById("repo-pick");
732
1455
  const MENU = document.getElementById("repo-menu");
733
1456
 
@@ -757,11 +1480,28 @@ async function loadRepos() {
757
1480
  if (!res.ok) return;
758
1481
  const data = await res.json();
759
1482
  REPOS = data.repos || [];
760
- if (currentRepo !== "all" && !REPOS.some((r) => r.key === currentRepo)) currentRepo = "all";
1483
+ if (currentRepo !== "all" && !REPOS.some((r) => r.key === currentRepo)) {
1484
+ // 解析口径跟后端 resolveKey 对齐:精确 → 忽略大小写 → 仓名唯一匹配
1485
+ // 这样?repo=Envoy 和大小写/owner 写错的整名链接都能落到同一个仓,不会误退回全部仓库
1486
+ const q = currentRepo.toLowerCase();
1487
+ const nameOf = (k) => k.split("/")[1]?.toLowerCase() || "";
1488
+ // 只传仓名的链接按仓名唯一匹配;带 owner 的链接必须整个 key 对上(忽略大小写)
1489
+ const byName = currentRepo.includes("/") ? [] : REPOS.filter((r) => nameOf(r.key) === q);
1490
+ const hit = REPOS.find((r) => r.key.toLowerCase() === q)
1491
+ || (byName.length === 1 ? byName[0] : null);
1492
+ const asked = currentRepo;
1493
+ currentRepo = hit ? hit.key : "all";
1494
+ // 链接里的仓没绑定时把参数改掉:否则下次刷新又退回全部仓库,还看不出为什么
1495
+ const u = new URL(location.href);
1496
+ if (hit) u.searchParams.set("repo", hit.key);
1497
+ else { u.searchParams.delete("repo"); stickyNote = true; repoNote("没有绑定 " + asked + ",已切回全部仓库"); }
1498
+ history.replaceState(null, "", u);
1499
+ }
761
1500
  paintRepos();
762
1501
  const cur = REPOS.find((r) => r.key === currentRepo);
763
1502
  document.getElementById("repo-name").textContent = cur ? cur.key.replace(/^[^/]+\//, "") : "全部仓库";
764
1503
  document.getElementById("repo-owner").textContent = cur ? cur.key.split("/")[0] + " /" : "";
1504
+ setRepoLink(cur ? cur.key : null);
765
1505
  } catch (e) {}
766
1506
  }
767
1507
 
@@ -772,63 +1512,352 @@ PICK.addEventListener("click", (e) => {
772
1512
  PICK.setAttribute("aria-expanded", String(open));
773
1513
  });
774
1514
 
1515
+ function switchRepo(key) {
1516
+ stickyNote = false;
1517
+ currentRepo = key;
1518
+ paintRepos();
1519
+ const cur = REPOS.find((r) => r.key === key);
1520
+ document.getElementById("repo-name").textContent = key === "all" ? "全部仓库" : key.replace(/^[^/]+\//, "");
1521
+ document.getElementById("repo-owner").textContent = key === "all" ? "" : key.split("/")[0] + " /";
1522
+ setRepoLink(key === "all" ? null : key);
1523
+ const u = new URL(location.href);
1524
+ if (key === "all") u.searchParams.delete("repo"); else u.searchParams.set("repo", key);
1525
+ history.replaceState(null, "", u);
1526
+ pull(currentRange, true);
1527
+ }
1528
+
775
1529
  MENU.addEventListener("click", (e) => {
776
1530
  const b = e.target.closest("button");
777
1531
  if (!b) return;
778
- currentRepo = b.dataset.key;
779
- [...MENU.children].forEach((x) => x.classList.toggle("on", x === b));
780
- paintRepos();
781
- const cur = REPOS.find((r) => r.key === currentRepo);
782
- document.getElementById("repo-name").textContent = b.textContent;
783
- document.getElementById("repo-owner").textContent = cur ? cur.key.split("/")[0] + " /" : "";
784
- pull(currentRange, true);
1532
+ switchRepo(b.dataset.key);
785
1533
  });
786
1534
 
787
1535
  document.addEventListener("click", () => closeMenu());
788
1536
 
789
- async function pull(days, force) {
1537
+ let PULL_SEQ = 0;
1538
+ // 「这个仓没绑定」这类要一直留着,直到用户自己换仓;网络抖动的提示下次拉通就清
1539
+ let stickyNote = false;
1540
+ function repoNote(txt) {
1541
+ const el = document.getElementById("repo-note");
1542
+ if (!el) return;
1543
+ el.textContent = txt || "";
1544
+ el.hidden = !txt;
1545
+ }
1546
+ let FIRST_T = null;
1547
+ async function pull(days, force, quiet) {
1548
+ const seq = ++PULL_SEQ;
1549
+ const want = currentRepo;
790
1550
  try {
791
- const res = await fetch("/api/data?days=" + days + "&repo=" + encodeURIComponent(currentRepo), { cache: "no-store" });
1551
+ const res = await fetch("/api/data?days=" + days + "&repo=" + encodeURIComponent(want), { cache: "no-store" });
1552
+ if (res.status === 404) {
1553
+ // ?repo= 指向没绑定的仓:退回全部仓库重拉,别把上一个仓的数字留在屏上
1554
+ const info = await res.json().catch(() => ({}));
1555
+ if (seq !== PULL_SEQ) return null;
1556
+ currentRepo = "all";
1557
+ const u = new URL(location.href);
1558
+ u.searchParams.delete("repo");
1559
+ history.replaceState(null, "", u);
1560
+ document.getElementById("repo-name").textContent = "全部仓库";
1561
+ document.getElementById("repo-owner").textContent = "";
1562
+ setRepoLink(null);
1563
+ paintRepos();
1564
+ stickyNote = true;
1565
+ repoNote(info.error || "这个仓库不在监控列表,已切回全部仓库");
1566
+ return pull(days, true, quiet);
1567
+ }
792
1568
  if (!res.ok) throw new Error(res.status);
793
1569
  const json = await res.json();
794
- if (json.repo && !json.repo.stars && !force) { /* 未同步过也照常渲染 */ }
1570
+ // 连点切仓时慢的那次不许盖掉新仓:只认最后一次请求
1571
+ if (seq !== PULL_SEQ) return null;
1572
+ // 还没绑定:整屏交给绑定页,别让空 KPI 在底下闪
1573
+ if (json.needsBinding) {
1574
+ // 服务端知道这台机器上有哪几条登录路可走,先问到再开绑定页
1575
+ if (!GATE.state) await gateBoot();
1576
+ if (!GATE.state) gateOpen({ bound: false, repos: 0 });
1577
+ return null;
1578
+ }
1579
+ // 冷启动时第一次同步还没落盘:显示进度并自己重试,别把空快照画成「没有流量」
1580
+ if (json.empty) {
1581
+ const st = await fetch("/api/progress", { cache: "no-store" }).then((r) => r.json()).catch(() => null);
1582
+ if (seq === PULL_SEQ && st && st.running) {
1583
+ repoNote("正在同步 " + st.done + "/" + st.total + " 个仓库,第一次要一会儿");
1584
+ clearTimeout(FIRST_T);
1585
+ FIRST_T = setTimeout(() => { if (seq === PULL_SEQ) pull(days, true, quiet); }, 2500);
1586
+ return null;
1587
+ }
1588
+ }
1589
+ if (!stickyNote) repoNote("");
795
1590
  applyLive(json);
796
1591
  if (!(days === LIVE.range.days)) LIVE.range.days = days;
797
1592
  render(days);
798
- loadSummary(days);
1593
+ if (!quiet) loadSummary(days);
799
1594
  return json;
800
1595
  } catch (e) {
801
- render(days);
1596
+ if (seq !== PULL_SEQ) return null;
1597
+ // 拉不到就明说屏上是旧数据,别让旧仓数字看起来像新仓的
1598
+ repoNote("没连上服务,屏上还是上一次的数据");
1599
+ // 旧数据就按旧范围重画,别挂上新范围的名字
1600
+ render(LIVE.range?.days || days);
802
1601
  return null;
803
1602
  }
804
1603
  }
805
1604
 
806
- async function loadSummary(days) {
1605
+ // 概览别停在旧状态:切回页面立刻拉一次,1 天窗口 60 秒,其它 5 分钟
1606
+ let SOFT_T = null;
1607
+ async function softRefresh() {
1608
+ clearTimeout(SOFT_T);
1609
+ if (!document.hidden) await pull(currentRange, true, true);
1610
+ SOFT_T = setTimeout(softRefresh, currentRange === 1 ? 60000 : 300000);
1611
+ }
1612
+ addEventListener("visibilitychange", () => { if (!document.hidden) softRefresh(); });
1613
+
1614
+ let SUM_SEQ = 0;
1615
+ async function loadSummary(days, tries = 0) {
1616
+ const seq = ++SUM_SEQ;
807
1617
  try {
808
1618
  const res = await fetch("/api/summary?days=" + days + "&repo=" + encodeURIComponent(currentRepo), { cache: "no-store" });
809
- if (!res.ok) return;
1619
+ if (!res.ok || seq !== SUM_SEQ) return;
810
1620
  const data = await res.json();
1621
+ if (seq !== SUM_SEQ) return;
811
1622
  const lines = data.lines || [];
812
1623
  ["sum-1", "sum-2", "sum-3"].forEach((id, i) => {
813
1624
  const node = document.getElementById(id);
814
1625
  if (!node) return;
815
1626
  node.textContent = lines[i] || "";
1627
+ node.hidden = !lines[i];
816
1628
  });
817
1629
  const at = document.getElementById("sum-at");
818
1630
  if (at) at.textContent = new Date().toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).replace("/", "-");
819
- } catch (e) {}
1631
+ // 来源和回退原因都写出来,别让人以为这就是模型写的
1632
+ const why = { checked: "数字没对上", empty: "模型没返回内容" }[data.error] || (data.error ? "请求失败" : "");
1633
+ const srcEl = document.getElementById("sum-src");
1634
+ // 没有 error 的 template 是后台还在生成,不是失败,别写成「模板兜底」
1635
+ if (srcEl) srcEl.textContent = data.source === "ai" ? "" : data.source === "none" ? "未配置模型" : why ? "模板兜底 · " + why : "模型生成中…";
1636
+ const modelEl = document.getElementById("ai-model");
1637
+ if (modelEl) modelEl.textContent = data.source === "ai" ? (data.model || "") : "";
1638
+ // 摘要第一次生成要几十秒,先给模板,生成好了再换过来
1639
+ // 模型一次要几十秒、最坏两三分钟,间隔逐次拉长,最多等近三分钟
1640
+ if (data.source === "template" && tries < 9) setTimeout(() => loadSummary(days, tries + 1), Math.min(5000 * (tries + 1), 20000));
1641
+ } catch (e) {
1642
+ console.error("summary failed", e);
1643
+ }
820
1644
  }
821
1645
 
822
1646
  document.querySelector(".ask button").addEventListener("click", async () => {
823
1647
  const input = document.querySelector(".ask input");
824
- if (!input.value.trim()) return;
1648
+ const btn = document.querySelector(".ask button");
1649
+ const out = document.getElementById("ask-out");
1650
+ const q = input.value.trim();
1651
+ if (!q) return;
825
1652
  input.disabled = true;
826
- const res = await loadSummary(currentRange);
827
- input.disabled = false;
1653
+ btn.disabled = true;
1654
+ out.hidden = false;
1655
+ out.textContent = "在查…";
1656
+ const slow = setTimeout(() => { if (!out.hidden && /在查/.test(out.textContent)) out.textContent = "还在查…"; }, 8000);
1657
+ const ac = new AbortController();
1658
+ const to = setTimeout(() => ac.abort(), 32000);
1659
+ try {
1660
+ const r = await postJson("/api/ask", { question: q, repo: currentRepo, days: currentRange }, { signal: ac.signal });
1661
+ const d = await r.json();
1662
+ out.replaceChildren();
1663
+ out.appendChild(document.createTextNode(d.answer || "没答上来。"));
1664
+ for (const l of d.links || []) {
1665
+ out.appendChild(document.createElement("br"));
1666
+ const a = document.createElement("a");
1667
+ a.href = l.url;
1668
+ a.target = "_blank";
1669
+ a.rel = "noreferrer";
1670
+ a.textContent = l.label;
1671
+ out.appendChild(a);
1672
+ }
1673
+ if (d.source === "ai") input.value = "";
1674
+ } catch (e) {
1675
+ out.textContent = e && e.name === "AbortError" ? "等太久了,再问一次。" : "连不上本地服务。";
1676
+ } finally {
1677
+ clearTimeout(to);
1678
+ clearTimeout(slow);
1679
+ input.disabled = false;
1680
+ btn.disabled = false;
1681
+ }
828
1682
  });
829
1683
 
830
1684
 
831
- loadRepos().then(() => pull(7));
1685
+ const segInit = document.getElementById("seg");
1686
+ [...segInit.children].forEach((b) => b.classList.toggle("on", +b.dataset.r === currentRange));
1687
+ // 「刷新」周期跟着后端启动参数走,页面上不写死一个时间
1688
+ async function loadInterval() {
1689
+ try {
1690
+ const r = await fetch("/api/progress");
1691
+ const st = await r.json();
1692
+ const el = document.getElementById("r-interval");
1693
+ if (el && st.intervalHours) el.textContent = `每 ${st.intervalHours} 小时`;
1694
+ const row = document.getElementById("r-contrib-row");
1695
+ const cb = document.getElementById("r-contrib");
1696
+ if (row && cb && st.contribMinutes > 0) {
1697
+ cb.textContent = `每 ${st.contribMinutes} 分钟`;
1698
+ row.hidden = false;
1699
+ }
1700
+ } catch { /* 拿不到就留着占位 */ }
1701
+ }
1702
+
1703
+ // ---- 绑定账号 ----
1704
+ // 只有一条主路:在浏览器里登录 GitHub 确认一次,绑的就是点确认的那个人。
1705
+ // 不读这台机器已有的登录态,别人打开不会绑到当前电脑的账号上。
1706
+ // 没有 git 命令行时退回粘贴访问令牌。
1707
+ const GATE = { on: false, state: null, timer: null };
1708
+ function gateSay(txt) { const el = document.getElementById("gate-out"); if (el) el.textContent = txt || ""; }
1709
+ function gateOpen(state) {
1710
+ GATE.on = true;
1711
+ GATE.state = state;
1712
+ document.getElementById("gate").classList.add("on");
1713
+ document.body.classList.add("gated");
1714
+ const main = document.getElementById("gate-main");
1715
+ const lead = document.getElementById("gate-lead");
1716
+ main.textContent = "";
1717
+ const browser = state.loginMode === "device" || state.loginMode === "gh";
1718
+ if (browser) {
1719
+ lead.textContent = "登录你的账号,数据只存在这台电脑上。";
1720
+ } else {
1721
+ lead.textContent = "粘贴访问令牌就能绑上。";
1722
+ }
1723
+ // 令牌输入是兜底,不是可选项:浏览器这条路走不通时它就顶上来,别把它藏掉
1724
+ const alt = document.querySelector(".gate-alt");
1725
+ if (alt) alt.classList.toggle("sep-top", browser);
1726
+ const altLead = document.getElementById("gate-alt-lead");
1727
+ if (altLead) altLead.hidden = !browser;
1728
+ const btn = document.createElement("button");
1729
+ btn.className = "primary";
1730
+ btn.id = "gate-go";
1731
+ btn.textContent = browser ? "用 GitHub 登录" : "绑定访问令牌";
1732
+ btn.onclick = () => (browser ? gateLogin(btn) : gatePaste(btn));
1733
+ main.appendChild(btn);
1734
+ }
1735
+ function gateClose() {
1736
+ GATE.on = false;
1737
+ clearInterval(GATE.timer);
1738
+ document.getElementById("gate").classList.remove("on");
1739
+ document.body.classList.remove("gated");
1740
+ }
1741
+ // 刚绑上时快照还是空的,第一次同步要跑好几十秒;这段时间说清楚在等什么,
1742
+ // 别让「没连上服务」这种失败文案盖在一个其实正常的首次同步上
1743
+ async function gateWaitSync() {
1744
+ for (let i = 0; i < 90; i++) {
1745
+ const st = await fetch("/api/progress", { cache: "no-store" }).then((r) => r.json()).catch(() => null);
1746
+ if (!st || !st.running) return true;
1747
+ repoNote(`正在同步 ${st.done}/${st.total} 个仓库,第一次要一会儿`);
1748
+ await new Promise((r) => setTimeout(r, 2000));
1749
+ }
1750
+ return false;
1751
+ }
1752
+ async function gateDone(json) {
1753
+ gateClose();
1754
+ gateSay("");
1755
+ await loadRepos();
1756
+ repoNote("已绑定 " + (json.login || "") + "," + json.repos + " 个仓库,正在同步");
1757
+ await gateWaitSync();
1758
+ await pull(currentRange, true, true);
1759
+ }
1760
+ async function gatePost(url, body) {
1761
+ const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body || {}) });
1762
+ const json = await res.json().catch(() => ({}));
1763
+ if (!res.ok) throw new Error(json.error || "没成功(" + res.status + ")");
1764
+ return json;
1765
+ }
1766
+ async function gateLogin(btn) {
1767
+ btn.disabled = true;
1768
+ gateSay("正在打开 GitHub…");
1769
+ let d;
1770
+ try {
1771
+ d = await gatePost("/api/auth/login");
1772
+ } catch (e) {
1773
+ gateSay(e.message);
1774
+ btn.disabled = false;
1775
+ return;
1776
+ }
1777
+ gateSay("");
1778
+ // 码、确认入口、进度都放在按钮下面,和这一步贴着,不要挂到卡片底部
1779
+ const box = document.createElement("div");
1780
+ box.style.cssText = "margin-top:10px;line-height:1.7";
1781
+ if (d.userCode) {
1782
+ const code = document.createElement("p");
1783
+ code.className = "gate-code";
1784
+ code.id = "gate-veri";
1785
+ code.style.margin = "0";
1786
+ code.textContent = d.userCode;
1787
+ box.appendChild(code);
1788
+ }
1789
+ if (d.verifyUrl) {
1790
+ const p = document.createElement("p");
1791
+ p.style.margin = "0";
1792
+ const a = document.createElement("a");
1793
+ a.href = d.verifyUrl;
1794
+ a.target = "_blank";
1795
+ a.rel = "noopener";
1796
+ a.textContent = "在 GitHub 里确认";
1797
+ p.appendChild(a);
1798
+ box.appendChild(p);
1799
+ // 能在点击里直接开更好;被拦了还有上面那个链接
1800
+ window.open(d.verifyUrl, "_blank", "noopener");
1801
+ }
1802
+ const wait = document.createElement("p");
1803
+ wait.style.cssText = "margin:0;font-size:12px;color:var(--label-secondary)";
1804
+ wait.textContent = d.userCode ? "输入这个码后确认,会自动绑上" : "确认后会自动绑上";
1805
+ box.appendChild(wait);
1806
+ document.getElementById("gate-main").appendChild(box);
1807
+ clearInterval(GATE.timer);
1808
+ GATE.timer = setInterval(async () => {
1809
+ try {
1810
+ const out = await gatePost("/api/auth/login/poll", { mode: d.mode, id: d.id, deviceCode: d.deviceCode });
1811
+ if (out.status === "ok") {
1812
+ clearInterval(GATE.timer);
1813
+ gateSay("已绑定 " + out.login + "," + out.repos + " 个仓库");
1814
+ await gateDone(out);
1815
+ } else if (out.status !== "pending") {
1816
+ clearInterval(GATE.timer);
1817
+ gateSay(out.message || "没绑上,再点一次");
1818
+ btn.disabled = false;
1819
+ }
1820
+ } catch (e) {
1821
+ clearInterval(GATE.timer);
1822
+ gateSay(e.message);
1823
+ btn.disabled = false;
1824
+ }
1825
+ }, Math.max(2, d.interval || 3) * 1000);
1826
+ }
1827
+ async function gatePaste(btn) {
1828
+ const token = document.getElementById("gate-token").value.trim();
1829
+ if (!token) {
1830
+ gateSay("先粘贴访问令牌");
1831
+ document.getElementById("gate-token").focus();
1832
+ return;
1833
+ }
1834
+ btn.disabled = true;
1835
+ gateSay("正在核对…");
1836
+ try {
1837
+ const out = await gatePost("/api/auth", { token });
1838
+ gateSay("已绑定 " + out.login + "," + out.repos + " 个仓库");
1839
+ await gateDone(out);
1840
+ } catch (e) {
1841
+ gateSay(e.message);
1842
+ btn.disabled = false;
1843
+ }
1844
+ }
1845
+ document.getElementById("gate-new").href =
1846
+ "https://github.com/settings/tokens/new?scopes=repo,read:user&description=github-overview";
1847
+ document.getElementById("gate-token").addEventListener("keydown", (e) => {
1848
+ if (e.key === "Enter") { const b = document.getElementById("gate-go"); if (b && !b.disabled) b.click(); }
1849
+ });
1850
+ async function gateBoot() {
1851
+ try {
1852
+ const st = await fetch("/api/auth", { cache: "no-store" }).then((r) => r.json());
1853
+ GATE.state = st;
1854
+ if (!st.bound || !st.repos) gateOpen(st);
1855
+ } catch { /* 服务没起来时别挡着页面的错误提示 */ }
1856
+ }
1857
+
1858
+ loadRepos().then(() => { pull(currentRange); loadInterval(); });
1859
+ gateBoot();
1860
+ softRefresh();
832
1861
  let rzT;
833
1862
  addEventListener("resize", () => { clearTimeout(rzT); rzT = setTimeout(() => render(currentRange), 160); });
834
1863
  </script>