pi-scenes 0.11.1 → 0.13.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/README.md +17 -1
- package/assets/scene-prompts/learning/notes.md +20 -0
- package/assets/scene-prompts/productivity/task-review.md +10 -0
- package/assets/scene-skills/data/validate-data/SKILL.md +383 -0
- package/assets/scene-skills/data/write-query/SKILL.md +122 -0
- package/assets/scene-skills/learning/course-book/SKILL.md +157 -0
- package/assets/scene-skills/learning/course-book/annotate.js +522 -0
- package/assets/scene-skills/learning/course-book/assets/book.css +1167 -0
- package/assets/scene-skills/learning/course-book/assets/paging.js +234 -0
- package/assets/scene-skills/learning/course-book/book.css +1167 -0
- package/assets/scene-skills/learning/course-book/build.py +277 -0
- package/assets/scene-skills/learning/course-book/paging.js +234 -0
- package/assets/scene-skills/learning/eli5/SKILL.md +26 -0
- package/assets/scene-skills/pm/sprint-planning/SKILL.md +94 -0
- package/assets/scene-skills/pm/write-spec/SKILL.md +250 -0
- package/assets/scene-skills/productivity/task-management/SKILL.md +91 -0
- package/extensions/scenes.ts +256 -8
- package/package.json +35 -35
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
/* course-book · annotate.js — 浏览器内标注层(书桌模式下激活)
|
|
2
|
+
* 划选文字 → 浮动按钮 → 备注框(类型 + 处理方式);双击段落 → 段落级批注;
|
|
3
|
+
* 练习块「作答」按钮 → 答案标注;右侧面板管理全部备注;
|
|
4
|
+
* 标注锚定采用 W3C TextQuoteSelector(exact + prefix/suffix + 章节内偏移),
|
|
5
|
+
* 经 POST /annotations 落盘,由 AI 侧「处理书稿备注」流程消化。
|
|
6
|
+
* file:// 打开时自动休眠(fetch 失败即 inert,不影响阅读与打印)。
|
|
7
|
+
*/
|
|
8
|
+
(() => {
|
|
9
|
+
if (window.__courseBookAnno) return;
|
|
10
|
+
window.__courseBookAnno = true;
|
|
11
|
+
|
|
12
|
+
/* 全局错误自报:标注层任何炸裂都可见,绝不无声 */
|
|
13
|
+
let errOnce = false;
|
|
14
|
+
window.addEventListener("error", (e) => {
|
|
15
|
+
if (errOnce) return; errOnce = true;
|
|
16
|
+
try {
|
|
17
|
+
const t = document.createElement("div");
|
|
18
|
+
t.className = "cb-toast show";
|
|
19
|
+
t.style.cssText = "position:fixed;left:50%;bottom:4.4rem;transform:translateX(-50%);z-index:130;background:#a03b2a;color:#fff;font:600 13px/1.4 sans-serif;padding:.7rem 1.1rem;border-radius:8px;max-width:80vw";
|
|
20
|
+
t.textContent = "⚠ 标注层报错:" + (e.message || "unknown") + "(详情见控制台,请发给老师)";
|
|
21
|
+
document.body.appendChild(t);
|
|
22
|
+
setTimeout(() => t.remove(), 6000);
|
|
23
|
+
} catch {}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const TYPES = {
|
|
27
|
+
question: { icon: "❓", label: "疑问", color: "#b0541f" },
|
|
28
|
+
suggest: { icon: "✏️", label: "修改建议", color: "#3d5a73" },
|
|
29
|
+
bug: { icon: "🐛", label: "错误报告", color: "#a03b2a" },
|
|
30
|
+
discuss: { icon: "💬", label: "讨论", color: "#8a8272" },
|
|
31
|
+
answer: { icon: "✍️", label: "作答", color: "#3f7a3f" },
|
|
32
|
+
};
|
|
33
|
+
const DISPOS = {
|
|
34
|
+
sidebar: "进书 · 读者问答(默认)",
|
|
35
|
+
rewrite: "进书 · 改写正文",
|
|
36
|
+
chat: "只聊 · 不改书",
|
|
37
|
+
};
|
|
38
|
+
const PRIORITY = { bug: 0, question: 1, answer: 2, suggest: 3, discuss: 4 };
|
|
39
|
+
|
|
40
|
+
const state = { items: [], dialogOpen: false, stamp: 0 };
|
|
41
|
+
|
|
42
|
+
/* ---------- 轻提示 toast ---------- */
|
|
43
|
+
let toastEl = null, toastTimer = null;
|
|
44
|
+
function toast(msg) {
|
|
45
|
+
if (!toastEl) {
|
|
46
|
+
toastEl = document.createElement("div");
|
|
47
|
+
toastEl.className = "cb-toast";
|
|
48
|
+
document.body.appendChild(toastEl);
|
|
49
|
+
}
|
|
50
|
+
toastEl.textContent = msg;
|
|
51
|
+
toastEl.classList.add("show");
|
|
52
|
+
clearTimeout(toastTimer);
|
|
53
|
+
toastTimer = setTimeout(() => toastEl?.classList.remove("show"), 2600);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/* ---------- 工具 ---------- */
|
|
57
|
+
const $ = (s, r = document) => r.querySelector(s);
|
|
58
|
+
const esc = (s) => String(s).replace(/[&<>"']/g, (c) =>
|
|
59
|
+
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
60
|
+
const fmtTime = (iso) => new Date(iso).toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
|
|
61
|
+
|
|
62
|
+
/* ---------- API ---------- */
|
|
63
|
+
async function loadAll() {
|
|
64
|
+
const r = await fetch("/annotations");
|
|
65
|
+
if (!r.ok) throw new Error(r.status);
|
|
66
|
+
state.items = await r.json();
|
|
67
|
+
}
|
|
68
|
+
async function save(item) {
|
|
69
|
+
const r = await fetch("/annotations", {
|
|
70
|
+
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(item),
|
|
71
|
+
});
|
|
72
|
+
if (!r.ok) throw new Error(r.status);
|
|
73
|
+
const saved = await r.json();
|
|
74
|
+
const i = state.items.findIndex((x) => x.id === saved.id);
|
|
75
|
+
i >= 0 ? (state.items[i] = saved) : state.items.push(saved);
|
|
76
|
+
return saved;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* ---------- 锚点:构建与查找(W3C TextQuoteSelector 风格) ---------- */
|
|
80
|
+
// 章节文本地图:把 section.chapter 内所有文本节点拉平成全文 + 位置索引
|
|
81
|
+
function textMap(chapter) {
|
|
82
|
+
const nodes = [];
|
|
83
|
+
const index = new Map();
|
|
84
|
+
const walker = document.createTreeWalker(chapter, NodeFilter.SHOW_TEXT);
|
|
85
|
+
let n, text = "";
|
|
86
|
+
while ((n = walker.nextNode())) {
|
|
87
|
+
index.set(n, text.length);
|
|
88
|
+
nodes.push({ node: n, start: text.length });
|
|
89
|
+
text += n.nodeValue;
|
|
90
|
+
}
|
|
91
|
+
return { nodes, index, text, end: text.length };
|
|
92
|
+
}
|
|
93
|
+
// range 端点→章节全文偏移:探针 range 从章节起点重到目标端点,
|
|
94
|
+
// 其 toString 长度即偏移(文本/元素容器同构可靠,不依赖 TreeWalker 根语义)
|
|
95
|
+
function endPointOffset(container, offset, chapter) {
|
|
96
|
+
const probe = document.createRange();
|
|
97
|
+
probe.setStart(chapter, 0);
|
|
98
|
+
if (container.nodeType === Node.TEXT_NODE) {
|
|
99
|
+
probe.setEnd(container, Math.min(offset, container.nodeValue.length));
|
|
100
|
+
} else {
|
|
101
|
+
probe.setEnd(container, Math.min(offset, container.childNodes.length));
|
|
102
|
+
}
|
|
103
|
+
return probe.toString().length;
|
|
104
|
+
}
|
|
105
|
+
function buildAnchor(range, chapter) {
|
|
106
|
+
const map = textMap(chapter);
|
|
107
|
+
const exact = range.toString();
|
|
108
|
+
if (!exact.trim()) return null;
|
|
109
|
+
// range 在章节全文中的起止(文本/元素容器均兼容)
|
|
110
|
+
const start = endPointOffset(range.startContainer, range.startOffset, chapter);
|
|
111
|
+
const end = endPointOffset(range.endContainer, range.endOffset, chapter);
|
|
112
|
+
if (start < 0 || end < start || end > map.text.length) return null;
|
|
113
|
+
if (map.text.slice(start, end) !== exact) return null; // 安全网
|
|
114
|
+
const prefix = map.text.slice(Math.max(0, start - 32), start);
|
|
115
|
+
const suffix = map.text.slice(end, end + 32);
|
|
116
|
+
return {
|
|
117
|
+
mode: "quote", exact, prefix, suffix,
|
|
118
|
+
start, end, chapterTextLen: map.text.length,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
// 改写后重新定位:先 exact+prefix 精确匹配,退化为偏移,再退化为 fuzzy(去空白匹配)
|
|
122
|
+
function findRange(item, chapter) {
|
|
123
|
+
const map = textMap(chapter);
|
|
124
|
+
const a = item.anchor;
|
|
125
|
+
let idx = -1;
|
|
126
|
+
const strict = a.prefix + a.exact;
|
|
127
|
+
const at = map.text.indexOf(strict);
|
|
128
|
+
if (at >= 0) idx = at + a.prefix.length;
|
|
129
|
+
if (idx < 0) { // 偏移兜底(同章长度未剧变时)
|
|
130
|
+
if (a.start != null && a.end <= map.text.length && map.text.slice(a.start, a.end) === a.exact) idx = a.start;
|
|
131
|
+
}
|
|
132
|
+
if (idx < 0) { // fuzzy:压缩空白后匹配
|
|
133
|
+
const norm = (s) => s.replace(/\s+/g, "");
|
|
134
|
+
const ne = norm(a.exact);
|
|
135
|
+
let i = 0; const hits = [];
|
|
136
|
+
while (i < map.text.length && hits.length < 5) {
|
|
137
|
+
const j = norm(map.text.slice(i, i + ne.length + 40)).indexOf(ne);
|
|
138
|
+
if (j < 0) break;
|
|
139
|
+
i += Math.max(1, j); hits.push(i);
|
|
140
|
+
}
|
|
141
|
+
if (hits.length === 1) idx = hits[0];
|
|
142
|
+
}
|
|
143
|
+
if (idx < 0) return null;
|
|
144
|
+
return offsetsToRange(map, idx, idx + a.exact.length);
|
|
145
|
+
}
|
|
146
|
+
function offsetsToRange(map, start, end) {
|
|
147
|
+
const r = document.createRange();
|
|
148
|
+
let s = null, e = null;
|
|
149
|
+
for (const { node, start: ns } of map.nodes) {
|
|
150
|
+
const len = node.nodeValue.length;
|
|
151
|
+
if (s === null && start < ns + len) s = { node, off: start - ns };
|
|
152
|
+
if (end <= ns + len) { e = { node, off: end - ns }; break; }
|
|
153
|
+
}
|
|
154
|
+
if (!s || !e) return null;
|
|
155
|
+
r.setStart(s.node, Math.max(0, s.off));
|
|
156
|
+
r.setEnd(e.node, Math.min(e.node.length, e.off));
|
|
157
|
+
return r;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/* ---------- 高亮渲染 ---------- */
|
|
161
|
+
function clearMarks() {
|
|
162
|
+
document.querySelectorAll("mark.cb-anno").forEach((m) => {
|
|
163
|
+
const parent = m.parentNode;
|
|
164
|
+
while (m.firstChild) parent.insertBefore(m.firstChild, m);
|
|
165
|
+
parent.normalize(); m.remove();
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
function highlight(item, range) {
|
|
169
|
+
// 跨元素选择:把相交的每个文本节点片段各自包一个 mark(共享 data-id)
|
|
170
|
+
const map = (() => { // 局部:range 覆盖的文本节点
|
|
171
|
+
const arr = []; const w = document.createTreeWalker(range.commonAncestorContainer.nodeType === 1 ? range.commonAncestorContainer : range.commonAncestorContainer.parentNode, NodeFilter.SHOW_TEXT);
|
|
172
|
+
let n; while ((n = w.nextNode())) if (range.intersectsNode(n)) arr.push(n);
|
|
173
|
+
return arr;
|
|
174
|
+
})();
|
|
175
|
+
const t = TYPES[item.type] || TYPES.discuss;
|
|
176
|
+
for (const node of map) {
|
|
177
|
+
let s = 0, e = node.nodeValue.length;
|
|
178
|
+
if (node === range.startContainer) s = range.startOffset;
|
|
179
|
+
if (node === range.endContainer) e = range.endOffset;
|
|
180
|
+
if (e <= s) continue;
|
|
181
|
+
const mark = document.createElement("mark");
|
|
182
|
+
mark.className = "cb-anno" + (item.status === "resolved" ? " resolved" : "");
|
|
183
|
+
mark.dataset.id = item.id;
|
|
184
|
+
mark.style.setProperty("--anno-color", t.color);
|
|
185
|
+
node.splitText(e); const mid = node.splitText(s);
|
|
186
|
+
mid.parentNode.insertBefore(mark, mid);
|
|
187
|
+
mark.appendChild(mid);
|
|
188
|
+
mark.addEventListener("click", () => openDialog(item, null));
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function render() {
|
|
192
|
+
clearMarks();
|
|
193
|
+
let lost = 0;
|
|
194
|
+
for (const item of state.items) {
|
|
195
|
+
if (item.status === "archived") continue; // 已吸收进正文:退役,不再渲染
|
|
196
|
+
const ch = document.getElementById(item.chapter);
|
|
197
|
+
if (!ch) { lost++; continue; }
|
|
198
|
+
const range = item.anchor?.mode === "quote" && findRange(item, ch);
|
|
199
|
+
if (!range) { lost++; badgeLost(item, ch); continue; }
|
|
200
|
+
highlight(item, range);
|
|
201
|
+
}
|
|
202
|
+
renderPanel();
|
|
203
|
+
return lost;
|
|
204
|
+
}
|
|
205
|
+
function badgeLost(item, chapter) {
|
|
206
|
+
const host = chapter.querySelector(".chapter-opener") || chapter;
|
|
207
|
+
if (host.querySelector(`.cb-lost[data-id="${item.id}"]`)) return;
|
|
208
|
+
const b = document.createElement("span");
|
|
209
|
+
b.className = "cb-lost"; b.dataset.id = item.id;
|
|
210
|
+
b.textContent = `⚓ 锚点失效:${TYPES[item.type]?.icon ?? ""}${(item.note || "").slice(0, 24)}…`;
|
|
211
|
+
b.addEventListener("click", () => openDialog(item, null));
|
|
212
|
+
host.appendChild(b);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/* ---------- 浮动按钮 + 备注框 ---------- */
|
|
216
|
+
let floatBtn = null;
|
|
217
|
+
function hideFloat() { floatBtn?.remove(); floatBtn = null; }
|
|
218
|
+
function showFloat(x, y, type) {
|
|
219
|
+
hideFloat();
|
|
220
|
+
floatBtn = document.createElement("button");
|
|
221
|
+
floatBtn.className = "cb-float";
|
|
222
|
+
const t = TYPES[type];
|
|
223
|
+
floatBtn.innerHTML = `${t.icon} ${t.label === "作答" ? "作答" : "备注"}`;
|
|
224
|
+
floatBtn.style.left = Math.min(x, innerWidth - 130) + "px";
|
|
225
|
+
floatBtn.style.top = Math.max(8, y - 44) + "px";
|
|
226
|
+
floatBtn.addEventListener("mousedown", (ev) => ev.preventDefault()); // 保住选区
|
|
227
|
+
floatBtn.addEventListener("click", () => { hideFloat(); dialogFromSelection(type); });
|
|
228
|
+
document.body.appendChild(floatBtn);
|
|
229
|
+
}
|
|
230
|
+
let pending = null; // {type, range, chapter, exercise?}
|
|
231
|
+
function dialogFromSelection(type) {
|
|
232
|
+
try {
|
|
233
|
+
const sel = getSelection();
|
|
234
|
+
if (!sel.rangeCount) return;
|
|
235
|
+
const range = sel.getRangeAt(0);
|
|
236
|
+
const chapter = range.startContainer.parentElement?.closest("section.chapter");
|
|
237
|
+
if (!chapter) return;
|
|
238
|
+
const anchor = buildAnchor(range, chapter);
|
|
239
|
+
if (!anchor) { toast("⚠ 锚点构建失败,请重选一段文字再试"); return; }
|
|
240
|
+
openDialog({ type, disposition: type === "answer" ? "answer" : "sidebar", chapter: chapter.id, anchor, note: "", exercise: exerciseIdOf(range) }, null);
|
|
241
|
+
} catch (err) {
|
|
242
|
+
console.error("[course-book] dialogFromSelection:", err);
|
|
243
|
+
toast("⚠ 弹窗失败:" + err.message + "(请把控制台报错发给老师)");
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function exerciseIdOf(range) {
|
|
247
|
+
const el = range.startContainer.parentElement?.closest(".exercise");
|
|
248
|
+
if (!el) return null;
|
|
249
|
+
const head = el.querySelector(".ex-head")?.textContent.match(/练习\s*[\d-]+[A-Z]/)?.[0];
|
|
250
|
+
return head || null;
|
|
251
|
+
}
|
|
252
|
+
function dialogFromElement(el, type) { // 双击段落 / 练习作答
|
|
253
|
+
try {
|
|
254
|
+
const chapter = el.closest("section.chapter");
|
|
255
|
+
if (!chapter) return;
|
|
256
|
+
const r = document.createRange(); r.selectNodeContents(el);
|
|
257
|
+
const anchor = buildAnchor(r, chapter);
|
|
258
|
+
if (!anchor) { toast("⚠ 锚点构建失败(该元素无文本?),请改用划选文字备注"); return; }
|
|
259
|
+
const isEx = el.classList.contains("exercise");
|
|
260
|
+
openDialog({
|
|
261
|
+
type: isEx ? "answer" : type || "question",
|
|
262
|
+
disposition: isEx ? "answer" : "sidebar",
|
|
263
|
+
chapter: chapter.id, anchor,
|
|
264
|
+
note: "", exercise: isEx ? (el.querySelector(".ex-head")?.textContent.match(/练习\s*[\d-]+[A-Z]/)?.[0] || null) : null,
|
|
265
|
+
}, null);
|
|
266
|
+
} catch (err) {
|
|
267
|
+
console.error("[course-book] dialogFromElement:", err);
|
|
268
|
+
toast("⚠ 弹窗失败:" + err.message + "(请把控制台报错发给老师)");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const dlg = document.createElement("div");
|
|
273
|
+
dlg.className = "cb-dialog"; dlg.style.display = "none";
|
|
274
|
+
dlg.innerHTML = `
|
|
275
|
+
<div class="cb-card">
|
|
276
|
+
<p class="cb-quote"></p>
|
|
277
|
+
<div class="cb-types"></div>
|
|
278
|
+
<textarea class="cb-note" placeholder="写下你的备注:不懂的地方提问;或直接写「重写:…」「改为:…」等明确指令,AI 将照做"></textarea>
|
|
279
|
+
<div class="cb-dispo">
|
|
280
|
+
<span class="cb-lbl">处理方式</span>
|
|
281
|
+
<select class="cb-dispo-sel">
|
|
282
|
+
<option value="sidebar">进书 · 读者问答(默认)</option>
|
|
283
|
+
<option value="rewrite">进书 · 改写正文</option>
|
|
284
|
+
<option value="chat">只聊 · 不改书</option>
|
|
285
|
+
</select>
|
|
286
|
+
</div>
|
|
287
|
+
<p class="cb-hint"></p>
|
|
288
|
+
<div class="cb-actions">
|
|
289
|
+
<button class="cb-btn ghost cb-cancel">取消 (Esc)</button>
|
|
290
|
+
<button class="cb-btn primary cb-ok">保存 (⌘↵)</button>
|
|
291
|
+
</div>
|
|
292
|
+
</div>`;
|
|
293
|
+
document.body.appendChild(dlg);
|
|
294
|
+
const q = (s) => dlg.querySelector(s);
|
|
295
|
+
q(".cb-types").innerHTML = Object.entries(TYPES)
|
|
296
|
+
.filter(([k]) => k !== "answer")
|
|
297
|
+
.map(([k, t]) => `<button type="button" data-t="${k}" class="cb-type">${t.icon} ${t.label}</button>`).join("");
|
|
298
|
+
function setType(t) {
|
|
299
|
+
pending = { ...pending, type: t };
|
|
300
|
+
q(".cb-types").querySelectorAll(".cb-type").forEach((b) => b.classList.toggle("on", b.dataset.t === t));
|
|
301
|
+
q(".cb-dispo").style.display = t === "answer" ? "none" : "";
|
|
302
|
+
q(".cb-hint").textContent = t === "answer" ? "作答由 AI 批改后补入书中答案栏" : "";
|
|
303
|
+
}
|
|
304
|
+
q(".cb-types").addEventListener("click", (e) => { const b = e.target.closest(".cb-type"); if (b) setType(b.dataset.t); });
|
|
305
|
+
function openDialog(item, _patch) {
|
|
306
|
+
state.dialogOpen = true;
|
|
307
|
+
pending = { ...item };
|
|
308
|
+
q(".cb-quote").textContent = item.anchor?.mode === "quote" ? `「${item.anchor.exact.slice(0, 90)}${item.anchor.exact.length > 90 ? "…" : ""}」` : "";
|
|
309
|
+
q(".cb-note").value = item.note || "";
|
|
310
|
+
q(".cb-dispo-sel").value = item.disposition === "answer" ? "sidebar" : item.disposition;
|
|
311
|
+
q(".cb-dispo-sel").style.display = item.type === "answer" ? "none" : "";
|
|
312
|
+
q(".cb-dispo").style.display = item.type === "answer" ? "none" : "";
|
|
313
|
+
setType(item.type);
|
|
314
|
+
dlg.style.display = "";
|
|
315
|
+
q(".cb-note").focus();
|
|
316
|
+
if (_patch) { // 已有备注:补出「标记解决」
|
|
317
|
+
if (!q(".cb-resolve")) {
|
|
318
|
+
const rb = document.createElement("button");
|
|
319
|
+
rb.className = "cb-btn ghost cb-resolve"; rb.textContent = "标记已解决";
|
|
320
|
+
q(".cb-actions").insertBefore(rb, q(".cb-ok"));
|
|
321
|
+
rb.addEventListener("click", async () => {
|
|
322
|
+
await save({ ...item, note: q(".cb-note").value, status: "resolved" });
|
|
323
|
+
closeDialog(); render();
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function closeDialog() { state.dialogOpen = false; dlg.style.display = "none"; dlg.querySelector(".cb-resolve")?.remove(); }
|
|
329
|
+
q(".cb-cancel").addEventListener("click", closeDialog);
|
|
330
|
+
q(".cb-ok").addEventListener("click", submit);
|
|
331
|
+
dlg.addEventListener("keydown", (e) => {
|
|
332
|
+
if (e.key === "Escape") closeDialog();
|
|
333
|
+
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) submit();
|
|
334
|
+
});
|
|
335
|
+
async function submit() {
|
|
336
|
+
if (!pending) return;
|
|
337
|
+
const note = q(".cb-note").value.trim();
|
|
338
|
+
if (!note) { q(".cb-note").focus(); return; }
|
|
339
|
+
const item = {
|
|
340
|
+
...pending,
|
|
341
|
+
note,
|
|
342
|
+
disposition: pending.type === "answer" ? "answer" : q(".cb-dispo-sel").value,
|
|
343
|
+
status: "open",
|
|
344
|
+
created: new Date().toISOString(),
|
|
345
|
+
};
|
|
346
|
+
await save(item);
|
|
347
|
+
closeDialog(); render(); flash(item.id);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/* ---------- 选区交互 ---------- */
|
|
351
|
+
document.addEventListener("mouseup", (e) => {
|
|
352
|
+
if (dlg.style.display !== "none" || e.target?.closest?.(".cb-panel,.cb-dialog,.cb-float")) return;
|
|
353
|
+
setTimeout(() => {
|
|
354
|
+
const sel = getSelection();
|
|
355
|
+
const txt = sel?.toString().trim();
|
|
356
|
+
if (!txt || txt.length < 2 || !sel.rangeCount) return hideFloat();
|
|
357
|
+
const r = sel.getRangeAt(0);
|
|
358
|
+
if (!r.startContainer.parentElement?.closest("section.chapter")) {
|
|
359
|
+
hideFloat();
|
|
360
|
+
if (e.target.closest?.("section.cover, nav.toc"))
|
|
361
|
+
toast("此处是封面/目录,暂不支持备注——到章节正文划选文字或双击段落");
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const rect = r.getBoundingClientRect();
|
|
365
|
+
showFloat(e.clientX, rect.top + scrollY, "question");
|
|
366
|
+
}, 10);
|
|
367
|
+
});
|
|
368
|
+
document.addEventListener("dblclick", (e) => {
|
|
369
|
+
const el = e.target.closest("p,li,h2,h3,.abstract,td,dd,figcaption,pre");
|
|
370
|
+
if (!el || !el.closest("section.chapter")) return;
|
|
371
|
+
dialogFromElement(el, "question");
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
/* ---------- 右侧面板 ---------- */
|
|
375
|
+
const panel = document.createElement("aside");
|
|
376
|
+
panel.className = "cb-panel";
|
|
377
|
+
panel.innerHTML = `
|
|
378
|
+
<button class="cb-toggle" title="备注面板">🗒 <span class="cb-count"></span></button>
|
|
379
|
+
<div class="cb-body">
|
|
380
|
+
<div class="cb-head"><strong>书稿备注</strong><span class="cb-sum"></span></div>
|
|
381
|
+
<div class="cb-filter"></div>
|
|
382
|
+
<ol class="cb-list"></ol>
|
|
383
|
+
</div>`;
|
|
384
|
+
document.body.appendChild(panel);
|
|
385
|
+
panel.querySelector(".cb-toggle").addEventListener("click", () => panel.classList.toggle("open"));
|
|
386
|
+
function renderPanel() {
|
|
387
|
+
const open = state.items.filter((i) => i.status === "open");
|
|
388
|
+
const visible = state.items.filter((i) => i.status !== "archived");
|
|
389
|
+
const archived = state.items.length - visible.length;
|
|
390
|
+
panel.querySelector(".cb-count").textContent = open.length || "";
|
|
391
|
+
panel.querySelector(".cb-count").classList.toggle("any", open.length > 0);
|
|
392
|
+
panel.querySelector(".cb-sum").textContent = open.length ? `${open.length} 待处理 · ${visible.length - open.length} 已解决` + (archived ? ` · 归档 ${archived}` : "") : visible.length ? "全部已解决 🎉" + (archived ? ` · 归档 ${archived}` : "") : "尚无备注";
|
|
393
|
+
const list = panel.querySelector(".cb-list");
|
|
394
|
+
list.innerHTML = [...visible]
|
|
395
|
+
.sort((a, b) => (a.status === b.status ? (PRIORITY[a.type] ?? 9) - (PRIORITY[b.type] ?? 9) : a.status === "open" ? -1 : 1))
|
|
396
|
+
.map((i) => {
|
|
397
|
+
const t = TYPES[i.type] || TYPES.discuss;
|
|
398
|
+
const res = i.status === "resolved" && i.resolution ? `<p class="cb-res">✅ ${esc(i.resolution.summary || "")}</p>` : "";
|
|
399
|
+
const dispo = i.type === "answer" ? "作答" : (DISPOS[i.disposition] || "").split("(")[0];
|
|
400
|
+
return `<li class="${i.status}" data-id="${i.id}" style="--anno-color:${t.color}">
|
|
401
|
+
<p class="cb-li-head">${t.icon} ${t.label}<span class="cb-li-dispo">${dispo}</span><span class="cb-li-time">${fmtTime(i.created)}</span></p>
|
|
402
|
+
<p class="cb-li-note">${esc((i.note || "").slice(0, 140))}${(i.note || "").length > 140 ? "…" : ""}</p>
|
|
403
|
+
${res}
|
|
404
|
+
</li>`;
|
|
405
|
+
}).join("");
|
|
406
|
+
list.querySelectorAll("li").forEach((li) =>
|
|
407
|
+
li.addEventListener("click", () => { flash(li.dataset.id); const it = state.items.find((x) => x.id === li.dataset.id); if (it) openDialog(it, true); }));
|
|
408
|
+
}
|
|
409
|
+
function flash(id) {
|
|
410
|
+
const m = document.querySelector(`mark.cb-anno[data-id="${id}"]`);
|
|
411
|
+
if (!m) return;
|
|
412
|
+
m.scrollIntoView({ behavior: "smooth", block: "center" });
|
|
413
|
+
document.querySelectorAll(".cb-flash").forEach((x) => x.classList.remove("cb-flash"));
|
|
414
|
+
m.classList.add("cb-flash");
|
|
415
|
+
setTimeout(() => m.classList.remove("cb-flash"), 1600);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/* ---------- 练习块作答按钮 ---------- */
|
|
419
|
+
function injectAnswerButtons() {
|
|
420
|
+
document.querySelectorAll(".exercise").forEach((ex) => {
|
|
421
|
+
if (ex.querySelector(".cb-answer-btn")) return;
|
|
422
|
+
const b = document.createElement("button");
|
|
423
|
+
b.className = "cb-answer-btn"; b.textContent = "✍️ 在此作答";
|
|
424
|
+
b.addEventListener("click", () => dialogFromElement(ex, "answer"));
|
|
425
|
+
ex.appendChild(b);
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/* ---------- 代码块一键复制(全书所有 pre,file:// 亦有回退) ---------- */
|
|
430
|
+
async function copyText(s) {
|
|
431
|
+
try { await navigator.clipboard.writeText(s); return true; }
|
|
432
|
+
catch {
|
|
433
|
+
const ta = document.createElement("textarea");
|
|
434
|
+
ta.value = s; ta.style.cssText = "position:fixed;opacity:0";
|
|
435
|
+
document.body.appendChild(ta); ta.select();
|
|
436
|
+
try { return document.execCommand("copy"); } catch { return false; } finally { ta.remove(); }
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
document.querySelectorAll("pre").forEach((pre) => {
|
|
440
|
+
if (pre.querySelector(".cb-copy-btn")) return;
|
|
441
|
+
const code = pre.innerText; // 注入按钮前先存纯代码文本
|
|
442
|
+
const btn = document.createElement("button");
|
|
443
|
+
btn.className = "cb-copy-btn"; btn.type = "button"; btn.textContent = "复制";
|
|
444
|
+
btn.addEventListener("click", async (e) => {
|
|
445
|
+
e.stopPropagation();
|
|
446
|
+
const okFlag = await copyText(code);
|
|
447
|
+
btn.textContent = okFlag ? "已复制 ✓" : "复制失败";
|
|
448
|
+
btn.classList.add("ok");
|
|
449
|
+
setTimeout(() => { btn.textContent = "复制"; btn.classList.remove("ok"); }, 1500);
|
|
450
|
+
});
|
|
451
|
+
pre.appendChild(btn);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
/* ---------- 热刷新:记住滚动位置 ---------- */
|
|
455
|
+
try {
|
|
456
|
+
const saved = parseInt(sessionStorage.getItem("cb-scroll") || "", 10);
|
|
457
|
+
if (saved > 0) setTimeout(() => scrollTo(0, saved), 60);
|
|
458
|
+
} catch { /* 无 sessionStorage 则跳过 */ }
|
|
459
|
+
|
|
460
|
+
/* ---------- 左侧目录:滚动高亮当前章 ---------- */
|
|
461
|
+
const bookNav = document.querySelector(".book-nav ol");
|
|
462
|
+
if (bookNav) {
|
|
463
|
+
const links = [...bookNav.querySelectorAll("a")];
|
|
464
|
+
const marks = links
|
|
465
|
+
.map((a) => document.getElementById(decodeURIComponent(a.hash.slice(1))))
|
|
466
|
+
.filter(Boolean);
|
|
467
|
+
let ticking = false;
|
|
468
|
+
const spy = () => {
|
|
469
|
+
ticking = false;
|
|
470
|
+
const probe = scrollY + innerHeight * 0.3;
|
|
471
|
+
let cur = -1;
|
|
472
|
+
marks.forEach((el, i) => { if (el.offsetTop <= probe) cur = i; });
|
|
473
|
+
links.forEach((a, i) => a.classList.toggle("on", i === cur));
|
|
474
|
+
};
|
|
475
|
+
addEventListener("scroll", () => { if (!ticking) { ticking = true; requestAnimationFrame(spy); } }, { passive: true });
|
|
476
|
+
spy();
|
|
477
|
+
// 目录开关:窄屏作为覆盖层呼出,宽屏亦可手动开关
|
|
478
|
+
const navBtn = document.createElement("button");
|
|
479
|
+
navBtn.className = "cb-nav-toggle"; navBtn.textContent = "📑 目录"; navBtn.title = "章节目录";
|
|
480
|
+
navBtn.addEventListener("click", (e) => { e.stopPropagation(); document.body.classList.toggle("nav-open"); });
|
|
481
|
+
document.body.appendChild(navBtn);
|
|
482
|
+
document.addEventListener("click", (e) => {
|
|
483
|
+
if (document.body.classList.contains("nav-open") && !e.target?.closest?.(".book-nav, .cb-nav-toggle"))
|
|
484
|
+
document.body.classList.remove("nav-open");
|
|
485
|
+
});
|
|
486
|
+
bookNav.addEventListener("click", (e) => {
|
|
487
|
+
if (!matchMedia("(min-width: 1100px)").matches && e.target?.closest?.("a"))
|
|
488
|
+
document.body.classList.remove("nav-open");
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/* ---------- 热刷新轮询 ---------- */
|
|
493
|
+
setInterval(async () => {
|
|
494
|
+
if (state.dialogOpen) return;
|
|
495
|
+
try {
|
|
496
|
+
const r = await fetch(`/poll?stamp=${state.stamp}`);
|
|
497
|
+
const j = await r.json();
|
|
498
|
+
if (state.stamp && j.stamp > state.stamp) {
|
|
499
|
+
try { sessionStorage.setItem("cb-scroll", String(Math.round(scrollY))); } catch {}
|
|
500
|
+
location.reload();
|
|
501
|
+
}
|
|
502
|
+
state.stamp = j.stamp;
|
|
503
|
+
} catch { /* 书桌离线则静默 */ }
|
|
504
|
+
}, 2000);
|
|
505
|
+
|
|
506
|
+
/* ---------- 启动 ---------- */
|
|
507
|
+
(async () => {
|
|
508
|
+
try {
|
|
509
|
+
await loadAll();
|
|
510
|
+
const r = await fetch("/poll"); state.stamp = (await r.json()).stamp;
|
|
511
|
+
const lost = render();
|
|
512
|
+
injectAnswerButtons();
|
|
513
|
+
if (state.items.some((i) => i.status === "open")) panel.classList.add("open");
|
|
514
|
+
if (lost) console.info(`[course-book] ${lost} 条备注锚点退化(改写后失锚),已显示章节级提示`);
|
|
515
|
+
console.info("[course-book] annotate layer v0.3 booted(改动后请跑 selftest.mjs 回归)");
|
|
516
|
+
} catch (err) {
|
|
517
|
+
console.error("[course-book] boot:", err);
|
|
518
|
+
/* 书桌离线则静默休眠;在线但启动失败要说话 */
|
|
519
|
+
try { await fetch("/poll"); toast("⚠ 标注层启动失败:" + err.message); } catch { /* file:// 休眠 */ }
|
|
520
|
+
}
|
|
521
|
+
})();
|
|
522
|
+
})();
|