-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfigure_esm.js
More file actions
3615 lines (3331 loc) · 157 KB
/
figure_esm.js
File metadata and controls
3615 lines (3331 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// figure_esm.js
// Unified JS renderer for the Figure widget.
// Each panel gets its own three-canvas stack (plot / overlay / markers).
// Panels are drawn independently; only the changed panel's listener fires.
function render({ model, el }) {
const dpr = window.devicePixelRatio || 1;
// ── shared plot-area padding (mirrors 1D drawing constants) ─────────────
// The image/plot area for BOTH 1D and 2D panels sits at:
// x: PAD_L → pw-PAD_R, y: PAD_T → ph-PAD_B
// This guarantees pixel-perfect alignment of all panels in a row/column.
const PAD_L=58, PAD_R=12, PAD_T=12, PAD_B=42;
// ── theme ────────────────────────────────────────────────────────────────
function _isDarkBg(node) {
while (node && node !== document.body) {
const bg = window.getComputedStyle(node).backgroundColor;
const m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (m) {
const [r,g,b] = [+m[1],+m[2],+m[3]];
if (!(r===0&&g===0&&b===0&&bg.includes('0)')))
return (0.299*r + 0.587*g + 0.114*b) < 128;
}
node = node.parentElement;
}
return window.matchMedia('(prefers-color-scheme: dark)').matches;
}
function _makeTheme(dark) {
return dark ? {
bg:'#1e1e2e', bgPlot:'#181825', bgCanvas:'#181825',
border:'#44475a', axisBg:'#1e1e2e',
axisStroke:'rgba(98,114,164,0.5)', gridStroke:'rgba(98,114,164,0.18)',
tickStroke:'#6272a4', tickText:'rgba(205,214,244,0.75)',
unitText:'rgba(98,114,164,0.85)', dark:true,
} : {
bg:'#f0f0f0', bgPlot:'#ffffff', bgCanvas:'#ffffff',
border:'#cccccc', axisBg:'#f0f0f0',
axisStroke:'rgba(0,0,0,0.35)', gridStroke:'rgba(0,0,0,0.07)',
tickStroke:'#666666', tickText:'rgba(40,40,40,0.85)',
unitText:'rgba(100,100,100,0.85)', dark:false,
};
}
let theme = _makeTheme(_isDarkBg(el));
const _mq = window.matchMedia('(prefers-color-scheme: dark)');
_mq.addEventListener('change', () => { theme = _makeTheme(_isDarkBg(el)); redrawAll(); });
new MutationObserver(() => { theme = _makeTheme(_isDarkBg(el)); redrawAll(); })
.observe(document.documentElement, { attributes:true,
attributeFilter:['data-jp-theme-name','data-vscode-theme-kind','class'] });
// ── shared math helpers ──────────────────────────────────────────────────
function findNice(t) {
if (t<=0) return 1;
const mag = Math.pow(10, Math.floor(Math.log10(t)));
let best=mag, bd=Math.abs(t-mag);
for (const n of [1,2,2.5,5,10]) { const v=n*mag,d=Math.abs(t-v); if(d<bd){best=v;bd=d;} }
return best;
}
function fmtVal(v) {
const a=Math.abs(v);
if(a===0) return '0';
if(a>=1e4) return v.toExponential(1);
if(a>=100) return v.toFixed(0);
if(a>=1) return v.toFixed(2);
if(a>=1e-2)return v.toFixed(4);
return v.toExponential(1);
}
function _axisValToFrac(arr,val) {
if(arr.length<2) return 0;
const n=arr.length, asc=arr[n-1]>=arr[0];
if(asc?val<=arr[0]:val>=arr[0]) return 0;
if(asc?val>=arr[n-1]:val<=arr[n-1]) return 1;
let lo=0,hi=n-2;
while(lo<hi){const mid=(lo+hi)>>1;const ok=asc?(arr[mid]<=val&&val<arr[mid+1]):(arr[mid]>=val&&val>arr[mid+1]);if(ok){lo=mid;break;}if(asc?arr[mid+1]<=val:arr[mid+1]>=val)lo=mid+1;else hi=mid;}
return (lo+(val-arr[lo])/(arr[lo+1]-arr[lo]))/(n-1);
}
function _axisFracToVal(arr,frac) {
if(arr.length<2) return arr.length?arr[0]:0;
const n=arr.length, pos=Math.max(0,Math.min(1,frac))*(n-1), lo=Math.min(Math.floor(pos),n-2), t=pos-lo;
return arr[lo]+t*(arr[lo+1]-arr[lo]);
}
// Blend a #rrggbb / #rgb colour toward white by `amt` (0=unchanged, 1=white).
function _brightenColor(hex, amt=0.45) {
if(!hex||hex[0]!=='#') return hex;
let r,g,b;
if(hex.length===4){r=parseInt(hex[1]+hex[1],16);g=parseInt(hex[2]+hex[2],16);b=parseInt(hex[3]+hex[3],16);}
else{r=parseInt(hex.slice(1,3),16);g=parseInt(hex.slice(3,5),16);b=parseInt(hex.slice(5,7),16);}
if(isNaN(r)||isNaN(g)||isNaN(b)) return hex;
r=Math.min(255,Math.round(r+(255-r)*amt));g=Math.min(255,Math.round(g+(255-g)*amt));b=Math.min(255,Math.round(b+(255-b)*amt));
return `#${r.toString(16).padStart(2,'0')}${g.toString(16).padStart(2,'0')}${b.toString(16).padStart(2,'0')}`;
}
// ── b64 array decode helpers ─────────────────────────────────────────────
// Convert a base-64 string (little-endian raw bytes) to a JS TypedArray.
// TypedArrays support .length and [i] indexing so they are drop-in
// replacements for plain arrays in all draw / hit-test functions.
function _decodeF64(b64) {
const bin = atob(b64);
const buf = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
return new Float64Array(buf.buffer);
}
function _decodeF32(b64) {
const bin = atob(b64);
const buf = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
return new Float32Array(buf.buffer);
}
function _decodeI32(b64) {
const bin = atob(b64);
const buf = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
return new Int32Array(buf.buffer);
}
// ── per-panel frame timing ────────────────────────────────────────────────
// Called at the entry of every draw function (draw2d / draw1d / draw3d /
// drawBar). Records a high-resolution timestamp in a 60-entry rolling
// buffer on the panel object, then:
// • updates window._aplTiming[p.id] — always, for Playwright readback
// • updates p.statsDiv text — only when display_stats is true
//
// Placing the call at the *start* of each draw function means we measure
// the inter-trigger interval: how often the CPU initiates a render, which
// is the right metric for both interactive (pan/zoom) and data-push paths.
const _FRAME_BUF = 60;
function _recordFrame(p) {
const now = performance.now();
p.frameTimes.push(now);
if (p.frameTimes.length > _FRAME_BUF) p.frameTimes.shift();
const n = p.frameTimes.length;
// Always keep the global timing dict fresh so Playwright can read it back
// at any point via window._aplTiming[panelId].
if (!window._aplTiming) window._aplTiming = {};
if (n >= 2) {
let sum = 0, minDt = Infinity, maxDt = -Infinity;
for (let i = 1; i < n; i++) {
const dt = p.frameTimes[i] - p.frameTimes[i - 1];
sum += dt; if (dt < minDt) minDt = dt; if (dt > maxDt) maxDt = dt;
}
const mean_ms = sum / (n - 1);
const fps = 1000 * (n - 1) / (now - p.frameTimes[0]);
window._aplTiming[p.id] = {
count: n, fps, mean_ms, min_ms: minDt, max_ms: maxDt,
};
if (p.statsDiv && model.get('display_stats')) {
p.statsDiv.style.display = 'block';
p.statsDiv.textContent =
`FPS ${fps.toFixed(1)}\n` +
` dt ${mean_ms.toFixed(1)} ms\n` +
`min ${minDt.toFixed(1)} ms\n` +
`max ${maxDt.toFixed(1)} ms`;
}
}
}
// Static layout styles live in the _css traitlet (.apl-scale-wrap /
// .apl-outer). Only the two dynamic properties — transform and
// marginBottom — are ever written here at runtime.
const scaleWrap = document.createElement('div');
scaleWrap.classList.add('apl-scale-wrap');
el.appendChild(scaleWrap);
const outerDiv = document.createElement('div');
outerDiv.classList.add('apl-outer');
scaleWrap.appendChild(outerDiv);
const gridDiv = document.createElement('div');
gridDiv.style.cssText = `display:grid;gap:4px;background:${theme.bg};padding:8px;border-radius:4px;`;
outerDiv.appendChild(gridDiv);
// Resize handle (figure-level)
const resizeHandle = document.createElement('div');
resizeHandle.style.cssText =
'position:absolute;bottom:2px;right:2px;width:16px;height:16px;cursor:nwse-resize;' +
'background:linear-gradient(135deg,transparent 50%,#888 50%);border-radius:0 0 4px 0;z-index:100;';
resizeHandle.title = 'Drag to resize figure';
outerDiv.appendChild(resizeHandle);
const sizeLabel = document.createElement('div');
sizeLabel.style.cssText =
'position:absolute;bottom:22px;right:22px;padding:3px 7px;background:rgba(0,0,0,0.7);' +
'color:white;font-size:11px;border-radius:4px;display:none;pointer-events:none;z-index:21;';
outerDiv.appendChild(sizeLabel);
// ── Help badge (figure-level) ─────────────────────────────────────────────
// A small '?' button in the top-right corner of the figure.
// • Hidden until the mouse enters outerDiv (plot "active").
// • Stays visible while the help card is open, even after mouse-leave.
// • Rounded square, tucked into the right padding band so it never
// overlaps plot content.
// • Clicking toggles the help card; click again (or mouse-leave with
// card closed) hides the button again.
const _BTN_BG = 'rgba(100,100,120,0.72)';
const _BTN_BG_ACTIVE = 'rgba(75,120,210,0.92)';
const helpBtn = document.createElement('div');
helpBtn.style.cssText =
'position:absolute;top:9px;right:6px;width:20px;height:20px;' +
'border-radius:4px;background:' + _BTN_BG + ';color:#fff;' +
'font-size:12px;font-weight:bold;font-family:sans-serif;' +
'display:none;align-items:center;justify-content:center;' +
'cursor:pointer;z-index:50;user-select:none;line-height:1;' +
'box-shadow:0 1px 4px rgba(0,0,0,0.35);';
helpBtn.textContent = '?';
helpBtn.title = 'Show help';
outerDiv.appendChild(helpBtn);
const helpCard = document.createElement('div');
helpCard.style.cssText =
'position:absolute;top:33px;right:6px;padding:10px 14px;' +
'background:rgba(28,28,38,0.95);color:#e0e0e8;font-size:12px;' +
'font-family:sans-serif;border-radius:6px;line-height:1.7;' +
'white-space:pre-wrap;max-width:300px;display:none;z-index:51;' +
'box-shadow:0 4px 14px rgba(0,0,0,0.55);pointer-events:none;' +
'border:1px solid rgba(120,120,160,0.3);';
outerDiv.appendChild(helpCard);
let _helpExists = false; // true when help_text is non-empty
let _helpHovered = false; // true while mouse is inside outerDiv
let _helpOpen = false; // true while the card is shown
function _updateHelp() {
const txt = model.get('help_text') || '';
_helpExists = !!txt;
helpCard.textContent = txt;
if (!txt) {
// Help removed — hide everything immediately.
helpBtn.style.display = 'none';
helpCard.style.display = 'none';
helpBtn.style.background = _BTN_BG;
_helpOpen = false;
} else if (_helpHovered || _helpOpen) {
// Already hovered or card open — make badge visible.
helpBtn.style.display = 'flex';
}
}
_updateHelp();
outerDiv.addEventListener('mouseenter', () => {
_helpHovered = true;
if (_helpExists) helpBtn.style.display = 'flex';
});
outerDiv.addEventListener('mouseleave', () => {
_helpHovered = false;
// Only hide the button if the card is also closed.
if (!_helpOpen) helpBtn.style.display = 'none';
});
helpBtn.addEventListener('click', (e) => {
e.stopPropagation();
_helpOpen = !_helpOpen;
helpCard.style.display = _helpOpen ? 'block' : 'none';
helpBtn.style.background = _helpOpen ? _BTN_BG_ACTIVE : _BTN_BG;
// If closing the card while the mouse has already left, hide the button too.
if (!_helpOpen && !_helpHovered) helpBtn.style.display = 'none';
});
model.on('change:help_text', _updateHelp);
const tooltip = document.createElement('div');
tooltip.style.cssText =
'position:fixed;padding:5px 9px;font-size:12px;font-family:sans-serif;' +
'background:rgba(30,30,30,0.92);color:#fff;border-radius:4px;' +
'pointer-events:none;white-space:pre;display:none;z-index:9999;' +
'box-shadow:0 2px 6px rgba(0,0,0,0.4);max-width:260px;';
document.body.appendChild(tooltip);
function _showTooltip(text,cx,cy) {
tooltip.textContent=text; tooltip.style.display='block';
const tw=tooltip.offsetWidth||160, th=tooltip.offsetHeight||28;
const vw=window.innerWidth, vh=window.innerHeight; // both used below
let lx=cx+14, ly=cy-th-8;
if(lx+tw>vw-8) lx=cx-tw-14;
if(ly<8) ly=cy+18;
if(ly+th>vh-8) ly=vh-th-8;
tooltip.style.left=lx+'px'; tooltip.style.top=ly+'px';
}
// ── coordinate helper: undo CSS transform:scale() ───────────────────────
// _applyScale() shrinks outerDiv with transform:scale(s). After that,
// getBoundingClientRect() reports *visual* (CSS-pixel) dimensions, while
// canvas drawing coordinates live in the *native* (un-scaled) space.
// Every event handler that does (e.clientX - rect.left) therefore receives
// a value in [0, nativeW*s] instead of [0, nativeW].
//
// _clientPos converts one mouse event back to canvas-pixel space:
// sfX = nativeW / rect.width = 1/s (1.0 when no scale is active)
// mx = (e.clientX - rect.left) * sfX
//
// Usage:
// const {mx, my} = _clientPos(e, overlayCanvas, p.pw, p.ph); // 1D / bar
// const {mx, my} = _clientPos(e, overlayCanvas, imgW, imgH); // 2D
function _clientPos(e, canvas, nativeW, nativeH) {
const rect = canvas.getBoundingClientRect();
const sfX = rect.width > 0 ? nativeW / rect.width : 1;
const sfY = rect.height > 0 ? nativeH / rect.height : 1;
return { mx: (e.clientX - rect.left) * sfX,
my: (e.clientY - rect.top ) * sfY, sfX, sfY };
}
// ── per-panel state maps ──────────────────────────────────────────────────
const panels = new Map();
let _suppressLayoutUpdate = false; // block re-entry during live resize
// ── layout application ───────────────────────────────────────────────────
function applyLayout() {
if (_suppressLayoutUpdate) return;
let layout;
try { layout = JSON.parse(model.get('layout_json')); } catch(_) { return; }
const { nrows, ncols, panel_specs } = layout;
// Build grid tracks directly from panel pixel sizes.
// Python already guarantees all panels in a row share the same height,
// and all panels in a col share the same width.
const colPx = new Array(ncols).fill(0);
const rowPx = new Array(nrows).fill(0);
for (const spec of panel_specs) {
const perCol = Math.round(spec.panel_width / (spec.col_stop - spec.col_start));
const perRow = Math.round(spec.panel_height / (spec.row_stop - spec.row_start));
for (let c = spec.col_start; c < spec.col_stop; c++) colPx[c] = Math.max(colPx[c], perCol);
for (let r = spec.row_start; r < spec.row_stop; r++) rowPx[r] = Math.max(rowPx[r], perRow);
}
gridDiv.style.gridTemplateColumns = colPx.map(px => px + 'px').join(' ');
gridDiv.style.gridTemplateRows = rowPx.map(px => px + 'px').join(' ');
gridDiv.style.width = '';
gridDiv.style.height = '';
const seen = new Set();
for (const spec of panel_specs) {
seen.add(spec.id);
if (!panels.has(spec.id)) {
_createPanelDOM(spec.id, spec.kind, spec.panel_width, spec.panel_height, spec);
} else {
_resizePanelDOM(spec.id, spec.panel_width, spec.panel_height);
}
}
for (const [id, p] of panels) {
if (!seen.has(id)) { p.cell.remove(); panels.delete(id); }
}
}
function _createPanelDOM(id, kind, pw, ph, spec) {
const cell = document.createElement('div');
cell.style.cssText = 'position:relative;overflow:visible;line-height:0;display:flex;justify-content:center;align-items:flex-start;';
cell.style.gridRow = `${spec.row_start+1} / ${spec.row_stop+1}`;
cell.style.gridColumn = `${spec.col_start+1} / ${spec.col_stop+1}`;
gridDiv.appendChild(cell);
let plotCanvas, overlayCanvas, markersCanvas, statusBar;
let xAxisCanvas=null, yAxisCanvas=null, scaleBar=null;
let _p2d = null; // extra 2D DOM refs, null for 1D panels
let _wrapNode = null; // container to which statsDiv is appended
if (kind === '2d') {
// ── 2D branch ──────────────────────────────────────────────────────────
// The outer container is exactly pw×ph — same as the 1D canvas.
// Inside it everything is absolutely positioned to mirror 1D's _plotRect1d:
// image area : [PAD_L, PAD_T] → [pw-PAD_R, ph-PAD_B]
// y-axis : [0, PAD_T] → [PAD_L, ph-PAD_B]
// x-axis : [PAD_L, ph-PAD_B] → [pw-PAD_R, ph]
// This makes the bottom-left corner of the image/plot areas line up exactly.
const plotWrap = document.createElement('div');
plotWrap.style.cssText = `position:relative;display:inline-block;line-height:0;` +
`width:${pw}px;height:${ph}px;overflow:visible;flex-shrink:0;`;
// Image canvas — positioned at the inner plot area
plotCanvas = document.createElement('canvas');
plotCanvas.style.cssText = `position:absolute;display:block;border-radius:2px;background:${theme.bgCanvas};`;
// Overlay + marker canvases (same size as plotCanvas, stacked on top)
overlayCanvas = document.createElement('canvas');
overlayCanvas.style.cssText = 'position:absolute;z-index:5;cursor:default;pointer-events:all;outline:none;';
overlayCanvas.tabIndex = 0;
markersCanvas = document.createElement('canvas');
markersCanvas.style.cssText = 'position:absolute;pointer-events:none;z-index:6;';
// Scale bar: single canvas drawn on demand
scaleBar = document.createElement('canvas');
scaleBar.style.cssText =
'position:absolute;pointer-events:none;display:none;z-index:7;';
const sbLine = null; // unused — drawing handled by canvas
const sbLabel = null; // unused — drawing handled by canvas
plotWrap.appendChild(scaleBar);
// Status bar: absolute, bottom-left of image area
statusBar = document.createElement('div');
statusBar.style.cssText =
'position:absolute;padding:2px 6px;' +
'background:rgba(0,0,0,0.55);color:white;font-size:10px;font-family:monospace;' +
'border-radius:4px;pointer-events:none;white-space:nowrap;display:none;z-index:9;';
// y-axis canvas: left gutter [0, PAD_T]..[PAD_L, ph-PAD_B]
yAxisCanvas = document.createElement('canvas');
yAxisCanvas.style.cssText = `position:absolute;display:none;background:${theme.axisBg};`;
// x-axis canvas: bottom gutter [PAD_L, ph-PAD_B]..[pw-PAD_R, ph]
xAxisCanvas = document.createElement('canvas');
xAxisCanvas.style.cssText = `position:absolute;display:none;background:${theme.axisBg};`;
// Colorbar canvas: narrow strip (16 px) to the right of the image area
const cbCanvas = document.createElement('canvas');
cbCanvas.style.cssText = 'position:absolute;display:none;pointer-events:none;border-radius:0 2px 2px 0;';
plotWrap.appendChild(plotCanvas);
plotWrap.appendChild(overlayCanvas);
plotWrap.appendChild(markersCanvas);
plotWrap.appendChild(yAxisCanvas);
plotWrap.appendChild(xAxisCanvas);
plotWrap.appendChild(cbCanvas);
plotWrap.appendChild(statusBar);
cell.appendChild(plotWrap);
const cbCtx = cbCanvas.getContext('2d');
_p2d = { cbCanvas, cbCtx, plotWrap };
_wrapNode = plotWrap;
} else if (kind === '3d') {
// ── 3D branch: one full-panel plotCanvas + overlayCanvas on top ───────
plotCanvas = document.createElement('canvas');
plotCanvas.style.cssText = `display:block;border-radius:2px;background:${theme.bgPlot};`;
const wrap3 = document.createElement('div');
wrap3.style.cssText = 'position:relative;display:inline-block;line-height:0;';
wrap3.appendChild(plotCanvas);
cell.appendChild(wrap3);
overlayCanvas = document.createElement('canvas');
overlayCanvas.style.cssText = 'position:absolute;top:0;left:0;z-index:5;pointer-events:all;outline:none;';
wrap3.appendChild(overlayCanvas);
markersCanvas = document.createElement('canvas');
markersCanvas.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none;z-index:6;display:none;';
wrap3.appendChild(markersCanvas);
statusBar = document.createElement('div');
statusBar.style.cssText =
'position:absolute;bottom:4px;right:4px;padding:2px 6px;display:none;';
wrap3.appendChild(statusBar);
_wrapNode = wrap3;
} else {
// ── 1D / bar branch ───────────────────────────────────────────────────
plotCanvas = document.createElement('canvas');
plotCanvas.tabIndex = 1;
plotCanvas.style.cssText = 'outline:none;cursor:crosshair;display:block;border-radius:2px;';
// wrap gives us a positioned container for the absolute canvases + status bar
const wrap = document.createElement('div');
wrap.style.cssText = 'position:relative;display:inline-block;line-height:0;';
wrap.appendChild(plotCanvas);
cell.appendChild(wrap);
overlayCanvas = document.createElement('canvas');
overlayCanvas.style.cssText = 'position:absolute;top:0;left:0;z-index:5;cursor:crosshair;pointer-events:all;';
wrap.appendChild(overlayCanvas);
markersCanvas = document.createElement('canvas');
markersCanvas.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none;z-index:6;';
wrap.appendChild(markersCanvas);
// Status bar overlays the 1D plot area
statusBar = document.createElement('div');
statusBar.style.cssText =
'position:absolute;bottom:4px;right:4px;padding:2px 6px;' +
'background:rgba(0,0,0,0.55);color:white;font-size:10px;font-family:monospace;' +
'border-radius:4px;pointer-events:none;white-space:nowrap;display:none;z-index:9;';
wrap.appendChild(statusBar);
_wrapNode = wrap;
}
const plotCtx = plotCanvas.getContext('2d');
const ovCtx = overlayCanvas.getContext('2d');
const mkCtx = markersCanvas.getContext('2d');
const xCtx = xAxisCanvas ? xAxisCanvas.getContext('2d') : null;
const yCtx = yAxisCanvas ? yAxisCanvas.getContext('2d') : null;
const blitCache = { bitmap:null, bytesKey:null, lutKey:null, w:0, h:0 };
// ── stats overlay (top-left of panel) ────────────────────────────────
// Positioned absolutely inside the panel's wrap container so it floats
// over the plot area. Visibility is toggled by the display_stats traitlet.
const statsDiv = document.createElement('div');
statsDiv.style.cssText =
'position:absolute;top:4px;left:4px;padding:4px 7px;' +
'background:rgba(0,0,0,0.65);color:#e0e0e0;font-size:10px;' +
'font-family:monospace;border-radius:4px;pointer-events:none;' +
'white-space:pre;line-height:1.5;z-index:20;display:none;';
if (_wrapNode) _wrapNode.appendChild(statsDiv);
const p = {
id, kind, cell, pw, ph,
plotCanvas, overlayCanvas, markersCanvas,
plotCtx, ovCtx, mkCtx,
xAxisCanvas, yAxisCanvas, xCtx, yCtx,
scaleBar, statusBar,
statsDiv, // ← per-panel FPS overlay element
frameTimes: [], // ← rolling 60-entry timestamp buffer (performance.now())
blitCache,
ovDrag: null,
isPanning: false, panStart: {},
state: null,
_hoverSi: -1, _hoverI: -1, // index of hovered marker group / marker (-1 = none)
_hovBar: null, // {slot,group} of hovered bar, or null
lastWidgetId: null, // id of the last clicked/dragged widget (for on_key Delete etc.)
mouseX: 0, mouseY: 0, // last known canvas-relative cursor position
// 2D extras (null for non-2D panels)
cbCanvas: _p2d ? _p2d.cbCanvas : null,
cbCtx: _p2d ? _p2d.cbCtx : null,
sbLine: null,
sbLabel: null,
plotWrap: _p2d ? _p2d.plotWrap : null,
};
panels.set(id, p);
_resizePanelDOM(id, pw, ph);
_attachPanelEvents(p);
// Listen for this panel's trait changes
model.on(`change:panel_${id}_json`, () => {
const p2 = panels.get(id);
if (!p2) return;
try { p2.state = JSON.parse(model.get(`panel_${id}_json`)); }
catch(_) { return; }
p2._hoverSi = -1; p2._hoverI = -1;
_redrawPanel(p2);
});
// Initial draw
try { p.state = JSON.parse(model.get(`panel_${id}_json`)); } catch(_) {}
_redrawPanel(p);
}
function _resizePanelDOM(id, pw, ph) {
const p = panels.get(id);
if (!p) return;
p.pw = pw; p.ph = ph;
function _sz(c, ctx, w, h) {
c.style.width=w+'px'; c.style.height=h+'px';
c.width=w*dpr; c.height=h*dpr;
ctx.setTransform(dpr,0,0,dpr,0,0);
}
if (p.kind === '2d') {
// ── 2D: all elements absolutely positioned within pw×ph container ──
// The image/plot area mirrors 1D's _plotRect1d:
// x: PAD_L → pw-PAD_R, y: PAD_T → ph-PAD_B
const imgX = PAD_L, imgY = PAD_T;
const imgW = Math.max(1, pw - PAD_L - PAD_R);
const imgH = Math.max(1, ph - PAD_T - PAD_B);
if (p.plotWrap) {
p.plotWrap.style.width = pw + 'px';
p.plotWrap.style.height = ph + 'px';
}
// Image canvas at the inner plot area
p.plotCanvas.style.left = imgX + 'px';
p.plotCanvas.style.top = imgY + 'px';
_sz(p.plotCanvas, p.plotCtx, imgW, imgH);
// Overlay and markers match the image canvas exactly
p.overlayCanvas.style.left = imgX + 'px';
p.overlayCanvas.style.top = imgY + 'px';
_sz(p.overlayCanvas, p.ovCtx, imgW, imgH);
p.markersCanvas.style.left = imgX + 'px';
p.markersCanvas.style.top = imgY + 'px';
_sz(p.markersCanvas, p.mkCtx, imgW, imgH);
// Status bar: bottom-left of image area
if (p.statusBar) {
p.statusBar.style.left = (imgX + 4) + 'px';
p.statusBar.style.bottom = (PAD_B + 4) + 'px';
p.statusBar.style.top = '';
}
// Scale bar: bottom-right of image area
if (p.scaleBar) {
p.scaleBar.style.right = (PAD_R + 12) + 'px';
p.scaleBar.style.bottom = (PAD_B + 12) + 'px';
p.scaleBar.style.left = '';
p.scaleBar.style.top = '';
}
const st = p.state;
// Show axis canvases only when the user explicitly provided coordinate
// arrays (has_axes), or for pcolormesh panels (is_mesh, always has edges).
const hasPhysAxis = st && (st.is_mesh || st.has_axes)
&& st.x_axis && st.x_axis.length >= 2
&& st.y_axis && st.y_axis.length >= 2;
// y-axis: left gutter [0, PAD_T]..[PAD_L, ph-PAD_B]
if (p.yAxisCanvas && p.yCtx) {
if (hasPhysAxis) {
p.yAxisCanvas.style.display = 'block';
p.yAxisCanvas.style.left = '0px';
p.yAxisCanvas.style.top = imgY + 'px';
p.yAxisCanvas.style.width = PAD_L + 'px';
p.yAxisCanvas.style.height = imgH + 'px';
p.yAxisCanvas.width = PAD_L * dpr;
p.yAxisCanvas.height = imgH * dpr;
p.yCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
} else {
p.yAxisCanvas.style.display = 'none';
}
}
// x-axis: bottom gutter [PAD_L, ph-PAD_B]..[pw-PAD_R, ph]
if (p.xAxisCanvas && p.xCtx) {
if (hasPhysAxis) {
p.xAxisCanvas.style.display = 'block';
p.xAxisCanvas.style.left = imgX + 'px';
p.xAxisCanvas.style.top = (ph - PAD_B) + 'px';
p.xAxisCanvas.style.width = imgW + 'px';
p.xAxisCanvas.style.height = PAD_B + 'px';
p.xAxisCanvas.width = imgW * dpr;
p.xAxisCanvas.height = PAD_B * dpr;
p.xCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
} else {
p.xAxisCanvas.style.display = 'none';
}
}
// Colorbar: narrow strip to the right of the image area
if (p.cbCanvas && p.cbCtx) {
const cbW = 16;
const vis = st && st.show_colorbar;
if (vis) {
p.cbCanvas.style.display = 'block';
p.cbCanvas.style.left = (imgX + imgW + 2) + 'px';
p.cbCanvas.style.top = imgY + 'px';
_sz(p.cbCanvas, p.cbCtx, cbW, imgH);
} else {
p.cbCanvas.style.display = 'none';
}
}
} else if (p.kind === '3d') {
// ── 3D: full-panel canvases ──
_sz(p.plotCanvas, p.plotCtx, pw, ph);
_sz(p.overlayCanvas, p.ovCtx, pw, ph);
} else {
// ── 1D: canvas is the full pw×ph, padding is drawn internally ──
_sz(p.plotCanvas, p.plotCtx, pw, ph);
_sz(p.overlayCanvas, p.ovCtx, pw, ph);
_sz(p.markersCanvas, p.mkCtx, pw, ph);
}
}
// ── 2D drawing ───────────────────────────────────────────────────────────
// Largest rect with the image's natural aspect that fits inside cw×ch,
// centred. All 2-D coordinate functions derive from this single rect so
// draw, hit-test, and coordinate conversion are always consistent.
// s = uniform scale factor (canvas px per image px).
function _imgFitRect(iw, ih, cw, ch) {
const s = Math.min(cw / iw, ch / ih);
const fw = iw * s, fh = ih * s;
return { x: (cw - fw) / 2, y: (ch - fh) / 2, w: fw, h: fh, s };
}
function _buildLut32(st) {
const dMin=st.display_min, dMax=st.display_max;
const hMin=st.raw_min!=null?st.raw_min:dMin;
const hMax=st.raw_max!=null?st.raw_max:dMax;
const mode=st.scale_mode||'linear';
const range=hMax-hMin||1;
const cmapData=st.colormap_data||[];
let cmapFlat=null;
if(cmapData.length===256){
cmapFlat=new Uint8Array(256*4);
for(let i=0;i<256;i++){cmapFlat[i*4]=cmapData[i][0];cmapFlat[i*4+1]=cmapData[i][1];cmapFlat[i*4+2]=cmapData[i][2];cmapFlat[i*4+3]=255;}
}
const lut=new Uint32Array(256);
const buf=new ArrayBuffer(4); const dv=new DataView(buf); const u32=new Uint32Array(buf);
for(let raw=0;raw<256;raw++){
const val=hMin+(raw/255)*range;
let t;
if(mode==='log'){const dMC=Math.max(dMin,1e-10),dXC=Math.max(dMax,dMC+1e-10);t=(Math.log10(Math.max(val,1e-10))-Math.log10(dMC))/(Math.log10(dXC)-Math.log10(dMC));}
else if(mode==='symlog'){const lt=Math.max((dMax-dMin)*0.01,1e-10);const sl=v=>v>=0?(v<=lt?v/lt:1+Math.log10(v/lt)):-(Math.abs(v)<=lt?Math.abs(v)/lt:1+Math.log10(Math.abs(v)/lt));t=(sl(val)-sl(dMin))/((sl(dMax)-sl(dMin))||1);}
else{t=(val-dMin)/((dMax-dMin)||1);}
const idx=Math.max(0,Math.min(255,Math.round(t*255)));
if(cmapFlat){dv.setUint8(0,cmapFlat[idx*4]);dv.setUint8(1,cmapFlat[idx*4+1]);dv.setUint8(2,cmapFlat[idx*4+2]);dv.setUint8(3,255);}
else{dv.setUint8(0,idx);dv.setUint8(1,idx);dv.setUint8(2,idx);dv.setUint8(3,255);}
lut[raw]=u32[0];
}
return lut;
}
function _lutKey(st) {
return [st.display_min,st.display_max,st.raw_min,st.raw_max,st.scale_mode,st.colormap_name].join('|');
}
function _imgToCanvas2d(ix, iy, st, pw, ph) {
const { x, y, w, h } = _imgFitRect(st.image_width, st.image_height, pw, ph);
const zoom = st.zoom, cx = st.center_x, cy = st.center_y;
const iw = st.image_width, ih = st.image_height;
if (zoom < 1.0) {
// Zoom-out path: full image drawn centred inside a scaled-down fit-rect
// (mirrors the zoom<1 branch in _blit2d exactly).
const dstW = w * zoom, dstH = h * zoom;
const dstX = x + (w - dstW) / 2, dstY = y + (h - dstH) / 2;
return [dstX + (ix / iw) * dstW, dstY + (iy / ih) * dstH];
}
const visW = iw / zoom, visH = ih / zoom;
const srcX = Math.max(0, Math.min(iw - visW, cx * iw - visW / 2));
const srcY = Math.max(0, Math.min(ih - visH, cy * ih - visH / 2));
return [x + (ix - srcX) / visW * w, y + (iy - srcY) / visH * h];
}
// Returns canvas-px per image-px at the current zoom (uniform in x and y).
function _imgScale2d(st, pw, ph) {
return _imgFitRect(st.image_width, st.image_height, pw, ph).s * st.zoom;
}
function _blit2d(bitmap, st, pw, ph, ctx) {
const { x, y, w, h } = _imgFitRect(st.image_width, st.image_height, pw, ph);
const zoom = st.zoom, cx = st.center_x, cy = st.center_y;
const iw = st.image_width, ih = st.image_height;
ctx.clearRect(0, 0, pw, ph);
ctx.fillStyle = theme.bgCanvas;
ctx.fillRect(0, 0, pw, ph);
ctx.imageSmoothingEnabled = false;
if (zoom >= 1.0) {
// Zoomed in: show a portion of the image filling the fit-rect.
const visW = iw / zoom, visH = ih / zoom;
const srcX = Math.max(0, Math.min(iw - visW, cx * iw - visW / 2));
const srcY = Math.max(0, Math.min(ih - visH, cy * ih - visH / 2));
ctx.drawImage(bitmap, srcX, srcY, visW, visH, x, y, w, h);
} else {
// Zoomed out: shrink the fit-rect proportionally, keep it centred.
const dstW = w * zoom, dstH = h * zoom;
ctx.drawImage(bitmap, 0, 0, iw, ih,
x + (w - dstW) / 2, y + (h - dstH) / 2, dstW, dstH);
}
}
function draw2d(p) {
const st=p.state;
if(!st) return;
_recordFrame(p);
// Re-sync axis/histogram canvas visibility whenever state changes
_resizePanelDOM(p.id, p.pw, p.ph);
const {pw,ph,plotCtx:ctx,blitCache} = p;
// The image canvas occupies the inner plot area, mirroring 1D's _plotRect1d
const imgW = Math.max(1, pw - PAD_L - PAD_R);
const imgH = Math.max(1, ph - PAD_T - PAD_B);
// Decode base64 image bytes
const b64=st.image_b64||'';
const iw=st.image_width, ih=st.image_height;
if(!b64||iw===0||ih===0){ctx.clearRect(0,0,imgW,imgH);return;}
let bytes;
try {
const bin=atob(b64);
bytes=new Uint8Array(bin.length);
for(let i=0;i<bin.length;i++) bytes[i]=bin.charCodeAt(i);
} catch(_){return;}
const lk=_lutKey(st);
const needRebuild = bytes!==blitCache.bytesKey || lk!==blitCache.lutKey
|| !blitCache.bitmap || blitCache.w!==iw || blitCache.h!==ih;
if(!needRebuild && blitCache.bitmap){
_blit2d(blitCache.bitmap, st, imgW, imgH, ctx);
} else {
const lut=_buildLut32(st);
const imgData=new ImageData(iw,ih);
const out32=new Uint32Array(imgData.data.buffer);
for(let i=0;i<iw*ih;i++) out32[i]=lut[bytes[i]];
const oc=new OffscreenCanvas(iw,ih);
oc.getContext('2d').putImageData(imgData,0,0);
blitCache.bitmap=oc; blitCache.bytesKey=bytes; blitCache.lutKey=lk;
blitCache.w=iw; blitCache.h=ih;
_blit2d(oc, st, imgW, imgH, ctx);
}
// Axes / scalebar / colorbar
_drawAxes2d(p);
drawScaleBar2d(p);
drawColorbar2d(p);
drawOverlay2d(p);
drawMarkers2d(p);
}
function drawScaleBar2d(p) {
const st=p.state; if(!st||!p.scaleBar) return;
// pcolormesh panels have non-uniform axes: no meaningful single pixel scale
if(st.is_mesh){p.scaleBar.style.display='none';return;}
const units=st.units||'px';
const scaleX=st.scale_x||0;
if(!scaleX||units==='px'){p.scaleBar.style.display='none';return;}
const imgW=Math.max(1,p.pw-PAD_L-PAD_R);
const imgH=Math.max(1,p.ph-PAD_T-PAD_B);
// Compute bar width in the fit-rect pixel space
const zoom=st.zoom||1;
const iw=st.image_width||imgW;
const fr=_imgFitRect(iw, st.image_height||imgH, imgW, imgH);
const visDataW=(zoom>=1?iw/zoom:iw)*scaleX;
const targetDataWidth=visDataW*0.2;
const niceWidth=findNice(targetDataWidth);
const barPx=Math.round((niceWidth/visDataW)*fr.w); // use fit-rect width
if(barPx<4){p.scaleBar.style.display='none';return;}
// Layout constants (CSS pixels)
const fontSize = 11;
const lineH = 3;
const gap = 6; // space between bottom of text and top of line
const padX = 8;
const padTop = 5;
const padBot = 5;
// Measure text to size the canvas
const label=`${fmtVal(niceWidth)} ${units}`;
const cvW=Math.max(barPx, fontSize*label.length*0.6|0) + padX*2;
const cvH=padTop + fontSize + gap + lineH + padBot;
const sb=p.scaleBar;
if(sb.width!==Math.round(cvW*dpr)||sb.height!==Math.round(cvH*dpr)){
sb.width=Math.round(cvW*dpr);
sb.height=Math.round(cvH*dpr);
sb.style.width=cvW+'px';
sb.style.height=cvH+'px';
}
const ctx=sb.getContext('2d');
ctx.setTransform(dpr,0,0,dpr,0,0);
ctx.clearRect(0,0,cvW,cvH);
// Background pill
ctx.fillStyle='rgba(0,0,0,0.60)';
const r=5;
ctx.beginPath();
ctx.moveTo(r,0);ctx.lineTo(cvW-r,0);ctx.arcTo(cvW,0,cvW,r,r);
ctx.lineTo(cvW,cvH-r);ctx.arcTo(cvW,cvH,cvW-r,cvH,r);
ctx.lineTo(r,cvH);ctx.arcTo(0,cvH,0,cvH-r,r);
ctx.lineTo(0,r);ctx.arcTo(0,0,r,0,r);
ctx.closePath();ctx.fill();
// Label (centred over the bar line)
const lineX=(cvW-barPx)/2;
const textY=padTop+fontSize;
ctx.fillStyle='white';
ctx.font=`bold ${fontSize}px sans-serif`;
ctx.textAlign='center';
ctx.textBaseline='alphabetic';
ctx.fillText(label, cvW/2, textY);
// Bar line
const lineY=padTop+fontSize+gap;
ctx.fillStyle='white';
ctx.fillRect(lineX, lineY, barPx, lineH);
// End ticks
ctx.fillRect(lineX, lineY-3, 2, lineH+3);
ctx.fillRect(lineX+barPx-2, lineY-3, 2, lineH+3);
sb.style.display='block';
}
function drawColorbar2d(p) {
const st=p.state; if(!st||!p.cbCanvas||!p.cbCtx) return;
const vis=st.show_colorbar||false;
p.cbCanvas.style.display = vis ? 'block' : 'none';
if(!vis) return;
const cbW=16;
const imgH=Math.max(1,p.ph-PAD_T-PAD_B);
const ctx=p.cbCtx;
ctx.clearRect(0,0,cbW,imgH);
// Gradient strip
if(st.colormap_data&&st.colormap_data.length===256){
for(let py=0;py<imgH;py++){
const frac=1-py/(imgH-1||1);
const ci=Math.max(0,Math.min(255,Math.round(frac*255)));
const [r2,g2,b2]=st.colormap_data[ci];
ctx.fillStyle=`rgb(${r2},${g2},${b2})`;
ctx.fillRect(0,py,cbW,1);
}
} else {
ctx.fillStyle=theme.dark?'#444':'#ccc';
ctx.fillRect(0,0,cbW,imgH);
}
// Border
ctx.strokeStyle=theme.border||'#888';
ctx.lineWidth=0.5;
ctx.strokeRect(0,0,cbW,imgH);
// display_min / display_max tick marks
const dMin=st.display_min, dMax=st.display_max;
const hMin=st.raw_min!=null?st.raw_min:dMin;
const hMax=st.raw_max!=null?st.raw_max:dMax;
const vRange=(hMax-hMin)||1;
function _vToY(v){return imgH-1-((v-hMin)/vRange)*(imgH-1);}
ctx.strokeStyle='rgba(255,255,255,0.85)'; ctx.lineWidth=1.5;
ctx.beginPath();ctx.moveTo(0,_vToY(dMax));ctx.lineTo(cbW,_vToY(dMax));ctx.stroke();
ctx.beginPath();ctx.moveTo(0,_vToY(dMin));ctx.lineTo(cbW,_vToY(dMin));ctx.stroke();
}
function _drawAxes2d(p) {
const st=p.state; if(!st) return;
const {pw,ph} = p;
const imgW = Math.max(1, pw - PAD_L - PAD_R);
const imgH = Math.max(1, ph - PAD_T - PAD_B);
const xArr=st.x_axis||[], yArr=st.y_axis||[];
const TICK=6;
const zoom=st.zoom, cx=st.center_x, cy=st.center_y;
const units=st.units||'px';
const hasPhysAxis = (st.is_mesh || st.has_axes) && xArr.length>=2 && yArr.length>=2;
const hasX = hasPhysAxis && p.xCtx && p.xAxisCanvas && p.xAxisCanvas.style.display!=='none';
const hasY = hasPhysAxis && p.yCtx && p.yAxisCanvas && p.yAxisCanvas.style.display!=='none';
function _visFrac(z,c){
if(z>=1.0){const h=0.5/z;const cc=Math.max(h,Math.min(1-h,c));return[cc-h,cc+h];}
return[0,1];
}
function _fracToPx(frac, z, center, span) {
if(z>=1.0){
const h=0.5/z, cc=Math.max(h,Math.min(1-h,center));
return (frac-(cc-h))/(2*h)*span;
}
return (span-span*z)/2+frac*span*z;
}
// ── X axis canvas: imgW × PAD_B, origin at top-left ─────────────────
// x=0 aligns with the left edge of the image, spans imgW pixels
if(hasX){
const aw=imgW, ah=PAD_B;
p.xCtx.clearRect(0,0,aw,ah);
p.xCtx.fillStyle=theme.axisBg; p.xCtx.fillRect(0,0,aw,ah);
p.xCtx.strokeStyle=theme.axisStroke; p.xCtx.lineWidth=1;
p.xCtx.beginPath(); p.xCtx.moveTo(0,0); p.xCtx.lineTo(aw,0); p.xCtx.stroke();
const [xF0,xF1]=_visFrac(zoom,cx);
const xVMin=_axisFracToVal(xArr,xF0), xVMax=_axisFracToVal(xArr,xF1);
const step=findNice((xVMax-xVMin)/Math.max(3,Math.floor(imgW/60)));
p.xCtx.strokeStyle=theme.tickStroke;
p.xCtx.fillStyle=theme.tickText; p.xCtx.font='10px sans-serif';
p.xCtx.textAlign='center'; p.xCtx.textBaseline='top';
// Generate nice tick values; place each at its true canvas position
// via binary-search into the axis array (works for both linear and
// non-linear / pcolormesh edge arrays).
const xTicks=[];
for(let v=Math.ceil(xVMin/step)*step; v<=xVMax+step*0.01; v+=step) xTicks.push(v);
// Clamp first/last label so it doesn't overflow the canvas edges
const minLabelGap=28; // px — minimum gap between adjacent labels
let lastPx=-Infinity;
for(let ti=0;ti<xTicks.length;ti++){
const v=xTicks[ti];
const frac=_axisValToFrac(xArr,v);
const px2=_fracToPx(frac,zoom,cx,imgW);
if(px2<0||px2>imgW) continue;
p.xCtx.beginPath(); p.xCtx.moveTo(px2,0); p.xCtx.lineTo(px2,TICK); p.xCtx.stroke();
// Skip label if too close to the previous one
if(px2-lastPx>=minLabelGap){
p.xCtx.fillText(fmtVal(v), px2, TICK+2);
lastPx=px2;
}
}
p.xCtx.textAlign='right'; p.xCtx.textBaseline='bottom';
p.xCtx.fillStyle=theme.unitText; p.xCtx.font='9px sans-serif';
p.xCtx.fillText(units, aw-2, ah-1);
}
// ── Y axis canvas: PAD_L × imgH, origin at top-left ─────────────────
// y=0 aligns with the top edge of the image, spans imgH pixels
if(hasY){
const aw=PAD_L, ah=imgH;
p.yCtx.clearRect(0,0,aw,ah);
p.yCtx.fillStyle=theme.axisBg; p.yCtx.fillRect(0,0,aw,ah);
p.yCtx.strokeStyle=theme.axisStroke; p.yCtx.lineWidth=1;
p.yCtx.beginPath(); p.yCtx.moveTo(aw,0); p.yCtx.lineTo(aw,ah); p.yCtx.stroke();
const [yF0,yF1]=_visFrac(zoom,cy);
const yVMin=_axisFracToVal(yArr,yF0), yVMax=_axisFracToVal(yArr,yF1);
const step=findNice((yVMax-yVMin)/Math.max(3,Math.floor(imgH/60)));
p.yCtx.strokeStyle=theme.tickStroke;
p.yCtx.fillStyle=theme.tickText; p.yCtx.font='10px sans-serif';
p.yCtx.textAlign='right'; p.yCtx.textBaseline='middle';
const yTicks=[];
for(let v=Math.ceil(yVMin/step)*step; v<=yVMax+step*0.01; v+=step) yTicks.push(v);
const minLabelGapY=14; // px
let lastPy=-Infinity;
for(let ti=0;ti<yTicks.length;ti++){
const v=yTicks[ti];
const frac=_axisValToFrac(yArr,v);
const py2=_fracToPx(frac,zoom,cy,imgH);
if(py2<0||py2>imgH) continue;
p.yCtx.beginPath(); p.yCtx.moveTo(aw,py2); p.yCtx.lineTo(aw-TICK,py2); p.yCtx.stroke();