dsh-learn-space 0.0.0-stage → 1.0.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,1305 @@
1
+ /**
2
+ * 学习空间 Client 半边:sidebar 面板图标 + main 面板页。
3
+ * 数据来自 Host 的 /api/learning-space/overview。
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-learn-space',
7
+ factory(require) {
8
+ const React = require('react')
9
+ const { useEffect, useState, useCallback, useRef } = React
10
+ const h = React.createElement
11
+
12
+ const STATUS_COLOR = {
13
+ done: '#3E6B4F',
14
+ doing: '#3D5A80',
15
+ warn: '#B5432E',
16
+ todo: '#9A968C',
17
+ }
18
+ const STATUS_LABEL = { done: '已确认', doing: '进行中', warn: '待修复', todo: '未学' }
19
+
20
+ function PanelIcon() {
21
+ return h('svg', { viewBox: '0 0 24 24', width: 22, height: 22, 'aria-hidden': true },
22
+ h('path', {
23
+ d: 'M4 4.5A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v16.5a1 1 0 0 1-1 1H6.5A2.5 2.5 0 0 0 4 22z',
24
+ fill: 'none', stroke: 'currentColor', 'stroke-width': '1.6',
25
+ }),
26
+ h('path', {
27
+ d: 'M8 7h8M8 11h8M8 15h5',
28
+ fill: 'none', stroke: 'currentColor', 'stroke-width': '1.6', 'stroke-linecap': 'round',
29
+ }))
30
+ }
31
+
32
+ const css = `
33
+ .ls-panel { padding: 20px 24px; overflow-y: auto; height: 100%;
34
+ color: var(--dsw-alias-label-primary); font-size: 14px; line-height: 1.7; }
35
+ .ls-title { font-size: 20px; font-weight: 700; letter-spacing: 1px; margin: 0 0 2px; }
36
+ .ls-sub { color: var(--dsw-alias-label-secondary); font-size: 13px; margin-bottom: 20px; }
37
+ .ls-section { margin-bottom: 24px; }
38
+ .ls-h { font-size: 13px; letter-spacing: 2px; color: var(--dsw-alias-label-secondary);
39
+ border-bottom: 1px solid var(--dsw-alias-border-l1); padding-bottom: 6px; margin-bottom: 10px; }
40
+ .ls-card { background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
41
+ border-radius: 8px; padding: 14px 16px; margin-bottom: 12px; cursor: pointer; }
42
+ .ls-card:hover { border-color: var(--dsw-alias-border-l2); }
43
+ .ls-card.open { border-color: var(--dsw-alias-brand-primary); }
44
+ .ls-card-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
45
+ .ls-name { font-size: 15px; font-weight: 600; }
46
+ .ls-frac { font-size: 13px; color: var(--dsw-alias-label-secondary); flex: none; }
47
+ .ls-goal { font-size: 13px; color: var(--dsw-alias-label-secondary); margin-top: 2px; }
48
+ .ls-bar { height: 4px; border-radius: 2px; background: var(--dsw-alias-border-l1); margin-top: 10px; overflow: hidden; }
49
+ .ls-bar-fill { height: 100%; background: var(--dsw-alias-state-success-primary); }
50
+ .ls-badges { display: flex; gap: 12px; margin-top: 8px; font-size: 12px;
51
+ color: var(--dsw-alias-label-secondary); }
52
+ .ls-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 5px; }
53
+ .ls-nodes { list-style: none; margin: 10px 0 0; padding: 0; }
54
+ .ls-node { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 13px; }
55
+ .ls-journal-item { padding: 3px 0; font-size: 13px; color: var(--dsw-alias-label-secondary); }
56
+ .ls-btn { font-family: inherit; font-size: 12px; padding: 3px 12px; cursor: pointer;
57
+ background: var(--dsw-alias-brand-primary); color: #fff; border: none; border-radius: 4px; flex: none; }
58
+ .ls-btn:disabled { opacity: .5; cursor: default; }
59
+ .ls-new { display: flex; gap: 8px; margin-bottom: 14px; flex-wrap: wrap; }
60
+ .ls-input { flex: 1; min-width: 120px; font-family: inherit; font-size: 13px; color: var(--dsw-alias-label-primary);
61
+ background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
62
+ border-radius: 4px; padding: 6px 10px; }
63
+ .ls-input:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }
64
+ .ls-empty { color: var(--dsw-alias-label-secondary); font-size: 13px; padding: 8px 0; }
65
+ .ls-dag-wrap { margin-top: 12px; overflow-x: auto; }
66
+ .ls-dag text { font-size: 11px; fill: var(--dsw-alias-label-primary); }
67
+ .ls-mermaid-wrap { margin-top: 12px; overflow-x: auto; }
68
+ .ls-mermaid-wrap svg { max-width: none; }
69
+ .ls-mermaid-err { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E);
70
+ padding: 4px 0; }
71
+ .ls-mermaid-src { margin: 6px 0; padding: 8px 10px; background: var(--dsw-alias-bg-layer-1);
72
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; overflow-x: auto; }
73
+ .ls-mermaid-src code { font-family: Consolas, monospace; font-size: 12px; white-space: pre; }
74
+ .ls-side-head { display: flex; align-items: baseline; justify-content: space-between; }
75
+ .ls-loading { color: var(--dsw-alias-label-secondary); padding: 32px 0; text-align: center; }
76
+ .ls-chat { margin-top: 12px; border-top: 1px solid var(--dsw-alias-border-l1); padding-top: 10px; }
77
+ .ls-chat-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
78
+ .ls-chat-title { font-size: 12px; color: var(--dsw-alias-label-secondary); }
79
+ .ls-chat-list { max-height: 320px; overflow-y: auto; padding: 4px 2px; display: flex; flex-direction: column; gap: 8px; }
80
+ .ls-msg { max-width: 88%; border-radius: 8px; padding: 6px 10px; font-size: 13px; }
81
+ .ls-msg-user { align-self: flex-end; background: var(--dsw-alias-brand-primary); color: #fff; }
82
+ .ls-msg-assistant { align-self: flex-start; background: var(--dsw-alias-bg-layer-2); }
83
+ .ls-msg-user .ls-md-code { background: rgba(255,255,255,.25); }
84
+ .ls-md-p { margin: 2px 0; white-space: pre-wrap; word-break: break-word; }
85
+ .ls-md-h { font-size: 13px; font-weight: 700; margin: 6px 0 2px; }
86
+ .ls-md-ul { margin: 2px 0; padding-left: 18px; }
87
+ .ls-md-code { font-family: inherit; background: var(--dsw-alias-bg-layer-1); border-radius: 3px; padding: 0 4px; }
88
+ .ls-md-pre { margin: 4px 0; padding: 8px 10px; background: var(--dsw-alias-bg-layer-1);
89
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; overflow-x: auto; }
90
+ .ls-md-pre code { font-family: Consolas, monospace; font-size: 12px; white-space: pre; }
91
+ .ls-tool { align-self: flex-start; font-size: 12px; color: var(--dsw-alias-label-secondary); }
92
+ .ls-thinking { align-self: flex-start; font-size: 12px; color: var(--dsw-alias-label-secondary); padding: 2px 4px; }
93
+ .ls-chat-err { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E); padding: 4px 0; }
94
+ .ls-chat-row { display: flex; gap: 8px; margin-top: 8px; align-items: flex-end; }
95
+ .ls-chat-input { flex: 1; resize: vertical; min-height: 34px; max-height: 120px; }
96
+ .ls-chat-more { font-size: 12px; color: var(--dsw-alias-label-secondary); align-self: center; }
97
+ .ls-ask { align-self: stretch; border: 1px solid var(--dsw-alias-brand-primary); border-radius: 8px;
98
+ padding: 10px 12px; background: var(--dsw-alias-bg-layer-2); }
99
+ .ls-ask-badge { font-size: 12px; font-weight: 700; color: var(--dsw-alias-brand-primary); margin-bottom: 6px; }
100
+ .ls-ask-q { margin-bottom: 8px; }
101
+ .ls-ask-h { font-size: 12px; color: var(--dsw-alias-label-secondary); letter-spacing: 1px; }
102
+ .ls-ask-text { font-size: 13px; font-weight: 600; margin: 2px 0 4px; }
103
+ .ls-ask-opts { display: flex; flex-direction: column; gap: 3px; }
104
+ .ls-ask-opt { font-size: 12px; padding: 3px 8px; border: 1px dashed var(--dsw-alias-border-l2); border-radius: 5px; }
105
+ .ls-ask-opt-label { font-weight: 600; margin-right: 6px; }
106
+ .ls-ask-opt-desc { color: var(--dsw-alias-label-secondary); }
107
+ .ls-ask-go { margin-top: 4px; }
108
+ .ls-layout { display: grid; grid-template-columns: 260px 1fr; gap: 16px; min-height: 0; align-items: start; }
109
+ .ls-side { position: sticky; top: 0; }
110
+ .ls-side-list { display: flex; flex-direction: column; gap: 4px; margin-top: 8px; }
111
+ .ls-side-item { display: flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 6px;
112
+ cursor: pointer; font-size: 13px; border-left: 3px solid transparent; word-break: break-all; }
113
+ .ls-side-item:hover { background: var(--dsw-alias-bg-layer-1); }
114
+ .ls-side-item.active { background: var(--dsw-alias-bg-layer-2); border-left-color: var(--dsw-alias-brand-primary); }
115
+ .ls-side-del { flex: none; border: none; background: none; color: var(--dsw-alias-label-secondary);
116
+ cursor: pointer; font-size: 13px; line-height: 1; padding: 2px 4px; border-radius: 4px; visibility: hidden; }
117
+ .ls-side-item:hover .ls-side-del { visibility: visible; }
118
+ .ls-side-del:hover { color: #B5432E; background: var(--dsw-alias-bg-layer-2); }
119
+ .ls-modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 100;
120
+ display: flex; align-items: center; justify-content: center; }
121
+ .ls-modal { width: 360px; max-width: 90vw; background: var(--dsw-alias-bg-layer-1);
122
+ border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; padding: 18px 20px; }
123
+ .ls-modal-title { font-size: 15px; font-weight: 700; margin-bottom: 8px; }
124
+ .ls-modal-body { font-size: 13px; color: var(--dsw-alias-label-secondary); line-height: 1.7; margin-bottom: 14px; }
125
+ .ls-modal-body strong { color: var(--dsw-alias-state-danger-primary, #B5432E); }
126
+ .ls-modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
127
+ .ls-btn-danger { background: #B5432E; }
128
+ .ls-title-row { display: flex; align-items: center; gap: 10px; }
129
+ .ls-title-row .ls-title { margin: 0 0 2px; }
130
+ .ls-gear { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1);
131
+ color: var(--dsw-alias-label-secondary); border-radius: 6px; cursor: pointer;
132
+ font-size: 14px; line-height: 1; padding: 5px 8px; flex: none; }
133
+ .ls-gear:hover { border-color: var(--dsw-alias-border-l2); color: var(--dsw-alias-label-primary); }
134
+ .ls-select { width: 100%; font-family: inherit; font-size: 13px; color: var(--dsw-alias-label-primary);
135
+ background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
136
+ border-radius: 4px; padding: 6px 8px; margin-top: 4px; }
137
+ .ls-select:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }
138
+ .ls-select:disabled { opacity: .5; }
139
+ .ls-set-label { font-size: 12px; color: var(--dsw-alias-label-secondary); margin-top: 10px; display: block; }
140
+ .ls-set-check { display: flex; align-items: center; gap: 6px; margin-top: 8px; font-size: 13px; }
141
+ .ls-set-note { font-size: 12px; color: var(--dsw-alias-label-secondary); margin: 8px 0 0; }
142
+ .ls-set-warn { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E); margin: 8px 0 0; }
143
+ .ls-set-ok { font-size: 12px; color: var(--dsw-alias-state-success-primary); margin: 8px 0 0; }
144
+ .ls-focus { display: grid; grid-template-columns: minmax(280px, 5fr) 7fr; gap: 16px; height: calc(100vh - 140px); }
145
+ .ls-focus-left { overflow-y: auto; padding-right: 4px; }
146
+ .ls-focus-head { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
147
+ .ls-focus-title { font-size: 17px; font-weight: 700; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
148
+ .ls-focus-right { display: flex; flex-direction: column; min-height: 0; border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; padding: 12px 14px; background: var(--dsw-alias-bg-layer-1); }
149
+ .ls-focus-right .ls-chat { margin-top: 0; border-top: none; padding-top: 0; flex: 1; display: flex; flex-direction: column; min-height: 0; }
150
+ .ls-focus-right .ls-chat-list { flex: 1; max-height: none; min-height: 200px; }
151
+ @media (max-width: 900px) { .ls-focus { grid-template-columns: 1fr; height: auto; } .ls-focus-left { max-height: 40vh; } }
152
+ .ls-side-name { flex: 1; min-width: 0; }
153
+ .ls-side-frac { font-size: 12px; color: var(--dsw-alias-label-secondary); flex: none; }
154
+ .ls-detail { background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
155
+ border-radius: 8px; padding: 16px 18px; min-width: 0; }
156
+ .ls-detail-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 4px; }
157
+ .ls-mat-item { display: flex; align-items: center; justify-content: space-between; gap: 10px;
158
+ padding: 4px 0; font-size: 13px; word-break: break-all; }
159
+ .ls-mat-size { color: var(--dsw-alias-label-secondary); font-size: 12px; flex: none; }
160
+ .ls-upload-bar { height: 4px; border-radius: 2px; background: var(--dsw-alias-border-l1); margin: 8px 0 4px; overflow: hidden; }
161
+ .ls-upload-fill { height: 100%; background: var(--dsw-alias-brand-primary); transition: width .15s; }
162
+ .ls-upload-err { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E); padding: 4px 0; }
163
+ .ls-file-label { display: inline-flex; align-items: center; gap: 6px; }
164
+ .ls-picked { margin-top: 6px; font-size: 12px; color: var(--dsw-alias-label-secondary); }
165
+ .ls-picked-item { display: flex; align-items: center; gap: 6px; padding: 1px 0; word-break: break-all; }
166
+ .ls-picked-x { cursor: pointer; border: none; background: none; color: var(--dsw-alias-label-secondary);
167
+ font-size: 13px; padding: 0 2px; flex: none; }
168
+ .ls-picked-x:hover { color: var(--dsw-alias-state-danger-primary, #B5432E); }
169
+ .ls-rebind { margin-top: 6px; }
170
+ .ls-ws { display: inline-flex; align-items: center; gap: 6px; font-size: 13px;
171
+ color: var(--dsw-alias-label-secondary); cursor: pointer; }
172
+ .ls-quiz { align-self: stretch; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px;
173
+ padding: 10px 12px; background: var(--dsw-alias-bg-layer-2); }
174
+ .ls-quiz-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
175
+ .ls-quiz-no { font-size: 12px; font-weight: 700; color: var(--dsw-alias-brand-primary); }
176
+ .ls-quiz-node { font-size: 12px; color: var(--dsw-alias-label-secondary); }
177
+ .ls-quiz-badge { font-size: 12px; font-weight: 600; margin-left: auto; }
178
+ .ls-quiz-badge.ok { color: var(--dsw-alias-state-success-primary); }
179
+ .ls-quiz-badge.bad { color: var(--dsw-alias-state-danger-primary, #B5432E); }
180
+ .ls-quiz-badge.wait { color: var(--dsw-alias-label-secondary); }
181
+ .ls-quiz-stem { font-size: 13px; margin-bottom: 8px; }
182
+ .ls-quiz-opts { display: flex; flex-direction: column; gap: 4px; }
183
+ .ls-quiz-opt { display: flex; gap: 8px; align-items: baseline; text-align: left; font-family: inherit;
184
+ font-size: 13px; padding: 5px 10px; border: 1px dashed var(--dsw-alias-border-l2); border-radius: 5px;
185
+ background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); cursor: pointer; }
186
+ .ls-quiz-opt:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary); }
187
+ .ls-quiz-opt:disabled { cursor: default; opacity: .8; }
188
+ .ls-quiz-opt.chosen { border-style: solid; border-color: var(--dsw-alias-brand-primary);
189
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 12%, var(--dsw-alias-bg-layer-1)); }
190
+ .ls-quiz-opt-key { font-weight: 700; flex: none; }
191
+ .ls-qh-list { display: flex; flex-direction: column; gap: 2px; }
192
+ .ls-qh-item { border-left: 2px solid var(--dsw-alias-border-l1); padding: 4px 8px; cursor: pointer;
193
+ font-size: 13px; }
194
+ .ls-qh-item:hover { background: var(--dsw-alias-bg-layer-1); }
195
+ .ls-qh-row { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
196
+ .ls-qh-date { color: var(--dsw-alias-label-secondary); font-size: 12px; }
197
+ .ls-qh-frac { font-size: 12px; }
198
+ .ls-qh-node { font-size: 12px; color: var(--dsw-alias-label-secondary); }
199
+ .ls-qh-ans { font-size: 12px; color: var(--dsw-alias-label-secondary); }
200
+ .ls-qh-detail { margin-top: 4px; padding: 6px 10px; background: var(--dsw-alias-bg-layer-1);
201
+ border-radius: 6px; font-size: 12px; }
202
+ .ls-qh-line { padding: 2px 0; word-break: break-word; }
203
+ @media (max-width: 720px) {
204
+ .ls-layout { grid-template-columns: 1fr; }
205
+ .ls-side { position: static; }
206
+ }
207
+ `
208
+
209
+ /** 极简 DAG 分层布局:roots 在底,目标在顶 */
210
+ function Dag({ nodes, edges }) {
211
+ if (!nodes.length) return null
212
+ const level = new Map()
213
+ const nexts = new Map(nodes.map(n => [n.id, []]))
214
+ for (const [a, b] of edges) if (nexts.has(a)) nexts.get(a).push(b)
215
+ const depth = id => {
216
+ if (level.has(id)) return level.get(id)
217
+ level.set(id, 0)
218
+ let d = 0
219
+ for (const nx of nexts.get(id) || []) d = Math.max(d, depth(nx) + 1)
220
+ level.set(id, d)
221
+ return d
222
+ }
223
+ nodes.forEach(n => depth(n.id))
224
+ const maxLevel = Math.max(...level.values())
225
+ const byLevel = new Map()
226
+ for (const n of nodes) {
227
+ const l = maxLevel - level.get(n.id) // roots (level0) 放最底一行
228
+ if (!byLevel.has(l)) byLevel.set(l, [])
229
+ byLevel.get(l).push(n)
230
+ }
231
+ const rowH = 46, colW = 150, nodeW = 118, nodeH = 30
232
+ const pos = new Map()
233
+ for (const [l, list] of byLevel) {
234
+ list.forEach((n, i) => pos.set(n.id, { x: colW / 2 + i * colW + l * 18, y: 24 + l * rowH, n }))
235
+ }
236
+ const width = Math.max(...[...pos.values()].map(p => p.x)) + 80
237
+ const height = 24 + (byLevel.size) * rowH
238
+ const key = n => (n.id === n.label ? n.id : `${n.id}`)
239
+ return h('svg', { className: 'ls-dag', width, height, viewBox: `0 0 ${width} ${height}` },
240
+ edges.map(([a, b], i) => {
241
+ const pa = pos.get(a), pb = pos.get(b)
242
+ if (!pa || !pb) return null
243
+ const x1 = pa.x + nodeW / 2, y1 = pa.y + nodeH / 2, x2 = pb.x + nodeW / 2, y2 = pb.y + nodeH / 2
244
+ return h('line', { key: `e${i}`, x1, y1, x2, y2, stroke: 'var(--dsw-alias-border-l2)', strokeWidth: 1 })
245
+ }),
246
+ [...pos.values()].map(({ x, y, n }) => h('g', { key: n.id },
247
+ h('rect', {
248
+ x: x - nodeW / 2, y, width: nodeW, height: nodeH, rx: 5,
249
+ fill: n.status === 'todo' ? 'var(--dsw-alias-bg-layer-2)' : STATUS_COLOR[n.status],
250
+ stroke: n.status === 'todo' ? STATUS_COLOR.todo : 'none',
251
+ strokeDasharray: n.status === 'todo' ? '3 3' : undefined,
252
+ }),
253
+ h('text', {
254
+ x, y: y + nodeH / 2 + 4, textAnchor: 'middle',
255
+ fill: n.status === 'todo' ? 'currentColor' : '#FAF7F0',
256
+ style: { fill: n.status === 'todo' ? undefined : '#FAF7F0' },
257
+ }, n.label.length > 8 ? n.label.slice(0, 7) + '…' : n.label),
258
+ )),
259
+ )
260
+ }
261
+
262
+ /** mermaid UMD 模块级 Promise 单例:动态注入 script,失败记 mermaidFailed 不再重试 */
263
+ let mermaidPromise = null
264
+ let mermaidFailed = false
265
+ function loadMermaid() {
266
+ if (mermaidFailed) return Promise.reject(new Error('mermaid asset failed'))
267
+ if (!mermaidPromise) {
268
+ mermaidPromise = new Promise((resolve, reject) => {
269
+ const s = document.createElement('script')
270
+ s.src = '/api/learning-space/assets/mermaid.min.js'
271
+ s.onload = () => {
272
+ try {
273
+ window.mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' })
274
+ resolve(window.mermaid)
275
+ } catch (e) { mermaidFailed = true; reject(e) }
276
+ }
277
+ s.onerror = () => { mermaidFailed = true; mermaidPromise = null; reject(new Error('mermaid 资产加载失败')) }
278
+ document.head.appendChild(s)
279
+ })
280
+ }
281
+ return mermaidPromise
282
+ }
283
+
284
+ /**
285
+ * 完整 mermaid 渲染:render 成功挂 SVG;失败(语法错/资产 404)提示 + 源码 + 旧 Dag 兜底。
286
+ * planMermaid 字符串未变时跳过重渲染(render 是秒级全量 SVG 重排,不能 15s 轮询盲跑)。
287
+ */
288
+ function MermaidGraph({ src, nodes, edges }) {
289
+ const wrapRef = useRef(null)
290
+ const lastSrcRef = useRef(null)
291
+ const [err, setErr] = useState(null)
292
+ useEffect(() => {
293
+ const el = wrapRef.current
294
+ if (!el) return
295
+ if (!src) { el.innerHTML = ''; lastSrcRef.current = null; setErr(null); return }
296
+ if (lastSrcRef.current === src && !err) return // 轮询未变化:跳过
297
+ let alive = true
298
+ loadMermaid().then(m => {
299
+ if (!alive || !wrapRef.current) return
300
+ return m.render(`ls-mermaid-${Date.now()}`, src).then(({ svg }) => {
301
+ if (!alive) return
302
+ el.innerHTML = svg
303
+ lastSrcRef.current = src
304
+ setErr(null)
305
+ })
306
+ }).catch(e => {
307
+ if (!alive) return
308
+ el.innerHTML = ''
309
+ lastSrcRef.current = null
310
+ setErr(String((e && e.message) || e))
311
+ })
312
+ return () => { alive = false }
313
+ }, [src])
314
+ return h('div', { className: 'ls-dag-wrap' },
315
+ err ? h('div', { className: 'ls-mermaid-err' }, `mermaid 渲染失败(${err}),已降级显示源码与简图`) : null,
316
+ err ? h('pre', { className: 'ls-mermaid-src' }, h('code', null, src)) : null,
317
+ h('div', { className: 'ls-mermaid-wrap', ref: wrapRef }),
318
+ err ? h('div', { className: 'ls-dag-wrap' }, h(Dag, { nodes, edges })) : null,
319
+ )
320
+ }
321
+
322
+ /** 行内 markdown:**加粗** 与 `行内码`,其余按原文本 */
323
+ function inlineNodes(text, keyBase) {
324
+ const out = []
325
+ const re = /(\*\*[^*]+\*\*|`[^`]+`)/g
326
+ let last = 0, m, i = 0
327
+ while ((m = re.exec(text))) {
328
+ if (m.index > last) out.push(text.slice(last, m.index))
329
+ const t = m[0]
330
+ if (t.startsWith('**')) out.push(h('strong', { key: `${keyBase}b${i}` }, t.slice(2, -2)))
331
+ else out.push(h('code', { key: `${keyBase}c${i}`, className: 'ls-md-code' }, t.slice(1, -1)))
332
+ last = m.index + t.length
333
+ i++
334
+ }
335
+ if (last < text.length) out.push(text.slice(last))
336
+ return out
337
+ }
338
+
339
+ /** 极简 markdown → React 元素数组(代码块/标题/列表/加粗/行内码),无法识别的行原样输出 */
340
+ function markdownLite(text) {
341
+ const lines = String(text || '').split(/\r?\n/)
342
+ const els = []
343
+ let code = null
344
+ let list = null
345
+ let k = 0
346
+ const flushCode = () => {
347
+ if (code) { els.push(h('pre', { key: `pre${k++}`, className: 'ls-md-pre' }, h('code', null, code.join('\n')))); code = null }
348
+ }
349
+ const flushList = () => {
350
+ if (list && list.length) { els.push(h('ul', { key: `ul${k++}`, className: 'ls-md-ul' }, list.map((li, i) => h('li', { key: i }, li)))); list = null }
351
+ }
352
+ for (const line of lines) {
353
+ if (/^\s*```/.test(line)) {
354
+ if (code) flushCode()
355
+ else { flushList(); code = [] }
356
+ continue
357
+ }
358
+ if (code) { code.push(line); continue }
359
+ const hm = /^(#{1,3})\s+(.*)$/.exec(line)
360
+ if (hm) {
361
+ flushList()
362
+ els.push(h(`h${hm[1].length + 3}`, { key: `h${k++}`, className: 'ls-md-h' }, inlineNodes(hm[2], `i${k}`)))
363
+ continue
364
+ }
365
+ if (/^\s*[-*]\s+/.test(line)) {
366
+ if (!list) list = []
367
+ list.push(inlineNodes(line.replace(/^\s*[-*]\s+/, ''), `l${k++}`))
368
+ continue
369
+ }
370
+ flushList()
371
+ if (line.trim()) els.push(h('p', { key: `p${k++}`, className: 'ls-md-p' }, inlineNodes(line, `i${k}`)))
372
+ }
373
+ flushCode()
374
+ flushList()
375
+ return els
376
+ }
377
+
378
+ /** 选择题卡片:题干 + 可点选项;点选即发送字母(复用 sendText 与发送锁) */
379
+ function QuizCard({ quiz, sending, onAnswer }) {
380
+ const [localAnswer, setLocalAnswer] = useState(null)
381
+ const answered = quiz.state === 'answered' || quiz.state === 'graded' || localAnswer
382
+ const chosen = quiz.answer || localAnswer
383
+ const disabled = !!answered || sending
384
+ return h('div', { className: 'ls-quiz' },
385
+ h('div', { className: 'ls-quiz-head' },
386
+ h('span', { className: 'ls-quiz-no' }, `第 ${quiz.index} / ${quiz.total} 题`),
387
+ quiz.node ? h('span', { className: 'ls-quiz-node' }, quiz.node) : null,
388
+ quiz.state === 'graded'
389
+ ? h('span', { className: 'ls-quiz-badge' + (quiz.correct ? ' ok' : ' bad') }, quiz.correct ? '✅ 答对' : '❌ 答错')
390
+ : answered ? h('span', { className: 'ls-quiz-badge wait' }, '已作答,等待反馈') : null),
391
+ quiz.stem ? h('div', { className: 'ls-quiz-stem' }, quiz.stem) : null,
392
+ h('div', { className: 'ls-quiz-opts' },
393
+ (quiz.options || []).map(o =>
394
+ h('button', {
395
+ key: o.key, type: 'button',
396
+ className: 'ls-quiz-opt' + (chosen === o.key ? ' chosen' : ''),
397
+ disabled,
398
+ // 发送失败(含非 409 错误)时回滚 localAnswer,允许重点重试
399
+ onClick: () => { Promise.resolve(onAnswer(o.key)).then(ok => setLocalAnswer(ok ? o.key : null)) },
400
+ },
401
+ h('span', { className: 'ls-quiz-opt-key' }, o.key),
402
+ h('span', null, o.text)))),
403
+ )
404
+ }
405
+
406
+ /** 答题历史:quizlog 时间线,点击展开题面与反馈;refreshKey 变化时重拉(答完题联动刷新) */
407
+ function QuizHistory({ topic, refreshKey }) {
408
+ const [records, setRecords] = useState(null)
409
+ const [openSeq, setOpenSeq] = useState(null)
410
+ useEffect(() => {
411
+ let alive = true
412
+ fetch(`/api/learning-space/quizlog?topic=${encodeURIComponent(topic)}`)
413
+ .then(r => r.json())
414
+ .then(j => { if (alive && j.ok) setRecords(j.records || []) })
415
+ .catch(() => { if (alive) setRecords([]) })
416
+ return () => { alive = false }
417
+ }, [topic, refreshKey])
418
+ if (!records || !records.length) return null
419
+ return h('div', { className: 'ls-section' },
420
+ h('div', { className: 'ls-h' }, `答题历史(${records.length})`),
421
+ h('div', { className: 'ls-qh-list' }, records.map((r, i) =>
422
+ h('div', { key: `${r.fbSeq}-${i}`, className: 'ls-qh-item' + (openSeq === r.fbSeq ? ' open' : ''),
423
+ onClick: () => setOpenSeq(openSeq === r.fbSeq ? null : r.fbSeq) },
424
+ h('div', { className: 'ls-qh-row' },
425
+ h('span', { className: 'ls-qh-mark ' + (r.correct ? 'ok' : 'bad') }, r.correct ? '✅' : '❌'),
426
+ h('span', { className: 'ls-qh-date' }, r.date),
427
+ h('span', { className: 'ls-qh-frac' }, `第 ${r.index} / ${r.total} 题`),
428
+ r.node ? h('span', { className: 'ls-qh-node' }, r.node) : null,
429
+ h('span', { className: 'ls-qh-ans' }, `答 ${r.answer}`)),
430
+ openSeq === r.fbSeq ? h('div', { className: 'ls-qh-detail' },
431
+ h('div', { className: 'ls-qh-line' }, `题面:${r.stem}`),
432
+ h('div', { className: 'ls-qh-line' }, `选项:${r.options}`),
433
+ h('div', { className: 'ls-qh-line' }, `反馈:${r.feedback}`)) : null))),
434
+ )
435
+ }
436
+
437
+ /** 内嵌对话窗:轮询收消息 + 发消息 + 兜底跳转;phase=1 摸底 / 2 学习(默认 2 兼容存量) */
438
+ function ChatWindow({ topic, phase = 2, sessionId: initialSessionId, onOpenInSession, onQuizGraded }) {
439
+ const [messages, setMessages] = useState([])
440
+ const [input, setInput] = useState('')
441
+ const [sending, setSending] = useState(false)
442
+ const [err, setErr] = useState(null)
443
+ const [running, setRunning] = useState(false)
444
+ const [hasMore, setHasMore] = useState(false)
445
+ const [sessionId, setSessionId] = useState(initialSessionId || null)
446
+ const [needRebind, setNeedRebind] = useState(false)
447
+ const lastSeqRef = useRef(null)
448
+ const inFlightRef = useRef(false)
449
+ const pendingIdRef = useRef(0)
450
+ const listRef = useRef(null)
451
+
452
+ const poll = useCallback(async () => {
453
+ if (inFlightRef.current) return
454
+ inFlightRef.current = true
455
+ try {
456
+ const afterSeq = lastSeqRef.current
457
+ const qs = `topic=${encodeURIComponent(topic)}&phase=${phase}` + (afterSeq != null ? `&afterSeq=${afterSeq}` : '')
458
+ const r = await fetch(`/api/learning-space/session/messages?${qs}`)
459
+ const j = await r.json()
460
+ if (!j.ok) {
461
+ setErr(j.error)
462
+ if (j.error === 'no session') setNeedRebind(true)
463
+ return
464
+ }
465
+ setErr(null)
466
+ setSessionId(j.sessionId)
467
+ setRunning(j.running)
468
+ setHasMore(!!j.hasMore)
469
+ const incoming = Array.isArray(j.messages) ? j.messages : []
470
+ const updates = Array.isArray(j.toolUpdates) ? j.toolUpdates : []
471
+ if (incoming.length || updates.length) {
472
+ // 新到达的 assistant 消息首字符是 ✅/❌ 即视为判分反馈,触发答题历史刷新
473
+ if (onQuizGraded && incoming.some(m => m.role === 'assistant' && /^\s*[✅❌]/.test(m.text || ''))) onQuizGraded()
474
+ setMessages(prev => {
475
+ // 乐观消息(pending)保持追加在末尾,真实消息到达后按文本确认并移除
476
+ const real = prev.filter(m => !m.pending)
477
+ const optimistic = prev.filter(m => m.pending)
478
+ const seen = new Set(real.map(m => m.seq))
479
+ for (const m of incoming) if (!seen.has(m.seq)) { seen.add(m.seq); real.push(m) }
480
+ const stateByCall = new Map(updates.map(u => [u.callId, u.state]))
481
+ const withState = stateByCall.size
482
+ ? real.map(m => m.role === 'tool' && m.callId && stateByCall.has(m.callId)
483
+ ? { ...m, state: stateByCall.get(m.callId) } : m)
484
+ : real
485
+ // 只把发送之后才出现的同文本用户消息当作乐观消息的确认,避免重发相同文本时误删
486
+ return [...withState, ...optimistic.filter(p =>
487
+ !withState.some(m => m.role === 'user' && m.text === p.text && m.seq > p.afterSeq))]
488
+ })
489
+ }
490
+ if (typeof j.cursor === 'number') {
491
+ lastSeqRef.current = lastSeqRef.current == null
492
+ ? j.cursor : Math.max(lastSeqRef.current, j.cursor)
493
+ }
494
+ } catch (e) { setErr(String(e)) } finally { inFlightRef.current = false }
495
+ }, [topic, phase])
496
+
497
+ useEffect(() => { poll(); const t = setInterval(poll, 2500); return () => clearInterval(t) }, [poll])
498
+ useEffect(() => { if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight }, [messages, running])
499
+
500
+ // 发文本(输入框与 QuizCard 点选共用):失败里 409 = 绑定会话已失效
501
+ const sendText = async (text) => {
502
+ if (!text || sending) return false
503
+ setSending(true); setErr(null)
504
+ try {
505
+ const r = await fetch('/api/learning-space/session/send', {
506
+ method: 'POST',
507
+ headers: { 'content-type': 'application/json' },
508
+ body: JSON.stringify({ topic, text, phase }),
509
+ })
510
+ const j = await r.json()
511
+ if (j.ok) {
512
+ pendingIdRef.current += 1
513
+ const afterSeq = lastSeqRef.current == null ? -1 : lastSeqRef.current
514
+ setMessages(prev => [...prev, {
515
+ seq: -pendingIdRef.current, role: 'user', text, pending: true, afterSeq,
516
+ }])
517
+ poll()
518
+ return true
519
+ }
520
+ if (j.error === 'session gone, start first') { setErr('会话已失效'); setNeedRebind(true); return false }
521
+ setErr(j.error)
522
+ return false
523
+ } catch (e) { setErr(String(e)); return false }
524
+ finally { setSending(false) }
525
+ }
526
+
527
+ const send = async () => {
528
+ const text = input.trim()
529
+ if (!text || sending) return
530
+ if (await sendText(text)) setInput('')
531
+ }
532
+
533
+ // 重新绑定:调 /session/start {rebind:true, phase} 只重建当前 phase 的会话,重置轮询
534
+ const rebind = async () => {
535
+ setNeedRebind(false)
536
+ setErr(null)
537
+ try {
538
+ const r = await fetch('/api/learning-space/session/start', {
539
+ method: 'POST',
540
+ headers: { 'content-type': 'application/json' },
541
+ body: JSON.stringify({ topic, rebind: true, phase }),
542
+ })
543
+ const j = await r.json()
544
+ if (j.ok && j.sessionId) {
545
+ setSessionId(j.sessionId)
546
+ setMessages([])
547
+ lastSeqRef.current = null
548
+ poll()
549
+ } else setErr(j.error || '重新绑定失败')
550
+ } catch (e) { setErr(String(e)) }
551
+ }
552
+
553
+ const last = messages[messages.length - 1]
554
+ return h('div', {
555
+ className: 'ls-chat',
556
+ // 点击对话窗(输入框/按钮/滚动)不冒泡到卡片折叠区,否则一点输入框整块就收起
557
+ onClick: e => e.stopPropagation(),
558
+ },
559
+ h('div', { className: 'ls-chat-head' },
560
+ h('span', { className: 'ls-chat-title' }, phase === 1 ? '摸底对话' : '学习对话'),
561
+ h('button', {
562
+ className: 'ls-btn', type: 'button',
563
+ disabled: !sessionId || !onOpenInSession,
564
+ onClick: () => onOpenInSession && onOpenInSession(sessionId),
565
+ }, '在会话中打开 ↗')),
566
+ h('div', { className: 'ls-chat-list', ref: listRef },
567
+ hasMore ? h('span', { className: 'ls-chat-more' }, '更早消息可在会话中查看') : null,
568
+ messages.map((m, i) => {
569
+ if (m.role === 'tool') {
570
+ // ask_user_question 待作答时渲染提示卡片:问题+选项只读展示,作答跳转完整会话
571
+ if (m.ask && m.state === 'running') {
572
+ return h('div', { key: `q${m.seq}`, className: 'ls-ask' },
573
+ h('div', { className: 'ls-ask-badge' }, '❓ AI 想问你'),
574
+ m.ask.map((q, qi) => h('div', { key: qi, className: 'ls-ask-q' },
575
+ q.header ? h('div', { className: 'ls-ask-h' }, q.header) : null,
576
+ h('div', { className: 'ls-ask-text' }, q.question || ''),
577
+ Array.isArray(q.options) && q.options.length
578
+ ? h('div', { className: 'ls-ask-opts' }, q.options.map((o, oi) =>
579
+ h('div', { key: oi, className: 'ls-ask-opt' },
580
+ h('span', { className: 'ls-ask-opt-label' }, o.label || ''),
581
+ o.description ? h('span', { className: 'ls-ask-opt-desc' }, o.description) : null)))
582
+ : null,
583
+ q.multi_select ? h('div', { className: 'ls-ask-opt-desc' }, '(可多选)') : null)),
584
+ h('button', {
585
+ className: 'ls-btn ls-ask-go', type: 'button',
586
+ disabled: !sessionId || !onOpenInSession,
587
+ onClick: () => onOpenInSession && onOpenInSession(sessionId),
588
+ }, '去回答 ↗'))
589
+ }
590
+ return h('div', { key: m.seq < 0 ? `t${i}${m.seq}` : m.seq, className: 'ls-tool' },
591
+ `🛠 ${m.toolName || '工具'} `,
592
+ m.state === 'done' ? '✓' : m.state === 'error' ? '✗' : '…')
593
+ }
594
+ return h('div', { key: m.seq < 0 ? `m${m.seq}` : m.seq, className: `ls-msg ls-msg-${m.role}` },
595
+ m.role === 'assistant' && m.quiz
596
+ ? h(QuizCard, { quiz: m.quiz, sending, onAnswer: sendText })
597
+ : m.role === 'assistant' ? markdownLite(m.text) : m.text)
598
+ }),
599
+ running && (!last || last.role !== 'assistant')
600
+ ? h('div', { className: 'ls-thinking' }, '思考中…') : null),
601
+ err ? h('div', { className: 'ls-chat-err' }, `出错:${err},可点「在会话中打开」继续`) : null,
602
+ needRebind ? h('button', { className: 'ls-btn ls-rebind', type: 'button', onClick: rebind }, '会话已失效,重新绑定') : null,
603
+ h('div', { className: 'ls-chat-row' },
604
+ h('textarea', {
605
+ className: 'ls-input ls-chat-input',
606
+ value: input,
607
+ placeholder: '输入问题,Enter 发送,Shift+Enter 换行',
608
+ onChange: e => setInput(e.target.value),
609
+ onKeyDown: e => {
610
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() }
611
+ },
612
+ }),
613
+ h('button', { className: 'ls-btn', type: 'button', disabled: sending || !input.trim(), onClick: send },
614
+ sending ? '发送中…' : '发送')),
615
+ )
616
+ }
617
+
618
+ /** 材料扩展名白名单(与 Host 上传路由一致),供 file input 的 accept */
619
+ const ACCEPT = '.pdf,.md,.txt,.docx,.pptx,.xlsx,.csv,.json,.epub,.png,.jpg,.jpeg,.gif,.webp,.zip'
620
+
621
+ /** XHR 上传(fetch 无上传进度):FormData + xhr.upload.onprogress 回传百分比 */
622
+ function uploadFiles(topic, fileList, onProgress) {
623
+ return new Promise((resolve, reject) => {
624
+ const fd = new FormData()
625
+ fd.append('topic', topic)
626
+ for (const f of fileList) fd.append('file', f)
627
+ const xhr = new XMLHttpRequest()
628
+ xhr.open('POST', '/api/learning-space/materials/upload')
629
+ if (xhr.upload && onProgress) {
630
+ xhr.upload.onprogress = e => { if (e.lengthComputable) onProgress(e.loaded / e.total) }
631
+ }
632
+ xhr.onload = () => {
633
+ let j = null
634
+ try { j = JSON.parse(xhr.responseText) } catch { /* 非 JSON */ }
635
+ if (xhr.status >= 200 && xhr.status < 300 && j && j.ok) resolve(j)
636
+ else reject(new Error((j && j.error) || `上传失败(HTTP ${xhr.status})`))
637
+ }
638
+ xhr.onerror = () => reject(new Error('网络错误,上传失败'))
639
+ xhr.send(fd)
640
+ })
641
+ }
642
+
643
+ /** 隐藏 file input + 样式化按钮触发,选中即回调 */
644
+ function FilePickButton({ onFiles, label, disabled }) {
645
+ const ref = useRef(null)
646
+ return h('span', { className: 'ls-file-label' },
647
+ h('input', {
648
+ ref, type: 'file', multiple: true, accept: ACCEPT, style: { display: 'none' },
649
+ onChange: e => { if (e.target.files && e.target.files.length) onFiles(e.target.files); e.target.value = '' },
650
+ }),
651
+ h('button', {
652
+ className: 'ls-btn', type: 'button', disabled,
653
+ onClick: () => ref.current && ref.current.click(),
654
+ }, label || '导入材料'),
655
+ )
656
+ }
657
+
658
+ /** 人类可读文件大小 */
659
+ function fmtSize(n) {
660
+ if (n == null) return ''
661
+ if (n < 1024) return `${n} B`
662
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
663
+ return `${(n / 1024 / 1024).toFixed(1)} MB`
664
+ }
665
+
666
+ /** 材料列表 + 导入按钮 + 上传进度 + 错误展示 */
667
+ function MaterialList({ topic, onRefresh }) {
668
+ const [uploading, setUploading] = useState(false)
669
+ const [pct, setPct] = useState(0)
670
+ const [err, setErr] = useState(null)
671
+ // 材料列表折叠态:默认收起,与「导入材料」按钮同行展示数量
672
+ const [open, setOpen] = useState(false)
673
+ const materials = (topic && topic.materials) || []
674
+ const doUpload = async files => {
675
+ setUploading(true); setPct(0); setErr(null)
676
+ try {
677
+ await uploadFiles(topic.name, files, p => setPct(Math.round(p * 100)))
678
+ onRefresh()
679
+ } catch (e) { setErr(String(e.message || e)) }
680
+ finally { setUploading(false) }
681
+ }
682
+ return h('div', { className: 'ls-section' },
683
+ h('div', { className: 'ls-side-head', style: { marginBottom: 0, flexWrap: 'wrap', rowGap: 6 } },
684
+ h('span', {
685
+ className: 'ls-h', style: { border: 'none', padding: 0, margin: 0, cursor: 'pointer', userSelect: 'none' },
686
+ onClick: () => setOpen(!open),
687
+ }, `${open ? '▾' : '▸'} 学习材料${materials.length ? `(${materials.length})` : ''}`),
688
+ h(FilePickButton, { onFiles: doUpload, disabled: uploading, label: uploading ? '上传中…' : '导入材料' })),
689
+ open ? (materials.length === 0
690
+ ? h('div', { className: 'ls-empty' }, '暂无材料')
691
+ : materials.map(m => h('div', { key: m.name, className: 'ls-mat-item' },
692
+ h('span', null, m.name),
693
+ h('span', { className: 'ls-mat-size' }, fmtSize(m.size))))) : null,
694
+ uploading ? h('div', { className: 'ls-upload-bar' },
695
+ h('div', { className: 'ls-upload-fill', style: { width: pct + '%' } })) : null,
696
+ uploading ? h('div', { className: 'ls-empty' }, `上传中 ${pct}%…`) : null,
697
+ err ? h('div', { className: 'ls-upload-err' }, err) : null,
698
+ )
699
+ }
700
+
701
+ /** 阶段卡:阶段一(摸底 + 计划生成)/ 计划已生成 两态;阶段二不渲染(详情区回归现有布局) */
702
+ function PhaseCard({ topic, onStartPhase1, onStartPhase2, onToggleWebSearch, starting }) {
703
+ if (topic.phase !== 1) return null
704
+ return h('div', { className: 'ls-section' },
705
+ h('div', { className: 'ls-h' }, topic.planReady ? '计划已生成' : '摸底 + 学习计划生成'),
706
+ !topic.planReady
707
+ ? h('div', null,
708
+ h('div', { className: 'ls-empty' }, '可先把学习材料导入下方「学习材料」,AI 摸底与计划生成会参考'),
709
+ h('label', { className: 'ls-ws' },
710
+ h('input', {
711
+ type: 'checkbox',
712
+ checked: topic.webSearch !== false,
713
+ onChange: e => onToggleWebSearch(topic.name, e.target.checked),
714
+ }),
715
+ ' 允许联网检索(对下一次新会话生效)'),
716
+ h('div', { style: { marginTop: 8 } },
717
+ h('button', {
718
+ className: 'ls-btn', type: 'button', disabled: starting,
719
+ onClick: () => onStartPhase1(topic.name),
720
+ }, starting ? '创建中…' : '开始摸底对话 →')))
721
+ : h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' } },
722
+ h('a', {
723
+ className: 'ls-btn', download: '',
724
+ href: `/api/learning-space/export/plan?topic=${encodeURIComponent(topic.name)}`,
725
+ style: { textDecoration: 'none', lineHeight: '20px' },
726
+ }, '导出学习计划'),
727
+ h('span', { className: 'ls-frac' }, '计划已就绪,开始学习?'),
728
+ h('button', {
729
+ className: 'ls-btn', type: 'button', disabled: starting,
730
+ onClick: () => onStartPhase2(topic.name),
731
+ }, starting ? '创建中…' : '开始学习 →')),
732
+ )
733
+ }
734
+
735
+ /** 学习记录:studyLog 条目(倒序,最新在前)+ 下载 study-log.md 原文 */
736
+ function StudyLogList({ topic }) {
737
+ const entries = (topic && topic.studyLog) || []
738
+ return h('div', { className: 'ls-section' },
739
+ h('div', { className: 'ls-side-head', style: { marginBottom: 8 } },
740
+ h('span', { className: 'ls-h', style: { border: 'none', padding: 0, margin: 0 } }, `学习记录(${entries.length})`),
741
+ entries.length ? h('a', {
742
+ className: 'ls-btn', download: '',
743
+ href: `/api/learning-space/studylog?topic=${encodeURIComponent(topic.name)}`,
744
+ style: { textDecoration: 'none', lineHeight: '20px' },
745
+ }, '下载学习记录') : null),
746
+ entries.length === 0
747
+ ? h('div', { className: 'ls-empty' }, '暂无学习记录(每教完一个节点 AI 应自动写入;长时间没有时可在对话里提醒它调用 learn_update 的 study_log)')
748
+ : entries.map((e, i) => h('div', {
749
+ key: `${e.date}-${i}`, className: 'ls-journal-item', style: { wordBreak: 'break-word' },
750
+ }, `${e.date} · ${e.node}${e.mastery ? ` · ${e.mastery}` : ''} — ${e.summary}`)),
751
+ )
752
+ }
753
+
754
+ /** 学习方案(节点列表 + 依赖图):可折叠;阶段二默认收起,点标题或箭头展开 */
755
+ function PlanSection({ topic, defaultOpen, nodeStatus }) {
756
+ const [open, setOpen] = useState(!!defaultOpen)
757
+ const total = topic.nodes.length || topic.order.length || 0
758
+ const done = topic.counts.done || 0
759
+ return h('div', { className: 'ls-section' },
760
+ h('div', {
761
+ className: 'ls-side-head',
762
+ style: { marginBottom: open ? 8 : 0, cursor: 'pointer', userSelect: 'none' },
763
+ onClick: () => setOpen(!open),
764
+ },
765
+ h('span', {
766
+ className: 'ls-h', style: { border: 'none', padding: 0, margin: 0, flex: 1 },
767
+ }, `${open ? '▾' : '▸'} 学习方案(${done}/${total})`)),
768
+ open ? h('div', null,
769
+ h('ul', { className: 'ls-nodes' },
770
+ (topic.order.length ? topic.order : topic.nodes.map(n => n.label)).map(label =>
771
+ h('li', { className: 'ls-node', key: label },
772
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR[nodeStatus.get(label) || 'todo'] } }),
773
+ cleanLabel(label)))),
774
+ h(MermaidGraph, { src: topic.planMermaid || '', nodes: topic.nodes, edges: topic.edges }),
775
+ ) : null,
776
+ )
777
+ }
778
+
779
+ /** 选中课程详情:按 phase 组装——phase1 = PhaseCard + 摸底对话窗;phase2 = 现有布局 + 学习记录 + 学习对话窗 */
780
+ function TopicDetail({ topic, onStart, starting, chat, onOpenInSession, onRefresh, onToggleWebSearch }) {
781
+ const [quizTick, setQuizTick] = useState(0)
782
+ const phase = topic.phase === 1 ? 1 : 2
783
+ const total = topic.nodes.length || topic.order.length || 0
784
+ const done = topic.counts.done || 0
785
+ const pct = total ? Math.round((done / total) * 100) : 0
786
+ const nodeStatus = new Map(topic.nodes.map(n => [n.label, n.status]))
787
+ return h('div', { className: 'ls-detail' },
788
+ h('div', { className: 'ls-detail-head' },
789
+ h('span', { className: 'ls-name' }, topic.name),
790
+ h('span', { style: { display: 'flex', gap: 10, alignItems: 'baseline' } },
791
+ h('span', { className: 'ls-frac' }, phase === 1 ? '阶段一 · 摸底' : `${done}/${total} 已确认`),
792
+ h('a', {
793
+ className: 'ls-btn', href: `/api/learning-space/export?topic=${encodeURIComponent(topic.name)}`,
794
+ download: '', style: { textDecoration: 'none', lineHeight: '20px' },
795
+ }, '导出报告'),
796
+ h('button', {
797
+ className: 'ls-btn',
798
+ disabled: starting,
799
+ onClick: () => onStart(topic.name, phase),
800
+ }, starting ? '创建中…' : phase === 2 ? '继续学习 →' : '开始摸底对话 →'),
801
+ phase === 2 ? h('button', {
802
+ className: 'ls-btn', title: '新建学习会话,从学习方案开头重新教;旧会话保留在会话列表',
803
+ disabled: starting,
804
+ onClick: () => onStart(topic.name, 2, true),
805
+ }, starting ? '…' : '重新学习 ↻') : null)),
806
+ topic.goal ? h('div', { className: 'ls-goal' }, topic.goal) : null,
807
+ h('div', { className: 'ls-bar' }, h('div', { className: 'ls-bar-fill', style: { width: pct + '%' } })),
808
+ h('div', { className: 'ls-badges' },
809
+ ['done', 'doing', 'warn', 'todo'].filter(s => topic.counts[s]).map(s =>
810
+ h('span', { key: s },
811
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR[s] } }),
812
+ `${STATUS_LABEL[s]} ${topic.counts[s]}`)),
813
+ topic.mistakes.length
814
+ ? h('span', null, `错题 ${topic.mistakes.length}`) : null),
815
+ h(PhaseCard, {
816
+ topic,
817
+ starting,
818
+ onStartPhase1: name => onStart(name, 1),
819
+ onStartPhase2: name => onStart(name, 2),
820
+ onToggleWebSearch,
821
+ }),
822
+ h(PlanSection, { topic, defaultOpen: phase === 1, nodeStatus }),
823
+ h(MaterialList, { topic, onRefresh }),
824
+ h(QuizHistory, { topic: topic.name, refreshKey: quizTick }),
825
+ phase === 2 ? h(StudyLogList, { topic }) : null,
826
+ chat ? h(ChatWindow, {
827
+ key: `${topic.name}-${phase}`, // phase 切换时重挂载,重置轮询游标,避免双会话消息串窗
828
+ topic: topic.name,
829
+ phase,
830
+ sessionId: phase === 1 ? topic.phase1SessionId : topic.phase2SessionId,
831
+ onOpenInSession,
832
+ onQuizGraded: () => setQuizTick(t => t + 1),
833
+ }) : null,
834
+ )
835
+ }
836
+
837
+ /** 节点标签清洗:去掉 mermaid 里带的 <br/> 换行标记(显示层处理,源数据不动) */
838
+ const cleanLabel = s => String(s || '').replace(/<br\s*\/?>/gi, ' ').replace(/\s{2,}/g, ' ').trim()
839
+
840
+ /** 专注页左栏:节点手风琴——点节点展开该节点的教学笔记(notes/<节点>.md) */
841
+ function NodeAccordion({ topic }) {
842
+ const [openNode, setOpenNode] = useState(null)
843
+ const [notes, setNotes] = useState({}) // label -> content(含 '' 已确认为无笔记)
844
+ const nodes = topic.nodes.length ? topic.nodes : (topic.order || []).map(l => ({ id: l, label: l, status: 'todo' }))
845
+ const label = n => cleanLabel(n.label || n.id)
846
+ const toggle = async label => {
847
+ if (openNode === label) { setOpenNode(null); return }
848
+ setOpenNode(label)
849
+ if (notes[label] === undefined) {
850
+ try {
851
+ const r = await fetch(`/api/learning-space/node-note?topic=${encodeURIComponent(topic.name)}&node=${encodeURIComponent(label)}`)
852
+ const j = await r.json()
853
+ setNotes(prev => ({ ...prev, [label]: j.ok ? j.content : null }))
854
+ } catch { setNotes(prev => ({ ...prev, [label]: null })) }
855
+ }
856
+ }
857
+ return h('div', { className: 'ls-section' },
858
+ h('div', { className: 'ls-side-head', style: { marginBottom: 8 } },
859
+ h('span', { className: 'ls-h', style: { border: 'none', padding: 0, margin: 0 } }, '知识节点(点击看教学内容)')),
860
+ h('div', { className: 'ls-side-list' }, nodes.map(n => {
861
+ const label = n.label || n.id // 原始标签:fetch/匹配 notes 文件用
862
+ const disp = cleanLabel(label) // 显示用:去 <br/>
863
+ const open = openNode === label
864
+ const content = notes[label]
865
+ return h('div', { key: label, style: { marginBottom: 2 } },
866
+ h('div', {
867
+ className: 'ls-side-item' + (open ? ' active' : ''),
868
+ onClick: () => toggle(label),
869
+ style: { cursor: 'pointer' },
870
+ },
871
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR[n.status] || STATUS_COLOR.todo, flex: 'none' } }),
872
+ h('span', { className: 'ls-side-name' }, `${open ? '▾' : '▸'} ${disp}`)),
873
+ open ? h('div', {
874
+ className: 'ls-md-p',
875
+ style: { padding: '8px 10px 8px 24px', fontSize: 13, lineHeight: 1.8 },
876
+ },
877
+ content === undefined ? '加载中…'
878
+ : content === null ? '(读取失败,稍后再试)'
879
+ : content.trim() ? markdownLite(content)
880
+ : '(还没有这个节点的教学笔记——学到这里时 AI 会写入 notes/<节点>.md)')
881
+ : null,
882
+ )
883
+ })),
884
+ )
885
+ }
886
+
887
+ /** 专注学习页:左 = 教的知识(方案/学习记录/材料),右 = 问答对话窗,头部带返回 */
888
+ function StudyFocusView({ topic, onBack, onOpenInSession, onRefresh }) {
889
+ const [quizTick, setQuizTick] = useState(0)
890
+ const phase = topic.phase === 1 ? 1 : 2
891
+ const total = topic.nodes.length || topic.order.length || 0
892
+ const done = topic.counts.done || 0
893
+ const nodeStatus = new Map(topic.nodes.map(n => [n.label, n.status]))
894
+ return h('div', { className: 'ls-focus' },
895
+ h('div', { className: 'ls-focus-left' },
896
+ h('div', { className: 'ls-focus-head' },
897
+ h('button', { className: 'ls-btn', type: 'button', onClick: onBack }, '← 返回'),
898
+ h('span', { className: 'ls-focus-title', title: topic.name }, topic.name),
899
+ h('span', { className: 'ls-frac' }, `${done}/${total} 已确认`)),
900
+ h(NodeAccordion, { topic }),
901
+ h(MaterialList, { topic, onRefresh })),
902
+ h('div', { className: 'ls-focus-right' },
903
+ h(ChatWindow, {
904
+ key: `${topic.name}-${phase}`,
905
+ topic: topic.name,
906
+ phase,
907
+ sessionId: phase === 1 ? topic.phase1SessionId : topic.phase2SessionId,
908
+ onOpenInSession,
909
+ onQuizGraded: () => setQuizTick(t => t + 1),
910
+ })),
911
+ )
912
+ }
913
+
914
+ /** 左栏:新建入口 + 课程列表(进度摘要 + 状态色点 + 选中态) */
915
+ function TopicSidebar({ topics, selected, onSelect, onCreated, onDelete }) {
916
+ return h('div', { className: 'ls-side' },
917
+ h('div', { className: 'ls-side-head' },
918
+ h('span', { className: 'ls-h', style: { flex: 1 } }, '课程'),
919
+ topics.length ? h('a', {
920
+ className: 'ls-btn', href: '/api/learning-space/export?all=1', download: '',
921
+ style: { textDecoration: 'none', lineHeight: '20px' },
922
+ }, '导出全部') : null),
923
+ h(NewTopicForm, { onCreated }),
924
+ topics.length === 0
925
+ ? h('div', { className: 'ls-empty' }, '还没有课程')
926
+ : h('div', { className: 'ls-side-list' }, topics.map(t => {
927
+ const total = t.nodes.length || t.order.length || 0
928
+ const color = t.counts.warn > 0 ? STATUS_COLOR.warn
929
+ : t.counts.doing > 0 ? STATUS_COLOR.doing
930
+ : t.counts.done > 0 ? STATUS_COLOR.done : STATUS_COLOR.todo
931
+ return h('div', {
932
+ key: t.name,
933
+ className: 'ls-side-item' + (selected === t.name ? ' active' : ''),
934
+ onClick: () => onSelect(t.name),
935
+ },
936
+ h('span', { className: 'ls-dot', style: { background: color, flex: 'none' } }),
937
+ h('span', { className: 'ls-side-name' }, t.name),
938
+ h('span', { className: 'ls-side-frac' }, `${t.counts.done || 0}/${total}`),
939
+ h('button', {
940
+ className: 'ls-side-del', type: 'button', title: '删除课程',
941
+ onClick: e => { e.stopPropagation(); onDelete(t) },
942
+ }, '✕'))
943
+ })),
944
+ )
945
+ }
946
+
947
+ /** 删除课程确认弹窗:警告不可恢复,会话保留说明 */
948
+ function DeleteTopicDialog({ topic, busy, onCancel, onConfirm }) {
949
+ const total = topic.nodes.length || topic.order.length || 0
950
+ return h('div', { className: 'ls-modal-mask', onClick: busy ? undefined : onCancel },
951
+ h('div', { className: 'ls-modal', onClick: e => e.stopPropagation() },
952
+ h('div', { className: 'ls-modal-title' }, `删除课程「${topic.name}」?`),
953
+ h('div', { className: 'ls-modal-body' },
954
+ h('p', { style: { margin: '0 0 6px' } },
955
+ `当前进度 ${topic.counts.done || 0}/${total} 已确认,材料 ${((topic.materials) || []).length} 个。`),
956
+ h('p', { style: { margin: 0 } },
957
+ h('strong', null, '删除后学习计划、错题本、学习记录、答题记录和上传材料均不可恢复。'),
958
+ '摸底/学习会话会保留在会话列表中,可自行归档。')),
959
+ h('div', { className: 'ls-modal-actions' },
960
+ h('button', { className: 'ls-btn', type: 'button', disabled: busy, onClick: onCancel }, '取消'),
961
+ h('button', {
962
+ className: 'ls-btn ls-btn-danger', type: 'button', disabled: busy, onClick: onConfirm,
963
+ }, busy ? '删除中…' : '确认删除'))))
964
+ }
965
+
966
+ /**
967
+ * 模型设置弹窗:跟随宿主默认开关 + provider/model 级联下拉 + 立即应用勾选。
968
+ * 每次打开都重新 GET(目录按当前实况渲染);已存模型不在目录时回显跟默认态并提示。
969
+ */
970
+ function ModelSettingsDialog({ currentTopic, onClose }) {
971
+ const [catalog, setCatalog] = useState(undefined) // undefined=加载中 null=目录失败
972
+ const [catalogError, setCatalogError] = useState(null)
973
+ const [followDefault, setFollowDefault] = useState(true)
974
+ const [provider, setProvider] = useState('')
975
+ const [model, setModel] = useState('')
976
+ const [savedStale, setSavedStale] = useState(false) // 已存模型不在当前目录
977
+ const [applyNow, setApplyNow] = useState(false)
978
+ const [busy, setBusy] = useState(false)
979
+ const [err, setErr] = useState(null)
980
+ const [applyNotice, setApplyNotice] = useState(null)
981
+
982
+ useEffect(() => {
983
+ let alive = true
984
+ fetch('/api/learning-space/settings/model').then(r => r.json()).then(j => {
985
+ if (!alive) return
986
+ const cat = j.ok ? j.catalog : null
987
+ const savedSel = j.ok && j.saved ? j.saved.model : null
988
+ let follow = true, prov = '', mdl = '', stale = false
989
+ if (savedSel && cat && Array.isArray(cat.groups)) {
990
+ const g = cat.groups.find(x => x.id === savedSel.provider)
991
+ const m = g && (g.models || []).find(x => x.id === savedSel.model)
992
+ if (g && m) { follow = false; prov = g.id; mdl = m.id }
993
+ else stale = true // 已存选择不在当前目录:回显跟默认 + 提示
994
+ }
995
+ if (!follow && !prov && cat && Array.isArray(cat.groups) && cat.groups.length) {
996
+ prov = cat.groups[0].id
997
+ mdl = (cat.groups[0].models || [])[0] ? cat.groups[0].models[0].id : ''
998
+ }
999
+ setCatalog(cat || null)
1000
+ setCatalogError(j.ok ? (j.error || null) : (j.error || '加载失败'))
1001
+ setFollowDefault(follow); setProvider(prov); setModel(mdl); setSavedStale(stale)
1002
+ }).catch(e => { if (alive) { setCatalog(null); setCatalogError(String(e)) } })
1003
+ return () => { alive = false }
1004
+ }, [])
1005
+
1006
+ const groups = (catalog && Array.isArray(catalog.groups)) ? catalog.groups : []
1007
+ const group = groups.find(g => g.id === provider)
1008
+ const models = group ? (group.models || []) : []
1009
+
1010
+ const onProviderChange = id => {
1011
+ setProvider(id)
1012
+ const g = groups.find(x => x.id === id)
1013
+ setModel((g && (g.models || [])[0]) ? g.models[0].id : '')
1014
+ }
1015
+
1016
+ const save = async () => {
1017
+ if (busy) return
1018
+ setBusy(true); setErr(null); setApplyNotice(null)
1019
+ let sel = null
1020
+ if (!followDefault) {
1021
+ if (!provider || !model) { setErr('请先选择模型'); setBusy(false); return }
1022
+ sel = { provider, model }
1023
+ // effort 不做 UI:目录里该模型有 defaultEffort 就随保存带上
1024
+ const m = models.find(x => x.id === model)
1025
+ if (m && m.reasoning && m.reasoning.defaultEffort) sel.reasoningEffort = m.reasoning.defaultEffort
1026
+ }
1027
+ try {
1028
+ const r = await fetch('/api/learning-space/settings/model', {
1029
+ method: 'POST', headers: { 'content-type': 'application/json' },
1030
+ body: JSON.stringify({ model: sel,
1031
+ applyToTopic: applyNow && currentTopic ? currentTopic : undefined }),
1032
+ })
1033
+ const j = await r.json()
1034
+ if (!j.ok) { setErr(j.error || '保存失败'); return }
1035
+ if (j.applyError) { setApplyNotice(`已保存,但应用到会话失败:${j.applyError}`); return }
1036
+ onClose(true)
1037
+ } catch (e) { setErr(String(e)) }
1038
+ finally { setBusy(false) }
1039
+ }
1040
+
1041
+ const catalogDown = catalog === null
1042
+ return h('div', { className: 'ls-modal-mask', onClick: busy ? undefined : onClose },
1043
+ h('div', { className: 'ls-modal', onClick: e => e.stopPropagation() },
1044
+ h('div', { className: 'ls-modal-title' }, '模型设置'),
1045
+ h('div', { className: 'ls-modal-body' },
1046
+ catalog === undefined ? h('div', { className: 'ls-empty' }, '加载模型目录…') : [
1047
+ h('label', { key: 'follow', className: 'ls-set-check' },
1048
+ h('input', { type: 'checkbox', checked: followDefault,
1049
+ onChange: e => setFollowDefault(e.target.checked) }),
1050
+ '跟随宿主默认模型'),
1051
+ followDefault && catalog && catalog.default
1052
+ ? h('div', { key: 'def', className: 'ls-set-note' },
1053
+ `当前默认:${catalog.default.provider} / ${catalog.default.model}`)
1054
+ : null,
1055
+ h('label', { key: 'prov', className: 'ls-set-label' }, 'Provider'),
1056
+ h('select', {
1057
+ key: 'provsel', className: 'ls-select', value: provider,
1058
+ disabled: followDefault || catalogDown, onChange: e => onProviderChange(e.target.value),
1059
+ }, catalogDown ? null : groups.map(g =>
1060
+ h('option', { key: g.id, value: g.id }, g.name || g.id))),
1061
+ h('label', { key: 'mdl', className: 'ls-set-label' }, '模型'),
1062
+ h('select', {
1063
+ key: 'mdlsel', className: 'ls-select', value: model,
1064
+ disabled: followDefault || catalogDown || !provider, onChange: e => setModel(e.target.value),
1065
+ }, catalogDown ? null : models.map(m =>
1066
+ h('option', { key: m.id, value: m.id }, m.name || m.id))),
1067
+ h('label', { key: 'apply', className: 'ls-set-check' },
1068
+ h('input', { type: 'checkbox', checked: applyNow, disabled: !currentTopic,
1069
+ onChange: e => setApplyNow(e.target.checked) }),
1070
+ `同时应用到当前课程的学习会话${currentTopic ? `(${currentTopic})` : '(未选择课程)'}`),
1071
+ applyNow && followDefault
1072
+ ? h('div', { key: 'an', className: 'ls-set-note' }, '跟随默认不会改动已有会话。')
1073
+ : null,
1074
+ h('p', { key: 'doc', className: 'ls-set-note' },
1075
+ '选择会保存到项目根 .learning-space.json,新建的教学会话将使用该模型;',
1076
+ '宿主会同时把它记为部署默认偏好(DSH 设置里可改回)。'),
1077
+ savedStale ? h('div', { key: 'stale', className: 'ls-set-warn' }, '已保存的模型当前不可用,暂按跟随默认显示。') : null,
1078
+ catalogError ? h('div', { key: 'cerr', className: 'ls-set-warn' }, catalogError) : null,
1079
+ applyNotice ? h('div', { key: 'anotice', className: 'ls-set-warn' }, applyNotice) : null,
1080
+ err ? h('div', { key: 'err', className: 'ls-set-warn' }, err) : null,
1081
+ ]),
1082
+ h('div', { className: 'ls-modal-actions' },
1083
+ h('button', { className: 'ls-btn', type: 'button', disabled: busy, onClick: onClose }, '取消'),
1084
+ h('button', {
1085
+ className: 'ls-btn', type: 'button', disabled: busy || catalog === undefined,
1086
+ onClick: save,
1087
+ }, busy ? '保存中…' : '保存'))))
1088
+ }
1089
+
1090
+ /** 新建课程(可带文件):create 成功后紧接着对所选文件调上传,两步全成才算完成 */
1091
+ function NewTopicForm({ onCreated }) {
1092
+ const [name, setName] = useState('')
1093
+ const [goal, setGoal] = useState('')
1094
+ const [files, setFiles] = useState([])
1095
+ const [busy, setBusy] = useState(false)
1096
+ const [err, setErr] = useState(null)
1097
+ const fileRef = useRef(null)
1098
+ const submit = async e => {
1099
+ e.preventDefault()
1100
+ const t = name.trim()
1101
+ if (!t || busy) return
1102
+ setBusy(true); setErr(null)
1103
+ try {
1104
+ // 第一步:建课
1105
+ const r = await fetch('/api/learning-space/topic/create', {
1106
+ method: 'POST', headers: { 'content-type': 'application/json' },
1107
+ body: JSON.stringify({ topic: t, goal: goal.trim() }),
1108
+ })
1109
+ const j = await r.json()
1110
+ if (!j.ok) { setErr(j.error || '创建失败'); return }
1111
+ // 第二步:对所选文件上传(失败有补救路径:课程已建成,详情区可再导入)
1112
+ if (files.length) {
1113
+ try { await uploadFiles(t, files) }
1114
+ catch (e2) { setErr(`课程已创建,但材料上传失败:${e2.message || e2}`) }
1115
+ }
1116
+ setName(''); setGoal(''); setFiles([])
1117
+ onCreated(t)
1118
+ } catch (e2) { setErr(String(e2)) }
1119
+ finally { setBusy(false) }
1120
+ }
1121
+ return h('form', { className: 'ls-new', onSubmit: submit, style: { flexDirection: 'column' } },
1122
+ err ? h('div', { className: 'ls-upload-err' }, err) : null,
1123
+ h('input', { className: 'ls-input', placeholder: '课程名,如:傅里叶变换', value: name,
1124
+ onChange: e => setName(e.target.value) }),
1125
+ h('input', { className: 'ls-input', placeholder: '学习目标(可选)', value: goal,
1126
+ onChange: e => setGoal(e.target.value) }),
1127
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
1128
+ h(FilePickButton, {
1129
+ onFiles: fl => setFiles(prev => [...prev, ...Array.from(fl)]),
1130
+ disabled: busy, label: files.length ? `+ 追加材料(${files.length})` : '+ 附带材料',
1131
+ }),
1132
+ h('button', { className: 'ls-btn', type: 'submit', disabled: busy || !name.trim() },
1133
+ busy ? '创建中…' : '+ 新建课程'),
1134
+ ),
1135
+ files.length ? h('div', { className: 'ls-picked' }, files.map((f, i) =>
1136
+ h('div', { key: `${f.name}${i}`, className: 'ls-picked-item' },
1137
+ h('span', null, `${f.name}(${fmtSize(f.size)})`),
1138
+ h('button', {
1139
+ className: 'ls-picked-x', type: 'button', title: '移除',
1140
+ onClick: () => setFiles(prev => prev.filter((_, j) => j !== i)),
1141
+ }, '×')),
1142
+ )) : null,
1143
+ )
1144
+ }
1145
+
1146
+ function LearningPanel() {
1147
+ const [data, setData] = useState(null)
1148
+ const [error, setError] = useState(null)
1149
+ const [selectedTopic, setSelectedTopic] = useState(null)
1150
+ const [starting, setStarting] = useState(null)
1151
+ const [chatTopic, setChatTopic] = useState(null)
1152
+ // 待删除课程 { name, topic, busy },非空时渲染确认弹窗
1153
+ const [deleting, setDeleting] = useState(null)
1154
+ // 专注学习页:课程名非空时整面板切换为左知识右问答视图
1155
+ const [studyView, setStudyView] = useState(null)
1156
+ // 模型设置弹窗:非空时渲染 ModelSettingsDialog
1157
+ const [modelSettings, setModelSettings] = useState(false)
1158
+
1159
+ const load = useCallback(() => {
1160
+ fetch('/api/learning-space/overview').then(r => r.json())
1161
+ .then(j => { if (j.ok) { setData(j); setError(null) } else setError(j.error) })
1162
+ .catch(e => setError(String(e)))
1163
+ }, [])
1164
+ useEffect(() => { load(); const t = setInterval(load, 15000); return () => clearInterval(t) }, [load])
1165
+
1166
+ // 默认选中第一门课;已选课程被删则回退
1167
+ useEffect(() => {
1168
+ if (data && data.topics.length) {
1169
+ if (!selectedTopic || !data.topics.some(t => t.name === selectedTopic)) {
1170
+ setSelectedTopic(data.topics[0].name)
1171
+ }
1172
+ } else if (selectedTopic !== null) setSelectedTopic(null)
1173
+ }, [data])
1174
+
1175
+ // rebind=true:抛弃旧绑定强制新建会话并重注 seed(「重新学习」用;旧会话保留在会话列表)
1176
+ const startLearning = useCallback(async (topic, phase, rebind) => {
1177
+ setStarting(topic)
1178
+ try {
1179
+ const r = await fetch('/api/learning-space/session/start', {
1180
+ method: 'POST',
1181
+ headers: { 'content-type': 'application/json' },
1182
+ body: JSON.stringify(rebind ? { topic, phase, rebind: true } : { topic, phase }),
1183
+ })
1184
+ const j = await r.json()
1185
+ if (j.ok && j.sessionId) {
1186
+ setSelectedTopic(topic) // 切到该课程详情
1187
+ setChatTopic(topic) // 详情区展开内嵌对话窗(单窗互斥;窗内按 topic.phase 路由)
1188
+ setStudyView(topic) // 直接进入专注学习页(左知识右问答,可返回)
1189
+ load()
1190
+ } else setError(j.error || '创建会话失败')
1191
+ } catch (e) { setError(String(e)) }
1192
+ finally { setStarting(null) }
1193
+ }, [load])
1194
+
1195
+ // 联网开关:只改 session.json 的 webSearch 字段(对下一次新建会话生效)
1196
+ const toggleWebSearch = useCallback(async (topic, enabled) => {
1197
+ try {
1198
+ const r = await fetch('/api/learning-space/session/websearch', {
1199
+ method: 'POST',
1200
+ headers: { 'content-type': 'application/json' },
1201
+ body: JSON.stringify({ topic, enabled }),
1202
+ })
1203
+ const j = await r.json()
1204
+ if (!j.ok) setError(j.error || '设置失败')
1205
+ else load()
1206
+ } catch (e) { setError(String(e)) }
1207
+ }, [load])
1208
+
1209
+ // 删除课程:确认后调 /topic/delete,成功后刷新并清掉选中/对话窗状态
1210
+ const confirmDeleteTopic = useCallback(async () => {
1211
+ if (!deleting) return
1212
+ setDeleting(d => ({ ...d, busy: true }))
1213
+ try {
1214
+ const r = await fetch('/api/learning-space/topic/delete', {
1215
+ method: 'POST',
1216
+ headers: { 'content-type': 'application/json' },
1217
+ body: JSON.stringify({ topic: deleting.name }),
1218
+ })
1219
+ const j = await r.json()
1220
+ if (j.ok) {
1221
+ setDeleting(null)
1222
+ if (selectedTopic === deleting.name) { setSelectedTopic(null); setChatTopic(null) }
1223
+ load()
1224
+ } else setError(j.error || '删除失败')
1225
+ } catch (e) { setError(String(e)) }
1226
+ finally { setDeleting(d => d && { ...d, busy: false }) }
1227
+ }, [deleting, selectedTopic, load])
1228
+
1229
+ const selected = data && data.topics.find(t => t.name === selectedTopic)
1230
+ // 专注学习页:课程还在就整面板切换(overview 刷新后 topic 对象取最新)
1231
+ const studyTopic = studyView && data ? data.topics.find(t => t.name === studyView) : null
1232
+ if (studyTopic) return h('div', { className: 'ls-panel' },
1233
+ h('style', null, css),
1234
+ error ? h('div', { className: 'ls-empty' }, `出错:${error}`) : null,
1235
+ h(StudyFocusView, {
1236
+ topic: studyTopic,
1237
+ onBack: () => setStudyView(null),
1238
+ onOpenInSession: sid => panelCtx && panelCtx.uiWorkspace && panelCtx.uiWorkspace.openSession(sid),
1239
+ onRefresh: load,
1240
+ }),
1241
+ )
1242
+ return h('div', { className: 'ls-panel' },
1243
+ h('style', null, css),
1244
+ h('div', { className: 'ls-title-row' },
1245
+ h('h1', { className: 'ls-title' }, '学习空间'),
1246
+ h('button', {
1247
+ className: 'ls-gear', type: 'button', 'aria-label': '模型设置', title: '模型设置',
1248
+ onClick: () => setModelSettings(true),
1249
+ }, '⚙')),
1250
+ h('p', { className: 'ls-sub' }, '左侧管理课程,右侧看进度、依赖图和错题,材料可导入给教学会话'),
1251
+ error ? h('div', { className: 'ls-empty' }, `出错:${error}`) : null,
1252
+ !data && !error ? h('div', { className: 'ls-loading' }, '加载中…') : null,
1253
+ data ? h('div', { className: 'ls-layout' },
1254
+ h(TopicSidebar, {
1255
+ topics: data.topics,
1256
+ selected: selectedTopic,
1257
+ onSelect: name => setSelectedTopic(name),
1258
+ onCreated: name => { setSelectedTopic(name); load() },
1259
+ onDelete: t => setDeleting({ name: t.name, topic: t, busy: false }),
1260
+ }),
1261
+ selected
1262
+ ? h(TopicDetail, {
1263
+ key: selected.name,
1264
+ topic: selected,
1265
+ starting: starting === selected.name,
1266
+ chat: chatTopic === selected.name,
1267
+ onStart: startLearning,
1268
+ onToggleWebSearch: toggleWebSearch,
1269
+ onOpenInSession: sid => panelCtx && panelCtx.uiWorkspace && panelCtx.uiWorkspace.openSession(sid),
1270
+ onRefresh: load,
1271
+ })
1272
+ : h('div', { className: 'ls-empty' }, '在左侧新建或选择一门课程'),
1273
+ ) : null,
1274
+ data && data.journal.length ? h('div', { className: 'ls-section' },
1275
+ h('div', { className: 'ls-h' }, '最近日志'),
1276
+ data.journal.map((line, i) => h('div', { key: i, className: 'ls-journal-item' }, line)),
1277
+ ) : null,
1278
+ deleting ? h(DeleteTopicDialog, {
1279
+ topic: deleting.topic,
1280
+ busy: deleting.busy,
1281
+ onCancel: () => { if (!deleting.busy) setDeleting(null) },
1282
+ onConfirm: confirmDeleteTopic,
1283
+ }) : null,
1284
+ modelSettings ? h(ModelSettingsDialog, {
1285
+ currentTopic: selectedTopic,
1286
+ onClose: () => setModelSettings(false),
1287
+ }) : null,
1288
+ )
1289
+ }
1290
+
1291
+ let panelCtx = null
1292
+ return {
1293
+ inject: ['slots', 'uiWorkspace'],
1294
+ apply(ctx) {
1295
+ panelCtx = ctx
1296
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register(
1297
+ { name: 'sidebar.panellist', id: 'learning-space', order: 60, label: '学习空间' },
1298
+ PanelIcon))
1299
+ ctx.slots.inject('main', () => ctx.slots.register(
1300
+ { name: 'main', key: 'learning-space' },
1301
+ LearningPanel))
1302
+ },
1303
+ }
1304
+ },
1305
+ })