@nxxxsooo/opencode-annotate 0.17.1 → 0.19.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/CHANGELOG.md +20 -0
- package/README.md +10 -4
- package/browser/capture.js +248 -40
- package/browser/inspector.js +66 -1
- package/browser/manifest.json +1 -1
- package/browser/panel.css +2 -2
- package/browser/panel.html +1 -1
- package/browser/panel.mjs +82 -16
- package/browser/protocol.mjs +27 -8
- package/browser/worker.mjs +123 -36
- package/package.json +1 -1
- package/review.mjs +75 -11
- package/tui/bin/darwin-arm64/annotate-tui +0 -0
- package/tui/bin/darwin-x64/annotate-tui +0 -0
- package/tui/bin/linux-arm64/annotate-tui +0 -0
- package/tui/bin/linux-x64/annotate-tui +0 -0
- package/tui/bin/win32-x64/annotate-tui.exe +0 -0
- package/tui.ts +8 -0
package/browser/panel.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PROTOCOL, markdown, validateReview } from "./protocol.mjs"
|
|
1
|
+
import { PROTOCOL, areaLabel, markdown, validateReview } from "./protocol.mjs"
|
|
2
2
|
import { panelPolling, panelWindowID } from "./env.mjs"
|
|
3
3
|
|
|
4
4
|
const $ = id => document.getElementById(id)
|
|
@@ -13,6 +13,7 @@ let state, model, destination, available, targets = [], workspaces = [], disconn
|
|
|
13
13
|
let deliverySupported = true
|
|
14
14
|
let refreshID = 0, connectionRevision = 0, connectionRefresh, connectionRefreshRevision, connectionTimer, scheduledRefresh
|
|
15
15
|
let pendingAction, pendingFocus, undoRecord, clearBatchID, selectedNoteID, noteRenderKey, notice, outdated = false
|
|
16
|
+
let areaViewKey
|
|
16
17
|
let sessionSort = localStorage.getItem("sessionSort") || "updated", showAllSessions = false
|
|
17
18
|
|
|
18
19
|
function icon(name) {
|
|
@@ -74,7 +75,47 @@ function dirty(m = model) {
|
|
|
74
75
|
anchorIdentity(value.anchor) !== anchorIdentity(value.editing.anchor) : !!value.comment.trim()
|
|
75
76
|
}
|
|
76
77
|
const validDraft = () => !!model?.value?.comment.trim() && dirty()
|
|
77
|
-
const anchorIdentity = anchor => anchor ? JSON.stringify([anchor.frame, anchor.type, anchor.selector, anchor.quote, anchor.prefix, anchor.suffix]) : ""
|
|
78
|
+
const anchorIdentity = anchor => anchor ? JSON.stringify([anchor.frame, anchor.type, anchor.type === "area" ? anchor.rect : anchor.selector, anchor.quote, anchor.prefix, anchor.suffix]) : ""
|
|
79
|
+
const targetLabel = anchor => anchor.type === "area" ? `${areaLabel(anchor)}${anchor.quote ? `: ${anchor.quote}` : ""}` : anchor.quote
|
|
80
|
+
function areaDraft() {
|
|
81
|
+
const value = model?.value
|
|
82
|
+
if (value?.anchor.type !== "area" || value.editing) return null
|
|
83
|
+
const captureID = value.captures?.[state.tabID] || Object.values(value.captures || {})[0]
|
|
84
|
+
return captureID ? { id: `draft:${captureID}`, anchor: value.anchor } : null
|
|
85
|
+
}
|
|
86
|
+
function syncAreaView() {
|
|
87
|
+
if (!state || outdated) return
|
|
88
|
+
const focus = state.notes.some(note => note.id === selectedNoteID && note.page.url === state.page.url && note.anchor.type === "area") ? selectedNoteID : null
|
|
89
|
+
const view = { tabID: state.tabID, url: state.page.url, focus, draft: areaDraft(), eventID: state.areaEvent?.token }
|
|
90
|
+
const key = JSON.stringify(view)
|
|
91
|
+
if (key === areaViewKey) return
|
|
92
|
+
// Leave a tab's last marker view intact when its panel switches away.
|
|
93
|
+
areaViewKey = key
|
|
94
|
+
call({ action: "area-view", ...view }).catch(error => {
|
|
95
|
+
if (areaViewKey === key) areaViewKey = null
|
|
96
|
+
if (error.code !== "outdated" && state?.tabID === view.tabID) status(error.message, "error")
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
function applyAreaEvent(event) {
|
|
100
|
+
if (!event || model.areaEvent === event.token) return
|
|
101
|
+
model.areaEvent = event.token
|
|
102
|
+
if (event.draft) {
|
|
103
|
+
if (areaDraft()?.id !== event.id) return
|
|
104
|
+
selectedNoteID = null
|
|
105
|
+
if (event.anchor && anchorIdentity(model.value.anchor) !== anchorIdentity(event.anchor)) {
|
|
106
|
+
model.value.anchor = event.anchor
|
|
107
|
+
persistDraft(model).catch(() => {})
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
const note = state.notes.find(note => note.id === event.id)
|
|
111
|
+
if (!note) return
|
|
112
|
+
selectedNoteID = note.id
|
|
113
|
+
if (model.value?.editing?.id === note.id && event.revision === note.revision && model.value.editing.revision + 1 === note.revision) {
|
|
114
|
+
model.value.anchor = note.anchor; model.value.editing = clone(note)
|
|
115
|
+
persistDraft(model).catch(() => {})
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
78
119
|
function pendingCount() {
|
|
79
120
|
const pending = state?.notes.filter(note => note.sentRevision !== note.revision) || []
|
|
80
121
|
return pending.length + (validDraft() && !pending.some(note => note.id === model.value.editing?.id) ? 1 : 0)
|
|
@@ -86,7 +127,7 @@ function controls() {
|
|
|
86
127
|
for (const button of $("kind").querySelectorAll("button")) button.disabled = lock
|
|
87
128
|
$("save").disabled = lock || !state || !validDraft() || !!model?.conflict
|
|
88
129
|
$("save-switch").disabled = lock || !validDraft() || !!model?.conflict
|
|
89
|
-
$("pick").disabled = !state || lock
|
|
130
|
+
$("pick").disabled = $("area").disabled = !state || lock
|
|
90
131
|
$("cancel").disabled = lock
|
|
91
132
|
for (const id of ["discard-switch", "keep-editing", "retry-draft", "reload-draft", "keep-draft", "copy-draft", "undo", "restore-round", "change-target"]) $(id).disabled = lock
|
|
92
133
|
for (const row of $("targets").querySelectorAll(".session-row")) row.disabled = lock || !targets.some(target => target.id === row.dataset.targetId)
|
|
@@ -99,7 +140,7 @@ function controls() {
|
|
|
99
140
|
$("disconnect").hidden = !available
|
|
100
141
|
$("disconnect").disabled = lock || !available
|
|
101
142
|
$("copy").disabled = $("export").disabled = !state?.notes.length
|
|
102
|
-
for (const button of $("notes").querySelectorAll("button")) button.disabled = lock
|
|
143
|
+
for (const button of $("notes").querySelectorAll("button")) button.disabled = lock || !state
|
|
103
144
|
for (const id of ["clear", "confirm-clear", "cancel-clear"]) $(id).disabled = lock || !state?.notes.length
|
|
104
145
|
for (const id of busy) if ($(id)) $(id).disabled = true
|
|
105
146
|
if (outdated) for (const button of document.querySelectorAll("button:not(#reload-extension)")) button.disabled = true
|
|
@@ -229,7 +270,7 @@ function renderComposer() {
|
|
|
229
270
|
renderEmpty()
|
|
230
271
|
if (!value) return
|
|
231
272
|
$("composer-title").textContent = value.editing ? "Edit note" : "New note"
|
|
232
|
-
$("quote").textContent = value.anchor
|
|
273
|
+
$("quote").textContent = targetLabel(value.anchor)
|
|
233
274
|
if ($("comment").value !== value.comment) $("comment").value = value.comment
|
|
234
275
|
for (const button of $("kind").querySelectorAll("button")) {
|
|
235
276
|
const selected = button.dataset.kind === value.kind
|
|
@@ -264,8 +305,12 @@ function renderNotes() {
|
|
|
264
305
|
$("notes-section").hidden = !notes.length
|
|
265
306
|
const pageCount = new Set(notes.map(note => note.page.url)).size
|
|
266
307
|
$("count").textContent = `${plural(notes.length)} in this round${pageCount > 1 ? ` · ${pageCount} pages` : ""}`
|
|
267
|
-
const key = JSON.stringify([notes, state?.page.url, state?.anchorStates
|
|
268
|
-
if (key === noteRenderKey)
|
|
308
|
+
const key = JSON.stringify([notes, state?.page.url, state?.anchorStates])
|
|
309
|
+
if (key === noteRenderKey) {
|
|
310
|
+
for (const item of $("notes").querySelectorAll("[data-note-id]")) item.classList.toggle("is-current", item.dataset.noteId === selectedNoteID)
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
const focused = document.activeElement?.classList.contains("note-target") ? document.activeElement.closest("[data-note-id]").dataset.noteId : null
|
|
269
314
|
noteRenderKey = key; $("notes").replaceChildren()
|
|
270
315
|
let pageURL
|
|
271
316
|
for (const [index, note] of notes.entries()) {
|
|
@@ -285,10 +330,15 @@ function renderNotes() {
|
|
|
285
330
|
item.className = `note${selectedNoteID === note.id ? " is-current" : ""}`; item.dataset.noteId = note.id
|
|
286
331
|
number.className = "note-number"; number.setAttribute("aria-label", `Note ${index + 1}`)
|
|
287
332
|
target.className = "note-target"; target.setAttribute("aria-label", `Show note ${index + 1} on page`)
|
|
288
|
-
target.append(make("span", note.anchor.
|
|
333
|
+
target.append(make("span", targetLabel(note.anchor).slice(0, 200)), icon("reveal"))
|
|
334
|
+
target.onfocus = () => {
|
|
335
|
+
if (note.anchor.type === "area" && note.page.url === state.page.url && selectedNoteID !== note.id) {
|
|
336
|
+
selectedNoteID = note.id; renderNotes(); syncAreaView()
|
|
337
|
+
}
|
|
338
|
+
}
|
|
289
339
|
target.onclick = () => run("reveal", async () => {
|
|
290
340
|
await call({ action: "reveal", url: state.page.url, noteID: note.id }); selectedNoteID = note.id
|
|
291
|
-
await refresh(); status("Element highlighted on the page
|
|
341
|
+
await refresh(); status(`${note.anchor.type === "area" ? "Area" : "Element"} highlighted on the page`); renderNotes()
|
|
292
342
|
$("notes").querySelector(`[data-note-id="${CSS.escape(note.id)}"] .note-target`)?.focus({ preventScroll: true })
|
|
293
343
|
})
|
|
294
344
|
const comment = make("p", note.comment); comment.className = "note-comment"
|
|
@@ -305,7 +355,9 @@ function renderNotes() {
|
|
|
305
355
|
bottom.append(meta, edit, remove); content.append(bottom); item.append(number, content); $("notes").append(item)
|
|
306
356
|
}
|
|
307
357
|
$("preview").textContent = notes.length ? markdown(review()) : "Add a note to preview the feedback."
|
|
308
|
-
|
|
358
|
+
if (focused && (focused === selectedNoteID || notes.find(note => note.id === focused)?.anchor.type !== "area")) {
|
|
359
|
+
$("notes").querySelector(`[data-note-id="${CSS.escape(focused)}"] .note-target`)?.focus({ preventScroll: true })
|
|
360
|
+
}
|
|
309
361
|
}
|
|
310
362
|
// Send always means session delivery; Copy instead is a separate, stable action.
|
|
311
363
|
function renderDelivery() {
|
|
@@ -356,6 +408,7 @@ function renderDelivery() {
|
|
|
356
408
|
}
|
|
357
409
|
function render() {
|
|
358
410
|
renderComposer(); renderNotes()
|
|
411
|
+
syncAreaView()
|
|
359
412
|
$("undo-notice").hidden = !undoRecord
|
|
360
413
|
$("undo-text").textContent = undoRecord ? `${plural(undoRecord.notes.length)} removed.` : ""
|
|
361
414
|
controls()
|
|
@@ -367,7 +420,9 @@ async function refresh() {
|
|
|
367
420
|
const next = await call({ action: "current" })
|
|
368
421
|
if (request !== refreshID) return
|
|
369
422
|
if (next.protocol !== PROTOCOL) { markOutdated(); return }
|
|
370
|
-
if (state?.page.url !== next.page.url) {
|
|
423
|
+
if (state?.tabID !== next.tabID || state?.page.url !== next.page.url) {
|
|
424
|
+
pendingAction = null; selectedNoteID = null; pendingFocus = null; if (notice?.page) notice = null
|
|
425
|
+
}
|
|
371
426
|
state = next; model = modelFor(next)
|
|
372
427
|
$("page-title").textContent = next.page.title; $("page-title").title = next.page.title
|
|
373
428
|
const url = new URL(next.page.url)
|
|
@@ -375,17 +430,21 @@ async function refresh() {
|
|
|
375
430
|
$("page-url").title = next.page.url
|
|
376
431
|
const pageError = next.detached || next.error
|
|
377
432
|
$("page-error").hidden = !pageError; $("page-error").textContent = pageError || ""
|
|
378
|
-
$("pick-label").textContent = next.
|
|
379
|
-
$("pick").setAttribute("aria-pressed", String(
|
|
433
|
+
$("pick-label").textContent = next.mode === "element" ? "Cancel pick (Esc)" : "Pick element"
|
|
434
|
+
$("pick").setAttribute("aria-pressed", String(next.mode === "element"))
|
|
435
|
+
$("area").setAttribute("aria-pressed", String(next.mode === "area"))
|
|
436
|
+
$("pick-hint").hidden = next.mode === "element"
|
|
437
|
+
$("pick-hint").textContent = next.mode === "area" ? "Drag on page · Esc to cancel" : "or select text"
|
|
380
438
|
if (next.captureID && next.captureID !== model.captureID) {
|
|
381
439
|
model.captureID = next.captureID
|
|
382
|
-
if (next.anchor && next.draft.consumedCaptures?.[next.tabID] !== next.captureID) {
|
|
440
|
+
if (next.anchor && next.draft.consumedCaptures?.[next.tabID] !== next.captureID && model.value?.captures?.[next.tabID] !== next.captureID) {
|
|
383
441
|
notice = null
|
|
384
442
|
if (anchorIdentity(next.anchor) !== anchorIdentity(model.value?.anchor)) await requestAction({ type: "select", anchor: next.anchor,
|
|
385
443
|
capture: { id: next.captureID, tabID: next.tabID } })
|
|
386
444
|
else model.value.captures = { ...model.value.captures, [next.tabID]: next.captureID }
|
|
387
445
|
} else if (next.error) status(next.error, "error")
|
|
388
446
|
}
|
|
447
|
+
applyAreaEvent(next.areaEvent)
|
|
389
448
|
render()
|
|
390
449
|
} catch (error) {
|
|
391
450
|
if (request !== refreshID || error.code === "outdated") return
|
|
@@ -497,6 +556,11 @@ $("comment").addEventListener("input", () => {
|
|
|
497
556
|
model.value.comment = $("comment").value; notice = null
|
|
498
557
|
persistDraft(model).catch(() => {}); controls()
|
|
499
558
|
})
|
|
559
|
+
$("comment").addEventListener("focus", () => {
|
|
560
|
+
if (!model?.value || model.value.anchor.type !== "area") return
|
|
561
|
+
selectedNoteID = model.value.editing?.id || null
|
|
562
|
+
renderNotes(); syncAreaView()
|
|
563
|
+
})
|
|
500
564
|
$("comment").addEventListener("keydown", event => {
|
|
501
565
|
if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !$("save").disabled) { event.preventDefault(); $("save").click() }
|
|
502
566
|
})
|
|
@@ -508,7 +572,9 @@ for (const button of $("kind").querySelectorAll("button")) {
|
|
|
508
572
|
})
|
|
509
573
|
}
|
|
510
574
|
$("save-shortcut").textContent = navigator.platform.includes("Mac") ? "⌘↵" : "Ctrl↵"
|
|
511
|
-
|
|
575
|
+
for (const [button, mode] of [["pick", "element"], ["area", "area"]]) {
|
|
576
|
+
task(button, async () => { notice = null; await call({ action: "pick", mode: state.mode === mode ? null : mode }); await refresh() })
|
|
577
|
+
}
|
|
512
578
|
task("save", async () => { await saveCurrent(); focusWhenReady("#pick") })
|
|
513
579
|
task("cancel", async () => { await discardDraft(); focusWhenReady("#pick") })
|
|
514
580
|
task("save-switch", async () => { const action = pendingAction; await saveCurrent(); await performAction(action) })
|
|
@@ -671,7 +737,7 @@ document.addEventListener("click", event => {
|
|
|
671
737
|
})
|
|
672
738
|
document.addEventListener("keydown", event => {
|
|
673
739
|
if (event.key !== "Escape") return
|
|
674
|
-
if (state?.
|
|
740
|
+
if (state?.mode) $(state.mode === "area" ? "area" : "pick").click()
|
|
675
741
|
pendingAction = null; $("utilities").hidden = true; $("more").setAttribute("aria-expanded", "false"); showSessionOptions(false); renderComposer()
|
|
676
742
|
})
|
|
677
743
|
chrome.storage.onChanged.addListener((changes, area) => {
|
package/browser/protocol.mjs
CHANGED
|
@@ -1,7 +1,22 @@
|
|
|
1
1
|
export const MAX_BYTES = 512 * 1024
|
|
2
2
|
export const HOST = "fun.mjshao.annotate"
|
|
3
3
|
// Bump when panel ↔ worker actions change. Chrome can keep an older worker running beside a newer panel.
|
|
4
|
-
export const PROTOCOL =
|
|
4
|
+
export const PROTOCOL = 10
|
|
5
|
+
const finiteFields = (value, keys) => value && keys.every(key => Number.isFinite(value[key]))
|
|
6
|
+
export function validateAnchor(anchor) {
|
|
7
|
+
if (typeof anchor?.quote !== "string" || anchor.quote.length > 4000 ||
|
|
8
|
+
!["text", "element", "area"].includes(anchor.type) ||
|
|
9
|
+
(anchor.type !== "area" && typeof anchor.selector !== "string")) throw new Error("Invalid annotation anchor")
|
|
10
|
+
for (const key of ["prefix", "suffix", "styles", "accessibility", "element", "fullPath", "frame"]) {
|
|
11
|
+
if (anchor[key] !== undefined && typeof anchor[key] !== "string") throw new Error("Invalid anchor field")
|
|
12
|
+
}
|
|
13
|
+
if (anchor.type === "area" && (
|
|
14
|
+
!finiteFields(anchor.rect, ["x", "y", "width", "height"]) || anchor.rect.width <= 0 || anchor.rect.height <= 0 ||
|
|
15
|
+
!finiteFields(anchor.viewport, ["width", "height", "scrollX", "scrollY"]) || anchor.viewport.width <= 0 || anchor.viewport.height <= 0 ||
|
|
16
|
+
!Array.isArray(anchor.selectors) || anchor.selectors.length > 5 ||
|
|
17
|
+
Array.from(anchor.selectors).some(value => typeof value !== "string" || !value.trim() || value.length > 1000)
|
|
18
|
+
)) throw new Error("Invalid area anchor")
|
|
19
|
+
}
|
|
5
20
|
export function safeUrl(input) {
|
|
6
21
|
const url = new URL(input)
|
|
7
22
|
if (!["http:", "https:", "file:"].includes(url.protocol)) throw new Error("Unsupported page URL")
|
|
@@ -20,12 +35,8 @@ export function validateReview(review) {
|
|
|
20
35
|
if (!note || typeof note.page?.title !== "string" || pageTitle(note.page.title) !== note.page.title ||
|
|
21
36
|
typeof note.page?.url !== "string" || safeUrl(note.page.url) !== note.page.url ||
|
|
22
37
|
typeof note.id !== "string" || ids.has(note.id) || !Number.isSafeInteger(note.revision) || note.revision < 1 ||
|
|
23
|
-
!["comment", "ask"].includes(note.kind) || typeof note.comment !== "string" || !note.comment.trim() || note.comment.length > 8000
|
|
24
|
-
|
|
25
|
-
!["text", "element"].includes(note.anchor.type)) throw new Error("Invalid annotation")
|
|
26
|
-
for (const key of ["prefix", "suffix", "styles", "accessibility", "element", "fullPath", "frame"]) {
|
|
27
|
-
if (note.anchor[key] !== undefined && typeof note.anchor[key] !== "string") throw new Error("Invalid anchor field")
|
|
28
|
-
}
|
|
38
|
+
!["comment", "ask"].includes(note.kind) || typeof note.comment !== "string" || !note.comment.trim() || note.comment.length > 8000) throw new Error("Invalid annotation")
|
|
39
|
+
validateAnchor(note.anchor)
|
|
29
40
|
if (typeof note.createdAt !== "string" || Number.isNaN(Date.parse(note.createdAt))) throw new Error("Invalid annotation timestamp")
|
|
30
41
|
ids.add(note.id)
|
|
31
42
|
}
|
|
@@ -41,6 +52,9 @@ export function orderedNotes(notes) {
|
|
|
41
52
|
}
|
|
42
53
|
return [...groups.values()].flat()
|
|
43
54
|
}
|
|
55
|
+
export function areaLabel({ rect: { x, y, width, height } }) {
|
|
56
|
+
return `Area (${x},${y} ${width}×${height})`
|
|
57
|
+
}
|
|
44
58
|
export function markdown(review) {
|
|
45
59
|
validateReview(review)
|
|
46
60
|
const lines = ["# Web annotations", "",
|
|
@@ -52,7 +66,12 @@ export function markdown(review) {
|
|
|
52
66
|
lines.push(`## ${note.page.title}`, `URL: ${pageURL}`, "")
|
|
53
67
|
}
|
|
54
68
|
const a = note.anchor
|
|
55
|
-
lines.push(`### Annotation ${index + 1} (${note.kind})`, `Captured: ${note.createdAt}
|
|
69
|
+
lines.push(`### Annotation ${index + 1} (${note.kind})`, `Captured: ${note.createdAt}`)
|
|
70
|
+
if (a.type === "area") {
|
|
71
|
+
lines.push(`${areaLabel(a)} on ${note.page.title}`)
|
|
72
|
+
if (a.selectors.length) lines.push("Selector hints:", ...a.selectors.map(selector => `- ${selector}`))
|
|
73
|
+
} else lines.push(`Selector hint: ${a.selector}`, `Element: ${a.element || a.type}`)
|
|
74
|
+
lines.push("", "Page evidence:")
|
|
56
75
|
lines.push(...`${a.prefix || ""}【${a.quote}】${a.suffix || ""}`.split("\n").map(line => `> ${line}`))
|
|
57
76
|
if (a.fullPath) lines.push(`DOM path: ${a.fullPath}`)
|
|
58
77
|
if (a.frame) lines.push(`Frame: ${a.frame}`)
|
package/browser/worker.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HOST, PROTOCOL, orderedNotes, pageTitle, safeUrl, validateReview } from "./protocol.mjs"
|
|
1
|
+
import { HOST, PROTOCOL, orderedNotes, pageTitle, safeUrl, validateAnchor, validateReview } from "./protocol.mjs"
|
|
2
2
|
import { openPanel, reconnectHint, resolveTargetTab, sameExtensionURL, sessionDelivery } from "./env.mjs"
|
|
3
3
|
|
|
4
4
|
const DELIVERY = sessionDelivery()
|
|
@@ -23,10 +23,10 @@ async function inject(tabId) {
|
|
|
23
23
|
} })
|
|
24
24
|
return frames.filter(item => item.result).map(item => ({ frameId: item.frameId, frame: frameLocator(item.result.frame) }))
|
|
25
25
|
}
|
|
26
|
-
async function pickFrames(tabId,
|
|
26
|
+
async function pickFrames(tabId, mode, frames = undefined) {
|
|
27
27
|
frames ??= await inject(tabId)
|
|
28
|
-
await Promise.all(frames.map(({ frameId }) => chrome.tabs.sendMessage(tabId, { action: "pick",
|
|
29
|
-
return {
|
|
28
|
+
await Promise.all(frames.map(({ frameId }) => chrome.tabs.sendMessage(tabId, { action: "pick", mode }, { frameId })))
|
|
29
|
+
return { mode }
|
|
30
30
|
}
|
|
31
31
|
async function anchorMessage(tabId, message, frames = undefined) {
|
|
32
32
|
frames ??= await inject(tabId)
|
|
@@ -49,15 +49,32 @@ async function waitLoaded(tabID) {
|
|
|
49
49
|
})
|
|
50
50
|
}
|
|
51
51
|
const delivered = note => !note.deleted && note.sentRevision === note.revision
|
|
52
|
-
|
|
52
|
+
const pendingNotes = storage => orderedNotes(Object.entries(storage).filter(([key, note]) =>
|
|
53
|
+
key.startsWith("note:") && !note.deleted && !delivered(note)).map(([, note]) => note))
|
|
54
|
+
async function paintMarkers(tabID, frames, notes, page, view) {
|
|
55
|
+
await Promise.all(frames.map(({ frameId, frame }) => chrome.tabs.sendMessage(tabID, {
|
|
56
|
+
action: "markers",
|
|
57
|
+
notes: notes.map(note => note.page.url === page.url && note.anchor.frame === frame
|
|
58
|
+
? { id: note.id, revision: note.revision, anchor: note.anchor } : { anchor: null }),
|
|
59
|
+
draft: view?.draft && view.draft.anchor.frame === frame ? view.draft : undefined,
|
|
60
|
+
focus: view?.focus,
|
|
61
|
+
}, { frameId })))
|
|
62
|
+
}
|
|
63
|
+
async function syncMarkers(tabID, frames = undefined) {
|
|
64
|
+
frames ??= await inject(tabID)
|
|
65
|
+
const keys = [`tab:${tabID}`, `area:${tabID}`]
|
|
66
|
+
const [session, storage] = await Promise.all([readSession(keys), chrome.storage.local.get(null)])
|
|
67
|
+
const page = session[keys[0]]?.page, view = session[keys[1]]
|
|
68
|
+
if (page) await paintMarkers(tabID, frames, pendingNotes(storage), page, view?.url === page.url ? view : null)
|
|
69
|
+
}
|
|
70
|
+
async function readSession(keys) {
|
|
71
|
+
return Object.assign({}, ...await Promise.all(keys.map(key => chrome.storage.session.get(key))))
|
|
72
|
+
}
|
|
73
|
+
async function updateMarkers() {
|
|
53
74
|
const session = await chrome.storage.session.get(null)
|
|
54
75
|
await Promise.all((await chrome.tabs.query({})).map(async tab => {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
try {
|
|
58
|
-
const frames = await inject(tab.id)
|
|
59
|
-
await Promise.all(frames.map(({ frameId, frame }) => chrome.tabs.sendMessage(tab.id, { action: "markers", notes: notes.map(note => ({ anchor: note.page.url === page.url && note.anchor.frame === frame ? note.anchor : null })) }, { frameId })))
|
|
60
|
-
} catch { /* Closed or navigated tabs are refreshed when reopened. */ }
|
|
76
|
+
if (!session[`tab:${tab.id}`]?.page) return
|
|
77
|
+
try { await syncMarkers(tab.id) } catch { /* Closed or navigated tabs are refreshed when reopened. */ }
|
|
61
78
|
}))
|
|
62
79
|
}
|
|
63
80
|
async function closeRound(annotations, details) {
|
|
@@ -76,6 +93,7 @@ async function closeRound(annotations, details) {
|
|
|
76
93
|
}
|
|
77
94
|
const expired = [...rounds.values()].sort((a, b) => b.at.localeCompare(a.at)).slice(KEPT_ROUNDS).flatMap(round => round.keys)
|
|
78
95
|
if (expired.length) await chrome.storage.local.remove(expired)
|
|
96
|
+
await updateMarkers()
|
|
79
97
|
return Object.keys(updates).length
|
|
80
98
|
}
|
|
81
99
|
function lastRound(entries) {
|
|
@@ -94,13 +112,14 @@ chrome.action.onClicked.addListener(tab => {
|
|
|
94
112
|
})
|
|
95
113
|
async function current(message) {
|
|
96
114
|
const tab = await resolveTargetTab(message)
|
|
97
|
-
const
|
|
115
|
+
const keys = [`tab:${tab.id}`, `area:${tab.id}`], session = await readSession(keys)
|
|
116
|
+
const state = session[keys[0]], view = session[keys[1]]
|
|
98
117
|
if (!state?.page) throw new Error(state?.error || "Click the extension icon on this page to grant access")
|
|
99
118
|
const hash = await pageKey(state.page.url)
|
|
100
119
|
const storage = await chrome.storage.local.get(null)
|
|
101
120
|
const entries = Object.entries(storage).filter(([key]) => key.startsWith("note:")).map(([, value]) => value)
|
|
102
121
|
// Delivered notes leave the working list; the latest rounds stay restorable.
|
|
103
|
-
const notes =
|
|
122
|
+
const notes = pendingNotes(storage)
|
|
104
123
|
const draft = storage[`draft:${hash}`] || { revision: 0, value: null }
|
|
105
124
|
const outbox = storage.outbox
|
|
106
125
|
const localNotes = notes.filter(note => note.page.url === state.page.url)
|
|
@@ -109,7 +128,8 @@ async function current(message) {
|
|
|
109
128
|
const anchors = localNotes.map(note => note.anchor).concat(draft.value ? [draft.value.anchor] : [])
|
|
110
129
|
const frames = await inject(tab.id)
|
|
111
130
|
const latest = (await chrome.storage.session.get(`tab:${tab.id}`))[`tab:${tab.id}`]
|
|
112
|
-
await pickFrames(tab.id,
|
|
131
|
+
await pickFrames(tab.id, latest?.mode ?? null, frames)
|
|
132
|
+
await syncMarkers(tab.id, frames)
|
|
113
133
|
const states = await Promise.all(anchors.map(async anchor => {
|
|
114
134
|
const result = await anchorMessage(tab.id, { action: "locate", anchor, anchors: [anchor] }, frames)
|
|
115
135
|
return result.states?.[0] || "missing frame"
|
|
@@ -118,7 +138,8 @@ async function current(message) {
|
|
|
118
138
|
anchorStates = notes.map(note => note.page.url === state.page.url ? states[index++] : "elsewhere")
|
|
119
139
|
if (draft.value) draftAnchorState = states[localNotes.length]
|
|
120
140
|
} catch (error) { if (error.message === RECONNECT) detached = RECONNECT /* otherwise visibly unavailable while navigating */ }
|
|
121
|
-
return { protocol: PROTOCOL, tabID: tab.id, ...state,
|
|
141
|
+
return { protocol: PROTOCOL, tabID: tab.id, ...state, areaEvent: view?.url === state.page.url ? view.event : undefined,
|
|
142
|
+
notes, anchorStates, hash, draft, draftAnchorState, detached, lastRound: lastRound(entries),
|
|
122
143
|
outbox: outbox ? { batchID: outbox.batchID, targetID: outbox.targetID, count: outbox.review.annotations.length } : null }
|
|
123
144
|
}
|
|
124
145
|
function draftConflict(draft) {
|
|
@@ -142,6 +163,51 @@ function consumedCaptures(previous, captures) {
|
|
|
142
163
|
}
|
|
143
164
|
return result
|
|
144
165
|
}
|
|
166
|
+
async function pageSource(message, sender) {
|
|
167
|
+
if (!sender.tab || !sender.url || new URL(message.page.url).origin !== new URL(sender.url).origin) throw new Error("Invalid page source")
|
|
168
|
+
const tab = await chrome.tabs.get(sender.tab.id)
|
|
169
|
+
if ((sender.origin || new URL(sender.url).origin) !== new URL(tab.url).origin) throw new Error("Invalid frame source")
|
|
170
|
+
const frame = sender.frameId ? frameLocator(message.frame) : undefined
|
|
171
|
+
if (sender.frameId && !frame) throw new Error("Missing frame locator")
|
|
172
|
+
return { tab, frame, page: { url: safeUrl(tab.url), title: pageTitle(tab.title || "") } }
|
|
173
|
+
}
|
|
174
|
+
async function areaGesture(message, sender) {
|
|
175
|
+
const { tab, frame, page } = await pageSource(message, sender)
|
|
176
|
+
const key = `area:${tab.id}`, tabKey = `tab:${tab.id}`
|
|
177
|
+
const session = await readSession([key, tabKey])
|
|
178
|
+
if (session[tabKey]?.page.url !== page.url || (!frame && safeUrl(message.page.url) !== page.url)) throw new Error("The page changed")
|
|
179
|
+
const view = session[key]?.url === page.url ? session[key] : { url: page.url }
|
|
180
|
+
const { id } = message
|
|
181
|
+
if (typeof id !== "string" || !id) throw new Error("Invalid area marker")
|
|
182
|
+
const event = { token: crypto.randomUUID(), id, draft: id === view.draft?.id }
|
|
183
|
+
const adjust = message.action === "area-adjust"
|
|
184
|
+
if (adjust) {
|
|
185
|
+
validateAnchor(message.anchor)
|
|
186
|
+
if (message.anchor.type !== "area") throw new Error("Invalid area marker")
|
|
187
|
+
event.anchor = { ...message.anchor, frame }
|
|
188
|
+
}
|
|
189
|
+
if (event.draft) {
|
|
190
|
+
if (view.draft.anchor.frame !== frame) throw new Error("The area draft changed")
|
|
191
|
+
if (adjust) {
|
|
192
|
+
if (JSON.stringify(view.draft.anchor.rect) !== JSON.stringify(message.baseRect)) throw new Error("The area draft changed")
|
|
193
|
+
view.draft = { ...view.draft, anchor: event.anchor }
|
|
194
|
+
}
|
|
195
|
+
} else {
|
|
196
|
+
const storage = await chrome.storage.local.get(null)
|
|
197
|
+
const noteKey = `note:${await pageKey(page.url)}:${id}`, old = storage[noteKey]
|
|
198
|
+
if (!old || old.deleted || delivered(old) || old.anchor.type !== "area" || old.anchor.frame !== frame) throw new Error("This area note is no longer adjustable")
|
|
199
|
+
if (adjust) {
|
|
200
|
+
if (old.revision !== message.revision) throw new Error("The area note changed; try again")
|
|
201
|
+
const note = { ...old, anchor: event.anchor, revision: old.revision + 1, updatedAt: new Date().toISOString() }
|
|
202
|
+
validateReview({ version: 2, annotations: pendingNotes({ ...storage, [noteKey]: note }) })
|
|
203
|
+
await chrome.storage.local.set({ [noteKey]: note })
|
|
204
|
+
event.revision = note.revision
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
await chrome.storage.session.set({ [key]: { ...view, focus: event.draft ? null : id, event } })
|
|
208
|
+
await syncMarkers(tab.id)
|
|
209
|
+
return {}
|
|
210
|
+
}
|
|
145
211
|
const sameSession = (a, b) => a?.sessionID && b?.sessionID && a.sessionID === b.sessionID && (a.provider || "opencode") === (b.provider || "opencode")
|
|
146
212
|
// Called within serial(): receiver IDs may change, but retries belong to a session.
|
|
147
213
|
async function rememberTarget(target, storage = undefined) {
|
|
@@ -184,28 +250,47 @@ async function handle(message, sender) {
|
|
|
184
250
|
if (message.action === "frames-changed") {
|
|
185
251
|
if (!sender.tab) throw new Error("Invalid page source")
|
|
186
252
|
const state = (await chrome.storage.session.get(`tab:${sender.tab.id}`))[`tab:${sender.tab.id}`]
|
|
187
|
-
if (state?.page)
|
|
253
|
+
if (state?.page) {
|
|
254
|
+
const frames = await inject(sender.tab.id)
|
|
255
|
+
await pickFrames(sender.tab.id, state.mode ?? null, frames)
|
|
256
|
+
await syncMarkers(sender.tab.id, frames)
|
|
257
|
+
}
|
|
188
258
|
return {}
|
|
189
259
|
}
|
|
260
|
+
if (["area-focus", "area-adjust"].includes(message.action)) return serial(() => areaGesture(message, sender))
|
|
190
261
|
if (message.action === "capture") {
|
|
191
|
-
|
|
192
|
-
const key = `tab:${
|
|
262
|
+
const { tab, frame, page } = await pageSource(message, sender)
|
|
263
|
+
const key = `tab:${tab.id}`
|
|
193
264
|
const previous = (await chrome.storage.session.get(key))[key] || {}
|
|
194
|
-
const tab = await chrome.tabs.get(sender.tab.id)
|
|
195
|
-
if ((sender.origin || new URL(sender.url).origin) !== new URL(tab.url).origin) throw new Error("Invalid frame source")
|
|
196
|
-
const frame = sender.frameId ? frameLocator(message.frame) : undefined
|
|
197
|
-
if (sender.frameId && !frame) throw new Error("Missing frame locator")
|
|
198
265
|
const captured = !message.modeOnly
|
|
199
|
-
|
|
200
|
-
const
|
|
201
|
-
|
|
266
|
+
if (captured && message.anchor) validateAnchor(message.anchor)
|
|
267
|
+
const changedPage = previous.page?.url !== page.url
|
|
268
|
+
const mode = changedPage || captured || !message.ready && !message.error ? null : previous.mode ?? null
|
|
269
|
+
await chrome.storage.session.set({ [key]: { ...previous, page, mode,
|
|
202
270
|
...(captured ? { anchor: message.anchor ? { ...message.anchor, ...(frame ? { frame } : {}) } : null, error: message.error, captureID: crypto.randomUUID() } : changedPage ? { anchor: null, error: null } : message.error ? { error: message.error } : {}) } })
|
|
203
|
-
if (message.ready) await chrome.tabs.sendMessage(sender.tab.id, { action: "pick",
|
|
204
|
-
if (!
|
|
271
|
+
if (message.ready) await chrome.tabs.sendMessage(sender.tab.id, { action: "pick", mode }, { frameId: sender.frameId || 0 })
|
|
272
|
+
if (!mode && previous.mode) await pickFrames(sender.tab.id, null)
|
|
273
|
+
if (message.ready) await syncMarkers(tab.id, [{ frameId: sender.frameId || 0, frame }])
|
|
274
|
+
else if (changedPage) await syncMarkers(tab.id)
|
|
205
275
|
return {}
|
|
206
276
|
}
|
|
207
277
|
if (sender.url && !sameExtensionURL(sender.url)) throw new Error("Only the extension panel can manage feedback")
|
|
208
278
|
if (message.action === "current") return current(message)
|
|
279
|
+
if (message.action === "area-view") return serial(async () => {
|
|
280
|
+
const { tabID, url, focus, draft, eventID } = message
|
|
281
|
+
if (!Number.isInteger(tabID) || (focus !== null && typeof focus !== "string")) throw new Error("Invalid marker view")
|
|
282
|
+
if (draft) {
|
|
283
|
+
validateAnchor(draft.anchor)
|
|
284
|
+
if (draft.anchor.type !== "area" || typeof draft.id !== "string" || !draft.id.startsWith("draft:")) throw new Error("Invalid area draft")
|
|
285
|
+
}
|
|
286
|
+
const key = `area:${tabID}`, tabKey = `tab:${tabID}`, session = await readSession([key, tabKey])
|
|
287
|
+
if (session[tabKey]?.page.url !== url) return {}
|
|
288
|
+
const view = session[key]?.url === url ? session[key] : null
|
|
289
|
+
if (view?.event?.token !== eventID) return {}
|
|
290
|
+
await chrome.storage.session.set({ [key]: { url, focus, draft, event: view?.event } })
|
|
291
|
+
await syncMarkers(tabID)
|
|
292
|
+
return {}
|
|
293
|
+
})
|
|
209
294
|
if (message.action === "draft") return serial(async () => {
|
|
210
295
|
// A route change must still be able to persist the previous page's draft.
|
|
211
296
|
if (!message.page || safeUrl(message.page.url) !== message.page.url || typeof message.page.title !== "string" ||
|
|
@@ -272,10 +357,10 @@ async function handle(message, sender) {
|
|
|
272
357
|
const state = await current(message)
|
|
273
358
|
if (["save", "pick"].includes(message.action) && message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
|
|
274
359
|
if (message.action === "pick") {
|
|
275
|
-
|
|
360
|
+
if (![null, "element", "area"].includes(message.mode)) throw new Error("Invalid capture mode")
|
|
276
361
|
const key = `tab:${state.tabID}`, previous = (await chrome.storage.session.get(key))[key]
|
|
277
|
-
await chrome.storage.session.set({ [key]: { ...previous,
|
|
278
|
-
return pickFrames(state.tabID,
|
|
362
|
+
await chrome.storage.session.set({ [key]: { ...previous, mode: message.mode } })
|
|
363
|
+
return pickFrames(state.tabID, message.mode)
|
|
279
364
|
}
|
|
280
365
|
if (message.action === "reveal") {
|
|
281
366
|
const note = state.notes.find(note => note.id === message.noteID)
|
|
@@ -302,8 +387,8 @@ async function handle(message, sender) {
|
|
|
302
387
|
catch { throw new Error(RECONNECT) }
|
|
303
388
|
}
|
|
304
389
|
const key = `tab:${tabID}`, previous = (await chrome.storage.session.get(key))[key]
|
|
305
|
-
await chrome.storage.session.set({ [key]: { ...previous,
|
|
306
|
-
await pickFrames(tabID,
|
|
390
|
+
await chrome.storage.session.set({ [key]: { ...previous, mode: null } })
|
|
391
|
+
await pickFrames(tabID, null)
|
|
307
392
|
const result = await anchorMessage(tabID, { action: "reveal", anchor: note.anchor })
|
|
308
393
|
if (!result.ok) throw new Error(result.error)
|
|
309
394
|
return result
|
|
@@ -329,7 +414,7 @@ async function handle(message, sender) {
|
|
|
329
414
|
updates.outbox = null
|
|
330
415
|
}
|
|
331
416
|
await chrome.storage.local.set(updates)
|
|
332
|
-
await updateMarkers(
|
|
417
|
+
await updateMarkers()
|
|
333
418
|
return { notes }
|
|
334
419
|
})
|
|
335
420
|
if (["save", "delete", "restore"].includes(message.action)) return serial(async () => {
|
|
@@ -359,11 +444,12 @@ async function handle(message, sender) {
|
|
|
359
444
|
consumedCaptures: consumedCaptures(previous.consumedCaptures, message.captures), updatedAt: new Date().toISOString() }
|
|
360
445
|
updates[draftKey] = draft
|
|
361
446
|
}
|
|
362
|
-
await chrome.storage.local.set(updates)
|
|
447
|
+
await chrome.storage.local.set(updates)
|
|
448
|
+
await updateMarkers()
|
|
449
|
+
return { note, draft }
|
|
363
450
|
})
|
|
364
451
|
if (message.action === "markers") {
|
|
365
|
-
|
|
366
|
-
await Promise.all(frames.map(({ frameId, frame }) => chrome.tabs.sendMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.page.url === state.page.url && note.anchor.frame === frame ? note.anchor : null })) }, { frameId })))
|
|
452
|
+
await syncMarkers(state.tabID)
|
|
367
453
|
return {}
|
|
368
454
|
}
|
|
369
455
|
if (message.action === "copied") return serial(async () => {
|
|
@@ -385,6 +471,7 @@ async function handle(message, sender) {
|
|
|
385
471
|
if (latest.notes.length + Object.keys(updates).length > 200) throw new Error("This round would exceed 200 notes; send or remove some first")
|
|
386
472
|
validateReview({ version: 2, annotations: [...latest.notes, ...Object.values(updates)] })
|
|
387
473
|
await chrome.storage.local.set(updates)
|
|
474
|
+
await updateMarkers()
|
|
388
475
|
return { count: Object.keys(updates).length }
|
|
389
476
|
})
|
|
390
477
|
if (message.action === "send") return serial(async () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nxxxsooo/opencode-annotate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"description": "Unofficial OpenCode annotation plugin: review AI replies and Markdown with a bundled terminal reviewer; annotate webpages with the browser companion.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|