diff --git a/.changeset/camera-views.md b/.changeset/camera-views.md new file mode 100644 index 0000000000..2583d8e194 --- /dev/null +++ b/.changeset/camera-views.md @@ -0,0 +1,5 @@ +--- +'layerchart': minor +--- + +feat(Chart): Add `perspective` and `orthographic` views for 3D layers (ex. `@layerchart/webgl`) diff --git a/.changeset/config.json b/.changeset/config.json index d3c43a3c64..c652867c5c 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -2,7 +2,7 @@ "$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json", "changelog": ["@svitejs/changesets-changelog-github-compact", { "repo": "techniq/layerchart" }], "commit": false, - "fixed": [], + "fixed": [["layerchart", "@layerchart/webgl"]], "linked": [], "access": "public", "baseBranch": "main", diff --git a/.changeset/drag-dblclick.md b/.changeset/drag-dblclick.md new file mode 100644 index 0000000000..57fd8a2549 --- /dev/null +++ b/.changeset/drag-dblclick.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(TransformContext): Don't zoom in on the double click two quick drags make diff --git a/.changeset/highlight-domain-motion.md b/.changeset/highlight-domain-motion.md new file mode 100644 index 0000000000..d6e176faac --- /dev/null +++ b/.changeset/highlight-domain-motion.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(Highlight): Follow a `domain` pan or zoom at once rather than springing after it diff --git a/.changeset/isometric-axis-tick-spacing.md b/.changeset/isometric-axis-tick-spacing.md new file mode 100644 index 0000000000..882bc74457 --- /dev/null +++ b/.changeset/isometric-axis-tick-spacing.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(Axis): Space ticks evenly along every axis of an `isometric` chart, rather than wider along `x` diff --git a/.changeset/isometric-pivot.md b/.changeset/isometric-pivot.md new file mode 100644 index 0000000000..783cea2e14 --- /dev/null +++ b/.changeset/isometric-pivot.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(Chart): Turn a panned `isometric` view about what's in the middle rather than the floor's center diff --git a/.changeset/isometric-view-code.md b/.changeset/isometric-view-code.md new file mode 100644 index 0000000000..4d6a4e8ac1 --- /dev/null +++ b/.changeset/isometric-view-code.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +refactor(isometric): Rename the view's `impl` to `isometric`, and `IsometricImpl` to `Isometric` (the old type name kept, deprecated) diff --git a/.changeset/layerchart-webgl.md b/.changeset/layerchart-webgl.md new file mode 100644 index 0000000000..535ab9e7e3 --- /dev/null +++ b/.changeset/layerchart-webgl.md @@ -0,0 +1,5 @@ +--- +'@layerchart/webgl': minor +--- + +feat: New `@layerchart/webgl` package, drawing data-dense 2D charts and 3D views (perspective, lights and shadows, surfaces, globes, map terrain) with WebGL diff --git a/.changeset/mark-z-extent.md b/.changeset/mark-z-extent.md new file mode 100644 index 0000000000..72d9c038cc --- /dev/null +++ b/.changeset/mark-z-extent.md @@ -0,0 +1,5 @@ +--- +'layerchart': minor +--- + +feat(Chart): Add `MarkInfo.zExtent`, so a mark's own heights widen an automatic `zDomain` diff --git a/.changeset/numeric-color-key-no-grouping.md b/.changeset/numeric-color-key-no-grouping.md new file mode 100644 index 0000000000..38955a0054 --- /dev/null +++ b/.changeset/numeric-color-key-no-grouping.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(Spline, Area): Color by a numeric data key (`stroke="value"`) without splitting into a line per value diff --git a/.changeset/quadtree-domain-settle.md b/.changeset/quadtree-domain-settle.md new file mode 100644 index 0000000000..0f183a169b --- /dev/null +++ b/.changeset/quadtree-domain-settle.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(TooltipContext): Rebuild a `quadtree` tooltip once a `domain` pan or zoom settles, rather than at every step diff --git a/.changeset/shared-exports.md b/.changeset/shared-exports.md new file mode 100644 index 0000000000..c8c052d919 --- /dev/null +++ b/.changeset/shared-exports.md @@ -0,0 +1,5 @@ +--- +'layerchart': minor +--- + +feat: Export `binCells`, `binGrid`, and `isScaleLinear` for drawing marks in other layers (ex. `@layerchart/webgl`) diff --git a/.changeset/shift-scroll-zoom.md b/.changeset/shift-scroll-zoom.md new file mode 100644 index 0000000000..fc5ea5395c --- /dev/null +++ b/.changeset/shift-scroll-zoom.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(TransformContext): Zoom on a slightly diagonal `shift` scroll (ex. a trackpad swipe) rather than panning a `domain` sideways diff --git a/.changeset/tooltip-reappear.md b/.changeset/tooltip-reappear.md new file mode 100644 index 0000000000..f2288c1d49 --- /dev/null +++ b/.changeset/tooltip-reappear.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(Tooltip): Appear at the pointer when shown again (ex. after a drag), rather than gliding from where it was last diff --git a/.changeset/transform-rotation-extent.md b/.changeset/transform-rotation-extent.md new file mode 100644 index 0000000000..9ca4cc2f4a --- /dev/null +++ b/.changeset/transform-rotation-extent.md @@ -0,0 +1,5 @@ +--- +'layerchart': minor +--- + +feat(TransformContext): Add `rotationExtent` (or `rotateExtent` / `tiltExtent`) to limit how far a drag turns a `view` or globe, and pass the turned `rotation` to `constrain` diff --git a/.gitignore b/.gitignore index e66fd2bb23..61120b8c4d 100644 --- a/.gitignore +++ b/.gitignore @@ -20,10 +20,12 @@ bench-results/ .live-code/ # Generated API documentation -**/generated/api/*.json +**/generated/api/**/*.json # Generated StackBlitz files **/static/stackblitz-files.json .playwright-mcp -.openchamber \ No newline at end of file +.openchamber +# Local promo / video projects (ex. examples/promo-webgl), not part of the repo +examples/promo-*/ diff --git a/docs/.gitignore b/docs/.gitignore index 55465cfaae..dbe92131e9 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -27,7 +27,7 @@ vite.config.ts.timestamp-* .content-collections # Generated API documentation -generated/api/*.json +generated/api/**/*.json # Generated StackBlitz files static/stackblitz-files.json \ No newline at end of file diff --git a/docs/package.json b/docs/package.json index fa4f9d42f0..8ecf4669fd 100644 --- a/docs/package.json +++ b/docs/package.json @@ -4,6 +4,7 @@ "version": "0.0.1", "type": "module", "scripts": { + "predev": "pnpm generate:stackblitz", "dev": "vite dev --port 3002", "build": "vite build", "prebuild": "pnpm generate:api && pnpm generate:stackblitz && pnpm generate:releases", @@ -17,9 +18,9 @@ "test": "pnpm test:unit -- --run", "test:visual": "node scripts/visual-snapshot.mjs capture snapshots/current.json --repeat 1 && node scripts/visual-snapshot.mjs compare snapshots/baseline.json snapshots/current.json", "test:visual:update": "node scripts/visual-snapshot.mjs capture snapshots/baseline.json --repeat 3", - "generate:api": "layerstack-docs generate-api ../packages/layerchart/src/lib/components generated/api", + "generate:api": "layerstack-docs generate-api ../packages/layerchart/src/lib/components generated/api && layerstack-docs generate-api ../packages/webgl/src/lib/components generated/api/webgl", "generate:screenshots": "layerstack-docs generate-screenshots src/examples/components static/screenshots", - "generate:catalog": "layerstack-docs generate-catalog ../packages/layerchart/src/lib/components src/examples/components src/examples/catalog", + "generate:catalog": "layerstack-docs generate-catalog ../packages/layerchart/src/lib/components src/examples/components src/examples/catalog && layerstack-docs generate-catalog ../packages/webgl/src/lib/components src/examples/components/webgl src/examples/catalog/webgl", "generate:stackblitz": "layerstack-docs generate-stackblitz src static/stackblitz-files.json static/remote-sources.json --source src/lib/utils/data.ts=lib/utils/data.ts --remote data.remote.ts=lib/data.remote.ts --remote geo.remote.ts=lib/geo.remote.ts --remote graph.remote.ts=lib/graph.remote.ts", "generate:releases": "layerstack-docs generate-releases techniq/layerchart generated/releases", "generate:all": "pnpm generate:api && pnpm generate:screenshots && pnpm generate:catalog && pnpm generate:stackblitz && pnpm generate:releases" @@ -33,6 +34,7 @@ "@iconify-json/lucide": "^1.2.111", "@iconify-json/simple-icons": "^1.2.85", "@iconify-json/vscode-icons": "^1.2.53", + "@layerchart/webgl": "workspace:*", "@layerstack/docs": "1.0.0-next.6", "@layerstack/svelte-actions": "1.0.1-next.20", "@layerstack/svelte-state": "0.1.0-next.25", @@ -44,6 +46,7 @@ "@sveltejs/kit": "^2.70.4", "@sveltejs/vite-plugin-svelte": "^7.1.2", "@tailwindcss/vite": "^4.3.0", + "@threlte/core": "^8.6.1", "@types/d3-array": "^3.2.2", "@types/d3-color": "^3.1.3", "@types/d3-dsv": "^3.0.7", @@ -59,6 +62,7 @@ "@types/d3-time": "^3.0.4", "@types/node": "^25.9.1", "@types/shapefile": "^0.6.4", + "@types/three": "^0.187.0", "@types/topojson-client": "^3.1.5", "@types/topojson-server": "^3.0.4", "@types/topojson-simplify": "^3.0.3", @@ -98,6 +102,7 @@ "svelte-check": "^4.5.0", "svelte-ux": "2.0.0-next.22", "tailwindcss": "^4.3.0", + "three": "^0.187.0", "topojson-client": "^3.1.0", "topojson-server": "^3.0.1", "topojson-simplify": "^3.0.3", diff --git a/docs/scripts/kontur-population.mjs b/docs/scripts/kontur-population.mjs new file mode 100644 index 0000000000..d355abd5e4 --- /dev/null +++ b/docs/scripts/kontur-population.mjs @@ -0,0 +1,151 @@ +/** + * Builds the people in each state for the `WebGL/state-population` example from Kontur Population + * (November 2023, CC BY 4.0): 400m H3 hexagons, which for the whole US is a 300MB download and an + * 840MB GeoPackage — too much to commit or fetch on every build. + * + * node scripts/kontur-population.mjs + * + * Download and unzip it first: + * https://geodata-eu-central-1-kontur-public.s3.amazonaws.com/kontur_datasets/kontur_population_US_20231101.gpkg.gz + * + * Each hexagon's people go to the 0.01° cell its center is in, and each state's cells (clipped to + * us-atlas' 1:10m outlines) are summed again into about `COLUMNS` cells across the state. Its + * largest places, from Natural Earth's populated places (public domain), are kept to label. + * Writes `static/data/examples/geo/kontur-population/.json`: the cells as whole steps from + * the state's southwest corner, and the places as `[name, longitude, latitude]`, + * `{ origin, step, cells: [i, j, people, ...], cities }`. + */ +import { mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { geoBounds, geoContains, geoDistance } from 'd3-geo'; +import { feature } from 'topojson-client'; + +/** us-atlas' territories, which Kontur's US population leaves out */ +const TERRITORIES = [ + 'American Samoa', + 'Commonwealth of the Northern Mariana Islands', + 'Guam', + 'Puerto Rico', + 'United States Virgin Islands' +]; +/** How many places to label in each state, and how far apart, as a share of its size */ +const CITIES = 6; +const CITY_SPACING = 0.12; +/** About how many cells across each state, so its hexagons have a few each */ +const COLUMNS = 160; +/** The cells hexagons are first summed into, in degrees */ +const FINE = 0.01; +const ATLAS_URL = 'https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json'; +const PLACES_URL = + 'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson/ne_10m_populated_places_simple.geojson'; +const OUT = 'static/data/examples/geo/kontur-population'; + +const [source] = process.argv.slice(2); +if (!source) { + console.error('Usage: node scripts/kontur-population.mjs '); + process.exit(1); +} + +const topology = await fetch(ATLAS_URL).then((r) => r.json()); +const states = feature(topology, topology.objects.states).features.filter( + (f) => !TERRITORIES.includes(f.properties.name) +); +const places = (await fetch(PLACES_URL).then((r) => r.json())).features + .map((f) => f.properties) + .filter((p) => p.adm0_a3 === 'USA'); + +// Web Mercator (the GeoPackage's EPSG:3857) to and from longitude / latitude +const R = 20037508.342789244; +const toLonLat = (x, y) => [ + (x / R) * 180, + (2 * Math.atan(Math.exp((y / R) * Math.PI)) - Math.PI / 2) * (180 / Math.PI) +]; + +/** People in each fine cell, by `i,j` */ +const fine = new Map(); +const db = new DatabaseSync(source, { readOnly: true }); +for (const { population, geom } of db + .prepare('select population, geom from population') + .iterate()) { + // A GeoPackage geometry's header: "GP", version, flags, SRS id, then (as its flags say) its + // envelope — here `[minx, maxx, miny, maxy]`, whose middle is the hexagon's center + const flags = geom[3]; + if (((flags >> 1) & 7) === 0) continue; + const view = new DataView(geom.buffer, geom.byteOffset + 8, 32); + const little = (flags & 1) === 1; + const [minx, maxx, miny, maxy] = [0, 8, 16, 24].map((o) => view.getFloat64(o, little)); + const [lon, lat] = toLonLat((minx + maxx) / 2, (miny + maxy) / 2); + const key = `${Math.round(lon / FINE)},${Math.round(lat / FINE)}`; + fine.set(key, (fine.get(key) ?? 0) + population); +} +const rows = Array.from(fine, ([key, people]) => { + const [i, j] = key.split(',').map(Number); + return [+(i * FINE).toFixed(2), +(j * FINE).toFixed(2), Math.round(people)]; +}); + +mkdirSync(OUT, { recursive: true }); +for (const state of states) { + const [[w, s], [e, n]] = geoBounds(state); + // Alaska's Aleutians cross the antimeridian, so its west edge is east of its east edge + const wraps = w > e; + const width = wraps ? e - w + 360 : e - w; + const inside = (lon) => (wraps ? lon >= w || lon <= e : lon >= w && lon <= e); + const lat = (s + n) / 2; + // Cells about square on the ground: a degree of longitude is shorter than one of latitude + const across = Math.cos((lat * Math.PI) / 180); + const step = +(Math.max(width * across, n - s) / COLUMNS).toPrecision(2); + const stepLon = +(step / across).toPrecision(2); + + const cells = new Map(); + let people = 0; + for (const [lon, la, count] of rows) { + if (!inside(lon) || la < s || la > n || !geoContains(state, [lon, la])) continue; + const key = `${Math.round(lon / stepLon)},${Math.round(la / step)}`; + cells.set(key, (cells.get(key) ?? 0) + count); + people += count; + } + const entries = Array.from(cells, ([key, count]) => [ + ...key.split(',').map(Number), + Math.round(count) + ]).filter((d) => d[2] > 0); + const i0 = Math.min(...entries.map((d) => d[0])); + const j0 = Math.min(...entries.map((d) => d[1])); + const data = { + origin: [+(i0 * stepLon).toFixed(4), +(j0 * step).toFixed(4)], + step: [stepLon, step], + cells: entries.flatMap(([i, j, count]) => [i - i0, j - j0, count]) + }; + // The largest places, each a little way from those already kept + const spacing = geoDistance([w, s], [w + width, n]) * CITY_SPACING; + const cities = []; + const candidates = places + .filter((p) => p.adm1name === state.properties.name) + .sort((a, b) => b.pop_max - a.pop_max); + for (const p of candidates) { + if (cities.length >= CITIES) break; + const at = [p.longitude, p.latitude]; + if (cities.some(([, lon, la]) => geoDistance(at, [lon, la]) < spacing)) continue; + cities.push([p.name, +p.longitude.toFixed(3), +p.latitude.toFixed(3)]); + } + data.cities = cities; + + const slug = state.properties.name.toLowerCase().replace(/ /g, '-'); + writeFileSync(join(OUT, `${slug}.json`), JSON.stringify(data)); + console.log( + `${slug}: ${entries.length} cells, ${Math.round(people).toLocaleString()} people, ${cities.map((c) => c[0]).join(', ')}` + ); +} + +// Every state there's a file for, by its file and name, for the example's list (and prerendering) +writeFileSync( + join(OUT, 'states.json'), + JSON.stringify( + states + .map((state) => ({ + value: state.properties.name.toLowerCase().replace(/ /g, '-'), + label: state.properties.name + })) + .sort((a, b) => a.label.localeCompare(b.label)) + ) +); diff --git a/docs/src/content/components/webgl/Arc.md b/docs/src/content/components/webgl/Arc.md new file mode 100644 index 0000000000..59b78f6866 --- /dev/null +++ b/docs/src/content/components/webgl/Arc.md @@ -0,0 +1,21 @@ +--- +description: 'Primitive component which draws a curved segment on a chart to represent portions of a whole or highlight specific data ranges. In a WebGL layer, it stands up by its z.' +category: WebGL marks +related: [Arc, guides/webgl] +components: + - { name: webgl/Arc, label: Arc } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +An arc with the core [Arc](/docs/components/Arc) props: from `startAngle` to `endAngle` (ex. a slice from `d3.pie()`), or to a `value` through its `domain` and `range`, over a `track`. Radii are pixels, fractions of the chart's radius, or offsets from it, as the core are, and `class` styles it as on any core mark. It's centered in the plot (where the core draws inside a centered `Layer` or `Group`); `x` / `y` move it. `z` stands it up, as on an `isometric` chart; without one it lies flat. + +:example{ name="pie" } + +The core [concentric gauges](/docs/components/Arc/concentric) example, unchanged but for `z`: + +:example{ name="concentric" } diff --git a/docs/src/content/components/webgl/Area.md b/docs/src/content/components/webgl/Area.md new file mode 100644 index 0000000000..2407f2ebc7 --- /dev/null +++ b/docs/src/content/components/webgl/Area.md @@ -0,0 +1,19 @@ +--- +description: 'Marking component which shades the space under a line on a chart to emphasize the magnitude and trend of data over a range. In a WebGL layer, it lies on the floor, or rises as a curtain with a z.' +category: WebGL marks +related: [Area, guides/webgl] +components: + - { name: webgl/Area, label: Area } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A curtain from the floor (or `z0`) up to `z` along the rows, one per group. + +:example{ name="areas" } + +:example{ name="ridgeline" } diff --git a/docs/src/content/components/webgl/Axis.md b/docs/src/content/components/webgl/Axis.md new file mode 100644 index 0000000000..fed0547f87 --- /dev/null +++ b/docs/src/content/components/webgl/Axis.md @@ -0,0 +1,35 @@ +--- +description: "Commonly used component displays the scale and reference lines on a chart, providing context for interpreting data values. In a WebGL layer, it runs along the plot box's edges: bottom for x, left for y, and back for z." +category: WebGL +related: [Axis, guides/webgl] +components: + - { name: webgl/Axis, label: Axis } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Tick labels along an edge: `bottom` for `x`, `left` for `y`, and `back` for `z` (up the corner behind the plot). They keep to the edges in front as the view turns. + +Labels are drawn on the plot box, turning with it: the floor's (`bottom`, `left`) lie on it, as on an [isometric](/docs/guides/isometric#text) chart, and the height axis' (`back`) stand on the back wall beside its edge. `tickLabelProps={{ viewport: true }}` and `labelProps={{ viewport: true }}` draw them facing the viewer instead, over the scene, upright and crisp however the view turns. + +```svelte + + + + + + +``` + +:example{ component="webgl/Points" name="scatter-3d" } + +:example{ component="webgl/Spline" name="temperatures" } diff --git a/docs/src/content/components/webgl/Bars.md b/docs/src/content/components/webgl/Bars.md new file mode 100644 index 0000000000..e66fb874c8 --- /dev/null +++ b/docs/src/content/components/webgl/Bars.md @@ -0,0 +1,45 @@ +--- +description: 'Marking component which applies horizontal bars to represent and visually compare discrete data values. In a WebGL layer, each bar is a box standing as tall as its z.' +category: WebGL marks +related: [Bars, guides/webgl] +components: + - { name: webgl/Bars, label: Bars } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A box per row, standing on its `x` × `y` band cell, as tall as its `z`. + +```svelte + + + + + +``` + +:example{ name="columns" } + +## Stacked + +With series and `valueAxis="z"`, bars stack up off the floor. + +:example{ name="stacked-columns" } + +## Heatmap and calendar + +:example{ name="heatmap" } + +:example{ name="calendar" } diff --git a/docs/src/content/components/webgl/Bin.md b/docs/src/content/components/webgl/Bin.md new file mode 100644 index 0000000000..8cc8848567 --- /dev/null +++ b/docs/src/content/components/webgl/Bin.md @@ -0,0 +1,31 @@ +--- +description: 'Composite mark grouping two-dimensional points into a grid of hexagons, squares, or triangles, to count or summarize what falls in each cell. In a WebGL layer, each cell stands as tall as its z.' +category: WebGL marks +related: [Bin, GeoBin, guides/webgl] +components: + - { name: webgl/Bin, label: Bin } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Rows grouped into hexagons (or squares, or triangles) of the plot, or of the map as projected, as the core [Bin](/docs/components/Bin) groups them. Each cell stands up `z` tall (ex. its `count`), colored by its count unless given a `fill`. Every cell is the same shape, so thousands draw as one. + +```svelte + + + +``` + +:example{ name="hexbin" } + +## On a map + +:example{ name="walmart" } + +`weight` counts each row by a value (ex. the people in a cell of gridded population), and `gap` stands the cells apart. + +:example{ name="state-population" } diff --git a/docs/src/content/components/webgl/Contour.md b/docs/src/content/components/webgl/Contour.md new file mode 100644 index 0000000000..4ff422ffa7 --- /dev/null +++ b/docs/src/content/components/webgl/Contour.md @@ -0,0 +1,17 @@ +--- +description: 'Composite mark drawing isolines to delineate regions above and below a particular continuous value. Supports grid data, scattered data with spatial interpolation, and continuous functions. In a WebGL layer, its lines lie flat or rise to their heights.' +category: WebGL surfaces +related: [Contour, guides/webgl] +components: + - { name: webgl/Contour, label: Contour } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Contour lines on their own: flat at `z` pixels (ex. over a `Raster`), or each raised to its threshold's height with `z="value"`. It takes values the same ways as [Surface](/docs/components/webgl/Surface). + +:example{ name="basic" } diff --git a/docs/src/content/components/webgl/GeoPath.md b/docs/src/content/components/webgl/GeoPath.md new file mode 100644 index 0000000000..613a1a7fcf --- /dev/null +++ b/docs/src/content/components/webgl/GeoPath.md @@ -0,0 +1,37 @@ +--- +description: 'Geographic component which renders shapes such as countries, states, or regions by drawing their boundaries based on coordinate data. In a WebGL layer, features rise by their z, or follow a globe.' +category: WebGL geo +related: [GeoPath, guides/webgl, guides/geo] +components: + - { name: webgl/GeoPath, label: GeoPath } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Features on the floor through the chart's projection, extruded `z` tall (a property key or function of the feature, through the chart's `z` scale, or pixels). Lines, and outlines with `stroke`, draw on top. A collection draws as one mark, so thousands of features stay quick. `motion` eases each feature's height and fill to new values. + +```svelte + + + d.properties.population} fill="var(--color-primary)" /> + + +``` + +:example{ name="election" } + +## Buildings, with shadows + +d3-geo reads a polygon's outside ring clockwise, and the other way round as the rest of the world, so rewind rings from other sources (ex. OpenStreetMap) before drawing them. + +:example{ component="webgl/Light" name="buildings" } + +## On a globe + +With the `globe` projection, features' lines draw over the sphere, and `{ type: 'Sphere' }` fills the globe itself (ex. beneath an image still loading). + +:example{ component="webgl/GeoRaster" name="globe-tiles" } diff --git a/docs/src/content/components/webgl/GeoRaster.md b/docs/src/content/components/webgl/GeoRaster.md new file mode 100644 index 0000000000..769ce42016 --- /dev/null +++ b/docs/src/content/components/webgl/GeoRaster.md @@ -0,0 +1,48 @@ +--- +description: 'Geographic component which reprojects a raster image (such as NASA Blue Marble) onto any d3-geo projection. In a WebGL layer, the image can rise into terrain or wrap a globe.' +category: WebGL geo +related: [GeoRaster, guides/webgl, guides/geo] +components: + - { name: webgl/GeoRaster, label: GeoRaster } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +An image (`image`: a URL, or an image, canvas, or bitmap) laid over the map through the chart's projection, as the core [GeoRaster](/docs/components/GeoRaster) reprojects one, and with the same props: it's equirectangular unless `sourceProjection` gives the projection it was drawn in, and `interpolate` / `pixelated` choose blended or crisp pixels. Unlike core's, it blends (`'bilinear'`) by default, which costs the GPU nothing. `elevation` (a function of longitude and latitude) raises it into terrain, and `tooltip` shows the longitude and latitude under the pointer. + +:example{ name="projections" } + +## Terrain + +Map tiles stitched into one image (`sourceProjection` maps longitude and latitude onto its Web Mercator pixels) and draped over `elevation`, lit by a `Light`: satellite imagery over a mountain, at true scale times the exaggeration. The tiles load once for the area, so they don't sharpen as you zoom in. + +:example{ name="terrain" } + +## Globe + +The `globe` projection lays the map on a real sphere you can orbit. Fit it as an orthographic map (the sphere is the size and place the disk would be, standing on the floor) and the same marks draw on it: `GeoRaster` wraps it in an image, `GeoPath` follows its curve, `Points` and `Bars` stand out from it, `Spline` runs along great circles, and `Surface` / `Raster` cover it. + +```svelte + + + + + + + + +``` + +:example{ name="globe" } + +:example{ name="planets" } + +:example{ name="globe-textures" } + +:example{ name="globe-tiles" } diff --git a/docs/src/content/components/webgl/GeoTile.md b/docs/src/content/components/webgl/GeoTile.md new file mode 100644 index 0000000000..85d5e9318c --- /dev/null +++ b/docs/src/content/components/webgl/GeoTile.md @@ -0,0 +1,40 @@ +--- +description: 'Geographic component which renders map tiles in a grid supporting efficient zooming and panning for larger scale maps. In a WebGL layer, tiles can rise into terrain from elevation tiles.' +category: WebGL geo +related: [GeoTile, GeoRaster, guides/webgl, guides/geo] +components: + - { name: webgl/GeoTile, label: GeoTile } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Map tiles from an XYZ tile service, with the core [GeoTile](/docs/components/GeoTile) props (`url`, `zoomDelta`, `tileSize`, `disableCache`, `debug`), picked for the chart's Web Mercator projection as it picks them. A `projection` transform zooms the map, and sharper tiles load as it does. + +:example{ name="zoomable" } + +## Terrain + +`elevation` raises the tiles from a second tile service of elevation tiles (ex. AWS's open terrain tiles, or Mapterhorn): their `url`, `encoding` (`'terrarium'`, or Terrain-RGB as `'mapbox'`), and `maxZoom`, their meters through the chart's `z` scale. `maxZoom` and the elevation's `maxZoom` say how deep each service goes: deeper tiles show part of their ancestor, enlarged. + +```svelte + `https://tiles.versatiles.org/tiles/satellite-raster/${z}/${x}/${y}`} + maxZoom={12} + elevation={{ + url: (x, y, z) => `https://s3.amazonaws.com/elevation-tiles-prod/terrarium/${z}/${x}/${y}.png`, + maxZoom: 15 + }} +/> +``` + +:example{ name="terrain" } + +## Detail that follows the camera + +In a 3D view, tiles are picked from the camera rather than the projection: each tile is as deep as it needs to be to look about `tileSize` pixels across on screen, so tiles are sharp up close and coarse in the distance, and sharpen as the camera moves in. A new tile draws at once from an ancestor already loaded (blurrier, as the tile it's zoomed in from), then fades to its own as it arrives; tiles leaving the view stay until those taking their place are drawn. So moving never opens a hole, as the core seamless layering of `GeoTile`s does, with one `GeoTile`. The same works on the `globe`, where tiles on its far side are left out. + +:example{ name="globe" } diff --git a/docs/src/content/components/webgl/Grid.md b/docs/src/content/components/webgl/Grid.md new file mode 100644 index 0000000000..35209b96c8 --- /dev/null +++ b/docs/src/content/components/webgl/Grid.md @@ -0,0 +1,28 @@ +--- +description: "Commonly used component which draws horizontal and vertical lines respecting scales across a chart to enhance readability and help align data points with axis values. In a WebGL layer, it lines the plot box's floor and back walls." +category: WebGL +related: [Grid, guides/webgl] +components: + - { name: webgl/Grid, label: Grid } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +The floor and the two walls behind the plot, with lines at the scales' ticks. The walls move to the far sides as the view turns. + +```svelte + + + + +``` + +:example{ component="webgl/Points" name="scatter-3d" } + +Set `x`, `y`, or `z` to `false` to leave out a direction's lines (ex. ``). + +:example{ component="webgl/Bin" name="hexbin" } diff --git a/docs/src/content/components/webgl/Highlight.md b/docs/src/content/components/webgl/Highlight.md new file mode 100644 index 0000000000..84deb542d9 --- /dev/null +++ b/docs/src/content/components/webgl/Highlight.md @@ -0,0 +1,27 @@ +--- +description: 'Interaction component manages and displays tooltips allowing dynamic information to appear in response to user interactions. In a WebGL layer, it marks the hovered row with a point facing the viewer, traced on the floor and back walls.' +category: WebGL +related: [Highlight, Tooltip, guides/webgl] +components: + - { name: webgl/Highlight, label: Highlight } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +The tooltip's row (or `data`), marked as the core [Highlight](/docs/components/Highlight) marks it on an `isometric` chart, with the same props: `points` rings it with a circle facing the viewer, `lines` trace its position across the floor and, with a `z`, across and up each back wall (`axis` picks which), and `shadows` put a spot beneath it on the floor and level with it on each wall. Pass props to style each, ex. `points={{ r: 8, fill: 'none' }}`. + +```svelte + + + + + +``` + +On a flat `WebGL` chart, core's own `Highlight` in an `Svg` layer over it works as well (ex. [scatter](/docs/components/webgl/Points/scatter)). + +:example{ component="webgl/Points" name="scatter-3d" } diff --git a/docs/src/content/components/webgl/Light.md b/docs/src/content/components/webgl/Light.md new file mode 100644 index 0000000000..ce255ce314 --- /dev/null +++ b/docs/src/content/components/webgl/Light.md @@ -0,0 +1,39 @@ +--- +description: 'Light for a WebGL layer: directional (like the sun), a point (like a star), or ambient, with optional shadows.' +category: WebGL +related: [guides/webgl] +components: + - { name: webgl/Light, label: Light } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A `WebGL` layer lights itself until it has a `Light` of its own. A `directional` light shines from an `azimuth` (degrees clockwise from the plot's top edge) and an `altitude` (degrees above the floor), and `shadow` casts shadows onto the marks and the floor. An `ambient` light fills in evenly. + +```svelte + + + + ... + +``` + +:example{ name="buildings" } + +## Point lights + +A `point` light shines every way from a place in the plot (`x`, `y`, and `z`, in pixels), without fading with distance, so it can light planets from their star. + +```svelte + +``` + +:example{ component="webgl/Points" name="solar-system" } + +## Shadows on a map + +:example{ component="webgl/Bin" name="state-population" } diff --git a/docs/src/content/components/webgl/Link.md b/docs/src/content/components/webgl/Link.md new file mode 100644 index 0000000000..8ffaca078b --- /dev/null +++ b/docs/src/content/components/webgl/Link.md @@ -0,0 +1,23 @@ +--- +description: 'Marking component which draws a line or curve between two points to highlight or connect data. In a WebGL layer, links can rise or arch between their ends.' +category: WebGL marks +related: [Link, guides/webgl] +components: + - { name: webgl/Link, label: Link } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A line per row, straight or arched (`arc`), placed as the core [`Link`](/docs/components/Link) places it. `x1` / `y1` and `x2` / `y2` are its ends, as data properties or functions of the row through the chart's scales (longitude and latitude on a map), or numbers in pixels; the end defaults to the start. `z1` / `z2` raise them, through the chart's `z` scale or in pixels: ex. a pin's stem from the floor up to its head. + +```svelte + +``` + +Without `x1` / `y1`, each row is a link from its `source` node to its `target`, at their `x` / `y` in pixels: ex. a hierarchy's `links()`. + +:example{ name="pin-map" } diff --git a/docs/src/content/components/webgl/Points.md b/docs/src/content/components/webgl/Points.md new file mode 100644 index 0000000000..705b04b789 --- /dev/null +++ b/docs/src/content/components/webgl/Points.md @@ -0,0 +1,45 @@ +--- +description: 'Marking component which plots individual data points on a graph to show distribution, relationships, or clusters without connecting lines. In a WebGL layer, each point is a sphere (a disc when flat), and can glow or wear an image.' +category: WebGL marks +related: [Points, guides/webgl] +components: + - { name: webgl/Points, label: Points } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A sphere per row, at its `x`, `y`, and `z`. `r` sets the radius in pixels, else the chart's `r` scale. + +```svelte + + + + + +``` + +:example{ name="scatter-3d" } + +## Glow and images + +`glow` draws each sphere in its own color whatever the lights (ex. a star), and `image` wraps each in an equirectangular image (ex. a planet), turned by `rotate` and leaning by `tilt`. + +:example{ name="solar-system" } + +Tens of thousands of glowing points, placed along spiral arms and colored from the middle out, turning slowly (drag to look from another angle). + +:example{ name="galaxy" } + +## Flat + +Without a view, points are discs, for many thousands of them. + +:example{ name="scatter" } + +The grid, axes, and highlight can be core's own `Svg` layers instead, with only the points in WebGL: + +:example{ name="scatter-with-svg" } diff --git a/docs/src/content/components/webgl/Polygon.md b/docs/src/content/components/webgl/Polygon.md new file mode 100644 index 0000000000..fbbc07396b --- /dev/null +++ b/docs/src/content/components/webgl/Polygon.md @@ -0,0 +1,17 @@ +--- +description: 'Primitive component which renders a multi-sided shape on a chart to represent complex areas, boundaries, or regions of interest. In a WebGL layer, it stands up by its z.' +category: WebGL marks +related: [Polygon, guides/webgl] +components: + - { name: webgl/Polygon, label: Polygon } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A polygon per row, with the core [Polygon](/docs/components/Polygon) props: a regular polygon (or star, with `inset`) of `points` corners about `cx` / `cy` with radius `r`, or explicit `points` in pixels, `rotate`d, stretched, skewed, and rounded by `cornerRadius`. `z` stands it up, as on an `isometric` chart; without one it lies flat. + +:example{ name="tree" } diff --git a/docs/src/content/components/webgl/Raster.md b/docs/src/content/components/webgl/Raster.md new file mode 100644 index 0000000000..b0fb00ccb0 --- /dev/null +++ b/docs/src/content/components/webgl/Raster.md @@ -0,0 +1,17 @@ +--- +description: 'Composite mark rendering a pixel-based heatmap where each pixel is colored by a scalar value. Supports grid data, scattered data with spatial interpolation, and continuous functions. In a WebGL layer, it lies on the floor as an image.' +category: WebGL surfaces +related: [Raster, guides/webgl] +components: + - { name: webgl/Raster, label: Raster } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +The values as an image on the floor (or `z` pixels above it), sampled as finely as the image allows rather than at a surface's vertices. It takes values the same ways as [Surface](/docs/components/webgl/Surface), and `imageRendering="pixelated"` shows each cell with hard edges. + +:example{ name="basic" } diff --git a/docs/src/content/components/webgl/Rect.md b/docs/src/content/components/webgl/Rect.md new file mode 100644 index 0000000000..b22ec38f52 --- /dev/null +++ b/docs/src/content/components/webgl/Rect.md @@ -0,0 +1,21 @@ +--- +description: "Primitive component which draws a rectangle to highlight areas, ranges, or specific regions of interest. In a WebGL layer, it's a box standing as tall as its z." +category: WebGL marks +related: [Rect, guides/webgl] +components: + - { name: webgl/Rect, label: Rect } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A box per row, `z` tall, placed as the core [`Rect`](/docs/components/Rect) places it: by its sides `x0` / `x1` and `y0` / `y1`, or by `x` / `y` and a `width` / `height` in pixels. Sides and positions are data properties or functions of the row through the chart's scales, or numbers in pixels. A `z` function can return `[start, end]` to float a box between two values (ex. a treemap's tiers). + +```svelte + [d.depth, d.depth + 1]} /> +``` + +:example{ name="treemap" } diff --git a/docs/src/content/components/webgl/Rule.md b/docs/src/content/components/webgl/Rule.md new file mode 100644 index 0000000000..9ee15f511b --- /dev/null +++ b/docs/src/content/components/webgl/Rule.md @@ -0,0 +1,17 @@ +--- +description: 'Commonly used component acting as a visual guideline on a chart that helps align and measure data values along an axis. In a WebGL layer, rules lie on the floor.' +category: WebGL marks +related: [Rule, guides/webgl] +components: + - { name: webgl/Rule, label: Rule } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Reference lines with the core [Rule](/docs/components/Rule) props, on the floor (or `z` pixels above it): `x` / `y` at a value, at the plot's edges (`true`, `'$left'`, `'$top'`, ...), or as an accessor for a line per row, from zero (or the band) to its value. `class` styles them as on any core mark. + +:example{ name="lollipop" } diff --git a/docs/src/content/components/webgl/Spline.md b/docs/src/content/components/webgl/Spline.md new file mode 100644 index 0000000000..f211a9094a --- /dev/null +++ b/docs/src/content/components/webgl/Spline.md @@ -0,0 +1,29 @@ +--- +description: 'Marking component which applies data points connected by smooth, curved lines to show trends or patterns over a continuous range. In a WebGL layer, lines run through 3D, colored per point.' +category: WebGL marks +related: [Spline, guides/webgl] +components: + - { name: webgl/Spline, label: Spline } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A line through the rows, one per `g` (or `stroke` key, or `c`) value, at each row's `x`, `y`, and `z`. `stroke` colors it per point, so a line can change color along its length. + +```svelte + + + + + +``` + +:example{ name="series" } + +:example{ name="line3d" } + +:example{ name="temperatures" } diff --git a/docs/src/content/components/webgl/Surface.md b/docs/src/content/components/webgl/Surface.md new file mode 100644 index 0000000000..13630be3fb --- /dev/null +++ b/docs/src/content/components/webgl/Surface.md @@ -0,0 +1,56 @@ +--- +description: 'Mark raising a grid of values into a lit surface in a WebGL chart, with optional wireframe and contour lines.' +category: WebGL surfaces +related: [Raster, Contour, guides/webgl] +components: + - { name: webgl/Surface, label: Surface } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Heights from values, through the chart's `z` scale (whose domain widens to reach them), colored through the chart's continuous color scale (`cScale`), else yellow-green-blue. Values come the same ways as the core [Raster](/docs/components/Raster): + +- **A grid:** `data` (row-major values) with `width` × `height`, laid across the plot, or across `x1` / `y1` to `x2` / `y2` in data coordinates. +- **A function:** `value={(x, y) => ...}`, sampled every `pixelSize` pixels, in data coordinates (longitude and latitude on a map). +- **Scattered rows:** `data` with `x`, `y`, and `value`, interpolated onto a grid (`interpolate`). + +```svelte + + + Math.sin(x * Math.PI) * Math.sin(y * Math.PI)} wireframe /> + + +``` + +:example{ name="basic" } + +## Contours, and raising or flattening + +`contours` draws contour lines at their heights. To raise or flatten a surface, ease the chart's `zRange` (ex. with a `Tween`), which the surface, its contours, and the view's fit all follow. + +:example{ name="volcano" } + +## Motion + +`motion` eases to new values (ex. a new `value` function): heights, colors, and contours move together. + +:example{ name="math-functions" } + +## Terrain + +A function of longitude and latitude on a map is terrain. These load elevation from the open terrain tiles AWS hosts, and light it with a sun you can move. + +:example{ name="us-elevation" } + +:example{ name="terrain" } + +:example{ name="world-elevation" } diff --git a/docs/src/content/components/webgl/Text.md b/docs/src/content/components/webgl/Text.md new file mode 100644 index 0000000000..50620e3412 --- /dev/null +++ b/docs/src/content/components/webgl/Text.md @@ -0,0 +1,27 @@ +--- +description: 'Primitive component which adds custom text for labeling, annotation, or commentary. In a WebGL layer, text lies on the surface beneath it, or faces the viewer.' +category: WebGL +related: [Text, guides/webgl] +components: + - { name: webgl/Text, label: Text } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A label per row, placed as the core [`Text`](/docs/components/Text) places it: `x`, `y`, and `z` are data properties or functions of the row, through the chart's scales (longitude and latitude on a map), or numbers in pixels. `value` is a property, a function, or the text itself. + +By default a label lies on the surface at its height (ex. the tops of boxes), turning and tipping with the view, in `fontSize` and `fill`. With `viewport` it faces the viewer instead, drawn over the scene upright and crisp however the view turns, styled with `class`. + +```svelte + +``` + +For a layout already in pixels (ex. a tree), place a label per node by numbers. + +:example{ component="webgl/Polygon" name="tree" } + +:example{ component="webgl/Rect" name="treemap" } diff --git a/docs/src/content/components/webgl/Vector.md b/docs/src/content/components/webgl/Vector.md new file mode 100644 index 0000000000..1e77b9dbaf --- /dev/null +++ b/docs/src/content/components/webgl/Vector.md @@ -0,0 +1,23 @@ +--- +description: 'Primitive component which draws directional arrows or spikes at data points to show magnitude and direction. In a WebGL layer, they lie on the floor.' +category: WebGL marks +related: [Vector, guides/webgl] +components: + - { name: webgl/Vector, label: Vector } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +Arrows (`shape="arrow"`), filled arrows (`'arrow-filled'`), or spikes (`'spike'`) with the core [Vector](/docs/components/Vector) props: placed at `x` / `y`, `length` long (through the chart's `r` scale), and turned `rotate` degrees clockwise from up the plot. + +In a 3D view, each is a solid arrow (or cone) that can point any way: `z` places it in the box (through the chart's `z` scale), and `tilt` points it up out of the floor (`90` straight up). Flat, it lies on the floor as core draws it. + +```svelte + +``` + +:example{ name="field" } diff --git a/docs/src/content/components/webgl/WebGL.md b/docs/src/content/components/webgl/WebGL.md new file mode 100644 index 0000000000..a548ba12ff --- /dev/null +++ b/docs/src/content/components/webgl/WebGL.md @@ -0,0 +1,48 @@ +--- +description: "Layer drawing its marks with WebGL (three.js), through the chart's perspective or orthographic view in 3D, or flat for many marks in 2D." +category: layers +related: [Layer, Canvas, guides/webgl, guides/isometric] +components: + - { name: webgl/WebGL, label: WebGL } +--- + +::tip +Part of [`@layerchart/webgl`](/docs/guides/webgl), drawn in a `WebGL` layer. See the [WebGL guide](/docs/guides/webgl) to get started. +:: + +## Usage + +A `WebGL` layer draws the `@layerchart/webgl` marks inside it. The chart's `view` says how it's seen, and its `transform` turns, pans, and zooms it. + +```svelte + + + + + + + +``` + +## The view + +`perspective` draws farther things smaller; `orthographic` keeps sizes true at any depth. Both take `rotate`, `tilt`, `aspect`, and `motion` (and `perspective` a `fov`). Dragging hands its angles back through the chart's `onTransform`. + +:example{ name="playground" } + +## Flat + +Without a `view`, the layer is seen from directly above and drawn unshaded, each chart pixel where an `Svg` or `Canvas` layer would draw it, for charts with more marks than those keep up with. + +:example{ component="webgl/Points" name="scatter" } + +Only the marks need to be drawn by it. Here `Svg` layers draw the grid, axes, and highlight as on any chart, with the chart's tooltip finding the nearest point, and the `WebGL` layer the 100,000 points between them. + +:example{ component="webgl/Points" name="scatter-with-svg" } + +## Limits + +- Browsers limit how many WebGL contexts a page can have at once (16 in Chromium). A `WebGL` layer only holds one while it's on screen (or nearly), and gives it back when it's scrolled away. +- Nothing is drawn on the server. The layer renders once it mounts in the browser. diff --git a/docs/src/content/guides/isometric.md b/docs/src/content/guides/isometric.md index e9a64067a4..f13f7c1466 100644 --- a/docs/src/content/guides/isometric.md +++ b/docs/src/content/guides/isometric.md @@ -5,6 +5,8 @@ category: state `view={isometric}` draws a chart's plot area as a floor seen from above at an angle. Works in any layer type (`Svg`, `Canvas`, `Html`) and marks (ex. `Axis`, `Rect`, etc). +It's faux 3D, drawn in 2D. For true 3D (depth, lighting, and perspective) in a `WebGL` layer, see [WebGL](/docs/guides/webgl), and [Views](/docs/guides/views) to compare them. + ## Quick start Import `isometric` and pass as `view` to `Chart`. @@ -107,7 +109,7 @@ With a `transform`, an isometric chart can pan and zoom, and it can also turn: d ``` -The view starts at its `rotate` and `tilt`, and moves to new values when they change. `onTransform` reports the current angles as `rotation` (`x` is the turn, `y` the tilt, in degrees). `reset()` restores them along with the pan and zoom. `transform.drag` is reactive, so a control can switch it. `TransformContextControls` has one built in. +The view starts at its `rotate` and `tilt`, and moves to new values when they change. `onTransform` reports the current angles as `rotation` (`x` is the turn, `y` the tilt, in degrees). `reset()` restores them along with the pan and zoom. `transform.drag` is reactive, so a control can switch it. `TransformContextControls` has one built in. A drag tips the floor from directly above to just short of edge on; `rotateExtent` and `tiltExtent` narrow that (see [constraints](/docs/guides/transform#constraints)). In the playground below, the sliders and dragging set the same angles. diff --git a/docs/src/content/guides/layers.md b/docs/src/content/guides/layers.md index dacedb03db..a27cc2e58c 100644 --- a/docs/src/content/guides/layers.md +++ b/docs/src/content/guides/layers.md @@ -54,12 +54,18 @@ LayerChart also support CSS classes and styling for the `Canvas` layer. ### WebGL -At the moment LayerChart does not provide WebGL primitive support, but is considering adding in the future, possibly for 3D visualizations. - -> 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. - -- **Stengths:** performance -- **Weaknesses:** complexity, concurrency limits, styling, interactivity, introspection, text +WebGL layers are drawn by the separate `@layerchart/webgl` package, whose `WebGL` layer and marks are rendered on the GPU. With a `perspective` or `orthographic` chart `view` they're true 3D (lit, shadowed, and orbited); without one they're flat, for charts with far more marks than `Svg` or `Canvas` handle well. See [WebGL](/docs/guides/webgl). + +> 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. + +- **Stengths:** performance (hundreds of thousands of marks), true 3D, lighting and shadows +- **Weaknesses:** + - nothing rendered on the server (SSR); the layer draws once it's hydrated + - not accessible to screen readers, and text can't be selected + - increased bundle size + - concurrency limits + - text (labels are drawn as HTML over the layer) + - styling (no CSS on marks), interactivity, introspection ## Comparison diff --git a/docs/src/content/guides/layers/features.ts b/docs/src/content/guides/layers/features.ts index 3394169920..63a8615947 100644 --- a/docs/src/content/guides/layers/features.ts +++ b/docs/src/content/guides/layers/features.ts @@ -398,6 +398,55 @@ export const other = [ support: true } }, + { + feature: 'Server-side rendered (SSR)', + html: { + support: true + }, + svg: { + support: true + }, + canvas: { + support: false, + note: 'Draws once hydrated' + }, + webgl: { + support: false, + note: 'Draws once hydrated' + } + }, + { + feature: 'Accessible (screen readers)', + html: { + support: true + }, + svg: { + support: true + }, + canvas: { + support: false + }, + webgl: { + support: false + } + }, + { + feature: 'True 3D (perspective, lighting, shadows)', + html: { + support: false + }, + svg: { + support: false, + note: 'Faux 3D with `isometric`' + }, + canvas: { + support: false, + note: 'Faux 3D with `isometric`' + }, + webgl: { + support: true + } + }, { feature: 'Marks can contain children', html: { diff --git a/docs/src/content/guides/transform.md b/docs/src/content/guides/transform.md index 189588507b..4aaa3e8eb6 100644 --- a/docs/src/content/guides/transform.md +++ b/docs/src/content/guides/transform.md @@ -151,7 +151,7 @@ When set, scroll events without the key held are ignored (no `preventDefault`), ### Pointer interactions - **Drag** — pan (click and drag to move the view) -- **Shift + drag** — on an `isometric` chart, turn the view instead. `drag: 'rotate'` swaps the two, and `dragSwitchKey` changes the key (see [Dragging the view](/docs/guides/isometric#dragging-the-view)) +- **Shift + drag** — on a chart with a [`view`](/docs/guides/views) (ex. `isometric`), turn the view instead. `drag: 'rotate'` swaps the two, and `dragSwitchKey` changes the key (see [Dragging the view](/docs/guides/isometric#dragging-the-view)) - **Double-click** — zoom in 2x at the click point - **Shift + double-click** — zoom out 0.5x - **Trackpad pinch** — detected as ctrl+wheel events, always zooms regardless of scroll mode @@ -359,7 +359,7 @@ Using `'data'` for `min`/`max` is the most common pattern — it prevents pannin ### `constrain` — custom constraint function -For full control, provide a `constrain` function that receives the proposed `{ scale, translate }` and returns corrected values. Called after `scaleExtent` and `translateExtent` are applied. +For full control, provide a `constrain` function that receives the proposed `{ scale, translate }` and returns corrected values. Called after `scaleExtent` and `translateExtent` are applied. As a drag turns a `view`, it also receives the proposed `rotation` (`x` the turn, `y` the tilt), and can return a corrected one. ```svelte +``` + +A custom `constrain` function does the same, given the angles as `translate`: ```svelte +``` + +Without them, a drag tips the view from `0` (seen from directly above) to edge on. An `isometric` floor can't go further, but a 3D view (`@layerchart/webgl`) can: `tiltExtent: [0, 180]` turns it on round to look from beneath, ex. a [globe](/docs/components/webgl/GeoRaster)'s south pole. The view's own `rotate` and `tilt` aren't limited, only where a drag takes them. + +On a globe projection (`mode: 'projection'`), they bound its yaw and pitch instead: `tiltExtent: [-90, 90]` stops it at the poles (see [Globe rotation constraints](#globe-rotation-constraints)). + ### How constraints compose When multiple constraint options are provided, they are applied in order: 1. `scaleExtent` — clamps scale (relative multipliers in projection mode) 2. `translateExtent` — clamps translate (zoom-aware bounds in projection mode) -3. `domainExtent` — clamps in domain space (converted to a `constrain` function internally) -4. `constrain` — final custom adjustment +3. `rotationExtent` / `rotateExtent` / `tiltExtent` — clamp a view's rotation as a drag turns it +4. `domainExtent` — clamps in domain space (converted to a `constrain` function internally) +5. `constrain` — final custom adjustment A user-provided `constrain` function runs after all other constraints, giving it the final say. @@ -539,7 +570,8 @@ On an `isometric` chart, it also has a menu to pick what a drag does: pan or tur | World map (geo) | Projection mode + world countries | [transform-world-projection](/docs/components/GeoPath/transform-world-projection) | | Globe rotation | `transform={{ mode: 'projection' }}` (auto-detected) | [translucent-globe](/docs/components/GeoPath/translucent-globe) | | Geo map zoom limits | `scaleExtent: [1, 8]` | [transform-canvas-scale-extent](/docs/components/GeoPath/transform-canvas-scale-extent) | -| Globe pitch clamping | `constrain` with `Math.max(-90, ...)` | [transform-globe-constrain](/docs/components/GeoPath/transform-globe-constrain) | +| Globe pitch clamping | `tiltExtent: [-90, 90]` | [transform-globe-constrain](/docs/components/GeoPath/transform-globe-constrain) | +| Limit turning a view | `rotateExtent: [-90, 0]`, `tiltExtent: [30, 80]` | [isometric](/docs/guides/isometric#dragging-the-view) | | Brush-to-zoom | `brush` + `transform={{ mode: 'domain' }}` | [brush-pan-zoom](/docs/components/LineChart/brush-pan-zoom) | | Brush-to-zoom (band) | `brush` + `transform` on band scale | [brush-pan-zoom-band](/docs/components/BarChart/brush-pan-zoom-band) | | Overview brush | Separate chart with `brush.x` synced to `context.xDomain` | [pan-zoom-with-overview](/docs/components/LineChart/pan-zoom-with-overview) | diff --git a/docs/src/content/guides/views.md b/docs/src/content/guides/views.md new file mode 100644 index 0000000000..ec1f396924 --- /dev/null +++ b/docs/src/content/guides/views.md @@ -0,0 +1,76 @@ +--- +title: Views (2D and 3D) +category: state +--- + +A chart's `view` says how its plot area is seen. Without one, it's flat: `x` across, `y` down, as on any chart. With one, the plot area becomes a **floor** seen at an angle, and `z` rises off it. + +```svelte + + +``` + +Besides the flat default, there are three views, which differ in how they're drawn and which layers can draw them. + +| | `isometric` | `orthographic` | `perspective` | +| ---------- | ----------------------------------- | ------------------------------------ | ------------------------------------ | +| Projection | Parallel | Parallel | Far things smaller | +| Layers | `Svg`, `Canvas`, `Html` | `WebGL` | `WebGL` | +| Depth | Faux (2D, back to front) | True (depth tested, lit) | True (depth tested, lit) | +| Guide | [Isometric](/docs/guides/isometric) | [WebGL](/docs/guides/webgl#the-view) | [WebGL](/docs/guides/webgl#the-view) | + +`isometric` draws with LayerChart's own marks, from `layerchart`. The two cameras draw with [`@layerchart/webgl`](/docs/guides/webgl)'s marks, which take the same props. + +## The flat default + +Without a `view`, the plot area is drawn straight on, as every chart is: `x` across and `y` down through their scales, nothing turned or tipped. It's what most charts want, and it's the only view every layer draws: `Svg`, `Canvas`, `Html`, and `WebGL` layers all line up pixel for pixel, so they mix freely (ex. a [`WebGL` layer](/docs/guides/webgl#flat-2d) for 100,000 points under `Svg` axes and a tooltip highlight). + +- **Height** (`z`) needs a view: without one, nothing rises off the plot. +- **A `transform`** pans and zooms. There's nothing to turn, so `drag: 'rotate'` pans as a plain drag does. +- **Seen from directly above,** a view looks flat too: `isometric({ rotate: 0, tilt: 0 })`. Easing between that and a tilted view animates a chart into 3D and back (see [Animating the view](/docs/guides/isometric#animating-the-view)). + +## Choosing a view + +- **`isometric`** keeps everything you already use: the same layers, marks, axes, text, and CSS, with no extra package. It's faux 3D, a 2D drawing of a floor turned and tipped, so it suits charts that read as a raised floor (ex. [3D bars](/docs/guides/isometric#height), calendars, treemaps, maps with height). +- **`orthographic`** draws the same parallel projection in true 3D, with [`@layerchart/webgl`](/docs/guides/webgl): marks hide what's behind them, faces are lit, and lights cast shadows. Reach for it when faux depth isn't enough (ex. dense 3D scatters, surfaces, terrain), or for more marks than `Svg` and `Canvas` keep up with. +- **`perspective`** is `orthographic` with a camera's depth: farther things are smaller, which reads as more natural for scenes and globes, at the cost of comparing sizes across depth. + +The same data drawn both ways: `isometric` in an `Svg` layer, and `perspective` (or `orthographic`, with its toggle) in a `WebGL` layer. + +:example{ component="Chart" name="isometric-scatter-3d" } + +:example{ component="webgl/Points" name="scatter-3d" } + +## What they share + +All three views take the same options, so moving a chart between them is mostly changing its `view`: + +| Option | What it does | Default | +| -------- | --------------------------------------------------------------------------------- | --------------------------------------- | +| `rotate` | Turns the floor about its center, clockwise, in degrees | `-45` | +| `tilt` | Tips it away from the viewer, from `0` (seen from directly above) towards edge on | `54.7356` (`isometric`), `60` (cameras) | +| `aspect` | The floor's width over its depth, or `'auto'` to take it from the data | `'auto'` | +| `motion` | Eases the view to new angles, ex. `'tween'` | | +| `fov` | `perspective` only: the vertical field of view, in degrees | `35` | + +- **Height:** `z` is a third position channel, through the chart's `zScale`, from the floor up. Its range defaults to half the floor's shorter side. Marks take `z` the same way in every view (see [Height](/docs/guides/isometric#height)). +- **Turning, panning, and zooming:** a chart's `transform` with `drag: 'rotate'` turns any view, `onTransform` reports the angles as `rotation`, and `rotateExtent` / `tiltExtent` limit them (see [Transform](/docs/guides/transform#constraints), [Dragging the view](/docs/guides/isometric#dragging-the-view), and [Turning, panning, and zooming](/docs/guides/webgl#turning-panning-and-zooming)). +- **Fit:** the floor, and anything rising off it, is fitted into the plot area inside the chart's `padding`. Give it `padding` for room around it (ex. for axis labels). +- **Axes:** `Axis placement="bottom"` and `"left"` run along the floor's edges, and `"back"` up its back corner. Tick labels lie on the floor unless `tickLabelProps={{ viewport: true }}` turns them to face the viewer. + +## Views and geo projections + +A [geo projection](/docs/guides/geo) and a view do different jobs, and they combine. The projection maps longitude and latitude to the plot area, in place of the `x` / `y` scales: it decides where places are on the flat map. The view then decides how that plot area is seen: straight on without one, or as a floor seen at an angle with one. + +So any projection can be the floor of any view, with `z` raising features, points, or bins off the map: ex. [an election map](/docs/components/GeoPath/election-isometric) or [pins](/docs/components/Chart/isometric-pin-map) on an `isometric` floor (see [Paths and maps](/docs/guides/isometric#paths-and-maps)), or [population bins](/docs/components/webgl/Bin/state-population) under a `perspective` camera. + +Two things look alike but aren't: + +- **A globe as a projection** (ex. `geoOrthographic`) is a flat drawing of a sphere: a disk on the plot. Turning it changes the projection's `rotate` (see [Globe rotation](/docs/guides/geo#globe-rotation)), and it works in any layer, with or without a view. +- **A globe in a view** is a real sphere: `@layerchart/webgl`'s `globe` projection under a `perspective` or `orthographic` camera lays the map around it, and the view orbits it (see [Maps and globes](/docs/guides/webgl#maps-and-globes)). + +## Mixing layers + +An `isometric` view draws in every `Svg`, `Canvas`, and `Html` layer of the chart, so they can be mixed as on a flat chart. `orthographic` and `perspective` are drawn by `WebGL` layers only: `Svg`, `Canvas`, and `Html` layers can't draw through a camera, and warn when they're given one. A layer with `ignoreTransform` draws over the scene, flat (ex. a title), as do `Tooltip` and `Legend`. + +Without a `view`, a `WebGL` layer is flat too, lined up pixel for pixel with the chart's other layers: see [Flat (2D)](/docs/guides/webgl#flat-2d). diff --git a/docs/src/content/guides/webgl.md b/docs/src/content/guides/webgl.md new file mode 100644 index 0000000000..6dee0ffcae --- /dev/null +++ b/docs/src/content/guides/webgl.md @@ -0,0 +1,197 @@ +--- +title: WebGL +category: state +--- + +`@layerchart/webgl` draws charts with WebGL, using [three.js](https://threejs.org) through [Threlte](https://threlte.xyz): in true 3D, or flat for far more marks than `Svg` or `Canvas` keep up with. It's a separate package, so charts that don't use it never load three.js. For 3D on the existing `Svg`, `Canvas`, and `Html` layers, see [Isometric](/docs/guides/isometric), and [Views](/docs/guides/views) to compare them. + +## Installation + +:::tabs{key="bundler"} + + ::tab{label="pnpm" icon="vscode-icons:file-type-pnpm"} + ```sh + pnpm i @layerchart/webgl + ``` + :: + + ::tab{label="npm" icon="vscode-icons:file-type-npm"} + ```sh + npm i @layerchart/webgl + ``` + :: + + ::tab{label="bun" icon="vscode-icons:file-type-bun"} + ```sh + bun add @layerchart/webgl + ``` + :: + + ::tab{label="deno" icon="vscode-icons:file-type-deno"} + ```sh + deno add npm:@layerchart/webgl + ``` + :: + + ::tab{label="yarn" icon="vscode-icons:file-type-yarn"} + ```sh + yarn add @layerchart/webgl three @threlte/core + ``` + :: + +::: + +`@layerchart/webgl` is released with `layerchart`, at the same version, and installs it. If your project also depends on `layerchart` directly, keep the two on the same version. `three` and `@threlte/core` are peer dependencies, so a project has one copy of each that its own code shares with the charts. Most package managers install them along with `@layerchart/webgl`; Yarn needs them listed. + +## Quick start + +Everything comes from `@layerchart/webgl`. `Chart`, `Tooltip`, and `Legend` are core's own, re-exported. The chart's `view` says how it's seen (`perspective`, as `isometric` does for flat layers), and the marks inside a [`WebGL`](/docs/components/webgl/WebGL) layer are drawn through it. A `transform` turns, pans, and zooms it. + +```svelte + + + + + + + + + + + +``` + +:example{ component="webgl/Points" name="scatter-3d" } + +Drag to turn the view, and shift-drag to pan. Hold shift and scroll to zoom, moving the camera in and out. + +## How it works + +The chart lays out exactly as a flat one would: `x` across the plot's width, `y` down its height, and `z` up off the floor, all through the chart's scales. The `WebGL` layer then stands that plot box up in 3D, with the floor seen at an angle. + +- **The `z` scale** measures up from the floor, as it does for [isometric](/docs/guides/isometric#height). Its range defaults to half the floor's shorter side. Set `zRange={({ height }) => [0, height]}` for a cube. +- **Color, series, stacking, and domains** work as on any chart: marks register with the chart, and `fill` / `stroke` take a CSS color, or a data key or function run through the color scale (`c`, `cRange`, ...). CSS variables like `var(--color-primary)` resolve against the page, and follow theme changes. +- **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. + +## 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: + +```svelte + + +``` + +| Option | What it does | Default | +| -------- | ------------------------------------------------------------------------------------ | -------- | +| `rotate` | Turns the floor about its center, clockwise, in degrees (as `isometric`) | `-45` | +| `tilt` | Tips it away from the viewer, from `0` (seen from directly above) towards edge on | `60` | +| `fov` | `perspective`'s vertical field of view, in degrees | `35` | +| `aspect` | The floor's width over its depth, kept as the chart resizes; `'auto'` as `isometric` | `'auto'` | +| `motion` | Ease to new angles (and `fov`), ex. `'tween'` | | + +The camera fits the whole plot box into the plot area, inside the chart's `padding` as an `isometric` chart does, and refits when the chart resizes. Give it `padding` for room around the box (ex. for its axes' labels). New angles turn the view to them. Without a `view`, the layer is seen from directly above (see [Flat](#flat-2d)). + +### Turning, panning, and zooming + +A chart's `transform` moves a 3D view as it does an [isometric](/docs/guides/isometric#dragging-the-view) one: `mode: 'canvas'` pans and zooms what's drawn, and with `drag: 'rotate'` a drag turns the view (holding `dragSwitchKey`, `shift` by default, does the other). `scrollMode: 'scale'` zooms on scroll, and `scrollActivationKey` only while a key is held, so scrolling past the chart scrolls the page. + +```svelte + +``` + +`onTransform` reports the angles a drag turns to as `rotation` (`x` is `rotate`, `y` is `tilt`). Hand them back to the view's options to keep controls in step with a drag. The transform's `zoomIn()`, `zoomOut()`, and `reset()` work as on any chart, so `TransformContextControls` works too; the [terrain](/docs/components/webgl/Surface#terrain) examples have them. + +```svelte + + + { + if (dragging && rotation) [rotate, tilt] = [rotation.x, rotation.y]; + }} + ondragstart={() => (dragging = true)} + ondragend={() => (dragging = false)} +> +``` + +In the playground below, the controls and dragging set the same view. + +:example{ component="webgl/WebGL" name="playground" } + +There are two ways to zoom. `mode: 'domain'` zooms the chart's `x` / `y` domains, as on a flat chart: the camera stays, so the axes keep their place and re-tick, and marks are clipped to the plot box (the `WebGL` layer's `clip`). `mode: 'canvas'` dollies the camera in and out instead, moving up to what's drawn (ex. a globe or a terrain). On a `globe`, zooming in brings the camera down towards the surface (its height above it divided by the zoom), so it comes close to the ground without ever passing inside. The transform's [constraints](/docs/guides/transform#constraints) limit how far the view goes: ex. `scaleExtent: [0.5, 3]` stops short of where an image starts to blur. A drag tips the view no further than edge on unless `tiltExtent` lets it: `tiltExtent: [0, 180]` turns on round to look from beneath (ex. a globe's south pole). + +`Svg`, `Canvas`, and `Html` layers can't draw through a 3D view, and warn when they're given one. A layer with `ignoreTransform` draws over the scene as usual (ex. a title). + +## Flat (2D) + +Without a `view`, a `WebGL` layer is seen from directly above and drawn unshaded, each chart pixel where an `Svg` or `Canvas` layer would draw it, so flat layers can draw over it (ex. annotations). Points are discs rather than spheres. It's for charts with more marks than `Svg` or `Canvas` keep up with: a `transform` pans and zooms them. + +```svelte + + + + + +``` + +:example{ component="webgl/Points" name="scatter" } + +Only the marks need a `WebGL` layer: the grid, axes, tooltip highlight, and legend can be core's own, in `Svg` layers above and below it. + +:example{ component="webgl/Points" name="scatter-with-svg" } + +## Lights and shadows + +A `WebGL` layer lights itself until it has a [`Light`](/docs/components/webgl/Light) of its own: `directional` (like the sun on a map, with `shadow`), `point` (like a star among its planets), or `ambient`. + +```svelte + + + + ... + +``` + +:example{ component="webgl/Light" name="buildings" } + +## Maps and globes + +Set a projection on the chart as for a flat map (see the [Geo guide](/docs/guides/geo)), and marks lay out through it: [`Points`](/docs/components/webgl/Points), [`Bars`](/docs/components/webgl/Bars), [`Bin`](/docs/components/webgl/Bin), [`Spline`](/docs/components/webgl/Spline), and [`Area`](/docs/components/webgl/Area) place rows at their longitude (`x`) and latitude (`y`), [`GeoPath`](/docs/components/webgl/GeoPath) extrudes features, [`GeoRaster`](/docs/components/webgl/GeoRaster) lays an image over the map, and a [`Surface`](/docs/components/webgl/Surface) of longitude and latitude is terrain. + +:example{ component="webgl/Bin" name="state-population" } + +The `globe` projection lays the map on a real sphere you can orbit, and the same marks draw on it. + +```svelte + + + + + + +``` + +:example{ component="webgl/GeoRaster" name="globe" } + +## Surfaces + +Grids of values (a `data` grid, a function of `x` and `y`, or scattered rows) raised into a [`Surface`](/docs/components/webgl/Surface), laid on the floor as a [`Raster`](/docs/components/webgl/Raster), or traced by [`Contour`](/docs/components/webgl/Contour) lines, colored through the chart's continuous `cScale`. + +:example{ component="webgl/Surface" name="volcano" } + +## Limits + +- Browsers limit how many WebGL contexts a page can have at once (16 in Chromium). A `WebGL` layer only holds one while it's on screen (or nearly), and gives it back when it's scrolled away. +- Nothing is drawn on the server. The layer renders once it mounts in the browser. diff --git a/docs/src/examples/catalog/WebGL.json b/docs/src/examples/catalog/WebGL.json deleted file mode 100644 index 86df785376..0000000000 --- a/docs/src/examples/catalog/WebGL.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "component": "WebGL", - "examples": [], - "usage": [], - "updatedAt": "2025-11-03T12:48:28.426Z" -} \ No newline at end of file diff --git a/docs/src/examples/components/Chart/isometric-pan-zoom.svelte b/docs/src/examples/components/Chart/isometric-pan-zoom.svelte index 8806090ddd..9446510485 100644 --- a/docs/src/examples/components/Chart/isometric-pan-zoom.svelte +++ b/docs/src/examples/components/Chart/isometric-pan-zoom.svelte @@ -36,7 +36,6 @@ padding={{ top: 24, bottom: 40, left: 40, right: 24 }} height={400} clip - class="cursor-grab active:cursor-grabbing" > diff --git a/docs/src/examples/components/Chart/isometric-scatter-3d.svelte b/docs/src/examples/components/Chart/isometric-scatter-3d.svelte index 7873df645f..85e5466a79 100644 --- a/docs/src/examples/components/Chart/isometric-scatter-3d.svelte +++ b/docs/src/examples/components/Chart/isometric-scatter-3d.svelte @@ -51,7 +51,6 @@ tooltipContext={{ mode: 'quadtree', radius: 20 }} padding={{ top: 24, bottom: 24, left: 40, right: 24 }} height={500} - class="cursor-grab active:cursor-grabbing" > {#snippet children({ context })} {@const hovered = context.tooltip.data} diff --git a/docs/src/examples/components/Chart/isometric-treemap.svelte b/docs/src/examples/components/Chart/isometric-treemap.svelte index 10260be452..80805c6a07 100644 --- a/docs/src/examples/components/Chart/isometric-treemap.svelte +++ b/docs/src/examples/components/Chart/isometric-treemap.svelte @@ -80,8 +80,9 @@ transform={{ mode: 'canvas', scrollMode: 'scale', - // Drag to pan and shift-drag to turn, or the reverse via the controls. Eases the zoom - // buttons and reset + // Drag to turn and shift-drag to pan (flat, from above, drag pans), or the reverse via the + // controls. Eases the zoom buttons and reset + drag: view === 'flat' ? 'pan' : 'rotate', motion: { type: 'tween', duration: 800, easing: cubicInOut } }} padding={24} diff --git a/docs/src/examples/components/webgl/Arc/concentric.svelte b/docs/src/examples/components/webgl/Arc/concentric.svelte new file mode 100644 index 0000000000..f9c99a3dae --- /dev/null +++ b/docs/src/examples/components/webgl/Arc/concentric.svelte @@ -0,0 +1,53 @@ + + + + + + + + + + diff --git a/docs/src/examples/components/webgl/Arc/pie.svelte b/docs/src/examples/components/webgl/Arc/pie.svelte new file mode 100644 index 0000000000..8c8092ccaf --- /dev/null +++ b/docs/src/examples/components/webgl/Arc/pie.svelte @@ -0,0 +1,83 @@ + + + + + Pie + Donut + + + + + + {#snippet children({ context })} + {@const outer = Math.min(context.width, context.height) / 2} + + + {#each arcs as arc} + {@const angle = (arc.startAngle + arc.endAngle) / 2} + + + {/each} + + + + {#snippet children({ data })} + {data.data.fruit} + + + + {/snippet} + + {/snippet} + diff --git a/docs/src/examples/components/webgl/Area/areas.svelte b/docs/src/examples/components/webgl/Area/areas.svelte new file mode 100644 index 0000000000..e66a206509 --- /dev/null +++ b/docs/src/examples/components/webgl/Area/areas.svelte @@ -0,0 +1,60 @@ + + + + + Front + Angled + + + + + [0, width * 0.3]} + c="series" + cScale={scaleOrdinal()} + cRange={['#2caffe', '#544fc5', '#00e272', '#fe6a35']} + height={500} +> + + + + + + + + + diff --git a/docs/src/examples/components/webgl/Area/ridgeline.svelte b/docs/src/examples/components/webgl/Area/ridgeline.svelte new file mode 100644 index 0000000000..509ba472bf --- /dev/null +++ b/docs/src/examples/components/webgl/Area/ridgeline.svelte @@ -0,0 +1,149 @@ + + +
+ + + + +
+ + + + + N - 1 - i)} + z="value" + zDomain={[0, 128]} + zRange={({ height }) => [0, height * 0.6]} + height={500} +> + + {#each rowIndexes as row (row)} + {@const frame = rows.filter((d) => d.row === row)} + + + {/each} + + diff --git a/docs/src/examples/components/webgl/Bars/calendar.svelte b/docs/src/examples/components/webgl/Bars/calendar.svelte new file mode 100644 index 0000000000..9ba7957113 --- /dev/null +++ b/docs/src/examples/components/webgl/Bars/calendar.svelte @@ -0,0 +1,58 @@ + + + + d.date.getDay()} + yScale={scaleBand()} + yDomain={range(7)} + c="value" + cScale={scaleThreshold().unknown('var(--color-surface-200)')} + cDomain={[1, 5, 10, 15]} + cRange={['var(--color-surface-200)', '#9be9a8', '#40c463', '#30a14e', '#216e39']} + z="value" + zDomain={[0, 20]} + zRange={[0, 60]} + tooltipContext + height={260} +> + + + + + + + + {#snippet children({ data })} + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Bars/columns.svelte b/docs/src/examples/components/webgl/Bars/columns.svelte new file mode 100644 index 0000000000..5abe426254 --- /dev/null +++ b/docs/src/examples/components/webgl/Bars/columns.svelte @@ -0,0 +1,53 @@ + + + timeWeek.count(timeYear(d.date), d.date)} + xScale={scaleBand().padding(0.2)} + y={(d) => d.date.getDay()} + yScale={scaleBand().padding(0.2)} + yDomain={range(7)} + z="value" + zDomain={[0, 100]} + c="value" + cDomain={[25, 50, 75]} + cRange={[ + 'var(--color-primary-100)', + 'var(--color-primary-300)', + 'var(--color-primary-500)', + 'var(--color-primary-700)' + ]} + tooltipContext + height={500} +> + + + 'W' + d} /> + daysOfWeek[d]} /> + + + + + + {#snippet children({ data })} + {format(data.date, 'day')} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Bars/heatmap.svelte b/docs/src/examples/components/webgl/Bars/heatmap.svelte new file mode 100644 index 0000000000..a85690a038 --- /dev/null +++ b/docs/src/examples/components/webgl/Bars/heatmap.svelte @@ -0,0 +1,52 @@ + + + + timeWeek.count(timeYear(d.date), d.date)} + xScale={scaleBand()} + y={(d) => d.date.getDay()} + yScale={scaleBand()} + yDomain={range(7)} + c="value" + cDomain={[25, 50, 75]} + cRange={[ + 'var(--color-primary-100)', + 'var(--color-primary-300)', + 'var(--color-primary-500)', + 'var(--color-primary-700)' + ]} + tooltipContext + height={400} +> + + + 'W' + d} /> + daysOfWeek[d]} /> + + + + + {#snippet children({ data })} + {format(data.date, 'day')} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Bars/stacked-columns.svelte b/docs/src/examples/components/webgl/Bars/stacked-columns.svelte new file mode 100644 index 0000000000..516a55243d --- /dev/null +++ b/docs/src/examples/components/webgl/Bars/stacked-columns.svelte @@ -0,0 +1,51 @@ + + + + [0, height * 1.2]} + c="fruit" + cRange={[ + 'var(--color-green-500)', + 'var(--color-yellow-500)', + 'var(--color-red-500)', + 'var(--color-purple-500)' + ]} + tooltipContext + padding={{ top: 24 }} + height={500} +> + + + + `Basket ${d}`} /> + + + + + + + + {#snippet children({ data })} + {data.year} · Basket {data.basket} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Bin/hexbin.svelte b/docs/src/examples/components/webgl/Bin/hexbin.svelte new file mode 100644 index 0000000000..858a58f587 --- /dev/null +++ b/docs/src/examples/components/webgl/Bin/hexbin.svelte @@ -0,0 +1,43 @@ + + + + + + [0, height * 0.4]} + tooltipContext + height={500} +> + + + + + + + + + {#snippet children({ data })} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Bin/state-population.svelte b/docs/src/examples/components/webgl/Bin/state-population.svelte new file mode 100644 index 0000000000..0fa96fbc63 --- /dev/null +++ b/docs/src/examples/components/webgl/Bin/state-population.svelte @@ -0,0 +1,185 @@ + + + + +
+ + ({ label, value: label }))} + bind:value={palette} + clearable={false} + toggleIcon={null} + stepper + /> +
+ + + d[0]} + y={(d: Cell) => d[1]} + geo={{ projection, fitGeojson: outline }} + zScale={scaleSqrt()} + cScale={scaleSequentialLog(interpolator)} + zRange={({ height }) => [0, height * 0.25]} + tooltipContext + height={600} +> + {#snippet children({ context })} + {@const project = context.geo.projection} + {@const center = project?.invert?.([context.width / 2, context.height / 2]) ?? [0, 0]} + + {@const pixelsPerSqMeter = (() => { + if (!project) return 1; + const [lon, lat] = center; + const d = 0.01; + const a = project([lon, lat]); + const b = project([lon + d, lat]); + const c = project([lon, lat + d]); + if (!a || !b || !c) return 1; + const pixels = Math.abs((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])); + const meters = d * 111_320 * Math.cos((lat * Math.PI) / 180) * (d * 110_574); + return pixels / meters; + })()} + + {@const density = (cell: { count: number; area: number }) => + cell.count / ((cell.area / pixelsPerSqMeter) * SQ_MI)} + + + + + + + + + + d[2]} + z={density} + fill={(cell) => Math.max(10, density(cell))} + tooltip + /> + + + city[1]} + y1={(city: City) => city[2]} + z2={context.zDepth * 0.9} + stroke="color-mix(in oklab, var(--color-surface-content) 60%, transparent)" + /> + city[1]} + y={(city: City) => city[2]} + z={context.zDepth * 0.9 + 10} + value={(city: City) => city[0]} + viewport + class="rounded-sm bg-surface-100/90 px-1.5 py-0.5 text-[11px] font-semibold uppercase tracking-wider text-surface-content shadow-sm ring-1 ring-surface-content/15" + /> + + + + {#snippet children({ data })} + + + + + {/snippet} + + {/snippet} + diff --git a/docs/src/examples/components/webgl/Bin/walmart.svelte b/docs/src/examples/components/webgl/Bin/walmart.svelte new file mode 100644 index 0000000000..d918182a3e --- /dev/null +++ b/docs/src/examples/components/webgl/Bin/walmart.svelte @@ -0,0 +1,53 @@ + + + + + + [0, height * 0.25]} + tooltipContext + height={550} +> + + + + + + + + + {#snippet children({ data })} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Contour/basic.svelte b/docs/src/examples/components/webgl/Contour/basic.svelte new file mode 100644 index 0000000000..0a3600e2a7 --- /dev/null +++ b/docs/src/examples/components/webgl/Contour/basic.svelte @@ -0,0 +1,34 @@ + + + + + + [0, height * 0.35]} + height={450} +> + + + + + diff --git a/docs/src/examples/components/webgl/GeoPath/election.svelte b/docs/src/examples/components/webgl/GeoPath/election.svelte new file mode 100644 index 0000000000..4012acc094 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoPath/election.svelte @@ -0,0 +1,81 @@ + + + + + + + Democratic + Republican + + + + + GeoProjection, fitGeojson: states }} + zDomain={[0, 1]} + zRange={[0, 50]} + tooltipContext + height={550} +> + + interpolateRgb('white', parties[party])(shareOf(state))} + stroke="color-mix(in oklab, black 25%, var(--color-surface-100))" + strokeWidth={0.5} + motion={{ type: 'tween', duration: 800, easing: cubicInOut }} + /> + + + + {#snippet children({ data })} + {@const share = shares.get(data.properties.name)} + {data.properties.name} + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/GeoRaster/globe-textures.svelte b/docs/src/examples/components/webgl/GeoRaster/globe-textures.svelte new file mode 100644 index 0000000000..1542b0d642 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoRaster/globe-textures.svelte @@ -0,0 +1,167 @@ + + +
+ +
+ + + + + {#if texture} + + {/if} + + diff --git a/docs/src/examples/components/webgl/GeoRaster/globe-tiles.svelte b/docs/src/examples/components/webgl/GeoRaster/globe-tiles.svelte new file mode 100644 index 0000000000..a047e917dd --- /dev/null +++ b/docs/src/examples/components/webgl/GeoRaster/globe-tiles.svelte @@ -0,0 +1,111 @@ + + + + +
+ + +
+ + + + + + {#if image} + + {/if} + + + diff --git a/docs/src/examples/components/webgl/GeoRaster/globe.svelte b/docs/src/examples/components/webgl/GeoRaster/globe.svelte new file mode 100644 index 0000000000..033a704b8d --- /dev/null +++ b/docs/src/examples/components/webgl/GeoRaster/globe.svelte @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + {#snippet children({ data })} + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/GeoRaster/planets.svelte b/docs/src/examples/components/webgl/GeoRaster/planets.svelte new file mode 100644 index 0000000000..91742941bd --- /dev/null +++ b/docs/src/examples/components/webgl/GeoRaster/planets.svelte @@ -0,0 +1,95 @@ + + +
+ + + + + + + + + + +
+ + { + if (!dragging || !rotation) return; + rotate = rotation.x; + tilt = rotation.y; + }} + ondragstart={() => (dragging = true)} + ondragend={() => (dragging = false)} + height={500} +> + + + + + + + diff --git a/docs/src/examples/components/webgl/GeoRaster/projections.svelte b/docs/src/examples/components/webgl/GeoRaster/projections.svelte new file mode 100644 index 0000000000..0f6a123b96 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoRaster/projections.svelte @@ -0,0 +1,77 @@ + + + + +
+ +
+ + + + + + + + + diff --git a/docs/src/examples/components/webgl/GeoRaster/terrain.svelte b/docs/src/examples/components/webgl/GeoRaster/terrain.svelte new file mode 100644 index 0000000000..edeb17f722 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoRaster/terrain.svelte @@ -0,0 +1,235 @@ + + +
+ ({ label, value: label }))} + bind:value={placeLabel} + clearable={false} + toggleIcon={null} + stepper + /> + ({ label, value: label }))} + bind:value={surface} + clearable={false} + toggleIcon={null} + stepper + /> + +
+ + + { + if (!terrain) return [0, 0]; + // Meters on the ground in pixels where the map is drawn, so heights are true to scale + const ground = geoMercator().fitSize([width, height], area); + const center = [ + (place.bounds[0][0] + place.bounds[1][0]) / 2, + (place.bounds[0][1] + place.bounds[1][1]) / 2 + ] as [number, number]; + return [0, (terrain.high - terrain.low) * pixelsPerMeter(ground, center) * exaggeration]; + }} + tooltipContext + height={600} + class="rounded-sm bg-surface-200" +> + + + + {#if terrain && imagery?.label === place.label} + + {/if} + + + + + {#snippet children({ data })} + + + + + + {/snippet} + + + + diff --git a/docs/src/examples/components/webgl/GeoTile/globe.svelte b/docs/src/examples/components/webgl/GeoTile/globe.svelte new file mode 100644 index 0000000000..2a6fd26e63 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoTile/globe.svelte @@ -0,0 +1,34 @@ + + + + + + + + diff --git a/docs/src/examples/components/webgl/GeoTile/terrain.svelte b/docs/src/examples/components/webgl/GeoTile/terrain.svelte new file mode 100644 index 0000000000..79c239b698 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoTile/terrain.svelte @@ -0,0 +1,191 @@ + + +
+ ({ label, value: label }))} + bind:value={placeLabel} + clearable={false} + toggleIcon={null} + stepper + /> + ({ label, value: label }))} + bind:value={surface} + clearable={false} + toggleIcon={null} + stepper + /> + + + + +
+ + + + + + + + + + + + {#snippet children({ data })} + + + + + + {/snippet} + + + + diff --git a/docs/src/examples/components/webgl/GeoTile/zoomable.svelte b/docs/src/examples/components/webgl/GeoTile/zoomable.svelte new file mode 100644 index 0000000000..ccc2b53ac1 --- /dev/null +++ b/docs/src/examples/components/webgl/GeoTile/zoomable.svelte @@ -0,0 +1,50 @@ + + + + + + + +{#if serviceUrl} + + + + + + + +{/if} diff --git a/docs/src/examples/components/webgl/Light/buildings.svelte b/docs/src/examples/components/webgl/Light/buildings.svelte new file mode 100644 index 0000000000..c81f679855 --- /dev/null +++ b/docs/src/examples/components/webgl/Light/buildings.svelte @@ -0,0 +1,65 @@ + + + + +
+ + + + + +
+ + [ + 0, + // Meters to pixels at the map's scale, so towers stand as tall as they are wide + 420 * pixelsPerMeter(geoMercator().fitSize([width, height], buildings), [-74.01, 40.708]) + ]} + tooltipContext + height={600} +> + + + + + + + + {#snippet children({ data })} + {data.properties.name ?? 'Building'} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Link/pin-map.svelte b/docs/src/examples/components/webgl/Link/pin-map.svelte new file mode 100644 index 0000000000..1ae419299d --- /dev/null +++ b/docs/src/examples/components/webgl/Link/pin-map.svelte @@ -0,0 +1,95 @@ + + + + + + GeoProjection, fitGeojson: states }} + zDomain={[0, largest.population]} + zRange={[0, 200]} + tooltipContext + height={550} +> + {#snippet children({ context })} + {@const at = (pin: (typeof pins)[number]) => context.geo.projection?.([pin.x, pin.y]) ?? [0, 0]} + + + + + + + + + + {#snippet children({ data })} + {data.name} + + + + {/snippet} + + {/snippet} + diff --git a/docs/src/examples/components/webgl/Points/galaxy.svelte b/docs/src/examples/components/webgl/Points/galaxy.svelte new file mode 100644 index 0000000000..e46c2c402a --- /dev/null +++ b/docs/src/examples/components/webgl/Points/galaxy.svelte @@ -0,0 +1,119 @@ + + +
+ ({ + label: value.toLocaleString(), + value + }))} + bind:value={count} + clearable={false} + toggleIcon={null} + stepper + /> + + + + +
+ +
+ [0, width / VIEW]} + view={perspective({ rotate: -30, tilt: 55, fov: 75 })} + transform={{ + mode: 'canvas', + drag: 'rotate', + scrollMode: 'scale', + scrollActivationKey: 'shift' + }} + bind:context + padding={20} + height={600} + > + + colorOf(d.out)} glow class="mix-blend-plus-lighter" /> + + +
diff --git a/docs/src/examples/components/webgl/Points/scatter-3d.svelte b/docs/src/examples/components/webgl/Points/scatter-3d.svelte new file mode 100644 index 0000000000..a9a3724bbe --- /dev/null +++ b/docs/src/examples/components/webgl/Points/scatter-3d.svelte @@ -0,0 +1,103 @@ + + +
+ + + Perspective + Orthographic + + + + + Default + Viewport + + +
+ + [0, height]} + c="z" + cScale={scaleQuantize()} + cDomain={[0, 10]} + cRange={[ + 'var(--color-primary-300)', + 'var(--color-primary-500)', + 'var(--color-primary-700)', + 'var(--color-primary-900)' + ]} + tooltipContext + height={500} +> + + + + + + + + + + + + + + {#snippet children({ data })} + + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Points/scatter-with-svg.svelte b/docs/src/examples/components/webgl/Points/scatter-with-svg.svelte new file mode 100644 index 0000000000..3491f3b7bb --- /dev/null +++ b/docs/src/examples/components/webgl/Points/scatter-with-svg.svelte @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + {#snippet children({ data })} + {data.cluster} + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Points/scatter.svelte b/docs/src/examples/components/webgl/Points/scatter.svelte new file mode 100644 index 0000000000..4f587c0494 --- /dev/null +++ b/docs/src/examples/components/webgl/Points/scatter.svelte @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + {#snippet children({ data })} + {data.cluster} + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Points/solar-system.svelte b/docs/src/examples/components/webgl/Points/solar-system.svelte new file mode 100644 index 0000000000..deb7a5255d --- /dev/null +++ b/docs/src/examples/components/webgl/Points/solar-system.svelte @@ -0,0 +1,308 @@ + + +
+ + + + + + + Log + To scale + + + + + +
+ +
+ { + const side = Math.min(width, height); + return [(width - side) / 2, (width + side) / 2]; + }} + yRange={({ width, height }) => { + const side = Math.min(width, height); + return [(height - side) / 2, (height + side) / 2]; + }} + zDomain={[-1, 1]} + zRange={({ width, height }) => { + // The same pixels to the AU up as across, so orbits keep their tilt + const perUnit = Math.min(width, height) / (2 * reach); + return [-perUnit, perUnit]; + }} + tooltipContext + height={600} + > + {#snippet children({ context })} + {@const sun = [context.xScale(0), context.yScale(0)] as [number, number]} + + {@const toPixels = Math.min(context.width, context.height) / (2 * reach)} + + {@const radiusOf = (planet: Planet) => + Math.max(1, Math.min(size(planet), room.get(planet.name)! * toPixels * 0.4))} + {@const sunRadius = Math.max( + 1.5, + Math.min(scale === 'log' ? 14 : 7, out(PLANETS[0].elements[0]) * toPixels * 0.5) + )} + + {@const named = (() => { + if (scale === 'log') return new Set(PLANETS.map((planet) => planet.name)); + let last = Infinity; + return new Set( + [...PLANETS] + .reverse() + .filter((planet) => { + const at = out(planet.elements[0]) * toPixels; + if (last - at < 28) return false; + last = at; + return true; + }) + .map((planet) => planet.name) + ); + })()} + + + + + + d.x * reach * 4} + y={(d) => d.y * reach * 4} + z={(d) => d.z * reach * 4} + r={(d) => d.r * 2.5} + fill={(d) => `rgb(${[0, 1, 2].map(() => Math.round(110 + d.bright * 145)).join(',')})`} + glow + /> + + + + + + + + {@const saturn = planets.find((p) => p.rings)!} + saturn.x + (d.radius * radiusOf(saturn) * d.across) / toPixels} + y={(d) => saturn.y + (d.radius * radiusOf(saturn) * d.down) / toPixels} + z={(d) => saturn.z + (d.radius * radiusOf(saturn) * d.up) / toPixels} + stroke="color-mix(in oklab, #e3d29b 45%, transparent)" + strokeWidth={1} + /> + + + {#each planets.filter((p) => named.has(p.name)) as planet (planet.name)} + + {/each} + + + + {#snippet children({ data })} + {data.name} + + + {#if data.elements} + + {/if} + + {/snippet} + + {/snippet} + +
diff --git a/docs/src/examples/components/webgl/Polygon/tree.svelte b/docs/src/examples/components/webgl/Polygon/tree.svelte new file mode 100644 index 0000000000..c19b048226 --- /dev/null +++ b/docs/src/examples/components/webgl/Polygon/tree.svelte @@ -0,0 +1,65 @@ + + + + {#snippet children({ context })} + {@const layout = tree().size([context.width, context.height])(data.copy())} + {@const nodes = layout.descendants()} + + + + + {#each nodes as node} + {@const { points, rotate, r, z, fill } = shapeOf(node)} + + + {/each} + + {/snippet} + diff --git a/docs/src/examples/components/webgl/Raster/basic.svelte b/docs/src/examples/components/webgl/Raster/basic.svelte new file mode 100644 index 0000000000..a6241a39fb --- /dev/null +++ b/docs/src/examples/components/webgl/Raster/basic.svelte @@ -0,0 +1,31 @@ + + + + + + + + Math.sin(x) * Math.cos(y)} pixelSize={3} tooltip /> + + + + {#snippet children({ data })} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Rect/treemap.svelte b/docs/src/examples/components/webgl/Rect/treemap.svelte new file mode 100644 index 0000000000..5b84bf5373 --- /dev/null +++ b/docs/src/examples/components/webgl/Rect/treemap.svelte @@ -0,0 +1,128 @@ + + + + +
+ + + + + +
+ + + [0, ((root.height + 1) * height) / 80]} + tooltipContext + height={600} +> + {#snippet children({ context })} + {@const label = (d: Node) => leafLabel(d, context)} + + + + [d.depth, d.depth + 1]} + fill={(d) => nodeColor(d).toString()} + class="stroke-black/25" + strokeWidth={0.5} + /> + + !d.children && label(d).fontSize >= 2)} + x={(d) => (d.x0 + d.x1) / 2} + y={(d) => (d.y0 + d.y1) / 2} + z={(d) => d.depth + 1} + value={(d) => label(d).name} + fontSize={(d) => label(d).fontSize} + rotate={(d) => (label(d).vertical ? 90 : 0)} + // Lit along with the tops they lie on, so a shade darker than the flat chart's to read + fill={(d) => nodeColor(d).darker(2).toString()} + /> + + + + {#snippet children({ data })} + + {data + .ancestors() + .reverse() + .slice(1) + .map((n: HierarchyNode) => n.data.name) + .join(' / ') || data.data.name} + + + + + {/snippet} + + {/snippet} + diff --git a/docs/src/examples/components/webgl/Rule/lollipop.svelte b/docs/src/examples/components/webgl/Rule/lollipop.svelte new file mode 100644 index 0000000000..e4820b1a56 --- /dev/null +++ b/docs/src/examples/components/webgl/Rule/lollipop.svelte @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + {#snippet children({ data })} + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Spline/line3d.svelte b/docs/src/examples/components/webgl/Spline/line3d.svelte new file mode 100644 index 0000000000..57c5af6fc9 --- /dev/null +++ b/docs/src/examples/components/webgl/Spline/line3d.svelte @@ -0,0 +1,37 @@ + + + [0, height]} + c="z" + cScale={scaleSequential(interpolateViridis)} + height={550} +> + + + + + + + + + diff --git a/docs/src/examples/components/webgl/Spline/series.svelte b/docs/src/examples/components/webgl/Spline/series.svelte new file mode 100644 index 0000000000..75c477371c --- /dev/null +++ b/docs/src/examples/components/webgl/Spline/series.svelte @@ -0,0 +1,48 @@ + + + + + + + + + + + diff --git a/docs/src/examples/components/webgl/Spline/temperatures.svelte b/docs/src/examples/components/webgl/Spline/temperatures.svelte new file mode 100644 index 0000000000..45d408f176 --- /dev/null +++ b/docs/src/examples/components/webgl/Spline/temperatures.svelte @@ -0,0 +1,129 @@ + + + + + + + Radial + Linear + + + +{#if layout === 'radial'} + + [0, height]} + c="year" + cScale={scaleSequential(interpolatePlasma)} + g="year" + tooltipContext + height={550} + > + + + + + {@render tooltip()} + +{:else} + + [0, height * 0.6]} + c="year" + cScale={scaleSequential(interpolatePlasma)} + g="year" + tooltipContext + height={550} + > + + + + v + '° F'} /> + + + {@render tooltip()} + +{/if} + +{#snippet tooltip()} + + {#snippet children({ data })} + + + {data.date.toLocaleDateString(undefined, { + month: 'short', + day: 'numeric', + timeZone: 'UTC' + })}, + {data.year} + + + + + {/snippet} + +{/snippet} diff --git a/docs/src/examples/components/webgl/Surface/basic.svelte b/docs/src/examples/components/webgl/Surface/basic.svelte new file mode 100644 index 0000000000..f1fcb87a15 --- /dev/null +++ b/docs/src/examples/components/webgl/Surface/basic.svelte @@ -0,0 +1,41 @@ + + + [0, height * 0.6]} + cScale={scaleSequential((t) => interpolateRdYlBu(1 - t))} + tooltipContext + height={500} +> + + + + + + Math.sin(x * Math.PI) * Math.sin(y * Math.PI)} + pixelSize={6} + wireframe + /> + + + + {#snippet children({ data })} + + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Surface/math-functions.svelte b/docs/src/examples/components/webgl/Surface/math-functions.svelte new file mode 100644 index 0000000000..80a5367011 --- /dev/null +++ b/docs/src/examples/components/webgl/Surface/math-functions.svelte @@ -0,0 +1,141 @@ + + +
+
+ + + + + Flat + Raised + + + + + +
+ + [0, height * 0.3 * raised.current]} + height={450} + > + + + + + + + +
diff --git a/docs/src/examples/components/webgl/Surface/terrain.svelte b/docs/src/examples/components/webgl/Surface/terrain.svelte new file mode 100644 index 0000000000..0f76a5fe16 --- /dev/null +++ b/docs/src/examples/components/webgl/Surface/terrain.svelte @@ -0,0 +1,176 @@ + + +
+ ({ label: p.label, value: p.label }))} + bind:value={selected} + clearable={false} + toggleIcon={null} + stepper + /> + + + +
+
+ + + + +
+ + + [ + 0, + // At the map's scale, times the exaggeration + (terrain ? terrain.range[1] - terrain.range[0] : 0) * + pixelsPerMeter(geoMercator().fitSize([width, height], box), [west, (south + north) / 2]) * + exaggeration || 1 + ]} + tooltipContext + height={550} +> + + + + {#if terrain} + + {/if} + + + + + + {#snippet children({ data })} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Surface/us-elevation.svelte b/docs/src/examples/components/webgl/Surface/us-elevation.svelte new file mode 100644 index 0000000000..5685910482 --- /dev/null +++ b/docs/src/examples/components/webgl/Surface/us-elevation.svelte @@ -0,0 +1,99 @@ + + + + +
+ + + + + + +
+ + + [0, (height / 80) * exaggeration]} + tooltipContext + height={550} +> + + + + {#if elevation} + + {/if} + + + + + + {#snippet children({ data })} + + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Surface/volcano.svelte b/docs/src/examples/components/webgl/Surface/volcano.svelte new file mode 100644 index 0000000000..14c63d5105 --- /dev/null +++ b/docs/src/examples/components/webgl/Surface/volcano.svelte @@ -0,0 +1,61 @@ + + + + + + + Raised + Flat + + + + + [0, height * 0.35 * raised.current]} + tooltipContext + height={500} +> + + + + + + + + {#snippet children({ data })} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Surface/world-elevation.svelte b/docs/src/examples/components/webgl/Surface/world-elevation.svelte new file mode 100644 index 0000000000..3f3083180e --- /dev/null +++ b/docs/src/examples/components/webgl/Surface/world-elevation.svelte @@ -0,0 +1,97 @@ + + +
+ ({ label, value }))} + bind:value={selected} + clearable={false} + toggleIcon={null} + stepper + /> + +
+ + [0, (height / 50) * exaggeration]} + tooltipContext + height={500} +> + + + + {#if elevation} + + + {/if} + + + + {#snippet children({ data })} + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/Vector/field.svelte b/docs/src/examples/components/webgl/Vector/field.svelte new file mode 100644 index 0000000000..ef784c2641 --- /dev/null +++ b/docs/src/examples/components/webgl/Vector/field.svelte @@ -0,0 +1,81 @@ + + + + [0, height]} + r="magnitude" + rRange={[10, 34]} + c="magnitude" + cScale={scaleSequential(interpolateTurbo)} + view={perspective({ rotate: -30, tilt: 65 })} + transform={{ mode: 'canvas', drag: 'rotate', scrollMode: 'scale', scrollActivationKey: 'shift' }} + tooltipContext + padding={40} + height={550} +> + + + + + + + + + + {#snippet children({ data })} + ({data.x}, {data.y}, {data.z}) + + + + + + + {/snippet} + + diff --git a/docs/src/examples/components/webgl/WebGL/playground.svelte b/docs/src/examples/components/webgl/WebGL/playground.svelte new file mode 100644 index 0000000000..0f76392fde --- /dev/null +++ b/docs/src/examples/components/webgl/WebGL/playground.svelte @@ -0,0 +1,135 @@ + + +
+ + + Perspective + Orthographic + + + + + On + Off + + + + + + + +
+ + d.value)} + cRange={[ + 'var(--color-primary-100)', + 'var(--color-primary-300)', + 'var(--color-primary-500)', + 'var(--color-primary-700)' + ]} + view={camera === 'orthographic' + ? orthographic({ rotate, tilt }) + : perspective({ rotate, tilt, fov })} + {padding} + transform={{ mode: 'canvas', drag: 'rotate', scrollMode: 'scale', disablePointer: !controls }} + onTransform={({ rotation }) => { + // Keep the sliders in step with a drag + if (!dragging || !rotation) return; + // Wrapped to the slider's ±180° — the same turn either way round + rotate = ((((rotation.x + 180) % 360) + 360) % 360) - 180; + tilt = rotation.y; + }} + ondragstart={() => (dragging = true)} + ondragend={() => (dragging = false)} + tooltipContext + height={500} +> + + + + + + + + + + {#snippet children({ data })} + + + + + + {/snippet} + + diff --git a/docs/src/lib/componentPage.ts b/docs/src/lib/componentPage.ts new file mode 100644 index 0000000000..a22cc83aa1 --- /dev/null +++ b/docs/src/lib/componentPage.ts @@ -0,0 +1,116 @@ +import type { ComponentCatalog } from '@layerstack/docs/catalog'; +import type { Examples } from '@layerstack/docs/examples'; +import { allComponents } from 'content-collections'; +import { getMarkdownComponent, loadExamplesFromMarkdown } from '$lib/content.js'; + +/** + * A component page's data, for the component named `componentName`: its slug, and the folder its + * examples are in under `src/examples/components` (ex. `Points`, or `webgl/Points` for + * `@layerchart/webgl`'s, whose names repeat LayerChart's) + */ +export async function loadComponentPage( + componentName: string, + { + params, + parent + }: { params: { example?: string }; parent: () => Promise<{ examples?: Examples }> } +) { + // Get examples from parent layout + const parentData = await parent(); + + const allCatalogs = import.meta.glob('/src/examples/catalog/**/*.json', { + import: 'default' + }); + + const { PageComponent, metadata } = await getMarkdownComponent(componentName); + + // Load the catalog file for the current component + const catalogPath = `/src/examples/catalog/${componentName}.json`; + const loaded: ComponentCatalog | null = + catalogPath in allCatalogs ? ((await allCatalogs[catalogPath]()) as ComponentCatalog) : null; + const catalog = loaded && componentName.startsWith('webgl/') ? webglCatalog(loaded) : loaded; + + // Eagerly load examples referenced in the markdown content + // Only examples explicitly in the markdown are included (not the full catalog) + const pageExamples = await loadExamplesFromMarkdown( + metadata.content, + componentName // default component for implicit usage + ); + + // If navigating directly to an individual example page, also load that specific example. + // This is necessary because Component functions aren't serializable, so page.data.example + // from [example]/+page.ts can't be used to update context after initialization. + const exampleName = params.example; + if (exampleName && !pageExamples[componentName]?.[exampleName]) { + const { loadExample } = await import('$lib/examples.js'); + const loaded = await loadExample(componentName, exampleName); + if (loaded) { + if (!pageExamples[componentName]) pageExamples[componentName] = {}; + pageExamples[componentName][exampleName] = loaded; + } + } + + // Merge with parent examples (from /docs layout) + // Page examples take precedence + const examples: Examples = { ...parentData.examples, ...pageExamples }; + + return { + componentName, + PageComponent, + metadata, + catalog, + examples, + counterpart: counterpartOf(componentName) + }; +} + +/** + * The same-named component on the other side, to link to: `@layerchart/webgl`'s for one of + * LayerChart's (ex. `Points` ↔ `webgl/Points`), and LayerChart's for one of its, labeled with its layers + */ +function counterpartOf(componentName: string): { href: string; label: string } | null { + const webgl = componentName.startsWith('webgl/'); + const name = webgl ? componentName.slice(6) : `webgl/${componentName}`; + const other = allComponents.find((c) => c.slug === name); + if (!other) return null; + const layers = ((other as { layers?: string[] }).layers ?? []).map( + (layer) => layer[0].toUpperCase() + layer.slice(1) + ); + return { + href: `/docs/components/${name}`, + label: webgl ? layers.join(' / ') || 'Core' : 'WebGL' + }; +} + +/** + * A `@layerchart/webgl` catalog (generated from its own components and examples) with its + * components named as their pages are, `webgl/`, so its examples load from their folder and + * its links go to the WebGL pages rather than LayerChart's same-named ones + */ +function webglCatalog(catalog: ComponentCatalog): ComponentCatalog { + const pages = new Set( + allComponents.filter((c) => c.slug.startsWith('webgl/')).map((c) => c.slug.slice(6)) + ); + const rename = (name: string) => (pages.has(name) ? `webgl/${name}` : name); + const repath = (path: string) => + path.replace(/^\/docs\/components\/([^/]+)\//, (whole, name) => + pages.has(name) ? `/docs/components/webgl/${name}/` : whole + ); + return { + ...catalog, + component: rename(catalog.component), + examples: catalog.examples.map((example) => ({ + ...example, + path: example.path && repath(example.path), + components: example.components?.map((usage) => ({ + ...usage, + component: rename(usage.component) + })) + })), + usage: catalog.usage?.map((usage) => ({ + ...usage, + component: rename(usage.component), + path: usage.path && repath(usage.path) + })) + } as ComponentCatalog; +} diff --git a/docs/src/lib/components/DocsMenu.svelte b/docs/src/lib/components/DocsMenu.svelte index 080f1e9263..ee8df0f531 100644 --- a/docs/src/lib/components/DocsMenu.svelte +++ b/docs/src/lib/components/DocsMenu.svelte @@ -7,6 +7,7 @@ import { page } from '$app/state'; import { sortFunc } from '@layerstack/utils'; import { cls } from '@layerstack/tailwind'; + import { webglCategories } from '$lib/webglCategories.js'; import LucideBot from '~icons/lucide/bot'; import LucideCompass from '~icons/lucide/compass'; @@ -16,6 +17,7 @@ import LucideGlobe from '~icons/lucide/globe'; import LucideNotebookPen from '~icons/lucide/notebook-pen'; import LucideBlocks from '~icons/lucide/blocks'; + import LucideBox from '~icons/lucide/box'; import LucideFileCode2 from '~icons/lucide/file-code-2'; import LucideCirclePlay from '~icons/lucide/circle-play'; import LucideParentheses from '~icons/lucide/parentheses'; @@ -29,8 +31,12 @@ const collapsibleCategories = ['migrations']; - const componentsByCategory = flatGroup(allComponents, (d) => d.category?.toLowerCase()) - .filter(([category]) => category !== 'examples') + const byCategory = flatGroup(allComponents, (d) => d.category?.toLowerCase()).filter( + ([category]) => category !== 'examples' + ); + + const componentsByCategory = byCategory + .filter(([category]) => !(category in webglCategories)) .sort( sortFunc(([category]) => [ @@ -49,6 +55,10 @@ ].indexOf(category) ) ); + + const webglByCategory = byCategory + .filter(([category]) => category in webglCategories) + .sort(sortFunc(([category]) => Object.keys(webglCategories).indexOf(category))); +{#snippet componentGroup(category: string, components: typeof allComponents)} +
+

{category}

+
+ {#each sortCollection(components) as component} + {@render navItem({ label: component.name, path: `/docs/components/${component.slug}` })} + {/each} +
+
+{/snippet} + {#snippet navItem({ label, path, icon }: { label: string; path: string; icon?: IconProp })} ; showOpenWith?: boolean; + /** The same component drawn the other way (LayerChart's, or `@layerchart/webgl`'s), to link to */ + counterpart?: { href: string; label: string } | null; /** Docs section icon (matching the sidebar), shown on links to parent pages */ icon?: Component<{ class?: string }>; } = $props(); @@ -210,6 +214,24 @@ {/each} {/if} + {#if counterpart} + + + + {/if}