The Open Standard for Generative UI
Charts component base
i-subham087705e3b8ff
diff --git a/frontend-sdk/packages/react-ui/package.json b/frontend-sdk/packages/react-ui/package.jsonindex b7c84f6b0..79d8dd9ee 100644--- a/frontend-sdk/packages/react-ui/package.json+++ b/frontend-sdk/packages/react-ui/package.json@@ -1,5 +1,6 @@{"name": "@crayonai/react-ui",+ "type": "module","version": "1.0.0","description": "","main": "dist/index.js",@@ -51,20 +52,13 @@"@radix-ui/react-switch": "^1.1.2","@storybook/addon-styling-webpack": "^1.0.1","clsx": "^2.1.1",+ "lodash-es": "^4.17.21","lucide-react": "^0.469.0",- "sass": "^1.83.4"+ "recharts": "^2.15.1",+ "sass": "^1.83.4",+ "typescript": "^5.7.3"},"devDependencies": {- "vite": "^5.0.0",- "@typescript-eslint/eslint-plugin": "^8.18.0",- "eslint": "^9.17.0",- "eslint-config-prettier": "^9.1.0",- "eslint-plugin-prettier": "^5.2.1",- "eslint-plugin-react-hooks": "^5.1.0",- "eslint-plugin-react-refresh": "^0.4.16",- "eslint-plugin-storybook": "^0.11.1",- "eslint-plugin-unused-imports": "^3.1.0",- "prettier-plugin-organize-imports": "^3.2.4","@chromatic-com/storybook": "^3.2.4","@storybook/addon-essentials": "^8.5.2","@storybook/addon-interactions": "^8.5.2",@@ -73,9 +67,20 @@"@storybook/react": "^8.5.2","@storybook/react-vite": "^8.5.2","@storybook/test": "^8.5.2",+ "@types/lodash-es": "^4.17.12","@types/react": "^19.0.8",+ "@typescript-eslint/eslint-plugin": "^8.18.0",+ "eslint": "^9.17.0",+ "eslint-config-prettier": "^9.1.0",+ "eslint-plugin-prettier": "^5.2.1",+ "eslint-plugin-react-hooks": "^5.1.0",+ "eslint-plugin-react-refresh": "^0.4.16",+ "eslint-plugin-storybook": "^0.11.1",+ "eslint-plugin-unused-imports": "^3.1.0",+ "prettier-plugin-organize-imports": "^3.2.4","prop-types": "^15.8.1",- "storybook": "^8.5.2"+ "storybook": "^8.5.2",+ "vite": "^5.0.0"},"keywords": [],"author": "",diff --git a/frontend-sdk/packages/react-ui/src/components/Charts/Charts.tsx b/frontend-sdk/packages/react-ui/src/components/Charts/Charts.tsxnew file mode 100644index 000000000..e8d71b4ad--- /dev/null+++ b/frontend-sdk/packages/react-ui/src/components/Charts/Charts.tsx@@ -0,0 +1,409 @@+import clsx from 'clsx'+import { uniqueId } from 'lodash-es'+import {+ ComponentProps,+ createContext,+ forwardRef,+ useContext,+ useId,+ useMemo,+} from 'react'+import * as RechartsPrimitive from 'recharts'+import './Charts.scss'++/**+ * @module Charts+ * A collection of chart components built on top of Recharts with enhanced styling and theming capabilities.+ */++/**+ * Available themes for chart customization+ * @constant+ * @type {Record<'light' | 'dark', string>}+ */+const THEMES = { light: '', dark: '.dark' } as const++/**+ * Configuration type for chart elements+ */+export type ChartConfig = {+ [k in string]: {+ label?: React.ReactNode+ icon?: React.ComponentType+ } & (+ | { color?: string; theme?: never }+ | { color?: never; theme: Record<keyof typeof THEMES, string> }+ )+}++/**+ * Context props for chart configuration+ */+type ChartContextProps = {+ config: ChartConfig+}++const ChartContext = createContext<ChartContextProps | null>(null)++/**+ * Hook to access chart context+ * @throws Error if used outside of ChartContainer+ */+function useChart() {+ const context = useContext(ChartContext)++ if (!context) {+ throw new Error('useChart must be used within a <ChartContainer />')+ }++ return context+}++/**+ * Container component for charts that provides configuration context and styling+ */+const ChartContainer = forwardRef<+ HTMLDivElement,+ ComponentProps<'div'> & {+ config: ChartConfig+ children: React.ComponentProps<+ typeof RechartsPrimitive.ResponsiveContainer+ >['children']+ }+>(({ id, className, children, config, ...props }, ref) => {+ const uniqueId = useId()+ const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`++ return (+ <ChartContext.Provider value={{ config }}>+ <div+ data-chart={chartId}+ ref={ref}+ className={clsx('crayon-chart-container', className)}+ {...props}+ >+ <ChartStyle id={chartId} config={config} />+ <RechartsPrimitive.ResponsiveContainer>+ {children}+ </RechartsPrimitive.ResponsiveContainer>+ </div>+ </ChartContext.Provider>+ )+})+ChartContainer.displayName = 'Chart'++/**+ * Component that generates theme-specific styles for chart elements+ */+const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {+ const colorConfig = Object.entries(config).filter(+ ([_, config]) => config.theme || config.color,+ )++ if (!colorConfig.length) {+ return null+ }++ return (+ <style+ dangerouslySetInnerHTML={{+ __html: Object.entries(THEMES)+ .map(+ ([theme, prefix]) => `+ ${prefix} [data-chart=${id}] {+ ${colorConfig+ .map(([key, itemConfig]) => {+ const color =+ itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||+ itemConfig.color+ return color ? ` --color-${key}: ${color};` : null+ })+ .filter(Boolean)+ .join('\n')}+ }+ `,+ )+ .join('\n'),+ }}+ />+ )+}++/**+ * Re-exported Tooltip component from Recharts+ */+const ChartTooltip = RechartsPrimitive.Tooltip++/**+ * Custom tooltip content component with enhanced styling and formatting+ */+const ChartTooltipContent = forwardRef<+ HTMLDivElement,+ React.ComponentProps<typeof RechartsPrimitive.Tooltip> &+ React.ComponentProps<'div'> & {+ hideLabel?: boolean+ hideIndicator?: boolean+ indicator?: 'line' | 'dot' | 'dashed'+ nameKey?: string+ labelKey?: string+ showPercentage?: boolean+ }+>(+ (+ {+ active,+ payload,+ className,+ indicator = 'dot',+ hideLabel = false,+ hideIndicator = false,+ label,+ labelFormatter,+ labelClassName,+ formatter,+ color,+ nameKey,+ labelKey,+ showPercentage = false,+ },+ ref,+ ) => {+ const { config } = useChart()++ const tooltipLabel = useMemo(() => {+ if (hideLabel || !payload?.length) {+ return null+ }++ const [item] = payload+ const key = `${labelKey ?? item?.dataKey ?? item?.name ?? 'value'}`+ const itemConfig = getPayloadConfigFromPayload(config, item, key)+ const value =+ !labelKey && typeof label === 'string'+ ? config[label]?.label || label+ : itemConfig?.label++ if (labelFormatter) {+ return (+ <div className={clsx('crayon-chart-tooltip-label', labelClassName)}>+ {labelFormatter(value, payload)}+ </div>+ )+ }++ if (!value) {+ return null+ }++ return (+ <div className={clsx('crayon-chart-tooltip-label', labelClassName)}>+ {value}+ </div>+ )+ }, [+ label,+ labelFormatter,+ payload,+ hideLabel,+ labelClassName,+ config,+ labelKey,+ ])++ if (!active || !payload?.length) {+ return null+ }++ const nestLabel = payload.length === 1 && indicator !== 'dot'++ return (+ <div ref={ref} className={clsx('crayon-chart-tooltip', className)}>+ {!nestLabel && tooltipLabel}+ <div className="crayon-chart-tooltip-content">+ {payload.map((item, index) => {+ const key = `${nameKey ?? item.name ?? item.dataKey ?? 'value'}`+ const itemConfig = getPayloadConfigFromPayload(config, item, key)+ const indicatorColor = (color ?? item.payload.fill) || item.color++ return (+ <div+ key={item.dataKey}+ className="crayon-chart-tooltip-content-item"+ >+ {formatter && item?.value !== undefined && item.name ? (+ formatter(item.value, item.name, item, index, item.payload)+ ) : (+ <>+ {itemConfig?.icon ? (+ <itemConfig.icon />+ ) : (+ !hideIndicator && (+ <div+ className={clsx(+ 'crayon-chart-tooltip-content-indicator',+ `crayon-chart-tooltip-content-indicator--${indicator}`,+ )}+ style={+ {+ '--color-bg': indicatorColor,+ '--color-border': indicatorColor,+ } as React.CSSProperties+ }+ />+ )+ )}+ <div+ className={clsx(+ 'crayon-chart-tooltip-content-value-wrapper',+ nestLabel+ ? 'crayon-chart-tooltip-content-value-wrapper--nested'+ : 'crayon-chart-tooltip-content-value-wrapper--standard',+ )}+ >+ <div className="crayon-chart-tooltip-content-label">+ {nestLabel && tooltipLabel}+ <span>{itemConfig?.label || item.name}</span>+ </div>+ {item.value !== undefined && (+ <span+ className={clsx(+ 'crayon-chart-tooltip-content-value',+ showPercentage && 'percentage',+ )}+ >+ {item.value.toLocaleString()}+ {showPercentage ? '%' : ''}+ </span>+ )}+ </div>+ </>+ )}+ </div>+ )+ })}+ </div>+ </div>+ )+ },+)+ChartTooltipContent.displayName = 'ChartTooltip'++/**+ * Re-exported Legend component from Recharts+ */+const ChartLegend = RechartsPrimitive.Legend++/**+ * Custom legend content component with enhanced styling+ */+const ChartLegendContent = forwardRef<+ HTMLDivElement,+ React.ComponentProps<'div'> &+ Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {+ hideIcon?: boolean+ nameKey?: string+ }+>(+ (+ { className, hideIcon = false, payload, verticalAlign = 'bottom', nameKey },+ ref,+ ) => {+ const { config } = useChart()++ const payloadWithKeys = useMemo(+ () =>+ payload?.map((item) => ({+ ...item,+ uniqueKey: uniqueId(+ `chart-legend-${item.dataKey || item.value || ''}-`,+ ),+ })),+ [payload],+ )++ if (!payload?.length) {+ return null+ }++ return (+ <div+ ref={ref}+ className={clsx(+ 'crayon-chart-legend',+ `crayon-chart-legend--${verticalAlign}`,+ className,+ )}+ >+ {payloadWithKeys?.map((item) => {+ const key = `${nameKey || item.dataKey || 'value'}`+ const itemConfig = getPayloadConfigFromPayload(config, item, key)++ return (+ <div key={item.uniqueKey} className="crayon-chart-legend-item">+ {itemConfig?.icon && !hideIcon ? (+ <itemConfig.icon />+ ) : (+ <div+ className="crayon-chart-legend-item-indicator"+ style={{ backgroundColor: item.color }}+ />+ )}+ <span className="crayon-chart-legend-item-label">+ {itemConfig?.label}+ </span>+ </div>+ )+ })}+ </div>+ )+ },+)+ChartLegendContent.displayName = 'ChartLegend'++/**+ * Helper function to extract configuration for a chart element from a payload+ */+function getPayloadConfigFromPayload(+ config: ChartConfig,+ payload: unknown,+ key: string,+) {+ if (typeof payload !== 'object' || payload === null) {+ return undefined+ }++ const payloadPayload =+ 'payload' in payload &&+ typeof payload.payload === 'object' &&+ payload.payload !== null+ ? payload.payload+ : undefined++ let configLabelKey: string = key++ if (+ key in payload &&+ typeof payload[key as keyof typeof payload] === 'string'+ ) {+ configLabelKey = payload[key as keyof typeof payload] as string+ } else if (+ payloadPayload &&+ key in payloadPayload &&+ typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'+ ) {+ configLabelKey = payloadPayload[+ key as keyof typeof payloadPayload+ ] as string+ }++ return configLabelKey in config ? config[configLabelKey] : config[key]+}++export {+ ChartContainer,+ ChartLegend,+ ChartLegendContent,+ ChartStyle,+ ChartTooltip,+ ChartTooltipContent,+}\ No newline at end of filediff --git a/frontend-sdk/packages/react-ui/src/components/Charts/charts.scss b/frontend-sdk/packages/react-ui/src/components/Charts/charts.scssnew file mode 100644index 000000000..0c81ae6c0--- /dev/null+++ b/frontend-sdk/packages/react-ui/src/components/Charts/charts.scss@@ -0,0 +1,199 @@+.crayon-chart {+ // Container styles+ &-container {+ display: flex;+ aspect-ratio: 16 / 9;+ justify-content: center;+ font-size: 0.75rem;++ // Recharts overrides+ // Text and fills+ .recharts-cartesian-axis-tick text {+ fill: var(--t-comp-primary);+ }++ .recharts-radial-bar-background-sector {+ fill: var(--t-comp-background);+ }++ .recharts-rectangle.recharts-tooltip-cursor {+ fill: var(--t-comp-background);+ }++ // Strokes and borders+ .recharts-cartesian-grid line[stroke="#ccc"],+ .recharts-curve.recharts-tooltip-cursor,+ .recharts-polar-grid[stroke="#ccc"],+ .recharts-reference-line[stroke="#ccc"] {+ stroke: var(--t-comp-default);+ }++ // Transparency settings+ .recharts-dot[stroke="#fff"],+ .recharts-sector[stroke="#fff"] {+ stroke: transparent;+ }++ // Outline resets+ .recharts-layer,+ .recharts-sector,+ .recharts-surface {+ outline: none;+ }+ }++ // Tooltip styles+ &-tooltip {+ display: grid;+ align-items: start;+ min-width: 8rem;+ gap: var(--t-comp-spacing-xs);+ padding: var(--t-comp-spacing-xs);+ color: var(--t-comp-primary);+ font-family: var(--t-comp-typography-label-family);+ font-size: var(--t-comp-typography-label-size);+ font-weight: var(--t-comp-typography-label-weight);+ border-radius: var(--t-comp-clickables-radius);+ border: 1px solid var(--t-comp-default);+ background-color: var(--t-comp-container);+ box-shadow: var(--t-comp-shadow-small);++ &-label {+ color: var(--t-comp-primary);+ font-family: var(--t-comp-typography-label-family);+ font-size: var(--t-comp-typography-label-size);+ font-weight: var(--t-comp-typography-label-weight);+ }++ &-content {+ display: grid;+ gap: 0.375rem;++ &-item {+ display: flex;+ width: 100%;+ flex-wrap: wrap;+ gap: 0.5rem;+ align-items: center;++ svg {+ height: 0.625rem;+ width: 0.625rem;+ color: var(--t-comp-primary);+ }+ }++ &-indicator {+ flex-shrink: 0;+ border-radius: 2px;++ &--dot {+ height: 0.625rem;+ width: 0.625rem;+ background-color: var(--color-bg);+ border-color: var(--color-border);+ }++ &--line {+ width: 0.25rem;+ height: 100%;+ background-color: var(--color-bg);+ border-color: var(--color-border);+ }++ &--dashed {+ width: 0;+ border: 1.5px dashed var(--color-border);+ background-color: transparent;+ }++ &--nested-dashed {+ margin: 0.125rem 0;+ }+ }++ &-value-wrapper {+ display: flex;+ flex: 1;+ justify-content: space-between;+ line-height: 1;++ &--nested {+ align-items: flex-end;+ }++ &--standard {+ align-items: center;+ }+ }++ &-label {+ display: grid;+ gap: 0.375rem;+ color: var(--t-comp-primary);+ font-family: var(--t-comp-typography-label-family);+ font-size: var(--t-comp-typography-label-size);+ font-weight: var(--t-comp-typography-label-weight);+ }++ &-value {+ font-variant-numeric: tabular-nums;+ color: var(--t-comp-primary);+ font-family: var(--t-comp-typography-label-family);+ font-size: var(--t-comp-typography-label-size);+ font-weight: var(--t-comp-typography-label-weight);++ &--percentage {+ padding-left: 0.5rem;+ }+ }+ }+ }++ // Legend styles+ &-legend {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 1rem;++ &--top {+ padding-bottom: 0.75rem;+ }++ &--bottom {+ padding-top: 0.75rem;+ }++ &-item {+ display: flex;+ align-items: center;+ gap: 0.375rem;++ svg {+ height: 0.75rem;+ width: 0.75rem;+ color: var(--t-comp-primary);+ }++ &-indicator {+ height: 0.5rem;+ width: 0.5rem;+ flex-shrink: 0;+ border-radius: 2px;+ background-color: var(--color-bg);+ }++ &-label {+ font-family: var(--t-comp-typography-label-heavy-family);+ font-size: var(--t-comp-typography-label-heavy-size);+ font-weight: var(--t-comp-typography-label-heavy-weight);+ max-width: 4rem;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--t-comp-primary);+ }+ }+ }+}\ No newline at end of filediff --git a/frontend-sdk/packages/react-ui/src/stories/Button.stories.ts b/frontend-sdk/packages/react-ui/src/stories/Button.stories.tsdeleted file mode 100644index 07c1f386d..000000000--- a/frontend-sdk/packages/react-ui/src/stories/Button.stories.ts+++ /dev/null@@ -1,53 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react";-import { fn } from "@storybook/test";--import { Button } from "./Button";--// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export-const meta = {- title: "Example/Button",- component: Button,- parameters: {- // Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout- layout: "centered",- },- // This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs- tags: ["autodocs"],- // More on argTypes: https://storybook.js.org/docs/api/argtypes- argTypes: {- backgroundColor: { control: "color" },- },- // Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args- args: { onClick: fn() },-} satisfies Meta<typeof Button>;--export default meta;-type Story = StoryObj<typeof meta>;--// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args-export const Primary: Story = {- args: {- primary: true,- label: "Button",- },-};--export const Secondary: Story = {- args: {- label: "Button",- },-};--export const Large: Story = {- args: {- size: "large",- label: "Button",- },-};--export const Small: Story = {- args: {- size: "small",- label: "Button",- },-};diff --git a/frontend-sdk/packages/react-ui/src/stories/Header.stories.ts b/frontend-sdk/packages/react-ui/src/stories/Header.stories.tsdeleted file mode 100644index eb3e27757..000000000--- a/frontend-sdk/packages/react-ui/src/stories/Header.stories.ts+++ /dev/null@@ -1,33 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react";-import { fn } from "@storybook/test";--import { Header } from "./Header";--const meta = {- title: "Example/Header",- component: Header,- // This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs- tags: ["autodocs"],- parameters: {- // More on how to position stories at: https://storybook.js.org/docs/configure/story-layout- layout: "fullscreen",- },- args: {- onLogin: fn(),- onLogout: fn(),- onCreateAccount: fn(),- },-} satisfies Meta<typeof Header>;--export default meta;-type Story = StoryObj<typeof meta>;--export const LoggedIn: Story = {- args: {- user: {- name: "Jane Doe",- },- },-};--export const LoggedOut: Story = {};diff --git a/frontend-sdk/packages/react-ui/src/stories/Page.stories.ts b/frontend-sdk/packages/react-ui/src/stories/Page.stories.tsdeleted file mode 100644index f5c5a0b38..000000000--- a/frontend-sdk/packages/react-ui/src/stories/Page.stories.ts+++ /dev/null@@ -1,32 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react";-import { expect, userEvent, within } from "@storybook/test";--import { Page } from "./Page";--const meta = {- title: "Example/Page",- component: Page,- parameters: {- // More on how to position stories at: https://storybook.js.org/docs/configure/story-layout- layout: "fullscreen",- },-} satisfies Meta<typeof Page>;--export default meta;-type Story = StoryObj<typeof meta>;--export const LoggedOut: Story = {};--// More on interaction testing: https://storybook.js.org/docs/writing-tests/interaction-testing-export const LoggedIn: Story = {- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const loginButton = canvas.getByRole("button", { name: /Log in/i });- await expect(loginButton).toBeInTheDocument();- await userEvent.click(loginButton);- await expect(loginButton).not.toBeInTheDocument();-- const logoutButton = canvas.getByRole("button", { name: /Log out/i });- await expect(logoutButton).toBeInTheDocument();- },-};diff --git a/frontend-sdk/packages/react-ui/tsconfig.json b/frontend-sdk/packages/react-ui/tsconfig.jsonindex a02ab67d7..bcd5a8591 100644--- a/frontend-sdk/packages/react-ui/tsconfig.json+++ b/frontend-sdk/packages/react-ui/tsconfig.json@@ -2,6 +2,8 @@"$schema": "https://json.schemastore.org/tsconfig","extends": "../../tsconfig.json","compilerOptions": {+ "module": "ESNext",+ "moduleResolution": "bundler","outDir": "./dist","rootDir": "./src","types": ["./src/types.d.ts"]