Skip to content

The Open Standard for Generative UI

Theme specific improvements: tooltip, themeprovider, CrayonChat (#156)

Ankit Das5143e98ee35c
diff --git a/js/packages/react-ui/package.json b/js/packages/react-ui/package.json
index 0d4fc4d4f..214e37659 100644
--- a/js/packages/react-ui/package.json
+++ b/js/packages/react-ui/package.json
@@ -2,7 +2,7 @@
"type": "module",
"name": "@crayonai/react-ui",
"license": "MIT",
- "version": "0.8.9",
+ "version": "0.8.10",
"description": "Component library for Generative UI SDK",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx b/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx
deleted file mode 100644
index 7fa14f418..000000000
--- a/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { Bar } from "recharts";
-import { LineInBarShape } from "../shared";
-import { getRadiusArray } from "../utils/BarCharts/BarChartsUtils";
-import { BarChartVariant } from "./types";
-import { BAR_WIDTH } from "./utils/BarChartUtils";
-
-const BAR_INTERNAL_LINE_WIDTH = 1;
-
-export interface BarSeriesProps {
- dataKeys: string[];
- transformedKeys: Record<string, string>;
- variant: BarChartVariant;
- radius: number;
- isAnimationActive: boolean;
- barInternalLineColor: string;
- hoveredCategory: string | number | null;
- categoryKey: string;
-}
-
-export const BarSeries = ({
- dataKeys,
- transformedKeys,
- variant,
- radius,
- isAnimationActive,
- barInternalLineColor,
- hoveredCategory,
- categoryKey,
-}: BarSeriesProps) => {
- return (
- <>
- {dataKeys.map((key, index) => {
- const transformedKey = transformedKeys[key];
- const color = `var(--color-${transformedKey})`;
- const isFirstInStack = index === 0;
- const isLastInStack = index === dataKeys.length - 1;
-
- return (
- <Bar
- key={`main-${key}`}
- dataKey={key}
- fill={color}
- radius={getRadiusArray(
- variant,
- radius,
- "vertical",
- variant === "stacked" ? isFirstInStack : undefined,
- variant === "stacked" ? isLastInStack : undefined,
- )}
- stackId={variant === "stacked" ? "a" : undefined}
- isAnimationActive={isAnimationActive}
- maxBarSize={BAR_WIDTH}
- barSize={BAR_WIDTH}
- shape={
- <LineInBarShape
- internalLineColor={barInternalLineColor}
- internalLineWidth={BAR_INTERNAL_LINE_WIDTH}
- isHovered={hoveredCategory !== null}
- hoveredCategory={hoveredCategory}
- categoryKey={categoryKey}
- variant={variant}
- />
- }
- />
- );
- })}
- </>
- );
-};
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
index 5ee115f6b..6aaf78601 100644
--- a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
@@ -29,12 +29,12 @@ import {
} from "../utils/dataUtils";
import { numberTickFormatter } from "../utils/styleUtils";
import { CustomBarShape } from "./components/CustomBarShape";
+import { useMaxCategoryLabelWidth } from "./hooks/useMaxCategoryLabelWidth";
import { HorizontalBarChartData, HorizontalBarChartVariant } from "./types";
import {
BAR_GAP,
BAR_HEIGHT,
getHeightOfData,
- getMaxCategoryLabelWidth,
getPadding,
getSnapPositions,
} from "./utils/HorizontalBarChartUtils";
@@ -85,7 +85,7 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
height,
width,
}: HorizontalBarChartProps<T>) => {
- const maxCategoryLabelWidth = getMaxCategoryLabelWidth(data, categoryKey as string);
+ const maxCategoryLabelWidth = useMaxCategoryLabelWidth(data, categoryKey as string);
const chartContainerRef = useRef<HTMLDivElement>(null);
const mainContainerRef = useRef<HTMLDivElement>(null);
@@ -288,7 +288,7 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
</ChartContainer>
</div>
);
- }, [showXAxis, chartConfig, data, dataKeys, variant, id, maxCategoryLabelWidth]);
+ }, [showXAxis, chartConfig, data, dataKeys, variant, id]);
// Handle mouse events for group hovering
const handleChartMouseMove = useCallback((state: any) => {
@@ -366,6 +366,7 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
}}
>
{grid && verticalCartesianGrid()}
+ {/* this x axis is not visible but is needed for the chart to work */}
<XAxis type="number" tickLine={false} axisLine={false} hide />
<YAxis
type="category"
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/hooks/useMaxCategoryLabelWidth.tsx b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/hooks/useMaxCategoryLabelWidth.tsx
new file mode 100644
index 000000000..b2dd1f19b
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/hooks/useMaxCategoryLabelWidth.tsx
@@ -0,0 +1,29 @@
+import { useMemo } from "react";
+
+import { useCanvasContextForLabelSize } from "../../hooks/useCanvasContextForLabelSize";
+
+export const useMaxCategoryLabelWidth = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+): number => {
+ const context = useCanvasContextForLabelSize();
+
+ return useMemo(() => {
+ if (data.length === 0) {
+ return 100; // Default fallback
+ }
+
+ if (!context) {
+ // Fallback if canvas is not available
+ return Math.max(...data.map((item) => String(item[categoryKey] || "").length * 8), 100);
+ }
+
+ return Math.max(
+ ...data.map((item) => {
+ const text = String(item[categoryKey] || "");
+ return context.measureText(text).width;
+ }),
+ 100,
+ );
+ }, [data, categoryKey, context]);
+};
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts
index d22c25c82..a429e030a 100644
--- a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts
@@ -1,38 +1,9 @@
import { getDataKeys } from "../../utils/dataUtils";
-import { getCanvasContext } from "../../utils/styleUtils";
import { HorizontalBarChartVariant } from "../types";
export const BAR_HEIGHT = 16;
export const BAR_GAP = 10;
-/**
- * Get the maximum text width for category labels
- * @param data - The data to be displayed in the chart
- * @param categoryKey - The key of the category to be displayed in the chart
- * @returns The maximum width needed for category labels
- */
-export const getMaxCategoryLabelWidth = (
- data: Array<Record<string, string | number>>,
- categoryKey: string,
-): number => {
- if (data.length === 0) {
- return 100; // Default fallback
- }
-
- const context = getCanvasContext();
- if (!context) {
- return Math.max(...data.map((item) => String(item[categoryKey] || "").length * 8), 100);
- }
-
- return Math.max(
- ...data.map((item) => {
- const text = String(item[categoryKey] || "");
- return context.measureText(text).width;
- }),
- 100,
- );
-};
-
/**
* This function returns the height of the data in the chart, used for padding calculation, scroll amount calculation, and
* for the height of the chart container.
diff --git a/js/packages/react-ui/src/components/Charts/hooks/index.ts b/js/packages/react-ui/src/components/Charts/hooks/index.ts
index 1f50b568e..43d79c214 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/index.ts
+++ b/js/packages/react-ui/src/components/Charts/hooks/index.ts
@@ -1,3 +1,4 @@
+export * from "./useCanvasContextForLabelSize";
export * from "./useMaxLabelHeight";
export * from "./useTransformKey";
export * from "./useYAxisLabelWidth";
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useCanvasContextForLabelSize.ts b/js/packages/react-ui/src/components/Charts/hooks/useCanvasContextForLabelSize.ts
new file mode 100644
index 000000000..4c5d75bea
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/hooks/useCanvasContextForLabelSize.ts
@@ -0,0 +1,32 @@
+import { useMemo } from "react";
+
+import { useTheme } from "../../ThemeProvider";
+
+/**
+ * Creates a canvas 2D rendering context and sets its font style.
+ *
+ * This hook initializes a canvas element in memory, gets its 2D context,
+ * and then applies a font style based on the theme. It includes a fallback
+ * to a default font if the theme property is not available.
+ *
+ * @returns The canvas 2D context with the font style applied, or `null` if the
+ *
+ */
+
+export const useCanvasContextForLabelSize = () => {
+ const { theme: userTheme } = useTheme();
+
+ return useMemo(() => {
+ if (typeof window === "undefined" || typeof document === "undefined") {
+ return null;
+ }
+ const canvas = document.createElement("canvas");
+ const context = canvas.getContext("2d");
+ if (context) {
+ // Should match the chart's actual font for accuracy.
+ const font = userTheme.fontLabelExtraSmall ?? "400 10px/12px Inter";
+ context.font = font;
+ }
+ return context;
+ }, [userTheme.fontLabelExtraSmall]);
+};
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx b/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx
index d50ac66c2..d8941877e 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx
+++ b/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx
@@ -1,35 +1,30 @@
import { useMemo } from "react";
-import { useTheme } from "../../ThemeProvider";
import { AreaChartData } from "../AreaChart";
import { BarChartData } from "../BarChart";
import { LineChartData } from "../LineChart";
-import { getCanvasContext, numberTickFormatter } from "../utils";
+import { numberTickFormatter } from "../utils";
+import { useCanvasContextForLabelSize } from "./useCanvasContextForLabelSize";
const DEFAULT_Y_AXIS_WIDTH = 40;
-const MIN_Y_AXIS_WIDTH = 30;
-const MAX_Y_AXIS_WIDTH = 120;
+const MIN_Y_AXIS_WIDTH = 20;
+const MAX_Y_AXIS_WIDTH = 200;
export const useYAxisLabelWidth = (
data: AreaChartData | LineChartData | BarChartData,
dataKeys: string[],
) => {
- const { theme: userTheme } = useTheme();
+ const context = useCanvasContextForLabelSize();
const maxLabelWidth = useMemo(() => {
if (typeof window === "undefined" || !data || data.length === 0 || !dataKeys.length) {
return DEFAULT_Y_AXIS_WIDTH;
}
- const context = getCanvasContext();
if (!context) {
return DEFAULT_Y_AXIS_WIDTH;
}
- // Set font to match Y-axis tick styling
- const font = userTheme.fontLabelExtraSmall ?? "400 10px/12px Inter";
- context.font = font;
-
let maxWidth = 0;
// Measure all possible Y-axis values
@@ -47,11 +42,11 @@ export const useYAxisLabelWidth = (
});
// Add padding for better visual appearance
- const totalWidth = Math.ceil(maxWidth) + 10; // 6px padding on each side
+ const totalWidth = Math.ceil(maxWidth) + 10; // 5px padding on each side
// Clamp the width between MIN and MAX values
return Math.max(MIN_Y_AXIS_WIDTH, Math.min(MAX_Y_AXIS_WIDTH, totalWidth));
- }, [data, dataKeys, userTheme.fontLabelExtraSmall]);
+ }, [data, dataKeys, context]);
return maxLabelWidth;
};
diff --git a/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/DefaultLegend.tsx b/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/DefaultLegend.tsx
index a3b02963c..68b7f2183 100644
--- a/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/DefaultLegend.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/DefaultLegend.tsx
@@ -1,9 +1,9 @@
import clsx from "clsx";
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
-import React, { memo, useCallback, useMemo, useState } from "react";
+import React, { memo, useCallback, useState } from "react";
import { Button } from "../../../Button/Button";
import { type LegendItem } from "../../types";
-import { calculateVisibleItems, getToggleButtonText } from "./utils/defaultLegendUtils";
+import { useDefaultLegend } from "./hooks/useDefaultLegend";
interface DefaultLegendProps {
items: LegendItem[];
@@ -32,6 +32,12 @@ const DefaultLegend = memo(
ref,
) => {
const [buttonWidth, setButtonWidth] = useState(0);
+ const { displayItems, hasMoreItems, toggleButtonText } = useDefaultLegend({
+ items,
+ containerWidth,
+ buttonWidth,
+ isExpanded,
+ });
// We use a callback ref to measure the button's width as soon as it's mounted.
// This is more reliable than useEffect with ref.current in the dependency array,
@@ -49,24 +55,12 @@ const DefaultLegend = memo(
[buttonWidth],
);
- const { visibleItems, hasMoreItems } = useMemo(() => {
- return calculateVisibleItems(items, containerWidth, buttonWidth);
- }, [items, containerWidth, buttonWidth]);
-
- const displayItems = useMemo(() => {
- return isExpanded ? items : visibleItems;
- }, [isExpanded, items, visibleItems]);
-
const handleToggleExpanded = () => {
setIsExpanded(!isExpanded);
};
const showToggleButton = hasMoreItems;
- const toggleButtonText = useMemo(() => {
- return getToggleButtonText(isExpanded, items.length, visibleItems.length);
- }, [isExpanded, items.length, visibleItems.length]);
-
return (
<div
ref={ref}
diff --git a/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/hooks/useDefaultLegend.ts b/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/hooks/useDefaultLegend.ts
new file mode 100644
index 000000000..c04bce878
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/hooks/useDefaultLegend.ts
@@ -0,0 +1,105 @@
+import { useMemo } from "react";
+import { useCanvasContextForLabelSize } from "../../../hooks/useCanvasContextForLabelSize";
+import { LegendItem } from "../../../types";
+
+const CHARACTER_WIDTH = 7; // Fallback width per character
+const INDICATOR_WIDTH = 10;
+const GAP_WIDTH = 12;
+
+interface UseDefaultLegendProps {
+ items: LegendItem[];
+ containerWidth?: number;
+ buttonWidth?: number;
+ isExpanded: boolean;
+}
+
+interface UseDefaultLegendResult {
+ displayItems: LegendItem[];
+ hasMoreItems: boolean;
+ toggleButtonText: string;
+}
+
+export const useDefaultLegend = ({
+ items,
+ containerWidth,
+ buttonWidth,
+ isExpanded,
+}: UseDefaultLegendProps): UseDefaultLegendResult => {
+ const canvasContext = useCanvasContextForLabelSize();
+
+ const calculateItemWidth = useMemo(
+ () =>
+ (label: string): number => {
+ if (canvasContext) {
+ // If canvas is supported, measure text width accurately
+ return canvasContext.measureText(label).width + INDICATOR_WIDTH + GAP_WIDTH;
+ }
+
+ // Fallback for SSR or if canvas is not supported
+ return label.length * CHARACTER_WIDTH + INDICATOR_WIDTH + GAP_WIDTH;
+ },
+ [canvasContext],
+ );
+
+ const { visibleItems, hasMoreItems } = useMemo(() => {
+ if (!containerWidth || items.length === 0) {
+ return { visibleItems: items, hasMoreItems: false };
+ }
+
+ const availableWidth = containerWidth - (buttonWidth ?? 0);
+ let currentWidth = 0;
+ let visibleCount = 0;
+
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+ if (!item) continue;
+
+ const itemWidth = calculateItemWidth(item.label);
+ // Add gap between items except for the first one
+ const requiredWidth = visibleCount > 0 ? itemWidth + GAP_WIDTH : itemWidth;
+
+ if (currentWidth + requiredWidth <= availableWidth) {
+ currentWidth += requiredWidth;
+ visibleCount++;
+ } else {
+ break;
+ }
+ }
+ // If all items fit within available width, show all items
+ if (visibleCount === items.length) {
+ return { visibleItems: items, hasMoreItems: false };
+ }
+
+ // If no items fit within available width, show at least the first item
+ if (visibleCount === 0 && items[0]) {
+ return {
+ visibleItems: [items[0]], // Show first item
+ hasMoreItems: items.length > 1, // Has more if there are additional items
+ };
+ }
+
+ return {
+ visibleItems: items.slice(0, visibleCount),
+ hasMoreItems: items.length > visibleCount,
+ };
+ }, [items, containerWidth, buttonWidth, calculateItemWidth]);
+
+ const displayItems = useMemo(
+ () => (isExpanded ? items : visibleItems),
+ [isExpanded, items, visibleItems],
+ );
+
+ const toggleButtonText = useMemo(() => {
+ if (isExpanded) {
+ return "Show Less";
+ }
+ const hiddenCount = items.length - visibleItems.length;
+ return `${hiddenCount} more`;
+ }, [isExpanded, items.length, visibleItems.length]);
+
+ return {
+ displayItems,
+ hasMoreItems,
+ toggleButtonText,
+ };
+};
diff --git a/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/utils/defaultLegendUtils.ts b/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/utils/defaultLegendUtils.ts
deleted file mode 100644
index 0cb456e77..000000000
--- a/js/packages/react-ui/src/components/Charts/shared/DefaultLegend/utils/defaultLegendUtils.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { LegendItem } from "../../../types";
-import { getCanvasContext } from "../../../utils/styleUtils";
-
-const CHARACTER_WIDTH = 7; // Now only used as a fallback
-const INDICATOR_WIDTH = 10;
-const GAP_WIDTH = 12;
-
-// Memoize canvas context to avoid recreating it on every call
-let canvasContext: CanvasRenderingContext2D | null;
-const getMemoizedCanvasContext = (): CanvasRenderingContext2D | null => {
- if (canvasContext === undefined) {
- canvasContext = getCanvasContext();
- }
- return canvasContext;
-};
-
-/**
- * Calculate the estimated width of a legend item
- */
-export const calculateItemWidth = (label: string): number => {
- const context = getMemoizedCanvasContext();
-
- if (context) {
- // If canvas is supported, measure text width accurately
- return context.measureText(label).width + INDICATOR_WIDTH + GAP_WIDTH;
- }
-
- // Fallback for SSR or if canvas is not supported
- return label.length * CHARACTER_WIDTH + INDICATOR_WIDTH + GAP_WIDTH;
-};
-
-/**
- * Calculate which items can fit in the available width
- */
-export const calculateVisibleItems = (
- items: LegendItem[],
- containerWidth?: number,
- buttonWidth?: number,
-): {
- visibleItems: LegendItem[];
- hasMoreItems: boolean;
-} => {
- // If no containerWidth provided, show all items (default behavior)
- if (!containerWidth || items.length === 0) {
- return { visibleItems: items, hasMoreItems: false };
- }
-
- // Reserve space for "show more" button
- const availableWidth = containerWidth - (buttonWidth ?? 0);
-
- let currentWidth = 0;
- let visibleCount = 0;
-
- for (let i = 0; i < items.length; i++) {
- const item = items[i];
- if (!item) continue;
-
- const itemWidth = calculateItemWidth(item.label);
-
- // + GAP for the gap between the items
- if (currentWidth + itemWidth + GAP_WIDTH <= availableWidth) {
- currentWidth += itemWidth + GAP_WIDTH;
- visibleCount++;
- } else {
- break;
- }
- }
-
- // If all items fit, don't need show more button
- if (visibleCount === items.length) {
- return { visibleItems: items, hasMoreItems: false };
- }
-
- // If no items fit even with show more button, show at least one
- if (visibleCount === 0 && items[0]) {
- return { visibleItems: [items[0]], hasMoreItems: items.length > 1 };
- }
-
- return {
- visibleItems: items.slice(0, visibleCount),
- hasMoreItems: items.length > visibleCount,
- };
-};
-
-/**
- * Generate toggle button text based on the number of hidden items
- */
-export const getToggleButtonText = (
- isExpanded: boolean,
- totalItems: number,
- visibleItemsCount: number,
-): string => {
- if (isExpanded) {
- return "Show Less";
- }
-
- const hiddenCount = totalItems - visibleItemsCount;
- return `${hiddenCount} more`;
-};
diff --git a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx
index c63c469ce..49bf58c59 100644
--- a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx
@@ -3,6 +3,7 @@ import { computePosition, flip, offset, shift } from "@floating-ui/react-dom";
import clsx from "clsx";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
+import { useTheme } from "../../../ThemeProvider";
interface VirtualElement {
getBoundingClientRect(): DOMRect;
@@ -31,6 +32,7 @@ export const FloatingUIPortal: React.FC<FloatingUIPortalProps> = ({
const tooltipRef = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isPositioned, setIsPositioned] = useState(false);
+ const { portalThemeClassName } = useTheme();
// Memoize the virtual element to avoid recreating it on every render
// this virtual element basically shares the same position as the mouse position
@@ -120,7 +122,7 @@ export const FloatingUIPortal: React.FC<FloatingUIPortalProps> = ({
return createPortal(
<div
ref={tooltipRef}
- className={clsx("crayon-portal-tooltip", className)}
+ className={clsx("crayon-portal-tooltip", portalThemeClassName, className)}
data-chart={chartId}
style={{
left: position.x,
diff --git a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
index b1ed9609c..ed78eb035 100644
--- a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
+++ b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
@@ -23,39 +23,4 @@ const numberTickFormatter = (value: number) => {
return String(value);
};
-/**
- * Creates a canvas 2D rendering context and sets its font style.
- *
- * This function initializes a canvas element in memory, gets its 2D context,
- * and then attempts to apply a font style based on the `--crayon-font-label-extra-small`
- * CSS custom property from the document's body. It includes a fallback to a default
- * font if the custom property is not available (e.g., in an SSR environment).
- *
- * @returns The canvas 2D context with the font style applied, or `null` if the
- * context could not be created.
- */
-const getCanvasContext = (): CanvasRenderingContext2D | null => {
- if (typeof document === "undefined" || typeof window === "undefined") {
- return null;
- }
- const canvas = document.createElement("canvas");
- const context = canvas.getContext("2d");
- if (context) {
- // Should match the chart's actual font for accuracy.
- // The font is defined in `xAxisTick.scss` via a mixin, which uses the
- // CSS variable `--crayon-font-label-extra-small`.
- // in future we have to target the actual element instead of the body
- let font = "12px Inter"; // Default fallback.
- const value = window
- .getComputedStyle(document.body)
- .getPropertyValue("--crayon-font-label-extra-small");
- // trim is important, it can come with whitespace.
- if (value) {
- font = value.trim();
- }
- context.font = font;
- }
- return context;
-};
-
-export { getCanvasContext, numberTickFormatter };
+export { numberTickFormatter };
diff --git a/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx b/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx
index 76785affb..51acb6459 100644
--- a/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx
+++ b/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx
@@ -11,7 +11,7 @@ import {
useThreadListManager,
useThreadManager,
} from "@crayonai/react-core";
-import { useEffect, useRef } from "react";
+import { Fragment, useEffect, useRef } from "react";
import invariant from "tiny-invariant";
import { ScrollVariant } from "../../hooks/useScrollToBottom";
import { ThemeProps, ThemeProvider } from "../ThemeProvider";
@@ -43,6 +43,7 @@ type CrayonChatProps = {
scrollVariant?: ScrollVariant;
messageLoadingComponent?: () => React.ReactNode;
+ disableThemeProvider?: boolean;
};
export const CrayonChat = ({
@@ -59,8 +60,10 @@ export const CrayonChat = ({
type = "standalone",
theme,
scrollVariant = "user-message-anchor",
+ disableThemeProvider,
}: CrayonChatProps) => {
invariant(processMessage || userThreadManager, "processMessage or threadManager is required");
+ const ThemeProviderComponent = disableThemeProvider ? Fragment : ThemeProvider;
const threadMessages = useRef<{ [threadId: string]: Message[] }>({});
const defaultThreadListManager = useThreadListManager({
@@ -133,7 +136,7 @@ export const CrayonChat = ({
}, [threadManager.messages]);
return (
- <ThemeProvider {...theme}>
+ <ThemeProviderComponent {...theme}>
<ChatProvider threadListManager={threadListManager} threadManager={threadManager}>
{type === "copilot" ? (
<ComposedCopilot
@@ -151,6 +154,6 @@ export const CrayonChat = ({
/>
)}
</ChatProvider>
- </ThemeProvider>
+ </ThemeProviderComponent>
);
};
diff --git a/js/packages/react-ui/src/components/DatePicker/helpers/components/FloatingDatePickerRenderer.tsx b/js/packages/react-ui/src/components/DatePicker/helpers/components/FloatingDatePickerRenderer.tsx
index b3e2657f3..2e58f2c7f 100644
--- a/js/packages/react-ui/src/components/DatePicker/helpers/components/FloatingDatePickerRenderer.tsx
+++ b/js/packages/react-ui/src/components/DatePicker/helpers/components/FloatingDatePickerRenderer.tsx
@@ -4,6 +4,7 @@ import { ChevronDown } from "lucide-react";
import { forwardRef, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { useMultipleRefs } from "../../../../hooks/useMultipleRefs";
+import { useTheme } from "../../../ThemeProvider";
import { useDatePicker } from "../context/DatePickerContext";
import { formatDateRange, formatSingleDate } from "../utils/helperFn";
import { DatepickerRenderer } from "./DatePickerRenderer";
@@ -42,6 +43,7 @@ const FloatingDateInput = () => {
const FloatingDatePicker = forwardRef<HTMLDivElement>((_, ref) => {
const { isOpen } = useDatePicker();
const menuPositionDivRef = useRef<HTMLDivElement>(null);
+ const { portalThemeClassName } = useTheme();
const {
refs: { setFloating, setReference },
@@ -62,12 +64,15 @@ const FloatingDatePicker = forwardRef<HTMLDivElement>((_, ref) => {
return (
<>
- <div ref={menuPositionDivRefs} className="crayon-date-picker-renderer-floating-reference" />
+ <div
+ ref={menuPositionDivRefs}
+ className={clsx("crayon-date-picker-renderer-floating-reference")}
+ />
{createPortal(
<div
ref={floatingRef}
style={{ ...floatingStyles, width: "fit-content" }}
- className="crayon-date-picker-renderer-floating-content"
+ className={clsx("crayon-date-picker-renderer-floating-content", portalThemeClassName)}
>
<div className="crayon-date-picker-renderer-floating-menu">
<DatepickerRenderer />
diff --git a/js/packages/react-ui/src/components/Select/Select.tsx b/js/packages/react-ui/src/components/Select/Select.tsx
index 04fac7164..0477fc3dd 100644
--- a/js/packages/react-ui/src/components/Select/Select.tsx
+++ b/js/packages/react-ui/src/components/Select/Select.tsx
@@ -2,6 +2,7 @@ import * as SelectPrimitive from "@radix-ui/react-select";
import clsx from "clsx";
import { Check, ChevronDown } from "lucide-react";
import React, { forwardRef } from "react";
+import { useTheme } from "../ThemeProvider";
export const Select = SelectPrimitive.Root;
@@ -52,21 +53,25 @@ export interface SelectContentProps
export const SelectContent = forwardRef<
React.ComponentRef<typeof SelectPrimitive.Content>,
SelectContentProps
->(({ className, children, position = "popper", ...props }, ref) => (
- <SelectPrimitive.Portal>
- <SelectPrimitive.Content
- ref={ref}
- className={clsx("crayon-select-content", className)}
- position={position}
- sideOffset={2}
- {...props}
- >
- <SelectPrimitive.Viewport className="crayon-select-viewport" data-position={position}>
- {children}
- </SelectPrimitive.Viewport>
- </SelectPrimitive.Content>
- </SelectPrimitive.Portal>
-));
+>(({ className, children, position = "popper", ...props }, ref) => {
+ const { portalThemeClassName } = useTheme();
+
+ return (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ ref={ref}
+ className={clsx("crayon-select-content", className, portalThemeClassName)}
+ position={position}
+ sideOffset={2}
+ {...props}
+ >
+ <SelectPrimitive.Viewport className="crayon-select-viewport" data-position={position}>
+ {children}
+ </SelectPrimitive.Viewport>
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+ );
+});
export interface SelectLabelProps
extends React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> {
diff --git a/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx b/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
index 76cacb695..9fddd271d 100644
--- a/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
+++ b/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
@@ -1,5 +1,6 @@
import React, { createContext, useContext, useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
+import { useId } from "../../polyfills";
import { ColorTheme, EffectTheme, LayoutTheme, Theme, ThemeMode, TypographyTheme } from "./types";
export type ThemeProps = {
@@ -8,11 +9,13 @@ export type ThemeProps = {
// merged with lightTheme or darkTheme(if darkTheme is not provided)
theme?: Theme;
darkTheme?: Theme;
+ cssSelector?: string;
};
type ThemeContextType = {
theme: Theme;
mode: ThemeMode;
+ portalThemeClassName: string;
};
// Update the context to include both theme and mode
@@ -25,6 +28,7 @@ export const useTheme = () => {
return {
theme: themes.light,
mode: "light",
+ portalThemeClassName: "",
};
}
return context;
@@ -321,7 +325,9 @@ export const ThemeProvider = ({
children,
theme: userTheme = {},
darkTheme: userDarkTheme,
+ cssSelector = "body",
}: ThemeProps) => {
+ const id = useId();
const baseTheme = themes[mode];
const lightTheme = useShallow(() => ({ ...baseTheme, ...userTheme }))(undefined);
const darkTheme = useShallow(() => ({ ...baseTheme, ...(userDarkTheme || userTheme) }))(
@@ -329,12 +335,15 @@ export const ThemeProvider = ({
);
const theme = mode === "light" ? lightTheme : darkTheme;
- const contextValue = useMemo(() => ({ theme, mode }), [theme, mode]);
+ const contextValue = useMemo(
+ () => ({ theme, mode, portalThemeClassName: `crayon-theme-portal-${id}` }),
+ [theme, mode, id],
+ );
return (
<ThemeContext.Provider value={contextValue}>
<style>{`
- body {
+ ${cssSelector}, .${contextValue.portalThemeClassName} {
--crayon-background-fills: ${theme.backgroundFills};
--crayon-brand-el-fills: ${theme.brandElFills};
--crayon-brand-el-hover-fills: ${theme.brandElHoverFills};