dsh-work-summary 0.0.0-stage → 0.3.0

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/client.js ADDED
@@ -0,0 +1,1233 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-work-summary',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const { useState, useEffect, useCallback } = React
7
+ // apply(ctx) 里保存,供「开工」按钮新建会话、发送首条任务。
8
+ let appCtx = null
9
+
10
+ const PANEL_ID = 'dsh-work-summary'
11
+ const ENDPOINT = '/dsh-work-summary/state'
12
+ const SCHEDULE_ENDPOINT = '/dsh-work-summary/schedule'
13
+ const BOARD_ENDPOINT = '/dsh-work-summary/board'
14
+ // 4 档活跃度;0 档(无日报)用虚线边框表示,不占颜色。
15
+ const HEAT_COLORS = [
16
+ 'rgba(47,158,68,.22)',
17
+ 'rgba(47,158,68,.44)',
18
+ 'rgba(47,158,68,.68)',
19
+ 'rgba(47,158,68,.95)',
20
+ ]
21
+ const DAY_MS = 86400000
22
+ // 热力图格子随窗口放大,窄屏收回到 20px,宽屏最大 50px。
23
+ const HEAT_CELL = 'clamp(20px, 4.6vw, 50px)'
24
+ const HEAT_GAP = 6
25
+ const DELIVERY_COLORS = {
26
+ done: '#2f9e44',
27
+ doing: '#1971c2',
28
+ todo: '#d9480f',
29
+ drop: '#868e96',
30
+ }
31
+
32
+ const S = {
33
+ page: {
34
+ boxSizing: 'border-box',
35
+ height: '100%',
36
+ overflow: 'auto',
37
+ padding: '24px 32px 48px',
38
+ marginTop: 'var(--dsh-frame-top-clearance, 0px)',
39
+ color: 'inherit',
40
+ fontSize: 14,
41
+ lineHeight: 1.65,
42
+ },
43
+ bar: { display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18, flexWrap: 'wrap' },
44
+ title: { fontSize: 20, fontWeight: 600, margin: 0 },
45
+ tabs: { display: 'flex', gap: 4, marginLeft: 'auto' },
46
+ tab: (active) => ({
47
+ border: '1px solid rgba(127,127,127,.28)',
48
+ background: active ? 'rgba(127,127,127,.16)' : 'transparent',
49
+ color: 'inherit',
50
+ borderRadius: 8,
51
+ padding: '5px 12px',
52
+ fontSize: 13,
53
+ cursor: 'pointer',
54
+ }),
55
+ ghost: {
56
+ border: '1px solid rgba(127,127,127,.28)', background: 'transparent', color: 'inherit',
57
+ borderRadius: 8, padding: '5px 12px', fontSize: 13, cursor: 'pointer',
58
+ },
59
+ muted: { opacity: 0.62, fontSize: 12 },
60
+ split: { display: 'flex', gap: 20, alignItems: 'flex-start' },
61
+ list: {
62
+ flex: '0 0 176px', display: 'flex', flexDirection: 'column', gap: 2,
63
+ maxHeight: 'calc(100vh - 200px)', overflow: 'auto', paddingRight: 4,
64
+ },
65
+ item: (active) => ({
66
+ textAlign: 'left', border: 'none', borderRadius: 8, cursor: 'pointer', color: 'inherit',
67
+ background: active ? 'rgba(99,155,255,.16)' : 'transparent',
68
+ fontWeight: active ? 600 : 400, padding: '6px 10px', fontSize: 13, display: 'block', width: '100%',
69
+ }),
70
+ doc: { flex: 1, minWidth: 0, maxWidth: 860 },
71
+ heading: { fontWeight: 600, margin: '18px 0 6px' },
72
+ para: { margin: '4px 0' },
73
+ bullet: { margin: '3px 0', paddingLeft: 4 },
74
+ table: { fontFamily: 'ui-monospace, SFMono-Regular, Consolas, monospace', fontSize: 12.5, whiteSpace: 'pre-wrap' },
75
+ code: { fontFamily: 'ui-monospace, SFMono-Regular, Consolas, monospace', fontSize: 12.5, background: 'rgba(127,127,127,.14)', padding: '1px 4px', borderRadius: 4 },
76
+ quote: { margin: '6px 0', paddingLeft: 10, borderLeft: '3px solid rgba(127,127,127,.3)', opacity: 0.8 },
77
+ hr: { border: 'none', borderTop: '1px solid rgba(127,127,127,.24)', margin: '14px 0' },
78
+ section: { marginBottom: 22 },
79
+ boardHead: { fontSize: 15, fontWeight: 600, margin: '0 0 8px' },
80
+ row: { display: 'flex', gap: 8, alignItems: 'flex-start', padding: '5px 0' },
81
+ dot: (open) => ({
82
+ flex: '0 0 auto', width: 13, height: 13, borderRadius: 3, marginTop: 4,
83
+ border: '1.5px solid rgba(127,127,127,.6)',
84
+ background: open ? 'transparent' : 'rgba(127,127,127,.55)',
85
+ }),
86
+ boardItem: { flex: 1, minWidth: 0 },
87
+ boardGroup: { marginBottom: 12 },
88
+ boardGroupHead: { fontSize: 12.5, fontWeight: 600, opacity: 0.72, margin: '10px 0 2px' },
89
+ boardBadge: (kind) => ({
90
+ display: 'inline-block', marginLeft: 6, padding: '0 5px', borderRadius: 5, fontSize: 11,
91
+ lineHeight: '18px', whiteSpace: 'nowrap',
92
+ color: kind === 'overdue' ? '#d14343' : kind === 'P1' ? '#d9480f' : kind === 'P2' ? '#1971c2' : kind === 'P3' ? '#5f3dc4' : 'inherit',
93
+ background: kind === 'overdue' ? 'rgba(209,67,67,.12)' : 'rgba(127,127,127,.14)',
94
+ }),
95
+ boardControls: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' },
96
+ boardSelect: {
97
+ border: '1px solid rgba(127,127,127,.3)', background: 'transparent', color: 'inherit',
98
+ borderRadius: 8, padding: '2px 4px', fontSize: 12, fontFamily: 'inherit',
99
+ },
100
+ boardDate: {
101
+ border: '1px solid rgba(127,127,127,.3)', background: 'transparent', color: 'inherit',
102
+ borderRadius: 8, padding: '2px 4px', fontSize: 12, fontFamily: 'inherit', width: 125,
103
+ },
104
+ boardHint: { fontSize: 12, opacity: 0.62, margin: '0 0 14px', maxWidth: 760 },
105
+ boardStart: {
106
+ border: '1px solid rgba(47,158,68,.45)', background: 'rgba(47,158,68,.12)', color: 'inherit',
107
+ borderRadius: 8, padding: '2px 9px', fontSize: 12, fontFamily: 'inherit', cursor: 'pointer',
108
+ },
109
+ empty: { opacity: 0.6, padding: '24px 0' },
110
+ heatCount: { fontSize: 13.5, opacity: 0.75, margin: '0 0 16px' },
111
+ heatScroll: { width: '100%', overflowX: 'auto' },
112
+ heatGrid: { display: 'flex', gap: 12, alignItems: 'flex-start', width: 'max-content', margin: '0 auto' },
113
+ heatWeekdays: { display: 'flex', flexDirection: 'column', gap: HEAT_GAP, paddingTop: 22 },
114
+ heatWeekday: {
115
+ width: 20, height: HEAT_CELL, lineHeight: HEAT_CELL,
116
+ textAlign: 'right', fontSize: 10.5, opacity: 0.55,
117
+ },
118
+ heatBody: { display: 'flex', flexDirection: 'column', gap: 4 },
119
+ heatMonths: { display: 'flex', gap: HEAT_GAP, height: 18 },
120
+ heatMonth: {
121
+ flexGrow: 0, flexShrink: 0, flexBasis: HEAT_CELL, width: HEAT_CELL,
122
+ fontSize: 11, lineHeight: '18px', opacity: 0.55, whiteSpace: 'nowrap',
123
+ },
124
+ heatWeeks: { display: 'flex', gap: HEAT_GAP },
125
+ heatWeek: { display: 'flex', flexDirection: 'column', gap: HEAT_GAP },
126
+ heatCell: (level, future) => ({
127
+ boxSizing: 'border-box', width: HEAT_CELL, height: HEAT_CELL, padding: 0, borderRadius: 4,
128
+ border: level > 0 ? '1px solid transparent' : '1px solid rgba(127,127,127,.28)',
129
+ background: level > 0 ? HEAT_COLORS[level - 1] : 'transparent',
130
+ cursor: future ? 'default' : 'pointer',
131
+ opacity: future ? 0.35 : 1,
132
+ }),
133
+ heatLegend: {
134
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
135
+ gap: 8, marginTop: 18, fontSize: 13, opacity: 0.8, flexWrap: 'wrap',
136
+ },
137
+ heatSwatch: (level) => ({
138
+ width: 16, height: 16, borderRadius: 3, display: 'inline-block',
139
+ border: level > 0 ? '1px solid transparent' : '1px solid rgba(127,127,127,.28)',
140
+ background: level > 0 ? HEAT_COLORS[level - 1] : 'transparent',
141
+ }),
142
+ heatNotice: { marginTop: 14, fontSize: 13.5, opacity: 0.8 },
143
+ statsPage: { width: '100%', maxWidth: 1120, margin: '0 auto' },
144
+ statsPanel: {
145
+ border: '1px solid rgba(127,127,127,.18)', borderRadius: 14,
146
+ background: 'rgba(127,127,127,.035)', padding: '18px 20px 20px',
147
+ },
148
+ statsPanelHead: {
149
+ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
150
+ gap: 14, flexWrap: 'wrap', marginBottom: 14,
151
+ },
152
+ statsPanelTitle: { fontSize: 16, fontWeight: 600, margin: '0 0 3px' },
153
+ statsPanelHint: { fontSize: 12.5, opacity: 0.68, margin: 0 },
154
+ statsCoverage: {
155
+ flex: '0 0 auto', borderRadius: 999, padding: '1px 10px',
156
+ background: 'rgba(47,158,68,.12)', color: '#2f9e44',
157
+ fontSize: 12, lineHeight: '22px', whiteSpace: 'nowrap',
158
+ },
159
+ statsGrid: {
160
+ display: 'flex', flexWrap: 'wrap', alignItems: 'stretch',
161
+ gap: 18, marginTop: 18,
162
+ },
163
+ statCard: {
164
+ display: 'flex', flexDirection: 'column', flex: '1 1 340px',
165
+ minWidth: 'min(100%, 320px)', minHeight: 0,
166
+ border: '1px solid rgba(127,127,127,.22)', borderRadius: 12,
167
+ background: 'rgba(127,127,127,.02)', padding: '16px 18px 18px',
168
+ },
169
+ statCardWide: { flex: '1.6 1 560px' },
170
+ statCardHead: {
171
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
172
+ gap: 10, marginBottom: 2,
173
+ },
174
+ statTitle: { fontSize: 14.5, fontWeight: 600, margin: 0 },
175
+ statPill: {
176
+ flex: '0 0 auto', borderRadius: 999, padding: '0 8px',
177
+ background: 'rgba(127,127,127,.12)', opacity: 0.8,
178
+ fontSize: 11.5, lineHeight: '20px', whiteSpace: 'nowrap',
179
+ },
180
+ statHint: { fontSize: 12, opacity: 0.62, margin: '0 0 10px' },
181
+ statNote: { fontSize: 11.5, opacity: 0.55, marginTop: 10 },
182
+ trendChart: { width: '100%', minWidth: 0 },
183
+ trendPlot: { position: 'relative', height: 160, marginTop: 4 },
184
+ trendGrid: {
185
+ position: 'absolute', top: 0, bottom: 0, left: 24, right: 4,
186
+ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', pointerEvents: 'none',
187
+ },
188
+ trendGridLine: { borderTop: '1px solid rgba(127,127,127,.14)' },
189
+ trendBars: {
190
+ position: 'absolute', top: 0, bottom: 0, left: 24, right: 4,
191
+ display: 'flex', alignItems: 'flex-end', gap: 2,
192
+ },
193
+ trendBarWrap: { flex: '1 1 0', height: '100%', display: 'flex', alignItems: 'flex-end', minWidth: 0 },
194
+ trendBar: { width: '100%', borderRadius: '2px 2px 0 0' },
195
+ trendLine: {
196
+ position: 'absolute', top: 0, left: 24, width: 'calc(100% - 28px)',
197
+ height: '100%', overflow: 'visible', pointerEvents: 'none',
198
+ },
199
+ trendMax: { position: 'absolute', left: 0, top: -3, fontSize: 10, opacity: 0.5 },
200
+ trendZero: { position: 'absolute', left: 0, bottom: -3, fontSize: 10, opacity: 0.5 },
201
+ trendAxis: {
202
+ display: 'flex', justifyContent: 'space-between',
203
+ margin: '4px 4px 0 24px', fontSize: 10.5, opacity: 0.55,
204
+ },
205
+ statLegend: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px 14px', marginTop: 8, fontSize: 12, opacity: 0.72 },
206
+ statKey: { display: 'inline-flex', alignItems: 'center', gap: 5 },
207
+ statSwatch: (color) => ({ width: 10, height: 10, borderRadius: 2, background: color, display: 'inline-block' }),
208
+ deliveryBody: { display: 'flex', flexDirection: 'column', flex: 1 },
209
+ deliveryBar: {
210
+ display: 'flex', width: '100%', height: 26, borderRadius: 7, overflow: 'hidden',
211
+ background: 'rgba(127,127,127,.12)', margin: '6px 0 12px',
212
+ },
213
+ deliveryLegend: { display: 'flex', flexWrap: 'wrap', gap: '7px 14px', fontSize: 12.5 },
214
+ deliveryItem: { display: 'inline-flex', alignItems: 'center', gap: 6 },
215
+ deliveryDot: (color) => ({ width: 9, height: 9, borderRadius: 2, background: color, display: 'inline-block' }),
216
+ statKpis: {
217
+ display: 'flex', flexWrap: 'wrap', gap: '14px 28px',
218
+ marginTop: 'auto', paddingTop: 14, borderTop: '1px solid rgba(127,127,127,.14)',
219
+ },
220
+ statKpi: { display: 'flex', flexDirection: 'column', gap: 1 },
221
+ statKpiValue: { fontSize: 21, fontWeight: 600, lineHeight: 1.15 },
222
+ statKpiLabel: { fontSize: 11.5, opacity: 0.6 },
223
+ error: { color: '#d14343', margin: '12px 0', whiteSpace: 'pre-wrap' },
224
+ notice: { color: '#2f9e44', fontSize: 13 },
225
+ field: { display: 'flex', alignItems: 'center', gap: 10, margin: '14px 0' },
226
+ label: { width: 88, opacity: 0.75, fontSize: 13 },
227
+ input: {
228
+ border: '1px solid rgba(127,127,127,.3)', background: 'transparent', color: 'inherit',
229
+ borderRadius: 8, padding: '5px 8px', fontSize: 13, fontFamily: 'inherit',
230
+ },
231
+ hint: { opacity: 0.62, fontSize: 12, lineHeight: 1.7, marginTop: 20, maxWidth: 620 },
232
+ }
233
+
234
+ function inline(text) {
235
+ const out = []
236
+ const re = /(\*\*[^*]+\*\*|`[^`]+`)/g
237
+ let last = 0
238
+ let match
239
+ let key = 0
240
+ while ((match = re.exec(text)) !== null) {
241
+ if (match.index > last) out.push(text.slice(last, match.index))
242
+ const token = match[0]
243
+ if (token.startsWith('**')) out.push(h('strong', { key: `b${key++}` }, token.slice(2, -2)))
244
+ else out.push(h('code', { key: `c${key++}`, style: S.code }, token.slice(1, -1)))
245
+ last = match.index + token.length
246
+ }
247
+ if (last < text.length) out.push(text.slice(last))
248
+ return out.length === 0 ? text : out
249
+ }
250
+
251
+ function renderLine(line, index) {
252
+ const text = line.replace(/\s+$/, '')
253
+ const trimmed = text.trim()
254
+ if (trimmed === '') return h('div', { key: index, style: { height: 7 } })
255
+ if (/^(---|\*\*\*)$/.test(trimmed)) return h('hr', { key: index, style: S.hr })
256
+ let match
257
+ if ((match = /^(#{1,4})\s+(.*)$/.exec(trimmed))) {
258
+ const level = match[1].length
259
+ const size = [21, 17, 15.5, 14.5][level - 1]
260
+ return h('div', { key: index, style: { ...S.heading, fontSize: size, marginTop: level === 1 ? 0 : 18 } }, inline(match[2]))
261
+ }
262
+ if ((match = /^[-*]\s+(.*)$/.exec(trimmed))) {
263
+ return h('div', { key: index, style: S.bullet }, '• ', inline(match[1]))
264
+ }
265
+ if ((match = /^(\d+)[.、]\s+(.*)$/.exec(trimmed))) {
266
+ return h('div', { key: index, style: S.bullet }, `${match[1]}. `, inline(match[2]))
267
+ }
268
+ if (trimmed.startsWith('|')) return h('div', { key: index, style: S.table }, text)
269
+ if (trimmed.startsWith('>')) return h('div', { key: index, style: S.quote }, inline(trimmed.replace(/^>\s?/, '')))
270
+ return h('div', { key: index, style: S.para }, inline(trimmed))
271
+ }
272
+
273
+ const BOARD_STATUS = { '待办': 'todo', '进行中': 'doing', '已完成': 'done', '已放弃': 'drop' }
274
+
275
+ // 条目格式:日期 | 标题 | 来源:… | #h指纹 | @P1 | !2026-11-30;后两段可省略。
276
+ function parseBoardItem(text) {
277
+ const parts = String(text).split('|').map(part => part.trim()).filter(Boolean)
278
+ const priorityMatch = /(?:^|\s)@([Pp][1-3])(?=\s|$)/.exec(text)
279
+ const dueMatch = /(?:^|\s)!(\d{4}-\d{2}-\d{2})(?=\s|$)/.exec(text)
280
+ const hashMatch = /#h([0-9a-fA-F]{8})/.exec(text)
281
+ const sourcePart = parts.find(part => /^来源[::]/.test(part))
282
+ let title = parts.length >= 2 ? parts[1] : (parts[0] || '')
283
+ title = title
284
+ .replace(/(?:^|\s)@[Pp][1-3](?=\s|$)/g, ' ')
285
+ .replace(/(?:^|\s)!\d{4}-\d{2}-\d{2}(?=\s|$)/g, ' ')
286
+ .replace(/((?:完成|放弃) \d{4}-\d{2}-\d{2})\s*$/, '')
287
+ .replace(/\s+/g, ' ')
288
+ .trim()
289
+ return {
290
+ open: false,
291
+ title: title || (parts[0] || ''),
292
+ date: /^\d{4}-\d{2}-\d{2}$/.test(parts[0] || '') ? parts[0] : '',
293
+ source: sourcePart ? sourcePart.replace(/^来源[::]\s*/, '') : '',
294
+ fingerprint: hashMatch ? `#h${hashMatch[1]}` : '',
295
+ priority: priorityMatch ? priorityMatch[1].toUpperCase() : '',
296
+ due: dueMatch ? dueMatch[1] : '',
297
+ detail: '',
298
+ }
299
+ }
300
+
301
+ function parseBoard(text) {
302
+ const sections = []
303
+ let current = null
304
+ let last = null
305
+ for (const raw of String(text ?? '').split(/\r?\n/)) {
306
+ const heading = /^##\s+(.+?)\s*$/.exec(raw)
307
+ if (heading) {
308
+ current = { title: heading[1], status: BOARD_STATUS[heading[1]] || 'todo', items: [] }
309
+ sections.push(current)
310
+ last = null
311
+ continue
312
+ }
313
+ const item = /^\s*-\s*(?:\[( |x|X)\]|⛔)\s*(.*)$/.exec(raw)
314
+ if (item && current) {
315
+ const parsed = parseBoardItem(item[2])
316
+ parsed.open = item[1] === ' '
317
+ current.items.push(parsed)
318
+ last = parsed
319
+ continue
320
+ }
321
+ const detail = /^\s{2,}-\s*详情[::]\s*(.+)$/.exec(raw)
322
+ if (detail && last) last.detail = detail[1].trim()
323
+ }
324
+ return sections.filter(section => section.items.length > 0)
325
+ }
326
+
327
+ // 待办/进行中:过期单独一组,其余按 P1/P2/P3/未标注;组内先按截止日,再按日期倒序。
328
+ function boardGroups(items, today) {
329
+ const groups = [
330
+ { key: 'overdue', title: '已过期', items: [] },
331
+ { key: 'P1', title: 'P1', items: [] },
332
+ { key: 'P2', title: 'P2', items: [] },
333
+ { key: 'P3', title: 'P3', items: [] },
334
+ { key: 'none', title: '未标注', items: [] },
335
+ ]
336
+ const byKey = new Map(groups.map(group => [group.key, group]))
337
+ for (const item of items) {
338
+ const overdue = item.open && item.due !== '' && item.due < today
339
+ const key = overdue ? 'overdue' : (item.priority || 'none')
340
+ byKey.get(key).items.push(item)
341
+ }
342
+ for (const group of groups) {
343
+ group.items.sort((a, b) => {
344
+ const dueA = a.due || '9999-99-99'
345
+ const dueB = b.due || '9999-99-99'
346
+ if (dueA !== dueB) return dueA < dueB ? -1 : 1
347
+ return b.date.localeCompare(a.date)
348
+ })
349
+ }
350
+ return groups.filter(group => group.items.length > 0)
351
+ }
352
+
353
+ function parseIsoDay(text) {
354
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(text || ''))
355
+ return match ? Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])) : NaN
356
+ }
357
+
358
+ function isoFromMs(ms) {
359
+ const date = new Date(ms)
360
+ const pad = value => String(value).padStart(2, '0')
361
+ return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`
362
+ }
363
+
364
+ function shiftIsoDay(date, delta) {
365
+ return isoFromMs(parseIsoDay(date) + delta * DAY_MS)
366
+ }
367
+
368
+ function mondayOffset(date) {
369
+ return (new Date(parseIsoDay(date)).getUTCDay() + 6) % 7
370
+ }
371
+
372
+ function localIsoDay() {
373
+ const now = new Date()
374
+ const pad = value => String(value).padStart(2, '0')
375
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
376
+ }
377
+
378
+ // 最近 13 周(周一到周日),按当天热力值在样本里的四分位切成 4 档。
379
+ function buildHeat(state) {
380
+ const reports = state.reports || []
381
+ const byDate = new Map()
382
+ for (const report of reports) byDate.set(report.date, report)
383
+ const today = Number.isFinite(parseIsoDay(state.today)) ? state.today : localIsoDay()
384
+ const start = shiftIsoDay(today, -mondayOffset(today) - 12 * 7)
385
+ const scores = reports
386
+ .filter(report => report.date >= start && report.date <= today)
387
+ .map(report => Number(report.score) || 0)
388
+ .sort((a, b) => a - b)
389
+ const pick = (ratio) => {
390
+ if (scores.length === 0) return 0
391
+ return scores[Math.min(scores.length - 1, Math.floor((scores.length - 1) * ratio))]
392
+ }
393
+ const thresholds = [pick(0.25), pick(0.5), pick(0.75)]
394
+ const levelOf = (score) => {
395
+ if (!(score > 0)) return 0
396
+ let level = 1
397
+ for (const threshold of thresholds) if (score > threshold) level += 1
398
+ return level
399
+ }
400
+ const weeks = []
401
+ let previousMonth = ''
402
+ for (let week = 0; week < 13; week += 1) {
403
+ const days = []
404
+ for (let offset = 0; offset < 7; offset += 1) {
405
+ const date = shiftIsoDay(start, week * 7 + offset)
406
+ const report = byDate.get(date) || null
407
+ days.push({
408
+ date,
409
+ report,
410
+ future: date > today,
411
+ level: report ? levelOf(Number(report.score) || 0) : 0,
412
+ })
413
+ }
414
+ const month = days[0].date.slice(0, 7)
415
+ weeks.push({ days, label: month !== previousMonth ? `${Number(month.slice(5))}月` : '' })
416
+ previousMonth = month
417
+ }
418
+ const days = weeks.flatMap(week => week.days).filter(day => !day.future)
419
+ return {
420
+ today,
421
+ start,
422
+ weeks,
423
+ total: days.length,
424
+ covered: days.filter(day => day.report).length,
425
+ }
426
+ }
427
+
428
+ // 最近 N 个自然日,缺日报的日期补 0,避免趋势把空档“连”起来。
429
+ function buildTrend(state, days = 30) {
430
+ const count = Math.max(7, Math.min(91, Math.floor(Number(days) || 30)))
431
+ const reports = state.reports || []
432
+ const byDate = new Map()
433
+ for (const report of reports) byDate.set(report.date, report)
434
+ const today = Number.isFinite(parseIsoDay(state.today)) ? state.today : localIsoDay()
435
+ const start = shiftIsoDay(today, -(count - 1))
436
+ const points = []
437
+ for (let index = 0; index < count; index += 1) {
438
+ const date = shiftIsoDay(start, index)
439
+ const report = byDate.get(date) || null
440
+ points.push({
441
+ date,
442
+ outputs: report ? Number(report.outputs) || 0 : 0,
443
+ lines: report ? Number(report.lines) || 0 : 0,
444
+ hasReport: Boolean(report),
445
+ })
446
+ }
447
+ const values = points.map(point => point.outputs)
448
+ const max = Math.max(2, Math.ceil(Math.max(1, ...values) / 2) * 2)
449
+ const average = points.map((point, index) => {
450
+ const window = values.slice(Math.max(0, index - 6), index + 1)
451
+ return window.reduce((sum, value) => sum + value, 0) / window.length
452
+ })
453
+ return {
454
+ start,
455
+ today,
456
+ points,
457
+ max,
458
+ average,
459
+ total: values.reduce((sum, value) => sum + value, 0),
460
+ covered: points.filter(point => point.hasReport).length,
461
+ }
462
+ }
463
+
464
+ function boardStats(state) {
465
+ const sections = parseBoard(state && state.board ? state.board.text : '')
466
+ const counts = { todo: 0, doing: 0, done: 0, drop: 0 }
467
+ for (const section of sections) {
468
+ if (section.status in counts) counts[section.status] += section.items.length
469
+ }
470
+ const total = counts.todo + counts.doing + counts.done + counts.drop
471
+ const rate = value => (total > 0 ? Math.round((value / total) * 100) : 0)
472
+ return {
473
+ counts,
474
+ total,
475
+ open: counts.todo + counts.doing,
476
+ doneRate: rate(counts.done),
477
+ dropRate: rate(counts.drop),
478
+ closedRate: rate(counts.done + counts.drop),
479
+ }
480
+ }
481
+
482
+ function Icon(props) {
483
+ const size = (props && props.size) || 16
484
+ return h('svg', {
485
+ viewBox: '0 0 16 16', width: size, height: size, fill: 'none',
486
+ stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round',
487
+ 'aria-hidden': true, style: { display: 'block' },
488
+ },
489
+ h('rect', { x: 3, y: 2, width: 10, height: 12, rx: 1.5 }),
490
+ h('path', { d: 'M5.5 5.5h5M5.5 8h5M5.5 10.5h3' }),
491
+ )
492
+ }
493
+
494
+ function ReportsView({ state, focus, onFocusDone }) {
495
+ const reports = state.reports || []
496
+ const [selected, setSelected] = useState(reports.length > 0 ? reports[0].file : null)
497
+ useEffect(() => {
498
+ if (!reports.some(report => report.file === selected)) setSelected(reports.length > 0 ? reports[0].file : null)
499
+ }, [reports, selected])
500
+ useEffect(() => {
501
+ if (!focus) return
502
+ const target = reports.find(report => report.date === focus)
503
+ if (target) setSelected(target.file)
504
+ onFocusDone()
505
+ }, [focus, reports, onFocusDone])
506
+ const current = reports.find(report => report.file === selected)
507
+ if (reports.length === 0) return h('div', { style: S.empty }, '这个目录里还没有日报。')
508
+ return h('div', { style: S.split },
509
+ h('div', { style: S.list }, reports.map(report => h('button', {
510
+ key: report.file,
511
+ type: 'button',
512
+ onClick: () => setSelected(report.file),
513
+ style: S.item(report.file === selected),
514
+ title: `${report.file} · ${Math.round(report.size / 102.4) / 10} KB`,
515
+ }, report.date))),
516
+ h('div', { style: S.doc },
517
+ current
518
+ ? [
519
+ h('div', { key: 'meta', style: S.muted },
520
+ `${current.date} · ${Math.round(current.size / 102.4) / 10} KB · ${current.file}`),
521
+ ...current.content.split(/\r?\n/).map(renderLine),
522
+ ]
523
+ : h('div', { style: S.empty }, '选一天看。'),
524
+ ),
525
+ )
526
+ }
527
+
528
+ function PeriodsView({ state }) {
529
+ const periods = state.periods || []
530
+ const [selected, setSelected] = useState(periods.length > 0 ? periods[0].file : null)
531
+ useEffect(() => {
532
+ if (!periods.some(period => period.file === selected)) setSelected(periods.length > 0 ? periods[0].file : null)
533
+ }, [periods, selected])
534
+ const current = periods.find(period => period.file === selected)
535
+ if (periods.length === 0) return h('div', { style: S.empty }, '还没有周报或月报:生成时会写到日报目录下。')
536
+ const label = (period) => {
537
+ const badge = period.kind === 'month' ? '月' : period.kind === 'week' ? '周' : '期'
538
+ const short = period.kind === 'month' ? period.period : String(period.period).replace(/\d{4}-/g, '')
539
+ return `${badge} ${short}`
540
+ }
541
+ return h('div', { style: S.split },
542
+ h('div', { style: S.list }, periods.map(period => h('button', {
543
+ key: period.file,
544
+ type: 'button',
545
+ onClick: () => setSelected(period.file),
546
+ style: S.item(period.file === selected),
547
+ title: `${period.file} · ${Math.round(period.size / 102.4) / 10} KB`,
548
+ }, label(period)))),
549
+ h('div', { style: S.doc },
550
+ current
551
+ ? [
552
+ h('div', { key: 'meta', style: S.muted },
553
+ `${current.period} · ${Math.round(current.size / 102.4) / 10} KB · ${current.file}`),
554
+ ...current.content.split(/\r?\n/).map(renderLine),
555
+ ]
556
+ : h('div', { style: S.empty }, '选一份周期报告看。'),
557
+ ),
558
+ )
559
+ }
560
+
561
+ // 当前会话所在的工作区优先;没有会话归属时退回第一个工作区。
562
+ function activeWorkspace(ctx) {
563
+ const workspaces = ctx && typeof ctx.get === 'function' ? ctx.get('workspaces') : null
564
+ const store = workspaces && workspaces.list
565
+ const snapshot = store && typeof store.getSnapshot === 'function' ? store.getSnapshot() : null
566
+ const items = snapshot && Array.isArray(snapshot.items) ? snapshot.items : []
567
+ if (items.length === 0) return null
568
+ const ui = ctx && typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null
569
+ const selection = ui && ui.selection && typeof ui.selection.getSnapshot === 'function'
570
+ ? ui.selection.getSnapshot() : null
571
+ const sessionId = (ui && ui.mainReference && ui.mainReference.sessionId)
572
+ || (selection && selection.sessionId)
573
+ || ''
574
+ const current = sessionId
575
+ ? items.find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId))
576
+ : null
577
+ return current || items[0]
578
+ }
579
+
580
+ function boardStartPrompt(item) {
581
+ const title = String(item && item.title ? item.title : '').trim() || '未命名待办'
582
+ const lines = [`看板待办:${title}`]
583
+ if (item.date) lines.push(`登记日期:${item.date}`)
584
+ if (item.priority) lines.push(`优先级:${item.priority}`)
585
+ if (item.due) lines.push(`截止日:${item.due}`)
586
+ if (item.detail) lines.push(`详情:${item.detail}`)
587
+ if (item.source) lines.push(`来源:${item.source}`)
588
+ if (item.fingerprint) lines.push(`看板指纹:${item.fingerprint}`)
589
+ lines.push('', '请先简短说明打算怎么做,然后直接开始处理。完成后把这条待办在看板里标记为已完成。')
590
+ return lines.join('\n')
591
+ }
592
+
593
+ async function startBoardTask(ctx, item) {
594
+ const workspace = activeWorkspace(ctx)
595
+ if (!workspace) throw new Error('还没有工作区:先在左侧新建一个工作区,再点「开工」。')
596
+ const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null
597
+ if (!sessions || typeof sessions.create !== 'function' || typeof sessions.using !== 'function') {
598
+ throw new Error('当前 DSH 版本不支持从插件新建会话,请升级 DSH 后重试。')
599
+ }
600
+ const created = await sessions.create({ workspaceId: workspace.workspaceId })
601
+ const sessionId = typeof created === 'string' ? created : created && created.sessionId
602
+ if (!sessionId) throw new Error('新会话没有创建成功,请再试一次。')
603
+ await sessions.using(sessionId, { source: 'controllerOperation' }, async (reference) => {
604
+ if (reference && reference.ready && typeof reference.ready.then === 'function') await reference.ready
605
+ const session = reference && reference.binding ? reference.binding.session : null
606
+ if (!session || typeof session.prompt !== 'function') throw new Error('新会话没有准备好,请再试一次。')
607
+ const result = await session.prompt([{ type: 'text', text: boardStartPrompt(item) }], 'queue')
608
+ if (result && result.ok === false) {
609
+ throw new Error(result.error && result.error.message ? result.error.message : '会话拒绝了这条任务')
610
+ }
611
+ })
612
+ // 先确认首条任务已被接受,再切走;发送失败就留在看板显示原因。
613
+ const ui = ctx.get('uiWorkspace')
614
+ if (ui && typeof ui.openSession === 'function') ui.openSession(sessionId)
615
+ return { sessionId, workspace }
616
+ }
617
+
618
+ function BoardView({ state, onChanged }) {
619
+ const sections = parseBoard(state.board && state.board.text)
620
+ const today = /^\d{4}-\d{2}-\d{2}$/.test(String(state.today || '')) ? state.today : localIsoDay()
621
+ const [busy, setBusy] = useState(null)
622
+ const [starting, setStarting] = useState(null)
623
+ const [notice, setNotice] = useState(null)
624
+ const [error, setError] = useState(null)
625
+
626
+ const mutate = useCallback(async (item, patch) => {
627
+ const key = item.fingerprint || item.title
628
+ setBusy(key)
629
+ setNotice(null)
630
+ setError(null)
631
+ try {
632
+ const response = await fetch(BOARD_ENDPOINT, {
633
+ method: 'POST',
634
+ headers: { 'content-type': 'application/json' },
635
+ body: JSON.stringify({ keyword: key, ...patch }),
636
+ })
637
+ const payload = await response.json()
638
+ if (!response.ok) throw new Error(payload && payload.error ? payload.error : `HTTP ${response.status}`)
639
+ setNotice(String(payload.updated || '已更新').split(/\r?\n/)[0])
640
+ if (onChanged) await onChanged()
641
+ } catch (cause) {
642
+ setError(`更新看板失败:${cause && cause.message ? cause.message : String(cause)}`)
643
+ } finally {
644
+ setBusy(null)
645
+ }
646
+ }, [onChanged])
647
+
648
+ const start = async (item) => {
649
+ const key = item.fingerprint || item.title
650
+ setStarting(key)
651
+ setNotice(null)
652
+ setError(null)
653
+ try {
654
+ const result = await startBoardTask(appCtx, item)
655
+ const where = result.workspace.title || result.workspace.path || '当前工作区'
656
+ setNotice(`已在新会话开始处理:${item.title}(${where})`)
657
+ } catch (cause) {
658
+ setError(`开始处理失败:${cause && cause.message ? cause.message : String(cause)}`)
659
+ } finally {
660
+ setStarting(null)
661
+ }
662
+ }
663
+
664
+ if (sections.length === 0) return h('div', { style: S.empty }, '看板里还没有条目。')
665
+
666
+ const statusOptions = [['todo', '待办'], ['doing', '进行中'], ['done', '已完成'], ['drop', '已放弃']]
667
+ const priorityOptions = [['', '未标注'], ['P1', 'P1'], ['P2', 'P2'], ['P3', 'P3']]
668
+
669
+ const row = (item, section, index) => {
670
+ const overdue = item.open && item.due !== '' && item.due < today
671
+ const key = item.fingerprint || item.title
672
+ const disabled = busy === key || starting === key
673
+ const editable = section.status === 'todo' || section.status === 'doing'
674
+ const meta = [item.date, item.source ? `来源 ${item.source}` : '', item.fingerprint].filter(Boolean).join(' · ')
675
+ return h('div', { key: `${section.title}-${index}-${key}`, style: S.row },
676
+ h('span', { style: S.dot(item.open) }),
677
+ h('div', { style: S.boardItem },
678
+ h('div', { style: item.open ? undefined : { opacity: 0.65 } },
679
+ item.title,
680
+ item.priority ? h('span', { style: S.boardBadge(item.priority) }, item.priority) : null,
681
+ item.due
682
+ ? h('span', { style: S.boardBadge(overdue ? 'overdue' : 'due') },
683
+ overdue ? `已过期 · ${item.due}` : `截止 ${item.due}`)
684
+ : null,
685
+ ),
686
+ meta ? h('div', { style: S.muted }, meta) : null,
687
+ item.detail ? h('div', { style: S.muted }, `详情:${item.detail}`) : null,
688
+ ),
689
+ h('div', { style: S.boardControls },
690
+ editable
691
+ ? h('button', {
692
+ type: 'button',
693
+ style: S.boardStart,
694
+ disabled,
695
+ title: '把这条待办带进新会话,立即开始处理',
696
+ 'aria-label': `开工:${item.title}`,
697
+ onClick: () => start(item),
698
+ }, starting === key ? '建会话…' : '开工')
699
+ : null,
700
+ editable
701
+ ? h('select', {
702
+ value: item.priority,
703
+ disabled,
704
+ style: S.boardSelect,
705
+ title: '优先级',
706
+ onChange: event => mutate(item, { priority: event.target.value || 'none' }),
707
+ }, priorityOptions.map(([value, label]) => h('option', { key: value, value }, label)))
708
+ : null,
709
+ editable
710
+ ? h('input', {
711
+ type: 'date',
712
+ value: item.due,
713
+ disabled,
714
+ style: S.boardDate,
715
+ title: '截止日',
716
+ onChange: event => mutate(item, { due: event.target.value || 'none' }),
717
+ })
718
+ : null,
719
+ h('select', {
720
+ value: section.status,
721
+ disabled,
722
+ style: S.boardSelect,
723
+ title: '状态',
724
+ onChange: event => mutate(item, { status: event.target.value }),
725
+ }, statusOptions.map(([value, label]) => h('option', { key: value, value }, label))),
726
+ ),
727
+ )
728
+ }
729
+
730
+ return h('div', null,
731
+ h('div', { style: S.boardHint },
732
+ '待办 / 进行中按「已过期 → P1 → P2 → P3 → 未标注」分组;优先级、截止日或状态一改就写回看板。点「开工」会在当前工作区新建会话,并把标题、详情和来源作为首条任务发出去。'),
733
+ error ? h('div', { style: S.error }, error) : null,
734
+ notice ? h('div', { style: S.notice, role: 'status' }, notice) : null,
735
+ sections.map(section => {
736
+ const editable = section.status === 'todo' || section.status === 'doing'
737
+ const groups = editable ? boardGroups(section.items, today) : [{ key: 'all', title: '', items: section.items }]
738
+ return h('div', { key: section.title, style: S.section },
739
+ h('h3', { style: S.boardHead }, `${section.title}(${section.items.length})`),
740
+ groups.map(group => h('div', { key: group.key, style: S.boardGroup },
741
+ group.title
742
+ ? h('div', { style: S.boardGroupHead }, `${group.title}(${group.items.length})`)
743
+ : null,
744
+ group.items.map((item, index) => row(item, section, index)),
745
+ )),
746
+ )
747
+ }),
748
+ )
749
+ }
750
+
751
+ function TrendChart({ trend }) {
752
+ const count = trend.points.length
753
+ const labelIndexes = [0, Math.floor((count - 1) / 2), count - 1]
754
+ const linePoints = trend.average
755
+ .map((value, index) => `${((index + 0.5) / count) * 100},${100 - (value / trend.max) * 100}`)
756
+ .join(' ')
757
+
758
+ return h('div', {
759
+ style: S.trendChart,
760
+ role: 'img',
761
+ 'aria-label': `最近 ${count} 天产出趋势,共 ${trend.total} 条产出,有日报 ${trend.covered} 天`,
762
+ },
763
+ h('div', { style: S.trendPlot },
764
+ h('div', { style: S.trendGrid },
765
+ [0, 1, 2].map(index => h('div', { key: index, style: S.trendGridLine })),
766
+ ),
767
+ h('div', { style: S.trendBars },
768
+ trend.points.map((point, index) => h('div', {
769
+ key: point.date,
770
+ style: S.trendBarWrap,
771
+ title: point.hasReport
772
+ ? `${point.date} · ${point.outputs} 条产出 · ${point.lines} 行`
773
+ : `${point.date} · 无日报`,
774
+ }, h('div', {
775
+ style: {
776
+ ...S.trendBar,
777
+ height: `${(point.outputs / trend.max) * 100}%`,
778
+ background: index === count - 1 ? 'rgba(25,113,194,.9)' : 'rgba(25,113,194,.55)',
779
+ },
780
+ }))),
781
+ ),
782
+ h('svg', {
783
+ viewBox: '0 0 100 100',
784
+ preserveAspectRatio: 'none',
785
+ 'aria-hidden': true,
786
+ style: S.trendLine,
787
+ }, h('polyline', {
788
+ points: linePoints,
789
+ fill: 'none',
790
+ stroke: '#e8590c',
791
+ strokeWidth: 2,
792
+ vectorEffect: 'non-scaling-stroke',
793
+ strokeLinejoin: 'round',
794
+ strokeLinecap: 'round',
795
+ })),
796
+ h('span', { style: S.trendMax }, String(trend.max)),
797
+ h('span', { style: S.trendZero }, '0'),
798
+ ),
799
+ h('div', { style: S.trendAxis },
800
+ labelIndexes.map((index, order) => h('span', {
801
+ key: `x-${index}`,
802
+ style: { textAlign: order === 0 ? 'left' : order === 2 ? 'right' : 'center' },
803
+ }, trend.points[index].date.slice(5))),
804
+ ),
805
+ )
806
+ }
807
+
808
+ function DeliveryBar({ delivery }) {
809
+ if (delivery.total === 0) return null
810
+ const rows = [
811
+ { key: 'done', label: '已完成', color: DELIVERY_COLORS.done },
812
+ { key: 'doing', label: '进行中', color: DELIVERY_COLORS.doing },
813
+ { key: 'todo', label: '待办', color: DELIVERY_COLORS.todo },
814
+ { key: 'drop', label: '已放弃', color: DELIVERY_COLORS.drop },
815
+ ]
816
+ const label = `看板共 ${delivery.total} 条:完成 ${delivery.counts.done}、进行中 ${delivery.counts.doing}、待办 ${delivery.counts.todo}、已放弃 ${delivery.counts.drop}`
817
+ return h('div', { style: S.deliveryBody },
818
+ h('div', { style: S.deliveryBar, role: 'img', 'aria-label': label },
819
+ rows.filter(row => delivery.counts[row.key] > 0).map(row => h('div', {
820
+ key: row.key,
821
+ title: `${row.label} ${delivery.counts[row.key]} 条`,
822
+ style: {
823
+ width: `${(delivery.counts[row.key] / delivery.total) * 100}%`,
824
+ height: '100%',
825
+ background: row.color,
826
+ },
827
+ })),
828
+ ),
829
+ h('div', { style: S.deliveryLegend },
830
+ rows.map(row => h('span', { key: row.key, style: S.deliveryItem },
831
+ h('span', { style: S.deliveryDot(row.color) }),
832
+ `${row.label} ${delivery.counts[row.key]}`,
833
+ )),
834
+ ),
835
+ h('div', { style: S.statNote }, '完成率按全部条目算;放弃也计入已关闭。'),
836
+ h('div', { style: S.statKpis },
837
+ h('div', { style: S.statKpi },
838
+ h('span', { style: S.statKpiValue }, `${delivery.doneRate}%`),
839
+ h('span', { style: S.statKpiLabel }, '完成率'),
840
+ ),
841
+ h('div', { style: S.statKpi },
842
+ h('span', { style: S.statKpiValue }, `${delivery.dropRate}%`),
843
+ h('span', { style: S.statKpiLabel }, '放弃率'),
844
+ ),
845
+ h('div', { style: S.statKpi },
846
+ h('span', { style: S.statKpiValue }, String(delivery.open)),
847
+ h('span', { style: S.statKpiLabel }, '未关闭'),
848
+ ),
849
+ ),
850
+ )
851
+ }
852
+
853
+ function StatsView({ state, onOpen }) {
854
+ const heat = buildHeat(state)
855
+ const trend = buildTrend(state, 30)
856
+ const delivery = boardStats(state)
857
+ const [notice, setNotice] = useState(null)
858
+ if ((state.reports || []).length === 0) {
859
+ return h('div', { style: S.empty }, '还没有日报:写完第一份后,这里会按天亮起来。')
860
+ }
861
+
862
+ const tooltip = (day) => {
863
+ if (day.future) return `${day.date} · 还没到`
864
+ if (!day.report) return `${day.date} · 无日报`
865
+ return `${day.date} · ${day.report.lines} 行 · ${day.report.outputs} 条产出 · 强度 ${day.report.score}`
866
+ }
867
+
868
+ const clickCell = (day) => {
869
+ if (day.future) return
870
+ if (!day.report) {
871
+ setNotice(`该日无日报(${day.date})`)
872
+ return
873
+ }
874
+ setNotice(null)
875
+ onOpen(day.date)
876
+ }
877
+
878
+ return h('div', { style: S.statsPage },
879
+ h('section', { style: S.statsPanel },
880
+ h('div', { style: S.statsPanelHead },
881
+ h('div', null,
882
+ h('h3', { style: S.statsPanelTitle }, '贡献热力图'),
883
+ h('div', { style: S.statsPanelHint },
884
+ `最近 13 周(${heat.start} ~ ${heat.today})。点亮的格子点一下就到当天日报。`),
885
+ ),
886
+ h('span', { style: S.statsCoverage }, `${heat.covered} / ${heat.total} 天有日报`),
887
+ ),
888
+ h('div', { style: S.heatScroll },
889
+ h('div', { style: S.heatGrid },
890
+ h('div', { style: S.heatWeekdays },
891
+ ['一', '', '三', '', '五', '', ''].map((label, index) => (
892
+ h('div', { key: index, style: S.heatWeekday }, label)
893
+ )),
894
+ ),
895
+ h('div', { style: S.heatBody },
896
+ h('div', { style: S.heatMonths },
897
+ heat.weeks.map((week, index) => h('div', { key: index, style: S.heatMonth }, week.label)),
898
+ ),
899
+ h('div', { style: S.heatWeeks },
900
+ heat.weeks.map((week, index) => h('div', { key: index, style: S.heatWeek },
901
+ week.days.map(day => h('button', {
902
+ key: day.date,
903
+ type: 'button',
904
+ title: tooltip(day),
905
+ 'aria-label': tooltip(day),
906
+ disabled: day.future,
907
+ onClick: () => clickCell(day),
908
+ style: S.heatCell(day.level, day.future),
909
+ })),
910
+ )),
911
+ ),
912
+ ),
913
+ ),
914
+ ),
915
+ h('div', { style: S.heatLegend },
916
+ h('span', null, '图例:'),
917
+ h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
918
+ h('span', { style: S.heatSwatch(0) }), '无日报'),
919
+ h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 3 } },
920
+ [1, 2, 3, 4].map(level => h('span', { key: level, style: S.heatSwatch(level) }))),
921
+ h('span', null, '少 → 多(按当天行数 + 产出条数 × 3 分档)'),
922
+ ),
923
+ notice ? h('div', { style: S.heatNotice, role: 'status' }, notice) : null,
924
+ ),
925
+ h('div', { style: S.statsGrid },
926
+ h('section', { style: { ...S.statCard, ...S.statCardWide } },
927
+ h('div', { style: S.statCardHead },
928
+ h('h3', { style: S.statTitle }, '产出趋势'),
929
+ h('span', { style: S.statPill }, `30 天 · ${trend.total} 条`),
930
+ ),
931
+ h('div', { style: S.statHint },
932
+ `${trend.start} ~ ${trend.today} · 有日报 ${trend.covered} / 30 天`),
933
+ h(TrendChart, { trend }),
934
+ h('div', { style: S.statLegend },
935
+ h('span', { style: S.statKey },
936
+ h('span', { style: S.statSwatch('rgba(25,113,194,.55)') }), '柱:当日产出'),
937
+ h('span', { style: S.statKey },
938
+ h('span', { style: S.statSwatch('#e8590c') }), '线:7 日均值'),
939
+ ),
940
+ ),
941
+ h('section', { style: S.statCard },
942
+ h('div', { style: S.statCardHead },
943
+ h('h3', { style: S.statTitle }, '看板交付结构'),
944
+ h('span', { style: S.statPill }, `共 ${delivery.total} 条`),
945
+ ),
946
+ h('div', { style: S.statHint },
947
+ delivery.total > 0
948
+ ? `已关闭 ${delivery.counts.done + delivery.counts.drop} 条 · 未关闭 ${delivery.open} 条`
949
+ : '看板里还没有条目。'),
950
+ h(DeliveryBar, { delivery }),
951
+ ),
952
+ ),
953
+ )
954
+ }
955
+
956
+ function SettingsView() {
957
+ const [info, setInfo] = useState(null)
958
+ const [time, setTime] = useState('23:00')
959
+ const [weekTime, setWeekTime] = useState('01:00')
960
+ const [monthTime, setMonthTime] = useState('01:00')
961
+ const [weekActive, setWeekActive] = useState(true)
962
+ const [monthActive, setMonthActive] = useState(true)
963
+ const [reportDir, setReportDir] = useState('')
964
+ const [workspace, setWorkspace] = useState('')
965
+ const [logDir, setLogDir] = useState('')
966
+ const [busy, setBusy] = useState(false)
967
+ const [notice, setNotice] = useState(null)
968
+ const [error, setError] = useState(null)
969
+
970
+ const applyPayload = useCallback((payload) => {
971
+ if (payload.time) setTime(payload.time)
972
+ if (typeof payload.reportDir === 'string') setReportDir(payload.reportDir)
973
+ if (typeof payload.workspace === 'string') setWorkspace(payload.workspace)
974
+ if (typeof payload.logDir === 'string') setLogDir(payload.logDir)
975
+ if (payload.week) {
976
+ if (payload.week.time) setWeekTime(payload.week.time)
977
+ if (typeof payload.week.active === 'boolean') setWeekActive(payload.week.active)
978
+ }
979
+ if (payload.month) {
980
+ if (payload.month.time) setMonthTime(payload.month.time)
981
+ if (typeof payload.month.active === 'boolean') setMonthActive(payload.month.active)
982
+ }
983
+ }, [])
984
+
985
+ const load = useCallback(async () => {
986
+ try {
987
+ const response = await fetch(SCHEDULE_ENDPOINT, { cache: 'no-store' })
988
+ const payload = await response.json()
989
+ if (!response.ok) throw new Error(payload && payload.error ? payload.error : `HTTP ${response.status}`)
990
+ setInfo(payload)
991
+ applyPayload(payload)
992
+ setError(null)
993
+ } catch (cause) {
994
+ setError(`读取定时设置失败:${cause && cause.message ? cause.message : String(cause)}`)
995
+ }
996
+ }, [applyPayload])
997
+
998
+ useEffect(() => { load() }, [load])
999
+
1000
+ const save = useCallback(async (patch) => {
1001
+ setBusy(true)
1002
+ setNotice(null)
1003
+ setError(null)
1004
+ try {
1005
+ const response = await fetch(SCHEDULE_ENDPOINT, {
1006
+ method: 'POST',
1007
+ headers: { 'content-type': 'application/json' },
1008
+ body: JSON.stringify(patch),
1009
+ })
1010
+ const payload = await response.json()
1011
+ if (!response.ok) throw new Error(payload && payload.error ? payload.error : `HTTP ${response.status}`)
1012
+ setInfo(payload)
1013
+ applyPayload(payload)
1014
+ setNotice('已保存')
1015
+ } catch (cause) {
1016
+ setError(`保存失败:${cause && cause.message ? cause.message : String(cause)}`)
1017
+ } finally {
1018
+ setBusy(false)
1019
+ }
1020
+ }, [applyPayload])
1021
+
1022
+ if (!info) return error ? h('div', { style: S.error }, error) : h('div', { style: S.empty }, '加载中…')
1023
+
1024
+ const scheduleBlock = info.found
1025
+ ? h('div', null,
1026
+ h('h3', { style: S.boardHead }, '日报定时'),
1027
+ h('div', { style: S.field },
1028
+ h('span', { style: S.label }, '每天'),
1029
+ h('input', {
1030
+ type: 'time',
1031
+ value: time,
1032
+ style: S.input,
1033
+ onChange: event => setTime(event.target.value),
1034
+ }),
1035
+ h('span', { style: S.muted }, info.timeZone),
1036
+ ),
1037
+ h('div', { style: S.field },
1038
+ h('span', { style: S.label }, '启用'),
1039
+ h('input', {
1040
+ type: 'checkbox',
1041
+ checked: Boolean(info.active),
1042
+ onChange: event => save({ active: event.target.checked }),
1043
+ }),
1044
+ h('span', { style: S.muted }, info.active ? '到点投递到会话' : '已暂停,任务仍保留'),
1045
+ ),
1046
+ h('div', { style: S.field },
1047
+ h('button', { type: 'button', style: S.ghost, disabled: busy, onClick: () => save({ time }) },
1048
+ busy ? '保存中…' : '保存时间'),
1049
+ notice ? h('span', { style: S.notice }, notice) : null,
1050
+ ),
1051
+ )
1052
+ : h('div', { style: S.empty }, '还没找到日报计划任务:重启一次 DSH,插件会把它建出来。')
1053
+
1054
+ const periodBlock = (label, ruleText, sub, timeValue, setTimeValue, timeField, activeField, activeValue, setActiveValue) => {
1055
+ if (!sub || !sub.found) {
1056
+ return h('div', { key: label },
1057
+ h('h3', { style: S.boardHead }, `${label}定时`),
1058
+ h('div', { style: S.empty }, `还没找到${label}计划任务:重启一次 DSH,开关打开时会按设置建出来。`),
1059
+ )
1060
+ }
1061
+ return h('div', { key: label },
1062
+ h('h3', { style: S.boardHead }, `${label}定时`),
1063
+ h('div', { style: S.field },
1064
+ h('span', { style: S.label }, '规则'),
1065
+ h('span', { style: S.muted }, ruleText),
1066
+ ),
1067
+ h('div', { style: S.field },
1068
+ h('span', { style: S.label }, '时间'),
1069
+ h('input', {
1070
+ type: 'time',
1071
+ value: timeValue,
1072
+ style: S.input,
1073
+ onChange: event => setTimeValue(event.target.value),
1074
+ }),
1075
+ h('button', { type: 'button', style: S.ghost, disabled: busy, onClick: () => save({ [timeField]: timeValue }) },
1076
+ busy ? '保存中…' : '保存时间'),
1077
+ h('span', { style: S.muted }, sub.timeZone),
1078
+ ),
1079
+ h('div', { style: S.field },
1080
+ h('span', { style: S.label }, '启用'),
1081
+ h('input', {
1082
+ type: 'checkbox',
1083
+ checked: Boolean(activeValue),
1084
+ onChange: (event) => {
1085
+ setActiveValue(event.target.checked)
1086
+ save({ [activeField]: event.target.checked })
1087
+ },
1088
+ }),
1089
+ h('span', { style: S.muted }, activeValue ? '到点生成并投递' : '已暂停,任务仍保留'),
1090
+ ),
1091
+ sub.nextRunAt ? h('div', { style: S.hint }, `下次触发:${sub.nextRunAt}`) : null,
1092
+ )
1093
+ }
1094
+
1095
+ return h('div', { style: { maxWidth: 640 } },
1096
+ h('h3', { style: S.boardHead }, '日报文件目录'),
1097
+ h('div', { style: S.field },
1098
+ h('span', { style: S.label }, '目录'),
1099
+ h('input', {
1100
+ type: 'text',
1101
+ value: reportDir,
1102
+ placeholder: info.reportDirDefault,
1103
+ style: { ...S.input, width: 360 },
1104
+ onChange: event => setReportDir(event.target.value),
1105
+ }),
1106
+ h('button', { type: 'button', style: S.ghost, disabled: busy, onClick: () => save({ reportDir }) },
1107
+ busy ? '保存中…' : '保存目录'),
1108
+ ),
1109
+ h('div', { style: { ...S.hint, marginTop: 4 } },
1110
+ `默认 ${info.reportDirDefault};日报、看板、_源数据 都写在这里。改目录不会搬动已有文件。`,
1111
+ ),
1112
+ h('h3', { style: S.boardHead }, '工作空间'),
1113
+ h('div', { style: S.field },
1114
+ h('span', { style: S.label }, '目录'),
1115
+ h('input', {
1116
+ type: 'text',
1117
+ value: workspace,
1118
+ placeholder: info.workspaceDefault,
1119
+ style: { ...S.input, width: 360 },
1120
+ onChange: event => setWorkspace(event.target.value),
1121
+ }),
1122
+ h('button', { type: 'button', style: S.ghost, disabled: busy, onClick: () => save({ workspace }) },
1123
+ busy ? '保存中…' : '保存目录'),
1124
+ ),
1125
+ h('div', { style: { ...S.hint, marginTop: 4 } },
1126
+ '日报从这里扫当天改了哪些文件、有哪些 git 仓库;默认和插件数据目录同一个(装好就有),填你平时干活的目录更贴合实际。',
1127
+ ),
1128
+ scheduleBlock,
1129
+ periodBlock('周报', '每周一生成上一周(周一至周日)', info.week,
1130
+ weekTime, setWeekTime, 'weekTime', 'weekActive', weekActive, setWeekActive),
1131
+ periodBlock('月报', '每月 1 号生成上一个自然月', info.month,
1132
+ monthTime, setMonthTime, 'monthTime', 'monthActive', monthActive, setMonthActive),
1133
+ h('h3', { style: S.boardHead }, '日志'),
1134
+ h('div', { style: S.field },
1135
+ h('span', { style: S.label }, '目录'),
1136
+ h('input', {
1137
+ type: 'text',
1138
+ value: logDir,
1139
+ placeholder: info.logDirDefault,
1140
+ style: { ...S.input, width: 360 },
1141
+ onChange: event => setLogDir(event.target.value),
1142
+ }),
1143
+ h('button', { type: 'button', style: S.ghost, disabled: busy, onClick: () => save({ logDir }) },
1144
+ busy ? '保存中…' : '保存目录'),
1145
+ ),
1146
+ h('div', { style: { ...S.hint, marginTop: 4 } },
1147
+ `留空表示用数据目录下的 _日志(${info.logDirDefault})。`,
1148
+ h('br'),
1149
+ `文件名 ${info.logPattern},每次调脚本记一行:参数、退出码、耗时;失败带 stderr 尾部。`,
1150
+ ),
1151
+ error ? h('div', { style: S.error }, error) : null,
1152
+ info.found
1153
+ ? h('div', { style: S.hint },
1154
+ `任务:${info.title}(${info.id})`,
1155
+ h('br'),
1156
+ info.nextRunAt ? `下次触发:${info.nextRunAt}` : '当前没有下次触发时间',
1157
+ h('br'),
1158
+ '日报时间改的是任务本身,重启后不会被 scheduleTime 默认值盖回去;周报 / 月报的时间会同时记住。暂停只停投递,不删任务。',
1159
+ )
1160
+ : null,
1161
+ )
1162
+ }
1163
+
1164
+ function Panel() {
1165
+ const [state, setState] = useState(null)
1166
+ const [error, setError] = useState(null)
1167
+ const [tab, setTab] = useState('board')
1168
+ const [focusDate, setFocusDate] = useState(null)
1169
+ const [busy, setBusy] = useState(false)
1170
+ const clearFocus = useCallback(() => setFocusDate(null), [])
1171
+
1172
+ const load = useCallback(async () => {
1173
+ setBusy(true)
1174
+ try {
1175
+ const response = await fetch(ENDPOINT, { cache: 'no-store' })
1176
+ const payload = await response.json()
1177
+ if (!response.ok) throw new Error(payload && payload.error ? payload.error : `HTTP ${response.status}`)
1178
+ setState(payload)
1179
+ setError(null)
1180
+ } catch (cause) {
1181
+ setError(`读取日报数据失败:${cause && cause.message ? cause.message : String(cause)}`)
1182
+ } finally {
1183
+ setBusy(false)
1184
+ }
1185
+ }, [])
1186
+
1187
+ useEffect(() => { load() }, [load])
1188
+
1189
+ const open = state && state.board ? state.board.open : 0
1190
+ return h('div', { style: S.page },
1191
+ h('div', { style: S.bar },
1192
+ h('h1', { style: S.title }, '工作日报'),
1193
+ state ? h('span', { style: S.muted }, `${state.reportDir} · 待办 ${open} 条`) : null,
1194
+ h('div', { style: S.tabs },
1195
+ h('button', { type: 'button', style: S.tab(tab === 'board'), onClick: () => setTab('board') }, '看板'),
1196
+ h('button', { type: 'button', style: S.tab(tab === 'reports'), onClick: () => { setFocusDate(null); setTab('reports') } }, '日报'),
1197
+ h('button', { type: 'button', style: S.tab(tab === 'periods'), onClick: () => setTab('periods') }, '周期'),
1198
+ h('button', { type: 'button', style: S.tab(tab === 'stats'), onClick: () => setTab('stats') }, '统计'),
1199
+ h('button', { type: 'button', style: S.tab(tab === 'settings'), onClick: () => setTab('settings') }, '设置'),
1200
+ h('button', { type: 'button', style: S.ghost, onClick: load, disabled: busy }, busy ? '刷新中…' : '刷新'),
1201
+ ),
1202
+ ),
1203
+ error ? h('div', { style: S.error }, error) : null,
1204
+ tab === 'settings' ? h(SettingsView)
1205
+ : !state ? (error ? null : h('div', { style: S.empty }, '加载中…'))
1206
+ : tab === 'reports' ? h(ReportsView, { state, focus: focusDate, onFocusDone: clearFocus })
1207
+ : tab === 'periods' ? h(PeriodsView, { state })
1208
+ : tab === 'stats' ? h(StatsView, {
1209
+ state,
1210
+ onOpen: (date) => { setFocusDate(date); setTab('reports') },
1211
+ }) : h(BoardView, { state, onChanged: load }),
1212
+ )
1213
+ }
1214
+
1215
+ return {
1216
+ inject: ['slots'],
1217
+ __test: { activeWorkspace, boardStartPrompt, startBoardTask, buildTrend, boardStats, StatsView },
1218
+ apply(ctx) {
1219
+ appCtx = ctx
1220
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1221
+ name: 'sidebar.panellist',
1222
+ id: PANEL_ID,
1223
+ order: 10,
1224
+ label: '日报',
1225
+ }, Icon))
1226
+ ctx.slots.inject('main', () => ctx.slots.register({
1227
+ name: 'main',
1228
+ key: PANEL_ID,
1229
+ }, Panel))
1230
+ },
1231
+ }
1232
+ },
1233
+ })