@object-ui/plugin-charts 0.3.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.
@@ -0,0 +1,345 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { ResponsiveContainer, Tooltip, Legend } from "recharts"
5
+
6
+ // Utility function to merge class names (inline to avoid external dependency)
7
+ const cn = (...classes: (string | undefined)[]) => classes.filter(Boolean).join(' ')
8
+
9
+ // Format: { THEME_NAME: CSS_SELECTOR }
10
+ const THEMES = { light: "", dark: ".dark" } as const
11
+
12
+ export type ChartConfig = {
13
+ [k in string]: {
14
+ label?: React.ReactNode
15
+ icon?: React.ComponentType
16
+ } & (
17
+ | { color?: string; theme?: never }
18
+ | { color?: never; theme: Record<keyof typeof THEMES, string> }
19
+ )
20
+ }
21
+
22
+ type ChartContextProps = {
23
+ config: ChartConfig
24
+ }
25
+
26
+ const ChartContext = React.createContext<ChartContextProps | null>(null)
27
+
28
+ function useChart() {
29
+ const context = React.useContext(ChartContext)
30
+
31
+ if (!context) {
32
+ throw new Error("useChart must be used within a <ChartContainer />")
33
+ }
34
+
35
+ return context
36
+ }
37
+
38
+ function ChartContainer({
39
+ id,
40
+ className,
41
+ children,
42
+ config,
43
+ ...props
44
+ }: React.ComponentProps<"div"> & {
45
+ config: ChartConfig
46
+ children: React.ComponentProps<
47
+ typeof ResponsiveContainer
48
+ >["children"]
49
+ }) {
50
+ const uniqueId = React.useId()
51
+ const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
52
+
53
+ return (
54
+ <ChartContext.Provider value={{ config }}>
55
+ <div
56
+ data-slot="chart"
57
+ data-chart={chartId}
58
+ className={cn(
59
+ "flex w-full h-[350px] justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground",
60
+ className
61
+ )}
62
+ {...props}
63
+ >
64
+ <ChartStyle id={chartId} config={config} />
65
+ <ResponsiveContainer width="100%" height="100%">
66
+ {children}
67
+ </ResponsiveContainer>
68
+ </div>
69
+ </ChartContext.Provider>
70
+ )
71
+ }
72
+
73
+ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
74
+ const colorConfig = Object.entries(config).filter(
75
+ ([, config]) => config.theme || config.color
76
+ )
77
+
78
+ if (!colorConfig.length) {
79
+ return null
80
+ }
81
+
82
+ return (
83
+ <style
84
+ dangerouslySetInnerHTML={{
85
+ __html: Object.entries(THEMES)
86
+ .map(
87
+ ([theme, prefix]) => `
88
+ ${prefix} [data-chart=${id}] {
89
+ ${colorConfig
90
+ .map(([key, itemConfig]) => {
91
+ const color =
92
+ itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
93
+ itemConfig.color
94
+ return color ? ` --color-${key}: ${color};` : null
95
+ })
96
+ .join("\n")}
97
+ }
98
+ `
99
+ )
100
+ .join("\n"),
101
+ }}
102
+ />
103
+ )
104
+ }
105
+
106
+ const ChartTooltip = Tooltip
107
+
108
+ function ChartTooltipContent({
109
+ active,
110
+ payload,
111
+ className,
112
+ indicator = "dot",
113
+ hideLabel = false,
114
+ hideIndicator = false,
115
+ label,
116
+ labelFormatter,
117
+ labelClassName,
118
+ formatter,
119
+ color,
120
+ nameKey,
121
+ labelKey,
122
+ }: any) {
123
+ const { config } = useChart()
124
+
125
+ const tooltipLabel = React.useMemo(() => {
126
+ if (hideLabel || !payload?.length) {
127
+ return null
128
+ }
129
+
130
+ const [item] = payload
131
+ const key = `${labelKey || item?.dataKey || item?.name || "value"}`
132
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
133
+ const value =
134
+ !labelKey && typeof label === "string"
135
+ ? config[label as keyof typeof config]?.label || label
136
+ : itemConfig?.label
137
+
138
+ if (labelFormatter) {
139
+ return (
140
+ <div className={cn("font-medium", labelClassName)}>
141
+ {labelFormatter(value, payload)}
142
+ </div>
143
+ )
144
+ }
145
+
146
+ if (!value) {
147
+ return null
148
+ }
149
+
150
+ return <div className={cn("font-medium", labelClassName)}>{value}</div>
151
+ }, [
152
+ label,
153
+ labelFormatter,
154
+ payload,
155
+ hideLabel,
156
+ labelClassName,
157
+ config,
158
+ labelKey,
159
+ ])
160
+
161
+ if (!active || !payload?.length) {
162
+ return null
163
+ }
164
+
165
+ const nestLabel = payload.length === 1 && indicator !== "dot"
166
+
167
+ return (
168
+ <div
169
+ className={cn(
170
+ "border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
171
+ className
172
+ )}
173
+ >
174
+ {!nestLabel ? tooltipLabel : null}
175
+ <div className="grid gap-1.5">
176
+ {payload
177
+ .filter((item: any) => item.type !== "none")
178
+ .map((item: any, index: number) => {
179
+ const key = `${nameKey || item.name || item.dataKey || "value"}`
180
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
181
+ const indicatorColor = color || item.payload.fill || item.color
182
+
183
+ return (
184
+ <div
185
+ key={item.dataKey}
186
+ className={cn(
187
+ "[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
188
+ indicator === "dot" ? "items-center" : ""
189
+ )}
190
+ >
191
+ {formatter && item?.value !== undefined && item.name ? (
192
+ formatter(item.value, item.name, item, index, item.payload)
193
+ ) : (
194
+ <>
195
+ {itemConfig?.icon ? (
196
+ <itemConfig.icon />
197
+ ) : (
198
+ !hideIndicator && (
199
+ <div
200
+ className={cn(
201
+ "shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
202
+ indicator === "dot" ? "h-2.5 w-2.5" : "",
203
+ indicator === "line" ? "w-1" : "",
204
+ indicator === "dashed" ? "w-0 border-[1.5px] border-dashed bg-transparent" : "",
205
+ (nestLabel && indicator === "dashed") ? "my-0.5" : "",
206
+ )}
207
+ style={
208
+
209
+ {
210
+ "--color-bg": indicatorColor,
211
+ "--color-border": indicatorColor,
212
+ } as React.CSSProperties
213
+ }
214
+ />
215
+ )
216
+ )}
217
+ <div
218
+ className={cn(
219
+ "flex flex-1 justify-between leading-none",
220
+ nestLabel ? "items-end" : "items-center"
221
+ )}
222
+ >
223
+ <div className="grid gap-1.5">
224
+ {nestLabel ? tooltipLabel : null}
225
+ <span className="text-muted-foreground">
226
+ {itemConfig?.label || item.name}
227
+ </span>
228
+ </div>
229
+ {item.value && (
230
+ <span className="text-foreground font-mono font-medium tabular-nums">
231
+ {item.value.toLocaleString()}
232
+ </span>
233
+ )}
234
+ </div>
235
+ </>
236
+ )}
237
+ </div>
238
+ )
239
+ })}
240
+ </div>
241
+ </div>
242
+ )
243
+ }
244
+
245
+ const ChartLegend = Legend
246
+
247
+ function ChartLegendContent({
248
+ className,
249
+ hideIcon = false,
250
+ payload,
251
+ verticalAlign = "bottom",
252
+ nameKey,
253
+ }: any) {
254
+ const { config } = useChart()
255
+
256
+ if (!payload?.length) {
257
+ return null
258
+ }
259
+
260
+ return (
261
+ <div
262
+ className={cn(
263
+ "flex items-center justify-center gap-4",
264
+ verticalAlign === "top" ? "pb-3" : "pt-3",
265
+ className
266
+ )}
267
+ >
268
+ {payload
269
+ .filter((item: any) => item.type !== "none")
270
+ .map((item: any) => {
271
+ const key = `${nameKey || item.dataKey || "value"}`
272
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
273
+
274
+ return (
275
+ <div
276
+ key={item.value}
277
+ className={cn(
278
+ "[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
279
+ )}
280
+ >
281
+ {itemConfig?.icon && !hideIcon ? (
282
+ <itemConfig.icon />
283
+ ) : (
284
+ <div
285
+ className="h-2 w-2 shrink-0 rounded-[2px]"
286
+ style={{
287
+ backgroundColor: item.color,
288
+ }}
289
+ />
290
+ )}
291
+ {itemConfig?.label}
292
+ </div>
293
+ )
294
+ })}
295
+ </div>
296
+ )
297
+ }
298
+
299
+ // Helper to extract item config from a payload.
300
+ function getPayloadConfigFromPayload(
301
+ config: ChartConfig,
302
+ payload: unknown,
303
+ key: string
304
+ ) {
305
+ if (typeof payload !== "object" || payload === null) {
306
+ return undefined
307
+ }
308
+
309
+ const payloadPayload =
310
+ "payload" in payload &&
311
+ typeof payload.payload === "object" &&
312
+ payload.payload !== null
313
+ ? payload.payload
314
+ : undefined
315
+
316
+ let configLabelKey: string = key
317
+
318
+ if (
319
+ key in payload &&
320
+ typeof payload[key as keyof typeof payload] === "string"
321
+ ) {
322
+ configLabelKey = payload[key as keyof typeof payload] as string
323
+ } else if (
324
+ payloadPayload &&
325
+ key in payloadPayload &&
326
+ typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
327
+ ) {
328
+ configLabelKey = payloadPayload[
329
+ key as keyof typeof payloadPayload
330
+ ] as string
331
+ }
332
+
333
+ return configLabelKey in config
334
+ ? config[configLabelKey]
335
+ : config[key as keyof typeof config]
336
+ }
337
+
338
+ export {
339
+ ChartContainer,
340
+ ChartTooltip,
341
+ ChartTooltipContent,
342
+ ChartLegend,
343
+ ChartLegendContent,
344
+ ChartStyle,
345
+ }
@@ -0,0 +1,83 @@
1
+ import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
2
+
3
+ export interface ChartImplProps {
4
+ data?: Array<Record<string, any>>;
5
+ dataKey?: string;
6
+ xAxisKey?: string;
7
+ height?: number;
8
+ className?: string;
9
+ color?: string;
10
+ }
11
+
12
+ /**
13
+ * ChartImpl - The heavy implementation that imports Recharts
14
+ * This component is lazy-loaded to avoid including Recharts in the initial bundle
15
+ */
16
+ export default function ChartImpl({
17
+ data = [],
18
+ dataKey = 'value',
19
+ xAxisKey = 'name',
20
+ height = 400,
21
+ className = '',
22
+ // Default to standard primary color
23
+ color = 'hsl(var(--primary))',
24
+ }: ChartImplProps) {
25
+ return (
26
+ <div className={`p-4 rounded-xl border border-border bg-card/40 backdrop-blur-sm shadow-lg shadow-background/5 ${className}`}>
27
+ <ResponsiveContainer width="100%" height={height}>
28
+ <BarChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
29
+ <defs>
30
+ <linearGradient id="barGradient" x1="0" y1="0" x2="0" y2="1">
31
+ <stop offset="0%" stopColor={color} stopOpacity={1} />
32
+ <stop offset="90%" stopColor={color} stopOpacity={0.6} />
33
+ <stop offset="100%" stopColor={color} stopOpacity={0.3} />
34
+ </linearGradient>
35
+ <filter id="glow" height="130%">
36
+ <feGaussianBlur in="SourceAlpha" stdDeviation="3" result="blur" />
37
+ <feOffset in="blur" dx="0" dy="0" result="offsetBlur" />
38
+ <feFlood floodColor={color} floodOpacity="0.5" result="offsetColor" />
39
+ <feComposite in="offsetColor" in2="offsetBlur" operator="in" result="offsetBlur" />
40
+ <feMerge>
41
+ <feMergeNode in="offsetBlur" />
42
+ <feMergeNode in="SourceGraphic" />
43
+ </feMerge>
44
+ </filter>
45
+ </defs>
46
+ <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
47
+ <XAxis
48
+ dataKey={xAxisKey}
49
+ tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12, fontFamily: 'monospace' }}
50
+ tickLine={false}
51
+ axisLine={{ stroke: 'hsl(var(--border))' }}
52
+ dy={10}
53
+ />
54
+ <YAxis
55
+ tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12, fontFamily: 'monospace' }}
56
+ tickLine={false}
57
+ axisLine={false}
58
+ />
59
+ <Tooltip
60
+ cursor={{ fill: 'hsl(var(--muted))', opacity: 0.2 }}
61
+ contentStyle={{
62
+ backgroundColor: 'hsl(var(--popover))',
63
+ borderColor: 'hsl(var(--border))',
64
+ color: 'hsl(var(--popover-foreground))',
65
+ borderRadius: '8px',
66
+ fontFamily: 'monospace',
67
+ boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'
68
+ }}
69
+ itemStyle={{ color: 'hsl(var(--primary))' }}
70
+ />
71
+ <Legend wrapperStyle={{ paddingTop: '20px', fontFamily: 'monospace' }} />
72
+ <Bar
73
+ dataKey={dataKey}
74
+ fill="url(#barGradient)"
75
+ radius={[4, 4, 0, 0]}
76
+ filter="url(#glow)"
77
+ animationDuration={1500}
78
+ />
79
+ </BarChart>
80
+ </ResponsiveContainer>
81
+ </div>
82
+ );
83
+ }
@@ -0,0 +1,128 @@
1
+ import { describe, it, expect, beforeAll } from 'vitest';
2
+ import { ComponentRegistry } from '@object-ui/core';
3
+
4
+ describe('Plugin Charts', () => {
5
+ // Import all renderers to register them
6
+ beforeAll(async () => {
7
+ await import('./index');
8
+ });
9
+
10
+ describe('chart-bar component', () => {
11
+ it('should be registered in ComponentRegistry', () => {
12
+ const chartBarRenderer = ComponentRegistry.get('chart-bar');
13
+ expect(chartBarRenderer).toBeDefined();
14
+ });
15
+
16
+ it('should have proper metadata', () => {
17
+ const config = ComponentRegistry.getConfig('chart-bar');
18
+ expect(config).toBeDefined();
19
+ expect(config?.label).toBe('Bar Chart');
20
+ expect(config?.category).toBe('plugin');
21
+ expect(config?.inputs).toBeDefined();
22
+ expect(config?.defaultProps).toBeDefined();
23
+ });
24
+
25
+ it('should have expected inputs', () => {
26
+ const config = ComponentRegistry.getConfig('chart-bar');
27
+ const inputNames = config?.inputs?.map((input: any) => input.name) || [];
28
+
29
+ expect(inputNames).toContain('data');
30
+ expect(inputNames).toContain('dataKey');
31
+ expect(inputNames).toContain('xAxisKey');
32
+ expect(inputNames).toContain('height');
33
+ expect(inputNames).toContain('color');
34
+ });
35
+
36
+ it('should have data as required input', () => {
37
+ const config = ComponentRegistry.getConfig('chart-bar');
38
+ const dataInput = config?.inputs?.find((input: any) => input.name === 'data');
39
+
40
+ expect(dataInput).toBeDefined();
41
+ expect(dataInput?.required).toBe(true);
42
+ expect(dataInput?.type).toBe('array');
43
+ });
44
+
45
+ it('should have sensible default props', () => {
46
+ const config = ComponentRegistry.getConfig('chart-bar');
47
+ const defaults = config?.defaultProps;
48
+
49
+ expect(defaults).toBeDefined();
50
+ expect(defaults?.dataKey).toBe('value');
51
+ expect(defaults?.xAxisKey).toBe('name');
52
+ expect(defaults?.height).toBe(400);
53
+ expect(defaults?.color).toBe('#8884d8');
54
+ expect(defaults?.data).toBeDefined();
55
+ expect(Array.isArray(defaults?.data)).toBe(true);
56
+ expect(defaults?.data.length).toBeGreaterThan(0);
57
+ });
58
+ });
59
+
60
+ describe('chart (advanced) component', () => {
61
+ it('should be registered in ComponentRegistry', () => {
62
+ const chartRenderer = ComponentRegistry.get('chart');
63
+ expect(chartRenderer).toBeDefined();
64
+ });
65
+
66
+ it('should have proper metadata', () => {
67
+ const config = ComponentRegistry.getConfig('chart');
68
+ expect(config).toBeDefined();
69
+ expect(config?.label).toBe('Chart');
70
+ expect(config?.category).toBe('plugin');
71
+ expect(config?.inputs).toBeDefined();
72
+ expect(config?.defaultProps).toBeDefined();
73
+ });
74
+
75
+ it('should have expected inputs', () => {
76
+ const config = ComponentRegistry.getConfig('chart');
77
+ const inputNames = config?.inputs?.map((input: any) => input.name) || [];
78
+
79
+ expect(inputNames).toContain('chartType');
80
+ expect(inputNames).toContain('data');
81
+ expect(inputNames).toContain('config');
82
+ expect(inputNames).toContain('xAxisKey');
83
+ expect(inputNames).toContain('series');
84
+ expect(inputNames).toContain('className');
85
+ });
86
+
87
+ it('should have chartType as enum input', () => {
88
+ const config = ComponentRegistry.getConfig('chart');
89
+ const chartTypeInput = config?.inputs?.find((input: any) => input.name === 'chartType');
90
+
91
+ expect(chartTypeInput).toBeDefined();
92
+ expect(chartTypeInput?.type).toBe('enum');
93
+ expect(chartTypeInput?.enum).toBeDefined();
94
+ expect(Array.isArray(chartTypeInput?.enum)).toBe(true);
95
+
96
+ const enumValues = chartTypeInput?.enum?.map((e: any) => e.value) || [];
97
+ expect(enumValues).toContain('bar');
98
+ expect(enumValues).toContain('line');
99
+ expect(enumValues).toContain('area');
100
+ });
101
+
102
+ it('should have data and series as required inputs', () => {
103
+ const config = ComponentRegistry.getConfig('chart');
104
+ const dataInput = config?.inputs?.find((input: any) => input.name === 'data');
105
+ const seriesInput = config?.inputs?.find((input: any) => input.name === 'series');
106
+
107
+ expect(dataInput?.required).toBe(true);
108
+ expect(seriesInput?.required).toBe(true);
109
+ });
110
+
111
+ it('should have sensible default props', () => {
112
+ const config = ComponentRegistry.getConfig('chart');
113
+ const defaults = config?.defaultProps;
114
+
115
+ expect(defaults).toBeDefined();
116
+ expect(defaults?.chartType).toBe('bar');
117
+ expect(defaults?.xAxisKey).toBe('name');
118
+ expect(defaults?.data).toBeDefined();
119
+ expect(Array.isArray(defaults?.data)).toBe(true);
120
+ expect(defaults?.data.length).toBeGreaterThan(0);
121
+ expect(defaults?.config).toBeDefined();
122
+ expect(typeof defaults?.config).toBe('object');
123
+ expect(defaults?.series).toBeDefined();
124
+ expect(Array.isArray(defaults?.series)).toBe(true);
125
+ expect(defaults?.series.length).toBeGreaterThan(0);
126
+ });
127
+ });
128
+ });