matterviz 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/dist/EmptyState.svelte +10 -2
  2. package/dist/FilePicker.svelte +123 -82
  3. package/dist/Icon.svelte +18 -12
  4. package/dist/MillerIndexInput.svelte +27 -21
  5. package/dist/api/optimade.js +6 -6
  6. package/dist/app.css +216 -207
  7. package/dist/brillouin/BrillouinZone.svelte +292 -149
  8. package/dist/brillouin/BrillouinZone.svelte.d.ts +1 -1
  9. package/dist/brillouin/BrillouinZoneControls.svelte +32 -5
  10. package/dist/brillouin/BrillouinZoneExportPane.svelte +69 -42
  11. package/dist/brillouin/BrillouinZoneExportPane.svelte.d.ts +1 -1
  12. package/dist/brillouin/BrillouinZoneInfoPane.svelte +99 -68
  13. package/dist/brillouin/BrillouinZoneScene.svelte +275 -163
  14. package/dist/brillouin/BrillouinZoneScene.svelte.d.ts +1 -1
  15. package/dist/brillouin/BrillouinZoneTooltip.svelte +17 -7
  16. package/dist/brillouin/compute.js +11 -6
  17. package/dist/chempot-diagram/ChemPotDiagram.svelte +162 -27
  18. package/dist/chempot-diagram/ChemPotDiagram2D.svelte +451 -281
  19. package/dist/chempot-diagram/ChemPotDiagram3D.svelte +2148 -1642
  20. package/dist/chempot-diagram/ChemPotScene3D.svelte +8 -5
  21. package/dist/chempot-diagram/async-compute.svelte.d.ts +3 -0
  22. package/dist/chempot-diagram/async-compute.svelte.js +77 -0
  23. package/dist/chempot-diagram/chempot-worker.d.ts +1 -0
  24. package/dist/chempot-diagram/chempot-worker.js +11 -0
  25. package/dist/chempot-diagram/color.js +1 -2
  26. package/dist/chempot-diagram/compute.d.ts +10 -0
  27. package/dist/chempot-diagram/compute.js +250 -88
  28. package/dist/chempot-diagram/index.d.ts +2 -1
  29. package/dist/chempot-diagram/index.js +2 -1
  30. package/dist/chempot-diagram/temperature.js +8 -9
  31. package/dist/chempot-diagram/types.d.ts +3 -0
  32. package/dist/chempot-diagram/types.js +1 -0
  33. package/dist/colors/index.d.ts +1 -1
  34. package/dist/colors/index.js +5 -3
  35. package/dist/composition/BarChart.svelte +128 -55
  36. package/dist/composition/BubbleChart.svelte +102 -49
  37. package/dist/composition/Composition.svelte +100 -79
  38. package/dist/composition/Formula.svelte +108 -62
  39. package/dist/composition/FormulaFilter.svelte +665 -537
  40. package/dist/composition/PieChart.svelte +183 -108
  41. package/dist/composition/format.d.ts +5 -0
  42. package/dist/composition/format.js +20 -3
  43. package/dist/composition/parse.js +14 -9
  44. package/dist/convex-hull/ConvexHull.svelte +93 -40
  45. package/dist/convex-hull/ConvexHull.svelte.d.ts +1 -1
  46. package/dist/convex-hull/ConvexHull2D.svelte +549 -360
  47. package/dist/convex-hull/ConvexHull2D.svelte.d.ts +1 -1
  48. package/dist/convex-hull/ConvexHull3D.svelte +1296 -827
  49. package/dist/convex-hull/ConvexHull3D.svelte.d.ts +1 -1
  50. package/dist/convex-hull/ConvexHull4D.svelte +1004 -688
  51. package/dist/convex-hull/ConvexHull4D.svelte.d.ts +1 -1
  52. package/dist/convex-hull/ConvexHullControls.svelte +115 -28
  53. package/dist/convex-hull/ConvexHullControls.svelte.d.ts +1 -1
  54. package/dist/convex-hull/ConvexHullInfoPane.svelte +29 -3
  55. package/dist/convex-hull/ConvexHullStats.svelte +425 -328
  56. package/dist/convex-hull/ConvexHullTooltip.svelte +40 -16
  57. package/dist/convex-hull/GasPressureControls.svelte +104 -61
  58. package/dist/convex-hull/StructurePopup.svelte +25 -4
  59. package/dist/convex-hull/TemperatureSlider.svelte +45 -25
  60. package/dist/convex-hull/barycentric-coords.js +13 -7
  61. package/dist/convex-hull/demo-temperature.js +8 -4
  62. package/dist/convex-hull/gas-thermodynamics.js +17 -12
  63. package/dist/convex-hull/helpers.d.ts +9 -0
  64. package/dist/convex-hull/helpers.js +77 -34
  65. package/dist/convex-hull/thermodynamics.js +61 -56
  66. package/dist/convex-hull/types.d.ts +9 -14
  67. package/dist/convex-hull/types.js +0 -17
  68. package/dist/coordination/CoordinationBarPlot.svelte +227 -154
  69. package/dist/element/BohrAtom.svelte +55 -12
  70. package/dist/element/ElementHeading.svelte +7 -2
  71. package/dist/element/ElementPhoto.svelte +15 -9
  72. package/dist/element/ElementStats.svelte +10 -4
  73. package/dist/element/ElementTile.svelte +137 -73
  74. package/dist/element/Nucleus.svelte +39 -11
  75. package/dist/element/data.js +1 -1
  76. package/dist/feedback/ClickFeedback.svelte +16 -5
  77. package/dist/feedback/DragOverlay.svelte +10 -2
  78. package/dist/feedback/Spinner.svelte +4 -2
  79. package/dist/feedback/StatusMessage.svelte +8 -2
  80. package/dist/fermi-surface/FermiSlice.svelte +118 -88
  81. package/dist/fermi-surface/FermiSurface.svelte +328 -187
  82. package/dist/fermi-surface/FermiSurface.svelte.d.ts +1 -1
  83. package/dist/fermi-surface/FermiSurfaceControls.svelte +113 -46
  84. package/dist/fermi-surface/FermiSurfaceControls.svelte.d.ts +1 -1
  85. package/dist/fermi-surface/FermiSurfaceScene.svelte +535 -342
  86. package/dist/fermi-surface/FermiSurfaceScene.svelte.d.ts +1 -1
  87. package/dist/fermi-surface/FermiSurfaceTooltip.svelte +14 -5
  88. package/dist/fermi-surface/compute.js +16 -20
  89. package/dist/fermi-surface/parse.js +24 -14
  90. package/dist/fermi-surface/symmetry.js +2 -7
  91. package/dist/fermi-surface/types.d.ts +3 -5
  92. package/dist/heatmap-matrix/HeatmapMatrix.svelte +1019 -765
  93. package/dist/heatmap-matrix/HeatmapMatrix.svelte.d.ts +1 -1
  94. package/dist/heatmap-matrix/HeatmapMatrixControls.svelte +76 -22
  95. package/dist/heatmap-matrix/HeatmapMatrixControls.svelte.d.ts +2 -3
  96. package/dist/icons.js +47 -0
  97. package/dist/index.d.ts +2 -1
  98. package/dist/index.js +2 -1
  99. package/dist/io/decompress.js +1 -1
  100. package/dist/io/export.d.ts +3 -0
  101. package/dist/io/export.js +129 -143
  102. package/dist/io/is-binary.js +2 -3
  103. package/dist/io/url-drop.js +1 -2
  104. package/dist/isosurface/Isosurface.svelte +202 -148
  105. package/dist/isosurface/IsosurfaceControls.svelte +46 -28
  106. package/dist/isosurface/parse.js +34 -29
  107. package/dist/isosurface/slice.js +5 -10
  108. package/dist/isosurface/types.d.ts +2 -1
  109. package/dist/isosurface/types.js +61 -12
  110. package/dist/labels.js +11 -8
  111. package/dist/layout/FullscreenToggle.svelte +11 -2
  112. package/dist/layout/InfoCard.svelte +38 -6
  113. package/dist/layout/InfoTag.svelte +63 -32
  114. package/dist/layout/PropertyFilter.svelte +82 -37
  115. package/dist/layout/SettingsSection.svelte +85 -55
  116. package/dist/layout/SubpageGrid.svelte +10 -2
  117. package/dist/layout/json-tree/JsonNode.svelte +183 -138
  118. package/dist/layout/json-tree/JsonTree.svelte +499 -413
  119. package/dist/layout/json-tree/JsonValue.svelte +127 -99
  120. package/dist/layout/json-tree/utils.js +4 -2
  121. package/dist/marching-cubes.js +25 -2
  122. package/dist/math.d.ts +13 -17
  123. package/dist/math.js +133 -67
  124. package/dist/overlays/ContextMenu.svelte +65 -40
  125. package/dist/overlays/DraggablePane.svelte +211 -139
  126. package/dist/periodic-table/PeriodicTable.svelte +278 -145
  127. package/dist/periodic-table/PeriodicTableControls.svelte +178 -128
  128. package/dist/periodic-table/PropertySelect.svelte +25 -7
  129. package/dist/periodic-table/TableInset.svelte +8 -3
  130. package/dist/phase-diagram/IsobaricBinaryPhaseDiagram.svelte +446 -309
  131. package/dist/phase-diagram/IsobaricBinaryPhaseDiagram.svelte.d.ts +1 -1
  132. package/dist/phase-diagram/PhaseDiagramControls.svelte +102 -43
  133. package/dist/phase-diagram/PhaseDiagramControls.svelte.d.ts +1 -1
  134. package/dist/phase-diagram/PhaseDiagramEditorPane.svelte +63 -40
  135. package/dist/phase-diagram/PhaseDiagramExportPane.svelte +71 -28
  136. package/dist/phase-diagram/PhaseDiagramExportPane.svelte.d.ts +1 -1
  137. package/dist/phase-diagram/PhaseDiagramTooltip.svelte +158 -101
  138. package/dist/phase-diagram/TdbInfoPanel.svelte +28 -4
  139. package/dist/phase-diagram/build-diagram.js +9 -9
  140. package/dist/phase-diagram/colors.js +1 -3
  141. package/dist/phase-diagram/parse.js +10 -9
  142. package/dist/phase-diagram/svg-to-diagram.js +53 -49
  143. package/dist/phase-diagram/utils.d.ts +1 -0
  144. package/dist/phase-diagram/utils.js +80 -25
  145. package/dist/plot/AxisLabel.svelte +28 -3
  146. package/dist/plot/BarPlot.svelte +1182 -734
  147. package/dist/plot/BarPlot.svelte.d.ts +2 -2
  148. package/dist/plot/BarPlotControls.svelte +31 -5
  149. package/dist/plot/BarPlotControls.svelte.d.ts +1 -1
  150. package/dist/plot/ColorBar.svelte +479 -329
  151. package/dist/plot/ColorScaleSelect.svelte +27 -6
  152. package/dist/plot/ElementScatter.svelte +36 -15
  153. package/dist/plot/FillArea.svelte +152 -95
  154. package/dist/plot/Histogram.svelte +934 -571
  155. package/dist/plot/Histogram.svelte.d.ts +1 -1
  156. package/dist/plot/HistogramControls.svelte +53 -9
  157. package/dist/plot/HistogramControls.svelte.d.ts +1 -1
  158. package/dist/plot/InteractiveAxisLabel.svelte +34 -11
  159. package/dist/plot/InteractiveAxisLabel.svelte.d.ts +1 -1
  160. package/dist/plot/Line.svelte +63 -28
  161. package/dist/plot/PlotControls.svelte +157 -114
  162. package/dist/plot/PlotControls.svelte.d.ts +1 -1
  163. package/dist/plot/PlotLegend.svelte +174 -91
  164. package/dist/plot/PlotTooltip.svelte +45 -6
  165. package/dist/plot/PortalSelect.svelte +175 -147
  166. package/dist/plot/ReferenceLine.svelte +76 -22
  167. package/dist/plot/ReferenceLine3D.svelte +132 -107
  168. package/dist/plot/ReferencePlane.svelte +146 -121
  169. package/dist/plot/ScatterPlot.svelte +1681 -1091
  170. package/dist/plot/ScatterPlot.svelte.d.ts +2 -2
  171. package/dist/plot/ScatterPlot3D.svelte +256 -131
  172. package/dist/plot/ScatterPlot3D.svelte.d.ts +2 -2
  173. package/dist/plot/ScatterPlot3DControls.svelte +113 -63
  174. package/dist/plot/ScatterPlot3DControls.svelte.d.ts +2 -1
  175. package/dist/plot/ScatterPlot3DScene.svelte +608 -403
  176. package/dist/plot/ScatterPlot3DScene.svelte.d.ts +2 -2
  177. package/dist/plot/ScatterPlotControls.svelte +65 -25
  178. package/dist/plot/ScatterPlotControls.svelte.d.ts +1 -1
  179. package/dist/plot/ScatterPoint.svelte +98 -26
  180. package/dist/plot/ScatterPoint.svelte.d.ts +1 -0
  181. package/dist/plot/SpacegroupBarPlot.svelte +142 -85
  182. package/dist/plot/Surface3D.svelte +159 -108
  183. package/dist/plot/ZeroLines.svelte +55 -3
  184. package/dist/plot/ZoomRect.svelte +4 -2
  185. package/dist/plot/axis-utils.js +1 -3
  186. package/dist/plot/data-cleaning.js +12 -28
  187. package/dist/plot/data-transform.js +2 -1
  188. package/dist/plot/fill-utils.js +2 -0
  189. package/dist/plot/layout.d.ts +4 -1
  190. package/dist/plot/layout.js +33 -14
  191. package/dist/plot/reference-line.d.ts +2 -2
  192. package/dist/plot/reference-line.js +7 -5
  193. package/dist/plot/scales.js +24 -36
  194. package/dist/plot/types.d.ts +11 -23
  195. package/dist/plot/types.js +6 -11
  196. package/dist/plot/utils/label-placement.d.ts +32 -15
  197. package/dist/plot/utils/label-placement.js +227 -66
  198. package/dist/plot/utils/series-visibility.js +2 -3
  199. package/dist/rdf/RdfPlot.svelte +143 -91
  200. package/dist/rdf/calc-rdf.js +4 -5
  201. package/dist/sanitize.d.ts +4 -0
  202. package/dist/sanitize.js +107 -0
  203. package/dist/settings.d.ts +18 -6
  204. package/dist/settings.js +46 -16
  205. package/dist/spectral/Bands.svelte +632 -453
  206. package/dist/spectral/BandsAndDos.svelte +90 -49
  207. package/dist/spectral/BrillouinBandsDos.svelte +151 -93
  208. package/dist/spectral/Dos.svelte +389 -258
  209. package/dist/spectral/helpers.js +55 -43
  210. package/dist/state.svelte.d.ts +1 -1
  211. package/dist/state.svelte.js +3 -2
  212. package/dist/structure/Arrow.svelte +59 -20
  213. package/dist/structure/AtomLegend.svelte +215 -134
  214. package/dist/structure/Bond.svelte +73 -47
  215. package/dist/structure/CanvasTooltip.svelte +10 -2
  216. package/dist/structure/CellSelect.svelte +72 -45
  217. package/dist/structure/Cylinder.svelte +33 -17
  218. package/dist/structure/Lattice.svelte +88 -33
  219. package/dist/structure/Structure.svelte +1063 -797
  220. package/dist/structure/Structure.svelte.d.ts +1 -1
  221. package/dist/structure/StructureControls.svelte +349 -118
  222. package/dist/structure/StructureExportPane.svelte +124 -89
  223. package/dist/structure/StructureExportPane.svelte.d.ts +1 -1
  224. package/dist/structure/StructureInfoPane.svelte +304 -237
  225. package/dist/structure/StructureScene.svelte +879 -443
  226. package/dist/structure/StructureScene.svelte.d.ts +15 -7
  227. package/dist/structure/atom-properties.js +8 -8
  228. package/dist/structure/bonding.js +6 -7
  229. package/dist/structure/export.js +14 -29
  230. package/dist/structure/ferrox-wasm.js +1 -1
  231. package/dist/structure/index.d.ts +13 -3
  232. package/dist/structure/index.js +83 -23
  233. package/dist/structure/measure.d.ts +2 -2
  234. package/dist/structure/measure.js +4 -44
  235. package/dist/structure/parse.js +113 -141
  236. package/dist/structure/partial-occupancy.js +7 -10
  237. package/dist/structure/pbc.d.ts +1 -0
  238. package/dist/structure/pbc.js +16 -6
  239. package/dist/structure/supercell.d.ts +2 -2
  240. package/dist/structure/supercell.js +12 -22
  241. package/dist/structure/validation.js +1 -2
  242. package/dist/symmetry/SymmetryStats.svelte +84 -41
  243. package/dist/symmetry/WyckoffTable.svelte +26 -6
  244. package/dist/symmetry/cell-transform.js +5 -3
  245. package/dist/symmetry/index.js +8 -7
  246. package/dist/symmetry/spacegroups.js +148 -148
  247. package/dist/table/HeatmapTable.svelte +790 -554
  248. package/dist/table/HeatmapTable.svelte.d.ts +1 -1
  249. package/dist/table/ToggleMenu.svelte +125 -92
  250. package/dist/table/index.js +2 -4
  251. package/dist/theme/ThemeControl.svelte +21 -12
  252. package/dist/time.js +4 -1
  253. package/dist/tooltip/TooltipContent.svelte +33 -8
  254. package/dist/trajectory/Trajectory.svelte +758 -558
  255. package/dist/trajectory/TrajectoryError.svelte +14 -3
  256. package/dist/trajectory/TrajectoryExportPane.svelte +137 -83
  257. package/dist/trajectory/TrajectoryInfoPane.svelte +272 -143
  258. package/dist/trajectory/extract.js +10 -26
  259. package/dist/trajectory/format-detect.js +5 -5
  260. package/dist/trajectory/frame-reader.d.ts +1 -1
  261. package/dist/trajectory/frame-reader.js +5 -12
  262. package/dist/trajectory/helpers.d.ts +0 -1
  263. package/dist/trajectory/helpers.js +2 -17
  264. package/dist/trajectory/index.js +14 -12
  265. package/dist/trajectory/parse/ase.js +5 -4
  266. package/dist/trajectory/parse/hdf5.js +26 -18
  267. package/dist/trajectory/parse/index.js +13 -18
  268. package/dist/trajectory/parse/lammps.js +17 -7
  269. package/dist/trajectory/parse/vasp.js +5 -2
  270. package/dist/trajectory/parse/xyz.js +8 -7
  271. package/dist/trajectory/plotting.js +13 -8
  272. package/dist/utils.d.ts +1 -0
  273. package/dist/utils.js +13 -0
  274. package/dist/xrd/XrdPlot.svelte +337 -247
  275. package/dist/xrd/broadening.js +14 -9
  276. package/dist/xrd/calc-xrd.js +12 -18
  277. package/dist/xrd/parse.d.ts +1 -1
  278. package/dist/xrd/parse.js +17 -17
  279. package/package.json +99 -103
  280. package/readme.md +1 -1
  281. /package/dist/theme/{themes.js → themes.mjs} +0 -0
@@ -1,1280 +1,1869 @@
1
1
  <script
2
2
  lang="ts"
3
3
  generics="Metadata extends Record<string, unknown> = Record<string, unknown>"
4
- >import { format_value, symbol_names } from '../labels';
5
- import { FullscreenToggle, set_fullscreen_bg } from '../layout';
6
- import { AxisLabel, ColorBar, compute_element_placement, FillArea, get_tick_label, Line, PlotLegend, PlotTooltip, ReferenceLine, ScatterPlotControls, ScatterPoint, ZeroLines, ZoomRect, } from './';
7
- import { create_axis_change_handler } from './axis-utils';
8
- import { get_series_color, get_series_symbol, process_prop, } from './data-transform';
9
- import { AXIS_DEFAULTS } from './defaults';
10
- import { create_dimension_tracker, create_hover_lock, } from './hover-lock.svelte';
11
- import { DEFAULT_GRID_STYLE, DEFAULT_MARKERS, get_scale_type_name, is_time_scale, } from './types';
12
- import { compute_label_positions } from './utils/label-placement';
13
- import { handle_legend_double_click, toggle_group_visibility, toggle_series_visibility, } from './utils/series-visibility';
14
- import { DEFAULTS } from '../settings';
15
- import { extent } from 'd3-array';
16
- import { scaleTime } from 'd3-scale';
17
- import { untrack } from 'svelte';
18
- import { Tween } from 'svelte/motion';
19
- import { SvelteSet } from 'svelte/reactivity';
20
- import { apply_range_constraints, apply_where_condition, clamp_for_log_scale, convert_error_band_to_fill_region, generate_fill_path, is_fill_gradient, resolve_boundary, } from './fill-utils';
21
- import { expand_range_if_needed, get_relative_coords, normalize_y2_sync, pan_range, PINCH_ZOOM_THRESHOLD, pixels_to_data_delta, sync_y2_range, } from './interactions';
22
- import { calc_auto_padding, constrain_tooltip_position, filter_padding, LABEL_GAP_DEFAULT, measure_max_tick_width, } from './layout';
23
- import { group_ref_lines_by_z, index_ref_lines } from './reference-line';
24
- import { create_color_scale, create_scale, create_size_scale, generate_ticks, get_nice_data_range, } from './scales';
25
- let { series = $bindable([]), x_axis = $bindable({}), x2_axis = $bindable({}), y_axis = $bindable({}), y2_axis = $bindable({}), display = $bindable(DEFAULTS.scatter.display), styles: styles_init = {}, controls: controls_init = {}, padding = {}, range_padding = 0.05, current_x_value = null, tooltip_point = $bindable(null), selected_point = null, hovered = $bindable(false), tooltip, user_content, change = () => { }, color_scale = {
26
- type: `linear`,
27
- scheme: `interpolateViridis`,
28
- value_range: undefined,
29
- }, color_bar = {}, size_scale = { type: `linear`, radius_range: [2, 10], value_range: undefined }, label_placement_config = {}, hover_config = {}, legend = {}, point_tween, line_tween, point_events, on_point_click, on_point_hover, fill_regions = $bindable([]), error_bands = [], on_fill_click, on_fill_hover, ref_lines = $bindable([]), on_ref_line_click, on_ref_line_hover, selected_series_idx = $bindable(0), wrapper = $bindable(), fullscreen = $bindable(false), fullscreen_toggle = true, children, header_controls, controls_extra, data_loader, on_axis_change, on_error, pan = {}, ...rest } = $props();
30
- // Merged axis/display values with defaults (use $derived to avoid breaking $bindable)
31
- const final_x_axis = $derived({
4
+ >
5
+ import type { D3ColorSchemeName, D3InterpolateName } from '../colors'
6
+ import type { D3SymbolName } from '../labels'
7
+ import { format_value, symbol_names } from '../labels'
8
+ import { sanitize_html } from '../sanitize'
9
+ import { FullscreenToggle, set_fullscreen_bg } from '../layout'
10
+ import type { Vec2 } from '../math'
11
+ import type {
12
+ AxisLoadError,
13
+ BasePlotProps,
14
+ ControlsConfig,
15
+ DataLoaderFn,
16
+ DataSeries,
17
+ ErrorBand,
18
+ FillHandlerEvent,
19
+ FillRegion,
20
+ HoverConfig,
21
+ InitialRanges,
22
+ InternalPoint,
23
+ LabelPlacementConfig,
24
+ LegendConfig,
25
+ PanConfig,
26
+ PlotConfig,
27
+ Point,
28
+ RefLine,
29
+ RefLineEvent,
30
+ ScaleType,
31
+ ScatterHandlerEvent,
32
+ ScatterHandlerProps,
33
+ Sides,
34
+ StyleOverrides,
35
+ TweenedOptions,
36
+ UserContentProps,
37
+ XyObj,
38
+ } from './'
39
+ import {
40
+ AxisLabel,
41
+ ColorBar,
42
+ compute_element_placement,
43
+ FillArea,
44
+ get_tick_label,
45
+ Line,
46
+ PlotLegend,
47
+ PlotTooltip,
48
+ ReferenceLine,
49
+ ScatterPlotControls,
50
+ ScatterPoint,
51
+ ZeroLines,
52
+ ZoomRect,
53
+ } from './'
54
+ import type { AxisChangeState } from './axis-utils'
55
+ import { create_axis_change_handler } from './axis-utils'
56
+ import {
57
+ get_series_color,
58
+ get_series_symbol,
59
+ process_prop,
60
+ } from './data-transform'
61
+ import { AXIS_DEFAULTS } from './defaults'
62
+ import {
63
+ create_dimension_tracker,
64
+ create_hover_lock,
65
+ } from './hover-lock.svelte'
66
+ import {
67
+ DEFAULT_GRID_STYLE,
68
+ DEFAULT_MARKERS,
69
+ get_scale_type_name,
70
+ is_time_scale,
71
+ } from './types'
72
+ import { compute_label_positions } from './utils/label-placement'
73
+ import {
74
+ handle_legend_double_click,
75
+ toggle_group_visibility,
76
+ toggle_series_visibility,
77
+ } from './utils/series-visibility'
78
+ import { DEFAULTS } from '../settings'
79
+ import { extent } from 'd3-array'
80
+ import { scaleTime } from 'd3-scale'
81
+ import type { ComponentProps, Snippet } from 'svelte'
82
+ import { untrack } from 'svelte'
83
+ import type { HTMLAttributes } from 'svelte/elements'
84
+ import { Tween } from 'svelte/motion'
85
+ import { SvelteSet } from 'svelte/reactivity'
86
+ import type { FillPathPoint } from './fill-utils'
87
+ import {
88
+ apply_range_constraints,
89
+ apply_where_condition,
90
+ clamp_for_log_scale,
91
+ convert_error_band_to_fill_region,
92
+ generate_fill_path,
93
+ is_fill_gradient,
94
+ resolve_boundary,
95
+ } from './fill-utils'
96
+ import {
97
+ expand_range_if_needed,
98
+ get_relative_coords,
99
+ normalize_y2_sync,
100
+ pan_range,
101
+ PINCH_ZOOM_THRESHOLD,
102
+ pixels_to_data_delta,
103
+ sync_y2_range,
104
+ } from './interactions'
105
+ import type { Rect } from './layout'
106
+ import {
107
+ calc_auto_padding,
108
+ constrain_tooltip_position,
109
+ filter_padding,
110
+ LABEL_GAP_DEFAULT,
111
+ measure_max_tick_width,
112
+ } from './layout'
113
+ import type { IndexedRefLine } from './reference-line'
114
+ import { group_ref_lines_by_z, index_ref_lines } from './reference-line'
115
+ import {
116
+ create_color_scale,
117
+ create_scale,
118
+ create_size_scale,
119
+ generate_ticks,
120
+ get_nice_data_range,
121
+ } from './scales'
122
+
123
+ let {
124
+ series = $bindable([]),
125
+ x_axis = $bindable({}),
126
+ x2_axis = $bindable({}),
127
+ y_axis = $bindable({}),
128
+ y2_axis = $bindable({}),
129
+ display = $bindable(DEFAULTS.scatter.display),
130
+ styles: styles_init = {},
131
+ controls: controls_init = {},
132
+ padding = {},
133
+ range_padding = 0.05,
134
+ current_x_value = null,
135
+ tooltip_point = $bindable(null),
136
+ selected_point = null,
137
+ hovered = $bindable(false),
138
+ tooltip,
139
+ user_content,
140
+ change = () => {},
141
+ color_scale = {
142
+ type: `linear`,
143
+ scheme: `interpolateViridis`,
144
+ value_range: undefined,
145
+ },
146
+ color_bar = {},
147
+ size_scale = { type: `linear`, radius_range: [2, 10], value_range: undefined },
148
+ label_placement_config = {},
149
+ hover_config = {},
150
+ legend = {},
151
+ point_tween,
152
+ line_tween,
153
+ point_events,
154
+ on_point_click,
155
+ on_point_hover,
156
+ fill_regions = $bindable([]),
157
+ error_bands = [],
158
+ on_fill_click,
159
+ on_fill_hover,
160
+ ref_lines = $bindable([]),
161
+ on_ref_line_click,
162
+ on_ref_line_hover,
163
+ selected_series_idx = $bindable(0),
164
+ wrapper = $bindable(),
165
+ fullscreen = $bindable(false),
166
+ fullscreen_toggle = true,
167
+ children,
168
+ header_controls,
169
+ controls_extra,
170
+ data_loader,
171
+ on_axis_change,
172
+ on_error,
173
+ pan = {},
174
+ ...rest
175
+ }: HTMLAttributes<HTMLDivElement> & Omit<BasePlotProps, `change`> & PlotConfig & {
176
+ series?: DataSeries<Metadata>[]
177
+ styles?: StyleOverrides
178
+ controls?: ControlsConfig
179
+ current_x_value?: number | null
180
+ tooltip_point?: InternalPoint<Metadata> | null
181
+ selected_point?: { series_idx: number; point_idx: number } | null
182
+ tooltip?: Snippet<[ScatterHandlerProps<Metadata>]>
183
+ user_content?: Snippet<[UserContentProps]>
184
+ header_controls?: Snippet<
185
+ [{ height: number; width: number; fullscreen: boolean }]
186
+ >
187
+ controls_extra?: Snippet<
188
+ [
189
+ & { styles: StyleOverrides; selected_series_idx: number }
190
+ & Required<PlotConfig>,
191
+ ]
192
+ >
193
+ change?: (
194
+ data: (Point<Metadata> & { series: DataSeries<Metadata> }) | null,
195
+ ) => void
196
+ color_scale?: {
197
+ type?: ScaleType
198
+ scheme?: D3ColorSchemeName | D3InterpolateName
199
+ value_range?: [number, number]
200
+ } | D3InterpolateName
201
+ size_scale?: {
202
+ type?: ScaleType
203
+ radius_range?: [number, number]
204
+ value_range?: [number, number]
205
+ }
206
+ color_bar?:
207
+ | (ComponentProps<typeof ColorBar> & {
208
+ margin?: number | Sides
209
+ tween?: TweenedOptions<XyObj>
210
+ responsive?: boolean // Allow colorbar to reposition if density changes (default: false)
211
+ })
212
+ | null
213
+ label_placement_config?: Partial<LabelPlacementConfig>
214
+ hover_config?: Partial<HoverConfig>
215
+ legend?: LegendConfig | null
216
+ point_tween?: TweenedOptions<XyObj>
217
+ line_tween?: TweenedOptions<string>
218
+ point_events?: Record<
219
+ string,
220
+ (payload: { point: InternalPoint<Metadata>; event: Event }) => void
221
+ >
222
+ on_point_click?: (data: ScatterHandlerEvent<Metadata>) => void
223
+ on_point_hover?: (data: ScatterHandlerEvent<Metadata> | null) => void
224
+ fill_regions?: FillRegion[] // Bindable for legend toggle support
225
+ error_bands?: ErrorBand[]
226
+ on_fill_click?: (event: FillHandlerEvent) => void
227
+ on_fill_hover?: (event: FillHandlerEvent | null) => void
228
+ ref_lines?: RefLine[] // Bindable for legend toggle support
229
+ on_ref_line_click?: (event: RefLineEvent) => void
230
+ on_ref_line_hover?: (event: RefLineEvent | null) => void
231
+ selected_series_idx?: number
232
+ wrapper?: HTMLDivElement
233
+ // Interactive axis props
234
+ data_loader?: DataLoaderFn<Metadata>
235
+ on_axis_change?: (
236
+ axis: `x` | `x2` | `y` | `y2`,
237
+ key: string,
238
+ new_series: DataSeries<Metadata>[],
239
+ ) => void
240
+ on_error?: (error: AxisLoadError) => void
241
+ pan?: PanConfig
242
+ } = $props()
243
+
244
+ // Merged axis/display values with defaults (use $derived to avoid breaking $bindable)
245
+ const final_x_axis = $derived({
32
246
  ...AXIS_DEFAULTS,
33
247
  label_shift: { x: 0, y: -40 }, // x-axis needs different label position
34
248
  ...(x_axis ?? {}),
35
- });
36
- const final_y_axis = $derived({ ...AXIS_DEFAULTS, ...(y_axis ?? {}) });
37
- const final_x2_axis = $derived({
249
+ })
250
+ const final_y_axis = $derived({ ...AXIS_DEFAULTS, ...(y_axis ?? {}) })
251
+ const final_x2_axis = $derived({
38
252
  ...AXIS_DEFAULTS,
39
253
  label_shift: { x: 0, y: 40 }, // x2-axis label above top edge
40
254
  ...(x2_axis ?? {}),
41
- });
42
- const final_y2_axis = $derived({ ...AXIS_DEFAULTS, ...(y2_axis ?? {}) });
43
- // Cache time-axis check — used in ~10 places for scale/tick/tooltip logic
44
- let is_time_x = $derived(is_time_scale(final_x_axis.scale_type, final_x_axis.format));
45
- let is_time_x2 = $derived(is_time_scale(final_x2_axis.scale_type, final_x2_axis.format));
46
- const final_display = $derived({ ...DEFAULTS.scatter.display, ...(display ?? {}) });
47
- // Local state for styles (initialized from prop, owned by this component for controls)
48
- // Using $state because styles has bindings in ScatterPlotControls
49
- // untrack() explicitly captures initial prop value (intentional - props provide initial config)
50
- let styles = $state(untrack(() => ({
255
+ })
256
+ const final_y2_axis = $derived({ ...AXIS_DEFAULTS, ...(y2_axis ?? {}) })
257
+ // Cache time-axis check — used in ~10 places for scale/tick/tooltip logic
258
+ let is_time_x = $derived(
259
+ is_time_scale(final_x_axis.scale_type, final_x_axis.format),
260
+ )
261
+ let is_time_x2 = $derived(
262
+ is_time_scale(final_x2_axis.scale_type, final_x2_axis.format),
263
+ )
264
+ const final_display = $derived({ ...DEFAULTS.scatter.display, ...(display ?? {}) })
265
+ // Local state for styles (initialized from prop, owned by this component for controls)
266
+ // Using $state because styles has bindings in ScatterPlotControls
267
+ // untrack() explicitly captures initial prop value (intentional - props provide initial config)
268
+ let styles = $state(untrack(() => ({
51
269
  show_points: DEFAULTS.scatter.show_points,
52
270
  show_lines: DEFAULTS.scatter.show_lines,
53
271
  point: { ...DEFAULTS.scatter.point, ...(styles_init?.point ?? {}) },
54
272
  line: { ...DEFAULTS.scatter.line, ...(styles_init?.line ?? {}) },
55
273
  ...(styles_init ?? {}),
56
- })));
57
- let controls = $derived({ show: true, open: false, ...controls_init });
58
- let [width, height] = $state([0, 0]);
59
- let svg_element = $state(null); // Bind the SVG element
60
- let svg_bounding_box = $state(null); // Store SVG bounds during drag
61
- // Track which specific control properties user has modified
62
- let touched = new SvelteSet();
63
- // Unique component ID to avoid clipPath conflicts between multiple instances
64
- let component_id = $state(`scatter-${crypto.randomUUID()}`);
65
- let clip_path_id = $derived(`plot-area-clip-${component_id}`);
66
- // Assign stable IDs to series for keying
67
- let series_with_ids = $derived(series.map((srs, idx) => {
68
- if (!srs || typeof srs !== `object`)
69
- return srs;
70
- // Use series.id if provided, otherwise fall back to index
71
- // prevents re-mounts when series are reordered if stable IDs are provided
72
- return { ...srs, _id: srs.id ?? idx };
73
- }));
74
- // State for rectangle zoom selection
75
- let drag_start_coords = $state(null);
76
- let drag_current_coords = $state(null);
77
- // Zoom/pan state - track both initial (data-driven) and current (after pan/zoom) ranges
78
- let initial_x_range = $state([0, 1]);
79
- let initial_x2_range = $state([0, 1]);
80
- let initial_y_range = $state([0, 1]);
81
- let initial_y2_range = $state([0, 1]);
82
- let zoom_x_range = $state([0, 1]);
83
- let zoom_x2_range = $state([0, 1]);
84
- let zoom_y_range = $state([0, 1]);
85
- let zoom_y2_range = $state([0, 1]);
86
- let previous_series_visibility = $state(null);
87
- // Y2 axis sync configuration
88
- let y2_sync_config = $derived(normalize_y2_sync(y2_axis?.sync));
89
- // Track previous sync mode to detect changes (updated in $effect.pre to avoid race conditions)
90
- let prev_sync_mode = $state(`none`);
91
- // Helper to compute synced y2 range or return fallback when sync disabled
92
- const get_synced_y2 = (y1_range, fallback) => y2_sync_config.mode !== `none`
93
- ? sync_y2_range(y1_range, initial_y2_range, y2_sync_config)
94
- : fallback;
95
- // Effect to update y2 range when sync mode changes - use $effect.pre to capture
96
- // mode change before the main range-update effect runs, ensuring sync is applied
97
- // immediately when toggled (not delayed until next data change)
98
- $effect.pre(() => {
99
- const mode = y2_sync_config.mode;
274
+ })))
275
+ let controls = $derived({ show: true, open: false, ...controls_init })
276
+
277
+ let [width, height] = $state([0, 0])
278
+ let svg_element: SVGElement | null = $state(null) // Bind the SVG element
279
+ let svg_bounding_box: DOMRect | null = $state(null) // Store SVG bounds during drag
280
+
281
+ // Track which specific control properties user has modified
282
+ let touched = new SvelteSet<string>()
283
+
284
+ // Unique component ID to avoid clipPath conflicts between multiple instances
285
+ let component_id = $state(`scatter-${crypto.randomUUID()}`)
286
+ let clip_path_id = $derived(`plot-area-clip-${component_id}`)
287
+
288
+ // Assign stable IDs to series for keying
289
+ let series_with_ids = $derived(
290
+ series.map((srs: DataSeries<Metadata>, idx: number) => {
291
+ if (!srs || typeof srs !== `object`) return srs
292
+ // Use series.id if provided, otherwise fall back to index
293
+ // prevents re-mounts when series are reordered if stable IDs are provided
294
+ return { ...srs, _id: srs.id ?? idx }
295
+ }),
296
+ )
297
+
298
+ // State for rectangle zoom selection
299
+ let drag_start_coords = $state<XyObj | null>(null)
300
+ let drag_current_coords = $state<XyObj | null>(null)
301
+
302
+ // Zoom/pan state - track both initial (data-driven) and current (after pan/zoom) ranges
303
+ let initial_x_range = $state<[number, number]>([0, 1])
304
+ let initial_x2_range = $state<[number, number]>([0, 1])
305
+ let initial_y_range = $state<[number, number]>([0, 1])
306
+ let initial_y2_range = $state<[number, number]>([0, 1])
307
+ let zoom_x_range = $state<[number, number]>([0, 1])
308
+ let zoom_x2_range = $state<[number, number]>([0, 1])
309
+ let zoom_y_range = $state<[number, number]>([0, 1])
310
+ let zoom_y2_range = $state<[number, number]>([0, 1])
311
+ let previous_series_visibility: boolean[] | null = $state(null)
312
+
313
+ // Y2 axis sync configuration
314
+ let y2_sync_config = $derived(normalize_y2_sync(y2_axis?.sync))
315
+ // Track previous sync mode to detect changes (updated in $effect.pre to avoid race conditions)
316
+ let prev_sync_mode = $state<string>(`none`)
317
+
318
+ // Helper to compute synced y2 range or return fallback when sync disabled
319
+ const get_synced_y2 = (y1_range: Vec2, fallback: Vec2): Vec2 =>
320
+ y2_sync_config.mode !== `none`
321
+ ? sync_y2_range(y1_range, initial_y2_range, y2_sync_config)
322
+ : fallback
323
+
324
+ // Effect to update y2 range when sync mode changes - use $effect.pre to capture
325
+ // mode change before the main range-update effect runs, ensuring sync is applied
326
+ // immediately when toggled (not delayed until next data change)
327
+ $effect.pre(() => {
328
+ const mode = y2_sync_config.mode
100
329
  if (mode !== prev_sync_mode) {
101
- // When sync mode becomes enabled (or changes), apply sync immediately
102
- if (mode !== `none`) {
103
- zoom_y2_range = sync_y2_range(zoom_y_range, initial_y2_range, y2_sync_config);
104
- }
105
- else {
106
- // When switching to independent mode, reset Y2 to its data range
107
- zoom_y2_range = [...initial_y2_range];
108
- }
109
- prev_sync_mode = mode;
330
+ // When sync mode becomes enabled (or changes), apply sync immediately
331
+ if (mode !== `none`) {
332
+ zoom_y2_range = sync_y2_range(zoom_y_range, initial_y2_range, y2_sync_config)
333
+ } else {
334
+ // When switching to independent mode, reset Y2 to its data range
335
+ zoom_y2_range = [...initial_y2_range] as [number, number]
336
+ }
337
+ prev_sync_mode = mode
110
338
  }
111
- });
112
- // Pan state
113
- let is_focused = $state(false);
114
- let shift_held = $state(false);
115
- let pan_drag_state = $state(null);
116
- let touch_state = $state(null);
117
- // Fill region hover state
118
- let hovered_fill_idx = $state(null);
119
- // Reference line hover state
120
- let hovered_ref_line_idx = $state(null);
121
- // Interactive axis loading state
122
- let axis_loading = $state(null);
123
- // State to hold the calculated label positions after simulation
124
- let label_positions = $state({});
125
- // State for legend dragging
126
- let legend_is_dragging = $state(false);
127
- let legend_drag_offset = $state({ x: 0, y: 0 });
128
- let legend_manual_position = $state(null);
129
- // State for legend/colorbar placement stability
130
- let legend_element = $state();
131
- let colorbar_element = $state();
132
- const legend_hover = create_hover_lock();
133
- const colorbar_hover = create_hover_lock();
134
- const dim_tracker = create_dimension_tracker();
135
- let has_initial_legend_placement = $state(false);
136
- let has_initial_colorbar_placement = $state(false);
137
- // Clear pending hover lock timeouts on unmount
138
- $effect(() => () => {
139
- legend_hover.cleanup();
140
- colorbar_hover.cleanup();
141
- });
142
- // Tooltip element reference for dynamic sizing
143
- let tooltip_el = $state();
144
- let points_by_axis = $derived.by(() => {
145
- const all = [];
146
- const y1 = [];
147
- const y2 = [];
148
- const x2 = [];
339
+ })
340
+
341
+ // Pan state
342
+ let is_focused = $state(false)
343
+ let shift_held = $state(false)
344
+ let pan_drag_state = $state<
345
+ InitialRanges & { start: { x: number; y: number } } | null
346
+ >(null)
347
+ let touch_state = $state<
348
+ InitialRanges & { start_touches: { x: number; y: number }[] } | null
349
+ >(null)
350
+
351
+ // Fill region hover state
352
+ let hovered_fill_idx = $state<number | null>(null)
353
+
354
+ // Reference line hover state
355
+ let hovered_ref_line_idx = $state<number | null>(null)
356
+
357
+ // Interactive axis loading state
358
+ let axis_loading = $state<`x` | `x2` | `y` | `y2` | null>(null)
359
+
360
+ // State to hold the calculated label positions after simulation
361
+ let label_positions = $state<Record<string, XyObj>>({})
362
+
363
+ // State for legend dragging
364
+ let legend_is_dragging = $state(false)
365
+ let legend_drag_offset = $state<{ x: number; y: number }>({ x: 0, y: 0 })
366
+ let legend_manual_position = $state<{ x: number; y: number } | null>(null)
367
+
368
+ // State for legend/colorbar placement stability
369
+ let legend_element = $state<HTMLDivElement | undefined>()
370
+ let colorbar_element = $state<HTMLDivElement | undefined>()
371
+ const legend_hover = create_hover_lock()
372
+ const colorbar_hover = create_hover_lock()
373
+ const dim_tracker = create_dimension_tracker()
374
+ let has_initial_legend_placement = $state(false)
375
+ let has_initial_colorbar_placement = $state(false)
376
+
377
+ // Clear pending hover lock timeouts on unmount
378
+ $effect(() => () => {
379
+ legend_hover.cleanup()
380
+ colorbar_hover.cleanup()
381
+ })
382
+
383
+ // Tooltip element reference for dynamic sizing
384
+ let tooltip_el = $state<HTMLDivElement | undefined>()
385
+
386
+ // Module-level constants to avoid repeated allocations
387
+ // Create and categorize points in a single pass (instead of 3 separate iterations)
388
+ type SimplePoint = { x: number; y: number }
389
+ let points_by_axis = $derived.by(() => {
390
+ const all: SimplePoint[] = []
391
+ const y1: SimplePoint[] = []
392
+ const y2: SimplePoint[] = []
393
+ const x2: SimplePoint[] = []
394
+
149
395
  for (const srs of series_with_ids) {
150
- if (!srs)
151
- continue;
152
- const { x: xs, y: ys, visible = true, y_axis = `y1`, x_axis: x_ax = `x1` } = srs;
153
- for (let idx = 0; idx < xs.length; idx++) {
154
- const point = { x: xs[idx], y: ys[idx] };
155
- all.push(point);
156
- if (visible) {
157
- if (y_axis === `y2`)
158
- y2.push(point);
159
- else
160
- y1.push(point);
161
- if (x_ax === `x2`)
162
- x2.push(point);
163
- }
396
+ if (!srs) continue
397
+ const { x: xs, y: ys, visible = true, y_axis = `y1`, x_axis: x_ax = `x1` } =
398
+ srs as DataSeries
399
+ for (let idx = 0; idx < xs.length; idx++) {
400
+ const point = { x: xs[idx], y: ys[idx] }
401
+ all.push(point)
402
+ if (visible) {
403
+ if (y_axis === `y2`) y2.push(point)
404
+ else y1.push(point)
405
+ if (x_ax === `x2`) x2.push(point)
164
406
  }
407
+ }
165
408
  }
166
- return { all, y1, y2, x2 };
167
- });
168
- let all_points = $derived(points_by_axis.all);
169
- let y1_points = $derived(points_by_axis.y1);
170
- let y2_points = $derived(points_by_axis.y2);
171
- let x2_points = $derived(points_by_axis.x2);
172
- // Layout: dynamic padding based on tick label widths
173
- const default_padding = { t: 5, b: 50, l: 50, r: 20 };
174
- let pad = $state(untrack(() => filter_padding(padding, default_padding)));
175
- // Update padding when format or ticks change
176
- $effect(() => {
409
+ return { all, y1, y2, x2 }
410
+ })
411
+
412
+ let all_points = $derived(points_by_axis.all)
413
+ let y1_points = $derived(points_by_axis.y1)
414
+ let y2_points = $derived(points_by_axis.y2)
415
+ let x2_points = $derived(points_by_axis.x2)
416
+
417
+ // Layout: dynamic padding based on tick label widths
418
+ const default_padding = { t: 5, b: 50, l: 50, r: 20 }
419
+ let pad = $state(untrack(() => filter_padding(padding, default_padding)))
420
+
421
+ // Update padding when format or ticks change
422
+ $effect(() => {
177
423
  const new_pad = width && height &&
178
424
  (y_tick_values.length || y2_tick_values.length || x2_tick_values.length)
179
- ? calc_auto_padding({
180
- padding,
181
- default_padding,
182
- x2_axis: { ...final_x2_axis, tick_values: x2_tick_values },
183
- y_axis: { ...final_y_axis, tick_values: y_tick_values },
184
- y2_axis: { ...final_y2_axis, tick_values: y2_tick_values },
185
- })
186
- : filter_padding(padding, default_padding);
187
- if (pad.t !== new_pad.t ||
188
- pad.b !== new_pad.b ||
189
- pad.l !== new_pad.l ||
190
- pad.r !== new_pad.r)
191
- pad = new_pad;
192
- });
193
- // Reactive clip area dimensions to ensure proper responsiveness
194
- let clip_area = $derived({
425
+ ? calc_auto_padding({
426
+ padding,
427
+ default_padding,
428
+ x2_axis: { ...final_x2_axis, tick_values: x2_tick_values },
429
+ y_axis: { ...final_y_axis, tick_values: y_tick_values },
430
+ y2_axis: { ...final_y2_axis, tick_values: y2_tick_values },
431
+ })
432
+ : filter_padding(padding, default_padding)
433
+
434
+ if (
435
+ pad.t !== new_pad.t ||
436
+ pad.b !== new_pad.b ||
437
+ pad.l !== new_pad.l ||
438
+ pad.r !== new_pad.r
439
+ ) pad = new_pad
440
+ })
441
+
442
+ // Reactive clip area dimensions to ensure proper responsiveness
443
+ let clip_area = $derived({
195
444
  x: pad.l || 0,
196
445
  y: pad.t || 0,
197
446
  width: isFinite(width - pad.l - pad.r) ? Math.max(1, width - pad.l - pad.r) : 1,
198
447
  height: isFinite(height - pad.t - pad.b)
199
- ? Math.max(1, height - pad.t - pad.b)
200
- : 1,
201
- });
202
- // Calculate plot area center coordinates
203
- let plot_center_x = $derived(pad.l + (width - pad.r - pad.l) / 2);
204
- let plot_center_y = $derived(pad.t + (height - pad.b - pad.t) / 2);
205
- // Extract color and size values in single pass (used for scale computations)
206
- let series_value_arrays = $derived.by(() => {
207
- const color_values = [];
208
- const size_values = [];
448
+ ? Math.max(1, height - pad.t - pad.b)
449
+ : 1,
450
+ })
451
+
452
+ // Calculate plot area center coordinates
453
+ let plot_center_x = $derived(pad.l + (width - pad.r - pad.l) / 2)
454
+ let plot_center_y = $derived(pad.t + (height - pad.b - pad.t) / 2)
455
+
456
+ // Extract color and size values in single pass (used for scale computations)
457
+ let series_value_arrays = $derived.by(() => {
458
+ const color_values: number[] = []
459
+ const size_values: number[] = []
209
460
  for (const srs of series_with_ids) {
210
- if (!srs)
211
- continue;
212
- const { color_values: cvs, size_values: svs } = srs;
213
- if (cvs) {
214
- for (const val of cvs)
215
- if (val != null)
216
- color_values.push(val);
217
- }
218
- if (svs) {
219
- for (const val of svs)
220
- if (val != null)
221
- size_values.push(val);
222
- }
461
+ if (!srs) continue
462
+ const { color_values: cvs, size_values: svs } = srs as DataSeries
463
+ if (cvs) { for (const val of cvs) if (val != null) color_values.push(val) }
464
+ if (svs) { for (const val of svs) if (val != null) size_values.push(val) }
223
465
  }
224
- return { color_values, size_values };
225
- });
226
- let all_color_values = $derived(series_value_arrays.color_values);
227
- // Compute auto ranges based on data and limits
228
- let auto_x_range = $derived(get_nice_data_range(all_points, ({ x }) => x, final_x_axis.range ?? [null, null], final_x_axis.scale_type ?? `linear`, range_padding, is_time_x));
229
- let auto_y_range = $derived(get_nice_data_range(y1_points, ({ y }) => y, final_y_axis.range ?? [null, null], final_y_axis.scale_type ?? `linear`, range_padding, false));
230
- let auto_x2_range = $derived(get_nice_data_range(x2_points, ({ x }) => x, final_x2_axis.range ?? [null, null], final_x2_axis.scale_type ?? `linear`, range_padding, is_time_x2));
231
- let auto_y2_range = $derived(get_nice_data_range(y2_points, ({ y }) => y, final_y2_axis.range ?? [null, null], final_y2_axis.scale_type ?? `linear`, range_padding, false));
232
- // Update zoom ranges when auto ranges or explicit ranges change
233
- // - Explicit ranges (from zoom/pan): apply directly
234
- // - Auto ranges (from data changes): use lazy expansion to preserve view context
235
- $effect(() => {
466
+ return { color_values, size_values }
467
+ })
468
+ let all_color_values = $derived(series_value_arrays.color_values)
469
+
470
+ // Compute auto ranges based on data and limits
471
+ let auto_x_range = $derived(
472
+ get_nice_data_range(
473
+ all_points,
474
+ ({ x }) => x,
475
+ final_x_axis.range ?? [null, null],
476
+ final_x_axis.scale_type ?? `linear`,
477
+ range_padding,
478
+ is_time_x,
479
+ ),
480
+ )
481
+
482
+ let auto_y_range = $derived(
483
+ get_nice_data_range(
484
+ y1_points,
485
+ ({ y }) => y,
486
+ final_y_axis.range ?? [null, null],
487
+ final_y_axis.scale_type ?? `linear`,
488
+ range_padding,
489
+ false,
490
+ ),
491
+ )
492
+
493
+ let auto_x2_range = $derived(
494
+ get_nice_data_range(
495
+ x2_points,
496
+ ({ x }) => x,
497
+ final_x2_axis.range ?? [null, null],
498
+ final_x2_axis.scale_type ?? `linear`,
499
+ range_padding,
500
+ is_time_x2,
501
+ ),
502
+ )
503
+
504
+ let auto_y2_range = $derived(
505
+ get_nice_data_range(
506
+ y2_points,
507
+ ({ y }) => y,
508
+ final_y2_axis.range ?? [null, null],
509
+ final_y2_axis.scale_type ?? `linear`,
510
+ range_padding,
511
+ false,
512
+ ),
513
+ )
514
+
515
+ // Update zoom ranges when auto ranges or explicit ranges change
516
+ // - Explicit ranges (from zoom/pan): apply directly
517
+ // - Auto ranges (from data changes): use lazy expansion to preserve view context
518
+ $effect(() => {
236
519
  // Helper to get effective range (explicit ?? auto) and check if explicit
237
- const get_range = (axis, auto) => {
238
- const explicit = axis.range?.[0] != null && axis.range?.[1] != null;
239
- return {
240
- explicit,
241
- range: [axis.range?.[0] ?? auto[0], axis.range?.[1] ?? auto[1]],
242
- };
243
- };
244
- const x = get_range(final_x_axis, auto_x_range);
245
- const x2 = get_range(final_x2_axis, auto_x2_range);
246
- const y = get_range(final_y_axis, auto_y_range);
247
- const y2 = get_range(final_y2_axis, auto_y2_range);
520
+ const get_range = (
521
+ axis: { range?: [number | null, number | null] },
522
+ auto: Vec2,
523
+ ): { explicit: boolean; range: Vec2 } => {
524
+ const explicit = axis.range?.[0] != null && axis.range?.[1] != null
525
+ const range = [axis.range?.[0] ?? auto[0], axis.range?.[1] ?? auto[1]] as Vec2
526
+ return { explicit, range }
527
+ }
528
+
529
+ const x = get_range(final_x_axis, auto_x_range)
530
+ const x2 = get_range(final_x2_axis, auto_x2_range)
531
+ const y = get_range(final_y_axis, auto_y_range)
532
+ const y2 = get_range(final_y2_axis, auto_y2_range)
533
+
248
534
  // X axis: explicit → direct, auto → lazy expand
249
535
  if (x.explicit) {
250
- zoom_x_range = x.range;
251
- }
252
- else {
253
- const result = expand_range_if_needed(initial_x_range, x.range);
254
- if (result.changed) {
255
- ;
256
- [initial_x_range, zoom_x_range] = [result.range, result.range];
257
- }
536
+ zoom_x_range = x.range
537
+ } else {
538
+ const result = expand_range_if_needed(initial_x_range, x.range)
539
+ if (result.changed) {
540
+ ;[initial_x_range, zoom_x_range] = [result.range, result.range]
541
+ }
258
542
  }
543
+
259
544
  // X2 axis: explicit → direct, auto → lazy expand
260
545
  if (x2.explicit) {
261
- zoom_x2_range = x2.range;
262
- }
263
- else {
264
- const result = expand_range_if_needed(initial_x2_range, x2.range);
265
- if (result.changed) {
266
- ;
267
- [initial_x2_range, zoom_x2_range] = [result.range, result.range];
268
- }
546
+ zoom_x2_range = x2.range
547
+ } else {
548
+ const result = expand_range_if_needed(initial_x2_range, x2.range)
549
+ if (result.changed) {
550
+ ;[initial_x2_range, zoom_x2_range] = [result.range, result.range]
551
+ }
269
552
  }
553
+
270
554
  // Y axis: explicit → direct, auto → lazy expand
271
555
  if (y.explicit) {
272
- zoom_y_range = y.range;
273
- }
274
- else {
275
- const result = expand_range_if_needed(initial_y_range, y.range);
276
- if (result.changed) {
277
- ;
278
- [initial_y_range, zoom_y_range] = [result.range, result.range];
279
- }
556
+ zoom_y_range = y.range
557
+ } else {
558
+ const result = expand_range_if_needed(initial_y_range, y.range)
559
+ if (result.changed) {
560
+ ;[initial_y_range, zoom_y_range] = [result.range, result.range]
561
+ }
280
562
  }
563
+
281
564
  // Y2 axis: explicit → direct, else expand initial range then optionally sync
282
565
  if (y2.explicit) {
283
- zoom_y2_range = y2.range;
284
- }
285
- else {
286
- const result = expand_range_if_needed(initial_y2_range, y2.range);
287
- if (result.changed)
288
- initial_y2_range = result.range;
289
- // Apply sync if enabled, otherwise use expanded range (or keep current if unchanged)
290
- if (y2_sync_config.mode !== `none`) {
291
- zoom_y2_range = sync_y2_range(zoom_y_range, initial_y2_range, y2_sync_config);
292
- }
293
- else if (result.changed) {
294
- zoom_y2_range = result.range;
295
- }
566
+ zoom_y2_range = y2.range
567
+ } else {
568
+ const result = expand_range_if_needed(initial_y2_range, y2.range)
569
+ if (result.changed) initial_y2_range = result.range
570
+ // Apply sync if enabled, otherwise use expanded range (or keep current if unchanged)
571
+ if (y2_sync_config.mode !== `none`) {
572
+ zoom_y2_range = sync_y2_range(zoom_y_range, initial_y2_range, y2_sync_config)
573
+ } else if (result.changed) {
574
+ zoom_y2_range = result.range
575
+ }
296
576
  }
297
- });
298
- let [x_min, x_max] = $derived(zoom_x_range);
299
- let [x2_min, x2_max] = $derived(zoom_x2_range);
300
- let [y_min, y_max] = $derived(zoom_y_range);
301
- let [y2_min, y2_max] = $derived(zoom_y2_range);
302
- // Create auto color range
303
- let auto_color_range = $derived(
304
- // Ensure we only calculate extent on actual numbers, filtering out nulls/undefined
305
- all_color_values.length > 0
306
- ? extent(all_color_values.filter((color_val) => typeof color_val === `number`))
307
- : [0, 1]);
308
- // Create scale functions
309
- // For time scales, use scaleTime directly; otherwise use create_scale (supports linear/log/arcsinh)
310
- let x_scale_fn = $derived(is_time_x
311
- ? scaleTime()
577
+ })
578
+
579
+ let [x_min, x_max] = $derived(zoom_x_range)
580
+ let [x2_min, x2_max] = $derived(zoom_x2_range)
581
+ let [y_min, y_max] = $derived(zoom_y_range)
582
+ let [y2_min, y2_max] = $derived(zoom_y2_range)
583
+
584
+ // Create auto color range
585
+ let auto_color_range = $derived(
586
+ // Ensure we only calculate extent on actual numbers, filtering out nulls/undefined
587
+ all_color_values.length > 0
588
+ ? extent(
589
+ all_color_values.filter((color_val: number | null): color_val is number =>
590
+ typeof color_val === `number`
591
+ ),
592
+ )
593
+ : [0, 1],
594
+ ) as Vec2
595
+
596
+ // Create scale functions
597
+ // For time scales, use scaleTime directly; otherwise use create_scale (supports linear/log/arcsinh)
598
+ let x_scale_fn = $derived(
599
+ is_time_x
600
+ ? scaleTime()
312
601
  .domain([new Date(x_min), new Date(x_max)])
313
602
  .range([pad.l, width - pad.r])
314
- : create_scale(final_x_axis.scale_type ?? `linear`, [x_min, x_max], [
603
+ : create_scale(final_x_axis.scale_type ?? `linear`, [x_min, x_max], [
315
604
  pad.l,
316
605
  width - pad.r,
317
- ]));
318
- let x2_scale_fn = $derived(is_time_x2
319
- ? scaleTime()
606
+ ]),
607
+ )
608
+
609
+ let x2_scale_fn = $derived(
610
+ is_time_x2
611
+ ? scaleTime()
320
612
  .domain([new Date(x2_min), new Date(x2_max)])
321
613
  .range([pad.l, width - pad.r])
322
- : create_scale(final_x2_axis.scale_type ?? `linear`, [x2_min, x2_max], [
614
+ : create_scale(final_x2_axis.scale_type ?? `linear`, [x2_min, x2_max], [
323
615
  pad.l,
324
616
  width - pad.r,
325
- ]));
326
- let y_scale_fn = $derived(create_scale(final_y_axis.scale_type ?? `linear`, [y_min, y_max], [
327
- height - pad.b,
328
- pad.t,
329
- ]));
330
- let y2_scale_fn = $derived(create_scale(final_y2_axis.scale_type ?? `linear`, [y2_min, y2_max], [
331
- height - pad.b,
332
- pad.t,
333
- ]));
334
- // All size values from series (for size scale) - extracted in series_value_arrays
335
- let all_size_values = $derived(series_value_arrays.size_values);
336
- // Size scale function (using shared utility)
337
- let size_scale_fn = $derived(create_size_scale(size_scale, all_size_values));
338
- // Color scale function (using shared utility)
339
- let color_scale_fn = $derived(create_color_scale(color_scale, auto_color_range));
340
- // Filter series data to only include points within bounds and augment with internal data
341
- let filtered_series = $derived(series_with_ids
342
- .map((data_series, series_idx) => {
343
- // Handle null/undefined series first
344
- if (!data_series) {
345
- return {
617
+ ]),
618
+ )
619
+
620
+ let y_scale_fn = $derived(
621
+ create_scale(final_y_axis.scale_type ?? `linear`, [y_min, y_max], [
622
+ height - pad.b,
623
+ pad.t,
624
+ ]),
625
+ )
626
+
627
+ let y2_scale_fn = $derived(
628
+ create_scale(final_y2_axis.scale_type ?? `linear`, [y2_min, y2_max], [
629
+ height - pad.b,
630
+ pad.t,
631
+ ]),
632
+ )
633
+
634
+ // All size values from series (for size scale) - extracted in series_value_arrays
635
+ let all_size_values = $derived(series_value_arrays.size_values)
636
+
637
+ // Size scale function (using shared utility)
638
+ let size_scale_fn = $derived(create_size_scale(size_scale, all_size_values))
639
+
640
+ // Color scale function (using shared utility)
641
+ let color_scale_fn = $derived(create_color_scale(color_scale, auto_color_range))
642
+
643
+ // Filter series data to only include points within bounds and augment with internal data
644
+ let filtered_series = $derived(
645
+ series_with_ids
646
+ .map((data_series: DataSeries<Metadata>, series_idx): DataSeries<Metadata> => {
647
+ // Handle null/undefined series first
648
+ if (!data_series) {
649
+ return {
346
650
  x: [],
347
651
  y: [],
348
652
  visible: true,
349
653
  filtered_data: [],
350
654
  _id: series_idx,
351
655
  orig_series_idx: series_idx,
352
- };
353
- }
354
- // Handle explicitly hidden series
355
- if (!(data_series.visible ?? true)) {
356
- return {
656
+ }
657
+ }
658
+
659
+ // Handle explicitly hidden series
660
+ if (!(data_series.visible ?? true)) {
661
+ return {
357
662
  ...data_series,
358
663
  visible: false,
359
664
  filtered_data: [],
360
665
  orig_series_idx: series_idx,
361
- };
362
- }
363
- const { x: xs, y: ys, color_values, size_values, ...rest } = data_series;
364
- // Process points internally, adding properties beyond the base Point type
365
- const processed_points = xs.map((x_val, point_idx) => ({
366
- x: x_val,
367
- y: ys[point_idx],
368
- color_value: color_values?.[point_idx],
369
- metadata: process_prop(rest.metadata, point_idx),
370
- point_style: process_prop(rest.point_style, point_idx),
371
- point_hover: process_prop(rest.point_hover, point_idx),
372
- point_label: process_prop(rest.point_label, point_idx),
373
- point_offset: process_prop(rest.point_offset, point_idx),
374
- series_idx,
375
- point_idx,
376
- size_value: size_values?.[point_idx],
377
- }));
378
- // Filter to points within the plot bounds (handles inverted ranges like [3.5, 1.4])
379
- const in_range = (val, lo, hi) => val != null && !isNaN(val) && val >= Math.min(lo, hi) &&
380
- val <= Math.max(lo, hi);
381
- // Determine which ranges to use based on series axis properties
382
- const [series_x_min, series_x_max] = (data_series.x_axis ?? `x1`) === `x2`
383
- ? [x2_min, x2_max]
384
- : [x_min, x_max];
385
- const [series_y_min, series_y_max] = (data_series.y_axis ?? `y1`) === `y2`
386
- ? [y2_min, y2_max]
387
- : [y_min, y_max];
388
- const filtered_data_with_extras = processed_points.filter(({ x, y }) => in_range(x, series_x_min, series_x_max) &&
389
- in_range(y, series_y_min, series_y_max));
390
- // Return structure consistent with DataSeries but acknowledge internal data structure (filtered_data)
391
- return {
392
- ...data_series,
393
- visible: true, // Mark series as visible here
394
- filtered_data: filtered_data_with_extras,
395
- orig_series_idx: series_idx, // Store original index for auto-cycling colors/symbols
396
- };
397
- })
398
- // Filter series end up completely empty after point filtering
399
- .filter((srs) => !!srs.filtered_data && srs.filtered_data.length > 0));
400
- // Collect all plot points for legend placement calculation
401
- let plot_points_for_placement = $derived.by(() => {
402
- if (!width || !height || !filtered_series)
403
- return [];
404
- const points = [];
666
+ }
667
+ }
668
+
669
+ const { x: xs, y: ys, color_values, size_values, ...rest } = data_series
670
+
671
+ // Process points internally, adding properties beyond the base Point type
672
+ const processed_points: InternalPoint<Metadata>[] = xs.map(
673
+ (x_val: number, point_idx: number) => ({
674
+ x: x_val,
675
+ y: ys[point_idx],
676
+ color_value: color_values?.[point_idx],
677
+ metadata: process_prop(rest.metadata, point_idx) as Metadata | undefined,
678
+ point_style: process_prop(rest.point_style, point_idx),
679
+ point_hover: process_prop(rest.point_hover, point_idx),
680
+ point_label: process_prop(rest.point_label, point_idx),
681
+ point_offset: process_prop(rest.point_offset, point_idx),
682
+ series_idx,
683
+ point_idx,
684
+ size_value: size_values?.[point_idx],
685
+ }),
686
+ )
687
+
688
+ // Filter to points within the plot bounds (handles inverted ranges like [3.5, 1.4])
689
+ const in_range = (val: number | null | undefined, lo: number, hi: number) =>
690
+ val != null && !isNaN(val) && val >= Math.min(lo, hi) &&
691
+ val <= Math.max(lo, hi)
692
+
693
+ // Determine which ranges to use based on series axis properties
694
+ const [series_x_min, series_x_max] = (data_series.x_axis ?? `x1`) === `x2`
695
+ ? [x2_min, x2_max]
696
+ : [x_min, x_max]
697
+ const [series_y_min, series_y_max] = (data_series.y_axis ?? `y1`) === `y2`
698
+ ? [y2_min, y2_max]
699
+ : [y_min, y_max]
700
+
701
+ const filtered_data_with_extras = processed_points.filter(
702
+ ({ x, y }) =>
703
+ in_range(x, series_x_min, series_x_max) &&
704
+ in_range(y, series_y_min, series_y_max),
705
+ )
706
+
707
+ // Return structure consistent with DataSeries but acknowledge internal data structure (filtered_data)
708
+ return {
709
+ ...data_series,
710
+ visible: true, // Mark series as visible here
711
+ filtered_data: filtered_data_with_extras,
712
+ orig_series_idx: series_idx, // Store original index for auto-cycling colors/symbols
713
+ }
714
+ })
715
+ // Filter series end up completely empty after point filtering
716
+ .filter((
717
+ srs,
718
+ ): srs is DataSeries<Metadata> & { filtered_data: InternalPoint<Metadata>[] } =>
719
+ !!srs.filtered_data && srs.filtered_data.length > 0
720
+ ),
721
+ )
722
+
723
+ // Collect all plot points for legend placement calculation
724
+ let plot_points_for_placement = $derived.by(() => {
725
+ if (!width || !height || !filtered_series) return []
726
+
727
+ const points: { x: number; y: number }[] = []
728
+
405
729
  for (const series_data of filtered_series) {
406
- if (!series_data?.filtered_data)
407
- continue;
408
- const use_x2_scale = series_data.x_axis === `x2`;
409
- for (const point of series_data.filtered_data) {
410
- const active_x_scale = use_x2_scale ? x2_scale_fn : x_scale_fn;
411
- const active_is_time_x = use_x2_scale ? is_time_x2 : is_time_x;
412
- const point_x_coord = active_is_time_x
413
- ? active_x_scale(new Date(point.x))
414
- : active_x_scale(point.x);
415
- const point_y_coord = (series_data.y_axis === `y2` ? y2_scale_fn : y_scale_fn)(point.y);
416
- if (isFinite(point_x_coord) && isFinite(point_y_coord)) {
417
- points.push({ x: point_x_coord, y: point_y_coord });
418
- }
730
+ if (!series_data?.filtered_data) continue
731
+ const use_x2_scale = series_data.x_axis === `x2`
732
+ for (const point of series_data.filtered_data) {
733
+ const active_x_scale = use_x2_scale ? x2_scale_fn : x_scale_fn
734
+ const active_is_time_x = use_x2_scale ? is_time_x2 : is_time_x
735
+ const point_x_coord = active_is_time_x
736
+ ? active_x_scale(new Date(point.x))
737
+ : active_x_scale(point.x)
738
+ const point_y_coord =
739
+ (series_data.y_axis === `y2` ? y2_scale_fn : y_scale_fn)(
740
+ point.y,
741
+ )
742
+
743
+ if (isFinite(point_x_coord) && isFinite(point_y_coord)) {
744
+ points.push({ x: point_x_coord, y: point_y_coord })
419
745
  }
746
+ }
420
747
  }
421
- return points;
422
- });
423
- let computed_fills = $derived.by(() => {
748
+ return points
749
+ })
750
+
751
+ // Explicitly define the type for display_style matching PlotLegend expectations
752
+ type LegendDisplayStyle = {
753
+ symbol_type?: D3SymbolName
754
+ symbol_color?: string
755
+ line_color?: string
756
+ line_dash?: string
757
+ }
758
+
759
+ // Computed fill regions: merge fill_regions and converted error_bands, resolve boundaries
760
+ type ComputedFill = FillRegion & {
761
+ idx: number
762
+ source_type: `fill_region` | `error_band`
763
+ source_idx: number
764
+ path_segments: string[]
765
+ }
766
+ let computed_fills = $derived.by((): ComputedFill[] => {
424
767
  // Early exit: skip expensive computation if no fills to render
425
- const has_fill_regions = fill_regions && fill_regions.length > 0;
426
- const has_error_bands = error_bands && error_bands.length > 0;
427
- if (!has_fill_regions && !has_error_bands)
428
- return [];
768
+ const has_fill_regions = fill_regions && fill_regions.length > 0
769
+ const has_error_bands = error_bands && error_bands.length > 0
770
+ if (!has_fill_regions && !has_error_bands) return []
771
+
429
772
  // Merge fill_regions and converted error_bands, tracking source
430
- const all_regions = [
431
- ...(fill_regions ?? []).map((region, source_idx) => ({
432
- region,
433
- source_type: `fill_region`,
434
- source_idx,
435
- })),
436
- ...(error_bands ?? []).map((band, source_idx) => ({
437
- region: convert_error_band_to_fill_region(band, series_with_ids),
438
- source_type: `error_band`,
439
- source_idx,
440
- })),
441
- ];
773
+ const all_regions: {
774
+ region: FillRegion | null
775
+ source_type: `fill_region` | `error_band`
776
+ source_idx: number
777
+ }[] = [
778
+ ...(fill_regions ?? []).map((region, source_idx) => ({
779
+ region,
780
+ source_type: `fill_region` as const,
781
+ source_idx,
782
+ })),
783
+ ...(error_bands ?? []).map((band, source_idx) => ({
784
+ region: convert_error_band_to_fill_region(band, series_with_ids),
785
+ source_type: `error_band` as const,
786
+ source_idx,
787
+ })),
788
+ ]
789
+
442
790
  // Compute unique x-values once for all fills
443
791
  // Optimization: deduplicate first (O(n)), then sort only unique values (O(k log k))
444
792
  // This is faster for datasets with many duplicate x-values across series
445
- const x_set = new SvelteSet();
793
+ const x_set = new SvelteSet<number>()
446
794
  for (const data_series of series_with_ids) {
447
- if (!data_series)
448
- continue;
449
- for (const val of data_series.x) {
450
- if (typeof val === `number` && isFinite(val))
451
- x_set.add(val);
452
- }
795
+ if (!data_series) continue
796
+ for (const val of data_series.x) {
797
+ if (typeof val === `number` && isFinite(val)) x_set.add(val)
798
+ }
453
799
  }
454
- const unique_x = [...x_set].sort((val_a, val_b) => val_a - val_b);
455
- if (unique_x.length === 0)
456
- return [];
800
+ const unique_x = [...x_set].sort((val_a, val_b) => val_a - val_b)
801
+
802
+ if (unique_x.length === 0) return []
803
+
457
804
  return all_regions
458
- .filter((entry) => entry.region !== null)
459
- .map(({ region, source_type, source_idx }, idx) => {
460
- if (region.visible === false)
461
- return null;
805
+ .filter((
806
+ entry,
807
+ ): entry is {
808
+ region: FillRegion
809
+ source_type: `fill_region` | `error_band`
810
+ source_idx: number
811
+ } => entry.region !== null)
812
+ .map(({ region, source_type, source_idx }, idx) => {
813
+ if (region.visible === false) return null
814
+
462
815
  // Domain context for boundary resolution
463
816
  const domains = {
464
- y_domain: [y_min, y_max],
465
- y2_domain: [y2_min, y2_max],
466
- };
817
+ y_domain: [y_min, y_max] as Vec2,
818
+ y2_domain: [y2_min, y2_max] as Vec2,
819
+ }
820
+
467
821
  // Resolve upper and lower boundaries
468
- const upper_values = resolve_boundary(region.upper, series_with_ids, unique_x, domains);
469
- const lower_values = resolve_boundary(region.lower, series_with_ids, unique_x, domains);
470
- if (!upper_values || !lower_values)
471
- return null;
822
+ const upper_values = resolve_boundary(
823
+ region.upper,
824
+ series_with_ids,
825
+ unique_x,
826
+ domains,
827
+ )
828
+ const lower_values = resolve_boundary(
829
+ region.lower,
830
+ series_with_ids,
831
+ unique_x,
832
+ domains,
833
+ )
834
+
835
+ if (!upper_values || !lower_values) return null
836
+
472
837
  // Apply range constraints
473
- const range_filtered = apply_range_constraints(unique_x, lower_values, upper_values, region);
838
+ const range_filtered = apply_range_constraints(
839
+ unique_x,
840
+ lower_values,
841
+ upper_values,
842
+ region,
843
+ )
844
+
474
845
  // Clamp for log scale if needed
475
- const y_scale_type = final_y_axis.scale_type ?? `linear`;
476
- const x_scale_type = final_x_axis.scale_type ?? `linear`;
477
- const clamped = clamp_for_log_scale(range_filtered.x, range_filtered.y1, range_filtered.y2, y_scale_type, x_scale_type);
846
+ const y_scale_type = final_y_axis.scale_type ?? `linear`
847
+ const x_scale_type = final_x_axis.scale_type ?? `linear`
848
+ const clamped = clamp_for_log_scale(
849
+ range_filtered.x,
850
+ range_filtered.y1,
851
+ range_filtered.y2,
852
+ y_scale_type,
853
+ x_scale_type,
854
+ )
855
+
478
856
  // Apply where condition (splits into segments)
479
- const conditioned = apply_where_condition(clamped.x, clamped.y1, clamped.y2, region);
857
+ const conditioned = apply_where_condition(
858
+ clamped.x,
859
+ clamped.y1,
860
+ clamped.y2,
861
+ region,
862
+ )
863
+
480
864
  // Generate paths for each segment (convert to pixel coordinates)
481
865
  const path_segments = conditioned.segments
482
- .filter((segment) => segment.length > 1)
483
- .map((segment) => {
484
- const pixel_data = segment.map((point) => ({
485
- x: x_scale_fn(point.x),
486
- y1: y_scale_fn(point.y1),
487
- y2: y_scale_fn(point.y2),
488
- }));
489
- return generate_fill_path(pixel_data, region.curve ?? `monotoneX`);
490
- })
491
- .filter((path) => path.length > 0);
492
- if (path_segments.length === 0)
493
- return null;
494
- return { ...region, idx, source_type, source_idx, path_segments };
495
- })
496
- .filter((fill) => fill !== null);
497
- });
498
- // Prepare data needed for the legend component
499
- let legend_data = $derived.by(() => {
500
- const items = series_with_ids.map((data_series, series_idx) => {
501
- const is_visible = data_series?.visible ?? true;
866
+ .filter((segment) => segment.length > 1)
867
+ .map((segment) => {
868
+ const pixel_data: FillPathPoint[] = segment.map((point) => ({
869
+ x: x_scale_fn(point.x),
870
+ y1: y_scale_fn(point.y1),
871
+ y2: y_scale_fn(point.y2),
872
+ }))
873
+ return generate_fill_path(pixel_data, region.curve ?? `monotoneX`)
874
+ })
875
+ .filter((path) => path.length > 0)
876
+
877
+ if (path_segments.length === 0) return null
878
+
879
+ return { ...region, idx, source_type, source_idx, path_segments }
880
+ })
881
+ .filter((fill): fill is ComputedFill => fill !== null)
882
+ })
883
+
884
+ // Prepare data needed for the legend component
885
+ let legend_data = $derived.by(() => {
886
+ const items = series_with_ids.map(
887
+ (data_series: DataSeries & { _id?: string | number }, series_idx: number) => {
888
+ const is_visible = data_series?.visible ?? true
502
889
  // Prefer top-level label, fallback to metadata label
503
890
  const explicit_label = data_series?.label ??
504
- (typeof data_series?.metadata === `object` &&
505
- data_series.metadata !== null &&
506
- `label` in data_series.metadata &&
507
- typeof data_series.metadata.label === `string`
508
- ? data_series.metadata.label
509
- : null);
891
+ (typeof data_series?.metadata === `object` &&
892
+ data_series.metadata !== null &&
893
+ `label` in data_series.metadata &&
894
+ typeof data_series.metadata.label === `string`
895
+ ? data_series.metadata.label
896
+ : null)
510
897
  // Use explicit label or generate default
511
- const label = explicit_label ?? `Series ${series_idx + 1}`;
512
- const has_explicit_label = explicit_label != null;
898
+ const label = explicit_label ?? `Series ${series_idx + 1}`
899
+ const has_explicit_label = explicit_label != null
900
+
513
901
  // Use series-specific defaults for auto-differentiation
514
- const series_default_color = get_series_color(series_idx);
515
- const series_default_symbol = get_series_symbol(series_idx);
516
- const display_style = {
517
- symbol_type: series_default_symbol,
518
- symbol_color: series_default_color,
519
- line_color: series_default_color,
520
- };
521
- const series_markers = data_series?.markers ?? DEFAULT_MARKERS;
902
+ const series_default_color = get_series_color(series_idx)
903
+ const series_default_symbol = get_series_symbol(series_idx)
904
+
905
+ const display_style: LegendDisplayStyle = {
906
+ symbol_type: series_default_symbol,
907
+ symbol_color: series_default_color,
908
+ line_color: series_default_color,
909
+ }
910
+ const series_markers = data_series?.markers ?? DEFAULT_MARKERS
911
+
522
912
  // Check point_style (could be object or array)
523
913
  const first_point_style = Array.isArray(data_series?.point_style)
524
- ? data_series.point_style[0]
525
- : data_series?.point_style;
914
+ ? data_series.point_style[0]
915
+ : data_series?.point_style
916
+
526
917
  if (series_markers?.includes(`points`)) {
527
- if (first_point_style) {
528
- // Use explicit symbol_type if provided and valid, otherwise keep series default
529
- if (typeof first_point_style.symbol_type === `string` &&
530
- symbol_names.includes(first_point_style.symbol_type)) {
531
- display_style.symbol_type = first_point_style
532
- .symbol_type;
533
- }
534
- // Use explicit fill color if provided
535
- if (first_point_style.fill) {
536
- display_style.symbol_color = first_point_style.fill;
537
- }
538
- if (first_point_style.stroke) {
539
- // Use stroke color if fill is none or transparent
540
- if (!display_style.symbol_color ||
541
- display_style.symbol_color === `none` ||
542
- display_style.symbol_color.startsWith(`rgba(`, 0) // Check if transparent
543
- )
544
- display_style.symbol_color = first_point_style.stroke;
545
- }
918
+ if (first_point_style) {
919
+ // Use explicit symbol_type if provided and valid, otherwise keep series default
920
+ if (
921
+ typeof first_point_style.symbol_type === `string` &&
922
+ symbol_names.includes(first_point_style.symbol_type as D3SymbolName)
923
+ ) {
924
+ display_style.symbol_type = first_point_style
925
+ .symbol_type as D3SymbolName
546
926
  }
547
- // else: keep series-specific defaults for symbol_type and symbol_color
548
- }
549
- else {
550
- // If no points marker, explicitly remove marker style for legend
551
- display_style.symbol_type = undefined;
552
- display_style.symbol_color = undefined;
927
+
928
+ // Use explicit fill color if provided
929
+ if (first_point_style.fill) {
930
+ display_style.symbol_color = first_point_style.fill
931
+ }
932
+ if (first_point_style.stroke) {
933
+ // Use stroke color if fill is none or transparent
934
+ if (
935
+ !display_style.symbol_color ||
936
+ display_style.symbol_color === `none` ||
937
+ display_style.symbol_color.startsWith(`rgba(`, 0) // Check if transparent
938
+ ) display_style.symbol_color = first_point_style.stroke
939
+ }
940
+ }
941
+ // else: keep series-specific defaults for symbol_type and symbol_color
942
+ } else {
943
+ // If no points marker, explicitly remove marker style for legend
944
+ display_style.symbol_type = undefined
945
+ display_style.symbol_color = undefined
553
946
  }
947
+
554
948
  // Check line_style
555
949
  if (series_markers?.includes(`line`)) {
556
- // Prefer explicit line stroke, then other explicit colors, then series default
557
- let legend_line_color = data_series?.line_style?.stroke;
558
- if (!legend_line_color) {
559
- // Try color scale if available
560
- const first_cv = Array.isArray(data_series?.color_values)
561
- ? data_series.color_values.find((color_val) => color_val != null)
562
- : undefined;
563
- legend_line_color =
564
- (first_cv != null ? color_scale_fn(first_cv) : undefined) ||
565
- first_point_style?.fill ||
566
- first_point_style?.stroke ||
567
- series_default_color;
568
- }
569
- display_style.line_color = legend_line_color;
570
- display_style.line_dash = data_series?.line_style?.line_dash;
571
- }
572
- else {
573
- // If no line marker, explicitly remove line style for legend
574
- display_style.line_dash = undefined;
575
- display_style.line_color = undefined;
950
+ // Prefer explicit line stroke, then other explicit colors, then series default
951
+ let legend_line_color = data_series?.line_style?.stroke
952
+ if (!legend_line_color) {
953
+ // Try color scale if available
954
+ const first_cv = Array.isArray(data_series?.color_values)
955
+ ? data_series?.color_values?.find((color_val: number | null) =>
956
+ color_val != null
957
+ )
958
+ : undefined
959
+ legend_line_color =
960
+ (first_cv != null ? color_scale_fn(first_cv) : undefined) ||
961
+ first_point_style?.fill ||
962
+ first_point_style?.stroke ||
963
+ series_default_color
964
+ }
965
+ display_style.line_color = legend_line_color
966
+ display_style.line_dash = data_series?.line_style?.line_dash
967
+ } else {
968
+ // If no line marker, explicitly remove line style for legend
969
+ display_style.line_dash = undefined
970
+ display_style.line_color = undefined
576
971
  }
972
+
577
973
  return {
578
- series_idx,
579
- label,
580
- visible: is_visible,
581
- display_style,
582
- has_explicit_label,
583
- legend_group: data_series?.legend_group,
584
- };
585
- });
974
+ series_idx,
975
+ label,
976
+ visible: is_visible,
977
+ display_style,
978
+ has_explicit_label,
979
+ legend_group: data_series?.legend_group,
980
+ }
981
+ },
982
+ )
983
+
586
984
  // Deduplicate by label+legend_group - keep first occurrence of each unique combination
587
- const seen_labels = new SvelteSet();
588
- const series_items = items.filter((legend_item) => {
985
+ const seen_labels = new SvelteSet<string>()
986
+ const series_items = items.filter(
987
+ (
988
+ legend_item: {
989
+ label: string
990
+ series_idx: number
991
+ visible: boolean
992
+ display_style: LegendDisplayStyle
993
+ has_explicit_label: boolean
994
+ legend_group?: string
995
+ },
996
+ ) => {
589
997
  // Use label+group as unique key (group may be undefined)
590
- const unique_key = `${legend_item.legend_group ?? ``}::${legend_item.label}`;
591
- if (seen_labels.has(unique_key))
592
- return false;
593
- seen_labels.add(unique_key);
594
- return true;
595
- });
998
+ const unique_key = `${legend_item.legend_group ?? ``}::${legend_item.label}`
999
+ if (seen_labels.has(unique_key)) return false
1000
+ seen_labels.add(unique_key)
1001
+ return true
1002
+ },
1003
+ )
1004
+
596
1005
  // Add fill region items to legend (deduplicated using same key format as series)
597
1006
  const fill_items = computed_fills
598
- .filter((fill) => fill.show_in_legend !== false && fill.label)
599
- .filter((fill) => {
1007
+ .filter((fill) => fill.show_in_legend !== false && fill.label)
1008
+ .filter((fill) => {
600
1009
  // Use same composite key as series: legend_group::label
601
- const unique_key = `${fill.legend_group ?? ``}::${fill.label}`;
602
- if (seen_labels.has(unique_key))
603
- return false;
604
- seen_labels.add(unique_key);
605
- return true;
606
- })
607
- .map((fill) => {
1010
+ const unique_key = `${fill.legend_group ?? ``}::${fill.label ?? ``}`
1011
+ if (seen_labels.has(unique_key)) return false
1012
+ seen_labels.add(unique_key)
1013
+ return true
1014
+ })
1015
+ .map((fill) => {
608
1016
  // Pass gradient for swatch rendering, or solid color as fallback
609
- const fill_gradient = is_fill_gradient(fill.fill) ? fill.fill : undefined;
610
- const fill_color = typeof fill.fill === `string` ? fill.fill : undefined;
1017
+ const fill_gradient = is_fill_gradient(fill.fill) ? fill.fill : undefined
1018
+ const fill_color = typeof fill.fill === `string` ? fill.fill : undefined
1019
+
611
1020
  return {
612
- series_idx: -1, // Not a series
613
- fill_idx: fill.idx,
614
- fill_source_type: fill.source_type,
615
- fill_source_idx: fill.source_idx,
616
- item_type: `fill`,
617
- label: fill.label,
618
- visible: fill.visible !== false,
619
- legend_group: fill.legend_group,
620
- display_style: {
621
- fill_color,
622
- fill_opacity: fill.fill_opacity ?? 0.3,
623
- edge_color: fill.edge_upper?.color,
624
- fill_gradient,
625
- },
626
- };
627
- });
628
- return [...series_items, ...fill_items];
629
- });
630
- // Group fills by z-index for ordered rendering (single pass instead of 4 filters)
631
- let fills_by_z = $derived.by(() => {
632
- const groups = { below_grid: [], below_lines: [], below_points: [], above_all: [] };
1021
+ series_idx: -1, // Not a series
1022
+ fill_idx: fill.idx,
1023
+ fill_source_type: fill.source_type,
1024
+ fill_source_idx: fill.source_idx,
1025
+ item_type: `fill` as const,
1026
+ label: fill.label ?? ``,
1027
+ visible: fill.visible !== false,
1028
+ legend_group: fill.legend_group,
1029
+ display_style: {
1030
+ fill_color,
1031
+ fill_opacity: fill.fill_opacity ?? 0.3,
1032
+ edge_color: fill.edge_upper?.color,
1033
+ fill_gradient,
1034
+ },
1035
+ }
1036
+ })
1037
+
1038
+ return [...series_items, ...fill_items]
1039
+ })
1040
+
1041
+ // Group fills by z-index for ordered rendering (single pass instead of 4 filters)
1042
+ let fills_by_z = $derived.by(() => {
1043
+ const groups: {
1044
+ below_grid: typeof computed_fills
1045
+ below_lines: typeof computed_fills
1046
+ below_points: typeof computed_fills
1047
+ above_all: typeof computed_fills
1048
+ } = { below_grid: [], below_lines: [], below_points: [], above_all: [] }
1049
+
633
1050
  for (const fill of computed_fills) {
634
- if (fill.z_index === `below-grid`)
635
- groups.below_grid.push(fill);
636
- else if (fill.z_index === `below-points`)
637
- groups.below_points.push(fill);
638
- else if (fill.z_index === `above-all`)
639
- groups.above_all.push(fill);
640
- else
641
- groups.below_lines.push(fill); // default: no z_index or 'below-lines'
1051
+ if (fill.z_index === `below-grid`) groups.below_grid.push(fill)
1052
+ else if (fill.z_index === `below-points`) groups.below_points.push(fill)
1053
+ else if (fill.z_index === `above-all`) groups.above_all.push(fill)
1054
+ else groups.below_lines.push(fill) // default: no z_index or 'below-lines'
642
1055
  }
643
- return groups;
644
- });
645
- // Compute ref_lines with index and group by z-index (using shared utilities)
646
- let indexed_ref_lines = $derived(index_ref_lines(ref_lines));
647
- let ref_lines_by_z = $derived(group_ref_lines_by_z(indexed_ref_lines));
648
- // Calculate best legend placement using continuous grid sampling
649
- let legend_placement = $derived.by(() => {
1056
+ return groups
1057
+ })
1058
+
1059
+ // Compute ref_lines with index and group by z-index (using shared utilities)
1060
+ let indexed_ref_lines = $derived(index_ref_lines(ref_lines))
1061
+ let ref_lines_by_z = $derived(group_ref_lines_by_z(indexed_ref_lines))
1062
+
1063
+ // Calculate best legend placement using continuous grid sampling
1064
+ let legend_placement = $derived.by(() => {
650
1065
  const should_place = legend != null &&
651
- (legend_data.length > 1 || Object.keys(legend).length > 0);
652
- if (!should_place || !width || !height)
653
- return null;
654
- const plot_width = width - pad.l - pad.r;
655
- const plot_height = height - pad.t - pad.b;
1066
+ (legend_data.length > 1 || Object.keys(legend).length > 0)
1067
+
1068
+ if (!should_place || !width || !height) return null
1069
+
1070
+ const plot_width = width - pad.l - pad.r
1071
+ const plot_height = height - pad.t - pad.b
1072
+
656
1073
  // Use measured size if available, otherwise estimate
657
1074
  const legend_size = legend_element
658
- ? { width: legend_element.offsetWidth, height: legend_element.offsetHeight }
659
- : { width: 120, height: 80 };
1075
+ ? { width: legend_element.offsetWidth, height: legend_element.offsetHeight }
1076
+ : { width: 120, height: 80 }
1077
+
660
1078
  const placement_config = {
661
- plot_bounds: { x: pad.l, y: pad.t, width: plot_width, height: plot_height },
662
- element_size: legend_size,
663
- axis_clearance: legend?.axis_clearance,
664
- exclude_rects: [],
665
- points: plot_points_for_placement,
666
- };
667
- return compute_element_placement(placement_config);
668
- });
669
- // Calculate color bar placement (coordinates with legend to avoid overlap)
670
- let color_bar_placement = $derived.by(() => {
671
- if (!color_bar || !all_color_values.length || !width || !height)
672
- return null;
673
- const plot_width = width - pad.l - pad.r;
674
- const plot_height = height - pad.t - pad.b;
1079
+ plot_bounds: { x: pad.l, y: pad.t, width: plot_width, height: plot_height },
1080
+ element_size: legend_size,
1081
+ axis_clearance: legend?.axis_clearance,
1082
+ exclude_rects: [],
1083
+ points: plot_points_for_placement,
1084
+ }
1085
+
1086
+ return compute_element_placement(placement_config)
1087
+ })
1088
+
1089
+ // Calculate color bar placement (coordinates with legend to avoid overlap)
1090
+ let color_bar_placement = $derived.by(() => {
1091
+ if (!color_bar || !all_color_values.length || !width || !height) return null
1092
+
1093
+ const plot_width = width - pad.l - pad.r
1094
+ const plot_height = height - pad.t - pad.b
1095
+
675
1096
  // Use measured size if available, otherwise estimate based on orientation
676
- const is_horizontal = color_bar.orientation === `horizontal`;
1097
+ const is_horizontal = color_bar.orientation === `horizontal`
677
1098
  const colorbar_size = colorbar_element
678
- ? { width: colorbar_element.offsetWidth, height: colorbar_element.offsetHeight }
679
- : is_horizontal
680
- ? { width: 220, height: 40 }
681
- : { width: 40, height: 100 };
1099
+ ? { width: colorbar_element.offsetWidth, height: colorbar_element.offsetHeight }
1100
+ : is_horizontal
1101
+ ? { width: 220, height: 40 }
1102
+ : { width: 40, height: 100 }
1103
+
682
1104
  // Build exclusion rects (avoid legend if it's placed)
683
- const exclude_rects = [];
1105
+ const exclude_rects: Rect[] = []
684
1106
  if (legend_element && legend_placement) {
685
- exclude_rects.push({
686
- x: legend_placement.x,
687
- y: legend_placement.y,
688
- width: legend_element.offsetWidth || 120,
689
- height: legend_element.offsetHeight || 80,
690
- });
1107
+ exclude_rects.push({
1108
+ x: legend_placement.x,
1109
+ y: legend_placement.y,
1110
+ width: legend_element.offsetWidth || 120,
1111
+ height: legend_element.offsetHeight || 80,
1112
+ })
691
1113
  }
1114
+
692
1115
  return compute_element_placement({
693
- plot_bounds: { x: pad.l, y: pad.t, width: plot_width, height: plot_height },
694
- element_size: colorbar_size,
695
- // Colorbar needs slightly more clearance than legend to avoid axis labels
696
- axis_clearance: 15,
697
- exclude_rects,
698
- points: plot_points_for_placement,
699
- });
700
- });
701
- // Active legend placement (null if user set explicit position)
702
- let active_legend_placement = $derived.by(() => {
703
- if (!legend_placement)
704
- return null;
1116
+ plot_bounds: { x: pad.l, y: pad.t, width: plot_width, height: plot_height },
1117
+ element_size: colorbar_size,
1118
+ // Colorbar needs slightly more clearance than legend to avoid axis labels
1119
+ axis_clearance: 15,
1120
+ exclude_rects,
1121
+ points: plot_points_for_placement,
1122
+ })
1123
+ })
1124
+
1125
+ // Active legend placement (null if user set explicit position)
1126
+ let active_legend_placement = $derived.by(() => {
1127
+ if (!legend_placement) return null
1128
+
705
1129
  // Skip auto-placement if user set explicit position in style
706
- const legend_style = legend?.style ?? ``;
707
- if (/(^|[;{]\s*)(top|bottom|left|right)\s*:|position\s*:\s*absolute/.test(legend_style))
708
- return null;
709
- return legend_placement;
710
- });
711
- // Initialize tweened values for color bar position - create once, update target via effect
712
- // untrack() explicitly captures initial tween config (intentional - config set once at mount)
713
- const tweened_colorbar_coords = new Tween({ x: 0, y: 0 }, untrack(() => ({ duration: 400, ...(color_bar?.tween ?? {}) })));
714
- // Initialize tweened values for legend position - create once, update target via effect
715
- const tweened_legend_coords = new Tween({ x: 0, y: 0 }, untrack(() => ({ duration: 400, ...(legend?.tween ?? {}) })));
716
- // Update placement positions (with animation and stability checks)
717
- $effect(() => {
718
- if (!width || !height)
719
- return;
1130
+ const legend_style = legend?.style ?? ``
1131
+ if (
1132
+ /(^|[;{]\s*)(top|bottom|left|right)\s*:|position\s*:\s*absolute/.test(
1133
+ legend_style,
1134
+ )
1135
+ ) return null
1136
+
1137
+ return legend_placement
1138
+ })
1139
+
1140
+ // Initialize tweened values for color bar position - create once, update target via effect
1141
+ // untrack() explicitly captures initial tween config (intentional - config set once at mount)
1142
+ const tweened_colorbar_coords = new Tween(
1143
+ { x: 0, y: 0 },
1144
+ untrack(() => ({ duration: 400, ...(color_bar?.tween ?? {}) })),
1145
+ )
1146
+ // Initialize tweened values for legend position - create once, update target via effect
1147
+ const tweened_legend_coords = new Tween(
1148
+ { x: 0, y: 0 },
1149
+ untrack(() => ({ duration: 400, ...(legend?.tween ?? {}) })),
1150
+ )
1151
+
1152
+ // Update placement positions (with animation and stability checks)
1153
+ $effect(() => {
1154
+ if (!width || !height) return
1155
+
720
1156
  // Track dimensions for resize detection
721
- const dims_changed = dim_tracker.has_changed(width, height);
722
- if (dims_changed)
723
- dim_tracker.update(width, height);
1157
+ const dims_changed = dim_tracker.has_changed(width, height)
1158
+ if (dims_changed) dim_tracker.update(width, height)
1159
+
724
1160
  // Update colorbar position (stable after initial placement unless responsive)
725
1161
  if (color_bar_placement) {
726
- const is_responsive = color_bar?.responsive ?? false;
727
- const should_update = dims_changed || (!colorbar_hover.is_locked.current &&
728
- (is_responsive || !has_initial_colorbar_placement));
729
- if (should_update) {
730
- tweened_colorbar_coords.set({ x: color_bar_placement.x, y: color_bar_placement.y }, has_initial_colorbar_placement ? undefined : { duration: 0 });
731
- if (colorbar_element && !has_initial_colorbar_placement) {
732
- has_initial_colorbar_placement = true;
733
- }
1162
+ const is_responsive = color_bar?.responsive ?? false
1163
+ const should_update = dims_changed || (!colorbar_hover.is_locked.current &&
1164
+ (is_responsive || !has_initial_colorbar_placement))
1165
+
1166
+ if (should_update) {
1167
+ tweened_colorbar_coords.set(
1168
+ { x: color_bar_placement.x, y: color_bar_placement.y },
1169
+ has_initial_colorbar_placement ? undefined : { duration: 0 },
1170
+ )
1171
+ if (colorbar_element && !has_initial_colorbar_placement) {
1172
+ has_initial_colorbar_placement = true
734
1173
  }
1174
+ }
735
1175
  }
1176
+
736
1177
  // Update legend position (stable after initial placement unless responsive)
737
1178
  if (legend_manual_position && !legend_is_dragging) {
738
- // Immediate update (no animation) for manually dragged positions
739
- tweened_legend_coords.set(legend_manual_position, { duration: 0 });
740
- }
741
- else if (active_legend_placement && !legend_is_dragging) {
742
- const is_responsive = legend?.responsive ?? false;
743
- const should_update = dims_changed || (!legend_hover.is_locked.current &&
744
- (is_responsive || !has_initial_legend_placement));
745
- if (should_update) {
746
- tweened_legend_coords.set({ x: active_legend_placement.x, y: active_legend_placement.y }, has_initial_legend_placement ? undefined : { duration: 0 });
747
- if (legend_element)
748
- has_initial_legend_placement = true;
749
- }
1179
+ // Immediate update (no animation) for manually dragged positions
1180
+ tweened_legend_coords.set(legend_manual_position, { duration: 0 })
1181
+ } else if (active_legend_placement && !legend_is_dragging) {
1182
+ const is_responsive = legend?.responsive ?? false
1183
+ const should_update = dims_changed || (!legend_hover.is_locked.current &&
1184
+ (is_responsive || !has_initial_legend_placement))
1185
+
1186
+ if (should_update) {
1187
+ tweened_legend_coords.set(
1188
+ { x: active_legend_placement.x, y: active_legend_placement.y },
1189
+ has_initial_legend_placement ? undefined : { duration: 0 },
1190
+ )
1191
+ if (legend_element) has_initial_legend_placement = true
1192
+ }
750
1193
  }
751
- });
752
- // Generate axis ticks - consolidated into single derived for efficiency
753
- let axis_ticks = $derived.by(() => {
754
- if (!width || !height)
755
- return { x: [], x2: [], y: [], y2: [] };
1194
+ })
1195
+
1196
+ // Generate axis ticks - consolidated into single derived for efficiency
1197
+ let axis_ticks = $derived.by(() => {
1198
+ if (!width || !height) return { x: [], x2: [], y: [], y2: [] }
1199
+
756
1200
  // X-axis ticks: choose appropriate scale for tick generation
757
1201
  // Time scales (format starts with %) use scaleTime for better tick placement
758
1202
  const x_scale_for_ticks = is_time_x
759
- ? scaleTime().domain([new Date(x_min), new Date(x_max)])
760
- : create_scale(final_x_axis.scale_type ?? `linear`, [x_min, x_max], [0, 1]);
1203
+ ? scaleTime().domain([new Date(x_min), new Date(x_max)])
1204
+ : create_scale(final_x_axis.scale_type ?? `linear`, [x_min, x_max], [0, 1])
1205
+
761
1206
  const x2_scale_for_ticks = is_time_x2
762
- ? scaleTime().domain([new Date(x2_min), new Date(x2_max)])
763
- : create_scale(final_x2_axis.scale_type ?? `linear`, [x2_min, x2_max], [0, 1]);
1207
+ ? scaleTime().domain([new Date(x2_min), new Date(x2_max)])
1208
+ : create_scale(final_x2_axis.scale_type ?? `linear`, [x2_min, x2_max], [0, 1])
1209
+
764
1210
  return {
765
- x: generate_ticks([x_min, x_max], final_x_axis.scale_type ?? `linear`, final_x_axis.ticks, x_scale_for_ticks, { format: final_x_axis.format }),
766
- x2: x2_points.length > 0
767
- ? generate_ticks([x2_min, x2_max], final_x2_axis.scale_type ?? `linear`, final_x2_axis.ticks, x2_scale_for_ticks, { format: final_x2_axis.format })
768
- : [],
769
- y: generate_ticks([y_min, y_max], final_y_axis.scale_type ?? `linear`, final_y_axis.ticks, y_scale_fn, { default_count: 5 }),
770
- y2: y2_points.length > 0
771
- ? generate_ticks([y2_min, y2_max], final_y2_axis.scale_type ?? `linear`, final_y2_axis.ticks, y2_scale_fn, { default_count: 5 })
772
- : [],
773
- };
774
- });
775
- let x_tick_values = $derived(axis_ticks.x);
776
- let x2_tick_values = $derived(axis_ticks.x2);
777
- let y_tick_values = $derived(axis_ticks.y);
778
- let y2_tick_values = $derived(axis_ticks.y2);
779
- // Cache measured tick-label widths so expensive text measurement only runs
780
- // when tick values/format change, not on every template rerender.
781
- let tick_label_widths = $derived({
1211
+ x: generate_ticks(
1212
+ [x_min, x_max],
1213
+ final_x_axis.scale_type ?? `linear`,
1214
+ final_x_axis.ticks,
1215
+ x_scale_for_ticks,
1216
+ { format: final_x_axis.format },
1217
+ ),
1218
+ x2: x2_points.length > 0
1219
+ ? generate_ticks(
1220
+ [x2_min, x2_max],
1221
+ final_x2_axis.scale_type ?? `linear`,
1222
+ final_x2_axis.ticks,
1223
+ x2_scale_for_ticks,
1224
+ { format: final_x2_axis.format },
1225
+ )
1226
+ : [],
1227
+ y: generate_ticks(
1228
+ [y_min, y_max],
1229
+ final_y_axis.scale_type ?? `linear`,
1230
+ final_y_axis.ticks,
1231
+ y_scale_fn,
1232
+ { default_count: 5 },
1233
+ ),
1234
+ y2: y2_points.length > 0
1235
+ ? generate_ticks(
1236
+ [y2_min, y2_max],
1237
+ final_y2_axis.scale_type ?? `linear`,
1238
+ final_y2_axis.ticks,
1239
+ y2_scale_fn,
1240
+ { default_count: 5 },
1241
+ )
1242
+ : [],
1243
+ }
1244
+ })
1245
+
1246
+ let x_tick_values = $derived(axis_ticks.x)
1247
+ let x2_tick_values = $derived(axis_ticks.x2)
1248
+ let y_tick_values = $derived(axis_ticks.y)
1249
+ let y2_tick_values = $derived(axis_ticks.y2)
1250
+
1251
+ // Cache measured tick-label widths so expensive text measurement only runs
1252
+ // when tick values/format change, not on every template rerender.
1253
+ let tick_label_widths = $derived({
782
1254
  x2_max: measure_max_tick_width(x2_tick_values, final_x2_axis.format ?? ``),
783
1255
  y_max: measure_max_tick_width(y_tick_values, final_y_axis.format ?? ``),
784
1256
  y2_max: measure_max_tick_width(y2_tick_values, final_y2_axis.format ?? ``),
785
- });
786
- // Define global handlers reference for adding/removing listeners
787
- const on_window_mouse_move = (evt) => {
788
- if (!drag_start_coords || !svg_bounding_box)
789
- return; // Exit if not dragging or no bounds
1257
+ })
1258
+
1259
+ // Define global handlers reference for adding/removing listeners
1260
+ const on_window_mouse_move = (evt: MouseEvent) => {
1261
+ if (!drag_start_coords || !svg_bounding_box) return // Exit if not dragging or no bounds
1262
+
790
1263
  // Calculate mouse position relative to the stored SVG bounding box
791
- const current_x = evt.clientX - svg_bounding_box.left;
792
- const current_y = evt.clientY - svg_bounding_box.top;
793
- drag_current_coords = { x: current_x, y: current_y };
1264
+ const current_x = evt.clientX - svg_bounding_box.left
1265
+ const current_y = evt.clientY - svg_bounding_box.top
1266
+ drag_current_coords = { x: current_x, y: current_y }
1267
+
794
1268
  // Optional: update tooltip only if inside SVG bounds
795
1269
  const is_inside_svg = current_x >= 0 &&
796
- current_x <= svg_bounding_box.width &&
797
- current_y >= 0 &&
798
- current_y <= svg_bounding_box.height;
1270
+ current_x <= svg_bounding_box.width &&
1271
+ current_y >= 0 &&
1272
+ current_y <= svg_bounding_box.height
1273
+
799
1274
  if (is_inside_svg) {
800
- // Use the already calculated relative coordinates
801
- update_tooltip_point(current_x, current_y);
802
- }
803
- else
804
- tooltip_point = null; // Clear tooltip if outside
805
- };
806
- const on_window_mouse_up = (_evt) => {
1275
+ // Use the already calculated relative coordinates
1276
+ update_tooltip_point(current_x, current_y)
1277
+ } else tooltip_point = null // Clear tooltip if outside
1278
+ }
1279
+
1280
+ const on_window_mouse_up = (_evt: MouseEvent) => {
807
1281
  if (drag_start_coords && drag_current_coords) {
808
- // Use current scales to invert screen coords to data coords
809
- const start_data_x_val = x_scale_fn.invert(drag_start_coords.x);
810
- const end_data_x_val = x_scale_fn.invert(drag_current_coords.x);
811
- const start_data_y_val = y_scale_fn.invert(drag_start_coords.y);
812
- const end_data_y_val = y_scale_fn.invert(drag_current_coords.y);
813
- // Ensure range is not zero and order is correct
814
- let x1, x2;
815
- if (start_data_x_val instanceof Date && end_data_x_val instanceof Date) {
816
- x1 = start_data_x_val.getTime();
817
- x2 = end_data_x_val.getTime();
818
- }
819
- else if (typeof start_data_x_val === `number` &&
820
- typeof end_data_x_val === `number`) {
821
- x1 = start_data_x_val;
822
- x2 = end_data_x_val;
823
- }
824
- else {
825
- console.error(`Mismatched types for x-axis zoom calculation`);
826
- // Reset states without zooming if types are wrong
827
- drag_start_coords = null;
828
- drag_current_coords = null;
829
- window.removeEventListener(`mousemove`, on_window_mouse_move);
830
- window.removeEventListener(`mouseup`, on_window_mouse_up);
831
- return;
832
- }
833
- const next_x_range = [Math.min(x1, x2), Math.max(x1, x2)];
834
- // Y axis is always number
835
- const next_y_range = [
836
- Math.min(start_data_y_val, end_data_y_val),
837
- Math.max(start_data_y_val, end_data_y_val),
838
- ];
839
- // Check for minuscule zoom box (e.g. accidental click)
840
- const min_zoom_size = 5; // Minimum pixels to trigger zoom
841
- const dx = Math.abs(drag_start_coords.x - drag_current_coords.x);
842
- const dy = Math.abs(drag_start_coords.y - drag_current_coords.y);
843
- if (dx > min_zoom_size &&
844
- dy > min_zoom_size &&
845
- next_x_range[0] !== next_x_range[1] &&
846
- next_y_range[0] !== next_y_range[1]) {
847
- // Update axis ranges to trigger reactivity (like BarPlot/Histogram do)
848
- // Y2 sync is handled by the effect that reacts to y_axis changes
849
- x_axis = { ...x_axis, range: next_x_range };
850
- y_axis = { ...y_axis, range: next_y_range };
851
- // X2 axis: invert screen coords using x2 scale
852
- if (x2_points.length > 0) {
853
- const start_x2_val = x2_scale_fn.invert(drag_start_coords.x);
854
- const end_x2_val = x2_scale_fn.invert(drag_current_coords.x);
855
- const x2_a = start_x2_val instanceof Date
856
- ? start_x2_val.getTime()
857
- : start_x2_val;
858
- const x2_b = end_x2_val instanceof Date
859
- ? end_x2_val.getTime()
860
- : end_x2_val;
861
- x2_axis = {
862
- ...x2_axis,
863
- range: [Math.min(x2_a, x2_b), Math.max(x2_a, x2_b)],
864
- };
865
- }
1282
+ // Use current scales to invert screen coords to data coords
1283
+ const start_data_x_val = x_scale_fn.invert(drag_start_coords.x)
1284
+ const end_data_x_val = x_scale_fn.invert(drag_current_coords.x)
1285
+ const start_data_y_val = y_scale_fn.invert(drag_start_coords.y)
1286
+ const end_data_y_val = y_scale_fn.invert(drag_current_coords.y)
1287
+
1288
+ // Ensure range is not zero and order is correct
1289
+ let x1: number, x2: number
1290
+ if (start_data_x_val instanceof Date && end_data_x_val instanceof Date) {
1291
+ x1 = start_data_x_val.getTime()
1292
+ x2 = end_data_x_val.getTime()
1293
+ } else if (
1294
+ typeof start_data_x_val === `number` &&
1295
+ typeof end_data_x_val === `number`
1296
+ ) {
1297
+ x1 = start_data_x_val
1298
+ x2 = end_data_x_val
1299
+ } else {
1300
+ console.error(`Mismatched types for x-axis zoom calculation`)
1301
+ // Reset states without zooming if types are wrong
1302
+ drag_start_coords = null
1303
+ drag_current_coords = null
1304
+ window.removeEventListener(`mousemove`, on_window_mouse_move)
1305
+ window.removeEventListener(`mouseup`, on_window_mouse_up)
1306
+ return
1307
+ }
1308
+
1309
+ const next_x_range: [number, number] = [Math.min(x1, x2), Math.max(x1, x2)]
1310
+ // Y axis is always number
1311
+ const next_y_range: [number, number] = [
1312
+ Math.min(start_data_y_val, end_data_y_val),
1313
+ Math.max(start_data_y_val, end_data_y_val),
1314
+ ]
1315
+
1316
+ // Check for minuscule zoom box (e.g. accidental click)
1317
+ const min_zoom_size = 5 // Minimum pixels to trigger zoom
1318
+ const dx = Math.abs(drag_start_coords.x - drag_current_coords.x)
1319
+ const dy = Math.abs(drag_start_coords.y - drag_current_coords.y)
1320
+
1321
+ if (
1322
+ dx > min_zoom_size &&
1323
+ dy > min_zoom_size &&
1324
+ next_x_range[0] !== next_x_range[1] &&
1325
+ next_y_range[0] !== next_y_range[1]
1326
+ ) {
1327
+ // Update axis ranges to trigger reactivity (like BarPlot/Histogram do)
1328
+ // Y2 sync is handled by the effect that reacts to y_axis changes
1329
+ x_axis = { ...x_axis, range: next_x_range }
1330
+ y_axis = { ...y_axis, range: next_y_range }
1331
+
1332
+ // X2 axis: invert screen coords using x2 scale
1333
+ if (x2_points.length > 0) {
1334
+ const start_x2_val = x2_scale_fn.invert(drag_start_coords.x)
1335
+ const end_x2_val = x2_scale_fn.invert(drag_current_coords.x)
1336
+ const x2_a = start_x2_val instanceof Date
1337
+ ? start_x2_val.getTime()
1338
+ : start_x2_val as number
1339
+ const x2_b = end_x2_val instanceof Date
1340
+ ? end_x2_val.getTime()
1341
+ : end_x2_val as number
1342
+ x2_axis = {
1343
+ ...x2_axis,
1344
+ range: [Math.min(x2_a, x2_b), Math.max(x2_a, x2_b)],
1345
+ }
866
1346
  }
1347
+ }
867
1348
  }
1349
+
868
1350
  // Reset states and remove listeners
869
- drag_start_coords = null;
870
- drag_current_coords = null;
871
- svg_bounding_box = null;
872
- window.removeEventListener(`mousemove`, on_window_mouse_move);
873
- window.removeEventListener(`mouseup`, on_window_mouse_up);
874
- document.body.style.cursor = `default`;
875
- };
876
- // Pan drag handlers
877
- const on_pan_move = (evt) => {
878
- if (!pan_drag_state)
879
- return;
880
- const dx = evt.clientX - pan_drag_state.start.x;
881
- const dy = evt.clientY - pan_drag_state.start.y;
1351
+ drag_start_coords = null
1352
+ drag_current_coords = null
1353
+ svg_bounding_box = null
1354
+ window.removeEventListener(`mousemove`, on_window_mouse_move)
1355
+ window.removeEventListener(`mouseup`, on_window_mouse_up)
1356
+ document.body.style.cursor = `default`
1357
+ }
1358
+
1359
+ // Pan drag handlers
1360
+ const on_pan_move = (evt: MouseEvent) => {
1361
+ if (!pan_drag_state) return
1362
+ const dx = evt.clientX - pan_drag_state.start.x
1363
+ const dy = evt.clientY - pan_drag_state.start.y
1364
+
882
1365
  // Convert pixel delta to data delta (note: drag direction is inverted for natural pan feel)
883
1366
  // Clamp to at least 1 to avoid Infinity deltas when padding equals container size
884
- const plot_width = Math.max(1, width - pad.l - pad.r);
885
- const plot_height = Math.max(1, height - pad.t - pad.b);
886
- const sensitivity = pan?.drag_sensitivity ?? 1;
887
- const x_delta = pixels_to_data_delta(-dx * sensitivity, pan_drag_state.initial_x_range, plot_width);
888
- const x2_delta = pixels_to_data_delta(-dx * sensitivity, pan_drag_state.initial_x2_range, plot_width);
889
- const y_delta = pixels_to_data_delta(dy * sensitivity, pan_drag_state.initial_y_range, plot_height);
890
- const y2_delta = pixels_to_data_delta(dy * sensitivity, pan_drag_state.initial_y2_range, plot_height);
891
- zoom_x_range = pan_range(pan_drag_state.initial_x_range, x_delta);
892
- zoom_x2_range = pan_range(pan_drag_state.initial_x2_range, x2_delta);
893
- zoom_y_range = pan_range(pan_drag_state.initial_y_range, y_delta);
894
- zoom_y2_range = get_synced_y2(zoom_y_range, pan_range(pan_drag_state.initial_y2_range, y2_delta));
895
- };
896
- const on_pan_end = () => {
897
- pan_drag_state = null;
898
- document.body.style.cursor = ``;
899
- window.removeEventListener(`mousemove`, on_pan_move);
900
- window.removeEventListener(`mouseup`, on_pan_end);
901
- };
902
- function handle_mouse_down(evt) {
903
- if (!svg_element)
904
- return;
1367
+ const plot_width = Math.max(1, width - pad.l - pad.r)
1368
+ const plot_height = Math.max(1, height - pad.t - pad.b)
1369
+ const sensitivity = pan?.drag_sensitivity ?? 1
1370
+
1371
+ const x_delta = pixels_to_data_delta(
1372
+ -dx * sensitivity,
1373
+ pan_drag_state.initial_x_range,
1374
+ plot_width,
1375
+ )
1376
+ const x2_delta = pixels_to_data_delta(
1377
+ -dx * sensitivity,
1378
+ pan_drag_state.initial_x2_range,
1379
+ plot_width,
1380
+ )
1381
+ const y_delta = pixels_to_data_delta(
1382
+ dy * sensitivity,
1383
+ pan_drag_state.initial_y_range,
1384
+ plot_height,
1385
+ )
1386
+ const y2_delta = pixels_to_data_delta(
1387
+ dy * sensitivity,
1388
+ pan_drag_state.initial_y2_range,
1389
+ plot_height,
1390
+ )
1391
+
1392
+ zoom_x_range = pan_range(pan_drag_state.initial_x_range, x_delta)
1393
+ zoom_x2_range = pan_range(pan_drag_state.initial_x2_range, x2_delta)
1394
+ zoom_y_range = pan_range(pan_drag_state.initial_y_range, y_delta)
1395
+ zoom_y2_range = get_synced_y2(
1396
+ zoom_y_range,
1397
+ pan_range(pan_drag_state.initial_y2_range, y2_delta),
1398
+ )
1399
+ }
1400
+
1401
+ const on_pan_end = () => {
1402
+ pan_drag_state = null
1403
+ document.body.style.cursor = ``
1404
+ window.removeEventListener(`mousemove`, on_pan_move)
1405
+ window.removeEventListener(`mouseup`, on_pan_end)
1406
+ }
1407
+
1408
+ function handle_mouse_down(evt: MouseEvent) {
1409
+ if (!svg_element) return
1410
+
905
1411
  // Check if pan is enabled and shift is held for pan mode
906
- const pan_enabled = pan?.enabled !== false;
1412
+ const pan_enabled = pan?.enabled !== false
907
1413
  if (pan_enabled && evt.shiftKey) {
908
- evt.preventDefault();
909
- pan_drag_state = {
910
- start: { x: evt.clientX, y: evt.clientY },
911
- initial_x_range: [...zoom_x_range],
912
- initial_x2_range: [...zoom_x2_range],
913
- initial_y_range: [...zoom_y_range],
914
- initial_y2_range: [...zoom_y2_range],
915
- };
916
- document.body.style.cursor = `grabbing`;
917
- window.addEventListener(`mousemove`, on_pan_move);
918
- window.addEventListener(`mouseup`, on_pan_end);
919
- return;
1414
+ evt.preventDefault()
1415
+ pan_drag_state = {
1416
+ start: { x: evt.clientX, y: evt.clientY },
1417
+ initial_x_range: [...zoom_x_range] as [number, number],
1418
+ initial_x2_range: [...zoom_x2_range] as [number, number],
1419
+ initial_y_range: [...zoom_y_range] as [number, number],
1420
+ initial_y2_range: [...zoom_y2_range] as [number, number],
1421
+ }
1422
+ document.body.style.cursor = `grabbing`
1423
+ window.addEventListener(`mousemove`, on_pan_move)
1424
+ window.addEventListener(`mouseup`, on_pan_end)
1425
+ return
920
1426
  }
1427
+
921
1428
  // Store bounding box first, then calculate coords using it
922
- svg_bounding_box = svg_element.getBoundingClientRect();
1429
+ svg_bounding_box = svg_element.getBoundingClientRect()
1430
+
923
1431
  // Calculate initial coords using the same bounding box that will be used during drag
924
- const initial_x = evt.clientX - svg_bounding_box.left;
925
- const initial_y = evt.clientY - svg_bounding_box.top;
926
- const coords = { x: initial_x, y: initial_y };
927
- drag_start_coords = coords;
928
- drag_current_coords = coords;
929
- window.addEventListener(`mousemove`, on_window_mouse_move);
930
- window.addEventListener(`mouseup`, on_window_mouse_up);
931
- document.body.style.cursor = `crosshair`;
932
- evt.preventDefault();
933
- }
934
- // Wheel handler for pan (requires focus and shift)
935
- function handle_wheel(evt) {
936
- const pan_enabled = pan?.enabled !== false;
1432
+ const initial_x = evt.clientX - svg_bounding_box.left
1433
+ const initial_y = evt.clientY - svg_bounding_box.top
1434
+ const coords = { x: initial_x, y: initial_y }
1435
+
1436
+ drag_start_coords = coords
1437
+ drag_current_coords = coords
1438
+
1439
+ window.addEventListener(`mousemove`, on_window_mouse_move)
1440
+ window.addEventListener(`mouseup`, on_window_mouse_up)
1441
+ document.body.style.cursor = `crosshair`
1442
+ evt.preventDefault()
1443
+ }
1444
+
1445
+ // Wheel handler for pan (requires focus and shift)
1446
+ function handle_wheel(evt: WheelEvent) {
1447
+ const pan_enabled = pan?.enabled !== false
937
1448
  // Only capture wheel when focused AND Shift is held
938
1449
  // Use shift_held state (tracked via keydown/keyup) for compatibility with synthetic events
939
- if (!pan_enabled || !is_focused || !shift_held)
940
- return;
941
- evt.preventDefault();
1450
+ if (!pan_enabled || !is_focused || !shift_held) return
1451
+
1452
+ evt.preventDefault()
1453
+
942
1454
  // Clamp to at least 1 to avoid Infinity deltas when padding equals container size
943
- const plot_width = Math.max(1, width - pad.l - pad.r);
944
- const plot_height = Math.max(1, height - pad.t - pad.b);
945
- const sensitivity = pan?.wheel_sensitivity ?? 1;
1455
+ const plot_width = Math.max(1, width - pad.l - pad.r)
1456
+ const plot_height = Math.max(1, height - pad.t - pad.b)
1457
+ const sensitivity = pan?.wheel_sensitivity ?? 1
1458
+
946
1459
  // Determine pan direction based on wheel delta
947
1460
  // deltaX for horizontal scroll (trackpad), deltaY for vertical
948
- const x_delta = pixels_to_data_delta(evt.deltaX * sensitivity, zoom_x_range, plot_width);
949
- const x2_delta = pixels_to_data_delta(evt.deltaX * sensitivity, zoom_x2_range, plot_width);
950
- const y_delta = pixels_to_data_delta(evt.deltaY * sensitivity, zoom_y_range, plot_height);
951
- const y2_delta = pixels_to_data_delta(evt.deltaY * sensitivity, zoom_y2_range, plot_height);
1461
+ const x_delta = pixels_to_data_delta(
1462
+ evt.deltaX * sensitivity,
1463
+ zoom_x_range,
1464
+ plot_width,
1465
+ )
1466
+ const x2_delta = pixels_to_data_delta(
1467
+ evt.deltaX * sensitivity,
1468
+ zoom_x2_range,
1469
+ plot_width,
1470
+ )
1471
+ const y_delta = pixels_to_data_delta(
1472
+ evt.deltaY * sensitivity,
1473
+ zoom_y_range,
1474
+ plot_height,
1475
+ )
1476
+ const y2_delta = pixels_to_data_delta(
1477
+ evt.deltaY * sensitivity,
1478
+ zoom_y2_range,
1479
+ plot_height,
1480
+ )
1481
+
952
1482
  if (Math.abs(evt.deltaX) > Math.abs(evt.deltaY)) {
953
- zoom_x_range = pan_range(zoom_x_range, x_delta);
954
- zoom_x2_range = pan_range(zoom_x2_range, x2_delta);
955
- }
956
- else {
957
- zoom_y_range = pan_range(zoom_y_range, y_delta);
958
- zoom_y2_range = get_synced_y2(zoom_y_range, pan_range(zoom_y2_range, y2_delta));
1483
+ zoom_x_range = pan_range(zoom_x_range, x_delta)
1484
+ zoom_x2_range = pan_range(zoom_x2_range, x2_delta)
1485
+ } else {
1486
+ zoom_y_range = pan_range(zoom_y_range, y_delta)
1487
+ zoom_y2_range = get_synced_y2(zoom_y_range, pan_range(zoom_y2_range, y2_delta))
959
1488
  }
960
- }
961
- // Touch handlers for pinch-zoom and two-finger pan
962
- function handle_touch_start(evt) {
963
- const touch_enabled = pan?.enabled !== false && pan?.touch_enabled !== false;
964
- if (!touch_enabled || evt.touches.length !== 2)
965
- return;
966
- evt.preventDefault();
967
- const touches = Array.from(evt.touches);
1489
+ }
1490
+
1491
+ // Touch handlers for pinch-zoom and two-finger pan
1492
+ function handle_touch_start(evt: TouchEvent) {
1493
+ const touch_enabled = pan?.enabled !== false && pan?.touch_enabled !== false
1494
+ if (!touch_enabled || evt.touches.length !== 2) return
1495
+
1496
+ evt.preventDefault()
1497
+ const touches = Array.from(evt.touches)
968
1498
  touch_state = {
969
- start_touches: touches.map((touch) => ({ x: touch.clientX, y: touch.clientY })),
970
- initial_x_range: [...zoom_x_range],
971
- initial_x2_range: [...zoom_x2_range],
972
- initial_y_range: [...zoom_y_range],
973
- initial_y2_range: [...zoom_y2_range],
974
- };
975
- }
976
- function handle_touch_move(evt) {
977
- if (!touch_state || evt.touches.length !== 2)
978
- return;
979
- evt.preventDefault();
980
- const [t1, t2] = Array.from(evt.touches);
981
- const [s1, s2] = touch_state.start_touches;
1499
+ start_touches: touches.map((touch) => ({ x: touch.clientX, y: touch.clientY })),
1500
+ initial_x_range: [...zoom_x_range] as [number, number],
1501
+ initial_x2_range: [...zoom_x2_range] as [number, number],
1502
+ initial_y_range: [...zoom_y_range] as [number, number],
1503
+ initial_y2_range: [...zoom_y2_range] as [number, number],
1504
+ }
1505
+ }
1506
+
1507
+ function handle_touch_move(evt: TouchEvent) {
1508
+ if (!touch_state || evt.touches.length !== 2) return
1509
+ evt.preventDefault()
1510
+
1511
+ const [t1, t2] = Array.from(evt.touches)
1512
+ const [s1, s2] = touch_state.start_touches
1513
+
982
1514
  // Calculate center movement for pan
983
- const start_center = { x: (s1.x + s2.x) / 2, y: (s1.y + s2.y) / 2 };
1515
+ const start_center = { x: (s1.x + s2.x) / 2, y: (s1.y + s2.y) / 2 }
984
1516
  const curr_center = {
985
- x: (t1.clientX + t2.clientX) / 2,
986
- y: (t1.clientY + t2.clientY) / 2,
987
- };
988
- const dx = curr_center.x - start_center.x;
989
- const dy = curr_center.y - start_center.y;
1517
+ x: (t1.clientX + t2.clientX) / 2,
1518
+ y: (t1.clientY + t2.clientY) / 2,
1519
+ }
1520
+ const dx = curr_center.x - start_center.x
1521
+ const dy = curr_center.y - start_center.y
1522
+
990
1523
  // Calculate pinch scale (curr/start so spread = zoom out, pinch = zoom in)
991
- const start_dist = Math.hypot(s2.x - s1.x, s2.y - s1.y);
1524
+ const start_dist = Math.hypot(s2.x - s1.x, s2.y - s1.y)
992
1525
  // Guard against zero-distance pinch to avoid Infinity scale
993
- if (start_dist < Number.EPSILON)
994
- return;
995
- const curr_dist = Math.hypot(t2.clientX - t1.clientX, t2.clientY - t1.clientY);
996
- const scale = curr_dist / start_dist;
1526
+ if (start_dist < Number.EPSILON) return
1527
+ const curr_dist = Math.hypot(t2.clientX - t1.clientX, t2.clientY - t1.clientY)
1528
+ const scale = curr_dist / start_dist
1529
+
997
1530
  // Clamp to at least 1 to avoid Infinity deltas when padding equals container size
998
- const plot_width = Math.max(1, width - pad.l - pad.r);
999
- const plot_height = Math.max(1, height - pad.t - pad.b);
1531
+ const plot_width = Math.max(1, width - pad.l - pad.r)
1532
+ const plot_height = Math.max(1, height - pad.t - pad.b)
1533
+
1000
1534
  // If scale changed significantly, treat as pinch-zoom
1001
1535
  // Also guard against scale being too small to avoid division by zero
1002
1536
  if (Math.abs(scale - 1) > PINCH_ZOOM_THRESHOLD && scale > Number.EPSILON) {
1003
- // Pinch zoom centered on gesture center
1004
- // Divide by scale so spread (scale > 1) = smaller span (zoom in)
1005
- const x_span = touch_state.initial_x_range[1] - touch_state.initial_x_range[0];
1006
- const x2_span = touch_state.initial_x2_range[1] -
1007
- touch_state.initial_x2_range[0];
1008
- const y_span = touch_state.initial_y_range[1] - touch_state.initial_y_range[0];
1009
- const y2_span = touch_state.initial_y2_range[1] -
1010
- touch_state.initial_y2_range[0];
1011
- const x_center = (touch_state.initial_x_range[0] + touch_state.initial_x_range[1]) / 2;
1012
- const x2_center = (touch_state.initial_x2_range[0] + touch_state.initial_x2_range[1]) / 2;
1013
- const y_center = (touch_state.initial_y_range[0] + touch_state.initial_y_range[1]) / 2;
1014
- const y2_center = (touch_state.initial_y2_range[0] + touch_state.initial_y2_range[1]) / 2;
1015
- zoom_x_range = [x_center - x_span / scale / 2, x_center + x_span / scale / 2];
1016
- zoom_x2_range = [
1017
- x2_center - x2_span / scale / 2,
1018
- x2_center + x2_span / scale / 2,
1019
- ];
1020
- zoom_y_range = [y_center - y_span / scale / 2, y_center + y_span / scale / 2];
1021
- zoom_y2_range = get_synced_y2(zoom_y_range, [
1022
- y2_center - y2_span / scale / 2,
1023
- y2_center + y2_span / scale / 2,
1024
- ]);
1025
- }
1026
- else {
1027
- // Pan
1028
- const x_delta = pixels_to_data_delta(-dx, touch_state.initial_x_range, plot_width);
1029
- const x2_delta = pixels_to_data_delta(-dx, touch_state.initial_x2_range, plot_width);
1030
- const y_delta = pixels_to_data_delta(dy, touch_state.initial_y_range, plot_height);
1031
- const y2_delta = pixels_to_data_delta(dy, touch_state.initial_y2_range, plot_height);
1032
- zoom_x_range = pan_range(touch_state.initial_x_range, x_delta);
1033
- zoom_x2_range = pan_range(touch_state.initial_x2_range, x2_delta);
1034
- zoom_y_range = pan_range(touch_state.initial_y_range, y_delta);
1035
- zoom_y2_range = get_synced_y2(zoom_y_range, pan_range(touch_state.initial_y2_range, y2_delta));
1537
+ // Pinch zoom centered on gesture center
1538
+ // Divide by scale so spread (scale > 1) = smaller span (zoom in)
1539
+ const x_span = touch_state.initial_x_range[1] - touch_state.initial_x_range[0]
1540
+ const x2_span = touch_state.initial_x2_range[1] -
1541
+ touch_state.initial_x2_range[0]
1542
+ const y_span = touch_state.initial_y_range[1] - touch_state.initial_y_range[0]
1543
+ const y2_span = touch_state.initial_y2_range[1] -
1544
+ touch_state.initial_y2_range[0]
1545
+ const x_center =
1546
+ (touch_state.initial_x_range[0] + touch_state.initial_x_range[1]) / 2
1547
+ const x2_center =
1548
+ (touch_state.initial_x2_range[0] + touch_state.initial_x2_range[1]) / 2
1549
+ const y_center =
1550
+ (touch_state.initial_y_range[0] + touch_state.initial_y_range[1]) / 2
1551
+ const y2_center =
1552
+ (touch_state.initial_y2_range[0] + touch_state.initial_y2_range[1]) / 2
1553
+
1554
+ zoom_x_range = [x_center - x_span / scale / 2, x_center + x_span / scale / 2]
1555
+ zoom_x2_range = [
1556
+ x2_center - x2_span / scale / 2,
1557
+ x2_center + x2_span / scale / 2,
1558
+ ]
1559
+ zoom_y_range = [y_center - y_span / scale / 2, y_center + y_span / scale / 2]
1560
+ zoom_y2_range = get_synced_y2(zoom_y_range, [
1561
+ y2_center - y2_span / scale / 2,
1562
+ y2_center + y2_span / scale / 2,
1563
+ ])
1564
+ } else {
1565
+ // Pan
1566
+ const x_delta = pixels_to_data_delta(
1567
+ -dx,
1568
+ touch_state.initial_x_range,
1569
+ plot_width,
1570
+ )
1571
+ const x2_delta = pixels_to_data_delta(
1572
+ -dx,
1573
+ touch_state.initial_x2_range,
1574
+ plot_width,
1575
+ )
1576
+ const y_delta = pixels_to_data_delta(
1577
+ dy,
1578
+ touch_state.initial_y_range,
1579
+ plot_height,
1580
+ )
1581
+ const y2_delta = pixels_to_data_delta(
1582
+ dy,
1583
+ touch_state.initial_y2_range,
1584
+ plot_height,
1585
+ )
1586
+ zoom_x_range = pan_range(touch_state.initial_x_range, x_delta)
1587
+ zoom_x2_range = pan_range(touch_state.initial_x2_range, x2_delta)
1588
+ zoom_y_range = pan_range(touch_state.initial_y_range, y_delta)
1589
+ zoom_y2_range = get_synced_y2(
1590
+ zoom_y_range,
1591
+ pan_range(touch_state.initial_y2_range, y2_delta),
1592
+ )
1036
1593
  }
1037
- }
1038
- function handle_touch_end() {
1039
- touch_state = null;
1040
- }
1041
- // tooltip logic: find closest point and update tooltip state
1042
- function update_tooltip_point(x_rel, y_rel, evt) {
1043
- if (!width || !height)
1044
- return;
1045
- let closest_point = null;
1046
- let closest_series = null;
1047
- let min_screen_dist_sq = Infinity;
1048
- const { threshold_px = 20 } = hover_config; // Use configured threshold
1049
- const hover_threshold_px_sq = threshold_px * threshold_px;
1594
+ }
1595
+
1596
+ function handle_touch_end() {
1597
+ touch_state = null
1598
+ }
1599
+
1600
+ // tooltip logic: find closest point and update tooltip state
1601
+ function update_tooltip_point(x_rel: number, y_rel: number, evt?: MouseEvent) {
1602
+ if (!width || !height) return
1603
+
1604
+ let closest_point: InternalPoint<Metadata> | null = null
1605
+ let closest_series: DataSeries<Metadata> | null = null
1606
+ let min_screen_dist_sq = Infinity
1607
+ const { threshold_px = 20 } = hover_config // Use configured threshold
1608
+ const hover_threshold_px_sq = threshold_px * threshold_px
1609
+
1050
1610
  // Iterate through points to find the closest one in screen coordinates
1051
1611
  for (const series_data of filtered_series) {
1052
- if (!series_data?.filtered_data)
1053
- continue;
1054
- const tooltip_use_x2 = series_data.x_axis === `x2`;
1055
- const tooltip_x_scale = tooltip_use_x2 ? x2_scale_fn : x_scale_fn;
1056
- const tooltip_is_time_x = tooltip_use_x2 ? is_time_x2 : is_time_x;
1057
- for (const point of series_data.filtered_data) {
1058
- // Calculate screen coordinates of the point
1059
- const point_cx = tooltip_is_time_x
1060
- ? tooltip_x_scale(new Date(point.x))
1061
- : tooltip_x_scale(point.x);
1062
- const point_cy = (series_data.y_axis === `y2` ? y2_scale_fn : y_scale_fn)(point.y);
1063
- // Calculate squared screen distance between mouse and point
1064
- const screen_dx = x_rel - point_cx;
1065
- const screen_dy = y_rel - point_cy;
1066
- const screen_distance_sq = screen_dx * screen_dx + screen_dy * screen_dy;
1067
- // Update if this point is closer
1068
- if (screen_distance_sq < min_screen_dist_sq) {
1069
- min_screen_dist_sq = screen_distance_sq;
1070
- closest_point = point;
1071
- closest_series = series_data;
1072
- }
1612
+ if (!series_data?.filtered_data) continue
1613
+
1614
+ const tooltip_use_x2 = series_data.x_axis === `x2`
1615
+ const tooltip_x_scale = tooltip_use_x2 ? x2_scale_fn : x_scale_fn
1616
+ const tooltip_is_time_x = tooltip_use_x2 ? is_time_x2 : is_time_x
1617
+ for (const point of series_data.filtered_data) {
1618
+ // Calculate screen coordinates of the point
1619
+ const point_cx = tooltip_is_time_x
1620
+ ? tooltip_x_scale(new Date(point.x))
1621
+ : tooltip_x_scale(point.x)
1622
+ const point_cy = (series_data.y_axis === `y2` ? y2_scale_fn : y_scale_fn)(
1623
+ point.y,
1624
+ )
1625
+
1626
+ // Calculate squared screen distance between mouse and point
1627
+ const screen_dx = x_rel - point_cx
1628
+ const screen_dy = y_rel - point_cy
1629
+ const screen_distance_sq = screen_dx * screen_dx + screen_dy * screen_dy
1630
+
1631
+ // Update if this point is closer
1632
+ if (screen_distance_sq < min_screen_dist_sq) {
1633
+ min_screen_dist_sq = screen_distance_sq
1634
+ closest_point = point
1635
+ closest_series = series_data
1073
1636
  }
1637
+ }
1074
1638
  }
1639
+
1075
1640
  // Check if the closest point is within the hover threshold
1076
- if (closest_point &&
1077
- closest_series &&
1078
- min_screen_dist_sq <= hover_threshold_px_sq) {
1079
- // Construct handler props synchronously to avoid stale derived reads
1080
- const props = construct_handler_props(closest_point);
1081
- tooltip_point = closest_point;
1082
- // Construct object matching change signature
1083
- const { x, y, metadata } = closest_point;
1084
- change({ x, y, metadata, series: closest_series });
1085
- // Call hover handler with synchronously constructed props
1086
- if (evt && props) {
1087
- on_point_hover?.({ ...props, event: evt, point: closest_point });
1088
- }
1089
- }
1090
- else {
1091
- tooltip_point = null;
1092
- change(null);
1093
- on_point_hover?.(null);
1641
+ if (
1642
+ closest_point &&
1643
+ closest_series &&
1644
+ min_screen_dist_sq <= hover_threshold_px_sq
1645
+ ) {
1646
+ // Construct handler props synchronously to avoid stale derived reads
1647
+ const props = construct_handler_props(closest_point)
1648
+ tooltip_point = closest_point
1649
+ // Construct object matching change signature
1650
+ const { x, y, metadata } = closest_point
1651
+ change({ x, y, metadata, series: closest_series })
1652
+ // Call hover handler with synchronously constructed props
1653
+ if (evt && props) {
1654
+ on_point_hover?.({ ...props, event: evt, point: closest_point })
1655
+ }
1656
+ } else {
1657
+ tooltip_point = null
1658
+ change(null)
1659
+ on_point_hover?.(null)
1094
1660
  }
1095
- }
1096
- function on_mouse_move(evt) {
1097
- hovered = true;
1098
- const coords = get_relative_coords(evt);
1099
- if (!coords)
1100
- return;
1101
- update_tooltip_point(coords.x, coords.y, evt);
1102
- }
1103
- // Merge user config with defaults before the effect that uses it
1104
- let actual_label_config = $derived({
1105
- collision_strength: 1.5, // Increased from 1.1 for stronger overlap prevention
1106
- link_strength: 0.8,
1107
- link_distance: 10,
1108
- placement_ticks: 200, // Increased from 120 for better settling
1109
- link_distance_range: [5, 20], // Default min and max distance (replacing max_link_distance)
1110
- max_labels: 300, // Maximum labels before falling back to simple offsets
1111
- charge_strength: 50, // Repulsion strength for markers
1112
- charge_distance_max: 30, // Limit range of repulsion
1661
+ }
1662
+
1663
+ function on_mouse_move(evt: MouseEvent) {
1664
+ hovered = true
1665
+
1666
+ const coords = get_relative_coords(evt)
1667
+ if (!coords) return
1668
+
1669
+ update_tooltip_point(coords.x, coords.y, evt)
1670
+ }
1671
+
1672
+ // Merge user config with defaults before the effect that uses it
1673
+ let actual_label_config = $derived({
1674
+ sa_iterations: 2000,
1675
+ max_labels: 300,
1676
+ leader_line_threshold: 15,
1113
1677
  ...label_placement_config,
1114
- });
1115
- $effect(() => {
1678
+ })
1679
+
1680
+ $effect(() => {
1116
1681
  if (!width || !height) {
1117
- label_positions = {};
1118
- return;
1682
+ label_positions = {}
1683
+ return
1119
1684
  }
1120
- label_positions = compute_label_positions(filtered_series, actual_label_config, { x_scale_fn, y_scale_fn, y2_scale_fn, x_axis: final_x_axis }, { width, height, pad });
1121
- });
1122
- // Legend drag handlers
1123
- function handle_legend_drag_start(event) {
1124
- if (!svg_element)
1125
- return;
1126
- legend_is_dragging = true;
1685
+
1686
+ label_positions = compute_label_positions(
1687
+ filtered_series,
1688
+ actual_label_config,
1689
+ { x_scale_fn, y_scale_fn, y2_scale_fn, x_axis: final_x_axis },
1690
+ { width, height, pad },
1691
+ )
1692
+ })
1693
+
1694
+ // Legend drag handlers
1695
+ function handle_legend_drag_start(event: MouseEvent) {
1696
+ if (!svg_element) return
1697
+
1698
+ legend_is_dragging = true
1699
+
1127
1700
  // Get the actual rendered position of the legend element (accounts for transforms)
1128
- const legend_el = event.currentTarget;
1129
- if (!(legend_el instanceof HTMLElement))
1130
- return;
1131
- const legend_rect = legend_el.getBoundingClientRect();
1701
+ const legend_el = event.currentTarget
1702
+ if (!(legend_el instanceof HTMLElement)) return
1703
+ const legend_rect = legend_el.getBoundingClientRect()
1704
+
1132
1705
  // Calculate offset from mouse to legend's actual rendered position relative to SVG
1133
- const [x, y] = [event.clientX - legend_rect.left, event.clientY - legend_rect.top];
1134
- legend_drag_offset = { x, y };
1135
- }
1136
- function handle_legend_drag(event) {
1137
- if (!legend_is_dragging || !svg_element || !legend_element)
1138
- return;
1139
- const svg_rect = svg_element.getBoundingClientRect();
1706
+ const [x, y] = [event.clientX - legend_rect.left, event.clientY - legend_rect.top]
1707
+ legend_drag_offset = { x, y }
1708
+ }
1709
+
1710
+ function handle_legend_drag(event: MouseEvent) {
1711
+ if (!legend_is_dragging || !svg_element || !legend_element) return
1712
+
1713
+ const svg_rect = svg_element.getBoundingClientRect()
1714
+
1140
1715
  // Calculate new position: mouse position relative to SVG, minus the offset within the legend
1141
- const new_x = event.clientX - svg_rect.left - legend_drag_offset.x;
1142
- const new_y = event.clientY - svg_rect.top - legend_drag_offset.y;
1716
+ const new_x = event.clientX - svg_rect.left - legend_drag_offset.x
1717
+ const new_y = event.clientY - svg_rect.top - legend_drag_offset.y
1718
+
1143
1719
  // Get actual legend dimensions for accurate bounds checking using the bound element reference
1144
1720
  const { width: legend_width, height: legend_height } = legend_element
1145
- .getBoundingClientRect();
1721
+ .getBoundingClientRect()
1722
+
1146
1723
  // Constrain to plot bounds using measured legend size
1147
- const constrained_x = Math.max(0, Math.min(width - legend_width, new_x));
1148
- const constrained_y = Math.max(0, Math.min(height - legend_height, new_y));
1149
- legend_manual_position = { x: constrained_x, y: constrained_y };
1150
- }
1151
- function get_screen_coords(point, series) {
1724
+ const constrained_x = Math.max(0, Math.min(width - legend_width, new_x))
1725
+ const constrained_y = Math.max(0, Math.min(height - legend_height, new_y))
1726
+
1727
+ legend_manual_position = { x: constrained_x, y: constrained_y }
1728
+ }
1729
+
1730
+ function get_screen_coords(point: Point, series?: DataSeries): [number, number] {
1152
1731
  // convert data coordinates to potentially non-finite screen coordinates
1153
- const use_x2 = series?.x_axis === `x2`;
1154
- const active_x_scale = use_x2 ? x2_scale_fn : x_scale_fn;
1155
- const active_is_time_x = use_x2 ? is_time_x2 : is_time_x;
1732
+ const use_x2 = series?.x_axis === `x2`
1733
+ const active_x_scale = use_x2 ? x2_scale_fn : x_scale_fn
1734
+ const active_is_time_x = use_x2 ? is_time_x2 : is_time_x
1156
1735
  const screen_x = active_is_time_x
1157
- ? active_x_scale(new Date(point.x))
1158
- : active_x_scale(point.x);
1159
- const y_val = point.y;
1736
+ ? active_x_scale(new Date(point.x))
1737
+ : active_x_scale(point.x)
1738
+
1739
+ const y_val = point.y
1160
1740
  // Determine which y-scale to use based on series y_axis property
1161
- const use_y2 = series?.y_axis === `y2`;
1162
- const y_scale = use_y2 ? y2_scale_fn : y_scale_fn;
1741
+ const use_y2 = series?.y_axis === `y2`
1742
+ const y_scale = use_y2 ? y2_scale_fn : y_scale_fn
1163
1743
  const y_scale_type = use_y2
1164
- ? get_scale_type_name(final_y2_axis.scale_type)
1165
- : get_scale_type_name(final_y_axis.scale_type);
1744
+ ? get_scale_type_name(final_y2_axis.scale_type)
1745
+ : get_scale_type_name(final_y_axis.scale_type)
1166
1746
  // Only log scale needs domain clamping; linear and arcsinh can handle any value
1167
- const min_domain_y = y_scale_type === `log` ? y_scale.domain()[0] : -Infinity;
1168
- const safe_y_val = y_scale_type === `log` ? Math.max(y_val, min_domain_y) : y_val;
1169
- const screen_y = y_scale(safe_y_val); // This might be non-finite
1170
- return [screen_x, screen_y];
1171
- }
1172
- // Helper function to construct ScatterHandlerProps synchronously from InternalPoint
1173
- function construct_handler_props(point) {
1174
- const hovered_series = series_with_ids[point.series_idx];
1175
- if (!hovered_series)
1176
- return null;
1177
- const { x, y, color_value, metadata, series_idx } = point;
1178
- const handler_use_x2 = hovered_series.x_axis === `x2`;
1179
- const handler_x_scale = handler_use_x2 ? x2_scale_fn : x_scale_fn;
1180
- const handler_is_time_x = handler_use_x2 ? is_time_x2 : is_time_x;
1181
- const cx = handler_is_time_x ? handler_x_scale(new Date(x)) : handler_x_scale(x);
1182
- const cy = (hovered_series.y_axis === `y2` ? y2_scale_fn : y_scale_fn)(y);
1183
- const active_x_config = handler_use_x2 ? final_x2_axis : final_x_axis;
1747
+ const min_domain_y = y_scale_type === `log` ? y_scale.domain()[0] : -Infinity
1748
+ const safe_y_val = y_scale_type === `log` ? Math.max(y_val, min_domain_y) : y_val
1749
+ const screen_y = y_scale(safe_y_val) // This might be non-finite
1750
+
1751
+ return [screen_x, screen_y]
1752
+ }
1753
+
1754
+ // Helper function to construct ScatterHandlerProps synchronously from InternalPoint
1755
+ function construct_handler_props(
1756
+ point: InternalPoint<Metadata>,
1757
+ ): ScatterHandlerProps<Metadata> | null {
1758
+ const hovered_series = series_with_ids[point.series_idx]
1759
+ if (!hovered_series) return null
1760
+ const { x, y, color_value, metadata, series_idx } = point
1761
+ const handler_use_x2 = hovered_series.x_axis === `x2`
1762
+ const handler_x_scale = handler_use_x2 ? x2_scale_fn : x_scale_fn
1763
+ const handler_is_time_x = handler_use_x2 ? is_time_x2 : is_time_x
1764
+ const cx = handler_is_time_x ? handler_x_scale(new Date(x)) : handler_x_scale(x)
1765
+ const cy = (hovered_series.y_axis === `y2` ? y2_scale_fn : y_scale_fn)(y)
1766
+ const active_x_config = handler_use_x2 ? final_x2_axis : final_x_axis
1184
1767
  const active_y_config = hovered_series.y_axis === `y2`
1185
- ? final_y2_axis
1186
- : final_y_axis;
1768
+ ? final_y2_axis
1769
+ : final_y_axis
1187
1770
  const coords = {
1188
- x,
1189
- y,
1190
- cx,
1191
- cy,
1192
- x_axis: active_x_config,
1193
- x2_axis: final_x2_axis,
1194
- y_axis: active_y_config,
1195
- y2_axis: final_y2_axis,
1196
- };
1771
+ x,
1772
+ y,
1773
+ cx,
1774
+ cy,
1775
+ x_axis: active_x_config,
1776
+ x2_axis: final_x2_axis,
1777
+ y_axis: active_y_config,
1778
+ y2_axis: final_y2_axis,
1779
+ }
1197
1780
  return {
1198
- ...coords,
1199
- fullscreen,
1200
- metadata,
1201
- label: hovered_series.label ?? null,
1202
- series_idx,
1203
- x_formatted: format_value(x, active_x_config.format || `.3~s`),
1204
- y_formatted: format_value(y, active_y_config.format || `.3~s`),
1205
- color_value: color_value ?? null,
1206
- colorbar: {
1207
- value: color_value ?? null,
1208
- title: color_bar?.title ?? null,
1209
- scale: color_scale,
1210
- tick_format: color_bar?.tick_format ?? null,
1211
- },
1212
- };
1213
- }
1214
- // Derive handler props from hovered point for both tooltip and event handlers
1215
- let handler_props = $derived.by(() => {
1216
- if (!tooltip_point)
1217
- return null;
1218
- return construct_handler_props(tooltip_point);
1219
- });
1220
- let using_controls = $derived(controls.show);
1221
- let has_multiple_series = $derived(series_with_ids.filter(Boolean).length > 1);
1222
- // Precompute non-click event names from point_events so we don't rebuild
1223
- // the entries array on every point render.
1224
- let point_event_names = $derived(point_events
1225
- ? Object.keys(point_events).filter((name) => name !== `onclick`)
1226
- : []);
1227
- // Set theme-aware background when entering fullscreen
1228
- $effect(() => {
1229
- set_fullscreen_bg(wrapper, fullscreen, `--scatter-fullscreen-bg`);
1230
- });
1231
- // State accessors for shared axis change handler
1232
- const axis_state = {
1781
+ ...coords,
1782
+ fullscreen,
1783
+ metadata,
1784
+ label: hovered_series.label ?? null,
1785
+ series_idx,
1786
+ x_formatted: format_value(x, active_x_config.format || `.3~s`),
1787
+ y_formatted: format_value(y, active_y_config.format || `.3~s`),
1788
+ color_value: color_value ?? null,
1789
+ colorbar: {
1790
+ value: color_value ?? null,
1791
+ title: color_bar?.title ?? null,
1792
+ scale: color_scale,
1793
+ tick_format: color_bar?.tick_format ?? null,
1794
+ },
1795
+ }
1796
+ }
1797
+
1798
+ // Derive handler props from hovered point for both tooltip and event handlers
1799
+ let handler_props = $derived.by((): ScatterHandlerProps<Metadata> | null => {
1800
+ if (!tooltip_point) return null
1801
+ return construct_handler_props(tooltip_point)
1802
+ })
1803
+
1804
+ let using_controls = $derived(controls.show)
1805
+ let has_multiple_series = $derived(series_with_ids.filter(Boolean).length > 1)
1806
+
1807
+ // Precompute non-click event names from point_events so we don't rebuild
1808
+ // the entries array on every point render.
1809
+ let point_event_names = $derived(
1810
+ point_events
1811
+ ? Object.keys(point_events).filter((name) => name !== `onclick`)
1812
+ : [],
1813
+ )
1814
+
1815
+ // Set theme-aware background when entering fullscreen
1816
+ $effect(() => {
1817
+ set_fullscreen_bg(wrapper, fullscreen, `--scatter-fullscreen-bg`)
1818
+ })
1819
+
1820
+ // State accessors for shared axis change handler
1821
+ const axis_state: AxisChangeState<DataSeries<Metadata>> = {
1233
1822
  get_axis: (axis) => {
1234
- if (axis === `x`)
1235
- return x_axis;
1236
- if (axis === `x2`)
1237
- return x2_axis;
1238
- if (axis === `y`)
1239
- return y_axis;
1240
- return y2_axis;
1823
+ if (axis === `x`) return x_axis
1824
+ if (axis === `x2`) return x2_axis
1825
+ if (axis === `y`) return y_axis
1826
+ return y2_axis
1241
1827
  },
1242
1828
  set_axis: (axis, config) => {
1243
- // Spread into existing state to preserve merged type structure
1244
- if (axis === `x`)
1245
- x_axis = { ...x_axis, ...config };
1246
- else if (axis === `x2`)
1247
- x2_axis = { ...x2_axis, ...config };
1248
- else if (axis === `y`)
1249
- y_axis = { ...y_axis, ...config };
1250
- else
1251
- y2_axis = { ...y2_axis, ...config };
1829
+ // Spread into existing state to preserve merged type structure
1830
+ if (axis === `x`) x_axis = { ...x_axis, ...config }
1831
+ else if (axis === `x2`) x2_axis = { ...x2_axis, ...config }
1832
+ else if (axis === `y`) y_axis = { ...y_axis, ...config }
1833
+ else y2_axis = { ...y2_axis, ...config }
1252
1834
  },
1253
1835
  get_series: () => series,
1254
1836
  set_series: (new_series) => (series = new_series),
1255
1837
  get_loading: () => axis_loading,
1256
1838
  set_loading: (axis) => (axis_loading = axis),
1257
- };
1258
- // Create shared handler bound to this component's state
1259
- // Using $derived so handler updates when callback props change
1260
- const handle_axis_change = $derived(create_axis_change_handler(axis_state, data_loader, on_axis_change, on_error));
1261
- let auto_load_attempted = false; // prevent infinite retries on failure
1262
- // Auto-load data if series is empty but options exist (runs once)
1263
- $effect(() => {
1839
+ }
1840
+
1841
+ // Create shared handler bound to this component's state
1842
+ // Using $derived so handler updates when callback props change
1843
+ const handle_axis_change = $derived(create_axis_change_handler(
1844
+ axis_state,
1845
+ data_loader,
1846
+ on_axis_change,
1847
+ on_error,
1848
+ ))
1849
+
1850
+ let auto_load_attempted = false // prevent infinite retries on failure
1851
+
1852
+ // Auto-load data if series is empty but options exist (runs once)
1853
+ $effect(() => {
1264
1854
  if (series.length === 0 && data_loader && !auto_load_attempted) {
1265
- // Check x-axis first, then y-axis
1266
- if (x_axis.options?.length) {
1267
- auto_load_attempted = true;
1268
- const first_key = x_axis.selected_key ?? x_axis.options[0].key;
1269
- handle_axis_change(`x`, first_key).catch(() => { });
1270
- }
1271
- else if (y_axis.options?.length) {
1272
- auto_load_attempted = true;
1273
- const first_key = y_axis.selected_key ?? y_axis.options[0].key;
1274
- handle_axis_change(`y`, first_key).catch(() => { });
1275
- }
1855
+ // Check x-axis first, then y-axis
1856
+ if (x_axis.options?.length) {
1857
+ auto_load_attempted = true
1858
+ const first_key = x_axis.selected_key ?? x_axis.options[0].key
1859
+ handle_axis_change(`x`, first_key).catch(() => {})
1860
+ } else if (y_axis.options?.length) {
1861
+ auto_load_attempted = true
1862
+ const first_key = y_axis.selected_key ?? y_axis.options[0].key
1863
+ handle_axis_change(`y`, first_key).catch(() => {})
1864
+ }
1276
1865
  }
1277
- });
1866
+ })
1278
1867
  </script>
1279
1868
 
1280
1869
  {#snippet fill_regions_layer(fills: typeof computed_fills)}
@@ -1474,7 +2063,7 @@ $effect(() => {
1474
2063
  {/if}
1475
2064
 
1476
2065
  <!-- Current frame indicator -->
1477
- {#if current_x_value !== null && current_x_value !== undefined}
2066
+ {#if current_x_value != null}
1478
2067
  {@const current_pos_raw = is_time_x
1479
2068
  ? x_scale_fn(new Date(current_x_value))
1480
2069
  : x_scale_fn(current_x_value)}
@@ -1854,6 +2443,7 @@ $effect(() => {
1854
2443
  tooltip_point?.point_idx === point.point_idx}
1855
2444
  is_selected={selected_point?.series_idx === point.series_idx &&
1856
2445
  selected_point?.point_idx === point.point_idx}
2446
+ leader_line_threshold={actual_label_config.leader_line_threshold}
1857
2447
  style={{
1858
2448
  symbol_type: pt?.symbol_type ?? series_default_symbol,
1859
2449
  ...pt,
@@ -1971,11 +2561,11 @@ $effect(() => {
1971
2561
  {:else}
1972
2562
  {@const hp = handler_props}
1973
2563
  {#if has_multiple_series && hp.label}<strong>{hp.label}</strong><br />{/if}
1974
- {@html point_label?.text ? `${point_label.text}<br />` : ``}
1975
- {@html hp.x_axis.label || `x`}: {hp.x_formatted}<br />
1976
- {@html hp.y_axis.label || `y`}: {hp.y_formatted}
2564
+ {@html sanitize_html(point_label?.text ? `${point_label.text}<br />` : ``)}
2565
+ {@html sanitize_html(hp.x_axis.label || `x`)}: {hp.x_formatted}<br />
2566
+ {@html sanitize_html(hp.y_axis.label || `y`)}: {hp.y_formatted}
1977
2567
  {#if hp.colorbar?.value != null}
1978
- <br />{@html hp.colorbar.title || `Color`}: {
2568
+ <br />{@html sanitize_html(hp.colorbar.title || `Color`)}: {
1979
2569
  format_value(hp.colorbar.value, hp.colorbar.tick_format || `.3~g`)
1980
2570
  }
1981
2571
  {/if}