@dxos/react-ui-plot 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +2 -2
  3. package/dist/lib/index.mjs +223 -0
  4. package/dist/lib/index.mjs.map +1 -0
  5. package/dist/px-icons/anthropic.svg +12 -0
  6. package/dist/px-icons/bar-high.svg +21 -0
  7. package/dist/px-icons/bar-low.svg +18 -0
  8. package/dist/px-icons/bar-medium.svg +20 -0
  9. package/dist/px-icons/circle.svg +5 -0
  10. package/dist/px-icons/deepseek.svg +10 -0
  11. package/dist/types/src/components/Plot/Plot.d.ts +12 -0
  12. package/dist/types/src/components/Plot/Plot.d.ts.map +1 -0
  13. package/dist/types/src/components/Plot/Plot.stories.d.ts +29 -0
  14. package/dist/types/src/components/Plot/Plot.stories.d.ts.map +1 -0
  15. package/dist/types/src/components/Plot/index.d.ts +2 -0
  16. package/dist/types/src/components/Plot/index.d.ts.map +1 -0
  17. package/dist/types/src/components/index.d.ts +2 -0
  18. package/dist/types/src/components/index.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +4 -0
  20. package/dist/types/src/index.d.ts.map +1 -0
  21. package/dist/types/src/types.d.ts +29 -0
  22. package/dist/types/src/types.d.ts.map +1 -0
  23. package/dist/types/src/util/data.d.ts +13 -0
  24. package/dist/types/src/util/data.d.ts.map +1 -0
  25. package/dist/types/src/util/data.test.d.ts +2 -0
  26. package/dist/types/src/util/data.test.d.ts.map +1 -0
  27. package/dist/types/src/util/index.d.ts +2 -0
  28. package/dist/types/src/util/index.d.ts.map +1 -0
  29. package/dist/types/tsconfig.tsbuildinfo +1 -0
  30. package/package.json +50 -3
  31. package/src/components/Plot/Plot.stories.tsx +46 -0
  32. package/src/components/Plot/Plot.tsx +158 -0
  33. package/src/components/Plot/index.ts +5 -0
  34. package/src/components/index.ts +5 -0
  35. package/src/index.ts +7 -0
  36. package/src/types.ts +39 -0
  37. package/src/util/data.test.ts +53 -0
  38. package/src/util/data.ts +63 -0
  39. package/src/util/index.ts +5 -0
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@dxos/react-ui-plot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Chart and plot components.",
5
+ "homepage": "https://github.com/dxos",
6
+ "bugs": "https://github.com/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
11
+ "license": "FSL-1.1-Apache-2.0",
12
+ "author": "DXOS.org",
13
+ "sideEffects": false,
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "source": "./src/index.ts",
18
+ "types": "./dist/types/src/index.d.ts",
19
+ "import": "./dist/lib/index.mjs"
20
+ }
21
+ },
22
+ "types": "dist/types/src/index.d.ts",
23
+ "files": [
24
+ "dist",
25
+ "src"
26
+ ],
27
+ "dependencies": {
28
+ "@observablehq/plot": "^0.6.11",
29
+ "d3": "^7.9.0",
30
+ "effect": "4.0.4",
31
+ "react-resize-detector": "^11.0.1",
32
+ "@dxos/ui-types": "0.14.0"
33
+ },
34
+ "devDependencies": {
35
+ "@storybook/react-vite": "^10.6.0",
36
+ "@types/d3": "^7.4.3",
37
+ "@types/react": "~19.2.17",
38
+ "@types/react-dom": "~19.2.3",
39
+ "react": "~19.2.7",
40
+ "react-dom": "~19.2.7",
41
+ "@dxos/react-ui": "0.14.0",
42
+ "@dxos/ui-theme": "0.14.0"
43
+ },
44
+ "peerDependencies": {
45
+ "react": "~19.2.7",
46
+ "react-dom": "~19.2.7",
47
+ "@dxos/react-ui": "^0.14.0",
48
+ "@dxos/ui-theme": "^0.14.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
6
53
  }
@@ -0,0 +1,46 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { type Meta, type StoryObj } from '@storybook/react-vite';
6
+ import React from 'react';
7
+
8
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
9
+
10
+ import { PLOT_TYPES, type PlotOptions } from '../../types.ts';
11
+ import { toPlotData } from '../../util/index.ts';
12
+ import { Plot } from './Plot.tsx';
13
+
14
+ const data = toPlotData(
15
+ [
16
+ ['Month', 'North', 'South'],
17
+ ['Jan', 12, 8],
18
+ ['Feb', 18, 11],
19
+ ['Mar', 15, 16],
20
+ ['Apr', 22, 14],
21
+ ],
22
+ { header: true },
23
+ );
24
+
25
+ type StoryArgs = Pick<PlotOptions, 'type' | 'grid'>;
26
+
27
+ const DefaultStory = (options: StoryArgs) => <Plot classNames='h-[24rem]' data={data} options={options} />;
28
+
29
+ const meta = {
30
+ title: 'ui/react-ui-plot/Plot',
31
+ render: DefaultStory,
32
+ decorators: [withTheme(), withLayout({ classNames: 'w-[40rem]' })],
33
+ args: { type: 'bar', grid: true },
34
+ argTypes: { type: { control: 'inline-radio', options: PLOT_TYPES } },
35
+ parameters: { layout: 'centered' },
36
+ } satisfies Meta<StoryArgs>;
37
+
38
+ export default meta;
39
+
40
+ type Story = StoryObj<typeof meta>;
41
+
42
+ export const Default: Story = {};
43
+
44
+ export const Pie: Story = { args: { type: 'pie' } };
45
+
46
+ export const XY: Story = { args: { type: 'xy' } };
@@ -0,0 +1,158 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as ObservablePlot from '@observablehq/plot';
6
+ import * as d3 from 'd3';
7
+ import React, { useEffect, useMemo } from 'react';
8
+ import { useResizeDetector } from 'react-resize-detector';
9
+
10
+ import { mx } from '@dxos/ui-theme';
11
+ import { type ThemedClassName } from '@dxos/ui-types';
12
+
13
+ import { type PlotData, type PlotDatum, type PlotOptions } from '../../types.ts';
14
+ import { toPlotDatums } from '../../util/index.ts';
15
+
16
+ const MARGIN = 40;
17
+ const MIN_SIZE = MARGIN * 2;
18
+
19
+ // Plot's tip box defaults to a white fill, while its text follows the theme's currentColor.
20
+ const TIP = { fill: 'var(--color-modal-surface)', stroke: 'var(--color-separator)' };
21
+
22
+ export type PlotProps = ThemedClassName<{
23
+ data: PlotData;
24
+ options: PlotOptions;
25
+ }>;
26
+
27
+ /** Renders tabular data as a bar, pie, or xy chart sized to its container. */
28
+ export const Plot = ({ classNames, data, options }: PlotProps) => {
29
+ const { ref: containerRef, width = 0, height = 0 } = useResizeDetector<HTMLDivElement>({ refreshRate: 100 });
30
+ const datums = useMemo(() => toPlotDatums(data), [data]);
31
+
32
+ useEffect(() => {
33
+ const container = containerRef.current;
34
+ // Below twice the margin the plot frame has a negative extent.
35
+ if (!container || width < MIN_SIZE || height < MIN_SIZE || options.type === 'pie') {
36
+ return;
37
+ }
38
+
39
+ const label = data.columns[0];
40
+ let plot = createPlot(datums, options, { width, height, label });
41
+ container.append(plot);
42
+
43
+ // A legend is laid out above an SVG of the full height, pushing the x axis out of view; redraw shorter.
44
+ const overflow = plot.getBoundingClientRect().height - height;
45
+ if (overflow > 0) {
46
+ plot.remove();
47
+ plot = createPlot(datums, options, { width, height: height - overflow, label });
48
+ container.append(plot);
49
+ }
50
+
51
+ return () => plot.remove();
52
+ }, [data, datums, options, width, height]);
53
+
54
+ return (
55
+ <div ref={containerRef} role='img' className={mx('relative dx-fill overflow-hidden', classNames)}>
56
+ {options.type === 'pie' && width >= MIN_SIZE && height >= MIN_SIZE && (
57
+ <Pie datums={datums} width={width} height={height} />
58
+ )}
59
+ </div>
60
+ );
61
+ };
62
+
63
+ Plot.displayName = 'Plot';
64
+
65
+ const createPlot = (
66
+ datums: PlotDatum[],
67
+ { type, grid = true }: PlotOptions,
68
+ { label, ...size }: { width: number; height: number; label?: string },
69
+ ): SVGSVGElement | HTMLElement => {
70
+ const series = new Set(datums.map((datum) => datum.series));
71
+ // Ordinal scales sort by default; keep the sheet's row and column order.
72
+ const keys = [...new Set(datums.map((datum) => datum.key))];
73
+ const seriesOrder = [...series];
74
+ const options = {
75
+ ...size,
76
+ grid,
77
+ marginLeft: MARGIN,
78
+ marginBottom: MARGIN,
79
+ style: { background: 'transparent', color: 'currentColor' },
80
+ color: { legend: series.size > 1, domain: seriesOrder },
81
+ y: { label: null },
82
+ };
83
+
84
+ switch (type) {
85
+ case 'xy':
86
+ return ObservablePlot.plot({
87
+ ...options,
88
+ x: { label },
89
+ marks: [
90
+ ObservablePlot.ruleY([0]),
91
+ ObservablePlot.line(datums, { x: 'key', y: 'value', stroke: 'series' }),
92
+ ObservablePlot.dot(datums, { x: 'key', y: 'value', fill: 'series', r: 3 }),
93
+ ],
94
+ });
95
+
96
+ case 'bar':
97
+ default:
98
+ return ObservablePlot.plot({
99
+ ...options,
100
+ ...(series.size > 1
101
+ ? { fx: { label: null, domain: keys, axis: 'bottom' }, x: { axis: null, domain: seriesOrder } }
102
+ : { x: { label: null, domain: keys } }),
103
+ marks: [
104
+ ObservablePlot.ruleY([0]),
105
+ series.size > 1
106
+ ? ObservablePlot.barY(datums, { fx: 'key', x: 'series', y: 'value', fill: 'series', tip: TIP })
107
+ : ObservablePlot.barY(datums, { x: 'key', y: 'value', fill: 'series', tip: TIP }),
108
+ ],
109
+ });
110
+ }
111
+ };
112
+
113
+ type PieProps = {
114
+ datums: PlotDatum[];
115
+ width: number;
116
+ height: number;
117
+ };
118
+
119
+ /** Observable Plot has no polar marks, so the pie is drawn directly with d3-shape; the first series is used. */
120
+ const Pie = ({ datums, width, height }: PieProps) => {
121
+ const radius = Math.max(0, Math.min(width, height) / 2 - MARGIN / 2);
122
+ const slices = useMemo(() => {
123
+ const first = datums[0]?.series;
124
+ const values = datums.filter((datum) => datum.series === first && datum.value > 0);
125
+ return d3
126
+ .pie<PlotDatum>()
127
+ .sort(null)
128
+ .value((datum) => datum.value)(values);
129
+ }, [datums]);
130
+
131
+ const arc = d3.arc<d3.PieArcDatum<PlotDatum>>().innerRadius(0).outerRadius(radius);
132
+ const label = d3
133
+ .arc<d3.PieArcDatum<PlotDatum>>()
134
+ .innerRadius(radius * 0.65)
135
+ .outerRadius(radius * 0.65);
136
+ const color = d3.scaleOrdinal<string, string>(d3.schemeTableau10);
137
+
138
+ return (
139
+ <svg width={width} height={height} viewBox={`${-width / 2} ${-height / 2} ${width} ${height}`}>
140
+ {slices.map((slice, index) => (
141
+ <g key={index}>
142
+ <path d={arc(slice) ?? undefined} fill={color(String(slice.data.key))} stroke='var(--color-base-surface)'>
143
+ <title>{`${slice.data.key}: ${slice.data.value}`}</title>
144
+ </path>
145
+ <text
146
+ transform={`translate(${label.centroid(slice)})`}
147
+ textAnchor='middle'
148
+ dominantBaseline='middle'
149
+ fontSize={11}
150
+ fill='white'
151
+ >
152
+ {String(slice.data.key)}
153
+ </text>
154
+ </g>
155
+ ))}
156
+ </svg>
157
+ );
158
+ };
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ export * from './Plot.tsx';
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ export * from './Plot/index.ts';
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ export * from './components/index.ts';
6
+ export * from './types.ts';
7
+ export * from './util/index.ts';
package/src/types.ts ADDED
@@ -0,0 +1,39 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+
7
+ export const PlotType = Schema.Literals(['bar', 'pie', 'xy']);
8
+ export type PlotType = Schema.Schema.Type<typeof PlotType>;
9
+
10
+ export const PLOT_TYPES: readonly PlotType[] = PlotType.literals;
11
+
12
+ /** Presentation options; persisted alongside the data source by the host. */
13
+ export const PlotOptions = Schema.Struct({
14
+ type: PlotType.annotate({ title: 'Chart type' }),
15
+ /** The first row holds the series names. */
16
+ header: Schema.optional(Schema.Boolean.annotate({ title: 'Header row' })),
17
+ /** Draw grid lines (bar and xy). */
18
+ grid: Schema.optional(Schema.Boolean.annotate({ title: 'Grid lines' })),
19
+ });
20
+
21
+ export type PlotOptions = Schema.Schema.Type<typeof PlotOptions>;
22
+
23
+ export type PlotValue = string | number | boolean | null;
24
+
25
+ /**
26
+ * Column-oriented table: the first column is the category (bar, pie) or the x axis (xy);
27
+ * each remaining column is a series.
28
+ */
29
+ export type PlotData = {
30
+ columns: string[];
31
+ rows: PlotValue[][];
32
+ };
33
+
34
+ /** One series value in long form, the shape Observable Plot marks consume. */
35
+ export type PlotDatum = {
36
+ key: PlotValue;
37
+ series: string;
38
+ value: number;
39
+ };
@@ -0,0 +1,53 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, expect, test } from 'vitest';
6
+
7
+ import { toPlotData, toPlotDatums } from './data.ts';
8
+
9
+ describe('toPlotData', () => {
10
+ test('header row names the columns', ({ expect }) => {
11
+ const data = toPlotData(
12
+ [
13
+ ['Month', 'Sales'],
14
+ ['Jan', 10],
15
+ ],
16
+ { header: true },
17
+ );
18
+ expect(data).to.deep.eq({ columns: ['Month', 'Sales'], rows: [['Jan', 10]] });
19
+ });
20
+
21
+ test('without a header the columns are lettered', ({ expect }) => {
22
+ expect(toPlotData([[1, 2]]).columns).to.deep.eq(['A', 'B']);
23
+ });
24
+
25
+ test('columns past Z continue as AA, AB', ({ expect }) => {
26
+ const columns = toPlotData([Array.from({ length: 28 }, () => 0)]).columns;
27
+ expect(columns.slice(24)).to.deep.eq(['Y', 'Z', 'AA', 'AB']);
28
+ });
29
+ });
30
+
31
+ describe('toPlotDatums', () => {
32
+ test('first column is the key, remaining columns are series', () => {
33
+ const datums = toPlotDatums({
34
+ columns: ['Month', 'A', 'B'],
35
+ rows: [
36
+ ['Jan', 1, '2'],
37
+ ['Feb', 3, 'n/a'],
38
+ ],
39
+ });
40
+ expect(datums).to.deep.eq([
41
+ { key: 'Jan', series: 'A', value: 1 },
42
+ { key: 'Jan', series: 'B', value: 2 },
43
+ { key: 'Feb', series: 'A', value: 3 },
44
+ ]);
45
+ });
46
+
47
+ test('a single column is keyed by row number', () => {
48
+ expect(toPlotDatums({ columns: ['A'], rows: [[5], ['$1,000']] })).to.deep.eq([
49
+ { key: 1, series: 'A', value: 5 },
50
+ { key: 2, series: 'A', value: 1000 },
51
+ ]);
52
+ });
53
+ });
@@ -0,0 +1,63 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { type PlotData, type PlotDatum, type PlotValue } from '../types.ts';
6
+
7
+ /** Spreadsheet column letters for a zero-based index: A–Z, then AA, AB, … (bijective base 26). */
8
+ const columnName = (index: number): string => {
9
+ let name = '';
10
+ for (let remaining = index + 1; remaining > 0; remaining = Math.floor((remaining - 1) / 26)) {
11
+ name = String.fromCharCode('A'.charCodeAt(0) + ((remaining - 1) % 26)) + name;
12
+ }
13
+ return name;
14
+ };
15
+
16
+ const toNumber = (value: PlotValue): number | undefined => {
17
+ if (typeof value === 'number') {
18
+ return Number.isFinite(value) ? value : undefined;
19
+ }
20
+
21
+ if (typeof value === 'string' && value.trim() !== '') {
22
+ const number = Number(value.replace(/[$,%]/g, ''));
23
+ return Number.isFinite(number) ? number : undefined;
24
+ }
25
+
26
+ return undefined;
27
+ };
28
+
29
+ export type ToPlotDataOptions = {
30
+ /** The first row holds the series names. */
31
+ header?: boolean;
32
+ };
33
+
34
+ /** Converts a 2D block of cell values (rows of columns) into `PlotData`. */
35
+ export const toPlotData = (values: PlotValue[][], { header = false }: ToPlotDataOptions = {}): PlotData => {
36
+ const width = values.reduce((max, row) => Math.max(max, row.length), 0);
37
+ const [first, ...rest] = values;
38
+ const columns = Array.from({ length: width }, (_, index) =>
39
+ header && first?.[index] != null ? String(first[index]) : columnName(index),
40
+ );
41
+
42
+ return { columns, rows: header ? rest : values };
43
+ };
44
+
45
+ /**
46
+ * Flattens `PlotData` into long form. With a single column the row index is the key;
47
+ * otherwise the first column is the key and each remaining column a series. Non-numeric values are dropped.
48
+ */
49
+ export const toPlotDatums = ({ columns, rows }: PlotData): PlotDatum[] => {
50
+ if (columns.length === 1) {
51
+ return rows.flatMap((row, index) => {
52
+ const value = toNumber(row[0]);
53
+ return value === undefined ? [] : [{ key: index + 1, series: columns[0], value }];
54
+ });
55
+ }
56
+
57
+ return rows.flatMap((row) =>
58
+ columns.slice(1).flatMap((series, index) => {
59
+ const value = toNumber(row[index + 1]);
60
+ return value === undefined ? [] : [{ key: row[0], series, value }];
61
+ }),
62
+ );
63
+ };
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ export * from './data.ts';