@lumesync/studio 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.
@@ -0,0 +1,455 @@
1
+ // 通用题目组件:场景里只写 <lume-quiz ref="题目 id"></lume-quiz>,
2
+ // 题干、选项与作答策略全部来自交互数据,避免场景 HTML 与题目配置各写一份。
3
+ // 同一份渲染代码同时供三处使用:学生端/预览 iframe(自定义元素)、
4
+ // Studio 属性页的“学生视角”实时预览。文件保持无构建的经典脚本,挂到 window.LumeQuizView。
5
+ (() => {
6
+ if (typeof window === 'undefined' || window.LumeQuizView) return;
7
+
8
+ // 宿主协议版本:运行时据此判断课件 SDK 是否支持发布状态与提交回填。
9
+ window.LumeQuizProtocol = 2;
10
+
11
+ const TYPE_LABELS = {
12
+ 'single-choice': '单选题',
13
+ 'multi-choice': '多选题',
14
+ 'fill-blank': '填空题',
15
+ code: '代码题',
16
+ open: '开放题',
17
+ };
18
+
19
+ // 记录已挂载的题目,便于学生宿主把服务端判定结果回填到组件。
20
+ const mounted = new Map();
21
+
22
+ const CSS = `
23
+ lume-quiz { display: block; }
24
+ .lq {
25
+ display: flex;
26
+ flex-direction: column;
27
+ gap: 12px;
28
+ color: inherit;
29
+ font: inherit;
30
+ text-align: left;
31
+ }
32
+ .lq-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12px; opacity: .72; }
33
+ .lq-type {
34
+ padding: 1px 9px;
35
+ border-radius: 999px;
36
+ background: rgba(99, 102, 241, .16);
37
+ color: #6366f1;
38
+ font-weight: 600;
39
+ opacity: 1;
40
+ }
41
+ .lq-stem { margin: 0; font-size: clamp(16px, 1.9vw, 22px); font-weight: 600; line-height: 1.5; white-space: pre-wrap; }
42
+ .lq-options { display: grid; gap: 8px; }
43
+ .lq-option {
44
+ display: flex;
45
+ align-items: flex-start;
46
+ gap: 10px;
47
+ padding: 10px 12px;
48
+ border: 1px solid rgba(127, 127, 127, .35);
49
+ border-radius: 10px;
50
+ background: rgba(127, 127, 127, .06);
51
+ cursor: pointer;
52
+ transition: border-color .12s ease, background .12s ease;
53
+ }
54
+ .lq-option:hover { border-color: rgba(99, 102, 241, .7); }
55
+ .lq-option.is-checked { border-color: #6366f1; background: rgba(99, 102, 241, .13); }
56
+ .lq-option input { margin: 3px 0 0; accent-color: #6366f1; }
57
+ .lq-key {
58
+ display: inline-grid;
59
+ place-items: center;
60
+ flex: none;
61
+ width: 22px;
62
+ height: 22px;
63
+ border-radius: 6px;
64
+ border: 1px solid rgba(127, 127, 127, .4);
65
+ font-size: 12px;
66
+ font-weight: 600;
67
+ }
68
+ .lq-option.is-checked .lq-key { border-color: #6366f1; color: #6366f1; }
69
+ .lq-text { line-height: 1.5; }
70
+ .lq-input, .lq-textarea {
71
+ width: 100%;
72
+ padding: 9px 12px;
73
+ border: 1px solid rgba(127, 127, 127, .35);
74
+ border-radius: 10px;
75
+ background: rgba(127, 127, 127, .06);
76
+ color: inherit;
77
+ font: inherit;
78
+ line-height: 1.5;
79
+ }
80
+ .lq-input:focus, .lq-textarea:focus { outline: 2px solid rgba(99, 102, 241, .5); outline-offset: 1px; }
81
+ .lq-textarea { min-height: 96px; resize: vertical; }
82
+ .lq-textarea.is-code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 13px; }
83
+ .lq-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
84
+ .lq-submit {
85
+ padding: 7px 18px;
86
+ border: 0;
87
+ border-radius: 999px;
88
+ background: #4f46e5;
89
+ color: #fff;
90
+ font: inherit;
91
+ cursor: pointer;
92
+ }
93
+ .lq-submit:hover:not(:disabled) { background: #4338ca; }
94
+ .lq-submit:disabled { opacity: .55; cursor: not-allowed; }
95
+ .lq-feedback { font-size: 13px; line-height: 1.5; }
96
+ .lq-feedback.is-ok { color: #10b981; }
97
+ .lq-feedback.is-bad { color: #ef4444; }
98
+ .lq-feedback.is-pending { opacity: .72; }
99
+ .lq-explain { flex-basis: 100%; margin: 0; font-size: 13px; line-height: 1.55; opacity: .8; }
100
+ .lq-status {
101
+ padding: 18px;
102
+ border-radius: 12px;
103
+ background: rgba(127, 127, 127, .08);
104
+ font-size: 14px;
105
+ line-height: 1.6;
106
+ opacity: .8;
107
+ }
108
+ `;
109
+
110
+ function ensureStyles(doc) {
111
+ if (!doc || !doc.head) return;
112
+ if (doc.querySelector('style[data-lume-quiz-style]')) return;
113
+ const style = doc.createElement('style');
114
+ style.setAttribute('data-lume-quiz-style', '');
115
+ style.textContent = CSS;
116
+ doc.head.append(style);
117
+ }
118
+
119
+ // 学生宿主提交后把服务端判定以 postMessage 回填到当前题目,避免重复渲染。
120
+ let listening = false;
121
+ function listenHost() {
122
+ if (listening) return;
123
+ listening = true;
124
+ window.addEventListener('message', (event) => {
125
+ if (window.parent && window.parent !== window && event.source !== window.parent) return;
126
+ const data = event.data;
127
+ if (!data || data.source !== 'lume-quiz-host' || data.type !== 'quiz-result') return;
128
+ const entry = mounted.get(String(data.interactionId ?? ''));
129
+ if (!entry) return;
130
+ const feedback = entry.host.querySelector('.lq-feedback');
131
+ if (!feedback) return;
132
+ const result = data.result && typeof data.result === 'object' ? data.result : {};
133
+ if (result.isCorrect === true) {
134
+ feedback.className = 'lq-feedback is-ok';
135
+ feedback.textContent = '回答正确。';
136
+ } else if (result.isCorrect === false) {
137
+ feedback.className = 'lq-feedback is-bad';
138
+ feedback.textContent = '这次没有答对,可以再检查一下。';
139
+ } else {
140
+ feedback.className = 'lq-feedback is-pending';
141
+ feedback.textContent = '已提交,等待结果。';
142
+ }
143
+ if (result.explain) {
144
+ const foot = feedback.parentElement;
145
+ let explain = foot?.querySelector('.lq-explain');
146
+ if (!explain && foot) {
147
+ explain = entry.host.ownerDocument.createElement('p');
148
+ explain.className = 'lq-explain';
149
+ foot.append(explain);
150
+ }
151
+ if (explain) explain.textContent = String(result.explain);
152
+ }
153
+ });
154
+ }
155
+
156
+ function normalize(raw) {
157
+ const input = raw && typeof raw === 'object' ? raw : {};
158
+ const type = TYPE_LABELS[input.type] ? input.type : 'single-choice';
159
+ const options = Array.isArray(input.options)
160
+ ? input.options
161
+ .filter((option) => option && option.key !== undefined && option.key !== null)
162
+ .map((option) => ({ key: String(option.key), text: String(option.text ?? '') }))
163
+ : [];
164
+ const policy = input.policy && typeof input.policy === 'object' ? input.policy : {};
165
+ return {
166
+ id: typeof input.id === 'string' ? input.id : '',
167
+ type,
168
+ stem: typeof input.stem === 'string' ? input.stem : '',
169
+ options,
170
+ explain: typeof input.explain === 'string' ? input.explain : '',
171
+ points: Number.isFinite(input.points) ? input.points : 1,
172
+ graded: input.graded !== false,
173
+ partialCredit: input.partialCredit === true,
174
+ // 学生端的发布状态由运行时注入;Studio 作者视图没有该字段,默认可见。
175
+ published: input.published !== false,
176
+ closed: input.closed === true,
177
+ policy: {
178
+ maxAttempts: Number.isFinite(policy.maxAttempts) ? policy.maxAttempts : 1,
179
+ lockAfterSubmit: policy.lockAfterSubmit !== false,
180
+ showResultAfterSubmit: policy.showResultAfterSubmit !== false,
181
+ showAnswerAfterSubmit: policy.showAnswerAfterSubmit === true,
182
+ },
183
+ answer: input.answer && typeof input.answer === 'object' ? input.answer : null,
184
+ };
185
+ }
186
+
187
+ // 返回 true / false;没有答案材料(学生端)时返回 null,只上报答案不出结果。
188
+ function grade(quiz, answer) {
189
+ if (!quiz.answer) return null;
190
+ const key = quiz.answer;
191
+ if (quiz.type === 'single-choice') {
192
+ return Boolean(answer?.choice) && String(answer.choice) === String(key.choice);
193
+ }
194
+ if (quiz.type === 'multi-choice') {
195
+ const picked = Array.isArray(answer?.choices) ? answer.choices.map(String) : [];
196
+ const expected = Array.isArray(key.choices) ? key.choices.map(String) : [];
197
+ return picked.length === expected.length && expected.every((item) => picked.includes(item));
198
+ }
199
+ if (quiz.type === 'fill-blank') {
200
+ const picked = Array.isArray(answer?.blanks) ? answer.blanks : [];
201
+ const expected = Array.isArray(key.blanks) ? key.blanks : [];
202
+ return picked.length === expected.length
203
+ && expected.every((item, index) => String(picked[index] ?? '').trim() === String(item).trim());
204
+ }
205
+ if (quiz.type === 'code') {
206
+ return String(answer?.code ?? '').trim() === String(key.code ?? '').trim();
207
+ }
208
+ return null;
209
+ }
210
+
211
+ function render(host, raw, options = {}) {
212
+ const doc = host.ownerDocument || document;
213
+ ensureStyles(doc);
214
+ listenHost();
215
+ const quiz = normalize(raw);
216
+ const state = { submitted: false, attempts: 0 };
217
+
218
+ const root = doc.createElement('div');
219
+ root.className = 'lq';
220
+ if (quiz.id) root.dataset.quizId = quiz.id;
221
+ // 记录挂载点,服务端判定回来后只更新反馈,不重建整个题目。
222
+ if (quiz.id) mounted.set(quiz.id, { host, quiz });
223
+
224
+ // 未发布 / 已截止时只显示状态,不渲染题干选项,避免学生提前作答。
225
+ if (quiz.closed || !quiz.published) {
226
+ const status = doc.createElement('div');
227
+ status.className = 'lq-status';
228
+ status.textContent = quiz.closed ? '本题已截止提交。' : '等待教师发布本题。';
229
+ root.append(status);
230
+ host.replaceChildren(root);
231
+ return {
232
+ quiz,
233
+ element: root,
234
+ getAnswer: () => null,
235
+ submit: () => {},
236
+ };
237
+ }
238
+
239
+ const meta = doc.createElement('div');
240
+ meta.className = 'lq-meta';
241
+ const type = doc.createElement('span');
242
+ type.className = 'lq-type';
243
+ type.textContent = TYPE_LABELS[quiz.type] ?? '题目';
244
+ meta.append(type);
245
+ meta.append(doc.createTextNode(`${quiz.points} 分${quiz.graded ? '' : ' · 不计成绩'}`));
246
+
247
+ const stem = doc.createElement('p');
248
+ stem.className = 'lq-stem';
249
+ stem.textContent = quiz.stem || '(题干待填写)';
250
+ root.append(meta, stem);
251
+
252
+ let readAnswer = () => null;
253
+ let controls = [];
254
+ let answerInputs = [];
255
+
256
+ if (quiz.type === 'single-choice' || quiz.type === 'multi-choice') {
257
+ const list = doc.createElement('div');
258
+ list.className = 'lq-options';
259
+ const multi = quiz.type === 'multi-choice';
260
+ for (const option of quiz.options) {
261
+ const label = doc.createElement('label');
262
+ label.className = 'lq-option';
263
+ const input = doc.createElement('input');
264
+ input.type = multi ? 'checkbox' : 'radio';
265
+ input.name = `lq-${quiz.id || 'quiz'}`;
266
+ input.value = option.key;
267
+ const key = doc.createElement('span');
268
+ key.className = 'lq-key';
269
+ key.textContent = option.key;
270
+ const text = doc.createElement('span');
271
+ text.className = 'lq-text';
272
+ text.textContent = option.text;
273
+ label.append(input, key, text);
274
+ const sync = () => label.classList.toggle('is-checked', input.checked);
275
+ input.addEventListener('change', sync);
276
+ list.append(label);
277
+ answerInputs.push(input);
278
+ }
279
+ if (quiz.options.length === 0) {
280
+ const empty = doc.createElement('div');
281
+ empty.className = 'lq-feedback is-pending';
282
+ empty.textContent = '还没有选项,请在右侧编辑区添加。';
283
+ list.append(empty);
284
+ }
285
+ root.append(list);
286
+ readAnswer = () => {
287
+ const checked = answerInputs.filter((node) => node.checked).map((node) => node.value);
288
+ if (multi) return checked.length > 0 ? { choices: checked } : null;
289
+ return checked.length === 1 ? { choice: checked[0] } : null;
290
+ };
291
+ controls = answerInputs;
292
+ } else if (quiz.type === 'fill-blank') {
293
+ const blanks = Array.isArray(quiz.answer?.blanks) && quiz.answer.blanks.length > 0
294
+ ? quiz.answer.blanks.length
295
+ : 1;
296
+ const inputs = [];
297
+ for (let index = 0; index < blanks; index += 1) {
298
+ const field = doc.createElement('input');
299
+ field.className = 'lq-input';
300
+ field.type = 'text';
301
+ field.placeholder = blanks > 1 ? `第 ${index + 1} 空` : '填写答案';
302
+ field.setAttribute('aria-label', field.placeholder);
303
+ root.append(field);
304
+ inputs.push(field);
305
+ }
306
+ readAnswer = () => {
307
+ const values = inputs.map((node) => node.value.trim());
308
+ return values.some(Boolean) ? { blanks: values } : null;
309
+ };
310
+ controls = inputs;
311
+ } else if (quiz.type === 'code') {
312
+ const area = doc.createElement('textarea');
313
+ area.className = 'lq-textarea is-code';
314
+ area.rows = 8;
315
+ area.spellcheck = false;
316
+ area.placeholder = '在这里写代码';
317
+ root.append(area);
318
+ readAnswer = () => (area.value.trim() ? { code: area.value } : null);
319
+ controls = [area];
320
+ } else {
321
+ const area = doc.createElement('textarea');
322
+ area.className = 'lq-textarea';
323
+ area.rows = 5;
324
+ area.placeholder = '写下你的回答';
325
+ root.append(area);
326
+ readAnswer = () => (area.value.trim() ? { text: area.value } : null);
327
+ controls = [area];
328
+ }
329
+
330
+ const foot = doc.createElement('div');
331
+ foot.className = 'lq-foot';
332
+ const submit = doc.createElement('button');
333
+ submit.type = 'button';
334
+ submit.className = 'lq-submit';
335
+ submit.textContent = quiz.type === 'open' ? '提交给老师' : '提交答案';
336
+ const feedback = doc.createElement('span');
337
+ feedback.className = 'lq-feedback';
338
+ foot.append(submit, feedback);
339
+ root.append(foot);
340
+
341
+ let explain = null;
342
+ const setDisabled = (disabled) => {
343
+ for (const node of controls) node.disabled = disabled;
344
+ submit.disabled = disabled;
345
+ };
346
+
347
+ submit.addEventListener('click', () => {
348
+ const answer = readAnswer();
349
+ if (!answer) {
350
+ feedback.className = 'lq-feedback is-pending';
351
+ feedback.textContent = '请先作答再提交。';
352
+ return;
353
+ }
354
+ state.submitted = true;
355
+ state.attempts += 1;
356
+ const correct = grade(quiz, answer);
357
+ feedback.className = `lq-feedback ${correct === true ? 'is-ok' : correct === false ? 'is-bad' : 'is-pending'}`;
358
+ if (correct === true) feedback.textContent = '回答正确。';
359
+ else if (correct === false) feedback.textContent = '这次没有答对,可以再检查一下。';
360
+ else feedback.textContent = quiz.type === 'open' ? '已提交,等待老师批阅。' : '已提交,等待结果。';
361
+ if (correct === false && quiz.policy.showAnswerAfterSubmit && quiz.explain) {
362
+ explain = doc.createElement('p');
363
+ explain.className = 'lq-explain';
364
+ explain.textContent = quiz.explain;
365
+ foot.append(explain);
366
+ }
367
+ if (quiz.policy.lockAfterSubmit || state.attempts >= quiz.policy.maxAttempts) setDisabled(true);
368
+ options.onSubmit?.(answer, { correct, attempts: state.attempts });
369
+ });
370
+
371
+ host.replaceChildren(root);
372
+ return {
373
+ quiz,
374
+ element: root,
375
+ getAnswer: readAnswer,
376
+ submit: () => submit.click(),
377
+ };
378
+ }
379
+
380
+ // 数据来源优先级:宿主注入的题目表 > 组件内嵌 JSON > data 属性。
381
+ function dataOf(element, ref) {
382
+ const injected = typeof window !== 'undefined' ? window.__lumeQuizzes : null;
383
+ if (injected && ref && injected[ref]) return injected[ref];
384
+ const inline = element.querySelector('script[type="application/json"]');
385
+ if (inline && inline.textContent.trim()) {
386
+ try { return JSON.parse(inline.textContent); } catch { return null; }
387
+ }
388
+ const attr = element.getAttribute('data');
389
+ if (attr) {
390
+ try { return JSON.parse(attr); } catch { return null; }
391
+ }
392
+ return null;
393
+ }
394
+
395
+ function boot(element) {
396
+ if (element.__lumeQuizBooted) return;
397
+ const ref = element.getAttribute('ref') || element.getAttribute('cid') || '';
398
+ const data = dataOf(element, ref);
399
+ if (!data) {
400
+ if (!element.__lumeQuizWaiting) {
401
+ element.__lumeQuizWaiting = true;
402
+ element.textContent = '题目加载中…';
403
+ const retry = () => {
404
+ element.__lumeQuizWaiting = false;
405
+ element.textContent = '';
406
+ boot(element);
407
+ };
408
+ if (document.readyState === 'complete') setTimeout(retry, 0);
409
+ else window.addEventListener('load', retry, { once: true });
410
+ }
411
+ return;
412
+ }
413
+ element.__lumeQuizBooted = true;
414
+ const cid = element.getAttribute('cid') || ref || data.id || 'quiz';
415
+ let store = null;
416
+ const sdk = window.LumeCourseware;
417
+ if (sdk && typeof sdk.createStore === 'function') {
418
+ try { store = sdk.createStore(cid, { answer: null, submitted: false }, null); } catch { store = null; }
419
+ }
420
+ element.__lumeQuizView = render(element, data, {
421
+ onSubmit(answer, info) {
422
+ if (store) {
423
+ try { store.patch({ answer, submitted: true, correct: info.correct ?? null }); } catch { /* 忽略状态同步失败 */ }
424
+ }
425
+ if (sdk && typeof sdk.event === 'function') {
426
+ try {
427
+ sdk.event('quiz.answer', cid, { interactionId: quiz.id || cid, answer });
428
+ } catch { /* 宿主不可用时保留本地反馈 */ }
429
+ }
430
+ element.dispatchEvent(new CustomEvent('lume-quiz-submit', {
431
+ detail: { cid, answer, ...info },
432
+ bubbles: true,
433
+ }));
434
+ },
435
+ });
436
+ }
437
+
438
+ class LumeQuizElement extends HTMLElement {
439
+ connectedCallback() { boot(this); }
440
+ }
441
+
442
+ if (typeof customElements !== 'undefined' && !customElements.get('lume-quiz')) {
443
+ customElements.define('lume-quiz', LumeQuizElement);
444
+ }
445
+
446
+ window.LumeQuizView = {
447
+ TYPES: Object.entries(TYPE_LABELS).map(([value, label]) => ({ value, label })),
448
+ TYPE_LABELS,
449
+ normalize,
450
+ render,
451
+ ensureStyles,
452
+ grade,
453
+ boot,
454
+ };
455
+ })();