From 3a809fd435b11638acd1c28745e9de1e4f6c2772 Mon Sep 17 00:00:00 2001 From: Haotian Hong Date: Mon, 19 Oct 2026 19:41:24 -0400 Subject: [PATCH 1/7] Preview feature branches side by side on GitHub Pages The preview workflow served one branch, feature/simulation, at a fixed path. Each run replaced the whole site, so a second branch could not be previewed without wiping the first. It now builds main at the root and every branch in PREVIEW_BRANCHES under /preview//, each stamped with its commit in preview.txt. The branch that triggered the run is validated with `npm run check`. main and the other listed branches are only rebuilt, since their own pushes validate them. A run from a branch that is not listed fails before building anything. This branch, feature/measurement-markers, is the first entry. It is also in the github-pages environment's deployment branch policy. A deploy from main still removes the previews; re-run this workflow to restore them. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/preview-pages.yml | 99 +++++++++++++++++++++-------- 1 file changed, 71 insertions(+), 28 deletions(-) diff --git a/.github/workflows/preview-pages.yml b/.github/workflows/preview-pages.yml index 5839e6b..5fdef62 100644 --- a/.github/workflows/preview-pages.yml +++ b/.github/workflows/preview-pages.yml @@ -1,18 +1,22 @@ -name: Preview simulation branch on GitHub Pages +name: Preview feature branches on GitHub Pages # GitHub Pages serves one site per repository, and a deployment replaces all # of it. This workflow therefore deploys the production site built from main -# at the root, unchanged for visitors, and this branch's build under -# /preview/simulation/, so the branch can be checked on github.io before it is -# merged. A deployment from main (deploy-pages.yml) removes the preview again; -# re-run this workflow from the Actions tab to restore it. +# at the root, unchanged for visitors, and every branch in PREVIEW_BRANCHES +# under /preview//, so a branch can be checked on +# github.io before it is merged. Each run rebuilds all of them, so one +# branch's preview does not wipe another's. # -# Requires feature/simulation in the github-pages environment's deployment -# branch policy (Settings → Environments → github-pages). +# A deployment from main (deploy-pages.yml) removes the previews again; re-run +# this workflow from the Actions tab, on any listed branch, to restore them. +# +# Every listed branch needs an entry in the github-pages environment's +# deployment branch policy (Settings → Environments → github-pages), and its +# own copy of this file must list it under on.push.branches. on: push: - branches: ['feature/simulation'] + branches: ['feature/measurement-markers'] workflow_dispatch: permissions: @@ -24,51 +28,90 @@ concurrency: group: "pages" cancel-in-progress: false +env: + # Space-separated. The branch that triggers a run must be one of them. + PREVIEW_BRANCHES: feature/measurement-markers + jobs: build-and-deploy: environment: name: github-pages - url: ${{ steps.deployment.outputs.page_url }}preview/simulation/ + url: ${{ steps.deployment.outputs.page_url }}preview/${{ steps.assemble.outputs.slug }}/ runs-on: ubuntu-latest steps: + - name: Only listed branches deploy + run: | + case " $PREVIEW_BRANCHES " in + *" $GITHUB_REF_NAME "*) ;; + *) echo "::error::$GITHUB_REF_NAME is not in PREVIEW_BRANCHES ($PREVIEW_BRANCHES)"; exit 1 ;; + esac + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '24' + - name: Checkout main (production root) uses: actions/checkout@v4 with: ref: main path: main - - name: Checkout this branch (preview) + # deploy-pages.yml validates main on every push; here it is only rebuilt. + - name: Build the production site + working-directory: main + run: | + npm ci + npm run build:web + + - name: Checkout this branch uses: actions/checkout@v4 with: path: branch - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: '24' - - - name: Build the production site exactly as deploy-pages.yml does - working-directory: main + - name: Validate and build this branch + working-directory: branch run: | npm ci npm run check - - name: Validate and build the branch site - working-directory: branch + # Their own pushes validate them; here they are only rebuilt. + - name: Build the other preview branches run: | - npm ci - npm run check + for b in $PREVIEW_BRANCHES; do + [ "$b" = "$GITHUB_REF_NAME" ] && continue + s="${b#feature/}"; s="${s//\//-}" + if ! git -C branch fetch --no-tags --depth 1 origin "refs/heads/$b"; then + echo "::warning::$b could not be fetched; its preview is left out" + continue + fi + git -C branch worktree add --detach "$PWD/previews/$s" FETCH_HEAD + (cd "previews/$s" && npm ci && npm run build:web) + done - name: Assemble the site + id: assemble run: | - mkdir -p _site/preview/simulation - cp -R main/web/. _site/ - cp -R branch/web/. _site/preview/simulation/ - { - echo "branch: ${GITHUB_REF_NAME}" - echo "commit: ${GITHUB_SHA}" + stamp() { + echo "branch: $1" + echo "commit: $2" echo "built: $(date -u +%Y-%m-%dT%H:%M:%SZ)" - } > _site/preview/simulation/preview.txt + } + mkdir -p _site + cp -R main/web/. _site/ + s="${GITHUB_REF_NAME#feature/}"; s="${s//\//-}" + echo "slug=$s" >> "$GITHUB_OUTPUT" + mkdir -p "_site/preview/$s" + cp -R branch/web/. "_site/preview/$s/" + stamp "$GITHUB_REF_NAME" "$GITHUB_SHA" > "_site/preview/$s/preview.txt" + for d in previews/*/; do + [ -d "$d" ] || continue + o=$(basename "$d") + mkdir -p "_site/preview/$o" + cp -R "$d/web/." "_site/preview/$o/" + stamp "$o" "$(git -C "$d" rev-parse HEAD)" > "_site/preview/$o/preview.txt" + done + find _site/preview -maxdepth 2 -name preview.txt -exec sh -c 'echo "== $1"; cat "$1"' _ {} \; - name: Setup Pages uses: actions/configure-pages@v4 From c4cda347aa1e37b94943441bcd6de779925e16ea Mon Sep 17 00:00:00 2001 From: Haotian Hong Date: Mon, 19 Oct 2026 19:58:54 -0400 Subject: [PATCH 2/7] Carry RF centres and a reduced-samples flag to the viewer Measurement markers snap to RF centres and read waveform values at any time, so the viewer needs two facts the transport dropped: - `rf.c`, the pulse's effective centre (absolute), already computed by the decoder. TE and TR are measured from it. - `r: 1` on a gradient or RF waveform whose samples the overview reduced. Values interpolated across dropped samples are only approximate, and a reduced waveform's interior bends are not reliable snap targets. The flag is written only when set, to keep the JSON envelope small; exact detail windows never carry it. Both hosts use this packer (the web app calls it in the page), so neither needs another change. Co-Authored-By: Claude Opus 5.5 (1M context) --- python/src/seqeyes/resources/pulseq-bundle.js | 13 +++++-- src/editor/blockTransport.ts | 17 ++++++-- test/pulseq/block-transport.test.ts | 39 +++++++++++++++++++ web/pulseq-bundle.js | 13 +++++-- 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/python/src/seqeyes/resources/pulseq-bundle.js b/python/src/seqeyes/resources/pulseq-bundle.js index df6a027..3b2a453 100644 --- a/python/src/seqeyes/resources/pulseq-bundle.js +++ b/python/src/seqeyes/resources/pulseq-bundle.js @@ -2648,7 +2648,8 @@ var Pulseq = (() => { if (useM4) reduceM4Range(time, values, clipped.start, clipped.end, this.cap, this.emit); else reduceUniformRange(time, values, clipped.start, clipped.end, this.cap, this.emit); this.wrapPhase = false; - return { o: origin, n: this.cursor - origin }; + const kept = this.cursor - origin; + return kept < clipped.end - clipped.start ? { o: origin, n: kept, r: true } : { o: origin, n: kept }; } }; function discard() { @@ -2824,9 +2825,11 @@ var Pulseq = (() => { band.polarFlipDeg, band.mz ]); - return { + const packed = { s: rf.startTime, d: rf.duration, + // Absolute effective centre, the point TE and TR are measured from. + c: rf.centerTime, // `t`/`m` (magnitude) and `pt`/`p` (phase) buffer spans. o: magnitude.o, n: magnitude.n, @@ -2845,9 +2848,11 @@ var Pulseq = (() => { u: rf.use || "u" // 'e'=excitation, 'r'=refocusing, 'i'=inversion, 's'=saturation, 'u'=undefined }; + if (magnitude.r) packed.r = 1; + return packed; } function packGrad(grad, ref) { - return { + const packed = { s: grad.startTime, d: grad.duration, o: ref.o, @@ -2856,6 +2861,8 @@ var Pulseq = (() => { ty: grad.type, ch: grad.channel }; + if (ref.r) packed.r = 1; + return packed; } function waveformMagnitudeMetrics(time, values) { const count = Math.min(time.length, values.length); diff --git a/src/editor/blockTransport.ts b/src/editor/blockTransport.ts index 5444057..ee64330 100644 --- a/src/editor/blockTransport.ts +++ b/src/editor/blockTransport.ts @@ -98,6 +98,8 @@ export interface PackedBlocks { interface PairRef { o: number; n: number; + /** Fewer samples were kept than the (clipped) waveform has. */ + r?: boolean; } /** @@ -192,7 +194,8 @@ class WritingSink implements PairSink { if (useM4) reduceM4Range(time, values, clipped.start, clipped.end, this.cap, this.emit); else reduceUniformRange(time, values, clipped.start, clipped.end, this.cap, this.emit); this.wrapPhase = false; - return { o: origin, n: this.cursor - origin }; + const kept = this.cursor - origin; + return kept < clipped.end - clipped.start ? { o: origin, n: kept, r: true } : { o: origin, n: kept }; } } @@ -490,8 +493,10 @@ function packRf( band.polarFlipDeg, band.mz, ]); - return { + const packed: Record = { s: rf.startTime, d: rf.duration, + // Absolute effective centre, the point TE and TR are measured from. + c: rf.centerTime, // `t`/`m` (magnitude) and `pt`/`p` (phase) buffer spans. o: magnitude.o, n: magnitude.n, qo: phase.o, qn: phase.n, @@ -506,14 +511,20 @@ function packRf( fo: rf.freqOffset, po: rf.phaseOffset, u: rf.use || 'u', // 'e'=excitation, 'r'=refocusing, 'i'=inversion, 's'=saturation, 'u'=undefined }; + if (magnitude.r) packed.r = 1; + return packed; } function packGrad(grad: DecodedGradWaveform, ref: PairRef): Record { - return { + const packed: Record = { s: grad.startTime, d: grad.duration, o: ref.o, n: ref.n, a: grad.amplitude, ty: grad.type, ch: grad.channel, }; + // Only when set: most waveforms are whole, and the envelope is JSON. + // Readouts mark values interpolated across dropped samples as approximate. + if (ref.r) packed.r = 1; + return packed; } /** Peak, |area| and flat-top detection, measured on the undecimated pulse. */ diff --git a/test/pulseq/block-transport.test.ts b/test/pulseq/block-transport.test.ts index 18d0f24..075cc05 100644 --- a/test/pulseq/block-transport.test.ts +++ b/test/pulseq/block-transport.test.ts @@ -236,6 +236,45 @@ describe('packed block transport', () => { } }); + it('carries each RF centre and flags only the waveforms the overview reduced', () => { + // Measurement markers snap to RF centres and treat corners inside a reduced + // waveform as unknown, so both have to reach the webview. + const sequence = loadSequence('writeSpiral.seq'); + const decoded = loadBlocks('writeSpiral.seq'); + const packed = packSequenceBlocks(sequence); + type Packed = { r?: number; c?: number }; + let rfCount = 0; + let reducedCount = 0; + let wholeCount = 0; + decoded.forEach((block, index) => { + const entry = packed.blocks[index] as Record; + if (block.rf) { + rfCount++; + expect(entry.rf!.c).toBe(block.rf.centerTime); + } + for (const axis of ['gx', 'gy', 'gz'] as const) { + const native = block[axis]; + if (!native || native.type === 'none') continue; + const reduced = native.timePoints.length > MAX_DISPLAY_PTS; + expect(entry[axis]!.r === 1, `${axis} of block ${block.index}`).toBe(reduced); + if (reduced) reducedCount++; + else wholeCount++; + } + }); + expect(rfCount).toBeGreaterThan(0); + expect(reducedCount).toBeGreaterThan(0); + expect(wholeCount).toBeGreaterThan(0); + + // An exact detail window carries every sample it covers, so nothing is flagged. + const index = decoded.findIndex(b => b.gx && b.gx.type !== 'none' && b.gx.timePoints.length > 2000); + const native = decoded[index].gx!; + const detail = packSequenceBlockRange( + sequence, index, index + 1, undefined, MAX_DETAIL_PTS, undefined, + { startSec: native.timePoints[0], endSec: native.timePoints[native.timePoints.length - 1] }, + ); + expect((detail.blocks[0] as Record).gx.r).toBeUndefined(); + }); + it('falls back to a bounded reduction when a window cannot be sent exactly', () => { const sequence = loadSequence('writeSpiral.seq'); // A one-sample exactness budget forces the reduced path for any real window. diff --git a/web/pulseq-bundle.js b/web/pulseq-bundle.js index df6a027..3b2a453 100644 --- a/web/pulseq-bundle.js +++ b/web/pulseq-bundle.js @@ -2648,7 +2648,8 @@ var Pulseq = (() => { if (useM4) reduceM4Range(time, values, clipped.start, clipped.end, this.cap, this.emit); else reduceUniformRange(time, values, clipped.start, clipped.end, this.cap, this.emit); this.wrapPhase = false; - return { o: origin, n: this.cursor - origin }; + const kept = this.cursor - origin; + return kept < clipped.end - clipped.start ? { o: origin, n: kept, r: true } : { o: origin, n: kept }; } }; function discard() { @@ -2824,9 +2825,11 @@ var Pulseq = (() => { band.polarFlipDeg, band.mz ]); - return { + const packed = { s: rf.startTime, d: rf.duration, + // Absolute effective centre, the point TE and TR are measured from. + c: rf.centerTime, // `t`/`m` (magnitude) and `pt`/`p` (phase) buffer spans. o: magnitude.o, n: magnitude.n, @@ -2845,9 +2848,11 @@ var Pulseq = (() => { u: rf.use || "u" // 'e'=excitation, 'r'=refocusing, 'i'=inversion, 's'=saturation, 'u'=undefined }; + if (magnitude.r) packed.r = 1; + return packed; } function packGrad(grad, ref) { - return { + const packed = { s: grad.startTime, d: grad.duration, o: ref.o, @@ -2856,6 +2861,8 @@ var Pulseq = (() => { ty: grad.type, ch: grad.channel }; + if (ref.r) packed.r = 1; + return packed; } function waveformMagnitudeMetrics(time, values) { const count = Math.min(time.length, values.length); From 61fc5357dafb87c33ee868d5b8470b4e7bba287c Mon Sep 17 00:00:00 2001 From: Haotian Hong Date: Mon, 19 Oct 2026 19:58:54 -0400 Subject: [PATCH 3/7] Add measurement markers to the waveform viewer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Right-click the waveform viewer and choose Add marker to drop a vertical marker; add as many as needed (M1, M2, …). - Snapping. Near a gradient corner the menu offers that point: - a trapezoid's ramp and flat-top corners; - an extended trapezoid's breakpoints, or an arbitrary gradient's bends (found by simplifying the waveform and keeping flat↔ramp changes, reversals, steps and large slope changes); - RF start, centre and end; ADC start, centre and end; trigger starts; - block boundaries. Coincident targets share one label, with the pointer's own row first. Once markers are in use, a ring marks the snap point as the pointer approaches. "Add marker at pointer (no snap)", or Shift while dragging, places one exactly; a remembered checkbox turns snapping off. - Readouts. Each marker crosses the RF and gradient rows with a dot and its value, and Δt is drawn between neighbours. A table strip under the plot lists time, block and time within it, Δt, Gx/Gy/Gz in the current unit, RF amplitude and phase, the ADC sample and the trigger. Copy gives tab-separated text. Values read from a reduced overview are marked ≈. - Editing. Drag to move (without panning the view), right-click next to a marker to remove it, or use the table. Esc closes the menu or cancels a drag. Markers are cleared when another sequence loads. The viewer has two renderers: the bundle (VS Code) and web/index.html's own copy (web app, preview, MATLAB). So the feature is one module, markers.js, that each renderer installs with accessors to its own state. The last install wins, and the module owns its listeners on #cc. A capture-phase mousedown there claims a marker drag before either renderer's pan handler sees it, so neither copy's mouse code changed. Each renderer adds one line to its overlay pass and one reset per load path. Tests: - unit tests for corner detection, snapping and ranking, readouts with and without detail, the marker list and the table; - browser tests in the web app for add, snap, Δt, no-snap, Esc and outside-click, overlay pixels, zoom, a new file, remove and clear, drag with and without Shift, and the remembered setting; - one test through the VS Code renderer. Also corrects a comment from the simulation work: the Python viewer has its own renderer and does not load this bundle. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 30 + .../src/seqeyes/resources/webview-bundle.js | 1072 ++++++++++++++++- scripts/build-webview.mjs | 2 + src/editor/webview/assets/drawing.js | 1 + src/editor/webview/assets/interaction.js | 8 + src/editor/webview/assets/markers.js | 1045 ++++++++++++++++ src/editor/webview/assets/prefs-ui.js | 3 +- src/editor/webview/assets/prefs.js | 2 + src/editor/webview/assets/state.js | 10 +- src/editor/webview/assets/styles.css | 32 + test/browser/markers.spec.ts | 269 +++++ test/browser/vscode-webview.spec.ts | 54 + test/editor/markers.test.ts | 223 ++++ web/index.html | 11 +- web/styles.css | 32 + web/webview-bundle.js | 1072 ++++++++++++++++- 16 files changed, 3847 insertions(+), 19 deletions(-) create mode 100644 src/editor/webview/assets/markers.js create mode 100644 test/browser/markers.spec.ts create mode 100644 test/editor/markers.test.ts diff --git a/README.md b/README.md index c0b53d7..58c312a 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ All the same features as the other versions — interactive waveforms, k‑space - **Interactive Canvas**: cursor‑anchored time zoom, per‑row y‑axis zoom, drag‑pan, hover tooltips - **6 built‑in themes**: One Light · One Dark · Dracula · Nord · GitHub Light · GitHub Dark (+ system auto) - **Vertical cursor** with live time readout +- **Measurement markers**: right-click to drop markers that snap to gradient corners, RF/ADC edges and centres, and block boundaries; read each channel's value at every marker and Δt between them, and copy the table - **Unit switchers** for time (s / ms / µs) and gradient (Hz/m / mT/m / G/cm) - **K‑space unit toggle** (1/m ↔ rad/m) with auto‑updating axis ticks - **Block boundary lines** — toggle in toolbar @@ -377,6 +378,7 @@ long, the plan takes a coarser tested spacing and says so. **Not yet**: | Load an ASC profile | `Load ASC (PNS/Acoustic)`, then choose a scanner ASC. PNS coefficients and acoustic resonances are read independently — a file carrying only one still loads, and the viewer says which it found | | Toggle block boundaries | Checkbox `☐ Blocks` in toolbar | | Block details & values | Hover waveform | +| Measure times and values | Right-click the waveform → **Add marker** (see [Measurement markers](#measurement-markers)). Drag a marker to move it; hold `Shift` to place it off the snap points | | Switch theme | Toolbar `Theme` dropdown | | Cycle the analysis panel | Toolbar button: closed → **K-Space** → **Spectrogram** → closed. The label always names what the next click does | | Rotate 3D view | Left‑drag in k‑space panel | @@ -396,6 +398,34 @@ long, the plan takes a coarser tested spacing and says so. **Not yet**: | Play the simulated gradient sound | `▶` at the top-left of the panel. Playback runs from the marker (or the window start) to the end of the visible window | | Stop remembering settings | ⚙ in the toolbar, then untick **Remember my settings**. **Forget stored settings** deletes what is already there | +## Measurement markers + +Right-click the waveform viewer and choose **Add marker** to drop a vertical +marker. Add as many as you need (M1, M2, …): + +- **Snapping.** Near a gradient corner the menu offers that point instead: + a trapezoid's ramp and flat-top corners, the breakpoints of an extended + trapezoid or the bends of an arbitrary gradient, RF start, centre and end, + ADC start, centre and end, trigger starts, and block boundaries. Once + markers are in use, a ring marks the snap point as the pointer approaches + one. **Add marker at pointer (no snap)**, or `Shift` while dragging, places + a marker exactly where you point; the menu's checkbox turns snapping off. +- **Readouts.** Each marker crosses the RF and gradient rows with a dot and + its value, and Δt is shown between neighbouring markers. The table under + the plot lists every marker: time, block and time within it, Δt to the + previous one, Gx/Gy/Gz in the current gradient unit, RF amplitude and + phase, the ADC sample and the trigger. **Copy** puts it on the clipboard as + tab-separated text. +- **Exactness.** Trapezoid corners, RF/ADC edges and block boundaries are + always exact. A long arbitrary waveform is reduced for the whole-sequence + view; values read from those reduced samples are marked ≈ until you zoom + in far enough for the exact samples to load, and its interior bends are + only offered as snap points then. +- **Editing.** Drag a marker to move it, right-click next to one to remove + it, or use the table's × and **Clear**. `Esc` closes the menu or cancels a + drag. Markers belong to the open sequence and are cleared when another one + loads. + ## Remembered settings The viewer comes back the way you left it. Theme, time and gradient units, the diff --git a/python/src/seqeyes/resources/webview-bundle.js b/python/src/seqeyes/resources/webview-bundle.js index 0d22f85..fb2d3b8 100644 --- a/python/src/seqeyes/resources/webview-bundle.js +++ b/python/src/seqeyes/resources/webview-bundle.js @@ -39,6 +39,8 @@ var SeqEyesPrefs = (function () { kspaceUnit: 'seqeyes.kspace.unit', kspaceDotSize: 'seqeyes.kspace.dotSize', kspaceProjection: 'seqeyes.kspace.projection', + markerSnap: 'seqeyes.markers.snap', + markerTable: 'seqeyes.markers.table', ascName: 'seqeyes.asc.name', ascText: 'seqeyes.asc.text' }; @@ -1368,7 +1370,7 @@ function applySerializedKspace(payload){ much as the message: the progress overlay reaches "Ready" either way, so leaving stale blocks on screen would read as a successful load. */ function showSequenceLoadFailure(message){ - BL=[];waveformOverview=null;blockPos=[];mmCache=null;resetWaveformDetail(); + BL=[];waveformOverview=null;blockPos=[];mmCache=null;resetWaveformDetail();SeqEyesMarkers.reset(); labelInfo={names:[],kinds:[]};labelTable=null;labelBusy=false;chVis[11]=false;SeqEyesLabels.closeControls(false);buildLegend(); setViewerNotice('sequence',message); setExportButtonEnabled(false); @@ -1397,7 +1399,7 @@ window.addEventListener('message',function(e){ return; } if(m.type==='sequenceData'){ - resetWaveformDetail(m.sequenceGeneration); + resetWaveformDetail(m.sequenceGeneration);SeqEyesMarkers.reset(); try{ BL=unpackSequenceBlocks(m.blocks,m.sampleTimes,m.sampleValues,m.sampleCount||0); }catch(err){ @@ -2130,9 +2132,9 @@ window.SeqEyesPanelHost={ message.endSec=endSec; vscApi.postMessage(message); }, - /* Simulation: only inside VS Code, where the extension answers these. The - Python viewer runs this bundle too, with no host to ask, so it keeps the - Simulation button hidden. */ + /* Simulation: only inside VS Code, where the extension answers these. Any + page that loads this bundle without a VS Code host keeps the Simulation + button hidden. (The Python viewer has its own renderer and does not.) */ createSimulationWorker:vscApi?createSimulationWorkerStandIn:undefined, getSequenceSource:vscApi?simulationSequenceSource:undefined, getSequenceSourceStatus:vscApi?simulationSequenceStatus:undefined, @@ -2603,6 +2605,7 @@ function drawCursorOverlay(){ var dpr=window.devicePixelRatio||1,w=moc.width/dpr,h=moc.height/dpr; moctx.clearRect(0,0,w,h); drawPanelMarker(w,h); + if(typeof SeqEyesMarkers!=='undefined')SeqEyesMarkers.drawOverlay(moctx,w,h); if(!cursorActive)return;var cx=t2x(cursorT); if(cxw-M.r)return; var color=getComputedStyle(document.body).getPropertyValue('--cr').trim(); @@ -9980,7 +9983,8 @@ var SeqEyesPrefsUi = (function () { var note = element('div', 'prefs-note'); note.appendChild(element('div', null, 'Theme, time and gradient units, the Blocks toggle, k-space and ' - + 'spectrogram options, and panel sizes are kept between sessions.')); + + 'spectrogram options, marker snapping, and panel sizes are kept ' + + 'between sessions.')); note.appendChild(element('div', null, inVsCode() /* Different sentences because the two hosts really do keep different things: a path the extension re-reads, versus the file's text. */ @@ -10090,6 +10094,1054 @@ var SeqEyesPrefsUi = (function () { })(); +/* ══ markers.js ══ */ +/* ═══════════════════════════════════════════════════════════════════════ + Measurement markers + ═══════════════════════════════════════════════════════════════════════ + + Right-click the waveform viewer to drop a vertical marker. Each marker + reads out its time, its block and every channel's value where it crosses, + and Δt to its neighbour. Placement snaps to gradient corners, RF and ADC + edges and centres, and block boundaries. + + Two renderers draw this viewer: the bundle (VS Code) and web/index.html's + own copy inside its IIFE (web app, preview, MATLAB). Both install this + module with accessors to their own state. The last install wins and the + DOM is wired once, which is the pattern prefs-ui.js and panel.js use. + + The core takes everything it reads as arguments, so it runs in node:vm for + the unit tests; only install() touches the DOM. */ + +var SeqEyesMarkers = (function () { + /* Pointer distances in CSS pixels: how close a corner must be to pull a + marker onto it, how close a press must be to grab a marker, and how close + a right-click must be to offer removing one. */ + var SNAP_PX = 8; + var HIT_PX = 4; + var REMOVE_PX = 6; + /* More blocks than this inside the snap distance means the view is too + zoomed out for a corner to be a meaningful target. */ + var MAX_SNAP_BLOCKS = 32; + /* Interior corners of an arbitrary waveform are only searched in a slice + this small, so a hover never walks a whole readout. */ + var MAX_CORNER_SAMPLES = 512; + /* Candidates closer than this are one point with several names. */ + var MERGE_SEC = 1e-9; + + var AXES = ['gx', 'gy', 'gz']; + var AXIS_NAMES = { gx: 'Gx', gy: 'Gy', gz: 'Gz' }; + var AXIS_ROW = { gx: 2, gy: 3, gz: 4 }; + var ROW_COLOURS = { 0: '--rf', 1: '--rf', 2: '--gx', 3: '--gy', 4: '--gz', 5: '--adc', 6: '--tr' }; + var KIND_RANK = { corner: 0, event: 1, block: 2 }; + var TRAP_NAMES = ['ramp-up start', 'flat-top start', 'flat-top end', 'ramp-down end']; + + /* ── Core: lookups ─────────────────────────────────────────────────── */ + + /** First block whose end (s + d) is at or after `t`. */ + function firstBlockEndingAfter(blocks, t) { + var lo = 0, hi = blocks.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (blocks[mid].s + blocks[mid].d < t) lo = mid + 1; else hi = mid; + } + return lo; + } + + /** + * Index of the block that holds `t`, or -1 outside the sequence. A time on + * a boundary belongs to the block that starts there, except that a + * zero-duration block (labels, soft delays) hands it back to the block that + * ends there, which is the one with waveforms. + */ + function blockIndexAt(blocks, t) { + if (!blocks || !blocks.length || !(t >= blocks[0].s)) return -1; + var lo = 0, hi = blocks.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (blocks[mid].s <= t) lo = mid + 1; else hi = mid; + } + var i = lo - 1; + while (i > 0 && !(blocks[i].d > 0) && blocks[i - 1].s + blocks[i - 1].d >= t) i--; + var block = blocks[i]; + return t <= block.s + block.d + 1e-12 ? i : -1; + } + + /** Linear interpolation, 0 outside the waveform (the tooltip's convention). */ + function sampleAt(times, values, t) { + var n = Math.min(times.length, values.length); + if (!n || t < times[0] || t > times[n - 1]) return 0; + var lo = 0, hi = n - 1; + while (hi - lo > 1) { + var mid = (lo + hi) >> 1; + if (times[mid] <= t) lo = mid; else hi = mid; + } + var dt = times[hi] - times[lo]; + if (!(dt > 0)) return values[hi]; + return values[lo] + (values[hi] - values[lo]) * (t - times[lo]) / dt; + } + + /** The sample nearest `t`; for wrapped phase, where interpolating is wrong. */ + function nearestAt(times, values, t) { + var n = Math.min(times.length, values.length); + if (!n) return NaN; + var lo = 0, hi = n - 1; + while (hi - lo > 1) { + var mid = (lo + hi) >> 1; + if (times[mid] <= t) lo = mid; else hi = mid; + } + return Math.abs(times[hi] - t) < Math.abs(t - times[lo]) ? values[hi] : values[lo]; + } + + function lowerIndex(times, n, t) { + var lo = 0, hi = n; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (times[mid] < t) lo = mid + 1; else hi = mid; + } + return lo; + } + + /** + * The detail block for `bi`, when the held detail covers [lo, hi]. + * + * Not blockAt(): that answers for the view being drawn, and its arrays are + * clipped to that view, so a marker scrolled off screen would read zero. + */ + function detailBlock(detail, bi, lo, hi) { + if (!detail || !detail.blocks || bi < detail.startBlock || bi >= detail.endBlock) return null; + if (detail.startSec > lo || detail.endSec < hi) return null; + return detail.blocks[bi - detail.startBlock] || null; + } + + /** Detail the renderer currently holds for this sequence, or null. */ + function liveDetail() { + if (typeof waveformDetail === 'undefined' || !waveformDetail) return null; + if (typeof waveformDetailGeneration !== 'undefined' && waveformDetail.generation !== waveformDetailGeneration) return null; + return waveformDetail; + } + + /* ── Core: corners ─────────────────────────────────────────────────── */ + + /** Coincident corners are one point; name it for what it is. */ + function mergeCoincident(corners) { + var out = []; + for (var i = 0; i < corners.length; i++) { + var c = corners[i], last = out[out.length - 1]; + if (last && Math.abs(c.t - last.t) <= MERGE_SEC) { + if (last.name === 'flat-top start' && c.name === 'flat-top end') last.name = 'peak'; + else if (last.name === 'ramp-up start' && c.name === 'flat-top start') last.name = 'flat-top start'; + else if (last.name === 'flat-top end' && c.name === 'ramp-down end') last.name = 'flat-top end'; + else if (last.name !== c.name) last.name += ' / ' + c.name; + continue; + } + out.push({ t: c.t, w: c.w, name: c.name }); + } + return out; + } + + /** + * A trapezoid's four corners. The decoder writes exactly these points, plus + * a leading zero at the block start when the gradient is delayed, and the + * overview never reduces a waveform this short, so they are exact. + */ + function trapezoidCorners(g) { + var n = Math.min(g.t.length, g.w.length), first = n === 5 ? 1 : 0; + if (n - first !== 4) return endpointCorners(g); + var corners = []; + for (var k = 0; k < 4; k++) corners.push({ t: g.t[first + k], w: g.w[first + k], name: TRAP_NAMES[k] }); + return mergeCoincident(corners); + } + + /** First and last sample: exact even after reduction, which keeps both. */ + function endpointCorners(g) { + var n = Math.min(g.t.length, g.w.length); + if (!n) return []; + return n === 1 + ? [{ t: g.t[0], w: g.w[0], name: 'start' }] + : [{ t: g.t[0], w: g.w[0], name: 'start' }, { t: g.t[n - 1], w: g.w[n - 1], name: 'end' }]; + } + + /** + * Douglas–Peucker on samples i0..i1: the indices a polyline within `eps` + * (vertically) of every sample needs. Iterative, so a long slice cannot + * overflow the stack. + */ + function simplify(t, w, i0, i1, eps) { + var keep = [i0, i1], stack = [i0, i1]; + while (stack.length) { + var b = stack.pop(), a = stack.pop(); + if (b - a < 2) continue; + var ta = t[a], wa = w[a], span = t[b] - ta, slope = span > 0 ? (w[b] - wa) / span : 0; + var worst = -1, at = -1; + for (var k = a + 1; k < b; k++) { + var deviation = Math.abs(w[k] - (wa + slope * (t[k] - ta))); + if (deviation > worst) { worst = deviation; at = k; } + } + if (worst > eps) { keep.push(at); stack.push(a, at, at, b); } + } + keep.sort(function (x, y) { return x - y; }); + return keep; + } + + /** + * Corners inside an arbitrary or extended-trapezoid waveform near [lo, hi]. + * + * Both arrive as 'arb', so breakpoints cannot be told from raster samples. + * The shape is simplified to a polyline within 0.5 % of the waveform's + * scale, and a vertex is a corner where the line goes flat↔ramp, reverses + * (a peak), steps, or changes slope by at least half. That finds every + * breakpoint of an extended trapezoid and the trapezoid-like corners of a + * raster-sampled one, while a smooth spiral keeps little more than its + * peaks. + */ + function interiorCorners(g, lo, hi, amplitude) { + var n = Math.min(g.t.length, g.w.length); + if (n < 3) return []; + var i0 = Math.max(0, lowerIndex(g.t, n, lo) - 1); + var i1 = Math.min(n - 1, lowerIndex(g.t, n, hi)); + if (i1 - i0 < 2 || i1 - i0 + 1 > MAX_CORNER_SAMPLES) return []; + var scale = Math.abs(amplitude) || 0; + for (var i = i0; i <= i1; i++) scale = Math.max(scale, Math.abs(g.w[i])); + if (!(scale > 0)) return []; + var eps = 0.005 * scale, keep = simplify(g.t, g.w, i0, i1, eps), out = []; + for (var j = 1; j < keep.length - 1; j++) { + var p = keep[j - 1], k = keep[j], q = keep[j + 1]; + var d1 = g.w[k] - g.w[p], d2 = g.w[q] - g.w[k], dt1 = g.t[k] - g.t[p], dt2 = g.t[q] - g.t[k]; + var name = null; + if (!(dt1 > 0) || !(dt2 > 0)) { + if (Math.abs(!(dt1 > 0) ? d1 : d2) > 0.02 * scale) name = 'step'; + } else { + var flat1 = Math.abs(d1) <= eps, flat2 = Math.abs(d2) <= eps; + if (flat1 && flat2) continue; + if (flat1) name = Math.abs(g.w[q]) > Math.abs(g.w[k]) ? 'ramp-up start' : 'ramp-down start'; + else if (flat2) name = Math.abs(g.w[k]) > Math.abs(g.w[p]) ? 'ramp-up end' : 'ramp-down end'; + else { + var s1 = d1 / dt1, s2 = d2 / dt2; + if (s1 * s2 < 0) name = 'peak'; + else if (Math.abs(s2 - s1) >= 0.5 * Math.max(Math.abs(s1), Math.abs(s2))) name = 'slope change'; + } + } + if (name) out.push({ t: g.t[k], w: g.w[k], name: name }); + } + return out; + } + + /** + * Corners of one gradient near [lo, hi]. Trapezoids come from the overview, + * which always has them whole. An arbitrary waveform's interior corners + * come from exact detail when it covers the window, otherwise from the + * overview unless the overview was reduced; a reduced waveform only offers + * its ends. + */ + function gradientCorners(overview, detail, lo, hi) { + if (overview.ty === 'trap') return trapezoidCorners(overview); + var corners = endpointCorners(overview); + var source = detail && detail.t && !detail.r ? detail : (!overview.r ? overview : null); + if (source) corners = corners.concat(interiorCorners(source, lo, hi, overview.a)); + corners.sort(function (a, b) { return a.t - b.t; }); + return mergeCoincident(corners); + } + + /* ── Core: snapping ────────────────────────────────────────────────── */ + + function blockLabel(blocks, bi) { + return bi > 0 ? 'block #' + blocks[bi - 1].i + '/#' + blocks[bi].i : 'block #' + blocks[bi].i + ' start'; + } + + /** + * Every snap target within `tol` seconds of `t`. + * + * opts.rows: visible channel indices; a channel whose row is hidden offers + * no corners. Block boundaries are always offered. opts.detail: the held + * waveform detail, or null. + */ + function snapCandidates(blocks, t, tol, opts) { + var out = []; + if (!blocks || !blocks.length || !(tol > 0)) return out; + opts = opts || {}; + var rows = opts.rows || [0, 1, 2, 3, 4, 5, 6], shown = {}; + for (var r = 0; r < rows.length; r++) shown[rows[r]] = true; + var lo = t - tol, hi = t + tol, count = 0; + for (var bi = firstBlockEndingAfter(blocks, lo); bi < blocks.length && blocks[bi].s <= hi; bi++) { + if (++count > MAX_SNAP_BLOCKS) return []; + var b = blocks[bi]; + out.push({ t: b.s, kind: 'block', ci: -1, value: 0, label: blockLabel(blocks, bi) }); + if (bi === blocks.length - 1) out.push({ t: b.s + b.d, kind: 'block', ci: -1, value: 0, label: 'block #' + b.i + ' end' }); + for (var a = 0; a < AXES.length; a++) { + var axis = AXES[a], g = b[axis]; + if (!shown[AXIS_ROW[axis]] || !g || g.ty === 'none' || !g.t || !g.t.length) continue; + if (g.t[g.t.length - 1] < lo || g.t[0] > hi) continue; + var detail = detailBlock(opts.detail, bi, lo, hi); + var corners = gradientCorners(g, detail && detail[axis], lo, hi); + for (var c = 0; c < corners.length; c++) { + out.push({ t: corners[c].t, kind: 'corner', ci: AXIS_ROW[axis], value: corners[c].w, label: AXIS_NAMES[axis] + ' ' + corners[c].name }); + } + } + var rf = b.rf; + if (rf && (shown[0] || shown[1])) { + var rfValue = function (time) { return rf.t && rf.m ? sampleAt(rf.t, rf.m, time) : 0; }; + out.push({ t: rf.s, kind: 'event', ci: 0, value: 0, label: 'RF start' }); + if (isFinite(rf.c)) out.push({ t: rf.c, kind: 'event', ci: 0, value: rfValue(rf.c), label: 'RF centre' }); + out.push({ t: rf.s + rf.d, kind: 'event', ci: 0, value: 0, label: 'RF end' }); + } + var adc = b.adc; + if (adc && shown[5] && adc.n > 0) { + var start = adc.s + (adc.d || 0), span = adc.n * adc.dw; + out.push({ t: start, kind: 'event', ci: 5, value: 0, label: 'ADC start' }); + out.push({ t: start + span / 2, kind: 'event', ci: 5, value: 0, label: 'ADC centre' }); + out.push({ t: start + span, kind: 'event', ci: 5, value: 0, label: 'ADC end' }); + } + if (b.trg && shown[6]) { + for (var g2 = 0; g2 < b.trg.length; g2++) { + var tg = b.trg[g2]; + out.push({ t: tg.s + (tg.d || 0), kind: 'event', ci: 6, value: 0, label: 'trigger start' }); + } + } + } + return out.filter(function (candidate) { return candidate.t >= lo && candidate.t <= hi; }); + } + + function rank(candidate, pointerCi) { + var own = candidate.kind === 'corner' && candidate.ci === pointerCi ? 0 : 1; + return own * 10 + KIND_RANK[candidate.kind]; + } + + /** + * The candidate to snap to: the nearest, except that within `onePx` seconds + * a corner on the pointer's own row beats other corners, which beat event + * edges, which beat block boundaries. Everything at the same instant is + * folded into its label, e.g. "Gx ramp-down end · block #12/#13". + */ + function chooseSnap(candidates, t, onePx, pointerCi) { + var best = null, bestDistance = Infinity; + for (var i = 0; i < candidates.length; i++) { + var c = candidates[i], distance = Math.abs(c.t - t); + if (!best || distance < bestDistance - onePx) { best = c; bestDistance = distance; continue; } + if (distance > bestDistance + onePx) continue; + var difference = rank(c, pointerCi) - rank(best, pointerCi); + if (difference < 0 || (difference === 0 && distance < bestDistance)) { best = c; bestDistance = distance; } + } + if (!best) return null; + var same = candidates.filter(function (c) { return Math.abs(c.t - best.t) <= MERGE_SEC; }); + same.sort(function (a, b) { return rank(a, pointerCi) - rank(b, pointerCi); }); + var labels = [best.label]; + for (var j = 0; j < same.length; j++) if (labels.indexOf(same[j].label) < 0) labels.push(same[j].label); + var text = labels.length > 3 ? labels.slice(0, 3).join(' · ') + ' +' + (labels.length - 3) : labels.join(' · '); + return { t: best.t, kind: best.kind, ci: best.ci, value: best.value, label: best.label, labels: labels, text: text }; + } + + function snapAt(blocks, t, tol, opts) { + opts = opts || {}; + return chooseSnap(snapCandidates(blocks, t, tol, opts), t, opts.onePx || tol / SNAP_PX, opts.pointerCi); + } + + /* ── Core: readout ─────────────────────────────────────────────────── */ + + /** + * Every channel's value at `t`. Gradients are in Hz/m; `approx` names the + * channels read from a reduced overview, where the samples either side of + * `t` may not be adjacent. + */ + function readoutAt(blocks, t, detail) { + var out = { t: t, index: -1, block: -1, offset: NaN, gx: 0, gy: 0, gz: 0, approx: {}, rf: null, adc: null, trigger: false }; + var bi = blockIndexAt(blocks, t); + if (bi < 0) return out; + var b = blocks[bi], d = detailBlock(detail, bi, t, t); + out.index = bi; out.block = b.i; out.offset = t - b.s; + for (var a = 0; a < AXES.length; a++) { + var axis = AXES[a], g = b[axis]; + if (!g || g.ty === 'none' || !g.t || !g.w) continue; + var exact = d && d[axis] && g.ty !== 'trap' ? d[axis] : null; + var source = exact && exact.t && exact.t.length && exact.t[0] <= t && exact.t[exact.t.length - 1] >= t ? exact : g; + out[axis] = sampleAt(source.t, source.w, t); + if (source.r && t >= g.t[0] && t <= g.t[g.t.length - 1]) out.approx[axis] = true; + } + var rf = b.rf; + if (rf && t >= rf.s && t <= rf.s + rf.d && rf.t && rf.m) { + var rfSource = d && d.rf && d.rf.t && d.rf.t.length && d.rf.t[0] <= t && d.rf.t[d.rf.t.length - 1] >= t ? d.rf : rf; + out.rf = { + amplitude: sampleAt(rfSource.t, rfSource.m, t), + phase: rfSource.pt && rfSource.p ? nearestAt(rfSource.pt, rfSource.p, t) : NaN, + approx: !!rfSource.r + }; + } + var adc = b.adc; + if (adc && adc.n > 0) { + var start = adc.s + (adc.d || 0), end = start + adc.n * adc.dw; + if (t >= start && t <= end) { + // The tolerance keeps a time exactly on a sample edge (as snapping + // places it) from rounding down into the previous sample. + var sample = Math.floor((t - start) / adc.dw + 1e-6); + out.adc = { sample: Math.max(0, Math.min(adc.n - 1, sample)), count: adc.n }; + } + } + if (b.trg) { + for (var i = 0; i < b.trg.length; i++) { + var tg = b.trg[i], from = tg.s + (tg.d || 0); + if (t >= from && t <= from + (tg.dr || 0)) out.trigger = true; + } + } + return out; + } + + /* ── Core: formatting ──────────────────────────────────────────────── */ + + /* Digits that resolve 0.1 µs, the finest raster Pulseq uses (ADC dwell). */ + var TIME_DIGITS = { s: 7, ms: 4, us: 1 }; + var GRAD_DIGITS = { 'Hz/m': 0, 'mT/m': 2, 'G/cm': 3 }; + + function unitName(unit) { return unit === 'us' ? 'µs' : unit; } + + function formatTime(seconds, units) { + var digits = TIME_DIGITS[units.timeUnit]; + return units.timeConv(seconds).toFixed(digits === undefined ? 4 : digits); + } + + function formatGradient(hzPerM, units) { + var digits = GRAD_DIGITS[units.gradUnit]; + var text = units.gradConv(hzPerM).toFixed(digits === undefined ? 2 : digits); + return /^-0(\.0*)?$/.test(text) ? text.slice(1) : text; + } + + /** + * One row per marker, in time order, with everything formatted in the + * viewer's current units. `list` is [{id, t, snap}]. + */ + function tableRows(list, blocks, detail, units) { + var rows = []; + for (var i = 0; i < list.length; i++) { + var m = list[i], r = readoutAt(blocks, m.t, detail), previous = i > 0 ? list[i - 1] : null; + rows.push({ + id: m.id, + name: 'M' + m.id, + time: formatTime(m.t, units), + delta: previous ? formatTime(m.t - previous.t, units) : '', + block: r.block >= 0 ? '#' + r.block : '', + offset: r.block >= 0 ? formatTime(r.offset, units) : '', + gx: (r.approx.gx ? '≈' : '') + formatGradient(r.gx, units), + gy: (r.approx.gy ? '≈' : '') + formatGradient(r.gy, units), + gz: (r.approx.gz ? '≈' : '') + formatGradient(r.gz, units), + rf: r.rf ? (r.rf.approx ? '≈' : '') + r.rf.amplitude.toFixed(1) : '', + phase: r.rf && isFinite(r.rf.phase) ? (r.rf.phase * 180 / Math.PI).toFixed(1) : '', + adc: r.adc ? (r.adc.sample + 1) + '/' + r.adc.count : '', + trigger: r.trigger ? 'on' : '', + snap: m.snap || '', + approx: !!(r.approx.gx || r.approx.gy || r.approx.gz || (r.rf && r.rf.approx)) + }); + } + return rows; + } + + function columns(units) { + var t = unitName(units.timeUnit), g = units.gradUnit; + return [ + ['name', 'Marker'], ['time', 'Time (' + t + ')'], ['delta', 'Δt (' + t + ')'], + ['block', 'Block'], ['offset', 'In block (' + t + ')'], + ['gx', 'Gx (' + g + ')'], ['gy', 'Gy (' + g + ')'], ['gz', 'Gz (' + g + ')'], + ['rf', 'RF (Hz)'], ['phase', 'RF phase (°)'], ['adc', 'ADC sample'], ['trigger', 'Trigger'], + ['snap', 'Snapped to'] + ]; + } + + /** Tab-separated, with a header, for pasting into a spreadsheet. */ + function toTsv(rows, units) { + var cols = columns(units), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; + for (var i = 0; i < rows.length; i++) { + lines.push(cols.map(function (c) { return String(rows[i][c[0]]).replace(/[\t\n]/g, ' '); }).join('\t')); + } + return lines.join('\n'); + } + + /* ── Marker list ───────────────────────────────────────────────────── */ + + var markers = []; + var version = 0; + + function sortMarkers() { markers.sort(function (a, b) { return a.t - b.t || a.id - b.id; }); } + + /** Ids keep growing while markers exist, so "M2" keeps meaning one marker. */ + function addMarker(t, snap) { + var id = 1; + for (var i = 0; i < markers.length; i++) id = Math.max(id, markers[i].id + 1); + var marker = { id: id, t: t, snap: snap || '' }; + markers.push(marker); sortMarkers(); version++; + return marker; + } + + function findMarker(id) { + for (var i = 0; i < markers.length; i++) if (markers[i].id === id) return markers[i]; + return null; + } + + function moveMarker(id, t, snap) { + var marker = findMarker(id); + if (!marker) return null; + marker.t = t; marker.snap = snap || ''; sortMarkers(); version++; + return marker; + } + + function removeMarker(id) { + var before = markers.length; + markers = markers.filter(function (m) { return m.id !== id; }); + if (markers.length !== before) version++; + } + + function clearMarkers() { + if (markers.length) version++; + markers = []; + } + + function listMarkers() { return markers.map(function (m) { return { id: m.id, t: m.t, snap: m.snap }; }); } + + /* ══ UI (only install() reaches here) ══════════════════════════════════ */ + + var ctx = null; + var wired = false; + var snapEnabled = true; + var tableOpen = true; + /** Pointer over the plot, in canvas CSS pixels; null when elsewhere. */ + var hover = null; + var hoverMarkerId = 0; + /** {id, from, fromSnap, snap} while a marker is being dragged. */ + var drag = null; + var menu = null; + /** {x, y, snap} the open menu was opened for. */ + var menuTarget = null; + var tableEl = null; + var tableKey = ''; + var snapCache = null; + + function el(id) { return document.getElementById(id); } + function prefs() { return typeof SeqEyesPrefs !== 'undefined' ? SeqEyesPrefs : null; } + + function units() { + return { timeConv: ctx.timeConv, timeUnit: ctx.timeUnitStr(), gradConv: ctx.gradConv, gradUnit: ctx.gradUnitStr() }; + } + + function canvasPoint(event) { + var mc = el('mc'), rect = mc.getBoundingClientRect(); + return { x: event.clientX - rect.left, y: event.clientY - rect.top, width: rect.width, height: rect.height }; + } + + function insidePlot(p) { + var M = ctx.margins(); + return p.x >= M.l && p.x <= p.width - M.r && p.y >= M.t && p.y <= p.height - M.b; + } + + function rowAt(y) { + var M = ctx.margins(), rows = ctx.visChannels(), vi = Math.floor((y - M.t) / ctx.cH()); + return vi >= 0 && vi < rows.length ? rows[vi] : -1; + } + + function markerNear(x, px) { + var best = null, bestDistance = px + 1e-9; + for (var i = 0; i < markers.length; i++) { + var distance = Math.abs(ctx.t2x(markers[i].t) - x); + if (distance <= bestDistance) { best = markers[i]; bestDistance = distance; } + } + return best; + } + + function clampTime(t) { + var total = ctx.duration(); + return Math.max(0, total > 0 ? Math.min(total, t) : t); + } + + /** + * Snap target under the pointer, or null. Cached: in the web app the + * overlay is drawn twice a frame (once by the bundle, once by the page). + */ + function snapFor(x, y) { + if (!ctx || !snapEnabled) return null; + var blocks = ctx.blocks(); + if (!blocks || !blocks.length) return null; + var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + SNAP_PX) - t), rows = ctx.visChannels(); + var pointerCi = y === null || y === undefined ? -1 : rowAt(y), detail = liveDetail(), rowKey = rows.join(','); + var c = snapCache; + if (c && c.blocks === blocks && c.detail === detail && c.t === t && c.tol === tol && c.ci === pointerCi && c.rows === rowKey) { + return c.result; + } + var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / SNAP_PX }); + snapCache = { blocks: blocks, detail: detail, t: t, tol: tol, ci: pointerCi, rows: rowKey, result: result }; + return result; + } + + /** The suggestion shows once markers are in use, not while just browsing. */ + function currentSuggestion() { + if (menuTarget) return menuTarget.snap; + if (drag) return drag.snap; + if (hover && markers.length) return snapFor(hover.x, hover.y); + return null; + } + + function redraw() { + if (ctx && typeof ctx.requestOverlay === 'function') ctx.requestOverlay(); + } + + /* ── Drawing on the overlay canvas ─────────────────────────────────── */ + + function valueToY(ci, vi, value) { + var M = ctx.margins(), ch = ctx.cH(), y = ctx.cy(vi); + if (ci === 0 || ci === 1) return y + ch * 0.45 - value * (ch * 0.9 / ctx.channelRange(ci)); + if (ci >= 2 && ci <= 4) return y - value * (ch * 0.4 / ctx.channelRange(ci)); + if (ci === 7) return M.t + (vi + 1) * ch - ch * 0.08 - value * (ch * 0.84 / ctx.channelRange(7)); + if (ci >= 8 && ci <= 10) return y - value * (ch * 0.4 / ctx.channelRange(ci)); + return y; + } + + function clampToRow(vi, y) { + var M = ctx.margins(), ch = ctx.cH(), top = M.t + vi * ch; + return Math.max(top + 2, Math.min(top + ch - 2, y)); + } + + function colour(style, name, fallback) { + var value = style.getPropertyValue(name).trim(); + return value || fallback; + } + + function pill(g, text, x, y, left, right, fg, bg) { + var width = g.measureText(text).width + 8, cx = Math.max(left + width / 2, Math.min(right - width / 2, x)); + g.fillStyle = fg; g.fillRect(cx - width / 2, y - 7, width, 13); + g.fillStyle = bg; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(text, cx, y); + return { left: cx - width / 2, right: cx + width / 2 }; + } + + function drawSuggestion(g, w, h, s, style, fg) { + var M = ctx.margins(), x = ctx.t2x(s.t); + if (x < M.l || x > w - M.r) return; + g.save(); + g.globalAlpha = 0.75; g.strokeStyle = fg; g.lineWidth = 1; g.setLineDash([2, 3]); + g.beginPath(); g.moveTo(x, M.t); g.lineTo(x, h - M.b); g.stroke(); g.setLineDash([]); + g.globalAlpha = 1; + var rows = ctx.visChannels(), vi = rows.indexOf(s.ci), y = M.t + 12; + if (vi >= 0) { + y = clampToRow(vi, valueToY(s.ci, vi, s.value)); + g.lineWidth = 1.5; g.strokeStyle = colour(style, ROW_COLOURS[s.ci] || '--fg', fg); + g.beginPath(); g.arc(x, y, 5, 0, Math.PI * 2); g.stroke(); + } + g.font = '10px monospace'; + var text = s.text, width = g.measureText(text).width, right = x + 8 + width <= w - M.r; + g.fillStyle = colour(style, '--bg', '#fff'); g.globalAlpha = 0.85; + g.fillRect(right ? x + 7 : x - 9 - width, y - 16, width + 2, 12); + g.globalAlpha = 1; g.fillStyle = fg; g.textAlign = right ? 'left' : 'right'; g.textBaseline = 'middle'; + g.fillText(text, right ? x + 8 : x - 8, y - 10); + g.restore(); + } + + /** + * Called by both renderers' drawCursorOverlay, after the overlay is cleared: + * marker lines with a dot where each crosses RF and the gradients, Δt + * between neighbours, and the snap suggestion. + */ + function drawOverlay(g, w, h) { + if (!ctx || !g) return; + syncTable(); + var suggestion = currentSuggestion(); + if (!markers.length && !suggestion) return; + var style = getComputedStyle(document.body), fg = colour(style, '--fg', '#222'), bg = colour(style, '--bg', '#fff'); + var M = ctx.margins(), left = M.l, right = w - M.r, top = M.t, bottom = h - M.b; + var rows = ctx.visChannels(), detail = liveDetail(), blocks = ctx.blocks(), u = units(); + g.save(); + g.beginPath(); g.rect(left, top, Math.max(0, right - left), Math.max(0, bottom - top)); g.clip(); + g.font = '10px monospace'; + + // Δt between neighbours, just above the marker names. + var bracketY = bottom - 22; + for (var i = 1; i < markers.length; i++) { + var xa = ctx.t2x(markers[i - 1].t), xb = ctx.t2x(markers[i].t); + if (xb < left || xa > right || xb - xa < 2) continue; + var a = Math.max(left, xa), b = Math.min(right, xb); + g.strokeStyle = fg; g.lineWidth = 1; g.globalAlpha = 0.8; + g.beginPath(); g.moveTo(a, bracketY); g.lineTo(b, bracketY); + if (xa >= left) { g.moveTo(xa, bracketY - 4); g.lineTo(xa, bracketY + 4); } + if (xb <= right) { g.moveTo(xb, bracketY - 4); g.lineTo(xb, bracketY + 4); } + g.stroke(); g.globalAlpha = 1; + var label = 'Δ ' + formatTime(markers[i].t - markers[i - 1].t, u) + ' ' + unitName(u.timeUnit); + var width = g.measureText(label).width; + if (b - a > width + 10) { + g.fillStyle = bg; g.fillRect((a + b) / 2 - width / 2 - 3, bracketY - 15, width + 6, 12); + g.fillStyle = fg; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(label, (a + b) / 2, bracketY - 9); + } + } + + for (var k = 0; k < markers.length; k++) { + var m = markers[k], x = ctx.t2x(m.t); + if (x < left - 1 || x > right + 1) continue; + var active = m.id === hoverMarkerId || (drag && drag.id === m.id); + g.strokeStyle = fg; g.lineWidth = active ? 2 : 1.2; g.setLineDash([]); + g.beginPath(); g.moveTo(x, top); g.lineTo(x, bottom); g.stroke(); + + var reading = readoutAt(blocks, m.t, detail); + var next = k + 1 < markers.length ? ctx.t2x(markers[k + 1].t) : right; + for (var vi = 0; vi < rows.length; vi++) { + var ci = rows[vi], value = null; + if (ci === 0) value = reading.rf ? reading.rf.amplitude : null; + else if (ci >= 2 && ci <= 4) value = reading[AXES[ci - 2]]; + if (value === null) continue; + var y = clampToRow(vi, valueToY(ci, vi, value)); + g.fillStyle = colour(style, ROW_COLOURS[ci], fg); g.strokeStyle = bg; g.lineWidth = 1; + g.beginPath(); g.arc(x, y, 3, 0, Math.PI * 2); g.fill(); g.stroke(); + if (ci >= 2 && next - x > 70) { + var text = (reading.approx[AXES[ci - 2]] ? '≈' : '') + formatGradient(value, u); + g.fillStyle = fg; g.textAlign = 'left'; g.textBaseline = 'bottom'; g.fillText(text, x + 5, y - 2); + } + } + var nameRoom = Math.min(next, right) - x; + var name = 'M' + m.id, full = name + ' ' + formatTime(m.t, u) + ' ' + unitName(u.timeUnit); + pill(g, nameRoom > g.measureText(full).width + 24 ? full : name, x, bottom - 8, left, right, fg, bg); + } + if (suggestion) drawSuggestion(g, w, h, suggestion, style, fg); + g.restore(); + } + + /* ── Table strip ───────────────────────────────────────────────────── */ + + function element(tag, className, text) { + var node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + } + + function button(text, title, onClick) { + var b = element('button', null, text); + b.type = 'button'; if (title) b.title = title; + b.addEventListener('click', onClick); + return b; + } + + function buildTable() { + var cc = el('cc'); + if (!cc || !cc.parentNode) return; + tableEl = element('div', 'mk-table'); tableEl.id = 'mkTable'; tableEl.hidden = true; + tableEl.setAttribute('role', 'region'); tableEl.setAttribute('aria-label', 'Measurement markers'); + cc.parentNode.insertBefore(tableEl, cc.nextSibling); + } + + /** Re-render when the markers, units or underlying samples changed. */ + function syncTable() { + if (!tableEl || !ctx) return; + var u = units(), detail = liveDetail(), blocks = ctx.blocks(); + var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0].join('|'); + if (key === tableKey && tableEl.__blocks === blocks && tableEl.__detail === detail) return; + tableKey = key; tableEl.__blocks = blocks; tableEl.__detail = detail; + renderTable(u, detail, blocks); + } + + function renderTable(u, detail, blocks) { + var wasHidden = tableEl.hidden; + tableEl.textContent = ''; + tableEl.hidden = !markers.length; + if (!markers.length) { if (!wasHidden) relayout(); return; } + var rows = tableRows(markers, blocks, detail, u); + var head = element('div', 'mk-head'); + head.appendChild(element('span', 'mk-title', 'Markers')); + var span = markers.length > 1 ? ' · span ' + formatTime(markers[markers.length - 1].t - markers[0].t, u) + ' ' + unitName(u.timeUnit) : ''; + head.appendChild(element('span', 'mk-summary', markers.length + (markers.length === 1 ? ' marker' : ' markers') + span)); + if (rows.some(function (r) { return r.approx; })) { + head.appendChild(element('span', 'mk-note', '≈ from reduced samples; zoom in for exact values')); + } + var actions = element('span', 'mk-actions'); + actions.appendChild(button(tableOpen ? 'Hide' : 'Show', tableOpen ? 'Collapse the marker table' : 'Expand the marker table', function () { setTableOpen(!tableOpen); })); + actions.appendChild(button('Copy', 'Copy the table as tab-separated text', function () { copyTable(this); })); + actions.appendChild(button('Clear', 'Remove every marker', function () { clearMarkers(); afterChange(); })); + head.appendChild(actions); + tableEl.appendChild(head); + if (tableOpen) { + var scroll = element('div', 'mk-scroll'), table = element('table'), thead = element('thead'), tr = element('tr'); + var cols = columns(u); + cols.forEach(function (c) { tr.appendChild(element('th', null, c[1])); }); + tr.appendChild(element('th')); + thead.appendChild(tr); table.appendChild(thead); + var body = element('tbody'); + rows.forEach(function (row) { + var line = element('tr'); + line.setAttribute('data-marker', String(row.id)); + cols.forEach(function (c) { line.appendChild(element('td', c[0] === 'name' ? 'mk-name' : null, row[c[0]])); }); + var cell = element('td'); + cell.appendChild(button('×', 'Remove ' + row.name, function () { removeMarker(row.id); afterChange(); })); + line.appendChild(cell); + body.appendChild(line); + }); + table.appendChild(body); scroll.appendChild(table); tableEl.appendChild(scroll); + } + relayout(); + } + + /* The strip takes height from the plot; the hosts' ResizeObserver on #cc + redraws, but only once the size actually settles, so ask explicitly. */ + function relayout() { + if (typeof requestAnimationFrame === 'function') requestAnimationFrame(redraw); + } + + function setTableOpen(open) { + tableOpen = !!open; + var p = prefs(); if (p && p.KEYS.markerTable) p.setBool(p.KEYS.markerTable, tableOpen); + tableKey = ''; + syncTable(); + } + + function copyTable(source) { + var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()); + var done = function () { if (source) { var old = source.textContent; source.textContent = 'Copied'; setTimeout(function () { source.textContent = old; }, 1200); } }; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); }); + } else { fallbackCopy(text); done(); } + } + + function fallbackCopy(text) { + var area = element('textarea'); area.value = text; + area.style.position = 'fixed'; area.style.opacity = '0'; + document.body.appendChild(area); area.select(); + try { document.execCommand('copy'); } catch (e) { /* nothing more to try */ } + document.body.removeChild(area); + } + + function afterChange() { + snapCache = null; + syncTable(); + redraw(); + } + + /* ── Context menu ──────────────────────────────────────────────────── */ + + function isCompactLayout() { + return !!(window.matchMedia && window.matchMedia('(max-width: 768px), (pointer: coarse)').matches); + } + + function menuItem(label, detail, onSelect) { + var item = element('button', 'mk-item'); + item.type = 'button'; item.setAttribute('role', 'menuitem'); + item.appendChild(element('span', 'mk-item-label', label)); + if (detail) item.appendChild(element('span', 'mk-item-detail', detail)); + item.addEventListener('click', function () { closeMenu(); onSelect(); }); + return item; + } + + function menuToggle(label, checked, onChange) { + var row = element('label', 'mk-item mk-check'); + var box = element('input'); box.type = 'checkbox'; box.checked = checked; + box.setAttribute('role', 'menuitemcheckbox'); + box.addEventListener('change', function () { onChange(box.checked); }); + row.appendChild(box); row.appendChild(element('span', 'mk-item-label', label)); + return row; + } + + function openMenu(event, p) { + closeMenu(); + var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y), near = markerNear(p.x, REMOVE_PX); + var time = function (seconds) { return formatTime(seconds, u) + ' ' + unitName(u.timeUnit); }; + menuTarget = { x: p.x, y: p.y, snap: snap }; + menu = element('div', 'lblc mk-menu'); menu.id = 'markerMenu'; + menu.setAttribute('role', 'menu'); menu.setAttribute('aria-label', 'Measurement markers'); + if (snap) menu.appendChild(menuItem('Add marker at ' + snap.text, time(snap.t), function () { place(snap.t, snap.text); })); + menu.appendChild(menuItem(snap ? 'Add marker at pointer (no snap)' : 'Add marker here', time(t), function () { place(t, ''); })); + if (near) menu.appendChild(menuItem('Remove M' + near.id, time(near.t), function () { removeMarker(near.id); afterChange(); })); + if (markers.length) menu.appendChild(menuItem('Clear all markers', String(markers.length), function () { clearMarkers(); afterChange(); })); + menu.appendChild(element('div', 'mk-sep')); + menu.appendChild(menuToggle('Snap to corners and block edges', snapEnabled, function (on) { + snapEnabled = on; + var pr = prefs(); if (pr && pr.KEYS.markerSnap) pr.setBool(pr.KEYS.markerSnap, on); + menuTarget.snap = on ? snapFor(p.x, p.y) : null; + snapCache = null; redraw(); + })); + if (markers.length) menu.appendChild(menuToggle('Show the marker table', tableOpen, function (on) { setTableOpen(on); })); + document.body.appendChild(menu); + positionMenu(event.clientX, event.clientY); + el('cc').classList.add('mk-menu-open'); + document.addEventListener('pointerdown', onOutsidePointer, true); + window.addEventListener('resize', closeMenu); + var first = menu.querySelector('.mk-item'); + if (first && first.focus) first.focus(); + redraw(); + } + + function positionMenu(clientX, clientY) { + var compact = isCompactLayout(); + menu.classList.toggle('sheet', compact); + if (compact) { menu.style.left = ''; menu.style.top = ''; return; } + var width = menu.offsetWidth, height = menu.offsetHeight, vw = window.innerWidth, vh = window.innerHeight; + menu.style.left = Math.max(8, Math.min(clientX + 2, vw - width - 8)) + 'px'; + menu.style.top = Math.max(8, clientY + 2 + height > vh - 8 ? clientY - height - 2 : clientY + 2) + 'px'; + } + + function closeMenu() { + if (!menu) return; + document.removeEventListener('pointerdown', onOutsidePointer, true); + window.removeEventListener('resize', closeMenu); + if (menu.parentNode) menu.parentNode.removeChild(menu); + menu = null; menuTarget = null; + var cc = el('cc'); if (cc) cc.classList.remove('mk-menu-open'); + redraw(); + } + + function onOutsidePointer(event) { + if (menu && !menu.contains(event.target)) closeMenu(); + } + + function moveMenuFocus(step) { + var items = Array.prototype.slice.call(menu.querySelectorAll('.mk-item')); + var at = items.indexOf(document.activeElement && document.activeElement.closest ? document.activeElement.closest('.mk-item') : null); + var next = items[(at + step + items.length) % items.length]; + if (next) (next.querySelector('input') || next).focus(); + } + + function place(t, snap) { + addMarker(clampTime(t), snap); + afterChange(); + } + + /* ── Pointer handling ──────────────────────────────────────────────── */ + + function onContextMenu(event) { + if (!ctx || event.target !== el('mc')) return; + // Keeps the browser's menu, and VS Code's webview menu, off the plot. + event.preventDefault(); + var p = canvasPoint(event); + if (insidePlot(p)) openMenu(event, p); + } + + /* Capture phase on #cc runs before both renderers' mousedown on #mc, so + grabbing a marker never starts a pan. Anything else passes through. */ + function onMouseDown(event) { + if (!ctx || event.button !== 0 || event.ctrlKey || event.target !== el('mc') || !markers.length) return; + var p = canvasPoint(event), marker = insidePlot(p) ? markerNear(p.x, HIT_PX) : null; + if (!marker) return; + event.stopPropagation(); event.preventDefault(); + drag = { id: marker.id, from: marker.t, fromSnap: marker.snap, snap: null }; + el('cc').classList.add('mk-drag'); + redraw(); + } + + function onWindowMove(event) { + if (!drag || !ctx) return; + var p = canvasPoint(event), bypass = event.shiftKey || event.altKey; + var snap = bypass ? null : snapFor(p.x, p.y); + drag.snap = snap; + moveMarker(drag.id, clampTime(snap ? snap.t : ctx.x2t(p.x)), snap ? snap.text : ''); + afterChange(); + } + + function onWindowUp() { + if (!drag) return; + drag = null; + var cc = el('cc'); if (cc) cc.classList.remove('mk-drag'); + afterChange(); + } + + function onHoverMove(event) { + if (!ctx || drag) return; + var p = canvasPoint(event), inside = insidePlot(p); + hover = inside ? { x: p.x, y: p.y } : null; + var near = inside && markers.length ? markerNear(p.x, HIT_PX) : null, id = near ? near.id : 0; + if (id !== hoverMarkerId) { hoverMarkerId = id; redraw(); } + el('cc').classList.toggle('mk-hover', !!near); + } + + function onHoverLeave() { + if (drag) return; + hover = null; hoverMarkerId = 0; + var cc = el('cc'); if (cc) cc.classList.remove('mk-hover'); + redraw(); + } + + function onKeyDown(event) { + if (event.key === 'Escape' && (menu || drag)) { + event.preventDefault(); event.stopPropagation(); + if (menu) { closeMenu(); return; } + moveMarker(drag.id, drag.from, drag.fromSnap); + onWindowUp(); + return; + } + if (menu && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + event.preventDefault(); moveMenuFocus(event.key === 'ArrowDown' ? 1 : -1); + } + } + + function wire() { + var cc = el('cc'); + if (!cc || !el('mc')) return; + wired = true; + cc.addEventListener('mousedown', onMouseDown, true); + cc.addEventListener('contextmenu', onContextMenu); + cc.addEventListener('mousemove', onHoverMove); + cc.addEventListener('mouseleave', onHoverLeave); + window.addEventListener('mousemove', onWindowMove); + window.addEventListener('mouseup', onWindowUp); + window.addEventListener('blur', onWindowUp); + document.addEventListener('keydown', onKeyDown, true); + buildTable(); + var p = prefs(); + if (p && p.KEYS.markerSnap) snapEnabled = p.getBool(p.KEYS.markerSnap, true); + if (p && p.KEYS.markerTable) tableOpen = p.getBool(p.KEYS.markerTable, true); + if (typeof window !== 'undefined') { + var dev = window.SeqEyesDev = window.SeqEyesDev || {}; + dev.markers = function () { + var detail = liveDetail(), blocks = ctx ? ctx.blocks() : []; + return markers.map(function (m) { return { id: m.id, t: m.t, snap: m.snap, readout: readoutAt(blocks, m.t, detail) }; }); + }; + dev.addMarker = function (t, snap) { var m = addMarker(clampTime(t), snap); afterChange(); return m.id; }; + dev.snapAt = function (t) { return ctx ? snapFor(ctx.t2x(t), null) : null; }; + dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()) : ''; }; + dev.markerState = function () { + return { suggestion: currentSuggestion(), menuOpen: !!menu, dragging: !!drag, snapEnabled: snapEnabled, tableOpen: tableOpen }; + }; + } + } + + /** + * Hand the module a renderer's state. ctx: blocks(), duration(), margins(), + * t2x, x2t, visChannels, cH, cy, channelRange, timeConv, timeUnitStr, + * gradConv, gradUnitStr, requestOverlay. A later install replaces an + * earlier one; the DOM is wired once. + */ + function install(context) { + ctx = context; + snapCache = null; tableKey = ''; + if (!wired && typeof document !== 'undefined') wire(); + syncTable(); + } + + /** A new sequence: its markers would point at nothing. */ + function reset() { + clearMarkers(); + drag = null; hover = null; hoverMarkerId = 0; snapCache = null; + closeMenu(); + var cc = typeof document !== 'undefined' ? el('cc') : null; + if (cc) cc.classList.remove('mk-drag', 'mk-hover'); + syncTable(); + } + + return { + install: install, + reset: reset, + drawOverlay: drawOverlay, + // List operations, also used by tests and dev hooks. + add: function (t, snap) { var m = addMarker(t, snap); if (ctx) afterChange(); return m; }, + remove: function (id) { removeMarker(id); if (ctx) afterChange(); }, + clear: function () { clearMarkers(); if (ctx) afterChange(); }, + move: moveMarker, + list: listMarkers, + // Pure core, exported for the unit tests. + core: { + blockIndexAt: blockIndexAt, + sampleAt: sampleAt, + trapezoidCorners: trapezoidCorners, + gradientCorners: gradientCorners, + interiorCorners: interiorCorners, + snapCandidates: snapCandidates, + chooseSnap: chooseSnap, + snapAt: snapAt, + readoutAt: readoutAt, + tableRows: tableRows, + toTsv: toTsv, + formatTime: formatTime, + formatGradient: formatGradient + } + }; +})(); + + /* ══ interaction.js ══ */ /* ═══════════════════════════════════════════════════════════════════════ Mouse interaction @@ -10491,6 +11543,14 @@ rs(); this one — install() swaps the host without re-binding the DOM. */ SeqEyesPanel.install(window.SeqEyesPanelHost); SeqEyesPrefsUi.install(); +/* Measurement markers read this renderer's state through these accessors. + web/index.html installs its own over them, as it does the panel host. */ +SeqEyesMarkers.install({ + blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, + t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, + timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, + requestOverlay:drawCursorOverlay +}); /* Deferred by one macrotask so web/index.html, whose inline IIFE runs after this bundle, has installed its own adapter before the persisted mode is restored against it. */ diff --git a/scripts/build-webview.mjs b/scripts/build-webview.mjs index 6797793..0d9dc94 100644 --- a/scripts/build-webview.mjs +++ b/scripts/build-webview.mjs @@ -45,6 +45,8 @@ const files = [ 'ndview.js', 'simulation-panel.js', 'prefs-ui.js', + // Before interaction.js, which installs it with the bundle's renderer. + 'markers.js', 'interaction.js', ]; diff --git a/src/editor/webview/assets/drawing.js b/src/editor/webview/assets/drawing.js index 887d536..3e02f0f 100644 --- a/src/editor/webview/assets/drawing.js +++ b/src/editor/webview/assets/drawing.js @@ -26,6 +26,7 @@ function drawCursorOverlay(){ var dpr=window.devicePixelRatio||1,w=moc.width/dpr,h=moc.height/dpr; moctx.clearRect(0,0,w,h); drawPanelMarker(w,h); + if(typeof SeqEyesMarkers!=='undefined')SeqEyesMarkers.drawOverlay(moctx,w,h); if(!cursorActive)return;var cx=t2x(cursorT); if(cxw-M.r)return; var color=getComputedStyle(document.body).getPropertyValue('--cr').trim(); diff --git a/src/editor/webview/assets/interaction.js b/src/editor/webview/assets/interaction.js index 7c19cae..dfcee57 100644 --- a/src/editor/webview/assets/interaction.js +++ b/src/editor/webview/assets/interaction.js @@ -398,6 +398,14 @@ rs(); this one — install() swaps the host without re-binding the DOM. */ SeqEyesPanel.install(window.SeqEyesPanelHost); SeqEyesPrefsUi.install(); +/* Measurement markers read this renderer's state through these accessors. + web/index.html installs its own over them, as it does the panel host. */ +SeqEyesMarkers.install({ + blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, + t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, + timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, + requestOverlay:drawCursorOverlay +}); /* Deferred by one macrotask so web/index.html, whose inline IIFE runs after this bundle, has installed its own adapter before the persisted mode is restored against it. */ diff --git a/src/editor/webview/assets/markers.js b/src/editor/webview/assets/markers.js new file mode 100644 index 0000000..a653496 --- /dev/null +++ b/src/editor/webview/assets/markers.js @@ -0,0 +1,1045 @@ +/* ═══════════════════════════════════════════════════════════════════════ + Measurement markers + ═══════════════════════════════════════════════════════════════════════ + + Right-click the waveform viewer to drop a vertical marker. Each marker + reads out its time, its block and every channel's value where it crosses, + and Δt to its neighbour. Placement snaps to gradient corners, RF and ADC + edges and centres, and block boundaries. + + Two renderers draw this viewer: the bundle (VS Code) and web/index.html's + own copy inside its IIFE (web app, preview, MATLAB). Both install this + module with accessors to their own state. The last install wins and the + DOM is wired once, which is the pattern prefs-ui.js and panel.js use. + + The core takes everything it reads as arguments, so it runs in node:vm for + the unit tests; only install() touches the DOM. */ + +var SeqEyesMarkers = (function () { + /* Pointer distances in CSS pixels: how close a corner must be to pull a + marker onto it, how close a press must be to grab a marker, and how close + a right-click must be to offer removing one. */ + var SNAP_PX = 8; + var HIT_PX = 4; + var REMOVE_PX = 6; + /* More blocks than this inside the snap distance means the view is too + zoomed out for a corner to be a meaningful target. */ + var MAX_SNAP_BLOCKS = 32; + /* Interior corners of an arbitrary waveform are only searched in a slice + this small, so a hover never walks a whole readout. */ + var MAX_CORNER_SAMPLES = 512; + /* Candidates closer than this are one point with several names. */ + var MERGE_SEC = 1e-9; + + var AXES = ['gx', 'gy', 'gz']; + var AXIS_NAMES = { gx: 'Gx', gy: 'Gy', gz: 'Gz' }; + var AXIS_ROW = { gx: 2, gy: 3, gz: 4 }; + var ROW_COLOURS = { 0: '--rf', 1: '--rf', 2: '--gx', 3: '--gy', 4: '--gz', 5: '--adc', 6: '--tr' }; + var KIND_RANK = { corner: 0, event: 1, block: 2 }; + var TRAP_NAMES = ['ramp-up start', 'flat-top start', 'flat-top end', 'ramp-down end']; + + /* ── Core: lookups ─────────────────────────────────────────────────── */ + + /** First block whose end (s + d) is at or after `t`. */ + function firstBlockEndingAfter(blocks, t) { + var lo = 0, hi = blocks.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (blocks[mid].s + blocks[mid].d < t) lo = mid + 1; else hi = mid; + } + return lo; + } + + /** + * Index of the block that holds `t`, or -1 outside the sequence. A time on + * a boundary belongs to the block that starts there, except that a + * zero-duration block (labels, soft delays) hands it back to the block that + * ends there, which is the one with waveforms. + */ + function blockIndexAt(blocks, t) { + if (!blocks || !blocks.length || !(t >= blocks[0].s)) return -1; + var lo = 0, hi = blocks.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (blocks[mid].s <= t) lo = mid + 1; else hi = mid; + } + var i = lo - 1; + while (i > 0 && !(blocks[i].d > 0) && blocks[i - 1].s + blocks[i - 1].d >= t) i--; + var block = blocks[i]; + return t <= block.s + block.d + 1e-12 ? i : -1; + } + + /** Linear interpolation, 0 outside the waveform (the tooltip's convention). */ + function sampleAt(times, values, t) { + var n = Math.min(times.length, values.length); + if (!n || t < times[0] || t > times[n - 1]) return 0; + var lo = 0, hi = n - 1; + while (hi - lo > 1) { + var mid = (lo + hi) >> 1; + if (times[mid] <= t) lo = mid; else hi = mid; + } + var dt = times[hi] - times[lo]; + if (!(dt > 0)) return values[hi]; + return values[lo] + (values[hi] - values[lo]) * (t - times[lo]) / dt; + } + + /** The sample nearest `t`; for wrapped phase, where interpolating is wrong. */ + function nearestAt(times, values, t) { + var n = Math.min(times.length, values.length); + if (!n) return NaN; + var lo = 0, hi = n - 1; + while (hi - lo > 1) { + var mid = (lo + hi) >> 1; + if (times[mid] <= t) lo = mid; else hi = mid; + } + return Math.abs(times[hi] - t) < Math.abs(t - times[lo]) ? values[hi] : values[lo]; + } + + function lowerIndex(times, n, t) { + var lo = 0, hi = n; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (times[mid] < t) lo = mid + 1; else hi = mid; + } + return lo; + } + + /** + * The detail block for `bi`, when the held detail covers [lo, hi]. + * + * Not blockAt(): that answers for the view being drawn, and its arrays are + * clipped to that view, so a marker scrolled off screen would read zero. + */ + function detailBlock(detail, bi, lo, hi) { + if (!detail || !detail.blocks || bi < detail.startBlock || bi >= detail.endBlock) return null; + if (detail.startSec > lo || detail.endSec < hi) return null; + return detail.blocks[bi - detail.startBlock] || null; + } + + /** Detail the renderer currently holds for this sequence, or null. */ + function liveDetail() { + if (typeof waveformDetail === 'undefined' || !waveformDetail) return null; + if (typeof waveformDetailGeneration !== 'undefined' && waveformDetail.generation !== waveformDetailGeneration) return null; + return waveformDetail; + } + + /* ── Core: corners ─────────────────────────────────────────────────── */ + + /** Coincident corners are one point; name it for what it is. */ + function mergeCoincident(corners) { + var out = []; + for (var i = 0; i < corners.length; i++) { + var c = corners[i], last = out[out.length - 1]; + if (last && Math.abs(c.t - last.t) <= MERGE_SEC) { + if (last.name === 'flat-top start' && c.name === 'flat-top end') last.name = 'peak'; + else if (last.name === 'ramp-up start' && c.name === 'flat-top start') last.name = 'flat-top start'; + else if (last.name === 'flat-top end' && c.name === 'ramp-down end') last.name = 'flat-top end'; + else if (last.name !== c.name) last.name += ' / ' + c.name; + continue; + } + out.push({ t: c.t, w: c.w, name: c.name }); + } + return out; + } + + /** + * A trapezoid's four corners. The decoder writes exactly these points, plus + * a leading zero at the block start when the gradient is delayed, and the + * overview never reduces a waveform this short, so they are exact. + */ + function trapezoidCorners(g) { + var n = Math.min(g.t.length, g.w.length), first = n === 5 ? 1 : 0; + if (n - first !== 4) return endpointCorners(g); + var corners = []; + for (var k = 0; k < 4; k++) corners.push({ t: g.t[first + k], w: g.w[first + k], name: TRAP_NAMES[k] }); + return mergeCoincident(corners); + } + + /** First and last sample: exact even after reduction, which keeps both. */ + function endpointCorners(g) { + var n = Math.min(g.t.length, g.w.length); + if (!n) return []; + return n === 1 + ? [{ t: g.t[0], w: g.w[0], name: 'start' }] + : [{ t: g.t[0], w: g.w[0], name: 'start' }, { t: g.t[n - 1], w: g.w[n - 1], name: 'end' }]; + } + + /** + * Douglas–Peucker on samples i0..i1: the indices a polyline within `eps` + * (vertically) of every sample needs. Iterative, so a long slice cannot + * overflow the stack. + */ + function simplify(t, w, i0, i1, eps) { + var keep = [i0, i1], stack = [i0, i1]; + while (stack.length) { + var b = stack.pop(), a = stack.pop(); + if (b - a < 2) continue; + var ta = t[a], wa = w[a], span = t[b] - ta, slope = span > 0 ? (w[b] - wa) / span : 0; + var worst = -1, at = -1; + for (var k = a + 1; k < b; k++) { + var deviation = Math.abs(w[k] - (wa + slope * (t[k] - ta))); + if (deviation > worst) { worst = deviation; at = k; } + } + if (worst > eps) { keep.push(at); stack.push(a, at, at, b); } + } + keep.sort(function (x, y) { return x - y; }); + return keep; + } + + /** + * Corners inside an arbitrary or extended-trapezoid waveform near [lo, hi]. + * + * Both arrive as 'arb', so breakpoints cannot be told from raster samples. + * The shape is simplified to a polyline within 0.5 % of the waveform's + * scale, and a vertex is a corner where the line goes flat↔ramp, reverses + * (a peak), steps, or changes slope by at least half. That finds every + * breakpoint of an extended trapezoid and the trapezoid-like corners of a + * raster-sampled one, while a smooth spiral keeps little more than its + * peaks. + */ + function interiorCorners(g, lo, hi, amplitude) { + var n = Math.min(g.t.length, g.w.length); + if (n < 3) return []; + var i0 = Math.max(0, lowerIndex(g.t, n, lo) - 1); + var i1 = Math.min(n - 1, lowerIndex(g.t, n, hi)); + if (i1 - i0 < 2 || i1 - i0 + 1 > MAX_CORNER_SAMPLES) return []; + var scale = Math.abs(amplitude) || 0; + for (var i = i0; i <= i1; i++) scale = Math.max(scale, Math.abs(g.w[i])); + if (!(scale > 0)) return []; + var eps = 0.005 * scale, keep = simplify(g.t, g.w, i0, i1, eps), out = []; + for (var j = 1; j < keep.length - 1; j++) { + var p = keep[j - 1], k = keep[j], q = keep[j + 1]; + var d1 = g.w[k] - g.w[p], d2 = g.w[q] - g.w[k], dt1 = g.t[k] - g.t[p], dt2 = g.t[q] - g.t[k]; + var name = null; + if (!(dt1 > 0) || !(dt2 > 0)) { + if (Math.abs(!(dt1 > 0) ? d1 : d2) > 0.02 * scale) name = 'step'; + } else { + var flat1 = Math.abs(d1) <= eps, flat2 = Math.abs(d2) <= eps; + if (flat1 && flat2) continue; + if (flat1) name = Math.abs(g.w[q]) > Math.abs(g.w[k]) ? 'ramp-up start' : 'ramp-down start'; + else if (flat2) name = Math.abs(g.w[k]) > Math.abs(g.w[p]) ? 'ramp-up end' : 'ramp-down end'; + else { + var s1 = d1 / dt1, s2 = d2 / dt2; + if (s1 * s2 < 0) name = 'peak'; + else if (Math.abs(s2 - s1) >= 0.5 * Math.max(Math.abs(s1), Math.abs(s2))) name = 'slope change'; + } + } + if (name) out.push({ t: g.t[k], w: g.w[k], name: name }); + } + return out; + } + + /** + * Corners of one gradient near [lo, hi]. Trapezoids come from the overview, + * which always has them whole. An arbitrary waveform's interior corners + * come from exact detail when it covers the window, otherwise from the + * overview unless the overview was reduced; a reduced waveform only offers + * its ends. + */ + function gradientCorners(overview, detail, lo, hi) { + if (overview.ty === 'trap') return trapezoidCorners(overview); + var corners = endpointCorners(overview); + var source = detail && detail.t && !detail.r ? detail : (!overview.r ? overview : null); + if (source) corners = corners.concat(interiorCorners(source, lo, hi, overview.a)); + corners.sort(function (a, b) { return a.t - b.t; }); + return mergeCoincident(corners); + } + + /* ── Core: snapping ────────────────────────────────────────────────── */ + + function blockLabel(blocks, bi) { + return bi > 0 ? 'block #' + blocks[bi - 1].i + '/#' + blocks[bi].i : 'block #' + blocks[bi].i + ' start'; + } + + /** + * Every snap target within `tol` seconds of `t`. + * + * opts.rows: visible channel indices; a channel whose row is hidden offers + * no corners. Block boundaries are always offered. opts.detail: the held + * waveform detail, or null. + */ + function snapCandidates(blocks, t, tol, opts) { + var out = []; + if (!blocks || !blocks.length || !(tol > 0)) return out; + opts = opts || {}; + var rows = opts.rows || [0, 1, 2, 3, 4, 5, 6], shown = {}; + for (var r = 0; r < rows.length; r++) shown[rows[r]] = true; + var lo = t - tol, hi = t + tol, count = 0; + for (var bi = firstBlockEndingAfter(blocks, lo); bi < blocks.length && blocks[bi].s <= hi; bi++) { + if (++count > MAX_SNAP_BLOCKS) return []; + var b = blocks[bi]; + out.push({ t: b.s, kind: 'block', ci: -1, value: 0, label: blockLabel(blocks, bi) }); + if (bi === blocks.length - 1) out.push({ t: b.s + b.d, kind: 'block', ci: -1, value: 0, label: 'block #' + b.i + ' end' }); + for (var a = 0; a < AXES.length; a++) { + var axis = AXES[a], g = b[axis]; + if (!shown[AXIS_ROW[axis]] || !g || g.ty === 'none' || !g.t || !g.t.length) continue; + if (g.t[g.t.length - 1] < lo || g.t[0] > hi) continue; + var detail = detailBlock(opts.detail, bi, lo, hi); + var corners = gradientCorners(g, detail && detail[axis], lo, hi); + for (var c = 0; c < corners.length; c++) { + out.push({ t: corners[c].t, kind: 'corner', ci: AXIS_ROW[axis], value: corners[c].w, label: AXIS_NAMES[axis] + ' ' + corners[c].name }); + } + } + var rf = b.rf; + if (rf && (shown[0] || shown[1])) { + var rfValue = function (time) { return rf.t && rf.m ? sampleAt(rf.t, rf.m, time) : 0; }; + out.push({ t: rf.s, kind: 'event', ci: 0, value: 0, label: 'RF start' }); + if (isFinite(rf.c)) out.push({ t: rf.c, kind: 'event', ci: 0, value: rfValue(rf.c), label: 'RF centre' }); + out.push({ t: rf.s + rf.d, kind: 'event', ci: 0, value: 0, label: 'RF end' }); + } + var adc = b.adc; + if (adc && shown[5] && adc.n > 0) { + var start = adc.s + (adc.d || 0), span = adc.n * adc.dw; + out.push({ t: start, kind: 'event', ci: 5, value: 0, label: 'ADC start' }); + out.push({ t: start + span / 2, kind: 'event', ci: 5, value: 0, label: 'ADC centre' }); + out.push({ t: start + span, kind: 'event', ci: 5, value: 0, label: 'ADC end' }); + } + if (b.trg && shown[6]) { + for (var g2 = 0; g2 < b.trg.length; g2++) { + var tg = b.trg[g2]; + out.push({ t: tg.s + (tg.d || 0), kind: 'event', ci: 6, value: 0, label: 'trigger start' }); + } + } + } + return out.filter(function (candidate) { return candidate.t >= lo && candidate.t <= hi; }); + } + + function rank(candidate, pointerCi) { + var own = candidate.kind === 'corner' && candidate.ci === pointerCi ? 0 : 1; + return own * 10 + KIND_RANK[candidate.kind]; + } + + /** + * The candidate to snap to: the nearest, except that within `onePx` seconds + * a corner on the pointer's own row beats other corners, which beat event + * edges, which beat block boundaries. Everything at the same instant is + * folded into its label, e.g. "Gx ramp-down end · block #12/#13". + */ + function chooseSnap(candidates, t, onePx, pointerCi) { + var best = null, bestDistance = Infinity; + for (var i = 0; i < candidates.length; i++) { + var c = candidates[i], distance = Math.abs(c.t - t); + if (!best || distance < bestDistance - onePx) { best = c; bestDistance = distance; continue; } + if (distance > bestDistance + onePx) continue; + var difference = rank(c, pointerCi) - rank(best, pointerCi); + if (difference < 0 || (difference === 0 && distance < bestDistance)) { best = c; bestDistance = distance; } + } + if (!best) return null; + var same = candidates.filter(function (c) { return Math.abs(c.t - best.t) <= MERGE_SEC; }); + same.sort(function (a, b) { return rank(a, pointerCi) - rank(b, pointerCi); }); + var labels = [best.label]; + for (var j = 0; j < same.length; j++) if (labels.indexOf(same[j].label) < 0) labels.push(same[j].label); + var text = labels.length > 3 ? labels.slice(0, 3).join(' · ') + ' +' + (labels.length - 3) : labels.join(' · '); + return { t: best.t, kind: best.kind, ci: best.ci, value: best.value, label: best.label, labels: labels, text: text }; + } + + function snapAt(blocks, t, tol, opts) { + opts = opts || {}; + return chooseSnap(snapCandidates(blocks, t, tol, opts), t, opts.onePx || tol / SNAP_PX, opts.pointerCi); + } + + /* ── Core: readout ─────────────────────────────────────────────────── */ + + /** + * Every channel's value at `t`. Gradients are in Hz/m; `approx` names the + * channels read from a reduced overview, where the samples either side of + * `t` may not be adjacent. + */ + function readoutAt(blocks, t, detail) { + var out = { t: t, index: -1, block: -1, offset: NaN, gx: 0, gy: 0, gz: 0, approx: {}, rf: null, adc: null, trigger: false }; + var bi = blockIndexAt(blocks, t); + if (bi < 0) return out; + var b = blocks[bi], d = detailBlock(detail, bi, t, t); + out.index = bi; out.block = b.i; out.offset = t - b.s; + for (var a = 0; a < AXES.length; a++) { + var axis = AXES[a], g = b[axis]; + if (!g || g.ty === 'none' || !g.t || !g.w) continue; + var exact = d && d[axis] && g.ty !== 'trap' ? d[axis] : null; + var source = exact && exact.t && exact.t.length && exact.t[0] <= t && exact.t[exact.t.length - 1] >= t ? exact : g; + out[axis] = sampleAt(source.t, source.w, t); + if (source.r && t >= g.t[0] && t <= g.t[g.t.length - 1]) out.approx[axis] = true; + } + var rf = b.rf; + if (rf && t >= rf.s && t <= rf.s + rf.d && rf.t && rf.m) { + var rfSource = d && d.rf && d.rf.t && d.rf.t.length && d.rf.t[0] <= t && d.rf.t[d.rf.t.length - 1] >= t ? d.rf : rf; + out.rf = { + amplitude: sampleAt(rfSource.t, rfSource.m, t), + phase: rfSource.pt && rfSource.p ? nearestAt(rfSource.pt, rfSource.p, t) : NaN, + approx: !!rfSource.r + }; + } + var adc = b.adc; + if (adc && adc.n > 0) { + var start = adc.s + (adc.d || 0), end = start + adc.n * adc.dw; + if (t >= start && t <= end) { + // The tolerance keeps a time exactly on a sample edge (as snapping + // places it) from rounding down into the previous sample. + var sample = Math.floor((t - start) / adc.dw + 1e-6); + out.adc = { sample: Math.max(0, Math.min(adc.n - 1, sample)), count: adc.n }; + } + } + if (b.trg) { + for (var i = 0; i < b.trg.length; i++) { + var tg = b.trg[i], from = tg.s + (tg.d || 0); + if (t >= from && t <= from + (tg.dr || 0)) out.trigger = true; + } + } + return out; + } + + /* ── Core: formatting ──────────────────────────────────────────────── */ + + /* Digits that resolve 0.1 µs, the finest raster Pulseq uses (ADC dwell). */ + var TIME_DIGITS = { s: 7, ms: 4, us: 1 }; + var GRAD_DIGITS = { 'Hz/m': 0, 'mT/m': 2, 'G/cm': 3 }; + + function unitName(unit) { return unit === 'us' ? 'µs' : unit; } + + function formatTime(seconds, units) { + var digits = TIME_DIGITS[units.timeUnit]; + return units.timeConv(seconds).toFixed(digits === undefined ? 4 : digits); + } + + function formatGradient(hzPerM, units) { + var digits = GRAD_DIGITS[units.gradUnit]; + var text = units.gradConv(hzPerM).toFixed(digits === undefined ? 2 : digits); + return /^-0(\.0*)?$/.test(text) ? text.slice(1) : text; + } + + /** + * One row per marker, in time order, with everything formatted in the + * viewer's current units. `list` is [{id, t, snap}]. + */ + function tableRows(list, blocks, detail, units) { + var rows = []; + for (var i = 0; i < list.length; i++) { + var m = list[i], r = readoutAt(blocks, m.t, detail), previous = i > 0 ? list[i - 1] : null; + rows.push({ + id: m.id, + name: 'M' + m.id, + time: formatTime(m.t, units), + delta: previous ? formatTime(m.t - previous.t, units) : '', + block: r.block >= 0 ? '#' + r.block : '', + offset: r.block >= 0 ? formatTime(r.offset, units) : '', + gx: (r.approx.gx ? '≈' : '') + formatGradient(r.gx, units), + gy: (r.approx.gy ? '≈' : '') + formatGradient(r.gy, units), + gz: (r.approx.gz ? '≈' : '') + formatGradient(r.gz, units), + rf: r.rf ? (r.rf.approx ? '≈' : '') + r.rf.amplitude.toFixed(1) : '', + phase: r.rf && isFinite(r.rf.phase) ? (r.rf.phase * 180 / Math.PI).toFixed(1) : '', + adc: r.adc ? (r.adc.sample + 1) + '/' + r.adc.count : '', + trigger: r.trigger ? 'on' : '', + snap: m.snap || '', + approx: !!(r.approx.gx || r.approx.gy || r.approx.gz || (r.rf && r.rf.approx)) + }); + } + return rows; + } + + function columns(units) { + var t = unitName(units.timeUnit), g = units.gradUnit; + return [ + ['name', 'Marker'], ['time', 'Time (' + t + ')'], ['delta', 'Δt (' + t + ')'], + ['block', 'Block'], ['offset', 'In block (' + t + ')'], + ['gx', 'Gx (' + g + ')'], ['gy', 'Gy (' + g + ')'], ['gz', 'Gz (' + g + ')'], + ['rf', 'RF (Hz)'], ['phase', 'RF phase (°)'], ['adc', 'ADC sample'], ['trigger', 'Trigger'], + ['snap', 'Snapped to'] + ]; + } + + /** Tab-separated, with a header, for pasting into a spreadsheet. */ + function toTsv(rows, units) { + var cols = columns(units), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; + for (var i = 0; i < rows.length; i++) { + lines.push(cols.map(function (c) { return String(rows[i][c[0]]).replace(/[\t\n]/g, ' '); }).join('\t')); + } + return lines.join('\n'); + } + + /* ── Marker list ───────────────────────────────────────────────────── */ + + var markers = []; + var version = 0; + + function sortMarkers() { markers.sort(function (a, b) { return a.t - b.t || a.id - b.id; }); } + + /** Ids keep growing while markers exist, so "M2" keeps meaning one marker. */ + function addMarker(t, snap) { + var id = 1; + for (var i = 0; i < markers.length; i++) id = Math.max(id, markers[i].id + 1); + var marker = { id: id, t: t, snap: snap || '' }; + markers.push(marker); sortMarkers(); version++; + return marker; + } + + function findMarker(id) { + for (var i = 0; i < markers.length; i++) if (markers[i].id === id) return markers[i]; + return null; + } + + function moveMarker(id, t, snap) { + var marker = findMarker(id); + if (!marker) return null; + marker.t = t; marker.snap = snap || ''; sortMarkers(); version++; + return marker; + } + + function removeMarker(id) { + var before = markers.length; + markers = markers.filter(function (m) { return m.id !== id; }); + if (markers.length !== before) version++; + } + + function clearMarkers() { + if (markers.length) version++; + markers = []; + } + + function listMarkers() { return markers.map(function (m) { return { id: m.id, t: m.t, snap: m.snap }; }); } + + /* ══ UI (only install() reaches here) ══════════════════════════════════ */ + + var ctx = null; + var wired = false; + var snapEnabled = true; + var tableOpen = true; + /** Pointer over the plot, in canvas CSS pixels; null when elsewhere. */ + var hover = null; + var hoverMarkerId = 0; + /** {id, from, fromSnap, snap} while a marker is being dragged. */ + var drag = null; + var menu = null; + /** {x, y, snap} the open menu was opened for. */ + var menuTarget = null; + var tableEl = null; + var tableKey = ''; + var snapCache = null; + + function el(id) { return document.getElementById(id); } + function prefs() { return typeof SeqEyesPrefs !== 'undefined' ? SeqEyesPrefs : null; } + + function units() { + return { timeConv: ctx.timeConv, timeUnit: ctx.timeUnitStr(), gradConv: ctx.gradConv, gradUnit: ctx.gradUnitStr() }; + } + + function canvasPoint(event) { + var mc = el('mc'), rect = mc.getBoundingClientRect(); + return { x: event.clientX - rect.left, y: event.clientY - rect.top, width: rect.width, height: rect.height }; + } + + function insidePlot(p) { + var M = ctx.margins(); + return p.x >= M.l && p.x <= p.width - M.r && p.y >= M.t && p.y <= p.height - M.b; + } + + function rowAt(y) { + var M = ctx.margins(), rows = ctx.visChannels(), vi = Math.floor((y - M.t) / ctx.cH()); + return vi >= 0 && vi < rows.length ? rows[vi] : -1; + } + + function markerNear(x, px) { + var best = null, bestDistance = px + 1e-9; + for (var i = 0; i < markers.length; i++) { + var distance = Math.abs(ctx.t2x(markers[i].t) - x); + if (distance <= bestDistance) { best = markers[i]; bestDistance = distance; } + } + return best; + } + + function clampTime(t) { + var total = ctx.duration(); + return Math.max(0, total > 0 ? Math.min(total, t) : t); + } + + /** + * Snap target under the pointer, or null. Cached: in the web app the + * overlay is drawn twice a frame (once by the bundle, once by the page). + */ + function snapFor(x, y) { + if (!ctx || !snapEnabled) return null; + var blocks = ctx.blocks(); + if (!blocks || !blocks.length) return null; + var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + SNAP_PX) - t), rows = ctx.visChannels(); + var pointerCi = y === null || y === undefined ? -1 : rowAt(y), detail = liveDetail(), rowKey = rows.join(','); + var c = snapCache; + if (c && c.blocks === blocks && c.detail === detail && c.t === t && c.tol === tol && c.ci === pointerCi && c.rows === rowKey) { + return c.result; + } + var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / SNAP_PX }); + snapCache = { blocks: blocks, detail: detail, t: t, tol: tol, ci: pointerCi, rows: rowKey, result: result }; + return result; + } + + /** The suggestion shows once markers are in use, not while just browsing. */ + function currentSuggestion() { + if (menuTarget) return menuTarget.snap; + if (drag) return drag.snap; + if (hover && markers.length) return snapFor(hover.x, hover.y); + return null; + } + + function redraw() { + if (ctx && typeof ctx.requestOverlay === 'function') ctx.requestOverlay(); + } + + /* ── Drawing on the overlay canvas ─────────────────────────────────── */ + + function valueToY(ci, vi, value) { + var M = ctx.margins(), ch = ctx.cH(), y = ctx.cy(vi); + if (ci === 0 || ci === 1) return y + ch * 0.45 - value * (ch * 0.9 / ctx.channelRange(ci)); + if (ci >= 2 && ci <= 4) return y - value * (ch * 0.4 / ctx.channelRange(ci)); + if (ci === 7) return M.t + (vi + 1) * ch - ch * 0.08 - value * (ch * 0.84 / ctx.channelRange(7)); + if (ci >= 8 && ci <= 10) return y - value * (ch * 0.4 / ctx.channelRange(ci)); + return y; + } + + function clampToRow(vi, y) { + var M = ctx.margins(), ch = ctx.cH(), top = M.t + vi * ch; + return Math.max(top + 2, Math.min(top + ch - 2, y)); + } + + function colour(style, name, fallback) { + var value = style.getPropertyValue(name).trim(); + return value || fallback; + } + + function pill(g, text, x, y, left, right, fg, bg) { + var width = g.measureText(text).width + 8, cx = Math.max(left + width / 2, Math.min(right - width / 2, x)); + g.fillStyle = fg; g.fillRect(cx - width / 2, y - 7, width, 13); + g.fillStyle = bg; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(text, cx, y); + return { left: cx - width / 2, right: cx + width / 2 }; + } + + function drawSuggestion(g, w, h, s, style, fg) { + var M = ctx.margins(), x = ctx.t2x(s.t); + if (x < M.l || x > w - M.r) return; + g.save(); + g.globalAlpha = 0.75; g.strokeStyle = fg; g.lineWidth = 1; g.setLineDash([2, 3]); + g.beginPath(); g.moveTo(x, M.t); g.lineTo(x, h - M.b); g.stroke(); g.setLineDash([]); + g.globalAlpha = 1; + var rows = ctx.visChannels(), vi = rows.indexOf(s.ci), y = M.t + 12; + if (vi >= 0) { + y = clampToRow(vi, valueToY(s.ci, vi, s.value)); + g.lineWidth = 1.5; g.strokeStyle = colour(style, ROW_COLOURS[s.ci] || '--fg', fg); + g.beginPath(); g.arc(x, y, 5, 0, Math.PI * 2); g.stroke(); + } + g.font = '10px monospace'; + var text = s.text, width = g.measureText(text).width, right = x + 8 + width <= w - M.r; + g.fillStyle = colour(style, '--bg', '#fff'); g.globalAlpha = 0.85; + g.fillRect(right ? x + 7 : x - 9 - width, y - 16, width + 2, 12); + g.globalAlpha = 1; g.fillStyle = fg; g.textAlign = right ? 'left' : 'right'; g.textBaseline = 'middle'; + g.fillText(text, right ? x + 8 : x - 8, y - 10); + g.restore(); + } + + /** + * Called by both renderers' drawCursorOverlay, after the overlay is cleared: + * marker lines with a dot where each crosses RF and the gradients, Δt + * between neighbours, and the snap suggestion. + */ + function drawOverlay(g, w, h) { + if (!ctx || !g) return; + syncTable(); + var suggestion = currentSuggestion(); + if (!markers.length && !suggestion) return; + var style = getComputedStyle(document.body), fg = colour(style, '--fg', '#222'), bg = colour(style, '--bg', '#fff'); + var M = ctx.margins(), left = M.l, right = w - M.r, top = M.t, bottom = h - M.b; + var rows = ctx.visChannels(), detail = liveDetail(), blocks = ctx.blocks(), u = units(); + g.save(); + g.beginPath(); g.rect(left, top, Math.max(0, right - left), Math.max(0, bottom - top)); g.clip(); + g.font = '10px monospace'; + + // Δt between neighbours, just above the marker names. + var bracketY = bottom - 22; + for (var i = 1; i < markers.length; i++) { + var xa = ctx.t2x(markers[i - 1].t), xb = ctx.t2x(markers[i].t); + if (xb < left || xa > right || xb - xa < 2) continue; + var a = Math.max(left, xa), b = Math.min(right, xb); + g.strokeStyle = fg; g.lineWidth = 1; g.globalAlpha = 0.8; + g.beginPath(); g.moveTo(a, bracketY); g.lineTo(b, bracketY); + if (xa >= left) { g.moveTo(xa, bracketY - 4); g.lineTo(xa, bracketY + 4); } + if (xb <= right) { g.moveTo(xb, bracketY - 4); g.lineTo(xb, bracketY + 4); } + g.stroke(); g.globalAlpha = 1; + var label = 'Δ ' + formatTime(markers[i].t - markers[i - 1].t, u) + ' ' + unitName(u.timeUnit); + var width = g.measureText(label).width; + if (b - a > width + 10) { + g.fillStyle = bg; g.fillRect((a + b) / 2 - width / 2 - 3, bracketY - 15, width + 6, 12); + g.fillStyle = fg; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(label, (a + b) / 2, bracketY - 9); + } + } + + for (var k = 0; k < markers.length; k++) { + var m = markers[k], x = ctx.t2x(m.t); + if (x < left - 1 || x > right + 1) continue; + var active = m.id === hoverMarkerId || (drag && drag.id === m.id); + g.strokeStyle = fg; g.lineWidth = active ? 2 : 1.2; g.setLineDash([]); + g.beginPath(); g.moveTo(x, top); g.lineTo(x, bottom); g.stroke(); + + var reading = readoutAt(blocks, m.t, detail); + var next = k + 1 < markers.length ? ctx.t2x(markers[k + 1].t) : right; + for (var vi = 0; vi < rows.length; vi++) { + var ci = rows[vi], value = null; + if (ci === 0) value = reading.rf ? reading.rf.amplitude : null; + else if (ci >= 2 && ci <= 4) value = reading[AXES[ci - 2]]; + if (value === null) continue; + var y = clampToRow(vi, valueToY(ci, vi, value)); + g.fillStyle = colour(style, ROW_COLOURS[ci], fg); g.strokeStyle = bg; g.lineWidth = 1; + g.beginPath(); g.arc(x, y, 3, 0, Math.PI * 2); g.fill(); g.stroke(); + if (ci >= 2 && next - x > 70) { + var text = (reading.approx[AXES[ci - 2]] ? '≈' : '') + formatGradient(value, u); + g.fillStyle = fg; g.textAlign = 'left'; g.textBaseline = 'bottom'; g.fillText(text, x + 5, y - 2); + } + } + var nameRoom = Math.min(next, right) - x; + var name = 'M' + m.id, full = name + ' ' + formatTime(m.t, u) + ' ' + unitName(u.timeUnit); + pill(g, nameRoom > g.measureText(full).width + 24 ? full : name, x, bottom - 8, left, right, fg, bg); + } + if (suggestion) drawSuggestion(g, w, h, suggestion, style, fg); + g.restore(); + } + + /* ── Table strip ───────────────────────────────────────────────────── */ + + function element(tag, className, text) { + var node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + } + + function button(text, title, onClick) { + var b = element('button', null, text); + b.type = 'button'; if (title) b.title = title; + b.addEventListener('click', onClick); + return b; + } + + function buildTable() { + var cc = el('cc'); + if (!cc || !cc.parentNode) return; + tableEl = element('div', 'mk-table'); tableEl.id = 'mkTable'; tableEl.hidden = true; + tableEl.setAttribute('role', 'region'); tableEl.setAttribute('aria-label', 'Measurement markers'); + cc.parentNode.insertBefore(tableEl, cc.nextSibling); + } + + /** Re-render when the markers, units or underlying samples changed. */ + function syncTable() { + if (!tableEl || !ctx) return; + var u = units(), detail = liveDetail(), blocks = ctx.blocks(); + var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0].join('|'); + if (key === tableKey && tableEl.__blocks === blocks && tableEl.__detail === detail) return; + tableKey = key; tableEl.__blocks = blocks; tableEl.__detail = detail; + renderTable(u, detail, blocks); + } + + function renderTable(u, detail, blocks) { + var wasHidden = tableEl.hidden; + tableEl.textContent = ''; + tableEl.hidden = !markers.length; + if (!markers.length) { if (!wasHidden) relayout(); return; } + var rows = tableRows(markers, blocks, detail, u); + var head = element('div', 'mk-head'); + head.appendChild(element('span', 'mk-title', 'Markers')); + var span = markers.length > 1 ? ' · span ' + formatTime(markers[markers.length - 1].t - markers[0].t, u) + ' ' + unitName(u.timeUnit) : ''; + head.appendChild(element('span', 'mk-summary', markers.length + (markers.length === 1 ? ' marker' : ' markers') + span)); + if (rows.some(function (r) { return r.approx; })) { + head.appendChild(element('span', 'mk-note', '≈ from reduced samples; zoom in for exact values')); + } + var actions = element('span', 'mk-actions'); + actions.appendChild(button(tableOpen ? 'Hide' : 'Show', tableOpen ? 'Collapse the marker table' : 'Expand the marker table', function () { setTableOpen(!tableOpen); })); + actions.appendChild(button('Copy', 'Copy the table as tab-separated text', function () { copyTable(this); })); + actions.appendChild(button('Clear', 'Remove every marker', function () { clearMarkers(); afterChange(); })); + head.appendChild(actions); + tableEl.appendChild(head); + if (tableOpen) { + var scroll = element('div', 'mk-scroll'), table = element('table'), thead = element('thead'), tr = element('tr'); + var cols = columns(u); + cols.forEach(function (c) { tr.appendChild(element('th', null, c[1])); }); + tr.appendChild(element('th')); + thead.appendChild(tr); table.appendChild(thead); + var body = element('tbody'); + rows.forEach(function (row) { + var line = element('tr'); + line.setAttribute('data-marker', String(row.id)); + cols.forEach(function (c) { line.appendChild(element('td', c[0] === 'name' ? 'mk-name' : null, row[c[0]])); }); + var cell = element('td'); + cell.appendChild(button('×', 'Remove ' + row.name, function () { removeMarker(row.id); afterChange(); })); + line.appendChild(cell); + body.appendChild(line); + }); + table.appendChild(body); scroll.appendChild(table); tableEl.appendChild(scroll); + } + relayout(); + } + + /* The strip takes height from the plot; the hosts' ResizeObserver on #cc + redraws, but only once the size actually settles, so ask explicitly. */ + function relayout() { + if (typeof requestAnimationFrame === 'function') requestAnimationFrame(redraw); + } + + function setTableOpen(open) { + tableOpen = !!open; + var p = prefs(); if (p && p.KEYS.markerTable) p.setBool(p.KEYS.markerTable, tableOpen); + tableKey = ''; + syncTable(); + } + + function copyTable(source) { + var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()); + var done = function () { if (source) { var old = source.textContent; source.textContent = 'Copied'; setTimeout(function () { source.textContent = old; }, 1200); } }; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); }); + } else { fallbackCopy(text); done(); } + } + + function fallbackCopy(text) { + var area = element('textarea'); area.value = text; + area.style.position = 'fixed'; area.style.opacity = '0'; + document.body.appendChild(area); area.select(); + try { document.execCommand('copy'); } catch (e) { /* nothing more to try */ } + document.body.removeChild(area); + } + + function afterChange() { + snapCache = null; + syncTable(); + redraw(); + } + + /* ── Context menu ──────────────────────────────────────────────────── */ + + function isCompactLayout() { + return !!(window.matchMedia && window.matchMedia('(max-width: 768px), (pointer: coarse)').matches); + } + + function menuItem(label, detail, onSelect) { + var item = element('button', 'mk-item'); + item.type = 'button'; item.setAttribute('role', 'menuitem'); + item.appendChild(element('span', 'mk-item-label', label)); + if (detail) item.appendChild(element('span', 'mk-item-detail', detail)); + item.addEventListener('click', function () { closeMenu(); onSelect(); }); + return item; + } + + function menuToggle(label, checked, onChange) { + var row = element('label', 'mk-item mk-check'); + var box = element('input'); box.type = 'checkbox'; box.checked = checked; + box.setAttribute('role', 'menuitemcheckbox'); + box.addEventListener('change', function () { onChange(box.checked); }); + row.appendChild(box); row.appendChild(element('span', 'mk-item-label', label)); + return row; + } + + function openMenu(event, p) { + closeMenu(); + var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y), near = markerNear(p.x, REMOVE_PX); + var time = function (seconds) { return formatTime(seconds, u) + ' ' + unitName(u.timeUnit); }; + menuTarget = { x: p.x, y: p.y, snap: snap }; + menu = element('div', 'lblc mk-menu'); menu.id = 'markerMenu'; + menu.setAttribute('role', 'menu'); menu.setAttribute('aria-label', 'Measurement markers'); + if (snap) menu.appendChild(menuItem('Add marker at ' + snap.text, time(snap.t), function () { place(snap.t, snap.text); })); + menu.appendChild(menuItem(snap ? 'Add marker at pointer (no snap)' : 'Add marker here', time(t), function () { place(t, ''); })); + if (near) menu.appendChild(menuItem('Remove M' + near.id, time(near.t), function () { removeMarker(near.id); afterChange(); })); + if (markers.length) menu.appendChild(menuItem('Clear all markers', String(markers.length), function () { clearMarkers(); afterChange(); })); + menu.appendChild(element('div', 'mk-sep')); + menu.appendChild(menuToggle('Snap to corners and block edges', snapEnabled, function (on) { + snapEnabled = on; + var pr = prefs(); if (pr && pr.KEYS.markerSnap) pr.setBool(pr.KEYS.markerSnap, on); + menuTarget.snap = on ? snapFor(p.x, p.y) : null; + snapCache = null; redraw(); + })); + if (markers.length) menu.appendChild(menuToggle('Show the marker table', tableOpen, function (on) { setTableOpen(on); })); + document.body.appendChild(menu); + positionMenu(event.clientX, event.clientY); + el('cc').classList.add('mk-menu-open'); + document.addEventListener('pointerdown', onOutsidePointer, true); + window.addEventListener('resize', closeMenu); + var first = menu.querySelector('.mk-item'); + if (first && first.focus) first.focus(); + redraw(); + } + + function positionMenu(clientX, clientY) { + var compact = isCompactLayout(); + menu.classList.toggle('sheet', compact); + if (compact) { menu.style.left = ''; menu.style.top = ''; return; } + var width = menu.offsetWidth, height = menu.offsetHeight, vw = window.innerWidth, vh = window.innerHeight; + menu.style.left = Math.max(8, Math.min(clientX + 2, vw - width - 8)) + 'px'; + menu.style.top = Math.max(8, clientY + 2 + height > vh - 8 ? clientY - height - 2 : clientY + 2) + 'px'; + } + + function closeMenu() { + if (!menu) return; + document.removeEventListener('pointerdown', onOutsidePointer, true); + window.removeEventListener('resize', closeMenu); + if (menu.parentNode) menu.parentNode.removeChild(menu); + menu = null; menuTarget = null; + var cc = el('cc'); if (cc) cc.classList.remove('mk-menu-open'); + redraw(); + } + + function onOutsidePointer(event) { + if (menu && !menu.contains(event.target)) closeMenu(); + } + + function moveMenuFocus(step) { + var items = Array.prototype.slice.call(menu.querySelectorAll('.mk-item')); + var at = items.indexOf(document.activeElement && document.activeElement.closest ? document.activeElement.closest('.mk-item') : null); + var next = items[(at + step + items.length) % items.length]; + if (next) (next.querySelector('input') || next).focus(); + } + + function place(t, snap) { + addMarker(clampTime(t), snap); + afterChange(); + } + + /* ── Pointer handling ──────────────────────────────────────────────── */ + + function onContextMenu(event) { + if (!ctx || event.target !== el('mc')) return; + // Keeps the browser's menu, and VS Code's webview menu, off the plot. + event.preventDefault(); + var p = canvasPoint(event); + if (insidePlot(p)) openMenu(event, p); + } + + /* Capture phase on #cc runs before both renderers' mousedown on #mc, so + grabbing a marker never starts a pan. Anything else passes through. */ + function onMouseDown(event) { + if (!ctx || event.button !== 0 || event.ctrlKey || event.target !== el('mc') || !markers.length) return; + var p = canvasPoint(event), marker = insidePlot(p) ? markerNear(p.x, HIT_PX) : null; + if (!marker) return; + event.stopPropagation(); event.preventDefault(); + drag = { id: marker.id, from: marker.t, fromSnap: marker.snap, snap: null }; + el('cc').classList.add('mk-drag'); + redraw(); + } + + function onWindowMove(event) { + if (!drag || !ctx) return; + var p = canvasPoint(event), bypass = event.shiftKey || event.altKey; + var snap = bypass ? null : snapFor(p.x, p.y); + drag.snap = snap; + moveMarker(drag.id, clampTime(snap ? snap.t : ctx.x2t(p.x)), snap ? snap.text : ''); + afterChange(); + } + + function onWindowUp() { + if (!drag) return; + drag = null; + var cc = el('cc'); if (cc) cc.classList.remove('mk-drag'); + afterChange(); + } + + function onHoverMove(event) { + if (!ctx || drag) return; + var p = canvasPoint(event), inside = insidePlot(p); + hover = inside ? { x: p.x, y: p.y } : null; + var near = inside && markers.length ? markerNear(p.x, HIT_PX) : null, id = near ? near.id : 0; + if (id !== hoverMarkerId) { hoverMarkerId = id; redraw(); } + el('cc').classList.toggle('mk-hover', !!near); + } + + function onHoverLeave() { + if (drag) return; + hover = null; hoverMarkerId = 0; + var cc = el('cc'); if (cc) cc.classList.remove('mk-hover'); + redraw(); + } + + function onKeyDown(event) { + if (event.key === 'Escape' && (menu || drag)) { + event.preventDefault(); event.stopPropagation(); + if (menu) { closeMenu(); return; } + moveMarker(drag.id, drag.from, drag.fromSnap); + onWindowUp(); + return; + } + if (menu && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + event.preventDefault(); moveMenuFocus(event.key === 'ArrowDown' ? 1 : -1); + } + } + + function wire() { + var cc = el('cc'); + if (!cc || !el('mc')) return; + wired = true; + cc.addEventListener('mousedown', onMouseDown, true); + cc.addEventListener('contextmenu', onContextMenu); + cc.addEventListener('mousemove', onHoverMove); + cc.addEventListener('mouseleave', onHoverLeave); + window.addEventListener('mousemove', onWindowMove); + window.addEventListener('mouseup', onWindowUp); + window.addEventListener('blur', onWindowUp); + document.addEventListener('keydown', onKeyDown, true); + buildTable(); + var p = prefs(); + if (p && p.KEYS.markerSnap) snapEnabled = p.getBool(p.KEYS.markerSnap, true); + if (p && p.KEYS.markerTable) tableOpen = p.getBool(p.KEYS.markerTable, true); + if (typeof window !== 'undefined') { + var dev = window.SeqEyesDev = window.SeqEyesDev || {}; + dev.markers = function () { + var detail = liveDetail(), blocks = ctx ? ctx.blocks() : []; + return markers.map(function (m) { return { id: m.id, t: m.t, snap: m.snap, readout: readoutAt(blocks, m.t, detail) }; }); + }; + dev.addMarker = function (t, snap) { var m = addMarker(clampTime(t), snap); afterChange(); return m.id; }; + dev.snapAt = function (t) { return ctx ? snapFor(ctx.t2x(t), null) : null; }; + dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()) : ''; }; + dev.markerState = function () { + return { suggestion: currentSuggestion(), menuOpen: !!menu, dragging: !!drag, snapEnabled: snapEnabled, tableOpen: tableOpen }; + }; + } + } + + /** + * Hand the module a renderer's state. ctx: blocks(), duration(), margins(), + * t2x, x2t, visChannels, cH, cy, channelRange, timeConv, timeUnitStr, + * gradConv, gradUnitStr, requestOverlay. A later install replaces an + * earlier one; the DOM is wired once. + */ + function install(context) { + ctx = context; + snapCache = null; tableKey = ''; + if (!wired && typeof document !== 'undefined') wire(); + syncTable(); + } + + /** A new sequence: its markers would point at nothing. */ + function reset() { + clearMarkers(); + drag = null; hover = null; hoverMarkerId = 0; snapCache = null; + closeMenu(); + var cc = typeof document !== 'undefined' ? el('cc') : null; + if (cc) cc.classList.remove('mk-drag', 'mk-hover'); + syncTable(); + } + + return { + install: install, + reset: reset, + drawOverlay: drawOverlay, + // List operations, also used by tests and dev hooks. + add: function (t, snap) { var m = addMarker(t, snap); if (ctx) afterChange(); return m; }, + remove: function (id) { removeMarker(id); if (ctx) afterChange(); }, + clear: function () { clearMarkers(); if (ctx) afterChange(); }, + move: moveMarker, + list: listMarkers, + // Pure core, exported for the unit tests. + core: { + blockIndexAt: blockIndexAt, + sampleAt: sampleAt, + trapezoidCorners: trapezoidCorners, + gradientCorners: gradientCorners, + interiorCorners: interiorCorners, + snapCandidates: snapCandidates, + chooseSnap: chooseSnap, + snapAt: snapAt, + readoutAt: readoutAt, + tableRows: tableRows, + toTsv: toTsv, + formatTime: formatTime, + formatGradient: formatGradient + } + }; +})(); diff --git a/src/editor/webview/assets/prefs-ui.js b/src/editor/webview/assets/prefs-ui.js index f03fab3..bcba8ac 100644 --- a/src/editor/webview/assets/prefs-ui.js +++ b/src/editor/webview/assets/prefs-ui.js @@ -77,7 +77,8 @@ var SeqEyesPrefsUi = (function () { var note = element('div', 'prefs-note'); note.appendChild(element('div', null, 'Theme, time and gradient units, the Blocks toggle, k-space and ' - + 'spectrogram options, and panel sizes are kept between sessions.')); + + 'spectrogram options, marker snapping, and panel sizes are kept ' + + 'between sessions.')); note.appendChild(element('div', null, inVsCode() /* Different sentences because the two hosts really do keep different things: a path the extension re-reads, versus the file's text. */ diff --git a/src/editor/webview/assets/prefs.js b/src/editor/webview/assets/prefs.js index 1985ca2..98bc8bc 100644 --- a/src/editor/webview/assets/prefs.js +++ b/src/editor/webview/assets/prefs.js @@ -36,6 +36,8 @@ var SeqEyesPrefs = (function () { kspaceUnit: 'seqeyes.kspace.unit', kspaceDotSize: 'seqeyes.kspace.dotSize', kspaceProjection: 'seqeyes.kspace.projection', + markerSnap: 'seqeyes.markers.snap', + markerTable: 'seqeyes.markers.table', ascName: 'seqeyes.asc.name', ascText: 'seqeyes.asc.text' }; diff --git a/src/editor/webview/assets/state.js b/src/editor/webview/assets/state.js index 9db7837..63837f5 100644 --- a/src/editor/webview/assets/state.js +++ b/src/editor/webview/assets/state.js @@ -353,7 +353,7 @@ function applySerializedKspace(payload){ much as the message: the progress overlay reaches "Ready" either way, so leaving stale blocks on screen would read as a successful load. */ function showSequenceLoadFailure(message){ - BL=[];waveformOverview=null;blockPos=[];mmCache=null;resetWaveformDetail(); + BL=[];waveformOverview=null;blockPos=[];mmCache=null;resetWaveformDetail();SeqEyesMarkers.reset(); labelInfo={names:[],kinds:[]};labelTable=null;labelBusy=false;chVis[11]=false;SeqEyesLabels.closeControls(false);buildLegend(); setViewerNotice('sequence',message); setExportButtonEnabled(false); @@ -382,7 +382,7 @@ window.addEventListener('message',function(e){ return; } if(m.type==='sequenceData'){ - resetWaveformDetail(m.sequenceGeneration); + resetWaveformDetail(m.sequenceGeneration);SeqEyesMarkers.reset(); try{ BL=unpackSequenceBlocks(m.blocks,m.sampleTimes,m.sampleValues,m.sampleCount||0); }catch(err){ @@ -1115,9 +1115,9 @@ window.SeqEyesPanelHost={ message.endSec=endSec; vscApi.postMessage(message); }, - /* Simulation: only inside VS Code, where the extension answers these. The - Python viewer runs this bundle too, with no host to ask, so it keeps the - Simulation button hidden. */ + /* Simulation: only inside VS Code, where the extension answers these. Any + page that loads this bundle without a VS Code host keeps the Simulation + button hidden. (The Python viewer has its own renderer and does not.) */ createSimulationWorker:vscApi?createSimulationWorkerStandIn:undefined, getSequenceSource:vscApi?simulationSequenceSource:undefined, getSequenceSourceStatus:vscApi?simulationSequenceStatus:undefined, diff --git a/src/editor/webview/assets/styles.css b/src/editor/webview/assets/styles.css index 904fc84..ee1b713 100644 --- a/src/editor/webview/assets/styles.css +++ b/src/editor/webview/assets/styles.css @@ -275,3 +275,35 @@ body.layout-vertical.sg-split-drag{cursor:col-resize} .lblc-swatches{gap:6px;padding-left:0} .lblc-foot button{min-height:34px;flex:1} } +/* ── Measurement markers (markers.js) ───────────────────────────────── */ +#cc.mk-hover,#cc.mk-drag{cursor:ew-resize} +#cc.mk-drag #tt,#cc.mk-menu-open #tt{display:none!important} +.mk-menu{min-width:240px;padding:4px 0} +.mk-menu .mk-item{display:flex;align-items:center;gap:16px;width:100%;padding:5px 12px;background:none;border:0;border-radius:0;color:var(--fg);font-size:11px;text-align:left;cursor:pointer} +.mk-menu .mk-item:hover,.mk-menu .mk-item:focus-visible,.mk-menu .mk-item:focus-within{background:var(--gr);opacity:1;outline:none} +.mk-item-label{flex:1} +.mk-item-detail{font:10px monospace;color:var(--lb)} +.mk-menu .mk-check{gap:8px} +.mk-check input{margin:0;cursor:pointer} +.mk-sep{height:1px;background:var(--gr);margin:4px 0} +.mk-table{flex-shrink:0;max-height:34%;display:flex;flex-direction:column;border-top:1px solid var(--gr);background:var(--trbg);font-size:11px} +.mk-table[hidden]{display:none} +.mk-head{display:flex;align-items:center;gap:4px 10px;padding:3px 8px;flex-wrap:wrap} +.mk-title{font-weight:600} +.mk-summary{color:var(--lb);font:10px monospace} +.mk-note{color:var(--lb);font-size:10px} +.mk-actions{margin-left:auto;display:flex;gap:4px} +.mk-table button{background:var(--gr);border:1px solid var(--ax);color:var(--fg);border-radius:3px;font-size:10px;padding:1px 6px;cursor:pointer} +.mk-table button:hover{opacity:.75} +.mk-scroll{overflow:auto;min-height:0} +.mk-table table{border-collapse:collapse;font:10px monospace;white-space:nowrap} +.mk-table th{position:sticky;top:0;background:var(--trbg);text-align:right;font-weight:600;color:var(--lb);padding:2px 8px;border-bottom:1px solid var(--gr)} +.mk-table td{text-align:right;padding:1px 8px} +.mk-table th:first-child,.mk-table td.mk-name,.mk-table td:nth-last-child(2){text-align:left} +.mk-table tbody tr:nth-child(even){background:rgba(127,127,127,.06)} +.mk-table td button{padding:0 5px} +@media(max-width:768px),(pointer:coarse){ + .mk-menu .mk-item{padding:10px 14px;font-size:13px} + .mk-table{max-height:40%} + .mk-table button{min-height:28px;padding:2px 10px} +} diff --git a/test/browser/markers.spec.ts b/test/browser/markers.spec.ts new file mode 100644 index 0000000..74ef37a --- /dev/null +++ b/test/browser/markers.spec.ts @@ -0,0 +1,269 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { expect, test, type Locator, type Page } from '@playwright/test'; + +import { decodeAllBlocks } from '../../src/pulseq/decoder'; +import { parseSequenceBytes } from '../../src/pulseq/sequenceReader'; + +/* Measurement markers in the standalone viewer (the renderer the web app, + the GitHub Pages preview and MATLAB run). */ + +const gre = resolve('test/kspace_baselines/v151_gre/seq/writeGradientEcho.seq'); +const epi = resolve('test/seqeyes_demo_seq_files/writeEpi.seq'); + +interface MarkerInfo { id: number; t: number; snap: string; readout: { block: number; gx: number } } +interface DevWindow { + SeqEyesDev: { + markers(): MarkerInfo[]; + markerState(): { suggestion: { t: number; label: string } | null; menuOpen: boolean; dragging: boolean; snapEnabled: boolean }; + }; + __seqeyesDebug: { + state(): { offset: number; scale: number; visibleChannels: string[] }; + setView(start: number, end: number): boolean; + }; +} + +/** The first Gx trapezoid's corners, as the decoder places them. */ +function firstGxTrapezoid(): number[] { + const seq = parseSequenceBytes(new Uint8Array(readFileSync(gre)), 'writeGradientEcho.seq'); + const block = decodeAllBlocks(seq).find(b => b.gx && b.gx.type === 'trap' && b.gx.duration > 5e-4)!; + const times = Array.from(block.gx!.timePoints); + return times.length === 5 ? times.slice(1) : times; +} + +const consoleFailures = new WeakMap(); + +test.beforeEach(async ({ page }) => { + const failures: string[] = []; + consoleFailures.set(page, failures); + page.on('console', (message) => { if (message.type() === 'error') failures.push(message.text()); }); + page.on('pageerror', (error) => failures.push(error.message)); +}); + +test.afterEach(async ({ page }) => { + expect(consoleFailures.get(page) ?? []).toEqual([]); +}); + +test('right-click adds a marker snapped to a gradient corner, and a second gives Δt', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + + // Nothing is suggested while just browsing. + await hoverAt(page, corners[1], 'Gx', 3); + expect((await markerState(page)).suggestion).toBeNull(); + + await rightClickAt(page, corners[1], 'Gx', 3); + const menu = page.locator('#markerMenu'); + await expect(menu).toBeVisible(); + await expect(menu.locator('.mk-item').first()).toContainText('Add marker at Gx flat-top start'); + // While the menu is open the ring marks its target. + expect((await markerState(page)).suggestion?.label).toBe('Gx flat-top start'); + await menu.locator('.mk-item').first().click(); + await expect(menu).toBeHidden(); + + let markers = await markerList(page); + expect(markers).toHaveLength(1); + expect(Math.abs(markers[0].t - corners[1])).toBeLessThan(1e-12); + // This GRE plays Gx and Gy corners together; the pointer's row is named first. + expect(markers[0].snap).toMatch(/^Gx flat-top start( · |$)/); + expect(markers[0].readout.gx).not.toBe(0); + + await rightClickAt(page, corners[2], 'Gx', -3); + await page.locator('#markerMenu .mk-item').first().click(); + markers = await markerList(page); + expect(markers.map(m => m.snap.split(' · ')[0])).toEqual(['Gx flat-top start', 'Gx flat-top end']); + + const table = page.locator('#mkTable'); + await expect(table).toBeVisible(); + await expect(table.locator('tbody tr')).toHaveCount(2); + const delta = ((corners[2] - corners[1]) * 1e3).toFixed(4); + await expect(table.locator('tbody tr').nth(1).locator('td').nth(2)).toHaveText(delta); + await expect(table.locator('.mk-summary')).toContainText('span ' + delta + ' ms'); + + // Once markers are in use, approaching a corner suggests it. + await hoverAt(page, corners[3], 'Gx', 2); + expect((await markerState(page)).suggestion?.label).toContain('Gx ramp-down end'); +}); + +test('places a marker without snapping, and the menu closes on Escape or an outside click', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + + const prevented = page.evaluate(() => new Promise(done => { + window.addEventListener('contextmenu', e => done(e.defaultPrevented), { once: true }); + })); + await rightClickAt(page, corners[1], 'Gx', 4); + expect(await prevented).toBe(true); + await expect(page.locator('#markerMenu')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.locator('#markerMenu')).toBeHidden(); + + await rightClickAt(page, corners[1], 'Gx', 4); + await page.mouse.click(5, 5); + await expect(page.locator('#markerMenu')).toBeHidden(); + + const pointerTime = await rightClickAt(page, corners[1], 'Gx', 4); + await page.locator('#markerMenu .mk-item', { hasText: 'no snap' }).click(); + const [marker] = await markerList(page); + expect(marker.snap).toBe(''); + expect(Math.abs(marker.t - pointerTime)).toBeLessThan(2 / (await viewState(page)).scale); + expect(Math.abs(marker.t - corners[1])).toBeGreaterThan(1e-7); +}); + +test('draws markers on the overlay, keeps their times across zoom, and clears them for a new file', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + await page.mouse.move(5, 5); + const before = await opaquePixelCount(page.locator('#moc')); + + await rightClickAt(page, corners[1], 'Gx', 3); + await page.locator('#markerMenu .mk-item').first().click(); + await page.mouse.move(5, 5); + await expect.poll(() => opaquePixelCount(page.locator('#moc'))).toBeGreaterThan(before + 200); + + const placed = (await markerList(page))[0].t; + await setView(page, corners[0] - 1e-3, corners[3] + 1e-3); + expect((await markerList(page))[0].t).toBe(placed); + + await page.locator('#fileInput').setInputFiles(epi); + await expect.poll(async () => (await markerList(page)).length).toBe(0); + await expect(page.locator('#mkTable')).toBeHidden(); +}); + +test('removes one marker or all of them, from the menu or the table', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + for (const [i, t] of corners.entries()) { + await rightClickAt(page, t, 'Gx', i === 0 ? 3 : -3); + await page.locator('#markerMenu .mk-item').first().click(); + } + expect(await markerList(page)).toHaveLength(4); + + await rightClickAt(page, corners[1], 'Gx', 0); + await page.locator('#markerMenu .mk-item', { hasText: 'Remove M2' }).click(); + expect((await markerList(page)).map(m => m.id)).toEqual([1, 3, 4]); + + await page.locator('#mkTable tr[data-marker="3"] button').click(); + expect((await markerList(page)).map(m => m.id)).toEqual([1, 4]); + + await rightClickAt(page, corners[1], 'Gx', 0); + await page.locator('#markerMenu .mk-item', { hasText: 'Clear all markers' }).click(); + expect(await markerList(page)).toEqual([]); + await expect(page.locator('#mkTable')).toBeHidden(); +}); + +test('drags a marker without panning, snapping unless Shift is held', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + await rightClickAt(page, corners[1], 'Gx', 0); + await page.locator('#markerMenu .mk-item').first().click(); + const offset = (await viewState(page)).offset; + + const start = await pointFor(page, corners[1], 'Gx', 0); + const target = await pointFor(page, corners[2], 'Gx', -4); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move((start.x + target.x) / 2, target.y, { steps: 4 }); + expect((await markerState(page)).dragging).toBe(true); + await page.mouse.move(target.x, target.y, { steps: 4 }); + await page.mouse.up(); + expect((await viewState(page)).offset).toBe(offset); + let [marker] = await markerList(page); + expect(Math.abs(marker.t - corners[2])).toBeLessThan(1e-12); + expect(marker.snap).toMatch(/^Gx flat-top end( · |$)/); + + const back = await pointFor(page, corners[1], 'Gx', 4); + await page.mouse.move(target.x + 4, target.y); + await page.mouse.down(); + await page.keyboard.down('Shift'); + await page.mouse.move(back.x, back.y, { steps: 6 }); + await page.mouse.up(); + await page.keyboard.up('Shift'); + [marker] = await markerList(page); + expect(marker.snap).toBe(''); + expect(Math.abs(marker.t - corners[1])).toBeGreaterThan(1e-7); + expect((await viewState(page)).offset).toBe(offset); +}); + +test('remembers whether to snap', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + await rightClickAt(page, corners[1], 'Gx', 3); + await page.locator('#markerMenu .mk-check input').first().uncheck(); + await page.keyboard.press('Escape'); + expect(await page.evaluate(() => localStorage.getItem('seqeyes.markers.snap'))).toBe('0'); + + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + await rightClickAt(page, corners[1], 'Gx', 3); + await expect(page.locator('#markerMenu .mk-item').first()).toHaveText(/^Add marker here/); + expect((await markerState(page)).snapEnabled).toBe(false); +}); + +/* ── Helpers ─────────────────────────────────────────────────────────── */ + +async function loadViewer(page: Page, sequencePath: string): Promise { + await page.goto('/?debug=1'); + await page.locator('#fileInput').setInputFiles(sequencePath); + await expect(page.locator('#exportKspaceBtn')).toBeEnabled({ timeout: 60_000 }); + await expect(page.locator('#poverlay')).toBeHidden({ timeout: 10_000 }); +} + +async function setView(page: Page, start: number, end: number): Promise { + await page.evaluate(([s, e]) => (window as unknown as DevWindow).__seqeyesDebug.setView(s, e), [start, end]); +} + +async function viewState(page: Page) { + return await page.evaluate(() => (window as unknown as DevWindow).__seqeyesDebug.state()); +} + +/** Page coordinates of time `t` on a channel's row, `dx` pixels to the right. */ +async function pointFor(page: Page, t: number, channel: string, dx: number): Promise<{ x: number; y: number; t: number }> { + const box = (await page.locator('#mc').boundingBox())!; + const view = await viewState(page); + const top = 8, bottom = 22, left = 92; + const row = view.visibleChannels.indexOf(channel); + const height = (box.height - top - bottom) / view.visibleChannels.length; + const x = left + (t - view.offset) * view.scale + dx; + return { x: box.x + x, y: box.y + top + (row + 0.5) * height, t: view.offset + (x - left) / view.scale }; +} + +async function hoverAt(page: Page, t: number, channel: string, dx: number): Promise { + const p = await pointFor(page, t, channel, dx); + await page.mouse.move(p.x, p.y); + await page.waitForTimeout(50); +} + +/** Right-click there; returns the time under the pointer. */ +async function rightClickAt(page: Page, t: number, channel: string, dx: number): Promise { + const p = await pointFor(page, t, channel, dx); + await page.mouse.click(p.x, p.y, { button: 'right' }); + return p.t; +} + +async function markerList(page: Page): Promise { + return await page.evaluate(() => (window as unknown as DevWindow).SeqEyesDev.markers()); +} + +async function markerState(page: Page) { + return await page.evaluate(() => (window as unknown as DevWindow).SeqEyesDev.markerState()); +} + +async function opaquePixelCount(locator: Locator): Promise { + return await locator.evaluate((element) => { + const canvas = element as HTMLCanvasElement; + const context = canvas.getContext('2d'); + if (!context || !canvas.width || !canvas.height) return 0; + const image = context.getImageData(0, 0, canvas.width, canvas.height).data; + let count = 0; + for (let i = 3; i < image.length; i += 4) if (image[i] > 8) count++; + return count; + }); +} diff --git a/test/browser/vscode-webview.spec.ts b/test/browser/vscode-webview.spec.ts index 948904a..f8803cd 100644 --- a/test/browser/vscode-webview.spec.ts +++ b/test/browser/vscode-webview.spec.ts @@ -765,3 +765,57 @@ test.describe('minimap block cache', () => { expect(failures).toEqual([]); }); }); + +/** + * Measurement markers through the bundle's own renderer, which is the one + * VS Code runs (the standalone page installs its copy over it): right-click + * keeps VS Code's menu away and offers a marker; adding one fills the table. + */ +test('adds a measurement marker from the right-click menu', async ({ page }) => { + const failures: string[] = []; + page.on('pageerror', e => failures.push(e.message)); + page.on('console', m => { if (m.type() === 'error') failures.push(m.text()); }); + const { seq } = loadSequence(); + const packed = packSequenceBlocks(seq); + await openWebview(page); + await post(page, { + type: 'sequenceData', + sequenceGeneration: 1, + blocks: packed.blocks, + sampleCount: packed.sampleCount, + totalDuration: getTotalDuration(seq), + gradRaster: seq.rasterTimes.gradientRaster, + rfRaster: seq.rasterTimes.rfRaster, + adcRaster: seq.rasterTimes.adcRaster, + blockRaster: seq.rasterTimes.blockDurationRaster, + timing: detectSequenceTiming(seq), + notices: [], + }, { sampleTimes: b64(packed.sampleTimes), sampleValues: b64(packed.sampleValues) }); + + const cc = (await page.locator('#cc').boundingBox())!; + const prevented = page.evaluate(() => new Promise(done => { + window.addEventListener('contextmenu', e => done(e.defaultPrevented), { once: true }); + })); + await page.mouse.click(cc.x + cc.width * 0.5, cc.y + cc.height * 0.4, { button: 'right' }); + expect(await prevented).toBe(true); + const items = page.locator('#markerMenu .mk-item'); + await expect(items.first()).toContainText('Add marker'); + await items.first().click(); + + await expect(page.locator('#mkTable tbody tr')).toHaveCount(1); + await expect(page.locator('#mkTable tbody tr td').first()).toHaveText('M1'); + const markers = await page.evaluate(() => + (window as unknown as { SeqEyesDev: { markers(): { t: number }[] } }).SeqEyesDev.markers()); + expect(markers).toHaveLength(1); + expect(markers[0].t).toBeGreaterThan(0); + + // A new sequence clears them. + await post(page, { + type: 'sequenceData', sequenceGeneration: 2, blocks: packed.blocks, sampleCount: packed.sampleCount, + totalDuration: getTotalDuration(seq), gradRaster: seq.rasterTimes.gradientRaster, + rfRaster: seq.rasterTimes.rfRaster, adcRaster: seq.rasterTimes.adcRaster, + blockRaster: seq.rasterTimes.blockDurationRaster, timing: detectSequenceTiming(seq), notices: [], + }, { sampleTimes: b64(packed.sampleTimes), sampleValues: b64(packed.sampleValues) }); + await expect(page.locator('#mkTable')).toBeHidden(); + expect(failures).toEqual([]); +}); diff --git a/test/editor/markers.test.ts b/test/editor/markers.test.ts new file mode 100644 index 0000000..f3b16a1 --- /dev/null +++ b/test/editor/markers.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, it } from 'vitest'; + +import { loadWebviewAssets } from '../pulseq/blockTransportFixtures'; + +/* The measurement-marker core, run from the shipped asset in a bare context: + no DOM, so only the pure functions and the marker list are reachable. */ + +interface Corner { t: number; w: number; name: string } +interface Snap { t: number; kind: string; ci: number; label: string; labels: string[]; text: string } +interface Units { timeConv(t: number): number; timeUnit: string; gradConv(v: number): number; gradUnit: string } +interface Core { + blockIndexAt(blocks: Block[], t: number): number; + trapezoidCorners(g: Grad): Corner[]; + gradientCorners(overview: Grad, detail: Grad | null, lo: number, hi: number): Corner[]; + snapCandidates(blocks: Block[], t: number, tol: number, opts?: object): Snap[]; + snapAt(blocks: Block[], t: number, tol: number, opts?: object): Snap | null; + readoutAt(blocks: Block[], t: number, detail: object | null): Record; + tableRows(list: object[], blocks: Block[], detail: object | null, units: Units): Record[]; + toTsv(rows: object[], units: Units): string; + formatTime(seconds: number, units: Units): string; + formatGradient(value: number, units: Units): string; +} +interface Markers { + core: Core; + add(t: number, snap?: string): { id: number; t: number }; + remove(id: number): void; + clear(): void; + list(): { id: number; t: number; snap: string }[]; +} +interface Grad { ty: string; t: Float64Array; w: Float32Array; a?: number; r?: number } +interface Block { i: number; s: number; d: number; gx?: Grad; gy?: Grad; gz?: Grad; rf?: object; adc?: object; trg?: object[] } + +function load(): Markers { + return loadWebviewAssets<{ SeqEyesMarkers: Markers }>(['block-transport.js', 'markers.js']).SeqEyesMarkers; +} + +const grad = (ty: string, t: number[], w: number[], extra: Partial = {}): Grad => ({ + ty, t: new Float64Array(t), w: new Float32Array(w), a: Math.max(...w.map(Math.abs)), ...extra, +}); + +/** A trapezoid as the decoder writes it: ramp 0.1 ms, flat 0.6 ms, from `start`. */ +const trap = (start: number, amplitude = 1000): Grad => + grad('trap', [start, start + 1e-4, start + 7e-4, start + 8e-4], [0, amplitude, amplitude, 0]); + +const MS: Units = { timeConv: t => t * 1e3, timeUnit: 'ms', gradConv: v => v / 42576, gradUnit: 'mT/m' }; +const names = (corners: Corner[]) => corners.map(c => c.name); + +describe('measurement marker corners', () => { + it('names a trapezoid\'s four corners, skipping the delay anchor', () => { + const { core } = load(); + expect(names(core.trapezoidCorners(trap(0)))).toEqual(['ramp-up start', 'flat-top start', 'flat-top end', 'ramp-down end']); + const delayed = grad('trap', [0, 2e-4, 3e-4, 5e-4, 6e-4], [0, 0, 500, 500, 0]); + const corners = core.trapezoidCorners(delayed); + expect(corners.map(c => c.t)).toEqual([2e-4, 3e-4, 5e-4, 6e-4]); + }); + + it('folds coincident corners into one point', () => { + const { core } = load(); + const triangle = grad('trap', [0, 1e-4, 1e-4, 2e-4], [0, 800, 800, 0]); + expect(names(core.trapezoidCorners(triangle))).toEqual(['ramp-up start', 'peak', 'ramp-down end']); + }); + + it('finds every breakpoint of an extended trapezoid', () => { + const { core } = load(); + const ext = grad('arb', [0, 1e-4, 3e-4, 4e-4, 6e-4], [0, 1000, 1000, 400, 0]); + const corners = core.gradientCorners(ext, null, 0, 6e-4); + expect(corners.map(c => [c.t, c.name])).toEqual([ + [0, 'start'], [1e-4, 'ramp-up end'], [3e-4, 'ramp-down start'], [4e-4, 'slope change'], [6e-4, 'end'], + ]); + }); + + it('finds trapezoid corners in a raster-sampled arbitrary gradient', () => { + const { core } = load(); + // 10 µs raster: 10-sample ramps either side of a 30-sample plateau. + const t: number[] = [], w: number[] = []; + for (let i = 0; i <= 50; i++) { + t.push(i * 1e-5); + w.push(i <= 10 ? i * 100 : i <= 40 ? 1000 : (50 - i) * 100); + } + const corners = core.gradientCorners(grad('arb', t, w), null, 0, 5e-4); + expect(corners.map(c => [Math.round(c.t * 1e6), c.name])).toEqual([ + [0, 'start'], [100, 'ramp-up end'], [400, 'ramp-down start'], [500, 'end'], + ]); + }); + + it('keeps little more than the peaks of a smooth waveform', () => { + const { core } = load(); + const t: number[] = [], w: number[] = []; + for (let i = 0; i <= 400; i++) { t.push(i * 1e-5); w.push(1000 * Math.sin(2 * Math.PI * i / 400)); } + const corners = core.gradientCorners(grad('arb', t, w), null, 0, 4e-3).filter(c => c.name !== 'start' && c.name !== 'end'); + // Within a sample of each extreme: Float32 values there are flat to rounding. + const peaks = corners.filter(c => c.name === 'peak').map(c => Math.round(c.t * 1e5)); + expect(peaks).toHaveLength(2); + expect(Math.abs(peaks[0] - 100)).toBeLessThanOrEqual(1); + expect(Math.abs(peaks[1] - 300)).toBeLessThanOrEqual(1); + // Bends near each peak may also qualify, but never a run of them. + expect(corners.length).toBeLessThanOrEqual(6); + }); + + it('offers only the ends of a waveform the overview reduced', () => { + const { core } = load(); + const reduced = grad('arb', [0, 1e-4, 3e-4, 4e-4, 6e-4], [0, 1000, 1000, 400, 0], { r: 1 }); + expect(names(core.gradientCorners(reduced, null, 0, 6e-4))).toEqual(['start', 'end']); + // Exact detail covering the window restores the interior. + const detail = grad('arb', [0, 1e-4, 3e-4, 4e-4, 6e-4], [0, 1000, 1000, 400, 0]); + expect(core.gradientCorners(reduced, detail, 0, 6e-4)).toHaveLength(5); + }); +}); + +describe('measurement marker snapping', () => { + const blocks = (): Block[] => [ + { i: 1, s: 0, d: 1e-3, gx: trap(1e-4), adc: { s: 0, d: 2e-4, n: 100, dw: 5e-6 } }, + { i: 2, s: 1e-3, d: 1e-3, gy: trap(1e-3) }, + ]; + + it('pulls the pointer onto the nearest corner and names it', () => { + const { core } = load(); + const snap = core.snapAt(blocks(), 2.03e-4, 1e-5)!; + expect(snap.t).toBeCloseTo(2e-4, 12); + expect(snap.label).toBe('Gx flat-top start'); + expect(snap.kind).toBe('corner'); + }); + + it('prefers a corner to a block boundary at the same instant, and names both', () => { + const { core } = load(); + const snap = core.snapAt(blocks(), 1.0001e-3, 1e-5)!; + expect(snap.t).toBe(1e-3); + expect(snap.label).toBe('Gy ramp-up start'); + expect(snap.labels).toContain('block #1/#2'); + }); + + it('snaps to ADC edges and centre', () => { + const { core } = load(); + expect(core.snapAt(blocks(), 4.49e-4, 5e-6)!.label).toBe('ADC centre'); + expect(core.snapAt(blocks(), 7.01e-4, 5e-6)!.label).toBe('ADC end'); + }); + + it('offers nothing from a hidden row, and nothing beyond the tolerance', () => { + const { core } = load(); + const hidden = core.snapAt(blocks(), 2.03e-4, 1e-5, { rows: [0, 1, 3, 4, 5, 6] }); + expect(hidden?.label ?? null).not.toBe('Gx flat-top start'); + expect(core.snapAt(blocks(), 5e-4, 1e-5)).toBeNull(); + }); + + it('refuses to snap when the tolerance spans too many blocks', () => { + const { core } = load(); + const many: Block[] = []; + for (let i = 0; i < 100; i++) many.push({ i: i + 1, s: i * 1e-6, d: 1e-6 }); + expect(core.snapCandidates(many, 5e-5, 5e-5)).toEqual([]); + }); +}); + +describe('measurement marker readout', () => { + it('reads every channel at the marker, marking reduced samples as approximate', () => { + const { core } = load(); + const blocks: Block[] = [ + { i: 7, s: 0, d: 1e-3, gx: trap(1e-4, 2000), gy: grad('arb', [0, 1e-3], [0, 1000], { r: 1 }), + adc: { s: 0, d: 2e-4, n: 100, dw: 5e-6 }, trg: [{ s: 0, d: 0, dr: 1e-4 }] }, + ]; + const r = core.readoutAt(blocks, 1.5e-4, null); + expect(r.block).toBe(7); + expect(r.gx).toBeCloseTo(1000, 3); + expect(r.gy).toBeCloseTo(150, 3); + expect(r.gz).toBe(0); + expect(r.approx).toEqual({ gy: true }); + expect(r.adc).toBeNull(); + expect(r.trigger).toBe(false); + const inAdc = core.readoutAt(blocks, 2.5e-4, null); + expect(inAdc.adc).toEqual({ sample: 10, count: 100 }); + }); + + it('reads exact detail instead of a reduced overview where it covers the time', () => { + const { core } = load(); + const blocks: Block[] = [{ i: 1, s: 0, d: 1e-3, gx: grad('arb', [0, 1e-3], [0, 0], { r: 1 }) }]; + const detail = { startBlock: 0, endBlock: 1, startSec: 0, endSec: 1e-3, blocks: [{ gx: grad('arb', [0, 5e-4, 1e-3], [0, 900, 0]) }] }; + const r = core.readoutAt(blocks, 5e-4, detail); + expect(r.gx).toBeCloseTo(900, 3); + expect(r.approx).toEqual({}); + }); + + it('gives a block boundary to the block that starts there, unless that block is empty', () => { + const { core } = load(); + const blocks: Block[] = [ + { i: 1, s: 0, d: 1e-3 }, { i: 2, s: 1e-3, d: 0 }, { i: 3, s: 1e-3, d: 1e-3 }, { i: 4, s: 2e-3, d: 0 }, + ]; + expect(core.blockIndexAt(blocks, 1e-3)).toBe(2); + expect(core.blockIndexAt(blocks, 2e-3)).toBe(2); + expect(core.blockIndexAt(blocks, 3e-3)).toBe(-1); + }); +}); + +describe('measurement marker list and table', () => { + it('keeps markers in time order with ids that do not repeat until cleared', () => { + const markers = load(); + markers.add(3e-3); + markers.add(1e-3); + const third = markers.add(2e-3); + expect(markers.list().map(m => m.id)).toEqual([2, 3, 1]); + markers.remove(third.id); + expect(markers.add(4e-3).id).toBe(3); + markers.clear(); + expect(markers.list()).toEqual([]); + expect(markers.add(1e-3).id).toBe(1); + }); + + it('tabulates Δt and gradients in the viewer\'s units', () => { + const { core } = load(); + const blocks: Block[] = [{ i: 1, s: 0, d: 1e-3, gx: trap(1e-4, 42576) }]; + const rows = core.tableRows([{ id: 1, t: 1e-4, snap: 'Gx ramp-up start' }, { id: 2, t: 2e-4, snap: '' }], blocks, null, MS); + expect(rows[0]).toMatchObject({ name: 'M1', time: '0.1000', delta: '', block: '#1', gx: '0.00', snap: 'Gx ramp-up start' }); + expect(rows[1]).toMatchObject({ name: 'M2', time: '0.2000', delta: '0.1000', gx: '1.00' }); + const tsv = core.toTsv(rows, MS).split('\n'); + expect(tsv[0].split('\t').slice(0, 6)).toEqual(['Marker', 'Time (ms)', 'Δt (ms)', 'Block', 'In block (ms)', 'Gx (mT/m)']); + expect(tsv).toHaveLength(3); + }); + + it('formats times to 0.1 µs and never prints a negative zero', () => { + const { core } = load(); + expect(core.formatTime(1.23456789e-3, MS)).toBe('1.2346'); + expect(core.formatTime(1.23456789e-3, { ...MS, timeConv: t => t * 1e6, timeUnit: 'us' })).toBe('1234.6'); + expect(core.formatGradient(-1e-6, MS)).toBe('0.00'); + }); +}); diff --git a/web/index.html b/web/index.html index 1dbb26b..dc4da70 100644 --- a/web/index.html +++ b/web/index.html @@ -832,7 +832,7 @@

SeqEyes

showProgress('decode',15,'Preparing blocks in bounded batches...'); var packed=Pulseq.packSequenceBlocks(seq); - resetWaveformDetail(); + resetWaveformDetail();SeqEyesMarkers.reset(); BL=unpackSequenceBlocks(packed.blocks,packed.sampleTimes,packed.sampleValues,packed.sampleCount); decodedBlocks=null; decodeContext=Pulseq.createSequenceDecodeContext(seq); @@ -1573,6 +1573,7 @@

SeqEyes

var dpr=window.devicePixelRatio||1,w=moc.width/dpr,h=moc.height/dpr; moctx.clearRect(0,0,w,h); drawPanelMarker(w,h); + if(typeof SeqEyesMarkers!=='undefined')SeqEyesMarkers.drawOverlay(moctx,w,h); if(!cursorActive)return;var cx=t2x(cursorT); if(cxw-M.r)return; var color=getComputedStyle(document.body).getPropertyValue('--cr').trim(); @@ -3013,6 +3014,14 @@

SeqEyes

SeqEyesPanel.install(window.SeqEyesPanelHost); SeqEyesPrefsUi.install(); +/* Over the bundle's install: markers must read this page's BL and view, not + the bundle's empty copies. */ +SeqEyesMarkers.install({ + blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, + t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, + timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, + requestOverlay:drawCursorOverlay +}); /* Re-apply the ASC profile cached from an earlier session. Only the display side runs here: there is no sequence open yet, so PNS waits for diff --git a/web/styles.css b/web/styles.css index 904fc84..ee1b713 100644 --- a/web/styles.css +++ b/web/styles.css @@ -275,3 +275,35 @@ body.layout-vertical.sg-split-drag{cursor:col-resize} .lblc-swatches{gap:6px;padding-left:0} .lblc-foot button{min-height:34px;flex:1} } +/* ── Measurement markers (markers.js) ───────────────────────────────── */ +#cc.mk-hover,#cc.mk-drag{cursor:ew-resize} +#cc.mk-drag #tt,#cc.mk-menu-open #tt{display:none!important} +.mk-menu{min-width:240px;padding:4px 0} +.mk-menu .mk-item{display:flex;align-items:center;gap:16px;width:100%;padding:5px 12px;background:none;border:0;border-radius:0;color:var(--fg);font-size:11px;text-align:left;cursor:pointer} +.mk-menu .mk-item:hover,.mk-menu .mk-item:focus-visible,.mk-menu .mk-item:focus-within{background:var(--gr);opacity:1;outline:none} +.mk-item-label{flex:1} +.mk-item-detail{font:10px monospace;color:var(--lb)} +.mk-menu .mk-check{gap:8px} +.mk-check input{margin:0;cursor:pointer} +.mk-sep{height:1px;background:var(--gr);margin:4px 0} +.mk-table{flex-shrink:0;max-height:34%;display:flex;flex-direction:column;border-top:1px solid var(--gr);background:var(--trbg);font-size:11px} +.mk-table[hidden]{display:none} +.mk-head{display:flex;align-items:center;gap:4px 10px;padding:3px 8px;flex-wrap:wrap} +.mk-title{font-weight:600} +.mk-summary{color:var(--lb);font:10px monospace} +.mk-note{color:var(--lb);font-size:10px} +.mk-actions{margin-left:auto;display:flex;gap:4px} +.mk-table button{background:var(--gr);border:1px solid var(--ax);color:var(--fg);border-radius:3px;font-size:10px;padding:1px 6px;cursor:pointer} +.mk-table button:hover{opacity:.75} +.mk-scroll{overflow:auto;min-height:0} +.mk-table table{border-collapse:collapse;font:10px monospace;white-space:nowrap} +.mk-table th{position:sticky;top:0;background:var(--trbg);text-align:right;font-weight:600;color:var(--lb);padding:2px 8px;border-bottom:1px solid var(--gr)} +.mk-table td{text-align:right;padding:1px 8px} +.mk-table th:first-child,.mk-table td.mk-name,.mk-table td:nth-last-child(2){text-align:left} +.mk-table tbody tr:nth-child(even){background:rgba(127,127,127,.06)} +.mk-table td button{padding:0 5px} +@media(max-width:768px),(pointer:coarse){ + .mk-menu .mk-item{padding:10px 14px;font-size:13px} + .mk-table{max-height:40%} + .mk-table button{min-height:28px;padding:2px 10px} +} diff --git a/web/webview-bundle.js b/web/webview-bundle.js index 0d22f85..fb2d3b8 100644 --- a/web/webview-bundle.js +++ b/web/webview-bundle.js @@ -39,6 +39,8 @@ var SeqEyesPrefs = (function () { kspaceUnit: 'seqeyes.kspace.unit', kspaceDotSize: 'seqeyes.kspace.dotSize', kspaceProjection: 'seqeyes.kspace.projection', + markerSnap: 'seqeyes.markers.snap', + markerTable: 'seqeyes.markers.table', ascName: 'seqeyes.asc.name', ascText: 'seqeyes.asc.text' }; @@ -1368,7 +1370,7 @@ function applySerializedKspace(payload){ much as the message: the progress overlay reaches "Ready" either way, so leaving stale blocks on screen would read as a successful load. */ function showSequenceLoadFailure(message){ - BL=[];waveformOverview=null;blockPos=[];mmCache=null;resetWaveformDetail(); + BL=[];waveformOverview=null;blockPos=[];mmCache=null;resetWaveformDetail();SeqEyesMarkers.reset(); labelInfo={names:[],kinds:[]};labelTable=null;labelBusy=false;chVis[11]=false;SeqEyesLabels.closeControls(false);buildLegend(); setViewerNotice('sequence',message); setExportButtonEnabled(false); @@ -1397,7 +1399,7 @@ window.addEventListener('message',function(e){ return; } if(m.type==='sequenceData'){ - resetWaveformDetail(m.sequenceGeneration); + resetWaveformDetail(m.sequenceGeneration);SeqEyesMarkers.reset(); try{ BL=unpackSequenceBlocks(m.blocks,m.sampleTimes,m.sampleValues,m.sampleCount||0); }catch(err){ @@ -2130,9 +2132,9 @@ window.SeqEyesPanelHost={ message.endSec=endSec; vscApi.postMessage(message); }, - /* Simulation: only inside VS Code, where the extension answers these. The - Python viewer runs this bundle too, with no host to ask, so it keeps the - Simulation button hidden. */ + /* Simulation: only inside VS Code, where the extension answers these. Any + page that loads this bundle without a VS Code host keeps the Simulation + button hidden. (The Python viewer has its own renderer and does not.) */ createSimulationWorker:vscApi?createSimulationWorkerStandIn:undefined, getSequenceSource:vscApi?simulationSequenceSource:undefined, getSequenceSourceStatus:vscApi?simulationSequenceStatus:undefined, @@ -2603,6 +2605,7 @@ function drawCursorOverlay(){ var dpr=window.devicePixelRatio||1,w=moc.width/dpr,h=moc.height/dpr; moctx.clearRect(0,0,w,h); drawPanelMarker(w,h); + if(typeof SeqEyesMarkers!=='undefined')SeqEyesMarkers.drawOverlay(moctx,w,h); if(!cursorActive)return;var cx=t2x(cursorT); if(cxw-M.r)return; var color=getComputedStyle(document.body).getPropertyValue('--cr').trim(); @@ -9980,7 +9983,8 @@ var SeqEyesPrefsUi = (function () { var note = element('div', 'prefs-note'); note.appendChild(element('div', null, 'Theme, time and gradient units, the Blocks toggle, k-space and ' - + 'spectrogram options, and panel sizes are kept between sessions.')); + + 'spectrogram options, marker snapping, and panel sizes are kept ' + + 'between sessions.')); note.appendChild(element('div', null, inVsCode() /* Different sentences because the two hosts really do keep different things: a path the extension re-reads, versus the file's text. */ @@ -10090,6 +10094,1054 @@ var SeqEyesPrefsUi = (function () { })(); +/* ══ markers.js ══ */ +/* ═══════════════════════════════════════════════════════════════════════ + Measurement markers + ═══════════════════════════════════════════════════════════════════════ + + Right-click the waveform viewer to drop a vertical marker. Each marker + reads out its time, its block and every channel's value where it crosses, + and Δt to its neighbour. Placement snaps to gradient corners, RF and ADC + edges and centres, and block boundaries. + + Two renderers draw this viewer: the bundle (VS Code) and web/index.html's + own copy inside its IIFE (web app, preview, MATLAB). Both install this + module with accessors to their own state. The last install wins and the + DOM is wired once, which is the pattern prefs-ui.js and panel.js use. + + The core takes everything it reads as arguments, so it runs in node:vm for + the unit tests; only install() touches the DOM. */ + +var SeqEyesMarkers = (function () { + /* Pointer distances in CSS pixels: how close a corner must be to pull a + marker onto it, how close a press must be to grab a marker, and how close + a right-click must be to offer removing one. */ + var SNAP_PX = 8; + var HIT_PX = 4; + var REMOVE_PX = 6; + /* More blocks than this inside the snap distance means the view is too + zoomed out for a corner to be a meaningful target. */ + var MAX_SNAP_BLOCKS = 32; + /* Interior corners of an arbitrary waveform are only searched in a slice + this small, so a hover never walks a whole readout. */ + var MAX_CORNER_SAMPLES = 512; + /* Candidates closer than this are one point with several names. */ + var MERGE_SEC = 1e-9; + + var AXES = ['gx', 'gy', 'gz']; + var AXIS_NAMES = { gx: 'Gx', gy: 'Gy', gz: 'Gz' }; + var AXIS_ROW = { gx: 2, gy: 3, gz: 4 }; + var ROW_COLOURS = { 0: '--rf', 1: '--rf', 2: '--gx', 3: '--gy', 4: '--gz', 5: '--adc', 6: '--tr' }; + var KIND_RANK = { corner: 0, event: 1, block: 2 }; + var TRAP_NAMES = ['ramp-up start', 'flat-top start', 'flat-top end', 'ramp-down end']; + + /* ── Core: lookups ─────────────────────────────────────────────────── */ + + /** First block whose end (s + d) is at or after `t`. */ + function firstBlockEndingAfter(blocks, t) { + var lo = 0, hi = blocks.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (blocks[mid].s + blocks[mid].d < t) lo = mid + 1; else hi = mid; + } + return lo; + } + + /** + * Index of the block that holds `t`, or -1 outside the sequence. A time on + * a boundary belongs to the block that starts there, except that a + * zero-duration block (labels, soft delays) hands it back to the block that + * ends there, which is the one with waveforms. + */ + function blockIndexAt(blocks, t) { + if (!blocks || !blocks.length || !(t >= blocks[0].s)) return -1; + var lo = 0, hi = blocks.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (blocks[mid].s <= t) lo = mid + 1; else hi = mid; + } + var i = lo - 1; + while (i > 0 && !(blocks[i].d > 0) && blocks[i - 1].s + blocks[i - 1].d >= t) i--; + var block = blocks[i]; + return t <= block.s + block.d + 1e-12 ? i : -1; + } + + /** Linear interpolation, 0 outside the waveform (the tooltip's convention). */ + function sampleAt(times, values, t) { + var n = Math.min(times.length, values.length); + if (!n || t < times[0] || t > times[n - 1]) return 0; + var lo = 0, hi = n - 1; + while (hi - lo > 1) { + var mid = (lo + hi) >> 1; + if (times[mid] <= t) lo = mid; else hi = mid; + } + var dt = times[hi] - times[lo]; + if (!(dt > 0)) return values[hi]; + return values[lo] + (values[hi] - values[lo]) * (t - times[lo]) / dt; + } + + /** The sample nearest `t`; for wrapped phase, where interpolating is wrong. */ + function nearestAt(times, values, t) { + var n = Math.min(times.length, values.length); + if (!n) return NaN; + var lo = 0, hi = n - 1; + while (hi - lo > 1) { + var mid = (lo + hi) >> 1; + if (times[mid] <= t) lo = mid; else hi = mid; + } + return Math.abs(times[hi] - t) < Math.abs(t - times[lo]) ? values[hi] : values[lo]; + } + + function lowerIndex(times, n, t) { + var lo = 0, hi = n; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (times[mid] < t) lo = mid + 1; else hi = mid; + } + return lo; + } + + /** + * The detail block for `bi`, when the held detail covers [lo, hi]. + * + * Not blockAt(): that answers for the view being drawn, and its arrays are + * clipped to that view, so a marker scrolled off screen would read zero. + */ + function detailBlock(detail, bi, lo, hi) { + if (!detail || !detail.blocks || bi < detail.startBlock || bi >= detail.endBlock) return null; + if (detail.startSec > lo || detail.endSec < hi) return null; + return detail.blocks[bi - detail.startBlock] || null; + } + + /** Detail the renderer currently holds for this sequence, or null. */ + function liveDetail() { + if (typeof waveformDetail === 'undefined' || !waveformDetail) return null; + if (typeof waveformDetailGeneration !== 'undefined' && waveformDetail.generation !== waveformDetailGeneration) return null; + return waveformDetail; + } + + /* ── Core: corners ─────────────────────────────────────────────────── */ + + /** Coincident corners are one point; name it for what it is. */ + function mergeCoincident(corners) { + var out = []; + for (var i = 0; i < corners.length; i++) { + var c = corners[i], last = out[out.length - 1]; + if (last && Math.abs(c.t - last.t) <= MERGE_SEC) { + if (last.name === 'flat-top start' && c.name === 'flat-top end') last.name = 'peak'; + else if (last.name === 'ramp-up start' && c.name === 'flat-top start') last.name = 'flat-top start'; + else if (last.name === 'flat-top end' && c.name === 'ramp-down end') last.name = 'flat-top end'; + else if (last.name !== c.name) last.name += ' / ' + c.name; + continue; + } + out.push({ t: c.t, w: c.w, name: c.name }); + } + return out; + } + + /** + * A trapezoid's four corners. The decoder writes exactly these points, plus + * a leading zero at the block start when the gradient is delayed, and the + * overview never reduces a waveform this short, so they are exact. + */ + function trapezoidCorners(g) { + var n = Math.min(g.t.length, g.w.length), first = n === 5 ? 1 : 0; + if (n - first !== 4) return endpointCorners(g); + var corners = []; + for (var k = 0; k < 4; k++) corners.push({ t: g.t[first + k], w: g.w[first + k], name: TRAP_NAMES[k] }); + return mergeCoincident(corners); + } + + /** First and last sample: exact even after reduction, which keeps both. */ + function endpointCorners(g) { + var n = Math.min(g.t.length, g.w.length); + if (!n) return []; + return n === 1 + ? [{ t: g.t[0], w: g.w[0], name: 'start' }] + : [{ t: g.t[0], w: g.w[0], name: 'start' }, { t: g.t[n - 1], w: g.w[n - 1], name: 'end' }]; + } + + /** + * Douglas–Peucker on samples i0..i1: the indices a polyline within `eps` + * (vertically) of every sample needs. Iterative, so a long slice cannot + * overflow the stack. + */ + function simplify(t, w, i0, i1, eps) { + var keep = [i0, i1], stack = [i0, i1]; + while (stack.length) { + var b = stack.pop(), a = stack.pop(); + if (b - a < 2) continue; + var ta = t[a], wa = w[a], span = t[b] - ta, slope = span > 0 ? (w[b] - wa) / span : 0; + var worst = -1, at = -1; + for (var k = a + 1; k < b; k++) { + var deviation = Math.abs(w[k] - (wa + slope * (t[k] - ta))); + if (deviation > worst) { worst = deviation; at = k; } + } + if (worst > eps) { keep.push(at); stack.push(a, at, at, b); } + } + keep.sort(function (x, y) { return x - y; }); + return keep; + } + + /** + * Corners inside an arbitrary or extended-trapezoid waveform near [lo, hi]. + * + * Both arrive as 'arb', so breakpoints cannot be told from raster samples. + * The shape is simplified to a polyline within 0.5 % of the waveform's + * scale, and a vertex is a corner where the line goes flat↔ramp, reverses + * (a peak), steps, or changes slope by at least half. That finds every + * breakpoint of an extended trapezoid and the trapezoid-like corners of a + * raster-sampled one, while a smooth spiral keeps little more than its + * peaks. + */ + function interiorCorners(g, lo, hi, amplitude) { + var n = Math.min(g.t.length, g.w.length); + if (n < 3) return []; + var i0 = Math.max(0, lowerIndex(g.t, n, lo) - 1); + var i1 = Math.min(n - 1, lowerIndex(g.t, n, hi)); + if (i1 - i0 < 2 || i1 - i0 + 1 > MAX_CORNER_SAMPLES) return []; + var scale = Math.abs(amplitude) || 0; + for (var i = i0; i <= i1; i++) scale = Math.max(scale, Math.abs(g.w[i])); + if (!(scale > 0)) return []; + var eps = 0.005 * scale, keep = simplify(g.t, g.w, i0, i1, eps), out = []; + for (var j = 1; j < keep.length - 1; j++) { + var p = keep[j - 1], k = keep[j], q = keep[j + 1]; + var d1 = g.w[k] - g.w[p], d2 = g.w[q] - g.w[k], dt1 = g.t[k] - g.t[p], dt2 = g.t[q] - g.t[k]; + var name = null; + if (!(dt1 > 0) || !(dt2 > 0)) { + if (Math.abs(!(dt1 > 0) ? d1 : d2) > 0.02 * scale) name = 'step'; + } else { + var flat1 = Math.abs(d1) <= eps, flat2 = Math.abs(d2) <= eps; + if (flat1 && flat2) continue; + if (flat1) name = Math.abs(g.w[q]) > Math.abs(g.w[k]) ? 'ramp-up start' : 'ramp-down start'; + else if (flat2) name = Math.abs(g.w[k]) > Math.abs(g.w[p]) ? 'ramp-up end' : 'ramp-down end'; + else { + var s1 = d1 / dt1, s2 = d2 / dt2; + if (s1 * s2 < 0) name = 'peak'; + else if (Math.abs(s2 - s1) >= 0.5 * Math.max(Math.abs(s1), Math.abs(s2))) name = 'slope change'; + } + } + if (name) out.push({ t: g.t[k], w: g.w[k], name: name }); + } + return out; + } + + /** + * Corners of one gradient near [lo, hi]. Trapezoids come from the overview, + * which always has them whole. An arbitrary waveform's interior corners + * come from exact detail when it covers the window, otherwise from the + * overview unless the overview was reduced; a reduced waveform only offers + * its ends. + */ + function gradientCorners(overview, detail, lo, hi) { + if (overview.ty === 'trap') return trapezoidCorners(overview); + var corners = endpointCorners(overview); + var source = detail && detail.t && !detail.r ? detail : (!overview.r ? overview : null); + if (source) corners = corners.concat(interiorCorners(source, lo, hi, overview.a)); + corners.sort(function (a, b) { return a.t - b.t; }); + return mergeCoincident(corners); + } + + /* ── Core: snapping ────────────────────────────────────────────────── */ + + function blockLabel(blocks, bi) { + return bi > 0 ? 'block #' + blocks[bi - 1].i + '/#' + blocks[bi].i : 'block #' + blocks[bi].i + ' start'; + } + + /** + * Every snap target within `tol` seconds of `t`. + * + * opts.rows: visible channel indices; a channel whose row is hidden offers + * no corners. Block boundaries are always offered. opts.detail: the held + * waveform detail, or null. + */ + function snapCandidates(blocks, t, tol, opts) { + var out = []; + if (!blocks || !blocks.length || !(tol > 0)) return out; + opts = opts || {}; + var rows = opts.rows || [0, 1, 2, 3, 4, 5, 6], shown = {}; + for (var r = 0; r < rows.length; r++) shown[rows[r]] = true; + var lo = t - tol, hi = t + tol, count = 0; + for (var bi = firstBlockEndingAfter(blocks, lo); bi < blocks.length && blocks[bi].s <= hi; bi++) { + if (++count > MAX_SNAP_BLOCKS) return []; + var b = blocks[bi]; + out.push({ t: b.s, kind: 'block', ci: -1, value: 0, label: blockLabel(blocks, bi) }); + if (bi === blocks.length - 1) out.push({ t: b.s + b.d, kind: 'block', ci: -1, value: 0, label: 'block #' + b.i + ' end' }); + for (var a = 0; a < AXES.length; a++) { + var axis = AXES[a], g = b[axis]; + if (!shown[AXIS_ROW[axis]] || !g || g.ty === 'none' || !g.t || !g.t.length) continue; + if (g.t[g.t.length - 1] < lo || g.t[0] > hi) continue; + var detail = detailBlock(opts.detail, bi, lo, hi); + var corners = gradientCorners(g, detail && detail[axis], lo, hi); + for (var c = 0; c < corners.length; c++) { + out.push({ t: corners[c].t, kind: 'corner', ci: AXIS_ROW[axis], value: corners[c].w, label: AXIS_NAMES[axis] + ' ' + corners[c].name }); + } + } + var rf = b.rf; + if (rf && (shown[0] || shown[1])) { + var rfValue = function (time) { return rf.t && rf.m ? sampleAt(rf.t, rf.m, time) : 0; }; + out.push({ t: rf.s, kind: 'event', ci: 0, value: 0, label: 'RF start' }); + if (isFinite(rf.c)) out.push({ t: rf.c, kind: 'event', ci: 0, value: rfValue(rf.c), label: 'RF centre' }); + out.push({ t: rf.s + rf.d, kind: 'event', ci: 0, value: 0, label: 'RF end' }); + } + var adc = b.adc; + if (adc && shown[5] && adc.n > 0) { + var start = adc.s + (adc.d || 0), span = adc.n * adc.dw; + out.push({ t: start, kind: 'event', ci: 5, value: 0, label: 'ADC start' }); + out.push({ t: start + span / 2, kind: 'event', ci: 5, value: 0, label: 'ADC centre' }); + out.push({ t: start + span, kind: 'event', ci: 5, value: 0, label: 'ADC end' }); + } + if (b.trg && shown[6]) { + for (var g2 = 0; g2 < b.trg.length; g2++) { + var tg = b.trg[g2]; + out.push({ t: tg.s + (tg.d || 0), kind: 'event', ci: 6, value: 0, label: 'trigger start' }); + } + } + } + return out.filter(function (candidate) { return candidate.t >= lo && candidate.t <= hi; }); + } + + function rank(candidate, pointerCi) { + var own = candidate.kind === 'corner' && candidate.ci === pointerCi ? 0 : 1; + return own * 10 + KIND_RANK[candidate.kind]; + } + + /** + * The candidate to snap to: the nearest, except that within `onePx` seconds + * a corner on the pointer's own row beats other corners, which beat event + * edges, which beat block boundaries. Everything at the same instant is + * folded into its label, e.g. "Gx ramp-down end · block #12/#13". + */ + function chooseSnap(candidates, t, onePx, pointerCi) { + var best = null, bestDistance = Infinity; + for (var i = 0; i < candidates.length; i++) { + var c = candidates[i], distance = Math.abs(c.t - t); + if (!best || distance < bestDistance - onePx) { best = c; bestDistance = distance; continue; } + if (distance > bestDistance + onePx) continue; + var difference = rank(c, pointerCi) - rank(best, pointerCi); + if (difference < 0 || (difference === 0 && distance < bestDistance)) { best = c; bestDistance = distance; } + } + if (!best) return null; + var same = candidates.filter(function (c) { return Math.abs(c.t - best.t) <= MERGE_SEC; }); + same.sort(function (a, b) { return rank(a, pointerCi) - rank(b, pointerCi); }); + var labels = [best.label]; + for (var j = 0; j < same.length; j++) if (labels.indexOf(same[j].label) < 0) labels.push(same[j].label); + var text = labels.length > 3 ? labels.slice(0, 3).join(' · ') + ' +' + (labels.length - 3) : labels.join(' · '); + return { t: best.t, kind: best.kind, ci: best.ci, value: best.value, label: best.label, labels: labels, text: text }; + } + + function snapAt(blocks, t, tol, opts) { + opts = opts || {}; + return chooseSnap(snapCandidates(blocks, t, tol, opts), t, opts.onePx || tol / SNAP_PX, opts.pointerCi); + } + + /* ── Core: readout ─────────────────────────────────────────────────── */ + + /** + * Every channel's value at `t`. Gradients are in Hz/m; `approx` names the + * channels read from a reduced overview, where the samples either side of + * `t` may not be adjacent. + */ + function readoutAt(blocks, t, detail) { + var out = { t: t, index: -1, block: -1, offset: NaN, gx: 0, gy: 0, gz: 0, approx: {}, rf: null, adc: null, trigger: false }; + var bi = blockIndexAt(blocks, t); + if (bi < 0) return out; + var b = blocks[bi], d = detailBlock(detail, bi, t, t); + out.index = bi; out.block = b.i; out.offset = t - b.s; + for (var a = 0; a < AXES.length; a++) { + var axis = AXES[a], g = b[axis]; + if (!g || g.ty === 'none' || !g.t || !g.w) continue; + var exact = d && d[axis] && g.ty !== 'trap' ? d[axis] : null; + var source = exact && exact.t && exact.t.length && exact.t[0] <= t && exact.t[exact.t.length - 1] >= t ? exact : g; + out[axis] = sampleAt(source.t, source.w, t); + if (source.r && t >= g.t[0] && t <= g.t[g.t.length - 1]) out.approx[axis] = true; + } + var rf = b.rf; + if (rf && t >= rf.s && t <= rf.s + rf.d && rf.t && rf.m) { + var rfSource = d && d.rf && d.rf.t && d.rf.t.length && d.rf.t[0] <= t && d.rf.t[d.rf.t.length - 1] >= t ? d.rf : rf; + out.rf = { + amplitude: sampleAt(rfSource.t, rfSource.m, t), + phase: rfSource.pt && rfSource.p ? nearestAt(rfSource.pt, rfSource.p, t) : NaN, + approx: !!rfSource.r + }; + } + var adc = b.adc; + if (adc && adc.n > 0) { + var start = adc.s + (adc.d || 0), end = start + adc.n * adc.dw; + if (t >= start && t <= end) { + // The tolerance keeps a time exactly on a sample edge (as snapping + // places it) from rounding down into the previous sample. + var sample = Math.floor((t - start) / adc.dw + 1e-6); + out.adc = { sample: Math.max(0, Math.min(adc.n - 1, sample)), count: adc.n }; + } + } + if (b.trg) { + for (var i = 0; i < b.trg.length; i++) { + var tg = b.trg[i], from = tg.s + (tg.d || 0); + if (t >= from && t <= from + (tg.dr || 0)) out.trigger = true; + } + } + return out; + } + + /* ── Core: formatting ──────────────────────────────────────────────── */ + + /* Digits that resolve 0.1 µs, the finest raster Pulseq uses (ADC dwell). */ + var TIME_DIGITS = { s: 7, ms: 4, us: 1 }; + var GRAD_DIGITS = { 'Hz/m': 0, 'mT/m': 2, 'G/cm': 3 }; + + function unitName(unit) { return unit === 'us' ? 'µs' : unit; } + + function formatTime(seconds, units) { + var digits = TIME_DIGITS[units.timeUnit]; + return units.timeConv(seconds).toFixed(digits === undefined ? 4 : digits); + } + + function formatGradient(hzPerM, units) { + var digits = GRAD_DIGITS[units.gradUnit]; + var text = units.gradConv(hzPerM).toFixed(digits === undefined ? 2 : digits); + return /^-0(\.0*)?$/.test(text) ? text.slice(1) : text; + } + + /** + * One row per marker, in time order, with everything formatted in the + * viewer's current units. `list` is [{id, t, snap}]. + */ + function tableRows(list, blocks, detail, units) { + var rows = []; + for (var i = 0; i < list.length; i++) { + var m = list[i], r = readoutAt(blocks, m.t, detail), previous = i > 0 ? list[i - 1] : null; + rows.push({ + id: m.id, + name: 'M' + m.id, + time: formatTime(m.t, units), + delta: previous ? formatTime(m.t - previous.t, units) : '', + block: r.block >= 0 ? '#' + r.block : '', + offset: r.block >= 0 ? formatTime(r.offset, units) : '', + gx: (r.approx.gx ? '≈' : '') + formatGradient(r.gx, units), + gy: (r.approx.gy ? '≈' : '') + formatGradient(r.gy, units), + gz: (r.approx.gz ? '≈' : '') + formatGradient(r.gz, units), + rf: r.rf ? (r.rf.approx ? '≈' : '') + r.rf.amplitude.toFixed(1) : '', + phase: r.rf && isFinite(r.rf.phase) ? (r.rf.phase * 180 / Math.PI).toFixed(1) : '', + adc: r.adc ? (r.adc.sample + 1) + '/' + r.adc.count : '', + trigger: r.trigger ? 'on' : '', + snap: m.snap || '', + approx: !!(r.approx.gx || r.approx.gy || r.approx.gz || (r.rf && r.rf.approx)) + }); + } + return rows; + } + + function columns(units) { + var t = unitName(units.timeUnit), g = units.gradUnit; + return [ + ['name', 'Marker'], ['time', 'Time (' + t + ')'], ['delta', 'Δt (' + t + ')'], + ['block', 'Block'], ['offset', 'In block (' + t + ')'], + ['gx', 'Gx (' + g + ')'], ['gy', 'Gy (' + g + ')'], ['gz', 'Gz (' + g + ')'], + ['rf', 'RF (Hz)'], ['phase', 'RF phase (°)'], ['adc', 'ADC sample'], ['trigger', 'Trigger'], + ['snap', 'Snapped to'] + ]; + } + + /** Tab-separated, with a header, for pasting into a spreadsheet. */ + function toTsv(rows, units) { + var cols = columns(units), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; + for (var i = 0; i < rows.length; i++) { + lines.push(cols.map(function (c) { return String(rows[i][c[0]]).replace(/[\t\n]/g, ' '); }).join('\t')); + } + return lines.join('\n'); + } + + /* ── Marker list ───────────────────────────────────────────────────── */ + + var markers = []; + var version = 0; + + function sortMarkers() { markers.sort(function (a, b) { return a.t - b.t || a.id - b.id; }); } + + /** Ids keep growing while markers exist, so "M2" keeps meaning one marker. */ + function addMarker(t, snap) { + var id = 1; + for (var i = 0; i < markers.length; i++) id = Math.max(id, markers[i].id + 1); + var marker = { id: id, t: t, snap: snap || '' }; + markers.push(marker); sortMarkers(); version++; + return marker; + } + + function findMarker(id) { + for (var i = 0; i < markers.length; i++) if (markers[i].id === id) return markers[i]; + return null; + } + + function moveMarker(id, t, snap) { + var marker = findMarker(id); + if (!marker) return null; + marker.t = t; marker.snap = snap || ''; sortMarkers(); version++; + return marker; + } + + function removeMarker(id) { + var before = markers.length; + markers = markers.filter(function (m) { return m.id !== id; }); + if (markers.length !== before) version++; + } + + function clearMarkers() { + if (markers.length) version++; + markers = []; + } + + function listMarkers() { return markers.map(function (m) { return { id: m.id, t: m.t, snap: m.snap }; }); } + + /* ══ UI (only install() reaches here) ══════════════════════════════════ */ + + var ctx = null; + var wired = false; + var snapEnabled = true; + var tableOpen = true; + /** Pointer over the plot, in canvas CSS pixels; null when elsewhere. */ + var hover = null; + var hoverMarkerId = 0; + /** {id, from, fromSnap, snap} while a marker is being dragged. */ + var drag = null; + var menu = null; + /** {x, y, snap} the open menu was opened for. */ + var menuTarget = null; + var tableEl = null; + var tableKey = ''; + var snapCache = null; + + function el(id) { return document.getElementById(id); } + function prefs() { return typeof SeqEyesPrefs !== 'undefined' ? SeqEyesPrefs : null; } + + function units() { + return { timeConv: ctx.timeConv, timeUnit: ctx.timeUnitStr(), gradConv: ctx.gradConv, gradUnit: ctx.gradUnitStr() }; + } + + function canvasPoint(event) { + var mc = el('mc'), rect = mc.getBoundingClientRect(); + return { x: event.clientX - rect.left, y: event.clientY - rect.top, width: rect.width, height: rect.height }; + } + + function insidePlot(p) { + var M = ctx.margins(); + return p.x >= M.l && p.x <= p.width - M.r && p.y >= M.t && p.y <= p.height - M.b; + } + + function rowAt(y) { + var M = ctx.margins(), rows = ctx.visChannels(), vi = Math.floor((y - M.t) / ctx.cH()); + return vi >= 0 && vi < rows.length ? rows[vi] : -1; + } + + function markerNear(x, px) { + var best = null, bestDistance = px + 1e-9; + for (var i = 0; i < markers.length; i++) { + var distance = Math.abs(ctx.t2x(markers[i].t) - x); + if (distance <= bestDistance) { best = markers[i]; bestDistance = distance; } + } + return best; + } + + function clampTime(t) { + var total = ctx.duration(); + return Math.max(0, total > 0 ? Math.min(total, t) : t); + } + + /** + * Snap target under the pointer, or null. Cached: in the web app the + * overlay is drawn twice a frame (once by the bundle, once by the page). + */ + function snapFor(x, y) { + if (!ctx || !snapEnabled) return null; + var blocks = ctx.blocks(); + if (!blocks || !blocks.length) return null; + var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + SNAP_PX) - t), rows = ctx.visChannels(); + var pointerCi = y === null || y === undefined ? -1 : rowAt(y), detail = liveDetail(), rowKey = rows.join(','); + var c = snapCache; + if (c && c.blocks === blocks && c.detail === detail && c.t === t && c.tol === tol && c.ci === pointerCi && c.rows === rowKey) { + return c.result; + } + var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / SNAP_PX }); + snapCache = { blocks: blocks, detail: detail, t: t, tol: tol, ci: pointerCi, rows: rowKey, result: result }; + return result; + } + + /** The suggestion shows once markers are in use, not while just browsing. */ + function currentSuggestion() { + if (menuTarget) return menuTarget.snap; + if (drag) return drag.snap; + if (hover && markers.length) return snapFor(hover.x, hover.y); + return null; + } + + function redraw() { + if (ctx && typeof ctx.requestOverlay === 'function') ctx.requestOverlay(); + } + + /* ── Drawing on the overlay canvas ─────────────────────────────────── */ + + function valueToY(ci, vi, value) { + var M = ctx.margins(), ch = ctx.cH(), y = ctx.cy(vi); + if (ci === 0 || ci === 1) return y + ch * 0.45 - value * (ch * 0.9 / ctx.channelRange(ci)); + if (ci >= 2 && ci <= 4) return y - value * (ch * 0.4 / ctx.channelRange(ci)); + if (ci === 7) return M.t + (vi + 1) * ch - ch * 0.08 - value * (ch * 0.84 / ctx.channelRange(7)); + if (ci >= 8 && ci <= 10) return y - value * (ch * 0.4 / ctx.channelRange(ci)); + return y; + } + + function clampToRow(vi, y) { + var M = ctx.margins(), ch = ctx.cH(), top = M.t + vi * ch; + return Math.max(top + 2, Math.min(top + ch - 2, y)); + } + + function colour(style, name, fallback) { + var value = style.getPropertyValue(name).trim(); + return value || fallback; + } + + function pill(g, text, x, y, left, right, fg, bg) { + var width = g.measureText(text).width + 8, cx = Math.max(left + width / 2, Math.min(right - width / 2, x)); + g.fillStyle = fg; g.fillRect(cx - width / 2, y - 7, width, 13); + g.fillStyle = bg; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(text, cx, y); + return { left: cx - width / 2, right: cx + width / 2 }; + } + + function drawSuggestion(g, w, h, s, style, fg) { + var M = ctx.margins(), x = ctx.t2x(s.t); + if (x < M.l || x > w - M.r) return; + g.save(); + g.globalAlpha = 0.75; g.strokeStyle = fg; g.lineWidth = 1; g.setLineDash([2, 3]); + g.beginPath(); g.moveTo(x, M.t); g.lineTo(x, h - M.b); g.stroke(); g.setLineDash([]); + g.globalAlpha = 1; + var rows = ctx.visChannels(), vi = rows.indexOf(s.ci), y = M.t + 12; + if (vi >= 0) { + y = clampToRow(vi, valueToY(s.ci, vi, s.value)); + g.lineWidth = 1.5; g.strokeStyle = colour(style, ROW_COLOURS[s.ci] || '--fg', fg); + g.beginPath(); g.arc(x, y, 5, 0, Math.PI * 2); g.stroke(); + } + g.font = '10px monospace'; + var text = s.text, width = g.measureText(text).width, right = x + 8 + width <= w - M.r; + g.fillStyle = colour(style, '--bg', '#fff'); g.globalAlpha = 0.85; + g.fillRect(right ? x + 7 : x - 9 - width, y - 16, width + 2, 12); + g.globalAlpha = 1; g.fillStyle = fg; g.textAlign = right ? 'left' : 'right'; g.textBaseline = 'middle'; + g.fillText(text, right ? x + 8 : x - 8, y - 10); + g.restore(); + } + + /** + * Called by both renderers' drawCursorOverlay, after the overlay is cleared: + * marker lines with a dot where each crosses RF and the gradients, Δt + * between neighbours, and the snap suggestion. + */ + function drawOverlay(g, w, h) { + if (!ctx || !g) return; + syncTable(); + var suggestion = currentSuggestion(); + if (!markers.length && !suggestion) return; + var style = getComputedStyle(document.body), fg = colour(style, '--fg', '#222'), bg = colour(style, '--bg', '#fff'); + var M = ctx.margins(), left = M.l, right = w - M.r, top = M.t, bottom = h - M.b; + var rows = ctx.visChannels(), detail = liveDetail(), blocks = ctx.blocks(), u = units(); + g.save(); + g.beginPath(); g.rect(left, top, Math.max(0, right - left), Math.max(0, bottom - top)); g.clip(); + g.font = '10px monospace'; + + // Δt between neighbours, just above the marker names. + var bracketY = bottom - 22; + for (var i = 1; i < markers.length; i++) { + var xa = ctx.t2x(markers[i - 1].t), xb = ctx.t2x(markers[i].t); + if (xb < left || xa > right || xb - xa < 2) continue; + var a = Math.max(left, xa), b = Math.min(right, xb); + g.strokeStyle = fg; g.lineWidth = 1; g.globalAlpha = 0.8; + g.beginPath(); g.moveTo(a, bracketY); g.lineTo(b, bracketY); + if (xa >= left) { g.moveTo(xa, bracketY - 4); g.lineTo(xa, bracketY + 4); } + if (xb <= right) { g.moveTo(xb, bracketY - 4); g.lineTo(xb, bracketY + 4); } + g.stroke(); g.globalAlpha = 1; + var label = 'Δ ' + formatTime(markers[i].t - markers[i - 1].t, u) + ' ' + unitName(u.timeUnit); + var width = g.measureText(label).width; + if (b - a > width + 10) { + g.fillStyle = bg; g.fillRect((a + b) / 2 - width / 2 - 3, bracketY - 15, width + 6, 12); + g.fillStyle = fg; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(label, (a + b) / 2, bracketY - 9); + } + } + + for (var k = 0; k < markers.length; k++) { + var m = markers[k], x = ctx.t2x(m.t); + if (x < left - 1 || x > right + 1) continue; + var active = m.id === hoverMarkerId || (drag && drag.id === m.id); + g.strokeStyle = fg; g.lineWidth = active ? 2 : 1.2; g.setLineDash([]); + g.beginPath(); g.moveTo(x, top); g.lineTo(x, bottom); g.stroke(); + + var reading = readoutAt(blocks, m.t, detail); + var next = k + 1 < markers.length ? ctx.t2x(markers[k + 1].t) : right; + for (var vi = 0; vi < rows.length; vi++) { + var ci = rows[vi], value = null; + if (ci === 0) value = reading.rf ? reading.rf.amplitude : null; + else if (ci >= 2 && ci <= 4) value = reading[AXES[ci - 2]]; + if (value === null) continue; + var y = clampToRow(vi, valueToY(ci, vi, value)); + g.fillStyle = colour(style, ROW_COLOURS[ci], fg); g.strokeStyle = bg; g.lineWidth = 1; + g.beginPath(); g.arc(x, y, 3, 0, Math.PI * 2); g.fill(); g.stroke(); + if (ci >= 2 && next - x > 70) { + var text = (reading.approx[AXES[ci - 2]] ? '≈' : '') + formatGradient(value, u); + g.fillStyle = fg; g.textAlign = 'left'; g.textBaseline = 'bottom'; g.fillText(text, x + 5, y - 2); + } + } + var nameRoom = Math.min(next, right) - x; + var name = 'M' + m.id, full = name + ' ' + formatTime(m.t, u) + ' ' + unitName(u.timeUnit); + pill(g, nameRoom > g.measureText(full).width + 24 ? full : name, x, bottom - 8, left, right, fg, bg); + } + if (suggestion) drawSuggestion(g, w, h, suggestion, style, fg); + g.restore(); + } + + /* ── Table strip ───────────────────────────────────────────────────── */ + + function element(tag, className, text) { + var node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + } + + function button(text, title, onClick) { + var b = element('button', null, text); + b.type = 'button'; if (title) b.title = title; + b.addEventListener('click', onClick); + return b; + } + + function buildTable() { + var cc = el('cc'); + if (!cc || !cc.parentNode) return; + tableEl = element('div', 'mk-table'); tableEl.id = 'mkTable'; tableEl.hidden = true; + tableEl.setAttribute('role', 'region'); tableEl.setAttribute('aria-label', 'Measurement markers'); + cc.parentNode.insertBefore(tableEl, cc.nextSibling); + } + + /** Re-render when the markers, units or underlying samples changed. */ + function syncTable() { + if (!tableEl || !ctx) return; + var u = units(), detail = liveDetail(), blocks = ctx.blocks(); + var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0].join('|'); + if (key === tableKey && tableEl.__blocks === blocks && tableEl.__detail === detail) return; + tableKey = key; tableEl.__blocks = blocks; tableEl.__detail = detail; + renderTable(u, detail, blocks); + } + + function renderTable(u, detail, blocks) { + var wasHidden = tableEl.hidden; + tableEl.textContent = ''; + tableEl.hidden = !markers.length; + if (!markers.length) { if (!wasHidden) relayout(); return; } + var rows = tableRows(markers, blocks, detail, u); + var head = element('div', 'mk-head'); + head.appendChild(element('span', 'mk-title', 'Markers')); + var span = markers.length > 1 ? ' · span ' + formatTime(markers[markers.length - 1].t - markers[0].t, u) + ' ' + unitName(u.timeUnit) : ''; + head.appendChild(element('span', 'mk-summary', markers.length + (markers.length === 1 ? ' marker' : ' markers') + span)); + if (rows.some(function (r) { return r.approx; })) { + head.appendChild(element('span', 'mk-note', '≈ from reduced samples; zoom in for exact values')); + } + var actions = element('span', 'mk-actions'); + actions.appendChild(button(tableOpen ? 'Hide' : 'Show', tableOpen ? 'Collapse the marker table' : 'Expand the marker table', function () { setTableOpen(!tableOpen); })); + actions.appendChild(button('Copy', 'Copy the table as tab-separated text', function () { copyTable(this); })); + actions.appendChild(button('Clear', 'Remove every marker', function () { clearMarkers(); afterChange(); })); + head.appendChild(actions); + tableEl.appendChild(head); + if (tableOpen) { + var scroll = element('div', 'mk-scroll'), table = element('table'), thead = element('thead'), tr = element('tr'); + var cols = columns(u); + cols.forEach(function (c) { tr.appendChild(element('th', null, c[1])); }); + tr.appendChild(element('th')); + thead.appendChild(tr); table.appendChild(thead); + var body = element('tbody'); + rows.forEach(function (row) { + var line = element('tr'); + line.setAttribute('data-marker', String(row.id)); + cols.forEach(function (c) { line.appendChild(element('td', c[0] === 'name' ? 'mk-name' : null, row[c[0]])); }); + var cell = element('td'); + cell.appendChild(button('×', 'Remove ' + row.name, function () { removeMarker(row.id); afterChange(); })); + line.appendChild(cell); + body.appendChild(line); + }); + table.appendChild(body); scroll.appendChild(table); tableEl.appendChild(scroll); + } + relayout(); + } + + /* The strip takes height from the plot; the hosts' ResizeObserver on #cc + redraws, but only once the size actually settles, so ask explicitly. */ + function relayout() { + if (typeof requestAnimationFrame === 'function') requestAnimationFrame(redraw); + } + + function setTableOpen(open) { + tableOpen = !!open; + var p = prefs(); if (p && p.KEYS.markerTable) p.setBool(p.KEYS.markerTable, tableOpen); + tableKey = ''; + syncTable(); + } + + function copyTable(source) { + var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()); + var done = function () { if (source) { var old = source.textContent; source.textContent = 'Copied'; setTimeout(function () { source.textContent = old; }, 1200); } }; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); }); + } else { fallbackCopy(text); done(); } + } + + function fallbackCopy(text) { + var area = element('textarea'); area.value = text; + area.style.position = 'fixed'; area.style.opacity = '0'; + document.body.appendChild(area); area.select(); + try { document.execCommand('copy'); } catch (e) { /* nothing more to try */ } + document.body.removeChild(area); + } + + function afterChange() { + snapCache = null; + syncTable(); + redraw(); + } + + /* ── Context menu ──────────────────────────────────────────────────── */ + + function isCompactLayout() { + return !!(window.matchMedia && window.matchMedia('(max-width: 768px), (pointer: coarse)').matches); + } + + function menuItem(label, detail, onSelect) { + var item = element('button', 'mk-item'); + item.type = 'button'; item.setAttribute('role', 'menuitem'); + item.appendChild(element('span', 'mk-item-label', label)); + if (detail) item.appendChild(element('span', 'mk-item-detail', detail)); + item.addEventListener('click', function () { closeMenu(); onSelect(); }); + return item; + } + + function menuToggle(label, checked, onChange) { + var row = element('label', 'mk-item mk-check'); + var box = element('input'); box.type = 'checkbox'; box.checked = checked; + box.setAttribute('role', 'menuitemcheckbox'); + box.addEventListener('change', function () { onChange(box.checked); }); + row.appendChild(box); row.appendChild(element('span', 'mk-item-label', label)); + return row; + } + + function openMenu(event, p) { + closeMenu(); + var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y), near = markerNear(p.x, REMOVE_PX); + var time = function (seconds) { return formatTime(seconds, u) + ' ' + unitName(u.timeUnit); }; + menuTarget = { x: p.x, y: p.y, snap: snap }; + menu = element('div', 'lblc mk-menu'); menu.id = 'markerMenu'; + menu.setAttribute('role', 'menu'); menu.setAttribute('aria-label', 'Measurement markers'); + if (snap) menu.appendChild(menuItem('Add marker at ' + snap.text, time(snap.t), function () { place(snap.t, snap.text); })); + menu.appendChild(menuItem(snap ? 'Add marker at pointer (no snap)' : 'Add marker here', time(t), function () { place(t, ''); })); + if (near) menu.appendChild(menuItem('Remove M' + near.id, time(near.t), function () { removeMarker(near.id); afterChange(); })); + if (markers.length) menu.appendChild(menuItem('Clear all markers', String(markers.length), function () { clearMarkers(); afterChange(); })); + menu.appendChild(element('div', 'mk-sep')); + menu.appendChild(menuToggle('Snap to corners and block edges', snapEnabled, function (on) { + snapEnabled = on; + var pr = prefs(); if (pr && pr.KEYS.markerSnap) pr.setBool(pr.KEYS.markerSnap, on); + menuTarget.snap = on ? snapFor(p.x, p.y) : null; + snapCache = null; redraw(); + })); + if (markers.length) menu.appendChild(menuToggle('Show the marker table', tableOpen, function (on) { setTableOpen(on); })); + document.body.appendChild(menu); + positionMenu(event.clientX, event.clientY); + el('cc').classList.add('mk-menu-open'); + document.addEventListener('pointerdown', onOutsidePointer, true); + window.addEventListener('resize', closeMenu); + var first = menu.querySelector('.mk-item'); + if (first && first.focus) first.focus(); + redraw(); + } + + function positionMenu(clientX, clientY) { + var compact = isCompactLayout(); + menu.classList.toggle('sheet', compact); + if (compact) { menu.style.left = ''; menu.style.top = ''; return; } + var width = menu.offsetWidth, height = menu.offsetHeight, vw = window.innerWidth, vh = window.innerHeight; + menu.style.left = Math.max(8, Math.min(clientX + 2, vw - width - 8)) + 'px'; + menu.style.top = Math.max(8, clientY + 2 + height > vh - 8 ? clientY - height - 2 : clientY + 2) + 'px'; + } + + function closeMenu() { + if (!menu) return; + document.removeEventListener('pointerdown', onOutsidePointer, true); + window.removeEventListener('resize', closeMenu); + if (menu.parentNode) menu.parentNode.removeChild(menu); + menu = null; menuTarget = null; + var cc = el('cc'); if (cc) cc.classList.remove('mk-menu-open'); + redraw(); + } + + function onOutsidePointer(event) { + if (menu && !menu.contains(event.target)) closeMenu(); + } + + function moveMenuFocus(step) { + var items = Array.prototype.slice.call(menu.querySelectorAll('.mk-item')); + var at = items.indexOf(document.activeElement && document.activeElement.closest ? document.activeElement.closest('.mk-item') : null); + var next = items[(at + step + items.length) % items.length]; + if (next) (next.querySelector('input') || next).focus(); + } + + function place(t, snap) { + addMarker(clampTime(t), snap); + afterChange(); + } + + /* ── Pointer handling ──────────────────────────────────────────────── */ + + function onContextMenu(event) { + if (!ctx || event.target !== el('mc')) return; + // Keeps the browser's menu, and VS Code's webview menu, off the plot. + event.preventDefault(); + var p = canvasPoint(event); + if (insidePlot(p)) openMenu(event, p); + } + + /* Capture phase on #cc runs before both renderers' mousedown on #mc, so + grabbing a marker never starts a pan. Anything else passes through. */ + function onMouseDown(event) { + if (!ctx || event.button !== 0 || event.ctrlKey || event.target !== el('mc') || !markers.length) return; + var p = canvasPoint(event), marker = insidePlot(p) ? markerNear(p.x, HIT_PX) : null; + if (!marker) return; + event.stopPropagation(); event.preventDefault(); + drag = { id: marker.id, from: marker.t, fromSnap: marker.snap, snap: null }; + el('cc').classList.add('mk-drag'); + redraw(); + } + + function onWindowMove(event) { + if (!drag || !ctx) return; + var p = canvasPoint(event), bypass = event.shiftKey || event.altKey; + var snap = bypass ? null : snapFor(p.x, p.y); + drag.snap = snap; + moveMarker(drag.id, clampTime(snap ? snap.t : ctx.x2t(p.x)), snap ? snap.text : ''); + afterChange(); + } + + function onWindowUp() { + if (!drag) return; + drag = null; + var cc = el('cc'); if (cc) cc.classList.remove('mk-drag'); + afterChange(); + } + + function onHoverMove(event) { + if (!ctx || drag) return; + var p = canvasPoint(event), inside = insidePlot(p); + hover = inside ? { x: p.x, y: p.y } : null; + var near = inside && markers.length ? markerNear(p.x, HIT_PX) : null, id = near ? near.id : 0; + if (id !== hoverMarkerId) { hoverMarkerId = id; redraw(); } + el('cc').classList.toggle('mk-hover', !!near); + } + + function onHoverLeave() { + if (drag) return; + hover = null; hoverMarkerId = 0; + var cc = el('cc'); if (cc) cc.classList.remove('mk-hover'); + redraw(); + } + + function onKeyDown(event) { + if (event.key === 'Escape' && (menu || drag)) { + event.preventDefault(); event.stopPropagation(); + if (menu) { closeMenu(); return; } + moveMarker(drag.id, drag.from, drag.fromSnap); + onWindowUp(); + return; + } + if (menu && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + event.preventDefault(); moveMenuFocus(event.key === 'ArrowDown' ? 1 : -1); + } + } + + function wire() { + var cc = el('cc'); + if (!cc || !el('mc')) return; + wired = true; + cc.addEventListener('mousedown', onMouseDown, true); + cc.addEventListener('contextmenu', onContextMenu); + cc.addEventListener('mousemove', onHoverMove); + cc.addEventListener('mouseleave', onHoverLeave); + window.addEventListener('mousemove', onWindowMove); + window.addEventListener('mouseup', onWindowUp); + window.addEventListener('blur', onWindowUp); + document.addEventListener('keydown', onKeyDown, true); + buildTable(); + var p = prefs(); + if (p && p.KEYS.markerSnap) snapEnabled = p.getBool(p.KEYS.markerSnap, true); + if (p && p.KEYS.markerTable) tableOpen = p.getBool(p.KEYS.markerTable, true); + if (typeof window !== 'undefined') { + var dev = window.SeqEyesDev = window.SeqEyesDev || {}; + dev.markers = function () { + var detail = liveDetail(), blocks = ctx ? ctx.blocks() : []; + return markers.map(function (m) { return { id: m.id, t: m.t, snap: m.snap, readout: readoutAt(blocks, m.t, detail) }; }); + }; + dev.addMarker = function (t, snap) { var m = addMarker(clampTime(t), snap); afterChange(); return m.id; }; + dev.snapAt = function (t) { return ctx ? snapFor(ctx.t2x(t), null) : null; }; + dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()) : ''; }; + dev.markerState = function () { + return { suggestion: currentSuggestion(), menuOpen: !!menu, dragging: !!drag, snapEnabled: snapEnabled, tableOpen: tableOpen }; + }; + } + } + + /** + * Hand the module a renderer's state. ctx: blocks(), duration(), margins(), + * t2x, x2t, visChannels, cH, cy, channelRange, timeConv, timeUnitStr, + * gradConv, gradUnitStr, requestOverlay. A later install replaces an + * earlier one; the DOM is wired once. + */ + function install(context) { + ctx = context; + snapCache = null; tableKey = ''; + if (!wired && typeof document !== 'undefined') wire(); + syncTable(); + } + + /** A new sequence: its markers would point at nothing. */ + function reset() { + clearMarkers(); + drag = null; hover = null; hoverMarkerId = 0; snapCache = null; + closeMenu(); + var cc = typeof document !== 'undefined' ? el('cc') : null; + if (cc) cc.classList.remove('mk-drag', 'mk-hover'); + syncTable(); + } + + return { + install: install, + reset: reset, + drawOverlay: drawOverlay, + // List operations, also used by tests and dev hooks. + add: function (t, snap) { var m = addMarker(t, snap); if (ctx) afterChange(); return m; }, + remove: function (id) { removeMarker(id); if (ctx) afterChange(); }, + clear: function () { clearMarkers(); if (ctx) afterChange(); }, + move: moveMarker, + list: listMarkers, + // Pure core, exported for the unit tests. + core: { + blockIndexAt: blockIndexAt, + sampleAt: sampleAt, + trapezoidCorners: trapezoidCorners, + gradientCorners: gradientCorners, + interiorCorners: interiorCorners, + snapCandidates: snapCandidates, + chooseSnap: chooseSnap, + snapAt: snapAt, + readoutAt: readoutAt, + tableRows: tableRows, + toTsv: toTsv, + formatTime: formatTime, + formatGradient: formatGradient + } + }; +})(); + + /* ══ interaction.js ══ */ /* ═══════════════════════════════════════════════════════════════════════ Mouse interaction @@ -10491,6 +11543,14 @@ rs(); this one — install() swaps the host without re-binding the DOM. */ SeqEyesPanel.install(window.SeqEyesPanelHost); SeqEyesPrefsUi.install(); +/* Measurement markers read this renderer's state through these accessors. + web/index.html installs its own over them, as it does the panel host. */ +SeqEyesMarkers.install({ + blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, + t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, + timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, + requestOverlay:drawCursorOverlay +}); /* Deferred by one macrotask so web/index.html, whose inline IIFE runs after this bundle, has installed its own adapter before the persisted mode is restored against it. */ From 9b27f8a497c68034dafa3751cf8483b1bff9affa Mon Sep 17 00:00:00 2001 From: Haotian Hong Date: Mon, 19 Oct 2026 20:11:10 -0400 Subject: [PATCH 4/7] Measurement markers on touch screens, and M1/PNS in the marker table Touch: - A long-press (half a second, without moving) opens the marker menu. The finger's later moves and lift are swallowed, so the view does not pan and the tap tooltip does not appear. - A finger on a marker drags it, again without panning; snapping reaches twice as far as with a mouse. - A plain tap still shows the readout, as before. Like the mouse handling, this runs in the capture phase on #cc, so neither renderer's touch code changed. The table gains an "M1 / PNS" column while those rows are shown. It takes each renderer's own hover-readout lines, so the values match the tooltip and the plot (including coarse bands), and the column is in the copied TSV. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 14 +- .../src/seqeyes/resources/webview-bundle.js | 142 +++++++++++++++--- src/editor/webview/assets/interaction.js | 3 +- src/editor/webview/assets/markers.js | 139 ++++++++++++++--- test/browser/markers.spec.ts | 70 +++++++++ web/index.html | 3 +- web/webview-bundle.js | 142 +++++++++++++++--- 7 files changed, 446 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 58c312a..296de5a 100644 --- a/README.md +++ b/README.md @@ -378,7 +378,7 @@ long, the plan takes a coarser tested spacing and says so. **Not yet**: | Load an ASC profile | `Load ASC (PNS/Acoustic)`, then choose a scanner ASC. PNS coefficients and acoustic resonances are read independently — a file carrying only one still loads, and the viewer says which it found | | Toggle block boundaries | Checkbox `☐ Blocks` in toolbar | | Block details & values | Hover waveform | -| Measure times and values | Right-click the waveform → **Add marker** (see [Measurement markers](#measurement-markers)). Drag a marker to move it; hold `Shift` to place it off the snap points | +| Measure times and values | Right-click (or long-press) the waveform → **Add marker** (see [Measurement markers](#measurement-markers)). Drag a marker to move it; hold `Shift` to place it off the snap points | | Switch theme | Toolbar `Theme` dropdown | | Cycle the analysis panel | Toolbar button: closed → **K-Space** → **Spectrogram** → closed. The label always names what the next click does | | Rotate 3D view | Left‑drag in k‑space panel | @@ -400,8 +400,9 @@ long, the plan takes a coarser tested spacing and says so. **Not yet**: ## Measurement markers -Right-click the waveform viewer and choose **Add marker** to drop a vertical -marker. Add as many as you need (M1, M2, …): +Right-click the waveform viewer (or long-press it on a touch screen) and +choose **Add marker** to drop a vertical marker. Add as many as you need +(M1, M2, …): - **Snapping.** Near a gradient corner the menu offers that point instead: a trapezoid's ramp and flat-top corners, the breakpoints of an extended @@ -414,14 +415,15 @@ marker. Add as many as you need (M1, M2, …): its value, and Δt is shown between neighbouring markers. The table under the plot lists every marker: time, block and time within it, Δt to the previous one, Gx/Gy/Gz in the current gradient unit, RF amplitude and - phase, the ADC sample and the trigger. **Copy** puts it on the clipboard as - tab-separated text. + phase, the ADC sample and the trigger, plus M1 and PNS while those rows + are shown. **Copy** puts it on the clipboard as tab-separated text. - **Exactness.** Trapezoid corners, RF/ADC edges and block boundaries are always exact. A long arbitrary waveform is reduced for the whole-sequence view; values read from those reduced samples are marked ≈ until you zoom in far enough for the exact samples to load, and its interior bends are only offered as snap points then. -- **Editing.** Drag a marker to move it, right-click next to one to remove +- **Editing.** Drag a marker to move it (with a finger on a touch screen), + right-click next to one to remove it, or use the table's × and **Clear**. `Esc` closes the menu or cancels a drag. Markers belong to the open sequence and are cleared when another one loads. diff --git a/python/src/seqeyes/resources/webview-bundle.js b/python/src/seqeyes/resources/webview-bundle.js index fb2d3b8..515e364 100644 --- a/python/src/seqeyes/resources/webview-bundle.js +++ b/python/src/seqeyes/resources/webview-bundle.js @@ -10119,6 +10119,11 @@ var SeqEyesMarkers = (function () { var SNAP_PX = 8; var HIT_PX = 4; var REMOVE_PX = 6; + /* Fingers are wider and the press hides what is under it. */ + var SNAP_PX_TOUCH = 16; + var HIT_PX_TOUCH = 12; + var LONG_PRESS_MS = 500; + var TOUCH_SLOP_PX = 8; /* More blocks than this inside the snap distance means the view is too zoomed out for a corner to be a meaningful target. */ var MAX_SNAP_BLOCKS = 32; @@ -10505,9 +10510,11 @@ var SeqEyesMarkers = (function () { /** * One row per marker, in time order, with everything formatted in the - * viewer's current units. `list` is [{id, t, snap}]. + * viewer's current units. `list` is [{id, t, snap}]. `derived`, when + * given, returns the M1/PNS text for a time (the rows shown, as the hover + * readout words them). */ - function tableRows(list, blocks, detail, units) { + function tableRows(list, blocks, detail, units, derived) { var rows = []; for (var i = 0; i < list.length; i++) { var m = list[i], r = readoutAt(blocks, m.t, detail), previous = i > 0 ? list[i - 1] : null; @@ -10525,6 +10532,7 @@ var SeqEyesMarkers = (function () { phase: r.rf && isFinite(r.rf.phase) ? (r.rf.phase * 180 / Math.PI).toFixed(1) : '', adc: r.adc ? (r.adc.sample + 1) + '/' + r.adc.count : '', trigger: r.trigger ? 'on' : '', + derived: derived ? derived(m.t) : '', snap: m.snap || '', approx: !!(r.approx.gx || r.approx.gy || r.approx.gz || (r.rf && r.rf.approx)) }); @@ -10532,20 +10540,27 @@ var SeqEyesMarkers = (function () { return rows; } - function columns(units) { + function columns(units, withDerived) { var t = unitName(units.timeUnit), g = units.gradUnit; - return [ + var cols = [ ['name', 'Marker'], ['time', 'Time (' + t + ')'], ['delta', 'Δt (' + t + ')'], ['block', 'Block'], ['offset', 'In block (' + t + ')'], ['gx', 'Gx (' + g + ')'], ['gy', 'Gy (' + g + ')'], ['gz', 'Gz (' + g + ')'], ['rf', 'RF (Hz)'], ['phase', 'RF phase (°)'], ['adc', 'ADC sample'], ['trigger', 'Trigger'], ['snap', 'Snapped to'] ]; + if (withDerived) cols.splice(cols.length - 1, 0, ['derived', 'M1 / PNS']); + return cols; + } + + function hasDerived(rows) { + for (var i = 0; i < rows.length; i++) if (rows[i].derived) return true; + return false; } /** Tab-separated, with a header, for pasting into a spreadsheet. */ function toTsv(rows, units) { - var cols = columns(units), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; + var cols = columns(units, hasDerived(rows)), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; for (var i = 0; i < rows.length; i++) { lines.push(cols.map(function (c) { return String(rows[i][c[0]]).replace(/[\t\n]/g, ' '); }).join('\t')); } @@ -10614,6 +10629,15 @@ var SeqEyesMarkers = (function () { function el(id) { return document.getElementById(id); } function prefs() { return typeof SeqEyesPrefs !== 'undefined' ? SeqEyesPrefs : null; } + /** M1/PNS text at a time, when the renderer can give it and those rows are on. */ + function derivedText() { + if (!ctx || typeof ctx.derivedLines !== 'function') return null; + var rows = ctx.visChannels(), shown = false; + for (var i = 0; i < rows.length; i++) if (rows[i] >= 7 && rows[i] <= 10) shown = true; + if (!shown) return null; + return function (t) { return ctx.derivedLines(t).join(' '); }; + } + function units() { return { timeConv: ctx.timeConv, timeUnit: ctx.timeUnitStr(), gradConv: ctx.gradConv, gradUnit: ctx.gradUnitStr() }; } @@ -10651,17 +10675,18 @@ var SeqEyesMarkers = (function () { * Snap target under the pointer, or null. Cached: in the web app the * overlay is drawn twice a frame (once by the bundle, once by the page). */ - function snapFor(x, y) { + function snapFor(x, y, px) { if (!ctx || !snapEnabled) return null; var blocks = ctx.blocks(); if (!blocks || !blocks.length) return null; - var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + SNAP_PX) - t), rows = ctx.visChannels(); + var reach = px || SNAP_PX; + var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + reach) - t), rows = ctx.visChannels(); var pointerCi = y === null || y === undefined ? -1 : rowAt(y), detail = liveDetail(), rowKey = rows.join(','); var c = snapCache; if (c && c.blocks === blocks && c.detail === detail && c.t === t && c.tol === tol && c.ci === pointerCi && c.rows === rowKey) { return c.result; } - var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / SNAP_PX }); + var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / reach }); snapCache = { blocks: blocks, detail: detail, t: t, tol: tol, ci: pointerCi, rows: rowKey, result: result }; return result; } @@ -10822,18 +10847,19 @@ var SeqEyesMarkers = (function () { function syncTable() { if (!tableEl || !ctx) return; var u = units(), detail = liveDetail(), blocks = ctx.blocks(); - var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0].join('|'); + var derived = derivedText(), derivedKey = derived ? markers.map(function (m) { return derived(m.t); }).join('|') : ''; + var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0, derivedKey].join('|'); if (key === tableKey && tableEl.__blocks === blocks && tableEl.__detail === detail) return; tableKey = key; tableEl.__blocks = blocks; tableEl.__detail = detail; - renderTable(u, detail, blocks); + renderTable(u, detail, blocks, derived); } - function renderTable(u, detail, blocks) { + function renderTable(u, detail, blocks, derived) { var wasHidden = tableEl.hidden; tableEl.textContent = ''; tableEl.hidden = !markers.length; if (!markers.length) { if (!wasHidden) relayout(); return; } - var rows = tableRows(markers, blocks, detail, u); + var rows = tableRows(markers, blocks, detail, u, derived); var head = element('div', 'mk-head'); head.appendChild(element('span', 'mk-title', 'Markers')); var span = markers.length > 1 ? ' · span ' + formatTime(markers[markers.length - 1].t - markers[0].t, u) + ' ' + unitName(u.timeUnit) : ''; @@ -10849,7 +10875,7 @@ var SeqEyesMarkers = (function () { tableEl.appendChild(head); if (tableOpen) { var scroll = element('div', 'mk-scroll'), table = element('table'), thead = element('thead'), tr = element('tr'); - var cols = columns(u); + var cols = columns(u, hasDerived(rows)); cols.forEach(function (c) { tr.appendChild(element('th', null, c[1])); }); tr.appendChild(element('th')); thead.appendChild(tr); table.appendChild(thead); @@ -10882,7 +10908,7 @@ var SeqEyesMarkers = (function () { } function copyTable(source) { - var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()); + var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units(), derivedText()), units()); var done = function () { if (source) { var old = source.textContent; source.textContent = 'Copied'; setTimeout(function () { source.textContent = old; }, 1200); } }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); }); @@ -10927,9 +10953,10 @@ var SeqEyesMarkers = (function () { return row; } - function openMenu(event, p) { + function openMenu(event, p, reach) { closeMenu(); - var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y), near = markerNear(p.x, REMOVE_PX); + var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y, reach); + var near = markerNear(p.x, reach ? HIT_PX_TOUCH : REMOVE_PX); var time = function (seconds) { return formatTime(seconds, u) + ' ' + unitName(u.timeUnit); }; menuTarget = { x: p.x, y: p.y, snap: snap }; menu = element('div', 'lblc mk-menu'); menu.id = 'markerMenu'; @@ -10942,7 +10969,7 @@ var SeqEyesMarkers = (function () { menu.appendChild(menuToggle('Snap to corners and block edges', snapEnabled, function (on) { snapEnabled = on; var pr = prefs(); if (pr && pr.KEYS.markerSnap) pr.setBool(pr.KEYS.markerSnap, on); - menuTarget.snap = on ? snapFor(p.x, p.y) : null; + menuTarget.snap = on ? snapFor(p.x, p.y, reach) : null; snapCache = null; redraw(); })); if (markers.length) menu.appendChild(menuToggle('Show the marker table', tableOpen, function (on) { setTableOpen(on); })); @@ -11045,6 +11072,74 @@ var SeqEyesMarkers = (function () { redraw(); } + /* ── Touch ────────────────────────────────────────────────────────── + + Capture phase on #cc again, ahead of both renderers' touch handlers on + #mc. A finger on a marker drags it, and the renderer never starts its + pan. A finger held still opens the menu, and its later moves and lift + are swallowed so the view does not pan and the tap tooltip does not + show. Any other touch passes through untouched. */ + + /** {x0, y0, timer, fired} for a press that may become a long-press, or {dragging}. */ + var press = null; + + function endPress() { + if (press && press.timer) clearTimeout(press.timer); + press = null; + } + + function onTouchStart(event) { + endPress(); + if (!ctx || event.target !== el('mc') || event.touches.length !== 1) return; + var finger = event.touches[0], p = canvasPoint(finger); + if (!insidePlot(p)) return; + var marker = markers.length ? markerNear(p.x, HIT_PX_TOUCH) : null; + if (marker) { + event.stopPropagation(); event.preventDefault(); + press = { dragging: true }; + drag = { id: marker.id, from: marker.t, fromSnap: marker.snap, snap: null }; + el('cc').classList.add('mk-drag'); + redraw(); + return; + } + var x0 = finger.clientX, y0 = finger.clientY; + press = { x0: x0, y0: y0, fired: false, timer: setTimeout(function () { + if (!press || press.dragging) return; + press.fired = true; press.timer = 0; + var cc = el('cc'); if (cc) cc.classList.remove('pan'); + var tip = el('tt'); if (tip) tip.style.display = 'none'; + var at = { clientX: x0, clientY: y0 }; + openMenu(at, canvasPoint(at), SNAP_PX_TOUCH); + }, LONG_PRESS_MS) }; + } + + function onTouchMove(event) { + if (!press) return; + if (press.dragging) { + event.stopPropagation(); event.preventDefault(); + var p = canvasPoint(event.touches[0]), snap = snapFor(p.x, p.y, SNAP_PX_TOUCH); + drag.snap = snap; + moveMarker(drag.id, clampTime(snap ? snap.t : ctx.x2t(p.x)), snap ? snap.text : ''); + afterChange(); + return; + } + if (press.fired) { event.stopPropagation(); event.preventDefault(); return; } + var finger = event.touches[0]; + if (event.touches.length !== 1 || Math.abs(finger.clientX - press.x0) > TOUCH_SLOP_PX || Math.abs(finger.clientY - press.y0) > TOUCH_SLOP_PX) { + endPress(); + } + } + + function onTouchEnd(event) { + if (!press) return; + if (press.dragging || press.fired) { + event.stopPropagation(); event.preventDefault(); + var cc = el('cc'); if (cc) cc.classList.remove('pan'); + if (press.dragging) onWindowUp(); + } + endPress(); + } + function onKeyDown(event) { if (event.key === 'Escape' && (menu || drag)) { event.preventDefault(); event.stopPropagation(); @@ -11070,6 +11165,10 @@ var SeqEyesMarkers = (function () { window.addEventListener('mouseup', onWindowUp); window.addEventListener('blur', onWindowUp); document.addEventListener('keydown', onKeyDown, true); + cc.addEventListener('touchstart', onTouchStart, { capture: true, passive: false }); + cc.addEventListener('touchmove', onTouchMove, { capture: true, passive: false }); + cc.addEventListener('touchend', onTouchEnd, { capture: true, passive: false }); + cc.addEventListener('touchcancel', onTouchEnd, { capture: true, passive: false }); buildTable(); var p = prefs(); if (p && p.KEYS.markerSnap) snapEnabled = p.getBool(p.KEYS.markerSnap, true); @@ -11082,7 +11181,7 @@ var SeqEyesMarkers = (function () { }; dev.addMarker = function (t, snap) { var m = addMarker(clampTime(t), snap); afterChange(); return m.id; }; dev.snapAt = function (t) { return ctx ? snapFor(ctx.t2x(t), null) : null; }; - dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()) : ''; }; + dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units(), derivedText()), units()) : ''; }; dev.markerState = function () { return { suggestion: currentSuggestion(), menuOpen: !!menu, dragging: !!drag, snapEnabled: snapEnabled, tableOpen: tableOpen }; }; @@ -11092,7 +11191,8 @@ var SeqEyesMarkers = (function () { /** * Hand the module a renderer's state. ctx: blocks(), duration(), margins(), * t2x, x2t, visChannels, cH, cy, channelRange, timeConv, timeUnitStr, - * gradConv, gradUnitStr, requestOverlay. A later install replaces an + * gradConv, gradUnitStr, requestOverlay, and optionally derivedLines(t) + * (the hover readout's M1/PNS lines). A later install replaces an * earlier one; the DOM is wired once. */ function install(context) { @@ -11106,6 +11206,7 @@ var SeqEyesMarkers = (function () { function reset() { clearMarkers(); drag = null; hover = null; hoverMarkerId = 0; snapCache = null; + endPress(); closeMenu(); var cc = typeof document !== 'undefined' ? el('cc') : null; if (cc) cc.classList.remove('mk-drag', 'mk-hover'); @@ -11549,7 +11650,8 @@ SeqEyesMarkers.install({ blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, - requestOverlay:drawCursorOverlay + requestOverlay:drawCursorOverlay, + derivedLines:function(t){var lines=[];appendDerivedTooltipLines(lines,t);return lines;} }); /* Deferred by one macrotask so web/index.html, whose inline IIFE runs after this bundle, has installed its own adapter before the persisted mode is diff --git a/src/editor/webview/assets/interaction.js b/src/editor/webview/assets/interaction.js index dfcee57..a9cdab4 100644 --- a/src/editor/webview/assets/interaction.js +++ b/src/editor/webview/assets/interaction.js @@ -404,7 +404,8 @@ SeqEyesMarkers.install({ blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, - requestOverlay:drawCursorOverlay + requestOverlay:drawCursorOverlay, + derivedLines:function(t){var lines=[];appendDerivedTooltipLines(lines,t);return lines;} }); /* Deferred by one macrotask so web/index.html, whose inline IIFE runs after this bundle, has installed its own adapter before the persisted mode is diff --git a/src/editor/webview/assets/markers.js b/src/editor/webview/assets/markers.js index a653496..04f4f21 100644 --- a/src/editor/webview/assets/markers.js +++ b/src/editor/webview/assets/markers.js @@ -22,6 +22,11 @@ var SeqEyesMarkers = (function () { var SNAP_PX = 8; var HIT_PX = 4; var REMOVE_PX = 6; + /* Fingers are wider and the press hides what is under it. */ + var SNAP_PX_TOUCH = 16; + var HIT_PX_TOUCH = 12; + var LONG_PRESS_MS = 500; + var TOUCH_SLOP_PX = 8; /* More blocks than this inside the snap distance means the view is too zoomed out for a corner to be a meaningful target. */ var MAX_SNAP_BLOCKS = 32; @@ -408,9 +413,11 @@ var SeqEyesMarkers = (function () { /** * One row per marker, in time order, with everything formatted in the - * viewer's current units. `list` is [{id, t, snap}]. + * viewer's current units. `list` is [{id, t, snap}]. `derived`, when + * given, returns the M1/PNS text for a time (the rows shown, as the hover + * readout words them). */ - function tableRows(list, blocks, detail, units) { + function tableRows(list, blocks, detail, units, derived) { var rows = []; for (var i = 0; i < list.length; i++) { var m = list[i], r = readoutAt(blocks, m.t, detail), previous = i > 0 ? list[i - 1] : null; @@ -428,6 +435,7 @@ var SeqEyesMarkers = (function () { phase: r.rf && isFinite(r.rf.phase) ? (r.rf.phase * 180 / Math.PI).toFixed(1) : '', adc: r.adc ? (r.adc.sample + 1) + '/' + r.adc.count : '', trigger: r.trigger ? 'on' : '', + derived: derived ? derived(m.t) : '', snap: m.snap || '', approx: !!(r.approx.gx || r.approx.gy || r.approx.gz || (r.rf && r.rf.approx)) }); @@ -435,20 +443,27 @@ var SeqEyesMarkers = (function () { return rows; } - function columns(units) { + function columns(units, withDerived) { var t = unitName(units.timeUnit), g = units.gradUnit; - return [ + var cols = [ ['name', 'Marker'], ['time', 'Time (' + t + ')'], ['delta', 'Δt (' + t + ')'], ['block', 'Block'], ['offset', 'In block (' + t + ')'], ['gx', 'Gx (' + g + ')'], ['gy', 'Gy (' + g + ')'], ['gz', 'Gz (' + g + ')'], ['rf', 'RF (Hz)'], ['phase', 'RF phase (°)'], ['adc', 'ADC sample'], ['trigger', 'Trigger'], ['snap', 'Snapped to'] ]; + if (withDerived) cols.splice(cols.length - 1, 0, ['derived', 'M1 / PNS']); + return cols; + } + + function hasDerived(rows) { + for (var i = 0; i < rows.length; i++) if (rows[i].derived) return true; + return false; } /** Tab-separated, with a header, for pasting into a spreadsheet. */ function toTsv(rows, units) { - var cols = columns(units), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; + var cols = columns(units, hasDerived(rows)), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; for (var i = 0; i < rows.length; i++) { lines.push(cols.map(function (c) { return String(rows[i][c[0]]).replace(/[\t\n]/g, ' '); }).join('\t')); } @@ -517,6 +532,15 @@ var SeqEyesMarkers = (function () { function el(id) { return document.getElementById(id); } function prefs() { return typeof SeqEyesPrefs !== 'undefined' ? SeqEyesPrefs : null; } + /** M1/PNS text at a time, when the renderer can give it and those rows are on. */ + function derivedText() { + if (!ctx || typeof ctx.derivedLines !== 'function') return null; + var rows = ctx.visChannels(), shown = false; + for (var i = 0; i < rows.length; i++) if (rows[i] >= 7 && rows[i] <= 10) shown = true; + if (!shown) return null; + return function (t) { return ctx.derivedLines(t).join(' '); }; + } + function units() { return { timeConv: ctx.timeConv, timeUnit: ctx.timeUnitStr(), gradConv: ctx.gradConv, gradUnit: ctx.gradUnitStr() }; } @@ -554,17 +578,18 @@ var SeqEyesMarkers = (function () { * Snap target under the pointer, or null. Cached: in the web app the * overlay is drawn twice a frame (once by the bundle, once by the page). */ - function snapFor(x, y) { + function snapFor(x, y, px) { if (!ctx || !snapEnabled) return null; var blocks = ctx.blocks(); if (!blocks || !blocks.length) return null; - var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + SNAP_PX) - t), rows = ctx.visChannels(); + var reach = px || SNAP_PX; + var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + reach) - t), rows = ctx.visChannels(); var pointerCi = y === null || y === undefined ? -1 : rowAt(y), detail = liveDetail(), rowKey = rows.join(','); var c = snapCache; if (c && c.blocks === blocks && c.detail === detail && c.t === t && c.tol === tol && c.ci === pointerCi && c.rows === rowKey) { return c.result; } - var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / SNAP_PX }); + var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / reach }); snapCache = { blocks: blocks, detail: detail, t: t, tol: tol, ci: pointerCi, rows: rowKey, result: result }; return result; } @@ -725,18 +750,19 @@ var SeqEyesMarkers = (function () { function syncTable() { if (!tableEl || !ctx) return; var u = units(), detail = liveDetail(), blocks = ctx.blocks(); - var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0].join('|'); + var derived = derivedText(), derivedKey = derived ? markers.map(function (m) { return derived(m.t); }).join('|') : ''; + var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0, derivedKey].join('|'); if (key === tableKey && tableEl.__blocks === blocks && tableEl.__detail === detail) return; tableKey = key; tableEl.__blocks = blocks; tableEl.__detail = detail; - renderTable(u, detail, blocks); + renderTable(u, detail, blocks, derived); } - function renderTable(u, detail, blocks) { + function renderTable(u, detail, blocks, derived) { var wasHidden = tableEl.hidden; tableEl.textContent = ''; tableEl.hidden = !markers.length; if (!markers.length) { if (!wasHidden) relayout(); return; } - var rows = tableRows(markers, blocks, detail, u); + var rows = tableRows(markers, blocks, detail, u, derived); var head = element('div', 'mk-head'); head.appendChild(element('span', 'mk-title', 'Markers')); var span = markers.length > 1 ? ' · span ' + formatTime(markers[markers.length - 1].t - markers[0].t, u) + ' ' + unitName(u.timeUnit) : ''; @@ -752,7 +778,7 @@ var SeqEyesMarkers = (function () { tableEl.appendChild(head); if (tableOpen) { var scroll = element('div', 'mk-scroll'), table = element('table'), thead = element('thead'), tr = element('tr'); - var cols = columns(u); + var cols = columns(u, hasDerived(rows)); cols.forEach(function (c) { tr.appendChild(element('th', null, c[1])); }); tr.appendChild(element('th')); thead.appendChild(tr); table.appendChild(thead); @@ -785,7 +811,7 @@ var SeqEyesMarkers = (function () { } function copyTable(source) { - var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()); + var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units(), derivedText()), units()); var done = function () { if (source) { var old = source.textContent; source.textContent = 'Copied'; setTimeout(function () { source.textContent = old; }, 1200); } }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); }); @@ -830,9 +856,10 @@ var SeqEyesMarkers = (function () { return row; } - function openMenu(event, p) { + function openMenu(event, p, reach) { closeMenu(); - var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y), near = markerNear(p.x, REMOVE_PX); + var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y, reach); + var near = markerNear(p.x, reach ? HIT_PX_TOUCH : REMOVE_PX); var time = function (seconds) { return formatTime(seconds, u) + ' ' + unitName(u.timeUnit); }; menuTarget = { x: p.x, y: p.y, snap: snap }; menu = element('div', 'lblc mk-menu'); menu.id = 'markerMenu'; @@ -845,7 +872,7 @@ var SeqEyesMarkers = (function () { menu.appendChild(menuToggle('Snap to corners and block edges', snapEnabled, function (on) { snapEnabled = on; var pr = prefs(); if (pr && pr.KEYS.markerSnap) pr.setBool(pr.KEYS.markerSnap, on); - menuTarget.snap = on ? snapFor(p.x, p.y) : null; + menuTarget.snap = on ? snapFor(p.x, p.y, reach) : null; snapCache = null; redraw(); })); if (markers.length) menu.appendChild(menuToggle('Show the marker table', tableOpen, function (on) { setTableOpen(on); })); @@ -948,6 +975,74 @@ var SeqEyesMarkers = (function () { redraw(); } + /* ── Touch ────────────────────────────────────────────────────────── + + Capture phase on #cc again, ahead of both renderers' touch handlers on + #mc. A finger on a marker drags it, and the renderer never starts its + pan. A finger held still opens the menu, and its later moves and lift + are swallowed so the view does not pan and the tap tooltip does not + show. Any other touch passes through untouched. */ + + /** {x0, y0, timer, fired} for a press that may become a long-press, or {dragging}. */ + var press = null; + + function endPress() { + if (press && press.timer) clearTimeout(press.timer); + press = null; + } + + function onTouchStart(event) { + endPress(); + if (!ctx || event.target !== el('mc') || event.touches.length !== 1) return; + var finger = event.touches[0], p = canvasPoint(finger); + if (!insidePlot(p)) return; + var marker = markers.length ? markerNear(p.x, HIT_PX_TOUCH) : null; + if (marker) { + event.stopPropagation(); event.preventDefault(); + press = { dragging: true }; + drag = { id: marker.id, from: marker.t, fromSnap: marker.snap, snap: null }; + el('cc').classList.add('mk-drag'); + redraw(); + return; + } + var x0 = finger.clientX, y0 = finger.clientY; + press = { x0: x0, y0: y0, fired: false, timer: setTimeout(function () { + if (!press || press.dragging) return; + press.fired = true; press.timer = 0; + var cc = el('cc'); if (cc) cc.classList.remove('pan'); + var tip = el('tt'); if (tip) tip.style.display = 'none'; + var at = { clientX: x0, clientY: y0 }; + openMenu(at, canvasPoint(at), SNAP_PX_TOUCH); + }, LONG_PRESS_MS) }; + } + + function onTouchMove(event) { + if (!press) return; + if (press.dragging) { + event.stopPropagation(); event.preventDefault(); + var p = canvasPoint(event.touches[0]), snap = snapFor(p.x, p.y, SNAP_PX_TOUCH); + drag.snap = snap; + moveMarker(drag.id, clampTime(snap ? snap.t : ctx.x2t(p.x)), snap ? snap.text : ''); + afterChange(); + return; + } + if (press.fired) { event.stopPropagation(); event.preventDefault(); return; } + var finger = event.touches[0]; + if (event.touches.length !== 1 || Math.abs(finger.clientX - press.x0) > TOUCH_SLOP_PX || Math.abs(finger.clientY - press.y0) > TOUCH_SLOP_PX) { + endPress(); + } + } + + function onTouchEnd(event) { + if (!press) return; + if (press.dragging || press.fired) { + event.stopPropagation(); event.preventDefault(); + var cc = el('cc'); if (cc) cc.classList.remove('pan'); + if (press.dragging) onWindowUp(); + } + endPress(); + } + function onKeyDown(event) { if (event.key === 'Escape' && (menu || drag)) { event.preventDefault(); event.stopPropagation(); @@ -973,6 +1068,10 @@ var SeqEyesMarkers = (function () { window.addEventListener('mouseup', onWindowUp); window.addEventListener('blur', onWindowUp); document.addEventListener('keydown', onKeyDown, true); + cc.addEventListener('touchstart', onTouchStart, { capture: true, passive: false }); + cc.addEventListener('touchmove', onTouchMove, { capture: true, passive: false }); + cc.addEventListener('touchend', onTouchEnd, { capture: true, passive: false }); + cc.addEventListener('touchcancel', onTouchEnd, { capture: true, passive: false }); buildTable(); var p = prefs(); if (p && p.KEYS.markerSnap) snapEnabled = p.getBool(p.KEYS.markerSnap, true); @@ -985,7 +1084,7 @@ var SeqEyesMarkers = (function () { }; dev.addMarker = function (t, snap) { var m = addMarker(clampTime(t), snap); afterChange(); return m.id; }; dev.snapAt = function (t) { return ctx ? snapFor(ctx.t2x(t), null) : null; }; - dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()) : ''; }; + dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units(), derivedText()), units()) : ''; }; dev.markerState = function () { return { suggestion: currentSuggestion(), menuOpen: !!menu, dragging: !!drag, snapEnabled: snapEnabled, tableOpen: tableOpen }; }; @@ -995,7 +1094,8 @@ var SeqEyesMarkers = (function () { /** * Hand the module a renderer's state. ctx: blocks(), duration(), margins(), * t2x, x2t, visChannels, cH, cy, channelRange, timeConv, timeUnitStr, - * gradConv, gradUnitStr, requestOverlay. A later install replaces an + * gradConv, gradUnitStr, requestOverlay, and optionally derivedLines(t) + * (the hover readout's M1/PNS lines). A later install replaces an * earlier one; the DOM is wired once. */ function install(context) { @@ -1009,6 +1109,7 @@ var SeqEyesMarkers = (function () { function reset() { clearMarkers(); drag = null; hover = null; hoverMarkerId = 0; snapCache = null; + endPress(); closeMenu(); var cc = typeof document !== 'undefined' ? el('cc') : null; if (cc) cc.classList.remove('mk-drag', 'mk-hover'); diff --git a/test/browser/markers.spec.ts b/test/browser/markers.spec.ts index 74ef37a..672aa6f 100644 --- a/test/browser/markers.spec.ts +++ b/test/browser/markers.spec.ts @@ -267,3 +267,73 @@ async function opaquePixelCount(locator: Locator): Promise { return count; }); } + +test('adds an M1 column once the M1 rows are shown', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + await rightClickAt(page, corners[1], 'Gx', 3); + await page.locator('#markerMenu .mk-item').first().click(); + await expect(page.locator('#mkTable th', { hasText: 'M1 / PNS' })).toHaveCount(0); + + await page.locator('#legend .li').filter({ hasText: 'M1x' }).click(); + await expect(page.locator('#mkTable th', { hasText: 'M1 / PNS' })).toHaveCount(1, { timeout: 20_000 }); + const cells = page.locator('#mkTable tbody tr').first().locator('td'); + await expect(cells.nth(12)).toHaveText(/^M1: M1x/); + expect(await page.evaluate(() => (window as unknown as { SeqEyesDev: { markerTable(): string } }).SeqEyesDev.markerTable())) + .toContain('M1 / PNS'); +}); + +test.describe('on a touch screen', () => { + test.use({ hasTouch: true }); + + test('a long-press opens the menu, a tap still shows the readout, and a finger drags a marker', async ({ page }) => { + const corners = firstGxTrapezoid(); + await loadViewer(page, gre); + await setView(page, corners[0] - 2e-4, corners[3] + 2e-4); + + // A tap is still the renderer's: the tooltip, no menu. + const tap = await pointFor(page, (corners[1] + corners[2]) / 2, 'Gx', 0); + await touch(page, 'touchstart', tap.x, tap.y); + await touch(page, 'touchend', tap.x, tap.y); + await expect(page.locator('#tt')).toBeVisible(); + await expect(page.locator('#markerMenu')).toHaveCount(0); + + // Held still, it opens the menu, which offers the corner within reach. + const offset = (await viewState(page)).offset; + const press = await pointFor(page, corners[1], 'Gx', 10); + await touch(page, 'touchstart', press.x, press.y); + await page.waitForTimeout(650); + await expect(page.locator('#markerMenu')).toBeVisible(); + await touch(page, 'touchmove', press.x + 30, press.y); + await touch(page, 'touchend', press.x + 30, press.y); + expect((await viewState(page)).offset).toBe(offset); + await expect(page.locator('#tt')).toBeHidden(); + await expect(page.locator('#markerMenu .mk-item').first()).toContainText('Add marker at Gx flat-top start'); + await page.locator('#markerMenu .mk-item').first().click(); + expect((await markerList(page)).map(m => m.snap.split(' · ')[0])).toEqual(['Gx flat-top start']); + + // A finger on the marker moves it instead of panning. + const grab = await pointFor(page, corners[1], 'Gx', 6); + const drop = await pointFor(page, corners[2], 'Gx', -10); + await touch(page, 'touchstart', grab.x, grab.y); + await touch(page, 'touchmove', (grab.x + drop.x) / 2, grab.y); + await touch(page, 'touchmove', drop.x, drop.y); + await touch(page, 'touchend', drop.x, drop.y); + expect((await viewState(page)).offset).toBe(offset); + const [marker] = await markerList(page); + expect(Math.abs(marker.t - corners[2])).toBeLessThan(1e-12); + }); +}); + +/** Dispatch one touch event on the plot, as a single finger. */ +async function touch(page: Page, type: string, x: number, y: number): Promise { + await page.evaluate(({ type, x, y }) => { + const mc = document.getElementById('mc')!; + const finger = new Touch({ identifier: 1, target: mc, clientX: x, clientY: y }); + const down = type === 'touchend' ? [] : [finger]; + mc.dispatchEvent(new TouchEvent(type, { + touches: down, targetTouches: down, changedTouches: [finger], bubbles: true, cancelable: true, + })); + }, { type, x, y }); +} diff --git a/web/index.html b/web/index.html index dc4da70..f4aa59b 100644 --- a/web/index.html +++ b/web/index.html @@ -3020,7 +3020,8 @@

SeqEyes

blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, - requestOverlay:drawCursorOverlay + requestOverlay:drawCursorOverlay, + derivedLines:function(t){var lines=[];appendDerivedTooltipLines(lines,t);return lines;} }); /* Re-apply the ASC profile cached from an earlier session. Only the display diff --git a/web/webview-bundle.js b/web/webview-bundle.js index fb2d3b8..515e364 100644 --- a/web/webview-bundle.js +++ b/web/webview-bundle.js @@ -10119,6 +10119,11 @@ var SeqEyesMarkers = (function () { var SNAP_PX = 8; var HIT_PX = 4; var REMOVE_PX = 6; + /* Fingers are wider and the press hides what is under it. */ + var SNAP_PX_TOUCH = 16; + var HIT_PX_TOUCH = 12; + var LONG_PRESS_MS = 500; + var TOUCH_SLOP_PX = 8; /* More blocks than this inside the snap distance means the view is too zoomed out for a corner to be a meaningful target. */ var MAX_SNAP_BLOCKS = 32; @@ -10505,9 +10510,11 @@ var SeqEyesMarkers = (function () { /** * One row per marker, in time order, with everything formatted in the - * viewer's current units. `list` is [{id, t, snap}]. + * viewer's current units. `list` is [{id, t, snap}]. `derived`, when + * given, returns the M1/PNS text for a time (the rows shown, as the hover + * readout words them). */ - function tableRows(list, blocks, detail, units) { + function tableRows(list, blocks, detail, units, derived) { var rows = []; for (var i = 0; i < list.length; i++) { var m = list[i], r = readoutAt(blocks, m.t, detail), previous = i > 0 ? list[i - 1] : null; @@ -10525,6 +10532,7 @@ var SeqEyesMarkers = (function () { phase: r.rf && isFinite(r.rf.phase) ? (r.rf.phase * 180 / Math.PI).toFixed(1) : '', adc: r.adc ? (r.adc.sample + 1) + '/' + r.adc.count : '', trigger: r.trigger ? 'on' : '', + derived: derived ? derived(m.t) : '', snap: m.snap || '', approx: !!(r.approx.gx || r.approx.gy || r.approx.gz || (r.rf && r.rf.approx)) }); @@ -10532,20 +10540,27 @@ var SeqEyesMarkers = (function () { return rows; } - function columns(units) { + function columns(units, withDerived) { var t = unitName(units.timeUnit), g = units.gradUnit; - return [ + var cols = [ ['name', 'Marker'], ['time', 'Time (' + t + ')'], ['delta', 'Δt (' + t + ')'], ['block', 'Block'], ['offset', 'In block (' + t + ')'], ['gx', 'Gx (' + g + ')'], ['gy', 'Gy (' + g + ')'], ['gz', 'Gz (' + g + ')'], ['rf', 'RF (Hz)'], ['phase', 'RF phase (°)'], ['adc', 'ADC sample'], ['trigger', 'Trigger'], ['snap', 'Snapped to'] ]; + if (withDerived) cols.splice(cols.length - 1, 0, ['derived', 'M1 / PNS']); + return cols; + } + + function hasDerived(rows) { + for (var i = 0; i < rows.length; i++) if (rows[i].derived) return true; + return false; } /** Tab-separated, with a header, for pasting into a spreadsheet. */ function toTsv(rows, units) { - var cols = columns(units), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; + var cols = columns(units, hasDerived(rows)), lines = [cols.map(function (c) { return c[1]; }).join('\t')]; for (var i = 0; i < rows.length; i++) { lines.push(cols.map(function (c) { return String(rows[i][c[0]]).replace(/[\t\n]/g, ' '); }).join('\t')); } @@ -10614,6 +10629,15 @@ var SeqEyesMarkers = (function () { function el(id) { return document.getElementById(id); } function prefs() { return typeof SeqEyesPrefs !== 'undefined' ? SeqEyesPrefs : null; } + /** M1/PNS text at a time, when the renderer can give it and those rows are on. */ + function derivedText() { + if (!ctx || typeof ctx.derivedLines !== 'function') return null; + var rows = ctx.visChannels(), shown = false; + for (var i = 0; i < rows.length; i++) if (rows[i] >= 7 && rows[i] <= 10) shown = true; + if (!shown) return null; + return function (t) { return ctx.derivedLines(t).join(' '); }; + } + function units() { return { timeConv: ctx.timeConv, timeUnit: ctx.timeUnitStr(), gradConv: ctx.gradConv, gradUnit: ctx.gradUnitStr() }; } @@ -10651,17 +10675,18 @@ var SeqEyesMarkers = (function () { * Snap target under the pointer, or null. Cached: in the web app the * overlay is drawn twice a frame (once by the bundle, once by the page). */ - function snapFor(x, y) { + function snapFor(x, y, px) { if (!ctx || !snapEnabled) return null; var blocks = ctx.blocks(); if (!blocks || !blocks.length) return null; - var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + SNAP_PX) - t), rows = ctx.visChannels(); + var reach = px || SNAP_PX; + var t = ctx.x2t(x), tol = Math.abs(ctx.x2t(x + reach) - t), rows = ctx.visChannels(); var pointerCi = y === null || y === undefined ? -1 : rowAt(y), detail = liveDetail(), rowKey = rows.join(','); var c = snapCache; if (c && c.blocks === blocks && c.detail === detail && c.t === t && c.tol === tol && c.ci === pointerCi && c.rows === rowKey) { return c.result; } - var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / SNAP_PX }); + var result = snapAt(blocks, t, tol, { rows: rows, pointerCi: pointerCi, detail: detail, onePx: tol / reach }); snapCache = { blocks: blocks, detail: detail, t: t, tol: tol, ci: pointerCi, rows: rowKey, result: result }; return result; } @@ -10822,18 +10847,19 @@ var SeqEyesMarkers = (function () { function syncTable() { if (!tableEl || !ctx) return; var u = units(), detail = liveDetail(), blocks = ctx.blocks(); - var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0].join('|'); + var derived = derivedText(), derivedKey = derived ? markers.map(function (m) { return derived(m.t); }).join('|') : ''; + var key = [version, markers.length, u.timeUnit, u.gradUnit, tableOpen, detail ? detail.startSec + ':' + detail.endSec : '-', blocks ? blocks.length : 0, derivedKey].join('|'); if (key === tableKey && tableEl.__blocks === blocks && tableEl.__detail === detail) return; tableKey = key; tableEl.__blocks = blocks; tableEl.__detail = detail; - renderTable(u, detail, blocks); + renderTable(u, detail, blocks, derived); } - function renderTable(u, detail, blocks) { + function renderTable(u, detail, blocks, derived) { var wasHidden = tableEl.hidden; tableEl.textContent = ''; tableEl.hidden = !markers.length; if (!markers.length) { if (!wasHidden) relayout(); return; } - var rows = tableRows(markers, blocks, detail, u); + var rows = tableRows(markers, blocks, detail, u, derived); var head = element('div', 'mk-head'); head.appendChild(element('span', 'mk-title', 'Markers')); var span = markers.length > 1 ? ' · span ' + formatTime(markers[markers.length - 1].t - markers[0].t, u) + ' ' + unitName(u.timeUnit) : ''; @@ -10849,7 +10875,7 @@ var SeqEyesMarkers = (function () { tableEl.appendChild(head); if (tableOpen) { var scroll = element('div', 'mk-scroll'), table = element('table'), thead = element('thead'), tr = element('tr'); - var cols = columns(u); + var cols = columns(u, hasDerived(rows)); cols.forEach(function (c) { tr.appendChild(element('th', null, c[1])); }); tr.appendChild(element('th')); thead.appendChild(tr); table.appendChild(thead); @@ -10882,7 +10908,7 @@ var SeqEyesMarkers = (function () { } function copyTable(source) { - var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()); + var text = toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units(), derivedText()), units()); var done = function () { if (source) { var old = source.textContent; source.textContent = 'Copied'; setTimeout(function () { source.textContent = old; }, 1200); } }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); }); @@ -10927,9 +10953,10 @@ var SeqEyesMarkers = (function () { return row; } - function openMenu(event, p) { + function openMenu(event, p, reach) { closeMenu(); - var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y), near = markerNear(p.x, REMOVE_PX); + var u = units(), t = clampTime(ctx.x2t(p.x)), snap = snapFor(p.x, p.y, reach); + var near = markerNear(p.x, reach ? HIT_PX_TOUCH : REMOVE_PX); var time = function (seconds) { return formatTime(seconds, u) + ' ' + unitName(u.timeUnit); }; menuTarget = { x: p.x, y: p.y, snap: snap }; menu = element('div', 'lblc mk-menu'); menu.id = 'markerMenu'; @@ -10942,7 +10969,7 @@ var SeqEyesMarkers = (function () { menu.appendChild(menuToggle('Snap to corners and block edges', snapEnabled, function (on) { snapEnabled = on; var pr = prefs(); if (pr && pr.KEYS.markerSnap) pr.setBool(pr.KEYS.markerSnap, on); - menuTarget.snap = on ? snapFor(p.x, p.y) : null; + menuTarget.snap = on ? snapFor(p.x, p.y, reach) : null; snapCache = null; redraw(); })); if (markers.length) menu.appendChild(menuToggle('Show the marker table', tableOpen, function (on) { setTableOpen(on); })); @@ -11045,6 +11072,74 @@ var SeqEyesMarkers = (function () { redraw(); } + /* ── Touch ────────────────────────────────────────────────────────── + + Capture phase on #cc again, ahead of both renderers' touch handlers on + #mc. A finger on a marker drags it, and the renderer never starts its + pan. A finger held still opens the menu, and its later moves and lift + are swallowed so the view does not pan and the tap tooltip does not + show. Any other touch passes through untouched. */ + + /** {x0, y0, timer, fired} for a press that may become a long-press, or {dragging}. */ + var press = null; + + function endPress() { + if (press && press.timer) clearTimeout(press.timer); + press = null; + } + + function onTouchStart(event) { + endPress(); + if (!ctx || event.target !== el('mc') || event.touches.length !== 1) return; + var finger = event.touches[0], p = canvasPoint(finger); + if (!insidePlot(p)) return; + var marker = markers.length ? markerNear(p.x, HIT_PX_TOUCH) : null; + if (marker) { + event.stopPropagation(); event.preventDefault(); + press = { dragging: true }; + drag = { id: marker.id, from: marker.t, fromSnap: marker.snap, snap: null }; + el('cc').classList.add('mk-drag'); + redraw(); + return; + } + var x0 = finger.clientX, y0 = finger.clientY; + press = { x0: x0, y0: y0, fired: false, timer: setTimeout(function () { + if (!press || press.dragging) return; + press.fired = true; press.timer = 0; + var cc = el('cc'); if (cc) cc.classList.remove('pan'); + var tip = el('tt'); if (tip) tip.style.display = 'none'; + var at = { clientX: x0, clientY: y0 }; + openMenu(at, canvasPoint(at), SNAP_PX_TOUCH); + }, LONG_PRESS_MS) }; + } + + function onTouchMove(event) { + if (!press) return; + if (press.dragging) { + event.stopPropagation(); event.preventDefault(); + var p = canvasPoint(event.touches[0]), snap = snapFor(p.x, p.y, SNAP_PX_TOUCH); + drag.snap = snap; + moveMarker(drag.id, clampTime(snap ? snap.t : ctx.x2t(p.x)), snap ? snap.text : ''); + afterChange(); + return; + } + if (press.fired) { event.stopPropagation(); event.preventDefault(); return; } + var finger = event.touches[0]; + if (event.touches.length !== 1 || Math.abs(finger.clientX - press.x0) > TOUCH_SLOP_PX || Math.abs(finger.clientY - press.y0) > TOUCH_SLOP_PX) { + endPress(); + } + } + + function onTouchEnd(event) { + if (!press) return; + if (press.dragging || press.fired) { + event.stopPropagation(); event.preventDefault(); + var cc = el('cc'); if (cc) cc.classList.remove('pan'); + if (press.dragging) onWindowUp(); + } + endPress(); + } + function onKeyDown(event) { if (event.key === 'Escape' && (menu || drag)) { event.preventDefault(); event.stopPropagation(); @@ -11070,6 +11165,10 @@ var SeqEyesMarkers = (function () { window.addEventListener('mouseup', onWindowUp); window.addEventListener('blur', onWindowUp); document.addEventListener('keydown', onKeyDown, true); + cc.addEventListener('touchstart', onTouchStart, { capture: true, passive: false }); + cc.addEventListener('touchmove', onTouchMove, { capture: true, passive: false }); + cc.addEventListener('touchend', onTouchEnd, { capture: true, passive: false }); + cc.addEventListener('touchcancel', onTouchEnd, { capture: true, passive: false }); buildTable(); var p = prefs(); if (p && p.KEYS.markerSnap) snapEnabled = p.getBool(p.KEYS.markerSnap, true); @@ -11082,7 +11181,7 @@ var SeqEyesMarkers = (function () { }; dev.addMarker = function (t, snap) { var m = addMarker(clampTime(t), snap); afterChange(); return m.id; }; dev.snapAt = function (t) { return ctx ? snapFor(ctx.t2x(t), null) : null; }; - dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units()), units()) : ''; }; + dev.markerTable = function () { return ctx ? toTsv(tableRows(markers, ctx.blocks(), liveDetail(), units(), derivedText()), units()) : ''; }; dev.markerState = function () { return { suggestion: currentSuggestion(), menuOpen: !!menu, dragging: !!drag, snapEnabled: snapEnabled, tableOpen: tableOpen }; }; @@ -11092,7 +11191,8 @@ var SeqEyesMarkers = (function () { /** * Hand the module a renderer's state. ctx: blocks(), duration(), margins(), * t2x, x2t, visChannels, cH, cy, channelRange, timeConv, timeUnitStr, - * gradConv, gradUnitStr, requestOverlay. A later install replaces an + * gradConv, gradUnitStr, requestOverlay, and optionally derivedLines(t) + * (the hover readout's M1/PNS lines). A later install replaces an * earlier one; the DOM is wired once. */ function install(context) { @@ -11106,6 +11206,7 @@ var SeqEyesMarkers = (function () { function reset() { clearMarkers(); drag = null; hover = null; hoverMarkerId = 0; snapCache = null; + endPress(); closeMenu(); var cc = typeof document !== 'undefined' ? el('cc') : null; if (cc) cc.classList.remove('mk-drag', 'mk-hover'); @@ -11549,7 +11650,8 @@ SeqEyesMarkers.install({ blocks:function(){return BL;},duration:function(){return TD;},margins:function(){return M;}, t2x:t2x,x2t:x2t,visChannels:visChannels,cH:cH,cy:cy,channelRange:channelRange, timeConv:timeConv,timeUnitStr:timeUnitStr,gradConv:gradConv,gradUnitStr:gradUnitStr, - requestOverlay:drawCursorOverlay + requestOverlay:drawCursorOverlay, + derivedLines:function(t){var lines=[];appendDerivedTooltipLines(lines,t);return lines;} }); /* Deferred by one macrotask so web/index.html, whose inline IIFE runs after this bundle, has installed its own adapter before the persisted mode is From a31d49a1c0e1c32dba93bda815252001d07e0945 Mon Sep 17 00:00:00 2001 From: Haotian Hong Date: Fri, 23 Oct 2026 16:34:29 -0400 Subject: [PATCH 5/7] Lead marker rows with their remove button, theme the table's scrollbar, default to mT/m MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The marker table's × moves from the last column to the first, so it stays in reach when the table is wider than the window. Cells now carry data-col, and alignment uses classes rather than column positions, which shift when the M1/PNS column appears. - The table's scrollbars use the theme's colours (thumb --ax, hovered --lb, on the strip's --trbg), via ::-webkit-scrollbar in Chromium, VS Code and Safari, and scrollbar-color elsewhere. They replace the platform's light grey bar, which stood out in dark themes. - Gradients read in mT/m by default in the web app, VS Code and MATLAB. A unit someone has already chosen is still restored. The Python viewer's grad_disp default is part of its API and is unchanged. The persistence test now picks G/cm, since choosing the default proved nothing, and the opt-out test expects the new default. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/seqeyes/resources/webview-bundle.js | 25 +++++++++++++------ src/editor/webview/assets/markers.js | 23 ++++++++++++----- src/editor/webview/assets/state.js | 2 +- src/editor/webview/assets/styles.css | 10 +++++++- src/editor/webview/assets/template.html | 2 +- test/browser/markers.spec.ts | 10 +++++--- test/browser/persisted-settings.spec.ts | 6 ++--- test/browser/vscode-webview.spec.ts | 2 +- web/index.html | 4 +-- web/styles.css | 10 +++++++- web/webview-bundle.js | 25 +++++++++++++------ 11 files changed, 86 insertions(+), 33 deletions(-) diff --git a/python/src/seqeyes/resources/webview-bundle.js b/python/src/seqeyes/resources/webview-bundle.js index 515e364..52da89d 100644 --- a/python/src/seqeyes/resources/webview-bundle.js +++ b/python/src/seqeyes/resources/webview-bundle.js @@ -1041,7 +1041,7 @@ var cursorT=0,cursorActive=false; // mouse time position putting the viewer in a state its own toolbar cannot express. */ function selectOptionValues(sel){var out=[],i;if(!sel)return out;for(i=0;iTheme:
Time: -Grad: +Grad:
diff --git a/test/browser/markers.spec.ts b/test/browser/markers.spec.ts index 672aa6f..6538680 100644 --- a/test/browser/markers.spec.ts +++ b/test/browser/markers.spec.ts @@ -79,8 +79,13 @@ test('right-click adds a marker snapped to a gradient corner, and a second gives await expect(table).toBeVisible(); await expect(table.locator('tbody tr')).toHaveCount(2); const delta = ((corners[2] - corners[1]) * 1e3).toFixed(4); - await expect(table.locator('tbody tr').nth(1).locator('td').nth(2)).toHaveText(delta); + await expect(table.locator('tbody tr').nth(1).locator('td[data-col="delta"]')).toHaveText(delta); await expect(table.locator('.mk-summary')).toContainText('span ' + delta + ' ms'); + // Gradients read in mT/m by default, and each row leads with its remove button. + await expect(page.locator('#gu')).toHaveValue('mT/m'); + await expect(table.locator('th[data-col="gx"]')).toHaveText('Gx (mT/m)'); + await expect(table.locator('tbody tr').first().locator('td').first().locator('button')).toHaveText('×'); + await expect(table.locator('thead th').nth(1)).toHaveText('Marker'); // Once markers are in use, approaching a corner suggests it. await hoverAt(page, corners[3], 'Gx', 2); @@ -278,8 +283,7 @@ test('adds an M1 column once the M1 rows are shown', async ({ page }) => { await page.locator('#legend .li').filter({ hasText: 'M1x' }).click(); await expect(page.locator('#mkTable th', { hasText: 'M1 / PNS' })).toHaveCount(1, { timeout: 20_000 }); - const cells = page.locator('#mkTable tbody tr').first().locator('td'); - await expect(cells.nth(12)).toHaveText(/^M1: M1x/); + await expect(page.locator('#mkTable tbody tr').first().locator('td[data-col="derived"]')).toHaveText(/^M1: M1x/); expect(await page.evaluate(() => (window as unknown as { SeqEyesDev: { markerTable(): string } }).SeqEyesDev.markerTable())) .toContain('M1 / PNS'); }); diff --git a/test/browser/persisted-settings.spec.ts b/test/browser/persisted-settings.spec.ts index 4e8f31f..7636bb2 100644 --- a/test/browser/persisted-settings.spec.ts +++ b/test/browser/persisted-settings.spec.ts @@ -70,7 +70,7 @@ test('brings back the units, Blocks toggle and k-space controls after a reload', await loadSequence(page); await page.locator('#tu').selectOption('us'); - await page.locator('#gu').selectOption('mT/m'); + await page.locator('#gu').selectOption('G/cm'); await page.locator('#bbc').check(); await page.locator('#theme').selectOption('nord'); @@ -82,7 +82,7 @@ test('brings back the units, Blocks toggle and k-space controls after a reload', await openViewer(page); await expect(page.locator('#tu')).toHaveValue('us'); - await expect(page.locator('#gu')).toHaveValue('mT/m'); + await expect(page.locator('#gu')).toHaveValue('G/cm'); await expect(page.locator('#bbc')).toBeChecked(); await expect(page.locator('#theme')).toHaveValue('nord'); await expect(page.locator('body')).toHaveClass(/theme-nord/); @@ -133,7 +133,7 @@ test('stores nothing and returns to defaults once the user opts out', async ({ p await openViewer(page); await expect(page.locator('#tu')).toHaveValue('ms'); - await expect(page.locator('#gu')).toHaveValue('Hz/m'); + await expect(page.locator('#gu')).toHaveValue('mT/m'); await expect(page.locator('#prefsBtn')).toBeVisible(); }); diff --git a/test/browser/vscode-webview.spec.ts b/test/browser/vscode-webview.spec.ts index f8803cd..c9b8d88 100644 --- a/test/browser/vscode-webview.spec.ts +++ b/test/browser/vscode-webview.spec.ts @@ -803,7 +803,7 @@ test('adds a measurement marker from the right-click menu', async ({ page }) => await items.first().click(); await expect(page.locator('#mkTable tbody tr')).toHaveCount(1); - await expect(page.locator('#mkTable tbody tr td').first()).toHaveText('M1'); + await expect(page.locator('#mkTable tbody tr td[data-col="name"]')).toHaveText('M1'); const markers = await page.evaluate(() => (window as unknown as { SeqEyesDev: { markers(): { t: number }[] } }).SeqEyesDev.markers()); expect(markers).toHaveLength(1); diff --git a/web/index.html b/web/index.html index f4aa59b..192ca07 100644 --- a/web/index.html +++ b/web/index.html @@ -77,7 +77,7 @@

SeqEyes

Theme:
Time: -Grad: +Grad:
@@ -269,7 +269,7 @@

SeqEyes

the viewer in a state its own toolbar cannot express. */ function selectOptionValues(sel){var out=[],i;if(!sel)return out;for(i=0;i Date: Fri, 23 Oct 2026 16:58:34 -0400 Subject: [PATCH 6/7] Default the Python viewer to mT/m too The web app, VS Code and MATLAB viewers now open in mT/m, so the Python package follows: `grad_disp` defaults to "mT/m" in `SeqEyesViewer`, `render_html` and the patched `Sequence.plot`. An unsupported unit falls back to it, and the bundled viewer template selects it. Passing grad_disp="Hz/m" still works as before. The demo notebook's parameter table says so (it also listed Hz/m twice). Co-Authored-By: Claude Opus 5.5 (1M context) --- python/examples/demo.ipynb | 2 +- python/src/seqeyes/_plot.py | 2 +- python/src/seqeyes/_renderer.py | 11 ++++++----- python/src/seqeyes/resources/viewer.html | 6 +++--- python/tests/test_plot.py | 6 +++--- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/python/examples/demo.ipynb b/python/examples/demo.ipynb index 4833da8..f6925a4 100644 --- a/python/examples/demo.ipynb +++ b/python/examples/demo.ipynb @@ -311,7 +311,7 @@ "| `show_blocks` | `False` | Show block‑boundary lines |\n", "| `time_range` | `(0, inf)` | Zoom to `(start_sec, end_sec)` |\n", "| `time_disp` | `\"s\"` | Time unit: `\"s\"`, `\"ms\"`, `\"us\"` |\n", - "| `grad_disp` | `\"Hz/m\"` | Gradient unit: `\"Hz/m\"`, `\"Hz/m\"`, `\"mT/m\"`, `\"G/cm\"` |\n", + "| `grad_disp` | `\"mT/m\"` | Gradient unit: `\"mT/m\"`, `\"Hz/m\"`, `\"G/cm\"` |\n", "| `theme` | `\"system\"` | `\"light\"`, `\"dark\"`, `\"dracula\"`, `\"nord\"`, ... |" ] }, diff --git a/python/src/seqeyes/_plot.py b/python/src/seqeyes/_plot.py index 29acd31..32ff640 100644 --- a/python/src/seqeyes/_plot.py +++ b/python/src/seqeyes/_plot.py @@ -120,7 +120,7 @@ def _seqeyes_plot( show_blocks: bool = False, time_range: Any = (0, float("inf")), time_disp: str = "s", - grad_disp: str = "Hz/m", + grad_disp: str = "mT/m", **kwargs: Any, ) -> None: # Merge globals — per‑call args take precedence diff --git a/python/src/seqeyes/_renderer.py b/python/src/seqeyes/_renderer.py index 1002cf1..972860d 100644 --- a/python/src/seqeyes/_renderer.py +++ b/python/src/seqeyes/_renderer.py @@ -76,7 +76,7 @@ def _read_viewer_template() -> str: def _normalize_grad_disp(unit: str) -> str: """Return a viewer-supported gradient unit.""" - return unit if unit in _VALID_GRAD_UNITS else "Hz/m" + return unit if unit in _VALID_GRAD_UNITS else "mT/m" def _build_html( @@ -88,7 +88,7 @@ def _build_html( show_blocks: bool = False, time_range: tuple = (0, float("inf")), time_disp: str = "s", - grad_disp: str = "Hz/m", + grad_disp: str = "mT/m", ) -> str: """Assemble the complete viewer HTML. @@ -109,7 +109,8 @@ def _build_html( time_disp : str Initial time display unit (``"s"``, ``"ms"``, ``"us"``). grad_disp : str - Initial gradient display unit (``"Hz/m"``, ``"mT/m"``, ``"G/cm"``). + Initial gradient display unit (``"mT/m"``, the default, ``"Hz/m"`` + or ``"G/cm"``). """ template = _read_viewer_template() grad_disp = _normalize_grad_disp(grad_disp) @@ -189,7 +190,7 @@ class SeqEyesViewer: time_disp : str Time axis unit — ``"s"``, ``"ms"``, or ``"us"``. grad_disp : str - Gradient axis unit — ``"Hz/m"``, ``"mT/m"``, or ``"G/cm"``. + Gradient axis unit — ``"mT/m"`` (default), ``"Hz/m"``, or ``"G/cm"``. theme : str or None Colour theme. width : str @@ -206,7 +207,7 @@ def __init__( show_blocks: bool = False, time_range: tuple = (0, float("inf")), time_disp: str = "s", - grad_disp: str = "Hz/m", + grad_disp: str = "mT/m", theme: Optional[str] = None, width: str = "100%", height: str = "550px", diff --git a/python/src/seqeyes/resources/viewer.html b/python/src/seqeyes/resources/viewer.html index 1de4521..865ca79 100644 --- a/python/src/seqeyes/resources/viewer.html +++ b/python/src/seqeyes/resources/viewer.html @@ -114,7 +114,7 @@ Theme:
Time: -Grad: +Grad:
@@ -171,7 +171,7 @@ var ox=0,sc=1; var dr=false,dsx=0,dso=0; var cursorT=0,cursorActive=false; -var timeUnit='ms',gradUnit='Hz/m'; +var timeUnit='ms',gradUnit='mT/m'; var showBB=false; var GAMMA=42576; var ampZoom=[1,1,1,1,1,1,1,1,1,1,1,1]; @@ -201,7 +201,7 @@ // ── Unit conversion ── function gradConv(v){if(gradUnit==='mT/m')return v/GAMMA;if(gradUnit==='G/cm')return v/(GAMMA*10);return v;} function gradUnitStr(){return gradUnit;} -function normalizeGradUnit(unit){return(unit==='mT/m'||unit==='G/cm'||unit==='Hz/m')?unit:'Hz/m';} +function normalizeGradUnit(unit){return(unit==='mT/m'||unit==='G/cm'||unit==='Hz/m')?unit:'mT/m';} function timeConv(t){if(timeUnit==='ms')return t*1e3;if(timeUnit==='us')return t*1e6;return t;} function timeUnitStr(){return timeUnit;} diff --git a/python/tests/test_plot.py b/python/tests/test_plot.py index 669687d..4815b45 100644 --- a/python/tests/test_plot.py +++ b/python/tests/test_plot.py @@ -111,15 +111,15 @@ def test_viewer_with_units(self): assert '"ms"' in raw assert '"mT/m"' in raw - def test_viewer_default_gradient_unit_is_hz_per_m(self): + def test_viewer_default_gradient_unit_is_mt_per_m(self): v = SeqEyesViewer(SAMPLE_SEQ_TEXT) raw = v.to_html(inject_bundle=False) - assert 'window.SEQEYES_GRAD_DISP = "Hz/m";' in raw + assert 'window.SEQEYES_GRAD_DISP = "mT/m";' in raw def test_viewer_normalizes_unsupported_gradient_unit(self): v = SeqEyesViewer(SAMPLE_SEQ_TEXT, grad_disp="kHz/m") raw = v.to_html(inject_bundle=False) - assert 'window.SEQEYES_GRAD_DISP = "Hz/m";' in raw + assert 'window.SEQEYES_GRAD_DISP = "mT/m";' in raw assert "kHz/m" not in raw From 248546222785a59c573c4b9ac4fd179eef77b456 Mon Sep 17 00:00:00 2001 From: Haotian Hong Date: Fri, 23 Oct 2026 16:58:50 -0400 Subject: [PATCH 7/7] Release v0.4.1 Bump every surface carrying a version: package.json, both root package-lock entries, python/pyproject.toml, the Python __version__, matlab/toolboxInfo.xml, and the generated pulseq bundles. The lock entries are edited by line, so a dependency sharing the version is not rewritten. This release adds measurement markers to the waveform viewer and makes mT/m the default gradient unit in every host. Co-Authored-By: Claude Opus 5.5 (1M context) --- matlab/toolboxInfo.xml | 2 +- package-lock.json | 4 ++-- package.json | 2 +- python/pyproject.toml | 2 +- python/src/seqeyes/__init__.py | 2 +- python/src/seqeyes/resources/pulseq-bundle.js | 2 +- web/pulseq-bundle.js | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/matlab/toolboxInfo.xml b/matlab/toolboxInfo.xml index e4744ec..a1375d3 100644 --- a/matlab/toolboxInfo.xml +++ b/matlab/toolboxInfo.xml @@ -2,7 +2,7 @@ SeqEyes seqeyes - 0.4.0 + 0.4.1 R2022a SeqEyes Developers diff --git a/package-lock.json b/package-lock.json index 41e368c..053ce11 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seqeyes-web", - "version": "0.4.0", + "version": "0.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seqeyes-web", - "version": "0.4.0", + "version": "0.4.1", "license": "MIT", "devDependencies": { "@playwright/test": "^1.61.1", diff --git a/package.json b/package.json index bc8f1be..4f74261 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "seqeyes-web", "displayName": "SeqEyes", "description": "Visualize Pulseq .seq and .bseq MRI sequences inside VS Code with interactive diagrams and k-space trajectories.", - "version": "0.4.0", + "version": "0.4.1", "publisher": "SeqEyesDeveloper", "license": "MIT", "icon": "images/logo.png", diff --git a/python/pyproject.toml b/python/pyproject.toml index 3081ec1..4fded84 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "seqeyes-python" -version = "0.4.0" +version = "0.4.1" description = "Interactive Pulseq MRI sequence viewer for Jupyter — lightweight, beautiful, replaces seq.plot() in pypulseq." readme = "README.md" license = {text = "MIT"} diff --git a/python/src/seqeyes/__init__.py b/python/src/seqeyes/__init__.py index fd5bcc0..b1d56cd 100644 --- a/python/src/seqeyes/__init__.py +++ b/python/src/seqeyes/__init__.py @@ -29,4 +29,4 @@ from seqeyes._renderer import SeqEyesViewer __all__ = ["set", "reset", "SeqEyesViewer"] -__version__ = "0.4.0" +__version__ = "0.4.1" diff --git a/python/src/seqeyes/resources/pulseq-bundle.js b/python/src/seqeyes/resources/pulseq-bundle.js index 3b2a453..9c2c808 100644 --- a/python/src/seqeyes/resources/pulseq-bundle.js +++ b/python/src/seqeyes/resources/pulseq-bundle.js @@ -90,7 +90,7 @@ var Pulseq = (() => { }); // package.json - var version = "0.4.0"; + var version = "0.4.1"; // src/pulseq/decompressor.ts function decompressShape(compressed, numSamples) { diff --git a/web/pulseq-bundle.js b/web/pulseq-bundle.js index 3b2a453..9c2c808 100644 --- a/web/pulseq-bundle.js +++ b/web/pulseq-bundle.js @@ -90,7 +90,7 @@ var Pulseq = (() => { }); // package.json - var version = "0.4.0"; + var version = "0.4.1"; // src/pulseq/decompressor.ts function decompressShape(compressed, numSamples) {