Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/trim-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'layerchart': patch
---

chore: Remove `d3-dsv`, `d3-geo-polygon` and `d3-sankey` dependencies, dropping 12 packages (~2.9 MB) from installs, including the command-line-only `commander`, `iconv-lite` and `rw`, and older duplicate versions of `d3-array`, `d3-shape` and `d3-path` (`sankeyGraphFromCsv()` no longer handles quoted fields)
2 changes: 0 additions & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
"@types/d3-hierarchy": "^3.1.7",
"@types/d3-interpolate": "^3.0.4",
"@types/d3-random": "^3.0.3",
"@types/d3-sankey": "^0.12.5",
"@types/d3-scale": "^4.0.9",
"@types/d3-scale-chromatic": "^3.1.0",
"@types/d3-shape": "^3.1.8",
Expand All @@ -78,7 +77,6 @@
"d3-hierarchy": "^3.1.2",
"d3-interpolate": "^3.0.1",
"d3-random": "^3.0.1",
"d3-sankey": "^0.12.3",
"d3-scale": "^4.0.2",
"d3-scale-chromatic": "^3.1.0",
"d3-shape": "^3.2.0",
Expand Down
12 changes: 6 additions & 6 deletions docs/src/content/guides/bundle-size.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ These additions to your chart cause an extra HTTP fetch the first time the corre

Components that bring in large d3 modules or framework-specific libraries are not re-exported from the root `'layerchart'` entry. They live behind opt-in sub-paths so the default barrel doesn't drag those deps into bundlers that don't tree-shake aggressively.

| Sub-path | Components | Heavy dep saved |
| ---------------------- | -------------------------------------- | -------------------------------------------------- |
| `layerchart/geo` | `Geo*` (12), `Graticule`, `TileImage` | `d3-geo` (~15 KB), `d3-tile` |
| `layerchart/hierarchy` | `Tree`, `Treemap`, `Pack`, `Partition` | `d3-hierarchy` (~6 KB) |
| `layerchart/force` | `ForceSimulation` | `d3-force` (~7 KB) |
| `layerchart/graph` | `Dagre`, `Sankey`, `Chord`, `Ribbon` | `@dagrejs/dagre` (~22 KB), `d3-sankey`, `d3-chord` |
| Sub-path | Components | Heavy dep saved |
| ---------------------- | -------------------------------------- | ---------------------------------------------------- |
| `layerchart/geo` | `Geo*` (12), `Graticule`, `TileImage` | `d3-geo` (~15 KB), `d3-tile` |
| `layerchart/hierarchy` | `Tree`, `Treemap`, `Pack`, `Partition` | `d3-hierarchy` (~6 KB) |
| `layerchart/force` | `ForceSimulation` | `d3-force` (~7 KB) |
| `layerchart/graph` | `Dagre`, `Sankey`, `Chord`, `Ribbon` | `@dagrejs/dagre` (~22 KB), Sankey layout, `d3-chord` |

If you use these components, just import from the sub-path:

Expand Down
3 changes: 1 addition & 2 deletions docs/src/examples/components/Sankey/complex.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
onUpdate={(e) => {
// Calculate domain extents from Sankey data
// TODO: Update as 'nodeColorBy' changes
// @ts-expect-error
const extents = extent(e.nodes, (d) => d[config.nodeColorBy]);
// @ts-expect-error
colorScale.domain(extents);
Expand Down Expand Up @@ -93,7 +92,7 @@
<Rect
width={nodeWidth}
height={nodeHeight}
fill={colorScale(node[config.nodeColorBy])}
fill={colorScale(node[config.nodeColorBy]!)}
fillOpacity={0.5}
onpointerenter={() => {
highlightLinkIndexes = [
Expand Down
3 changes: 1 addition & 2 deletions docs/src/examples/components/Sankey/hierarchy.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
onUpdate={(e) => {
// Calculate domain extents from Sankey data
// TODO: Update as 'nodeColorBy' changes
// @ts-expect-error
const extents = extent(e.nodes, (d) => d[config.nodeColorBy]);
// @ts-expect-error
colorScale.domain(extents);
Expand Down Expand Up @@ -94,7 +93,7 @@
<Rect
width={nodeWidth}
height={nodeHeight}
fill={colorScale(node[config.nodeColorBy])}
fill={colorScale(node[config.nodeColorBy]!)}
fillOpacity={0.5}
onpointerenter={() => {
highlightLinkIndexes = [
Expand Down
2 changes: 1 addition & 1 deletion docs/src/examples/components/Sankey/node-select.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
</script>

<script lang="ts">
import type { SankeyNode } from 'd3-sankey';
import type { SankeyNode } from 'layerchart';
import { Chart, Group, Link, Rect, Layer, Text, sankeyGraphFromNode } from 'layerchart';
import { Sankey } from 'layerchart/graph';

Expand Down
5 changes: 0 additions & 5 deletions packages/layerchart/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
"@types/d3-color": "^3.1.3",
"@types/d3-contour": "^3.0.6",
"@types/d3-delaunay": "^6.0.4",
"@types/d3-dsv": "^3.0.7",
"@types/d3-force": "^3.0.10",
"@types/d3-geo": "^3.1.0",
"@types/d3-hierarchy": "^3.1.7",
Expand All @@ -47,7 +46,6 @@
"@types/d3-polygon": "^3.0.2",
"@types/d3-quadtree": "^3.0.6",
"@types/d3-random": "^3.0.3",
"@types/d3-sankey": "^0.12.5",
"@types/d3-scale": "^4.0.9",
"@types/d3-scale-chromatic": "^3.1.0",
"@types/d3-shape": "^3.1.8",
Expand Down Expand Up @@ -80,10 +78,8 @@
"d3-color": "^3.1.0",
"d3-contour": "^4.0.2",
"d3-delaunay": "^6.0.4",
"d3-dsv": "^3.0.1",
"d3-force": "^3.0.0",
"d3-geo": "^3.1.1",
"d3-geo-polygon": "^2.0.1",
"d3-geo-voronoi": "^2.1.0",
"d3-hierarchy": "^3.1.2",
"d3-interpolate": "^3.0.1",
Expand All @@ -92,7 +88,6 @@
"d3-polygon": "^3.0.1",
"d3-quadtree": "^3.0.1",
"d3-random": "^3.0.1",
"d3-sankey": "^0.12.3",
"d3-scale": "^4.0.2",
"d3-scale-chromatic": "^3.1.0",
"d3-shape": "^3.2.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ComponentProps, Snippet } from 'svelte';
import type { HTMLAttributes } from 'svelte/elements';
import type { TimeInterval } from 'd3-time';
import type { HierarchyNode } from 'd3-hierarchy';
import type { SankeyGraph } from 'd3-sankey';
import type { SankeyGraph } from '$lib/utils/graph/sankeyLayout.js';

import type { Accessor } from '$lib/utils/common.js';
import type { MotionProp } from '$lib/utils/motion.svelte.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ import {
geoRotation,
} from 'd3-geo';
// @ts-expect-error - no types available
import { geoGrayFullerRaw } from 'd3-geo-polygon';
// @ts-expect-error - no types available
import { geoDelaunay } from 'd3-geo-voronoi';
import { radiansToDegrees } from '$lib/utils/math.js';
import { sideShade } from '$lib/utils/isometric.js';
import { weightOf } from '../../Bin/Bin.shared.svelte.js';
import { geoGrayFullerRaw } from './grayFuller.js';
import type {
BinCell,
BinShape,
Expand Down
64 changes: 64 additions & 0 deletions packages/layerchart/src/lib/components/geo/GeoBin/grayFuller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Buckminster Fuller’s spherical triangle transformation procedure
*
* Based on Robert W. Gray’s formulae published in “Exact Transformation Equations
* For Fuller's World Map,” _Cartographica_, 32(3): 17-25 (1995).
*
* Implemented for D3.js by Philippe Rivière, 2018 (https://visionscarto.net/), as
* `geoGrayFullerRaw` in d3-geo-polygon.
*
* To the extent possible under law, Philippe Rivière has waived all copyright
* and related or neighboring rights to this implementation. (Public Domain.)
*/
import { geoGnomonicRaw, type GeoRawProjection } from 'd3-geo';

const epsilon = 1e-6;

// `geoGnomonicRaw` is the raw projection itself, though `@types/d3-geo` types it as a factory
const gnomonicRaw = geoGnomonicRaw as unknown as GeoRawProjection;

/** Maps one spherical icosahedron face onto a flat triangle with equal areas */
export function geoGrayFullerRaw(): GeoRawProjection {
const SQRT_3 = Math.sqrt(3);

// Gray’s constants
const Z = Math.sqrt(5 + 2 * Math.sqrt(5)) / Math.sqrt(15);
const el = Math.sqrt(8) / Math.sqrt(5 + Math.sqrt(5));
const dve = Math.sqrt(3 + Math.sqrt(5)) / Math.sqrt(5 + Math.sqrt(5));

const grayFuller: GeoRawProjection = (lambda, phi) => {
const cosPhi = Math.cos(phi);
const s = Z / (cosPhi * Math.cos(lambda));
const x = cosPhi * Math.sin(lambda) * s;
const y = Math.sin(phi) * s;
const a1p = Math.atan2((2 * y) / SQRT_3 + el / 3 - el / 2, dve);
const a2p = Math.atan2(x - y / SQRT_3 + el / 3 - el / 2, dve);
const a3p = Math.atan2(el / 3 - x - y / SQRT_3 - el / 2, dve);

return [SQRT_3 * (a2p - a3p), 2 * a1p - a2p - a3p];
};

// Inverse approximation
grayFuller.invert = (x, y) => {
// A point outside the triangle returns something meaningless, but far enough away
if (x * x + y * y > 5) return [0, 3];

const R = 2.9309936378128416;
const p = gnomonicRaw.invert!(x / R, y / R);

let j = 0;
let dx: number;
let dy: number;
do {
const f = grayFuller(p[0], p[1]);
dx = x - f[0];
dy = y - f[1];
p[0] += 0.2 * dx;
p[1] += 0.2 * dy;
} while (j++ < 30 && Math.abs(dx) + Math.abs(dy) > epsilon);

return p;
};

return grayFuller;
}
48 changes: 23 additions & 25 deletions packages/layerchart/src/lib/components/graph/Sankey.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script lang="ts" module>
import type { Snippet } from 'svelte';
import type { SankeyGraph, SankeyLink, SankeyNode } from '$lib/utils/graph/sankeyLayout.js';

export type NodeExtraProperties = Record<string, any>;

Expand All @@ -17,9 +18,11 @@
*/
nodeId?: (d: any) => any;
/**
* @see https://github.com/d3/d3-sankey#alignments
* Which column each node goes in: `left` by depth from the sources, `right` by height from the
* sinks, `center` next to the nodes it links to, and `justify` like `left` but with sinks in the
* last column
*
* @default sankeyJustify
* @default 'justify'
*/
nodeAlign?:
| ((node: SankeyNode<any, any>, n: number) => number)
Expand Down Expand Up @@ -69,32 +72,29 @@
[
{
nodes: SankeyNode<NodeExtraProperties, any>[];
links: SankeyNode<NodeExtraProperties, any>[];
links: SankeyLink<NodeExtraProperties, any>[];
},
]
>;
};
</script>

<script lang="ts">
// https://github.com/d3/d3-sankey
import {
sankey as d3Sankey,
sankeyLayout,
sankeyLeft,
sankeyCenter,
sankeyRight,
sankeyJustify,
type SankeyNode,
type SankeyLink,
type SankeyGraph,
} from 'd3-sankey';
type SankeyLayoutOptions,
} from '$lib/utils/graph/sankeyLayout.js';

import { getChartContext } from '$lib/contexts/chart.js';

let {
nodes: nodesProp = (d: any) => d.nodes,
nodeId = (d: any) => d.index,
nodeAlign = sankeyJustify,
nodeAlign = 'justify',
nodeWidth = 4,
nodePadding = 10,
nodeSort,
Expand All @@ -107,12 +107,13 @@
const ctx = getChartContext();

const sankeyData = $derived.by(() => {
return (
d3Sankey()
.size([ctx.width, ctx.height])
.nodes(nodesProp)
.nodeId(nodeId)
.nodeAlign(
const data = structuredClone(ctx.data);
return sankeyLayout(
{ nodes: nodesProp(data), links: linksProp(data) },
{
size: [ctx.width, ctx.height],
nodeId,
nodeAlign:
nodeAlign === 'left'
? sankeyLeft
: nodeAlign === 'center'
Expand All @@ -121,15 +122,12 @@
? sankeyRight
: nodeAlign === 'justify'
? sankeyJustify
: nodeAlign
)
.nodeWidth(nodeWidth)
.nodePadding(nodePadding)
// @ts-expect-error
.nodeSort(nodeSort)
.links(linksProp)
// @ts-expect-error
.linkSort(linkSort)(structuredClone(ctx.data))
: nodeAlign,
nodeWidth,
nodePadding,
nodeSort: nodeSort as SankeyLayoutOptions['nodeSort'],
linkSort: linkSort as SankeyLayoutOptions['linkSort'],
}
);
});

Expand Down
32 changes: 32 additions & 0 deletions packages/layerchart/src/lib/utils/graph/sankey.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest';
import { sankeyGraphFromCsv } from './sankey.js';

describe('sankeyGraphFromCsv', () => {
it('parses source,target,value rows into links and distinct nodes', () => {
const graph = sankeyGraphFromCsv('A,B,5\nA,C,3\nB,C,2');
expect(graph.links).toEqual([
{ source: 'A', target: 'B', value: 5 },
{ source: 'A', target: 'C', value: 3 },
{ source: 'B', target: 'C', value: 2 },
]);
expect(graph.nodes).toEqual([{ name: 'A' }, { name: 'B' }, { name: 'C' }]);
});

it('defaults a missing or non-numeric value to 1', () => {
const graph = sankeyGraphFromCsv('A,B\nA,C,\nB,C,abc');
expect(graph.links.map((l) => l.value)).toEqual([1, 1, 1]);
});

it('skips blank lines and rows without a source or target', () => {
const graph = sankeyGraphFromCsv('\nA,B,1\n\nA\n,B,2\nB,C,3\n');
expect(graph.links).toEqual([
{ source: 'A', target: 'B', value: 1 },
{ source: 'B', target: 'C', value: 3 },
]);
});

it('handles CRLF and CR line endings', () => {
expect(sankeyGraphFromCsv('A,B,1\r\nB,C,2').links).toHaveLength(2);
expect(sankeyGraphFromCsv('A,B,1\rB,C,2').links).toHaveLength(2);
});
});
27 changes: 15 additions & 12 deletions packages/layerchart/src/lib/utils/graph/sankey.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
import { csvParseRows } from 'd3-dsv';
import type {
SankeyExtraProperties,
SankeyGraph,
SankeyLink,
SankeyNode,
SankeyNodeMinimal,
} from 'd3-sankey';
} from './sankeyLayout.js';
import type { hierarchy as d3Hierarchy } from 'd3-hierarchy';

export type { SankeyGraph, SankeyLink, SankeyNode } from './sankeyLayout.js';

/**
* Convert CSV rows in format: 'source,target,value' to SankeyGraph
* Convert CSV rows in format: 'source,target,value' to SankeyGraph.
*
* Rows missing a source or target are skipped, and a missing or non-numeric value defaults to `1`.
* Splits on newlines and commas only (no quoted fields). Parse other formats yourself and pass
* the links to `sankeyNodesFromLinks()`.
*/
export function sankeyGraphFromCsv(csv: string): SankeyGraph<any, any> {
const links = csvParseRows(csv, (row) => {
const [source, target, rawValue] = row;
if (!source || !target) return null;
const links: Array<{ source: string; target: string; value: number }> = [];

for (const line of csv.split(/\r\n|\r|\n/)) {
const [source, target, rawValue] = line.split(',');
if (!source || !target) continue;
const num = rawValue ? +rawValue : NaN;
return {
source,
target,
value: isNaN(num) ? 1 : num,
};
});
links.push({ source, target, value: isNaN(num) ? 1 : num });
}

return { nodes: sankeyNodesFromLinks(links), links };
}
Expand Down
Loading
Loading