Repository navigation
Phase 4: HED annotation in the signal viewer - #263
neuromechanist merged 11 commits into
Conversation
Parses base HED 8.4.0 and the HED-SCORE 2.1.0 library schema from a local hed-schemas checkout into a committed JSON bundle (488 tags, 138 KB): the whole SCORE clinical EEG vocabulary plus curated base-HED subtrees for artifacts, event categories, temporal markers and vigilance state. SCORE paths carry the `sc:` namespace prefix so an exported HED string is usable as-is with `"HEDVersion": ["8.4.0", "sc:score_2.1.0"]`. Hand-rolled hedxml scanner rather than an XML dependency; the script header documents how to regenerate. Biome skips the generated bundle. Tested: script runs clean, resolves all 26 quick picks, rejects duplicates.
`loadHedVocab` is the only reference to the JSON bundle, so Vite splits it into its own chunk and the viewer's initial bundle never carries it; the fetch happens when annotation mode is first entered. Search is hand-rolled scoring over the 488-entry list: exact, prefix, hyphen word-boundary, substring, path, description, shortest-tag tiebreak. Multi-word queries are a conjunction scored by their weakest term. Tested: 28 vitest cases against the real bundle, including chunk-size and prefix invariants.
Two disjoint kinds: TimeAnnotation (an events.tsv row, duration 0 for a point marker) and ChannelAnnotation (a channels.tsv row with status and status_description). Pure module - construction with clamping, sorting, upsert/remove, windowing, overlap detection, greedy lane assignment for drawing overlapping spans, and both serializers. Output is deterministic: total sort order, 0.1 ms rounding without float noise, n/a for missing, tabs and newlines stripped from free text at the point it enters the model. Tested: 64 vitest cases, including byte-identical output for a set built in a different order.
Keyed by dataset id, dataset version and recording path (a JSON tuple, so no separator a BIDS path could contain). Not keyed by user: the issue requires persistence regardless of sign-in. Every IndexedDB call is guarded. A synchronous throw on open (Firefox private windows), an absent factory, or a later quota failure degrades to an in-memory store for the session with `persistent` false, which the viewer surfaces as "download these". Records read back are re-validated through the model's constructors rather than trusted. Tested: 22 vitest cases; the no-IndexedDB fallback is the real path under node, not a simulated one.
A pencil toggle beside the topomap arms the tool. On the trace, a click drops a zero-duration event marker and a horizontal drag makes a span, both opening a focus-trapped popover with fuzzy HED search, grouped quick picks and a free-text note. In the gutter, channel selection stays the viewer's existing bad-channel click, which the panel then annotates as a set; the two exports are separate downloads. The layer is self-contained: an overlay canvas above the chrome canvas, a popover and a panel, reading geometry the renderer already computed. It never owns the arrow keys, and pointer handlers are capture-phase on the scope so gutter clicks still reach the existing handler. Annotations restore on mount and flush on teardown, so a recording swap or an enlarge round trip keeps them. Anonymous or unpersisted work arms a beforeunload confirm and an in-panel notice. Tested: driven end to end in Chromium against the dev server on on005514, both themes, inline and enlarged - marker, drag, edit, delete, search, quick picks, channel marks, both downloads, restore across a remount.
Records why annotations are two BIDS kinds rather than one type with optional fields, why storage is local-only in v1, and what that forecloses (channel-scoped time ranges, cross-device access, sharing).
Deploying nemar-website with
|
| Latest commit: |
1ab6938
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://abe3335f.nemar-website.pages.dev |
| Branch Preview URL: | https://feature-issue-255-phase4-hed.nemar-website.pages.dev |
A mount can be destroyed while openAnnotationStore is still in flight — a recording swap, or the enlarge dialog closing. The resolved connection was then unreachable: destroy() flushes through `store`, which is still null, so the IDBDatabase stayed open for the life of the page. Close it at the point the layer learns it is gone.
formatSeconds rounds before printing, and a value just below zero rounds to -0, which stringifies as the cell "-0" — a value no reader of an onset column expects. Return "0" for a rounded zero of either sign.
The channel annotations downloaded as <stem>_channels.tsv, which is the name of the recording's real channels table while being deliberately not one: it lists only the annotated channels and omits the type/units columns BIDS requires. Dropped into a dataset under that name it would delete every unannotated channel's row. Rename it <stem>_channels-annotations.tsv.
Three changes from live design feedback, plus two fixes in the same code. Placement. The popover opened at a fixed offset under the toolbar, which put it on top of the very span the annotator had just dragged out. It is now placed adjacent to its selection: right of it, else left, else below, else above, else — only when nothing clears it — at the right-centre of the trace. Coordinates are relative to the viewer root, so the same arithmetic serves the inline and the enlarged mount. Bounds are the *visible* box (root box intersected with the viewport and any clipping ancestor), because inside the enlarge dialog the viewer root is taller than the dialog that clips it, and placing against the root put the footer below the dialog's edge. It follows the selection across a frame (scrubbing, channel zoom) and a window resize. Pinned footer. The popover no longer scrolls as a whole: its body does, and Save/Cancel sit in a footer that cannot leave the frame however long the vocabulary list is. Enter now saves, once the draft carries a tag or a note, except where a control owns Enter itself (a textarea's newline, a button's activation) or an IME is mid-composition. Escape still cancels. Channel entry. With annotate mode on, clicking a channel label opens the channel popover for that channel directly rather than only toggling the bad mark — the popover's status field decides that mark on save. Its quick picks are the artifact vocabulary (base HED's artifact tree plus SCORE's terms for what the artifact cost the recording), derived from the bundle rather than curated a second time. Outside annotate mode the marking gesture is unchanged. Escape and the enlarge dialog. Whether a cancelled keydown suppresses a modal dialog's own close request is engine-dependent, so one Escape could have closed the popover and ejected the enlarged viewer behind it. The layer now guards the surrounding dialog's `cancel` while its popover is open (and briefly after, since the close request can arrive once it has closed), and exposes isPopoverOpen for the same question asked from outside. Overlay caching. The lane assignment and the channel index were rebuilt on every drawOverlay, which runs on every pointer move of a drag. Both are now cached on the set's identity, the visible-window filter is shared with the hit test, and drag repaints are coalesced to one per frame.
The placement arithmetic decides whether the popover covers the signal being annotated, which a screenshot review catches unreliably; it and the other pure helpers are exported precisely so they can be driven without a browser. 26 tests over placement (each candidate, the clamps, bounds that do not start at the viewer's origin), the time/pixel mapping, Enter's submit rule, the unsaved-work predicate and the colour blend. Storage gains a real IndexedDB. fake-indexeddb is a platform shim rather than a mock of anything here — the actual W3C algorithms under Node, as jsdom is a real DOM — so nothing in annotation-store.ts is stubbed: the tests drive the genuine open-and-upgrade, a round trip through a second connection, key separation, and the degrade-to-memory path through a genuine write failure. Until now only the no-IndexedDB fallback was covered, because Node has none.
|
Both rounds are in, gates green on the tip ( Design feedback
Two things I hit while testing that are worth knowing:
Review findings
Nothing deferred. On "Save does nothing"I could not reproduce it on the settled build, and I think the report caught a mid-edit module: the refactor that hoists the save handler out of the click listener passes through a state where the file does not parse, and a reload in that window leaves the viewer's JS not evaluated at all — which fails Save, Escape and Enter together, exactly as described. On the current tip, with real mouse and real key events in Chrome (
Worth a retest now that the build is settled. Two notes for whoever retests locally:
|
e281dc4
into
feature/issue-256-epic-viewer-workbench
Part of epic #256. Implements #255.
Summary
Domain experts can now annotate a recording directly in the signal viewer using
the HED-SCORE clinical EEG vocabulary and base HED's artifact terms, and export
the result as BIDS TSV.
A pencil toggle beside the topomap arms annotation mode. With it on:
for a span with a live range highlight. Both open a popover offering fuzzy
search over the vocabulary, grouped quick picks, and a free-text note.
rather than duplicated — then annotate the marked channels as a set.
cap for a marker, translucent violet span for a duration) and as a dedicated
strip on the events minimap, visually distinct from the dataset's own events.
Clicking one reopens it to edit or delete.
<stem>_events.tsvand<stem>_channels.tsv.Annotations persist in IndexedDB per (dataset, version, recording), restore on
mount, and flush on teardown, so a recording swap (#258) or an enlarge round
trip keeps them.
Vocabulary bundle
scripts/extract-hed-vocab.mjsparses base HED 8.4.0 and HED-SCORE 2.1.0 from alocal
hed-standard/hed-schemascheckout intosrc/lib/eeg-viewer/hed-vocab.json.The script header documents regeneration; there is no runtime schema fetch and no
new dependency (the hedxml scanner is ~40 lines).
dist/_astro/hed-vocab.*.js, its own lazy chunkCurated rather than complete: the whole SCORE library (every root is clinical EEG
by construction) plus base-HED's artifact tree, event categories, temporal markers,
and vigilance/postural state. Build verified the viewer chunk does not contain it —
the fetch happens when annotation mode is first entered.
Decisions
zero-duration marker and a drag makes a span (both ordinary
events.tsvrows),and channel annotations are a separate, timeless kind with
channels.tsvsemantics. The two kinds stay separate through model, persistence and export.
Recorded as ADR 0013, which also states what that forecloses.
name, notchannel, as the channels TSV's first column. BIDSchannels.tsvrequiresname; usingchannelwould make the exportun-mergeable into a real one. It is an annotation file, so it omits the
type/unitscolumns that belong to the dataset rather than the annotator.sc:Episode/Epileptic-seizure), so an exportis usable with
"HEDVersion": ["8.4.0", "sc:score_2.1.0"]. The panel says so.Open question:
sc:is the conventional prefix in the HED-SCORE examples, buta sidecar may choose another. Emitting it here keeps the serializer dumb; making
it configurable is a small change if anyone wants it.
[data-user-menu]from the DOM.Nav.astrorendersit only when
getSessionreturned one, so its presence is exactly "there is asession this page can act on" — no extra fetch. A false negative only ever costs
an extra confirm on leaving.
beforeunloadwarning also fires when persistence itself failed, not justwhen anonymous. Same exposure, same fix: download the file.
why and when to revisit.
src/pages/dataset/[id].astro— the layer mounts from insideviewer.ts, so all three mount paths (including Phase 5: View data button opens the enlarge viewer #262's newopenRecordingInDialog)get annotations for free. Rebased onto e8f9d6c; no conflicts.
Test plan
Gates on the branch tip: lint, typecheck (0 errors), 1347 tests, build — all green.
114 new unit tests (64 model, 28 vocabulary, 22 storage), no mocks; the vocabulary
tests run against the real committed bundle and the storage fallback is the genuine
no-IndexedDB path under node.
Driven end to end in headless Chromium against the dev server on
on005514(129-channel HBN EEG), both themes, inline and enlarged:
n/a, long-form HED)ArrowRightstill scrolls time (0.0–10.0 → 2.5–12.5)Two bugs found and fixed during that pass: an author
display:flexsilentlybeating the UA
[hidden]rule (popover and panel never hid), and a defaultfocus()on close scrolling the trace out from under the annotator.Deliberately left out
Channel-scoped time ranges (per the scope correction), server-side storage,
sharing, and any contribution path back to the dataset. Keyboard creation of
annotations — the popover, its controls and the annotation list are all
focus-reachable and focus-trapped, but placing a marker still needs the pointer.
Design feedback round
Live testing turned up three things about the popover. All three are in
7a22569, along with two review findings that live in the same code.1. It covered what it was about. The popover opened at a fixed offset under
the toolbar, so a span dragged out in the middle of the trace was hidden behind
the box asking what it was. It is now placed adjacent to its selection and
never over it: right of it, else left, else below, else above, and only when no
placement clears it, at the right-centre of the trace area. A channel
annotation anchors to that channel's row in the gutter, so the labels it names
stay readable.
The arithmetic (
placeAnnotationPopover) is pure and unit-tested — it decideswhether the annotator can see the signal they are describing, which is not
something a screenshot review catches reliably. Coordinates are relative to the
viewer root, so inline and enlarged differ only in the numbers.
One subtlety worth recording: bounds are the visible box, not the viewer
root. Inside the enlarge dialog the root is taller than the dialog that clips
it (834 px of root in a 739 px dialog on a 1400×900 window), so placing
against the root's own height put the footer below the dialog's edge. Bounds
are therefore the root box intersected with the viewport and with any clipping
ancestor — stopping at
<body>, because overflow on the root element clips theviewport rather than a box, and
documentElement.getBoundingClientRect()on ascrolled page is nowhere near it. That one is a real bug found by testing
inline, not a defensive flourish.
Placement re-runs on every frame the popover survives (time scrubbing, channel
zoom, the enlarge move) and on window resize — twice there, once immediately
and once on the next frame, because a resize can arrive before the new viewport
metrics have settled.
2. Save and Cancel are pinned. The popover no longer scrolls as a whole:
the body scrolls, the footer does not, so the two buttons are on screen
whatever the vocabulary list is doing. Its height is also capped to the visible
bounds, which is what keeps the footer inside the dialog. Enter now saves,
once the draft carries at least one tag or a non-empty comment, except where a
control owns Enter itself (a textarea's newline, a button's or link's
activation — otherwise the quick-pick chips would stop being keyboard
reachable) or an IME is mid-composition. Escape still cancels, and the
footer says so.
3. A channel click annotates that channel. With annotate mode on, clicking
a channel label opens the channel popover for that channel directly instead of
only toggling the bad mark; the popover's status field then decides that mark
on save, so the two cannot disagree. Its quick picks are filtered to the noise
and artifact vocabulary — base HED's artifact tree (the causes) plus SCORE's
terms for what the artifact cost the recording — because "this electrode had a
seizure" is not a thing anybody annotates. The groups are derived from the
bundle (
artifactQuickPicks), not curated a second time, so a regeneratedbundle keeps them in step. Outside annotate mode the bad-channel gesture is
exactly as it was. The bulk "annotate N marked channels" entry point stays for
channels marked before the pencil was armed.
Review findings
7a22569— guards the surrounding dialog'scancelwhile the popover is open, and briefly after, since the close request can arrive once it has closed;isPopoverOpen()exposes the same question outwards. Wired from inside the layer viaroot.closest("dialog")at open time, sodataset/[id].astrostays untouched and the enlarge move cannot leave a stale listener.openAnnotationStoreleaked the connectionaf72bd07a22569— both cached on the set's identity (the set is replaced, never mutated, so a stale cache is impossible), the visible-window filter shared with the hit test, drag repaints coalesced to one per frame1ab6938—fake-indexeddbas a dev dependency. It is a platform shim, not a mock of anything this repo owns: the actual W3C algorithms under Node, as jsdom is a real DOM. Covers open-and-upgrade, a round trip through a second connection, key separation, and the degrade-to-memory flip through a genuine write failureannotation-ui.ts's pure helpers untested1ab6938— 26 tests over placement, the time/pixel mapping, Enter's submit rule, the unsaved-work predicate, the colour blendchannels.tsvdbdfbf3— now<stem>_channels-annotations.tsv, with a line beside the button saying to merge it into the dataset's own table rather than use it as oneformatSecondscould emit-096db415Verified live
Chrome against
bun run devonon005514(129-channel HBN EEG), inline andenlarged, both themes, with real mouse and real key events:
persists (
1.9912–3.1316 s · Electroencephalographic-seizure +1), thespan draws, the dialog stays open
(
4.6228–5.5 s · Spike)second Escape then closes the dialog — the layering the guard is for
flips left near the right edge; falls back only where nothing clears
dialog's 780 px), body scrolling (633 px of content in a 557 px box)
Annotate 1 channelfor thatchannel with 31 artifact picks in 4 groups, no epileptiform or sleep
terms; saving marks it (
E54 · bad · Line-noise-artifact)so the footer stays in view
One caveat on that last line: the automation harness resizes the browser
window without dispatching
resize(0 events observed across severalresizes), so it was exercised by dispatching a
resizeevent on the same codepath a user's drag of the window edge takes — 709 px tall → 641 px, footer back
inside the viewport. A human dragging the window edge is worth one look.