dsh-study-tools 0.0.0-stage → 0.2.6

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/src/client.js ADDED
@@ -0,0 +1,1718 @@
1
+ /**
2
+ * Client 半边:把模型输出的 ```ds_tools 块渲染成可作答的卡片,
3
+ * 提供会话独立的答题、代码编辑与要求栏。公式输入由独立插件提供。
4
+ *
5
+ * 浏览器里没有 JSX 和打包工具,全部用 React.createElement 手写。
6
+ */
7
+ window.__ModuleLoader__.load({
8
+ id: 'dsh-study-tools',
9
+ factory(require) {
10
+ const React = require('react')
11
+ const { createPortal } = require('react-dom')
12
+ const h = React.createElement
13
+ const { useState, useMemo, useCallback, useEffect, useRef, useLayoutEffect, useSyncExternalStore } = React
14
+ const quizStyles = /* QUIZ_STYLES */ ''
15
+
16
+ function createComponents(){
17
+ const OK = 'var(--dsw-alias-state-business-primary, #16a34a)'
18
+ const BAD = 'var(--dsw-alias-state-error-primary, #dc2626)'
19
+ const THIN = 'var(--dsw-alias-border-l2, rgba(0,0,0,.12))'
20
+ const TEXT = 'var(--dsw-alias-label-primary, #1f2328)'
21
+ const SOFT = 'var(--dsw-alias-label-secondary, #57606a)'
22
+ const FAINT = 'var(--dsw-alias-label-tertiary, #8c959f)'
23
+ const CARD = 'var(--dsw-alias-bg-layer-1, rgba(0,0,0,.02))'
24
+ const CODE_BG = 'var(--dsw-alias-markdown-code-block, rgba(0,0,0,.06))'
25
+
26
+ /* ------------------------------------------------------------------ *
27
+ * 1. 输入文本 → LaTeX(从 input-math.js 移植,去掉符号面板)
28
+ * ------------------------------------------------------------------ */
29
+
30
+ const LATEX_WORDS = new Set((
31
+ 'frac dfrac tfrac cfrac sqrt sum prod int iint oint lim log ln exp sin cos tan cot sec csc '
32
+ + 'arcsin arccos arctan sinh cosh tanh max min sup inf '
33
+ + 'alpha beta gamma delta epsilon varepsilon zeta eta theta vartheta iota kappa lambda mu '
34
+ + 'nu xi pi varpi rho varrho sigma varsigma tau upsilon phi varphi chi psi omega '
35
+ + 'Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega '
36
+ + 'times div cdot cdots ldots dots pm mp le leq ge geq ne neq approx sim simeq equiv cong propto '
37
+ + 'partial nabla infty in setminus cup cap subset supset subseteq supseteq emptyset '
38
+ + 'to rightarrow leftarrow Rightarrow Leftarrow leftrightarrow mapsto '
39
+ + 'left right big Big bigl bigr langle rangle lvert rvert lfloor rfloor lceil rceil '
40
+ + 'text textbf textit mathrm mathbf mathit mathbb mathcal operatorname '
41
+ + 'bar overline underline hat widehat vec dot ddot tilde widetilde '
42
+ + 'quad qquad hspace vspace '
43
+ + 'begin end over choose binom pmod bmod '
44
+ + 'deg angle triangle perp parallel mid forall exists neg land lor implies iff '
45
+ + 'prime circ bullet star ast '
46
+ ).split(/\s+/).filter(Boolean))
47
+
48
+ /** 把被 JSON 当成合法转义的 LaTeX 命令(\frac 的 \f、\theta 的 \t)补成双反斜杠。 */
49
+ function escapeLatexCommands(text) {
50
+ return text.replace(/(?<!\\)\\([A-Za-z]{2,20}|[,;:!])/g, (match, name) => (
51
+ name.length === 1 || LATEX_WORDS.has(name) ? `\\\\${name}` : match
52
+ ))
53
+ }
54
+
55
+ function repairJson(text) {
56
+ const out = text.replace(/\\(?![\\"/bfnrtu])/g, '\\\\')
57
+ return escapeLatexCommands(out)
58
+ }
59
+
60
+ function countControl(value) {
61
+ let count = 0
62
+ const walk = (node) => {
63
+ if (typeof node === 'string') {
64
+ for (const ch of node) if (ch.charCodeAt(0) < 32) count += 1
65
+ return
66
+ }
67
+ if (Array.isArray(node)) {
68
+ for (const item of node) walk(item)
69
+ return
70
+ }
71
+ if (node !== null && typeof node === 'object') {
72
+ for (const key of Object.keys(node)) walk(node[key])
73
+ }
74
+ }
75
+ walk(value)
76
+ return count
77
+ }
78
+
79
+ function tryParse(text) {
80
+ try {
81
+ const parsed = JSON.parse(text)
82
+ if (Array.isArray(parsed)) return parsed
83
+ if (parsed && Array.isArray(parsed.ds_tools)) return parsed.ds_tools
84
+ if (parsed && typeof parsed === 'object' && typeof parsed.type === 'string') return [parsed]
85
+ } catch {
86
+ // 交给修版重试
87
+ }
88
+ return null
89
+ }
90
+
91
+ /**
92
+ * 解析 ds_tools 块。JSON.parse 会把 "\frac" 吃成换页符,所以只要结果里
93
+ * 出现控制字符,就改用转义修版再 parse 一次。
94
+ */
95
+ function parseTools(code) {
96
+ const body = String(code ?? '').trim()
97
+ if (body === '') return null
98
+ const plain = tryParse(body)
99
+ if (plain !== null && countControl(plain) === 0) return plain
100
+ const repaired = tryParse(repairJson(body))
101
+ if (repaired !== null && (plain === null || countControl(repaired) < countControl(plain))) return repaired
102
+ return plain
103
+ }
104
+
105
+ /* ------------------------------------------------------------------ *
106
+ * 3. 富文本(题干/选项/解析)
107
+ * ------------------------------------------------------------------ */
108
+
109
+ const RichText = React.memo(function RichText({ value, style }) {
110
+ return h('span', {
111
+ onDoubleClick: event => {
112
+ const code = event.target.closest('pre,code')
113
+ if (code) navigator.clipboard.writeText(code.textContent).catch(() => {})
114
+ },
115
+ dangerouslySetInnerHTML: { __html: runtime.DSWTQuizText.html(value, style) },
116
+ })
117
+ })
118
+
119
+ function renderRich(value,style,key){
120
+ return h(RichText, { key, value: String(value ?? ''), style })
121
+ }
122
+
123
+ /* ------------------------------------------------------------------ *
124
+ * 3.5 LaTeX → MathML(Chromium 原生渲染,不依赖 KaTeX)
125
+ * ------------------------------------------------------------------ */
126
+
127
+ const cardStyle = {
128
+ marginTop: '10px',
129
+ padding: '14px 16px',
130
+ border: `1px solid ${THIN}`,
131
+ borderRadius: '12px',
132
+ background: CARD,
133
+ display: 'flex',
134
+ flexDirection: 'column',
135
+ gap: '10px',
136
+ }
137
+
138
+ const buttonStyle = (active, positive) => ({
139
+ padding: '8px 14px',
140
+ borderRadius: '8px',
141
+ border: `1px solid ${active ? (positive ? OK : 'var(--dsw-alias-label-secondary, #57606a)') : THIN}`,
142
+ background: active ? (positive ? 'rgba(22,163,74,.10)' : 'var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,.05))') : 'transparent',
143
+ color: TEXT,
144
+ cursor: 'pointer',
145
+ font: 'inherit',
146
+ textAlign: 'left',
147
+ })
148
+
149
+ function Badge({ tone, children }) {
150
+ return h(
151
+ 'span',
152
+ {
153
+ style: {
154
+ fontSize: '12px',
155
+ fontWeight: 600,
156
+ color: tone === 'ok' ? OK : tone === 'bad' ? BAD : SOFT,
157
+ background: tone === 'ok' ? 'rgba(22,163,74,.10)' : tone === 'bad' ? 'rgba(220,38,38,.10)' : 'transparent',
158
+ borderRadius: '999px',
159
+ padding: '1px 8px',
160
+ whiteSpace: 'nowrap',
161
+ },
162
+ },
163
+ children,
164
+ )
165
+ }
166
+
167
+ function StarButton({ on, onClick }) {
168
+ return h(
169
+ 'button',
170
+ {
171
+ type: 'button',
172
+ onClick,
173
+ title: on ? '取消收藏' : '收藏这题',
174
+ 'aria-pressed': on ? 'true' : 'false',
175
+ className: 'dsh-study-star',
176
+ },
177
+ on ? '★' : '☆',
178
+ )
179
+ }
180
+
181
+ function externalImageUrl(value) {
182
+ if (typeof value !== 'string' || !/^https:\/\//i.test(value)) return null
183
+ try {
184
+ const url = new URL(value)
185
+ return url.protocol === 'https:' && !url.username && !url.password ? url : null
186
+ } catch { return null }
187
+ }
188
+
189
+ function openExternalMedia(href) {
190
+ window.open(href, '_blank', 'noopener,noreferrer')
191
+ }
192
+
193
+ function RemoteImage({ url, alt }) {
194
+ const [state, setState] = useState('idle')
195
+ return h('div', { style: { display: 'grid', gap: '6px', margin: '8px 0' } },
196
+ h('div', { style: { color: SOFT, fontSize: '13px', overflowWrap: 'anywhere' } },
197
+ '外部图片:', h('bdi', null, url.host), alt ? ` · ${alt}` : ''),
198
+ state === 'visible'
199
+ ? h('img', {
200
+ src: url.href,
201
+ alt,
202
+ referrerPolicy: 'no-referrer',
203
+ onError: () => setState('failed'),
204
+ style: { maxWidth: '100%', borderRadius: '8px', border: `1px solid ${THIN}` },
205
+ })
206
+ : h('button', { type: 'button', style: buttonStyle(false), onClick: () => setState('visible') },
207
+ state === 'failed' ? '重试加载这张图片' : '加载这张图片'),
208
+ state === 'failed' ? h('div', { role: 'status', style: { color: SOFT } }, '图片加载失败;也可以在浏览器打开原图。') : null,
209
+ h('button', { type: 'button', style: buttonStyle(false), onClick: () => openExternalMedia(url.href) }, '在浏览器打开原图'),
210
+ )
211
+ }
212
+
213
+ function MediaBox({ descriptor }) {
214
+ if (descriptor === null || typeof descriptor !== 'object') return null
215
+ const url = externalImageUrl(descriptor.url)
216
+ if (url) {
217
+ // Consent belongs only to this rendered item and URL, not a whole card or session.
218
+ return h(RemoteImage, { key: url.href, url, alt: String(descriptor.alt ?? '') })
219
+ }
220
+ if (typeof descriptor.prompt === 'string' && descriptor.prompt.trim() !== '') {
221
+ return h(
222
+ 'div',
223
+ {
224
+ style: {
225
+ border: `1px dashed ${THIN}`,
226
+ borderRadius: '8px',
227
+ padding: '10px 12px',
228
+ color: FAINT,
229
+ fontSize: '13px',
230
+ lineHeight: 1.6,
231
+ },
232
+ },
233
+ h('div', { style: { fontWeight: 600, marginBottom: '2px' } }, '画面描述(本发行未启用生图)'),
234
+ descriptor.prompt,
235
+ )
236
+ }
237
+ return descriptor.url != null ? h('span', { style: { color: SOFT } }, '图片地址不是有效的 HTTPS 链接。') : null
238
+ }
239
+
240
+ /* ------------------------------------------------------------------ *
241
+ * 5. 题库:共享状态仓(行内卡片与右侧抽屉读同一份)
242
+ * ------------------------------------------------------------------ */
243
+
244
+ const BOOKMARK_KEY = 'dsh-quiz-bookmarks-v1'
245
+ const EMPTY_ANSWER = { picked: -1, filled: '', fillResult: null, loose: null }
246
+
247
+ function loadBookmarks() {
248
+ try {
249
+ const raw = window.localStorage.getItem(BOOKMARK_KEY)
250
+ const parsed = raw === null ? null : JSON.parse(raw)
251
+ if (!Array.isArray(parsed)) return []
252
+ return parsed.filter((item) => item !== null && typeof item === 'object')
253
+ } catch (error) {
254
+ return []
255
+ }
256
+ }
257
+
258
+ function saveBookmarks(list) {
259
+ try {
260
+ window.localStorage.setItem(BOOKMARK_KEY, JSON.stringify(list.slice(-240)))
261
+ } catch (error) {
262
+ // 隐私模式或配额不足时放弃持久化,不影响本次答题
263
+ }
264
+ }
265
+
266
+ function textHash(text) {
267
+ let hash = 0
268
+ const source = String(text ?? '')
269
+ for (let index = 0; index < source.length; index += 1) hash = (hash * 31 + source.charCodeAt(index)) | 0
270
+ return (hash >>> 0).toString(36)
271
+ }
272
+
273
+ function createQuizState() {
274
+ return {
275
+ batches: [],
276
+ states: {},
277
+ reports: {},
278
+ autoReview: {},
279
+ bookmarks: loadBookmarks(),
280
+ openId: null,
281
+ tab: 'all',
282
+ libraryOpen: false,
283
+ cursor: 0,
284
+ }
285
+ }
286
+
287
+ function quizPatch(values) {
288
+ store.patch({ quiz: { ...store.quiz, ...values } })
289
+ }
290
+
291
+ function answerOf(stateKey) {
292
+ const saved = store.quiz.states[stateKey]
293
+ return saved === undefined ? EMPTY_ANSWER : saved
294
+ }
295
+
296
+ function setAnswer(stateKey, values) {
297
+ const current = answerOf(stateKey)
298
+ const states = { ...store.quiz.states }
299
+ states[stateKey] = { ...current, ...values }
300
+ if (!stateKey.startsWith('review:') && (current.picked !== states[stateKey].picked || current.fillResult !== states[stateKey].fillResult)) {
301
+ // A changed assessment answer invalidates any practice for that question.
302
+ delete states['review:' + stateKey]
303
+ }
304
+ quizPatch({ states })
305
+ }
306
+
307
+ function registerBatch(id, items) {
308
+ if (store.quiz.batches.some((batch) => batch.id === id)) return
309
+ quizPatch({ batches: [...store.quiz.batches, { id, items }] })
310
+ }
311
+
312
+ function batchOf(id) {
313
+ return store.quiz.batches.find((batch) => batch.id === id) ?? null
314
+ }
315
+
316
+ const bookmarkKeys = new WeakMap()
317
+ function itemKeyOf(spec) {
318
+ if (!bookmarkKeys.has(spec)) {
319
+ const options = Array.isArray(spec.options) ? spec.options.join('|') : ''
320
+ bookmarkKeys.set(spec, textHash(`${spec.type}|${spec.question}|${options}`))
321
+ }
322
+ return bookmarkKeys.get(spec)
323
+ }
324
+
325
+ function toggleBookmark(spec, stateKey, wanted) {
326
+ const key = itemKeyOf(spec)
327
+ const list = [...store.quiz.bookmarks]
328
+ const at = list.findIndex((item) => item.key === key)
329
+ if (wanted === (at >= 0)) return
330
+ if (at >= 0) {
331
+ list.splice(at, 1)
332
+ } else {
333
+ const state = answerOf(stateKey)
334
+ list.push({
335
+ key,
336
+ type: String(spec.type ?? 'quiz'),
337
+ question: spec.question,
338
+ question_style: spec.question_style,
339
+ options: spec.options,
340
+ answer: spec.answer,
341
+ answers: spec.answers,
342
+ explanation: spec.explanation,
343
+ image: spec.image,
344
+ optionImages: spec.optionImages,
345
+ picked: state.picked,
346
+ filled: state.filled,
347
+ correct: verdictOf(spec, state),
348
+ savedAt: Date.now(),
349
+ })
350
+ }
351
+ quizPatch({ bookmarks: list })
352
+ saveBookmarks(list)
353
+ }
354
+
355
+ function verdictOf(spec, state) {
356
+ if (spec.type === 'fill') {
357
+ return state.fillResult === 'ok' ? true : state.fillResult === 'bad' ? false : null
358
+ }
359
+ const count = Array.isArray(spec.options) ? spec.options.length : 0
360
+ const answer = Number.isInteger(spec.answer) ? spec.answer : -1
361
+ if (state.picked < 0 || state.picked >= count || answer < 0 || answer >= count) return null
362
+ return state.picked === answer
363
+ }
364
+
365
+ function optionText(option) {
366
+ return typeof option === 'object' ? String(option?.text ?? option?.label ?? '') : String(option ?? '')
367
+ }
368
+
369
+ function pickOption(stateKey, index) {
370
+ if (answerOf(stateKey).picked !== index) setAnswer(stateKey, { picked: index })
371
+ }
372
+
373
+ const QuizCounts = React.createContext(null)
374
+ const QuizNavigation = React.createContext(null)
375
+
376
+ function QuestionHeading({ number, spec, starred, onStar }) {
377
+ return h('div', { className: 'dsh-study-card-head' },
378
+ h('span', { className: 'dsh-study-card-number', 'aria-hidden': true }, number),
379
+ h('div', { className: 'dsh-study-stem' }, renderRich(spec.question, spec.question_style), h(QuestionMedia, { spec })),
380
+ h(StarButton, { on: starred, onClick: onStar }))
381
+ }
382
+
383
+ function QuestionStats() {
384
+ const counts = React.useContext(QuizCounts)
385
+ if (!counts) return null
386
+ return h('div', { className: 'dsh-study-metrics' },
387
+ h(StatCell, { label: '已答', value: counts.answered }),
388
+ h(StatCell, { label: '正确', value: counts.right }),
389
+ h(StatCell, { label: '错题', value: counts.wrong }))
390
+ }
391
+
392
+ function QuestionTools({ stateKey, options, fill }) {
393
+ const navigation = React.useContext(QuizNavigation)
394
+ if (!navigation) return null
395
+ const at = navigation.positions.get(stateKey)
396
+ return h(React.Fragment, null,
397
+ h('div', { className: 'dsh-study-nav' },
398
+ h('button', { type: 'button', className: 'dsh-study-control', 'data-step': 'prev',
399
+ disabled: at <= 0, onClick: () => navigation.move(-1, stateKey) }, '↑ 上一题'),
400
+ h('button', { type: 'button', className: 'dsh-study-control', 'data-step': 'next',
401
+ disabled: at >= navigation.positions.size - 1, onClick: () => navigation.move(1, stateKey) }, '↓ 下一题'),
402
+ !navigation.inLibrary ? h('button', { type: 'button', className: 'dsh-study-control',
403
+ onClick: () => navigation.openLibrary(at) }, '题库 / 错题 / 复盘') : null),
404
+ h('p', { className: 'dsh-study-keys' }, fill
405
+ ? '↑↓ 切题 · Enter 检查'
406
+ : options <= 4 ? '↑↓ 切题 · 数字键选答案 · 5 收藏 / 6 取消'
407
+ : '↑↓ 切题 · 数字键选答案 · B 收藏 / 取消'))
408
+ }
409
+
410
+ function Explanation({ value, style, initiallyOpen = false }) {
411
+ const [open, setOpen] = useState(initiallyOpen)
412
+ return String(value ?? '').trim() ? h('details', {
413
+ className: 'dsh-study-explanation', open,
414
+ onToggle: event => setOpen(event.currentTarget.open),
415
+ },
416
+ h('summary', null, '解析'),
417
+ h('div', { className: 'dsh-study-explanation-body' },
418
+ h('div', { className: 'dsh-study-explanation-text' }, renderRich(value, style)))) : null
419
+ }
420
+
421
+ const QuizCard = React.memo(function QuizCard({ spec, stateKey, state, number, starred }) {
422
+ const options = useMemo(() => (Array.isArray(spec.options) ? spec.options : []).map((option, index) => ({
423
+ text: optionText(option),
424
+ media: {
425
+ ...(option && typeof option === 'object' ? option : {}),
426
+ image: spec.optionImages?.[index] ?? option?.image,
427
+ plot: spec.optionPlots?.[index] ?? option?.plot,
428
+ table: spec.optionTables?.[index] ?? option?.table,
429
+ media: spec.optionMedia?.[index] ?? option?.media,
430
+ },
431
+ })), [spec])
432
+ const answer = Number.isInteger(spec.answer) ? spec.answer : -1
433
+ const style = spec.question_style
434
+ const picked = state.picked
435
+
436
+ const verdict = verdictOf(spec, state)
437
+ const settled = verdict !== null
438
+
439
+ return h(
440
+ 'article',
441
+ { className: 'dsh-study-card', 'data-bookmarked': starred || undefined },
442
+ h(QuestionHeading, { number, spec, starred, onStar: () => toggleBookmark(spec, stateKey) }),
443
+ h(QuestionStats),
444
+ h(
445
+ 'div',
446
+ { className: 'dsh-study-options' },
447
+ options.map((option, index) => {
448
+ const right = settled && index === answer
449
+ const wrong = settled && index === picked && index !== answer
450
+ return h(
451
+ 'div',
452
+ { key: index, className: 'dsh-study-option-group' },
453
+ h(
454
+ 'button',
455
+ {
456
+ type: 'button',
457
+ className: 'dsh-study-option',
458
+ 'aria-pressed': picked === index,
459
+ 'data-tone': right ? 'correct' : wrong ? 'wrong' : undefined,
460
+ onClick: () => pickOption(stateKey, index),
461
+ },
462
+ h('span', { className: 'dsh-study-option-letter' }, String.fromCharCode(65 + index)),
463
+ h('span', { className: 'dsh-study-option-caption' }, renderRich(option.text, style)),
464
+ h('span', { className: 'dsh-study-option-mark', 'aria-hidden': true },
465
+ picked === index && settled ? (verdict ? '✅' : '❌') : ''),
466
+ ),
467
+ h(QuestionMedia, { spec: option.media }),
468
+ )
469
+ }),
470
+ ),
471
+ settled ? h('div', { role: 'status', className: 'dsh-study-result', 'data-tone': verdict ? 'correct' : 'wrong' },
472
+ verdict ? '✅ 答对了' : '❌ 答错了',
473
+ !verdict
474
+ ? h('span', null, `正确答案:${String.fromCharCode(65 + answer)}`)
475
+ : null,
476
+ ) : null,
477
+ settled ? h(Explanation, { key: picked, value: spec.explanation, style, initiallyOpen: !verdict }) : null,
478
+ h(QuestionTools, { stateKey, options: options.length }),
479
+ )
480
+ })
481
+
482
+ function normalizeAnswer(value, loose) {
483
+ let text = String(value ?? '').trim().toLowerCase()
484
+ if (loose) text = text.replace(/\s+/g, '').replace(/[.,;:!?'"`~()[\]{},。;:!?、""''()【】《》]/g, '')
485
+ else text = text.replace(/\s+/g, ' ')
486
+ return text
487
+ }
488
+
489
+ function checkFill(spec, stateKey) {
490
+ const { filled, loose } = answerOf(stateKey)
491
+ if (!filled.trim()) return false
492
+ const answers = Array.isArray(spec.answers) ? spec.answers : []
493
+ const target = normalizeAnswer(filled, loose === true)
494
+ const result = answers.length
495
+ ? answers.some(answer => normalizeAnswer(answer, loose === true) === target) ? 'ok' : 'bad'
496
+ : 'unknown'
497
+ setAnswer(stateKey, { fillResult: result })
498
+ return true
499
+ }
500
+
501
+ const FillCard = React.memo(function FillCard({ spec, stateKey, state, number, starred }) {
502
+ const reference = Array.isArray(spec.answers) ? spec.answers[0] : undefined
503
+ const style = spec.question_style
504
+ const draft = state.filled
505
+ const loose = state.loose === true
506
+ const result = state.fillResult
507
+
508
+ return h(
509
+ 'article',
510
+ { className: 'dsh-study-card', 'data-bookmarked': starred || undefined },
511
+ h(QuestionHeading, { number, spec, starred, onStar: () => toggleBookmark(spec, stateKey) }),
512
+ h(QuestionStats),
513
+ h(
514
+ 'div',
515
+ { className: 'dsh-study-fill-row' },
516
+ h('input', {
517
+ value: draft,
518
+ placeholder: '输入答案,按 Enter 检查',
519
+ 'aria-label': '填写答案',
520
+ className: 'dsh-study-fill-field',
521
+ 'data-tone': result === 'ok' ? 'correct' : result === 'bad' ? 'wrong' : undefined,
522
+ 'data-dsh-quiz-fill': '',
523
+ onChange: (event) => setAnswer(stateKey, { filled: event.target.value, fillResult: null }),
524
+ onKeyDown: (event) => {
525
+ if (event.key !== 'Enter' || event.nativeEvent.isComposing || event.keyCode === 229) return
526
+ event.preventDefault()
527
+ event.stopPropagation()
528
+ const question = event.currentTarget.closest('[data-dsh-quiz-question]')
529
+ if (checkFill(spec, stateKey)) question?.focus({ preventScroll: true })
530
+ },
531
+ }),
532
+ h('label', { className: 'dsh-study-mode' }, '判断模式',
533
+ h('select', {
534
+ value: loose ? 'loose' : 'strict',
535
+ onChange: event => setAnswer(stateKey, { loose: event.target.value === 'loose', fillResult: null }),
536
+ }, h('option', { value: 'strict' }, '严格'), h('option', { value: 'loose' }, '宽松(忽略空格和标点)'))),
537
+ h('button', { type: 'button', disabled: !draft.trim(), onClick: () => checkFill(spec, stateKey), className: 'dsh-study-control', 'data-variant': 'primary' }, '检查答案'),
538
+ ),
539
+ result === 'ok' || result === 'bad' ? h('div', { role: 'status', className: 'dsh-study-result', 'data-tone': result === 'ok' ? 'correct' : 'wrong' },
540
+ result === 'ok' ? '✅ 答对了' : '❌ 再想想',
541
+ h('span', null, '参考答案:', renderRich(reference))) : null,
542
+ result === 'ok' || result === 'bad' ? h(Explanation, { key: result, value: spec.explanation, style, initiallyOpen: result === 'bad' }) : null,
543
+ result === 'unknown' ? h('span', { className: 'dsh-study-subtle' }, '这题没有提供参考答案。') : null,
544
+ h(QuestionTools, { stateKey, fill: true }),
545
+ )
546
+ })
547
+
548
+ /* ------------------------------------------------------------------ *
549
+ * 6. 图片类卡片
550
+ * ------------------------------------------------------------------ */
551
+
552
+ function ImagesCard({ spec }) {
553
+ const query = String(spec.query ?? '').trim()
554
+ const title = String(spec.title ?? '').trim()
555
+ if(Array.isArray(spec.items)&&spec.items.length)return h('div',{style:cardStyle},title,spec.items.map((item,i)=>h(MediaBox,{key:i,descriptor:item})));
556
+ return h(
557
+ 'div',
558
+ { style: cardStyle },
559
+ h('div', { style: { display: 'flex', gap: '8px', alignItems: 'center' } },
560
+ h(Badge, { tone: 'plain' }, '找图'),
561
+ h('span', { style: { color: FAINT, fontSize: '12px' } }, '在浏览器打开会将搜索词发给 Bing')),
562
+ title !== '' ? h('div', { style: { fontWeight: 600 } }, title) : null,
563
+ query !== ''
564
+ ? h('button', {
565
+ type: 'button',
566
+ onClick: () => {
567
+ const url = new URL('https://www.bing.com/images/search')
568
+ url.searchParams.set('q', query)
569
+ openExternalMedia(url.href)
570
+ },
571
+ style: { ...buttonStyle(false), overflowWrap: 'anywhere' },
572
+ }, `在 Bing 搜索「${query}」`)
573
+ : h('div', { style: { color: FAINT } }, '模型没有给出搜索词'),
574
+ )
575
+ }
576
+
577
+ function GenerateImageCard({ spec }) {
578
+ if(spec.url)return h(MediaBox,{descriptor:spec});
579
+ const prompt = String(spec.prompt ?? '').trim()
580
+ const ratio = String(spec.aspect_ratio ?? '4:3')
581
+ return h(
582
+ 'div',
583
+ { style: cardStyle },
584
+ h('div', { style: { display: 'flex', gap: '8px', alignItems: 'center' } },
585
+ h(Badge, { tone: 'plain' }, '生图'),
586
+ h('span', { style: { color: FAINT, fontSize: '12px' } }, ratio)),
587
+ prompt !== '' ? h('div', { style: { fontSize: '14px', lineHeight: 1.7, color: SOFT } }, prompt) : null,
588
+ h('div', { style: { color: FAINT, fontSize: '13px' } }, '本发行未启用 KIE 生图。'),
589
+ )
590
+ }
591
+
592
+ /* ------------------------------------------------------------------ *
593
+ * 7. fence 渲染器
594
+ * ------------------------------------------------------------------ */
595
+
596
+ function PlotCard({spec, lazy = false}){
597
+ const ref=useRef(null);
598
+ useEffect(()=>{
599
+ const node=ref.current;if(!node)return;
600
+ let shadow, dispose, observer, active = true
601
+ function mount() {
602
+ if (!active || shadow) return
603
+ shadow = node.shadowRoot || node.attachShadow({ mode: 'open' })
604
+ const css = document.createElement('style')
605
+ css.textContent = ':host{display:block}canvas{width:100%;height:300px;touch-action:none;background:#fff;border-radius:7px}.dswt-axis-label{color:var(--dsw-alias-label-secondary,#546271)!important}label{display:flex;gap:8px;align-items:center;margin:5px 0}input[type=range]{flex:1}.row{display:flex;gap:8px;flex-wrap:wrap}button,textarea{font:inherit}textarea{width:95%;height:80px}.muted{font-size:12px;opacity:.7}'
606
+ shadow.replaceChildren(css)
607
+ try { dispose = runtime.mountPlot(spec, shadow) }
608
+ catch (error) { shadow.append(document.createTextNode(error.message)) }
609
+ }
610
+ if (lazy && typeof IntersectionObserver === 'function') {
611
+ observer = new IntersectionObserver(entries => {
612
+ if (!entries.some(entry => entry.isIntersecting)) return
613
+ observer.disconnect()
614
+ mount()
615
+ }, { rootMargin: '180px' })
616
+ observer.observe(node)
617
+ } else mount()
618
+ return () => {
619
+ active = false
620
+ observer?.disconnect()
621
+ dispose?.()
622
+ shadow?.replaceChildren()
623
+ }
624
+ },[spec,lazy]);
625
+ return h('div',{style:{...cardStyle,minWidth:0}},spec.title?h('strong',null,renderRich(spec.title)):null,h('div',{ref,style:lazy?{minHeight:300}:undefined}));
626
+ }
627
+ function TableCard({spec}){
628
+ const headers = Array.isArray(spec.headers) ? spec.headers : Array.isArray(spec.columns) ? spec.columns : []
629
+ const rows = Array.isArray(spec.rows) ? spec.rows.filter(Array.isArray) : []
630
+ const cellText = value => value !== null && typeof value === 'object' ? value.text : value
631
+ const style = { border: '1px solid ' + THIN, padding: 8 }
632
+ const head = headers.map((v, i) => h('th', { key: i, style }, renderRich(cellText(v))))
633
+ const body = rows.map((row, i) => h('tr', { key: i },
634
+ row.map((v, j) => h('td', { key: j, style }, renderRich(cellText(v))))))
635
+ return h('div', { style: { overflowX: 'auto', margin: '8px 0' } },
636
+ spec.title ? h('strong', null, renderRich(spec.title)) : null,
637
+ h('table', { style: { borderCollapse: 'collapse', width: '100%' } },
638
+ h('thead', null, h('tr', null, head)), h('tbody', null, body)))
639
+ }
640
+ const QuestionMedia = React.memo(function QuestionMedia({spec}){
641
+ const items=[...(Array.isArray(spec.media)?spec.media:[]),...(Array.isArray(spec.graphs)?spec.graphs.map(p=>({...p,type:'plot'})):[])];
642
+ if(spec.image)items.push(typeof spec.image==='string'?{url:spec.image}:spec.image);
643
+ if(spec.plot)items.push({...spec.plot,type:'plot'});
644
+ if(spec.table)items.push({...spec.table,type:'table'});
645
+ return h(React.Fragment,null,items.map((item,i)=>item?.type==='plot'?h(PlotCard,{key:i,spec:item,lazy:true}):item?.type==='table'?h(TableCard,{key:i,spec:item}):h(MediaBox,{key:i,descriptor:item})));
646
+ })
647
+
648
+ function DsToolsFence({ code, streaming, children }) {
649
+ const specs = useMemo(() => streaming ? null : parseTools(code), [code, streaming])
650
+ const batchId = useMemo(() => streaming ? '' : textHash(code), [code, streaming])
651
+ const open = useSyncExternalStore(subscribeToStore, () => store.quiz.openId === batchId)
652
+ const items = useMemo(
653
+ () => (Array.isArray(specs) ? specs.filter((spec) => spec !== null && typeof spec === 'object' && (spec.type === 'quiz' || spec.type === 'fill')) : []),
654
+ [specs],
655
+ )
656
+ const requirementsSpec = useMemo(() => {
657
+ if (!Array.isArray(specs)) return null
658
+ const found = specs.find((spec) => spec !== null && typeof spec === 'object' && spec.type === 'requirements')
659
+ return found ?? null
660
+ }, [specs])
661
+ const wasStreaming=useRef(false);
662
+ useEffect(()=>{if(streaming){wasStreaming.current=true;return;}if(wasStreaming.current){wasStreaming.current=false;if(requirementsSpec)store.patch({requirements:requirementsSpec,autoStarter:requirementsSpec});if(items.length)quizPatch({openId:batchId,cursor:0,tab:'all',libraryOpen:false});}},[streaming,requirementsSpec,items,batchId]);
663
+ useEffect(() => {
664
+ if (items.length === 0) return
665
+ registerBatch(batchId, items)
666
+ }, [batchId, items])
667
+ if (streaming) return children
668
+ if (specs === null) {
669
+ return h('div', null,
670
+ h('div', { style: { color: BAD, fontSize: '13px', marginBottom: '6px' } }, 'ds_tools 不是合法 JSON,按原文显示'),
671
+ children)
672
+ }
673
+ const cards = []
674
+ specs.forEach((spec, index) => {
675
+ if (spec === null || typeof spec !== 'object') return
676
+ if (spec.type === 'quiz' || spec.type === 'fill') return
677
+ const key = `c${index}`
678
+ const extra =
679
+ spec.type === 'plot' ? h(PlotCard,{key,spec}) : spec.type === 'table' ? h(TableCard,{key,spec}) : spec.type === 'images'
680
+ ? h(ImagesCard, { key, spec })
681
+ : spec.type === 'generate_image'
682
+ ? h(GenerateImageCard, { key, spec })
683
+ : spec.type === 'requirements'
684
+ ? h('div',{key},h('button',{type:'button',style:buttonStyle(false,false),onClick:()=>store.patch({requirements:spec})},'在输入区显示要求'),h(RequirementsCard,{spec}))
685
+ : null
686
+ if (extra !== null) cards.push(extra)
687
+ })
688
+ if (cards.length === 0 && items.length === 0) return children
689
+ const entry = items.length === 0
690
+ ? null
691
+ : h(
692
+ 'button',
693
+ {
694
+ type: 'button',
695
+ onClick: () => quizPatch({
696
+ openId: open ? null : batchId,
697
+ cursor: 0,
698
+ tab: 'all',
699
+ libraryOpen: false,
700
+ }),
701
+ 'data-dsh-quiz-entry': batchId,
702
+ 'aria-expanded': open ? 'true' : 'false',
703
+ className: 'dsh-study-entry',
704
+ },
705
+ `${open ? '收起题目' : '打开题目'}(${items.length} 题)`,
706
+ )
707
+ return h(
708
+ 'div',
709
+ { style: { display: 'flex', flexDirection: 'column' } },
710
+ entry,
711
+ cards,
712
+ )
713
+ }
714
+
715
+ /* ------------------------------------------------------------------ *
716
+ * 8. 输入框上方的按钮
717
+ * ------------------------------------------------------------------ */
718
+
719
+ /* ------------------------------------------------------------------ *
720
+ * 8. 输入框旁的控件:右上角按钮 / 要求栏 / 公式预览
721
+ * ------------------------------------------------------------------ */
722
+
723
+ // 客户端内的极小状态仓:右上角按钮、要求栏、预览条共享,不需要走 Host
724
+ const store = {
725
+ codeMode: false,
726
+ requirements: null,
727
+ quiz: createQuizState(),
728
+ listeners: new Set(),
729
+ patch(values) {
730
+ Object.assign(this, values)
731
+ for (const listener of Array.from(this.listeners)) listener()
732
+ },
733
+ subscribe(listener) {
734
+ this.listeners.add(listener)
735
+ return () => { this.listeners.delete(listener) }
736
+ },
737
+ }
738
+
739
+ function useStore() {
740
+ const [, bump] = useState(0)
741
+ useEffect(() => store.subscribe(() => bump((value) => value + 1)), [])
742
+ return store
743
+ }
744
+
745
+ const subscribeToStore = listener => store.subscribe(listener)
746
+ const readQuiz = () => store.quiz
747
+
748
+ /* ------------------------------------------------------------------ *
749
+ * 8.2 右侧题目抽屉(网页工具箱同款)
750
+ * ------------------------------------------------------------------ */
751
+
752
+ const TAB_LIST = [
753
+ { id: 'all', label: '📋 全部' },
754
+ { id: 'wrong', label: '❌ 错题' },
755
+ { id: 'bookmark', label: '⭐ 收藏' },
756
+ { id: 'review', label: '🔄 复盘' },
757
+ ]
758
+
759
+ function StatCell({ label, value, tone }) {
760
+ return h('div', { className: 'dsh-study-metric', 'data-tone': tone },
761
+ h('strong', null, value), h('span', null, label))
762
+ }
763
+
764
+ function BookmarkCard({ item, onRemove }) {
765
+ const isFill = item.type === 'fill'
766
+ const options = Array.isArray(item.options) ? item.options : []
767
+ const answers = Array.isArray(item.answers) ? item.answers : []
768
+ const saved = new Date(Number(item.savedAt) || Date.now())
769
+ const when = `${saved.getMonth() + 1}月${saved.getDate()}日 ${String(saved.getHours()).padStart(2, '0')}:${String(saved.getMinutes()).padStart(2, '0')}`
770
+ return h('article', { className: 'dsh-study-card dsh-study-bookmark', 'data-bookmarked': true },
771
+ h('div', { className: 'dsh-study-card-head' },
772
+ h('span', { className: 'dsh-study-card-type' }, isFill ? '填空题' : '选择题'),
773
+ h('span', { className: 'dsh-study-subtle' }, `收藏于 ${when}`),
774
+ h(StarButton, { on: true, onClick: onRemove })),
775
+ h('div', { className: 'dsh-study-stem' }, renderRich(item.question, item.question_style, 'bq')),
776
+ item.image !== undefined && item.image !== null ? h(MediaBox, { descriptor: item.image }) : null,
777
+ isFill
778
+ ? h('div', { style: { fontSize: '14px', lineHeight: 1.8 } },
779
+ h('span', { style: { color: FAINT } }, '参考答案:'), renderRich(answers[0] ?? '(未给出)', item.question_style, 'ba'))
780
+ : h('div', { className: 'dsh-study-options' },
781
+ options.map((option, index) => h('div', {
782
+ key: `bo${index}`,
783
+ className: 'dsh-study-option',
784
+ 'data-tone': index === item.answer ? 'correct' : index === item.picked ? 'wrong' : undefined,
785
+ },
786
+ h('span', { className: 'dsh-study-option-letter' }, String.fromCharCode(65 + index)),
787
+ h('span', { className: 'dsh-study-option-caption' }, renderRich(optionText(option), item.question_style, `bt${index}`))))),
788
+ h(Explanation, { value: item.explanation, style: item.question_style }))
789
+ }
790
+
791
+ function recordedAnswer(spec, state) {
792
+ if (spec.type === 'fill') return state.filled.slice(0, 400)
793
+ if (state.picked < 0) return ''
794
+ const label = optionText(spec.options?.[state.picked])
795
+ return (String.fromCharCode(65 + state.picked) + (label ? ' ' + label : '')).slice(0, 400)
796
+ }
797
+
798
+ function quizReviewPrompt(rows) {
799
+ const lines = rows.map(({ index, spec, state, correct, stateKey }) => {
800
+ const question = String(spec.question ?? '').replace(/\s+/g, ' ').slice(0, 180)
801
+ const report = {
802
+ 题号: index + 1,
803
+ 题干摘要: question,
804
+ 我的答案: recordedAnswer(spec, state),
805
+ 判定: correct === null ? '未作答' : correct ? '正确' : '错误',
806
+ }
807
+ const retry = answerOf('review:' + stateKey)
808
+ const retryVerdict = correct === false ? verdictOf(spec, retry) : null
809
+ if (retryVerdict !== null) {
810
+ report.复盘答案 = recordedAnswer(spec, retry)
811
+ report.复盘判定 = retryVerdict ? '正确' : '错误'
812
+ }
813
+ return JSON.stringify(report)
814
+ })
815
+ return [
816
+ '这是我在本会话答题栏提交的作答记录。请结合你之前出的题,区分当次答案和复盘答案,按题号解释仍有疑问的错题。除非我另外要求,先不用再出题。',
817
+ '以下各行为答题数据:',
818
+ ...lines,
819
+ ].join('\n')
820
+ }
821
+
822
+ function QuizDrawer(props) {
823
+ const quiz = useSyncExternalStore(subscribeToStore, readQuiz)
824
+ const openId = quiz.openId
825
+ const batchId = openId
826
+ const cardRefs = useRef({})
827
+ const lastFocusedQuestion = useRef(null)
828
+ const focusScope = useRef(null)
829
+ const assessmentPosition = useRef(0)
830
+ const anchorRef = useRef(null)
831
+ const drawerRef = useRef(null)
832
+ const scrollRef = useRef(null)
833
+ const [region, setRegion] = useState(null)
834
+ const [layout, setLayout] = useState('split')
835
+ const tab = quiz.tab
836
+ const inLibrary = quiz.libraryOpen
837
+ const cursor = quiz.cursor
838
+ const batch = batchId === null || batchId === undefined ? null : batchOf(batchId)
839
+
840
+ useLayoutEffect(() => {
841
+ const container = anchorRef.current?.closest('[data-conversation-content]')
842
+ if (!openId || !container) {
843
+ setRegion(null)
844
+ return
845
+ }
846
+ const previous = container.style.getPropertyValue('--dsh-study-quiz-width')
847
+ function size() {
848
+ const width = container.clientWidth
849
+ const narrow = width < 660
850
+ const panelWidth = narrow ? Math.min(width, 420) : Math.min(600, Math.max(320, Math.round(width * .36)))
851
+ if (panelWidth > 0) container.style.setProperty('--dsh-study-quiz-width', panelWidth + 'px')
852
+ setLayout(narrow ? 'overlay' : 'split')
853
+ }
854
+ size()
855
+ setRegion(container)
856
+ const observer = new ResizeObserver(size)
857
+ observer.observe(container, { box: 'border-box' })
858
+ return () => {
859
+ observer.disconnect()
860
+ if (previous) container.style.setProperty('--dsh-study-quiz-width', previous)
861
+ else container.style.removeProperty('--dsh-study-quiz-width')
862
+ }
863
+ }, [openId])
864
+
865
+ const rows = useMemo(() => {
866
+ if (batch === null) return []
867
+ return batch.items.map((spec, index) => {
868
+ const stateKey = `${batch.id}:${index}`
869
+ const state = answerOf(stateKey)
870
+ return { spec, index, stateKey, state, correct: verdictOf(spec, state) }
871
+ })
872
+ // eslint-disable-next-line react-hooks/exhaustive-deps
873
+ }, [batch, quiz.states])
874
+
875
+ const answered = rows.filter((row) => row.correct !== null)
876
+ const right = rows.filter((row) => row.correct === true)
877
+ const wrong = rows.filter((row) => row.correct === false)
878
+ const bookmarks = quiz.bookmarks
879
+ const bookmarkedKeys = useMemo(() => new Set(bookmarks.map(item => item.key)), [bookmarks])
880
+
881
+ const reviewRows = wrong.map(row => {
882
+ const stateKey = 'review:' + row.stateKey
883
+ const state = answerOf(stateKey)
884
+ return { ...row, stateKey, state, correct: verdictOf(row.spec, state) }
885
+ })
886
+ const reviewCorrect = reviewRows.filter(row => row.correct === true).length
887
+ const visible = tab === 'review' ? reviewRows : tab === 'wrong' ? wrong : tab === 'bookmark' ? [] : rows
888
+ const position = Math.max(0, Math.min(cursor, visible.length - 1))
889
+ const currentRow = visible[position]
890
+
891
+ const complete = rows.length > 0 && answered.length === rows.length
892
+ const autoReview = store.quiz.autoReview[batchId] === true
893
+ const report = store.quiz.reports[batchId]
894
+ const prompt = useMemo(() => answered.length ? quizReviewPrompt(rows) : '', [rows, answered.length])
895
+ const submitted = !!prompt && report?.status === 'sent' && report.prompt === prompt
896
+ const canSend = typeof props.sendQuizReview === 'function'
897
+ const sendReview = useCallback(async () => {
898
+ if (!batchId || !prompt || !canSend) return
899
+ const current = store.quiz.reports[batchId]
900
+ if (current?.status === 'sending' || (current?.status === 'sent' && current.prompt === prompt)) return
901
+ function update(status) {
902
+ quizPatch({ reports: { ...store.quiz.reports, [batchId]: { status, prompt, complete } } })
903
+ }
904
+ update('sending')
905
+ try {
906
+ await props.sendQuizReview(props.sessionId, prompt)
907
+ update('sent')
908
+ } catch {
909
+ update('error')
910
+ }
911
+ }, [batchId, prompt, complete, canSend, props.sessionId, props.sendQuizReview])
912
+
913
+ useEffect(() => {
914
+ const waitingForCompletion = !report || (report.status === 'sent' && !report.complete)
915
+ if (autoReview && complete && waitingForCompletion) void sendReview()
916
+ }, [autoReview, complete, report, sendReview])
917
+
918
+ function focusQuestion(row, smooth = false) {
919
+ const item = cardRefs.current[row?.stateKey]
920
+ if (!item) {
921
+ drawerRef.current?.focus({ preventScroll: true })
922
+ return
923
+ }
924
+ const field = row.spec.type === 'fill' ? item.querySelector('[data-dsh-quiz-fill]') : null
925
+ const target = field ?? item
926
+ target.focus({ preventScroll: true })
927
+ const scroll = scrollRef.current
928
+ if (!scroll) return
929
+ const outer = scroll.getBoundingClientRect()
930
+ const inner = target.getBoundingClientRect()
931
+ if (smooth && typeof scroll.scrollTo === 'function') {
932
+ const offset = inner.height > outer.height - 16
933
+ ? inner.top - outer.top - 8
934
+ : (inner.top + inner.bottom - outer.top - outer.bottom) / 2
935
+ scroll.scrollTo({
936
+ top: scroll.scrollTop + offset,
937
+ behavior: globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth',
938
+ })
939
+ } else if (field && inner.bottom > outer.bottom - 8) {
940
+ scroll.scrollTop += inner.bottom - outer.bottom + 8
941
+ } else if (inner.top < outer.top + 8 || inner.top > outer.bottom - 30) {
942
+ scroll.scrollTop += inner.top - outer.top - 8
943
+ }
944
+ }
945
+
946
+ useLayoutEffect(() => {
947
+ if (!openId || !region || !batch) {
948
+ focusScope.current = null
949
+ return
950
+ }
951
+ const previous = focusScope.current
952
+ const changedTab = previous?.openId !== openId || previous?.tab !== tab || previous?.region !== region || previous?.inLibrary !== inLibrary
953
+ focusScope.current = { openId, tab, region, inLibrary }
954
+ const focused = lastFocusedQuestion.current
955
+ const lostQuestionFocus = focused && !focused.isConnected && region.ownerDocument.activeElement === region.ownerDocument.body
956
+ if (changedTab && scrollRef.current) {
957
+ const scroll = scrollRef.current
958
+ scroll.scrollTop = 0
959
+ if (previous?.openId === openId && !globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
960
+ scroll.animate?.([{ opacity: .6 }, { opacity: 1 }], { duration: 160, easing: 'ease-out' })
961
+ }
962
+ }
963
+ if (changedTab || lostQuestionFocus) focusQuestion(currentRow)
964
+ }, [openId, region, batch, tab, inLibrary, currentRow?.stateKey])
965
+
966
+ function questionOf(target) {
967
+ const node = target instanceof Element ? target.closest('[data-dsh-quiz-question]') : null
968
+ if (!node || !drawerRef.current?.contains(node)) return null
969
+ return node
970
+ }
971
+
972
+ function onFocusCapture(event) {
973
+ const question = questionOf(event.target)
974
+ lastFocusedQuestion.current = question
975
+ const next = visible.findIndex(row => row.stateKey === question?.dataset.dshQuizQuestion)
976
+ if (next !== -1 && next !== cursor) quizPatch({ cursor: next })
977
+ }
978
+
979
+ function close() {
980
+ const entry = region?.querySelector(`[data-dsh-quiz-entry="${batchId}"]`)
981
+ quizPatch({ openId: null })
982
+ entry?.focus({ preventScroll: true })
983
+ }
984
+
985
+ function moveQuestion(direction, stateKey) {
986
+ const at = stateKey ? visible.findIndex(row => row.stateKey === stateKey) : position
987
+ const next = visible[at + direction]
988
+ if (next) focusQuestion(next, true)
989
+ }
990
+
991
+ const counts = useMemo(() => ({ answered: answered.length, right: right.length, wrong: wrong.length }),
992
+ [answered.length, right.length, wrong.length])
993
+ const navigation = {
994
+ inLibrary,
995
+ positions: new Map(visible.map((row, index) => [row.stateKey, index])),
996
+ move: moveQuestion,
997
+ openLibrary: at => {
998
+ assessmentPosition.current = at
999
+ quizPatch({ libraryOpen: true, tab: 'all', cursor: at })
1000
+ },
1001
+ }
1002
+ function returnToAssessment() {
1003
+ quizPatch({ libraryOpen: false, tab: 'all', cursor: assessmentPosition.current })
1004
+ }
1005
+
1006
+ function onKeyDown(event) {
1007
+ if (event.nativeEvent.isComposing || event.keyCode === 229 || event.ctrlKey || event.metaKey || event.altKey) return
1008
+ const target = event.target
1009
+ if (!(target instanceof Element) || !event.currentTarget.contains(target)) return
1010
+ const handled = () => {
1011
+ event.preventDefault()
1012
+ event.stopPropagation()
1013
+ }
1014
+ if (event.key === 'Escape') {
1015
+ handled()
1016
+ if (inLibrary) returnToAssessment()
1017
+ else close()
1018
+ return
1019
+ }
1020
+ const editing = target.closest('input, select, textarea, [contenteditable="true"]')
1021
+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
1022
+ if (!visible.length || (editing && (!editing.matches('[data-dsh-quiz-fill]') || event.shiftKey))) return
1023
+ handled()
1024
+ moveQuestion(event.key === 'ArrowUp' ? -1 : 1)
1025
+ return
1026
+ }
1027
+ if (editing) return
1028
+ const row = currentRow
1029
+ if (!row) return
1030
+ if (row.spec.type === 'quiz') {
1031
+ const number = /^[1-9]$/.test(event.key) ? Number(event.key) : 0
1032
+ const options = Array.isArray(row.spec.options) ? row.spec.options.length : 0
1033
+ if (options <= 4 && (number === 5 || number === 6)) {
1034
+ handled()
1035
+ if (!event.repeat) toggleBookmark(row.spec, row.stateKey, number === 5)
1036
+ return
1037
+ }
1038
+ if (number > 0 && number <= options) {
1039
+ handled()
1040
+ pickOption(row.stateKey, number - 1)
1041
+ return
1042
+ }
1043
+ if (event.key === 'Delete' && answerOf(row.stateKey).picked >= 0) {
1044
+ handled()
1045
+ setAnswer(row.stateKey, { picked: -1 })
1046
+ return
1047
+ }
1048
+ } else if (event.key === 'Enter' && !target.closest('button, a, summary, [role="button"]')) {
1049
+ handled()
1050
+ cardRefs.current[row.stateKey]?.querySelector('[data-dsh-quiz-fill]')?.focus({ preventScroll: true })
1051
+ return
1052
+ }
1053
+ if (event.key.toLowerCase() === 'b') {
1054
+ handled()
1055
+ if (!event.repeat) toggleBookmark(row.spec, row.stateKey)
1056
+ }
1057
+ }
1058
+
1059
+ const anchor = h('span', { hidden: true, ref: anchorRef })
1060
+ if (!batch || !region) return anchor
1061
+ const bar = h('header', { className: 'dsh-study-heading', 'data-library': inLibrary || undefined },
1062
+ h('div', { className: 'dsh-study-heading-row' },
1063
+ h('h2', null, inLibrary ? '📚 题库' : `本次考察 · ${rows.length} 题`),
1064
+ h('button', {
1065
+ type: 'button',
1066
+ className: 'dsh-study-control',
1067
+ 'data-variant': 'close',
1068
+ onClick: inLibrary ? returnToAssessment : close,
1069
+ 'aria-label': inLibrary ? '返回答题' : '收起答题栏',
1070
+ }, inLibrary ? '×' : '收起答题栏')),
1071
+ h('div', {
1072
+ className: 'dsh-study-track',
1073
+ role: 'progressbar',
1074
+ 'aria-label': '作答进度',
1075
+ 'aria-valuemin': 0,
1076
+ 'aria-valuemax': rows.length,
1077
+ 'aria-valuenow': answered.length,
1078
+ }, h('span', { style: { width: `${answered.length / rows.length * 100}%` } })),
1079
+ inLibrary ? h('nav', { className: 'dsh-study-tabs', 'aria-label': '题目筛选' },
1080
+ TAB_LIST.map((item) => {
1081
+ const count = item.id === 'all' ? rows.length
1082
+ : item.id === 'wrong' ? wrong.length
1083
+ : item.id === 'review' ? reviewRows.length - reviewCorrect
1084
+ : bookmarks.length
1085
+ return h('button', {
1086
+ key: item.id,
1087
+ type: 'button',
1088
+ 'aria-pressed': tab === item.id,
1089
+ onClick: () => quizPatch({ tab: item.id, cursor: 0 }),
1090
+ className: 'dsh-study-tab',
1091
+ },
1092
+ h('span', null, item.label),
1093
+ h('span', { className: 'dsh-study-tab-count' }, count))
1094
+ })) : null)
1095
+
1096
+ const reportActions = h('div', { className: 'dsh-study-review-actions' },
1097
+ h('button', {
1098
+ type: 'button', className: 'dsh-study-control', 'data-variant': 'primary',
1099
+ disabled: !prompt || !canSend || report?.status === 'sending' || submitted, onClick: sendReview,
1100
+ }, report?.status === 'sending' ? '正在提交…' : submitted ? '已交给 Agent' : '让 Agent 复盘'),
1101
+ h('label', null,
1102
+ h('input', {
1103
+ type: 'checkbox', checked: autoReview, disabled: !canSend,
1104
+ onChange: event => quizPatch({ autoReview: { ...store.quiz.autoReview, [batchId]: event.target.checked } }),
1105
+ }), '答完自动复盘'),
1106
+ report?.status === 'error' ? h('span', { role: 'status', style: { color: BAD } }, '提交失败,可点复盘重试') : null)
1107
+
1108
+ let body
1109
+ if (tab === 'bookmark') {
1110
+ body = bookmarks.length === 0
1111
+ ? h('div', { className: 'dsh-study-empty' }, '还没有收藏。点题卡右上角的星标收藏。')
1112
+ : bookmarks.slice().reverse().map((item, index) => h(BookmarkCard, {
1113
+ key: `${item.key}-${index}`,
1114
+ item,
1115
+ onRemove: () => {
1116
+ const list = store.quiz.bookmarks.filter((one) => one.key !== item.key)
1117
+ quizPatch({ bookmarks: list })
1118
+ saveBookmarks(list)
1119
+ },
1120
+ }))
1121
+ } else if (visible.length === 0) {
1122
+ body = h('div', { className: 'dsh-study-empty' },
1123
+ tab === 'wrong' ? (answered.length ? '目前没有错题。' : '答题后,错题会显示在这里。') : tab === 'review' ? '有错题后,可以在这里重做。' : '这批题还没有解析出来。')
1124
+ } else {
1125
+ body = visible.map((row) => h('div', {
1126
+ key: row.stateKey,
1127
+ 'data-dsh-quiz-question': row.stateKey,
1128
+ 'aria-label': `第 ${row.index + 1} 题`,
1129
+ className: 'dsh-study-question',
1130
+ 'data-current': currentRow === row ? 'true' : undefined,
1131
+ 'data-answer-tone': row.correct === true ? 'correct' : row.correct === false ? 'wrong' : undefined,
1132
+ tabIndex: -1,
1133
+ ref: (element) => {
1134
+ if (element) cardRefs.current[row.stateKey] = element
1135
+ else delete cardRefs.current[row.stateKey]
1136
+ },
1137
+ },
1138
+ h(row.spec.type === 'quiz' ? QuizCard : FillCard, {
1139
+ spec: row.spec, stateKey: row.stateKey, state: row.state,
1140
+ number: row.index + 1, starred: bookmarkedKeys.has(itemKeyOf(row.spec)),
1141
+ })))
1142
+ }
1143
+
1144
+ if (tab === 'review' && reviewRows.length > 0) {
1145
+ body = [
1146
+ h('div', { key: 'reset', className: 'dsh-study-practice' },
1147
+ h('span', { role: 'status', className: 'dsh-study-subtle' }, `已订正 ${reviewCorrect} / ${reviewRows.length}`),
1148
+ h('button', {
1149
+ type: 'button',
1150
+ onClick: () => {
1151
+ const states = { ...store.quiz.states }
1152
+ for (const row of reviewRows) delete states[row.stateKey]
1153
+ quizPatch({ states })
1154
+ focusQuestion(currentRow)
1155
+ },
1156
+ className: 'dsh-study-control',
1157
+ }, '重置复盘')),
1158
+ ...body,
1159
+ ]
1160
+ }
1161
+
1162
+ const panel = h('aside', {
1163
+ ref: drawerRef, tabIndex: -1, onKeyDown, onFocusCapture,
1164
+ 'data-dsh-quiz-drawer': '', 'data-layout': layout, 'aria-label': '答题栏',
1165
+ className: 'dsh-study-drawer',
1166
+ },
1167
+ bar,
1168
+ h('div', { ref: scrollRef, className: 'dsh-study-scroll' },
1169
+ h(QuizCounts.Provider, { value: counts },
1170
+ h(QuizNavigation.Provider, { value: navigation }, body)),
1171
+ reportActions))
1172
+ return h(React.Fragment, null, anchor, createPortal(panel, region))
1173
+ }
1174
+
1175
+ function guessLanguage(source) {
1176
+ const text = String(source ?? '').trim()
1177
+ if (text === '') return ''
1178
+ const fence = /^```(java|python|py|javascript|js|typescript|ts|json)?\s*\n[\s\S]*\n```$/i.exec(text)
1179
+ if (fence !== null) {
1180
+ const tag = String(fence[1] ?? '').toLowerCase()
1181
+ const mapped = { py: 'python', js: 'javascript', ts: 'typescript' }[tag] ?? tag
1182
+ if (mapped !== '') return mapped
1183
+ }
1184
+ if (/^[{[]/.test(text)) {
1185
+ try {
1186
+ if (typeof JSON.parse(text) === 'object') return 'json'
1187
+ } catch (error) { void error }
1188
+ }
1189
+ const lines = text
1190
+ .replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`]*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*|#[^\n]*/g, '')
1191
+ .split(/\r?\n/)
1192
+ .map((line) => line.trim())
1193
+ .filter((line) => line !== '')
1194
+ if (lines.length === 0) return ''
1195
+ if (lines.some((line) => /[\u3002\uff01\uff1f]/.test(line))) return ''
1196
+ const first = lines[0]
1197
+ if (/^(?:package\s+[\w.]+;|import\s+(?:static\s+)?java[.])/.test(first)) return 'java'
1198
+ if (/^(?:(?:public|private|protected|static|final|abstract)\s+)*(?:class|interface|enum)\s+\w+/.test(first)) return 'java'
1199
+ if (/^(?:(?:public|private|protected|static|final|abstract)\s+)*(?:int|long|float|double|boolean|char|void|String|byte|short)(?:\s*\[\s*\])?\s+[A-Za-z_$][\w$]*\s*[(=;,\[]/.test(first)) return 'java'
1200
+ if (/System\.out\./.test(text)) return 'java'
1201
+ if (/^(?:async\s+)?def\s+\w+\s*\(/.test(first) || /^from\s+[\w.]+\s+import\s+/.test(first)) return 'python'
1202
+ if (/^(?:class\s+\w+.*:|print\s*\()/.test(first)) return 'python'
1203
+ if (/^(?:interface|type)\s+\w+/.test(first) || /^(?:let|const)\s+\w+\s*:\s*\w+/.test(first)) return 'typescript'
1204
+ if (/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*[\w$]*\s*\(/.test(first)) return 'javascript'
1205
+ if (/^(?:let|const|var)\s+[\w$]+\s*=/.test(first) || /^console\.(?:log|warn|error)\(/.test(first)) return 'javascript'
1206
+ if (/^import\s+.+\s+from\s+/.test(first) || /^export\s+/.test(first)) return 'javascript'
1207
+ if (/^(?:for|while|if)\s+.+:\s*$/.test(first)) return 'python'
1208
+ if (/^(?:for|while|if)\s*\(.*\)\s*\{/.test(first)) return /;\s*(?:int|long)\b|\bint\s+\w/.test(text) ? 'java' : 'javascript'
1209
+ if (/^(?:SELECT|select)\s+/m.test(text)) return 'sql'
1210
+ if (/^<\/?[a-z][\w-]*/.test(first)) return 'html'
1211
+ if (/^[.#@][\w-]+[\s,{:]/.test(first)) return 'css'
1212
+ if (/^(?:if|then|else|fi|for|while|do|done|echo|export|local)\b/.test(first)) return 'bash'
1213
+ return ''
1214
+ }
1215
+
1216
+ const chipStyle = (active, tone) => ({
1217
+ padding: '3px 9px',
1218
+ borderRadius: '999px',
1219
+ border: `1px solid ${tone === 'warn' ? BAD : active ? OK : THIN}`,
1220
+ background: active ? 'var(--dsw-alias-bg-layer-1, rgba(0,0,0,.05))' : 'transparent',
1221
+ color: active ? TEXT : SOFT,
1222
+ fontSize: '12px',
1223
+ font: 'inherit',
1224
+ lineHeight: 1.6,
1225
+ cursor: 'pointer',
1226
+ whiteSpace: 'nowrap',
1227
+ })
1228
+
1229
+ const composerActionsStyle = {
1230
+ display: 'flex',
1231
+ flexWrap: 'wrap',
1232
+ gap: '4px',
1233
+ alignItems: 'center',
1234
+ }
1235
+
1236
+ function unfence(draft) {
1237
+ const source = String(draft ?? '')
1238
+ const match = /^(\x60{3,})([A-Za-z0-9+#._-]*)[ \t]*\n([\s\S]*?)\n\1[ \t]*$/.exec(source)
1239
+ return match ? { lang: match[2], text: match[3] } : { lang: '', text: source }
1240
+ }
1241
+
1242
+ const panelStyle = {
1243
+ position: 'relative',
1244
+ top: '0px',
1245
+ left: '0px',
1246
+ right: '0px',
1247
+ height: 'min(52vh, 440px)',
1248
+ display: 'flex',
1249
+ flexDirection: 'column',
1250
+ overflow: 'hidden',
1251
+ borderRadius: '12px',
1252
+ border: '1px solid #2c3242',
1253
+ background: '#12151d',
1254
+ boxShadow: '0 10px 28px rgba(0,0,0,.34)',
1255
+ pointerEvents: 'auto',
1256
+ zIndex: 8,
1257
+ }
1258
+
1259
+ const panelBarStyle = {
1260
+ display: 'flex',
1261
+ alignItems: 'center',
1262
+ gap: '7px',
1263
+ padding: '5px 9px',
1264
+ background: '#1d2130',
1265
+ borderBottom: '1px solid #2c3242',
1266
+ flexWrap: 'wrap',
1267
+ }
1268
+
1269
+ const panelButtonStyle = {
1270
+ padding: '2px 9px',
1271
+ borderRadius: '6px',
1272
+ border: '1px solid #515b72',
1273
+ background: '#2c3346',
1274
+ color: '#e6ebf7',
1275
+ fontSize: '12px',
1276
+ font: 'inherit',
1277
+ cursor: 'pointer',
1278
+ }
1279
+
1280
+ const statusStyle = {
1281
+ display: 'flex',
1282
+ alignItems: 'center',
1283
+ gap: '12px',
1284
+ padding: '3px 10px',
1285
+ borderTop: '1px solid #232937',
1286
+ background: '#0f1219',
1287
+ color: '#7d8bb0',
1288
+ fontSize: '11px',
1289
+ }
1290
+
1291
+ const monoStyle = {
1292
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
1293
+ fontSize: '12.5px',
1294
+ lineHeight: 1.65,
1295
+ background: CODE_BG,
1296
+ borderRadius: '8px',
1297
+ padding: '8px 10px',
1298
+ margin: 0,
1299
+ whiteSpace: 'pre',
1300
+ overflowX: 'auto',
1301
+ color: TEXT,
1302
+ }
1303
+
1304
+ function RequirementsCard({ spec, onInsert, onClose, insertBlocked = false }) {
1305
+ const [open, setOpen] = useState(true)
1306
+ const title = String(spec.title ?? '').trim() || '作答要求'
1307
+ const text = String(spec.text ?? '')
1308
+ const instructions = Array.isArray(spec.instructions) ? spec.instructions.filter(item => typeof item === 'string' && item.trim()) : []
1309
+ const signature = typeof spec.signature === 'string' ? spec.signature.trim() : ''
1310
+ const starter = typeof spec.starterCode === 'string' ? spec.starterCode.trim() : ''
1311
+ const language = validLanguage(spec.language)
1312
+
1313
+ return h(
1314
+ 'div',
1315
+ { style: { border: `1px solid ${THIN}`, borderRadius: '10px', background: CARD, overflow: 'hidden' } },
1316
+ h(
1317
+ 'div',
1318
+ { style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '7px 10px' } },
1319
+ h('button', {
1320
+ type: 'button',
1321
+ onClick: () => setOpen(!open),
1322
+ style: { border: 'none', background: 'transparent', color: SOFT, cursor: 'pointer', font: 'inherit', fontSize: '12px', padding: 0 },
1323
+ }, open ? '▾' : '▸'),
1324
+ h('span', { style: { fontWeight: 600, fontSize: '13px', color: TEXT, flex: 1 } }, title),
1325
+ language !== '' ? h(Badge, { tone: 'plain' }, language) : null,
1326
+ typeof onInsert === 'function' && starter !== ''
1327
+ ? h('button', {
1328
+ type: 'button',
1329
+ onClick: () => onInsert(starter, language),
1330
+ disabled: insertBlocked,
1331
+ title: insertBlocked ? '已有草稿,保留原文和引用' : undefined,
1332
+ style: { ...chipStyle(false), fontSize: '11.5px' },
1333
+ }, '插入代码模板')
1334
+ : null,
1335
+ insertBlocked && starter !== '' && typeof onInsert === 'function'
1336
+ ? h('span', { style: { color: FAINT, fontSize: '11px' } }, '仅在空草稿插入') : null,
1337
+ typeof onClose === 'function'
1338
+ ? h('button', {
1339
+ type: 'button',
1340
+ onClick: onClose,
1341
+ title: '关闭要求栏',
1342
+ style: { border: 'none', background: 'transparent', color: FAINT, cursor: 'pointer', font: 'inherit', fontSize: '14px', padding: '0 2px' },
1343
+ }, '×')
1344
+ : null,
1345
+ ),
1346
+ open
1347
+ ? h(
1348
+ 'div',
1349
+ { style: { padding: '0 12px 10px', display: 'flex', flexDirection: 'column', gap: '8px' } },
1350
+ text.trim() !== '' ? h('div', { style: { fontSize: '13.5px', lineHeight: 1.8, color: SOFT, whiteSpace: 'pre-wrap' } }, renderRich(text)) : null,
1351
+ instructions.length > 0
1352
+ ? h('ul', { style: { margin: 0, paddingLeft: '18px', color: SOFT, fontSize: '13px', lineHeight: 1.8 } },
1353
+ instructions.map((item, index) => h('li', { key: `i${index}` }, renderRich(item))))
1354
+ : null,
1355
+ signature !== ''
1356
+ ? h('div', null,
1357
+ h('div', { style: { color: FAINT, fontSize: '11.5px', marginBottom: '4px' } }, '方法签名'),
1358
+ h('pre', { style: monoStyle,onDoubleClick:()=>navigator.clipboard.writeText(signature).catch(()=>{}),dangerouslySetInnerHTML:{__html:runtime.DSWTCodeMirror.highlightSnippet(signature,language||'java')} }))
1359
+ : null,
1360
+ starter !== ''
1361
+ ? h('div', null,
1362
+ h('div', { style: { color: FAINT, fontSize: '11.5px', marginBottom: '4px' } }, '代码骨架'),
1363
+ h('pre', { style: monoStyle,onDoubleClick:()=>navigator.clipboard.writeText(starter).catch(()=>{}),dangerouslySetInnerHTML:{__html:runtime.DSWTCodeMirror.highlightSnippet(starter,language||'java')} }))
1364
+ : null,
1365
+ )
1366
+ : null,
1367
+ )
1368
+ }
1369
+
1370
+ // 选中器替身:DSH 没有注入 useInput 时直接退回 InputZone 的草稿快照
1371
+ const readerFor = (fallback) => () => fallback
1372
+
1373
+ function InputChips(props) {
1374
+ if (props.inputActions === undefined || props.inputActions === null) return null
1375
+ return h(InputChipsInner, {
1376
+ useInput: props.useInput,
1377
+ inputActions: props.inputActions,
1378
+ fallbackDraft: props.input?.draft ?? '',
1379
+ preset: props.useSessions?.(snapshot => snapshot.byId[props.sessionId]?.projectionValues?.agentPreset),
1380
+ })
1381
+ }
1382
+
1383
+ function InputChipsInner({ useInput, inputActions, fallbackDraft, preset }) {
1384
+ const state = useStore()
1385
+ const read = typeof useInput === 'function' ? useInput : readerFor(fallbackDraft)
1386
+ const draft = read((snapshot) => snapshot?.draft ?? '') ?? ''
1387
+ const hasChips = read(snapshot => Boolean(snapshot?.occurrences?.length))
1388
+ const [note, setNote] = useState('')
1389
+
1390
+ const hint = useCallback((text) => {
1391
+ setNote(text)
1392
+ window.setTimeout(() => { setNote((current) => (current === text ? '' : current)) }, 2400)
1393
+ }, [])
1394
+
1395
+ const onCode = useCallback(() => {
1396
+ if (hasChips) { hint('请先移除草稿里的引用'); return }
1397
+ store.patch({ codeMode: true })
1398
+ }, [hasChips, hint])
1399
+
1400
+ const onQuiz = useCallback(() => {
1401
+ if (preset && preset !== 'study') {
1402
+ hint('请在 Agent 里选择学习模式')
1403
+ return
1404
+ }
1405
+ const line = '请按学习模式的 ds_tools 格式给我出 5 道练习题。'
1406
+ const span = inputActions.captureInsertion()
1407
+ if (inputActions.insertText(draft.trim() ? '\n' + line + '\n' : line, { ...span, start: span.end })) hint('已填入')
1408
+ else hint('输入框已变化,请重试')
1409
+ }, [draft, inputActions, hint, preset])
1410
+
1411
+ // 代码模式下浮层接管输入,侧边按钮整体收起
1412
+ if (state.codeMode) return null
1413
+
1414
+ return h(
1415
+ 'div',
1416
+ { style: composerActionsStyle },
1417
+
1418
+ h('button', { type: 'button', onClick: onCode, style: chipStyle(false), title: 'Ctrl+Shift+Space 进入代码模式' }, '代码'),
1419
+ h('button', { type: 'button', onClick: onQuiz, style: chipStyle(false), title: '学习模式提供出题协议,此按钮只将出题请求填入草稿' }, '出题'),
1420
+ note !== '' ? h('span', { style: { color: FAINT, fontSize: '11px', maxWidth: '96px' } }, note) : null,
1421
+ )
1422
+ }
1423
+
1424
+ /* ------------------------------------------------------------------ *
1425
+ * 8.1 代码模式:黑底浮层编辑器,Ctrl+Enter 直接发送
1426
+ * ------------------------------------------------------------------ */
1427
+
1428
+ // DSH's overlay slot normally has zero height. A visible study panel
1429
+ // gives it a row inside the composer so the chat reflows above it.
1430
+ const composerPanelCss = `
1431
+ [data-composer-card] > [data-composer-overlay]:has([data-dsh-study-panel]) {
1432
+ position: relative;
1433
+ inset: auto;
1434
+ height: auto;
1435
+ min-width: 0;
1436
+ }
1437
+ [data-composer-card]:has(> [data-composer-overlay] [data-dsh-study-code])
1438
+ > [data-input-scroll] {
1439
+ display: none;
1440
+ }
1441
+ `
1442
+
1443
+ const languageAliases = { js: 'javascript', ts: 'typescript', py: 'python' }
1444
+ const editorLanguages = ['java', 'python', 'javascript', 'typescript', 'json']
1445
+ const normalizeLanguage = language => Object.hasOwn(languageAliases, language) ? languageAliases[language] : language
1446
+ const validLanguage = language => typeof language === 'string' && /^[a-z0-9][a-z0-9+#._-]{0,31}$/i.test(language.trim()) ? language.trim().toLowerCase() : ''
1447
+
1448
+ function codeFence(text, language) {
1449
+ if (!text) return ''
1450
+ const delimiter = '`'.repeat(Math.max(3, ...[...text.matchAll(/`{3,}/g)].map(match => match[0].length + 1)))
1451
+ return delimiter + language + '\n' + text + '\n' + delimiter
1452
+ }
1453
+
1454
+ function NativeCodeEditor({ text, language, onChange, onSend, onSelection }) {
1455
+ const ref = useRef(null)
1456
+ const editor = useRef(null)
1457
+ const latest = useRef(null)
1458
+ const synchronizing = useRef(false)
1459
+ latest.current = { text, language, onChange, onSend, onSelection }
1460
+
1461
+ useLayoutEffect(() => {
1462
+ const host = ref.current
1463
+ const shadow = host.shadowRoot ?? host.attachShadow({ mode: 'open' })
1464
+ const container = document.createElement('div')
1465
+ container.style.height = '100%'
1466
+ shadow.append(container)
1467
+ const { text: initialText, language: initialLanguage } = latest.current
1468
+ const instance = runtime.DSWTCodeMirror.mount(
1469
+ container, initialText, initialLanguage,
1470
+ value => { if (!synchronizing.current) latest.current.onChange(value) },
1471
+ () => latest.current.onSend(),
1472
+ )
1473
+ editor.current = instance
1474
+ const { view } = instance
1475
+ view.dispatch({ selection: { anchor: initialText.length } })
1476
+ function readSelection() {
1477
+ latest.current.onSelection(view.state.selection.main.head)
1478
+ }
1479
+ function onKey(event) {
1480
+ if (event.key === 'Enter') event.stopPropagation()
1481
+ readSelection()
1482
+ }
1483
+ host.addEventListener('keydown', onKey)
1484
+ host.addEventListener('keyup', readSelection)
1485
+ host.addEventListener('pointerup', readSelection)
1486
+ view.focus()
1487
+ readSelection()
1488
+ return () => {
1489
+ host.removeEventListener('keydown', onKey)
1490
+ host.removeEventListener('keyup', readSelection)
1491
+ host.removeEventListener('pointerup', readSelection)
1492
+ view.destroy()
1493
+ container.remove()
1494
+ editor.current = null
1495
+ }
1496
+ }, [])
1497
+
1498
+ useLayoutEffect(() => editor.current?.setLanguage(language), [language])
1499
+ useLayoutEffect(() => {
1500
+ const view = editor.current?.view
1501
+ if (!view || view.state.doc.toString() === text) return
1502
+ synchronizing.current = true
1503
+ try {
1504
+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } })
1505
+ } finally {
1506
+ synchronizing.current = false
1507
+ }
1508
+ }, [text])
1509
+ return h('div', { ref, style: { minWidth: 0, minHeight: 0, flex: '1 1 0' } })
1510
+ }
1511
+
1512
+ function CodePanel({ useInput, inputActions }) {
1513
+ const state = useStore()
1514
+ const draft = useInput(snapshot => snapshot?.draft ?? '')
1515
+ const hasChips = useInput(snapshot => Boolean(snapshot?.occurrences?.length))
1516
+ const marker = useRef(null)
1517
+ const blocked = useRef(false)
1518
+ const drag = useRef(null)
1519
+ const [caret, setCaret] = useState(0)
1520
+ const [height, setHeight] = useState(null)
1521
+ const [large, setLarge] = useState(false)
1522
+ const [languageChoice, setLanguageChoice] = useState(null)
1523
+ const parsed = unfence(draft)
1524
+ const detectedLanguage = normalizeLanguage(parsed.lang || guessLanguage(parsed.text))
1525
+ const chosenLanguage = languageChoice || detectedLanguage
1526
+ const language = editorLanguages.includes(chosenLanguage) ? chosenLanguage : 'java'
1527
+ const active = state.codeMode && !hasChips
1528
+
1529
+ useEffect(() => {
1530
+ if (!draft) blocked.current = false
1531
+ if (hasChips || state.codeMode || blocked.current) return
1532
+ const detected = guessLanguage(draft)
1533
+ if (parsed.lang || parsed.text !== draft || (detected && editorLanguages.includes(detected))) {
1534
+ store.patch({ codeMode: true })
1535
+ }
1536
+ }, [draft, state.codeMode, hasChips])
1537
+
1538
+ const close = useCallback(() => {
1539
+ blocked.current = true
1540
+ setLanguageChoice(null)
1541
+ store.patch({ codeMode: false })
1542
+ const card = marker.current?.closest('[data-composer-card]')
1543
+ requestAnimationFrame(() => card?.querySelector('[data-composer-input]')?.focus({ preventScroll: true }))
1544
+ }, [])
1545
+
1546
+ useEffect(() => {
1547
+ function onKey(event) {
1548
+ const card = marker.current?.closest('[data-composer-card]')
1549
+ if (!card || !(event.target instanceof Node) || !card.contains(event.target) || event.isComposing) return
1550
+ const toggle = event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey && event.code === 'Space'
1551
+ if ((!toggle && !(active && event.key === 'Escape')) || hasChips) return
1552
+ event.preventDefault()
1553
+ event.stopImmediatePropagation()
1554
+ if (event.repeat) return
1555
+ if (active) close()
1556
+ else store.patch({ codeMode: true })
1557
+ }
1558
+ window.addEventListener('keydown', onKey, true)
1559
+ return () => window.removeEventListener('keydown', onKey, true)
1560
+ }, [active, close, hasChips])
1561
+
1562
+ function send() {
1563
+ if (!parsed.text.trim()) return
1564
+ const fenced = codeFence(parsed.text, languageChoice || parsed.lang || detectedLanguage)
1565
+ if (fenced !== draft) inputActions.setDraft(fenced)
1566
+ close()
1567
+ queueMicrotask(() => inputActions.submit())
1568
+ }
1569
+ function startResize(event) {
1570
+ if (event.button !== 0) return
1571
+ event.preventDefault()
1572
+ event.currentTarget.setPointerCapture(event.pointerId)
1573
+ drag.current = { y: event.clientY, height: marker.current.getBoundingClientRect().height }
1574
+ }
1575
+ function resize(event) {
1576
+ if (!drag.current) return
1577
+ const pixels = drag.current.height + drag.current.y - event.clientY
1578
+ setHeight(Math.max(128, Math.min(innerHeight * .65, pixels)))
1579
+ }
1580
+
1581
+ if (!active) return h('span', { hidden: true, ref: marker })
1582
+
1583
+ const beforeCaret = parsed.text.slice(0, caret)
1584
+ return h('div', {
1585
+ ref: marker,
1586
+ 'data-dsh-study-panel': '',
1587
+ 'data-dsh-study-code': 'true',
1588
+ style: { ...panelStyle, height: height ?? (large ? 'min(62vh, 640px)' : 'min(34vh, 340px)') },
1589
+ },
1590
+ h('style', null, composerPanelCss),
1591
+ h('div', {
1592
+ title: '拖动调整代码编辑器高度',
1593
+ style: { height: 8, flexShrink: 0, cursor: 'ns-resize', background: '#38445d', touchAction: 'none' },
1594
+ onPointerDown: startResize, onPointerMove: resize,
1595
+ onLostPointerCapture: () => { drag.current = null },
1596
+ }),
1597
+ h('div', { style: panelBarStyle },
1598
+ h('span', { style: { color: '#9fb0cd', fontSize: 12 } }, '代码模式'),
1599
+ h('select', {
1600
+ value: languageChoice ?? (editorLanguages.includes(normalizeLanguage(parsed.lang)) ? normalizeLanguage(parsed.lang) : ''),
1601
+ onChange: event => {
1602
+ const value = event.target.value
1603
+ setLanguageChoice(value)
1604
+ if (parsed.text) inputActions.setDraft(codeFence(parsed.text, value))
1605
+ },
1606
+ 'aria-label': '代码语言',
1607
+ style: { ...panelButtonStyle, padding: '2px 4px' },
1608
+ }, ['', ...editorLanguages].map(item => h('option', { key: item, value: item }, item || '自动'))),
1609
+ h('span', { style: { flex: 1 } }),
1610
+ h('button', { type: 'button', onClick: () => { setHeight(null); setLarge(value => !value) }, style: panelButtonStyle }, large ? '复原' : '放大'),
1611
+ h('button', { type: 'button', onClick: send, disabled: !parsed.text.trim(), style: panelButtonStyle }, '发送'),
1612
+ h('button', { type: 'button', onClick: close, style: panelButtonStyle }, '退出'),
1613
+ ),
1614
+ h(NativeCodeEditor, {
1615
+ text: parsed.text, language,
1616
+ onChange: value => inputActions.setDraft(codeFence(value, languageChoice || parsed.lang || detectedLanguage)),
1617
+ onSend: send, onSelection: setCaret,
1618
+ }),
1619
+ h('div', { style: statusStyle },
1620
+ h('span', null, `行 ${beforeCaret.split('\n').length},列 ${beforeCaret.length - beforeCaret.lastIndexOf('\n')}`),
1621
+ h('span', { style: { marginLeft: 'auto' } }, 'Ctrl+Enter 发送 · Ctrl+Shift+Space 退出'),
1622
+ ),
1623
+ )
1624
+ }
1625
+
1626
+ function InputDock(props) {
1627
+ if (props.inputActions === undefined || props.inputActions === null) return null
1628
+ return h(InputDockInner, {
1629
+ useInput: props.useInput,
1630
+ inputActions: props.inputActions,
1631
+ fallbackDraft: props.input?.draft ?? '',
1632
+ })
1633
+ }
1634
+
1635
+ function InputDockInner({ useInput, inputActions, fallbackDraft }) {
1636
+ const state = useStore()
1637
+ const read = typeof useInput === 'function' ? useInput : readerFor(fallbackDraft)
1638
+ const draft = read((snapshot) => snapshot?.draft ?? '') ?? ''
1639
+ const hasChips = read(snapshot => Boolean(snapshot?.occurrences?.length))
1640
+ const insertBlocked = Boolean(hasChips || draft.trim())
1641
+ const [insertNote, setInsertNote] = useState('')
1642
+ const insert = useCallback((code, language) => {
1643
+ if (insertBlocked || typeof code !== 'string' || !code.trim()) return
1644
+ const fence = codeFence(code.replace(/\s+$/, ''), validLanguage(language))
1645
+ const span = inputActions.captureInsertion()
1646
+ if (inputActions.insertText(fence, { ...span, start: span.end })) {
1647
+ setInsertNote('')
1648
+ store.patch({ codeMode: true })
1649
+ } else setInsertNote('输入框已变化,请重试')
1650
+ }, [insertBlocked, inputActions])
1651
+
1652
+ useEffect(() => {
1653
+ const spec = state.autoStarter
1654
+ if (!spec) return
1655
+ store.patch({ autoStarter: null })
1656
+ if (hasChips || draft.trim() || typeof spec.starterCode !== 'string' || !spec.starterCode.trim()) return
1657
+ const instructions = Array.isArray(spec.instructions) ? spec.instructions : []
1658
+ const prefix = instructions.filter(t => typeof t === 'string' && t.trim()).map(t => '// ' + t.replace(/[\r\n]+/g, ' ')).join('\n')
1659
+ insert((prefix ? prefix + '\n' : '') + spec.starterCode, typeof spec.language === 'string' ? spec.language : '')
1660
+ }, [state.autoStarter])
1661
+ const bar = []
1662
+ if (state.requirements !== null) {
1663
+ bar.push(h(RequirementsCard, {
1664
+ key: 'req',
1665
+ spec: state.requirements,
1666
+ onInsert: insert,
1667
+ insertBlocked,
1668
+ onClose: () => { setInsertNote(''); store.patch({ requirements: null }) },
1669
+ }))
1670
+ if (insertNote) bar.push(h('div', { key: 'insert-note', role: 'status', style: { color: SOFT, fontSize: '11px' } }, insertNote))
1671
+ }
1672
+ if (bar.length === 0) return null
1673
+ return h('div', { 'data-dsh-study-panel': '', style: { margin: '0 10px', maxHeight: '30vh', overflowY: 'auto' } }, h('style', null, composerPanelCss), bar)
1674
+ }
1675
+
1676
+ /* ------------------------------------------------------------------ *
1677
+ * 9. 注册
1678
+ * ------------------------------------------------------------------ */
1679
+
1680
+ return {DsToolsFence,InputChips,CodePanel,InputDock,QuizDrawer};
1681
+ }
1682
+ const sessions=new Map();
1683
+ function sessionComponent(name, sendQuizReview){
1684
+ return function SessionComponent(props){
1685
+ const session=props.useSession(snapshot=>snapshot);
1686
+ const id=props.sessionId||session?.id;
1687
+ if(!id)return null;
1688
+ if(!sessions.has(id))sessions.set(id,createComponents());
1689
+ return h(sessions.get(id)[name], name === 'QuizDrawer' ? {...props, sessionId:id, sendQuizReview} : props);
1690
+ };
1691
+ }
1692
+ return {
1693
+ inject:['slots','sessions','conversation'],
1694
+ apply(ctx){
1695
+ ctx.effect(() => {
1696
+ const style = document.createElement('style')
1697
+ style.textContent = quizStyles
1698
+ document.head.append(style)
1699
+ return () => style.remove()
1700
+ })
1701
+ async function sendQuizReview(sessionId, text) {
1702
+ const scope = ctx.sessions.scope(sessionId)
1703
+ const conversation = scope?.get('conversation')
1704
+ if (!conversation) throw new Error('Session conversation unavailable')
1705
+ await conversation.send(text)
1706
+ }
1707
+ for(const [name,slot,order,key] of [
1708
+ ['DsToolsFence','conversation.chat.markdown.fence',0,'ds_tools'],
1709
+ ['InputChips','conversation.input.right',20],
1710
+ ['CodePanel','conversation.input.overlay',41],
1711
+ ['InputDock','conversation.input.overlay',40],
1712
+ ['QuizDrawer','conversation.composer.dock',50]
1713
+ ])ctx.slots.inject(slot,()=>ctx.slots.register({name:slot,id:'dsh-study-tools/'+name,order,...(key?{key}:{})},sessionComponent(name,sendQuizReview)));
1714
+ ctx.effect(()=>()=>sessions.clear());
1715
+ }
1716
+ };
1717
+ }
1718
+ });