From ad48f45ca9432c7e6208bbcaf916eb202717d477 Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Wed, 25 Nov 2026 16:49:15 -0500 Subject: [PATCH 01/16] feat(webgl): Layer-agnostic marks and `Layer`, with WebGL-only `@layerchart/webgl/webgl` Co-Authored-By: Claude Opus 5.5 --- .changeset/settings-layer-webgl.md | 5 + .changeset/webgl-layer-agnostic.md | 5 + docs/src/content/guides/bundle-size.md | 2 + docs/src/content/guides/webgl.md | 22 + .../ChartChildren/ChartChildren.base.svelte | 9 +- .../src/lib/components/layers/Layer.svelte | 22 +- .../layers/Layer.webgl.svelte.test.ts | 26 + .../layers/__fixtures__/WebGLSetting.svelte | 28 + .../src/lib/states/settings.svelte.ts | 10 +- packages/webgl/package.json | 5 + .../lib/components/Arc/Arc.shared.svelte.ts | 100 ++ .../webgl/src/lib/components/Arc/Arc.svelte | 291 +---- .../src/lib/components/Arc/Arc.webgl.svelte | 184 +++ .../lib/components/Area/Area.shared.svelte.ts | 70 ++ .../webgl/src/lib/components/Area/Area.svelte | 266 +--- .../src/lib/components/Area/Area.webgl.svelte | 190 +++ .../lib/components/Axis/Axis.shared.svelte.ts | 74 ++ .../webgl/src/lib/components/Axis/Axis.svelte | 354 +----- .../src/lib/components/Axis/Axis.webgl.svelte | 278 +++++ .../lib/components/Bars/Bars.shared.svelte.ts | 53 + .../webgl/src/lib/components/Bars/Bars.svelte | 196 +-- .../src/lib/components/Bars/Bars.webgl.svelte | 136 +++ .../lib/components/Bin/Bin.shared.svelte.ts | 63 + .../webgl/src/lib/components/Bin/Bin.svelte | 220 +--- .../src/lib/components/Bin/Bin.webgl.svelte | 151 +++ .../Contour/Contour.shared.svelte.ts | 31 + .../src/lib/components/Contour/Contour.svelte | 101 +- .../components/Contour/Contour.webgl.svelte | 63 + .../GeoPath/GeoPath.shared.svelte.ts | 61 + .../src/lib/components/GeoPath/GeoPath.svelte | 247 +--- .../components/GeoPath/GeoPath.webgl.svelte | 180 +++ .../GeoRaster/GeoRaster.shared.svelte.ts | 55 + .../lib/components/GeoRaster/GeoRaster.svelte | 295 +---- .../GeoRaster/GeoRaster.webgl.svelte | 233 ++++ .../GeoTile/GeoTile.shared.svelte.ts | 76 ++ .../src/lib/components/GeoTile/GeoTile.svelte | 1083 +---------------- .../components/GeoTile/GeoTile.webgl.svelte | 1001 +++++++++++++++ .../lib/components/Grid/Grid.shared.svelte.ts | 44 + .../webgl/src/lib/components/Grid/Grid.svelte | 180 +-- .../src/lib/components/Grid/Grid.webgl.svelte | 130 ++ .../Highlight/Highlight.shared.svelte.ts | 86 ++ .../lib/components/Highlight/Highlight.svelte | 336 +---- .../Highlight/Highlight.webgl.svelte | 238 ++++ .../lib/components/Link/Link.shared.svelte.ts | 55 + .../webgl/src/lib/components/Link/Link.svelte | 142 +-- .../src/lib/components/Link/Link.webgl.svelte | 80 ++ .../components/Points/Points.shared.svelte.ts | 85 ++ .../src/lib/components/Points/Points.svelte | 375 +----- .../lib/components/Points/Points.webgl.svelte | 284 +++++ .../Polygon/Polygon.shared.svelte.ts | 77 ++ .../src/lib/components/Polygon/Polygon.svelte | 207 +--- .../components/Polygon/Polygon.webgl.svelte | 123 ++ .../components/Raster/Raster.shared.svelte.ts | 30 + .../src/lib/components/Raster/Raster.svelte | 184 +-- .../lib/components/Raster/Raster.webgl.svelte | 147 +++ .../lib/components/Rect/Rect.shared.svelte.ts | 61 + .../webgl/src/lib/components/Rect/Rect.svelte | 184 +-- .../src/lib/components/Rect/Rect.webgl.svelte | 116 ++ .../lib/components/Rule/Rule.shared.svelte.ts | 51 + .../webgl/src/lib/components/Rule/Rule.svelte | 175 +-- .../src/lib/components/Rule/Rule.webgl.svelte | 118 ++ .../components/Spline/Spline.shared.svelte.ts | 55 + .../src/lib/components/Spline/Spline.svelte | 269 +--- .../lib/components/Spline/Spline.webgl.svelte | 208 ++++ .../lib/components/Text/Text.shared.svelte.ts | 99 ++ .../webgl/src/lib/components/Text/Text.svelte | 352 +----- .../src/lib/components/Text/Text.webgl.svelte | 247 ++++ .../components/Vector/Vector.shared.svelte.ts | 82 ++ .../src/lib/components/Vector/Vector.svelte | 276 +---- .../lib/components/Vector/Vector.webgl.svelte | 188 +++ .../src/lib/components/layers/Layer.svelte | 27 + .../components/layers/Layer.svelte.test.ts | 41 + .../components/{WebGL => layers}/WebGL.svelte | 0 .../{WebGL => layers}/WebGL.svelte.test.ts | 0 .../{WebGL => layers}/WebGLSetup.svelte | 0 .../__fixtures__/Orbit.svelte | 0 .../__fixtures__/Scatter.svelte | 0 .../layers/__fixtures__/Switched.svelte | 24 + ...-through--bind-rotate-----bind-tilt--1.png | Bin .../webgl/src/lib/contexts/scene.svelte.ts | 5 + packages/webgl/src/lib/index.ts | 11 +- packages/webgl/src/lib/webgl.ts | 70 ++ 82 files changed, 6227 insertions(+), 5421 deletions(-) create mode 100644 .changeset/settings-layer-webgl.md create mode 100644 .changeset/webgl-layer-agnostic.md create mode 100644 packages/layerchart/src/lib/components/layers/Layer.webgl.svelte.test.ts create mode 100644 packages/layerchart/src/lib/components/layers/__fixtures__/WebGLSetting.svelte create mode 100644 packages/webgl/src/lib/components/Arc/Arc.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Arc/Arc.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Area/Area.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Area/Area.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Axis/Axis.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Bars/Bars.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Bars/Bars.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Bin/Bin.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Bin/Bin.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Contour/Contour.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Contour/Contour.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoRaster/GeoRaster.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/GeoRaster/GeoRaster.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoTile/GeoTile.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/GeoTile/GeoTile.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Grid/Grid.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Highlight/Highlight.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Highlight/Highlight.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Link/Link.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Link/Link.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Points/Points.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Points/Points.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Raster/Raster.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Raster/Raster.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Rect/Rect.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Rule/Rule.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Rule/Rule.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Spline/Spline.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Text/Text.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Text/Text.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Vector/Vector.shared.svelte.ts create mode 100644 packages/webgl/src/lib/components/Vector/Vector.webgl.svelte create mode 100644 packages/webgl/src/lib/components/layers/Layer.svelte create mode 100644 packages/webgl/src/lib/components/layers/Layer.svelte.test.ts rename packages/webgl/src/lib/components/{WebGL => layers}/WebGL.svelte (100%) rename packages/webgl/src/lib/components/{WebGL => layers}/WebGL.svelte.test.ts (100%) rename packages/webgl/src/lib/components/{WebGL => layers}/WebGLSetup.svelte (100%) rename packages/webgl/src/lib/components/{WebGL => layers}/__fixtures__/Orbit.svelte (100%) rename packages/webgl/src/lib/components/{WebGL => layers}/__fixtures__/Scatter.svelte (100%) create mode 100644 packages/webgl/src/lib/components/layers/__fixtures__/Switched.svelte rename packages/webgl/src/lib/components/{WebGL => layers}/__screenshots__/Scene.svelte.test.ts/Scene-hands-orbiting-back-through--bind-rotate-----bind-tilt--1.png (100%) create mode 100644 packages/webgl/src/lib/webgl.ts diff --git a/.changeset/settings-layer-webgl.md b/.changeset/settings-layer-webgl.md new file mode 100644 index 0000000000..f986f7a9ce --- /dev/null +++ b/.changeset/settings-layer-webgl.md @@ -0,0 +1,5 @@ +--- +'layerchart': minor +--- + +feat: `settings.layer` accepts `webgl`, drawn by `@layerchart/webgl`'s `Layer` (and as `canvas` by core's, with a warning) diff --git a/.changeset/webgl-layer-agnostic.md b/.changeset/webgl-layer-agnostic.md new file mode 100644 index 0000000000..f2a782c477 --- /dev/null +++ b/.changeset/webgl-layer-agnostic.md @@ -0,0 +1,5 @@ +--- +'@layerchart/webgl': minor +--- + +feat: Layer-agnostic marks and `Layer` (adding `type="webgl"`), drawing core's versions in `Svg`, `Canvas`, and `Html` layers so one chart can switch between all four. Import from the new `@layerchart/webgl/webgl` sub-path for WebGL-only marks, without bundling core's versions diff --git a/docs/src/content/guides/bundle-size.md b/docs/src/content/guides/bundle-size.md index d06875f602..7704de2e53 100644 --- a/docs/src/content/guides/bundle-size.md +++ b/docs/src/content/guides/bundle-size.md @@ -129,6 +129,8 @@ Note that it's a flat cost per instance rather than a fixed percentage. The same So the saving matters when you render **many instances** — a scatter plot of thousands of ``s, a heatmap of ``s. For a chart with a handful of marks it won't be measurable. +`@layerchart/webgl` follows the same pattern: its marks are layer-agnostic, drawing core's versions outside a `WebGL` layer, and `@layerchart/webgl/webgl` is WebGL only. See [Switching layers](/docs/guides/webgl#switching-layers). + The `layerchart/svg`, `layerchart/canvas`, and `layerchart/html` sub-paths re-export every layer-agnostic helper too (layouts, scales, tooltip primitives, etc.), so a single per-layer import path can cover a typical chart end-to-end. ### When per-layer is worth it diff --git a/docs/src/content/guides/webgl.md b/docs/src/content/guides/webgl.md index 4af90339d2..2b2f0725d5 100644 --- a/docs/src/content/guides/webgl.md +++ b/docs/src/content/guides/webgl.md @@ -76,6 +76,28 @@ The chart lays out exactly as a flat one would: `x` across the plot's width, `y` - **Tooltips** show the row under the pointer, from the nearest mark with `tooltip` set (it's off by default, as for flat marks). Add `tooltipContext` to the chart and a `Tooltip.Root`. - **Positions on a mark** (`x`, `y`, `z`, and the like) take a data key or function through the chart's scales, or a number of pixels, as the core primitives do. Marks take their core namesakes' props, so a chart moves between `Canvas` and `WebGL` with few changes. +## Switching layers + +The marks from `@layerchart/webgl` are layer-agnostic, as core's are: each draws its WebGL version inside a `WebGL` layer, and its core namesake in an `Svg`, `Canvas`, or `Html` one. Its `Layer` adds `type="webgl"` to core's, so one chart can move between all four, or follow `settings.layer` with no `type` set. + +```svelte + + + + + + + + + +``` + +`Light` and `Surface` have no core namesake, so they're drawn only in a `WebGL` layer. Core's own `Layer` draws `settings.layer="webgl"` as `canvas`, and warns once. + +For a chart that's only ever WebGL, import from `@layerchart/webgl/webgl` instead, as `layerchart/svg` is for SVG. Its marks draw only in a `WebGL` layer (and `Layer` is `WebGL`), so the chart doesn't bundle core's versions of them: a few KB gz per chart. + ## The view The chart's `view` is the camera. `perspective` draws farther things smaller; `orthographic` keeps sizes true at any depth, as `isometric` does (see [Views](/docs/guides/views) for how they compare). Call either with options, or pass it as is for the defaults: diff --git a/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte b/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte index 0eb9b92bb0..d38bf7b835 100644 --- a/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte +++ b/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte @@ -69,6 +69,8 @@ let snippetProps = $derived({ context }); let layer = $derived(settings.layer); + // `Layer` draws `webgl` as `canvas` (`@layerchart/webgl`'s draws it with WebGL) + let layerTypeProps = $derived(layer === 'canvas' || layer === 'webgl' ? props.canvas : props.svg); {#if childrenProp} @@ -76,12 +78,7 @@ {:else} {@render belowContext?.(snippetProps)} - + - + {#if image} {/if} diff --git a/docs/src/examples/components/webgl/Light/buildings.svelte b/docs/src/examples/components/webgl/Light/buildings.svelte index c81f679855..3f6002a9e2 100644 --- a/docs/src/examples/components/webgl/Light/buildings.svelte +++ b/docs/src/examples/components/webgl/Light/buildings.svelte @@ -49,6 +49,7 @@ diff --git a/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts b/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts index 06af66fe82..3e8645b125 100644 --- a/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts @@ -53,13 +53,17 @@ export type AreaProps = { * @default 1 */ opacity?: number; + /** Opacity of its fill, with `opacity` (as the core `Area`'s `fillOpacity`) */ + fillOpacity?: number; /** - * Draw a line along the top, in the fill's color. + * Draw a line along the top: in the fill's color, or as the core `Area`'s `line` takes it, with + * its own `stroke` (a CSS color, or a key / function of the area's first row run through the + * color scale), `strokeWidth`, and `class` (ex. `{ class: 'stroke-2 stroke-primary' }`). * * @default false */ - line?: boolean; - /** @default 2 */ + line?: boolean | { stroke?: ColorProp; strokeWidth?: number; class?: string }; + /** The line's width, in pixels. @default 2 */ strokeWidth?: number; /** * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). diff --git a/packages/webgl/src/lib/components/Area/Area.webgl.svelte b/packages/webgl/src/lib/components/Area/Area.webgl.svelte index ff6e2cacec..177f66a660 100644 --- a/packages/webgl/src/lib/components/Area/Area.webgl.svelte +++ b/packages/webgl/src/lib/components/Area/Area.webgl.svelte @@ -27,6 +27,7 @@ fill, class: className, opacity = 1, + fillOpacity = 1, line = false, strokeWidth: strokeWidthProp, tooltip = false, @@ -36,7 +37,13 @@ const scene = getSceneContext(); /** What its `class` sets */ const look = $derived(scene.style(className)); - const strokeWidth = $derived(strokeWidthProp ?? look?.strokeWidth ?? 2); + /** The line's own props, when `line` gives them (as the core `Area` takes a `Spline`'s) */ + const lineProps = $derived(typeof line === 'object' ? line : null); + /** What the line's `class` sets */ + const lineLook = $derived(scene.style(lineProps?.class)); + const strokeWidth = $derived( + lineProps?.strokeWidth ?? lineLook?.strokeWidth ?? strokeWidthProp ?? look?.strokeWidth ?? 2 + ); ctx.registerComponent({ name: 'Area', @@ -133,6 +140,12 @@ })); } + /** The line's color: its own `stroke` (or its class's), else the area's */ + function lineColor(d: any, areaColor: string) { + if (lineProps?.stroke != null) return rowColor(ctx, lineProps.stroke, d, areaColor); + return lineLook?.stroke ?? areaColor; + } + createMerged({ tooltip: () => tooltip, items: () => @@ -180,11 +193,11 @@ geometry: positions.length ? geometry : null, fill: color, lines: line ? [columns.flatMap((c) => edges(c)[1])] : [], - stroke: line ? color : null, + stroke: line ? lineColor(areaRows[0], color) : null, }; }); }), - opacity: () => opacity * (look?.opacity ?? 1), + opacity: () => opacity * fillOpacity * (look?.opacity ?? 1), strokeWidth: () => strokeWidth, }); diff --git a/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts b/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts index dfb93ca3e0..2a3c1eef9e 100644 --- a/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts @@ -25,11 +25,18 @@ export type AxisLabelProps = { export type AxisProps = { /** - * Which axis: `bottom` labels `x` along the floor's front edge, `left` labels `y` along its - * side, and `back` labels `z` up a corner. Same as an `isometric` chart's. The edges turn - * to stay in front as the camera orbits. + * Which axis: `bottom` labels `x` along the floor's front edge (`top` along its back), `left` + * labels `y` along its side (`right` along the other), and `back` labels `z` up a corner. Same + * as an `isometric` chart's. The edges turn to stay in front as the camera orbits. */ - placement: 'bottom' | 'left' | 'back'; + placement: 'bottom' | 'top' | 'left' | 'right' | 'back'; + /** + * Lines across the plot at its ticks, as the core `Axis` draws them: in their CSS `stroke`, or + * the one a `class` sets + * + * @default false + */ + grid?: boolean | { stroke?: string; class?: string }; /** Title drawn beyond the tick labels */ label?: string; /** A count, values, or an interval */ diff --git a/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte b/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte index cff9494cb2..ea43858f7c 100644 --- a/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte +++ b/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte @@ -18,9 +18,11 @@ } from 'three'; import { disposeLabel, fontFamily, labelPlane } from '../../utils/labels.js'; import Text from '../Text/Text.webgl.svelte'; + import Grid from '../Grid/Grid.webgl.svelte'; let { placement, + grid = false, label, ticks, tickSpacing: tickSpacingProp, @@ -43,56 +45,71 @@ // Its labels lie beside the plot box, so aren't clipped to it setUnclipped(); - const scale = $derived( - placement === 'bottom' ? ctx.xScale : placement === 'left' ? ctx.yScale : ctx.zScale - ); - const length = $derived( - placement === 'bottom' ? ctx.width : placement === 'left' ? ctx.height : ctx.zDepth + /** Along `x` (`bottom` / `top`), or `y` (`left` / `right`), else the height `z` (`back`) */ + const along = $derived( + placement === 'bottom' || placement === 'top' + ? 'x' + : placement === 'left' || placement === 'right' + ? 'y' + : 'z' ); + const scale = $derived(along === 'x' ? ctx.xScale : along === 'y' ? ctx.yScale : ctx.zScale); + const length = $derived(along === 'x' ? ctx.width : along === 'y' ? ctx.height : ctx.zDepth); // Spaced as the core `Axis` spaces them const spacing = $derived( - tickSpacingProp !== undefined - ? tickSpacingProp - : tickSpacing(ctx, placement === 'bottom' ? 'x' : placement === 'left' ? 'y' : 'z') + tickSpacingProp !== undefined ? tickSpacingProp : tickSpacing(ctx, along) ); const count = $derived(spacing ? tickCount(length, spacing) : undefined); const values = $derived(autoTickVals(scale, ticks, count)); const formatTick = $derived(tickFormat({ scale, ticks, count, formatType: format })); - /** The floor's edges nearest the camera, which way is out from the plot box, and the corner `z` stands up */ + /** + * The floor's edges the axis lies along (the ones nearest the camera, else across from them), + * which way is out from the plot box, and the corner `z` stands up + */ const edges = $derived.by(() => { const w = ctx.width; const h = ctx.height; const nearX = scene.far.x === 'min' ? w : 0; const nearY = scene.far.y === 'min' ? h : 0; // `z` stands up the corner where the wall behind on `x` meets the front + const outX = nearX === w ? 1 : -1; + const outY = nearY === h ? 1 : -1; return { - nearX, + // The edge a `right` / `top` axis is on: the other side, facing out the other way + edgeX: placement === 'right' ? w - nearX : nearX, + edgeY: placement === 'top' ? h - nearY : nearY, + outX: placement === 'right' ? -outX : outX, + outY: placement === 'top' ? -outY : outY, nearY, - outX: nearX === w ? 1 : -1, - outY: nearY === h ? 1 : -1, farX: w - nearX, }; }); + /** The grid's stroke: its own, or the one its `class` sets (else `Grid`'s) */ + const gridStroke = $derived.by(() => { + if (typeof grid !== 'object') return undefined; + return grid.stroke ?? scene.style(grid.class)?.stroke ?? undefined; + }); + /** Pixels of the plot that read as one on screen, so marks and gaps keep their size in 3D */ const unit = $derived(scene.unit); const labels = $derived.by((): SceneLabel[] => { const w = ctx.width; const h = ctx.height; - const { nearX, nearY, outX, outY, farX } = edges; + const { edgeX, edgeY, nearY, outX, outY, farX } = edges; // On the floor, labels across are placed by their middle (half a label further out), and the // left axis' by their end. Facing the viewer, they're at the edge, anchored by their side // nearest it a gap of pixels away on screen, so the gap is the same however the view turns. - const half = (placement === 'left' ? 0 : 6) * unit; + const half = (along === 'y' ? 0 : 6) * unit; const tickOut = tickViewport ? 0 : tickLabelOffset * unit + half; - const outward = placement === 'left' ? { x: outX, y: 0, z: 0 } : { x: 0, y: outY, z: 0 }; + const outward = along === 'y' ? { x: outX, y: 0, z: 0 } : { x: 0, y: outY, z: 0 }; const at = (value: unknown): [number, number, number] => { const p = scaled(scale, value); - if (placement === 'bottom') return [p, nearY + outY * tickOut, 0]; - if (placement === 'left') return [nearX + outX * tickOut, p, 0]; + if (along === 'x') return [p, edgeY + outY * tickOut, 0]; + if (along === 'y') return [edgeX + outX * tickOut, p, 0]; return [farX, nearY + outY * tickOut, p]; }; @@ -111,15 +128,13 @@ if (label) { // Beyond the tick labels (facing the viewer, past as far as they reach out from the edge) - const titleOffset = labelViewport - ? 0 - : (tickLabelOffset + (placement === 'bottom' ? 26 : 34)) * unit; + const titleOffset = labelViewport ? 0 : (tickLabelOffset + (along === 'x' ? 26 : 34)) * unit; const [x, y, z] = - placement === 'bottom' - ? [w / 2, nearY + outY * titleOffset, 0] - : placement === 'left' - ? [nearX + outX * titleOffset, h / 2, 0] - : [farX, nearY + outY * titleOffset, ctx.zDepth / 2]; + along === 'x' + ? [w / 2, edgeY + outY * titleOffset, 0] + : along === 'y' + ? [edgeX + outX * titleOffset, h / 2, 0] + : [farX, nearY + edges.outY * titleOffset, ctx.zDepth / 2]; result.push({ key: `${placement}-label`, x, @@ -160,22 +175,22 @@ const w = ctx.width; const h = ctx.height; const d = ctx.zDepth; - const { nearX, nearY, outX, outY, farX } = edges; + const { edgeX, edgeY, nearY, outX, outY, farX } = edges; const reach = tickLength * unit; const segments: number[] = []; - if (placement === 'bottom') { - if (rule) segments.push(0, 0, nearY, w, 0, nearY); + if (along === 'x') { + if (rule) segments.push(0, 0, edgeY, w, 0, edgeY); if (tickMarks) for (const v of values) { const p = scaled(scale, v); - segments.push(p, 0, nearY, p, 0, nearY + outY * reach); + segments.push(p, 0, edgeY, p, 0, edgeY + outY * reach); } - } else if (placement === 'left') { - if (rule) segments.push(nearX, 0, 0, nearX, 0, h); + } else if (along === 'y') { + if (rule) segments.push(edgeX, 0, 0, edgeX, 0, h); if (tickMarks) for (const v of values) { const p = scaled(scale, v); - segments.push(nearX, 0, p, nearX + outX * reach, 0, p); + segments.push(edgeX, 0, p, edgeX + outX * reach, 0, p); } } else if (d > 0) { if (rule) segments.push(farX, 0, nearY, farX, d, nearY); @@ -253,15 +268,27 @@ }); /** - * A label lying on the floor: the left axis' end at it (away from the plot, on whichever side - * it's on), the others centered + * A label lying on the floor: a `left` / `right` axis' end at it (away from the plot, on + * whichever side it's on), the others centered */ function anchorOf(l: SceneLabel): 'start' | 'middle' | 'end' { - if (placement !== 'left') return 'middle'; + if (along !== 'y') return 'middle'; return l.x < ctx.width / 2 ? 'end' : 'start'; } +{#if grid && along !== 'z'} + +{/if} + {#if placement !== 'back'} {#each floorLabels as l (l.key)} & { + /** The row */ + data: any; +}; diff --git a/packages/webgl/src/lib/components/Bar/Bar.svelte b/packages/webgl/src/lib/components/Bar/Bar.svelte new file mode 100644 index 0000000000..ebd921eb69 --- /dev/null +++ b/packages/webgl/src/lib/components/Bar/Bar.svelte @@ -0,0 +1,24 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Bar/Bar.webgl.svelte b/packages/webgl/src/lib/components/Bar/Bar.webgl.svelte new file mode 100644 index 0000000000..9577aaf685 --- /dev/null +++ b/packages/webgl/src/lib/components/Bar/Bar.webgl.svelte @@ -0,0 +1,11 @@ + + + + + diff --git a/packages/webgl/src/lib/components/Bars/Bars.base.svelte b/packages/webgl/src/lib/components/Bars/Bars.base.svelte index 56c62f9c61..0d812503c4 100644 --- a/packages/webgl/src/lib/components/Bars/Bars.base.svelte +++ b/packages/webgl/src/lib/components/Bars/Bars.base.svelte @@ -2,10 +2,13 @@ import type { BarsProps } from './Bars.shared.svelte.js'; + + + + + +{#if children} + {@render children()} +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts b/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts new file mode 100644 index 0000000000..8bc412e885 --- /dev/null +++ b/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts @@ -0,0 +1,54 @@ +import type { ColorProp, DataProp } from 'layerchart'; + +export type CircleProps = { + /** Rows to draw a circle each for (else the chart's, when a position reads them) */ + data?: any[]; + /** + * The center across: a number of pixels, or a data key / function through the chart's `x` + * scale (a circle per row) + * + * @default 0 + */ + cx?: DataProp; + /** + * The center down: a number of pixels, or a data key / function through the chart's `y` + * scale (a circle per row) + * + * @default 0 + */ + cy?: DataProp; + /** + * The radius: a number of pixels, or a data key / function through the chart's `r` scale + * + * @default 1 + */ + r?: DataProp; + /** + * Its height off the floor: a number of pixels, or a data key / function through the chart's + * `z` scale. Flat on the floor without one. + */ + z?: DataProp; + /** + * A CSS color, or a data key / function run through the chart's color scale. + * + * @default 'var(--color-surface-content)' + */ + fill?: ColorProp; + /** A ring around it, in a CSS color or a data key / function run through the color scale */ + stroke?: ColorProp; + /** The ring's width, in pixels. @default 1 */ + strokeWidth?: number; + /** + * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): + * the fill, stroke, stroke width, and opacity they set, where its props don't say + */ + class?: string; + /** @default 1 */ + opacity?: number; + /** + * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). + * + * @default false + */ + tooltip?: boolean; +}; diff --git a/packages/webgl/src/lib/components/Circle/Circle.svelte b/packages/webgl/src/lib/components/Circle/Circle.svelte new file mode 100644 index 0000000000..d64c8ff89e --- /dev/null +++ b/packages/webgl/src/lib/components/Circle/Circle.svelte @@ -0,0 +1,24 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte b/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte new file mode 100644 index 0000000000..c848b9163d --- /dev/null +++ b/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte @@ -0,0 +1,95 @@ + + + diff --git a/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts b/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts index 4141d3b007..d22a673ac2 100644 --- a/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts +++ b/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts @@ -24,14 +24,15 @@ export type GeoPathProps = { z?: DataProp; /** * A CSS color, or a function of the feature returning one (or a value for the chart's color - * scale). Lines have no fill. - * - * @default 'color-mix(in oklab, var(--color-surface-content) 15%, var(--color-surface-100))' + * scale). Lines have no fill. None by default, as the core `GeoPath` (`null` for none where + * a `class` sets one). */ fill?: ColorProp | null; /** * The outlines' color: a CSS color, or a data key / function of the feature run through the - * chart's color scale. No outlines without one. + * chart's color scale (`null` for none). + * + * @default 'var(--color-surface-content)' */ stroke?: ColorProp | null; /** diff --git a/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte b/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte index 011d91cd55..c608f13f86 100644 --- a/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte +++ b/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte @@ -36,10 +36,18 @@ const scene = getSceneContext(); /** What its `class` sets, where its props don't say */ const look = $derived(scene.style(className)); + // As the core `GeoPath`: no fill and a `surface-content` outline, unless its props or `class` + // say otherwise (`null` for none) const fill = $derived( - fillProp !== undefined ? fillProp : look?.fill === 'none' ? null : (look?.fill ?? defaultFill) + fillProp !== undefined ? fillProp : look?.fill === 'none' ? null : (look?.fill ?? null) + ); + const stroke = $derived( + strokeProp !== undefined + ? strokeProp + : look?.stroke === 'none' + ? null + : (look?.stroke ?? 'var(--color-surface-content, currentColor)') ); - const stroke = $derived(strokeProp ?? look?.stroke); const strokeWidth = $derived(strokeWidthProp ?? look?.strokeWidth ?? 1); /** On a `globe`, features draw over it as lines */ const sphere = $derived(getSphere(ctx)); diff --git a/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts b/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts new file mode 100644 index 0000000000..8ca2bd9476 --- /dev/null +++ b/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts @@ -0,0 +1,14 @@ +import type { GeoPathProps } from '../GeoPath/GeoPath.shared.svelte.js'; + +type LineProps = Partial>; + +export type GraticuleProps = { + /** Each meridian and parallel as its own line, styled by these (or the graticule's) props */ + lines?: LineProps | boolean; + /** The graticule's outline, styled by these (or the graticule's) props */ + outline?: LineProps | boolean; + /** Degrees between meridians. @default 10 */ + stepX?: number; + /** Degrees between parallels. @default 10 */ + stepY?: number; +} & LineProps; diff --git a/packages/webgl/src/lib/components/Graticule/Graticule.svelte b/packages/webgl/src/lib/components/Graticule/Graticule.svelte new file mode 100644 index 0000000000..5fb9fef5f5 --- /dev/null +++ b/packages/webgl/src/lib/components/Graticule/Graticule.svelte @@ -0,0 +1,24 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte b/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte new file mode 100644 index 0000000000..b3374afa9e --- /dev/null +++ b/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte @@ -0,0 +1,28 @@ + + + + + +{#if !lines && !outline} + +{/if} + +{#if lines} + {#each graticule.lines() as line} + + {/each} +{/if} + +{#if outline} + +{/if} diff --git a/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts b/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts index 11301fae09..3ee965ae93 100644 --- a/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts @@ -2,8 +2,11 @@ import type { ColorProp, DataProp } from 'layerchart'; import type { ValueProp } from '../../utils/values.js'; export type LinkProps = { - /** Rows to draw a link each for. Falls back to the chart's data when `x1` / `y1` read rows. */ - data?: any[]; + /** + * Rows to draw a link each for, or one link (as the core `Link` takes it). Falls back to the + * chart's data when `x1` / `y1` read rows. + */ + data?: any[] | any; /** * Where each link starts across the plot: a data property name or function of the row * through the chart's `x` scale (longitude on a map), or pixels @@ -52,4 +55,9 @@ export type LinkProps = { stroke?: ColorProp; /** @default 1 */ strokeWidth?: number; + /** + * CSS classes to style it by, as the core marks take them (ex. `stroke-surface-content/20`): + * the stroke, stroke width, and opacity they set, where its props don't say + */ + class?: string; }; diff --git a/packages/webgl/src/lib/components/Link/Link.webgl.svelte b/packages/webgl/src/lib/components/Link/Link.webgl.svelte index 4f300ba80a..081369b028 100644 --- a/packages/webgl/src/lib/components/Link/Link.webgl.svelte +++ b/packages/webgl/src/lib/components/Link/Link.webgl.svelte @@ -4,6 +4,7 @@ diff --git a/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts b/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts index 7e6938d1f9..e013e7af44 100644 --- a/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts @@ -54,7 +54,7 @@ export type PolygonProps = { /** * A CSS color, or a key / function of the row run through the chart's color scale. * - * @default 'var(--color-primary)' + * @default 'var(--color-surface-content)' */ fill?: ColorProp; /** The outline: a CSS color, or a key / function of the row run through the color scale */ diff --git a/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte b/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte index cd683aa5d6..f96da6af5b 100644 --- a/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte +++ b/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte @@ -109,7 +109,7 @@ return { d, geometry: (fill ?? look?.fill) === 'none' ? null : extrude(context, z0, z1), - fill: rowColor(ctx, fill, d, 'var(--color-primary, currentColor)', look?.fill), + fill: rowColor(ctx, fill, d, 'var(--color-surface-content, currentColor)', look?.fill), lines: context.lines.map((line) => line.flatMap(([x, y]) => [x, outline, y])), stroke: stroke == null && !look?.stroke diff --git a/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts b/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts index d32eecd493..a3bb43e24f 100644 --- a/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts @@ -34,7 +34,7 @@ export type RectProps = { /** * A CSS color, or a key / function of the row run through the chart's color scale. * - * @default 'var(--color-primary)' + * @default 'var(--color-surface-content)' */ fill?: ColorProp; /** diff --git a/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte b/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte index 9578fa6881..eb60eac6f1 100644 --- a/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte +++ b/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte @@ -87,7 +87,7 @@ ...footprint(d), z: base, height: top - base, - color: rowColor(ctx, fill, d, 'var(--color-primary, currentColor)', look?.fill), + color: rowColor(ctx, fill, d, 'var(--color-surface-content, currentColor)', look?.fill), }; }) ); diff --git a/packages/webgl/src/lib/components/__fixtures__/Marks.svelte b/packages/webgl/src/lib/components/__fixtures__/Marks.svelte index bb7448fdb0..7a796a6da7 100644 --- a/packages/webgl/src/lib/components/__fixtures__/Marks.svelte +++ b/packages/webgl/src/lib/components/__fixtures__/Marks.svelte @@ -7,6 +7,7 @@ Axis, Bars, Bin, + Circle, Chart, Contour, GeoPath, @@ -36,6 +37,7 @@ surface, geopath, bin, + circle, light, text, rect, @@ -60,6 +62,7 @@ | 'geopath' | 'light' | 'bin' + | 'circle' | 'text' | 'rect' | 'link' @@ -80,6 +83,7 @@ surface?: ComponentProps; geopath?: ComponentProps; bin?: ComponentProps; + circle?: ComponentProps; light?: ComponentProps; text?: ComponentProps; rect?: ComponentProps; @@ -113,6 +117,8 @@ {:else if mark === 'bin'} + {:else if mark === 'circle'} + {:else if mark === 'text'} {:else if mark === 'rect'} diff --git a/packages/webgl/src/lib/components/marks.svelte.test.ts b/packages/webgl/src/lib/components/marks.svelte.test.ts index 5f16dc1233..89c3e6213e 100644 --- a/packages/webgl/src/lib/components/marks.svelte.test.ts +++ b/packages/webgl/src/lib/components/marks.svelte.test.ts @@ -164,6 +164,19 @@ describe('Spline and Area, as LayerChart draws them', () => { expect(Math.max(...downs)).toBeCloseTo(chart!.yScale(0), 0); expect(Math.min(...downs)).toBeCloseTo(chart!.yScale(7), 0); }); + + it('draws an `Area`’s `line` with its own `stroke` and `strokeWidth`, as the core `Area` takes it', async () => { + const scene = await renderMarks({ + mark: 'area', + chart: { ...chartProps, data: series.filter((d) => d.y != null) }, + area: { line: { stroke: 'rgb(255, 0, 0)', strokeWidth: 3 } }, + }); + const lines = () => layered(scene).find((o) => (o as any).isLineSegments2) as any; + await expect.poll(() => lines()?.visible).toBe(true); + expect(lines().material.linewidth).toBe(3); + const [r, g, b] = lines().geometry.attributes.instanceColorStart.array; + expect([r, g, b]).toEqual([1, 0, 0]); + }); }); describe('Polygon, as LayerChart draws it', () => { @@ -876,7 +889,7 @@ describe('GeoPath', () => { const scene = await renderMarks({ mark: 'geopath', chart: { geo: { projection: geoIdentity } }, - geopath: { geojson: square, z: 20 }, + geopath: { geojson: square, z: 20, fill: 'gray' }, }); const mesh = layered(scene).find((o: any) => o.isMesh) as any; await expect.poll(() => mesh.geometry.getAttribute('position')?.count ?? 0).toBeGreaterThan(0); @@ -1259,6 +1272,56 @@ describe('placed as LayerChart places its namesakes', () => { const ends = Array.from(segments.geometry.attributes.instanceStart.data.array as Float32Array); expect(ends.slice(0, 6)).toEqual([10, 0, 20, 30, 0, 40]); }); + + it('links one link given as `data`, in its `class`’s stroke, as the core `Link` takes it', async () => { + const style = document.createElement('style'); + style.textContent = '.test-link { stroke: rgb(255, 0, 0) }'; + document.head.append(style); + try { + const scene = await renderMarks({ + mark: 'link', + chart: chartProps, + link: { + data: { source: { x: 10, y: 20 }, target: { x: 30, y: 40 } }, + class: 'test-link', + }, + }); + const segments = () => layered(scene).find((o) => (o as any).isLineSegments2) as any; + await expect.poll(() => segments()?.geometry.attributes.instanceStart?.count ?? 0).toBe(1); + const [r, g, b] = segments().geometry.attributes.instanceColorStart.array; + expect([r, g, b]).toEqual([1, 0, 0]); + } finally { + style.remove(); + } + }); + + it('draws a `Circle` at `cx` / `cy` pixels, and through the scales with rows', async () => { + const center = (scene: SceneState, i = 0) => { + const matrix = new Matrix4(); + (children(scene, 'isInstancedMesh')[0] as InstancedMesh).getMatrixAt(i, matrix); + const position = new Vector3(); + const size = new Vector3(); + matrix.decompose(position, new Quaternion(), size); + return { x: position.x, y: position.z, r: size.x }; + }; + const pixels = await renderMarks({ + mark: 'circle', + chart: chartProps, + circle: { cx: 40, cy: 30, r: 6 }, + }); + expect(center(pixels)).toEqual({ x: 40, y: 30, r: 6 }); + + const scene = await renderMarks({ + mark: 'circle', + chart: chartProps, + circle: { data: rows, cx: 'x', cy: 'y', r: 4 }, + }); + await expect + .poll(() => (children(scene, 'isInstancedMesh')[0] as InstancedMesh)?.count) + .toBe(rows.length); + expect(center(scene).x).toBeCloseTo(chart!.xScale(rows[0].x)); + expect(center(scene).y).toBeCloseTo(chart!.yScale(rows[0].y)); + }); }); describe('Axis', () => { @@ -1282,6 +1345,53 @@ describe('Axis', () => { return found; }; + /** The axis' rule and tick marks (and not a `Grid`'s lines), as `[x, height, y]` pairs */ + const ruleSegments = (scene: SceneState) => { + const lines = layered(scene).find((o) => (o as any).isLineSegments) as any; + const positions = Array.from( + (lines?.geometry.getAttribute('position')?.array as Float32Array) ?? [] + ); + return Array.from({ length: positions.length / 6 }, (_, i) => + positions.slice(i * 6, i * 6 + 6).map((v) => Math.round(v)) + ); + }; + const flat = { ...chartProps, view: undefined, z: undefined, transform: undefined }; + + it('draws a `top` / `right` axis along the edges across from `bottom` / `left`', async () => { + const top = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'top', ticks: [], rule: true }, + }); + await expect.poll(() => ruleSegments(top)).toEqual([[0, 0, 0, Math.round(chart!.width), 0, 0]]); + + const right = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'right', ticks: [], rule: true }, + }); + const w = Math.round(chart!.width); + await expect + .poll(() => ruleSegments(right)) + .toEqual([[w, 0, 0, w, 0, Math.round(chart!.height)]]); + }); + + it('draws a `grid` across the plot at its ticks, as the core `Axis`', async () => { + const lineSets = (scene: SceneState) => + layered(scene).filter((o) => (o as any).isLineSegments || (o as any).isLineSegments2).length; + const plain = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'left', ticks: [0, 5, 10] }, + }); + const gridded = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'left', ticks: [0, 5, 10], grid: true }, + }); + await expect.poll(() => lineSets(gridded)).toBeGreaterThan(lineSets(plain)); + }); + it('lays the floor’s tick labels on it, as an `isometric` chart’s', async () => { const scene = await renderMarks({ mark: 'axis', @@ -2133,7 +2243,12 @@ describe('GeoPath motion', () => { const { rerender } = render(Marks, { mark: 'geopath', chart: { geo: { projection: geoIdentity as any } }, - geopath: { geojson: square(10), z: 10, motion: { type: 'tween', duration: 400 } }, + geopath: { + geojson: square(10), + z: 10, + fill: 'gray', + motion: { type: 'tween', duration: 400 }, + }, onScene: (s: SceneState) => (scene = s), }); await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); @@ -2145,7 +2260,12 @@ describe('GeoPath motion', () => { await expect.poll(top).toBeCloseTo(10); await rerender({ - geopath: { geojson: square(40), z: 40, motion: { type: 'tween', duration: 400 } }, + geopath: { + geojson: square(40), + z: 40, + fill: 'gray', + motion: { type: 'tween', duration: 400 }, + }, }); // Partway there, then all the way await expect.poll(top).toBeGreaterThan(11); @@ -2186,6 +2306,42 @@ describe('strokes, as LayerChart’s marks take them', () => { expect((instanced(scene)[0].material as any).polygonOffset).toBe(true); }); + const columns = { + data: [ + { x: 'a', y: 4 }, + { x: 'b', y: 8 }, + ], + x: 'x', + xScale: scaleBand().padding(0.2), + xDomain: ['a', 'b'], + y: 'y', + yDomain: [0, 10], + }; + + it('draws `Bars` without a `z` as LayerChart’s 2D bars, flat on the floor', async () => { + const scene = await renderMarks({ mark: 'bars', chart: columns, bars: { insets: { x: 2 } } }); + await expect.poll(() => instanced(scene)[0]?.count ?? 0).toBe(2); + const matrix = new Matrix4(); + instanced(scene)[0].getMatrixAt(1, matrix); + const position = new Vector3(); + const size = new Vector3(); + matrix.decompose(position, new Quaternion(), size); + // Across its band (less its insets), and from the baseline up to its value + expect(position.x).toBeCloseTo((chart!.xScale as any)('b') + 2); + expect(size.x).toBeCloseTo((chart!.xScale as any).bandwidth() - 4); + expect(position.z).toBeCloseTo(chart!.yScale(8)); + expect(size.z).toBeCloseTo(chart!.yScale(0) - chart!.yScale(8)); + expect(size.y).toBeLessThan(1); + }); + + it('outlines `Bars` with a `strokeWidth` alone, as LayerChart’s bars', async () => { + const plain = await renderMarks({ mark: 'bars', chart: columns }); + expect(segments(plain)).toBe(0); + const scene = await renderMarks({ mark: 'bars', chart: columns, bars: { strokeWidth: 1 } }); + // Flat, only around each bar's top: its four sides + await expect.poll(() => segments(scene)).toBe(8); + }); + it('outlines `Bin` cells around their tops and up their corners', async () => { const scene = await renderMarks({ mark: 'bin', diff --git a/packages/webgl/src/lib/index.ts b/packages/webgl/src/lib/index.ts index a359112bd6..b306b7ac79 100644 --- a/packages/webgl/src/lib/index.ts +++ b/packages/webgl/src/lib/index.ts @@ -19,6 +19,12 @@ export { default as Layer } from './components/layers/Layer.svelte'; export type { LayerProps } from './components/layers/Layer.svelte'; export { default as Axis } from './components/Axis/Axis.svelte'; export type { AxisProps, AxisLabelProps } from './components/Axis/Axis.svelte'; +export { default as Bar } from './components/Bar/Bar.svelte'; +export type { BarProps } from './components/Bar/Bar.svelte'; +export { default as Circle } from './components/Circle/Circle.svelte'; +export type { CircleProps } from './components/Circle/Circle.svelte'; +export { default as Graticule } from './components/Graticule/Graticule.svelte'; +export type { GraticuleProps } from './components/Graticule/Graticule.svelte'; export { default as Bars } from './components/Bars/Bars.svelte'; export { default as Bin } from './components/Bin/Bin.svelte'; export type { BinProps } from './components/Bin/Bin.svelte'; diff --git a/packages/webgl/src/lib/webgl.ts b/packages/webgl/src/lib/webgl.ts index c216fdff11..4a8495198d 100644 --- a/packages/webgl/src/lib/webgl.ts +++ b/packages/webgl/src/lib/webgl.ts @@ -14,6 +14,12 @@ export { default as WebGL, default as Layer } from './components/layers/WebGL.sv export type { WebGLProps, WebGLPropsWithoutHTML } from './components/layers/WebGL.svelte'; export { default as Axis } from './components/Axis/Axis.webgl.svelte'; export type { AxisProps, AxisLabelProps } from './components/Axis/Axis.svelte'; +export { default as Bar } from './components/Bar/Bar.webgl.svelte'; +export type { BarProps } from './components/Bar/Bar.svelte'; +export { default as Circle } from './components/Circle/Circle.webgl.svelte'; +export type { CircleProps } from './components/Circle/Circle.svelte'; +export { default as Graticule } from './components/Graticule/Graticule.webgl.svelte'; +export type { GraticuleProps } from './components/Graticule/Graticule.svelte'; export { default as Bars } from './components/Bars/Bars.webgl.svelte'; export { default as Bin } from './components/Bin/Bin.webgl.svelte'; export type { BinProps } from './components/Bin/Bin.svelte'; From 4edf47d9e41c6b6636bd9f0f40aa8ace8b0351a7 Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Wed, 25 Nov 2026 19:13:54 -0500 Subject: [PATCH 04/16] docs: Draw core examples with WebGL from the layer toggle Co-Authored-By: Claude Opus 5.5 --- docs/src/lib/components/Example.svelte | 58 ++++- docs/src/lib/components/LayerSetting.svelte | 20 ++ docs/src/lib/components/PageHeader.svelte | 28 ++- docs/src/lib/webglExamples.test.ts | 58 +++++ .../docs/components/[name]/+layout.svelte | 13 +- docs/src/webgl-examples.d.ts | 10 + docs/vite-plugin-webgl-examples.ts | 151 +++++++++++ docs/vite.config.ts | 7 + docs/webgl-examples.ts | 237 ++++++++++++++++++ 9 files changed, 572 insertions(+), 10 deletions(-) create mode 100644 docs/src/lib/components/LayerSetting.svelte create mode 100644 docs/src/lib/webglExamples.test.ts create mode 100644 docs/src/webgl-examples.d.ts create mode 100644 docs/vite-plugin-webgl-examples.ts create mode 100644 docs/webgl-examples.ts diff --git a/docs/src/lib/components/Example.svelte b/docs/src/lib/components/Example.svelte index 1de7cb6a10..f304ddfb1d 100644 --- a/docs/src/lib/components/Example.svelte +++ b/docs/src/lib/components/Example.svelte @@ -46,6 +46,8 @@ const settings = getSettings(); import { movable } from '$lib/actions/movable'; + import { webglExamples } from 'virtual:webgl-examples'; + import LayerSetting from '$lib/components/LayerSetting.svelte'; let { // The page's component: its folder under `src/examples/components` (ex. `webgl/Points`) @@ -77,7 +79,7 @@ const examplesCtx = examples.get(); // Use $state + $effect to break potential infinite reactivity loops during HMR - let example = $state<{ component: any; source: string } | undefined>(undefined); + let loadedExample = $state<{ component: any; source: string } | undefined>(undefined); $effect(() => { const current = examplesCtx?.current; @@ -99,12 +101,39 @@ // Only assign if the reference actually changed to avoid unnecessary downstream reactivity // Untrack both the read and write to prevent this effect from depending on its own output untrack(() => { - if (example !== next) { - example = next; + if (loadedExample !== next) { + loadedExample = next; } }); }); + /** + * With the layer toggle on `WebGL`, this example's WebGL version (its components imported from + * `@layerchart/webgl`), if it has one. Examples without one draw with Canvas, as LayerChart's + * `Layer` would. + */ + const loadWebGL = $derived( + settings.layer === 'webgl' && component && name && !path + ? webglExamples[`${component}/${name}`] + : undefined + ); + let webglExample = $state<{ component: any; source: string } | undefined>(undefined); + $effect(() => { + const load = loadWebGL; + webglExample = undefined; + if (!load) return; + let current = true; + load().then((loaded) => { + if (current) webglExample = loaded; + }); + return () => { + current = false; + }; + }); + const example = $derived(webglExample ?? loadedExample); + /** Drawn with Canvas while the layer is `webgl`: no WebGL version (or not loaded yet) */ + const canvasInstead = $derived(settings.layer === 'webgl' && !webglExample); + /** * Code beside the preview rather than below it. Only offered with room for both, and * only while the code is showing; the toggle is in the code panel's menu. @@ -322,7 +351,13 @@ > {/if} {#if !sandbox.showing && example} - + {#if canvasInstead} + + + + {:else} + + {/if} {/if} {#snippet failed(error, reset)}
@@ -378,7 +413,12 @@ bind:lineNumbers {highlight} onopenstackblitz={component && name - ? () => openInStackBlitz(component, name, sandbox.dirty ? sandbox.source : undefined) + ? () => + openInStackBlitz( + component, + name, + sandbox.dirty ? sandbox.source : webglExample?.source + ) : undefined} {split} onsplitchange={wide.current ? setSplit : undefined} @@ -467,7 +507,7 @@ openPngDialog('export')}> Export as PNG - {#if settings.layer !== 'canvas'} + {#if settings.layer !== 'canvas' && settings.layer !== 'webgl'} Copy as SVG Export as SVG @@ -476,6 +516,12 @@ + + {#if settings.layer === 'webgl' && !loadWebGL} + No WebGL version: drawn with Canvas + {/if}
{/if} {:else} diff --git a/docs/src/lib/components/LayerSetting.svelte b/docs/src/lib/components/LayerSetting.svelte new file mode 100644 index 0000000000..50c956ea9f --- /dev/null +++ b/docs/src/lib/components/LayerSetting.svelte @@ -0,0 +1,20 @@ + + +{@render children()} diff --git a/docs/src/lib/components/PageHeader.svelte b/docs/src/lib/components/PageHeader.svelte index d609b67a7f..075326e83e 100644 --- a/docs/src/lib/components/PageHeader.svelte +++ b/docs/src/lib/components/PageHeader.svelte @@ -15,6 +15,7 @@ import LucideChevronRight from '~icons/lucide/chevron-right'; import LucideSettings from '~icons/lucide/settings'; import LucideArrowUpToLine from '~icons/lucide/arrow-up-to-line'; + import LucideBox from '~icons/lucide/box'; type Crumb = { label: string; href?: string }; type TocItem = { id: string; text: string; level: number }; @@ -32,7 +33,7 @@ title: string; breadcrumbs?: Crumb[]; description?: string; - /** Layers offered by the page-wide Svg/Canvas/Html toggle (hidden when empty; a single layer is shown selected) */ + /** Layers offered by the page-wide Svg/Canvas/Html/WebGL toggle (hidden when empty; a single layer is shown selected) */ layers?: string[]; /** Passed to `OpenWithButton` */ metadata?: Record; @@ -60,11 +61,19 @@ return layers.length === 1 ? layers[0] : settings.layer; }, set current(value) { - // `webgl` is a page, not a setting - if (value !== 'webgl') settings.layer = value; + // A layer of this page's is a setting (`webgl` included, for its examples drawn with + // WebGL), and the counterpart's another page + if (value !== 'webgl' || layers.includes(value)) + settings.layer = value as typeof settings.layer; if (counterpart && !layers.includes(value)) goto(counterpart.href); } }; + // With WebGL a setting here, the toggle stays on the page: the counterpart's is a link beside it + const counterpartLink = $derived( + counterpart && layers.includes('webgl') && counterpart.layers.includes('webgl') + ? counterpart.href + : undefined + ); const origin = $derived(dev ? 'https://layerchart.com' : page.url.origin); const url = $derived(`${origin}${page.url.pathname}`); const toc = $derived(page.data.metadata?.toc ?? []); @@ -290,6 +299,19 @@ + + {#if counterpartLink} + + - {#if settings.layer === 'webgl' && !loadWebGL} + {#if settings.layer === 'webgl' && !loadWebGL && !nativeWebGL} No WebGL version: drawn with Canvas diff --git a/docs/src/lib/components/PageHeader.svelte b/docs/src/lib/components/PageHeader.svelte index 075326e83e..794846e759 100644 --- a/docs/src/lib/components/PageHeader.svelte +++ b/docs/src/lib/components/PageHeader.svelte @@ -1,7 +1,6 @@ + + + + +{#if marker || markerStart || markerMid || markerEnd} + + outlines() + .filter((outline) => outline.color) + .map((outline) => ({ + points: outline.subpaths.flat(), + color: outline.color!, + // Each vertex between its ends (its pieces' too, as an SVG path's subpaths') + get mids() { + return outline.vertices().slice(1, -1); + }, + }))} + {strokeWidth} + {opacity} + /> +{/if} + +{#if startContent || endContent} + {#each outlines() as outline, i (i)} + {@const ends = pathEnds(outline.subpaths, progress[i])} + {#if ends} + + {/if} + {/each} +{/if} diff --git a/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts b/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts index 073ed4b812..6085e82ae9 100644 --- a/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Area/Area.shared.svelte.ts @@ -1,21 +1,17 @@ +import type { Snippet } from 'svelte'; +import type { draw as drawTransition } from 'svelte/transition'; import type { MotionProp } from 'layerchart/utils/motion.svelte'; import type { Accessor, ColorProp, DataProp } from 'layerchart'; import type { CurveFactory } from 'd3-shape'; +import type { MarkerOptions } from '../Line/markers.js'; +/** + * The core `Area`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`y`, `z0`, `tooltip`) + */ export type AreaProps = { - /** Override the chart's `data` */ + /** Override data instead of using context */ data?: any[]; - /** Override the chart's `x` accessor */ - x?: Accessor; - /** Override the chart's `y` accessor */ - y?: Accessor; - /** - * The area's base down the plot, as the core `Area`: an accessor of the row. Defaults to - * a stacked row's base, else the bottom of the plot. - */ - y0?: Accessor; - /** The area's top down the plot, likewise. Defaults to a stacked row's top, else `y`. */ - y1?: Accessor; /** * Stand the area up as a curtain off the floor at each row's `y`, rising to this height: a * key or function of the row (through the chart's `z` scale), or a number of pixels. Defaults @@ -24,57 +20,115 @@ export type AreaProps = { */ z?: DataProp; /** - * A curtain's base, likewise. - * - * @default 0 (the floor) + * Pass `` explicitly instead of calculating from data / context: SVG path data + * in the plot's pixels, filled on the floor as the core `Path` draws it */ - z0?: DataProp; + pathData?: string | null; + /** Override the chart's `x` accessor */ + x?: Accessor; + /** + * The area's base down the plot, as the core `Area`: an accessor of the row. Defaults to + * a stacked row's base, else the bottom of the plot. + */ + y0?: Accessor; + /** The area's top down the plot, likewise. Defaults to a stacked row's top, else `y`. */ + y1?: Accessor; /** * Draw one area per distinct value, in data order. Defaults to the chart's `g`, else the - * categorical data key `fill` names, else the chart's `c` (as `Spline`). + * categorical data key `fill` / `stroke` names, else the chart's `c` (as `Spline`). */ g?: Accessor; + /** Series key to use for accessor. */ + seriesKey?: string; + /** + * Tween each area to where it's asked to be, as the core `Area` (ex. `'tween'`, or `{ type: + * 'tween', duration: 300 }`), a new one up from the baseline. A spring leaves it, as core's. + */ + motion?: MotionProp; /** The d3 curve the area's edges take through its rows (ex. `curveMonotoneX`) */ curve?: CurveFactory; /** Whether a row is drawn: the area breaks at rows it isn't, as the core `Area` does */ defined?: (d: any, index: number, data: any[]) => boolean; /** - * A CSS color, or a data key / function run through the chart's color scale (read from each - * area's first row). Defaults to the chart's `c`, else `var(--color-primary)`. + * Draw a line along the top: in the fill's color, or as the core `Area`'s `line` takes it, with + * its own `stroke` (a CSS color, or a key / function of the area's first row run through the + * color scale), `strokeWidth`, and `class` (ex. `{ class: 'stroke-2 stroke-primary' }`). + * + * @default false + */ + line?: boolean | { stroke?: ColorProp; strokeWidth?: number; class?: string }; + /** + * Fill color, the name of a data property (resolved via the chart's `c` scale), or a function + * (read from each area's first row). Defaults to the chart's `c`, else its series' color, + * else `var(--color-primary)`. */ fill?: ColorProp; + /** + * Stroke color, the name of a data property, or a function (read from each area's first row): + * an outline around each area, as the core `Area`'s path takes it. None without one (here or + * in `class`). + */ + stroke?: ColorProp; + /** + * Opacity of the area and its outline (its line stays solid). + * + * @default 1 + */ + opacity?: number; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): * the fill, stroke, stroke width, and opacity they set, where its props don't say */ class?: string; + /** - * Opacity of the area (its line stays solid). + * Whether to animate the drawing of its outline over time (with a `stroke`), as the core + * `Area`'s path draws it. Pass either `true` or an object with transition options + * (`duration`, `delay`, `speed`, `easing`) to enable the transition. * - * @default 1 + * Works best with `tweened` disabled. */ - opacity?: number; - /** Opacity of its fill, with `opacity` (as the core `Area`'s `fillOpacity`) */ + draw?: boolean | Parameters[1]; + /** + * Marker to attach to both start and end points of its outline (with a `stroke`): drawn flat + * on the floor, turned along it, in its stroke color + */ + marker?: MarkerOptions; + /** Marker to attach to the middle point of the outline (each vertex between its ends) */ + markerMid?: MarkerOptions; + /** Marker to attach to the start point of the outline */ + markerStart?: MarkerOptions; + /** Marker to attach to the end point of the outline (where it closes, at its start) */ + markerEnd?: MarkerOptions; + /** + * Add additional content at the start of the area's path (its top's first point). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + startContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Add additional content at the end of the area's path (following it as `draw` draws it). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + endContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** Opacity of its fill, with `opacity` @default 1 */ fillOpacity?: number; + /** Opacity of its outline (not its `line`), with `opacity` @default 1 */ + strokeOpacity?: number; + /** The width of the line and the outline, in pixels. @default 1 */ + strokeWidth?: number; + + /** Override the chart's `y` accessor */ + y?: Accessor; /** - * Draw a line along the top: in the fill's color, or as the core `Area`'s `line` takes it, with - * its own `stroke` (a CSS color, or a key / function of the area's first row run through the - * color scale), `strokeWidth`, and `class` (ex. `{ class: 'stroke-2 stroke-primary' }`). + * A curtain's base, likewise. * - * @default false + * @default 0 (the floor) */ - line?: boolean | { stroke?: ColorProp; strokeWidth?: number; class?: string }; - /** The line's width, in pixels. @default 1 */ - strokeWidth?: number; + z0?: DataProp; /** * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). * * @default false */ tooltip?: boolean; - /** - * Tween each area to where it's asked to be, as the core `Area` (ex. `'tween'`, or `{ type: - * 'tween', duration: 300 }`), a new one up from the baseline. A spring leaves it, as core's. - */ - motion?: MotionProp; }; diff --git a/packages/webgl/src/lib/components/Area/Area.webgl.svelte b/packages/webgl/src/lib/components/Area/Area.webgl.svelte index 0cc8756326..09467134f2 100644 --- a/packages/webgl/src/lib/components/Area/Area.webgl.svelte +++ b/packages/webgl/src/lib/components/Area/Area.webgl.svelte @@ -14,6 +14,10 @@ import { createMerged } from '../../utils/merged.svelte.js'; import { createPathMotion } from '../../utils/rowMotion.svelte.js'; import { defined, position, resolveAccessor, rowColor, scaled } from '../../utils/marks.js'; + import { curveVertices } from '../Line/markers.js'; + import PathWebGL from '../Path/Path.webgl.svelte'; + import { lengthOf } from '../Path/draw.svelte.js'; + import AreaOutline, { type AreaOutline as Outline } from './Area.outline.svelte'; let { data: dataProp, @@ -24,9 +28,12 @@ z, z0 = 0, g, + seriesKey, + pathData, curve, defined: definedProp, fill, + stroke, class: className, opacity = 1, fillOpacity = 1, @@ -34,6 +41,14 @@ strokeWidth: strokeWidthProp, tooltip = false, motion, + draw, + marker, + markerMid, + markerStart, + markerEnd, + startContent, + endContent, + strokeOpacity = 1, }: AreaProps = $props(); const ctx = getChartContext(); @@ -51,10 +66,32 @@ ctx.registerComponent({ name: 'Area', kind: 'mark', - markInfo: () => ({ data: dataProp, x, y, color: typeof fill === 'string' ? fill : undefined }), + markInfo: () => ({ + data: dataProp, + x, + y, + seriesKey, + color: typeof fill === 'string' ? fill : undefined, + }), }); - const rows = $derived((dataProp ?? ctx.data ?? []) as any[]); + /** + * The series it draws, as the core `Area`: its rows, edges, and color. Looked up only with a + * `seriesKey`, so areas without one don't read the series state. + */ + const series = $derived( + seriesKey == null ? undefined : ctx.series.series.find((s) => s.key === seriesKey) + ); + /** Faded while another series is highlighted, as the core `Area` */ + const seriesOpacity = $derived( + series == null || + ctx.series.visibleSeries.length <= 1 || + ctx.series.isHighlighted(series.key, true) + ? 1 + : 0.1 + ); + + const rows = $derived((dataProp ?? series?.data ?? ctx.data ?? []) as any[]); const xAccessor = $derived(resolveAccessor(x, ctx.config.x)); const yAccessor = $derived(resolveAccessor(y, ctx.config.y)); const y0Accessor = $derived(y0 == null ? null : accessor(y0)); @@ -64,7 +101,7 @@ * The chart's area bottoms and tops (as the core `Area`'s): a stack's (areas stack by nature, * as the chart's `seriesLayout` says), else its values over the baseline */ - const chartEdges = $derived(ctx.areaAccessorsFor({ ownData: dataProp != null })); + const chartEdges = $derived(ctx.areaAccessorsFor({ seriesKey, ownData: dataProp != null })); /** Standing up as a curtain, rather than lying on the floor as the core `Area` fills the plot */ const curtain = $derived(y0 == null && y1 == null && (z != null || ctx.config.z != null)); @@ -74,9 +111,9 @@ const gProp = g ?? (ctx.props as { g?: Accessor }).g; if (gProp != null) return accessor(gProp); const first = rows[0]; - const implied = colorPropGroupKey(fill, first); + const implied = colorPropGroupKey(fill, first) ?? colorPropGroupKey(stroke, first); if (implied != null) return accessor(implied); - if (dataProp != null) return null; + if (dataProp != null || series?.data != null) return null; return first != null && ctx.cKey(first) != null ? ctx.cKey : null; }); @@ -168,6 +205,27 @@ return lineLook?.stroke ?? areaColor; } + /** An area's fill: its own `fill`, else its class's, else the chart's `c`, else its series' */ + function fillColor(d: any) { + return rowColor( + ctx, + fill, + d, + series?.color ?? 'var(--color-primary, currentColor)', + look?.fill, + look?.fillSet + ); + } + + /** + * An area's outline, as the core `Area`'s path strokes it: its own `stroke`, or one its `class` + * sets (ex. `stroke-primary`), else none + */ + function outlineColor(d: any) { + if (stroke === 'none' || (stroke == null && !look?.strokeSet)) return null; + return rowColor(ctx, stroke, d, 'currentColor', look?.stroke, look?.strokeSet); + } + /** Each area's runs of columns as asked (broken where a row isn't drawn), with its colors */ const runs = $derived( (gAccessor ? [...group(rows, gAccessor).values()] : [rows]).flatMap((areaRows, area) => { @@ -177,18 +235,21 @@ if (column) pieces[pieces.length - 1].push(column); else if (pieces[pieces.length - 1].length) pieces.push([]); }); - const color = rowColor( - ctx, - fill, - areaRows[0], - 'var(--color-primary, currentColor)', - look?.fill, - look?.fillSet - ); - const stroke = line ? lineColor(areaRows[0], color) : null; + const color = fillColor(areaRows[0]); + const lineStroke = line ? lineColor(areaRows[0], color) : null; + const outline = outlineColor(areaRows[0]); return pieces .filter((piece) => piece.length >= 2) - .map((piece, k) => ({ key: `${area}:${k}`, color, stroke, columns: curved(piece) })); + .map((piece, k) => ({ + key: `${area}:${k}`, + area, + color, + stroke: lineStroke, + outline, + /** Its rows' columns, before `curve` */ + rows: piece, + columns: curved(piece), + })); }) ); @@ -232,49 +293,150 @@ })); } + /** A column's two edges, in the scene's axes (chart x, height, chart y): its base, and its top */ + function edges(c: Column): [number[], number[]] { + return curtain + ? [ + [c.x, c.a, c.y], + [c.x, c.b, c.y], + ] + : [ + [c.x, 0.1, c.a], + [c.x, 0.1, c.b], + ]; + } + + /** A point of an edge, a floor area's lifted over its fill */ + function lifted([x, up, y]: number[]) { + return [x, curtain ? up : up + LINE_LIFT, y]; + } + + /** A run's outline: along its top, back along its base, and closed, as an SVG path's stroke */ + function outlineOf(columns: Column[]) { + return [ + ...columns.flatMap((c) => lifted(edges(c)[1])), + ...columns + .slice() + .reverse() + .flatMap((c) => lifted(edges(c)[0])), + ...lifted(edges(columns[0])[1]), + ]; + } + + /** + * Where a run's outline's commands end, as indices into its points: each column, or along a + * `curve`, its top's and its base's commands' (and where it closes) + */ + function outlineVertices(run: { rows: Column[]; columns: Column[] }) { + const count = run.columns.length; + if (!curve || run.rows.length < 2) return Array.from({ length: 2 * count + 1 }, (_, i) => i); + const along = (edge: (c: Column) => number) => + curveVertices( + run.rows.map((c) => [c.x, edge(c)]), + curve, + run.columns.flatMap((c) => [c.x, 0, edge(c)]) + ); + return [ + ...along((c) => c.b), + ...along((c) => c.a) + .reverse() + .map((k) => 2 * count - 1 - k), + 2 * count, + ]; + } + + /** Each area's runs, as indices into `runs` */ + const areas = $derived.by(() => { + const out: number[][] = []; + runs.forEach((run, i) => (out[run.area] ??= []).push(i)); + return out.filter(Boolean); + }); + createMerged({ tooltip: () => tooltip, items: () => - runs.map((run) => { + runs.flatMap((run) => { const columns = columnsNow(run); const positions: number[] = []; - // In the scene's axes (chart x, height, chart y): each column's two edges - const edges = (c: Column): [number[], number[]] => - curtain - ? [ - [c.x, c.a, c.y], - [c.x, c.b, c.y], - ] - : [ - [c.x, 0.1, c.a], - [c.x, 0.1, c.b], - ]; for (let k = 0; k < columns.length - 1; k++) { const [a0, a1] = edges(columns[k]); const [b0, b1] = edges(columns[k + 1]); positions.push(...a0, ...b0, ...a1, ...a1, ...b0, ...b1); } - const geometry = new BufferGeometry(); - geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)); - geometry.computeVertexNormals(); + // Explicit `pathData` fills in its place (its line, as asked, still from the rows) + let geometry: BufferGeometry | null = null; + if (!pathData && positions.length) { + geometry = new BufferGeometry(); + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)); + geometry.computeVertexNormals(); + } return { d: columns[0].d, - geometry: positions.length ? geometry : null, + geometry, fill: run.color, // On the floor, a little above the fill, so all its width draws over it (a depth // offset alone isn't enough on every GPU for lines in the fill's own plane) - lines: line - ? [ - columns.flatMap((c) => { - const [x, up, y] = edges(c)[1]; - return [x, curtain ? up : up + LINE_LIFT, y]; - }), - ] - : [], + lines: line ? [columns.flatMap((c) => lifted(edges(c)[1]))] : [], stroke: run.stroke, }; }), - opacity: () => opacity * fillOpacity * (look?.opacity ?? 1), + opacity: () => opacity * fillOpacity * seriesOpacity * (look?.opacity ?? 1), + lineOpacity: () => seriesOpacity, strokeWidth: () => strokeWidth, }); + + +{#if pathData} + +{:else if startContent || endContent || runs.some((run) => run.outline)} + + + areas.map((members): Outline => { + const pieces = members.map((i) => runs[i]); + return { + subpaths: pieces.map((run) => outlineOf(columnsNow(run))), + color: pieces[0].outline, + vertices: () => { + let offset = 0; + return pieces.flatMap((run) => { + const own = outlineVertices(run).map((k) => offset + k); + offset += 2 * run.columns.length + 1; + return own; + }); + }, + }; + })} + lengths={() => + areas.map((members) => + members.reduce((sum, i) => sum + lengthOf(outlineOf(runs[i].columns)), 0) + )} + {draw} + {marker} + {markerMid} + {markerStart} + {markerEnd} + {startContent} + {endContent} + {strokeWidth} + opacity={opacity * strokeOpacity * seriesOpacity * (look?.opacity ?? 1)} + /> +{/if} diff --git a/packages/webgl/src/lib/components/Axis/Axis.base.svelte b/packages/webgl/src/lib/components/Axis/Axis.base.svelte new file mode 100644 index 0000000000..421c4e8ddb --- /dev/null +++ b/packages/webgl/src/lib/components/Axis/Axis.base.svelte @@ -0,0 +1,490 @@ + + + + + +{#if grid && along !== 'z'} + +{/if} + +{#if placement !== 'back'} + {#each floorLabels as l (l.key)} + + {/each} +{/if} + +{#each snippetLabels as l, i (l.key)} + {#if isTitle(l)} + {#if typeof label === 'function'}{@render label({ props: textProps(l) })}{/if} + {:else} + {@render tickLabel?.({ props: textProps(l), index: i })} + {/if} +{/each} diff --git a/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts b/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts index 9dde29b6bd..6b7f27f363 100644 --- a/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Axis/Axis.shared.svelte.ts @@ -1,4 +1,6 @@ -import type { autoTickFormat, TicksConfig } from 'layerchart'; +import type { Snippet } from 'svelte'; +import type { autoTickFormat, DataProp, TicksConfig } from 'layerchart'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; /** How an axis draws its labels, as `Text` draws them */ export type AxisLabelProps = { @@ -10,7 +12,7 @@ export type AxisLabelProps = { * @default false */ viewport?: boolean; - /** Class added to each `viewport` label */ + /** Class added to each `viewport` label, and the fill (and opacity) it sets, for the others */ class?: string; /** * Font size in pixels of the plot, for labels on the plot box. Defaults to read about as @@ -29,6 +31,38 @@ export type AxisLabelProps = { verticalAnchor?: 'start' | 'middle' | 'end'; }; +/** How an axis' rule or grid lines are drawn */ +export type AxisLineProps = { + /** CSS classes to style them by (their stroke, width, and opacity) */ + class?: string; + stroke?: string; + /** Width in pixels, the same at any depth. @default 1 */ + strokeWidth?: number; + opacity?: number; + /** Dashed-line pattern (grid lines): a dash length, `[dash, gap]`, or an SVG `stroke-dasharray` */ + dashArray?: number | number[] | string; +}; + +/** What a `label` or `tickLabel` snippet is given to spread on a `Text` */ +export type AxisTextProps = { + x: number; + y: number; + z: number; + value: string; + textAnchor: 'start' | 'middle' | 'end'; + verticalAnchor: 'start' | 'middle' | 'end'; + rotate: number; + fontSize: number; + fontWeight: number | string; + fill: string; + class?: string; + viewport?: boolean; +}; + +/** + * The core `Axis`' props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`tickLabelOffset`) + */ export type AxisProps = { /** * Which axis: `bottom` labels `x` along the floor's front edge (`top` along its back), `left` @@ -37,51 +71,134 @@ export type AxisProps = { */ placement: 'bottom' | 'top' | 'left' | 'right' | 'back'; /** - * Lines across the plot at its ticks, as the core `Axis` draws them: in their CSS `stroke`, or - * the one a `class` sets + * The label for the axis, drawn beyond the tick labels. * + * Can either be a string or a snippet to render custom content. The snippet receives + * spreadable props to apply to a `Text`. + */ + label?: string | Snippet<[{ props: AxisTextProps }]>; + /** + * Location of axis label along the axis + * @default 'middle' + */ + labelPlacement?: 'start' | 'middle' | 'end'; + /** Props applied to label Text */ + labelProps?: AxisLabelProps; + /** + * Draw a rule line along the axis' edge of the plot box, and how + * @default false + */ + rule?: boolean | AxisLineProps; + /** + * Draw grid lines across the plot at its ticks, as the core `Axis` draws them. Pass props + * (class, stroke, strokeWidth, opacity, dashArray) to forward onto the grid lines. * @default false */ - grid?: boolean | { stroke?: string; class?: string }; - /** Title drawn beyond the tick labels */ - label?: string; - /** A count, values, or an interval */ + grid?: boolean | AxisLineProps; + /** Control the number of ticks: a count, values, or an interval */ ticks?: TicksConfig; /** - * Pixels between ticks, picking how many there are as the axis' length changes (as the core - * `Axis`). `null` leaves the count to the scale. + * Width or height of each tick in pixels (enabling responsive count). `null` leaves the count + * to the scale. * * @default 50 in a 3D view (80 across a flat one) */ tickSpacing?: number | null; - /** How to format tick values */ - format?: Parameters[0]['formatType']; /** - * Draw a line along the axis' edge of the plot box. + * Drop ticks whose labels would overlap one already kept, measuring each label at the size + * it actually renders. Across a flat chart; a 3D view keeps every tick (its labels turn with + * the view, so what overlaps changes as it does). + * + * `tickSpacing` only picks a tick *count* — it cannot know how wide a formatted label turns + * out to be, so a long format (`'Wednesday'`, `'$1,234,567'`) still collides at any count + * that fits the axis. This measures instead. + * + * - `priority`: which ticks win when labels compete. `'end'` (default) keeps the last tick and + * walks backwards (the newest value on a time axis); `'start'` keeps the first; `'start-end'` + * anchors both ends of the axis and thins what is between them. + * - `padding`: minimum gap, in pixels, required between two kept labels. * * @default false */ - rule?: boolean; + tickOcclusion?: boolean | { padding?: number; priority?: 'start' | 'end' | 'start-end' }; /** - * Draw a mark out from the edge at each tick. + * Whether to render tick labels on multiple lines for additional context * - * @default true + * @default false */ - tickMarks?: boolean; + tickMultiline?: boolean; /** - * How far tick marks reach out from the edge, in pixels. - * + * Length of the tick line * @default 4 */ tickLength?: number; + /** + * Whether to render tick marks. + * + * @default true + */ + tickMarks?: boolean; + /** Format tick labels */ + format?: Parameters[0]['formatType']; + /** Props to apply to each tick label */ + tickLabelProps?: AxisLabelProps; + /** A snippet to render your own custom tick label, given props to spread on a `Text` */ + tickLabel?: Snippet<[{ props: AxisTextProps; index: number }]>; + /** Override scale for the axis */ + scale?: any; + /** + * Domain for the axis, on a copy of `scale` (or the chart's scale for this placement) that keeps + * its range and type. Useful for a secondary axis, e.g. `domain={[0, 100]}` on the right. + */ + domain?: any[]; + /** Stroke color for axis rule, grid lines, and tick marks. */ + stroke?: string; + /** Fill color for tick labels and axis label. */ + fill?: string; + /** + * Classes for styling various parts of the axis (the stroke, width, and opacity they set on + * its lines, and the fill on its labels) + * @default {} + */ + classes?: { + root?: string; + label?: string; + rule?: string; + tick?: string; + tickLabel?: string; + }; + /** Ease each tick (its mark, label, and grid line) to where it moves, ex. `'tween'` */ + motion?: MotionProp; + /** + * Translate x position of the axis, in pixels (or per row, through the `x` scale, as `Group`) + */ + x?: DataProp; + /** Initial translate x (pixel mode only). @default x */ + initialX?: number; + /** + * Translate y position of the axis, in pixels (or per row, through the `y` scale, as `Group`) + */ + y?: DataProp; + /** Initial translate y (pixel mode only). @default y */ + initialY?: number; + /** Data array to iterate over in data mode (an axis per row, as `Group`) */ + data?: any[]; + /** Key function for each row's axis in data mode. @default (d, i) => i */ + key?: (d: any, index: number) => any; + /** + * Series key to follow, fading the axis while another series is highlighted and removing it + * while the series is hidden. Only applicable if `` uses `series`. + */ + seriesKey?: string; + /** Center within chart. @default false */ + center?: boolean | 'x' | 'y'; + /** The opacity of the element. (0 to 1) */ + opacity?: number; + /** * Pixels between the plot box's edge and the tick labels, as the core `Axis` spaces them. * * @default tickLength beside the plot (`left` / `right`), tickLength + 2 above or below it */ tickLabelOffset?: number; - /** How the tick labels are drawn */ - tickLabelProps?: AxisLabelProps; - /** How `label` is drawn */ - labelProps?: AxisLabelProps; }; diff --git a/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte b/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte index 1fdd52a52a..5bd33ab4e9 100644 --- a/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte +++ b/packages/webgl/src/lib/components/Axis/Axis.webgl.svelte @@ -1,304 +1,24 @@ -{#if grid && along !== 'z'} - -{/if} - -{#if placement !== 'back'} - {#each floorLabels as l (l.key)} - - {/each} +{#if grouped} + + + +{:else} + {/if} diff --git a/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts b/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts index a834b3b137..d8b9fa6cc1 100644 --- a/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts @@ -1,7 +1,132 @@ -import type { BarsProps } from '../Bars/Bars.shared.svelte.js'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; +import type { Accessor, ColorProp, DataProp } from 'layerchart'; +import type { Insets } from 'layerchart/utils/rect.svelte'; +import type { MarkEvents } from '../../contexts/scene.svelte.js'; +import type { Rounded } from '../../utils/rounded.js'; -/** One row's bar, as `Bars` draws each (without registering it with the chart, as the core `Bar`) */ -export type BarProps = Omit & { - /** The row */ +/** + * The core `Bar`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`z`, `class`, `size`). One row's bar, as `Bars` draws each, without registering it with + * the chart. + */ +export type BarProps = { + /** Data to render the bar from */ data: any; + /** Override `x` from context. @default ctx.x */ + x?: Accessor; + /** Override `y` from context. @default ctx.y */ + y?: Accessor; + /** Override `x1` from context. @default ctx.x1 */ + x1?: Accessor; + /** Override `y1` from context. @default ctx.y1 */ + y1?: Accessor; + /** Series key to use for accessor. */ + seriesKey?: string; + /** Padding between stacked bars. */ + stackPadding?: number; + /** + * Corner radius in pixels, rounding flat bars. + * + * @default 0 + */ + radius?: number; + /** + * Pixels to leave between a bar and the edges of its band: on every side, or per side (ex. + * `{ x: 4 }`). A 3D bar takes the same on every side (`all`). + */ + insets?: number | Insets; + /** Where a new bar starts across `x` as it eases in with `motion`, in pixels */ + initialX?: number; + /** Where a new bar starts down `y` as it eases in with `motion`, in pixels */ + initialY?: number; + /** How tall (down `y`) a new bar starts as it eases in with `motion`, in pixels */ + initialHeight?: number; + /** How wide a new bar starts as it eases in with `motion`, in pixels */ + initialWidth?: number; + /** Fixed width in pixels. */ + width?: number; + /** Fixed height in pixels (down `y`, its depth in a 3D view). */ + height?: number; + /** + * Which corners to round. Takes an accessor as well as a value — which corner is the stack's + * edge depends on the row, not just on the series. + * + * @default 'all' + */ + rounded?: Rounded | ((d: any) => Rounded); + /** + * Ease each bar to where it's asked to be: one config for all (ex. `'spring'`, `{ type: + * 'tween', duration: 300 }`), or one per prop (ex. `{ y: { type: 'tween', delay: 300 } }`, of + * `x`, `y`, `z`, `width`, `depth`, and `height`). A new bar grows from the baseline. + */ + motion?: MotionProp<'x' | 'y' | 'z' | 'width' | 'depth' | 'height'>; + /** + * Setup pointer events to show tooltip for related data. + * + * @default false + */ + tooltip?: boolean; + /** + * The fill color: a CSS color, or a data key / function run through the chart's color scale. + * Defaults to the series', else the chart's `c`, else `var(--color-surface-content)`. + */ + fill?: ColorProp; + /** The fill opacity (0 to 1). @default 1 */ + fillOpacity?: number; + /** + * The stroke color, as the core isometric bars draw theirs: around each bar's top and up its + * corners. A CSS color, or a data key / function run through the chart's color scale. None + * without one (here or in `class`) or a `strokeWidth`, which outlines in black. + */ + stroke?: ColorProp; + /** The stroke width in pixels, the same at any depth. @default 1 */ + strokeWidth?: number; + /** The stroke opacity (0 to 1). @default 1 */ + strokeOpacity?: number; + /** The opacity (0 to 1). @default 1 */ + opacity?: number; + /** Click event handler, called with the bar's row (`{ data }`) */ + onclick?: MarkEvents['onclick']; + /** Double click event handler, called with the bar's row (`{ data }`) */ + ondblclick?: MarkEvents['ondblclick']; + /** Pointer enter event handler, called with the bar's row (`{ data }`) */ + onpointerenter?: MarkEvents['onpointerenter']; + /** Pointer move event handler, called with the bar's row (`{ data }`) */ + onpointermove?: MarkEvents['onpointermove']; + /** Pointer leave event handler, called with the bar's row (`{ data }`) */ + onpointerleave?: MarkEvents['onpointerleave']; + /** Pointer over event handler, called with the bar's row (`{ data }`) */ + onpointerover?: MarkEvents['onpointerover']; + /** Pointer out event handler, called with the bar's row (`{ data }`) */ + onpointerout?: MarkEvents['onpointerout']; + + /** + * The bar's height: a data key or function (through the chart's `z` scale), or a number of + * pixels. Defaults to the chart's `z`, stacked when the chart stacks along `z`. With neither, + * the bars are LayerChart's 2D ones, flat on the floor. + */ + z?: DataProp; + /** + * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): + * the fill, stroke, stroke width, and opacity they set, where its props don't say + */ + class?: string; + /** + * A bar's width and depth in pixels along an axis without bands (and on a `globe`). + * + * @default 10 + */ + size?: number; }; + +/** The pointer handlers a bar takes */ +export type BarEvents = Pick< + BarProps, + | 'onclick' + | 'ondblclick' + | 'onpointerenter' + | 'onpointermove' + | 'onpointerleave' + | 'onpointerover' + | 'onpointerout' +>; diff --git a/packages/webgl/src/lib/components/Bars/Bars.base.svelte b/packages/webgl/src/lib/components/Bars/Bars.base.svelte index 826c89b48b..dca70c7e9b 100644 --- a/packages/webgl/src/lib/components/Bars/Bars.base.svelte +++ b/packages/webgl/src/lib/components/Bars/Bars.base.svelte @@ -1,5 +1,6 @@ @@ -8,7 +9,7 @@ import { BoxGeometry, Color, Quaternion, Vector3 } from 'three'; import { getSceneContext } from '../../contexts/scene.svelte.js'; import { getChartContext, isScaleBand } from 'layerchart'; - import { createDimensionGetter } from 'layerchart/utils/rect.svelte'; + import { createDimensionGetter, type Insets } from 'layerchart/utils/rect.svelte'; import { untrack } from 'svelte'; import { getSphere } from '../../utils/globe.js'; @@ -23,20 +24,40 @@ data: dataProp, x, y, + x1, + y1, z, + seriesKey, + stackPadding = 0, fill, + fillOpacity = 1, stroke, strokeWidth: strokeWidthProp, + strokeOpacity = 1, class: className, opacity = 1, - insets = 0, + insets: insetsProp, size: sizeProp = 10, + width: widthProp, + height: heightProp, + initialX, + initialY, + initialWidth, + initialHeight, tooltip = false, motion, key = (_d: any, i: number) => i, radius = 0, rounded = 'all', - }: Omit = $props(); + onBarClick, + onclick, + ondblclick, + onpointerenter, + onpointermove, + onpointerleave, + onpointerover, + onpointerout, + }: Omit & BarEvents = $props(); const ctx = getChartContext(); const scene = getSceneContext(); @@ -49,34 +70,114 @@ */ const outlined = $derived(stroke != null || !!look?.stroke || (strokeWidthProp ?? 0) > 0); - const rows = $derived((dataProp ?? ctx.data ?? []) as any[]); + /** Its series, as the core `Bars`: its rows, values, and color */ + const series = $derived( + seriesKey ? ctx.series.series.find((s) => s.key === seriesKey) : undefined + ); + const rows = $derived((dataProp ?? series?.data ?? ctx.data ?? []) as any[]); const sphere = $derived(getSphere(ctx)); - const xAccessor = $derived(resolveAccessor(x, ctx.config.x)); - const yAccessor = $derived(resolveAccessor(y, ctx.config.y)); + const stack = $derived(ctx.stackAccessorsFor({ seriesKey, stacksImplicitly: true })); + const seriesAccessor = $derived(ctx.series.valueAccessor(seriesKey)); + /** Its values along the value axis: its stack's, else its series', as the core `Bar` reads them */ + const xProp = $derived( + x ?? (ctx.valueAxis === 'x' ? (stack?.value ?? seriesAccessor) : undefined) + ); + const yProp = $derived( + y ?? (ctx.valueAxis === 'y' ? (stack?.value ?? seriesAccessor) : undefined) + ); + const xAccessor = $derived(resolveAccessor(xProp, ctx.config.x)); + const yAccessor = $derived(resolveAccessor(yProp, ctx.config.y)); + + /** + * `stackPadding` between a stack's bars, as the core `Bar`: half on each side of a bar, but the + * stack's ends, along the value axis (where `insets` don't say) + */ + const stackInsets = $derived.by((): Insets | undefined => { + const index = seriesKey + ? ctx.series.visibleSeries.findIndex((s) => s.key === seriesKey) + : undefined; + if (ctx.series.stackLayout == null || stackPadding === 0 || index === undefined) return; + const first = index === 0; + const last = index === ctx.series.visibleSeries.length - 1; + const half = stackPadding / 2; + return ctx.valueAxis === 'y' + ? { bottom: first ? undefined : half, top: last ? undefined : half } + : { left: first ? undefined : half, right: last ? undefined : half }; + }); + const insets = $derived( + insetsProp == null + ? stackInsets + : typeof insetsProp === 'number' + ? { all: insetsProp } + : insetsProp + ); /** A 3D bar's insets, the same on every side */ - const inset = $derived(typeof insets === 'number' ? insets : (insets.all ?? 0)); + const inset = $derived(insets?.all ?? 0); /** * Without a height (`z`, here or the chart's), LayerChart's 2D bars, flat on the floor: across - * the band scale's bands, and along the value axis from its baseline (or between a stack's - * values) + * the band scale's bands (or a sub-band's, with `x1` / `y1`), and along the value axis from its + * baseline (or between a stack's values) */ const flat = $derived(!sphere && z == null && ctx.config.z == null); - const stack = $derived(ctx.stackAccessorsFor({ stacksImplicitly: true })); const dimensions = createDimensionGetter(ctx, () => ({ - x: x ?? (ctx.valueAxis === 'x' ? stack?.value : undefined), - y: y ?? (ctx.valueAxis === 'y' ? stack?.value : undefined), - insets: typeof insets === 'number' ? { all: insets } : insets, + x: xProp, + y: yProp, + x1, + y1, + insets, })); - /** Where a bar starts along an axis and how far it reaches */ - function extent(scale: any, value: unknown): [number, number] { + /** + * Where a bar starts along an axis and how far it reaches: across its band (or its `sub` + * band, ex. a grouped bar's), else `size` about its value + */ + function extent( + scale: any, + value: unknown, + sub?: { scale: any; value: unknown } | null + ): [number, number] { if (isScaleBand(scale)) { - return [Number(scale(value)) + inset, Math.max(0, scale.bandwidth() - inset * 2)]; + const start = Number(scale(value)) + (sub ? Number(sub.scale(sub.value)) || 0 : 0); + const band = sub ? (sub.scale.bandwidth?.() ?? 0) : scale.bandwidth(); + return [start + inset, Math.max(0, band - inset * 2)]; } return [Number(scale(value)) - sizeProp / 2, sizeProp]; } + /** A bar's sub-band along an axis, by `x1` / `y1` (here or the chart's) through its scale */ + function subBand(d: any, prop: unknown, fallback: unknown, scale: any) { + const sub = prop ?? fallback; + return sub != null && scale + ? { scale, value: resolveAccessor(sub as any, undefined)(d) } + : null; + } + + /** A bar's `width` and `height` (down `y`) when fixed, centered where it would have been */ + function fixed(bar: T): T { + if (widthProp != null) { + bar.x += (bar.width - widthProp) / 2; + bar.width = widthProp; + } + if (heightProp != null) { + bar.y += (bar.depth - heightProp) / 2; + bar.depth = heightProp; + } + return bar; + } + + /** A row's fill: `fill`, else its series', else the chart's `c` (or its `class`'s) */ + function colorOf(d: any) { + return rowColor( + ctx, + fill ?? series?.color, + d, + 'var(--color-surface-content, currentColor)', + look?.fill, + look?.fillSet + ); + } + const highlight = new Color(0xffffff); /** A flat bar's thickness: enough for its outline to sit on its top */ const FLAT_HEIGHT = 0.01; @@ -100,18 +201,27 @@ for (const t of targets) { active.add(t.key); const values = { x: t.x, y: t.y, z: t.z, width: t.width, depth: t.depth, height: t.height }; - untrack(() => motionMap.update(t.key, values, grown(t))); + untrack(() => motionMap.update(t.key, values, initialOf(t))); } untrack(() => motionMap.cleanup(active)); }); } - /** Where a new bar grows from: its baseline, flat along the value axis (or a 3D bar's floor) */ - function grown(t: Instance) { - if (!flat) return { height: 0 }; - return ctx.valueAxis === 'x' - ? { x: Math.min(...ctx.xRange), width: 0 } - : { y: Math.max(...ctx.yRange), depth: 0 }; + /** + * Where a new bar eases in from: `initialX` / `initialY` / `initialWidth` / `initialHeight` + * where they're given, else its baseline, flat along the value axis (or a 3D bar's floor) + */ + function initialOf(_t: Instance) { + const grown: Partial> = !flat + ? { height: 0 } + : ctx.valueAxis === 'x' + ? { x: Math.min(...ctx.xRange), width: 0 } + : { y: Math.max(...ctx.yRange), depth: 0 }; + if (initialX != null) grown.x = initialX; + if (initialY != null) grown.y = initialY; + if (initialWidth != null) grown.width = initialWidth; + if (initialHeight != null) grown.depth = initialHeight; + return grown; } /** Each row's bar where it is now */ @@ -120,7 +230,7 @@ ? targets.map((t) => { const now = motionMap.get(t.key); // A new one from the baseline, until its easing starts - return { ...t, ...(now ?? grown(t)) }; + return { ...t, ...(now ?? initialOf(t)) }; }) : targets ); @@ -129,26 +239,18 @@ function bar(d: any): Instance[] { if (flat) { const rect = dimensions(d); - if (!rect || !(rect.width > 0) || !(rect.height > 0)) return []; - return [ - { - d, - x: rect.x, - y: rect.y, - z: 0, - width: rect.width, - depth: rect.height, - height: FLAT_HEIGHT, - color: rowColor( - ctx, - fill, - d, - 'var(--color-surface-content, currentColor)', - look?.fill, - look?.fillSet - ), - }, - ]; + if (!rect) return []; + const placed = fixed({ + d, + x: rect.x, + y: rect.y, + z: 0, + width: rect.width, + depth: rect.height, + height: FLAT_HEIGHT, + color: colorOf(d), + }); + return placed.width > 0 && placed.depth > 0 ? [placed] : []; } const xValue = xAccessor(d); const yValue = yAccessor(d); @@ -163,35 +265,28 @@ .normalize(); const rotation = new Quaternion().setFromUnitVectors(new Vector3(0, 1, 0), outward); // The box's corner, half its footprint back from the center - const corner = new Vector3(-sizeProp / 2, 0, -sizeProp / 2) - .applyQuaternion(rotation) - .add(base); + const across = widthProp ?? sizeProp; + const down = heightProp ?? sizeProp; + const corner = new Vector3(-across / 2, 0, -down / 2).applyQuaternion(rotation).add(base); return [ { d, x: corner.x, y: corner.z, z: corner.y, - width: sizeProp, - depth: sizeProp, + width: across, + depth: down, height: Math.abs(z1 - z0), rotation, - color: rowColor( - ctx, - fill, - d, - 'var(--color-surface-content, currentColor)', - look?.fill, - look?.fillSet - ), + color: colorOf(d), }, ]; } - const [x0, width] = extent(ctx.xScale, xValue); - const [y0, depth] = extent(ctx.yScale, yValue); + const [x0, width] = extent(ctx.xScale, xValue, subBand(d, x1, ctx.config.x1, ctx.x1Scale)); + const [y0, depth] = extent(ctx.yScale, yValue, subBand(d, y1, ctx.config.y1, ctx.y1Scale)); const [z0, z1] = ctx.heightOf(d, z); return [ - { + fixed({ d, x: x0, y: y0, @@ -199,15 +294,8 @@ width, depth, height: Math.abs(z1 - z0), - color: rowColor( - ctx, - fill, - d, - 'var(--color-surface-content, currentColor)', - look?.fill, - look?.fillSet - ), - }, + color: colorOf(d), + }), ]; } @@ -242,11 +330,26 @@ : rowColor(ctx, stroke, d, 'black', look?.stroke, look?.strokeSet); } + /** Its pointer handlers, called with the bar's row (`onBarClick` is its `onclick`) */ + const events = () => ({ + onclick: onclick ?? onBarClick, + ondblclick, + onpointerenter, + onpointermove, + onpointerleave, + onpointerover, + onpointerout, + }); + + const fillAlpha = $derived(opacity * fillOpacity * (look?.opacity ?? 1)); + const strokeAlpha = $derived(opacity * strokeOpacity * (look?.opacity ?? 1)); + createInstances({ tooltip: () => tooltip, + events, geometry: new BoxGeometry(1, 1, 1).translate(0.5, 0.5, 0.5), instances: () => (roundedBars ? [] : bars), - opacity: () => opacity * (look?.opacity ?? 1), + opacity: () => fillAlpha, emphasize: (color) => color.lerp(highlight, 0.25), // Giving way to its outline in depth, so the outline sits on its edges behind: () => outlined, @@ -257,7 +360,7 @@ instances: () => (outlined && !roundedBars ? bars : []), stroke: outlineOf, strokeWidth: () => strokeWidth, - opacity: () => opacity * (look?.opacity ?? 1), + opacity: () => strokeAlpha, }); @@ -268,7 +371,9 @@ height={FLAT_HEIGHT} stroke={(d) => (outlined ? outlineOf(d) : null)} {strokeWidth} - opacity={opacity * (look?.opacity ?? 1)} + opacity={fillAlpha} + lineOpacity={strokeAlpha} {tooltip} + {events} /> {/if} diff --git a/packages/webgl/src/lib/components/Bars/Bars.rounded.svelte b/packages/webgl/src/lib/components/Bars/Bars.rounded.svelte index 6ed2302b6a..4cff1cddb8 100644 --- a/packages/webgl/src/lib/components/Bars/Bars.rounded.svelte +++ b/packages/webgl/src/lib/components/Bars/Bars.rounded.svelte @@ -1,6 +1,8 @@ diff --git a/packages/webgl/src/lib/components/Bin/Bin.shared.svelte.ts b/packages/webgl/src/lib/components/Bin/Bin.shared.svelte.ts index fa6c6ef982..5ac32218e8 100644 --- a/packages/webgl/src/lib/components/Bin/Bin.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Bin/Bin.shared.svelte.ts @@ -1,11 +1,28 @@ +import type { Snippet } from 'svelte'; import type { Accessor, BinCell, BinShape, ColorProp, DataProp } from 'layerchart'; +/** How `Bin`'s `grid` is drawn: `true`, or its stroke, width, opacity, and classes */ +export type BinGridProps = + | boolean + | { + class?: string; + style?: string; + stroke?: string; + strokeWidth?: number; + strokeOpacity?: number; + opacity?: number; + }; + +/** + * The core `Bin`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`gap`, `tooltip`) + */ export type BinProps = { /** Rows to bin. Falls back to the chart's data. */ data?: T[]; - /** Horizontal position accessor, or longitude on a map. Defaults to the chart's `x`. */ + /** Horizontal position accessor, or longitude on a geo chart. Defaults to the chart's `x`. */ x?: Accessor; - /** Vertical position accessor, or latitude on a map. Defaults to the chart's `y`. */ + /** Vertical position accessor, or latitude on a geo chart. Defaults to the chart's `y`. */ y?: Accessor; /** * How much each row counts toward its cell's `count`, ex. the people in a cell of gridded @@ -19,47 +36,79 @@ export type BinProps = { */ shape?: BinShape; /** - * Width of a cell in pixels: the distance between neighboring hexagon centers, a square's - * side, or a triangle's base. + * Width of a cell in pixels — the distance between neighboring hexagon centers, a square's side, + * or a triangle's base. * * @default 20 */ size?: number; /** - * Pixels between neighboring cells, so each stands apart. + * Outline every cell of the grid beneath the bins, clipped to the plot, to show how it is divided. + * Pass props (class, style, stroke, strokeWidth, strokeOpacity, opacity) to style its lines. * - * @default 0 - */ - gap?: number; - /** - * How tall each cell stands: a cell property or function of the cell (through the chart's `z` - * scale, ex. `'count'`), or a number of pixels. Flat on the floor without one. - */ - z?: DataProp>; - /** - * Size each cell by a value rather than filling the grid, as the core `Bin` (ex. `r="count"`): - * a cell property or function, its area in proportion (the largest filling its cell), or a - * number, a circumradius in pixels + * @default false */ - r?: DataProp>; + grid?: BinGridProps; /** - * Each cell's color: a cell property (ex. `'count'`) or a function of the cell, numbers - * colored as the core `Bin` colors them (the chart's continuous `cScale`, else - * yellow-green-blue), or a CSS color. + * Fill color of each cell. + * - `undefined`: the cell's `count`, through a color ramp + * - `string`: a cell property such as `'count'` through a color ramp, else a literal CSS color + * - `function(cell)`: any value derived from the cell, ex. `(cell) => mean(cell.data, (d) => d.price)` * - * @default 'count' + * Numbers are colored by the chart's `cScale` when it is continuous (re-domained to the cells' + * extent unless `cDomain` is given), else a `YlGnBu` ramp. Categories use the chart's `cScale`. */ fill?: ColorProp>; /** - * The cells' outline, as the core `Bin` draws it: around each cell's top, and up its - * corners when it stands any height. A CSS color, or a cell property / function run through - * the chart's color scale. None without one. + * Stroke color of each cell, resolved like `fill`: around each cell's top, and up its corners + * when it stands any height. None without one (here or in `class`). */ stroke?: ColorProp>; - /** Outline width in pixels, the same at any depth. @default 1 */ + /** The fill opacity (0 to 1). @default 1 */ + fillOpacity?: number; + /** The stroke opacity (0 to 1). @default 1 */ + strokeOpacity?: number; + /** The stroke width in pixels, the same at any depth. @default 1 */ strokeWidth?: number; - /** @default 1 */ + /** The opacity (0 to 1). @default 1 */ opacity?: number; + /** + * Size each cell by a value rather than filling the grid, ex. `r="count"`. + * - `string` / `function(cell)`: area proportional to the value, the largest filling its cell + * - `number`: circumradius in pixels + */ + r?: DataProp>; + /** + * Stand each cell up as a prism, ex. `z="count"`. Flat on the floor without one. + * - `string` / `function(cell)`: resolved through `zScale` + * - `number`: pixel height for every cell + */ + z?: DataProp>; + /** + * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): + * the fill, stroke, stroke width, and opacity they set, where its props don't say + */ + class?: string; + /** + * Render the cells yourself (ex. as `Points` or `Text` labels, at each cell's `x` / `y`) + * instead of as prisms + */ + children?: Snippet<[{ cells: BinCell[] }]>; + /** Called with the cell clicked */ + onclick?: (e: MouseEvent, cell: BinCell) => void; + /** Called with the cell the pointer enters */ + onpointerenter?: (e: PointerEvent, cell: BinCell) => void; + /** Called with the cell the pointer moves over */ + onpointermove?: (e: PointerEvent, cell: BinCell) => void; + /** Called with the cell the pointer leaves */ + onpointerleave?: (e: PointerEvent, cell: BinCell) => void; + + /** + * Pixels between neighboring cells, so each stands apart. + * + * @default 0 + */ + gap?: number; /** * Show the tooltip for the cell the pointer is over (with the chart's `tooltipContext`). * diff --git a/packages/webgl/src/lib/components/Bin/Bin.webgl.svelte b/packages/webgl/src/lib/components/Bin/Bin.webgl.svelte index 0a5861a88f..de8a2e614e 100644 --- a/packages/webgl/src/lib/components/Bin/Bin.webgl.svelte +++ b/packages/webgl/src/lib/components/Bin/Bin.webgl.svelte @@ -4,16 +4,19 @@ + +{#if grid} + +{/if} +{#if children} + {@render children({ cells })} +{/if} diff --git a/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts b/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts index e3a7bc95d5..c0bc81a43b 100644 --- a/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Circle/Circle.shared.svelte.ts @@ -1,25 +1,46 @@ import type { ColorProp, DataProp } from 'layerchart'; -import type { MotionOptions } from 'layerchart/utils/motion.svelte'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; +/** + * The core `Circle`'s props (in its order, as it describes them), then its style props, then + * those of a `WebGL` layer's own (`tooltip`, `style`) + */ export type CircleProps = { - /** Rows to draw a circle each for (else the chart's, when a position reads them) */ - data?: any[]; /** - * The center across: a number of pixels, or a data key / function through the chart's `x` - * scale (a circle per row) + * The center x position of the circle. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via xScale + * - `function(d)`: accessor called per data item, result passed through xScale * * @default 0 */ cx?: DataProp; /** - * The center down: a number of pixels, or a data key / function through the chart's `y` - * scale (a circle per row) + * The initial center x position of the circle (pixel mode only), to ease from with `motion`. + * + * @default cx + */ + initialCx?: number; + /** + * The center y position of the circle. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via yScale + * - `function(d)`: accessor called per data item, result passed through yScale * * @default 0 */ cy?: DataProp; /** - * The radius: a number of pixels, or a data key / function through the chart's `r` scale + * The initial center y position of the circle (pixel mode only), to ease from with `motion`. + * + * @default cy + */ + initialCy?: number; + /** + * The radius of the circle. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via rScale + * - `function(d)`: accessor called per data item, result passed through rScale * * @default 1 */ @@ -29,6 +50,45 @@ export type CircleProps = { * `z` scale. Flat on the floor without one. */ z?: DataProp; + /** + * Keep the circle facing the viewer (round), as the core `Circle` on an `isometric` chart. + * Always so here: a flat chart's circles are discs seen from above, and a 3D view's are + * spheres, round from any side. + * + * @default false + */ + viewport?: boolean; + /** + * The initial radius of the circle (pixel mode only), to ease from with `motion` (ex. `0` to + * grow in). + * + * @default r + */ + initialR?: number; + /** + * Data array to iterate over in data mode. + * Falls back to chart context data when not provided. + */ + data?: any[]; + /** + * Which circle each row is as rows change, for `motion`. + * + * @default (d, i) => i + */ + key?: (d: any, index: number) => unknown; + /** + * Ease each circle to where it's asked to be, as the core `Circle` (ex. `'spring'`, or + * `{ type: 'tween', duration: 300 }`), or each of `cx`, `cy`, and `r` by its own (ex. + * `{ r: 'spring' }`) + */ + motion?: MotionProp<'cx' | 'cy' | 'r'>; + /** + * Dashed-border pattern. Accepts a number (single dash length), a + * `[dash, gap, ...]` array, or a string (same syntax as SVG + * `stroke-dasharray`), in pixels: its ring's (drawn flat), its first dash and gap repeating. + */ + dashArray?: number | number[] | string; + /** * A CSS color, or a data key / function run through the chart's color scale (`none` or `null` * for only its ring). @@ -36,35 +96,31 @@ export type CircleProps = { * @default 'var(--color-surface-content)' */ fill?: ColorProp | null; + /** The fill opacity (0 to 1), as the core `Circle`'s. @default 1 */ + fillOpacity?: number; /** A ring around it, in a CSS color or a data key / function run through the color scale */ stroke?: ColorProp; /** The ring's width, in pixels. @default 1 */ strokeWidth?: number; + /** The ring's opacity (0 to 1), as the core `Circle`'s `strokeOpacity`. @default 1 */ + strokeOpacity?: number; + /** @default 1 */ + opacity?: number; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): * the fill, stroke, stroke width, and opacity they set, where its props don't say */ class?: string; - /** @default 1 */ - opacity?: number; + /** * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). * * @default false */ tooltip?: boolean; - /** - * Ease each circle to where it's asked to be, as the core `Circle` (ex. `'spring'`, or - * `{ type: 'tween', duration: 300 }`) - */ - motion?: MotionOptions; - /** The fill's opacity, as the core `Circle`'s (its ring's is `opacity`). @default 1 */ - fillOpacity?: number; /** * Inline CSS, as on the core marks' elements (ex. `--fill-color: var(--color-primary)`): the * colors it sets, as LayerChart's styles read them */ style?: string; - /** Which circle each row is as rows change, for `motion`. @default (d, i) => i */ - key?: (d: any, index: number) => unknown; }; diff --git a/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte b/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte index 9b2a3d6230..8145ca6c0d 100644 --- a/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte +++ b/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte @@ -5,17 +5,21 @@ diff --git a/packages/webgl/src/lib/components/Contour/Contour.lines.svelte b/packages/webgl/src/lib/components/Contour/Contour.lines.svelte index 85e39784e0..a49cc55cac 100644 --- a/packages/webgl/src/lib/components/Contour/Contour.lines.svelte +++ b/packages/webgl/src/lib/components/Contour/Contour.lines.svelte @@ -4,7 +4,7 @@ diff --git a/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts b/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts index d22a673ac2..59e1f1cf66 100644 --- a/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts +++ b/packages/webgl/src/lib/components/GeoPath/GeoPath.shared.svelte.ts @@ -1,15 +1,34 @@ +import type { Snippet } from 'svelte'; +import type { draw as drawTransition } from 'svelte/transition'; import type { ColorProp, DataProp } from 'layerchart'; import type { Feature, FeatureCollection, Geometry, GeometryCollection } from 'geojson'; -import type { GeoSphere } from 'd3-geo'; +import type { + GeoIdentityTransform, + GeoPath, + GeoProjection, + GeoSphere, + GeoTransformPrototype, +} from 'd3-geo'; +import type { CurveFactory, CurveFactoryLineOnly } from 'd3-shape'; import type { MotionOptions } from 'layerchart/utils/motion.svelte'; +import type { MarkerOptions } from '../Line/markers.js'; +/** + * The core `GeoPath`'s props (in its order, as it describes them), then those of a `WebGL` + * layer's own (`class`) + */ export type GeoPathProps = { + /** + * How tall each feature stands: a property key or function of the feature (through the chart's + * `z` scale), or a number of pixels. Flat on the floor without one. + */ + z?: DataProp; /** * A feature, a collection of them (drawn as one mark), or a geometry. On a `globe`, their * lines and outlines draw over it (filled shapes on a globe aren't drawn yet), and * `{ type: 'Sphere' }` fills the globe itself (ex. the ocean beneath an image still loading). */ - geojson: + geojson?: | Feature | FeatureCollection | Geometry @@ -18,16 +37,34 @@ export type GeoPathProps = { | null | undefined; /** - * How tall each feature stands: a property key or function of the feature (through the chart's - * `z` scale), or a number of pixels. Flat on the floor without one. + * Show the tooltip for the feature the pointer is over (with the chart's `tooltipContext`). + * + * @default false */ - z?: DataProp; + tooltip?: boolean; + /** + * Click event handler, called with the path generator (as the core `GeoPath`'s), and the + * feature clicked + */ + onclick?: ((e: MouseEvent, geoPath: GeoPath | undefined, feature: Feature) => void) | undefined; + /** + * The curve the projected outlines are drawn through, as the core `GeoPath`'s. + * + * @default curveLinearClosed + */ + curve?: CurveFactory | CurveFactoryLineOnly; + /** Transform the projection's output, ex. to offset or scale every point (a `geoTransform`) */ + geoTransform?: (projection: GeoProjection | GeoIdentityTransform) => GeoTransformPrototype; + /** Draw in place of the path, given the path generator (as the core `GeoPath`) */ + children?: Snippet<[{ geoPath: GeoPath | undefined }]>; /** * A CSS color, or a function of the feature returning one (or a value for the chart's color * scale). Lines have no fill. None by default, as the core `GeoPath` (`null` for none where * a `class` sets one). */ fill?: ColorProp | null; + /** The fill opacity of the element. (0 to 1) */ + fillOpacity?: number; /** * The outlines' color: a CSS color, or a data key / function of the feature run through the * chart's color scale (`null` for none). @@ -41,22 +78,47 @@ export type GeoPathProps = { * @default 1 */ strokeWidth?: number; + /** The stroke opacity of the element. (0 to 1) */ + strokeOpacity?: number; + /** The opacity of the element. (0 to 1) @default 1 */ + opacity?: number; /** - * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): - * the fill, stroke, stroke width, and opacity they set, where its props don't say + * Whether to animate the drawing of its outlines over time, as one path through its features. + * Pass either `true` or an object with transition options (`duration`, `delay`, `speed`, + * `easing`) to enable the transition. Drawn again as its shapes change. */ - class?: string; - /** @default 1 */ - opacity?: number; + draw?: boolean | Parameters[1]; /** - * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). - * - * @default false + * Marker to attach to both start and end points of the line (one path through its features' + * outlines): drawn flat on the floor (over a globe, along it), turned along the line, in the + * first feature's stroke color */ - tooltip?: boolean; + marker?: MarkerOptions; + /** Marker to attach to the middle point of the line (each point between its ends) */ + markerMid?: MarkerOptions; + /** Marker to attach to the start point of the line */ + markerStart?: MarkerOptions; + /** Marker to attach to the end point of the line */ + markerEnd?: MarkerOptions; + /** + * Add additional content at the start of the line (its first feature's first point). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + startContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Add additional content at the end of the line (following it as `draw` draws it). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + endContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; /** * Ease each feature's height and fill to new values rather than jumping, ex. `'tween'` or * `{ type: 'tween', duration: 800 }`. */ motion?: MotionOptions; + + /** + * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): + * the fill, stroke, stroke width, and opacity they set, where its props don't say + */ + class?: string; }; diff --git a/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte b/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte index c608f13f86..d1d901f1e3 100644 --- a/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte +++ b/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte @@ -5,13 +5,73 @@ /** A light gray that reads on either theme */ const defaultFill = 'color-mix(in oklab, var(--color-surface-content, currentColor) 15%, var(--color-surface-100, white))'; + + /** Segments each curve is drawn in, so outlines follow it as the fill does */ + const CURVE_STEPS = 8; + + /** + * A path context drawing into `target`, its curves (ex. a `curve`'s) as runs of short lines, so + * an outline follows a curve (a `ShapeContext` outlines only to its end) + */ + function sampling(target: ShapeContext) { + let x0 = 0; + let y0 = 0; + let startX = 0; + let startY = 0; + const lineTo = (x: number, y: number) => { + target.lineTo(x, y); + x0 = x; + y0 = y; + }; + return { + moveTo(x: number, y: number) { + target.moveTo(x, y); + x0 = startX = x; + y0 = startY = y; + }, + lineTo, + closePath() { + target.closePath(); + x0 = startX; + y0 = startY; + }, + quadraticCurveTo(cx: number, cy: number, x: number, y: number) { + const [ax, ay] = [x0, y0]; + for (let i = 1; i <= CURVE_STEPS; i++) { + const t = i / CURVE_STEPS; + const u = 1 - t; + lineTo(u * u * ax + 2 * u * t * cx + t * t * x, u * u * ay + 2 * u * t * cy + t * t * y); + } + }, + bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) { + const [ax, ay] = [x0, y0]; + for (let i = 1; i <= CURVE_STEPS; i++) { + const t = i / CURVE_STEPS; + const u = 1 - t; + const [a, b, c, d] = [u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t]; + lineTo(a * ax + b * c1x + c * c2x + d * x, a * ay + b * c1y + c * c2y + d * y); + } + }, + arc(x: number, y: number, r: number, a0: number, a1: number, ccw?: boolean) { + target.arc(x, y, r, a0, a1, ccw); + x0 = x + r * Math.cos(a1); + y0 = y + r * Math.sin(a1); + }, + rect(x: number, y: number, w: number, h: number) { + target.rect(x, y, w, h); + x0 = startX = x; + y0 = startY = y; + }, + }; + } + +{#if children} + {@render children({ geoPath: pathGenerator })} +{:else} + {#if marker || markerStart || markerMid || markerEnd} + + { + const color = features.length ? strokeOf(features[0]) : null; + const points = outlines.flat(2); + return color + ? [ + { + points, + color, + // Each vertex between its ends: its rings' and lines' every point + get mids() { + return Array.from( + { length: Math.max(0, points.length / 3 - 2) }, + (_, k) => k + 1 + ); + }, + }, + ] + : []; + }} + {strokeWidth} + opacity={opacity * (look?.opacity ?? 1)} + /> + {/if} + {#if startContent || endContent} + {@const ends = pathEnds(outlines.flat(), drawn.progress)} + {#if ends} + + {/if} + {/if} +{/if} diff --git a/packages/webgl/src/lib/components/GeoRaster/GeoRaster.shared.svelte.ts b/packages/webgl/src/lib/components/GeoRaster/GeoRaster.shared.svelte.ts index 48d588539d..b7f72e10ac 100644 --- a/packages/webgl/src/lib/components/GeoRaster/GeoRaster.shared.svelte.ts +++ b/packages/webgl/src/lib/components/GeoRaster/GeoRaster.shared.svelte.ts @@ -1,6 +1,10 @@ import type { GeoProjection } from 'd3-geo'; import type { ImageSource } from '../../utils/texture.js'; +/** + * The core `GeoRaster`'s props (in its order, as it describes them), then those of a `WebGL` + * layer's own (`elevation`, `pixelSize`, `opacity`, `tooltip`) + */ export type GeoRasterProps = { /** * The image to lay over the map through the chart's projection (ex. NASA's Blue Marble), or @@ -10,9 +14,11 @@ export type GeoRasterProps = { */ image: ImageSource; /** - * The projection the image was drawn in, mapping longitude / latitude to its own pixels (as - * the core `GeoRaster`). Equirectangular without one. Not on a `globe`, which wraps an - * equirectangular image. + * Projection used by the source image. Pass as an uncalled function, e.g. + * `sourceProjection={geoEquirectangular}`. + * + * When omitted, the source is assumed to be an equirectangular (plate carrée) image covering + * the full globe. Not on a `globe`, which wraps an equirectangular image. */ sourceProjection?: () => GeoProjection; /** @@ -23,14 +29,28 @@ export type GeoRasterProps = { * @default 'bilinear' */ interpolate?: 'nearest' | 'bilinear'; - /** Draw the image's pixels as crisp blocks (as `interpolate: 'nearest'`) */ - pixelated?: boolean; /** - * `crossOrigin` for an image loaded from a URL. `null` for none. + * `crossOrigin` attribute applied to the underlying `Image` element when loading from a URL. + * Set to `null` to disable. * * @default 'anonymous' */ crossOrigin?: string | null; + /** + * Resolution multiplier for the reprojected output, relative to chart CSS pixels: the image is + * laid over points `pixelSize / resolution` pixels apart, so a value greater than 1 follows the + * projection's curves (and terrain) more closely, at the cost of more of them. + * + * @default 1 + */ + resolution?: number; + /** + * Draw the image's pixels as crisp blocks (as `interpolate: 'nearest'`), for a pixel-art look. + * + * @default false + */ + pixelated?: boolean; + /** * Raise the image into terrain: a function of longitude and latitude returning a value for * the chart's `z` scale (ex. elevation in meters). `NaN` leaves a place out (ex. beyond the @@ -43,7 +63,7 @@ export type GeoRasterProps = { * @default 4 */ pixelSize?: number; - /** @default 1 */ + /** The opacity of the element. (0 to 1) @default 1 */ opacity?: number; /** * Show the tooltip for the longitude / latitude the pointer is over (with the chart's diff --git a/packages/webgl/src/lib/components/GeoRaster/GeoRaster.webgl.svelte b/packages/webgl/src/lib/components/GeoRaster/GeoRaster.webgl.svelte index d1feb085ce..459d04cd27 100644 --- a/packages/webgl/src/lib/components/GeoRaster/GeoRaster.webgl.svelte +++ b/packages/webgl/src/lib/components/GeoRaster/GeoRaster.webgl.svelte @@ -28,12 +28,16 @@ interpolate = 'bilinear', pixelated = false, crossOrigin = 'anonymous', + resolution = 1, elevation, - pixelSize = 4, + pixelSize: pixelSizeProp = 4, opacity = 1, tooltip = false, }: GeoRasterProps = $props(); + /** Pixels between the points the image is laid over, `resolution` times as many */ + const pixelSize = $derived(pixelSizeProp / (resolution > 0 ? resolution : 1)); + /** The image's size once loaded, for `sourceProjection` to map into */ let imageSize = $state<{ width: number; height: number } | null>(null); /** Where longitude / latitude falls on the image, `[0, 1]` across and up */ diff --git a/packages/webgl/src/lib/components/GeoTile/GeoTile.shared.svelte.ts b/packages/webgl/src/lib/components/GeoTile/GeoTile.shared.svelte.ts index 8efb0c82ca..736df70aaa 100644 --- a/packages/webgl/src/lib/components/GeoTile/GeoTile.shared.svelte.ts +++ b/packages/webgl/src/lib/components/GeoTile/GeoTile.shared.svelte.ts @@ -1,3 +1,5 @@ +import type { Snippet } from 'svelte'; +import type { GroupProps } from 'layerchart'; import type { ElevationEncoding, Tile } from '../../utils/tiles.js'; /** @@ -18,6 +20,10 @@ export type GeoTileElevation = { maxZoom?: number; }; +/** + * The core `GeoTile`'s props (in its order, as it describes them), then those of a `WebGL` + * layer's own (`maxZoom`, `elevation`, `segments`, ...) + */ export type GeoTileProps = { /** A tile's image URL, from its column, row, and zoom (an XYZ tile service, as the core `GeoTile` takes) */ url: (x: number, y: number, z: number) => string; @@ -34,6 +40,29 @@ export type GeoTileProps = { * @default 256 */ tileSize?: number; + /** + * Load each image anew rather than from those loaded before. + * + * @default false + */ + disableCache?: boolean; + /** + * Props for the `Group` the tiles are drawn in (ex. `{ opacity: 0.5 }`, or `x` / `y` to move + * them) + */ + group?: Partial; + /** + * Outline each tile, labeled with its zoom / column / row. + * + * @default false + */ + debug?: boolean; + /** + * Draw in place of the tiles, given those covering the view (each `[x, y, z]`): none of their + * images load + */ + children?: Snippet<[{ tiles: Tile[] }]>; + /** * The deepest zoom the image tiles go to: deeper tiles show part of their ancestor's image, * enlarged (ex. imagery that stops at zoom 12 under terrain that doesn't) @@ -50,20 +79,8 @@ export type GeoTileProps = { * @default 64 with `elevation`, else 16 */ segments?: number; - /** - * Load each image anew rather than from those loaded before. - * - * @default false - */ - disableCache?: boolean; - /** @default 1 */ + /** The opacity of the tiles. (0 to 1) @default 1 */ opacity?: number; - /** - * Outline each tile, labeled with its zoom / column / row. - * - * @default false - */ - debug?: boolean; /** * Show the tooltip for the longitude / latitude the pointer is over (with the chart's * `tooltipContext`), and its elevation. diff --git a/packages/webgl/src/lib/components/GeoTile/GeoTile.tiles.svelte b/packages/webgl/src/lib/components/GeoTile/GeoTile.tiles.svelte new file mode 100644 index 0000000000..2206dfd423 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoTile/GeoTile.tiles.svelte @@ -0,0 +1,1011 @@ + + + + +{#if children} + {@render children({ tiles })} +{/if} diff --git a/packages/webgl/src/lib/components/GeoTile/GeoTile.webgl.svelte b/packages/webgl/src/lib/components/GeoTile/GeoTile.webgl.svelte index 1c35fd4fa1..5a00cd6a49 100644 --- a/packages/webgl/src/lib/components/GeoTile/GeoTile.webgl.svelte +++ b/packages/webgl/src/lib/components/GeoTile/GeoTile.webgl.svelte @@ -1,1001 +1,19 @@ + + +{#if group} + + + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts b/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts index 8ca2bd9476..b494645370 100644 --- a/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Graticule/Graticule.shared.svelte.ts @@ -1,14 +1,16 @@ import type { GeoPathProps } from '../GeoPath/GeoPath.shared.svelte.js'; -type LineProps = Partial>; - +/** + * The core `Graticule`'s props (in its order), then the `GeoPath` props it draws its lines with, + * as the core `Graticule` takes them + */ export type GraticuleProps = { /** Each meridian and parallel as its own line, styled by these (or the graticule's) props */ - lines?: LineProps | boolean; + lines?: Partial> | boolean; /** The graticule's outline, styled by these (or the graticule's) props */ - outline?: LineProps | boolean; + outline?: Partial> | boolean; /** Degrees between meridians. @default 10 */ stepX?: number; /** Degrees between parallels. @default 10 */ stepY?: number; -} & LineProps; +} & Partial; diff --git a/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte b/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte index b3374afa9e..5004908cc4 100644 --- a/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte +++ b/packages/webgl/src/lib/components/Graticule/Graticule.webgl.svelte @@ -14,7 +14,8 @@ {#if !lines && !outline} - + + {/if} {#if lines} diff --git a/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts b/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts index b13ee3815c..0cf9b4015f 100644 --- a/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts @@ -1,44 +1,83 @@ import type { TicksConfig } from 'layerchart'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; +/** How one axis' grid lines are drawn, as the core `Grid` forwards them onto its lines */ +export type GridLineProps = { + /** CSS classes to style them by (their stroke, width, and opacity) */ + class?: string; + stroke?: string; + /** Width in pixels, the same at any depth. @default 1 */ + strokeWidth?: number; + opacity?: number; + /** Dashed-line pattern: a dash length, `[dash, gap]`, or an SVG `stroke-dasharray`, in pixels */ + dashArray?: number | number[] | string; +}; + +/** + * The core `Grid`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`walls`, `fill`) + */ export type GridProps = { /** - * Draw lines at the `x` scale's ticks, across the floor and up the wall behind. + * Draw a x-axis lines, across the floor and up the wall behind. Pass props (class, stroke, + * strokeWidth, opacity, dashArray) to style them. * * @default true */ - x?: boolean; + x?: boolean | GridLineProps; /** - * Draw lines at the `y` scale's ticks, across the floor and up the wall behind. + * Draw a y-axis lines, across the floor and up the wall behind. Pass props (class, stroke, + * strokeWidth, opacity, dashArray) to style them. * * @default true */ - y?: boolean; + y?: boolean | GridLineProps; /** - * Draw lines at the `z` scale's ticks, around both walls. + * Draw lines at the `z` scale's ticks, around both walls, and pass props to style them. * * @default true */ - z?: boolean; - /** The `x` ticks: a count, values, or an interval, as for `Axis` */ + z?: boolean | GridLineProps; + /** Control the number of x-axis ticks: a count, values, or an interval, as for `Axis` */ xTicks?: TicksConfig; - /** The `y` ticks: a count, values, or an interval, as for `Axis` */ + /** Control the number of y-axis ticks: a count, values, or an interval, as for `Axis` */ yTicks?: TicksConfig; - /** The `z` ticks: a count, values, or an interval, as for `Axis` */ + /** Control the number of `z` gridlines: a count, values, or an interval, as for `Axis` */ zTicks?: TicksConfig; /** - * Shade the floor and the two walls away from the camera. The walls turn to stay behind - * the plot as the camera orbits, and only stand when the chart has height (`z`). Flat - * (without a `view`), the floor is left clear, as the core `Grid` leaves it. + * Line alignment when band scale is used (x or y axis): through each band's middle, or between + * the bands (and past the last). * - * @default true with a `view`, else false + * @default 'center' */ - walls?: boolean; + bandAlign?: 'center' | 'between'; /** - * The lines' CSS color. + * Stroke color for grid lines. * * @default 'color-mix(in oklab, var(--color-surface-content) 10%, transparent)' */ stroke?: string; + /** + * Classes to style the lines by (their stroke, width, and opacity): `root` for all of it, + * `line` for every line. + * + * @default {} + */ + classes?: { + root?: string; + line?: string; + }; + /** Ease each line to where its tick moves, ex. `'tween'` or `{ type: 'spring' }` */ + motion?: MotionProp; + + /** + * Shade the floor and the two walls away from the camera. The walls turn to stay behind + * the plot as the camera orbits, and only stand when the chart has height (`z`). Flat + * (without a `view`), the floor is left clear, as the core `Grid` leaves it. + * + * @default true with a `view`, else false + */ + walls?: boolean; /** The floor and walls' CSS color */ fill?: string; }; diff --git a/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte b/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte index 92f69256ad..089eff423b 100644 --- a/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte +++ b/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte @@ -1,9 +1,10 @@ + + + diff --git a/packages/webgl/src/lib/components/Line/Line.markers.svelte b/packages/webgl/src/lib/components/Line/Line.markers.svelte new file mode 100644 index 0000000000..1636e9033e --- /dev/null +++ b/packages/webgl/src/lib/components/Line/Line.markers.svelte @@ -0,0 +1,45 @@ + + + + + +{#if markerStart} + +{/if} +{#if markerMid} + +{/if} +{#if markerEnd} + +{/if} diff --git a/packages/webgl/src/lib/components/Line/Line.shared.svelte.ts b/packages/webgl/src/lib/components/Line/Line.shared.svelte.ts index 5325d8c04d..19da8f9f02 100644 --- a/packages/webgl/src/lib/components/Line/Line.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Line/Line.shared.svelte.ts @@ -1,35 +1,118 @@ import type { ColorProp, DataProp } from 'layerchart'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; +import type { MarkerOptions } from './markers.js'; +/** + * The core `Line`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`style`) + */ export type LineProps = { - /** Rows to draw a line each for (else the chart's, when an end reads them) */ - data?: any[]; - /** Where it starts across: a number of pixels, or a data key / function through the `x` scale */ + /** + * The x-coordinate of the line's starting point. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via xScale + * - `function(d)`: accessor called per data item, result passed through xScale + * + * @required + */ x1: DataProp; - /** Where it starts down: a number of pixels, or a data key / function through the `y` scale */ + /** The initial x-coordinate of the line's starting point (pixel mode only). @default x1 */ + initialX1?: number; + /** + * The y-coordinate of the line's starting point. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via yScale + * - `function(d)`: accessor called per data item, result passed through yScale + * + * @required + */ y1: DataProp; - /** Where it ends across, as `x1` */ + /** The initial y-coordinate of the line's starting point (pixel mode only). @default y1 */ + initialY1?: number; + /** + * The x-coordinate of the line's ending point. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via xScale + * - `function(d)`: accessor called per data item, result passed through xScale + * + * @required + */ x2: DataProp; - /** Where it ends down, as `y1` */ + /** The initial x-coordinate of the line's ending point (pixel mode only). @default x2 */ + initialX2?: number; + /** + * The y-coordinate of the line's ending point. + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via yScale + * - `function(d)`: accessor called per data item, result passed through yScale + * + * @default y2 + */ y2: DataProp; - /** Its start's height off the floor: pixels, or a data key / function through the `z` scale */ + /** + * The height of the line's start off the floor (on an `isometric` chart, or in a 3D view): a + * data property or accessor (through zScale), or pixels. + * + * @default 0 + */ z1?: DataProp; - /** Its end's height off the floor, as `z1` */ + /** The height of the line's end (see `z1`). @default 0 */ z2?: DataProp; + /** The initial y-coordinate of the line's ending point (pixel mode only). @default y2 */ + initialY2?: number; + /** + * Data array to iterate over in data mode. + * Falls back to chart context data when not provided. + */ + data?: any[]; + /** + * Key function for each row in data mode, which its `motion` eases by. + * + * @default (d, i) => i + */ + key?: (d: any, index: number) => any; /** - * A CSS color, or a data key / function run through the chart's color scale. + * Marker to attach to both start and end points of the line: drawn flat on the floor, turned + * along the line, in its color + */ + marker?: MarkerOptions; + /** Marker to attach to the start point of the line */ + markerStart?: MarkerOptions; + /** Marker to attach to the mid point of the line (a straight line has none) */ + markerMid?: MarkerOptions; + /** Marker to attach to the end point of the line */ + markerEnd?: MarkerOptions; + /** + * Motion configuration: each end eased to where it's asked to be (ex. `'tween'`, or per end, + * `{ x2: { type: 'tween', duration: 300 } }`), from `initialX1` ... in pixel mode + */ + motion?: MotionProp; + /** + * Dashed-line pattern. Accepts a number (single dash length), a `[dash, gap, ...]` array, or a + * string (same syntax as SVG `stroke-dasharray`), in pixels: its first dash and gap. + */ + dashArray?: number | number[] | string; + /** + * The stroke color. + * - `string`: in data mode, if it matches a data property name, the value is extracted and + * passed through cScale. Otherwise used as a literal CSS color. + * - `function(d)`: accessor called per data item, result passed through cScale. * * @default 'var(--color-surface-content)' */ stroke?: ColorProp; - /** @default 1 */ + /** The stroke opacity (0 to 1) @default 1 */ + strokeOpacity?: number; + /** The stroke width, in pixels @default 1 */ strokeWidth?: number; - /** @default 1 */ + /** The opacity (0 to 1) @default 1 */ opacity?: number; /** - * CSS classes to style it by, as the core marks take them (ex. `stroke-primary`): the stroke, - * stroke width, and opacity they set, where its props don't say + * CSS class name(s), as the core marks take them (ex. `stroke-primary`): the stroke, stroke + * width, and opacity they set, where its props don't say */ class?: string; + /** * Inline CSS, as on the core marks' elements (ex. `--fill-color: var(--color-primary)`): the * colors it sets, as LayerChart's styles read them diff --git a/packages/webgl/src/lib/components/Line/Line.webgl.svelte b/packages/webgl/src/lib/components/Line/Line.webgl.svelte index d16588163d..f2076f6fc8 100644 --- a/packages/webgl/src/lib/components/Line/Line.webgl.svelte +++ b/packages/webgl/src/lib/components/Line/Line.webgl.svelte @@ -4,20 +4,35 @@ + +{#if marker || markerStart || markerMid || markerEnd} + + lines.map((t) => ({ + points: [t.x1, t.z1 + LIFT, t.y1, t.x2, t.z2 + LIFT, t.y2], + color: t.stroke, + }))} + {strokeWidth} + opacity={opacity * (look?.opacity ?? 1)} + /> +{/if} diff --git a/packages/webgl/src/lib/components/Line/markers.ts b/packages/webgl/src/lib/components/Line/markers.ts new file mode 100644 index 0000000000..056b4002ac --- /dev/null +++ b/packages/webgl/src/lib/components/Line/markers.ts @@ -0,0 +1,84 @@ +import { line, type CurveFactory } from 'd3-shape'; +import type { LineProps as CoreLineProps } from 'layerchart'; +import { flattenPath } from '../../utils/path.js'; + +/** + * A marker, as the core marks take one: a type (`arrow`, `triangle`, `line`, `circle`, + * `circle-stroke`, `dot`, `square`, `square-stroke`), or the core `Marker`'s props. A snippet + * (custom SVG) can't be drawn in a scene, so draws nothing. + */ +export type MarkerOptions = NonNullable; + +/** A line to mark: its points (`[x, height, y]` each), color, and vertices for `markerMid` */ +export type MarkedLine = { + points: ArrayLike; + color: string; + /** The points between its first and last a mid marker goes on (ex. a path's corners) */ + mids?: number[]; +}; + +/** + * Where SVG path data's commands end, as indices into `flattenPath(d)`'s points, but for its + * first and last: the vertices an SVG path draws its `marker-mid` on, rather than every point + * its curves are drawn in + */ +export function pathVertices(d: string): number[] { + const fine = flattenPath(d); + // A piece per curve, so just where each command ends + const coarse = flattenPath(d, 1); + const vertices: number[] = []; + let from = 0; + for (const [x, y] of coarse) { + let i = from; + while (i < fine.length && (fine[i][0] !== x || fine[i][1] !== y)) i++; + if (i < fine.length) { + vertices.push(i); + from = i + 1; + } + } + return vertices.slice(1, -1); +} + +/** + * Where the commands of a d3 `curve` through `points` end, as indices into `sampled` (the curve's + * points `[x, height, y]` each, as `curvePoints` samples it): the vertices an SVG path of it draws + * its `marker-mid` on, first and last included + */ +export function curveVertices( + points: [number, number][], + curve: CurveFactory, + sampled: ArrayLike +): number[] { + const ends: [number, number][] = []; + let start: [number, number] = [0, 0]; + line() + .curve(curve) + .context({ + moveTo: (x: number, y: number) => ends.push((start = [x, y])), + lineTo: (x: number, y: number) => ends.push([x, y]), + bezierCurveTo: (_a: number, _b: number, _c: number, _d: number, x: number, y: number) => + ends.push([x, y]), + quadraticCurveTo: (_a: number, _b: number, x: number, y: number) => ends.push([x, y]), + closePath: () => ends.push(start), + arc() {}, + arcTo() {}, + rect() {}, + } as unknown as CanvasRenderingContext2D)(points); + // Each command's end is one of the points sampled, exactly (a curve's last step lands on it) + const vertices: number[] = []; + const count = Math.floor(sampled.length / 3); + let from = 0; + for (const [x, y] of ends) { + let i = from; + while ( + i < count && + (Math.abs(sampled[3 * i] - x) > 1e-6 || Math.abs(sampled[3 * i + 2] - y) > 1e-6) + ) + i++; + if (i < count) { + vertices.push(i); + from = i + 1; + } + } + return vertices; +} diff --git a/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts b/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts index 4880aa569f..5e34830665 100644 --- a/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Link/Link.shared.svelte.ts @@ -1,15 +1,17 @@ +import type { Snippet } from 'svelte'; +import type { draw as drawTransition } from 'svelte/transition'; import type { MotionNoneOption, MotionTweenOption } from 'layerchart/utils/motion.svelte'; import type { CurveFactory } from 'd3-shape'; import type { ColorProp, DataProp } from 'layerchart'; import type { LinkSweep, LinkType } from 'layerchart/utils/linkUtils'; import type { ValueProp } from '../../utils/values.js'; +import type { MarkerOptions } from '../Line/markers.js'; +/** + * The core `Link`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`arc`) + */ export type LinkProps = { - /** - * Rows to draw a link each for, or one link (as the core `Link` takes it). Falls back to the - * chart's data when `x1` / `y1` read rows. - */ - data?: any[] | any; /** * Where each link starts across the plot: a data property name or function of the row * through the chart's `x` scale (longitude on a map), or pixels @@ -30,11 +32,23 @@ export type LinkProps = { z1?: DataProp; /** The height of each link's end, as `z1`. @default 0 */ z2?: DataProp; + /** + * Rows to draw a link each for, or one link (as the core `Link` takes it). Falls back to the + * chart's data when `x1` / `y1` read rows. + */ + data?: any[] | any; + /** + * Draw a `Sankey` layout's link (`data`), as the core `Link`: from its source node's right + * edge (`x1`) at its `y0` to its target's left edge (`x0`) at its `y1`, across horizontally. + * + * @default false + */ + sankey?: boolean; /** * Without `x1` / `y1`: the node each link starts at (ex. a hierarchy's links), placed by `x` * and `y` in pixels. * - * @default (d) => d.source + * @default (d) => d.source (with `sankey`, the source node, at the link's `y0`) */ source?: (d: any) => any; /** The node each link ends at, as `source`. @default (d) => d.target */ @@ -58,41 +72,99 @@ export type LinkProps = { * @default 'd3' */ type?: LinkType; - /** The d3 curve for `type="d3"`. @default curveBumpY (curveBumpX with a horizontal `orientation`) */ - curve?: CurveFactory; - /** Which way the tree it links grows. @default 'vertical' */ - orientation?: 'vertical' | 'horizontal'; - /** Which way a preset path turns first, as the core `Link` */ - sweep?: LinkSweep; /** A `rounded` path's corner radius. @default 20 */ radius?: number; /** A `swoop` path's bend, in degrees. @default 22.5 */ bend?: number; + /** The d3 curve for `type="d3"`. @default curveBumpY (curveBumpX with a horizontal `orientation`) */ + curve?: CurveFactory; + /** Which way a preset path turns first, as the core `Link` */ + sweep?: LinkSweep; + /** Which way the tree it links grows. @default 'vertical' ('horizontal' with `sankey`) */ + orientation?: 'vertical' | 'horizontal'; /** - * How high each link arches above the straight line between its ends, in pixels (ex. flight - * paths over a map), or per row (a data key or function). + * Lay the link out around a circle, as the core `Link` on a `radial` chart: a node's `x` is + * its angle (radians) and `y` its distance from the center, which is the origin (ex. inside a + * `Group center`). Defaults to the chart's `radial`. + */ + radial?: boolean; + /** + * Marker to attach to both start and end points of the line: drawn flat on the floor, turned + * along the link, in its color + */ + marker?: MarkerOptions; + /** Marker to attach to the middle point of the line (each corner between its ends) */ + markerMid?: MarkerOptions; + /** Marker to attach to the start point of the line */ + markerStart?: MarkerOptions; + /** Marker to attach to the end point of the line */ + markerEnd?: MarkerOptions; + /** + * Tween each link to where it's asked to be, as the core `Link` (ex. `'tween'`, or `{ type: + * 'tween', duration: 300 }`) + */ + motion?: MotionTweenOption | MotionNoneOption; + /** + * CSS classes to style it by, as the core marks take them (ex. `stroke-surface-content/20`): + * the stroke, stroke width, and opacity they set, where its props don't say + */ + class?: string; + /** + * The `d` attribute of the rendered ``: SVG path data in the chart's pixels, drawn in + * place of the path between each link's ends (eased from its start's height to its end's). * - * @default 0 (straight) + * Accepts either a value (resolved at call site) or a function that returns the current value. */ - arc?: ValueProp; + pathData?: string | null | (() => string | null | undefined); + /** + * Whether to animate the drawing of the path over time. Pass either `true` or an object with + * transition options (`duration`, `delay`, `speed`, `easing`) to enable the transition. Each + * link is drawn from its start, again as the links change. + * + * Works best with `tweened` disabled. + */ + draw?: boolean | Parameters[1]; + /** + * Add additional content at the start of each link (ex. a `Text`, inside a `Group` there). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + startContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Add additional content at the end of each link (following it as `draw` draws it). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + endContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Raise every link `z` pixels off the floor, or to the end of `[start, end]` (an unfilled path + * is only raised, as the core `Path`'s), over its ends' own `z1` / `z2`. @default 0 + */ + z?: number | [start: number, end: number]; + /** + * The fill color of the element, or a function of the row: between a link's path and the + * chord across its ends, as an SVG path fills an open one. Only for a link lying flat (its + * ends at one height, without an `arc`, off a `globe`). + */ + fill?: string | null | ((d: any) => string | null | undefined); + /** The fill opacity of the element. @default 1 */ + fillOpacity?: number; /** * A CSS color, or a data key / function run through the chart's color scale. * * @default 'var(--color-surface-content)' */ stroke?: ColorProp; + /** The stroke opacity (0 to 1) @default 1 */ + strokeOpacity?: number; /** @default 1 */ strokeWidth?: number; /** @default 1 */ opacity?: number; + /** - * CSS classes to style it by, as the core marks take them (ex. `stroke-surface-content/20`): - * the stroke, stroke width, and opacity they set, where its props don't say - */ - class?: string; - /** - * Tween each link to where it's asked to be, as the core `Link` (ex. `'tween'`, or `{ type: - * 'tween', duration: 300 }`) + * How high each link arches above the straight line between its ends, in pixels (ex. flight + * paths over a map), or per row (a data key or function). + * + * @default 0 (straight) */ - motion?: MotionTweenOption | MotionNoneOption; + arc?: ValueProp; }; diff --git a/packages/webgl/src/lib/components/Link/Link.webgl.svelte b/packages/webgl/src/lib/components/Link/Link.webgl.svelte index cd17d8c033..217254ca15 100644 --- a/packages/webgl/src/lib/components/Link/Link.webgl.svelte +++ b/packages/webgl/src/lib/components/Link/Link.webgl.svelte @@ -4,8 +4,14 @@ + +{#if marker || markerStart || markerMid || markerEnd} + + links.map((link, i) => ({ + points: drawn[i], + color: link.stroke, + // Where its path's commands end (ex. a `square` link's corners), for `markerMid` alone + get mids() { + const d = link.path?.(); + return d ? pathVertices(d) : []; + }, + }))} + {strokeWidth} + opacity={opacity * (look?.opacity ?? 1)} + /> +{/if} + +{#if startContent || endContent} + {#each drawn as line, i (i)} + {@const ends = pathEnds([line], progress?.[i] ?? 1)} + {#if ends} + + {/if} + {/each} +{/if} diff --git a/packages/webgl/src/lib/components/Path/Path.ends.svelte b/packages/webgl/src/lib/components/Path/Path.ends.svelte new file mode 100644 index 0000000000..a2e816d9a0 --- /dev/null +++ b/packages/webgl/src/lib/components/Path/Path.ends.svelte @@ -0,0 +1,44 @@ + + + + + +{#if startContent && start} + + {@render startContent(propsAt(start))} + +{/if} +{#if endContent && end} + + {@render endContent(propsAt(end))} + +{/if} diff --git a/packages/webgl/src/lib/components/Path/Path.shared.svelte.ts b/packages/webgl/src/lib/components/Path/Path.shared.svelte.ts index 64d196e76e..661328826a 100644 --- a/packages/webgl/src/lib/components/Path/Path.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Path/Path.shared.svelte.ts @@ -1,32 +1,78 @@ +import type { Snippet } from 'svelte'; +import type { draw as drawTransition } from 'svelte/transition'; import type { MotionProp } from 'layerchart/utils/motion.svelte'; +import type { MarkerOptions } from '../Line/markers.js'; +/** + * The core `Path`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`class`) + */ export type PathProps = { /** - * SVG path data in the chart's pixels (ex. a d3 shape's, as the core `Path` takes it), or a - * function returning it. Lines, curves, and arcs, absolute or relative, in any number of - * subpaths. + * The `d` attribute of the rendered ``: SVG path data in the chart's pixels (ex. a d3 + * shape's), lines, curves, and arcs, absolute or relative, in any number of subpaths. + * + * Accepts either a value (resolved at call site) or a function that returns the current value. */ pathData?: string | null | (() => string | null | undefined); - /** A CSS color. Drawn only with one (here or in `class`), as subpaths filled between them */ + /** + * Whether to animate the drawing of the path over time. Pass either `true` or an object with + * transition options (`duration`, `delay`, `speed`, `easing`) to enable the transition. Drawn + * again as the path data changes. + * + * Works best with `tweened` disabled. + */ + draw?: boolean | Parameters[1]; + /** + * Marker to attach to both start and end points of the line: drawn flat on the floor, turned + * along the path, in its stroke color + */ + marker?: MarkerOptions; + /** Marker to attach to the middle point of the line (each vertex between its ends) */ + markerMid?: MarkerOptions; + /** Marker to attach to the start point of the line */ + markerStart?: MarkerOptions; + /** Marker to attach to the end point of the line */ + markerEnd?: MarkerOptions; + /** + * Add additional content at the start of the line (ex. a `Text`, inside a `Group` there). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + startContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Add additional content at the end of the line (following it as `draw` draws it). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + endContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Tween to new path data, as the core `Path` (ex. `'tween'`, or `{ type: 'tween', duration: + * 300 }`) + */ + motion?: MotionProp; + /** + * Stand the shape up `z` pixels off the floor (on an `isometric` chart, or in a 3D view), or + * between `[start, end]` (it lies at the top). @default 0 + */ + z?: number | [start: number, end: number]; + /** The fill color of the element. Drawn only with one (here or in `class`), between its subpaths */ fill?: string | null; - /** @default 1 */ + /** The fill opacity of the element. @default 1 */ fillOpacity?: number; - /** A CSS color. The outline, drawn without a `fill` in `surface-content` unless `none` */ + /** + * The stroke color of the element. Drawn without a `fill` in `surface-content` unless + * `none`. + */ stroke?: string | null; - /** Outline width in pixels. @default 1 */ + /** The stroke width of the element, in pixels. @default 1 */ strokeWidth?: number; + /** The stroke opacity of the element. (0 to 1) @default 1 */ + strokeOpacity?: number; + /** The opacity of the element. (0 to 1) @default 1 */ + opacity?: number; + /** * CSS classes to style it by, as the core marks take them (ex. `fill-primary/20 * stroke-primary`): the fill, stroke, stroke width, and opacity they set, where its props don't */ class?: string; - /** @default 1 */ - opacity?: number; - /** How far above the floor it lies, in pixels (the top of a `[start, end]` pair). @default 0 */ - z?: number | [start: number, end: number]; - /** - * Tween to new path data, as the core `Path` (ex. `'tween'`, or `{ type: 'tween', duration: - * 300 }`) - */ - motion?: MotionProp; }; diff --git a/packages/webgl/src/lib/components/Path/Path.webgl.svelte b/packages/webgl/src/lib/components/Path/Path.webgl.svelte index f115b720d3..66a05030e8 100644 --- a/packages/webgl/src/lib/components/Path/Path.webgl.svelte +++ b/packages/webgl/src/lib/components/Path/Path.webgl.svelte @@ -10,17 +10,29 @@ import { createMerged } from '../../utils/merged.svelte.js'; import { parsePath, type Subpath } from '../../utils/path.js'; import { createPathMotion } from '../../utils/rowMotion.svelte.js'; + import LineMarkers from '../Line/Line.markers.svelte'; + import { pathVertices } from '../Line/markers.js'; + import PathEnds from './Path.ends.svelte'; + import { createDraw, drawnSubpaths, lengthOf, pathEnds } from './draw.svelte.js'; let { pathData, + draw, + marker, + markerMid, + markerStart, + markerEnd, + startContent, + endContent, + motion, + z = 0, fill, fillOpacity = 1, stroke, strokeWidth: strokeWidthProp, - class: className, + strokeOpacity = 1, opacity = 1, - z = 0, - motion, + class: className, }: PathProps = $props(); const scene = getSceneContext(); @@ -74,6 +86,26 @@ /** A little above its fill, so its outline draws over it, as `Area`'s */ const LINE_LIFT = 0.3; + /** Its subpaths' outlines where they are now, in the scene's axes (across, up, down the plot) */ + const outlines = $derived( + drawn.map(({ points }) => points.flatMap(([px, py]) => [px, height + 0.1 + LINE_LIFT, py])) + ); + + // Drawing the outline from its start, as the core `Path`'s `draw` (an SVG `draw` transition): + // again whenever the path data changes + const drawing = untrack(() => draw) + ? createDraw( + () => draw, + () => [ + subpaths.reduce((sum, s) => sum + lengthOf(s.points.flatMap(([x, y]) => [x, 0, y])), 0), + ] + ) + : null; + /** How much of it is drawn so far (all of it without `draw`) */ + const progress = $derived( + drawing ? drawing.progress(outlines.reduce((sum, s) => sum + lengthOf(s), 0)) : 1 + ); + createMerged({ items: () => { if (!drawn.length) return []; @@ -95,18 +127,45 @@ d: undefined, geometry, fill: filled ? fillColor : null, - lines: outlined - ? drawn.map(({ points }) => - points.flatMap(([px, py]) => [px, height + 0.1 + LINE_LIFT, py]) - ) - : [], + // Each subpath from its own start, as SVG dashes it + lines: outlined ? drawnSubpaths(outlines, progress) : [], stroke: outlined ? strokeColor : null, }, ]; }, opacity: () => opacity * fillOpacity * (look?.opacity ?? 1), - lineOpacity: () => opacity * (look?.opacity ?? 1), + lineOpacity: () => opacity * strokeOpacity * (look?.opacity ?? 1), strokeWidth: () => strokeWidth, once: true, }); + + /** Where `marker-mid` goes: each command's end between its first and last (read only for it) */ + const vertices = $derived(d ? pathVertices(d) : []); + + /** Where `startContent` / `endContent` go, as the core `Path` places them (following `draw`) */ + const ends = $derived(startContent || endContent ? pathEnds(outlines, progress) : null); + +{#if outlined && (marker || markerStart || markerMid || markerEnd)} + [ + { + points: outlines.flat(), + color: strokeColor!, + get mids() { + return vertices; + }, + }, + ]} + {strokeWidth} + opacity={opacity * (look?.opacity ?? 1)} + /> +{/if} + +{#if ends} + +{/if} diff --git a/packages/webgl/src/lib/components/Path/draw.svelte.ts b/packages/webgl/src/lib/components/Path/draw.svelte.ts new file mode 100644 index 0000000000..23235bddb1 --- /dev/null +++ b/packages/webgl/src/lib/components/Path/draw.svelte.ts @@ -0,0 +1,126 @@ +import { untrack } from 'svelte'; +import { cubicInOut, linear } from 'svelte/easing'; +import { Tween } from 'svelte/motion'; +import type { PathProps } from './Path.shared.svelte.js'; + +/** A path's `draw`, as the core `Path` takes it */ +export type DrawOption = PathProps['draw']; + +/** + * Drawing paths from their starts, as the core `Path`'s `draw` (an SVG `draw` transition): again + * whenever the lengths read in `lengths` change (ex. new path data). Each path takes as long as + * `draw` gives one of its length (`duration`, or its length over `speed`), so the paths of one + * mark keep their own pace, as each SVG path's transition does. Call during component setup, and + * only with a `draw`. + */ +export function createDraw(draw: () => DrawOption, lengths: () => number[]) { + const options = () => { + const value = draw(); + return typeof value === 'object' ? value : {}; + }; + /** How long a path of `length` pixels takes, as the SVG `draw` transition works it out */ + const durationOf = (length: number) => { + const { duration, speed } = options(); + if (typeof duration === 'function') return duration(length); + return duration ?? (speed ? length / speed : 800); + }; + + /** Milliseconds since it started, up to the longest path's duration */ + const elapsed = new Tween(0, { easing: linear }); + let end = $state(0); + + $effect(() => { + const all = lengths(); + untrack(() => { + const longest = all.reduce((max, length) => Math.max(max, durationOf(length)), 0); + end = longest; + elapsed.set(0, { duration: 0 }); + elapsed.set(longest, { duration: longest, delay: options().delay ?? 0 }); + }); + }); + + return { + /** Whether every path is drawn */ + get done() { + return elapsed.current >= end; + }, + /** How much of a path of `length` pixels is drawn so far (0 to 1) */ + progress(length: number) { + if (elapsed.current >= end) return 1; + const duration = durationOf(length); + if (!(duration > 0)) return 1; + return (options().easing ?? cubicInOut)(Math.min(1, elapsed.current / duration)); + }, + }; +} + +/** A line's length, its points `[x, height, y]` each in a flat array, in pixels */ +export function lengthOf(points: ArrayLike) { + let length = 0; + for (let i = 3; i + 2 < points.length; i += 3) { + length += Math.hypot( + points[i] - points[i - 3], + points[i + 1] - points[i - 2], + points[i + 2] - points[i - 1] + ); + } + return length; +} + +/** + * A line's first `length` pixels (points `[x, height, y]` each): its points up to there, and one + * part way to the next. Its `i`th point is the line's own, but the last, which heads to it. + */ +export function truncate(points: ArrayLike, length: number): number[] { + const out: number[] = []; + if (points.length < 3) return out; + out.push(points[0], points[1], points[2]); + let left = length; + for (let i = 3; i + 2 < points.length && left > 0; i += 3) { + const [ax, ah, ay] = [points[i - 3], points[i - 2], points[i - 1]]; + const [bx, bh, by] = [points[i], points[i + 1], points[i + 2]]; + const step = Math.hypot(bx - ax, bh - ah, by - ay); + if (step <= left) out.push(bx, bh, by); + else { + const t = left / step; + out.push(ax + (bx - ax) * t, ah + (bh - ah) * t, ay + (by - ay) * t); + } + left -= step; + } + return out; +} + +/** + * Each of a path's subpaths as far as `draw` has drawn it (`progress` of their total length): from + * its own start, as SVG dashes each subpath + */ +export function drawnSubpaths(subpaths: number[][], progress: number): number[][] { + if (progress >= 1) return subpaths; + const length = progress * subpaths.reduce((sum, s) => sum + lengthOf(s), 0); + return subpaths.map((s) => truncate(s, length)); +} + +/** + * Where a path's `startContent` / `endContent` go, as the core `Path` places them: its first + * point, and the point `progress` of the way along it (its last, once drawn), `[x, height, y]` + */ +export function pathEnds( + subpaths: ArrayLike[], + progress = 1 +): { start: number[]; end: number[] } | null { + const first = subpaths.find((s) => s.length >= 3); + if (!first) return null; + const start = [first[0], first[1], first[2]]; + let rest = + progress >= 1 ? Infinity : progress * subpaths.reduce((sum, s) => sum + lengthOf(s), 0); + let end = start; + for (const s of subpaths) { + if (s.length < 3) continue; + const length = lengthOf(s); + const reached = rest < length ? truncate(s, rest) : s; + end = [reached[reached.length - 3], reached[reached.length - 2], reached[reached.length - 1]]; + if (rest < length) break; + rest -= length; + } + return { start, end }; +} diff --git a/packages/webgl/src/lib/components/Points/Points.base.svelte b/packages/webgl/src/lib/components/Points/Points.base.svelte index 4a64141978..350cb1be68 100644 --- a/packages/webgl/src/lib/components/Points/Points.base.svelte +++ b/packages/webgl/src/lib/components/Points/Points.base.svelte @@ -17,19 +17,22 @@ type Texture, } from 'three'; import { untrack } from 'svelte'; - import { getChartContext, isScaleLinear } from 'layerchart'; + import { accessor, getChartContext, isScaleLinear } from 'layerchart'; import { getSceneContext } from '../../contexts/scene.svelte.js'; - import { createInstances, ringGeometry } from '../../utils/instances.svelte.js'; + import { createInstances, ringGeometry, scaledDash } from '../../utils/instances.svelte.js'; + import { dashPattern } from '../../utils/merged.svelte.js'; import { loadTexture } from '../../utils/texture.js'; import { fieldOrValueOf, isUrl, valueOf } from '../../utils/values.js'; import { getSphere } from '../../utils/globe.js'; import { colorer, defined, linearShift, placer, resolveAccessor } from '../../utils/marks.js'; + import { createRowMotion } from '../../utils/rowMotion.svelte.js'; let { data: dataProp, x, y, + seriesKey, z, r, fill, @@ -47,6 +50,12 @@ offsetY, fillOpacity = 1, strokeOpacity = 1, + dashArray, + initialCx, + initialCy, + initialR, + key = (_d: any, i: number) => i, + motion, }: PointsProps = $props(); const ctx = getChartContext(); @@ -62,13 +71,58 @@ ctx.registerComponent({ name: 'Points', kind: 'mark', - markInfo: () => ({ data: dataProp, x, y, color: typeof fill === 'string' ? fill : undefined }), + markInfo: () => ({ + data: dataProp, + x, + y, + seriesKey, + color: typeof fill === 'string' ? fill : undefined, + }), }); - const rows = $derived((dataProp ?? ctx.data ?? []) as any[]); + /** + * The series it draws, as the core `Points`: its rows, value, and color. Looked up only with a + * `seriesKey`, so points without one don't read the series state. + */ + const series = $derived( + seriesKey == null ? undefined : ctx.series.series.find((s) => s.key === seriesKey) + ); + const seriesAccessor = $derived( + seriesKey == null ? undefined : ctx.series.valueAccessor(seriesKey) + ); + /** Faded while another series is highlighted, as that series' other marks are */ + const seriesOpacity = $derived( + series == null || + ctx.series.visibleSeries.length <= 1 || + ctx.series.isHighlighted(series.key, true) + ? 1 + : 0.1 + ); + /** At the top of its stack, as the core `Points`, when the chart stacks its series */ + const stack = $derived(ctx.stackAccessorsFor({ seriesKey, ownData: dataProp != null })); + + const rows = $derived((dataProp ?? series?.data ?? ctx.data ?? []) as any[]); const sphere = $derived(getSphere(ctx)); - const xAccessor = $derived(resolveAccessor(x, ctx.config.x)); - const yAccessor = $derived(resolveAccessor(y, ctx.config.y)); + const xAccessor = $derived( + resolveAccessor(x ?? (ctx.valueAxis === 'x' ? seriesAccessor : undefined), ctx.config.x) + ); + const yAccessor = $derived.by(() => { + if (y != null) return accessor(y); + if (stack) return stack.y1; + // A series' `[start, end]` value, at its end + if (Array.isArray(seriesAccessor) && ctx.valueAxis === 'y') return accessor(seriesAccessor[1]); + return resolveAccessor(ctx.valueAxis === 'y' ? seriesAccessor : undefined, ctx.config.y); + }); + /** Its fill without one of its own: its class's, else its series' (as core's), else `c`'s */ + const fillValue = $derived(fill ?? (look?.fill ? undefined : series?.color)); + + // Easing to where they're asked to be, as core's points (a `Circle` each), each by its `key`, a + // new one from `initialCx` / `initialCy` / `initialR` where they're given + const motionMap = createRowMotion( + untrack(() => motion), + ['cx', 'cy', 'r'] as const + ); + const initial = $derived({ cx: initialCx, cy: initialCy, r: initialR }); /** * Panning and zooming a linear `domain` moves every row's pixels by one scale and offset an @@ -76,7 +130,9 @@ * picking the right one): a great many rows pan and zoom as fast as a few */ const shiftable = $derived( - ctx.transform.mode === 'domain' && + // Easing points are placed afresh as they move + !motionMap && + ctx.transform.mode === 'domain' && !sphere && !ctx.geo.projection && image == null && @@ -109,11 +165,48 @@ return kx === 1 && tx === 0 && ky === 1 && ty === 0 ? null : shift; }); + if (motionMap) { + $effect(() => { + const pointOf = placed(); + const from = initial; + const active = new Set(); + rows.forEach((d, i) => { + const point = pointOf(d); + if (!point) return; + const k = key(d, i); + active.add(k); + const values = { cx: point.x, cy: point.y, r: point.radius }; + untrack(() => motionMap.update(k, values, from)); + }); + untrack(() => motionMap.cleanup(active)); + }); + } + /** - * Where each row's sphere is in the scene and how large (`null` off the chart), with what it - * reads of the chart read once: there can be a great many rows + * Where each row's sphere is now (`null` off the chart): where it's asked to be, or with + * `motion`, on its way there (a new one where it eases in from, until it starts) */ - function pointer() { + function pointer(): (d: any, i: number) => ReturnType> { + const pointOf = placed(); + if (!motionMap) return pointOf; + return (d, i) => { + const point = pointOf(d); + if (!point) return null; + const now = motionMap.get(key(d, i)) ?? initial; + return { + ...point, + x: now.cx ?? point.x, + y: now.cy ?? point.y, + radius: now.r ?? point.radius, + }; + }; + } + + /** + * Where each row's sphere is asked to be in the scene and how large (`null` off the chart), + * with what it reads of the chart read once: there can be a great many rows + */ + function placed() { const [xOf, yOf] = [xAccessor, yAccessor]; const at = placer(ctx, sphere, placedScales ?? undefined, { x: offsetX, y: offsetY }); const raised = ctx.config.z != null || z != null; @@ -144,10 +237,10 @@ geometry: () => (ctx.view ? (glow ? star : ball) : disc), instances: () => { const pointOf = pointer(); - const colorOf = colorer(ctx, fill, 'var(--color-primary, currentColor)', look?.fill); - return rows.flatMap((d: any) => { + const colorOf = colorer(ctx, fillValue, 'var(--color-primary, currentColor)', look?.fill); + return rows.flatMap((d: any, i: number) => { if (image != null && imageOf(d)) return []; - const point = pointOf(d); + const point = pointOf(d, i); if (!point) return []; // Inside its ring, so the two don't overlap (and darken where they're translucent) const radius = ringed ? Math.max(0, point.radius - strokeWidth / 2) : point.radius; @@ -165,7 +258,7 @@ ]; }); }, - opacity: () => opacity * fillOpacity * (look?.opacity ?? 1), + opacity: () => opacity * fillOpacity * seriesOpacity * (look?.opacity ?? 1), shift: () => shift, emphasize: (_color, size) => size.multiplyScalar(hoverScale), }); @@ -174,13 +267,14 @@ createInstances({ geometry: ringGeometry(), ring: () => (strokeWidth / 2) * scene.unit, + dash: () => scaledDash(dashPattern(dashArray), scene.unit), instances: () => { if (!ringed) return []; const pointOf = pointer(); const colorOf = colorer(ctx, stroke, 'currentColor', look?.stroke); - return rows.flatMap((d: any) => { + return rows.flatMap((d: any, i: number) => { if (image != null && imageOf(d)) return []; - const point = pointOf(d); + const point = pointOf(d, i); if (!point) return []; return [ { @@ -197,7 +291,7 @@ ]; }); }, - opacity: () => opacity * strokeOpacity * (look?.opacity ?? 1), + opacity: () => opacity * strokeOpacity * seriesOpacity * (look?.opacity ?? 1), shift: () => shift, emphasize: (_color, size) => size.multiplyScalar(hoverScale), }); @@ -206,9 +300,9 @@ const textured = $derived.by(() => { if (image == null) return []; const pointOf = pointer(); - return rows.flatMap((d) => { + return rows.flatMap((d, i) => { const source = imageOf(d); - const point = source ? pointOf(d) : null; + const point = source ? pointOf(d, i) : null; return point ? [{ ...point, source: source! }] : []; }); }); @@ -255,7 +349,7 @@ ); } const material = materialFor(point.source, !glow); - material.opacity = opacity * fillOpacity * (look?.opacity ?? 1); + material.opacity = opacity * fillOpacity * seriesOpacity * (look?.opacity ?? 1); material.transparent = material.opacity < 1; mesh.material = material; mesh.castShadow = mesh.receiveShadow = !glow; diff --git a/packages/webgl/src/lib/components/Points/Points.shared.svelte.ts b/packages/webgl/src/lib/components/Points/Points.shared.svelte.ts index 912043de16..db3f04eaa3 100644 --- a/packages/webgl/src/lib/components/Points/Points.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Points/Points.shared.svelte.ts @@ -4,10 +4,11 @@ import type { Accessor, ColorProp, DataProp } from 'layerchart'; import type { ImageSource } from '../../utils/texture.js'; import type { Offset } from '../../utils/marks.js'; import type { ValueProp } from '../../utils/values.js'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; /** - * The core `Points`' props (in its order, as it describes them), then those of a `WebGL` layer's - * own (`z`, `glow`, `image`, ...) + * The core `Points`' props (in its order, as it describes them, then those it takes from + * `Circle`), then those of a `WebGL` layer's own (`glow`, `image`, ...) */ export type PointsProps = { /** Override data instead of using context */ @@ -49,12 +50,6 @@ export type PointsProps = { strokeOpacity?: number; /** Overall opacity (0-1) @default 1 */ opacity?: number; - - /** - * Height off the floor: a data key or function (through the chart's `z` scale), or a number - * of pixels. Defaults to the chart's `z`. - */ - z?: DataProp; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): * the fill, stroke, stroke width, and opacity they set. A `mix-blend-mode` of `plus-lighter` @@ -62,6 +57,58 @@ export type PointsProps = { * overlap. */ class?: string; + /** + * Height off the floor: a data key or function (through the chart's `z` scale), or a number + * of pixels. Defaults to the chart's `z`. + */ + z?: DataProp; + /** + * The initial center x position of each new point, in pixels, to ease from with `motion`. + * + * @default its own + */ + initialCx?: number; + /** + * The initial center y position of each new point, in pixels, to ease from with `motion` (ex. + * the plot's bottom, to rise in). + * + * @default its own + */ + initialCy?: number; + /** + * Keep the points facing the viewer (round), as the core `Points` on an `isometric` chart. + * Always so here: a flat chart's points are discs seen from above, and a 3D view's are + * spheres, round from any side. + * + * @default false + */ + viewport?: boolean; + /** + * The initial radius of each new point, to ease from with `motion` (ex. `0` to grow in). + * + * @default its own + */ + initialR?: number; + /** + * Which point each row is as rows change, for `motion` (a new key eases in from + * `initialCx` / `initialCy` / `initialR`). + * + * @default (d, i) => i + */ + key?: (d: any, index: number) => unknown; + /** + * Ease each point to where it's asked to be, as the core `Points` (a `Circle` each) do (ex. + * `'spring'`, or `{ type: 'tween', duration: 300 }`), or each of `cx`, `cy`, and `r` by its + * own (ex. `{ r: 'spring' }`). None without it, at no cost. + */ + motion?: MotionProp<'cx' | 'cy' | 'r'>; + /** + * Dashed-border pattern. Accepts a number (single dash length), a + * `[dash, gap, ...]` array, or a string (same syntax as SVG + * `stroke-dasharray`), in pixels: its ring's (drawn flat), its first dash and gap repeating. + */ + dashArray?: number | number[] | string; + /** * Scale of the hovered point. * diff --git a/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts b/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts index e013e7af44..7051fc3c67 100644 --- a/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Polygon/Polygon.shared.svelte.ts @@ -1,18 +1,25 @@ import type { ColorProp, DataProp } from 'layerchart'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; +/** + * The core `Polygon`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`tooltip`) + */ export type PolygonProps = { - /** Rows to draw a polygon each for. Falls back to the chart's data when the props read rows. */ - data?: any[]; /** * Center across: a data property name or function of the row through the chart's `x` scale * (or longitude, through its projection), or pixels */ cx?: DataProp; + /** The initial center across a polygon placed by pixels eases from with `motion`. @default cx */ + initialCx?: number; /** * Center down: a data property name or function of the row through the chart's `y` scale (or * latitude, through its projection), or pixels */ cy?: DataProp; + /** The initial center down, as `initialCx`. @default cy */ + initialCy?: number; /** * Radius: a data property name or function of the row through the chart's `r` scale, or * pixels. @@ -20,6 +27,16 @@ export type PolygonProps = { * @default 1 */ r?: DataProp; + /** The initial radius, as `initialCx`. @default r */ + initialR?: number; + /** Rows to draw a polygon each for. Falls back to the chart's data when the props read rows. */ + data?: any[]; + /** + * Key function for each row in data mode, which its `motion` eases by. + * + * @default (d, i) => i + */ + key?: (d: any, index: number) => any; /** * The number of corners of a regular polygon about `cx` / `cy`, or the corners themselves, in * pixels. @@ -45,6 +62,12 @@ export type PolygonProps = { tiltX?: number; /** The tilt factor for y-coordinates. @default 0 */ tiltY?: number; + /** + * Ease each polygon's center and radius to where they're asked to be (ex. `'tween'`, or per + * prop, `{ r: { type: 'spring' } }`): a row at a time by its `key`, and one placed by pixels + * from `initialCx` ... + */ + motion?: MotionProp; /** * How tall it stands, as the core `Polygon` on an `isometric` chart: a data property name * or function of the row through the chart's `z` scale, pixels, or a `[start, end]` pair of @@ -59,15 +82,20 @@ export type PolygonProps = { fill?: ColorProp; /** The outline: a CSS color, or a key / function of the row run through the color scale */ stroke?: ColorProp; + /** The fill opacity (0 to 1) @default 1 */ + fillOpacity?: number; + /** The stroke opacity (0 to 1) @default 1 */ + strokeOpacity?: number; /** @default 1 */ strokeWidth?: number; + /** @default 1 */ + opacity?: number; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): * the fill, stroke, stroke width, and opacity they set, where its props don't say */ class?: string; - /** @default 1 */ - opacity?: number; + /** * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). * diff --git a/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte b/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte index d9683990ff..5276d13496 100644 --- a/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte +++ b/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte @@ -3,19 +3,25 @@ diff --git a/packages/webgl/src/lib/components/Raster/Raster.shared.svelte.ts b/packages/webgl/src/lib/components/Raster/Raster.shared.svelte.ts index 59d32f5f09..74d5436512 100644 --- a/packages/webgl/src/lib/components/Raster/Raster.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Raster/Raster.shared.svelte.ts @@ -1,6 +1,40 @@ import type { GridDataProps } from '../../utils/grid.js'; -export type RasterProps = GridDataProps & { +/** + * The core `Raster`'s props (in its order, as it describes them), then those of a `WebGL` + * layer's own (`z`, `tooltip`) + */ +export type RasterProps = { + /** + * Row-major grid values (with `width` and `height`), or rows of scattered samples (with `x`, + * `y`, and `value`) to interpolate onto a grid. + */ + data?: GridDataProps['data']; + /** Columns in a `data` grid */ + width?: number; + /** Rows in a `data` grid */ + height?: number; + /** Where a `data` grid's first column starts, in data coordinates (longitude on a map) */ + x1?: number; + /** Where a `data` grid's first row starts, in data coordinates (latitude on a map) */ + y1?: number; + /** Where a `data` grid's last column ends, in data coordinates */ + x2?: number; + /** Where a `data` grid's last row ends, in data coordinates */ + y2?: number; + /** + * A scattered row's value (a key or accessor), or a function `(x, y) => value` sampled across + * the plot in data coordinates (longitude and latitude on a map). + * + * @default 'value' + */ + value?: GridDataProps['value']; + /** A scattered row's `x`. Defaults to the chart's. */ + x?: GridDataProps['x']; + /** A scattered row's `y`. Defaults to the chart's. */ + y?: GridDataProps['y']; + /** @default 'barycentric' */ + interpolate?: GridDataProps['interpolate']; /** * Pixels between samples of a function, scattered rows, or a grid on a map. * @@ -8,19 +42,27 @@ export type RasterProps = GridDataProps & { */ pixelSize?: number; /** - * Height off the floor, in pixels. + * Blur the image over this many cells, smoothing between them. * * @default 0 */ - z?: number; - /** @default 1 */ - opacity?: number; + blur?: number; /** * `'pixelated'` shows each cell as a hard-edged square; `'auto'` blends between them. + * `'crisp-edges'` is `'pixelated'`. * * @default 'auto' */ - imageRendering?: 'auto' | 'pixelated'; + imageRendering?: 'auto' | 'pixelated' | 'crisp-edges'; + /** The opacity of the element. (0 to 1) @default 1 */ + opacity?: number; + + /** + * Height off the floor, in pixels. + * + * @default 0 + */ + z?: number; /** * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). * diff --git a/packages/webgl/src/lib/components/Raster/Raster.webgl.svelte b/packages/webgl/src/lib/components/Raster/Raster.webgl.svelte index 47e4c2419d..bee22d288f 100644 --- a/packages/webgl/src/lib/components/Raster/Raster.webgl.svelte +++ b/packages/webgl/src/lib/components/Raster/Raster.webgl.svelte @@ -15,7 +15,7 @@ NearestFilter, SRGBColorSpace, } from 'three'; - import { getChartContext } from 'layerchart'; + import { blurGridIgnoringNaN, getChartContext } from 'layerchart'; import { getSceneContext } from '../../contexts/scene.svelte.js'; import { getSphere } from '../../utils/globe.js'; @@ -30,6 +30,7 @@ let { pixelSize = 1, + blur = 0, z = 0, opacity = 1, imageRendering = 'auto', @@ -44,12 +45,28 @@ /** On a `globe`, the colors wrapped around it */ const sphere = $derived(getSphere(ctx)); - const sphereSamples = $derived( - sphere - ? sphereValues(sphere, gridProps, sphereSegments(sphere.radius, Math.max(pixelSize, 2))) - : null - ); - const grid = $derived(sphere ? null : sampleGrid(ctx, gridProps, pixelSize)); + /** `values` blurred over `blur` cells of a `columns` by `rows` grid, as the core `Raster` blurs */ + function blurred( + samples: T | null, + columns: number, + rows: number + ): T | null { + if (!samples || !(blur > 0)) return samples; + return { ...samples, values: blurGridIgnoringNaN(samples.values, columns, rows, blur) }; + } + const sphereSamples = $derived.by(() => { + if (!sphere) return null; + const samples = sphereValues( + sphere, + gridProps, + sphereSegments(sphere.radius, Math.max(pixelSize, 2)) + ); + return blurred(samples, samples.grid.columns, samples.grid.rows); + }); + const grid = $derived.by(() => { + const sampled = sphere ? null : sampleGrid(ctx, gridProps, pixelSize); + return sampled ? blurred(sampled, sampled.columns, sampled.rows) : null; + }); // An image of the grid's colors, unlit so they read true const material = new MeshBasicMaterial({ transparent: true, side: DoubleSide }); @@ -93,7 +110,7 @@ texture = new DataTexture(pixels, g.columns, g.rows); texture.colorSpace = SRGBColorSpace; texture.magFilter = texture.minFilter = - imageRendering === 'pixelated' ? NearestFilter : LinearFilter; + imageRendering !== 'auto' ? NearestFilter : LinearFilter; texture.needsUpdate = true; // The grid's first row is at its top (`top`), which is texture row 0 (`v = 0`) diff --git a/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts b/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts index 6817bb3a18..dfe6be8fec 100644 --- a/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Rect/Rect.shared.svelte.ts @@ -1,85 +1,190 @@ -import type { Corners } from 'layerchart/utils/rect.svelte'; +import type { Corners, Insets } from 'layerchart/utils/rect.svelte'; import type { MotionOptions } from 'layerchart/utils/motion.svelte'; import type { ColorProp, DataProp } from 'layerchart'; +import type { MarkEvents } from '../../contexts/scene.svelte.js'; +/** + * The core `Rect`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`tooltip`) + */ export type RectProps = { - /** Rows to draw a box each for. Falls back to the chart's data when the props read rows. */ - data?: any[]; /** - * Left edge: a data property name or function of the row through the chart's `x` scale, or - * pixels + * The x position of the rectangle (its left edge). + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via xScale + * - `function(d)`: accessor called per data item, result passed through xScale + * + * @default 0 */ x?: DataProp; /** - * Top edge (its far side, before the view turns): a data property name or function of the - * row through the chart's `y` scale, or pixels + * The initial x position (pixel mode only), as it eases in with `motion`. + * + * @default x + */ + initialX?: number; + /** + * The y position of the rectangle (its top edge: its far side, before the view turns). + * - `number`: pixel value (direct) + * - `string`: data property name, resolved via yScale + * - `function(d)`: accessor called per data item, result passed through yScale + * + * @default 0 */ y?: DataProp; - /** Width across `x`, in pixels: a number, data property name, or function of the row */ + /** + * The initial y position (pixel mode only), as it eases in with `motion`. + * + * @default y + */ + initialY?: number; + /** + * The width of the rectangle (pixels): a number, data property name, or function of the row. + * + * @default 0 + */ width?: DataProp; - /** Depth down `y`, in pixels: a number, data property name, or function of the row */ + /** The initial width (pixel mode only), as it eases in with `motion` */ + initialWidth?: number; + /** + * The height of the rectangle (pixels, down `y`): a number, data property name, or function of + * the row. + * + * @default 0 + */ height?: DataProp; - /** One side across `x`, as `x` (with `x1`, rather than `x` and `width`) */ + /** The initial height (pixel mode only), as it eases in with `motion` */ + initialHeight?: number; + /** + * Left/start x edge (data mode). + * - `string`: data property name, resolved via xScale + * - `function(d)`: accessor called per data item, result passed through xScale + * - `number`: pixel value + */ x0?: DataProp; - /** The other side across `x`, as `x` */ + /** + * Right/end x edge (data mode). + * - `string`: data property name, resolved via xScale + * - `function(d)`: accessor called per data item, result passed through xScale + * - `number`: pixel value + */ x1?: DataProp; - /** One side down `y`, as `y` (with `y1`, rather than `y` and `height`) */ + /** + * Top/start y edge (data mode). + * - `string`: data property name, resolved via yScale + * - `function(d)`: accessor called per data item, result passed through yScale + * - `number`: pixel value + */ y0?: DataProp; - /** The other side down `y`, as `y` */ + /** + * Bottom/end y edge (data mode). + * - `string`: data property name, resolved via yScale + * - `function(d)`: accessor called per data item, result passed through yScale + * - `number`: pixel value + */ y1?: DataProp; /** - * How tall each box stands: a data property name or function of the row through the chart's - * `z` scale (a function can return `[start, end]` to float the box between them), pixels, or - * a `[start, end]` pair of pixels. Defaults to the chart's `z` with rows, else a thin tile. + * Height to raise the rectangle into a box, defaulting to the chart's `z` in data mode (else a + * thin tile). + * - `string`: data property name, resolved via zScale + * - `function(d)`: accessor called per data item, result passed through zScale (or returning + * `[start, end]` to float the box between them) + * - `number`: pixel height (also in pixel mode) + * - `[start, end]`: pixel heights to float the box between */ z?: DataProp | [start: number, end: number]; /** - * A CSS color, or a key / function of the row run through the chart's color scale. - * `none` draws only its outline. + * Whether a box raised by `z` shades its sides, by the scene's lights. Without, each face is + * its own color, unlit. + * + * @default true + */ + shade?: boolean; + /** + * Insets to shrink the rendered rectangle. + * Supports `all`, `x`, `y`, `left`, `right`, `top`, `bottom`. + */ + insets?: Insets; + /** + * Data array to iterate over in data mode. + * Falls back to chart context data when not provided. + */ + data?: any[]; + /** + * Which box each row is as rows change, for `motion`. + * + * @default (d, i) => i + */ + key?: (d: any, index: number) => unknown; + /** + * Motion configuration, easing each box to where it's asked to be (ex. `'spring'`, or + * `{ type: 'tween', duration: 300 }`) + */ + motion?: MotionOptions; + /** + * Dashed-border pattern. Accepts a number (single dash length), a + * `[dash, gap, ...]` array, or a string (same syntax as SVG + * `stroke-dasharray`). Its first dash and gap repeat. + */ + dashArray?: number | number[] | string; + /** + * Per-corner radii, rounding a flat rect. Accepts a number (all corners equal — same as `rx`), + * a `[tl, tr, br, bl]` tuple, or `{ topLeft, topRight, bottomRight, bottomLeft }`. + * Takes precedence over `rx`. + */ + corners?: Corners; + /** + * The fill color: a CSS color, or a key / function of the row run through the chart's color + * scale. `none` draws only its outline. * * @default 'var(--color-surface-content)' */ fill?: ColorProp; + /** The fill opacity (0 to 1). @default 1 */ + fillOpacity?: number; /** - * The outline, as the core isometric boxes draw theirs: around each box's top and up its + * The stroke color, as the core isometric boxes draw theirs: around each box's top and up its * corners (ex. lines between a treemap's siblings). A CSS color, or a key / function of the * row run through the color scale. None without one (here or in `class`). */ stroke?: ColorProp; - /** Outline width in pixels, the same at any depth. @default 1 */ + /** The stroke width in pixels, the same at any depth. @default 1 */ strokeWidth?: number; + /** The stroke opacity (0 to 1). @default 1 */ + strokeOpacity?: number; + /** The opacity (0 to 1). @default 1 */ + opacity?: number; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): * the fill, stroke, stroke width, and opacity they set, where its props don't say */ class?: string; - /** @default 1 */ - opacity?: number; - /** Corner radius in pixels, rounding a flat rect, as the core `Rect`'s. @default 0 */ - rx?: number; - /** - * Per-corner radii, rounding a flat rect, as the core `Rect`'s: a number, a `[tl, tr, br, bl]` - * tuple, or `{ topLeft, topRight, bottomRight, bottomLeft }`. Wins over `rx`. - */ - corners?: Corners; - /** The fill's opacity, as the core `Rect`'s (its outline's is `opacity`). @default 1 */ - fillOpacity?: number; /** * Inline CSS, as on the core marks' elements (ex. `--fill-color: var(--color-primary)`): the * colors it sets, as LayerChart's styles read them */ style?: string; + /** Corner radius in pixels, rounding a flat rect. @default 0 */ + rx?: number; + /** Click event handler, called with the box's row (`{ data }`, none in pixel mode) */ + onclick?: MarkEvents['onclick']; + /** Double click event handler, called with the box's row */ + ondblclick?: MarkEvents['ondblclick']; + /** Pointer enter event handler, called with the box's row */ + onpointerenter?: MarkEvents['onpointerenter']; + /** Pointer move event handler, called with the box's row */ + onpointermove?: MarkEvents['onpointermove']; + /** Pointer leave event handler, called with the box's row */ + onpointerleave?: MarkEvents['onpointerleave']; + /** Pointer over event handler, called with the box's row */ + onpointerover?: MarkEvents['onpointerover']; + /** Pointer out event handler, called with the box's row */ + onpointerout?: MarkEvents['onpointerout']; + /** * Show the tooltip for the row the pointer is over (with the chart's `tooltipContext`). * * @default false */ tooltip?: boolean; - /** - * Ease each box to where it's asked to be, as the core `Rect` (ex. `'spring'`, or - * `{ type: 'tween', duration: 300 }`) - */ - motion?: MotionOptions; - /** Which box each row is as rows change, for `motion`. @default (d, i) => i */ - key?: (d: any, index: number) => unknown; }; diff --git a/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte b/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte index 373b03fa31..7414ebccfe 100644 --- a/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte +++ b/packages/webgl/src/lib/components/Rect/Rect.webgl.svelte @@ -5,14 +5,14 @@ @@ -193,11 +257,12 @@ corners={radiiOf} height={0.1} {filled} - stroke={(d) => - outlined ? rowColor(ctx, stroke, d, 'currentColor', look?.stroke, look?.strokeSet) : null} + stroke={(d) => (outlined ? strokeOf(d) : null)} {strokeWidth} - opacity={opacity * fillOpacity * (look?.opacity ?? 1)} - lineOpacity={opacity * (look?.opacity ?? 1)} - {tooltip} + opacity={fillAlpha} + lineOpacity={strokeAlpha} + tooltip={tooltip && dataMode} + {events} + {dashArray} /> {/if} diff --git a/packages/webgl/src/lib/components/Rule/Rule.shared.svelte.ts b/packages/webgl/src/lib/components/Rule/Rule.shared.svelte.ts index 9d84395ff8..3779a87ffa 100644 --- a/packages/webgl/src/lib/components/Rule/Rule.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Rule/Rule.shared.svelte.ts @@ -1,5 +1,9 @@ import type { Accessor } from 'layerchart'; +/** + * The core `Rule`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`z`, and its line's look) + */ export type RuleProps = { /** Override the data from the context */ data?: any[]; @@ -27,6 +31,12 @@ export type RuleProps = { y?: number | Date | boolean | '$top' | '$bottom' | Accessor; /** Pixel offset to apply to `y` coordinate. @default 0 */ yOffset?: number; + /** + * Series key to follow, fading the rule while another series is highlighted and removing it + * while the series is hidden. Only applicable if `` uses `series`. + */ + seriesKey?: string; + /** Pixels up off the floor to draw at. @default 0 */ z?: number; /** diff --git a/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte b/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte index 623a9d375f..c054677353 100644 --- a/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte +++ b/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte @@ -16,6 +16,7 @@ xOffset = 0, y = false, yOffset = 0, + seriesKey, z = 0, stroke, strokeWidth: strokeWidthProp, @@ -31,6 +32,24 @@ ctx.registerComponent({ name: 'Rule', kind: 'composite-mark' }); + /** + * The series it follows (as the core `Rule`'s `Group`), looked up only with a `seriesKey`, so + * rules without one don't read the series state + */ + const series = $derived( + seriesKey == null ? undefined : ctx.series.series.find((s) => s.key === seriesKey) + ); + /** Not drawn while the legend hides its series */ + const hidden = $derived(series != null && !ctx.series.isVisible(series.key)); + /** Faded while another series is highlighted, as that series' marks are */ + const seriesOpacity = $derived( + series == null || + ctx.series.visibleSeries.length <= 1 || + ctx.series.isHighlighted(series.key, true) + ? 1 + : 0.1 + ); + /** A single line across or down the plot, rather than one per row */ function single(value: unknown, scale: any, domain: unknown[], ends: string[]) { return ( @@ -105,14 +124,15 @@ createMerged({ items: () => - lines.map((line) => ({ + (hidden ? [] : lines).map((line) => ({ d: undefined, geometry: null, fill: null, lines: [[line.x1, z + 0.5, line.y1, line.x2, z + 0.5, line.y2]], stroke: line.stroke, })), - opacity: () => opacity * (look?.opacity ?? 1), + opacity: () => opacity * seriesOpacity * (look?.opacity ?? 1), + lineOpacity: () => opacity * seriesOpacity * (look?.opacity ?? 1), strokeWidth: () => strokeWidth, }); diff --git a/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts b/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts index a85d46262b..2de72706cb 100644 --- a/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts @@ -1,68 +1,114 @@ +import type { Snippet } from 'svelte'; +import type { draw as drawTransition } from 'svelte/transition'; import type { MotionProp } from 'layerchart/utils/motion.svelte'; import type { Accessor, ColorProp, DataProp } from 'layerchart'; import type { CurveFactory } from 'd3-shape'; +import type { MarkerOptions } from '../Line/markers.js'; +/** + * The core `Spline`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`tooltip`) + */ export type SplineProps = { - /** Override the chart's `data` */ + /** Override data instead of using context */ data?: any[]; - /** Override the chart's `x` accessor */ - x?: Accessor; - /** Override the chart's `y` accessor */ - y?: Accessor; /** * Height off the floor: a data key or function (through the chart's `z` scale), or a number * of pixels. Defaults to the chart's `z`. */ z?: DataProp; + /** Override `x` accessor from Chart context */ + x?: Accessor; + /** Override `y` accessor from Chart context */ + y?: Accessor; /** * Draw one line per distinct value, in data order. Defaults to the chart's `g`, else the * categorical data key `stroke` names, else the chart's `c` (as the core `Spline`). A numeric * key (`stroke="z"`) colors along the line instead. */ g?: Accessor; + /** + * Series key to use for accessor. Only applicable if `` uses `series` and `x`/`y` are + * not set. + */ + seriesKey?: string; + /** Whether a row is drawn: a line breaks at rows it isn't, as the core `Spline` does */ + defined?: (d: any, index: number, data: any[]) => boolean; + /** + * Curve of path drawn. Imported via d3-shape (ex. `curveMonotoneX`). Straight between rows + * without one. + */ + curve?: CurveFactory; /** * A CSS color, or a data key / function run through the chart's color scale — per row, so a - * line can change color along its length. Defaults to the chart's `c`, else - * `var(--color-primary)`. + * line can change color along its length. Defaults to the chart's `c`, else its series' + * color, else `var(--color-primary)`. */ stroke?: ColorProp; /** - * Line width in pixels, the same at any depth. - * - * @default 1 + * A CSS color to fill the shape each line closes around, as an SVG path fills an open line (ex. + * a `Hull`'s). None without one (here or in `class`). */ - strokeWidth?: number; + fill?: string | null; + /** @default 1 */ + opacity?: number; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): * the fill, stroke, stroke width, and opacity they set, where its props don't say */ class?: string; - /** @default 1 */ - opacity?: number; /** - * The d3 curve each line takes through its rows (ex. `curveMonotoneX`), as the core - * `Spline` draws it. Straight between them without one. + * Tween each line to where it's asked to be, as the core `Spline` (ex. `'tween'`, or `{ type: + * 'tween', duration: 300 }`), a new one up from the baseline. A spring leaves it, as core's. */ - curve?: CurveFactory; - /** Whether a row is drawn: a line breaks at rows it isn't, as the core `Spline` does */ - defined?: (d: any, index: number, data: any[]) => boolean; + motion?: MotionProp; + /** - * Show the tooltip for the row nearest where the pointer is over a line (with the chart's - * `tooltipContext`). + * Pass `` explicitly, drawn in place of the line its rows make: SVG path data in + * the chart's pixels, as the core `Path` draws it + */ + pathData?: string | null | (() => string | null | undefined); + /** + * Whether to animate the drawing of the path over time. Pass either `true` or an object with + * transition options (`duration`, `delay`, `speed`, `easing`) to enable the transition. Each + * line is drawn from its start, again as its rows change. * - * @default false + * Works best with `tweened` disabled. */ - tooltip?: boolean; + draw?: boolean | Parameters[1]; /** - * Tween each line to where it's asked to be, as the core `Spline` (ex. `'tween'`, or `{ type: - * 'tween', duration: 300 }`), a new one up from the baseline. A spring leaves it, as core's. + * Marker to attach to both start and end points of the line: drawn flat on the floor, turned + * along the line, in its stroke color */ - motion?: MotionProp; + marker?: MarkerOptions; + /** Marker to attach to the middle point of the line (each row between its ends) */ + markerMid?: MarkerOptions; + /** Marker to attach to the start point of the line */ + markerStart?: MarkerOptions; + /** Marker to attach to the end point of the line */ + markerEnd?: MarkerOptions; /** - * A CSS color to fill the shape each line closes around, as an SVG path fills an open line (ex. - * a `Hull`'s). None without one (here or in `class`). + * Add additional content at the start of the line (one per line). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. */ - fill?: string | null; - /** @default 1 */ + startContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** + * Add additional content at the end of the line (following it as `draw` draws it). + * Receives `{ point: DOMPoint; value: { x: number; y: number } }` as a snippet prop. + */ + endContent?: Snippet<[{ point: DOMPoint; value: { x: number; y: number } }]>; + /** The fill opacity of the element. @default 1 */ fillOpacity?: number; + /** The stroke opacity of the element. (0 to 1) @default 1 */ + strokeOpacity?: number; + /** Line width in pixels, the same at any depth. @default 1 */ + strokeWidth?: number; + + /** + * Show the tooltip for the row nearest where the pointer is over a line (with the chart's + * `tooltipContext`). + * + * @default false + */ + tooltip?: boolean; }; diff --git a/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte b/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte index ca845c63f4..666022d1fc 100644 --- a/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte +++ b/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte @@ -17,6 +17,11 @@ import { curvePoints } from '../../utils/curve.js'; import { defined, position, resolveAccessor, rowColor } from '../../utils/marks.js'; import { createPathMotion } from '../../utils/rowMotion.svelte.js'; + import LineMarkers from '../Line/Line.markers.svelte'; + import { curveVertices } from '../Line/markers.js'; + import PathEnds from '../Path/Path.ends.svelte'; + import PathWebGL from '../Path/Path.webgl.svelte'; + import { createDraw, drawnSubpaths, lengthOf, pathEnds } from '../Path/draw.svelte.js'; import SplineFill from './Spline.fill.svelte'; let { @@ -25,6 +30,7 @@ y, z, g, + seriesKey, stroke, strokeWidth: strokeWidthProp, class: className, @@ -34,7 +40,16 @@ tooltip = false, motion, fill: fillProp, + pathData, + draw, + marker, + markerMid, + markerStart, + markerEnd, + startContent, + endContent, fillOpacity = 1, + strokeOpacity = 1, }: SplineProps = $props(); const ctx = getChartContext(); @@ -53,21 +68,45 @@ data: dataProp, x, y, + seriesKey, color: typeof stroke === 'string' ? stroke : undefined, }), }); + /** + * The series it draws, as the core `Spline`: its rows, value, and color. Looked up only with a + * `seriesKey`, so lines without one don't read the series state. + */ + const series = $derived( + seriesKey == null ? undefined : ctx.series.series.find((s) => s.key === seriesKey) + ); + const seriesAccessor = $derived( + seriesKey == null ? undefined : ctx.series.valueAccessor(seriesKey) + ); + /** Faded while another series is highlighted, as the core `Spline` */ + const seriesOpacity = $derived( + series == null || + ctx.series.visibleSeries.length <= 1 || + ctx.series.isHighlighted(series.key, true) + ? 1 + : 0.1 + ); + const sphere = $derived(getSphere(ctx)); - const xAccessor = $derived(resolveAccessor(x, ctx.config.x)); + const xAccessor = $derived( + resolveAccessor(x ?? (ctx.valueAxis === 'x' ? seriesAccessor : undefined), ctx.config.x) + ); /** * A line in a stack follows its top, as the core `Spline` (ex. over a stacked `Area`), when the * chart stacks (`seriesLayout`) and the line reads its rows */ - const stack = $derived(ctx.stackAccessorsFor({ ownData: dataProp != null })); + const stack = $derived(ctx.stackAccessorsFor({ seriesKey, ownData: dataProp != null })); const yAccessor = $derived( - y == null && ctx.valueAxis === 'y' && stack ? stack.y1 : resolveAccessor(y, ctx.config.y) + y == null && ctx.valueAxis === 'y' && stack + ? stack.y1 + : resolveAccessor(y ?? (ctx.valueAxis === 'y' ? seriesAccessor : undefined), ctx.config.y) ); - const rows = $derived((dataProp ?? ctx.data ?? []) as any[]); + const rows = $derived((dataProp ?? series?.data ?? ctx.data ?? []) as any[]); /** * What splits the rows into lines: this mark's `g`, the chart's `g`, the categorical data key @@ -80,20 +119,32 @@ const first = rows[0]; const implied = colorPropGroupKey(stroke, first); if (implied != null) return accessor(implied); - if (dataProp != null) return null; + if (dataProp != null || series?.data != null) return null; return first != null && ctx.cKey(first) != null ? ctx.cKey : null; }); + type Segment = { + positions: number[]; + colors: string[]; + data: any[]; + /** Which of its rows' lines it's a piece of (a gap breaks one into pieces) */ + group: number; + /** On a globe, which of its points are its rows' (the rest arc between them) */ + rowPoints?: number[]; + /** Along a `curve`, the points it was drawn through, on the floor */ + floor?: [number, number][]; + }; + + /** Its lines, broken into pieces where a row isn't drawn (none with its own `pathData`) */ const lines = $derived( - (gAccessor ? [...group(rows, gAccessor).values()] : [rows]) - .flatMap((lineRows) => { - type Line = { positions: number[]; colors: string[]; data: any[] }; - const segments: Line[] = []; - let line: Line = { positions: [], colors: [], data: [] }; + (pathData != null ? [] : gAccessor ? [...group(rows, gAccessor).values()] : [rows]) + .flatMap((lineRows, groupIndex) => { + const segments: Segment[] = []; + let line: Segment = { positions: [], colors: [], data: [], group: groupIndex }; /** A gap: the line so far is one segment, and the next row starts another */ const breakLine = () => { if (line.data.length) segments.push(line); - line = { positions: [], colors: [], data: [] }; + line = { positions: [], colors: [], data: [], group: groupIndex }; previous = null; previousRow = null; }; @@ -112,7 +163,7 @@ ctx, stroke, d, - 'var(--color-primary, currentColor)', + series?.color ?? 'var(--color-primary, currentColor)', look?.stroke, look?.strokeSet ); @@ -120,6 +171,9 @@ // Over the globe, along the great circle from the last row const here: [number, number, number] = [Number(xValue), Number(yValue), height]; const arc = previous ? sphereArc(sphere, previous, here) : sphere.toScene(...here); + (line.rowPoints ??= []).push( + line.positions.length / 3 + (previous ? arc.length / 3 - 2 : 0) + ); for (let k = previous ? 3 : 0; k < arc.length; k += 3) { line.positions.push(arc[k], arc[k + 1], arc[k + 2]); line.colors.push(color); @@ -148,7 +202,7 @@ ); /** A line's points taken along `curve`, each sampled point's height, color, and row from between its own */ - function curved(line: { positions: number[]; colors: string[]; data: any[] }) { + function curved(line: Segment): Segment { const count = line.data.length; if (count < 2 || !curve) return line; const floor: [number, number][] = []; @@ -157,7 +211,7 @@ floor.push([line.positions[i * 3], line.positions[i * 3 + 2]]); heights.push(line.positions[i * 3 + 1]); } - const out = { positions: [] as number[], colors: [] as string[], data: [] as any[] }; + const out: Segment = { positions: [], colors: [], data: [], group: line.group, floor }; for (const { x, y, at } of curvePoints(floor, curve)) { const k = Math.min(Math.floor(at), count - 1); const t = at - k; @@ -206,13 +260,62 @@ ) ); + /** Each line's segments (its pieces between gaps), as indices into `lines` */ + const groups = $derived.by(() => { + const out: number[][] = []; + lines.forEach((line, i) => (out[line.group] ??= []).push(i)); + return out.filter(Boolean); + }); + + // Drawing each line from its start, as the core `Spline`'s `draw` (its path's): again whenever + // the lines change + const drawing = untrack(() => draw) + ? createDraw( + () => draw, + () => + groups.map((members) => members.reduce((sum, i) => sum + lengthOf(lines[i].positions), 0)) + ) + : null; + /** How much of each line is drawn so far, by its group (all of it without `draw`) */ + const progress = $derived( + groups.map((members) => + drawing ? drawing.progress(members.reduce((sum, i) => sum + lengthOf(drawn[i]), 0)) : 1 + ) + ); + /** Each segment as far as it's drawn: from its own start, as SVG dashes each piece of a path */ + const shown = $derived.by(() => { + if (!drawing || drawing.done) return drawn; + const out = drawn.slice(); + groups.forEach((members, g) => { + const cut = drawnSubpaths( + members.map((i) => drawn[i]), + progress[g] + ); + members.forEach((i, k) => (out[i] = cut[k])); + }); + return out; + }); + + /** Set a line's points (fewer as `draw` draws it), and its colors to match */ + function place(line: Line2, points: number[]) { + const count = Math.floor(points.length / 3); + // A single point would still draw its round cap + line.visible = count >= 2; + if (count < 2) return; + line.geometry.setPositions(points); + if (line.userData.count !== count) { + line.geometry.setColors((line.userData.rgb as number[]).slice(0, count * 3)); + line.userData.count = count; + } + } + /** The lines' objects, whose points `drawn` moves */ let objects = $state.raw<{ line: Line2; removePickable: (() => void) | null }[]>([]); $effect(() => { const created = lines.map(({ positions, colors, data }, index) => { const geometry = new LineGeometry(); - geometry.setPositions(untrack(() => drawn[index] ?? positions)); + geometry.setPositions(positions); // A color per point, blended between them; a line's alpha is its first point's const rgb: number[] = []; let alpha = 1; @@ -222,13 +325,24 @@ if (i === 0) alpha = resolved?.opacity ?? 1; }); geometry.setColors(rgb); + const lineOpacity = opacity * strokeOpacity * (look?.opacity ?? 1) * alpha; + const faded = lineOpacity * untrack(() => seriesOpacity); const material = new LineMaterial({ vertexColors: true, linewidth: strokeWidth, - transparent: opacity * (look?.opacity ?? 1) * alpha < 1, - opacity: opacity * (look?.opacity ?? 1) * alpha, + transparent: faded < 1, + opacity: faded, }); const line = new Line2(geometry, material); + line.userData.opacity = lineOpacity; + line.userData.rgb = rgb; + line.userData.count = positions.length / 3; + // As far as it's drawn, or where it tweens from + if (pathMotion || drawing) + place( + line, + untrack(() => shown[index] ?? positions) + ); layer.add(line); // Each segment's row is the one at its nearer end const removePickable = tooltip @@ -261,22 +375,118 @@ }; }); - // Moving the lines' points as they tween, without making them again + // Fading with its series as the legend highlights another, without making the lines again + if (untrack(() => seriesKey) != null) { + $effect(() => { + const fade = seriesOpacity; + for (const { line } of untrack(() => objects)) { + const material = line.material; + material.opacity = line.userData.opacity * fade; + if (material.transparent !== material.opacity < 1) { + material.transparent = material.opacity < 1; + material.needsUpdate = true; + } + } + scene.invalidate(); + }); + } + + // Moving the lines' points as they tween (or `draw` draws them), without making them again $effect(() => { - if (!pathMotion) return; - const points = drawn; + if (!pathMotion && !drawing) return; + const points = shown; untrack(() => objects).forEach(({ line }, i) => { - if (points[i]) line.geometry.setPositions(points[i]); + if (points[i]) place(line, points[i]); }); scene.invalidate(); }); + + /** + * Where a line's path's commands end, as indices into its segments' points end to end: each + * row's point, or along a `curve`, each of its commands' (read only for `markerMid`) + */ + function vertices(members: number[]) { + const out: number[] = []; + let offset = 0; + for (const i of members) { + const line = lines[i]; + const own = line.floor + ? curveVertices(line.floor, curve!, line.positions) + : (line.rowPoints ?? line.data.map((_, k) => k)); + for (const k of own) out.push(offset + k); + offset += line.positions.length / 3; + } + return out; + } + +{#if pathData != null} + +{/if} + +{#if pathData == null && (marker || markerStart || markerMid || markerEnd)} + + groups.map((members) => ({ + // One path through its segments, as the core `Spline`'s + points: members.flatMap((i) => drawn[i] ?? lines[i].positions), + color: lines[members[0]].colors[0], + // Each vertex between its ends (a gap's ends too, as an SVG path's subpaths') + get mids() { + return vertices(members).slice(1, -1); + }, + }))} + {strokeWidth} + opacity={opacity * seriesOpacity * (look?.opacity ?? 1)} + /> +{/if} + +{#if pathData == null && (startContent || endContent)} + {#each groups as members, g (g)} + {@const ends = pathEnds( + members.map((i) => drawn[i] ?? lines[i].positions), + progress[g] + )} + {#if ends} + + {/if} + {/each} +{/if} + {#if fillColor} ({ positions: drawn[i] ?? line.positions, data: line.data }))} fill={fillColor} - opacity={opacity * fillOpacity * (look?.opacity ?? 1)} + opacity={opacity * fillOpacity * seriesOpacity * (look?.opacity ?? 1)} /> {/if} diff --git a/packages/webgl/src/lib/components/Text/Text.shared.svelte.ts b/packages/webgl/src/lib/components/Text/Text.shared.svelte.ts index fe228165f8..332338b8f2 100644 --- a/packages/webgl/src/lib/components/Text/Text.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Text/Text.shared.svelte.ts @@ -1,76 +1,97 @@ import type { ColorProp, DataProp, TruncateTextOptions } from 'layerchart'; +import type { MotionProp } from 'layerchart/utils/motion.svelte'; import type { FormatConfig, FormatType } from '@layerstack/utils'; import type { ValueProp } from '../../utils/values.js'; +/** A run of text in its own style, as the core `Text`'s `segments` take them */ +export type TextSegment = { + value: string | number; + /** Classes styling this run (ex. `font-bold fill-primary`), over the label's own */ + class?: string; +}; + +/** + * The core `Text`'s props (in its order, as it describes them), then those of a `WebGL` layer's + * own (`fontWeight`), and its letters' look + */ export type TextProps = { - /** Rows to draw a label each for. Falls back to the chart's data when `x` / `y` read rows. */ - data?: any[]; - /** The text: a data property name (with rows), a function of the row, or the text itself */ - value: string | number | ((d: any) => string | number | null | undefined); /** - * Across the plot: a data property name or function of the row through the chart's `x` scale - * (longitude on a map), or pixels. Defaults to the chart's `x` with rows. + * Text value to render. + * - `number`: direct value + * - `string`: in data mode, treated as a data property name (e.g. `"label"` → `d.label`); + * in pixel mode, used as literal text + * - `function(d)`: accessor called per data item to get the text value */ - x?: DataProp; + value?: string | number | ((d: any) => string | number | null | undefined); /** - * Down the plot: a data property name or function of the row through the chart's `y` scale - * (latitude on a map), or pixels. Defaults to the chart's `y` with rows. + * Array of styled text segments for inline mixed styling. + * Each segment has its own value and optional class (its color, font size, and weight). + * Mutually exclusive with `value`. */ - y?: DataProp; + segments?: TextSegment[]; + /** Wrap words onto more lines to keep each label within this many pixels */ + width?: number; /** - * Height off the floor: a data property name or function of the row through the chart's `z` - * scale, or pixels. Defaults to the chart's `z` with rows, else `0`. + * Across the plot: a data property name or function of the row through the chart's `x` scale + * (longitude on a map), or pixels. Defaults to the chart's `x` with rows. */ - z?: DataProp; + x?: DataProp; /** - * Keep each label facing the viewer, drawn over the scene upright and crisp however the view - * turns (styled with `class`). Otherwise it lies on the surface at its height (ex. the tops - * of boxes), turning and tipping with the view, and hidden behind whatever's nearer. + * Initial x position of the text (pixel mode only), in pixels, to ease from with `motion`. * - * @default false + * @default x */ - viewport?: boolean; + initialX?: number; /** - * Which end of a label is at its point: its `start`, `middle`, or `end` as it reads. Lying on - * the surface, it stays on that side of the point as the view turns. - * - * @default 'middle' + * Down the plot: a data property name or function of the row through the chart's `y` scale + * (latitude on a map), or pixels. Defaults to the chart's `y` with rows. */ - textAnchor?: 'start' | 'middle' | 'end'; + y?: DataProp; /** - * Which part of a label is at its point, as the core `Text`: its cap height's top (`start`), - * its middle (`middle`), or its baseline (`end`). + * Initial y position of the text (pixel mode only), in pixels, to ease from with `motion`. * - * @default 'end' + * @default y */ - verticalAnchor?: 'start' | 'middle' | 'end'; + initialY?: number; /** Pixels to move each label across: on screen with `viewport`, else across the plot */ dx?: number; /** Pixels to move each label down: on screen with `viewport`, else down the plot */ dy?: number; - /** How to format a number or date `value` (as the core `format`) */ - format?: FormatType | FormatConfig; - /** Wrap words onto more lines to keep each label within this many pixels */ - width?: number; /** Line spacing of wrapped labels, in multiples of the font size (or `'1.2em'`) */ lineHeight?: number | string; - /** Shorten each label with an ellipsis to fit `width` (or as the options say) */ - truncate?: boolean | TruncateTextOptions; - /** Shrink a label lying on the surface to fit `width`, rather than wrapping it */ - scaleToFit?: boolean; /** * Font size in pixels of the plot, for labels lying on the surface, or per row (a data key or - * function). + * function). When set, `capHeight` defaults to `fontSize * 0.71`. * * @default the chart's (or its `class`'s) font size, as a core label */ fontSize?: ValueProp; /** - * Font weight, for labels lying on the surface. + * Cap height of the text — used by vertical anchor math to align the text to its visual + * center (as opposed to the font box), for labels lying on the surface: pixels, or `'px'` / + * `'em'` (of 16px) as the core `Text` reads it. * - * @default the chart's (or its `class`'s) font weight, as a core label + * @default '0.71em' (or `fontSize * 0.71` when `fontSize` is set) */ - fontWeight?: number | string; + capHeight?: string | number; + /** Shrink a label lying on the surface to fit `width`, rather than wrapping it */ + scaleToFit?: boolean; + /** + * Which end of a label is at its point: its `start`, `middle`, or `end` as it reads. Lying on + * the surface, it stays on that side of the point as the view turns. + * + * @default 'middle' + */ + textAnchor?: 'start' | 'middle' | 'end'; + /** + * Which part of a label is at its point, as the core `Text`: its cap height's top (`start`), + * its middle (`middle`), or its baseline (`end`). + * + * @default 'end' + */ + verticalAnchor?: 'start' | 'middle' | 'end'; + /** Where its baseline sits on `path` (`'hanging'`, `'middle'`, else on it) */ + dominantBaseline?: string; /** * Which way labels lying on the surface run, in degrees clockwise from left to right across the plot, * or per row (a data key or function). @@ -79,6 +100,32 @@ export type TextProps = { * @default 0 */ rotate?: ValueProp; + /** + * Keep each label facing the viewer, drawn over the scene upright and crisp however the view + * turns (styled with `class`). Otherwise it lies on the surface at its height (ex. the tops + * of boxes), turning and tipping with the view, and hidden behind whatever's nearer. + * + * @default false + */ + viewport?: boolean; + /** + * Height off the floor: a data property name or function of the row through the chart's `z` + * scale, or pixels. Defaults to the chart's `z` with rows, else `0`. + */ + z?: DataProp; + /** + * How to format a number or date `value` (as the core `format`). When set with `motion` and a + * numeric `value`, the number will tween smoothly and be formatted for display. + */ + format?: FormatType | FormatConfig; + /** + * Ease each label to where it's asked to be, as the core `Text` (ex. `'spring'`, or + * `{ type: 'tween', duration: 300 }`), each by its `key`, or each of `x` and `y` by its own + * (ex. `{ y: 'spring' }`). A numeric `value` tweens too (pixel mode, with a `{ type }`). + */ + motion?: MotionProp<'x' | 'y'>; + /** Shorten each label with an ellipsis to fit `width` (or as the options say) */ + truncate?: boolean | TruncateTextOptions; /** * SVG path data to place it along, as the core `Text` sets it on a path (ex. from `Arc`'s * `getArcTextProps('outer')`): at `startOffset`, turned the way the path runs there (straight, @@ -87,8 +134,21 @@ export type TextProps = { path?: string; /** How far along `path`: pixels, or a percentage of its length (ex. `'50%'`). @default 0 */ startOffset?: string | number; - /** Where its baseline sits on `path` (`'hanging'`, `'middle'`, else on it) */ - dominantBaseline?: string; + /** Rows to draw a label each for. Falls back to the chart's data when `x` / `y` read rows. */ + data?: any[]; + /** + * Which label each row is as rows change, for `motion`. + * + * @default (d, i) => i + */ + key?: (d: any, index: number) => unknown; + + /** + * Font weight, for labels lying on the surface. + * + * @default the chart's (or its `class`'s) font weight, as a core label + */ + fontWeight?: number | string; /** * The labels' color: a CSS color, or a data key / function run through the chart's color * scale. `viewport` labels without one take their color from `class`. @@ -104,6 +164,24 @@ export type TextProps = { stroke?: ColorProp; /** The halo's width in pixels, half of it outside the letters. @default 1 */ strokeWidth?: number; + /** + * The fill opacity (0 to 1). + * - `number`: static value + * - `function(d)`: accessor called per data item + */ + fillOpacity?: number | ((d: any) => number | undefined); + /** + * The stroke opacity (0 to 1): its halo's. + * - `number`: static value + * - `function(d)`: accessor called per data item + */ + strokeOpacity?: number | ((d: any) => number | undefined); + /** + * The opacity (0 to 1): of the whole label, its halo and letters together. + * - `number`: static value + * - `function(d)`: accessor called per data item + */ + opacity?: number | ((d: any) => number | undefined); /** Class added to each `viewport` label */ class?: string; }; diff --git a/packages/webgl/src/lib/components/Text/Text.webgl.svelte b/packages/webgl/src/lib/components/Text/Text.webgl.svelte index c3d65ee94a..07e21fa42c 100644 --- a/packages/webgl/src/lib/components/Text/Text.webgl.svelte +++ b/packages/webgl/src/lib/components/Text/Text.webgl.svelte @@ -4,7 +4,8 @@ diff --git a/packages/webgl/src/lib/components/__fixtures__/Lines.svelte b/packages/webgl/src/lib/components/__fixtures__/Lines.svelte new file mode 100644 index 0000000000..20f27095fa --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/Lines.svelte @@ -0,0 +1,64 @@ + + +{#snippet start(props: { point: DOMPoint; value: any })} + {onContent?.('start', props)} +{/snippet} +{#snippet end(props: { point: DOMPoint; value: any })} + {onContent?.('end', props)} +{/snippet} + +
+ + + {#if mark === 'line'} + + {:else if mark === 'path'} + + {:else if mark === 'link'} + + {:else if mark === 'polygon'} + + {:else if mark === 'vector'} + + {:else if mark === 'graticule'} + + {/if} + + + +
diff --git a/packages/webgl/src/lib/components/__fixtures__/ParityScales.svelte b/packages/webgl/src/lib/components/__fixtures__/ParityScales.svelte new file mode 100644 index 0000000000..851a287199 --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/ParityScales.svelte @@ -0,0 +1,39 @@ + + + +
+ + + {#if mark === 'grid'} + + {:else if mark === 'raster'} + + {:else if mark === 'georaster' && georaster} + + {/if} + + + +
diff --git a/packages/webgl/src/lib/components/__fixtures__/Paths.svelte b/packages/webgl/src/lib/components/__fixtures__/Paths.svelte new file mode 100644 index 0000000000..96741faacd --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/Paths.svelte @@ -0,0 +1,58 @@ + + +{#snippet start(props: { point: DOMPoint; value: any })} + {onContent?.('start', props)} +{/snippet} +{#snippet end(props: { point: DOMPoint; value: any })} + {onContent?.('end', props)} +{/snippet} + +
+ + + {#if mark === 'spline'} + + {:else if mark === 'area'} + + {:else if mark === 'link'} + + {:else if mark === 'geoPath'} + + {:else if mark === 'graticule'} + + {/if} + + + +
diff --git a/packages/webgl/src/lib/components/layers/WebGL.svelte b/packages/webgl/src/lib/components/layers/WebGL.svelte index 41f14a7456..65d73ee7be 100644 --- a/packages/webgl/src/lib/components/layers/WebGL.svelte +++ b/packages/webgl/src/lib/components/layers/WebGL.svelte @@ -46,7 +46,7 @@ import { NoToneMapping, PCFShadowMap, WebGLRenderer } from 'three'; import { getChartContext } from 'layerchart'; - import { SceneState, setSceneContext } from '../../contexts/scene.svelte.js'; + import { SceneState, setSceneContext, type SceneMarker } from '../../contexts/scene.svelte.js'; import { ColorResolver } from '../../utils/color.js'; import WebGLSetup from './WebGLSetup.svelte'; @@ -74,6 +74,40 @@ }: WebGLProps = $props(); const sceneState = setSceneContext(new SceneState()); + + /** `color` at `opacity` (a label's letters or halo), as it is without one */ + function alpha(color: string, opacity: number | undefined) { + return opacity == null ? color : `color-mix(in srgb, ${color} ${opacity * 100}%, transparent)`; + } + + /** Whether a marker takes the pointer: only one with handlers does, while the scene takes it */ + const takesPointer = (marker: SceneMarker) => + pointerEvents !== false && !!(marker.onclick || marker.onpointerenter || marker.onpointerleave); + + /** + * Pass a pointer's move over a marker on to the scene beneath, so what's under it is still + * hovered (ex. a tooltip from the marks), and its leaving when it leaves for outside the scene + * rather than for the scene itself (which the scene sees for itself) + */ + function toScene(e: PointerEvent) { + const canvas = element?.querySelector('canvas'); + const to = e.relatedTarget as Element | null; + if ( + !canvas || + (e.type === 'pointerleave' && (to === canvas || to?.closest?.('.lc-webgl-markers'))) + ) + return; + canvas.dispatchEvent( + new PointerEvent(e.type, { + clientX: e.clientX, + clientY: e.clientY, + buttons: e.buttons, + pointerId: e.pointerId, + pointerType: e.pointerType, + relatedTarget: to, + }) + ); + } const ctx = getChartContext(); $effect.pre(() => { sceneState.clip = clip ?? ctx.props.transform?.mode === 'domain'; @@ -162,6 +196,9 @@ {#each markers as marker (marker.key)} {@const point = sceneState.project(marker.x, marker.y, marker.z)} {#if point} + + + e.stopPropagation())} + onpointerenter={marker.onpointerenter} + onpointermove={takesPointer(marker) ? (e: PointerEvent) => toScene(e) : undefined} + onpointerleave={takesPointer(marker) + ? (e: PointerEvent) => { + marker.onpointerleave?.(e); + toScene(e); + } + : undefined} /> {/if} {/each} @@ -197,8 +246,12 @@ style:max-width={label.width ? `${label.width}px` : undefined} style:color={label.color} style:-webkit-text-stroke={label.stroke - ? `${label.strokeWidth ?? 1}px ${label.stroke}` + ? `${label.strokeWidth ?? 1}px ${alpha(label.stroke, label.strokeOpacity)}` : undefined} + style:-webkit-text-fill-color={label.fillOpacity == null + ? undefined + : alpha('currentColor', label.fillOpacity)} + style:opacity={label.opacity} style:paint-order={label.stroke ? 'stroke fill' : undefined} style:white-space={label.width ? 'normal' : undefined} > diff --git a/packages/webgl/src/lib/components/layers/WebGLSetup.svelte b/packages/webgl/src/lib/components/layers/WebGLSetup.svelte index 19e18eca23..2d870cfbac 100644 --- a/packages/webgl/src/lib/components/layers/WebGLSetup.svelte +++ b/packages/webgl/src/lib/components/layers/WebGLSetup.svelte @@ -20,7 +20,7 @@ import { getChartContext } from 'layerchart'; import { createControlledMotion } from 'layerchart/utils/motion.svelte'; - import { getSceneContext } from '../../contexts/scene.svelte.js'; + import { getSceneContext, type Pickable } from '../../contexts/scene.svelte.js'; import { frameOrthographic, framePerspective, viewDirection } from '../../utils/camera.js'; import { geoPath } from 'd3-geo'; import { getSphere } from '../../utils/globe.js'; @@ -736,14 +736,8 @@ $effect(() => { const element = renderer.domElement; - const onPointerMove = (e: PointerEvent) => { - // Nothing here shows a tooltip, so leave it to the chart's (ex. a `quadtree` over the rows) - if (!sceneState.pickables.size) return; - // A drag turns or pans the view - if (e.buttons || ctx.transform.dragging) { - ctx.tooltip.hide(e); - return; - } + /** What's under the pointer: the pickable mark it hits first, and that hit's row */ + const pick = (e: MouseEvent) => { const rect = element.getBoundingClientRect(); pointer.set( ((e.clientX - rect.left) / rect.width) * 2 - 1, @@ -760,18 +754,77 @@ .find( ({ point }) => !sceneState.clip || clipPlanes.every((p) => p.distanceToPoint(point) >= 0) ); - const datum = hit ? pickables.find((p) => p.object === hit.object)?.datum(hit) : undefined; - if (datum != null) ctx.tooltip.show(e, datum); - else ctx.tooltip.hide(e); + const pickable = hit ? pickables.find((p) => p.object === hit.object) : undefined; + return pickable && hit ? { pickable, datum: pickable.datum(hit) } : null; + }; + + /** The mark and row the pointer was last over, for its enter / leave handlers */ + let over: { pickable: Pickable; datum: unknown } | null = null; + const leave = (e: PointerEvent) => { + if (!over) return; + const events = over.pickable.events?.(); + events?.onpointerleave?.(e, { data: over.datum }); + events?.onpointerout?.(e, { data: over.datum }); + over = null; + element.style.cursor = ''; + }; + const enter = (e: PointerEvent, next: { pickable: Pickable; datum: unknown }) => { + over = next; + const events = next.pickable.events?.(); + events?.onpointerenter?.(e, { data: next.datum }); + events?.onpointerover?.(e, { data: next.datum }); + // Clickable, as the core marks with an `onclick` show + if (events?.onclick || events?.ondblclick) element.style.cursor = 'pointer'; + }; + + const onPointerMove = (e: PointerEvent) => { + // Nothing here shows a tooltip or takes the pointer, so leave it to the chart's (ex. a + // `quadtree` over the rows) + if (!sceneState.pickables.size) return; + // A drag turns or pans the view + if (e.buttons || ctx.transform.dragging) { + ctx.tooltip.hide(e); + leave(e); + return; + } + const picked = pick(e); + const datum = picked?.datum; + if (picked?.pickable !== over?.pickable || datum !== over?.datum) { + leave(e); + if (picked && datum != null) enter(e, picked); + } + if (picked && datum != null) picked.pickable.events?.()?.onpointermove?.(e, { data: datum }); + // The tooltip from the marks that show it, and only them + if (picked && datum != null && (picked.pickable.tooltip?.() ?? true)) + ctx.tooltip.show(e, datum); + else if ([...sceneState.pickables].some((p) => p.tooltip?.() ?? true)) ctx.tooltip.hide(e); }; const onPointerLeave = (e: PointerEvent) => { - if (sceneState.pickables.size) ctx.tooltip.hide(e); + // Onto a marker over the scene (ex. a `Highlight`'s point taking clicks), which passes its + // moves on here, and its leaving + if ((e.relatedTarget as Element | null)?.closest?.('.lc-webgl-markers')) return; + leave(e); + if ([...sceneState.pickables].some((p) => p.tooltip?.() ?? true)) ctx.tooltip.hide(e); + }; + /** A click on a mark that takes one, with its row */ + const onClick = (type: 'onclick' | 'ondblclick') => (e: MouseEvent) => { + if (!sceneState.pickables.size) return; + const picked = pick(e); + if (picked && picked.datum != null) { + picked.pickable.events?.()?.[type]?.(e, { data: picked.datum }); + } }; + const onclick = onClick('onclick'); + const ondblclick = onClick('ondblclick'); element.addEventListener('pointermove', onPointerMove); element.addEventListener('pointerleave', onPointerLeave); + element.addEventListener('click', onclick); + element.addEventListener('dblclick', ondblclick); return () => { element.removeEventListener('pointermove', onPointerMove); element.removeEventListener('pointerleave', onPointerLeave); + element.removeEventListener('click', onclick); + element.removeEventListener('dblclick', ondblclick); }; }); diff --git a/packages/webgl/src/lib/components/parity-lines.svelte.test.ts b/packages/webgl/src/lib/components/parity-lines.svelte.test.ts new file mode 100644 index 0000000000..aece0f99fa --- /dev/null +++ b/packages/webgl/src/lib/components/parity-lines.svelte.test.ts @@ -0,0 +1,338 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { geoIdentity } from 'd3-geo'; +import type { Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import Lines from './__fixtures__/Lines.svelte'; + +type Props = Omit>[1], 'onScene'>; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderLines(props: Props) { + let scene: SceneState | undefined; + const result = render(Lines, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return { + scene: scene!, + rerender: (next: Props) => result.rerender({ ...(next as any), onScene: () => {} }), + }; +} + +/** Each mark's own group of objects, in the order they're declared */ +const layers = (scene: SceneState) => scene.root.children.filter((o) => o.userData.layer); +/** A layer's outlines, and its filled mesh */ +const linesOf = (layer: Object3D | undefined) => + layer?.children.find((o) => (o as any).isLineSegments2) as any; +const meshOf = (layer: Object3D | undefined) => + layer?.children.find((o) => (o as any).isMesh && !(o as any).isLineSegments2) as any; + +/** A layer's outline segments, as `[x, y]` pairs across and down the plot */ +const segments = (layer: Object3D | undefined): [number, number][][] => { + const lines = linesOf(layer); + if (!lines?.visible) return []; + const start = lines.geometry.attributes.instanceStart; + const end = lines.geometry.attributes.instanceEnd; + return Array.from({ length: start?.count ?? 0 }, (_, i) => [ + [start.getX(i), start.getZ(i)], + [end.getX(i), end.getZ(i)], + ]); +}; + +/** The extent of a layer's filled mesh along an axis (`0` across, `2` down the plot) */ +const extent = (layer: Object3D | undefined, axis: number): [number, number] => { + const array = meshOf(layer)?.geometry.attributes.position?.array as Float32Array | undefined; + const values = Array.from(array ?? []).filter((_, i) => i % 3 === axis); + return values.length ? [Math.min(...values), Math.max(...values)] : [NaN, NaN]; +}; + +const tween = { type: 'tween' as const, duration: 400 }; + +describe('Line, as the core `Line`', () => { + const across = { x1: 100, y1: 50, x2: 200, y2: 50 }; + + it('eases from `initialX1` with `motion`', async () => { + const { scene } = await renderLines({ + mark: 'line', + line: { ...across, initialX1: 0, motion: tween }, + }); + const startX = () => segments(layers(scene)[0])[0]?.[0][0] ?? NaN; + // On its way from its initial start... + await expect.poll(() => startX() > 1 && startX() < 99).toBe(true); + // ...to where it's asked to be + await expect.poll(startX).toBeCloseTo(100); + }); + + it('eases a row to its new place by its `key`, appearing where it is', async () => { + const props = (x: number): Props => ({ + mark: 'line', + chart: { xDomain: [0, 10], yDomain: [0, 10] }, + line: { + data: [{ id: 'a', x }], + key: (d: any) => d.id, + x1: 'x', + y1: 10, + x2: 'x', + y2: 100, + initialX1: 0, + motion: tween, + }, + }); + const { scene, rerender } = await renderLines(props(2)); + const startX = () => segments(layers(scene)[0])[0]?.[0][0] ?? NaN; + // At once where it's first asked to be (its `initial` ends are for pixel mode) + await expect.poll(startX).toBeCloseTo(chart!.xScale(2)); + await rerender(props(8)); + const [from, to] = [chart!.xScale(2), chart!.xScale(8)]; + await expect.poll(() => startX() > from + 1 && startX() < to - 1).toBe(true); + await expect.poll(startX).toBeCloseTo(to); + }); + + it('dashes with `dashArray`, solid without', async () => { + const plain = await renderLines({ mark: 'line', line: across }); + await expect.poll(() => segments(layers(plain.scene)[0]).length).toBe(1); + expect(linesOf(layers(plain.scene)[0]).material.dashed).toBe(false); + + const { scene } = await renderLines({ mark: 'line', line: { ...across, dashArray: '4 2' } }); + const material = () => linesOf(layers(scene)[0])?.material; + await expect.poll(() => material()?.dashed).toBe(true); + expect(material().dashSize).toBeCloseTo(4 * scene.unit); + expect(material().gapSize).toBeCloseTo(2 * scene.unit); + }); + + it('dims its stroke by `strokeOpacity`', async () => { + const { scene } = await renderLines({ + mark: 'line', + line: { ...across, strokeOpacity: 0.5, opacity: 0.5 }, + }); + await expect.poll(() => linesOf(layers(scene)[0])?.material.opacity).toBeCloseTo(0.25); + }); + + it('adds nothing without a marker', async () => { + const { scene } = await renderLines({ mark: 'line', line: across }); + await expect.poll(() => segments(layers(scene)[0]).length).toBe(1); + expect(layers(scene)).toHaveLength(1); + }); + + it('draws a `markerEnd` triangle with its tip at the end, pointing along the line', async () => { + const { scene } = await renderLines({ + mark: 'line', + line: { ...across, markerEnd: 'triangle' }, + }); + await expect.poll(() => layers(scene).length).toBe(2); + const marker = () => layers(scene)[1]; + await expect.poll(() => meshOf(marker())?.geometry.attributes.position?.count ?? 0).toBe(3); + // As the core `Marker`: 10px, its tip a pixel past the end (`refX` 9) + expect(extent(marker(), 0)[0]).toBeCloseTo(191); + expect(extent(marker(), 0)[1]).toBeCloseTo(201); + expect(extent(marker(), 2)[0]).toBeCloseTo(45); + expect(extent(marker(), 2)[1]).toBeCloseTo(55); + }); + + it('turns a `markerStart` back from the line (`auto-start-reverse`)', async () => { + const { scene } = await renderLines({ + mark: 'line', + line: { ...across, markerStart: 'triangle' }, + }); + await expect + .poll(() => meshOf(layers(scene)[1])?.geometry.attributes.position?.count ?? 0) + .toBe(3); + expect(extent(layers(scene)[1], 0)[0]).toBeCloseTo(99); + expect(extent(layers(scene)[1], 0)[1]).toBeCloseTo(109); + }); + + it('draws an `arrow` marker as lines, and `marker` at both ends', async () => { + const { scene } = await renderLines({ + mark: 'line', + line: { ...across, marker: { type: 'arrow', size: 20 } }, + }); + // Its start's and its end's (a straight line has no mid points) + await expect.poll(() => layers(scene).length).toBe(4); + const end = layers(scene)[3]; + await expect.poll(() => segments(end).length).toBe(2); + // 20px: from 18px back of the end to 2px past it + const xs = segments(end) + .flat() + .map(([x]) => x); + expect(Math.min(...xs)).toBeCloseTo(182); + expect(Math.max(...xs)).toBeCloseTo(202); + expect(segments(layers(scene)[2])).toEqual([]); + }); +}); + +describe('Path, as the core `Path`', () => { + it('dims its outline by `strokeOpacity`, not its fill', async () => { + const { scene } = await renderLines({ + mark: 'path', + path: { pathData: 'M0,0L100,0L100,100Z', fill: 'red', stroke: 'black', strokeOpacity: 0.5 }, + }); + await expect.poll(() => linesOf(layers(scene)[0])?.material.opacity).toBeCloseTo(0.5); + expect(meshOf(layers(scene)[0]).material.opacity).toBeCloseTo(1); + }); + + it('draws a `markerMid` at each vertex between its ends', async () => { + const { scene } = await renderLines({ + mark: 'path', + path: { pathData: 'M0,0L50,0L50,50L100,50', markerMid: 'dot' }, + }); + await expect.poll(() => layers(scene).length).toBe(2); + const mid = layers(scene)[1]; + // Two dots, a circle 10px across about each corner + await expect.poll(() => extent(mid, 0)[0]).toBeCloseTo(45); + expect(extent(mid, 0)[1]).toBeCloseTo(55); + expect(extent(mid, 2)[0]).toBeCloseTo(-5); + expect(extent(mid, 2)[1]).toBeCloseTo(55); + }); + + it('draws only where its commands end on a curve, not its every piece', async () => { + const { scene } = await renderLines({ + mark: 'path', + path: { pathData: 'M0,0C30,0 30,50 60,50L120,50', markerMid: 'dot' }, + }); + await expect + .poll(() => meshOf(layers(scene)[1])?.geometry.attributes.position?.count ?? 0) + .toBeGreaterThan(0); + // One dot, at the curve's end + expect(extent(layers(scene)[1], 0)).toEqual([expect.closeTo(55, 1), expect.closeTo(65, 1)]); + }); + + it('draws its outline from its start with `draw`', async () => { + const { scene } = await renderLines({ + mark: 'path', + path: { pathData: 'M0,0L200,0', draw: { duration: 400 } }, + }); + const reach = () => + Math.max( + ...segments(layers(scene)[0]) + .flat() + .map(([x]) => x), + 0 + ); + await expect.poll(() => reach() > 10 && reach() < 190).toBe(true); + await expect.poll(reach).toBeCloseTo(200); + }); + + it('gives `startContent` / `endContent` its first and last points', async () => { + const seen: Record = {}; + await renderLines({ + mark: 'path', + chart: { xDomain: [0, 10], yDomain: [0, 10] }, + path: { pathData: 'M10,20L200,40' }, + onContent: (at: string, props: { point: DOMPoint; value: any }) => (seen[at] = props), + }); + await expect.poll(() => seen.end?.point.x).toBeCloseTo(200); + expect(seen.end.point.y).toBeCloseTo(40); + expect([seen.start.point.x, seen.start.point.y]).toEqual([10, 20]); + expect(seen.end.value.x).toBeCloseTo((chart!.xScale as any).invert(200)); + }); +}); + +describe('Link, as the core `Link`', () => { + it('draws a `sankey` link from its source’s right edge to its target’s left', async () => { + const { scene } = await renderLines({ + mark: 'link', + link: { + sankey: true, + type: 'straight', + data: { source: { x0: 0, x1: 10 }, target: { x0: 100, x1: 110 }, y0: 20, y1: 60 }, + }, + }); + await expect.poll(() => segments(layers(scene)[0]).length).toBe(1); + expect(segments(layers(scene)[0])[0]).toEqual([ + [expect.closeTo(10), expect.closeTo(20)], + [expect.closeTo(100), expect.closeTo(60)], + ]); + }); + + it('lays a `radial` link out by angle and radius about the origin', async () => { + const { scene } = await renderLines({ + mark: 'link', + link: { + radial: true, + type: 'straight', + data: { source: { x: 0, y: 0 }, target: { x: Math.PI / 2, y: 50 } }, + }, + }); + await expect.poll(() => segments(layers(scene)[0]).length).toBe(1); + // A quarter turn clockwise from up: straight across + expect(segments(layers(scene)[0])[0][1]).toEqual([expect.closeTo(50), expect.closeTo(0)]); + }); + + it('marks each link’s end with `markerEnd`, and a `square` link’s corners with `markerMid`', async () => { + const { scene } = await renderLines({ + mark: 'link', + link: { + type: 'square', + data: [{ source: { x: 0, y: 0 }, target: { x: 100, y: 100 } }], + markerMid: 'square', + markerEnd: 'triangle', + }, + }); + await expect.poll(() => layers(scene).length).toBe(3); + await expect + .poll(() => meshOf(layers(scene)[1])?.geometry.attributes.position?.count ?? 0) + .toBeGreaterThan(0); + await expect + .poll(() => meshOf(layers(scene)[2])?.geometry.attributes.position?.count ?? 0) + .toBe(3); + // The triangle's tip at the target, a pixel past it + expect(extent(layers(scene)[2], 2)[1]).toBeCloseTo(101); + }); +}); + +describe('Polygon and Vector, as the core marks', () => { + it('eases a `Polygon` from `initialCx` with `motion`', async () => { + const { scene } = await renderLines({ + mark: 'polygon', + polygon: { cx: 200, initialCx: 0, cy: 100, r: 20, motion: tween }, + }); + const center = () => { + const [a, b] = extent(layers(scene)[0], 0); + return (a + b) / 2; + }; + await expect.poll(() => center() > 5 && center() < 195).toBe(true); + await expect.poll(center).toBeCloseTo(200); + }); + + it('eases a `Vector`’s length from `initialLength` with `motion`', async () => { + const { scene } = await renderLines({ + mark: 'vector', + vector: { x: 100, y: 100, length: 80, initialLength: 0, rotate: 90, motion: tween }, + }); + /** Its stem's length */ + const length = () => { + const [[from, to] = [[0], [0]]] = segments(layers(scene)[0]); + return Math.abs(to[0] - from[0]); + }; + await expect.poll(() => length() > 2 && length() < 78).toBe(true); + await expect.poll(length).toBeCloseTo(80); + }); +}); + +describe('Graticule, as the core `Graticule`', () => { + it('draws its own `geojson` in place of the graticule’s', async () => { + const { scene } = await renderLines({ + mark: 'graticule', + chart: { geo: { projection: geoIdentity } }, + graticule: { + geojson: { + type: 'LineString', + coordinates: [ + [0, 0], + [50, 0], + ], + }, + }, + }); + await expect.poll(() => segments(layers(scene)[0]).length).toBe(1); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-marks.svelte.test.ts b/packages/webgl/src/lib/components/parity-marks.svelte.test.ts new file mode 100644 index 0000000000..13b09b9ba9 --- /dev/null +++ b/packages/webgl/src/lib/components/parity-marks.svelte.test.ts @@ -0,0 +1,391 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { Color, Matrix4, Quaternion, Vector3, type InstancedMesh, type Object3D } from 'three'; + +import type { ChartState } from 'layerchart'; +import type { SceneState } from '../contexts/scene.svelte.js'; +import Marks from './__fixtures__/Marks.svelte'; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderMarks(props: Omit>[1], 'onScene'>) { + let scene: SceneState | undefined; + const result = render(Marks, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return { scene: scene!, rerender: result.rerender }; +} + +/** The objects marks put in the scene, looking through each mark's own layer */ +const layered = (scene: SceneState) => + scene.root.children.flatMap((o) => (o.userData.layer ? o.children : [o])); + +const instanced = (scene: SceneState) => + layered(scene).filter((o: Object3D) => (o as any).isInstancedMesh) as InstancedMesh[]; + +/** The merged meshes marks fill (not their outlines, nor instanced marks) */ +const fills = (scene: SceneState) => + layered(scene).filter( + (o) => (o as any).isMesh && !(o as any).isInstancedMesh && !(o as any).isLineSegments2 + ) as any[]; + +const outlines = (scene: SceneState) => + layered(scene).filter((o) => (o as any).isLineSegments2) as any[]; + +/** An instance's center (across, down the plot) and radius */ +function placed(mesh: InstancedMesh, i = 0) { + const matrix = new Matrix4(); + mesh.getMatrixAt(i, matrix); + const position = new Vector3(); + const size = new Vector3(); + matrix.decompose(position, new Quaternion(), size); + return { x: position.x, y: position.z, r: size.x }; +} + +const tween = { type: 'tween' as const, duration: 400 }; + +/** Two series, each with rows of its own, side by side (not stacked) */ +const seriesChart = { + x: 'x', + y: 'v', + xDomain: [0, 10], + yDomain: [0, 10], + seriesLayout: 'overlap' as const, + series: [ + { + key: 'a', + color: 'rgb(255, 0, 0)', + value: 'v', + data: [ + { x: 0, v: 2 }, + { x: 10, v: 2 }, + ], + }, + { + key: 'b', + color: 'rgb(0, 0, 255)', + value: 'v', + data: [ + { x: 0, v: 8 }, + { x: 10, v: 8 }, + ], + }, + ], +}; + +describe('Circle, with the core `Circle`’s props', () => { + it('eases in from `initialCx` and `initialR` with `motion`', async () => { + const { scene } = await renderMarks({ + mark: 'circle', + chart: {}, + circle: { cx: 100, cy: 50, r: 20, initialCx: 0, initialR: 0, motion: tween }, + }); + const now = () => placed(instanced(scene)[0]); + // On its way... + await expect.poll(() => now().r > 1 && now().r < 19).toBe(true); + expect(now().x).toBeLessThan(99); + // ...and there + await expect.poll(() => now().r).toBeCloseTo(20); + expect(now().x).toBeCloseTo(100); + expect(now().y).toBeCloseTo(50); + }); + + it('eases only the props its `motion` names', async () => { + const { scene } = await renderMarks({ + mark: 'circle', + chart: {}, + circle: { cx: 100, cy: 50, r: 20, initialCx: 0, initialR: 0, motion: { r: tween } }, + }); + const now = () => placed(instanced(scene)[0]); + await expect.poll(() => now().r > 1 && now().r < 19).toBe(true); + // Straight to its place, growing there + expect(now().x).toBeCloseTo(100); + }); + + it('draws its ring at `strokeOpacity`', async () => { + const { scene } = await renderMarks({ + mark: 'circle', + chart: {}, + circle: { cx: 100, cy: 50, r: 10, stroke: 'black', strokeOpacity: 0.25 }, + }); + await expect.poll(() => instanced(scene).length).toBe(2); + const [fill, ring] = instanced(scene); + expect((fill.material as any).opacity).toBe(1); + expect((ring.material as any).opacity).toBeCloseTo(0.25); + }); +}); + +describe('Points, with the props the core `Points` takes from `Circle`', () => { + const rows = [ + { x: 2, y: 2 }, + { x: 7, y: 6 }, + ]; + const chartProps = { data: rows, x: 'x', y: 'y', xDomain: [0, 10], yDomain: [0, 10] }; + + it('grows each point in from `initialR` with `motion`', async () => { + const { scene } = await renderMarks({ + mark: 'points', + chart: chartProps, + points: { r: 8, initialR: 0, motion: tween }, + }); + const mesh = () => instanced(scene)[0]; + await expect.poll(() => mesh()?.count).toBe(2); + await expect.poll(() => placed(mesh(), 1).r > 0.5 && placed(mesh(), 1).r < 7.5).toBe(true); + await expect.poll(() => placed(mesh(), 1).r).toBeCloseTo(8); + expect(placed(mesh(), 1).x).toBeCloseTo(chart!.xScale(7)); + }); + + it('eases each point to its new place by its `key`', async () => { + const { scene, rerender } = await renderMarks({ + mark: 'points', + chart: chartProps, + points: { data: [{ id: 'a', x: 2, y: 5 }], key: (d: any) => d.id, motion: tween }, + }); + const across = () => placed(instanced(scene)[0]).x; + await expect.poll(across).toBeCloseTo(chart!.xScale(2)); + await rerender({ + points: { data: [{ id: 'a', x: 8, y: 5 }], key: (d: any) => d.id, motion: tween }, + }); + await expect.poll(() => across() > chart!.xScale(2) + 1).toBe(true); + expect(across()).toBeLessThan(chart!.xScale(8) - 1); + await expect.poll(across).toBeCloseTo(chart!.xScale(8)); + }); + + it('draws its `seriesKey`’s rows, in its color', async () => { + const { scene } = await renderMarks({ + mark: 'points', + chart: seriesChart, + points: { seriesKey: 'b' }, + }); + const mesh = () => instanced(scene)[0]; + await expect.poll(() => mesh()?.count).toBe(2); + expect(placed(mesh()).y).toBeCloseTo(chart!.yScale(8)); + const color = new Color(); + mesh().getColorAt(0, color); + expect([color.r, color.b]).toEqual([expect.closeTo(0), expect.closeTo(1)]); + }); +}); + +describe('Spline and Area, with `seriesKey`', () => { + it('draws a `Spline` of its series’ rows, in its color, faded while another is highlighted', async () => { + const { scene } = await renderMarks({ + mark: 'spline', + chart: seriesChart, + spline: { seriesKey: 'b' }, + }); + const line = () => layered(scene).find((o) => (o as any).isLine2) as any; + await expect.poll(() => line()).toBeTruthy(); + const geometry = line().geometry; + expect(geometry.attributes.instanceStart.getZ(0)).toBeCloseTo(chart!.yScale(8)); + expect(geometry.attributes.instanceColorStart.getX(0)).toBeCloseTo(0); + expect(geometry.attributes.instanceColorStart.getZ(0)).toBeCloseTo(1); + expect(line().material.opacity).toBe(1); + + chart!.series.highlightKey = 'a'; + await expect.poll(() => line().material.opacity).toBeCloseTo(0.1); + chart!.series.highlightKey = null; + await expect.poll(() => line().material.opacity).toBe(1); + }); + + it('fills an `Area` from its series’ rows, in its color', async () => { + const { scene } = await renderMarks({ + mark: 'area', + chart: seriesChart, + area: { seriesKey: 'b' }, + }); + const mesh = () => fills(scene).find((m) => m.geometry.attributes.position?.count > 0); + await expect.poll(() => mesh()).toBeTruthy(); + const positions = mesh().geometry.attributes.position.array as Float32Array; + const downs = Array.from({ length: positions.length / 3 }, (_, i) => positions[i * 3 + 2]); + // From its top (its series' value) down to the plot's bottom + expect(Math.min(...downs)).toBeCloseTo(chart!.yScale(8)); + expect(Math.max(...downs)).toBeCloseTo(Math.max(...chart!.yRange)); + const colors = mesh().geometry.attributes.color.array as Float32Array; + expect([colors[0], colors[2]]).toEqual([expect.closeTo(0), expect.closeTo(1)]); + }); +}); + +describe('Area, with the core `Area`’s `stroke` and `pathData`', () => { + const chartProps = { + data: [ + { x: 0, y: 4 }, + { x: 10, y: 6 }, + ], + x: 'x', + y: 'y', + xDomain: [0, 10], + yDomain: [0, 10], + }; + + it('outlines each area with `stroke`, around its top, its base, and its ends', async () => { + const { scene } = await renderMarks({ mark: 'area', chart: chartProps, area: {} }); + await expect.poll(() => fills(scene).length).toBeGreaterThan(0); + expect(outlines(scene).every((o) => !o.visible)).toBe(true); + + const outlined = await renderMarks({ + mark: 'area', + chart: chartProps, + area: { stroke: 'rgb(255, 0, 0)' }, + }); + const lines = () => outlines(outlined.scene).find((o) => o.visible); + await expect.poll(() => lines()?.geometry.attributes.instanceStart.count).toBe(4); + const colors = lines().geometry.attributes.instanceColorStart; + expect([colors.getX(0), colors.getY(0)]).toEqual([expect.closeTo(1), expect.closeTo(0)]); + }); + + it('fills explicit `pathData` in place of its rows', async () => { + const { scene } = await renderMarks({ + mark: 'area', + chart: chartProps, + area: { pathData: 'M10,10L110,10L110,60L10,60Z', fill: 'rgb(0, 255, 0)' }, + }); + const filled = () => fills(scene).filter((m) => m.geometry.attributes.position?.count > 0); + await expect.poll(() => filled().length).toBe(1); + const positions = filled()[0].geometry.attributes.position.array as Float32Array; + const across = Array.from({ length: positions.length / 3 }, (_, i) => positions[i * 3]); + expect([Math.min(...across), Math.max(...across)]).toEqual([ + expect.closeTo(10), + expect.closeTo(110), + ]); + }); +}); + +describe('Arc, with the core `Arc`’s `fillOpacity` and `strokeOpacity`', () => { + it('draws its fill and its outline each at its own opacity, under `opacity`', async () => { + const { scene } = await renderMarks({ + mark: 'arc', + chart: {}, + arc: { + value: 50, + stroke: 'black', + opacity: 0.5, + fillOpacity: 0.5, + strokeOpacity: 0.4, + }, + }); + const mesh = () => fills(scene).find((m) => m.geometry.attributes.position?.count > 0); + await expect.poll(() => mesh()?.material.opacity).toBeCloseTo(0.25); + const outline = outlines(scene).find((o) => o.visible); + expect(outline.material.opacity).toBeCloseTo(0.2); + }); +}); + +describe('Rule, with `seriesKey`', () => { + it('fades while another series is highlighted, and hides with its series', async () => { + const { scene } = await renderMarks({ + mark: 'rule', + chart: seriesChart, + rule: { y: 5, seriesKey: 'b' }, + }); + const line = () => outlines(scene)[0]; + await expect.poll(() => line()?.visible).toBe(true); + expect(line().material.opacity).toBe(1); + + chart!.series.highlightKey = 'a'; + await expect.poll(() => line().material.opacity).toBeCloseTo(0.1); + chart!.series.highlightKey = null; + + chart!.series.selectedKeys.current = ['a']; + await expect.poll(() => line().visible).toBe(false); + }); +}); + +describe('Text, with the core `Text`’s props', () => { + /** The planes labels lying on the surface are painted on, in the order they're drawn */ + const planes = (scene: SceneState) => { + const found: any[] = []; + scene.root.traverse((o: any) => { + if (o.isMesh && o.material?.map) found.push(o); + }); + return found; + }; + + it('eases in from `initialX` with `motion`', async () => { + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, initialX: 0, value: 'hi', viewport: true, motion: tween }, + }); + const label = () => scene.labelSets.flat()[0]; + await expect.poll(() => label()?.x > 1 && label()?.x < 99).toBe(true); + await expect.poll(() => label().x).toBeCloseTo(100); + expect(label().y).toBeCloseTo(50); + }); + + it('tweens a numeric `value` with a motion `{ type }`', async () => { + const { scene, rerender } = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 0, format: 'integer', viewport: true, motion: tween }, + }); + const text = () => Number(scene.labelSets.flat()[0]?.text.replace(/,/g, '')); + await expect.poll(text).toBe(0); + await rerender({ + text: { x: 100, y: 50, value: 1000, format: 'integer', viewport: true, motion: tween }, + }); + await expect.poll(() => text() > 0 && text() < 1000).toBe(true); + await expect.poll(text).toBe(1000); + }); + + it('draws `segments` facing the viewer side by side, each in its own classes', async () => { + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { + x: 100, + y: 50, + segments: [{ value: 'Hello ' }, { value: 'world', class: 'font-bold' }], + textAnchor: 'start', + viewport: true, + }, + }); + await expect.poll(() => scene.labelSets.flat().length).toBe(2); + const [hello, world] = scene.labelSets.flat(); + expect([hello.text, world.text]).toEqual(['Hello', 'world']); + expect(world.class).toContain('font-bold'); + expect(hello.dx).toBe(0); + // Past `Hello ` (its space too) + expect(world.dx!).toBeGreaterThan(20); + expect([hello.textAnchor, world.textAnchor]).toEqual(['start', 'start']); + }); + + it('lays `segments` on the surface along one baseline', async () => { + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { + x: 100, + y: 50, + segments: [{ value: 'Hello ' }, { value: 'world' }], + fontSize: 12, + }, + }); + await expect.poll(() => planes(scene).length).toBe(2); + const [hello, world] = planes(scene); + // Centered on the point as a whole (`textAnchor` `middle`), one after the other + expect(hello.position.x).toBeLessThan(100); + expect(world.position.x).toBeGreaterThan(100); + expect(world.position.z).toBeCloseTo(hello.position.z); + }); + + it('places a label lying on the surface by its `capHeight`', async () => { + const at = async (capHeight?: string) => { + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'cap', fontSize: 12, verticalAnchor: 'start', capHeight }, + }); + await expect.poll(() => planes(scene).length).toBe(1); + return planes(scene)[0].position.z as number; + }; + const natural = await at(); + // Its cap height's top at its point: a taller cap height puts it further down + expect(await at('20px')).toBeCloseTo(natural + 20 - 0.71 * 12); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-paths.svelte.test.ts b/packages/webgl/src/lib/components/parity-paths.svelte.test.ts new file mode 100644 index 0000000000..e1e8dd676b --- /dev/null +++ b/packages/webgl/src/lib/components/parity-paths.svelte.test.ts @@ -0,0 +1,382 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { geoIdentity } from 'd3-geo'; +import { curveMonotoneX } from 'd3-shape'; +import type { Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import Paths from './__fixtures__/Paths.svelte'; + +type Props = Omit>[1], 'onScene'>; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderPaths(props: Props) { + let scene: SceneState | undefined; + render(Paths, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +/** Each mark's own group of objects, in the order they're declared */ +const layers = (scene: SceneState) => scene.root.children.filter((o) => o.userData.layer); +/** A layer's outlines, and its filled mesh */ +const linesOf = (layer: Object3D | undefined) => + layer?.children.find((o) => (o as any).isLineSegments2) as any; +const meshOf = (layer: Object3D | undefined) => + layer?.children.find((o) => (o as any).isMesh && !(o as any).isLineSegments2) as any; +/** A `Spline`'s lines (shown ones) */ +const splines = (scene: SceneState) => + layers(scene) + .flatMap((layer) => layer.children) + .filter((o) => (o as any).isLine2 && o.visible) as any[]; + +/** Line segments' ends, as `[x, y]` pairs across and down the plot (with their height) */ +const segmentsOf = (lines: any): [number, number, number][][] => { + if (!lines?.visible) return []; + const start = lines.geometry.attributes.instanceStart; + const end = lines.geometry.attributes.instanceEnd; + return Array.from({ length: start?.count ?? 0 }, (_, i) => [ + [start.getX(i), start.getZ(i), start.getY(i)], + [end.getX(i), end.getZ(i), end.getY(i)], + ]); +}; +const segments = (layer: Object3D | undefined) => segmentsOf(linesOf(layer)); +/** The farthest across a set of segments reaches */ +const reach = (segs: [number, number, number][][]) => Math.max(...segs.flat().map(([x]) => x), 0); + +/** The extent of a layer's filled mesh along an axis (`0` across, `2` down the plot) */ +const extent = (layer: Object3D | undefined, axis: number): [number, number] => { + const array = meshOf(layer)?.geometry.attributes.position?.array as Float32Array | undefined; + const values = Array.from(array ?? []).filter((_, i) => i % 3 === axis); + return values.length ? [Math.min(...values), Math.max(...values)] : [NaN, NaN]; +}; +const meshCount = (layer: Object3D | undefined) => + meshOf(layer)?.geometry.attributes.position?.count ?? 0; + +/** What a `startContent` / `endContent` is given */ +type Content = { point: DOMPoint; value: any }; + +const domain = { xDomain: [0, 10], yDomain: [0, 10] }; +/** Five rows across the plot, the middle one missing its `y` */ +const gapped = [0, 1, 2, 3, 4].map((x) => ({ x, y: x === 2 ? null : 5 })); + +describe('Spline, as the core `Spline`', () => { + const flat = { + ...domain, + data: [ + { x: 0, y: 5 }, + { x: 10, y: 5 }, + ], + x: 'x', + y: 'y', + }; + + it('draws its own `pathData` in place of its rows’ line', async () => { + const scene = await renderPaths({ + mark: 'spline', + chart: flat, + spline: { pathData: 'M10,20L200,20', stroke: 'red' }, + }); + await expect + .poll(() => layers(scene).flatMap((layer) => segments(layer))) + .toEqual([ + [ + [expect.closeTo(10), expect.closeTo(20), expect.anything()], + [expect.closeTo(200), expect.closeTo(20), expect.anything()], + ], + ]); + expect(splines(scene)).toHaveLength(0); + }); + + it('draws its line from its start with `draw`', async () => { + const scene = await renderPaths({ + mark: 'spline', + chart: flat, + spline: { draw: { duration: 1000 } }, + }); + const end = chart!.xScale(10); + const drawn = () => reach(splines(scene).flatMap(segmentsOf)); + await expect.poll(() => drawn() > 10 && drawn() < end - 10).toBe(true); + await expect.poll(drawn).toBeCloseTo(end); + }); + + it('dims its line by `strokeOpacity`', async () => { + const scene = await renderPaths({ + mark: 'spline', + chart: flat, + spline: { strokeOpacity: 0.5, opacity: 0.5 }, + }); + await expect.poll(() => splines(scene)[0]?.material.opacity).toBeCloseTo(0.25); + }); + + it('adds nothing without a marker or content', async () => { + const scene = await renderPaths({ mark: 'spline', chart: flat }); + await expect.poll(() => splines(scene).length).toBe(1); + expect(layers(scene)).toHaveLength(1); + }); + + it('draws a `markerEnd` triangle with its tip at the line’s end', async () => { + const scene = await renderPaths({ + mark: 'spline', + chart: flat, + spline: { markerEnd: 'triangle' }, + }); + await expect.poll(() => meshCount(layers(scene)[1])).toBe(3); + // A pixel past the end, along the line (`refX` 9 of 10) + expect(extent(layers(scene)[1], 0)[1]).toBeCloseTo(chart!.xScale(10) + 1); + expect(extent(layers(scene)[1], 2)[0]).toBeCloseTo(chart!.yScale(5) - 5); + }); + + it('draws a `markerMid` at each row between its ends, a gap’s ends too', async () => { + const scene = await renderPaths({ + mark: 'spline', + chart: { xDomain: [0, 4], yDomain: [0, 10], data: gapped, x: 'x', y: 'y' }, + spline: { markerMid: 'dot' }, + }); + await expect.poll(() => meshCount(layers(scene)[1])).toBeGreaterThan(0); + // Dots at rows 1 and 3, not the line's ends (rows 0 and 4) + expect(extent(layers(scene)[1], 0)).toEqual([ + expect.closeTo(chart!.xScale(1) - 5), + expect.closeTo(chart!.xScale(3) + 5), + ]); + }); + + it('draws a `markerMid` only where a `curve`’s commands end', async () => { + const scene = await renderPaths({ + mark: 'spline', + chart: { + ...domain, + data: [ + { x: 0, y: 2 }, + { x: 5, y: 8 }, + { x: 10, y: 2 }, + ], + x: 'x', + y: 'y', + }, + spline: { curve: curveMonotoneX, markerMid: 'dot' }, + }); + await expect.poll(() => meshCount(layers(scene)[1])).toBeGreaterThan(0); + // One dot, at the middle row + expect(extent(layers(scene)[1], 0)).toEqual([ + expect.closeTo(chart!.xScale(5) - 5), + expect.closeTo(chart!.xScale(5) + 5), + ]); + }); + + it('gives each line’s `startContent` / `endContent` its first and last points', async () => { + const seen: { at: string; point: DOMPoint; value: any }[] = []; + await renderPaths({ + mark: 'spline', + chart: { + ...domain, + data: [ + { k: 'a', x: 1, y: 2 }, + { k: 'a', x: 9, y: 2 }, + { k: 'b', x: 1, y: 6 }, + { k: 'b', x: 9, y: 6 }, + ], + x: 'x', + y: 'y', + }, + spline: { g: 'k' }, + onContent: (at: string, props: Content) => seen.push({ at, ...props }), + }); + await expect.poll(() => seen.filter((s) => s.at === 'end').length).toBeGreaterThanOrEqual(2); + const ends = seen.filter((s) => s.at === 'end').map((s) => s.value.y); + expect(ends).toEqual(expect.arrayContaining([expect.closeTo(2), expect.closeTo(6)])); + const start = seen.find((s) => s.at === 'start')!; + expect(start.point.x).toBeCloseTo(chart!.xScale(1)); + expect(start.value.x).toBeCloseTo(1); + }); +}); + +describe('Area, as the core `Area`', () => { + const band = { + ...domain, + data: [ + { x: 0, y: 5 }, + { x: 10, y: 5 }, + ], + x: 'x', + y: 'y', + }; + + it('dims its outline by `strokeOpacity`, not its fill or its line', async () => { + const scene = await renderPaths({ + mark: 'area', + chart: band, + area: { stroke: 'black', strokeOpacity: 0.5, line: true }, + }); + await expect.poll(() => linesOf(layers(scene)[1])?.material.opacity).toBeCloseTo(0.5); + expect(meshOf(layers(scene)[0]).material.opacity).toBeCloseTo(1); + expect(linesOf(layers(scene)[0]).material.opacity).toBeCloseTo(1); + }); + + it('draws its outline from its start with `draw`', async () => { + const scene = await renderPaths({ + mark: 'area', + chart: band, + area: { stroke: 'black', draw: { duration: 1000 } }, + }); + const outline = () => segments(layers(scene)[1]); + // Along its top first... + await expect + .poll(() => outline().length > 0 && reach(outline()) < chart!.xScale(10) - 1) + .toBe(true); + // ...then around it, closed + await expect.poll(() => outline().length).toBe(4); + }); + + it('marks its outline’s start with `markerStart`, and puts `endContent` where it closes', async () => { + const seen: Record = {}; + const scene = await renderPaths({ + mark: 'area', + chart: band, + area: { stroke: 'black', markerStart: 'dot' }, + onContent: (at: string, props: Content) => (seen[at] = props), + }); + await expect.poll(() => meshCount(layers(scene)[2])).toBeGreaterThan(0); + const [x0, y5] = [chart!.xScale(0), chart!.yScale(5)]; + expect(extent(layers(scene)[2], 0)).toEqual([expect.closeTo(x0 - 5), expect.closeTo(x0 + 5)]); + expect(extent(layers(scene)[2], 2)).toEqual([expect.closeTo(y5 - 5), expect.closeTo(y5 + 5)]); + await expect.poll(() => seen.end?.point.x).toBeCloseTo(x0); + expect(seen.end.point.y).toBeCloseTo(y5); + }); +}); + +describe('Link, as the core `Link`', () => { + const one = { source: { x: 0, y: 0 }, target: { x: 100, y: 100 } }; + + it('draws its own `pathData` in place of the path between its ends', async () => { + const scene = await renderPaths({ + mark: 'link', + link: { data: one, pathData: 'M10,20L200,20' }, + }); + await expect.poll(() => segments(layers(scene)[0]).length).toBeGreaterThan(0); + const xs = segments(layers(scene)[0]) + .flat() + .map(([x]) => x); + expect([Math.min(...xs), Math.max(...xs)]).toEqual([expect.closeTo(10), expect.closeTo(200)]); + }); + + it('draws each link from its start with `draw`', async () => { + const scene = await renderPaths({ + mark: 'link', + link: { data: one, type: 'straight', draw: { duration: 1000 } }, + }); + const drawn = () => reach(segments(layers(scene)[0])); + await expect.poll(() => drawn() > 5 && drawn() < 95).toBe(true); + await expect.poll(drawn).toBeCloseTo(100); + }); + + it('raises each link by `z`', async () => { + const scene = await renderPaths({ + mark: 'link', + link: { data: one, type: 'straight', z: 30 }, + }); + await expect.poll(() => segments(layers(scene)[0]).length).toBe(1); + // A little over it, as a link on the floor is + expect(segments(layers(scene)[0])[0][0][2]).toBeCloseTo(30); + }); + + it('fills a flat link with `fill`, and nothing without one', async () => { + const plain = await renderPaths({ mark: 'link', link: { data: one } }); + await expect.poll(() => segments(layers(plain)[0]).length).toBeGreaterThan(0); + expect(meshCount(layers(plain)[0])).toBe(0); + + const scene = await renderPaths({ + mark: 'link', + link: { data: one, type: 'square', fill: 'red', fillOpacity: 0.5 }, + }); + await expect.poll(() => meshCount(layers(scene)[0])).toBeGreaterThan(0); + expect(meshOf(layers(scene)[0]).material.opacity).toBeCloseTo(0.5); + }); + + it('gives each link’s `startContent` / `endContent` its ends', async () => { + const seen: { at: string; point: DOMPoint }[] = []; + await renderPaths({ + mark: 'link', + link: { data: [one, { source: { x: 0, y: 50 }, target: { x: 200, y: 50 } }] }, + onContent: (at: string, props: Content) => seen.push({ at, ...props }), + }); + await expect.poll(() => seen.filter((s) => s.at === 'end').length).toBeGreaterThanOrEqual(2); + const ends = seen.filter((s) => s.at === 'end').map((s) => s.point.x); + expect(ends).toEqual(expect.arrayContaining([expect.closeTo(100), expect.closeTo(200)])); + }); +}); + +describe('GeoPath and Graticule, as the core marks', () => { + const geo = { geo: { projection: geoIdentity } }; + /** Where the chart's projection puts a point */ + const at = (point: [number, number]) => (chart as any).geo.projection(point) as [number, number]; + const across = { + type: 'LineString' as const, + coordinates: [ + [0, 0], + [50, 0], + [50, 50], + ], + }; + + it('draws its outlines from their start with `draw`', async () => { + const scene = await renderPaths({ + mark: 'geoPath', + chart: geo, + geoPath: { geojson: across, draw: { duration: 1000 } }, + }); + const drawn = () => segments(layers(scene)[0]).length; + // Along its first side before it turns... + await expect + .poll(() => { + const segs = segments(layers(scene)[0]); + const [[x0], [x1]] = [at([0, 0]), at([50, 0])]; + return segs.length === 1 && reach(segs) > x0 + 2 && reach(segs) < x1 - 2; + }) + .toBe(true); + // ...then all of it + await expect.poll(drawn).toBe(2); + }); + + it('marks its line with `markerEnd` and `markerMid`, and gives `endContent` its end', async () => { + const seen: Record = {}; + const scene = await renderPaths({ + mark: 'geoPath', + chart: geo, + geoPath: { geojson: across, markerMid: 'dot', markerEnd: 'triangle' }, + onContent: (at: string, props: Content) => (seen[at] = props), + }); + await expect.poll(() => meshCount(layers(scene)[2])).toBe(3); + const [corner, end, start] = [at([50, 0]), at([50, 50]), at([0, 0])]; + // The corner's dot, and the triangle's tip a pixel past the end, along the last side + expect(extent(layers(scene)[1], 0)).toEqual([ + expect.closeTo(corner[0] - 5), + expect.closeTo(corner[0] + 5), + ]); + const tip = extent(layers(scene)[2], 2); + expect(end[1] > corner[1] ? tip[1] : tip[0]).toBeCloseTo( + end[1] + Math.sign(end[1] - corner[1]) + ); + await expect.poll(() => seen.end?.point.y).toBeCloseTo(end[1]); + expect(seen.start.point.x).toBeCloseTo(start[0]); + expect(seen.start.point.y).toBeCloseTo(start[1]); + }); + + it('passes `markerEnd` to a `Graticule`’s lines', async () => { + const scene = await renderPaths({ + mark: 'graticule', + chart: geo, + graticule: { geojson: across, markerEnd: 'triangle' }, + }); + await expect.poll(() => meshCount(layers(scene)[1])).toBe(3); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-rects.svelte.test.ts b/packages/webgl/src/lib/components/parity-rects.svelte.test.ts new file mode 100644 index 0000000000..90576fb8cb --- /dev/null +++ b/packages/webgl/src/lib/components/parity-rects.svelte.test.ts @@ -0,0 +1,366 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { createRawSnippet } from 'svelte'; +import { scaleBand } from 'd3-scale'; +import { Color, Matrix4, Quaternion, Vector3, type InstancedMesh, type Object3D } from 'three'; + +import type { ChartState } from 'layerchart'; +import type { SceneState } from '../contexts/scene.svelte.js'; +import Marks from './__fixtures__/Marks.svelte'; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderMarks(props: Omit>[1], 'onScene'>) { + let scene: SceneState | undefined; + render(Marks, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +let chart: ChartState | undefined; + +/** The objects marks put in the scene, looking through each mark's own layer */ +const layered = (scene: SceneState) => + scene.root.children.flatMap((o) => (o.userData.layer ? o.children : [o])); +const instanced = (scene: SceneState) => + layered(scene).filter((o: Object3D) => (o as any).isInstancedMesh) as InstancedMesh[]; +/** The first mesh with instances drawn */ +const drawn = (scene: SceneState) => instanced(scene).find((mesh) => mesh.count > 0); +/** The visible line segments' objects */ +const lineSets = (scene: SceneState) => + layered(scene).filter((o: any) => o.isLineSegments2 && o.visible !== false) as any[]; + +/** Instance `i`'s corner and size, in the scene's axes */ +function box(mesh: InstancedMesh, i: number) { + const matrix = new Matrix4(); + mesh.getMatrixAt(i, matrix); + const position = new Vector3(); + const size = new Vector3(); + matrix.decompose(position, new Quaternion(), size); + return { position, size }; +} + +/** + * Click the canvas over a point of the plot (in chart pixels) until `done`, as the scene takes a + * frame or two to place its camera + */ +async function clickAt(scene: SceneState, x: number, y: number, done: () => boolean) { + const canvas = document.querySelector('.lc-layout-webgl canvas') as HTMLCanvasElement; + await expect + .poll(() => { + const at = scene.project(x, y, 0); + if (at) { + const rect = canvas.getBoundingClientRect(); + canvas.dispatchEvent( + new MouseEvent('click', { + clientX: rect.left + at.x, + clientY: rect.top + at.y, + bubbles: true, + }) + ); + } + return done(); + }) + .toBe(true); +} + +const columns = { + data: [ + { x: 'a', y: 4 }, + { x: 'b', y: 8 }, + ], + x: 'x', + xScale: scaleBand().padding(0.2), + xDomain: ['a', 'b'], + y: 'y', + yDomain: [0, 10], +}; + +/** The middle of column `x`'s bar, from the baseline to `value`, in chart pixels */ +const middleOf = (x: string, value: number) => { + const xScale = chart!.xScale as any; + return [xScale(x) + xScale.bandwidth() / 2, (chart!.yScale(0) + chart!.yScale(value)) / 2]; +}; + +describe('Bars, as the core `Bars`', () => { + it('calls `onclick` with the row of the bar clicked', async () => { + const clicked: any[] = []; + const scene = await renderMarks({ + mark: 'bars', + chart: columns, + bars: { onclick: (_e: MouseEvent, { data }: { data: any }) => clicked.push(data) } as any, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const [x, y] = middleOf('b', 8); + await clickAt(scene, x, y, () => clicked.length > 0); + expect(clicked[0]).toBe(columns.data[1]); + }); + + it('calls `onBarClick` with the row of the bar clicked', async () => { + const clicked: any[] = []; + const scene = await renderMarks({ + mark: 'bars', + chart: columns, + bars: { onBarClick: (_e: MouseEvent, { data }: { data: any }) => clicked.push(data) }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const [x, y] = middleOf('a', 4); + await clickAt(scene, x, y, () => clicked.length > 0); + expect(clicked[0]).toBe(columns.data[0]); + }); + + it('makes nothing pickable without a handler (or `tooltip`)', async () => { + const scene = await renderMarks({ mark: 'bars', chart: columns }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + expect(scene.pickables.size).toBe(0); + }); + + it('draws `fillOpacity` and `strokeOpacity` into the fill and outline', async () => { + const scene = await renderMarks({ + mark: 'bars', + chart: columns, + bars: { fillOpacity: 0.4, strokeWidth: 1, strokeOpacity: 0.5, opacity: 0.5 }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + expect((drawn(scene)!.material as any).opacity).toBeCloseTo(0.2); + await expect.poll(() => lineSets(scene)[0]?.material.opacity).toBeCloseTo(0.25); + }); + + it('eases a new bar in from `initialY` and `initialHeight` with `motion`', async () => { + const scene = await renderMarks({ + mark: 'bars', + chart: columns, + // Slow enough to see where it starts + bars: { motion: { type: 'tween', duration: 60_000 }, initialY: 10, initialHeight: 20 }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const { position, size } = box(drawn(scene)!, 1); + expect(position.z).toBeCloseTo(10, 0); + expect(size.z).toBeCloseTo(20, 0); + }); + + it('takes a fixed `width`, centered in its band', async () => { + const scene = await renderMarks({ mark: 'bars', chart: columns, bars: { width: 10 } }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const xScale = chart!.xScale as any; + const { position, size } = box(drawn(scene)!, 1); + expect(size.x).toBeCloseTo(10); + expect(position.x).toBeCloseTo(xScale('b') + xScale.bandwidth() / 2 - 5); + }); + + const fruit = { + data: [ + { x: 'a', apples: 2, bananas: 3 }, + { x: 'b', apples: 4, bananas: 1 }, + ], + x: 'x', + xScale: scaleBand().padding(0.2), + xDomain: ['a', 'b'], + yDomain: [0, 10], + series: [ + { key: 'apples', color: 'rgb(255, 0, 0)' }, + { key: 'bananas', color: 'rgb(0, 0, 255)' }, + ], + seriesLayout: 'stack' as const, + }; + + it("reads a series' stacked values with `seriesKey`, spaced by `stackPadding`", async () => { + const scene = await renderMarks({ + mark: 'bars', + chart: fruit, + bars: { seriesKey: 'bananas', stackPadding: 4 }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const { position, size } = box(drawn(scene)!, 0); + // On top of the apples, less half the padding beneath (the top of the stack keeps its edge) + expect(position.z).toBeCloseTo(chart!.yScale(5)); + expect(size.z).toBeCloseTo(chart!.yScale(2) - chart!.yScale(5) - 2); + // In the series' color + const color = new Color(); + drawn(scene)!.getColorAt(0, color); + expect(color.b).toBeGreaterThan(0.9); + expect(color.r).toBeLessThan(0.1); + }); +}); + +describe('Bar, as the core `Bar`', () => { + it('is pickable with an `onpointerenter`, as `Bars` with one', async () => { + const scene = await renderMarks({ + mark: 'bars', + chart: columns, + bars: { onpointerenter: () => {} } as any, + }); + await expect.poll(() => scene.pickables.size).toBe(1); + }); +}); + +describe('Rect, as the core `Rect`', () => { + const rows = [ + { x0: 10, x1: 30, y0: 10, y1: 40 }, + { x0: 50, x1: 90, y0: 20, y1: 60 }, + ]; + const chartProps = { data: rows, xDomain: [0, 100], yDomain: [0, 100] }; + + it('calls `onclick` with the row of the box clicked', async () => { + const clicked: any[] = []; + const scene = await renderMarks({ + mark: 'rect', + chart: chartProps, + rect: { + x0: 'x0', + x1: 'x1', + y0: 'y0', + y1: 'y1', + onclick: (_e: MouseEvent, { data }: { data: any }) => clicked.push(data), + }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const x = (chart!.xScale(50) + chart!.xScale(90)) / 2; + const y = (chart!.yScale(20) + chart!.yScale(60)) / 2; + await clickAt(scene, x, y, () => clicked.length > 0); + expect(clicked[0]).toBe(rows[1]); + }); + + it('calls a pixel-mode rect’s `onclick` without a row', async () => { + const clicked: any[] = []; + const scene = await renderMarks({ + mark: 'rect', + chart: chartProps, + rect: { + x: 20, + y: 20, + width: 60, + height: 40, + onclick: (_e: MouseEvent, detail: { data: any }) => clicked.push(detail), + }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(1); + await clickAt(scene, 50, 40, () => clicked.length > 0); + expect(clicked[0].data).toBeUndefined(); + }); + + it('shrinks each box by its `insets`', async () => { + const scene = await renderMarks({ + mark: 'rect', + chart: chartProps, + rect: { x: 20, y: 20, width: 60, height: 40, insets: { x: 5, top: 2 } }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(1); + const { position, size } = box(drawn(scene)!, 0); + expect(position.x).toBeCloseTo(25); + expect(size.x).toBeCloseTo(50); + expect(position.z).toBeCloseTo(22); + expect(size.z).toBeCloseTo(38); + }); + + it('dashes its outline with `dashArray`, at `strokeOpacity`', async () => { + const scene = await renderMarks({ + mark: 'rect', + chart: chartProps, + rect: { + x: 20, + y: 20, + width: 60, + height: 40, + stroke: 'black', + dashArray: '4 2', + strokeOpacity: 0.5, + }, + }); + await expect.poll(() => lineSets(scene)[0]?.material.dashed).toBe(true); + expect(lineSets(scene)[0].material.opacity).toBeCloseTo(0.5); + }); + + it('draws its sides unlit with `shade={false}`', async () => { + const scene = await renderMarks({ + mark: 'rect', + chart: chartProps, + rect: { x: 20, y: 20, width: 60, height: 40, z: 20, shade: false }, + }); + await expect.poll(() => (drawn(scene)?.material as any)?.isMeshBasicMaterial).toBe(true); + }); + + it('eases in from `initialWidth` and `initialHeight` with `motion` (pixel mode)', async () => { + const scene = await renderMarks({ + mark: 'rect', + chart: chartProps, + rect: { + x: 20, + y: 20, + width: 60, + height: 40, + initialWidth: 4, + initialHeight: 6, + motion: { type: 'tween', duration: 60_000 }, + }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(1); + const { size } = box(drawn(scene)!, 0); + expect(size.x).toBeCloseTo(4, 0); + expect(size.z).toBeCloseTo(6, 0); + }); +}); + +describe('Bin, as the core `Bin`', () => { + const rows = [...Array.from({ length: 5 }, () => ({ x: 1, y: 1 })), { x: 9, y: 9 }]; + const chartProps = { data: rows, x: 'x', y: 'y', xDomain: [0, 10], yDomain: [0, 10] }; + + it('calls `onclick` with the cell clicked', async () => { + const clicked: any[] = []; + const scene = await renderMarks({ + mark: 'bin', + chart: chartProps, + bin: { size: 40, onclick: (_e: MouseEvent, cell: any) => clicked.push(cell) }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + const x = chart!.xScale(1); + const y = chart!.yScale(1); + await clickAt(scene, x, y, () => clicked.length > 0); + expect(clicked[0].count).toBe(5); + }); + + it('draws `fillOpacity` into its cells', async () => { + const scene = await renderMarks({ + mark: 'bin', + chart: chartProps, + bin: { size: 40, fillOpacity: 0.5, opacity: 0.8 }, + }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + expect((drawn(scene)!.material as any).opacity).toBeCloseTo(0.4); + }); + + it('outlines every cell of the plot with `grid`', async () => { + const scene = await renderMarks({ mark: 'bin', chart: chartProps, bin: { size: 40 } }); + await expect.poll(() => drawn(scene)?.count).toBe(2); + expect(lineSets(scene)).toHaveLength(0); + + const gridded = await renderMarks({ + mark: 'bin', + chart: chartProps, + bin: { size: 40, grid: { strokeOpacity: 0.5 } }, + }); + await expect + .poll(() => lineSets(gridded)[0]?.geometry.attributes.instanceStart?.count ?? 0) + .toBeGreaterThan(20); + }); + + it('hands `children` the cells to draw in their place', async () => { + const children = createRawSnippet((props: () => { cells: any[] }) => ({ + render: () => ``, + })); + const scene = await renderMarks({ + mark: 'bin', + chart: chartProps, + bin: { size: 40, children }, + }); + await expect + .poll(() => document.querySelector('[data-cells]')?.getAttribute('data-cells')) + .toBe('2'); + expect(instanced(scene).every((mesh) => mesh.count === 0)).toBe(true); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-scales.svelte.test.ts b/packages/webgl/src/lib/components/parity-scales.svelte.test.ts new file mode 100644 index 0000000000..0964f2d32d --- /dev/null +++ b/packages/webgl/src/lib/components/parity-scales.svelte.test.ts @@ -0,0 +1,468 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { createRawSnippet } from 'svelte'; +import { scaleBand } from 'd3-scale'; +import { curveCatmullRomClosed } from 'd3-shape'; +import { geoIdentity, geoMercator } from 'd3-geo'; +import { Color, type Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import Marks from './__fixtures__/Marks.svelte'; +import ParityScales from './__fixtures__/ParityScales.svelte'; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderMarks(props: Omit>[1], 'onScene'>) { + let scene: SceneState | undefined; + render(Marks, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +/** As `renderMarks`, for the marks `Marks.svelte` has no case for (`Grid`, `Raster`, ...) */ +async function renderOthers( + props: Omit>[1], 'onScene'> +) { + let scene: SceneState | undefined; + render(ParityScales, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +/** The objects marks put in the scene, looking through each mark's own layer */ +const layered = (scene: SceneState) => + scene.root.children.flatMap((o) => (o.userData.layer ? o.children : [o])); + +/** Everything in the scene that `is` */ +function all(scene: SceneState, is: (o: any) => boolean) { + const found: any[] = []; + scene.root.traverse((o: Object3D) => { + if (is(o)) found.push(o); + }); + return found; +} +const visibleLines = (scene: SceneState) => + all(scene, (o) => o.isLineSegments2 && o.visible && o.geometry.attributes.instanceStart); + +const square = { + type: 'Feature' as const, + properties: {}, + // Clockwise, as d3-geo reads an outside ring + geometry: { + type: 'Polygon' as const, + coordinates: [ + [ + [10, 10], + [10, 100], + [100, 100], + [100, 10], + [10, 10], + ], + ], + }, +}; + +describe('Contour', () => { + it('fades raised lines by `strokeOpacity` and `opacity`, and blurs the grid by `blur`', async () => { + const segmentsOf = async (blur: number) => { + const scene = await renderMarks({ + mark: 'contour', + chart: { xDomain: [0, 1], yDomain: [0, 1] }, + contour: { + // A ridge, which a blur spreads (and so moves its lines) + value: (x: number, _y: number) => (Math.abs(x - 0.5) < 0.05 ? 1 : 0), + thresholds: [0.5], + z: 2, + stroke: 'black', + strokeOpacity: 0.5, + opacity: 0.5, + blur, + }, + }); + await expect.poll(() => visibleLines(scene).length).toBeGreaterThan(0); + const [lines] = visibleLines(scene); + expect(lines.material.opacity).toBeCloseTo(0.25); + return Array.from(lines.geometry.attributes.instanceStart.data.array as Float32Array); + }; + const sharp = await segmentsOf(0); + const blurred = await segmentsOf(4); + expect(blurred).not.toEqual(sharp); + }); + + it('raises lines by a function of the band, through the `z` scale', async () => { + const scene = await renderMarks({ + mark: 'contour', + chart: { xDomain: [0, 1], yDomain: [0, 1], zDomain: [0, 10], zRange: [0, 100] }, + contour: { + value: (x: number, _y: number) => x, + thresholds: [0.5], + z: (band: { value: number }) => band.value * 10, + stroke: 'black', + }, + }); + await expect.poll(() => visibleLines(scene).length).toBeGreaterThan(0); + const [lines] = visibleLines(scene); + const start = lines.geometry.attributes.instanceStart.data.array as Float32Array; + // `[x, height, y]`: 0.5 × 10 through the `z` scale, a pixel off the floor + expect(start[1]).toBeCloseTo(51); + }); +}); + +describe('GeoPath', () => { + const meshOf = (scene: SceneState) => layered(scene).find((o: any) => o.isMesh) as any; + const linesOf = (scene: SceneState) => layered(scene).find((o: any) => o.isLineSegments2) as any; + + it('fades its fill by `fillOpacity` and its outlines by `strokeOpacity`', async () => { + const scene = await renderMarks({ + mark: 'geopath', + chart: { geo: { projection: geoIdentity } }, + geopath: { + geojson: square, + fill: 'gray', + stroke: 'black', + fillOpacity: 0.5, + strokeOpacity: 0.25, + opacity: 0.8, + }, + }); + await expect.poll(() => meshOf(scene)?.material.opacity).toBeCloseTo(0.4); + expect(linesOf(scene).material.opacity).toBeCloseTo(0.2); + }); + + it('draws through `geoTransform` and `curve`, as the core `GeoPath`', async () => { + const extent = async (props: Record) => { + const scene = await renderMarks({ + mark: 'geopath', + chart: { geo: { projection: geoIdentity } }, + geopath: { geojson: square, stroke: 'black', ...props }, + }); + await expect.poll(() => linesOf(scene)?.visible).toBe(true); + const positions = linesOf(scene).geometry.attributes.instanceStart.data.array; + const xs = Array.from(positions as Float32Array).filter((_, i) => i % 3 === 0); + return { min: Math.min(...xs), count: xs.length }; + }; + const plain = await extent({}); + const moved = await extent({ + // The methods of a `geoTransform`, as the core `GeoPath` takes them + geoTransform: (projection: any) => ({ + point(this: any, x: number, y: number) { + const [px, py] = projection([x, y]); + this.stream.point(px + 50, py); + }, + }), + }); + expect(moved.min - plain.min).toBeCloseTo(50); + // A curve's outline follows it in many short lines, rather than the square's four + const curved = await extent({ curve: curveCatmullRomClosed }); + expect(curved.count).toBeGreaterThan(plain.count * 4); + }); + + it('calls `onclick` with the path generator and the feature', async () => { + const calls: any[] = []; + const scene = await renderMarks({ + mark: 'geopath', + chart: { geo: { projection: geoIdentity } }, + geopath: { + geojson: square, + fill: 'gray', + onclick: (_e: MouseEvent, geoPath: any, feature: any) => calls.push([geoPath, feature]), + }, + }); + await expect.poll(() => scene.pickables.size).toBeGreaterThan(0); + // The handler the mark registers, as the pointer calls it with the feature it's over + const [pickable] = [...scene.pickables]; + pickable.events?.()?.onclick?.(new MouseEvent('click'), { data: square }); + expect(calls).toHaveLength(1); + expect(typeof calls[0][0]).toBe('function'); + expect(calls[0][0](square)).toMatch(/^M/); + expect(calls[0][1]).toBe(square); + }); + + it('draws `children` in its place, given the path generator', async () => { + const children = createRawSnippet((args: () => { geoPath: any }) => ({ + render: () => ``, + })); + const scene = await renderMarks({ + mark: 'geopath', + chart: { geo: { projection: geoIdentity } }, + geopath: { geojson: square, fill: 'gray', children }, + }); + await expect + .poll(() => + document.querySelector('[data-parity-geopath]')?.getAttribute('data-parity-geopath') + ) + .toBe('yes'); + expect(meshOf(scene).geometry.getAttribute('position')?.count ?? 0).toBe(0); + }); +}); + +describe('GeoTile', () => { + const solid = () => { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 256; + const context = canvas.getContext('2d')!; + context.fillStyle = 'rgb(10, 200, 30)'; + context.fillRect(0, 0, 256, 256); + return canvas.toDataURL(); + }; + const image = solid(); + const area = { + type: 'Feature' as const, + properties: {}, + geometry: { + type: 'Polygon' as const, + coordinates: [ + [ + [-10, -10], + [-10, 10], + [10, 10], + [10, -10], + [-10, -10], + ], + ], + }, + }; + const meshes = (scene: SceneState) => + all(scene, (o) => o.isMesh && !o.userData.backdrop && o.material?.map); + + it('fades its tiles with its `group`', async () => { + const scene = await renderMarks({ + mark: 'geotile', + chart: { geo: { projection: geoMercator, fitGeojson: area } }, + geotile: { url: () => image, group: { opacity: 0.5 } }, + }); + await expect.poll(() => meshes(scene).length).toBeGreaterThan(0); + await expect.poll(() => meshes(scene)[0].material.opacity).toBeCloseTo(0.5); + }); + + it('draws `children` in place of the tiles, given them', async () => { + const children = createRawSnippet((args: () => { tiles: any[] }) => ({ + render: () => ``, + })); + const scene = await renderMarks({ + mark: 'geotile', + chart: { geo: { projection: geoMercator, fitGeojson: area } }, + geotile: { url: () => image, children }, + }); + await expect + .poll(() => + Number(document.querySelector('[data-parity-tiles]')?.getAttribute('data-parity-tiles')) + ) + .toBeGreaterThan(0); + expect(meshes(scene)).toHaveLength(0); + }); +}); + +describe('Highlight', () => { + const data = [ + { x: 'a', y: 3 }, + { x: 'b', y: 5 }, + ]; + const chartProps = { data, x: 'x', y: 'y', xScale: scaleBand(), yDomain: [0, 10] }; + + it('draws the row’s `bar`, calling `onBarClick` with it', async () => { + const calls: any[] = []; + const scene = await renderMarks({ + mark: 'highlight', + chart: chartProps, + highlight: { + data: data[1], + bar: { fill: 'red' }, + onBarClick: (_e: MouseEvent, detail: { data: any }) => calls.push(detail.data), + }, + }); + await expect.poll(() => scene.pickables.size).toBeGreaterThan(0); + const [pickable] = [...scene.pickables].filter((p) => p.events?.()?.onclick); + pickable.events!()!.onclick!(new MouseEvent('click'), { data: data[1] }); + expect(calls).toEqual([data[1]]); + }); +}); + +describe('Highlight area', () => { + const data = [ + { x: 'a', y: 3 }, + { x: 'b', y: 5 }, + ]; + + it('calls `onAreaClick` with the highlighted row', async () => { + const calls: any[] = []; + const scene = await renderMarks({ + mark: 'highlight', + chart: { data, x: 'x', y: 'y', xScale: scaleBand(), yDomain: [0, 10] }, + highlight: { + data: data[0], + area: true, + onAreaClick: (_e: MouseEvent, detail: { data: any }) => calls.push(detail.data), + }, + }); + await expect + .poll(() => [...scene.pickables].filter((p) => p.events?.()?.onclick).length) + .toBeGreaterThan(0); + const [pickable] = [...scene.pickables].filter((p) => p.events?.()?.onclick); + pickable.events!()!.onclick!(new MouseEvent('click'), { data: undefined }); + expect(calls).toEqual([data[0]]); + }); +}); + +describe('Axis', () => { + const flat = { data: [{ x: 1, y: 1 }], x: 'x', y: 'y', xDomain: [0, 10], yDomain: [0, 10] }; + const viewportLabels = (scene: SceneState) => scene.labelSets.flat(); + + it('places its `label` by `labelPlacement`', async () => { + const xOf = async (labelPlacement: 'start' | 'middle' | 'end') => { + const scene = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { + placement: 'bottom', + ticks: [], + label: 'x', + labelPlacement, + labelProps: { viewport: true }, + }, + }); + await expect.poll(() => viewportLabels(scene).length).toBe(1); + return viewportLabels(scene)[0].x; + }; + expect(await xOf('start')).toBeCloseTo(0); + expect(await xOf('middle')).toBeCloseTo(chart!.width / 2); + expect(await xOf('end')).toBeCloseTo(chart!.width); + }); + + it('ticks its own `domain`, and moves with `x` / `y` as a `Group`', async () => { + const scene = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { + placement: 'left', + domain: [0, 100], + ticks: 2, + tickLabelProps: { viewport: true }, + x: 20, + }, + }); + await expect.poll(() => viewportLabels(scene).map((l) => l.text)).toContain('100'); + // On the left edge, moved 20 pixels across + expect(Math.round(viewportLabels(scene)[0].x)).toBe(20); + }); + + it('draws its tick marks in `stroke`, and tick labels through `tickLabel`', async () => { + const tickLabel = createRawSnippet((args: () => { props: any; index: number }) => ({ + render: () => ``, + })); + const scene = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'bottom', ticks: [0, 5, 10], stroke: 'rgb(255, 0, 0)', tickLabel }, + }); + await expect + .poll(() => + [...document.querySelectorAll('[data-parity-tick]')].map((e) => + e.getAttribute('data-parity-tick') + ) + ) + .toEqual(['0', '5', '10']); + const red = new Color('rgb(255, 0, 0)'); + await expect + .poll(() => visibleLines(scene).some((l) => l.material.color.equals(red))) + .toBe(true); + }); + + it('dashes its `grid` lines by their `dashArray`', async () => { + const scene = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'left', ticks: [0, 5, 10], grid: { dashArray: 4 } }, + }); + await expect.poll(() => visibleLines(scene).some((l) => l.material.dashed)).toBe(true); + }); +}); + +describe('Grid', () => { + const band = { + data: [{ x: 'a' }, { x: 'b' }, { x: 'c' }], + x: 'x', + xScale: scaleBand().padding(0.2), + yDomain: [0, 10], + }; + /** Each visible line set's segment count */ + const xLineCount = (scene: SceneState) => + visibleLines(scene).map((l) => l.geometry.attributes.instanceStart.count); + + it('lines up with bands by `bandAlign`, one past the last between them', async () => { + const center = await renderOthers({ mark: 'grid', chart: band, grid: { y: false, z: false } }); + await expect.poll(() => xLineCount(center)).toEqual([3]); + const between = await renderOthers({ + mark: 'grid', + chart: band, + grid: { y: false, z: false, bandAlign: 'between' }, + }); + await expect.poll(() => xLineCount(between)).toEqual([4]); + }); + + it('styles each axis’ lines by its own props', async () => { + const scene = await renderOthers({ + mark: 'grid', + chart: { xDomain: [0, 10], yDomain: [0, 10] }, + grid: { x: { stroke: 'rgb(0, 0, 255)', strokeWidth: 3 }, y: true, z: false }, + }); + const blue = new Color('rgb(0, 0, 255)'); + await expect.poll(() => visibleLines(scene).length).toBe(2); + const own = visibleLines(scene).find((l) => l.material.color.equals(blue)); + expect(own?.material.linewidth).toBe(3); + }); +}); + +describe('Raster', () => { + it('blurs the image over `blur` cells', async () => { + const pixelsOf = async (blur: number) => { + const scene = await renderOthers({ + mark: 'raster', + chart: { xDomain: [0, 1], yDomain: [0, 1] }, + raster: { data: [0, 0, 10, 0, 0], width: 5, height: 1, blur }, + }); + const mesh = () => all(scene, (o) => o.isMesh && o.material?.map)[0]; + await expect.poll(() => mesh()).toBeTruthy(); + return Array.from(mesh().material.map.image.data as Uint8Array); + }; + const sharp = await pixelsOf(0); + const blurred = await pixelsOf(1); + expect(blurred).not.toEqual(sharp); + }); +}); + +describe('GeoRaster', () => { + it('lays its image over `resolution` times as many points', async () => { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 16; + const countOf = async (resolution: number) => { + const scene = await renderOthers({ + mark: 'georaster', + chart: { geo: { projection: geoIdentity, fitGeojson: square } }, + georaster: { image: canvas, resolution }, + }); + const mesh = () => all(scene, (o) => o.isMesh)[0]; + await expect + .poll(() => mesh()?.geometry.getAttribute('position')?.count ?? 0) + .toBeGreaterThan(0); + return mesh().geometry.getAttribute('position').count; + }; + const one = await countOf(1); + const two = await countOf(2); + expect(two / one).toBeGreaterThan(3); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-shared.svelte.test.ts b/packages/webgl/src/lib/components/parity-shared.svelte.test.ts new file mode 100644 index 0000000000..a3d1d3c3ce --- /dev/null +++ b/packages/webgl/src/lib/components/parity-shared.svelte.test.ts @@ -0,0 +1,444 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { + Matrix4, + OrthographicCamera, + Quaternion, + Scene, + Vector3, + WebGLRenderer, + WebGLRenderTarget, + type InstancedMesh, + type Mesh, + type Object3D, +} from 'three'; + +import type { ChartState } from 'layerchart'; +import type { SceneState } from '../contexts/scene.svelte.js'; +import { contourSegments } from '../utils/contours.js'; +import { perspective } from '../index.js'; +import Marks from './__fixtures__/Marks.svelte'; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderMarks(props: Omit>[1], 'onScene'>) { + let scene: SceneState | undefined; + const result = render(Marks, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return { scene: scene!, rerender: result.rerender }; +} + +/** The objects marks put in the scene, looking through each mark's own layer */ +const layered = (scene: SceneState) => + scene.root.children.flatMap((o) => (o.userData.layer ? o.children : [o])); + +const instanced = (scene: SceneState) => + layered(scene).filter((o: Object3D) => (o as any).isInstancedMesh) as InstancedMesh[]; + +/** The planes labels lying on the surface are painted on */ +const planes = (scene: SceneState) => { + const found: Mesh[] = []; + scene.root.traverse((o: any) => { + if (o.isMesh && o.material?.map) found.push(o); + }); + return found; +}; + +/** The most opaque pixel painted on a label's plane (0 to 255) */ +function peakAlpha(plane: Mesh) { + const canvas = (plane.material as any).map.image as HTMLCanvasElement; + const pixels = canvas.getContext('2d')!.getImageData(0, 0, canvas.width, canvas.height).data; + let peak = 0; + for (let i = 3; i < pixels.length; i += 4) peak = Math.max(peak, pixels[i]); + return peak; +} + +describe('Text, with the core `Text`’s opacities', () => { + it('fades a `viewport` label’s letters, halo, and the whole of it', async () => { + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { + x: 100, + y: 50, + value: 'faded', + viewport: true, + stroke: 'white', + fillOpacity: 0.4, + strokeOpacity: 0.25, + opacity: 0.8, + }, + }); + await expect.poll(() => scene.labelSets.flat().length).toBe(1); + const [label] = scene.labelSets.flat(); + expect([label.fillOpacity, label.strokeOpacity, label.opacity]).toEqual([0.4, 0.25, 0.8]); + + const element = () => + [...document.querySelectorAll('.lc-webgl-label')].find( + (e) => e.textContent?.trim() === 'faded' + ); + await expect.poll(() => element()).toBeTruthy(); + const style = element()!.style; + expect(style.opacity).toBe('0.8'); + expect(style.getPropertyValue('-webkit-text-fill-color')).toContain('40%'); + expect(style.getPropertyValue('-webkit-text-stroke')).toContain('25%'); + }); + + it('takes them per row, as functions of it', async () => { + const { scene } = await renderMarks({ + mark: 'text', + chart: { xDomain: [0, 100], yDomain: [0, 100] }, + text: { + data: [ + { x: 10, y: 10, o: 0.2 }, + { x: 50, y: 50, o: 0.6 }, + ], + x: (d: any) => d.x, + y: (d: any) => d.y, + value: (d: any) => String(d.o), + viewport: true, + opacity: (d: any) => d.o, + }, + }); + await expect.poll(() => scene.labelSets.flat().length).toBe(2); + expect(scene.labelSets.flat().map((l) => l.opacity)).toEqual([0.2, 0.6]); + }); + + it('leaves a label without them as it was', async () => { + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'plain', viewport: true }, + }); + await expect.poll(() => scene.labelSets.flat().length).toBe(1); + const [label] = scene.labelSets.flat(); + expect([label.fillOpacity, label.strokeOpacity, label.opacity]).toEqual([ + undefined, + undefined, + undefined, + ]); + }); + + it('paints a label lying on the surface at `fillOpacity`, and fades its plane by `opacity`', async () => { + const solid = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'solid', fill: 'black' }, + }); + await expect.poll(() => planes(solid.scene).length).toBe(1); + const [plain] = planes(solid.scene); + expect(peakAlpha(plain)).toBeGreaterThan(250); + expect((plain.material as any).opacity).toBe(1); + + const { scene } = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'faded', fill: 'black', fillOpacity: 0.5, opacity: 0.4 }, + }); + await expect.poll(() => planes(scene).length).toBe(1); + const [plane] = planes(scene); + // Its letters painted half opaque, and the plane drawn at 0.4 + expect(peakAlpha(plane)).toBeGreaterThan(110); + expect(peakAlpha(plane)).toBeLessThan(145); + expect((plane.material as any).opacity).toBeCloseTo(0.4); + }); +}); + +/** An instance's center (across, down the plot) and radius */ +function placed(mesh: InstancedMesh, i = 0) { + const matrix = new Matrix4(); + mesh.getMatrixAt(i, matrix); + const position = new Vector3(); + const size = new Vector3(); + matrix.decompose(position, new Quaternion(), size); + return { x: position.x, y: position.z, r: size.x }; +} + +/** + * Which of `samples` points round a ring (at its radius, clockwise as the plot is seen from its + * rightmost point) are drawn, rendered from above on its own + */ +function ringCoverage(ring: InstancedMesh, samples: number) { + const { x, y, r } = placed(ring); + const scene = new Scene(); + scene.add(ring); + ring.updateMatrixWorld(); + const size = 128; + const half = r * 1.25; + const camera = new OrthographicCamera(-half, half, half, -half, 0.1, 1000); + // Looking straight down, the plot's `y` (the scene's `z`) running down the screen + camera.position.set(x, 100, y); + camera.up.set(0, 0, -1); + camera.lookAt(x, 0, y); + const renderer = new WebGLRenderer(); + const target = new WebGLRenderTarget(size, size); + renderer.setRenderTarget(target); + renderer.setClearColor(0x000000, 0); + renderer.render(scene, camera); + const pixels = new Uint8Array(size * size * 4); + renderer.readRenderTargetPixels(target, 0, 0, size, size, pixels); + renderer.setRenderTarget(null); + renderer.dispose(); + target.dispose(); + return Array.from({ length: samples }, (_, k) => { + const angle = ((k + 0.5) / samples) * Math.PI * 2; + // Down the screen is up the rows read back + const px = Math.round(size / 2 + ((Math.cos(angle) * r) / half) * (size / 2)); + const py = Math.round(size / 2 - ((Math.sin(angle) * r) / half) * (size / 2)); + return { angle, drawn: pixels[(py * size + px) * 4 + 3] > 0 }; + }); +} + +describe('dashed rings, as the core `Circle`’s `dashArray`', () => { + it('dashes a `Circle`’s ring from its rightmost point, clockwise', async () => { + const { scene } = await renderMarks({ + mark: 'circle', + chart: {}, + circle: { + cx: 100, + cy: 80, + r: 40, + fill: 'none', + stroke: 'black', + strokeWidth: 4, + dashArray: '10 30', + }, + }); + await expect.poll(() => instanced(scene)[0]?.count ?? 0).toBe(1); + const [ring] = instanced(scene); + const material = ring.material as any; + await expect.poll(() => material.defines.LC_RING_DASH).toBe(''); + const [dash, gap] = material.userData.ringDash.value.toArray(); + expect(gap / dash).toBeCloseTo(3); + + const { r } = placed(ring); + const samples = ringCoverage(ring, 180); + const expected = (around: number) => around % (dash + gap) <= dash; + // Where its dashes fall, going clockwise from the rightmost point, and not the other way + const clockwise = samples.filter((s) => s.drawn === expected(s.angle * r)).length; + const counter = samples.filter((s) => s.drawn === expected((Math.PI * 2 - s.angle) * r)).length; + expect(clockwise / samples.length).toBeGreaterThan(0.9); + expect(counter).toBeLessThan(clockwise); + // About a quarter of it drawn + const share = samples.filter((s) => s.drawn).length / samples.length; + expect(share).toBeGreaterThan(0.15); + expect(share).toBeLessThan(0.35); + }); + + it('draws a ring without one whole, compiled without dashes', async () => { + const { scene } = await renderMarks({ + mark: 'circle', + chart: {}, + circle: { cx: 100, cy: 80, r: 40, fill: 'none', stroke: 'black', strokeWidth: 4 }, + }); + await expect.poll(() => instanced(scene)[0]?.count ?? 0).toBe(1); + const [ring] = instanced(scene); + expect((ring.material as any).defines.LC_RING_DASH).toBeUndefined(); + const samples = ringCoverage(ring, 90); + expect(samples.every((s) => s.drawn)).toBe(true); + }); + + it('dashes `Points`’ rings, and stops when it’s taken away', async () => { + const rows = [ + { x: 2, y: 2 }, + { x: 7, y: 6 }, + ]; + const chartProps = { data: rows, x: 'x', y: 'y', xDomain: [0, 10], yDomain: [0, 10] }; + const { scene, rerender } = await renderMarks({ + mark: 'points', + chart: chartProps, + points: { r: 8, stroke: 'black', dashArray: [4, 2] }, + }); + await expect.poll(() => instanced(scene).length).toBe(2); + const ring = instanced(scene)[1]; + const material = ring.material as any; + await expect.poll(() => material.defines.LC_RING_DASH).toBe(''); + const [dash, gap] = material.userData.ringDash.value.toArray(); + expect(dash / gap).toBeCloseTo(2); + // The points' discs aren't dashed + expect((instanced(scene)[0].material as any).defines?.LC_RING_DASH).toBeUndefined(); + + await rerender({ points: { r: 8, stroke: 'black' } }); + await expect.poll(() => material.defines.LC_RING_DASH).toBeUndefined(); + }); +}); + +describe('Highlight, with the core `Highlight`’s point events', () => { + const row = { x: 4, y: 6 }; + const chartProps = { data: [row], x: 'x', y: 'y', xDomain: [0, 10], yDomain: [0, 10] }; + const marker = () => document.querySelector('.lc-webgl-markers circle'); + + it('calls `onPointClick`, `onPointEnter`, and `onPointLeave` with its point and row', async () => { + const calls: [string, any][] = []; + await renderMarks({ + mark: 'highlight', + chart: chartProps, + highlight: { + data: row, + points: true, + motion: 'none', + onPointClick: (_e: MouseEvent, detail: any) => calls.push(['click', detail]), + onPointEnter: (_e: MouseEvent, detail: any) => calls.push(['enter', detail]), + onPointLeave: (_e: MouseEvent, detail: any) => calls.push(['leave', detail]), + }, + }); + await expect.poll(() => marker()).toBeTruthy(); + // Taking the pointer, as a clickable point + expect(marker()!.style.pointerEvents).toBe('auto'); + expect(marker()!.style.cursor).toBe('pointer'); + + marker()!.dispatchEvent(new PointerEvent('pointerenter')); + marker()!.dispatchEvent(new MouseEvent('click', { bubbles: true })); + marker()!.dispatchEvent(new PointerEvent('pointerleave')); + expect(calls.map(([type]) => type)).toEqual(['enter', 'click', 'leave']); + const [, { point, data }] = calls[1]; + expect(data).toBe(row); + expect(point.x).toBeCloseTo(chart!.xScale(4)); + expect(point.y).toBeCloseTo(chart!.yScale(6)); + expect(point.data).toEqual({ x: 4, y: 6 }); + }); + + it('lets the pointer through to the scene without them', async () => { + await renderMarks({ + mark: 'highlight', + chart: chartProps, + highlight: { data: row, points: true, motion: 'none' }, + }); + await expect.poll(() => marker()).toBeTruthy(); + expect(marker()!.style.pointerEvents).toBe(''); + expect(getComputedStyle(marker()!).pointerEvents).toBe('none'); + }); +}); + +describe('Axis, with the core `Axis`’ `tickOcclusion`', () => { + const flat = { x: 'x', y: 'y', xDomain: [0, 10], yDomain: [0, 10] }; + const ticks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + const format = (d: number) => `Wednesday ${d}`; + const texts = (scene: SceneState) => scene.labelSets.flat().map((l) => l.text); + + it('keeps every tick without it', async () => { + const { scene } = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'bottom', ticks, format, tickLabelProps: { viewport: true } }, + }); + await expect.poll(() => texts(scene).length).toBe(11); + }); + + it('drops tick labels that would overlap, keeping the last (`end`) by default', async () => { + const { scene } = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { + placement: 'bottom', + ticks, + format, + tickOcclusion: true, + tickLabelProps: { viewport: true }, + }, + }); + await expect.poll(() => texts(scene).length).toBeGreaterThan(1); + const kept = texts(scene); + expect(kept.length).toBeLessThan(11); + expect(kept.at(-1)).toBe('Wednesday 10'); + }); + + it('keeps the first with `priority: start`, and both ends with `start-end`', async () => { + const start = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { + placement: 'bottom', + ticks, + format, + tickOcclusion: { priority: 'start' }, + tickLabelProps: { viewport: true }, + }, + }); + await expect.poll(() => texts(start.scene).length).toBeGreaterThan(1); + expect(texts(start.scene)[0]).toBe('Wednesday 0'); + expect(texts(start.scene).length).toBeLessThan(11); + + const ends = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { + placement: 'bottom', + ticks, + format, + tickOcclusion: { priority: 'start-end' }, + tickLabelProps: { viewport: true }, + }, + }); + await expect.poll(() => texts(ends.scene).length).toBeGreaterThan(1); + expect(texts(ends.scene)[0]).toBe('Wednesday 0'); + expect(texts(ends.scene).at(-1)).toBe('Wednesday 10'); + }); + + it('drops the tick marks and labels lying on the floor with them', async () => { + const { scene } = await renderMarks({ + mark: 'axis', + chart: flat, + axis: { placement: 'bottom', ticks, format, tickOcclusion: true }, + }); + await expect.poll(() => planes(scene).length).toBeGreaterThan(1); + const labels = planes(scene).length; + expect(labels).toBeLessThan(11); + const marks = () => { + const lines = layered(scene).filter((o) => (o as any).isLineSegments2) as any[]; + return Math.max( + ...lines.map((l) => (l.visible ? l.geometry.attributes.instanceStart.count : 0)) + ); + }; + await expect.poll(marks).toBe(labels); + }); + + it('keeps every tick in a 3D view, whose labels turn with it', async () => { + const { scene } = await renderMarks({ + mark: 'axis', + chart: { ...flat, view: perspective }, + axis: { + placement: 'bottom', + ticks, + format, + tickOcclusion: true, + tickLabelProps: { viewport: true }, + }, + }); + await expect.poll(() => texts(scene).length).toBe(11); + }); +}); + +describe('contourSegments, with `smooth`', () => { + // A peak in the middle of a 4 × 4 grid + const grid = { + values: Float64Array.from([0, 0, 0, 0, 0, 3, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0]), + columns: 4, + rows: 4, + left: 0, + top: 0, + right: 4, + bottom: 4, + }; + /** Each segment end across and down, in cells */ + const ends = (segments: number[]) => + segments.flatMap((_, i) => (i % 3 === 0 ? [segments[i], segments[i + 2]] : [])); + + it('interpolates where lines cross between cells by default', () => { + const smooth = ends(contourSegments(grid, [0, 3], [0.25], () => 0)); + expect(smooth.some((v) => !Number.isInteger(v * 2))).toBe(true); + }); + + it('runs them halfway between cells with `smooth: false`', () => { + const crisp = ends(contourSegments(grid, [0, 3], [0.25], () => 0, { smooth: false })); + expect(crisp.length).toBeGreaterThan(0); + expect(crisp.every((v) => Number.isInteger(v * 2))).toBe(true); + }); +}); diff --git a/packages/webgl/src/lib/contexts/scene.svelte.ts b/packages/webgl/src/lib/contexts/scene.svelte.ts index 6e3b6e8099..7859056b0c 100644 --- a/packages/webgl/src/lib/contexts/scene.svelte.ts +++ b/packages/webgl/src/lib/contexts/scene.svelte.ts @@ -32,6 +32,11 @@ export type SceneLabel = { /** A halo around the letters, behind them (a CSS color), and its width in pixels */ stroke?: string; strokeWidth?: number; + /** How opaque its letters and its halo are (0 to 1), as SVG text's fill and stroke opacity */ + fillOpacity?: number; + strokeOpacity?: number; + /** How opaque it is as a whole (0 to 1), letters and halo together */ + opacity?: number; /** * The way it sits out from its point, in the chart's axes (ex. out from an axis): it's anchored * by its side nearest the point, whichever way the view turns that on screen, so it keeps the @@ -58,12 +63,39 @@ export type SceneMarker = { strokeWidth?: number; opacity?: number; class?: string; + /** + * Pointer handlers, as on the core marks' elements (ex. a `Highlight`'s `onPointClick`). Only a + * marker with one takes the pointer; the rest let it through to the scene beneath. + */ + onclick?: (e: MouseEvent) => void; + onpointerenter?: (e: PointerEvent) => void; + onpointerleave?: (e: PointerEvent) => void; }; +/** Pointer handlers a mark takes, as the core marks' (called with the row under the pointer) */ +export type MarkEvents = { + onclick?: ((e: MouseEvent, detail: { data: any }) => void) | null; + ondblclick?: ((e: MouseEvent, detail: { data: any }) => void) | null; + onpointerenter?: ((e: PointerEvent, detail: { data: any }) => void) | null; + onpointerover?: ((e: PointerEvent, detail: { data: any }) => void) | null; + onpointermove?: ((e: PointerEvent, detail: { data: any }) => void) | null; + onpointerleave?: ((e: PointerEvent, detail: { data: any }) => void) | null; + onpointerout?: ((e: PointerEvent, detail: { data: any }) => void) | null; +}; + +/** Whether any of `events` is set */ +export function hasEvents(events: MarkEvents | undefined) { + return !!events && Object.values(events).some((handler) => typeof handler === 'function'); +} + /** A mark's object the pointer can hit, and the data row each hit is on */ export type Pickable = { object: Object3D; datum: (hit: Intersection) => unknown; + /** Whether hovering it shows the tooltip (else it's picked only for `events`) @default true */ + tooltip?: () => boolean; + /** Its pointer handlers, called with the row under the pointer */ + events?: () => MarkEvents | undefined; }; const KEY = Symbol('LayerChart3DScene'); @@ -101,6 +133,8 @@ export class SceneState { layer() { const group = new Group(); group.userData.layer = true; + // Past the plot box's sides where asked (ex. a line's markers at its edge, as SVG's overflow) + if (isUnclipped()) group.userData.unclipped = true; this.#layers.push(group); // Inside a `Group`, under its own (moved by it, as an SVG `` moves what's in it) const parent = getParent()?.object ?? this.root; diff --git a/packages/webgl/src/lib/utils/contours.ts b/packages/webgl/src/lib/utils/contours.ts index 02bf2c25ac..03890ceae1 100644 --- a/packages/webgl/src/lib/utils/contours.ts +++ b/packages/webgl/src/lib/utils/contours.ts @@ -19,13 +19,19 @@ export function contourSegments( grid: Grid, extent: [number, number], thresholds: number | number[], - height: (value: number) => number + height: (value: number) => number, + { + smooth = true, + }: { + /** Interpolate where lines cross each cell, else run them along the cells' corners */ + smooth?: boolean; + } = {} ): number[] { const { values, columns, rows } = grid; const levels = Array.isArray(thresholds) ? thresholds : ticks(extent[0], extent[1], thresholds); // Holes close around themselves rather than leaving lines open const field = Array.from(values, (v) => (Number.isFinite(v) ? v : -Infinity)); - const generator = d3Contours().size([columns, rows]).thresholds(levels); + const generator = d3Contours().size([columns, rows]).thresholds(levels).smooth(smooth); const onEdge = (x: number, y: number) => x <= 0 || y <= 0 || x >= columns || y >= rows; const segments: number[] = []; diff --git a/packages/webgl/src/lib/utils/dash.test.ts b/packages/webgl/src/lib/utils/dash.test.ts new file mode 100644 index 0000000000..4bdbc182ac --- /dev/null +++ b/packages/webgl/src/lib/utils/dash.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { dashPattern } from './merged.svelte.js'; + +describe('dashPattern', () => { + it('reads a dashArray as the core marks take it: a length, an array, or a string', () => { + expect(dashPattern(4)).toEqual([4, 4]); + expect(dashPattern([6, 2])).toEqual([6, 2]); + expect(dashPattern([6, 2, 1, 2])).toEqual([6, 2]); + expect(dashPattern('3 1')).toEqual([3, 1]); + expect(dashPattern('3,1')).toEqual([3, 1]); + }); + + it('is solid without one', () => { + for (const none of [undefined, null, '', 'none', 0, [0, 2]]) { + expect(dashPattern(none as any)).toBeNull(); + } + }); +}); diff --git a/packages/webgl/src/lib/utils/instances.svelte.ts b/packages/webgl/src/lib/utils/instances.svelte.ts index 21c7e1af58..d186021637 100644 --- a/packages/webgl/src/lib/utils/instances.svelte.ts +++ b/packages/webgl/src/lib/utils/instances.svelte.ts @@ -11,13 +11,19 @@ import { MeshLambertMaterial, NormalBlending, Quaternion, + Vector2, Vector3, Vector4, type BufferAttribute, } from 'three'; import { getChartContext } from 'layerchart'; -import { getSceneContext, groupOpacity } from '../contexts/scene.svelte.js'; +import { + getSceneContext, + groupOpacity, + hasEvents, + type MarkEvents, +} from '../contexts/scene.svelte.js'; /** * One shape of an instanced mark, in chart pixels: where it stands (`x` across, `y` down the @@ -49,6 +55,8 @@ type InstancesOptions = { emphasize: (color: Color, size: Vector3) => void; /** Whether hovering shows the tooltip */ tooltip?: () => boolean; + /** Pointer handlers, called with the row under the pointer (as the core marks' `onclick`, ...) */ + events?: () => MarkEvents | undefined; /** Draw each instance in its own color, unlit (ex. a star) */ glow?: () => boolean; /** @@ -73,6 +81,11 @@ type InstancesOptions = { * a circle's edge */ ring?: () => number; + /** + * Dash `ring`'s rings, `[dash, gap]` in scene units along each ring (from its rightmost point, + * clockwise as the plot is seen, as an SVG circle's dashes run), or `null` for none + */ + dash?: () => [dash: number, gap: number] | null; }; /** @@ -105,6 +118,14 @@ export function ringGeometry(segments = 32) { return geometry; } +/** A `dashPattern` in pixels on screen as scene units (`scale` of them a pixel), for `dash` */ +export function scaledDash( + pattern: [number, number] | null, + scale: number +): [number, number] | null { + return pattern && [pattern[0] * scale, pattern[1] * scale]; +} + /** The `shift` a material draws with, shared by its compiled program */ const shifts = new WeakMap(); @@ -120,14 +141,18 @@ function createMaterial(lit: boolean, ring = false) { material.userData.shift = shift.value; const ringHalf = { value: 0 }; material.userData.ringHalf = ringHalf; + // Dashes are only compiled in while a ring has them (`LC_RING_DASH`) + const ringDash = { value: new Vector2() }; + material.userData.ringDash = ringDash; if (ring) material.defines = { LC_RING: '' }; material.onBeforeCompile = (shader) => { shader.uniforms.uShift = shift; shader.uniforms.uRingHalf = ringHalf; + shader.uniforms.uRingDash = ringDash; shader.vertexShader = shader.vertexShader .replace( '#include ', - '#include \nattribute float instanceOpacity;\nvarying float vInstanceOpacity;\nuniform vec4 uShift;\n#ifdef LC_RING\nattribute float ringSide;\nuniform float uRingHalf;\n#endif' + '#include \nattribute float instanceOpacity;\nvarying float vInstanceOpacity;\nuniform vec4 uShift;\n#ifdef LC_RING\nattribute float ringSide;\nuniform float uRingHalf;\n#endif\n#ifdef LC_RING_DASH\nvarying vec2 vRingPoint;\nvarying float vRingRadius;\n#endif' ) .replace( '#include ', @@ -136,6 +161,10 @@ function createMaterial(lit: boolean, ring = false) { vInstanceOpacity = instanceOpacity; #if defined( LC_RING ) && defined( USE_INSTANCING ) transformed.xz *= 1.0 + ringSide * uRingHalf / max( length( instanceMatrix[0].xyz ), 1e-6 ); +#endif +#if defined( LC_RING_DASH ) && defined( USE_INSTANCING ) + vRingPoint = position.xz; + vRingRadius = length( instanceMatrix[0].xyz ); #endif` ) // Each instance's center moved by `shift` (chart `x` is the scene's `x`, chart `y` its `z`) @@ -151,7 +180,20 @@ mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;` ); shader.fragmentShader = shader.fragmentShader - .replace('#include ', '#include \nvarying float vInstanceOpacity;') + .replace( + '#include ', + '#include \nvarying float vInstanceOpacity;\n#ifdef LC_RING_DASH\nuniform vec2 uRingDash;\nvarying vec2 vRingPoint;\nvarying float vRingRadius;\n#endif' + ) + // A dashed ring's gaps: how far round the ring each pixel is, from its rightmost point + // (chart `y`, down the plot, is the scene's `z`), against the dash and gap repeating + .replace( + 'void main() {', + `void main() { +#ifdef LC_RING_DASH + float lcAround = mod( atan( vRingPoint.y, vRingPoint.x ), 6.28318530718 ) * vRingRadius; + if ( mod( lcAround, uRingDash.x + uRingDash.y ) > uRingDash.x ) discard; +#endif` + ) .replace( '#include ', '#include \ngl_FragColor.a *= vInstanceOpacity;' @@ -159,7 +201,7 @@ gl_Position = projectionMatrix * mvPosition;` }; // Keep the patched program apart from plain Lambert materials' in three's cache material.customProgramCacheKey = () => - `lc-instance-opacity-${lit ? 'lit' : 'unlit'}${ring ? '-ring' : ''}`; + `lc-instance-opacity-${lit ? 'lit' : 'unlit'}${ring ? '-ring' : ''}${material.defines?.LC_RING_DASH != null ? '-dash' : ''}`; return material; } @@ -174,11 +216,13 @@ export function createInstances({ opacity, emphasize, tooltip, + events, glow, additive, shift, behind, ring, + dash, }: InstancesOptions) { const ctx = getChartContext(); const scene = getSceneContext(); @@ -259,10 +303,13 @@ export function createInstances({ $effect(() => { const instanced = mesh; - if (!instanced || !tooltip?.()) return; + const shows = !!tooltip?.(); + if (!instanced || (!shows && !hasEvents(events?.()))) return; return scene.addPickable({ object: instanced, datum: (hit) => (hit.instanceId != null ? list[hit.instanceId]?.d : undefined), + tooltip: () => shows, + events, }); }); @@ -329,6 +376,16 @@ export function createInstances({ const o = opacity() * inGroup(); material.opacity = o; if (ring) material.userData.ringHalf.value = ring(); + if (dash) { + const pattern = ring ? dash() : null; + // Compiled in (or out) only as it starts or stops being dashed + if ((material.defines?.LC_RING_DASH != null) !== !!pattern) { + if (pattern) material.defines = { ...material.defines, LC_RING_DASH: '' }; + else delete material.defines!.LC_RING_DASH; + material.needsUpdate = true; + } + if (pattern) material.userData.ringDash.value.set(pattern[0], pattern[1]); + } // A depth offset needs no new program, so it can follow along const back = behind?.() ?? false; material.polygonOffset = back; diff --git a/packages/webgl/src/lib/utils/labels.ts b/packages/webgl/src/lib/utils/labels.ts index 07d3de212d..37ffccbadd 100644 --- a/packages/webgl/src/lib/utils/labels.ts +++ b/packages/webgl/src/lib/utils/labels.ts @@ -101,15 +101,31 @@ export function labelPlane( paint.lineJoin = 'round'; lines.forEach((line, i) => paint.strokeText(line, x, first + step * i)); } - paint.fillStyle = css(color?.color); - paint.globalAlpha = color?.opacity ?? 1; - lines.forEach((line, i) => paint.fillText(line, x, first + step * i)); + // Translucent letters are painted opaque on a canvas of their own, then laid over at their + // alpha, so where their hairline (below) covers their fill they don't come out more opaque + const alpha = color?.opacity ?? 1; + const letters = alpha < 1 ? document.createElement('canvas') : label; + if (letters !== label) { + letters.width = width; + letters.height = height; + } + const ink = letters === label ? paint : letters.getContext('2d')!; + ink.font = font; + ink.textAlign = paint.textAlign; + ink.textBaseline = paint.textBaseline; + ink.fillStyle = css(color?.color); + ink.globalAlpha = 1; + lines.forEach((line, i) => ink.fillText(line, x, first + step * i)); // Shrunk to size by the GPU and blended in linear light, glyphs come out thinner than the // browser draws them: a hairline of their own color brings back their weight - paint.strokeStyle = paint.fillStyle; - paint.lineWidth = WEIGHT_STROKE * RESOLUTION; - paint.lineJoin = 'round'; - lines.forEach((line, i) => paint.strokeText(line, x, first + step * i)); + ink.strokeStyle = ink.fillStyle; + ink.lineWidth = WEIGHT_STROKE * RESOLUTION; + ink.lineJoin = 'round'; + lines.forEach((line, i) => ink.strokeText(line, x, first + step * i)); + if (letters !== label) { + paint.globalAlpha = alpha; + paint.drawImage(letters, 0, 0); + } const texture = new CanvasTexture(label); texture.colorSpace = LinearSRGBColorSpace; diff --git a/packages/webgl/src/lib/utils/merged.svelte.ts b/packages/webgl/src/lib/utils/merged.svelte.ts index 1209009b7f..96b87ea638 100644 --- a/packages/webgl/src/lib/utils/merged.svelte.ts +++ b/packages/webgl/src/lib/utils/merged.svelte.ts @@ -13,7 +13,12 @@ import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js import { LineMaterial } from 'three/addons/lines/LineMaterial.js'; import { getChartContext } from 'layerchart'; -import { getSceneContext, groupOpacity } from '../contexts/scene.svelte.js'; +import { + getSceneContext, + groupOpacity, + hasEvents, + type MarkEvents, +} from '../contexts/scene.svelte.js'; /** One shape of a mark drawn as a single merged mesh: its geometry, outlines, and colors */ export type MergedItem = { @@ -32,12 +37,19 @@ type MergedOptions = { items: () => MergedItem[]; /** Whether hovering shows the tooltip (only marks that ask are picked) */ tooltip?: () => boolean; + /** Pointer handlers, called with the row under the pointer (as the core marks' `onclick`, ...) */ + events?: () => MarkEvents | undefined; opacity: () => number; /** Multiplies the outlines' alpha (the fills' is `opacity`) */ lineOpacity?: () => number; strokeWidth: () => number; /** Lose to other shapes in the same place (ex. an arc's track, beneath the arc) */ behind?: boolean; + /** + * Dash the outlines, as the core marks' `dashArray` (a dash length, `[dash, gap]`, or an SVG + * `stroke-dasharray` string), in pixels + */ + dash?: () => number | number[] | string | undefined; /** * Fill each pixel once, however many of its shapes overlap there, as SVG fills one path (ex. a * trail's overlapping pieces, translucent): for a mark whose shapes are one path's @@ -63,7 +75,9 @@ export function createMerged({ lineOpacity, strokeWidth, tooltip, + events, behind, + dash, once, }: MergedOptions) { const ctx = getChartContext(); @@ -169,6 +183,8 @@ export function createMerged({ lines.geometry.dispose(); lines.geometry = lineGeometry; lines.visible = linePositions.length > 0; + // Along each outline, for its dashes + if (lineMaterial.dashed && linePositions.length) lines.computeLineDistances(); lineMaterial.opacity = (strokeAlpha ?? 1) * (lineOpacity?.() ?? 1) * inGroup(); // Rebuilt without emphasis, so put back whatever's hovered @@ -194,6 +210,24 @@ export function createMerged({ scene.invalidate(); }); + // Dashes, as an SVG `stroke-dasharray` (the first dash and gap), the same on screen at any depth + if (dash) { + $effect(() => { + const pattern = dashPattern(dash()); + const dashed = pattern != null; + if (lineMaterial.dashed !== dashed) { + lineMaterial.dashed = dashed; + lineMaterial.needsUpdate = true; + if (dashed && lines.visible) lines.computeLineDistances(); + } + if (pattern) { + lineMaterial.dashSize = pattern[0] * scene.unit; + lineMaterial.gapSize = pattern[1] * scene.unit; + } + scene.invalidate(); + }); + } + $effect(() => { const hovered = ctx.tooltip.data; untrack(() => { @@ -210,8 +244,11 @@ export function createMerged({ }); $effect(() => { - if (!tooltip?.()) return; + const shows = !!tooltip?.(); + if (!shows && !hasEvents(events?.())) return; return scene.addPickable({ + tooltip: () => shows, + events, object: mesh, datum: (hit) => { const vertex = hit.face?.a; @@ -242,3 +279,21 @@ export function createMerged({ }; }); } + +/** + * A `dashArray` (as the core marks take it: a length, a `[dash, gap, ...]` array, or an SVG + * `stroke-dasharray` string) as a dash and gap, or `null` for a solid line + */ +export function dashPattern( + dashArray: number | number[] | string | undefined | null +): [number, number] | null { + if (dashArray == null || dashArray === '' || dashArray === 'none') return null; + const values = + typeof dashArray === 'number' + ? [dashArray] + : typeof dashArray === 'string' + ? dashArray.split(/[\s,]+/).map(Number) + : dashArray; + const [first, second = first] = values.filter((v) => Number.isFinite(v) && v >= 0); + return first > 0 ? [first, second] : null; +} diff --git a/packages/webgl/src/lib/utils/outlines.ts b/packages/webgl/src/lib/utils/outlines.ts index 72267372c7..be4549be23 100644 --- a/packages/webgl/src/lib/utils/outlines.ts +++ b/packages/webgl/src/lib/utils/outlines.ts @@ -48,12 +48,15 @@ export function createOutlines({ strokeWidth, opacity, footprint, + dash, }: { instances: () => Instance[]; stroke: (d: any) => string; strokeWidth: () => number; opacity: () => number; footprint?: () => [number, number][]; + /** Dash the outlines (see `createMerged`'s `dash`) */ + dash?: () => number | number[] | string | undefined; }) { const ctx = getChartContext(); createMerged({ @@ -73,5 +76,6 @@ export function createOutlines({ // Outlines are lines: the merged mark's `opacity` is its fills' lineOpacity: opacity, strokeWidth, + dash, }); } diff --git a/packages/webgl/vite.config.js b/packages/webgl/vite.config.js index 6392191bd2..d06d317ade 100644 --- a/packages/webgl/vite.config.js +++ b/packages/webgl/vite.config.js @@ -16,6 +16,9 @@ export default defineConfig({ }), ], test: { + // One test file at a time: run side by side, the browser starves some of animation frames, and + // the tests that watch a mark ease (from mount, or to new rows) miss it on its way + fileParallelism: false, projects: [ { extends: true, From 8bfc601d2becce6e336228567ad273546d39a14e Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Thu, 26 Nov 2026 11:48:33 -0500 Subject: [PATCH 10/16] docs: Shared and package-only API tables with inherited props, and more WebGL examples Co-Authored-By: Claude Opus 5.5 --- docs/package.json | 2 +- docs/src/content/guides/layers.md | 4 ++-- docs/src/content/guides/layers/features.ts | 7 ++++--- docs/vite-plugin-webgl-examples.ts | 3 ++- docs/webgl-examples.ts | 21 +++++++++++++++++++++ pnpm-lock.yaml | 10 +++++----- 6 files changed, 35 insertions(+), 12 deletions(-) diff --git a/docs/package.json b/docs/package.json index 9fa0736c19..c476add87d 100644 --- a/docs/package.json +++ b/docs/package.json @@ -38,7 +38,7 @@ "@iconify-json/vscode-icons": "^1.2.53", "@jsquash/webp": "^1.5.0", "@layerchart/webgl": "workspace:*", - "@layerstack/docs": "1.0.0-next.9", + "@layerstack/docs": "1.0.0-next.10", "@layerstack/svelte-actions": "1.0.1-next.20", "@layerstack/svelte-state": "0.1.0-next.25", "@layerstack/svelte-table": "1.0.1-next.20", diff --git a/docs/src/content/guides/layers.md b/docs/src/content/guides/layers.md index 1e93de7231..35870be753 100644 --- a/docs/src/content/guides/layers.md +++ b/docs/src/content/guides/layers.md @@ -59,9 +59,9 @@ WebGL layers are drawn by the separate `@layerchart/webgl` package, whose `WebGL Its marks share their core namesakes' props, and its `Layer` adds `type="webgl"`, so a chart imported from `@layerchart/webgl` moves between all four layers (see [Switching layers](/docs/guides/webgl#switching-layers)). Compound marks (`Pie`, `Labels`, `Calendar`, `BoxPlot`, ...) are LayerChart's own, drawn with its WebGL marks. Examples on these pages draw with WebGL from the layer toggle where they look the same; the rest draw with Canvas, as they use something WebGL doesn't draw yet: - `Ellipse`, `Image`, and Sankey and Dagre links -- rounded corners on a 3D chart (flat `Bars` and `Rect` round theirs), dashed strokes, and path markers +- rounded corners on a 3D chart (flat `Bars` and `Rect` round theirs) - radial charts' `Spline`, `Grid`, and `Axis` -- some `Axis` tick-label options (multiline, occlusion) and labels past the plot's edge +- labels past the plot's edge > Most browsers limit the number of concurrent WebGL contexts by page/domain (references: [Chromium](https://issues.chromium.org/issues/40543269), [Rive](https://rive.app/docs/runtimes/web/canvas-vs-webgl)) and is why some libraries such as [μPlot](https://github.com/leeoniya/uPlot) do not leverage it. A `WebGL` layer gives up its context when it's scrolled well off screen, so a page can have more of them than the limit, just not all on screen at once. diff --git a/docs/src/content/guides/layers/features.ts b/docs/src/content/guides/layers/features.ts index 791f7b1152..ed13f2c2f5 100644 --- a/docs/src/content/guides/layers/features.ts +++ b/docs/src/content/guides/layers/features.ts @@ -73,7 +73,7 @@ export const graphics = [ }, webgl: { support: true, - note: 'Path data lies on the floor, filled and outlined (ex. Trail, Violin, Density, Ribbon); no markers' + note: 'Path data lies on the floor, filled and outlined (ex. Trail, Violin, Density, Ribbon), with markers' } }, { @@ -154,7 +154,8 @@ export const styles = [ support: false }, webgl: { - support: false + support: true, + note: "LayerChart's marker shapes (arrow, triangle, circle, dot, square, ...), lying on the floor; not custom snippets" } }, { @@ -217,7 +218,7 @@ export const styles = [ }, webgl: { support: true, - note: 'Outlines of bars, rects, circles, and shapes, and lines a CSS pixel wide; no dashes (stroke-dasharray)' + note: 'Outlines of bars, rects, circles, and shapes, and lines a CSS pixel wide, dashed with dashArray' } }, { diff --git a/docs/vite-plugin-webgl-examples.ts b/docs/vite-plugin-webgl-examples.ts index aa85d7de31..04b456db3e 100644 --- a/docs/vite-plugin-webgl-examples.ts +++ b/docs/vite-plugin-webgl-examples.ts @@ -116,7 +116,8 @@ export function isNativeWebGL(source: string) { return /from '@layerchart\/webgl(\/webgl)?'/.test(source); } -const IMPORT = /^([ \t]*)import \{([^}]*)\} from '(layerchart|layerchart\/geo|layerchart\/graph)';?$/gm; +const IMPORT = + /^([ \t]*)import \{([^}]*)\} from '(layerchart|layerchart\/geo|layerchart\/graph)';?$/gm; /** * An example's source with its components imported from `@layerchart/webgl`, or `null` if it diff --git a/docs/webgl-examples.ts b/docs/webgl-examples.ts index b903c7e445..bedc6a0088 100644 --- a/docs/webgl-examples.ts +++ b/docs/webgl-examples.ts @@ -21,6 +21,7 @@ export const checkedWebGLExamples = [ 'Area/multiple-series-with-labels', 'Area/oscilloscope-ridgeline-isometric', 'Area/playground', + 'Area/ridgeline-kde', 'Area/stack', 'Area/tween-on-mount', 'Area/with-labels', @@ -63,6 +64,7 @@ export const checkedWebGLExamples = [ 'Bars/horizontal-inside-labels', 'Bars/horizontal-limit-ticks-count', 'Bars/horizontal-limit-ticks-second-scale', + 'Bars/horizontal-multiple-diverging', 'Bars/horizontal-multiple-overlapping', 'Bars/horizontal-outside-labels-default', 'Bars/horizontal-rounded-right-only', @@ -92,6 +94,7 @@ export const checkedWebGLExamples = [ 'Bars/vertical-inside-labels', 'Bars/vertical-limit-ticks-count', 'Bars/vertical-limit-ticks-second-scale', + 'Bars/vertical-multiple-diverging', 'Bars/vertical-multiple-diverging-rounded-specific', 'Bars/vertical-multiple-overlapping', 'Bars/vertical-outside-labels-default', @@ -122,6 +125,7 @@ export const checkedWebGLExamples = [ 'BoxPlot/basic', 'BoxPlot/horizontal', 'BoxPlot/pre-computed', + 'BoxPlot/styled', 'BoxPlot/with-tooltip', 'BoxPlot/with-violin', 'BrushContext/basic', @@ -130,6 +134,7 @@ export const checkedWebGLExamples = [ 'BrushContext/handle-labels', 'BrushContext/min-max-extent', 'BrushContext/programmatic-control', + 'BrushContext/selection', 'BrushContext/simple-styling', 'BrushContext/snap-to-month', 'BrushContext/striped-background', @@ -138,6 +143,7 @@ export const checkedWebGLExamples = [ 'Calendar/fixed-cell-size', 'Calendar/isometric', 'Calendar/last-month', + 'Calendar/multiple-years', 'Calendar/responsive-cell-size-default', 'Calendar/rounded-cells', 'Cell/basic', @@ -153,6 +159,8 @@ export const checkedWebGLExamples = [ 'Chart/isometric-playground', 'Chart/isometric-stacked-columns', 'Chart/isometric-treemap', + 'Chart/mixed-marks-with-stack', + 'Chart/mixed-marks-with-stack-long-data', 'Circle/color-via-ordinal-scale', 'Circle/color-via-threshold-scale', 'Circle/data-mode', @@ -222,10 +230,15 @@ export const checkedWebGLExamples = [ 'Line/styling-using-attributes', 'Line/styling-using-classes', 'Line/styling-using-css-variables', + 'Link/bended-arrows', 'Link/curves', 'Link/playground', 'Link/types', + 'Marker/line', 'Marker/orientation', + 'Marker/spline', + 'Marker/spline-w-thicker-stroke', + 'Marker/styling', 'Month/90-days', 'Month/basic', 'Month/multiple-years', @@ -316,7 +329,12 @@ export const checkedWebGLExamples = [ 'Rule/data-y-range', 'Rule/lollipop', 'Spline/basic', + 'Spline/basic-start-and-end-snippets', 'Spline/draw', + 'Spline/label-using-start-end-snippets', + 'Spline/markers-arrows', + 'Spline/multiple-series', + 'Spline/multiple-series-highlight-on-hover', 'Spline/multiple-series-tweened', 'Spline/multiple-series-using-overrides', 'Spline/multiple-series-with-labels', @@ -342,9 +360,12 @@ export const checkedWebGLExamples = [ 'Tooltip/disable-motion', 'Tooltip/externally-access-tooltip-data', 'Tooltip/invert-variant', + 'Tooltip/multiple-overlapping-bars', 'Tooltip/multiple-tooltips-with-fixed-single-axis', + 'Tooltip/multiple-tooltips-with-fixed-single-axis-scaleband', 'Tooltip/portal-overflow', 'Tooltip/scatter-plot', + 'Tooltip/simple-bars', 'Tooltip/single-date-time', 'Tooltip/stacked-area', 'Trail/basic', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fff9955e28..45843aa77b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -135,8 +135,8 @@ importers: specifier: workspace:* version: link:../packages/webgl '@layerstack/docs': - specifier: 1.0.0-next.9 - version: 1.0.0-next.9(@sveltejs/kit@2.70.4(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.1.2(svelte@5.57.1(@typescript-eslint/types@8.60.1))(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(svelte@5.57.1(@typescript-eslint/types@8.60.1))(typescript@6.0.3)(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.15)(tsx@4.22.4)(yaml@2.9.0))(postcss@8.5.15)(svelte@5.57.1(@typescript-eslint/types@8.60.1)) + specifier: 1.0.0-next.10 + version: 1.0.0-next.10(@sveltejs/kit@2.70.4(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.1.2(svelte@5.57.1(@typescript-eslint/types@8.60.1))(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(svelte@5.57.1(@typescript-eslint/types@8.60.1))(typescript@6.0.3)(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.15)(tsx@4.22.4)(yaml@2.9.0))(postcss@8.5.15)(svelte@5.57.1(@typescript-eslint/types@8.60.1)) '@layerstack/svelte-actions': specifier: 1.0.1-next.20 version: 1.0.1-next.20(svelte@5.57.1(@typescript-eslint/types@8.60.1)) @@ -2028,8 +2028,8 @@ packages: '@jsquash/webp@1.5.0': resolution: {integrity: sha512-KggLoj2MnRSfIqTeKe1EmbljTX2vuV7mh79k89PCL1pyqiDULcPM1L47twxXt0hkb68F70bXiL31MxsuoZtKFw==} - '@layerstack/docs@1.0.0-next.9': - resolution: {integrity: sha512-5VI//1CiMUBlfDJ13q36bi39J2dlKdZ0808cQDPVJUYhmp0pqMgN+yG7HWCp/Kccnlfru2vM360sxJ1GDfCEKA==} + '@layerstack/docs@1.0.0-next.10': + resolution: {integrity: sha512-aTlYwGvzedePwetc1oP8OJUSu+mGSzaYS1W1NWWDfssUz+GAnTrDNeVPf2Oq6epRx3HD3LtMFWzBvSgkQ2Bx4g==} hasBin: true peerDependencies: '@sveltejs/kit': ^2.0.0 @@ -7144,7 +7144,7 @@ snapshots: dependencies: wasm-feature-detect: 1.10.1 - '@layerstack/docs@1.0.0-next.9(@sveltejs/kit@2.70.4(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.1.2(svelte@5.57.1(@typescript-eslint/types@8.60.1))(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(svelte@5.57.1(@typescript-eslint/types@8.60.1))(typescript@6.0.3)(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.15)(tsx@4.22.4)(yaml@2.9.0))(postcss@8.5.15)(svelte@5.57.1(@typescript-eslint/types@8.60.1))': + '@layerstack/docs@1.0.0-next.10(@sveltejs/kit@2.70.4(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.1.2(svelte@5.57.1(@typescript-eslint/types@8.60.1))(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(svelte@5.57.1(@typescript-eslint/types@8.60.1))(typescript@6.0.3)(vite@8.0.16(@types/node@25.9.1)(esbuild@0.28.0)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))(postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.15)(tsx@4.22.4)(yaml@2.9.0))(postcss@8.5.15)(svelte@5.57.1(@typescript-eslint/types@8.60.1))': dependencies: '@content-collections/core': 0.14.3(typescript@5.9.3) '@content-collections/markdown': 0.1.4(@content-collections/core@0.14.3(typescript@6.0.3)) From ddabb2b1e0de3b73ba025c677502507dd8e5a51b Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Thu, 26 Nov 2026 12:18:07 -0500 Subject: [PATCH 11/16] docs: Filter examples by layer, type ahead in the category picker, and an icon sort toggle Co-Authored-By: Claude Opus 5.5 --- docs/src/routes/docs/examples/+page.server.ts | 24 +++++- docs/src/routes/docs/examples/+page.svelte | 84 +++++++++++++++++-- 2 files changed, 100 insertions(+), 8 deletions(-) diff --git a/docs/src/routes/docs/examples/+page.server.ts b/docs/src/routes/docs/examples/+page.server.ts index 93a69eeedd..654d8edbf3 100644 --- a/docs/src/routes/docs/examples/+page.server.ts +++ b/docs/src/routes/docs/examples/+page.server.ts @@ -1,5 +1,8 @@ import { allComponents } from 'content-collections'; import type { ComponentCatalog } from '@layerstack/docs/catalog'; +import { nativeWebGLExamples, webglExamples } from 'virtual:webgl-examples'; + +import { componentLayers, intersectExampleLayers } from '$lib/utils/layers.js'; import { metadata } from './metadata'; @@ -15,6 +18,8 @@ interface ExampleInfo { path: string; /** The commit that first added the example's file (absent until it's committed) */ createdAt?: string; + /** The layers it draws in (ex. `['svg', 'canvas', 'webgl']`), as its page's layer toggle offers */ + layers: string[]; }>; } @@ -59,7 +64,8 @@ export async function load() { name: example.name, title: example.title, path: `/docs/components/${slug}/${example.name}`, - createdAt: example.createdAt + createdAt: example.createdAt, + layers: exampleLayers(slug, catalog.component, example) })) }; }) @@ -70,3 +76,19 @@ export async function load() { metadata }; } + +/** + * The layers an example draws in, as its page's layer toggle offers them: those every component + * it uses can draw in, and `webgl` when it has a WebGL version. One written with + * `@layerchart/webgl` draws in a `WebGL` layer only. + */ +function exampleLayers( + slug: string, + component: string, + example: ComponentCatalog['examples'][number] +): string[] { + const key = `${slug}/${example.name}`; + if (nativeWebGLExamples.has(key)) return ['webgl']; + const layers = intersectExampleLayers(example.components ?? [], componentLayers[component] ?? []); + return key in webglExamples ? [...layers, 'webgl'] : layers; +} diff --git a/docs/src/routes/docs/examples/+page.svelte b/docs/src/routes/docs/examples/+page.svelte index f7a34acd8b..9208e69127 100644 --- a/docs/src/routes/docs/examples/+page.svelte +++ b/docs/src/routes/docs/examples/+page.svelte @@ -1,5 +1,13 @@ diff --git a/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte b/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte index d1d901f1e3..b8cff14554 100644 --- a/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte +++ b/packages/webgl/src/lib/components/GeoPath/GeoPath.webgl.svelte @@ -120,7 +120,7 @@ const stroke = $derived( strokeProp !== undefined ? strokeProp - : look?.stroke === 'none' + : look?.strokeNone || look?.stroke === 'none' ? null : (look?.stroke ?? 'var(--color-surface-content, currentColor)') ); diff --git a/packages/webgl/src/lib/components/GeoPoint/GeoPoint.webgl.svelte b/packages/webgl/src/lib/components/GeoPoint/GeoPoint.webgl.svelte index cf99337a13..1841ee21ab 100644 --- a/packages/webgl/src/lib/components/GeoPoint/GeoPoint.webgl.svelte +++ b/packages/webgl/src/lib/components/GeoPoint/GeoPoint.webgl.svelte @@ -4,11 +4,27 @@ - +{#if children} + + + {@render children({ x, y })} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts b/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts index 0cf9b4015f..6d622adc97 100644 --- a/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Grid/Grid.shared.svelte.ts @@ -19,23 +19,23 @@ export type GridLineProps = { */ export type GridProps = { /** - * Draw a x-axis lines, across the floor and up the wall behind. Pass props (class, stroke, - * strokeWidth, opacity, dashArray) to style them. + * Draw a x-axis lines, across the floor and up the wall behind (spokes at its ticks in a + * `radial` chart). Pass props (class, stroke, strokeWidth, opacity, dashArray) to style them. * - * @default true + * @default false, as the core `Grid`, unless none of `x`, `y`, and `z` is turned on (then true) */ x?: boolean | GridLineProps; /** - * Draw a y-axis lines, across the floor and up the wall behind. Pass props (class, stroke, - * strokeWidth, opacity, dashArray) to style them. + * Draw a y-axis lines, across the floor and up the wall behind (circles at its ticks in a + * `radial` chart). Pass props (class, stroke, strokeWidth, opacity, dashArray) to style them. * - * @default true + * @default false, as the core `Grid`, unless none of `x`, `y`, and `z` is turned on (then true) */ y?: boolean | GridLineProps; /** * Draw lines at the `z` scale's ticks, around both walls, and pass props to style them. * - * @default true + * @default false, unless none of `x`, `y`, and `z` is turned on (then true) */ z?: boolean | GridLineProps; /** Control the number of x-axis ticks: a count, values, or an interval, as for `Axis` */ @@ -51,6 +51,12 @@ export type GridProps = { * @default 'center' */ bandAlign?: 'center' | 'between'; + /** + * Render `y` lines with circles or linear splines + * + * @default 'circle' + */ + radialY?: 'circle' | 'linear'; /** * Stroke color for grid lines. * diff --git a/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte b/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte index 089eff423b..e32e9e1100 100644 --- a/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte +++ b/packages/webgl/src/lib/components/Grid/Grid.webgl.svelte @@ -19,15 +19,17 @@ import { createSegments } from '../../utils/lines.js'; import { dashPattern } from '../../utils/merged.svelte.js'; import { createRowMotion } from '../../utils/rowMotion.svelte.js'; + import { circleSegments, pointRadial, polygonSegments } from '../../utils/radial.js'; let { - x = true, - y = true, - z = true, + x: xProp, + y: yProp, + z: zProp, xTicks, yTicks, zTicks, bandAlign = 'center', + radialY = 'circle', // As core's `Grid` draws its lines stroke = 'color-mix(in oklab, var(--color-surface-content, currentColor) 10%, transparent)', classes = {}, @@ -44,6 +46,15 @@ const inGroup = groupOpacity(); const walls = $derived(wallsProp ?? !!ctx.view); + /** + * Which lines it draws: those turned on, as the core `Grid` (ex. `` only `x`'s), else + * all those not turned off (a bare ``, as a scene's grid is) + */ + const all = $derived(!xProp && !yProp && !zProp); + const x = $derived(xProp ?? all); + const y = $derived(yProp ?? all); + const z = $derived(zProp ?? all); + /** * Where a band scale's line goes from its band's start, as the core `Grid` aligns them: through * the band's middle, or half the padding before it (`between`) @@ -59,7 +70,10 @@ * Between bands, there's one past the last band too, as the core `Grid` draws. */ function ticks(scale: any, config: TicksConfig | undefined, length: number, spacing: number) { - const values = autoTickVals(scale, config, tickCount(length, spacing)); + // A count asked for, else one per `spacing` (as `Axis` spaces them) + const count = + typeof config === 'number' ? config : spacing ? tickCount(length, spacing) : undefined; + const values = autoTickVals(scale, config, count); const offset = bandOffset(scale); const lines = values.map((v) => ({ key: String(v), p: Number(scale(v)) + offset })); if (isScaleBand(scale) && bandAlign === 'between' && values.length) { @@ -96,7 +110,45 @@ for (const set of Object.values(sets)) set.object.renderOrder = -1; layer.add(planes, ...Object.values(sets).map((set) => set.object)); + // Around the center (in a `Layer center`), as the core `Grid` draws a `radial` chart's: spokes at + // the `x` ticks (angles), and a circle (or a polygon through the spokes) at each `y` tick + $effect(() => { + if (!ctx.radial) return; + const [r0, r1] = ctx.yRange as [number, number]; + // At the ticks the core `Grid` draws, rather than spaced as an axis' (it has none here) + const xLines = x ? ticks(ctx.xScale, xTicks, 0, 0) : []; + const yLines = y + ? ticks(ctx.yScale, yTicks ?? (isScaleBand(ctx.yScale) ? undefined : 4), 0, 0) + : []; + const active = new Set(); + const xs: number[] = []; + for (const a of placed('x', xLines, active)) { + const [x1, y1] = pointRadial(a, r0); + const [x2, y2] = pointRadial(a, r1); + xs.push(x1, 0, y1, x2, 0, y2); + } + const ys: number[] = []; + // Through every `x` tick, drawn or not, as the core `Grid`'s + const angles = radialY === 'linear' ? ticks(ctx.xScale, xTicks, 0, 0).map((l) => l.p) : []; + for (const r of placed('y', yLines, active)) { + ys.push(...(radialY === 'linear' ? polygonSegments(angles, r) : circleSegments(r))); + } + if (eased) untrack(() => eased.cleanup(active)); + for (const [set, segments] of [ + [sets.x, xs], + [sets.y, ys], + [sets.z, []], + ] as const) { + set.set(segments); + if (set.object.material.dashed && segments.length) set.object.computeLineDistances(); + } + planes.geometry.dispose(); + planes.geometry = new BufferGeometry(); + scene.invalidate(); + }); + $effect(() => { + if (ctx.radial) return; const w = ctx.width; const h = ctx.height; const d = ctx.zDepth; diff --git a/packages/webgl/src/lib/components/Highlight/Highlight.webgl.svelte b/packages/webgl/src/lib/components/Highlight/Highlight.webgl.svelte index 1d985e1720..c7590e1cd7 100644 --- a/packages/webgl/src/lib/components/Highlight/Highlight.webgl.svelte +++ b/packages/webgl/src/lib/components/Highlight/Highlight.webgl.svelte @@ -3,7 +3,7 @@ diff --git a/packages/webgl/src/lib/components/Hull/Hull.webgl.svelte b/packages/webgl/src/lib/components/Hull/Hull.webgl.svelte index 8e08fac49c..da3785d678 100644 --- a/packages/webgl/src/lib/components/Hull/Hull.webgl.svelte +++ b/packages/webgl/src/lib/components/Hull/Hull.webgl.svelte @@ -5,10 +5,11 @@ - + diff --git a/packages/webgl/src/lib/components/Points/Points.base.svelte b/packages/webgl/src/lib/components/Points/Points.base.svelte index 350cb1be68..bdeb1ca59a 100644 --- a/packages/webgl/src/lib/components/Points/Points.base.svelte +++ b/packages/webgl/src/lib/components/Points/Points.base.svelte @@ -171,52 +171,64 @@ const from = initial; const active = new Set(); rows.forEach((d, i) => { - const point = pointOf(d); - if (!point) return; - const k = key(d, i); - active.add(k); - const values = { cx: point.x, cy: point.y, r: point.radius }; - untrack(() => motionMap.update(k, values, from)); + const points = pointOf(d); + points.forEach((point, j) => { + const k = keyOf(key(d, i), j, points.length); + active.add(k); + const values = { cx: point.x, cy: point.y, r: point.radius }; + untrack(() => motionMap.update(k, values, from)); + }); }); untrack(() => motionMap.cleanup(active)); }); } + /** A row's point's motion key: the row's own, or with one per value, the row's and which */ + const keyOf = (k: unknown, j: number, count: number) => (count > 1 ? `${String(k)}:${j}` : k); + /** - * Where each row's sphere is now (`null` off the chart): where it's asked to be, or with - * `motion`, on its way there (a new one where it eases in from, until it starts) + * Where each row's spheres are now (none off the chart): where they're asked to be, or with + * `motion`, on their way there (a new one where it eases in from, until it starts) */ function pointer(): (d: any, i: number) => ReturnType> { const pointOf = placed(); if (!motionMap) return pointOf; return (d, i) => { - const point = pointOf(d); - if (!point) return null; - const now = motionMap.get(key(d, i)) ?? initial; - return { - ...point, - x: now.cx ?? point.x, - y: now.cy ?? point.y, - radius: now.r ?? point.radius, - }; + const points = pointOf(d); + return points.map((point, j) => { + const now = motionMap.get(keyOf(key(d, i), j, points.length)) ?? initial; + return { + ...point, + x: now.cx ?? point.x, + y: now.cy ?? point.y, + radius: now.r ?? point.radius, + }; + }); }; } /** - * Where each row's sphere is asked to be in the scene and how large (`null` off the chart), - * with what it reads of the chart read once: there can be a great many rows + * Where each row's spheres are asked to be in the scene and how large (none off the chart): one, + * or as the core `Points`, one per value of an `x` or `y` of several (ex. a duration's start and + * end). With what it reads of the chart read once: there can be a great many rows. */ function placed() { const [xOf, yOf] = [xAccessor, yAccessor]; const at = placer(ctx, sphere, placedScales ?? undefined, { x: offsetX, y: offsetY }); const raised = ctx.config.z != null || z != null; const sized = r != null ? (d: any) => valueOf(r, d) : ctx.config.r ? ctx.rGet : () => 5; - return (d: any) => { + type Point = { d: any; x: number; y: number; z: number; radius: number }; + const one = (d: any, xValue: any, yValue: any): Point[] => { + if (!defined(xValue) || !defined(yValue)) return []; + const [px, up, py] = at(xValue, yValue, raised ? ctx.heightOf(d, z)[1] : 0); + return [{ d, x: px, y: py, z: up, radius: sized(d) as number }]; + }; + return (d: any): Point[] => { const xValue = xOf(d); const yValue = yOf(d); - if (!defined(xValue) || !defined(yValue)) return null; - const [px, up, py] = at(xValue, yValue, raised ? ctx.heightOf(d, z)[1] : 0); - return { d, x: px, y: py, z: up, radius: sized(d) as number }; + if (Array.isArray(xValue)) return xValue.filter(Boolean).flatMap((v) => one(d, v, yValue)); + if (Array.isArray(yValue)) return yValue.filter(Boolean).flatMap((v) => one(d, xValue, v)); + return one(d, xValue, yValue); }; } @@ -240,12 +252,10 @@ const colorOf = colorer(ctx, fillValue, 'var(--color-primary, currentColor)', look?.fill); return rows.flatMap((d: any, i: number) => { if (image != null && imageOf(d)) return []; - const point = pointOf(d, i); - if (!point) return []; - // Inside its ring, so the two don't overlap (and darken where they're translucent) - const radius = ringed ? Math.max(0, point.radius - strokeWidth / 2) : point.radius; - return [ - { + return pointOf(d, i).map((point) => { + // Inside its ring, so the two don't overlap (and darken where they're translucent) + const radius = ringed ? Math.max(0, point.radius - strokeWidth / 2) : point.radius; + return { d, x: point.x, y: point.y, @@ -254,8 +264,8 @@ depth: radius, height: radius, color: colorOf(d), - }, - ]; + }; + }); }); }, opacity: () => opacity * fillOpacity * seriesOpacity * (look?.opacity ?? 1), @@ -274,21 +284,17 @@ const colorOf = colorer(ctx, stroke, 'currentColor', look?.stroke); return rows.flatMap((d: any, i: number) => { if (image != null && imageOf(d)) return []; - const point = pointOf(d, i); - if (!point) return []; - return [ - { - d, - x: point.x, - y: point.y, - // Over its point, flat - z: point.z + 0.01, - width: point.radius, - depth: point.radius, - height: point.radius, - color: colorOf(d), - }, - ]; + return pointOf(d, i).map((point) => ({ + d, + x: point.x, + y: point.y, + // Over its point, flat + z: point.z + 0.01, + width: point.radius, + depth: point.radius, + height: point.radius, + color: colorOf(d), + })); }); }, opacity: () => opacity * strokeOpacity * seriesOpacity * (look?.opacity ?? 1), @@ -302,8 +308,7 @@ const pointOf = pointer(); return rows.flatMap((d, i) => { const source = imageOf(d); - const point = source ? pointOf(d, i) : null; - return point ? [{ ...point, source: source! }] : []; + return source ? pointOf(d, i).map((point) => ({ ...point, source })) : []; }); }); const detailed = new SphereGeometry(1, 64, 32); diff --git a/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts b/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts index 2de72706cb..22ee3ad473 100644 --- a/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Spline/Spline.shared.svelte.ts @@ -1,7 +1,7 @@ import type { Snippet } from 'svelte'; import type { draw as drawTransition } from 'svelte/transition'; import type { MotionProp } from 'layerchart/utils/motion.svelte'; -import type { Accessor, ColorProp, DataProp } from 'layerchart'; +import type { Accessor, ColorProp, DataProp, StyleProp } from 'layerchart'; import type { CurveFactory } from 'd3-shape'; import type { MarkerOptions } from '../Line/markers.js'; @@ -50,13 +50,18 @@ export type SplineProps = { * a `Hull`'s). None without one (here or in `class`). */ fill?: string | null; - /** @default 1 */ - opacity?: number; + /** + * Opacity, or a function returning it per row: a line splits into a piece per run of rows + * it gives the same, as the core `Spline`'s. @default 1 + */ + opacity?: StyleProp; /** * CSS classes to style it by, as the core marks take them (ex. `fill-red-500 opacity-50`): - * the fill, stroke, stroke width, and opacity they set, where its props don't say + * the fill, stroke, stroke width, dashes, and opacity they set, where its props don't say. Or a + * function returning them per row, splitting a line into a piece per run of rows it gives the + * same (ex. dashed across missing data), as the core `Spline`'s. */ - class?: string; + class?: StyleProp; /** * Tween each line to where it's asked to be, as the core `Spline` (ex. `'tween'`, or `{ type: * 'tween', duration: 300 }`), a new one up from the baseline. A spring leaves it, as core's. diff --git a/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte b/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte index 666022d1fc..5eb8a8a134 100644 --- a/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte +++ b/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte @@ -1,6 +1,35 @@ + +{#snippet marks()} + {#each axes as axis, i (i)} + + {/each} + {#if grid} + + {/if} +{/snippet} + + +
+ + + {#if center} + {@render marks()} + {:else} + {@render marks()} + {/if} + + + +
diff --git a/packages/webgl/src/lib/components/__fixtures__/Geo2.svelte b/packages/webgl/src/lib/components/__fixtures__/Geo2.svelte new file mode 100644 index 0000000000..797f05b213 --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/Geo2.svelte @@ -0,0 +1,67 @@ + + +
+ + + {#if mark === 'geopoint'} + + {:else if mark === 'geopoint-children'} + + + + + {:else if mark === 'hull'} + + {:else if mark === 'geopath'} + + {:else if mark === 'vector'} + + {:else if mark === 'circle'} + + {:else if mark === 'points'} + + {/if} + + + +
+ + diff --git a/packages/webgl/src/lib/components/__fixtures__/SplineArea.svelte b/packages/webgl/src/lib/components/__fixtures__/SplineArea.svelte new file mode 100644 index 0000000000..03cee76795 --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/SplineArea.svelte @@ -0,0 +1,43 @@ + + +
+ + + {#if area} + + {/if} + {#if spline} + + {/if} + + + +
+ + diff --git a/packages/webgl/src/lib/components/marks.svelte.test.ts b/packages/webgl/src/lib/components/marks.svelte.test.ts index 18de580849..ceab820182 100644 --- a/packages/webgl/src/lib/components/marks.svelte.test.ts +++ b/packages/webgl/src/lib/components/marks.svelte.test.ts @@ -1187,7 +1187,7 @@ describe('placed as LayerChart places its namesakes', () => { const props = (x: number) => ({ mark: 'text' as const, chart: chartProps, - text: { x, y: 20, value: 'moving' }, + text: { x, y: 20, value: 'moving', textAnchor: 'middle' }, onScene: (s: SceneState, c: ChartState) => { latest = s; chart = c; @@ -1213,7 +1213,7 @@ describe('placed as LayerChart places its namesakes', () => { const scene = await renderMarks({ mark: 'text', chart: chartProps, - text: { x: 'x', y: 'y', value: 'name' }, + text: { x: 'x', y: 'y', value: 'name', textAnchor: 'middle' }, }); await expect .poll(() => { @@ -2607,7 +2607,7 @@ describe('strokes, as LayerChart’s marks take them', () => { it('draws `Contour` lines `strokeWidth` pixels wide, raised or flat (with a `stroke`, as core)', async () => { for (const contour of [ - { value: (x: number, y: number) => x + y, strokeWidth: 3, z: 2 }, + { value: (x: number, y: number) => x + y, strokeWidth: 3, z: 2, fill: 'none' }, // Flat, LayerChart's own (filled bands), outlined only with a `stroke` { value: (x: number, y: number) => x + y, strokeWidth: 3, stroke: 'black' }, ]) { @@ -2647,9 +2647,10 @@ describe('strokes, as LayerChart’s marks take them', () => { }); const plain = await label(); const haloed = await label('white'); - // Room for the halo's outer half on every side: 4px wide at 4 canvas pixels a pixel - expect(haloed.width - plain.width).toBe(16); - expect(haloed.height - plain.height).toBe(16); + // Room for the halo's outer half on every side: 4px wide at 4 canvas pixels a pixel, painted + // a little wider (4.5px) as the label is painted a step larger (12px at ~13.5px) and shrunk + expect(haloed.width - plain.width).toBe(18); + expect(haloed.height - plain.height).toBe(18); }); it('draws a halo around `viewport` labels, behind their letters', async () => { diff --git a/packages/webgl/src/lib/components/parity-axis-2.svelte.test.ts b/packages/webgl/src/lib/components/parity-axis-2.svelte.test.ts new file mode 100644 index 0000000000..ca8b44644c --- /dev/null +++ b/packages/webgl/src/lib/components/parity-axis-2.svelte.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { createRawSnippet } from 'svelte'; +import { pointRadial } from 'd3-shape'; +import type { Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import AxisGrid from './__fixtures__/AxisGrid.svelte'; + +type Props = Omit>[1], 'onScene'>; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderAxes(props: Props) { + let scene: SceneState | undefined; + render(AxisGrid, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +/** Everything in the scene that `is` */ +function all(scene: SceneState, is: (o: any) => boolean) { + const found: any[] = []; + scene.root.traverse((o: Object3D) => { + if (is(o)) found.push(o); + }); + return found; +} +const visibleLines = (scene: SceneState) => + all(scene, (o) => o.isLineSegments2 && o.visible && o.geometry.attributes.instanceStart); + +/** A line set's segments, as `[x, y]` pairs across and down the plot */ +const segmentsOf = (lines: any): [number, number][][] => { + const start = lines.geometry.attributes.instanceStart; + const end = lines.geometry.attributes.instanceEnd; + return Array.from({ length: start.count }, (_, i) => [ + [start.getX(i), start.getZ(i)], + [end.getX(i), end.getZ(i)], + ]); +}; + +/** A `tickLabel` (or `label`) snippet noting the props it's given, by `data-*` attributes */ +const noted = createRawSnippet((args: () => { props: any }) => ({ + render: () => { + const { value, x, y, dx, dy, textAnchor, verticalAnchor, rotate } = args().props; + return ``; + }, +})); +/** The props each noted label was given, by its text */ +function notedLabels() { + return Object.fromEntries( + [...document.querySelectorAll('[data-parity-label]')].map((e) => [ + e.dataset.parityLabel, + { + x: Number(e.dataset.x), + y: Number(e.dataset.y), + dx: Number(e.dataset.dx), + dy: Number(e.dataset.dy), + textAnchor: e.dataset.anchor, + verticalAnchor: e.dataset.vanchor, + rotate: Number(e.dataset.rotate), + }, + ]) + ); +} + +const flat = { xDomain: [0, 10], yDomain: [0, 10], padding: 20 }; + +describe('Axis tick labels, as the core `Axis` places them', () => { + it("hangs `bottom`'s below the tick by their cap height, a tick and 2px down", async () => { + await renderAxes({ + chart: flat, + axes: [{ placement: 'bottom', ticks: [0, 5], tickLabel: noted }], + }); + await expect.poll(() => Object.keys(notedLabels())).toEqual(['0', '5']); + const five = notedLabels()['5']; + expect(five.y).toBeCloseTo(chart!.height); + expect(five.verticalAnchor).toBe('start'); + expect(five.dy).toBeCloseTo(6); + }); + + it('takes `dx` / `dy` from `tickLabelProps` in place of its own offset', async () => { + await renderAxes({ + chart: flat, + axes: [ + { + placement: 'bottom', + ticks: [5], + tickLabelProps: { textAnchor: 'start', dx: 8, dy: 4 }, + tickLabel: noted, + }, + ], + }); + await expect.poll(() => notedLabels()['5']?.dy).toBeCloseTo(4); + expect(notedLabels()['5']).toMatchObject({ dx: 8, textAnchor: 'start' }); + }); + + it("turns a side's title to read up it, against the padding's edge", async () => { + await renderAxes({ + chart: flat, + axes: [{ placement: 'right', ticks: [], label: noted }], + }); + await expect.poll(() => notedLabels()['']?.rotate).toBe(-90); + const title = notedLabels()['']; + expect(title.x).toBeCloseTo(chart!.width + 20); + expect(title.y).toBeCloseTo(chart!.height / 2); + expect(title.verticalAnchor).toBe('end'); + }); +}); + +describe('Axis and Grid in a `radial` chart', () => { + const radial = { xDomain: [0, 100], yDomain: [0, 100], radial: true }; + + it("places `angle`'s labels around the rim, and `radius`' out from the center", async () => { + await renderAxes({ + chart: radial, + center: true, + axes: [ + { placement: 'angle', ticks: [25], tickLabel: noted }, + { placement: 'radius', ticks: [50], tickLabel: noted }, + ], + }); + await expect.poll(() => Object.keys(notedLabels()).sort()).toEqual(['25', '50']); + const outer = chart!.height / 2; + const [x, y] = pointRadial(Math.PI / 2, outer); + expect(notedLabels()['25']).toMatchObject({ textAnchor: 'start', verticalAnchor: 'middle' }); + expect(notedLabels()['25'].x).toBeCloseTo(x); + expect(notedLabels()['25'].y).toBeCloseTo(y); + expect(notedLabels()['50'].x).toBeCloseTo(0); + expect(notedLabels()['50'].y).toBeCloseTo(outer / 2); + }); + + it('draws spokes at the `x` ticks and circles at the `y` ticks', async () => { + const scene = await renderAxes({ + chart: radial, + center: true, + grid: { x: true, xTicks: [0, 25, 50, 75], y: true, yTicks: [50, 100] }, + }); + await expect.poll(() => visibleLines(scene).length).toBe(2); + const outer = chart!.height / 2; + const distances = visibleLines(scene).map((lines) => + segmentsOf(lines).flatMap((segment) => segment.map(([x, y]) => Math.hypot(x, y))) + ); + // The spokes: from the center out to the rim + const spokes = distances.find((d) => d.length === 8)!; + expect(Math.min(...spokes)).toBeCloseTo(0); + expect(Math.max(...spokes)).toBeCloseTo(outer); + // The circles: every point at one of the two radii + const circles = distances.find((d) => d.length > 8)!; + expect(circles.every((r) => Math.abs(r - outer / 2) < 0.01 || Math.abs(r - outer) < 0.01)).toBe( + true + ); + }); +}); + +describe('Grid', () => { + it('draws only the lines asked for, as the core `Grid`', async () => { + const scene = await renderAxes({ chart: flat, grid: { x: true } }); + await expect.poll(() => visibleLines(scene).length).toBe(1); + // Up and down the plot + const [[a, b]] = segmentsOf(visibleLines(scene)[0]); + expect(a[0]).toBeCloseTo(b[0]); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-geo-2.svelte.test.ts b/packages/webgl/src/lib/components/parity-geo-2.svelte.test.ts new file mode 100644 index 0000000000..62ac15e8c8 --- /dev/null +++ b/packages/webgl/src/lib/components/parity-geo-2.svelte.test.ts @@ -0,0 +1,247 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { geoIdentity, geoMercatorRaw, geoProjection, type GeoRawProjection } from 'd3-geo'; +import { Color, Matrix4, Quaternion, Vector3, type InstancedMesh, type Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import Geo2 from './__fixtures__/Geo2.svelte'; + +type Props = Omit>[1], 'onScene'>; + +let chart: ChartState | undefined; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderGeo(props: Props) { + let scene: SceneState | undefined; + render(Geo2, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +/** Every object under the scene's root */ +function all(scene: SceneState) { + const found: Object3D[] = []; + scene.root.traverse((o) => void (o !== scene.root && found.push(o))); + return found; +} +const instanced = (scene: SceneState) => + all(scene).filter((o) => (o as any).isInstancedMesh && (o as any).count > 0) as InstancedMesh[]; +/** Outlines with segments drawn */ +const outlines = (scene: SceneState) => + all(scene).filter( + (o) => + (o as any).isLineSegments2 && + o.visible && + ((o as any).geometry.attributes.instanceStart?.count ?? 0) > 0 + ); +const fills = (scene: SceneState) => + all(scene).filter( + (o) => (o as any).isMesh && !(o as any).isInstancedMesh && !(o as any).isLineSegments2 + ) as any[]; + +/** An instance's center on the plot (across, down, and up), through the groups it's in */ +function placed(mesh: InstancedMesh, i = 0, scene?: SceneState) { + const matrix = new Matrix4(); + mesh.getMatrixAt(i, matrix); + // Through the groups between it and the scene's root + mesh.updateWorldMatrix(true, false); + matrix.premultiply(mesh.matrixWorld); + if (scene) matrix.premultiply(scene.root.matrixWorld.clone().invert()); + const position = new Vector3(); + const size = new Vector3(); + matrix.decompose(position, new Quaternion(), size); + return { x: position.x, y: position.z, z: position.y, r: size.x }; +} + +const geo = { geo: { projection: geoIdentity } }; + +describe('GeoPoint', () => { + it('draws a circle at its point through the projection', async () => { + const scene = await renderGeo({ + mark: 'geopoint', + chart: geo, + geopoint: { lat: 50, long: 100, r: 5 }, + }); + await expect.poll(() => instanced(scene).length).toBeGreaterThan(0); + const at = placed(instanced(scene)[0], 0, scene); + const [px, py] = chart!.geo.projection!([100, 50])!; + expect([at.x, at.y]).toEqual([expect.closeTo(px), expect.closeTo(py)]); + }); + + it('places its `children` at its point, as in an `Svg` layer', async () => { + const scene = await renderGeo({ + mark: 'geopoint-children', + chart: geo, + geopoint: { lat: 50, long: 100 }, + }); + await expect.poll(() => instanced(scene).length).toBeGreaterThan(0); + const at = placed(instanced(scene)[0], 0, scene); + const [px, py] = chart!.geo.projection!([100, 50])!; + expect([at.x, at.y]).toEqual([expect.closeTo(px), expect.closeTo(py)]); + }); +}); + +describe('Hull', () => { + it('outlines its rows on a map', async () => { + const scene = await renderGeo({ + mark: 'hull', + chart: { + ...geo, + x: 'long', + y: 'lat', + data: [ + { long: 10, lat: 10 }, + { long: 40, lat: 10 }, + { long: 30, lat: 40 }, + ], + }, + hull: { stroke: 'red' }, + }); + await expect.poll(() => outlines(scene).length).toBeGreaterThan(0); + }); +}); + +describe('GeoPath', () => { + const square = { + type: 'Polygon' as const, + coordinates: [ + [ + [10, 10], + [10, 50], + [50, 50], + [50, 10], + [10, 10], + ], + ], + }; + + it('draws no outline for a class of `stroke: none`', async () => { + const scene = await renderGeo({ + mark: 'geopath', + chart: geo, + geopath: { geojson: square, class: 'geo2-fill-red geo2-stroke-none' }, + }); + await expect.poll(() => fills(scene).length).toBeGreaterThan(0); + expect(outlines(scene)).toHaveLength(0); + }); + + it('stops at a point the projection can’t place, as an SVG path does', async () => { + // A raw Mercator, with no clip extent, sends the pole off to infinity + const scene = await renderGeo({ + mark: 'geopath', + chart: { + geo: { + projection: () => geoProjection(geoMercatorRaw as unknown as GeoRawProjection).scale(30), + }, + }, + geopath: { + geojson: { + type: 'Polygon', + coordinates: [ + [ + [-20, -60], + [20, -60], + [20, -90], + [-20, -60], + ], + ], + }, + fill: 'red', + }, + }); + await expect.poll(() => fills(scene).length).toBeGreaterThan(0); + const positions = Array.from( + fills(scene)[0].geometry.attributes.position.array as Float32Array + ); + expect(positions.every(Number.isFinite)).toBe(true); + }); +}); + +describe('Vector', () => { + it('takes a `class` of the row', async () => { + const scene = await renderGeo({ + mark: 'vector', + chart: { xDomain: [0, 10], yDomain: [0, 10] }, + vector: { + data: [ + { x: 2, y: 5, party: 'a' }, + { x: 8, y: 5, party: 'b' }, + ], + x: 'x', + y: 'y', + length: 30, + shape: 'arrow-filled', + class: (d: any) => (d.party === 'a' ? 'geo2-fill-red' : 'geo2-fill-blue'), + }, + }); + const colors = () => { + const mesh = fills(scene)[0]; + const color = mesh?.geometry.attributes.color; + if (!color) return []; + const seen = new Set(); + for (let i = 0; i < color.count; i++) { + seen.add(new Color(color.getX(i), color.getY(i), color.getZ(i)).getHexString()); + } + return [...seen].sort(); + }; + await expect.poll(colors).toEqual(['0000ff', 'ff0000']); + }); +}); + +describe('Circle', () => { + it('draws no ring for a `stroke` of `none`', async () => { + const scene = await renderGeo({ + mark: 'circle', + chart: {}, + circle: { cx: 100, cy: 50, r: 10, stroke: 'none' }, + }); + await expect.poll(() => instanced(scene).length).toBe(1); + }); + + it('is raised by the chart’s `z` in data mode, as the core `Circle`', async () => { + const scene = await renderGeo({ + mark: 'circle', + chart: { + data: [{ x: 5, y: 5, z: 10 }], + x: 'x', + y: 'y', + z: 'z', + xDomain: [0, 10], + yDomain: [0, 10], + zDomain: [0, 10], + zRange: [0, 100], + }, + circle: { cx: 'x', cy: 'y', r: 4 }, + }); + await expect.poll(() => instanced(scene).length).toBeGreaterThan(0); + expect(placed(instanced(scene)[0], 0, scene).z).toBeCloseTo(100); + }); +}); + +describe('Points', () => { + it('draws a point at each value of an `x` of several, as the core `Points`', async () => { + const scene = await renderGeo({ + mark: 'points', + chart: { + data: [ + { start: 2, end: 6, name: 'a' }, + { start: 4, end: 9, name: 'b' }, + ], + x: ['start', 'end'], + y: 'name', + xDomain: [0, 10], + }, + points: {}, + }); + await expect.poll(() => instanced(scene)[0]?.count).toBe(4); + const across = [0, 1, 2, 3].map((i) => placed(instanced(scene)[0], i, scene).x); + expect(across).toEqual([2, 6, 4, 9].map((v) => expect.closeTo(chart!.xScale(v)))); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-marks.svelte.test.ts b/packages/webgl/src/lib/components/parity-marks.svelte.test.ts index 13b09b9ba9..35713025cb 100644 --- a/packages/webgl/src/lib/components/parity-marks.svelte.test.ts +++ b/packages/webgl/src/lib/components/parity-marks.svelte.test.ts @@ -364,6 +364,7 @@ describe('Text, with the core `Text`’s props', () => { y: 50, segments: [{ value: 'Hello ' }, { value: 'world' }], fontSize: 12, + textAnchor: 'middle', }, }); await expect.poll(() => planes(scene).length).toBe(2); diff --git a/packages/webgl/src/lib/components/parity-scales.svelte.test.ts b/packages/webgl/src/lib/components/parity-scales.svelte.test.ts index 0964f2d32d..640a9af085 100644 --- a/packages/webgl/src/lib/components/parity-scales.svelte.test.ts +++ b/packages/webgl/src/lib/components/parity-scales.svelte.test.ts @@ -2,10 +2,10 @@ import { describe, expect, it } from 'vitest'; import { render } from 'vitest-browser-svelte'; import { createRawSnippet } from 'svelte'; import { scaleBand } from 'd3-scale'; -import { curveCatmullRomClosed } from 'd3-shape'; +import { curveCatmullRomClosed, stack } from 'd3-shape'; import { geoIdentity, geoMercator } from 'd3-geo'; import { Color, type Object3D } from 'three'; -import type { ChartState } from 'layerchart'; +import { isometric, type BinCell, type ChartState } from 'layerchart'; import type { SceneState } from '../contexts/scene.svelte.js'; import Marks from './__fixtures__/Marks.svelte'; @@ -87,6 +87,7 @@ describe('Contour', () => { value: (x: number, _y: number) => (Math.abs(x - 0.5) < 0.05 ? 1 : 0), thresholds: [0.5], z: 2, + fill: 'none', stroke: 'black', strokeOpacity: 0.5, opacity: 0.5, @@ -111,6 +112,7 @@ describe('Contour', () => { value: (x: number, _y: number) => x, thresholds: [0.5], z: (band: { value: number }) => band.value * 10, + fill: 'none', stroke: 'black', }, }); @@ -292,6 +294,79 @@ describe('Highlight', () => { }); }); +describe('Highlight points', () => { + it('points each band of a stack (`y={[0, 1]}`) at its top, in its series’ color', async () => { + const keys = ['apples', 'bananas', 'oranges']; + const rows = [ + { x: 1, apples: 2, bananas: 3, oranges: 4 }, + { x: 2, apples: 1, bananas: 2, oranges: 3 }, + ]; + const series = stack().keys(keys)(rows); + const scene = await renderMarks({ + mark: 'highlight', + chart: { + data: series, + flatData: series.flat(), + x: (d: any) => d.data.x, + y: [0, 1], + c: 'key', + cDomain: keys, + cRange: ['red', 'green', 'blue'], + xDomain: [0, 3], + yDomain: [0, 10], + }, + highlight: { data: series[0][1], points: true }, + }); + await expect.poll(() => scene.markerSets.flat().length).toBe(3); + const markers = scene.markerSets.flat(); + // Each band's top (1, then 1 + 2, then 1 + 2 + 3) at the hovered row's x + expect(markers.map((m) => Math.round(chart!.yScale.invert!(m.y)))).toEqual([1, 3, 6]); + expect(new Set(markers.map((m) => Math.round(m.x)))).toEqual( + new Set([Math.round(chart!.xScale(2))]) + ); + expect(markers.map((m) => m.fill)).toEqual(['red', 'green', 'blue']); + }); +}); + +describe('Bin on an isometric floor', () => { + // A grid of rows, many on cells' edges + const data = Array.from({ length: 400 }, (_, i) => ({ + x: (i % 20) * 5, + y: Math.floor(i / 20) * 5, + })); + + /** The cells' counts, with the view turned to `rotate` */ + async function countsAt(rotate: number) { + let cells: BinCell[] = []; + const children = createRawSnippet((args: () => { cells: BinCell[] }) => { + cells = args().cells; + return { render: () => '' }; + }); + await renderMarks({ + mark: 'bin', + chart: { + data, + x: 'x', + y: 'y', + xDomain: [0, 100], + yDomain: [0, 100], + view: isometric({ rotate }), + }, + bin: { size: 24, children } as any, + }); + await expect.poll(() => cells.length).toBeGreaterThan(0); + return { counts: cells.map((cell) => cell.count).sort((a, b) => a - b), width: chart!.width }; + } + + it('holds the same cells as the view turns and the floor is refitted, as the core `Bin`', async () => { + const square = await countsAt(0); + const turned = await countsAt(45); + // The floor's refitted smaller turned, but measured against it laid flat, the cells are the same + expect(turned.width).not.toBeCloseTo(square.width, 0); + expect(turned.counts).toEqual(square.counts); + }); +}); + describe('Highlight area', () => { const data = [ { x: 'a', y: 3 }, diff --git a/packages/webgl/src/lib/components/parity-spline-2.svelte.test.ts b/packages/webgl/src/lib/components/parity-spline-2.svelte.test.ts new file mode 100644 index 0000000000..32817bd3e7 --- /dev/null +++ b/packages/webgl/src/lib/components/parity-spline-2.svelte.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import type { Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import SplineArea from './__fixtures__/SplineArea.svelte'; + +type Props = Omit>[1], 'onScene'>; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderMarks(props: Props) { + let scene: SceneState | undefined; + let chart: ChartState | undefined; + render(SplineArea, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return { scene: scene!, chart: chart! }; +} + +/** Every object in the scene */ +const all = (scene: SceneState) => { + const out: Object3D[] = []; + scene.root.traverse((o) => out.push(o)); + return out; +}; +/** The scene's lines (a `Spline`'s, each a `Line2`) */ +const lines = (scene: SceneState) => all(scene).filter((o) => (o as any).isLine2) as any[]; +/** A line's points, as `[x, y]` across and down the plot */ +const pointsOf = (line: any): [number, number][] => { + const start = line.geometry.attributes.instanceStart; + const end = line.geometry.attributes.instanceEnd; + const out: [number, number][] = []; + for (let i = 0; i < start.count; i++) out.push([start.getX(i), start.getZ(i)]); + if (start.count) out.push([end.getX(start.count - 1), end.getZ(start.count - 1)]); + return out; +}; + +const radial = { + radial: true, + x: 'x', + y: 'y', + xDomain: [0, 4], + xRange: [0, 2 * Math.PI], + yDomain: [0, 10], + yRange: [0, 100], +}; + +describe('Spline and Area, as the core marks', () => { + it("lays a `radial` chart's line out by angle and radius about the center", async () => { + const data = [ + { x: 0, y: 10 }, + { x: 1, y: 5 }, + { x: 2, y: 10 }, + ]; + const { scene } = await renderMarks({ chart: { ...radial, data }, spline: {} }); + await expect.poll(() => lines(scene).length).toBe(1); + const points = pointsOf(lines(scene)[0]); + // Up at 12 o'clock, right at 3, and down at 6, as `lineRadial` puts them + expect(points[0][0]).toBeCloseTo(0); + expect(points[0][1]).toBeCloseTo(-100); + expect(points[1][0]).toBeCloseTo(50); + expect(points[1][1]).toBeCloseTo(0); + expect(points[2][0]).toBeCloseTo(0); + expect(points[2][1]).toBeCloseTo(100); + }); + + it("fills a `radial` chart's area between its radii", async () => { + const data = [0, 1, 2, 3].map((x) => ({ x, lo: 4, hi: 8 })); + const { scene } = await renderMarks({ + chart: { ...radial, data }, + area: { y0: 'lo', y1: 'hi' }, + }); + const mesh = () => all(scene).find((o) => (o as any).isMesh && !(o as any).isLine2) as any; + await expect.poll(() => mesh()?.geometry.attributes.position?.count ?? 0).toBeGreaterThan(0); + const array = mesh().geometry.attributes.position.array as Float32Array; + const radii: number[] = []; + for (let i = 0; i < array.length; i += 3) radii.push(Math.hypot(array[i], array[i + 2])); + expect(Math.min(...radii)).toBeCloseTo(40); + expect(Math.max(...radii)).toBeCloseTo(80); + }); + + it('splits a line into runs by a `class` function, dashing the dashed ones', async () => { + const data = [0, 1, 2, 3, 4].map((x) => ({ x, y: x, gap: x === 2 })); + const { scene } = await renderMarks({ + chart: { data, x: 'x', y: 'y' }, + spline: { + class: (d: any) => (d.gap ? 'test-wide test-dashed' : 'test-wide'), + }, + }); + // Solid to the gap's row, dashed across to the next, then solid again + await expect.poll(() => lines(scene).length).toBe(3); + const runs = lines(scene); + expect(runs.map((l) => l.material.dashed)).toEqual([false, true, false]); + expect(runs.map((l) => pointsOf(l).length)).toEqual([3, 2, 2]); + expect(runs.every((l) => l.material.linewidth === 2)).toBe(true); + }); + + it("draws a line all the way with `draw`, past its first frame's length", async () => { + const data = Array.from({ length: 20 }, (_, x) => ({ x, y: x % 3 })); + const { scene } = await renderMarks({ + chart: { data, x: 'x', y: 'y' }, + spline: { draw: { duration: 300 } }, + }); + await expect.poll(() => lines(scene).length).toBe(1); + const line = lines(scene)[0]; + await expect.poll(() => pointsOf(line).length).toBe(20); + // three draws no more of a line's segments than it first drew, unless told it may + await new Promise((resolve) => requestAnimationFrame(resolve)); + expect(line.geometry._maxInstanceCount ?? Infinity).toBeGreaterThanOrEqual(19); + }); + + it('stacks an `Area` with no edges of its own, as the core `Area` registers', async () => { + const data = ['a', 'b'].flatMap((name, k) => + [0, 1, 2].map((x) => ({ x, value: 10 + k, name })) + ); + const { chart } = await renderMarks({ + chart: { data, x: 'x', y: 'value', c: 'name', seriesLayout: 'stack' }, + area: {}, + }); + await expect.poll(() => chart.isStacked).toBe(true); + await expect.poll(() => Math.max(...(chart.yDomain as number[]))).toBe(21); + }); +}); diff --git a/packages/webgl/src/lib/components/parity-text-2.svelte.test.ts b/packages/webgl/src/lib/components/parity-text-2.svelte.test.ts new file mode 100644 index 0000000000..2b5fe31ce4 --- /dev/null +++ b/packages/webgl/src/lib/components/parity-text-2.svelte.test.ts @@ -0,0 +1,215 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import type { Object3D } from 'three'; +import { isometric, type ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import Marks from './__fixtures__/Marks.svelte'; + +type Props = Omit>[1], 'onScene'>; + +/** Render, and wait for the marks to add their objects to the scene */ +async function renderMarks(props: Props) { + let scene: SceneState | undefined; + render(Marks, { + ...(props as any), + onScene: (s: SceneState, _c: ChartState) => { + scene = s; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +/** Classes for these tests, as Tailwind's would set them */ +let style: HTMLStyleElement; +beforeAll(() => { + style = document.createElement('style'); + style.textContent = ` + .t-red { color: rgb(255, 0, 0); } + .t-none { fill: none; } + .t-stroke-none { stroke: none; } + `; + document.head.append(style); +}); +afterAll(() => style.remove()); + +/** The planes labels lying on the surface are painted on, in the order they're drawn */ +const planes = (scene: SceneState) => { + const found: any[] = []; + scene.root.traverse((o: any) => { + if (o.isMesh && o.material?.map) found.push(o); + }); + return found; +}; + +/** Whether a label's painted canvas has a pixel mostly of `channel` (`0` red, `2` blue, ...) */ +function painted(plane: any, test: (r: number, g: number, b: number, a: number) => boolean) { + const image = plane.material.map.image as HTMLCanvasElement; + const pixels = image.getContext('2d')!.getImageData(0, 0, image.width, image.height).data; + for (let i = 0; i < pixels.length; i += 4) { + if (test(pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3])) return true; + } + return false; +} + +/** The objects marks put in the scene, looking through each mark's own layer */ +const layered = (scene: SceneState) => + scene.root.children.flatMap((o) => (o.userData.layer ? o.children : [o])); + +describe('Text, as the core `Text`', () => { + it('starts at its point by default (`textAnchor` `start`)', async () => { + const scene = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'hello', fontSize: 12 }, + }); + await expect.poll(() => planes(scene).length).toBe(1); + // Its plane's middle to the right of its point, not centered on it + expect(planes(scene)[0].position.x).toBeGreaterThan(110); + }); + + it('draws no halo with a `stroke-none` class, over its `stroke` prop (as CSS does)', async () => { + const blue = (r: number, g: number, b: number, a: number) => b > 200 && r < 60 && a > 100; + const haloed = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'hello', fontSize: 12, stroke: 'blue', strokeWidth: 4 }, + }); + await expect.poll(() => planes(haloed).length).toBe(1); + expect(painted(planes(haloed)[0], blue)).toBe(true); + + const plain = await renderMarks({ + mark: 'text', + chart: {}, + text: { + x: 100, + y: 50, + value: 'hello', + fontSize: 12, + stroke: 'blue', + strokeWidth: 4, + class: 't-stroke-none', + }, + }); + await expect.poll(() => planes(plain).length).toBe(1); + expect(painted(planes(plain)[0], blue)).toBe(false); + }); + + it('shares one painting between labels a little apart in size, each shrunk to its own', async () => { + const label = async (fontSize: number) => { + const scene = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 100, y: 50, value: 'shared', fontSize }, + }); + await expect.poll(() => planes(scene).length).toBe(1); + return planes(scene)[0]; + }; + const a = await label(12); + // A size changing a little (ex. fitted to a box as the view turns) paints nothing anew + const b = await label(12.4); + expect(b.material.map.image).toBe(a.material.map.image); + expect(b.scale.x / a.scale.x).toBeCloseTo(12.4 / 12); + // One a step apart is painted at its own size + const c = await label(24); + expect(c.material.map.image).not.toBe(a.material.map.image); + }); + + it('lays `segments` from its point, each in its own class’s text color', async () => { + const scene = await renderMarks({ + mark: 'text', + chart: {}, + text: { + x: 100, + y: 50, + fontSize: 12, + segments: [{ value: 'Hello', class: 't-red' }, { value: ' world' }], + }, + }); + await expect.poll(() => planes(scene).length).toBe(2); + const [hello, world] = planes(scene); + expect(hello.position.x).toBeGreaterThan(100); + expect(world.position.x).toBeGreaterThan(hello.position.x); + const red = (r: number, g: number, b: number, a: number) => a > 200 && r > 200 && g < 60; + expect(painted(hello, red)).toBe(true); + expect(painted(world, red)).toBe(false); + }); + + it('wraps on an explicit newline, starting at its point', async () => { + const scene = await renderMarks({ + mark: 'text', + chart: {}, + text: { x: 0, y: 0, value: 'March\n2025', verticalAnchor: 'start', fontSize: 12 }, + }); + await expect.poll(() => planes(scene).length).toBe(1); + const plane = planes(scene)[0]; + const image = plane.material.map.image as HTMLCanvasElement; + // Two lines tall, and all of it right of `x` (not cut off at the plot's left edge) + expect(image.height).toBeGreaterThan(image.width / 3); + expect(plane.position.x).toBeGreaterThan(0); + }); +}); + +describe('Arc, as the core `Arc`', () => { + it('leaves a `fill-none` track unfilled', async () => { + const meshes = (scene: SceneState) => + layered(scene).filter((o: Object3D) => (o as any).isMesh && (o as any).visible !== false); + const filled = await renderMarks({ + mark: 'arc', + chart: {}, + arc: { value: 0, outerRadius: 80, innerRadius: 70, track: { class: 't-none' } }, + }); + // Only drawn where there's something to draw + await expect.poll(() => filled.root.children.length).toBeGreaterThan(0); + const triangles = meshes(filled).reduce( + (sum, mesh: any) => sum + (mesh.geometry?.attributes?.position?.count ?? 0), + 0 + ); + expect(triangles).toBe(0); + }); +}); + +describe('Contour, as the core `Contour`', () => { + // A cone: a ring of each threshold, closing along the grid's edges at the lowest + const size = 20; + const values = Array.from({ length: size * size }, (_, k) => { + const [i, j] = [k % size, Math.floor(k / size)]; + return 100 - Math.hypot(i - size / 2, j - size / 2) * 5; + }); + const lines = (scene: SceneState) => + layered(scene).find((o: any) => o.isLineSegments2 && o.visible) as any; + + it('draws raised unfilled bands as lines in their colors, through the grid’s edges', async () => { + const scene = await renderMarks({ + mark: 'contour', + chart: { zDomain: [0, 100], zRange: [0, 50], view: isometric() }, + contour: { data: values, width: size, height: size, z: 'value', fill: 'none' }, + }); + await expect.poll(() => !!lines(scene)).toBe(true); + const segments = lines(scene); + expect(segments.material.vertexColors).toBe(true); + expect(segments.geometry.attributes.instanceColorStart).toBeTruthy(); + // Its lowest ring runs along the plot's left edge (`x` 0) + const start = segments.geometry.attributes.instanceStart; + const xs = Array.from({ length: start.count }, (_, i) => start.getX(i)); + expect(Math.min(...xs)).toBeCloseTo(0, 0); + }); + + it('keeps a `stroke` it is given, in one color', async () => { + const scene = await renderMarks({ + mark: 'contour', + chart: { zDomain: [0, 100], zRange: [0, 50], view: isometric() }, + contour: { + data: values, + width: size, + height: size, + z: 'value', + fill: 'none', + stroke: 'red', + }, + }); + await expect.poll(() => !!lines(scene)).toBe(true); + expect(lines(scene).material.vertexColors).toBe(false); + }); +}); diff --git a/packages/webgl/src/lib/utils/color.ts b/packages/webgl/src/lib/utils/color.ts index deff0e36a8..5dc45b2ea1 100644 --- a/packages/webgl/src/lib/utils/color.ts +++ b/packages/webgl/src/lib/utils/color.ts @@ -17,6 +17,8 @@ export type ClassStyle = { */ fillSet: boolean; strokeSet: boolean; + /** Whether its classes take its stroke away (`stroke-none`) */ + strokeNone?: boolean; strokeWidth: number | null; opacity: number; /** Its `mix-blend-mode`, when not `normal` (ex. `plus-lighter`) */ @@ -25,6 +27,10 @@ export type ClassStyle = { fontSize: number; /** Its font weight: its class's (ex. `font-semibold`), else what it inherits there */ fontWeight: string; + /** The `stroke-dasharray` its classes set, in pixels (ex. `4, 4`), else `null` */ + strokeDasharray?: string | null; + /** The text color its classes set (ex. `text-primary`), which a label's fill follows */ + color?: string | null; }; /** @@ -94,6 +100,9 @@ export class ColorResolver { svg.style.stroke = 'rgb(3, 2, 1)'; // Not 1px, SVG's own, which `stroke-1` sets svg.style.strokeWidth = '1.0625px'; + // A text color of its own, not the probe's (which `resolve` sets), so a class's (ex. + // `text-primary`) is told from none + svg.style.color = 'rgb(1, 2, 4)'; this.#classed = document.createElementNS('http://www.w3.org/2000/svg', 'path'); this.#plain = document.createElementNS('http://www.w3.org/2000/svg', 'path'); svg.append(this.#classed, this.#plain); @@ -108,8 +117,15 @@ export class ColorResolver { } const style = getComputedStyle(this.#classed); const plain = getComputedStyle(this.#plain); - const set = (key: 'fill' | 'stroke' | 'strokeWidth') => - style[key] !== plain[key] ? style[key] : null; + /** The text color its classes set, else `null` (the probe's own, see above) */ + const color = style.color !== plain.color ? style.color : null; + const set = (key: 'fill' | 'stroke' | 'strokeWidth') => { + if (style[key] === plain[key]) return null; + // `fill-current` with no text color of its own: the color it inherits where it's drawn + return key !== 'strokeWidth' && color == null && style[key] === style.color + ? 'currentColor' + : style[key]; + }; /** * A color the classes set as LayerChart's do for their marks (ex. `.lc-highlight-area`'s * `--fill-color`), which its SVG primitives read @@ -127,11 +143,17 @@ export class ColorResolver { stroke: stroke ?? variable('--stroke-color'), fillSet: fill != null, strokeSet: stroke != null, + strokeNone: set('stroke') === 'none', strokeWidth: strokeWidth == null ? null : parseFloat(strokeWidth), opacity: Number(style.opacity) * Number(style.fillOpacity || 1), blend: style.mixBlendMode && style.mixBlendMode !== 'normal' ? style.mixBlendMode : null, fontSize: parseFloat(style.fontSize), fontWeight: style.fontWeight, + strokeDasharray: + style.strokeDasharray !== plain.strokeDasharray && style.strokeDasharray !== 'none' + ? style.strokeDasharray.replace(/px/g, '') + : null, + color, }; } diff --git a/packages/webgl/src/lib/utils/contours.ts b/packages/webgl/src/lib/utils/contours.ts index 03890ceae1..73ef811240 100644 --- a/packages/webgl/src/lib/utils/contours.ts +++ b/packages/webgl/src/lib/utils/contours.ts @@ -20,30 +20,55 @@ export function contourSegments( extent: [number, number], thresholds: number | number[], height: (value: number) => number, - { - smooth = true, - }: { - /** Interpolate where lines cross each cell, else run them along the cells' corners */ - smooth?: boolean; - } = {} + options: ContourLevelOptions = {} ): number[] { + return contourLevels(grid, extent, thresholds, height, options).flatMap( + (level) => level.segments + ); +} + +export type ContourLevelOptions = { + /** Interpolate where lines cross each cell, else run them along the cells' corners */ + smooth?: boolean; + /** + * Keep where the rings close along the grid's edges, and count `thresholds` from the values' + * nice extent, as the core `Contour` draws its bands' outlines + */ + edges?: boolean; +}; + +/** + * Each threshold's contour lines through a grid (see `contourSegments`), with its value: ex. to + * color each level's lines by it + */ +export function contourLevels( + grid: Grid, + extent: [number, number], + thresholds: number | number[], + height: (value: number) => number, + { smooth = true, edges = false }: ContourLevelOptions = {} +): { value: number; segments: number[] }[] { const { values, columns, rows } = grid; - const levels = Array.isArray(thresholds) ? thresholds : ticks(extent[0], extent[1], thresholds); + // A count as the core `Contour`'s (d3's, from a nice extent), else evenly spaced over `extent` + const levels = + Array.isArray(thresholds) || edges ? thresholds : ticks(extent[0], extent[1], thresholds); // Holes close around themselves rather than leaving lines open const field = Array.from(values, (v) => (Number.isFinite(v) ? v : -Infinity)); - const generator = d3Contours().size([columns, rows]).thresholds(levels).smooth(smooth); + const generator = d3Contours().size([columns, rows]).smooth(smooth); + if (typeof levels === 'number') generator.thresholds(levels); + else generator.thresholds(levels); const onEdge = (x: number, y: number) => x <= 0 || y <= 0 || x >= columns || y >= rows; - const segments: number[] = []; - for (const contour of generator(field)) { + return generator(field).map((contour) => { const z = height(contour.value); + const segments: number[] = []; for (const polygon of contour.coordinates) { for (const ring of polygon) { for (let k = 0; k < ring.length - 1; k++) { const [x0, y0] = ring[k]; const [x1, y1] = ring[k + 1]; // The rings close along the grid's edges, which aren't contour lines - if (onEdge(x0, y0) && onEdge(x1, y1)) continue; + if (!edges && onEdge(x0, y0) && onEdge(x1, y1)) continue; // A contour's `(x, y)` is in cells, value `(i, j)` sitting at `(i + 0.5, j + 0.5)` const [ax, ay] = cellCenter(grid, x0 - 0.5, y0 - 0.5); const [bx, by] = cellCenter(grid, x1 - 0.5, y1 - 0.5); @@ -51,6 +76,6 @@ export function contourSegments( } } } - } - return segments; + return { value: contour.value, segments }; + }); } diff --git a/packages/webgl/src/lib/utils/curve.ts b/packages/webgl/src/lib/utils/curve.ts index 3da6d25fbd..ffff084036 100644 --- a/packages/webgl/src/lib/utils/curve.ts +++ b/packages/webgl/src/lib/utils/curve.ts @@ -1,17 +1,24 @@ import { line, type CurveFactory } from 'd3-shape'; -/** Points sampled along each curved segment */ +/** Points sampled along each curved segment, at most */ const STEPS = 12; +/** Pixels between points sampled along a curved segment, at least, when `adaptive` */ +const STEP_LENGTH = 2; /** * A line through `points` (`[x, y]` on the floor) shaped by a d3 `curve`, as the core `Spline` * draws it: each point sampled along it, with where it falls between the points it was drawn - * through (`at`: `1.5` is halfway from the second to the third), for its height, color, and row + * through (`at`: `1.5` is halfway from the second to the third), for its height, color, and row. + * With `adaptive`, a short curved segment takes fewer points (one every couple of pixels), for + * long lines of many rows; else each takes the same number (ex. so an area's two edges pair up). */ export function curvePoints( points: [number, number][], - curve: CurveFactory + curve: CurveFactory, + { adaptive = false }: { adaptive?: boolean } = {} ): { x: number; y: number; at: number }[] { + const stepsFor = (length: number) => + adaptive ? Math.max(1, Math.min(STEPS, Math.ceil(length / STEP_LENGTH))) : STEPS; const sampled: [number, number][] = []; let last: [number, number] = [0, 0]; const push = (x: number, y: number) => { @@ -26,8 +33,13 @@ export function curvePoints( closePath: () => sampled.length && push(...sampled[0]), bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) { const [x0, y0] = last; - for (let i = 1; i <= STEPS; i++) { - const t = i / STEPS; + const steps = stepsFor( + Math.hypot(c1x - x0, c1y - y0) + + Math.hypot(c2x - c1x, c2y - c1y) + + Math.hypot(x - c2x, y - c2y) + ); + for (let i = 1; i <= steps; i++) { + const t = i / steps; const u = 1 - t; push( u * u * u * x0 + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * x, @@ -37,8 +49,9 @@ export function curvePoints( }, quadraticCurveTo(cx: number, cy: number, x: number, y: number) { const [x0, y0] = last; - for (let i = 1; i <= STEPS; i++) { - const t = i / STEPS; + const steps = stepsFor(Math.hypot(cx - x0, cy - y0) + Math.hypot(x - cx, y - cy)); + for (let i = 1; i <= steps; i++) { + const t = i / steps; const u = 1 - t; push(u * u * x0 + 2 * u * t * cx + t * t * x, u * u * y0 + 2 * u * t * cy + t * t * y); } diff --git a/packages/webgl/src/lib/utils/labels.ts b/packages/webgl/src/lib/utils/labels.ts index 37ffccbadd..e2d74451c8 100644 --- a/packages/webgl/src/lib/utils/labels.ts +++ b/packages/webgl/src/lib/utils/labels.ts @@ -129,18 +129,26 @@ export function labelPlane( const texture = new CanvasTexture(label); texture.colorSpace = LinearSRGBColorSpace; - // Blended by coverage at the glyphs' edges, rather than against transparent black + // Premultiplied as it's sampled, so a glyph's edge blends by coverage rather than with the + // transparent black around it; the material takes the alpha back out once sampled (below) texture.premultiplyAlpha = true; texture.anisotropy = 8; - const mesh = new Mesh( - new PlaneGeometry(width / RESOLUTION, height / RESOLUTION), - new MeshLambertMaterial({ - map: texture, - transparent: true, - premultipliedAlpha: true, - depthWrite: false, - }) - ); + const material = new MeshLambertMaterial({ + map: texture, + transparent: true, + depthWrite: false, + }); + // Its color back to as painted (the alpha taken out), then lit, faded by `opacity`, encoded, + // and blended as any other's. Left premultiplied, three.js multiplies by the alpha again, and + // the letters' and halo's edges come out dark: a grey ring around a white halo. + material.onBeforeCompile = (shader) => { + shader.fragmentShader = shader.fragmentShader.replace( + '#include ', + '#include \n#ifdef USE_MAP\n\tdiffuseColor.rgb /= max( sampledDiffuseColor.a, 0.0001 );\n#endif' + ); + }; + material.customProgramCacheKey = () => 'lc-label-unpremultiplied'; + const mesh = new Mesh(new PlaneGeometry(width / RESOLUTION, height / RESOLUTION), material); return { mesh, width: width / RESOLUTION, @@ -183,3 +191,63 @@ export function disposeLabel(mesh: Mesh) { material.map?.dispose(); material.dispose(); } + +/** A label painted once, shared by every plane showing it */ +type SharedLabel = { + mesh: Mesh; + width: number; + height: number; + baseline: number; + lines: number; + /** How many planes show it */ + refs: number; +}; + +/** Painted labels by how they're painted (see `acquireLabel`) */ +const shared = new Map(); + +/** A label's plane, showing a painting shared with others painted the same */ +export type AcquiredLabel = Omit & { key: string }; + +/** + * A plane showing the label `key` names, painting it (`paint`) only when no plane shows it already: + * labels that pass between marks (ex. a treemap's, its rows drawn in a new order as the view + * turns) keep their paintings rather than measuring and painting their text again. `key` must + * name everything the painting depends on. `release` it when it's no longer shown. + */ +export function acquireLabel( + key: string, + paint: () => Omit | null +): AcquiredLabel | null { + let label = shared.get(key); + if (!label) { + const made = paint(); + if (!made) return null; + label = { ...made, refs: 0 }; + shared.set(key, label); + } + label.refs++; + // Its own plane (a mesh has one parent), drawing the shared geometry and painting + const mesh = new Mesh(label.mesh.geometry, label.mesh.material); + return { ...label, mesh, key }; +} + +/** + * Stop showing an acquired label's plane. Its painting is freed a frame after the last plane + * showing it goes, so a label passed to another mark in the same update is kept. + */ +export function releaseLabel(label: AcquiredLabel) { + const entry = shared.get(label.key); + if (!entry) return; + entry.refs--; + if (entry.refs > 0) return; + const later = + typeof requestAnimationFrame === 'function' + ? requestAnimationFrame + : (fn: () => void) => setTimeout(fn, 16); + later(() => { + if (entry.refs > 0 || shared.get(label.key) !== entry) return; + shared.delete(label.key); + disposeLabel(entry.mesh); + }); +} diff --git a/packages/webgl/src/lib/utils/lines.ts b/packages/webgl/src/lib/utils/lines.ts index 887f0ad7fd..e13cccd46b 100644 --- a/packages/webgl/src/lib/utils/lines.ts +++ b/packages/webgl/src/lib/utils/lines.ts @@ -14,12 +14,20 @@ export function createSegments() { object.visible = false; return { object, - /** Draw these segments, each a pair of points, as `[x, y, z, x, y, z, ...]` in the scene */ - set(segments: ArrayLike) { + /** + * Draw these segments, each a pair of points, as `[x, y, z, x, y, z, ...]` in the scene, in + * each point's own color (`[r, g, b, ...]`, linear, under their `style` color) when given + */ + set(segments: ArrayLike, colors?: ArrayLike) { object.geometry.dispose(); object.geometry = new LineSegmentsGeometry(); object.visible = segments.length >= 6; if (object.visible) object.geometry.setPositions(segments as number[]); + if (object.visible && colors) object.geometry.setColors(colors as number[]); + if (material.vertexColors !== !!colors) { + material.vertexColors = !!colors; + material.needsUpdate = true; + } }, /** Their color (and its alpha) and width in pixels */ style(color: ResolvedColor | null, width: number) { diff --git a/packages/webgl/src/lib/utils/marks.ts b/packages/webgl/src/lib/utils/marks.ts index 35ce0b514c..83b4ff3fb6 100644 --- a/packages/webgl/src/lib/utils/marks.ts +++ b/packages/webgl/src/lib/utils/marks.ts @@ -9,6 +9,7 @@ import { type DataProp, } from 'layerchart'; import type { ColorProp } from 'layerchart'; +import { pointRadial } from 'd3-shape'; import type { ScenePoint, Sphere } from './globe.js'; @@ -69,6 +70,13 @@ export function placer( } const xScale = scales?.x ?? (ctx.xScale as any); const yScale = scales?.y ?? (ctx.yScale as any); + // About the center on a `radial` chart, `x` an angle and `y` a radius, as the core `Points` + if (ctx.radial) { + return (x, y, height) => { + const [px, py] = pointRadial(Number(xScale(x)), Number(yScale(y))); + return [px, height, py]; + }; + } const xBand = isScaleBand(xScale) ? xScale.bandwidth() / 2 : 0; const yBand = isScaleBand(yScale) ? yScale.bandwidth() / 2 : 0; const shift = (offset: Offset, band: number, at: number) => diff --git a/packages/webgl/src/lib/utils/radial.ts b/packages/webgl/src/lib/utils/radial.ts new file mode 100644 index 0000000000..6e5bec4f07 --- /dev/null +++ b/packages/webgl/src/lib/utils/radial.ts @@ -0,0 +1,56 @@ +import { pointRadial } from 'd3-shape'; + +export { pointRadial }; + +/** + * A circle about the center, as line segments (`[x, height, y, x, height, y, ...]`, each a pair of + * points) for `createSegments`: ex. a `radial` chart's grid circle at a `y` tick. In enough pieces + * to read as round at its size. + */ +export function circleSegments(radius: number, up = 0): number[] { + if (!(radius > 0)) return []; + const pieces = Math.max(48, Math.min(360, Math.ceil((2 * Math.PI * radius) / 3))); + const segments: number[] = []; + for (let i = 0; i < pieces; i++) { + const [x1, y1] = pointRadial((i / pieces) * 2 * Math.PI, radius); + const [x2, y2] = pointRadial(((i + 1) / pieces) * 2 * Math.PI, radius); + segments.push(x1, up, y1, x2, up, y2); + } + return segments; +} + +/** + * A closed polygon through points at each angle, `radius` out (ex. a `radial` chart's grid line + * through its `x` ticks, as a linear closed curve draws it), as line segments for `createSegments` + */ +export function polygonSegments(angles: number[], radius: number, up = 0): number[] { + const segments: number[] = []; + if (angles.length < 2) return segments; + for (let i = 0; i < angles.length; i++) { + const [x1, y1] = pointRadial(angles[i], radius); + const [x2, y2] = pointRadial(angles[(i + 1) % angles.length], radius); + segments.push(x1, up, y1, x2, up, y2); + } + return segments; +} + +/** + * Where `x` / `y` values sit on a `radial` chart, about its center, as the core marks place them: + * `x` through its scale to an angle (clockwise from 12 o'clock), `y` through its own to a radius + * (at the middle of a band) + */ +export function radialPosition( + ctx: { xScale: any; yScale: any }, + xValue: unknown, + yValue: unknown +): [number, number] { + const yScale = ctx.yScale; + const band = typeof yScale.bandwidth === 'function' ? yScale.bandwidth() / 2 : 0; + return pointRadial(Number(ctx.xScale(xValue)), Number(yScale(yValue)) + band); +} + +/** A point about a `radial` chart's center moved along its angle to `radius` out */ +export function atRadius(x: number, y: number, radius: number): [number, number] { + const length = Math.hypot(x, y); + return length > 0 ? [(x / length) * radius, (y / length) * radius] : [0, 0]; +} diff --git a/packages/webgl/src/lib/utils/shapes.ts b/packages/webgl/src/lib/utils/shapes.ts index 4e2045b660..47d210fbf3 100644 --- a/packages/webgl/src/lib/utils/shapes.ts +++ b/packages/webgl/src/lib/utils/shapes.ts @@ -11,8 +11,20 @@ export class ShapeContext { readonly lines: [number, number][][] = []; #line: [number, number][] | null = null; #start: [number, number] | null = null; + /** + * Past a point that isn't finite (ex. a pole through a projection without a clip extent): the + * rest is left out, as an SVG path stops drawing at a value it can't read + */ + #broken = false; + + /** Whether drawing stops here, at values that aren't all finite */ + #stops(...values: number[]) { + if (!this.#broken && !values.every(Number.isFinite)) this.#broken = true; + return this.#broken; + } moveTo(x: number, y: number) { + if (this.#stops(x, y)) return; this.path.moveTo(x, -y); this.#line = [[x, y]]; this.lines.push(this.#line); @@ -20,27 +32,32 @@ export class ShapeContext { } lineTo(x: number, y: number) { + if (this.#stops(x, y)) return; if (!this.#line) return this.moveTo(x, y); this.path.lineTo(x, -y); this.#line.push([x, y]); } closePath() { + if (this.#broken) return; (this.path.currentPath as Path | null)?.closePath(); if (this.#line && this.#start) this.#line.push([...this.#start]); } quadraticCurveTo(cx: number, cy: number, x: number, y: number) { + if (this.#stops(cx, cy, x, y)) return; this.path.quadraticCurveTo(cx, -cy, x, -y); this.#line?.push([x, y]); } bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) { + if (this.#stops(c1x, c1y, c2x, c2y, x, y)) return; this.path.bezierCurveTo(c1x, -c1y, c2x, -c2y, x, -y); this.#line?.push([x, y]); } arc(x: number, y: number, r: number, a0: number, a1: number, ccw = false) { + if (this.#stops(x, y, r, a0, a1)) return; // Flipping `y` mirrors angles, and with them which way round the arc goes const start: [number, number] = [x + r * Math.cos(a0), y + r * Math.sin(a0)]; if (!this.#line) this.moveTo(...start); From f71246da8af4608116233e407fc38980929aa582 Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Thu, 26 Nov 2026 18:44:22 -0500 Subject: [PATCH 13/16] docs: Open examples in the filtered layer, and check 51 more WebGL examples Co-Authored-By: Claude Opus 5.5 --- docs/src/content/components/Contour.md | 2 +- docs/src/examples/components/Arc/pie.svelte | 1 + .../components/Bin/state-population.svelte | 1 + .../examples/components/Contour/basic.svelte | 1 + .../GeoPoint/us-state-capitals.svelte | 2 +- .../examples/components/Link/pin-map.svelte | 1 + .../components/Points/solar-system.svelte | 1 + .../examples/components/Polygon/tree.svelte | 1 + .../examples/components/Rect/treemap.svelte | 1 + .../docs/components/[name]/+layout.svelte | 14 +++++ docs/src/routes/docs/examples/+page.svelte | 3 ++ docs/webgl-examples.ts | 51 +++++++++++++++++++ 12 files changed, 77 insertions(+), 2 deletions(-) diff --git a/docs/src/content/components/Contour.md b/docs/src/content/components/Contour.md index adbc9defbe..389f111462 100644 --- a/docs/src/content/components/Contour.md +++ b/docs/src/content/components/Contour.md @@ -62,6 +62,6 @@ Adjust thresholds and blur on a sampled function. In a [`WebGL`](/docs/components/WebGL) layer, from [`@layerchart/webgl`](/docs/guides/webgl), its lines lie flat or rise to their heights. See the [WebGL guide](/docs/guides/webgl) to get started. -Flat, it's LayerChart's own `Contour` (filled bands through the color scale, outlined with a `stroke`), drawn with WebGL marks. Contour lines on their own lie at `z` pixels (ex. over a `Raster`), or each rises to its threshold's height with `z="value"`. It takes values the same ways as [Surface](/docs/components/Surface). +Filled, it's LayerChart's own `Contour` (bands through the color scale, outlined with a `stroke`, and stacked into terraces when raised), drawn with WebGL marks. Unfilled (`fill="none"`), its lines lie at `z` pixels (ex. over a `Raster`), or each rises to its threshold's height with `z="value"`, in the bands' colors unless given a `stroke`. It takes values the same ways as [Surface](/docs/components/Surface). :example{ name="basic" } diff --git a/docs/src/examples/components/Arc/pie.svelte b/docs/src/examples/components/Arc/pie.svelte index 9b0e30f516..0899e875bc 100644 --- a/docs/src/examples/components/Arc/pie.svelte +++ b/docs/src/examples/components/Arc/pie.svelte @@ -62,6 +62,7 @@ /> city[1]} y={(city: City) => city[2]} diff --git a/docs/src/examples/components/Contour/basic.svelte b/docs/src/examples/components/Contour/basic.svelte index 0a3600e2a7..cbe0abea41 100644 --- a/docs/src/examples/components/Contour/basic.svelte +++ b/docs/src/examples/components/Contour/basic.svelte @@ -28,6 +28,7 @@ height={volcano.height} thresholds={14} z="value" + fill="none" stroke="var(--color-surface-content)" />
diff --git a/docs/src/examples/components/GeoPoint/us-state-capitals.svelte b/docs/src/examples/components/GeoPoint/us-state-capitals.svelte index 6551d6e1bd..28dfbb8134 100644 --- a/docs/src/examples/components/GeoPoint/us-state-capitals.svelte +++ b/docs/src/examples/components/GeoPoint/us-state-capitals.svelte @@ -34,7 +34,7 @@ {#each data.us.capitals as capital} - {#if settings.layer === 'svg'} + {#if settings.layer === 'svg' || settings.layer === 'webgl'} named.has(p.name)) as planet (planet.name)} !d.children && label(d).fontSize >= 2)} x={(d) => (d.x0 + d.x1) / 2} y={(d) => (d.y0 + d.y1) / 2} diff --git a/docs/src/routes/docs/components/[name]/+layout.svelte b/docs/src/routes/docs/components/[name]/+layout.svelte index 03b98639e1..6206556805 100644 --- a/docs/src/routes/docs/components/[name]/+layout.svelte +++ b/docs/src/routes/docs/components/[name]/+layout.svelte @@ -5,6 +5,8 @@ import { intersectExampleLayers } from '$lib/utils/layers.js'; import { nativeWebGLExamples, webglExamples } from 'virtual:webgl-examples'; import { page } from '$app/state'; + import { untrack } from 'svelte'; + import { getSettings, type SettingsOptions } from 'layerchart'; import LucideBlocks from '~icons/lucide/blocks'; @@ -91,6 +93,18 @@ ] ); + // A link's `?layer=` (ex. from the examples page filtered to WebGL) opens the page in that layer, + // when it has it. Once per visit, so the layer toggle changes it from there. + const settings = getSettings(); + $effect(() => { + const requested = page.url.searchParams.get('layer'); + untrack(() => { + if (requested && layers.includes(requested)) { + settings.layer = requested as NonNullable; + } + }); + }); + // Component names as-is (ex. `ArcChart`), example names in sentence case (ex. `Axis labels inside`) const exampleTitle = $derived(page.params.example?.replaceAll('-', ' ')); const title = $derived( diff --git a/docs/src/routes/docs/examples/+page.svelte b/docs/src/routes/docs/examples/+page.svelte index 9208e69127..0a1782bc0b 100644 --- a/docs/src/routes/docs/examples/+page.svelte +++ b/docs/src/routes/docs/examples/+page.svelte @@ -330,6 +330,9 @@ component={example.component} example={example.name} title={example.label} + href={params.layer + ? `/docs/components/${example.component}/${example.name}?layer=${params.layer}` + : undefined} /> {/each} diff --git a/docs/webgl-examples.ts b/docs/webgl-examples.ts index bedc6a0088..7949069b2f 100644 --- a/docs/webgl-examples.ts +++ b/docs/webgl-examples.ts @@ -13,6 +13,7 @@ export const checkedWebGLExamples = [ 'Arc/draggable-arc', 'Arc/gauge-gradient', 'Arc/segmented-arc', + 'Arc/speedometer', 'Arc/tween-value-on-mount', 'Area/basic', 'Area/explicit-axis-ticks-min-max', @@ -21,34 +22,54 @@ export const checkedWebGLExamples = [ 'Area/multiple-series-with-labels', 'Area/oscilloscope-ridgeline-isometric', 'Area/playground', + 'Area/ridgeline', 'Area/ridgeline-kde', 'Area/stack', 'Area/tween-on-mount', 'Area/with-labels', 'Area/with-tooltip-and-highlight', + 'Axis/arrow-markers', 'Axis/auto-padding', 'Axis/axis-label-placement-left-right', 'Axis/axis-label-placement-top-bottom', 'Axis/explicit-ticks', 'Axis/extent-ticks-only', 'Axis/grid', + 'Axis/grid-dashed', 'Axis/hide-zero-filter', 'Axis/hide-zero-format', 'Axis/inject-ticks', 'Axis/integer-only-filter', 'Axis/integer-only-format', + 'Axis/labels-next-hash', 'Axis/log-scale', + 'Axis/multiline-tick-labels', 'Axis/multiple-axis-grid-and-rules', 'Axis/multiple-axis-grid-and-rules-separate-grid', 'Axis/multiple-axis-grid-with-single-rule', + 'Axis/multiple-axis-same-placement-bottom', + 'Axis/multiple-axis-same-placement-right', 'Axis/override-axis-ticks-scale', 'Axis/placement-bottom-left', 'Axis/placement-bottom-left-rule', 'Axis/placement-top-right', 'Axis/placement-top-right-rule', + 'Axis/radial-grid', + 'Axis/radial-rule', 'Axis/remove-tick-marks', + 'Axis/rotate-labels', 'Axis/tick-count', + 'Axis/tick-label-styling', + 'Axis/tick-occlusion-explicit-ticks', + 'Axis/tick-occlusion-priority', 'Axis/tick-spacing', + 'Axis/time-scale-auto', + 'Axis/time-scale-auto-format-filtering', + 'Axis/time-scale-auto-multiline', + 'Axis/time-scale-brush', + 'Axis/time-scale-brush-multiline', + 'Axis/time-scale-explicit', + 'Axis/time-scale-explicit-multiline', 'Axis/utc-scale', 'Bars/horizontal-average-annotation-rule', 'Bars/horizontal-basic', @@ -118,9 +139,11 @@ export const checkedWebGLExamples = [ 'Bin/categorical', 'Bin/image-render', 'Bin/isometric', + 'Bin/labels', 'Bin/shapes', 'Bin/size-by-count', 'Bin/tooltip', + 'Bin/walmart', 'Bin/walmart-isometric', 'BoxPlot/basic', 'BoxPlot/horizontal', @@ -157,6 +180,7 @@ export const checkedWebGLExamples = [ 'Chart/isometric-heatmap', 'Chart/isometric-pin-map', 'Chart/isometric-playground', + 'Chart/isometric-scatter-3d', 'Chart/isometric-stacked-columns', 'Chart/isometric-treemap', 'Chart/mixed-marks-with-stack', @@ -171,6 +195,7 @@ export const checkedWebGLExamples = [ 'Contour/sampled-interactive', 'Contour/volcano-filled', 'Contour/volcano-filled-interactive', + 'Contour/volcano-isometric', 'Contour/volcano-lines', 'Density/bandwidth', 'Density/basic', @@ -188,10 +213,12 @@ export const checkedWebGLExamples = [ 'Frame/basic', 'Frame/border', 'Frame/full', + 'GeoPath/choropleth', 'GeoPath/eclipses-globe', 'GeoPath/election-isometric', 'GeoPath/geojson-drilldown', 'GeoPath/sketchy-globe', + 'GeoPath/spike-map', 'GeoPath/transform-canvas', 'GeoPath/transform-canvas-scale-extent', 'GeoPath/transform-globe-constrain', @@ -199,11 +226,14 @@ export const checkedWebGLExamples = [ 'GeoPath/transform-projection', 'GeoPath/transform-world-canvas', 'GeoPath/transform-world-projection', + 'GeoPath/us-country-map', 'GeoPath/us-state', 'GeoPath/us-state-with-counties', 'GeoPoint/us-airports', + 'GeoPoint/us-state-capitals', 'GeoPoint/world-airports', 'GeoPoint/world-capitals', + 'GeoProjection/geojson-preview', 'GeoProjection/projection-playground', 'GeoProjection/satellite', 'GeoProjection/true-size', @@ -212,16 +242,22 @@ export const checkedWebGLExamples = [ 'Grid/band-scale-between', 'Grid/band-scale-default', 'Grid/basic', + 'Grid/dashed-lines', 'Grid/explicit-ticks', 'Grid/inject-tick-value', 'Grid/integer-only', 'Grid/padding', + 'Grid/radial', + 'Grid/radial-linear', 'Grid/tick-count', 'Grid/tick-count-null', + 'Grid/x-only', 'Grid/y-only', 'Group/basic', 'Group/data-mode', + 'Hull/geo', 'Hull/scatter', + 'Labels/shape-area', 'Labels/shape-geo', 'Labels/voronoi-geo', 'Line/color-via-ordinal-scale', @@ -241,6 +277,7 @@ export const checkedWebGLExamples = [ 'Marker/styling', 'Month/90-days', 'Month/basic', + 'Month/custom-cell-size', 'Month/multiple-years', 'Month/without-day-numbers', 'Month/without-month-labels', @@ -310,6 +347,7 @@ export const checkedWebGLExamples = [ 'Raster/with-contour-overlay', 'Rect/color-via-ordinal-scale', 'Rect/color-via-threshold-scale', + 'Rect/data-mode-edge', 'Rect/playground', 'Rect/styling-using-attributes', 'Rect/styling-using-classes', @@ -331,14 +369,21 @@ export const checkedWebGLExamples = [ 'Spline/basic', 'Spline/basic-start-and-end-snippets', 'Spline/draw', + 'Spline/end-snippet-with-draw', + 'Spline/geo-routes', 'Spline/label-using-start-end-snippets', 'Spline/markers-arrows', + 'Spline/missing-data-dashed', + 'Spline/missing-data-with-markers', 'Spline/multiple-series', 'Spline/multiple-series-highlight-on-hover', 'Spline/multiple-series-tweened', 'Spline/multiple-series-using-overrides', 'Spline/multiple-series-with-labels', 'Spline/playground', + 'Spline/radial-line-with-areas', + 'Spline/radial-multi-year-lines', + 'Spline/radial-radar', 'Spline/stroke-grouping', 'Spline/stroke-grouping-with-legend', 'Spline/tween-on-mount', @@ -349,6 +394,8 @@ export const checkedWebGLExamples = [ 'Text/color-via-ordinal-scale', 'Text/color-via-threshold-scale', 'Text/data-mode', + 'Text/segments', + 'Text/word-wrap-with-explicit-newline', 'Tooltip/anchor-location', 'Tooltip/area', 'Tooltip/basic', @@ -358,9 +405,11 @@ export const checkedWebGLExamples = [ 'Tooltip/data-snapping', 'Tooltip/default-mouse-position-with-offset', 'Tooltip/disable-motion', + 'Tooltip/duration', 'Tooltip/externally-access-tooltip-data', 'Tooltip/invert-variant', 'Tooltip/multiple-overlapping-bars', + 'Tooltip/multiple-overlapping-durations', 'Tooltip/multiple-tooltips-with-fixed-single-axis', 'Tooltip/multiple-tooltips-with-fixed-single-axis-scaleband', 'Tooltip/portal-overflow', @@ -372,6 +421,7 @@ export const checkedWebGLExamples = [ 'Trail/curves', 'Trail/playground', 'Trail/tdf-stage', + 'TransformContext/playground', 'Tree/basic', 'Tree/isometric', 'Tree/playground', @@ -379,6 +429,7 @@ export const checkedWebGLExamples = [ 'Vector/anchor', 'Vector/basic', 'Vector/data-mode', + 'Vector/election-wind-map', 'Vector/wind-map', 'Violin/bandwidth', 'Violin/basic', From 8d75d6323b4640a4015d84321075f2faba7eabdc Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Fri, 27 Nov 2026 00:29:44 -0500 Subject: [PATCH 14/16] feat(webgl): Simplified charts, facets, clip paths, gradients and patterns, and the remaining core components Co-Authored-By: Claude Opus 5.5 --- .changeset/webgl-core-parity.md | 20 +- packages/layerchart/src/lib/base.ts | 24 + .../ChartChildren/ChartChildren.base.svelte | 22 +- .../src/lib/components/FacetAxis.base.svelte | 74 ++ .../src/lib/components/FacetAxis.svelte | 61 +- .../src/lib/components/FacetPanel.base.svelte | 26 + .../src/lib/components/FacetPanel.svelte | 11 +- .../src/lib/components/graph/Chord.svelte | 4 +- .../AnnotationRange/AnnotationRange.svelte | 20 + .../AnnotationRange.webgl.svelte | 13 + .../lib/components/Arc/Arc.shared.svelte.ts | 4 + .../src/lib/components/Arc/Arc.webgl.svelte | 7 +- .../lib/components/ArcLabel/ArcLabel.svelte | 15 + .../src/lib/components/Area/Area.webgl.svelte | 34 +- .../src/lib/components/Axis/Axis.base.svelte | 10 +- .../lib/components/Axis/Axis.shared.svelte.ts | 5 + .../src/lib/components/Axis/Axis.webgl.svelte | 43 +- .../lib/components/Bar/Bar.shared.svelte.ts | 4 +- .../src/lib/components/Bars/Bar.radial.svelte | 10 + .../src/lib/components/Bars/Bars.base.svelte | 42 +- .../lib/components/Bars/Bars.radial.svelte | 13 + .../src/lib/components/Bars/Bars.webgl.svelte | 3 + .../src/lib/components/Bin/Bin.webgl.svelte | 5 +- .../src/lib/components/Brush/Brush.parts.ts | 34 + .../lib/components/Brush/Brush.rect.svelte | 62 ++ .../src/lib/components/Brush/Brush.svelte | 20 + .../lib/components/Brush/Brush.webgl.svelte | 62 ++ .../src/lib/components/Chart/Chart.svelte | 17 + .../ChartChildren/ChartAnnotations.svelte | 32 + .../ChartChildren/ChartChildren.svelte | 45 ++ .../ChartClipPath/ChartClipPath.svelte | 20 + .../ChartClipPath/ChartClipPath.webgl.svelte | 16 + .../lib/components/Circle/Circle.webgl.svelte | 11 +- .../CircleClipPath/CircleClipPath.svelte | 23 + .../CircleClipPath.webgl.svelte | 10 + .../lib/components/ClipPath/ClipPath.svelte | 20 + .../components/ClipPath/ClipPath.webgl.svelte | 145 ++++ .../lib/components/ClipPath/ClipShapes.svelte | 42 + .../src/lib/components/Ellipse/Ellipse.svelte | 20 + .../components/Ellipse/Ellipse.webgl.svelte | 109 +++ .../lib/components/FacetAxis/FacetAxis.svelte | 8 + .../src/lib/components/GeoBin/GeoBin.cells.ts | 31 + .../lib/components/GeoBin/GeoBin.path.svelte | 85 ++ .../src/lib/components/GeoBin/GeoBin.svelte | 20 + .../lib/components/GeoBin/GeoBin.webgl.svelte | 132 +++ .../lib/components/GeoCircle/GeoCircle.svelte | 20 + .../GeoCircle/GeoCircle.webgl.svelte | 10 + .../components/GeoClipPath/GeoClipPath.svelte | 20 + .../GeoClipPath/GeoClipPath.webgl.svelte | 10 + .../GeoEdgeFade/GeoEdgeFade.group.svelte | 9 + .../components/GeoEdgeFade/GeoEdgeFade.svelte | 20 + .../GeoEdgeFade/GeoEdgeFade.webgl.svelte | 11 + .../lib/components/GeoSpline/GeoSpline.svelte | 20 + .../GeoSpline/GeoSpline.webgl.svelte | 10 + .../src/lib/components/Image/Image.svelte | 20 + .../lib/components/Image/Image.webgl.svelte | 347 ++++++++ .../src/lib/components/Line/Line.webgl.svelte | 11 +- .../LinearGradient/LinearGradient.svelte | 20 + .../LinearGradient.webgl.svelte | 60 ++ .../src/lib/components/Link/Link.webgl.svelte | 80 +- .../src/lib/components/Pattern/Pattern.svelte | 20 + .../components/Pattern/Pattern.webgl.svelte | 46 ++ .../lib/components/Points/Points.base.svelte | 18 +- .../components/Points/Points.shared.svelte.ts | 6 +- .../src/lib/components/Points/Points.svelte | 11 +- .../components/Polygon/Polygon.webgl.svelte | 11 +- .../src/lib/components/Rect/Rect.webgl.svelte | 20 +- .../RectClipPath/RectClipPath.svelte | 20 + .../RectClipPath/RectClipPath.webgl.svelte | 10 + .../src/lib/components/Rule/Rule.webgl.svelte | 5 +- .../src/lib/components/Spline/Spline.svelte | 11 +- .../lib/components/Spline/Spline.webgl.svelte | 136 +++- .../src/lib/components/Text/Text.webgl.svelte | 11 +- .../lib/components/Vector/Vector.webgl.svelte | 5 +- .../src/lib/components/Voronoi/Voronoi.svelte | 20 + .../components/Voronoi/Voronoi.webgl.svelte | 12 + .../src/lib/components/Waffle/Waffle.svelte | 20 + .../lib/components/Waffle/Waffle.webgl.svelte | 251 ++++++ .../lib/components/__fixtures__/Clips.svelte | 138 ++++ .../__fixtures__/Components8.svelte | 69 ++ .../lib/components/__fixtures__/Paints.svelte | 60 ++ .../__fixtures__/SimplifiedChart.svelte | 24 + .../__fixtures__/ThrelteProbe.svelte | 26 + .../src/lib/components/charts.svelte.test.ts | 20 + .../src/lib/components/charts/ArcChart.svelte | 17 + .../lib/components/charts/AreaChart.svelte | 15 + .../src/lib/components/charts/BarChart.svelte | 15 + .../lib/components/charts/LineChart.svelte | 15 + .../src/lib/components/charts/PieChart.svelte | 18 + .../lib/components/charts/ScatterChart.svelte | 15 + .../lib/components/clipping-r8.svelte.test.ts | 306 +++++++ .../components/components-r8.svelte.test.ts | 201 +++++ .../components/gradients-r8.svelte.test.ts | 217 +++++ .../src/lib/components/layers/Layer.svelte | 22 +- .../lib/components/layers/WebGLSetup.svelte | 35 +- .../components/parity-lines.svelte.test.ts | 25 + .../components/parity-scales.svelte.test.ts | 50 ++ packages/webgl/src/lib/index.ts | 76 +- packages/webgl/src/lib/utils/clip.ts | 191 +++++ packages/webgl/src/lib/utils/clipMask.ts | 319 ++++++++ packages/webgl/src/lib/utils/marks.ts | 13 +- packages/webgl/src/lib/utils/merged.svelte.ts | 98 ++- packages/webgl/src/lib/utils/paint.svelte.ts | 752 ++++++++++++++++++ packages/webgl/src/lib/utils/shapes.ts | 11 +- packages/webgl/src/lib/webgl.ts | 36 + 105 files changed, 5361 insertions(+), 158 deletions(-) create mode 100644 packages/layerchart/src/lib/components/FacetAxis.base.svelte create mode 100644 packages/layerchart/src/lib/components/FacetPanel.base.svelte create mode 100644 packages/webgl/src/lib/components/AnnotationRange/AnnotationRange.svelte create mode 100644 packages/webgl/src/lib/components/AnnotationRange/AnnotationRange.webgl.svelte create mode 100644 packages/webgl/src/lib/components/ArcLabel/ArcLabel.svelte create mode 100644 packages/webgl/src/lib/components/Bars/Bar.radial.svelte create mode 100644 packages/webgl/src/lib/components/Bars/Bars.radial.svelte create mode 100644 packages/webgl/src/lib/components/Brush/Brush.parts.ts create mode 100644 packages/webgl/src/lib/components/Brush/Brush.rect.svelte create mode 100644 packages/webgl/src/lib/components/Brush/Brush.svelte create mode 100644 packages/webgl/src/lib/components/Brush/Brush.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Chart/Chart.svelte create mode 100644 packages/webgl/src/lib/components/ChartChildren/ChartAnnotations.svelte create mode 100644 packages/webgl/src/lib/components/ChartChildren/ChartChildren.svelte create mode 100644 packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.svelte create mode 100644 packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.webgl.svelte create mode 100644 packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.svelte create mode 100644 packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.webgl.svelte create mode 100644 packages/webgl/src/lib/components/ClipPath/ClipPath.svelte create mode 100644 packages/webgl/src/lib/components/ClipPath/ClipPath.webgl.svelte create mode 100644 packages/webgl/src/lib/components/ClipPath/ClipShapes.svelte create mode 100644 packages/webgl/src/lib/components/Ellipse/Ellipse.svelte create mode 100644 packages/webgl/src/lib/components/Ellipse/Ellipse.webgl.svelte create mode 100644 packages/webgl/src/lib/components/FacetAxis/FacetAxis.svelte create mode 100644 packages/webgl/src/lib/components/GeoBin/GeoBin.cells.ts create mode 100644 packages/webgl/src/lib/components/GeoBin/GeoBin.path.svelte create mode 100644 packages/webgl/src/lib/components/GeoBin/GeoBin.svelte create mode 100644 packages/webgl/src/lib/components/GeoBin/GeoBin.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoCircle/GeoCircle.svelte create mode 100644 packages/webgl/src/lib/components/GeoCircle/GeoCircle.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.svelte create mode 100644 packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.group.svelte create mode 100644 packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.svelte create mode 100644 packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.webgl.svelte create mode 100644 packages/webgl/src/lib/components/GeoSpline/GeoSpline.svelte create mode 100644 packages/webgl/src/lib/components/GeoSpline/GeoSpline.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Image/Image.svelte create mode 100644 packages/webgl/src/lib/components/Image/Image.webgl.svelte create mode 100644 packages/webgl/src/lib/components/LinearGradient/LinearGradient.svelte create mode 100644 packages/webgl/src/lib/components/LinearGradient/LinearGradient.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Pattern/Pattern.svelte create mode 100644 packages/webgl/src/lib/components/Pattern/Pattern.webgl.svelte create mode 100644 packages/webgl/src/lib/components/RectClipPath/RectClipPath.svelte create mode 100644 packages/webgl/src/lib/components/RectClipPath/RectClipPath.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Voronoi/Voronoi.svelte create mode 100644 packages/webgl/src/lib/components/Voronoi/Voronoi.webgl.svelte create mode 100644 packages/webgl/src/lib/components/Waffle/Waffle.svelte create mode 100644 packages/webgl/src/lib/components/Waffle/Waffle.webgl.svelte create mode 100644 packages/webgl/src/lib/components/__fixtures__/Clips.svelte create mode 100644 packages/webgl/src/lib/components/__fixtures__/Components8.svelte create mode 100644 packages/webgl/src/lib/components/__fixtures__/Paints.svelte create mode 100644 packages/webgl/src/lib/components/__fixtures__/SimplifiedChart.svelte create mode 100644 packages/webgl/src/lib/components/__fixtures__/ThrelteProbe.svelte create mode 100644 packages/webgl/src/lib/components/charts.svelte.test.ts create mode 100644 packages/webgl/src/lib/components/charts/ArcChart.svelte create mode 100644 packages/webgl/src/lib/components/charts/AreaChart.svelte create mode 100644 packages/webgl/src/lib/components/charts/BarChart.svelte create mode 100644 packages/webgl/src/lib/components/charts/LineChart.svelte create mode 100644 packages/webgl/src/lib/components/charts/PieChart.svelte create mode 100644 packages/webgl/src/lib/components/charts/ScatterChart.svelte create mode 100644 packages/webgl/src/lib/components/clipping-r8.svelte.test.ts create mode 100644 packages/webgl/src/lib/components/components-r8.svelte.test.ts create mode 100644 packages/webgl/src/lib/components/gradients-r8.svelte.test.ts create mode 100644 packages/webgl/src/lib/utils/clip.ts create mode 100644 packages/webgl/src/lib/utils/clipMask.ts create mode 100644 packages/webgl/src/lib/utils/paint.svelte.ts diff --git a/.changeset/webgl-core-parity.md b/.changeset/webgl-core-parity.md index 78ed65ef23..97ea912eb6 100644 --- a/.changeset/webgl-core-parity.md +++ b/.changeset/webgl-core-parity.md @@ -4,13 +4,20 @@ feat: Layer-agnostic marks and `Layer` (`type="webgl"`), drawing core's versions in `Svg`, `Canvas`, and `Html` layers so one chart can switch between all four; import WebGL-only marks from `@layerchart/webgl/webgl` feat: `Bar`, `Circle`, `Graticule`, `Group`, `Line`, and `Path`, and LayerChart's compound marks built from them (`Pie`, `Labels`, `Calendar`, `Month`, `Cell`, `BoxPlot`, `Frame`, `Hull`, `GeoPoint`, `AnnotationPoint`, `AnnotationLine`, `Violin`, `Trail`, `Density`, `Ribbon`) +feat: `BarChart`, `LineChart`, `AreaChart`, `ScatterChart`, `PieChart`, and `ArcChart`, with their axes, grid, highlight, and annotations, drawn in whichever layer they're in +feat: `AnnotationRange`, `ArcLabel`, `Brush`, `Ellipse`, `FacetAxis`, `GeoBin`, `GeoCircle`, `GeoEdgeFade`, `GeoSpline`, `Image`, `Voronoi`, and `Waffle` +feat: Re-export LayerChart's layouts, contexts, and legends (`ChartGroup`, `Dodge`, `Point`, `Bounds`, `ForceSimulation`, `Chord`, `Sankey`, `Dagre`, `Treemap`, `Partition`, `Tree`, `Pack`, `GeoProjection`, `GeoVisible`, `CircleLegend`, `GeoLegend`) +feat: `LinearGradient` and `Pattern` paint WebGL marks' fills and strokes, blended as SVG blends them +feat: `ClipPath`, `RectClipPath`, `CircleClipPath`, `GeoClipPath`, and `ChartClipPath` clip marks in a WebGL scene (to any path, a `clip` snippet's shapes, or their inverse) +feat: Faceted charts (`fx` / `fy`), each panel's marks drawing its own rows, axes on the grid's outer edge (`facetAll` for every panel) feat: Marks take core's `motion`, `key`, and `initial*` props, easing in as core's do feat: Lines and paths take core's `draw`, `marker*`, `startContent` / `endContent`, and `dashArray` feat: Marks take core's `fillOpacity`, `strokeOpacity`, `seriesKey`, pointer handlers, and the `--fill-color` / `--stroke-color` their classes or `style` set feat(Area): Stack as core's, and take `line`, `stroke`, and `pathData` feat(Axis): `top` / `right` / `angle` / `radius` placements, `grid`, rule markers, `tickOcclusion`, `tickMultiline`, `labelPlacement`, `label` / `tickLabel` snippets, tick label `rotate` / anchors / `dx` / `dy`, and `padding="auto"` -feat(Bars): Flat 2D bars without a `z`, with core's `insets`, `radius` / `rounded`, `stackPadding`, `x1` / `y1` sub-bands, fixed `width` / `height`, and `children` +feat(Bars): Radial bars, and flat 2D bars without a `z`, with core's `insets`, `radius` / `rounded`, `stackPadding`, `x1` / `y1` sub-bands, fixed `width` / `height`, and `children` feat(Bin): `r`, `grid`, `class`, and `children` +feat(Arc): Track `fillOpacity` and `strokeOpacity` feat(Contour): Flat filled bands as core's, raised bands as terraces or colored outlines, and `blur`, `smooth`, and a `z` function feat(GeoPath): `curve`, `geoTransform`, and `children` feat(Grid): Radial spokes and circles (`radialY`), per-axis line props, `bandAlign`, and `classes` @@ -32,8 +39,19 @@ fix: `opacity` dims a mark's outlines and lines fix: `Bars`, `Polygon`, and `Rect` default to `var(--color-surface-content)`, as core's fix(Axis): Ticks, tick labels, and titles placed, sized, and counted as core's fix(Highlight): Point each series at the hovered row, as core's (ex. a stack's bands) +fix(Bars): Take `opacity` as a function of the row, as core's +fix(Axis): Format an expanded stack's values as percentages, as core's +fix: `Spline` and `Points` take their series' `props`, as core's +fix: `Area` and `Spline` fade the other `c` categories while the legend highlights one, as core's fix(Bin): Keep its cells as an isometric view turns fix(Spline): Follow a stack's top, break at a map's edge, and default to 1px +fix(Area): Fill both sides of the baseline where its line crosses it +fix(Link): Draw a wide link as an even ribbon rather than overlapping round-capped segments +fix(Points): Lie flat on an isometric chart unless `viewport`, as core's +fix: Data-mode `Circle`, `Rect`, `Text`, `Line`, and `Polygon` add their data to the chart's domains, as core's +fix(Spline): Call a `stroke` function with the row's index and the line's rows, as core's +fix(Arc): Outline rounded corners the short way round (ex. a `fill-none` track) +fix: A scale with no domain (ex. `Dagre`'s pixel layout) places values as they are, as core's `Spline` fix(Text): Clean label halos, and take its class's fill and text color fix: Draw every mark of a flat chart with very many (ex. a `Calendar`'s day cells) perf(Text): Reuse label paintings as labels move between marks or change size slightly diff --git a/packages/layerchart/src/lib/base.ts b/packages/layerchart/src/lib/base.ts index 7b3923f80c..29b0c2b669 100644 --- a/packages/layerchart/src/lib/base.ts +++ b/packages/layerchart/src/lib/base.ts @@ -241,3 +241,27 @@ export type { export { GroupState } from './components/Group/Group.shared.svelte.js'; export { PointsState, type Point } from './components/Points/Points.shared.svelte.js'; export { ArcState } from './components/Arc/Arc.shared.svelte.js'; +// A `Waffle`'s layout (each row's outline, cell size, and color), for a layer's own `Waffle` +export { WaffleState, type WaffleItem } from './components/Waffle/Waffle.shared.svelte.js'; +// Where an `Image` or `Ellipse` is placed (pixel or data mode, motion), for a layer's own +export { ImageState } from './components/Image/Image.shared.svelte.js'; +export { EllipseState } from './components/Ellipse/Ellipse.shared.svelte.js'; +// `GeoBin`'s cells over the sphere, for `` +export { sphereBinning } from './components/geo/GeoBin/GeoBin.sphere.js'; +export { default as FacetAxisBase } from './components/FacetAxis.base.svelte'; +export type { FacetAxisBaseProps } from './components/FacetAxis.base.svelte'; +export { default as FacetPanelBase } from './components/FacetPanel.base.svelte'; +export type { FacetPanelBaseProps } from './components/FacetPanel.base.svelte'; +// A `Pattern`'s lines, circles, and rects, as its tile draws them +export { buildPatternShapes } from './components/Pattern/Pattern.shared.svelte.js'; + +// The rows a mark draws: its own `data`, else its series' or the chart's, narrowed to the facet +// panel it's drawn in +export { getFacetPanel, getMarkData } from './contexts/facet.js'; + +// What a data-mode mark tells the chart (its data and channels), so the chart's domains include it +export { circleMarkInfo } from './components/Circle/Circle.shared.svelte.js'; +export { lineMarkInfo } from './components/Line/Line.shared.svelte.js'; +export { polygonMarkInfo } from './components/Polygon/Polygon.shared.svelte.js'; +export { rectMarkInfo } from './components/Rect/Rect.shared.svelte.js'; +export { textMarkInfo } from './components/Text/Text.shared.svelte.js'; diff --git a/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte b/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte index d38bf7b835..e05da9251e 100644 --- a/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte +++ b/packages/layerchart/src/lib/components/ChartChildren/ChartChildren.base.svelte @@ -18,6 +18,14 @@ Rule: Component; Highlight: Component; ChartClipPath: Component; + /** The `points` drawn per series; LayerChart's own (loaded when first used) without it */ + Points?: Component; + /** The `labels` drawn per series; LayerChart's own (loaded when first used) without it */ + Labels?: Component; + /** The `annotations` drawn; LayerChart's own (loaded when first used) without it */ + ChartAnnotations?: Component; + /** The facet grid's headers; LayerChart's own without it */ + FacetAxis?: Component; }; export type ChartChildrenBaseProps< @@ -34,7 +42,7 @@ import { getChartContext } from '$lib/contexts/chart.js'; import { getSettings } from '$lib/contexts/settings.js'; import type { Facet } from '$lib/states/facet.svelte.js'; - import FacetAxis from '../FacetAxis.svelte'; + import FacetAxisCore from '../FacetAxis.svelte'; import { asAny } from '$lib/utils/types.js'; import { getObjectOrNull } from '$lib/utils/common.js'; @@ -48,6 +56,10 @@ Rule, Highlight, ChartClipPath, + Points: PointsProp, + Labels: LabelsProp, + ChartAnnotations: ChartAnnotationsProp, + FacetAxis = FacetAxisCore, props = {}, children: childrenProp, belowContext, @@ -100,7 +112,7 @@ {#if annotations.length > 0} - {#await import('../charts/ChartAnnotations.svelte') then { default: ChartAnnotations }} + {#await ChartAnnotationsProp ?? import('../charts/ChartAnnotations.svelte').then((m) => m.default) then ChartAnnotations} {/await} {/if} @@ -162,7 +174,7 @@ {#if typeof points === 'function'} {@render points(layerProps)} {:else if points} - {#await import('../Points/Points.svelte') then { default: Points }} + {#await PointsProp ?? import('../Points/Points.svelte').then((m) => m.default) then Points} {#each context.series.visibleSeries as s, i (s.key)} m.default) then Labels} {@const labelSeriesKey = typeof labels === 'object' ? labels.seriesKey : undefined} {#each context.series.visibleSeries.filter((s) => !labelSeriesKey || s.key === labelSeriesKey) as s, i (s.key)} @@ -192,7 +204,7 @@ {/if} {#if annotations.length > 0} - {#await import('../charts/ChartAnnotations.svelte') then { default: ChartAnnotations }} + {#await ChartAnnotationsProp ?? import('../charts/ChartAnnotations.svelte').then((m) => m.default) then ChartAnnotations} {/await} {/if} diff --git a/packages/layerchart/src/lib/components/FacetAxis.base.svelte b/packages/layerchart/src/lib/components/FacetAxis.base.svelte new file mode 100644 index 0000000000..296de9b6e4 --- /dev/null +++ b/packages/layerchart/src/lib/components/FacetAxis.base.svelte @@ -0,0 +1,74 @@ + + + + + +{#if ctx.facet.enabled && axis !== false && isFirstPanel} + {#if ctx.facet.xScale && ctx.facet.xDomain.length > 1} + + {/if} + + {#if ctx.facet.yScale && ctx.facet.yDomain.length > 1} + + + + + {/if} +{/if} diff --git a/packages/layerchart/src/lib/components/FacetAxis.svelte b/packages/layerchart/src/lib/components/FacetAxis.svelte index 785384848f..2a0878c015 100644 --- a/packages/layerchart/src/lib/components/FacetAxis.svelte +++ b/packages/layerchart/src/lib/components/FacetAxis.svelte @@ -1,63 +1,8 @@ - -{#if ctx.facet.enabled && axis !== false && isFirstPanel} - {#if ctx.facet.xScale && ctx.facet.xDomain.length > 1} - - {/if} - - {#if ctx.facet.yScale && ctx.facet.yDomain.length > 1} - - - - - {/if} -{/if} + + diff --git a/packages/layerchart/src/lib/components/FacetPanel.base.svelte b/packages/layerchart/src/lib/components/FacetPanel.base.svelte new file mode 100644 index 0000000000..8c001f4b04 --- /dev/null +++ b/packages/layerchart/src/lib/components/FacetPanel.base.svelte @@ -0,0 +1,26 @@ + + + + + + {@render children?.({ facet })} + diff --git a/packages/layerchart/src/lib/components/FacetPanel.svelte b/packages/layerchart/src/lib/components/FacetPanel.svelte index 13a0c571ea..80ff70aa81 100644 --- a/packages/layerchart/src/lib/components/FacetPanel.svelte +++ b/packages/layerchart/src/lib/components/FacetPanel.svelte @@ -9,17 +9,10 @@ - - {@render children?.({ facet })} - + diff --git a/packages/layerchart/src/lib/components/graph/Chord.svelte b/packages/layerchart/src/lib/components/graph/Chord.svelte index 3ee2c0ae15..ac2da53e6f 100644 --- a/packages/layerchart/src/lib/components/graph/Chord.svelte +++ b/packages/layerchart/src/lib/components/graph/Chord.svelte @@ -1,6 +1,6 @@ + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/AnnotationRange/AnnotationRange.webgl.svelte b/packages/webgl/src/lib/components/AnnotationRange/AnnotationRange.webgl.svelte new file mode 100644 index 0000000000..d90299bf07 --- /dev/null +++ b/packages/webgl/src/lib/components/AnnotationRange/AnnotationRange.webgl.svelte @@ -0,0 +1,13 @@ + + + + diff --git a/packages/webgl/src/lib/components/Arc/Arc.shared.svelte.ts b/packages/webgl/src/lib/components/Arc/Arc.shared.svelte.ts index 4408646a0a..4c00aca85d 100644 --- a/packages/webgl/src/lib/components/Arc/Arc.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Arc/Arc.shared.svelte.ts @@ -11,6 +11,10 @@ export type ArcTrackProps = { stroke?: string; /** @default 1 */ opacity?: number; + /** The fill's opacity (0 to 1). @default 1 */ + fillOpacity?: number; + /** The outline's opacity (0 to 1). @default 1 */ + strokeOpacity?: number; }; /** diff --git a/packages/webgl/src/lib/components/Arc/Arc.webgl.svelte b/packages/webgl/src/lib/components/Arc/Arc.webgl.svelte index 4e388e64e8..cd0438fb40 100644 --- a/packages/webgl/src/lib/components/Arc/Arc.webgl.svelte +++ b/packages/webgl/src/lib/components/Arc/Arc.webgl.svelte @@ -231,7 +231,12 @@ ), ] : [], - opacity: () => (trackLook?.opacity ?? 1) * (trackClassed?.opacity ?? 1), + // Its fill and outline each at their own opacity (ex. `ArcChart`'s `fillOpacity: 0.1`), as the + // core `Arc`'s track + opacity: () => + (trackLook?.opacity ?? 1) * (trackLook?.fillOpacity ?? 1) * (trackClassed?.opacity ?? 1), + lineOpacity: () => + (trackLook?.opacity ?? 1) * (trackLook?.strokeOpacity ?? 1) * (trackClassed?.opacity ?? 1), strokeWidth: () => strokeWidth, }); diff --git a/packages/webgl/src/lib/components/ArcLabel/ArcLabel.svelte b/packages/webgl/src/lib/components/ArcLabel/ArcLabel.svelte new file mode 100644 index 0000000000..1184014538 --- /dev/null +++ b/packages/webgl/src/lib/components/ArcLabel/ArcLabel.svelte @@ -0,0 +1,15 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/Area/Area.webgl.svelte b/packages/webgl/src/lib/components/Area/Area.webgl.svelte index e5be74fce6..19f41e874e 100644 --- a/packages/webgl/src/lib/components/Area/Area.webgl.svelte +++ b/packages/webgl/src/lib/components/Area/Area.webgl.svelte @@ -4,6 +4,7 @@ -{#if grouped} +{#if !visible} + +{:else if grouped} diff --git a/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts b/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts index d8b9fa6cc1..7c7c3e2552 100644 --- a/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts +++ b/packages/webgl/src/lib/components/Bar/Bar.shared.svelte.ts @@ -83,8 +83,8 @@ export type BarProps = { strokeWidth?: number; /** The stroke opacity (0 to 1). @default 1 */ strokeOpacity?: number; - /** The opacity (0 to 1). @default 1 */ - opacity?: number; + /** The opacity (0 to 1), or a bar's by its row (ex. fading other series). @default 1 */ + opacity?: number | ((d: any) => number); /** Click event handler, called with the bar's row (`{ data }`) */ onclick?: MarkEvents['onclick']; /** Double click event handler, called with the bar's row (`{ data }`) */ diff --git a/packages/webgl/src/lib/components/Bars/Bar.radial.svelte b/packages/webgl/src/lib/components/Bars/Bar.radial.svelte new file mode 100644 index 0000000000..50e391ccf1 --- /dev/null +++ b/packages/webgl/src/lib/components/Bars/Bar.radial.svelte @@ -0,0 +1,10 @@ + + + + diff --git a/packages/webgl/src/lib/components/Bars/Bars.base.svelte b/packages/webgl/src/lib/components/Bars/Bars.base.svelte index dca70c7e9b..3c15e2b691 100644 --- a/packages/webgl/src/lib/components/Bars/Bars.base.svelte +++ b/packages/webgl/src/lib/components/Bars/Bars.base.svelte @@ -6,6 +6,7 @@ + + + diff --git a/packages/webgl/src/lib/components/Bars/Bars.webgl.svelte b/packages/webgl/src/lib/components/Bars/Bars.webgl.svelte index f8bfc78d43..dd514202d6 100644 --- a/packages/webgl/src/lib/components/Bars/Bars.webgl.svelte +++ b/packages/webgl/src/lib/components/Bars/Bars.webgl.svelte @@ -5,6 +5,7 @@ + + diff --git a/packages/webgl/src/lib/components/Brush/Brush.svelte b/packages/webgl/src/lib/components/Brush/Brush.svelte new file mode 100644 index 0000000000..f41927dcad --- /dev/null +++ b/packages/webgl/src/lib/components/Brush/Brush.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Brush/Brush.webgl.svelte b/packages/webgl/src/lib/components/Brush/Brush.webgl.svelte new file mode 100644 index 0000000000..074a42898b --- /dev/null +++ b/packages/webgl/src/lib/components/Brush/Brush.webgl.svelte @@ -0,0 +1,62 @@ + + + + diff --git a/packages/webgl/src/lib/components/Chart/Chart.svelte b/packages/webgl/src/lib/components/Chart/Chart.svelte new file mode 100644 index 0000000000..af34e8ad6a --- /dev/null +++ b/packages/webgl/src/lib/components/Chart/Chart.svelte @@ -0,0 +1,17 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/ChartChildren/ChartAnnotations.svelte b/packages/webgl/src/lib/components/ChartChildren/ChartAnnotations.svelte new file mode 100644 index 0000000000..273944052a --- /dev/null +++ b/packages/webgl/src/lib/components/ChartChildren/ChartAnnotations.svelte @@ -0,0 +1,32 @@ + + +{#each visibleAnnotations as annotation} + {#if annotation.type === 'point'} + + {:else if annotation.type === 'line'} + + {:else if annotation.type === 'range'} + + {/if} +{/each} diff --git a/packages/webgl/src/lib/components/ChartChildren/ChartChildren.svelte b/packages/webgl/src/lib/components/ChartChildren/ChartChildren.svelte new file mode 100644 index 0000000000..33cabd0276 --- /dev/null +++ b/packages/webgl/src/lib/components/ChartChildren/ChartChildren.svelte @@ -0,0 +1,45 @@ + + + + diff --git a/packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.svelte b/packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.svelte new file mode 100644 index 0000000000..70b7b31103 --- /dev/null +++ b/packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.webgl.svelte b/packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.webgl.svelte new file mode 100644 index 0000000000..1a7098cc08 --- /dev/null +++ b/packages/webgl/src/lib/components/ChartClipPath/ChartClipPath.webgl.svelte @@ -0,0 +1,16 @@ + + + diff --git a/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte b/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte index 7509c9bb86..efb9a18e2a 100644 --- a/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte +++ b/packages/webgl/src/lib/components/Circle/Circle.webgl.svelte @@ -6,6 +6,7 @@ import { untrack } from 'svelte'; import { CircleGeometry, Color, SphereGeometry } from 'three'; import { getChartContext, isDataProp, resolveDataProp } from 'layerchart'; + import { getMarkData, circleMarkInfo } from 'layerchart/base'; import { getSceneContext } from '../../contexts/scene.svelte.js'; import { createInstances, ringGeometry, scaledDash } from '../../utils/instances.svelte.js'; import { dashPattern } from '../../utils/merged.svelte.js'; @@ -36,6 +37,8 @@ }: CircleProps = $props(); const ctx = getChartContext(); + /** Its rows in data mode, narrowed to the facet panel it's drawn in */ + const markData = getMarkData(); const scene = getSceneContext(); /** What its `class` sets */ const look = $derived(scene.style(className, style ? { style } : undefined)); @@ -53,6 +56,12 @@ /** With rows (`data`, or props reading the chart's), as the core `Circle` */ const dataMode = $derived(data != null || [cx, cy, r].some((p) => isDataProp(p))); + // Its data and channels, so the chart's domains include them, as the core `Circle` registers + ctx.registerComponent({ + name: 'Circle', + kind: 'mark', + markInfo: () => circleMarkInfo({ data, cx, cy, fill } as any, dataMode), + }); /** Raised by its `z`, or in data mode as the core `Circle`, by the chart's */ const raised = $derived(z != null || (dataMode && ctx.config.z != null)); @@ -60,7 +69,7 @@ /** Each row's circle as asked: its center, radius, and height */ const targets = $derived( // Through the scales as the core `Circle` (a band's start, ex. `Cell` centers it in a `Group`) - (dataMode ? markRows(ctx, data, cx, cy, r) : [undefined]).flatMap((d, i) => { + (dataMode ? markRows(markData, data, cx, cy, r) : [undefined]).flatMap((d, i) => { const [x, y] = positionOf(ctx, cx, cy, d, { bandStart: true }); const radius = resolveDataProp(r, d, ctx.rScale, 1); if (![x, y, radius].every(Number.isFinite) || radius <= 0) return []; diff --git a/packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.svelte b/packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.svelte new file mode 100644 index 0000000000..bb30ca1190 --- /dev/null +++ b/packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.svelte @@ -0,0 +1,23 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.webgl.svelte b/packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.webgl.svelte new file mode 100644 index 0000000000..f2de0a168e --- /dev/null +++ b/packages/webgl/src/lib/components/CircleClipPath/CircleClipPath.webgl.svelte @@ -0,0 +1,10 @@ + + + + diff --git a/packages/webgl/src/lib/components/ClipPath/ClipPath.svelte b/packages/webgl/src/lib/components/ClipPath/ClipPath.svelte new file mode 100644 index 0000000000..325a95ad6f --- /dev/null +++ b/packages/webgl/src/lib/components/ClipPath/ClipPath.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/ClipPath/ClipPath.webgl.svelte b/packages/webgl/src/lib/components/ClipPath/ClipPath.webgl.svelte new file mode 100644 index 0000000000..81497bf0ae --- /dev/null +++ b/packages/webgl/src/lib/components/ClipPath/ClipPath.webgl.svelte @@ -0,0 +1,145 @@ + + + + +{#if clipShapes && !path} + +{/if} +{@render children?.({ id, url, useId })} diff --git a/packages/webgl/src/lib/components/ClipPath/ClipShapes.svelte b/packages/webgl/src/lib/components/ClipPath/ClipShapes.svelte new file mode 100644 index 0000000000..38c63139cd --- /dev/null +++ b/packages/webgl/src/lib/components/ClipPath/ClipShapes.svelte @@ -0,0 +1,42 @@ + + + + diff --git a/packages/webgl/src/lib/components/Ellipse/Ellipse.svelte b/packages/webgl/src/lib/components/Ellipse/Ellipse.svelte new file mode 100644 index 0000000000..cef1775753 --- /dev/null +++ b/packages/webgl/src/lib/components/Ellipse/Ellipse.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Ellipse/Ellipse.webgl.svelte b/packages/webgl/src/lib/components/Ellipse/Ellipse.webgl.svelte new file mode 100644 index 0000000000..45b8d62f1d --- /dev/null +++ b/packages/webgl/src/lib/components/Ellipse/Ellipse.webgl.svelte @@ -0,0 +1,109 @@ + + + + diff --git a/packages/webgl/src/lib/components/FacetAxis/FacetAxis.svelte b/packages/webgl/src/lib/components/FacetAxis/FacetAxis.svelte new file mode 100644 index 0000000000..ac65ab27c5 --- /dev/null +++ b/packages/webgl/src/lib/components/FacetAxis/FacetAxis.svelte @@ -0,0 +1,8 @@ + + + + diff --git a/packages/webgl/src/lib/components/GeoBin/GeoBin.cells.ts b/packages/webgl/src/lib/components/GeoBin/GeoBin.cells.ts new file mode 100644 index 0000000000..6901f281c7 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoBin/GeoBin.cells.ts @@ -0,0 +1,31 @@ +import { getContext, setContext } from 'svelte'; + +/** One of a `GeoBin`'s paths (a cell, a column's side, its grid), with how it's painted */ +export type BinPath = { + readonly pathData: string | undefined; + readonly z: number; + readonly fill: string | undefined; + readonly fillOpacity: number; + readonly stroke: string | undefined; + readonly strokeOpacity: number; + readonly strokeWidth: number | undefined; + readonly opacity: number; + readonly class: string | undefined; + readonly onclick: ((e: MouseEvent) => void) | undefined; + readonly onpointerenter: ((e: PointerEvent) => void) | undefined; + readonly onpointermove: ((e: PointerEvent) => void) | undefined; + readonly onpointerleave: ((e: PointerEvent) => void) | undefined; +}; + +/** The paths a `GeoBin` draws, in order, and a count bumped (`bump`) as they come and go */ +export type BinPaths = { list: BinPath[]; readonly version: number; bump: () => void }; + +const KEY = Symbol('LayerChartWebGLBinPaths'); + +export function setBinPaths(paths: BinPaths) { + setContext(KEY, paths); +} + +export function getBinPaths(): BinPaths { + return getContext(KEY); +} diff --git a/packages/webgl/src/lib/components/GeoBin/GeoBin.path.svelte b/packages/webgl/src/lib/components/GeoBin/GeoBin.path.svelte new file mode 100644 index 0000000000..eae1c88b75 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoBin/GeoBin.path.svelte @@ -0,0 +1,85 @@ + diff --git a/packages/webgl/src/lib/components/GeoBin/GeoBin.svelte b/packages/webgl/src/lib/components/GeoBin/GeoBin.svelte new file mode 100644 index 0000000000..cd981d2b1e --- /dev/null +++ b/packages/webgl/src/lib/components/GeoBin/GeoBin.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/GeoBin/GeoBin.webgl.svelte b/packages/webgl/src/lib/components/GeoBin/GeoBin.webgl.svelte new file mode 100644 index 0000000000..f96d6af874 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoBin/GeoBin.webgl.svelte @@ -0,0 +1,132 @@ + + + + diff --git a/packages/webgl/src/lib/components/GeoCircle/GeoCircle.svelte b/packages/webgl/src/lib/components/GeoCircle/GeoCircle.svelte new file mode 100644 index 0000000000..148c6e8b9d --- /dev/null +++ b/packages/webgl/src/lib/components/GeoCircle/GeoCircle.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/GeoCircle/GeoCircle.webgl.svelte b/packages/webgl/src/lib/components/GeoCircle/GeoCircle.webgl.svelte new file mode 100644 index 0000000000..37a0913095 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoCircle/GeoCircle.webgl.svelte @@ -0,0 +1,10 @@ + + + + diff --git a/packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.svelte b/packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.svelte new file mode 100644 index 0000000000..ebba2c5016 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.webgl.svelte b/packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.webgl.svelte new file mode 100644 index 0000000000..6b59954ee3 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoClipPath/GeoClipPath.webgl.svelte @@ -0,0 +1,10 @@ + + + + diff --git a/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.group.svelte b/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.group.svelte new file mode 100644 index 0000000000..de23a7e765 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.group.svelte @@ -0,0 +1,9 @@ + + + diff --git a/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.svelte b/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.svelte new file mode 100644 index 0000000000..e21322c870 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.webgl.svelte b/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.webgl.svelte new file mode 100644 index 0000000000..684d0c5292 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoEdgeFade/GeoEdgeFade.webgl.svelte @@ -0,0 +1,11 @@ + + + + diff --git a/packages/webgl/src/lib/components/GeoSpline/GeoSpline.svelte b/packages/webgl/src/lib/components/GeoSpline/GeoSpline.svelte new file mode 100644 index 0000000000..993c2a0d32 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoSpline/GeoSpline.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/GeoSpline/GeoSpline.webgl.svelte b/packages/webgl/src/lib/components/GeoSpline/GeoSpline.webgl.svelte new file mode 100644 index 0000000000..6915a7f674 --- /dev/null +++ b/packages/webgl/src/lib/components/GeoSpline/GeoSpline.webgl.svelte @@ -0,0 +1,10 @@ + + + + diff --git a/packages/webgl/src/lib/components/Image/Image.svelte b/packages/webgl/src/lib/components/Image/Image.svelte new file mode 100644 index 0000000000..aa638a7c3e --- /dev/null +++ b/packages/webgl/src/lib/components/Image/Image.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Image/Image.webgl.svelte b/packages/webgl/src/lib/components/Image/Image.webgl.svelte new file mode 100644 index 0000000000..9bf356bb95 --- /dev/null +++ b/packages/webgl/src/lib/components/Image/Image.webgl.svelte @@ -0,0 +1,347 @@ + + + + diff --git a/packages/webgl/src/lib/components/Line/Line.webgl.svelte b/packages/webgl/src/lib/components/Line/Line.webgl.svelte index f2076f6fc8..2358802dbd 100644 --- a/packages/webgl/src/lib/components/Line/Line.webgl.svelte +++ b/packages/webgl/src/lib/components/Line/Line.webgl.svelte @@ -6,6 +6,7 @@ + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/LinearGradient/LinearGradient.webgl.svelte b/packages/webgl/src/lib/components/LinearGradient/LinearGradient.webgl.svelte new file mode 100644 index 0000000000..71e5070ffe --- /dev/null +++ b/packages/webgl/src/lib/components/LinearGradient/LinearGradient.webgl.svelte @@ -0,0 +1,60 @@ + + + +{@render children?.({ id, gradient: `url(#${id})` })} diff --git a/packages/webgl/src/lib/components/Link/Link.webgl.svelte b/packages/webgl/src/lib/components/Link/Link.webgl.svelte index 217254ca15..073b06d954 100644 --- a/packages/webgl/src/lib/components/Link/Link.webgl.svelte +++ b/packages/webgl/src/lib/components/Link/Link.webgl.svelte @@ -4,8 +4,9 @@ + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Pattern/Pattern.webgl.svelte b/packages/webgl/src/lib/components/Pattern/Pattern.webgl.svelte new file mode 100644 index 0000000000..08ac5a722a --- /dev/null +++ b/packages/webgl/src/lib/components/Pattern/Pattern.webgl.svelte @@ -0,0 +1,46 @@ + + + +{@render children?.({ id, pattern: `url(#${id})` })} diff --git a/packages/webgl/src/lib/components/Points/Points.base.svelte b/packages/webgl/src/lib/components/Points/Points.base.svelte index bdeb1ca59a..b0e660e36e 100644 --- a/packages/webgl/src/lib/components/Points/Points.base.svelte +++ b/packages/webgl/src/lib/components/Points/Points.base.svelte @@ -5,6 +5,7 @@ {#if inScene} - + {:else} {/if} diff --git a/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte b/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte index 5276d13496..aa53f59c1b 100644 --- a/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte +++ b/packages/webgl/src/lib/components/Polygon/Polygon.webgl.svelte @@ -5,6 +5,7 @@ + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/RectClipPath/RectClipPath.webgl.svelte b/packages/webgl/src/lib/components/RectClipPath/RectClipPath.webgl.svelte new file mode 100644 index 0000000000..d8f422067c --- /dev/null +++ b/packages/webgl/src/lib/components/RectClipPath/RectClipPath.webgl.svelte @@ -0,0 +1,10 @@ + + + + diff --git a/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte b/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte index c054677353..9ce1997d3b 100644 --- a/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte +++ b/packages/webgl/src/lib/components/Rule/Rule.webgl.svelte @@ -6,6 +6,7 @@ {#if inScene} - + {:else} {/if} diff --git a/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte b/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte index 5eb8a8a134..9024ca0c90 100644 --- a/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte +++ b/packages/webgl/src/lib/components/Spline/Spline.webgl.svelte @@ -33,8 +33,9 @@ @@ -105,6 +106,8 @@ : verticalAnchorProp ); const ctx = getChartContext(); + /** Its rows in data mode, narrowed to the facet panel it's drawn in */ + const markData = getMarkData(); const scene = getSceneContext(); /** A font's cap height in its size, as the core `Text` takes it (`0.71em`) */ const CAP_HEIGHT = 0.71; @@ -134,6 +137,12 @@ /** With rows (`data`, or `x` / `y` reading the chart's), as the core `Text` */ const dataMode = $derived(data != null || isDataProp(x) || isDataProp(y)); + // Its data and channels, so the chart's domains include them, as the core `Text` registers + ctx.registerComponent({ + name: 'Text', + kind: 'mark', + markInfo: () => textMarkInfo({ data, x, y, fill: fillProp } as any, dataMode), + }); const xProp = $derived(x ?? (dataMode ? (ctx.config.x as DataProp) : undefined)); const yProp = $derived(y ?? (dataMode ? (ctx.config.y as DataProp) : undefined)); const zProp = $derived(z ?? (dataMode ? (ctx.config.z as DataProp) : undefined)); @@ -162,7 +171,7 @@ /** Each row's label as asked: its text and place */ const targets = $derived( - (dataMode ? markRows(ctx, data, xProp, yProp) : [undefined]).flatMap((d, i) => { + (dataMode ? markRows(markData, data, xProp, yProp) : [undefined]).flatMap((d, i) => { const text = pieces ? pieces.map((piece) => piece.text).join('') : typeof value === 'number' && tweensValue && !dataMode diff --git a/packages/webgl/src/lib/components/Vector/Vector.webgl.svelte b/packages/webgl/src/lib/components/Vector/Vector.webgl.svelte index b30d8501da..547934db3d 100644 --- a/packages/webgl/src/lib/components/Vector/Vector.webgl.svelte +++ b/packages/webgl/src/lib/components/Vector/Vector.webgl.svelte @@ -1,5 +1,6 @@ @@ -54,6 +55,8 @@ }: VectorProps = $props(); const ctx = getChartContext(); + /** Its rows in data mode, narrowed to the facet panel it's drawn in */ + const markData = getMarkData(); const scene = getSceneContext(); /** What its `class` sets, where its props don't say (a row's own, for a function of the row) */ const look = $derived(typeof className === 'function' ? null : scene.style(className)); @@ -64,7 +67,7 @@ const filled = $derived(shape !== 'arrow'); const dataMode = $derived(hasAnyDataProp(x, y, length, rotate, tilt, z)); const rows = $derived( - dataMode ? markRows(ctx, data, x, y, length, rotate, tilt, z) : [undefined] + dataMode ? markRows(markData, data, x, y, length, rotate, tilt, z) : [undefined] ); /** A number prop, or a row's raw value for it (an angle, not through a scale) */ diff --git a/packages/webgl/src/lib/components/Voronoi/Voronoi.svelte b/packages/webgl/src/lib/components/Voronoi/Voronoi.svelte new file mode 100644 index 0000000000..691e0e854e --- /dev/null +++ b/packages/webgl/src/lib/components/Voronoi/Voronoi.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Voronoi/Voronoi.webgl.svelte b/packages/webgl/src/lib/components/Voronoi/Voronoi.webgl.svelte new file mode 100644 index 0000000000..fea59730e0 --- /dev/null +++ b/packages/webgl/src/lib/components/Voronoi/Voronoi.webgl.svelte @@ -0,0 +1,12 @@ + + + + diff --git a/packages/webgl/src/lib/components/Waffle/Waffle.svelte b/packages/webgl/src/lib/components/Waffle/Waffle.svelte new file mode 100644 index 0000000000..826b3944b5 --- /dev/null +++ b/packages/webgl/src/lib/components/Waffle/Waffle.svelte @@ -0,0 +1,20 @@ + + + + +{#if inScene} + +{:else} + +{/if} diff --git a/packages/webgl/src/lib/components/Waffle/Waffle.webgl.svelte b/packages/webgl/src/lib/components/Waffle/Waffle.webgl.svelte new file mode 100644 index 0000000000..194c396569 --- /dev/null +++ b/packages/webgl/src/lib/components/Waffle/Waffle.webgl.svelte @@ -0,0 +1,251 @@ + + + + + +{#if rounded} + { + const r = (bar as Instance & { radius: number }).radius; + return [r, r, r, r]; + }} + height={0.1} + stroke={() => null} + strokeWidth={0} + opacity={fillAlpha} + tooltip={!!tooltip} + {events} + /> +{/if} diff --git a/packages/webgl/src/lib/components/__fixtures__/Clips.svelte b/packages/webgl/src/lib/components/__fixtures__/Clips.svelte new file mode 100644 index 0000000000..55049627a7 --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/Clips.svelte @@ -0,0 +1,138 @@ + + +{#snippet fill()} + + +{/snippet} + +
+ + {#snippet children({ context }: { context: ChartState })} + + {#if clip === 'rect'} + + {@render fill()} + + {:else if clip === 'circle'} + + {@render fill()} + + {:else if clip === 'path'} + + + {@render fill()} + + {:else if clip === 'snippet'} + + + {#snippet clip()} + + + {/snippet} + {@render fill()} + + {:else if clip === 'elements'} + + + {#snippet clip()} + + + + + {/snippet} + {@render fill()} + + {:else if clip === 'geo'} + + {@render fill()} + + {:else if clip === 'chart'} + + {@render fill()} + + {:else if clip === 'crossing'} + + 0} + fill="red" + line={false} + /> + {:else if clip === 'labels'} + + + + + + {/if} + + + {/snippet} + +
diff --git a/packages/webgl/src/lib/components/__fixtures__/Components8.svelte b/packages/webgl/src/lib/components/__fixtures__/Components8.svelte new file mode 100644 index 0000000000..90386f8f4d --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/Components8.svelte @@ -0,0 +1,69 @@ + + +
+ {#if mark === 'waffle'} + + + + + + + {:else if mark === 'geobin'} + + + + + + + {:else} + + + + {#if mark === 'ellipse'} + + {:else if mark === 'image'} + + {:else} + + {/if} + + + {/if} +
diff --git a/packages/webgl/src/lib/components/__fixtures__/Paints.svelte b/packages/webgl/src/lib/components/__fixtures__/Paints.svelte new file mode 100644 index 0000000000..38bb84cee6 --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/Paints.svelte @@ -0,0 +1,60 @@ + + +
+ + + {#if mark === 'plain-rect'} + + {:else if mark === 'pattern'} + + {#snippet children({ pattern })} + + {/snippet} + + {:else} + + {#snippet children({ gradient })} + {#if mark === 'rect'} + + {:else if mark === 'area'} + + {:else} + + {/if} + {/snippet} + + {/if} + + + +
diff --git a/packages/webgl/src/lib/components/__fixtures__/SimplifiedChart.svelte b/packages/webgl/src/lib/components/__fixtures__/SimplifiedChart.svelte new file mode 100644 index 0000000000..af217591f4 --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/SimplifiedChart.svelte @@ -0,0 +1,24 @@ + + +
+ {#if chart === 'bar'} + + {:else if chart === 'line'} + + {:else} + + {/if} +
diff --git a/packages/webgl/src/lib/components/__fixtures__/ThrelteProbe.svelte b/packages/webgl/src/lib/components/__fixtures__/ThrelteProbe.svelte new file mode 100644 index 0000000000..2f45a6663f --- /dev/null +++ b/packages/webgl/src/lib/components/__fixtures__/ThrelteProbe.svelte @@ -0,0 +1,26 @@ + diff --git a/packages/webgl/src/lib/components/charts.svelte.test.ts b/packages/webgl/src/lib/components/charts.svelte.test.ts new file mode 100644 index 0000000000..65558f8704 --- /dev/null +++ b/packages/webgl/src/lib/components/charts.svelte.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +import SimplifiedChart from './__fixtures__/SimplifiedChart.svelte'; + +describe('simplified charts', () => { + it.each(['bar', 'line', 'pie'] as const)( + 'draws a %s chart, its axes and marks, in a WebGL layer', + async (chart) => { + const { container } = render(SimplifiedChart, { chart }); + // A WebGL canvas, and none of LayerChart's SVG or Canvas layers drawing in its place + await expect + .poll(() => [...container.querySelectorAll('canvas')].some((c) => !c.getContext('2d'))) + .toBe(true); + // (an `Svg` of the tooltip's hit areas aside, as every layer has) + expect(container.querySelector('svg path, svg text')).toBeNull(); + expect(container.querySelector('.lc-layout-canvas canvas')).toBeNull(); + } + ); +}); diff --git a/packages/webgl/src/lib/components/charts/ArcChart.svelte b/packages/webgl/src/lib/components/charts/ArcChart.svelte new file mode 100644 index 0000000000..18ed60f135 --- /dev/null +++ b/packages/webgl/src/lib/components/charts/ArcChart.svelte @@ -0,0 +1,17 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/charts/AreaChart.svelte b/packages/webgl/src/lib/components/charts/AreaChart.svelte new file mode 100644 index 0000000000..cc18358115 --- /dev/null +++ b/packages/webgl/src/lib/components/charts/AreaChart.svelte @@ -0,0 +1,15 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/charts/BarChart.svelte b/packages/webgl/src/lib/components/charts/BarChart.svelte new file mode 100644 index 0000000000..69521ecd8c --- /dev/null +++ b/packages/webgl/src/lib/components/charts/BarChart.svelte @@ -0,0 +1,15 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/charts/LineChart.svelte b/packages/webgl/src/lib/components/charts/LineChart.svelte new file mode 100644 index 0000000000..57b7de2aa5 --- /dev/null +++ b/packages/webgl/src/lib/components/charts/LineChart.svelte @@ -0,0 +1,15 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/charts/PieChart.svelte b/packages/webgl/src/lib/components/charts/PieChart.svelte new file mode 100644 index 0000000000..ef392ee392 --- /dev/null +++ b/packages/webgl/src/lib/components/charts/PieChart.svelte @@ -0,0 +1,18 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/charts/ScatterChart.svelte b/packages/webgl/src/lib/components/charts/ScatterChart.svelte new file mode 100644 index 0000000000..095b1b3ab4 --- /dev/null +++ b/packages/webgl/src/lib/components/charts/ScatterChart.svelte @@ -0,0 +1,15 @@ + + + + + + diff --git a/packages/webgl/src/lib/components/clipping-r8.svelte.test.ts b/packages/webgl/src/lib/components/clipping-r8.svelte.test.ts new file mode 100644 index 0000000000..adf2c0c617 --- /dev/null +++ b/packages/webgl/src/lib/components/clipping-r8.svelte.test.ts @@ -0,0 +1,306 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import type { Material, Mesh, Object3D, WebGLRenderer } from 'three'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import Clips from './__fixtures__/Clips.svelte'; + +type Threlte = { scene: SceneState; render: () => void; renderer: WebGLRenderer }; + +/** Render a clip around a red rectangle filling the plot (and past it) */ +async function renderClip(props: Omit>[1], 'onThrelte'>) { + let threlte: Threlte | undefined; + render(Clips, { ...(props as any), onThrelte: (t: Threlte) => (threlte = t) }); + await expect.poll(() => meshes(threlte?.scene).length).toBeGreaterThan(0); + return threlte!; +} + +function meshes(scene: SceneState | undefined) { + const found: Mesh[] = []; + scene?.root.traverse((o: Object3D) => { + if ((o as Mesh).isMesh) found.push(o as Mesh); + }); + return found; +} + +/** + * Whether the frame is painted at points of the chart (pixels across and down its 400 × 300), + * drawn now and read before the browser shows it + */ +function painted(threlte: Threlte, points: [number, number][]) { + threlte.render(); + const gl = threlte.renderer.getContext(); + const k = gl.drawingBufferWidth / 400; + return points.map(([x, y]) => { + const pixel = new Uint8Array(4); + gl.readPixels( + Math.round(x * k), + Math.round(gl.drawingBufferHeight - y * k), + 1, + 1, + gl.RGBA, + gl.UNSIGNED_BYTE, + pixel + ); + return pixel[3] > 128; + }); +} + +/** Painted where expected, once the clip's ready (a mask's code loads first) */ +async function expectPainted(threlte: Threlte, points: [number, number][], expected: boolean[]) { + await expect.poll(() => painted(threlte, points)).toEqual(expected); +} + +describe('RectClipPath', () => { + it('clips to its rectangle with planes', async () => { + const threlte = await renderClip({ clip: 'rect' }); + await expectPainted( + threlte, + [ + [50, 50], + [150, 50], + [50, 150], + [300, 250], + ], + [true, false, false, false] + ); + const material = meshes(threlte.scene)[0].material as Material; + expect(material.clippingPlanes).toHaveLength(4); + expect(material.userData.lcMask).toBeUndefined(); + }); + + it('draws everything when `disabled`', async () => { + const threlte = await renderClip({ clip: 'rect', disabled: true }); + await expectPainted( + threlte, + [ + [50, 50], + [300, 250], + ], + [true, true] + ); + }); + + it('draws only outside its rectangle when `invert`', async () => { + const threlte = await renderClip({ clip: 'rect', invert: true }); + await expectPainted( + threlte, + [ + [50, 50], + [150, 50], + [300, 250], + ], + [false, true, true] + ); + }); +}); + +describe('CircleClipPath', () => { + it('clips to its circle, not its bounds', async () => { + const threlte = await renderClip({ clip: 'circle' }); + // Its center, past its edge, and inside its bounds' corner but outside the circle + await expectPainted( + threlte, + [ + [200, 150], + [260, 150], + [240, 190], + [20, 20], + ], + [true, false, false, false] + ); + }); + + it('draws only outside its circle when `invert`', async () => { + const threlte = await renderClip({ clip: 'circle', invert: true }); + await expectPainted( + threlte, + [ + [200, 150], + [240, 190], + [20, 20], + ], + [false, true, true] + ); + }); +}); + +describe('ClipPath', () => { + it('clips to its `path`', async () => { + const threlte = await renderClip({ clip: 'path' }); + await expectPainted( + threlte, + [ + [50, 50], + [350, 250], + [300, 50], + [100, 250], + ], + [true, false, true, false] + ); + }); +}); + +describe('ClipPath with a `clip` snippet', () => { + it('clips to its marks’ shapes, drawing none of them', async () => { + const threlte = await renderClip({ clip: 'snippet' }); + await expectPainted( + threlte, + [ + [50, 50], + [200, 150], + [150, 50], + [240, 190], + [350, 250], + ], + [true, true, false, false, false] + ); + // None of its marks in the scene: only what the clipped rectangle draws, as clipped otherwise + const shown = meshes(threlte.scene).length; + const plain = await renderClip({ clip: 'rect' }); + expect(shown).toBe(meshes(plain.scene).length); + }); +}); + +describe('ClipPath with SVG elements in its `clip` snippet', () => { + it('clips to their shapes', async () => { + const threlte = await renderClip({ clip: 'elements' }); + await expectPainted( + threlte, + [ + [50, 50], + [200, 150], + [150, 50], + [240, 190], + [350, 250], + ], + [true, true, false, false, false] + ); + }); +}); + +describe('GeoClipPath', () => { + it('clips to its `geojson`, through the projection (centered on the plot)', async () => { + const threlte = await renderClip({ clip: 'geo' }); + await expectPainted( + threlte, + [ + [250, 200], + [150, 200], + [350, 200], + [50, 50], + ], + [true, false, false, false] + ); + }); + + it('draws only outside it when `invert`', async () => { + const threlte = await renderClip({ clip: 'geo', invert: true }); + await expectPainted( + threlte, + [ + [250, 200], + [150, 200], + [350, 200], + [50, 50], + ], + [false, true, true, true] + ); + }); +}); + +describe('ChartClipPath', () => { + const padding = { left: 50, top: 50, right: 50, bottom: 50 }; + + it('clips to the plot, though the scene doesn’t', async () => { + const threlte = await renderClip({ clip: 'chart', padding }); + await expectPainted( + threlte, + [ + [200, 150], + [25, 150], + [200, 25], + ], + [true, false, false] + ); + }); + + it('clips to the chart, with its padding, when `full`', async () => { + const threlte = await renderClip({ clip: 'chart', padding, full: true }); + await expectPainted( + threlte, + [ + [200, 150], + [25, 150], + [200, 25], + ], + [true, true, true] + ); + }); + + it('draws everything when `disabled`', async () => { + const threlte = await renderClip({ clip: 'chart', padding, disabled: true }); + await expectPainted( + threlte, + [ + [200, 150], + [25, 150], + ], + [true, true] + ); + }); +}); + +/** Whether any pixel is painted in a box of the chart (`[x0, y0, x1, y1]`), drawn now */ +function paintedIn(threlte: Threlte, [x0, y0, x1, y1]: [number, number, number, number]) { + threlte.render(); + const gl = threlte.renderer.getContext(); + const k = gl.drawingBufferWidth / 400; + const width = Math.round((x1 - x0) * k); + const height = Math.round((y1 - y0) * k); + const pixels = new Uint8Array(width * height * 4); + gl.readPixels( + Math.round(x0 * k), + Math.round(gl.drawingBufferHeight - y1 * k), + width, + height, + gl.RGBA, + gl.UNSIGNED_BYTE, + pixels + ); + for (let i = 3; i < pixels.length; i += 4) if (pixels[i] > 128) return true; + return false; +} + +describe('Clipped labels', () => { + it('clips a label sharing its painting with one that isn’t', async () => { + const threlte = await renderClip({ clip: 'labels' }); + // Both labels' planes, each with its own material: one clipped away, the other drawn + await expect.poll(() => meshes(threlte.scene).length).toBe(2); + await expect + .poll(() => [ + paintedIn(threlte, [90, 100, 300, 160]), + paintedIn(threlte, [90, 200, 300, 260]), + ]) + .toEqual([false, true]); + const [a, b] = meshes(threlte.scene); + expect(a.material).not.toBe(b.material); + }); +}); + +describe('Area', () => { + it('fills both sides of its baseline where its line crosses it, not a quad folded over', async () => { + const threlte = await renderClip({ clip: 'crossing' }); + // Its top falls from 10 to -10 across the plot, crossing its zero baseline at the middle + await expectPainted( + threlte, + [ + [100, 130], + [300, 130], + [300, 170], + [100, 170], + ], + [true, false, true, false] + ); + }); +}); diff --git a/packages/webgl/src/lib/components/components-r8.svelte.test.ts b/packages/webgl/src/lib/components/components-r8.svelte.test.ts new file mode 100644 index 0000000000..c389d6e4f6 --- /dev/null +++ b/packages/webgl/src/lib/components/components-r8.svelte.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { Box3, Matrix4, type BufferGeometry, type InstancedMesh, type Mesh, type Object3D } from 'three'; +import * as core from 'layerchart'; +import type { BrushState, ChartState } from 'layerchart'; + +import * as webgl from '../index.js'; +import type { SceneState } from '../contexts/scene.svelte.js'; +import Components8 from './__fixtures__/Components8.svelte'; + +let chart: ChartState | undefined; + +async function renderMark(props: Omit>[1], 'onScene'>) { + let scene: SceneState | undefined; + const result = render(Components8, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return { scene: scene!, result }; +} + +function all(scene: SceneState, is: (o: any) => boolean): T[] { + const found: T[] = []; + scene.root.traverse((o: Object3D) => { + if (is(o)) found.push(o as T); + }); + return found; +} + +/** The bounds of the mesh vertices a mark drew, in the chart's pixels (`x` across, `z` down) */ +function drawnBounds(scene: SceneState) { + const box = new Box3(); + for (const mesh of all(scene, (o) => o.isMesh && !o.isInstancedMesh)) { + const geometry = mesh.geometry as BufferGeometry; + if (!geometry.getAttribute('position')?.count) continue; + geometry.computeBoundingBox(); + box.union(geometry.boundingBox!); + } + return box; +} + +describe('re-exports', () => { + it("hands out LayerChart's contexts and layouts as they are", () => { + expect(webgl.ChartGroup).toBe(core.ChartGroup); + expect(webgl.Dodge).toBe(core.Dodge); + expect(webgl.Point).toBe(core.Point); + expect(webgl.Bounds).toBe(core.Bounds); + }); +}); + +describe('Waffle', () => { + it('draws a cell for each unit, the last cut short at a fractional value', async () => { + const { scene } = await renderMark({ + mark: 'waffle', + data: [{ x: 'a', y: 2.5 }], + markProps: { unit: 1, multiple: 1, gap: 0 }, + }); + let cells: InstancedMesh[] = []; + await expect + .poll(() => { + cells = all(scene, (o) => o.isInstancedMesh && o.count > 0); + return cells[0]?.count ?? 0; + }) + .toBe(3); + const depths = [0, 1, 2].map((i) => { + const m = new Matrix4(); + cells[0].getMatrixAt(i, m); + // Scaled by each cell's depth (down the plot) along its third column + return Math.hypot(m.elements[8], m.elements[9], m.elements[10]); + }); + // 300 pixels for 100 units: 3 pixels a cell, the last half that + expect(depths[0]).toBeCloseTo(3, 1); + expect(depths[1]).toBeCloseTo(3, 1); + expect(depths[2]).toBeCloseTo(1.5, 1); + }); + + it('draws rounded cells as shapes', async () => { + const { scene } = await renderMark({ + mark: 'waffle', + data: [{ x: 'a', y: 4 }], + markProps: { unit: 1, multiple: 2, rx: '100%' }, + }); + await expect.poll(() => drawnBounds(scene).isEmpty()).toBe(false); + expect(all(scene, (o) => o.isInstancedMesh && o.count > 0)).toHaveLength(0); + }); +}); + +describe('GeoBin', () => { + it("draws its cells together, in one mesh, each in its cell's color", async () => { + const data = [ + { lon: 0, lat: 0 }, + { lon: 60, lat: 30 }, + { lon: -90, lat: -40 }, + { lon: 120, lat: 10 }, + ]; + const { scene } = await renderMark({ mark: 'geobin', data, markProps: { size: 30 } }); + const filled = () => + all( + scene, + (o) => + o.isMesh && + !o.isInstancedMesh && + !o.isLineSegments2 && + o.geometry.getAttribute('position')?.count > 0 + ); + await expect.poll(() => filled().length).toBe(1); + const colors = filled()[0].geometry.getAttribute('color'); + // Four cells, each its own shape (several vertices each) + expect(colors.count).toBeGreaterThanOrEqual(4 * 3); + }); +}); + +describe('Ellipse', () => { + it('spans its `rx` across and `ry` down', async () => { + const { scene } = await renderMark({ + mark: 'ellipse', + markProps: { cx: 100, cy: 100, rx: 20, ry: 10, fill: 'red' }, + }); + await expect.poll(() => drawnBounds(scene).isEmpty()).toBe(false); + const box = drawnBounds(scene); + expect(box.max.x - box.min.x).toBeCloseTo(40, 0); + expect(box.max.z - box.min.z).toBeCloseTo(20, 0); + expect((box.min.x + box.max.x) / 2).toBeCloseTo(100, 0); + }); + + it('turns by `rotate`', async () => { + const { scene } = await renderMark({ + mark: 'ellipse', + markProps: { cx: 100, cy: 100, rx: 20, ry: 10, rotate: 90, fill: 'red' }, + }); + await expect.poll(() => drawnBounds(scene).isEmpty()).toBe(false); + const box = drawnBounds(scene); + expect(box.max.x - box.min.x).toBeCloseTo(20, 0); + expect(box.max.z - box.min.z).toBeCloseTo(40, 0); + }); +}); + +/** A 2 × 1 image */ +function wideImage() { + const canvas = document.createElement('canvas'); + canvas.width = 20; + canvas.height = 10; + const context = canvas.getContext('2d')!; + context.fillStyle = 'red'; + context.fillRect(0, 0, 20, 10); + return canvas.toDataURL(); +} + +describe('Image', () => { + it('fits the image in its box, as `preserveAspectRatio="xMidYMid meet"`', async () => { + const { scene } = await renderMark({ + mark: 'image', + markProps: { href: wideImage(), x: 100, y: 100, width: 40, height: 40 }, + }); + await expect.poll(() => drawnBounds(scene).isEmpty()).toBe(false); + const box = drawnBounds(scene); + expect(box.max.x - box.min.x).toBeCloseTo(40, 1); + expect(box.max.z - box.min.z).toBeCloseTo(20, 1); + }); + + it('fills its circle `r`, as `preserveAspectRatio="xMidYMid slice"`', async () => { + const { scene } = await renderMark({ + mark: 'image', + markProps: { href: wideImage(), x: 100, y: 100, r: 15, preserveAspectRatio: 'xMidYMid slice' }, + }); + await expect.poll(() => drawnBounds(scene).isEmpty()).toBe(false); + const box = drawnBounds(scene); + expect(box.max.x - box.min.x).toBeCloseTo(30, 0); + expect(box.max.z - box.min.z).toBeCloseTo(30, 0); + }); +}); + +describe('Brush', () => { + it('brushes a selection by dragging over the scene', async () => { + let brush: BrushState | undefined; + const { result } = await renderMark({ mark: 'brush', onBrush: (b: BrushState | undefined) => (brush = b) }); + await expect.poll(() => brush).toBeDefined(); + const container = result.container.querySelector('.lc-root-container') as HTMLElement | null; + const target = (container ?? chart!.containerRef)!; + const rect = target.getBoundingClientRect(); + const at = (type: string, x: number) => + new PointerEvent(type, { + clientX: rect.left + x, + clientY: rect.top + 150, + bubbles: true, + pointerId: 1, + buttons: type === 'pointerup' ? 0 : 1, + }); + chart!.containerRef!.querySelector('canvas')!.dispatchEvent(at('pointerdown', 100)); + window.dispatchEvent(at('pointermove', 200)); + window.dispatchEvent(at('pointerup', 200)); + await expect.poll(() => brush?.active).toBe(true); + // 400 pixels for 0 to 10 + expect(Number(brush!.x[0])).toBeCloseTo(2.5, 1); + expect(Number(brush!.x[1])).toBeCloseTo(5, 1); + }); +}); diff --git a/packages/webgl/src/lib/components/gradients-r8.svelte.test.ts b/packages/webgl/src/lib/components/gradients-r8.svelte.test.ts new file mode 100644 index 0000000000..1a64ee9503 --- /dev/null +++ b/packages/webgl/src/lib/components/gradients-r8.svelte.test.ts @@ -0,0 +1,217 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { Color, SRGBColorSpace, type Object3D } from 'three'; +import type { ChartState } from 'layerchart'; + +import type { SceneState } from '../contexts/scene.svelte.js'; +import { gradientAffine, paintOf, type LinearGradientPaint } from '../utils/paint.svelte.js'; +import { ShapeContext } from '../utils/shapes.js'; +import Paints from './__fixtures__/Paints.svelte'; + +let chart: ChartState | undefined; + +async function renderPaints(props: Omit>[1], 'onScene'>) { + let scene: SceneState | undefined; + render(Paints, { + ...(props as any), + onScene: (s: SceneState, c: ChartState) => { + scene = s; + chart = c; + }, + }); + await expect.poll(() => scene?.root.children.length ?? 0).toBeGreaterThan(0); + return scene!; +} + +function all(scene: SceneState, is: (o: any) => boolean) { + const found: any[] = []; + scene.root.traverse((o: Object3D) => { + if (is(o)) found.push(o); + }); + return found; +} + +/** The merged meshes' vertices that have any, as `[x, y (down the plot), r, g, b, a]` (sRGB) */ +function vertices(scene: SceneState) { + const out: number[][] = []; + const srgb = { r: 0, g: 0, b: 0 }; + for (const mesh of all( + scene, + (o) => o.isMesh && !o.isInstancedMesh && o.geometry.attributes.color?.itemSize === 4 + )) { + const position = mesh.geometry.attributes.position; + const color = mesh.geometry.attributes.color; + for (let i = 0; i < position.count; i++) { + new Color(color.getX(i), color.getY(i), color.getZ(i)).getRGB(srgb, SRGBColorSpace); + out.push([position.getX(i), position.getZ(i), srgb.r, srgb.g, srgb.b, color.getW(i)]); + } + } + return out; +} + +const close = (a: number, b: number) => Math.abs(a - b) < 0.02; + +describe('LinearGradient', () => { + it('paints a rect from its first stop to its last across its own box', async () => { + const scene = await renderPaints({ mark: 'rect', rect: { x: 50, width: 100 } }); + await expect.poll(() => vertices(scene).length).toBeGreaterThan(0); + const points = vertices(scene); + const left = points.filter((p) => close(p[0], 50)); + const right = points.filter((p) => close(p[0], 150)); + expect(left.length).toBeGreaterThan(0); + expect(right.length).toBeGreaterThan(0); + for (const p of left) expect([p[2], p[4]].map((v) => Math.round(v))).toEqual([1, 0]); + for (const p of right) expect([p[2], p[4]].map((v) => Math.round(v))).toEqual([0, 1]); + // Halfway, halfway between them (in sRGB, as SVG blends) + const middle = points.filter((p) => close(p[0], 100)); + expect(middle.length).toBeGreaterThan(0); + for (const p of middle) expect(close(p[2], 0.5) && close(p[4], 0.5)).toBe(true); + }); + + it('cuts a shape at a hard stop, each side in its own color (`userSpaceOnUse`)', async () => { + const scene = await renderPaints({ + mark: 'rect', + rect: { x: 0, y: 0, width: 100, height: 300 }, + gradient: { + stops: [ + [0.5, 'rgb(255, 0, 0)'], + [0.5, 'rgb(0, 0, 255)'], + ], + vertical: true, + units: 'userSpaceOnUse', + }, + }); + await expect.poll(() => vertices(scene).length).toBeGreaterThan(0); + const points = vertices(scene); + // Half the chart's height, as SVG's percentages of its viewport + const cut = chart!.containerHeight / 2; + const atCut = points.filter((p) => close(p[1], cut)); + expect(atCut.some((p) => p[2] > 0.99 && p[4] < 0.01)).toBe(true); + expect(atCut.some((p) => p[4] > 0.99 && p[2] < 0.01)).toBe(true); + for (const p of points.filter((p) => p[1] < cut - 1)) expect(p[2]).toBeGreaterThan(0.99); + for (const p of points.filter((p) => p[1] > cut + 1)) expect(p[4]).toBeGreaterThan(0.99); + }); + + it("turns by `rotate` in its box's own space, as SVG's `gradientTransform`", () => { + const paint = { + type: 'linear', + stops: [], + classes: undefined, + x1: '0%', + y1: '0%', + x2: '100%', + y2: '0%', + rotate: 90, + units: 'objectBoundingBox', + viewport: { width: 400, height: 300 }, + } satisfies LinearGradientPaint; + const [a, b, c] = gradientAffine(paint, { x: 10, y: 20, width: 100, height: 200 }); + // Turned a quarter, it runs down the box: 0 at its top, 1 at its bottom + expect(a).toBeCloseTo(0); + expect(b * 20 + c).toBeCloseTo(0); + expect(b * 220 + c).toBeCloseTo(1); + }); + + it("strokes a line with its stops' colors and alphas along it", async () => { + const scene = await renderPaints({ + mark: 'spline', + gradient: { stops: ['rgb(255 0 0 / 0.5)', 'rgb(0 0 255)'] }, + }); + await expect + .poll(() => all(scene, (o) => o.isLine2 && o.geometry.attributes.instanceAlphaStart).length) + .toBe(1); + const [line] = all(scene, (o) => o.isLine2); + const start = line.geometry.attributes.instanceColorStart; + const alpha = line.geometry.attributes.instanceAlphaStart; + // Red and half clear at its start, blue and opaque at its end + expect(start.getX(0)).toBeGreaterThan(0.99); + expect(alpha.getX(0)).toBeCloseTo(0.5); + const end = line.geometry.attributes.instanceColorEnd; + const last = end.count - 1; + expect(end.getZ(last)).toBeGreaterThan(0.99); + expect(line.geometry.attributes.instanceAlphaEnd.getX(last)).toBeGreaterThan(0.99); + }); + + it('strokes each run of rows a `stroke` function gives a gradient across its own bounds', async () => { + const scene = await renderPaints({ + mark: 'spline', + // The first stretch (row 0 to 1) red to blue, the next (row 1 to 2) plain green + spline: { stroke: (d: { x: number }) => (d.x === 0 ? 'url(#run)' : 'rgb(0, 255, 0)') }, + gradient: { id: 'run' }, + }); + await expect + .poll(() => all(scene, (o) => o.isLine2 && o.geometry.attributes.instanceAlphaStart).length) + .toBe(1); + const [line] = all(scene, (o) => o.isLine2); + const start = line.geometry.attributes.instanceColorStart; + const end = line.geometry.attributes.instanceColorEnd; + const last = end.count - 1; + // Red at its start, blue where the run ends (at row 1, not the line's end), then green + expect(start.getX(0)).toBeGreaterThan(0.99); + const at = line.geometry.attributes.instanceStart; + const row1 = chart!.xScale(1); + const before = [...Array(end.count).keys()].filter((k) => at.getX(k) < row1 - 0.5); + expect(end.getZ(before[before.length - 1])).toBeGreaterThan(0.99); + expect(end.getY(last)).toBeGreaterThan(0.99); + expect(end.getX(last)).toBeLessThan(0.01); + }); + + it("fills an area and strokes its line across each's bounds", async () => { + const scene = await renderPaints({ mark: 'area', gradient: { vertical: true } }); + await expect.poll(() => vertices(scene).length).toBeGreaterThan(0); + const points = vertices(scene); + const top = Math.min(...points.map((p) => p[1])); + const bottom = Math.max(...points.map((p) => p[1])); + for (const p of points.filter((p) => close(p[1], top))) expect(p[2]).toBeGreaterThan(0.99); + for (const p of points.filter((p) => close(p[1], bottom))) expect(p[4]).toBeGreaterThan(0.99); + const outlines = all( + scene, + (o) => o.isLineSegments2 && o.geometry.attributes.instanceAlphaStart + ); + expect(outlines.length).toBe(1); + }); +}); + +describe('Pattern', () => { + it('fills a rect with its tile, repeating from the plot origin', async () => { + const scene = await renderPaints({ + mark: 'pattern', + pattern: { size: 8, lines: { rotate: 45, color: 'red' }, background: 'white' }, + }); + await expect + .poll(() => all(scene, (o) => o.isMesh && o.material.map && o.visible).length) + .toBe(1); + const [mesh] = all(scene, (o) => o.isMesh && o.material.map); + const image = mesh.material.map.image as HTMLCanvasElement; + expect(image.width).toBe(image.height); + expect(image.width / 8).toBeGreaterThanOrEqual(2); + // Each vertex's place in the tiles: its pixels over the tile's size + const position = mesh.geometry.attributes.position; + const uv = mesh.geometry.attributes.uv; + for (let i = 0; i < position.count; i++) { + expect(uv.getX(i)).toBeCloseTo(position.getX(i) / 8); + expect(uv.getY(i)).toBeCloseTo(position.getZ(i) / 8); + } + }); +}); + +describe('Pay only when used', () => { + it('looks up no paint for a plain color, and draws a plain rect as an instance', async () => { + const scene = await renderPaints({ mark: 'plain-rect' }); + expect(paintOf(scene, 'red')).toBeNull(); + expect(paintOf(scene, 'var(--color-primary)')).toBeNull(); + await expect.poll(() => all(scene, (o) => o.isInstancedMesh && o.count > 0).length).toBe(1); + expect(vertices(scene).length).toBe(0); + }); +}); + +describe('ShapeContext', () => { + it("outlines an arc the short way round a canvas' `arc` goes, across ±π", () => { + // A rounded corner's arc (as `d3.arc` draws one), from just under π to just over -π + const context = new ShapeContext(); + context.arc(0, 0, 10, Math.PI - 0.2, -Math.PI + 0.2); + const [line] = context.lines; + // All of it about the left of the circle, not most of a turn round through its right + for (const [x] of line) expect(x).toBeLessThan(-9); + }); +}); diff --git a/packages/webgl/src/lib/components/layers/Layer.svelte b/packages/webgl/src/lib/components/layers/Layer.svelte index 18c499b124..a8978e6d76 100644 --- a/packages/webgl/src/lib/components/layers/Layer.svelte +++ b/packages/webgl/src/lib/components/layers/Layer.svelte @@ -10,16 +10,32 @@ + +{#snippet panels(children: any)} + {#if ctx.facet.enabled} + {#each ctx.facet.panels as facet (facet.key)} + + {/each} + {:else} + {@render children?.({ facet: ctx.facet.panels[0] })} + {/if} +{/snippet} + {#if layer === 'webgl'} {@const { type: _, @@ -30,9 +46,9 @@ {#if center} - {@render children?.()} + {@render panels(children)} {:else} - {@render children?.()} + {@render panels(children)} {/if} {:else} diff --git a/packages/webgl/src/lib/components/layers/WebGLSetup.svelte b/packages/webgl/src/lib/components/layers/WebGLSetup.svelte index 2d870cfbac..67b9e4e855 100644 --- a/packages/webgl/src/lib/components/layers/WebGLSetup.svelte +++ b/packages/webgl/src/lib/components/layers/WebGLSetup.svelte @@ -12,6 +12,7 @@ Plane, Quaternion, Raycaster, + type Camera, type Mesh, type Object3D, Vector2, @@ -24,6 +25,7 @@ import { frameOrthographic, framePerspective, viewDirection } from '../../utils/camera.js'; import { geoPath } from 'd3-geo'; import { getSphere } from '../../utils/globe.js'; + import { clipKeeps, clipMaterial, type ClipChain, type SceneClip } from '../../utils/clip.js'; let { children }: { children?: Snippet } = $props(); @@ -64,16 +66,28 @@ invalidate(); }); renderer.localClippingEnabled = true; - /** Clip `object`'s materials, and its children's, unless they're kept from it */ - function clip(object: Object3D, planes: Plane[] | null) { - if (object.userData.unclipped) planes = null; + /** + * Clip `object`'s materials, and its children's, to the plot box unless they're kept from it, + * and to the `ClipPath`s they're in (`userData.clip`, see `SceneClip`) + */ + let clipFrame = 0; + function clip(object: Object3D, plot: boolean, chain: ClipChain | null, camera: Camera) { + if (object.userData.unclipped) plot = false; + const region = object.userData.clip as SceneClip | undefined; + if (region) chain = region.chain(object, chain, clipPlanes, camera); + const planes = chain ? (plot ? chain.withPlot : chain.planes) : plot ? clipPlanes : null; const material = (object as Mesh).material; - if (material) { - for (const m of Array.isArray(material) ? material : [material]) m.clippingPlanes = planes; + if (Array.isArray(material)) { + for (const m of material) clipMaterial(null, m, planes, chain, clipFrame); + } else if (material) { + clipMaterial(object as Mesh, material, planes, chain, clipFrame); } - for (const child of object.children) clip(child, planes); + for (const child of object.children) clip(child, plot, chain, camera); } - scene.onBeforeRender = () => clip(sceneState.root, sceneState.clip ? clipPlanes : null); + scene.onBeforeRender = (_renderer, _scene, camera) => { + clipFrame++; + clip(sceneState.root, sceneState.clip, null, camera); + }; // Even light all round, plus a key light from above and to the left of the camera (it moves // with it) so faces turned different ways read apart. Lambert shading divides by π, so these @@ -492,7 +506,8 @@ ({ object, point }) => (object as Mesh).isMesh && shown(object) && - (!sceneState.clip || clipPlanes.every((p) => p.distanceToPoint(point) >= 0)) + (!sceneState.clip || clipPlanes.every((p) => p.distanceToPoint(point) >= 0)) && + clipKeeps(object, point) ); if (hit) return hit.point; // The floor only where the plot is: past it, towards the horizon, it goes on without end @@ -752,7 +767,9 @@ false ) .find( - ({ point }) => !sceneState.clip || clipPlanes.every((p) => p.distanceToPoint(point) >= 0) + ({ object, point }) => + (!sceneState.clip || clipPlanes.every((p) => p.distanceToPoint(point) >= 0)) && + clipKeeps(object, point) ); const pickable = hit ? pickables.find((p) => p.object === hit.object) : undefined; return pickable && hit ? { pickable, datum: pickable.datum(hit) } : null; diff --git a/packages/webgl/src/lib/components/parity-lines.svelte.test.ts b/packages/webgl/src/lib/components/parity-lines.svelte.test.ts index aece0f99fa..85119564bf 100644 --- a/packages/webgl/src/lib/components/parity-lines.svelte.test.ts +++ b/packages/webgl/src/lib/components/parity-lines.svelte.test.ts @@ -253,6 +253,31 @@ describe('Link, as the core `Link`', () => { ]); }); + it('draws a wide link as a ribbon of its width, not a line (so a translucent one is even)', async () => { + const data = { source: { x0: 0, x1: 10 }, target: { x0: 100, x1: 110 }, y0: 20, y1: 20 }; + const filled = (scene: SceneState) => { + let count = 0; + scene.root.traverse((o: any) => { + if (o.isMesh && !o.isLineSegments2 && o.geometry?.getAttribute('position')?.count) + count += o.geometry.getAttribute('position').count; + }); + return count; + }; + const wide = await renderLines({ + mark: 'link', + link: { sankey: true, type: 'straight', data, strokeWidth: 10, stroke: 'black' }, + }); + await expect.poll(() => filled(wide.scene)).toBeGreaterThan(0); + expect(segments(layers(wide.scene)[0])).toHaveLength(0); + + const thin = await renderLines({ + mark: 'link', + link: { sankey: true, type: 'straight', data, strokeWidth: 1, stroke: 'black' }, + }); + await expect.poll(() => segments(layers(thin.scene)[0]).length).toBe(1); + expect(filled(thin.scene)).toBe(0); + }); + it('lays a `radial` link out by angle and radius about the origin', async () => { const { scene } = await renderLines({ mark: 'link', diff --git a/packages/webgl/src/lib/components/parity-scales.svelte.test.ts b/packages/webgl/src/lib/components/parity-scales.svelte.test.ts index 640a9af085..03fd765949 100644 --- a/packages/webgl/src/lib/components/parity-scales.svelte.test.ts +++ b/packages/webgl/src/lib/components/parity-scales.svelte.test.ts @@ -367,6 +367,56 @@ describe('Bin on an isometric floor', () => { }); }); +describe('Area by category', () => { + it('fades the other categories while the legend highlights one, as core’s', async () => { + const data = [ + { x: 0, y: 1, c: 'a' }, + { x: 1, y: 2, c: 'a' }, + { x: 0, y: 2, c: 'b' }, + { x: 1, y: 3, c: 'b' }, + ]; + const scene = await renderMarks({ + mark: 'area', + chart: { data, x: 'x', y: 'y', c: 'c', cDomain: ['a', 'b'], cRange: ['red', 'blue'] }, + area: { fill: 'c' }, + }); + /** The alphas the areas' fills are drawn with, one per category */ + const alphas = () => { + const found = new Set(); + scene.root.traverse((o: any) => { + const color = o.isMesh && o.geometry?.getAttribute('color'); + if (color?.itemSize === 4) + for (let i = 0; i < color.count; i++) found.add(Math.round(color.getW(i) * 10) / 10); + }); + return [...found].sort(); + }; + await expect.poll(alphas).toEqual([1]); + chart!.series.highlightKey = 'a'; + await expect.poll(alphas).toEqual([0.1, 1]); + chart!.series.highlightKey = null; + await expect.poll(alphas).toEqual([1]); + }); +}); + +describe('Points on an isometric floor', () => { + const shape = (scene: SceneState) => { + let type: string | undefined; + scene.root.traverse((o: any) => { + if (o.isInstancedMesh && o.count > 0) type ??= o.geometry.type; + }); + return type; + }; + const data = [{ x: 1, y: 1 }]; + const chart = { data, x: 'x', y: 'y', xDomain: [0, 2], yDomain: [0, 2], view: isometric() }; + + it('lie flat on the floor, as core’s, unless `viewport` turns them to the viewer', async () => { + const flat = await renderMarks({ mark: 'points', chart, points: {} }); + await expect.poll(() => shape(flat)).toBe('CircleGeometry'); + const facing = await renderMarks({ mark: 'points', chart, points: { viewport: true } }); + await expect.poll(() => shape(facing)).toBe('SphereGeometry'); + }); +}); + describe('Highlight area', () => { const data = [ { x: 'a', y: 3 }, diff --git a/packages/webgl/src/lib/index.ts b/packages/webgl/src/lib/index.ts index 98eede2522..2cc7c91bad 100644 --- a/packages/webgl/src/lib/index.ts +++ b/packages/webgl/src/lib/index.ts @@ -5,7 +5,40 @@ // `settings.layer`), and LayerChart's `Svg`, `Canvas`, or `Html` layer otherwise, and each mark // draws its WebGL version in a scene and LayerChart's elsewhere. For WebGL only, without bundling // LayerChart's versions of the marks, import from `@layerchart/webgl/webgl`. -export { Chart, Legend, Tooltip, orthographic, perspective } from 'layerchart'; +export { Legend, Tooltip, orthographic, perspective } from 'layerchart'; +// LayerChart's contexts and layouts, which draw nothing themselves but hand their children data +// (for the marks here to draw), and its legends drawn beside the layer +export { Bounds, ChartGroup, CircleLegend, Dodge, Point } from 'layerchart'; +export type { + BoundsProps, + ChartGroupProps, + CircleLegendProps, + DodgeProps, + PointProps, +} from 'layerchart'; +export { Chord, Dagre, Sankey } from 'layerchart/graph'; +export type { ChordProps, DagreProps, SankeyProps } from 'layerchart/graph'; +export { Pack, Partition, Tree, Treemap } from 'layerchart/hierarchy'; +export type { PackProps, PartitionProps, TreeProps, TreemapProps } from 'layerchart/hierarchy'; +export { GeoLegend, GeoProjection, GeoVisible } from 'layerchart/geo'; +export type { GeoLegendProps, GeoProjectionProps, GeoVisibleProps } from 'layerchart/geo'; +export { ForceSimulation } from 'layerchart/force'; +export type { ForceSimulationProps } from 'layerchart/force'; +// LayerChart's `Chart`, its axes, grid, and highlight (`axis`, `grid`, ...) drawn with the marks here +export { default as Chart } from './components/Chart/Chart.svelte'; +export type { ChartProps } from './components/Chart/Chart.svelte'; +export { default as ChartClipPath } from './components/ChartClipPath/ChartClipPath.svelte'; +export type { ChartClipPathProps } from './components/ChartClipPath/ChartClipPath.svelte'; +// The facet grid's headers, drawn with the `Axis` here +export { default as FacetAxis } from './components/FacetAxis/FacetAxis.svelte'; +export { default as ClipPath } from './components/ClipPath/ClipPath.svelte'; +export type { ClipPathProps } from './components/ClipPath/ClipPath.svelte'; +export { default as RectClipPath } from './components/RectClipPath/RectClipPath.svelte'; +export type { RectClipPathProps } from './components/RectClipPath/RectClipPath.svelte'; +export { default as CircleClipPath } from './components/CircleClipPath/CircleClipPath.svelte'; +export type { CircleClipPathPropsWithoutHTML } from './components/CircleClipPath/CircleClipPath.svelte'; +export { default as GeoClipPath } from './components/GeoClipPath/GeoClipPath.svelte'; +export type { GeoClipPathProps } from './components/GeoClipPath/GeoClipPath.svelte'; export type { OrthographicOptions, OrthographicView, @@ -55,6 +88,10 @@ export { default as Rect } from './components/Rect/Rect.svelte'; export type { RectProps } from './components/Rect/Rect.svelte'; export { default as Text } from './components/Text/Text.svelte'; export type { TextProps } from './components/Text/Text.svelte'; +export { default as Image } from './components/Image/Image.svelte'; +export type { ImageProps } from './components/Image/Image.svelte'; +export { default as Ellipse } from './components/Ellipse/Ellipse.svelte'; +export type { EllipseProps } from './components/Ellipse/Ellipse.svelte'; export { default as Area } from './components/Area/Area.svelte'; export type { AreaProps } from './components/Area/Area.svelte'; export { default as Line } from './components/Line/Line.svelte'; @@ -91,6 +128,8 @@ export { default as AnnotationLine } from './components/AnnotationLine/Annotatio export type { AnnotationLineProps } from './components/AnnotationLine/AnnotationLine.svelte'; export { default as AnnotationPoint } from './components/AnnotationPoint/AnnotationPoint.svelte'; export type { AnnotationPointProps } from './components/AnnotationPoint/AnnotationPoint.svelte'; +export { default as AnnotationRange } from './components/AnnotationRange/AnnotationRange.svelte'; +export type { AnnotationRangeProps } from './components/AnnotationRange/AnnotationRange.svelte'; export { default as BoxPlot } from './components/BoxPlot/BoxPlot.svelte'; export type { BoxPlotProps } from './components/BoxPlot/BoxPlot.svelte'; export { default as Calendar } from './components/Calendar/Calendar.svelte'; @@ -105,10 +144,45 @@ export { default as Hull } from './components/Hull/Hull.svelte'; export type { HullProps } from './components/Hull/Hull.svelte'; export { default as Labels } from './components/Labels/Labels.svelte'; export type { LabelsProps } from './components/Labels/Labels.svelte'; +export { default as LinearGradient } from './components/LinearGradient/LinearGradient.svelte'; +export type { LinearGradientProps } from './components/LinearGradient/LinearGradient.svelte'; +export { default as Pattern } from './components/Pattern/Pattern.svelte'; +export type { PatternProps } from './components/Pattern/Pattern.svelte'; export { default as Month } from './components/Month/Month.svelte'; export type { MonthProps } from './components/Month/Month.svelte'; export { default as Pie } from './components/Pie/Pie.svelte'; export type { PieProps } from './components/Pie/Pie.svelte'; +export { default as Waffle } from './components/Waffle/Waffle.svelte'; +export type { WaffleProps } from './components/Waffle/Waffle.svelte'; +export { default as Voronoi } from './components/Voronoi/Voronoi.svelte'; +export type { VoronoiProps } from './components/Voronoi/Voronoi.svelte'; +export { default as GeoBin } from './components/GeoBin/GeoBin.svelte'; +export type { GeoBinProps } from './components/GeoBin/GeoBin.svelte'; +export { default as GeoCircle } from './components/GeoCircle/GeoCircle.svelte'; +export type { GeoCircleProps } from './components/GeoCircle/GeoCircle.svelte'; +export { default as GeoSpline } from './components/GeoSpline/GeoSpline.svelte'; +export type { GeoSplineProps } from './components/GeoSpline/GeoSpline.svelte'; +export { default as GeoEdgeFade } from './components/GeoEdgeFade/GeoEdgeFade.svelte'; +export type { GeoEdgeFadeProps } from './components/GeoEdgeFade/GeoEdgeFade.svelte'; +export { default as Brush } from './components/Brush/Brush.svelte'; +export type { BrushProps } from './components/Brush/Brush.svelte'; + +export { default as ArcLabel } from './components/ArcLabel/ArcLabel.svelte'; +export type { ArcLabelProps } from './components/ArcLabel/ArcLabel.svelte'; + +// LayerChart's simplified charts, drawn with the marks here in whichever layer they're in +export { default as ArcChart } from './components/charts/ArcChart.svelte'; +export type { ArcChartProps } from './components/charts/ArcChart.svelte'; +export { default as AreaChart } from './components/charts/AreaChart.svelte'; +export type { AreaChartProps } from './components/charts/AreaChart.svelte'; +export { default as BarChart } from './components/charts/BarChart.svelte'; +export type { BarChartProps } from './components/charts/BarChart.svelte'; +export { default as LineChart } from './components/charts/LineChart.svelte'; +export type { LineChartProps } from './components/charts/LineChart.svelte'; +export { default as PieChart } from './components/charts/PieChart.svelte'; +export type { PieChartProps } from './components/charts/PieChart.svelte'; +export { default as ScatterChart } from './components/charts/ScatterChart.svelte'; +export type { ScatterChartProps } from './components/charts/ScatterChart.svelte'; // LayerChart's marks drawn with `Path` export { default as Violin } from './components/Violin/Violin.svelte'; diff --git a/packages/webgl/src/lib/utils/clip.ts b/packages/webgl/src/lib/utils/clip.ts new file mode 100644 index 0000000000..edd801ed9d --- /dev/null +++ b/packages/webgl/src/lib/utils/clip.ts @@ -0,0 +1,191 @@ +import { Plane, Vector3, type Camera, type Material, type Object3D } from 'three'; + +/** + * A clip shape drawn as a mask the marks inside sample (see `clipMask.ts`, loaded only when a + * clip isn't a plain rectangle) + */ +export interface SceneClipMask { + /** Fit the mask to `object`'s frame as `camera` sees it, for this frame */ + update(object: Object3D, camera: Camera): void; + /** Clip `material` to the mask (it's recompiled to sample it) */ + attach(material: Material): void; + /** Stop clipping `material` to the mask */ + detach(material: Material): void; + /** Whether a point of its frame (`x` across, `y` down) is inside the shape */ + contains(x: number, y: number): boolean; + dispose(): void; +} + +/** A rectangle of a clip's frame, `x` across and `y` down, in the chart's pixels */ +export type ClipRect = { x: number; y: number; width: number; height: number }; + +/** What clips a mark: the planes of its clips' rectangles, and the nearest one's mask */ +export type ClipChain = { + /** Its clips' rectangles' sides, in the scene's (world) space */ + planes: Plane[]; + /** And the plot box's */ + withPlot: Plane[]; + mask: SceneClipMask | null; +}; + +/** A plane every point is behind: a clip waiting for its mask draws nothing */ +const NOTHING = new Plane(new Vector3(1, 0, 0), -1e12); + +/** + * A clip a `ClipPath` puts on its group (its `userData.clip`): what's in the group is drawn only + * inside its rectangle (as clipping planes, exact and cheap) or its mask (any shape), and inside + * any clip it's in + */ +export class SceneClip { + disabled = false; + rect: ClipRect | null = null; + mask: SceneClipMask | null = null; + /** Its mask is loading: nothing inside is drawn until it's ready */ + pending = false; + /** Called each frame before it clips (ex. to repaint its mask from shapes that have changed) */ + refresh: (() => void) | null = null; + + readonly #chain: ClipChain = { planes: [], withPlot: [], mask: null }; + readonly #own = [new Plane(), new Plane(), new Plane(), new Plane()]; + + /** What clips the marks inside, in `outer` (the clips it's in), this frame */ + chain(object: Object3D, outer: ClipChain | null, plot: Plane[], camera: Camera) { + if (this.disabled) return outer; + this.refresh?.(); + const chain = this.#chain; + chain.planes.length = 0; + if (outer) chain.planes.push(...outer.planes); + if (this.pending) { + chain.planes.push(NOTHING); + } else if (this.rect) { + // Its sides in its group's frame (chart `x` along the scene's `x`, `y` along its `z`), + // then where that frame is in the scene + const { x, y, width, height } = this.rect; + const [left, right, top, bottom] = this.#own; + left.set(left.normal.set(1, 0, 0), -Math.min(x, x + width)); + right.set(right.normal.set(-1, 0, 0), Math.max(x, x + width)); + top.set(top.normal.set(0, 0, 1), -Math.min(y, y + height)); + bottom.set(bottom.normal.set(0, 0, -1), Math.max(y, y + height)); + for (const plane of this.#own) chain.planes.push(plane.applyMatrix4(object.matrixWorld)); + } + chain.withPlot.length = 0; + chain.withPlot.push(...plot, ...chain.planes); + if (this.mask && !this.pending) this.mask.update(object, camera); + chain.mask = (this.pending ? null : this.mask) ?? outer?.mask ?? null; + return chain; + } + + /** Whether a point of its group's frame is drawn (inside its rectangle or mask) */ + contains(x: number, y: number) { + if (this.disabled) return true; + if (this.pending) return false; + if (this.rect) { + const { x: rx, y: ry, width, height } = this.rect; + const inside = + x >= Math.min(rx, rx + width) && + x <= Math.max(rx, rx + width) && + y >= Math.min(ry, ry + height) && + y <= Math.max(ry, ry + height); + if (!inside) return false; + } + return this.mask ? this.mask.contains(x, y) : true; + } +} + +const NUMBER = String.raw`([-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)`; +const RECT = new RegExp( + String.raw`^\s*M\s*${NUMBER}[\s,]+${NUMBER}\s*h\s*${NUMBER}\s*v\s*${NUMBER}\s*h\s*${NUMBER}\s*z\s*$`, + 'i' +); + +/** + * The rectangle path data draws, if it's a plain one as `RectClipPath` draws (`M x,y h w v h h -w + * Z`), to clip to with planes rather than a mask + */ +export function rectOf(path: string): ClipRect | null { + const match = RECT.exec(path); + if (!match) return null; + const [x, y, width, height, back] = match.slice(1).map(Number); + return back === -width ? { x, y, width, height } : null; +} + +const own = (o: object, key: string) => Object.prototype.hasOwnProperty.call(o, key); + +/** + * The material to draw `object` with, clipped by `planes` and `chain`'s mask: its own, unless it + * shares it with an object clipped otherwise this frame (ex. a label's painting, shared by the + * planes showing the same text), when it's given a copy of its own. Without `object` (one of a + * mesh's several materials) it's always its own. + */ +export function clipMaterial( + object: (Object3D & { material: Material | Material[] }) | null, + material: Material, + planes: Plane[] | null, + chain: ClipChain | null, + frame: number +) { + let m = material; + const data = m.userData; + if ( + object && + data.lcClipFrame === frame && + (data.lcClipPlanes !== planes || data.lcClipChain !== chain) + ) { + const copy = m.clone(); + // What `clone` leaves behind: its own shader changes (before any mask's), and its `userData` + // as it is (not copied through JSON) + const source = (data.lcMaskOwn as Record | undefined) ?? m; + for (const key of ['onBeforeCompile', 'customProgramCacheKey'] as const) { + if (own(source, key)) (copy as any)[key] = (source as any)[key]; + } + copy.userData = { ...data, lcMask: undefined, lcMaskOwn: undefined, lcClipFrame: undefined }; + m.addEventListener('dispose', () => copy.dispose()); + object.material = copy; + m = copy; + } + m.userData.lcClipFrame = frame; + m.userData.lcClipPlanes = planes; + m.userData.lcClipChain = chain; + m.clippingPlanes = planes; + const mask = chain?.mask ?? null; + const current = (m.userData.lcMask as SceneClipMask | undefined) ?? null; + if (current !== mask) { + current?.detach(m); + mask?.attach(m); + } + return m; +} + +/** + * Save a material's own shader changes (see `clipMaterial`), before a mask replaces them with its + * own that call them + */ +export function saveOwnShader(material: Material) { + const saved: Record = {}; + for (const key of ['onBeforeCompile', 'customProgramCacheKey']) { + if (own(material, key)) saved[key] = (material as any)[key]; + } + material.userData.lcMaskOwn = saved; + return saved; +} + +/** Put back a material's own shader changes, as `saveOwnShader` saved them */ +export function restoreOwnShader(material: Material) { + const saved = (material.userData.lcMaskOwn ?? {}) as Record; + for (const key of ['onBeforeCompile', 'customProgramCacheKey']) { + if (key in saved) (material as any)[key] = saved[key]; + else delete (material as any)[key]; + } + delete material.userData.lcMaskOwn; +} + +/** Whether a point in the scene on `object` is drawn, inside every clip it's in */ +export function clipKeeps(object: Object3D, point: Vector3) { + for (let o: Object3D | null = object; o; o = o.parent) { + const clip = o.userData.clip as SceneClip | undefined; + if (!clip) continue; + const local = o.worldToLocal(point.clone()); + if (!clip.contains(local.x, local.z)) return false; + } + return true; +} diff --git a/packages/webgl/src/lib/utils/clipMask.ts b/packages/webgl/src/lib/utils/clipMask.ts new file mode 100644 index 0000000000..c2a9d8e136 --- /dev/null +++ b/packages/webgl/src/lib/utils/clipMask.ts @@ -0,0 +1,319 @@ +import { + CanvasTexture, + LinearFilter, + Matrix4, + Vector3, + type BufferAttribute, + type Camera, + type InstancedMesh, + type InterleavedBufferAttribute, + type Mesh, + type Material, + type Object3D, + type WebGLProgramParametersWithUniforms, +} from 'three'; + +import { restoreOwnShader, saveOwnShader, type SceneClipMask } from './clip.js'; +import { parsePath } from './path.js'; + +/** The least and most `x` and `y` of points, skipping any that aren't finite */ +class Bounds { + x0 = Infinity; + y0 = Infinity; + x1 = -Infinity; + y1 = -Infinity; + add(x: number, y: number) { + if (!Number.isFinite(x) || !Number.isFinite(y)) return; + this.x0 = Math.min(this.x0, x); + this.y0 = Math.min(this.y0, y); + this.x1 = Math.max(this.x1, x); + this.y1 = Math.max(this.y1, y); + } +} + +/** + * Whether a mesh is a shape's fill: not its outline (fat lines are meshes too) nor a label's + * plane (a painting) + */ +function isFill(mesh: Mesh) { + const line = mesh as Mesh & { isLineSegments2?: boolean; isLine2?: boolean }; + if (line.isLineSegments2 || line.isLine2) return false; + const material = mesh.material as Material & { map?: unknown }; + return !(material && !Array.isArray(material) && material.map); +} + +/** The most pixels a mask's canvas is across or down */ +const MAX_SIZE = 4096; + +/** + * A clip shape (SVG path data, in its `ClipPath`'s frame) painted onto a canvas, which the marks + * inside sample: each fragment is drawn only where the canvas is painted under it, looked up by + * where it is on the plot (its `x` across and `y` down), so the shape clips the same seen from any + * angle, as a stencil would from above. Loaded only when a clip isn't a plain rectangle. + */ +export class ClipMask implements SceneClipMask { + readonly #canvas = document.createElement('canvas'); + readonly #context = this.#canvas.getContext('2d')!; + #texture = this.#makeTexture(); + /** The mask's lookup: a point in the camera's space to the mask's texture (`x` and `z`) */ + readonly #lookup = new Matrix4(); + /** Its frame to the texture */ + readonly #fit = new Matrix4(); + readonly uniforms = { lcMask: { value: this.#texture }, lcMaskLookup: { value: this.#lookup } }; + /** Its shapes, each filled on its own, so where they overlap they add up (as SVG's do) */ + #shapes: Path2D[] = []; + #rule: CanvasFillRule = 'nonzero'; + /** The materials clipped to it */ + readonly #materials = new Set(); + + #makeTexture() { + const texture = new CanvasTexture(this.#canvas); + // The canvas' top row is the frame's least `y`, where the texture's `v` is 0 + texture.flipY = false; + texture.generateMipmaps = false; + texture.minFilter = LinearFilter; + texture.magFilter = LinearFilter; + return texture; + } + + /** + * Paint `path` (`evenodd` for an inverted clip, as the core `ClipPath` fills it), at `scale` + * canvas pixels per chart pixel + */ + draw(path: string, rule: CanvasFillRule, scale: number) { + const bounds = new Bounds(); + for (const { points } of parsePath(path)) { + for (const [x, y] of points) bounds.add(x, y); + } + this.#paint([new Path2D(path)], rule, bounds, scale); + } + + /** + * Paint the fills of the meshes in `source` (a `ClipPath`'s `clip` snippet's marks, drawn there + * rather than in the scene), as seen from above, and `paths` (its SVG elements' shapes, see + * `elementPaths`), as an SVG `` takes the shapes in it: their fills' outlines, + * whatever their colors + */ + drawShapes(source: Object3D, paths: string[], scale: number) { + source.updateMatrixWorld(true); + const shape = new Path2D(); + const shapes = [shape]; + const bounds = new Bounds(); + for (const path of paths) { + shapes.push(new Path2D(path)); + for (const { points } of parsePath(path)) { + for (const [x, y] of points) bounds.add(x, y); + } + } + const point = new Vector3(); + const corners: number[] = []; + const matrix = new Matrix4(); + source.traverseVisible((object) => { + const mesh = object as Mesh; + if (!mesh.isMesh || !isFill(mesh)) return; + const position = mesh.geometry.getAttribute('position'); + if (!position) return; + const index = mesh.geometry.getIndex(); + const count = index ? index.count : position.count; + const instanced = mesh as InstancedMesh; + // Each instance where it's placed (ex. a `Circle`'s), else the mesh where it is + const placements = instanced.isInstancedMesh ? instanced.count : 1; + for (let n = 0; n < placements; n++) { + if (instanced.isInstancedMesh) { + instanced.getMatrixAt(n, matrix); + matrix.premultiply(mesh.matrixWorld); + } else { + matrix.copy(mesh.matrixWorld); + } + triangles(position, index, count, matrix); + } + }); + this.#paint(shapes, 'nonzero', bounds, scale); + + function triangles( + position: BufferAttribute | InterleavedBufferAttribute, + index: BufferAttribute | null, + count: number, + matrix: Matrix4 + ) { + for (let i = 0; i + 2 < count; i += 3) { + corners.length = 0; + for (let j = 0; j < 3; j++) { + const vertex = index ? index.getX(i + j) : i + j; + point.fromBufferAttribute(position, vertex).applyMatrix4(matrix); + // Across and down the plot (the scene's `x` and `z`) + corners.push(point.x, point.z); + } + const [ax, ay, bx, by, cx, cy] = corners; + const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); + // Edge on from above (ex. an extruded shape's sides): nothing to fill + if (!(Math.abs(area) > 1e-9)) continue; + // Each the same way round, so where they overlap (ex. an extruded shape's top and bottom) + // they add up rather than cancel out under the `nonzero` rule + shape.moveTo(ax, ay); + if (area > 0) { + shape.lineTo(bx, by); + shape.lineTo(cx, cy); + } else { + shape.lineTo(cx, cy); + shape.lineTo(bx, by); + } + shape.closePath(); + bounds.add(ax, ay); + bounds.add(bx, by); + bounds.add(cx, cy); + } + } + } + + #paint(shapes: Path2D[], rule: CanvasFillRule, bounds: Bounds, scale: number) { + let { x0, y0, x1, y1 } = bounds; + if (!(x1 >= x0 && y1 >= y0)) x0 = y0 = x1 = y1 = 0; + // A pixel around it, for its edges' antialiasing + x0 = Math.floor(x0) - 1; + y0 = Math.floor(y0) - 1; + const width = Math.ceil(x1) + 1 - x0; + const height = Math.ceil(y1) + 1 - y0; + const k = Math.min(scale, MAX_SIZE / Math.max(width, height, 1)); + const canvasWidth = Math.max(1, Math.ceil(width * k)); + const canvasHeight = Math.max(1, Math.ceil(height * k)); + + // A texture keeps the size it's first given: a new one for a new size + if (canvasWidth !== this.#canvas.width || canvasHeight !== this.#canvas.height) { + this.#canvas.width = canvasWidth; + this.#canvas.height = canvasHeight; + this.#texture.dispose(); + this.#texture = this.#makeTexture(); + this.uniforms.lcMask.value = this.#texture; + } + const context = this.#context; + context.setTransform(1, 0, 0, 1, 0, 0); + context.clearRect(0, 0, canvasWidth, canvasHeight); + context.setTransform(k, 0, 0, k, -x0 * k, -y0 * k); + this.#shapes = shapes; + this.#rule = rule; + context.fillStyle = '#fff'; + for (const shape of shapes) context.fill(shape, rule); + this.#texture.needsUpdate = true; + // Across and down its frame (the scene's `x` and `z`) to the texture's `u` and `v` + const sx = canvasWidth / k; + const sy = canvasHeight / k; + this.#fit.set(1 / sx, 0, 0, -x0 / sx, 0, 1, 0, 0, 0, 0, 1 / sy, -y0 / sy, 0, 0, 0, 1); + } + + /** + * The shapes of the SVG elements in `host` (ex. a `clip` snippet's `` and ``), as + * path data, by their attributes (they're never laid out) + */ + elementPaths(host: Element) { + const paths: string[] = []; + const number = (element: Element, name: string) => Number(element.getAttribute(name)) || 0; + for (const element of host.querySelectorAll('path, rect, circle, ellipse, polygon')) { + switch (element.localName) { + case 'path': { + const d = element.getAttribute('d'); + if (d) paths.push(d); + break; + } + case 'rect': { + const [x, y] = [number(element, 'x'), number(element, 'y')]; + const [width, height] = [number(element, 'width'), number(element, 'height')]; + if (width > 0 && height > 0) paths.push(`M${x},${y}h${width}v${height}h${-width}Z`); + break; + } + case 'circle': + case 'ellipse': { + const [cx, cy] = [number(element, 'cx'), number(element, 'cy')]; + const rx = number(element, element.localName === 'circle' ? 'r' : 'rx'); + const ry = element.localName === 'circle' ? rx : number(element, 'ry'); + if (rx > 0 && ry > 0) { + paths.push( + `M${cx - rx},${cy}a${rx},${ry} 0 1,0 ${2 * rx},0a${rx},${ry} 0 1,0 ${-2 * rx},0Z` + ); + } + break; + } + case 'polygon': { + const points = element.getAttribute('points')?.trim(); + if (points) paths.push(`M${points.split(/[\s,]+/).join(' ')}Z`); + break; + } + } + } + return paths; + } + + update(object: Object3D, camera: Camera) { + this.#lookup + .copy(object.matrixWorld) + .invert() + .multiply(camera.matrixWorld) + .premultiply(this.#fit); + } + + contains(x: number, y: number) { + if (!this.#shapes.length) return false; + this.#context.save(); + this.#context.setTransform(1, 0, 0, 1, 0, 0); + const inside = this.#shapes.some((shape) => + this.#context.isPointInPath(shape, x, y, this.#rule) + ); + this.#context.restore(); + return inside; + } + + attach(material: Material) { + const saved = saveOwnShader(material); + const before = (saved.onBeforeCompile as Material['onBeforeCompile']) ?? null; + const key = material.customProgramCacheKey(); + const uniforms = this.uniforms; + material.onBeforeCompile = function (shader, renderer) { + before?.call(this, shader, renderer); + maskShader(shader, uniforms); + }; + material.customProgramCacheKey = () => `${key}|lc-clip-mask`; + material.userData.lcMask = this; + material.needsUpdate = true; + this.#materials.add(material); + } + + detach(material: Material) { + restoreOwnShader(material); + delete material.userData.lcMask; + material.needsUpdate = true; + this.#materials.delete(material); + } + + dispose() { + for (const material of [...this.#materials]) this.detach(material); + this.#texture.dispose(); + this.#shapes = []; + } +} + +/** + * A material's shaders, dropping fragments outside the mask: where a fragment is on the plot, + * from its position in the camera's space (as its clipping planes take it, so every material that + * can be clipped can be masked), looked up in the mask's texture + */ +function maskShader(shader: WebGLProgramParametersWithUniforms, uniforms: ClipMask['uniforms']) { + shader.uniforms.lcMask = uniforms.lcMask; + shader.uniforms.lcMaskLookup = uniforms.lcMaskLookup; + shader.vertexShader = shader.vertexShader + .replace('#include ', '$&\nvarying vec3 vLcClipView;') + .replace('#include ', '$&\nvLcClipView = mvPosition.xyz;'); + shader.fragmentShader = shader.fragmentShader + .replace( + '#include ', + '$&\nvarying vec3 vLcClipView;\nuniform sampler2D lcMask;\nuniform mat4 lcMaskLookup;' + ) + .replace( + '#include ', + `$& +{ + vec2 lcMaskUv = ( lcMaskLookup * vec4( vLcClipView, 1.0 ) ).xz; + if ( any( lessThan( lcMaskUv, vec2( 0.0 ) ) ) || any( greaterThan( lcMaskUv, vec2( 1.0 ) ) ) || + texture2D( lcMask, lcMaskUv ).a < 0.5 ) discard; +}` + ); +} diff --git a/packages/webgl/src/lib/utils/marks.ts b/packages/webgl/src/lib/utils/marks.ts index 83b4ff3fb6..e557f4287f 100644 --- a/packages/webgl/src/lib/utils/marks.ts +++ b/packages/webgl/src/lib/utils/marks.ts @@ -15,6 +15,9 @@ import type { ScenePoint, Sphere } from './globe.js'; /** A chart scale's pixel position for `value`, at the middle of its band on a band scale */ export function scaled(scale: any, value: unknown): number { + // A scale with no domain (ex. a chart laid out in pixels by \`Dagre\`) takes values as they are, + // as the core \`Spline\` does + if (!scale.domain().length) return Number(value); const position = Number(scale(value)); return isScaleBand(scale) ? position + scale.bandwidth() / 2 : position; } @@ -170,9 +173,15 @@ export function placeOf( * The rows a mark draws: its `data`, else the chart's when its props read rows (as the core * primitives do), else one, for a mark placed by numbers alone */ -export function markRows(ctx: ChartState, data: any[] | undefined, ...props: unknown[]) { +export function markRows( + rows: ChartState | ((own?: any) => any[]), + data: any[] | undefined, + ...props: unknown[] +) { if (data) return data; - return props.some(isDataProp) ? ((ctx.data ?? []) as any[]) : [undefined]; + if (!props.some(isDataProp)) return [undefined]; + // A mark's `getMarkData` (its facet panel's rows), else the chart's + return typeof rows === 'function' ? rows() : ((rows.data ?? []) as any[]); } /** diff --git a/packages/webgl/src/lib/utils/merged.svelte.ts b/packages/webgl/src/lib/utils/merged.svelte.ts index 96b87ea638..c43d098ab7 100644 --- a/packages/webgl/src/lib/utils/merged.svelte.ts +++ b/packages/webgl/src/lib/utils/merged.svelte.ts @@ -19,6 +19,16 @@ import { hasEvents, type MarkEvents, } from '../contexts/scene.svelte.js'; +import { + boxOf, + createPatternFills, + gradientShader, + paintOf, + setLineAlphas, + shadeSegments, + shadeTriangles, + useLineAlphas, +} from './paint.svelte.js'; /** One shape of a mark drawn as a single merged mesh: its geometry, outlines, and colors */ export type MergedItem = { @@ -101,8 +111,16 @@ export function createMerged({ layer.add(mesh, lines); /** Each item's row and the vertices it spans, to pick and to highlight */ - let spans: { d: any; start: number; count: number; color: [number, number, number, number] }[] = - []; + let spans: { + d: any; + start: number; + count: number; + color: [number, number, number, number]; + /** A gradient's colors across it, vertex by vertex (RGBA), in place of `color` */ + shaded?: number[]; + }[] = []; + /** Shapes filled with a `Pattern`, made once one is */ + let patterned: ReturnType | null = null; let shown: any[] = []; const index = new Map(); let emphasized = -1; @@ -111,6 +129,15 @@ export function createMerged({ const span = spans[i]; const [r, g, b, a] = span.color; const c = new Color(r, g, b); + if (span.shaded) { + const shaded = span.shaded; + for (let v = 0; v < span.count; v++) { + c.setRGB(shaded[v * 4], shaded[v * 4 + 1], shaded[v * 4 + 2]); + if (hovered) c.lerp(highlight, 0.3); + colors.setXYZW(span.start + v, c.r, c.g, c.b, shaded[v * 4 + 3]); + } + return; + } if (hovered) c.lerp(highlight, 0.3); for (let v = span.start; v < span.start + span.count; v++) colors.setXYZW(v, c.r, c.g, c.b, a); } @@ -128,13 +155,21 @@ export function createMerged({ let translucent = false; /** Outlines share one material, so they take the first one's alpha */ let strokeAlpha: number | null = null; + /** + * Where each item's outline segments start and their alpha (a gradient's, its own), only once + * one is painted with a gradient: the outlines' alphas are then each segment's own + */ + let strokeRuns: { start: number; alpha: number | number[] }[] | null = null; + const runs: { start: number; alpha: number | number[] }[] = []; list.forEach((item, i) => { index.set(item.d, i); const start = positions.length / 3; + // A `LinearGradient`'s or `Pattern`'s `url(#id)` (looked up only for one) + const fillPaint = item.fillColor ? null : paintOf(scene, item.fill); const fill = item.fillColor ? { color: new Color(...item.fillColor.slice(0, 3)), opacity: item.fillColor[3] } - : item.fill + : item.fill && !fillPaint ? scene.color(item.fill) : null; const color: [number, number, number, number] = [ @@ -150,14 +185,33 @@ export function createMerged({ append(normals, geometry.getAttribute('normal').array); if (geometry !== item.geometry) geometry.dispose(); } + let shaded: number[] | undefined; + if (item.geometry && fillPaint) { + const geometry = item.geometry.index ? item.geometry.toNonIndexed() : item.geometry; + if (fillPaint.type === 'pattern') { + (patterned ??= createPatternFills(scene, layer)).add(fillPaint, geometry); + } else { + // Across its own bounds (or the plot), as SVG lays a gradient over a shape + const position = geometry.getAttribute('position').array; + const shader = gradientShader(scene, fillPaint, boxOf(position)); + if (shader) { + const from = colors.length; + if (shadeTriangles(geometry, shader, positions, normals, colors)) translucent = true; + shaded = colors.slice(from); + } + } + if (geometry !== item.geometry) geometry.dispose(); + } item.geometry?.dispose(); const count = positions.length / 3 - start; - for (let v = 0; v < count; v++) colors.push(...color); - spans.push({ d: item.d, start, count, color }); + if (!shaded) for (let v = 0; v < count; v++) colors.push(...color); + spans.push({ d: item.d, start, count, color, shaded }); - const stroke = item.stroke ? scene.color(item.stroke) : null; + const strokePaint = item.lines?.length ? paintOf(scene, item.stroke) : null; + const stroke = item.stroke && !strokePaint ? scene.color(item.stroke) : null; if (stroke && item.lines) { strokeAlpha ??= stroke.opacity; + runs.push({ start: linePositions.length / 6, alpha: stroke.opacity }); for (const line of item.lines) { const { r, g, b } = stroke.color; for (let k = 0; k + 5 < line.length; k += 3) { @@ -165,8 +219,23 @@ export function createMerged({ lineColors.push(r, g, b, r, g, b); } } + } else if (strokePaint?.type === 'linear' && item.lines) { + // Along its outlines' bounds (or the plot), each segment's ends in their own colors + const shader = gradientShader(scene, strokePaint, boxOf(item.lines.flat())); + if (shader) { + const alphas: number[] = []; + runs.push({ start: linePositions.length / 6, alpha: alphas }); + for (const line of item.lines) { + const segments = shadeSegments(line, shader); + append(linePositions, segments.positions); + append(lineColors, segments.colors); + append(alphas, segments.alphas); + } + strokeRuns = runs; + } } }); + patterned?.update(opacity() * inGroup()); const geometry = new BufferGeometry(); geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)); @@ -180,6 +249,22 @@ export function createMerged({ lineGeometry.setPositions(linePositions); lineGeometry.setColors(lineColors); } + // With a gradient's outline, each segment's alpha its own (as the material's is then 1) + if (strokeRuns || lineMaterial.userData.alphas) { + lineMaterial.userData.alphas = true; + useLineAlphas(lineMaterial); + // Each pixel once where segments' round ends overlap, as SVG strokes a path, so a + // translucent stretch isn't dotted darker at every joint + lineMaterial.depthFunc = LessDepth; + strokeAlpha = 1; + const alphas = new Float32Array(linePositions.length / 3).fill(1); + runs.forEach((run, k) => { + if (typeof run.alpha !== 'number') return alphas.set(run.alpha, run.start * 2); + const end = runs[k + 1]?.start ?? linePositions.length / 6; + alphas.fill(run.alpha, run.start * 2, end * 2); + }); + setLineAlphas(lineGeometry, alphas); + } lines.geometry.dispose(); lines.geometry = lineGeometry; lines.visible = linePositions.length > 0; @@ -271,6 +356,7 @@ export function createMerged({ $effect(() => { return () => { layer.remove(mesh, lines); + patterned?.dispose(); mesh.geometry.dispose(); lines.geometry.dispose(); material.dispose(); diff --git a/packages/webgl/src/lib/utils/paint.svelte.ts b/packages/webgl/src/lib/utils/paint.svelte.ts new file mode 100644 index 0000000000..7de751c7cd --- /dev/null +++ b/packages/webgl/src/lib/utils/paint.svelte.ts @@ -0,0 +1,752 @@ +import { untrack } from 'svelte'; +import { SvelteMap } from 'svelte/reactivity'; +import { + BufferGeometry, + CanvasTexture, + Color, + DoubleSide, + Float32BufferAttribute, + InstancedInterleavedBuffer, + InterleavedBufferAttribute, + LinearFilter, + Mesh, + MeshLambertMaterial, + RepeatWrapping, + SRGBColorSpace, + type Group, +} from 'three'; +import type { LineMaterial } from 'three/addons/lines/LineMaterial.js'; +import type { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js'; +import type { buildPatternShapes } from 'layerchart/base'; + +import type { SceneState } from '../contexts/scene.svelte.js'; + +/** + * A `LinearGradient` as a scene draws it: its stops and direction, as the core `LinearGradient`'s + * SVG `` has them (its fields read its props as they change) + */ +export type LinearGradientPaint = { + type: 'linear'; + readonly stops: (string | [string | number, string])[]; + /** The class its stops have (ex. `from-primary to-secondary`, which set the stops' colors) */ + readonly classes: string | undefined; + readonly x1: string; + readonly y1: string; + readonly x2: string; + readonly y2: string; + /** Degrees, as its `gradientTransform="rotate(...)"` */ + readonly rotate: number | undefined; + readonly units: 'objectBoundingBox' | 'userSpaceOnUse'; + /** The size `userSpaceOnUse` percentages are of: the chart's, as SVG's viewport */ + readonly viewport: { width: number; height: number }; +}; + +/** A `Pattern` as a scene draws it: its tile and what's in it, as the core `Pattern`'s */ +export type PatternPaint = { + type: 'pattern'; + readonly width: number; + readonly height: number; + readonly shapes: PatternShape[]; + /** A CSS color, or a gradient's `url(#id)` drawn across each tile */ + readonly background: string | undefined; +}; + +export type Paint = LinearGradientPaint | PatternPaint; + +/** A line, circle, or rect in a pattern's tile, as the core `Pattern` lays them out */ +type PatternShape = ReturnType[number]; + +const registries = new WeakMap>(); + +function registryOf(scene: SceneState) { + let registry = registries.get(scene); + if (!registry) registries.set(scene, (registry = new SvelteMap())); + return registry; +} + +/** + * Define `paint` as `id` in `scene` while the calling component lives, so marks drawn with + * `url(#id)` as their fill or stroke paint it. Call during component setup. + */ +export function registerPaint(scene: SceneState, id: () => string, paint: Paint) { + const registry = registryOf(scene); + // At once, so the marks inside find it as they first draw + let current = untrack(id); + registry.set(current, paint); + $effect.pre(() => { + const next = id(); + if (next === current) return; + untrack(() => { + if (registry.get(current) === paint) registry.delete(current); + registry.set(next, paint); + }); + current = next; + }); + $effect(() => () => { + const gone = current; + // Not written in the teardown itself (see `SceneState.addLabels`) + queueMicrotask(() => { + if (registry.get(gone) === paint) registry.delete(gone); + }); + if (paint.type === 'pattern') { + textures.get(paint)?.texture.dispose(); + textures.delete(paint); + } + }); +} + +/** Whether `scene` has any paint defined (so marks needn't look for one in each row's color) */ +export function hasPaints(scene: SceneState) { + return registryOf(scene).size > 0; +} + +/** + * The paint a fill or stroke names (`url(#id)`, as SVG's), or `null` for a color: only a + * `url(...)` value is looked up, so marks drawn in plain colors pay nothing + */ +export function paintOf(scene: SceneState, value: unknown): Paint | null { + if (typeof value !== 'string' || !value.startsWith('url(')) return null; + const id = /^url\(\s*["']?#([^"')]+)["']?\s*\)/.exec(value)?.[1]; + return id == null ? null : (registryOf(scene).get(id) ?? null); +} + +/** A box in the plot's pixels (`x` across, `y` down) */ +export type Box = { x: number; y: number; width: number; height: number }; + +/** sRGB (or linear RGB) and alpha, each 0 to 1 */ +type RGBA = [number, number, number, number]; +/** A stop's offset, its sRGB and alpha, and its color in Oklab */ +type Stop = { offset: number; rgba: RGBA; lab: [number, number, number] }; +/** What a gradient blends its stops in: sRGB with legacy colors only, else Oklab, as CSS */ +type Space = 'srgb' | 'oklab'; + +/** An SVG `offset`: a number (0 to 1), or a percentage */ +function parseOffset(value: string | number): number { + if (typeof value === 'number') return value; + const n = parseFloat(value); + return value.trim().endsWith('%') ? n / 100 : n; +} + +const srgb = { r: 0, g: 0, b: 0 }; + +/** Linear RGB as Oklab */ +function toOklab(r: number, g: number, b: number): [number, number, number] { + const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + return [ + 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, + 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, + 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s, + ]; +} + +/** Oklab as linear RGB (in gamut), into `out` */ +function fromOklab([L, a, b]: number[], out: RGBA) { + const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3; + const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3; + const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3; + const clamp = (v: number) => Math.min(1, Math.max(0, v)); + out[0] = clamp(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s); + out[1] = clamp(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s); + out[2] = clamp(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s); +} + +/** + * A CSS color as sRGB and alpha, as the scene resolves it (`classes` set on what it's read on), + * and whether it's a legacy color (`rgb()`, `hsl()`, hex, or named), which CSS blends in sRGB + */ +function rgbaOf( + scene: SceneState, + value: string, + classes: string | undefined +): { rgba: RGBA; legacy: boolean } | null { + // On an SVG shape (with the stops' class, as the core `LinearGradient`'s ``s have it, ex. + // `from-primary`, which sets the `--tw-gradient-from` its default stops read), as computed + const computed = scene.style(classes ?? '', { style: `fill: ${value}` })?.fill ?? value; + const resolved = scene.color(computed); + if (!resolved) return null; + // A translucent color's own RGB, opaque: read back translucent, it loses it (all of it when + // clear, ex. `rgb(... / 0)`), which would tint the blend towards its neighbors + const opaque = + resolved.opacity < 1 && relativeColors() + ? scene.color(`rgb(from ${computed} r g b / 1)`) + : null; + (opaque ?? resolved).color.getRGB(srgb, SRGBColorSpace); + return { + rgba: [srgb.r, srgb.g, srgb.b, resolved.opacity], + legacy: /^((rgba?|hsla?|hwb)\(|#|[a-z]+$)/i.test(computed.trim()), + }; +} + +let relative: boolean | undefined; +/** Whether the browser reads CSS relative colors (`rgb(from ... r g b / 1)`) */ +function relativeColors() { + return (relative ??= globalThis.CSS?.supports?.('color', 'rgb(from red r g b / 1)') ?? false); +} + +/** + * A gradient's stops, resolved: their offsets (each at least the one before, as SVG's) and colors, + * and the space it blends them in + */ +function resolveStops( + scene: SceneState, + paint: LinearGradientPaint +): { stops: Stop[]; space: Space } | null { + const stops = paint.stops; + if (!stops.length) return null; + const out: Stop[] = []; + let last = 0; + let legacy = true; + for (let i = 0; i < stops.length; i++) { + const stop = stops[i]; + const [offset, color] = Array.isArray(stop) + ? [parseOffset(stop[0]), stop[1]] + : [stops.length > 1 ? i / (stops.length - 1) : 0, stop]; + const resolved = rgbaOf(scene, color, paint.classes); + if (!resolved) return null; + legacy &&= resolved.legacy; + const { rgba } = resolved; + linear.setRGB(rgba[0], rgba[1], rgba[2], SRGBColorSpace); + last = Math.max(last, Math.min(1, Math.max(0, Number.isFinite(offset) ? offset : 0))); + out.push({ offset: last, rgba, lab: toOklab(linear.r, linear.g, linear.b) }); + } + return { stops: out, space: legacy ? 'srgb' : 'oklab' }; +} + +const mixed: RGBA = [0, 0, 0, 0]; + +/** + * A gradient's linear RGB and alpha at `t` (0 at its start, 1 at its end), padded past its ends + */ +function colorAt(stops: Stop[], space: Space, t: number, out: RGBA) { + const last = stops[stops.length - 1]; + let [a, b, s] = [stops[0], stops[0], 0]; + if (t >= last.offset) [a, b] = [last, last]; + else if (t > stops[0].offset) { + // The stops either side (past a hard stop's pair, the later one's color) + let k = 1; + while (stops[k].offset <= t) k++; + [a, b] = [stops[k - 1], stops[k]]; + s = (t - a.offset) / (b.offset - a.offset); + } + // Unpremultiplied, as SVG blends its stops (with a clear stop's own color, see `rgbaOf`) + const [ca, cb] = space === 'oklab' ? [a.lab, b.lab] : [a.rgba, b.rgba]; + for (let c = 0; c < 3; c++) mixed[c] = ca[c] + (cb[c] - ca[c]) * s; + if (space === 'oklab') fromOklab(mixed, out); + else { + linear.setRGB(mixed[0], mixed[1], mixed[2], SRGBColorSpace); + [out[0], out[1], out[2]] = [linear.r, linear.g, linear.b]; + } + out[3] = a.rgba[3] + (b.rgba[3] - a.rgba[3]) * s; +} + +/** A gradient coordinate (`x1`, ...): a fraction of the box, or pixels (`%` of `extent`) */ +function coordinate(value: string, units: LinearGradientPaint['units'], extent: number) { + const n = parseFloat(value); + if (!Number.isFinite(n)) return 0; + const percent = value.trim().endsWith('%'); + if (units === 'objectBoundingBox') return percent ? n / 100 : n; + return percent ? (n / 100) * extent : n; +} + +/** + * Where along a gradient each point of the plot is (`t = a·x + b·y + c`, 0 at its start, 1 at its + * end), over `box` (the shape's bounds, for `objectBoundingBox`), as SVG lays it out: its vector + * from (`x1`, `y1`) to (`x2`, `y2`), turned by `rotate` about its space's origin + */ +export function gradientAffine( + paint: LinearGradientPaint, + box: Box +): [a: number, b: number, c: number] { + const { units, viewport } = paint; + const x1 = coordinate(paint.x1, units, viewport.width); + const y1 = coordinate(paint.y1, units, viewport.height); + const dx = coordinate(paint.x2, units, viewport.width) - x1; + const dy = coordinate(paint.y2, units, viewport.height) - y1; + const length = dx * dx + dy * dy; + // No length: the last stop's color throughout, as SVG + if (!length) return [0, 0, 1]; + const angle = ((paint.rotate ?? 0) * Math.PI) / 180; + const [cos, sin] = [Math.cos(angle), Math.sin(angle)]; + // A point turned back by `rotate`, onto the vector + const A = (cos * dx - sin * dy) / length; + const B = (sin * dx + cos * dy) / length; + const C = -(x1 * dx + y1 * dy) / length; + if (units === 'userSpaceOnUse') return [A, B, C]; + // From the box's own space (0 to 1 across each side) + const a = box.width ? A / box.width : 0; + const b = box.height ? B / box.height : 0; + return [a, b, C - a * box.x - b * box.y]; +} + +/** + * A gradient over a shape: where along it each point is, the places its color changes course + * (`cuts`), and its color between them. Shapes are cut at each, so blending between their + * vertices follows the gradient's stops (and keeps to SVG's sRGB blend between stops of different + * colors). + */ +export type Shader = { + t: (x: number, y: number) => number; + cuts: number[]; + /** Linear RGB and alpha at `t`, within `[lo, hi]` (to take a hard stop's side) */ + color: (t: number, lo: number, hi: number, out: RGBA) => void; + /** Its stops' colors and its layout, to tell when it's changed */ + key: string; +}; + +const linear = new Color(); + +/** A `LinearGradient` over `box` as a `Shader`, or `null` before its colors resolve */ +export function gradientShader( + scene: SceneState, + paint: LinearGradientPaint, + box: Box +): Shader | null { + const resolved = resolveStops(scene, paint); + if (!resolved) return null; + const { stops, space } = resolved; + const [a, b, c] = gradientAffine(paint, box); + const cuts: number[] = []; + for (let i = 0; i < stops.length; i++) { + const { offset } = stops[i]; + if (cuts[cuts.length - 1] !== offset) cuts.push(offset); + const next = stops[i + 1]; + if (!next || next.offset <= offset) continue; + // Steps between stops of different colors, as a vertex blend is linear light, not sRGB (or + // Oklab) + const diff = Math.max(...[0, 1, 2].map((k) => Math.abs(next.rgba[k] - stops[i].rgba[k]))); + const steps = Math.min(8, Math.ceil(diff * 8)); + for (let s = 1; s < steps; s++) cuts.push(offset + ((next.offset - offset) * s) / steps); + } + return { + t: (x, y) => a * x + b * y + c, + cuts, + key: JSON.stringify([stops, space, a, b, c]), + color: (t, lo, hi, out) => { + const e = 1e-7; + const at = hi - lo <= 2 * e ? (lo + hi) / 2 : Math.min(Math.max(t, lo + e), hi - e); + colorAt(stops, space, at, out); + }, + }; +} + +/** The bounds of points in the scene's axes (`x` across, height, `y` down), on the floor */ +export function boxOf(points: ArrayLike): Box { + let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = 0; i + 2 < points.length; i += 3) { + const [x, y] = [points[i], points[i + 2]]; + if (x < x0) x0 = x; + if (x > x1) x1 = x; + if (y < y0) y0 = y; + if (y > y1) y1 = y; + } + return x0 <= x1 + ? { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } + : { x: 0, y: 0, width: 0, height: 0 }; +} + +/** The cuts between `lo` and `hi` (either way round), in order from `lo` */ +function cutsBetween(cuts: number[], lo: number, hi: number) { + const [min, max] = lo < hi ? [lo, hi] : [hi, lo]; + const inside = cuts.filter((c) => c > min + 1e-9 && c < max - 1e-9); + return lo < hi ? inside : inside.reverse(); +} + +/** The cuts either side of `t`: the slab it's in */ +function slabOf(cuts: number[], t: number): [number, number] { + let lo = -Infinity; + let hi = Infinity; + for (const c of cuts) { + if (c <= t) lo = c; + else { + hi = c; + break; + } + } + return [lo, hi]; +} + +type Vertex = { p: [number, number, number]; t: number }; + +/** A convex polygon's part on one side of `bound` (`above` it, or below) */ +function clip(polygon: Vertex[], bound: number, above: boolean): Vertex[] { + const out: Vertex[] = []; + for (let i = 0; i < polygon.length; i++) { + const a = polygon[i]; + const b = polygon[(i + 1) % polygon.length]; + const aIn = above ? a.t >= bound : a.t <= bound; + const bIn = above ? b.t >= bound : b.t <= bound; + if (aIn) out.push(a); + if (aIn !== bIn) { + const s = (bound - a.t) / (b.t - a.t); + out.push({ + p: [0, 1, 2].map((k) => a.p[k] + (b.p[k] - a.p[k]) * s) as [number, number, number], + t: bound, + }); + } + } + return out; +} + +/** + * A shape's triangles (non-indexed, in the scene's axes) colored by `shader`: cut where its color + * changes course, each vertex in its color there. Appends to `positions`, `normals` (each + * triangle's first vertex's), and `colors` (RGBA); returns whether any is translucent. + */ +export function shadeTriangles( + geometry: BufferGeometry, + shader: Shader, + positions: number[], + normals: number[], + colors: number[] +): boolean { + const source = geometry.getAttribute('position').array; + const sourceNormals = geometry.getAttribute('normal')?.array; + const rgba: RGBA = [0, 0, 0, 0]; + let translucent = false; + const emit = (v: Vertex, normal: number[], lo: number, hi: number) => { + positions.push(v.p[0], v.p[1], v.p[2]); + normals.push(normal[0], normal[1], normal[2]); + shader.color(v.t, lo, hi, rgba); + colors.push(rgba[0], rgba[1], rgba[2], rgba[3]); + if (rgba[3] < 1) translucent = true; + }; + for (let i = 0; i + 8 < source.length; i += 9) { + const triangle: Vertex[] = [0, 3, 6].map((k) => { + const p: [number, number, number] = [source[i + k], source[i + k + 1], source[i + k + 2]]; + return { p, t: shader.t(p[0], p[2]) }; + }); + const normal = sourceNormals + ? [sourceNormals[i], sourceNormals[i + 1], sourceNormals[i + 2]] + : [0, 1, 0]; + const ts = triangle.map((v) => v.t); + const [min, max] = [Math.min(...ts), Math.max(...ts)]; + const inner = cutsBetween(shader.cuts, min, max); + if (!inner.length) { + const [lo, hi] = slabOf(shader.cuts, (ts[0] + ts[1] + ts[2]) / 3); + for (const v of triangle) emit(v, normal, lo, hi); + continue; + } + const bounds = [-Infinity, ...inner, Infinity]; + for (let k = 0; k + 1 < bounds.length; k++) { + const [lo, hi] = [bounds[k], bounds[k + 1]]; + let piece = triangle; + if (lo > -Infinity) piece = clip(piece, lo, true); + if (hi < Infinity) piece = clip(piece, hi, false); + // Fanned out from its first corner (a triangle cut by two lines stays convex) + for (let j = 1; j + 1 < piece.length; j++) { + emit(piece[0], normal, lo, hi); + emit(piece[j], normal, lo, hi); + emit(piece[j + 1], normal, lo, hi); + } + } + } + return translucent; +} + +/** + * A polyline's segments (points in the scene's axes) colored by `shader`, cut where its color + * changes course: each segment's ends (`positions`, 6 a segment), their linear RGB (`colors`, 6 a + * segment) and alpha (`alphas`, 2 a segment), and for each segment the polyline's segment it's + * part of and how far along that it starts (`from`) + */ +export function shadeSegments(points: ArrayLike, shader: Shader) { + const positions: number[] = []; + const colors: number[] = []; + const alphas: number[] = []; + const from: [segment: number, at: number][] = []; + const rgba: RGBA = [0, 0, 0, 0]; + for (let i = 0; i + 5 < points.length; i += 3) { + const a = [points[i], points[i + 1], points[i + 2]]; + const b = [points[i + 3], points[i + 4], points[i + 5]]; + const [ta, tb] = [shader.t(a[0], a[2]), shader.t(b[0], b[2])]; + const along = [0, ...cutsBetween(shader.cuts, ta, tb).map((c) => (c - ta) / (tb - ta)), 1]; + for (let k = 0; k + 1 < along.length; k++) { + const [s0, s1] = [along[k], along[k + 1]]; + const [lo, hi] = slabOf(shader.cuts, ta + (tb - ta) * ((s0 + s1) / 2)); + for (const s of [s0, s1]) { + for (let m = 0; m < 3; m++) positions.push(a[m] + (b[m] - a[m]) * s); + shader.color(ta + (tb - ta) * s, lo, hi, rgba); + colors.push(rgba[0], rgba[1], rgba[2]); + alphas.push(rgba[3]); + } + from.push([i / 3, s0]); + } + } + return { positions, colors, alphas, from }; +} + +/** + * A polyline colored by `shader`, as points with a color each (for a `Line2`): its own points, + * with more where its color changes course (a hard stop's point twice, a color each side). + * `source` is the polyline's point each is nearest along it. + */ +export function shadePolyline(points: ArrayLike, shader: Shader) { + const segments = shadeSegments(points, shader); + const positions: number[] = []; + const colors: number[] = []; + const alphas: number[] = []; + const source: number[] = []; + const push = (segment: number, end: 0 | 1) => { + for (let m = 0; m < 3; m++) { + positions.push(segments.positions[segment * 6 + end * 3 + m]); + colors.push(segments.colors[segment * 6 + end * 3 + m]); + } + alphas.push(segments.alphas[segment * 2 + end]); + const [line, at] = segments.from[segment]; + const next = segments.from[segment + 1]; + // Its end is where the next one starts along the same polyline segment, else its end + const s = end === 0 ? at : next && next[0] === line ? next[1] : 1; + source.push(line + (s >= 0.5 ? 1 : 0)); + }; + const count = segments.from.length; + for (let k = 0; k < count; k++) { + if (k === 0) push(0, 0); + else { + // A hard stop: its point again, in the next segment's color + const same = [0, 1, 2].every( + (m) => Math.abs(segments.colors[k * 6 + m] - segments.colors[(k - 1) * 6 + 3 + m]) < 1e-3 + ); + if (!same || Math.abs(segments.alphas[k * 2] - segments.alphas[(k - 1) * 2 + 1]) >= 1e-3) + push(k, 0); + } + push(k, 1); + } + return { positions, colors, alphas, source }; +} + +const alphaPatched = new WeakSet(); + +/** + * Let a line material take an alpha at each segment's ends (`setLineAlphas`), as a gradient's + * stops can (three.js' line colors are RGB only). Once patched, its lines must all have them. + */ +export function useLineAlphas(material: LineMaterial) { + if (alphaPatched.has(material)) return; + alphaPatched.add(material); + const before = material.onBeforeCompile; + material.onBeforeCompile = (shader, renderer) => { + before.call(material, shader, renderer); + shader.vertexShader = shader.vertexShader + .replace( + 'attribute vec3 instanceColorEnd;', + 'attribute vec3 instanceColorEnd;\nattribute float instanceAlphaStart;\nattribute float instanceAlphaEnd;\nvarying float vLcAlpha;' + ) + .replace( + 'void main() {', + 'void main() {\n\tvLcAlpha = ( position.y < 0.5 ) ? instanceAlphaStart : instanceAlphaEnd;' + ); + shader.fragmentShader = shader.fragmentShader + .replace('void main() {', 'varying float vLcAlpha;\nvoid main() {') + .replace( + 'gl_FragColor = vec4( diffuseColor.rgb, alpha );', + 'gl_FragColor = vec4( diffuseColor.rgb, alpha * vLcAlpha );' + ); + }; + const key = material.customProgramCacheKey.bind(material); + material.customProgramCacheKey = () => `${key()}-lc-line-alphas`; + material.transparent = true; + material.needsUpdate = true; +} + +/** Each segment's alpha at its start and end (2 a segment), for a material `useLineAlphas` patched */ +export function setLineAlphas(geometry: LineSegmentsGeometry, alphas: ArrayLike) { + const buffer = new InstancedInterleavedBuffer(new Float32Array(alphas), 2, 1); + geometry.setAttribute('instanceAlphaStart', new InterleavedBufferAttribute(buffer, 1, 0)); + geometry.setAttribute('instanceAlphaEnd', new InterleavedBufferAttribute(buffer, 1, 1)); +} + +/** A polyline's per-point alphas as its segments' (2 a segment), for `setLineAlphas` */ +export function segmentAlphas(pointAlphas: ArrayLike) { + const out: number[] = []; + for (let i = 0; i + 1 < pointAlphas.length; i++) out.push(pointAlphas[i], pointAlphas[i + 1]); + return out; +} + +/** Each pattern's tile texture, and the colors it was painted in */ +const textures = new WeakMap(); + +/** A CSS color resolved in the scene, as a color a 2D canvas takes */ +function cssOf(scene: SceneState, value: string): string | null { + const rgba = rgbaOf(scene, value, undefined)?.rgba; + if (!rgba) return null; + const [r, g, b] = rgba.slice(0, 3).map((v) => Math.round(v * 255)); + return `rgba(${r}, ${g}, ${b}, ${rgba[3]})`; +} + +/** A rect corner radius: pixels, or a percentage of half its side, as the core `Pattern`'s */ +function cornerPx(value: number | string | undefined, side: number): number { + if (value == null) return 0; + if (typeof value === 'number') return value; + const n = parseFloat(value); + if (!Number.isFinite(n)) return 0; + return value.trim().endsWith('%') ? (side / 2) * (n / 100) : n; +} + +/** + * A pattern's tile as a repeating texture, painted as the core `Pattern` paints its canvas tile + * (at twice the device's pixels, to stay sharp), or `null` before its colors resolve + */ +export function patternTexture(scene: SceneState, paint: PatternPaint): CanvasTexture | null { + const { width, height, shapes, background } = paint; + if (!(width > 0 && height > 0)) return null; + const gradient = paintOf(scene, background); + const backgroundShader = + gradient?.type === 'linear' + ? gradientShader(scene, gradient, { x: 0, y: 0, width, height }) + : null; + const fills = shapes.map((s) => cssOf(scene, s.type === 'line' ? s.stroke : s.fill)); + const backgroundColor = background && !gradient ? cssOf(scene, background) : null; + if (fills.some((f) => f == null) || (gradient && !backgroundShader)) return null; + const scale = Math.max(2, Math.ceil(globalThis.devicePixelRatio ?? 1)); + const key = JSON.stringify([ + width, + height, + shapes, + background, + fills, + backgroundColor, + backgroundShader?.key, + scale, + ]); + const cached = textures.get(paint); + if (cached && cached.key === key) return cached.texture; + + const canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(width * scale)); + canvas.height = Math.max(1, Math.round(height * scale)); + const context = canvas.getContext('2d'); + if (!context) return null; + if (backgroundShader) { + // Across each tile, as SVG fills the tile's background rect with it + const image = context.createImageData(canvas.width, canvas.height); + const rgba: RGBA = [0, 0, 0, 0]; + for (let py = 0; py < canvas.height; py++) { + for (let px = 0; px < canvas.width; px++) { + const t = backgroundShader.t((px + 0.5) / scale, (py + 0.5) / scale); + const [lo, hi] = slabOf(backgroundShader.cuts, t); + backgroundShader.color(t, lo, hi, rgba); + linear.setRGB(rgba[0], rgba[1], rgba[2]); + linear.getRGB(srgb, SRGBColorSpace); + const o = (py * canvas.width + px) * 4; + image.data[o] = srgb.r * 255; + image.data[o + 1] = srgb.g * 255; + image.data[o + 2] = srgb.b * 255; + image.data[o + 3] = rgba[3] * 255; + } + } + context.putImageData(image, 0, 0); + } + context.scale(canvas.width / width, canvas.height / height); + if (backgroundColor) { + context.fillStyle = backgroundColor; + context.fillRect(0, 0, width, height); + } + shapes.forEach((shape, i) => { + context.save(); + context.globalAlpha = shape.opacity; + if (shape.type === 'line') { + context.strokeStyle = fills[i]!; + context.lineWidth = Number(shape.strokeWidth) || 1; + context.stroke(new Path2D(shape.path)); + } else if (shape.type === 'circle') { + context.fillStyle = fills[i]!; + context.beginPath(); + context.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2); + context.fill(); + } else { + context.fillStyle = fills[i]!; + const rx = cornerPx(shape.rx, shape.width); + const ry = shape.ry == null ? rx : cornerPx(shape.ry, shape.height); + context.beginPath(); + if (rx > 0 || ry > 0) { + context.roundRect(shape.x, shape.y, shape.width, shape.height, [{ x: rx, y: ry }]); + } else context.rect(shape.x, shape.y, shape.width, shape.height); + context.fill(); + } + context.restore(); + }); + + const texture = new CanvasTexture(canvas); + texture.colorSpace = SRGBColorSpace; + texture.wrapS = texture.wrapT = RepeatWrapping; + // Down the plot is down the tile + texture.flipY = false; + texture.generateMipmaps = false; + texture.minFilter = texture.magFilter = LinearFilter; + cached?.texture.dispose(); + textures.set(paint, { key, texture }); + return texture; +} + +/** + * Shapes filled with patterns, a mesh a pattern (its tile repeating from the plot's origin, as an + * SVG pattern's `userSpaceOnUse` tiles), beside a merged mark's own mesh. Made only once a mark + * has a patterned shape. + */ +export function createPatternFills(scene: SceneState, layer: Group) { + const meshes = new Map>(); + /** Each pattern's shapes this time, in the scene's axes: positions and normals */ + let pending = new Map(); + + return { + /** Add a shape (non-indexed) filled with `paint` */ + add(paint: PatternPaint, geometry: BufferGeometry) { + let entry = pending.get(paint); + if (!entry) pending.set(paint, (entry = { positions: [], normals: [] })); + const positions = geometry.getAttribute('position').array; + const normals = geometry.getAttribute('normal')?.array; + for (let i = 0; i < positions.length; i++) { + entry.positions.push(positions[i]); + entry.normals.push(normals ? normals[i] : i % 3 === 1 ? 1 : 0); + } + }, + /** Draw what was added since the last time, at `opacity` */ + update(opacity: number) { + for (const [paint, mesh] of meshes) { + if (pending.has(paint)) continue; + layer.remove(mesh); + mesh.geometry.dispose(); + mesh.material.dispose(); + meshes.delete(paint); + } + for (const [paint, { positions, normals }] of pending) { + let mesh = meshes.get(paint); + if (!mesh) { + const material = new MeshLambertMaterial({ transparent: true, side: DoubleSide }); + mesh = new Mesh(new BufferGeometry(), material); + mesh.receiveShadow = true; + layer.add(mesh); + meshes.set(paint, mesh); + } + const uvs: number[] = []; + for (let i = 0; i + 2 < positions.length; i += 3) { + uvs.push(positions[i] / paint.width, positions[i + 2] / paint.height); + } + const geometry = new BufferGeometry(); + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)); + geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3)); + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); + mesh.geometry.dispose(); + mesh.geometry = geometry; + const texture = patternTexture(scene, paint); + if (mesh.material.map !== texture) { + mesh.material.map = texture; + mesh.material.needsUpdate = true; + } + mesh.visible = texture != null; + mesh.material.opacity = opacity; + } + pending = new Map(); + }, + dispose() { + for (const mesh of meshes.values()) { + layer.remove(mesh); + mesh.geometry.dispose(); + mesh.material.dispose(); + } + meshes.clear(); + }, + }; +} diff --git a/packages/webgl/src/lib/utils/shapes.ts b/packages/webgl/src/lib/utils/shapes.ts index 47d210fbf3..5f92265d77 100644 --- a/packages/webgl/src/lib/utils/shapes.ts +++ b/packages/webgl/src/lib/utils/shapes.ts @@ -63,11 +63,14 @@ export class ShapeContext { if (!this.#line) this.moveTo(...start); else this.lineTo(...start); (this.path.currentPath as Path).absarc(x, -y, r, -a0, -a1, !ccw); - // Outlines follow the arc in steps - const sweep = ccw ? a0 - a1 : a1 - a0; - const steps = Math.max(2, Math.ceil((Math.abs(sweep) / Math.PI) * 16)); + // Outlines follow the arc in steps, the way round a canvas' `arc` goes (ex. a corner's arc + // from just under π to just over -π is short, not most of a turn) + const tau = Math.PI * 2; + const turn = ccw ? a0 - a1 : a1 - a0; + const sweep = Math.abs(a1 - a0) >= tau ? tau : ((turn % tau) + tau) % tau; + const steps = Math.max(2, Math.ceil((sweep / Math.PI) * 16)); for (let i = 1; i <= steps; i++) { - const a = a0 + ((ccw ? -1 : 1) * Math.abs(sweep) * i) / steps; + const a = a0 + ((ccw ? -1 : 1) * sweep * i) / steps; this.#line!.push([x + r * Math.cos(a), y + r * Math.sin(a)]); } } diff --git a/packages/webgl/src/lib/webgl.ts b/packages/webgl/src/lib/webgl.ts index 3e2e56c419..e08a7d6ae3 100644 --- a/packages/webgl/src/lib/webgl.ts +++ b/packages/webgl/src/lib/webgl.ts @@ -114,3 +114,39 @@ export { default as Density } from './components/Density/Density.webgl.svelte'; export type { DensityProps } from './components/Density/Density.svelte'; export { default as Ribbon } from './components/Ribbon/Ribbon.webgl.svelte'; export type { RibbonProps } from './components/Ribbon/Ribbon.svelte'; + +// Clips for the marks inside +export { default as ClipPath } from './components/ClipPath/ClipPath.webgl.svelte'; +export type { ClipPathProps } from './components/ClipPath/ClipPath.svelte'; +export { default as RectClipPath } from './components/RectClipPath/RectClipPath.webgl.svelte'; +export type { RectClipPathProps } from './components/RectClipPath/RectClipPath.svelte'; +export { default as CircleClipPath } from './components/CircleClipPath/CircleClipPath.webgl.svelte'; +export type { CircleClipPathPropsWithoutHTML } from './components/CircleClipPath/CircleClipPath.svelte'; +export { default as GeoClipPath } from './components/GeoClipPath/GeoClipPath.webgl.svelte'; +export type { GeoClipPathProps } from './components/GeoClipPath/GeoClipPath.svelte'; +export { default as ChartClipPath } from './components/ChartClipPath/ChartClipPath.webgl.svelte'; +export type { ChartClipPathProps } from './components/ChartClipPath/ChartClipPath.svelte'; + +// LayerChart's contexts and layouts (drawing nothing themselves), and its legends beside the scene +export { Bounds, ChartGroup, CircleLegend, Dodge, Point } from 'layerchart'; +export { Chord, Dagre, Sankey } from 'layerchart/graph'; +export { Pack, Partition, Tree, Treemap } from 'layerchart/hierarchy'; +export { GeoLegend, GeoProjection, GeoVisible } from 'layerchart/geo'; +export { default as Image } from './components/Image/Image.webgl.svelte'; +export type { ImageProps } from './components/Image/Image.svelte'; +export { default as Ellipse } from './components/Ellipse/Ellipse.webgl.svelte'; +export type { EllipseProps } from './components/Ellipse/Ellipse.svelte'; +export { default as Waffle } from './components/Waffle/Waffle.webgl.svelte'; +export type { WaffleProps } from './components/Waffle/Waffle.svelte'; +export { default as Voronoi } from './components/Voronoi/Voronoi.webgl.svelte'; +export type { VoronoiProps } from './components/Voronoi/Voronoi.svelte'; +export { default as GeoBin } from './components/GeoBin/GeoBin.webgl.svelte'; +export type { GeoBinProps } from './components/GeoBin/GeoBin.svelte'; +export { default as GeoCircle } from './components/GeoCircle/GeoCircle.webgl.svelte'; +export type { GeoCircleProps } from './components/GeoCircle/GeoCircle.svelte'; +export { default as GeoSpline } from './components/GeoSpline/GeoSpline.webgl.svelte'; +export type { GeoSplineProps } from './components/GeoSpline/GeoSpline.svelte'; +export { default as GeoEdgeFade } from './components/GeoEdgeFade/GeoEdgeFade.webgl.svelte'; +export type { GeoEdgeFadeProps } from './components/GeoEdgeFade/GeoEdgeFade.svelte'; +export { default as Brush } from './components/Brush/Brush.webgl.svelte'; +export type { BrushProps } from './components/Brush/Brush.svelte'; From bdf5f7c2bebd6191e03d1d5c7cf44f9ded7edbbd Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Fri, 27 Nov 2026 00:29:44 -0500 Subject: [PATCH 15/16] docs: Check 523 more WebGL examples, convert charts without a Layer, and group the zoom buttons Co-Authored-By: Claude Opus 5.5 --- docs/src/routes/docs/examples/+page.svelte | 46 +- docs/vite-plugin-webgl-examples.ts | 30 +- docs/webgl-examples.ts | 525 ++++++++++++++++++++- 3 files changed, 578 insertions(+), 23 deletions(-) diff --git a/docs/src/routes/docs/examples/+page.svelte b/docs/src/routes/docs/examples/+page.svelte index 0a1782bc0b..fd8381f955 100644 --- a/docs/src/routes/docs/examples/+page.svelte +++ b/docs/src/routes/docs/examples/+page.svelte @@ -1,6 +1,5 @@