diff --git a/Agent.md b/Agent.md index 255e5c16b..861eacd08 100644 --- a/Agent.md +++ b/Agent.md @@ -60,8 +60,8 @@ What EMRG does today — capabilities, not a changelog. Foreground daemon: `python -m emrg`. - Python: `uv run pytest tests/ -v` — re-count with `uv run --no-sync python3 scripts/check-doc-count.py --measure`. Import check: `uv run python -c "from emrg.client.app import run_client"` -GUI: `cd emrg/gui && npm test` (274: 107 daemon_client + 22 conn-manager + 7 integration + 7 nav-policy + 11 gui-state + 9 build-config + 10 config_fields + 16 boot-contract + 3 preload-api + 2 theme-guard + 2 image-hash + 8 switch-session + 19 atp_login + 4 gui-op-log + 9 theme-setting + 5 window-title + 4 frame-route + 11 browser-policy + 5 browser-wiring + 13 settings_store) — syntax: `node --check main.js preload.js daemon_client.js` -Renderer: `cd emrg/gui/renderer && npm run typecheck && npm test` (1271: 5 snapshot-store + 13 utils + 3 ErrorBoundary + 2 App + 12 commands + 4 copywriting + 14 i18n + 33 markdown + 22 selection + 41 transcript + 11 conversationType + 4 MarkdownText + 65 TranscriptView + 22 history + 30 historyReplay + 8 userImages + 43 composer + 97 Composer + 14 sidebar + 32 workspaceView + 18 WorkspaceView + 10 dialog + 6 Dialog + 9 ConfirmDialog + 9 RenameDialog + 13 dialogLists + 3 HelpDialog + 9 MemoryDialog + 8 SkillsDialog + 8 openSession + 6 WelcomeDialog + 20 OpenSessionDialog + 14 NewSessionDialog + 7 rewind + 8 RewindDialog + 7 GithubDeviceDialog + 82 daemonBridge + 13 DaemonBridgeProvider + 68 Shell + 19 page + 51 EditorPanel + 25 DialogHost + 48 SettingsPanel + 18 TaskFormDialog + 5 RantDialog + 8 vendorMarkdown + 10 highlightTheme + 8 ApprovalDialog + 20 SandboxRootsDialog + 42 cockpit + 4 editorSelectionCascade + 9 fileTree + 24 FileTree + 5 contextMenu + 1 residue + 24 StatusBand + 24 UsageRanking + 9 usageRanking + 6 SearchOverlay + 5 ResizeHandle + 8 IconRail + 6 SessionColumn + 5 EmrgMark + 38 editorDoc + 27 CodeEditor + 19 annotation + 10 AnnotationMode) +GUI: `cd emrg/gui && npm test` (279: 107 daemon_client + 22 conn-manager + 7 integration + 7 nav-policy + 11 gui-state + 9 build-config + 10 config_fields + 16 boot-contract + 3 preload-api + 2 theme-guard + 2 image-hash + 8 switch-session + 19 atp_login + 4 gui-op-log + 9 theme-setting + 5 window-title + 4 frame-route + 11 browser-policy + 5 browser-wiring + 13 settings_store + 5 preview-annotation-wiring) — syntax: `node --check main.js preload.js daemon_client.js` +Renderer: `cd emrg/gui/renderer && npm run typecheck && npm test` (1282: 5 snapshot-store + 13 utils + 3 ErrorBoundary + 2 App + 12 commands + 4 copywriting + 14 i18n + 33 markdown + 22 selection + 41 transcript + 11 conversationType + 4 MarkdownText + 65 TranscriptView + 22 history + 30 historyReplay + 8 userImages + 43 composer + 97 Composer + 14 sidebar + 32 workspaceView + 18 WorkspaceView + 10 dialog + 6 Dialog + 9 ConfirmDialog + 9 RenameDialog + 13 dialogLists + 3 HelpDialog + 9 MemoryDialog + 8 SkillsDialog + 8 openSession + 6 WelcomeDialog + 20 OpenSessionDialog + 14 NewSessionDialog + 7 rewind + 8 RewindDialog + 7 GithubDeviceDialog + 82 daemonBridge + 13 DaemonBridgeProvider + 68 Shell + 19 page + 51 EditorPanel + 25 DialogHost + 48 SettingsPanel + 18 TaskFormDialog + 5 RantDialog + 8 vendorMarkdown + 10 highlightTheme + 8 ApprovalDialog + 20 SandboxRootsDialog + 42 cockpit + 4 editorSelectionCascade + 9 fileTree + 24 FileTree + 5 contextMenu + 1 residue + 24 StatusBand + 24 UsageRanking + 9 usageRanking + 6 SearchOverlay + 5 ResizeHandle + 8 IconRail + 6 SessionColumn + 5 EmrgMark + 38 editorDoc + 27 CodeEditor + 26 annotation + 14 AnnotationMode) - CI: pytest on ubuntu **and windows-2025**, the GUI suites, and an actionlint gate over `.github/workflows/`; re-trigger a dropped push with `scripts/re-trigger-ci.sh `, never an empty commit - Merge gates, run before merging — `uv run --no-sync python3 scripts/check-vote-count.py` · `scripts/check-pr-base.py` · `scripts/check-merge-freshness.py` · `scripts/check-merge-order.py` · `scripts/check-merge-landing-diff.py` · `scripts/check-merge-pairs.py` / `scripts/check-merge-sequence.py` · `scripts/check-merge-tree-health.py` (the merged tree passes one guard) · `scripts/check-merge-plan-suite.py` — all under `uv run --no-sync python3` - Post-merge audit: `uv run --no-sync python3 scripts/check-merge-landed.py ` (did it land the reviewed tree) diff --git a/emrg/gui/main.js b/emrg/gui/main.js index 657bd4d13..6b0d70aa5 100644 --- a/emrg/gui/main.js +++ b/emrg/gui/main.js @@ -1140,6 +1140,19 @@ vision = false ipcMain.handle("emrg:previewHtml", async (_e, { path: p } = {}) => showPreview(p)); + // 预览页的批注(宿主 2026-12-03T18:38:18):浮框在预览视图里画,这里是它唯一的上行口。 + // 发送者必须是预览视图本身——别的 webContents 自称「这是预览里的批注」不算;文件路径取 + // 主进程记着的 previewPath,页面报什么地址都不信。 + ipcMain.on("emrg:previewAnnotate", (event, payload) => { + if (!previewView || previewView.webContents !== event.sender) return; + if (!previewPath) return; + const items = Array.isArray(payload && payload.items) ? payload.items : []; + if (!items.length) return; + if (win && !win.isDestroyed()) { + win.webContents.send("emrg:previewAnnotate", { file: previewPath, items }); + } + }); + ipcMain.handle("emrg:closePreview", async (_e, { path: p } = {}) => { // 关闭/切走 HTML tab → 隐藏预览(懒销毁:窗口关闭自动回收,R5-⑤) const target = typeof p === "string" && p.trim() ? path.resolve(p.trim()) : null; @@ -2124,7 +2137,15 @@ vision = false function ensurePreviewView() { if (previewView) return previewView; previewView = new WebContentsView({ - webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false }, + // 宿主 2026-12-03T18:38:18:预览页上的批注浮框画在这个文档内部(应用自己的浮层压不住 + // 一个 contentView 子视图)。preload 因此存在,但它**不挂 contextBridge**:页面拿不到 + // 任何对象,浮框与 IPC 都在 preload 自己的世界里。 + webPreferences: { + sandbox: true, + contextIsolation: true, + nodeIntegration: false, + preload: path.join(__dirname, "preview-preload.js"), + }, }); previewView.webContents.setWindowOpenHandler(() => ({ action: "deny" })); // 同一条:Electron 31 传的是 details 对象,位置参数读出来全是 undefined——这道 diff --git a/emrg/gui/preload.js b/emrg/gui/preload.js index d0f4ea7bf..5f2091f1b 100644 --- a/emrg/gui/preload.js +++ b/emrg/gui/preload.js @@ -135,6 +135,14 @@ const api = { ipcRenderer.on("emrg:event", listener); return () => ipcRenderer.removeListener("emrg:event", listener); }, + // 宿主 2026-12-03T18:38:18:预览页里的批注。浮框画在那个视图自己的文档内部(应用的图层 + // 压不住一个 contentView 子视图),由 preview-preload.js 发上来、main 转发到这里。 + // 只过纯文本:段落、意见、元素路径,没有节点也没有可求值的表达式。 + onPreviewAnnotation: (cb) => { + const listener = (_e, payload) => cb(payload); + ipcRenderer.on("emrg:previewAnnotate", listener); + return () => ipcRenderer.removeListener("emrg:previewAnnotate", listener); + }, }; contextBridge.exposeInMainWorld("emrg", api); diff --git a/emrg/gui/preview-preload.js b/emrg/gui/preview-preload.js new file mode 100644 index 000000000..7d5ac27bf --- /dev/null +++ b/emrg/gui/preview-preload.js @@ -0,0 +1,347 @@ +"use strict"; +/** + * preview-preload.js — annotate the HTML preview (host 2026-12-03T18:38:18). + * + * The preview is its own WebContentsView, composited by the main process *above* the app's own + * window. That is why the app's floating panel cannot hang over it: a DOM layer in the renderer + * sits under whatever the main process adds with `addChildView`. So the panel for a previewed page + * has to be drawn inside the page, and this file is where that happens. + * + * Two properties make that safe, and both are why nothing else lives here. + * + * **No `contextBridge`.** The page gets no function, no object, no `window.emrg`. This file runs in + * a preload's own world with DOM access, draws its interface behind a closed shadow root, and is + * the only thing that can talk to the main process. A page that runs its own scripts — every page + * does — has nothing to reach for. + * + * **The message is text.** What leaves is `{ items: [{ paragraph, body, selector }] }`, plain + * strings. No node, no element, no selector to evaluate: the main process forwards it and the + * renderer composes the message with `composeMessage`. + * + * Selecting text is the whole gesture. A selection is wrapped in a `` in place, its + * containing block becomes the quote, and the element path becomes the address — the rendered + * words are not the source words, so the file and the element are what make the annotation + * locatable again. Marks are not reattached after the page reloads: this layer keeps no store, and + * an annotation that silently moved is worse than one that is gone. + */ + +const { ipcRenderer } = require("electron"); + +const UI_ATTR = "data-emrg-anno-ui"; +const MARK_ATTR = "data-emrg-anno-mark"; + +/** Blocks whose text counts as "the paragraph the selection sits in". */ +const BLOCK_TAGS = new Set([ + "P", "LI", "PRE", "BLOCKQUOTE", "TD", "TH", "DD", "DT", + "H1", "H2", "H3", "H4", "H5", "H6", "SECTION", "ARTICLE", "DIV", +]); + +function flatten(text) { + return String(text || "").replace(/\s+/g, " ").trim(); +} + +/** Every text node under `root`, in document order. */ +function textNodesOf(root) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null); + const out = []; + for (let n = walker.nextNode(); n !== null; n = walker.nextNode()) out.push(n); + return out; +} + +/** The element path from `body` to `el`, which is the annotation's address in the source. */ +function selectorOf(el) { + const parts = []; + for (let node = el; node && node.nodeType === 1 && node !== document.body; node = node.parentElement) { + let part = node.tagName.toLowerCase(); + if (node.id) { + part += `#${node.id}`; + } else { + const parent = node.parentElement; + if (parent) { + const sameTag = Array.from(parent.children).filter((c) => c.tagName === node.tagName); + if (sameTag.length > 1) part += `:nth-of-type(${sameTag.indexOf(node) + 1})`; + } + } + parts.unshift(part); + } + return ["body", ...parts].join(" > "); +} + +/** The block the selection sits in, flattened — what travels as the quote. */ +function paragraphOf(node, fallbackText) { + let el = node && node.nodeType === 1 ? node : node && node.parentElement; + while (el && el !== document.body) { + if (BLOCK_TAGS.has(el.tagName)) return flatten(el.textContent); + el = el.parentElement; + } + return flatten(fallbackText); +} + +const STYLE = ` +:host { all: initial; } +* { box-sizing: border-box; } +.panel { + position: fixed; z-index: 2147483000; display: flex; flex-direction: column; + min-width: 240px; min-height: 160px; overflow: hidden; + background: #1b1f2a; color: #e6e9f0; border: 1px solid #39404f; + border-radius: 10px; box-shadow: 0 16px 40px rgba(0, 0, 0, .55); + font: 13px/1.55 -apple-system, "PingFang SC", system-ui, sans-serif; +} +.head { + display: flex; align-items: center; gap: 7px; flex: none; + padding: 7px 8px; background: #232937; border-bottom: 1px solid #333a49; + cursor: move; user-select: none; +} +.title { font-weight: 600; } +.count { color: #8b93a7; font-size: 12px; } +.spacer { flex: 1 1 auto; } +.head button { + background: transparent; border: 0; color: #9aa3b4; cursor: pointer; + font: inherit; font-size: 13px; line-height: 1; padding: 2px 5px; border-radius: 5px; +} +.head button:hover { background: #2f3646; color: #fff; } +.head .send { color: #8ab4ff; border: 1px solid #3a5581; background: #1d2534; font-size: 12px; } +.head .send:disabled { opacity: .45; cursor: not-allowed; } +.list { flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 8px; display: flex; flex-direction: column; gap: 7px; } +.hint { color: #78818f; } +.card { border-left: 3px solid var(--c); background: #161a23; border-radius: 5px; padding: 6px 8px; } +.card .top { display: flex; align-items: center; gap: 6px; margin-bottom: 4px; } +.badge { + display: inline-flex; align-items: center; justify-content: center; + min-width: 16px; height: 16px; padding: 0 3px; border-radius: 8px; + background: var(--c); color: #0f1116; font-size: 11px; font-weight: 700; +} +.card .del { margin-left: auto; background: transparent; border: 0; color: #6b7280; cursor: pointer; font: inherit; } +.quote { font-style: italic; color: #9aa3b4; font-size: 12px; margin-bottom: 5px; white-space: pre-wrap; } +textarea { + width: 100%; height: 46px; resize: vertical; background: #12151c; color: #e6e9f0; + border: 1px solid #333a49; border-radius: 5px; padding: 5px 6px; font: inherit; font-size: 12px; +} +textarea:focus { outline: none; border-color: #4f7cd6; } +.grip { position: absolute; right: 0; bottom: 0; width: 16px; height: 16px; cursor: nwse-resize; } +.grip::after { + content: ""; position: absolute; right: 4px; bottom: 4px; width: 8px; height: 8px; + border-right: 2px solid #55607a; border-bottom: 2px solid #55607a; +} +`; + +const COLORS = ["#4a9eff", "#f0a020", "#43c08a", "#d0559e", "#9d7bea", "#e06a4a"]; + +/** The whole interface, created once, behind a closed shadow root. */ +function buildPanel() { + const host = document.createElement("div"); + host.setAttribute(UI_ATTR, ""); + const shadow = host.attachShadow({ mode: "closed" }); + const style = document.createElement("style"); + style.textContent = STYLE; + + const panel = document.createElement("div"); + panel.className = "panel"; + + const head = document.createElement("div"); + head.className = "head"; + const gripDots = document.createElement("span"); + gripDots.textContent = "⋮⋮"; + gripDots.style.color = "#5f6879"; + const title = document.createElement("span"); + title.className = "title"; + title.textContent = "批注"; + const count = document.createElement("span"); + count.className = "count"; + const spacer = document.createElement("span"); + spacer.className = "spacer"; + const send = document.createElement("button"); + send.type = "button"; + send.className = "send"; + send.textContent = "发送"; + send.disabled = true; + const close = document.createElement("button"); + close.type = "button"; + close.textContent = "✕"; + head.append(gripDots, title, count, spacer, send, close); + + const list = document.createElement("div"); + list.className = "list"; + + const grip = document.createElement("div"); + grip.className = "grip"; + + panel.append(head, list, grip); + shadow.append(style, panel); + document.documentElement.appendChild(host); + return { host, panel, head, count, list, send, close, grip }; +} + +function main() { + const ui = buildPanel(); + /** `{ id, exact, paragraph, selector, body, mark }` — creation order is send order. */ + const items = []; + let seq = 0; + + const viewport = () => ({ w: window.innerWidth, h: window.innerHeight }); + const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v)); + + // The panel starts at the top right of the page, the same place the chat's panel starts. + const box = { x: Math.max(0, window.innerWidth - 360), y: 76, w: 320, h: 320 }; + const place = () => { + ui.panel.style.left = `${box.x}px`; + ui.panel.style.top = `${box.y}px`; + ui.panel.style.width = `${box.w}px`; + ui.panel.style.height = `${box.h}px`; + }; + place(); + + const render = () => { + ui.count.textContent = items.length ? String(items.length) : ""; + ui.send.disabled = !items.some((i) => i.body.trim().length > 0); + ui.list.textContent = ""; + if (items.length === 0) { + const hint = document.createElement("p"); + hint.className = "hint"; + hint.textContent = "在页面上选一段文字开始批注"; + ui.list.append(hint); + return; + } + items.forEach((item, index) => { + const card = document.createElement("div"); + card.className = "card"; + card.style.setProperty("--c", COLORS[index % COLORS.length]); + + const top = document.createElement("div"); + top.className = "top"; + const badge = document.createElement("span"); + badge.className = "badge"; + badge.textContent = String(index + 1); + const del = document.createElement("button"); + del.type = "button"; + del.className = "del"; + del.textContent = "✕"; + del.addEventListener("click", () => { + if (item.mark && item.mark.parentNode) { + const mark = item.mark; + while (mark.firstChild) mark.parentNode.insertBefore(mark.firstChild, mark); + mark.parentNode.removeChild(mark); + mark.parentNode.normalize && mark.parentNode.normalize(); + } + items.splice(items.indexOf(item), 1); + render(); + }); + top.append(badge, del); + + const quote = document.createElement("div"); + quote.className = "quote"; + quote.textContent = item.exact; + + const body = document.createElement("textarea"); + body.value = item.body; + body.placeholder = "这条批注要说什么"; + body.addEventListener("input", () => { + item.body = body.value; + ui.send.disabled = !items.some((i) => i.body.trim().length > 0); + }); + + card.append(top, quote, body); + ui.list.append(card); + }); + }; + render(); + + // ── What leaves the page ──────────────────────────────────────────── + const submit = () => { + const payload = items + .filter((i) => i.body.trim().length > 0) + .map((i) => ({ paragraph: i.paragraph, body: i.body.trim(), selector: i.selector })); + if (payload.length === 0) return; + ipcRenderer.send("emrg:previewAnnotate", { items: payload }); + items.length = 0; + render(); + ui.host.remove(); + }; + ui.send.addEventListener("click", submit); + ui.close.addEventListener("click", () => ui.host.remove()); + + // ── Moving and resizing: the panel belongs to the person dragging it ── + let drag = null; + const begin = (kind, event) => { + if (event.button !== 0) return; + event.preventDefault(); + drag = { kind, x: event.clientX, y: event.clientY, box: { ...box } }; + }; + ui.head.addEventListener("mousedown", (event) => { + if (event.target.closest("button")) return; + begin("move", event); + }); + ui.head.addEventListener("dblclick", (event) => { + if (event.target.closest("button")) return; + box.x = Math.max(0, window.innerWidth - 360); + box.y = 76; + box.w = 320; + box.h = 320; + place(); + }); + ui.grip.addEventListener("mousedown", (event) => { + event.stopPropagation(); + begin("resize", event); + }); + window.addEventListener("mousemove", (event) => { + if (!drag) return; + const dx = event.clientX - drag.x; + const dy = event.clientY - drag.y; + const vp = viewport(); + if (drag.kind === "move") { + box.x = clamp(drag.box.x + dx, 0, Math.max(0, vp.w - box.w)); + box.y = clamp(drag.box.y + dy, 0, Math.max(0, vp.h - box.h)); + } else { + box.w = clamp(drag.box.w + dx, 240, Math.max(240, vp.w - box.x)); + box.h = clamp(drag.box.h + dy, 160, Math.max(160, vp.h - box.y)); + } + place(); + }); + window.addEventListener("mouseup", () => { + drag = null; + }); + + // ── Selecting text is the gesture that makes an annotation ─────────── + document.addEventListener("mouseup", (event) => { + const path = typeof event.composedPath === "function" ? event.composedPath() : []; + if (path.includes(ui.host)) return; + const selection = window.getSelection(); + if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return; + const range = selection.getRangeAt(0); + if (!document.body.contains(range.commonAncestorContainer)) return; + const exact = flatten(range.toString()); + if (!exact) return; + + const anchorNode = range.startContainer; + const block = anchorNode.nodeType === 1 ? anchorNode : anchorNode.parentElement; + const id = `panno-${Date.now().toString(36)}-${++seq}`; + let mark; + try { + mark = document.createElement("mark"); + mark.setAttribute(MARK_ATTR, id); + mark.style.background = "rgba(255, 205, 0, .22)"; + mark.style.borderBottom = "2px solid rgba(255, 205, 0, .65)"; + mark.appendChild(range.extractContents()); + range.insertNode(mark); + } catch { + return; // a selection the DOM refuses to wrap is not an annotation + } + selection.removeAllRanges(); + + items.push({ + id, + exact, + paragraph: paragraphOf(block, exact), + selector: selectorOf(block && block.nodeType === 1 ? block : document.body), + body: "", + mark, + }); + render(); + }); +} + +if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", main, { once: true }); +} else { + main(); +} diff --git a/emrg/gui/renderer/src/annotation.css b/emrg/gui/renderer/src/annotation.css index f5aaa4f6e..41d4803dc 100644 --- a/emrg/gui/renderer/src/annotation.css +++ b/emrg/gui/renderer/src/annotation.css @@ -68,22 +68,20 @@ } /* The floating panel. `z-index` matches the usage ranking's flap: both hang over the transcript - and both must stay under a dialog (1000) and under a toast (1100). */ + and both must stay under a dialog (1000) and under a toast (1100). + + Position and size are not here any more (host 2026-12-03T18:38:18): the component writes them, + because the panel can be dragged by its header and resized from its corner, and the one rule + this block used to carry — never larger than the window — is `clampBox`'s now. `overflow: hidden` + is what keeps the cards inside the rounded corner at any size a drag produces. */ .react-shell .anno-panel { position: fixed; z-index: 900; - top: 76px; - right: 20px; - /* Wide enough for a line of the quote plus a short body; a narrow window narrows it. */ - width: 340px; - max-width: calc(100vw - 24px); - /* Bounded by the window below the status band, so the presence of many annotations changes the - panel's scrollbar and never its footprint. */ - max-height: calc(100vh - 168px); display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; + overflow: hidden; background: var(--bg-panel); border: 1px solid var(--border); border-radius: var(--radius-card); @@ -98,6 +96,9 @@ justify-content: space-between; gap: 8px; flex: none; + /* The header is the drag handle, so it looks and behaves like one. */ + cursor: move; + user-select: none; } .react-shell .anno-panel-title { @@ -225,6 +226,28 @@ color: var(--text-1); } +/* The corner grip: the only resize surface, so a press anywhere else keeps meaning "move". */ +.react-shell .anno-grip { + position: absolute; + right: 3px; + bottom: 3px; + width: 14px; + height: 14px; + border-right: 2px solid var(--text-3); + border-bottom: 2px solid var(--text-3); + border-radius: 0 0 var(--radius-sm) 0; + cursor: nwse-resize; +} + +/* A drag belongs to the panel while it lasts. The pointer crosses the reply on its way to a new + position, and a selection there would make an annotation mid-drag — the same bargain + `col-resizing` makes for a column handle. */ +body.anno-dragging, +body.anno-dragging * { + cursor: move !important; + user-select: none !important; +} + .react-shell .anno-stale { color: var(--amber); margin-bottom: 4px; diff --git a/emrg/gui/renderer/src/components/AnnotationMode.test.tsx b/emrg/gui/renderer/src/components/AnnotationMode.test.tsx index 1b75bcfec..e41e6ed67 100644 --- a/emrg/gui/renderer/src/components/AnnotationMode.test.tsx +++ b/emrg/gui/renderer/src/components/AnnotationMode.test.tsx @@ -11,6 +11,8 @@ import { AnnotationMode } from "./AnnotationMode"; import { messageFingerprint, offsetsToRange, + PANEL_MIN_H, + PANEL_MIN_W, plainTextOf, saveAnnotations, type Annotation, @@ -258,7 +260,12 @@ describe("the panel floats, and only its list scrolls (host 2026-12-03T16:11:38) expect(panel).toContain("z-index: 900"); // 旧版是 float: right —— 每加一条批注就把被批注的段落挤窄一次 expect(panel).not.toContain("float:"); - expect(panel).toContain("max-height: calc(100vh - 168px)"); + // 「永不大于窗口」这条边界跟着位置一起搬进了 `clampBox`(宿主 2026-12-03T18:38:18 要能 + // 拖能缩放):样式表钉不住一个拖动产生的值,所以这里量的是面板在窗口里的实际尺寸。 + render( {}} />); + const el = screen.getByTestId("anno-panel"); + expect(parseFloat(el.style.width)).toBeLessThanOrEqual(window.innerWidth); + expect(parseFloat(el.style.height)).toBeLessThanOrEqual(window.innerHeight); }); it("only the list scrolls, so twenty annotations cost one scrollbar", () => { @@ -293,3 +300,88 @@ describe("the panel floats, and only its list scrolls (host 2026-12-03T16:11:38) expect(onClose).toHaveBeenCalledTimes(2); }); }); + +describe("the panel can be moved and resized (host 2026-12-03T18:38:18)", () => { + const box = () => { + const el = screen.getByTestId("anno-panel"); + return { + x: parseFloat(el.style.left), + y: parseFloat(el.style.top), + w: parseFloat(el.style.width), + h: parseFloat(el.style.height), + }; + }; + + it("starts at the right edge under the status band, at the size the stylesheet used to fix", () => { + render( {}} />); + expect(box()).toEqual({ + x: window.innerWidth - 340 - 20, + y: 76, + w: 340, + h: 520, + }); + }); + + it("drags by its header, and never leaves the window", () => { + render( {}} />); + const before = box(); + const head = screen.getByTestId("anno-head"); + + fireEvent.mouseDown(head, { clientX: 500, clientY: 100, button: 0 }); + fireEvent.mouseMove(window, { clientX: 440, clientY: 140 }); + fireEvent.mouseUp(window); + expect(box()).toEqual({ ...before, x: before.x - 60, y: before.y + 40 }); + + // 拖出窗口右下角:位置被夹回来,尺寸不动 + fireEvent.mouseDown(head, { clientX: 500, clientY: 100, button: 0 }); + fireEvent.mouseMove(window, { clientX: 9000, clientY: 9000 }); + fireEvent.mouseUp(window); + const clamped = box(); + expect(clamped.x + clamped.w).toBeLessThanOrEqual(window.innerWidth); + expect(clamped.y + clamped.h).toBeLessThanOrEqual(window.innerHeight); + expect(clamped.w).toBe(before.w); + expect(clamped.h).toBe(before.h); + }); + + it("resizes from the corner, and a drag cannot make it unusable", () => { + render( {}} />); + const before = box(); + const grip = screen.getByTestId("anno-grip"); + + fireEvent.mouseDown(grip, { clientX: 900, clientY: 700, button: 0 }); + fireEvent.mouseMove(window, { clientX: 940, clientY: 730 }); + fireEvent.mouseUp(window); + expect(box().w).toBe(before.w + 40); + expect(box().h).toBe(before.h + 30); + + // 往回拖到远小于下限:停在下限,而不是缩成一条线 + fireEvent.mouseDown(grip, { clientX: 900, clientY: 700, button: 0 }); + fireEvent.mouseMove(window, { clientX: -5000, clientY: -5000 }); + fireEvent.mouseUp(window); + expect(box().w).toBe(PANEL_MIN_W); + expect(box().h).toBe(PANEL_MIN_H); + }); + + it("comes back where it was left, and a double-click puts it back", () => { + const first = render( {}} />); + const head = screen.getByTestId("anno-head"); + fireEvent.mouseDown(head, { clientX: 500, clientY: 100, button: 0 }); + fireEvent.mouseMove(window, { clientX: 440, clientY: 140 }); + fireEvent.mouseUp(window); + const moved = box(); + expect(moved).not.toEqual({ x: window.innerWidth - 360, y: 76, w: 340, h: 520 }); + first.unmount(); + + // 位置是宿主的,不是某一条回复的:关掉再开,它还在原处 + render( {}} />); + expect(box()).toEqual(moved); + + fireEvent.doubleClick(screen.getByTestId("anno-head")); + expect(box()).toEqual({ + x: window.innerWidth - 340 - 20, + y: 76, + w: 340, + h: 520, + }); + }); +}); diff --git a/emrg/gui/renderer/src/components/AnnotationMode.tsx b/emrg/gui/renderer/src/components/AnnotationMode.tsx index e930e2d18..db0a11f92 100644 --- a/emrg/gui/renderer/src/components/AnnotationMode.tsx +++ b/emrg/gui/renderer/src/components/AnnotationMode.tsx @@ -26,21 +26,26 @@ */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; -import type { CSSProperties } from "react"; +import type { CSSProperties, MouseEvent as ReactMouseEvent } from "react"; import type { TranslateFn } from "../lib/i18n"; import { anchorFromRange, + clampBox, composeMessage, + defaultPanelBox, loadAnnotations, messageFingerprint, offsetsToRange, paragraphTextAt, + persistPanelBox, plainTextOf, rangeToOffsets, relocate, saveAnnotations, splitSpans, + storedPanelBox, type Annotation, + type PanelBox, } from "../lib/annotation"; /** One colour per annotation, in creation order. */ @@ -50,6 +55,11 @@ export function annoColor(index: number): string { return ANNO_COLORS[Math.max(0, index) % ANNO_COLORS.length]; } +/** The window a dragged panel has to stay inside. */ +function viewport(): { w: number; h: number } { + return { w: window.innerWidth, h: window.innerHeight }; +} + /** Take every mark this mode painted back out, merging the text nodes it split. */ function unwrapMarks(root: HTMLElement): void { const marks = Array.from(root.querySelectorAll("mark.anno-mark")); @@ -139,6 +149,58 @@ export function AnnotationMode({ sid, root, messageKey, t, onSend, onClose }: An const seqRef = useRef(0); const loadedRef = useRef(false); + // Where the panel sits and how big it is (host 2026-12-03T18:38:18). State rather than a rule in + // the stylesheet: a drag produces a position, and a style sheet cannot clamp one. The one rule the + // CSS used to carry — never larger than the window — moved into `clampBox` with it. + const [box, setBox] = useState(() => storedPanelBox(viewport())); + const [drag, setDrag] = useState<"move" | "resize" | null>(null); + const dragStart = useRef<{ + kind: "move" | "resize"; + x: number; + y: number; + box: PanelBox; + } | null>(null); + + // Put it back where it was left: a position is the reader's choice, so it outlives the panel + // closing and outlives the reply it was opened on. + useEffect(() => { + persistPanelBox(box); + }, [box]); + + // One pair of window listeners for the whole drag. `anno-dragging` on the body does what + // `col-resizing` does for a column handle: the pointer crosses the reply on its way, and a + // selection there would create a new annotation mid-drag. + useEffect(() => { + if (!drag) return; + document.body.classList.add("anno-dragging"); + const onMove = (event: MouseEvent): void => { + const start = dragStart.current; + if (!start) return; + const dx = event.clientX - start.x; + const dy = event.clientY - start.y; + const next = + start.kind === "move" + ? { ...start.box, x: start.box.x + dx, y: start.box.y + dy } + : { ...start.box, w: start.box.w + dx, h: start.box.h + dy }; + setBox(clampBox(next, viewport())); + }; + const onUp = (): void => setDrag(null); + window.addEventListener("mousemove", onMove); + window.addEventListener("mouseup", onUp); + return () => { + window.removeEventListener("mousemove", onMove); + window.removeEventListener("mouseup", onUp); + document.body.classList.remove("anno-dragging"); + }; + }, [drag]); + + const beginDrag = (kind: "move" | "resize", event: ReactMouseEvent): void => { + if (event.button !== 0) return; + event.preventDefault(); + dragStart.current = { kind, x: event.clientX, y: event.clientY, box }; + setDrag(kind); + }; + // Load this reply's stored annotations. The key is the reply's own text, so the same words give // the same key across reloads and a rewritten reply keeps its own (different) key. useEffect(() => { @@ -286,8 +348,28 @@ export function AnnotationMode({ sid, root, messageKey, t, onSend, onClose }: An }; return ( -