Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Eslint rule: no-let-assign-in-react (#18181)

Ben Bachem7f1c74105e47
diff --git a/packages/config-eslint/next.js b/packages/config-eslint/next.js
index c752c2a55f..3537c343a8 100644
--- a/packages/config-eslint/next.js
+++ b/packages/config-eslint/next.js
@@ -124,6 +124,14 @@ export default [
...sharedConfig,
+ {
+ name: "langfuse/next/no-let-assign-in-react",
+ files: ["**/*.{js,jsx,mjs,ts,tsx,mts,cts}"],
+ rules: {
+ "@repo/no-let-assign-in-react": "error",
+ },
+ },
+
// Disable noisy turbo env var rule - project has many env vars not in turbo.json
{
name: "langfuse/next/turbo-overrides",
diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.ts
index c889be21d8..5ea578189e 100644
--- a/packages/eslint-plugin/src/index.ts
+++ b/packages/eslint-plugin/src/index.ts
@@ -6,6 +6,7 @@ import { default as noInSourceVitest } from "./rules/no-in-source-vitest.js";
import { default as noExoticOperators } from "./rules/no-exotic-operators.js";
import { default as noMarginOnRootElements } from "./rules/no-margin-on-root-elements.js";
import { default as noNullRender } from "./rules/no-null-render.js";
+import { default as noLetAssignInReact } from "./rules/no-let-assign-in-react.js";
import { default as noOverlayZindex } from "./rules/no-overlay-zindex.js";
import { default as noRawFontWeight } from "./rules/no-raw-font-weight.js";
import { default as requireTitleWithTruncate } from "./rules/require-title-with-truncate.js";
@@ -24,6 +25,7 @@ const plugin = {
"no-in-source-vitest": noInSourceVitest,
"no-margin-on-root-elements": noMarginOnRootElements,
"no-null-render": noNullRender,
+ "no-let-assign-in-react": noLetAssignInReact,
"no-overlay-zindex": noOverlayZindex,
"no-raw-font-weight": noRawFontWeight,
"no-style-props": noStyleProps,
diff --git a/packages/eslint-plugin/src/react-components.ts b/packages/eslint-plugin/src/react-components.ts
index 72e67f08a1..85ed1a9d22 100644
--- a/packages/eslint-plugin/src/react-components.ts
+++ b/packages/eslint-plugin/src/react-components.ts
@@ -14,6 +14,12 @@ type ResolveReturnExpression = (
) => TSESTree.Expression;
type ReturnExpressionCallbacks = {
+ onComponentFunction?: (
+ node:
+ | TSESTree.ArrowFunctionExpression
+ | TSESTree.FunctionDeclaration
+ | TSESTree.FunctionExpression,
+ ) => void;
onReturnExpression?: (
node: TSESTree.Expression,
resolve?: ResolveReturnExpression,
@@ -509,6 +515,7 @@ export function createComponentReturnExpressionVisitors(
node.expression
) {
if (!expressionReturnsJsxOrNull(node.body)) return;
+ callbacks.onComponentFunction?.(node);
const resolve = (expression: TSESTree.Expression) => expression;
callbacks.onComponentReturns?.([node.body], resolve);
callbacks.onReturnExpression?.(node.body, resolve);
@@ -531,6 +538,7 @@ export function createComponentReturnExpressionVisitors(
});
}
if (!returnExpressions.some(expressionReturnsJsxOrNull)) return;
+ callbacks.onComponentFunction?.(node);
callbacks.onComponentReturns?.(returnExpressions, resolve);
if (!callbacks.onReturnExpression) return;
for (const expression of returnExpressions) {
diff --git a/packages/eslint-plugin/src/rules/no-let-assign-in-react.test.ts b/packages/eslint-plugin/src/rules/no-let-assign-in-react.test.ts
new file mode 100644
index 0000000000..f0682fab16
--- /dev/null
+++ b/packages/eslint-plugin/src/rules/no-let-assign-in-react.test.ts
@@ -0,0 +1,80 @@
+import { RuleTester } from "@typescript-eslint/rule-tester";
+import * as typescriptEslintParser from "@typescript-eslint/parser";
+import rule from "./no-let-assign-in-react.js";
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ parser: typescriptEslintParser,
+ parserOptions: { ecmaFeatures: { jsx: true } },
+ },
+});
+
+ruleTester.run("no-let-assign-in-react", rule, {
+ valid: [
+ `function Card() { let x = 0; return <div>{x}</div>; }`,
+ `function calculate() { let x = 0; x = 1; return x; }`,
+ `function Card() { const x = useMemo(() => { let value = 0; if (condition) value = 1; return value; }, [condition]); return <div>{x}</div>; }`,
+ `function Card() { let x = 0; const click = () => { x++; }; useEffect(() => { x = 1; }, []); return <button onClick={click}>{x}</button>; }`,
+ `function Card() { let x = 0; function helper() { x = 1; let y = 0; y++; } return <div>{x}</div>; }`,
+ `function Card() { const x = {}; x.value = 1; return <div />; }`,
+ `function Card() { let x = {}; x.value = 1; return <div />; }`,
+ `let x = 0; function Card() { x = 1; return <div />; }`,
+ `function Card(x) { x = 1; return <div />; }`,
+ `function Card() { var x = 0; x = 1; return <div />; }`,
+ `function Card() { let x = 0; { const x = {}; x.value = 1; } return <div>{x}</div>; }`,
+ `function Card() { for (let x of values) { consume(x); } return <div />; }`,
+ `function Card() { for (let x = 0; x < 3; x++) {} return <div />; }`,
+ `function Card() { for (let x = 3; x > 0; --x) {} return <div />; }`,
+ `function Card() { for (let x = 0; x < 3; x += 2) {} return <div />; }`,
+ `function Card() { for (let x = 0; x < 3; x = x + 1) {} return <div />; }`,
+ `function Card() { for (let x = 0, y = 3; x < y; x++, y--) {} return <div />; }`,
+ ],
+ invalid: [
+ ...[
+ `function Card() { let x; if (condition) x = 1; return <div>{x}</div>; }`,
+ `function Card() { let x = 0; x = 1; return <div>{x}</div>; }`,
+ `const Card = () => { let x = 0; x += 1; return <div>{x}</div>; };`,
+ `const Card = function () { let x = 0; x++; return <div>{x}</div>; };`,
+ `export default function () { let x = 0; --x; return <div>{x}</div>; }`,
+ `const Card = memo(() => { let x = 0; x ||= 1; return <div />; });`,
+ `const Card = React.forwardRef(() => { let x = 0; x ??= 1; return <div />; });`,
+ `const Card = (() => { let x = 0; x &&= 1; return <div />; }) satisfies React.FC;`,
+ `function Card() { if (condition) { let x = 0; x = 1; } return <div />; }`,
+ `function Card() { let x = 0; { x = 1; } return <div />; }`,
+ `function Card() { let { x } = props; ({ x } = other); return <div />; }`,
+ `function Card() { let [x] = values; [x] = other; return <div />; }`,
+ `function Card() { for (let x = 0; x < 3; x++) { x = 1; } return <div />; }`,
+ `function Card() { let x = 0; for (let i = 0; i < 3; i++, x++) {} return <div />; }`,
+ `function Card() { let x = 0; for (; x < 3; x++) {} return <div />; }`,
+ `function Card() { let x = 0; for (let i = 0; i < 3; i++) { x += i; } return <div />; }`,
+ `function Card() { let x; for (x of values) {} return <div />; }`,
+ `function Card() { let x = 0; return <div>{x = 1}</div>; }`,
+ `function Card() { let x = 0; x = 1; return null; }`,
+ `export default memo(() => { let x = 0; x = 1; return <div />; });`,
+ `function Card() { let x = 0; x = 1; const view = <div />; return view; }`,
+ ].map((code) => ({
+ code,
+ errors: [
+ { messageId: "unexpectedReassignment" as const, data: { name: "x" } },
+ ],
+ })),
+ {
+ code: `function Card() { let x = 0; if (condition) x = 1; else x = 2; return <div />; }`,
+ errors: [
+ { messageId: "unexpectedReassignment", data: { name: "x" } },
+ { messageId: "unexpectedReassignment", data: { name: "x" } },
+ ],
+ },
+ {
+ code: `function Card() { let x = 0; { let x = 1; x++; } x++; return <div />; }`,
+ errors: [
+ { messageId: "unexpectedReassignment", data: { name: "x" } },
+ { messageId: "unexpectedReassignment", data: { name: "x" } },
+ ],
+ },
+ {
+ code: `function Card() { function Child() { let x = 0; x++; return <span />; } return <Child />; }`,
+ errors: [{ messageId: "unexpectedReassignment", data: { name: "x" } }],
+ },
+ ],
+});
diff --git a/packages/eslint-plugin/src/rules/no-let-assign-in-react.ts b/packages/eslint-plugin/src/rules/no-let-assign-in-react.ts
new file mode 100644
index 0000000000..7984cc50f2
--- /dev/null
+++ b/packages/eslint-plugin/src/rules/no-let-assign-in-react.ts
@@ -0,0 +1,88 @@
+import { AST_NODE_TYPES, type TSESTree } from "@typescript-eslint/utils";
+
+import { createComponentReturnExpressionVisitors } from "../react-components.js";
+import { createRule } from "../util.js";
+
+const rule = createRule({
+ name: "no-let-assign-in-react",
+ meta: {
+ type: "suggestion",
+ docs: {
+ description:
+ "Disallow render-time reassignment of let variables in React components.",
+ },
+ schema: [],
+ messages: {
+ unexpectedReassignment:
+ "Do not reassign let variable '{{name}}' during render. Compute the value with useMemo and assign it to a const instead.",
+ },
+ },
+ defaultOptions: [],
+ create(context) {
+ const components = new Set<
+ | TSESTree.ArrowFunctionExpression
+ | TSESTree.FunctionDeclaration
+ | TSESTree.FunctionExpression
+ >();
+
+ return {
+ ...createComponentReturnExpressionVisitors({
+ onComponentFunction(node) {
+ components.add(node);
+ },
+ }),
+ "Program:exit"() {
+ for (const component of components) {
+ const functionScope = context.sourceCode.getScope(component.body);
+ const scopes = [functionScope];
+ for (const scope of scopes) {
+ scopes.push(
+ ...scope.childScopes.filter(
+ (child) => child.variableScope === functionScope,
+ ),
+ );
+ for (const variable of scope.variables) {
+ const isLet = variable.defs.some(
+ (definition) =>
+ definition.type === "Variable" &&
+ definition.parent?.type ===
+ AST_NODE_TYPES.VariableDeclaration &&
+ definition.parent.kind === "let",
+ );
+ if (!isLet) continue;
+ const counterLoop = variable.defs
+ .map((definition) => definition.parent?.parent)
+ .find(
+ (node) =>
+ node?.type === AST_NODE_TYPES.ForStatement &&
+ variable.defs.some(
+ (definition) => definition.parent === node.init,
+ ),
+ );
+ for (const reference of variable.references) {
+ if (!reference.isWrite() || reference.init) continue;
+ if (reference.from.variableScope !== functionScope) continue;
+ if (
+ counterLoop?.type === AST_NODE_TYPES.ForStatement &&
+ counterLoop.update &&
+ reference.identifier.range[0] >=
+ counterLoop.update.range[0] &&
+ reference.identifier.range[1] <= counterLoop.update.range[1]
+ ) {
+ continue;
+ }
+ context.report({
+ node: reference.identifier,
+ messageId: "unexpectedReassignment",
+ data: { name: variable.name },
+ });
+ }
+ }
+ }
+ }
+ },
+ };
+ },
+});
+
+export default rule;
diff --git a/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsx b/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsx
index 1a0bf41829..2907ff4d9a 100644
--- a/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsx
+++ b/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsx
@@ -53,19 +53,17 @@ function ConfirmationDialogController<TValue = undefined>({
const confirmationInputId = React.useId();
const requiresConfirmationInput = Boolean(confirmationText);
- let resolvedTitle = "";
- if (typeof title === "string") {
- resolvedTitle = title;
- } else if (selectedValue !== undefined) {
- resolvedTitle = (title as (value: TValue) => string)(selectedValue);
- }
+ const resolvedTitle = React.useMemo(() => {
+ if (typeof title === "string") return title;
+ if (selectedValue === undefined) return "";
+ return (title as (value: TValue) => string)(selectedValue);
+ }, [title, selectedValue]);
- let resolvedText = "";
- if (typeof text === "string") {
- resolvedText = text;
- } else if (selectedValue !== undefined) {
- resolvedText = (text as (value: TValue) => string)(selectedValue);
- }
+ const resolvedText = React.useMemo(() => {
+ if (typeof text === "string") return text;
+ if (selectedValue === undefined) return "";
+ return (text as (value: TValue) => string)(selectedValue);
+ }, [text, selectedValue]);
return (
<DialogController
diff --git a/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx b/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
index ee602ccc6f..5ba2ec7616 100644
--- a/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
+++ b/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import preview from "../../../../../.storybook/preview";
import { expect, fireEvent, userEvent, waitFor, within } from "storybook/test";
import { AreaChart } from "./AreaChart";
@@ -48,6 +48,16 @@ function AreaChartDemo({
legend,
}: StoryProps) {
const [activeKey, setActiveKey] = useState<string>();
+ const chartData = useMemo(() => {
+ if (scenario === "gaps") return gaps;
+ if (scenario === "negative") {
+ return data.map((datum, index) => ({
+ ...datum,
+ values: { api: index * 3 - 18, worker: 12 - index * 2 },
+ }));
+ }
+ return data;
+ }, [scenario]);
if (scenario === "mixedBuckets") {
const mixedData = [
{ time_dimension: "2026-09-01", dimension: "api", metric: 12 },
@@ -112,18 +122,6 @@ function AreaChartDemo({
);
}
- let chartData: {
- x: Date;
- values: { api: number | null; worker: number | null };
- }[] = data;
- if (scenario === "gaps") chartData = gaps;
- else if (scenario === "negative") {
- chartData = data.map((datum, index) => ({
- ...datum,
- values: { api: index * 3 - 18, worker: 12 - index * 2 },
- }));
- }
-
return (
<AreaChart
data={chartData}
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
index ce90209927..45520b7ab3 100644
--- a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
+++ b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from "react";
import preview from "../../../../../.storybook/preview";
import { expect, fireEvent, userEvent, waitFor, within } from "storybook/test";
import {
@@ -26,15 +27,26 @@ type LineChartStoryProps = {
};
const LineChartDemo = (props: LineChartStoryProps) => {
+ const chartData = useMemo(() => {
+ if (props.variant === "many-lines") return manyLinesData;
+ if (props.variant === "boundary-points") return boundaryPointData;
+ if (props.variant === "negative-values") return negativeData;
+ if (props.variant === "intermittent") return intermittentData;
+ if (props.variant === "intraday") return intradayData;
+ if (props.variant === "year-boundary") return yearBoundaryData;
+ if (props.variant === "monthly") return monthlyData;
+ if (props.variant === "empty") return [];
+ return data;
+ }, [props.variant]);
if (
props.variant === "category-short-labels" ||
props.variant === "category-long-labels" ||
props.variant === "category-hidden-labels"
) {
- let categoryChartData = categoryData;
- if (props.variant === "category-short-labels") {
- categoryChartData = shortCategoryData;
- }
+ const categoryChartData =
+ props.variant === "category-short-labels"
+ ? shortCategoryData
+ : categoryData;
return (
<LineChart
data={categoryChartData}
@@ -48,18 +60,6 @@ const LineChartDemo = (props: LineChartStoryProps) => {
);
}
- let chartData: Array<{
- x: Date;
- values: Record<string, number | null>;
- }> = data;
- if (props.variant === "many-lines") chartData = manyLinesData;
- if (props.variant === "boundary-points") chartData = boundaryPointData;
- if (props.variant === "negative-values") chartData = negativeData;
- if (props.variant === "intermittent") chartData = intermittentData;
- if (props.variant === "intraday") chartData = intradayData;
- if (props.variant === "year-boundary") chartData = yearBoundaryData;
- if (props.variant === "monthly") chartData = monthlyData;
- if (props.variant === "empty") chartData = [];
const chartSeries = props.variant === "many-lines" ? manyLinesSeries : series;
return (
diff --git a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx
index e29c57ac18..b466ab75db 100644
--- a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx
+++ b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx
@@ -1,6 +1,6 @@
import { Slot } from "@radix-ui/react-slot";
import { Check, Search as SearchIcon } from "lucide-react";
-import { type ComponentPropsWithoutRef, type ReactNode } from "react";
+import { type ComponentPropsWithoutRef, type ReactNode, useMemo } from "react";
import { useScrollGradients } from "@/src/hooks/useScrollGradients";
import { cn } from "@/src/utils/tailwind";
@@ -122,29 +122,39 @@ function OptionContent({
type: "checkbox" | "checkmark" | "radio";
checked: boolean;
}) {
- let indicator = (
- <Check
- aria-hidden="true"
- className={cn("size-4", checked ? "opacity-100" : "opacity-0")}
- />
- );
- if (type === "checkbox") {
- indicator = (
- <Checkbox checked={checked} size="sm" tabIndex={-1} aria-hidden="true" />
- );
- } else if (type === "radio") {
- indicator = (
- <span
+ const indicator = useMemo(() => {
+ if (type === "checkbox") {
+ return (
+ <Checkbox
+ checked={checked}
+ size="sm"
+ tabIndex={-1}
+ aria-hidden="true"
+ />
+ );
+ }
+ if (type === "radio") {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn(
+ "border-control-border flex size-3.5 items-center justify-center rounded-full border shadow-sm",
+ checked && "border-control-fill",
+ )}
+ >
+ {checked && (
+ <span className="bg-control-fill size-1.5 rounded-full" />
+ )}
+ </span>
+ );
+ }
+ return (
+ <Check
aria-hidden="true"
- className={cn(
- "border-control-border flex size-3.5 items-center justify-center rounded-full border shadow-sm",
- checked && "border-control-fill",
- )}
- >
- {checked && <span className="bg-control-fill size-1.5 rounded-full" />}
- </span>
+ className={cn("size-4", checked ? "opacity-100" : "opacity-0")}
+ />
);
- }
+ }, [type, checked]);
return (
<>
diff --git a/web/src/components/design-system/internal/charts/ChartTooltip.tsx b/web/src/components/design-system/internal/charts/ChartTooltip.tsx
index 854b15ac04..69f7c43f1e 100644
--- a/web/src/components/design-system/internal/charts/ChartTooltip.tsx
+++ b/web/src/components/design-system/internal/charts/ChartTooltip.tsx
@@ -13,6 +13,7 @@ import {
Fragment,
useEffect,
useLayoutEffect,
+ useMemo,
useRef,
useState,
type FocusEvent,
@@ -136,20 +137,28 @@ export function ChartTooltip({
const chartAnchored =
placementStrategy === "chart-bottom" &&
activeTooltip?.anchor.type === "chart-column";
- let fallbackPlacements: Array<"top" | "bottom" | "left" | "right"> = [
- "bottom",
- "left",
- "right",
- ];
- if (placementStrategy === "horizontal") {
- fallbackPlacements = ["left", "top", "bottom"];
- } else if (chartAnchored) {
- fallbackPlacements = [activeTooltip.side === "top" ? "bottom" : "top"];
- }
- let placement: "top" | "bottom" | "left" | "right" = "top";
- if (placementStrategy === "horizontal") placement = "right";
- if (chartAnchored) placement = activeTooltip.side ?? "bottom";
- if (activeTooltip?.placement) placement = activeTooltip.placement;
+ const fallbackPlacements = useMemo<
+ Array<"top" | "bottom" | "left" | "right">
+ >(() => {
+ if (placementStrategy === "horizontal") {
+ return ["left", "top", "bottom"];
+ }
+ if (chartAnchored) {
+ return [activeTooltip?.side === "top" ? "bottom" : "top"];
+ }
+ return ["bottom", "left", "right"];
+ }, [placementStrategy, chartAnchored, activeTooltip?.side]);
+ const placement = useMemo<"top" | "bottom" | "left" | "right">(() => {
+ if (activeTooltip?.placement) return activeTooltip.placement;
+ if (chartAnchored) return activeTooltip?.side ?? "bottom";
+ if (placementStrategy === "horizontal") return "right";
+ return "top";
+ }, [
+ activeTooltip?.placement,
+ activeTooltip?.side,
+ chartAnchored,
+ placementStrategy,
+ ]);
const { floatingStyles, refs } = useFloating({
elements: { reference: activeTooltip?.reference },
placement,
@@ -383,40 +392,43 @@ export function ChartTooltip({
};
};
- const tooltipRows: Array<
- TooltipItem & {
- id: string;
- emphasis: "default" | "emphasized" | "dimmed";
- kind: "peer" | "primary" | "detail";
- }
- > = [];
- if (activeTooltip?.type === "items") {
- for (const item of activeTooltip.items) {
- let emphasis: "default" | "emphasized" | "dimmed" = "dimmed";
- if (activeTooltip.emphasizedItemId === undefined) emphasis = "default";
- else if (activeTooltip.emphasizedItemId === item.id) {
- emphasis = "emphasized";
+ const tooltipRows = useMemo(() => {
+ const tooltipRows: Array<
+ TooltipItem & {
+ id: string;
+ emphasis: "default" | "emphasized" | "dimmed";
+ kind: "peer" | "primary" | "detail";
+ }
+ > = [];
+ if (activeTooltip?.type === "items") {
+ for (const item of activeTooltip.items) {
+ let emphasis: "default" | "emphasized" | "dimmed" = "dimmed";
+ if (activeTooltip.emphasizedItemId === undefined) emphasis = "default";
+ else if (activeTooltip.emphasizedItemId === item.id) {
+ emphasis = "emphasized";
+ }
+ tooltipRows.push({ ...item, emphasis, kind: "peer" });
}
- tooltipRows.push({ ...item, emphasis, kind: "peer" });
+ } else if (activeTooltip?.type === "primary") {
+ tooltipRows.push({
+ id: "primary",
+ label: activeTooltip.label,
+ value: activeTooltip.value,
+ color: activeTooltip.color,
+ emphasis: "default",
+ kind: "primary",
+ });
+ tooltipRows.push(
+ ...(activeTooltip.details ?? []).map((item, index) => ({
+ ...item,
+ id: `detail-${index}`,
+ emphasis: "default" as const,
+ kind: "detail" as const,
+ })),
+ );
}
- } else if (activeTooltip?.type === "primary") {
- tooltipRows.push({
- id: "primary",
- label: activeTooltip.label,
- value: activeTooltip.value,
- color: activeTooltip.color,
- emphasis: "default",
- kind: "primary",
- });
- tooltipRows.push(
- ...(activeTooltip.details ?? []).map((item, index) => ({
- ...item,
- id: `detail-${index}`,
- emphasis: "default" as const,
- kind: "detail" as const,
- })),
- );
- }
+ return tooltipRows;
+ }, [activeTooltip]);
const activeCopyStatus =
copyFeedback?.index === activeTooltip?.index
diff --git a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
index e0c0c558d1..6afe7d9fe7 100644
--- a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
+++ b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
@@ -195,19 +195,21 @@ function useLineChartLegend(
hiddenSeriesIds: new Set(hidden ? series.map((item) => item.id) : []),
});
};
- const configuredSeries: ConfiguredLineChartSeries[] = series.flatMap(
- (item) => {
- if (hiddenSeriesIds.has(item.id)) return [];
- let emphasis: ConfiguredLineChartSeries["emphasis"] = "dimmed";
- if (highlightedSeriesId === undefined) emphasis = "default";
- else if (highlightedSeriesId === item.id) emphasis = "emphasized";
- return [
- {
- ...item,
- emphasis,
- },
- ];
- },
+ const configuredSeries = useMemo(
+ () =>
+ series.flatMap<ConfiguredLineChartSeries>((item) => {
+ if (hiddenSeriesIds.has(item.id)) return [];
+ let emphasis: ConfiguredLineChartSeries["emphasis"] = "dimmed";
+ if (highlightedSeriesId === undefined) emphasis = "default";
+ else if (highlightedSeriesId === item.id) emphasis = "emphasized";
+ return [
+ {
+ ...item,
+ emphasis,
+ },
+ ];
+ }),
+ [series, hiddenSeriesIds, highlightedSeriesId],
);
return {
@@ -329,10 +331,14 @@ export function SeriesChartCore(
items={series.map((item) => {
const hidden = hiddenSeriesIds.has(item.id);
const focused = highlightedSeriesId === item.id;
- let label = `Show only ${item.label}`;
- if (legend.interaction === "toggle") {
- label = hidden ? `Show ${item.label}` : `Hide ${item.label}`;
- } else if (focused) label = "Show all series";
+ const toggleLabel = hidden
+ ? `Show ${item.label}`
+ : `Hide ${item.label}`;
+ const highlightLabel = focused
+ ? "Show all series"
+ : `Show only ${item.label}`;
+ const label =
+ legend.interaction === "toggle" ? toggleLabel : highlightLabel;
return {
id: item.id,
label: item.label,
@@ -698,15 +704,16 @@ function LineChartContent(
const hasConfiguredEmphasis = series.some(
(item) => item.emphasis && item.emphasis !== "default",
);
- const configuredEmphasizedSeries = series.filter(
- (item) => item.emphasis === "emphasized",
- );
- let activeSeriesId: string | undefined;
- if (configuredEmphasizedSeries.length === 1) {
- activeSeriesId = configuredEmphasizedSeries[0]?.id;
- } else if (!hasConfiguredEmphasis) {
- activeSeriesId = hoveredSeriesId;
- }
+ const activeSeriesId = useMemo(() => {
+ const configuredEmphasizedSeries = series.filter(
+ (item) => item.emphasis === "emphasized",
+ );
+ if (configuredEmphasizedSeries.length === 1) {
+ return configuredEmphasizedSeries[0]?.id;
+ }
+ if (!hasConfiguredEmphasis) return hoveredSeriesId;
+ return undefined;
+ }, [series, hasConfiguredEmphasis, hoveredSeriesId]);
if (width <= 0 || height <= 0 || plotWidth <= 0 || plotHeight <= 0) {
return <svg width={width} height={height} aria-hidden="true" />;
diff --git a/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx b/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx
index 5cd00f893a..28cc670f90 100644
--- a/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx
+++ b/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx
@@ -10,7 +10,14 @@ import {
type MediaDescriptor,
} from "@/src/components/ui/media/mediaUtils";
import { cn } from "@/src/utils/tailwind";
-import { Fragment, memo, useRef, useState, type ReactNode } from "react";
+import {
+ Fragment,
+ memo,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import {
HoverCard,
HoverCardContent,
@@ -124,20 +131,6 @@ export const IOTableCell = memo(function IOTableCell({
const [isPointerOverMediaTag, setIsPointerOverMediaTag] = useState(false);
const isPointerOverMediaTagRef = useRef(false);
- if (state.isLoading) {
- return (
- <JsonSkeleton
- borderless
- numRows={singleLine ? 1 : undefined}
- className={cn(
- "h-full w-full overflow-hidden rounded-sm",
- paddingClassName,
- variantClassName,
- )}
- />
- );
- }
-
const { data } = state;
const stringifiedJson =
data !== null && data !== undefined ? stringifyJsonNode(data) : undefined;
@@ -151,78 +144,83 @@ export const IOTableCell = memo(function IOTableCell({
// marked `scrollbar-visible`: a region that scrolls without ever painting a
// scrollbar is indistinguishable from one whose content was cut off, and
// nobody reaches for the wheel on content they read as truncated.
- let content: ReactNode;
- if (!stringifiedJson) {
- // The payload arrived and is empty. Handing that to the JSON viewer renders
- // the word `null` (or a bare pair of quotes), which a reader takes for a
- // value, and a blank cell says nothing at all — so it gets the shared
- // empty treatment. A payload that is only PARTLY empty is untouched: a
- // `null` nested in a document is content and still renders as `null`.
- content = (
- <div
- className={cn(
- "h-full w-full self-stretch rounded-sm",
- paddingClassName,
- variantClassName,
- )}
- >
- <EmptyValue />
- </div>
- );
- } else if (singleLine) {
- content = (
- <div
- className={cn(
- "ph-no-capture h-full w-full self-stretch truncate overflow-hidden overflow-y-auto rounded-sm",
- paddingClassName,
- variantClassName,
- )}
- title={
- enableExpandOnHover || isPointerOverMediaTag
- ? undefined
- : singleLineText
- }
- onPointerOver={
- enableExpandOnHover
- ? undefined
- : (event) =>
- setIsPointerOverMediaTag(
- Boolean(
- (event.target as Element).closest("[data-media-tag]"),
- ),
- )
- }
- >
- {renderStringWithMediaReferences(singleLineText, renderMediaReference)}
- </div>
- );
- } else if (shouldTruncate) {
- content = (
- <div className="grid h-full grid-cols-1">
- <JSONView
- json={decodeUnicodeEscapesOnly(
- stringifiedJson.slice(0, IO_TABLE_CHAR_LIMIT) +
- `...[truncated ${stringifiedJson.length - IO_TABLE_CHAR_LIMIT} characters]`,
- true,
- )}
+ const content = useMemo(() => {
+ if (!stringifiedJson) {
+ // The payload arrived and is empty. Handing that to the JSON viewer renders
+ // the word `null` (or a bare pair of quotes), which a reader takes for a
+ // value, and a blank cell says nothing at all — so it gets the shared
+ // empty treatment. A payload that is only PARTLY empty is untouched: a
+ // `null` nested in a document is content and still renders as `null`.
+ return (
+ <div
className={cn(
- "h-full w-full self-stretch overflow-hidden rounded-sm",
+ "h-full w-full self-stretch rounded-sm",
+ paddingClassName,
variantClassName,
)}
- codeClassName={cn(
- "scrollbar-visible min-h-0 h-full overflow-y-auto",
+ >
+ <EmptyValue />
+ </div>
+ );
+ }
+ if (singleLine) {
+ return (
+ <div
+ className={cn(
+ "ph-no-capture h-full w-full self-stretch truncate overflow-hidden overflow-y-auto rounded-sm",
paddingClassName,
+ variantClassName,
+ )}
+ title={
+ enableExpandOnHover || isPointerOverMediaTag
+ ? undefined
+ : singleLineText
+ }
+ onPointerOver={
+ enableExpandOnHover
+ ? undefined
+ : (event) =>
+ setIsPointerOverMediaTag(
+ Boolean(
+ (event.target as Element).closest("[data-media-tag]"),
+ ),
+ )
+ }
+ >
+ {renderStringWithMediaReferences(
+ singleLineText,
+ renderMediaReference,
)}
- collapseStringsAfterLength={null}
- borderless
- />
- <div className="text-muted-foreground text-xs">
- Content was truncated.
</div>
- </div>
- );
- } else {
- content = (
+ );
+ }
+ if (shouldTruncate) {
+ return (
+ <div className="grid h-full grid-cols-1">
+ <JSONView
+ json={decodeUnicodeEscapesOnly(
+ stringifiedJson.slice(0, IO_TABLE_CHAR_LIMIT) +
+ `...[truncated ${stringifiedJson.length - IO_TABLE_CHAR_LIMIT} characters]`,
+ true,
+ )}
+ className={cn(
+ "h-full w-full self-stretch overflow-hidden rounded-sm",
+ variantClassName,
+ )}
+ codeClassName={cn(
+ "scrollbar-visible min-h-0 h-full overflow-y-auto",
+ paddingClassName,
+ )}
+ collapseStringsAfterLength={null}
+ borderless
+ />
+ <div className="text-muted-foreground text-xs">
+ Content was truncated.
+ </div>
+ </div>
+ );
+ }
+ return (
<JSONView
json={decodeUnicodeEscapesOnly(stringifiedJson, true)}
className={cn(
@@ -237,6 +235,30 @@ export const IOTableCell = memo(function IOTableCell({
borderless
/>
);
+ }, [
+ stringifiedJson,
+ singleLine,
+ shouldTruncate,
+ paddingClassName,
+ variantClassName,
+ enableExpandOnHover,
+ isPointerOverMediaTag,
+ singleLineText,
+ renderMediaReference,
+ ]);
+
+ if (state.isLoading) {
+ return (
+ <JsonSkeleton
+ borderless
+ numRows={singleLine ? 1 : undefined}
+ className={cn(
+ "h-full w-full overflow-hidden rounded-sm",
+ paddingClassName,
+ variantClassName,
+ )}
+ />
+ );
}
// The expand card renders `data` itself, so an empty payload would come back
diff --git a/web/src/components/ui/LangfuseMediaView.tsx b/web/src/components/ui/LangfuseMediaView.tsx
index f44a23f42f..41046be8a0 100644
--- a/web/src/components/ui/LangfuseMediaView.tsx
+++ b/web/src/components/ui/LangfuseMediaView.tsx
@@ -1,7 +1,7 @@
/* eslint-disable @repo/no-null-render */
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { Button } from "@/src/components/ui/button";
import { ImageOff, ExternalLink } from "lucide-react";
@@ -42,39 +42,43 @@ export const LangfuseMediaView = ({
// Non-previewable types (e.g. PDF) are always a click-to-open icon.
variant?: "inline" | "icon" | "preview";
}) => {
- let mediaData: {
+ const mediaData = useMemo<{
id: string;
type: MediaContentType;
referenceString?: string;
source?: string;
- } | null = null;
+ } | null>(() => {
+ if (mediaReferenceString && typeof mediaReferenceString === "string") {
+ const { success, data: parsedTag } =
+ MediaReferenceStringSchema.safeParse(mediaReferenceString);
+ if (success)
+ return {
+ id: parsedTag.id,
+ type: parsedTag.type as MediaContentType,
+ referenceString: parsedTag.referenceString,
+ source: parsedTag.source,
+ };
+ } else if (
+ mediaReferenceString &&
+ typeof mediaReferenceString !== "string"
+ ) {
+ return {
+ id: mediaReferenceString.id,
+ type: mediaReferenceString.type as MediaContentType,
+ referenceString: mediaReferenceString.referenceString,
+ source: mediaReferenceString.source,
+ };
+ } else if (mediaAPIReturnValue) {
+ return {
+ id: mediaAPIReturnValue.mediaId,
+ type: mediaAPIReturnValue.contentType,
+ };
+ }
+ return null;
+ }, [mediaReferenceString, mediaAPIReturnValue]);
const projectId = useProjectIdFromURL();
- if (mediaReferenceString && typeof mediaReferenceString === "string") {
- const { success, data: parsedTag } =
- MediaReferenceStringSchema.safeParse(mediaReferenceString);
- if (success)
- mediaData = {
- id: parsedTag.id,
- type: parsedTag.type as MediaContentType,
- referenceString: parsedTag.referenceString,
- source: parsedTag.source,
- };
- } else if (mediaReferenceString && typeof mediaReferenceString !== "string") {
- mediaData = {
- id: mediaReferenceString.id,
- type: mediaReferenceString.type as MediaContentType,
- referenceString: mediaReferenceString.referenceString,
- source: mediaReferenceString.source,
- };
- } else if (mediaAPIReturnValue) {
- mediaData = {
- id: mediaAPIReturnValue.mediaId,
- type: mediaAPIReturnValue.contentType,
- };
- }
-
if (!mediaData) {
const text = "Invalid Langfuse Media Tag";
diff --git a/web/src/components/ui/dropdown-menu.tsx b/web/src/components/ui/dropdown-menu.tsx
index 34833eb954..0fd0dd2b91 100644
--- a/web/src/components/ui/dropdown-menu.tsx
+++ b/web/src/components/ui/dropdown-menu.tsx
@@ -391,13 +391,12 @@ const DropdownMenuItemWithSecondaryAction = (
</span>
</>
);
- let secondaryActionContent: React.ReactNode = null;
-
- // The secondary action is intentionally pointer-only and cannot be targeted
- // with the keyboard; the parent remains the row's sole menu item.
- if (secondaryAction && SecondaryActionIcon) {
+ const secondaryActionContent = React.useMemo(() => {
+ // The secondary action is intentionally pointer-only and cannot be targeted
+ // with the keyboard; the parent remains the row's sole menu item.
+ if (!secondaryAction || !SecondaryActionIcon) return null;
if (secondaryAction.href !== undefined) {
- secondaryActionContent = (
+ return (
<Link
href={secondaryAction.href}
target={secondaryAction.target}
@@ -428,24 +427,23 @@ const DropdownMenuItemWithSecondaryAction = (
<SecondaryActionIcon size={12} />
</Link>
);
- } else {
- secondaryActionContent = (
- <button
- type="button"
- aria-label={secondaryAction.ariaLabel}
- disabled={isDisabled}
- className={dropdownMenuItemSecondaryActionVariants()}
- onClick={(event) => {
- event.stopPropagation();
- secondaryAction.onBeforeAction?.();
- secondaryAction.onClick();
- }}
- >
- <SecondaryActionIcon size={12} />
- </button>
- );
}
- }
+ return (
+ <button
+ type="button"
+ aria-label={secondaryAction.ariaLabel}
+ disabled={isDisabled}
+ className={dropdownMenuItemSecondaryActionVariants()}
+ onClick={(event) => {
+ event.stopPropagation();
+ secondaryAction.onBeforeAction?.();
+ secondaryAction.onClick();
+ }}
+ >
+ <SecondaryActionIcon size={12} />
+ </button>
+ );
+ }, [secondaryAction, SecondaryActionIcon, isDisabled]);
return (
<DropdownMenuItem
diff --git a/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx b/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx
index 806d682fdf..c0b12c0262 100644
--- a/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx
+++ b/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
import { type AsyncTableData } from "@/src/components/design-system/table/Table";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
@@ -46,17 +46,16 @@ export function ConnectedVerifiedDomainsSettingsTable({
onError: (err) => showErrorToast("Failed to remove domain", err.message),
});
- let data: AsyncTableData<DomainRowData[]> = {
- status: "success",
- data: query.data ?? [],
- };
- if (query.isLoading) data = { status: "loading" };
- if (query.isError) {
- data = {
- status: "error",
- error: "Failed to load verified domains. Please try again.",
- };
- }
+ const data = useMemo<AsyncTableData<DomainRowData[]>>(() => {
+ if (query.isError) {
+ return {
+ status: "error",
+ error: "Failed to load verified domains. Please try again.",
+ };
+ }
+ if (query.isLoading) return { status: "loading" };
+ return { status: "success", data: query.data ?? [] };
+ }, [query.isError, query.isLoading, query.data]);
return (
<ConfirmationDialogController<DomainRowData>
diff --git a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
index 9fb452d3ae..63054468be 100644
--- a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
+++ b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
@@ -84,15 +84,11 @@ function BaselineToggle({ runId }: { runId: string }) {
justSetBaselineRef.current = false;
};
- let text: string;
- if (!hasBaseline) {
- text = "Set as baseline";
- } else if (isBaseline) {
- text =
- isHovered && !justSetBaselineRef.current ? "Clear baseline" : "Baseline";
- } else {
- text = isHovered ? "Set as baseline" : "Comparison";
- }
+ const baselineText =
+ isHovered && !justSetBaselineRef.current ? "Clear baseline" : "Baseline";
+ const comparisonText = isHovered ? "Set as baseline" : "Comparison";
+ const selectedText = isBaseline ? baselineText : comparisonText;
+ const text = hasBaseline ? selectedText : "Set as baseline";
return (
<Toggle
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorStatusBadge/EvaluatorStatusBadge.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorStatusBadge/EvaluatorStatusBadge.tsx
index 7492de8779..92a572cb12 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorStatusBadge/EvaluatorStatusBadge.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorStatusBadge/EvaluatorStatusBadge.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from "react";
import Link from "next/link";
import {
getEvaluatorBlockMetadata,
@@ -55,24 +56,29 @@ export function EvaluatorStatusBadge({
executionsHref: string | null;
}) {
const status = getStatus({ ruleCount, summary, blocked });
- let explanation: string;
- if (status === "Blocked") {
- explanation =
- blockMessage ??
- (blockReason
- ? getEvaluatorBlockMetadata(blockReason).message
- : "This evaluator is blocked.");
- } else if (ruleCount === 0) {
- explanation = "No rule is attached to this evaluator.";
- } else if (status === "Unknown") {
- explanation = "Execution status is unavailable.";
- } else if (status === "Inactive") {
- explanation = "No execution traces in the last 7 days.";
- } else if (status === "Healthy") {
- explanation = "All runs passed in the last 7 days.";
- } else {
- explanation = `${summary?.failed} of ${summary?.total} execution traces failed in the last 7 days.`;
- }
+ const explanation = useMemo(() => {
+ if (status === "Blocked") {
+ return (
+ blockMessage ??
+ (blockReason
+ ? getEvaluatorBlockMetadata(blockReason).message
+ : "This evaluator is blocked.")
+ );
+ }
+ if (ruleCount === 0) {
+ return "No rule is attached to this evaluator.";
+ }
+ if (status === "Unknown") {
+ return "Execution status is unavailable.";
+ }
+ if (status === "Inactive") {
+ return "No execution traces in the last 7 days.";
+ }
+ if (status === "Healthy") {
+ return "All runs passed in the last 7 days.";
+ }
+ return `${summary?.failed} of ${summary?.total} execution traces failed in the last 7 days.`;
+ }, [status, blockMessage, blockReason, ruleCount, summary]);
const badge = (
<Badge text={status === "Unknown" ? "—" : status} color={colors[status]} />
diff --git a/web/src/features/models/ModelDefinitionsTable/ConnectedModelDefinitionsTable.tsx b/web/src/features/models/ModelDefinitionsTable/ConnectedModelDefinitionsTable.tsx
index 9b544dde30..d7433668c2 100644
--- a/web/src/features/models/ModelDefinitionsTable/ConnectedModelDefinitionsTable.tsx
+++ b/web/src/features/models/ModelDefinitionsTable/ConnectedModelDefinitionsTable.tsx
@@ -1,6 +1,6 @@
import { useRouter } from "next/router";
import { FlaskConical, PlusIcon } from "lucide-react";
-import { useRef } from "react";
+import { useMemo, useRef } from "react";
import { StringParam, useQueryParams, withDefault } from "use-query-params";
import { type AsyncTableData } from "@/src/components/design-system/table/Table";
@@ -75,17 +75,18 @@ export function ConnectedModelDefinitionsTable({
scope: "models:CUD",
});
- let data: AsyncTableData<ModelTableRow[]>;
- if (models.isPending) {
- data = { status: "loading" };
- } else if (models.isError) {
- data = { status: "error", error: models.error.message };
- } else {
- data = {
+ const data = useMemo<AsyncTableData<ModelTableRow[]>>(() => {
+ if (models.isPending) {
+ return { status: "loading" };
+ }
+ if (models.isError) {
+ return { status: "error", error: models.error.message };
+ }
+ return {
status: "success",
data: (models.data?.models ?? []).map(convertToTableRow),
};
- }
+ }, [models.isPending, models.isError, models.error, models.data]);
return (
<DialogController
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index 3d0c1e016b..3d503b648f 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -1,6 +1,6 @@
import capitalize from "lodash/capitalize";
import router from "next/router";
-import { useState, useEffect, useRef } from "react";
+import { useState, useEffect, useMemo, useRef } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/src/components/ui/button";
import { Checkbox } from "@/src/components/design-system/Checkbox/Checkbox";
@@ -64,15 +64,16 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
const utils = api.useUtils();
const capture = usePostHogClientCapture();
- let initialPromptVariant: PromptVariant | null;
- try {
- initialPromptVariant = PromptVariantSchema.parse({
- type: initialPrompt?.type,
- prompt: initialPrompt?.prompt?.valueOf(),
- });
- } catch (_err) {
- initialPromptVariant = null;
- }
+ const initialPromptVariant = useMemo<PromptVariant | null>(() => {
+ try {
+ return PromptVariantSchema.parse({
+ type: initialPrompt?.type,
+ prompt: initialPrompt?.prompt?.valueOf(),
+ });
+ } catch (_err) {
+ return null;
+ }
+ }, [initialPrompt]);
const defaultValues = {
type: initialPromptVariant?.type ?? PromptType.Text,
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index 98a2fdec1c..5f7cb30b90 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -207,21 +207,28 @@ export const PromptDetail = ({
},
);
- let chatMessages: z.infer<typeof ChatMlArraySchema> | null = null;
- try {
- chatMessages = ChatMlArraySchema.parse(
- resolutionMode === "resolved"
- ? promptGraph.data?.resolvedPrompt
- : prompt?.prompt,
- );
- } catch (error) {
- if (PromptType.Chat === prompt?.type) {
- console.warn(
- "Could not parse returned chat prompt to pretty ChatML",
- error,
+ const chatMessages = useMemo<z.infer<typeof ChatMlArraySchema> | null>(() => {
+ try {
+ return ChatMlArraySchema.parse(
+ resolutionMode === "resolved"
+ ? promptGraph.data?.resolvedPrompt
+ : prompt?.prompt,
);
+ } catch (error) {
+ if (PromptType.Chat === prompt?.type) {
+ console.warn(
+ "Could not parse returned chat prompt to pretty ChatML",
+ error,
+ );
+ }
}
- }
+ return null;
+ }, [
+ resolutionMode,
+ promptGraph.data?.resolvedPrompt,
+ prompt?.prompt,
+ prompt?.type,
+ ]);
const utils = api.useUtils();
diff --git a/web/src/features/scores/components/AnnotationSaveStatus.tsx b/web/src/features/scores/components/AnnotationSaveStatus.tsx
index 7b5a994ca5..69908bc4a4 100644
--- a/web/src/features/scores/components/AnnotationSaveStatus.tsx
+++ b/web/src/features/scores/components/AnnotationSaveStatus.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from "react";
import { useFormState, useWatch, type UseFormReturn } from "react-hook-form";
import { useStore } from "zustand";
import { Check } from "lucide-react";
@@ -24,10 +25,12 @@ export function AnnotationSaveStatus({
state.confirmedFields.get(annotationFieldKey(field))?.field,
),
);
- let status: "idle" | "saving" | "saved" | "error" = "idle";
- if (state.pending) status = "saving";
- else if (state.failed) status = "error";
- else if (state.saved && !dirty && !errors.scoreData) status = "saved";
+ const status = useMemo(() => {
+ if (state.pending) return "saving";
+ if (state.failed) return "error";
+ if (state.saved && !dirty && !errors.scoreData) return "saved";
+ return "idle";
+ }, [state.pending, state.failed, state.saved, dirty, errors.scoreData]);
return (
<div className="grid items-center justify-items-end">
diff --git a/web/src/features/search-bar/components/ComposerTokens.tsx b/web/src/features/search-bar/components/ComposerTokens.tsx
index 120f3e1242..7d2af2cf33 100644
--- a/web/src/features/search-bar/components/ComposerTokens.tsx
+++ b/web/src/features/search-bar/components/ComposerTokens.tsx
@@ -144,76 +144,87 @@ export function ComposerTokens({
freeTextReason?: string | null;
registry?: FieldRegistry;
}): React.ReactNode {
- const segments = deriveComposerSegments(draft, scoreTypes, registry);
- const out: React.ReactNode[] = [];
- let cursor = 0;
- for (const segment of segments) {
- if (segment.from > cursor) {
- out.push(
- ...renderPlainText(draft.slice(cursor, segment.from), `ws:${cursor}`),
- );
- }
- const visibleKind: TokenKind =
- segment.kind === "invalid" && !showDiagnostics
- ? "freeText"
- : segment.kind;
- // "Not applied on this surface" — a filter column the chart can't honour,
- // or free text a chart ignores.
- const deactivated =
- deactivationReason(segment, fieldReason, freeTextReason) !== null;
- const highlighted = segment.id === highlightedSegmentId;
- // No native `title`: hover copy is the styled per-token tooltip that
- // SearchComposer positions (explanation, or the error once diagnostics are
- // revealed). A second, slower browser tooltip on top of it just doubles up.
- const content = (
- <>
- {segment.kind === "filter" ? (
- <FilterTokenBody segment={segment} />
- ) : (
- segment.raw
- )}
- {/* Word-joiner INSIDE the pill. The caret at the token's trailing edge
+ const out = React.useMemo(() => {
+ const segments = deriveComposerSegments(draft, scoreTypes, registry);
+ const out: React.ReactNode[] = [];
+ let cursor = 0;
+ for (const segment of segments) {
+ if (segment.from > cursor) {
+ out.push(
+ ...renderPlainText(draft.slice(cursor, segment.from), `ws:${cursor}`),
+ );
+ }
+ const visibleKind: TokenKind =
+ segment.kind === "invalid" && !showDiagnostics
+ ? "freeText"
+ : segment.kind;
+ // "Not applied on this surface" — a filter column the chart can't honour,
+ // or free text a chart ignores.
+ const deactivated =
+ deactivationReason(segment, fieldReason, freeTextReason) !== null;
+ const highlighted = segment.id === highlightedSegmentId;
+ // No native `title`: hover copy is the styled per-token tooltip that
+ // SearchComposer positions (explanation, or the error once diagnostics are
+ // revealed). A second, slower browser tooltip on top of it just doubles up.
+ const content = (
+ <>
+ {segment.kind === "filter" ? (
+ <FilterTokenBody segment={segment} />
+ ) : (
+ segment.raw
+ )}
+ {/* Word-joiner INSIDE the pill. The caret at the token's trailing edge
lands on this joiner, which sits BEFORE the pill's right padding — so
WebKit/Safari paints the caret inside the pill at the glyph instead
of past the chrome. A sibling joiner (outside the span) made Safari
paint the caret past the padding + margin (the "caret renders outside
the block" bug). */}
- {WORD_JOINER}
- </>
- );
- out.push(
- segment.kind === "filter" ? (
- <FilterToken
- key={segment.id}
- data-testid="search-bar-token"
- data-kind={visibleKind}
- data-segment-id={segment.id}
- deactivated={deactivated}
- highlighted={highlighted}
- >
- {content}
- </FilterToken>
- ) : (
- <span
- key={segment.id}
- data-testid="search-bar-token"
- data-kind={visibleKind}
- data-deactivated={deactivated || undefined}
- data-segment-id={segment.id}
- className={composerTokenVariants({
- kind: visibleKind,
- deactivated,
- highlighted,
- })}
- >
- {content}
- </span>
- ),
- );
- cursor = segment.to;
- }
- if (cursor < draft.length) {
- out.push(...renderPlainText(draft.slice(cursor), `tail:${cursor}`));
- }
+ {WORD_JOINER}
+ </>
+ );
+ out.push(
+ segment.kind === "filter" ? (
+ <FilterToken
+ key={segment.id}
+ data-testid="search-bar-token"
+ data-kind={visibleKind}
+ data-segment-id={segment.id}
+ deactivated={deactivated}
+ highlighted={highlighted}
+ >
+ {content}
+ </FilterToken>
+ ) : (
+ <span
+ key={segment.id}
+ data-testid="search-bar-token"
+ data-kind={visibleKind}
+ data-deactivated={deactivated || undefined}
+ data-segment-id={segment.id}
+ className={composerTokenVariants({
+ kind: visibleKind,
+ deactivated,
+ highlighted,
+ })}
+ >
+ {content}
+ </span>
+ ),
+ );
+ cursor = segment.to;
+ }
+ if (cursor < draft.length) {
+ out.push(...renderPlainText(draft.slice(cursor), `tail:${cursor}`));
+ }
+ return out;
+ }, [
+ draft,
+ scoreTypes,
+ registry,
+ showDiagnostics,
+ fieldReason,
+ freeTextReason,
+ highlightedSegmentId,
+ ]);
return <>{out}</>;
}
diff --git a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx
index ed97fba529..b6ce9fea6e 100644
--- a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx
+++ b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { type FilterState } from "@langfuse/shared";
import {
@@ -108,27 +108,37 @@ export function ConnectedModernSessionBodyTimeline({
filter.value,
);
- const traceIndexById = new Map(
- traces.map((trace, index) => [trace.id, index] as const),
+ const traceIndexById = useMemo(
+ () => new Map(traces.map((trace, index) => [trace.id, index] as const)),
+ [traces],
);
- const activeChunkIndices = new Set<number>();
- if (!searchQuery) {
- let highestChunkIndex = Math.min(
- loadedThroughChunkIndex,
- Math.ceil(traces.length / SIDEBAR_TRACE_CHUNK_SIZE) - 1,
- );
- for (const traceId of visibleTraceIds) {
- const traceIndex = traceIndexById.get(traceId);
- if (traceIndex === undefined) continue;
- highestChunkIndex = Math.max(
- highestChunkIndex,
- Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE),
+ const activeChunkIndices = useMemo(() => {
+ const activeChunkIndices = new Set<number>();
+ if (!searchQuery) {
+ let highestChunkIndex = Math.min(
+ loadedThroughChunkIndex,
+ Math.ceil(traces.length / SIDEBAR_TRACE_CHUNK_SIZE) - 1,
);
+ for (const traceId of visibleTraceIds) {
+ const traceIndex = traceIndexById.get(traceId);
+ if (traceIndex === undefined) continue;
+ highestChunkIndex = Math.max(
+ highestChunkIndex,
+ Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE),
+ );
+ }
+ for (let chunkIndex = 0; chunkIndex <= highestChunkIndex; chunkIndex++) {
+ activeChunkIndices.add(chunkIndex);
+ }
}
- for (let chunkIndex = 0; chunkIndex <= highestChunkIndex; chunkIndex++) {
- activeChunkIndices.add(chunkIndex);
- }
- }
+ return activeChunkIndices;
+ }, [
+ searchQuery,
+ loadedThroughChunkIndex,
+ traces.length,
+ visibleTraceIds,
+ traceIndexById,
+ ]);
const queryDescriptors: Array<{
key: string;
diff --git a/web/src/features/sessions/ModernSessionFilterControls.tsx b/web/src/features/sessions/ModernSessionFilterControls.tsx
index b2a7091988..f83791707d 100644
--- a/web/src/features/sessions/ModernSessionFilterControls.tsx
+++ b/web/src/features/sessions/ModernSessionFilterControls.tsx
@@ -258,23 +258,20 @@ export function ModernSessionFilterControls({
});
};
- let filterDialogViewActions: ModernSessionFilterDialogViewActions = {
- type: "none",
- };
- if (hasWriteAccess && updateView) {
- filterDialogViewActions = {
- type: "update",
- viewName: updateView.name,
- isUpdating: updateConfigMutation.isPending,
- onCreate: openSaveViewDialog,
- onUpdate: updateCurrentView,
- };
- } else if (hasWriteAccess) {
- filterDialogViewActions = {
- type: "create",
- onCreate: openSaveViewDialog,
- };
- }
+ const writableViewActions: ModernSessionFilterDialogViewActions = updateView
+ ? {
+ type: "update",
+ viewName: updateView.name,
+ isUpdating: updateConfigMutation.isPending,
+ onCreate: openSaveViewDialog,
+ onUpdate: updateCurrentView,
+ }
+ : {
+ type: "create",
+ onCreate: openSaveViewDialog,
+ };
+ const filterDialogViewActions: ModernSessionFilterDialogViewActions =
+ hasWriteAccess ? writableViewActions : { type: "none" };
return (
<>
diff --git a/web/src/features/sessions/ModernSessionSidebar.tsx b/web/src/features/sessions/ModernSessionSidebar.tsx
index ae410055c9..e32f51f67b 100644
--- a/web/src/features/sessions/ModernSessionSidebar.tsx
+++ b/web/src/features/sessions/ModernSessionSidebar.tsx
@@ -1,5 +1,5 @@
/* eslint-disable no-nested-ternary */
-import React, { useCallback, useRef } from "react";
+import React, { useCallback, useMemo, useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
ChevronDown,
@@ -237,13 +237,11 @@ const TurnCard = React.memo(
sidebarTrace;
const isTraceLevelIOOnly =
hasMatchingTraceLevelIO && observations?.length === 0;
- let observationListClassName = "-mx-1";
- if (observations?.length) {
- observationListClassName = "mt-2";
- }
- if (isTraceLevelIOOnly) {
- observationListClassName = "-mx-1 mt-2";
- }
+ const observationListClassName = useMemo(() => {
+ if (isTraceLevelIOOnly) return "-mx-1 mt-2";
+ if (observations?.length) return "mt-2";
+ return "-mx-1";
+ }, [isTraceLevelIOOnly, observations?.length]);
return (
<div
diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
index 1e05ee4f15..d54df3d4b3 100644
--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
@@ -786,20 +786,27 @@ function LoadedSessionConversationTimeline({
]),
);
}, [observations]);
- let collapsedObservationIds = collapseState.observationIds;
- if (
- scrollTarget &&
- scrollTarget.requestId !== collapseState.scrollRequestId
- ) {
+ const collapsedObservationIds = useMemo(() => {
+ if (
+ !scrollTarget ||
+ scrollTarget.requestId === collapseState.scrollRequestId
+ ) {
+ return collapseState.observationIds;
+ }
const target = observations.find(
({ observation }) => observation.id === scrollTarget.observationId,
);
const observationIds = new Set(collapseState.observationIds);
target?.ancestorObservationIds.forEach((id) => observationIds.delete(id));
- collapsedObservationIds = observationIds;
+ return observationIds;
+ }, [scrollTarget, collapseState, observations]);
+ if (
+ scrollTarget &&
+ scrollTarget.requestId !== collapseState.scrollRequestId
+ ) {
setCollapseState({
scrollRequestId: scrollTarget.requestId,
- observationIds,
+ observationIds: collapsedObservationIds,
});
}
diff --git a/web/src/features/skills/components/SkillEditor.tsx b/web/src/features/skills/components/SkillEditor.tsx
index 97d48715ce..db192ba159 100644
--- a/web/src/features/skills/components/SkillEditor.tsx
+++ b/web/src/features/skills/components/SkillEditor.tsx
@@ -1,4 +1,4 @@
-import { type ComponentProps, useState } from "react";
+import { type ComponentProps, useMemo, useState } from "react";
import { useStore } from "zustand";
import { useMediaQuery } from "react-responsive";
import {
@@ -96,12 +96,12 @@ export function SkillEditor({
? null
: parseSkillFrontmatterMetadata(skillMarkdown);
const draftName = metadata?.name.trim() ?? name;
- let nameError: string | null = null;
- if (skillMarkdown !== undefined) {
- nameError = metadata
+ const nameError = useMemo(() => {
+ if (skillMarkdown === undefined) return null;
+ return metadata
? metadata.nameError
: `Add valid YAML frontmatter with a name in SKILL.md. ${SKILL_NAME_RULES}`;
- }
+ }, [skillMarkdown, metadata]);
const hasNameChanged =
baseVersion !== null &&
skillMarkdown !== undefined &&
@@ -113,15 +113,22 @@ export function SkillEditor({
);
const isCheckingName =
createsNewSkill && !nameError && nameAvailability.isPending;
- let createDisabledReason = nameError;
- if (createsNewSkill && !nameError) {
+ const createDisabledReason = useMemo(() => {
+ if (!createsNewSkill || nameError) return nameError;
if (nameAvailability.data?.data.length) {
- createDisabledReason = `A skill named "${draftName}" already exists. Choose a different name.`;
- } else if (nameAvailability.isError) {
- createDisabledReason =
- "Could not check whether this skill name is available. Please try again.";
+ return `A skill named "${draftName}" already exists. Choose a different name.`;
}
- }
+ if (nameAvailability.isError) {
+ return "Could not check whether this skill name is available. Please try again.";
+ }
+ return nameError;
+ }, [
+ createsNewSkill,
+ nameError,
+ nameAvailability.data,
+ nameAvailability.isError,
+ draftName,
+ ]);
const nameWarning = [
hasNameChanged
? `Versions must keep the name "${name}". Reset the name or create a new skill.`
@@ -528,32 +535,34 @@ function SkillFileEditor({
(state) => state.actions.updateActiveFile,
);
const fileContents = useSkillFileContents(projectId, activeFile);
+ const { refetch } = fileContents;
const content = activeFile.content ?? fileContents.data?.content;
- let editorContent;
- if (content === undefined && fileContents.isError) {
- editorContent = (
- <div className="flex flex-col items-start gap-2 text-sm">
- <p>{fileContents.error.message}</p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => {
- fileContents.refetch();
- }}
- >
- Retry
- </Button>
- </div>
- );
- } else if (content === undefined) {
- editorContent = (
- <div role="status" className="flex items-center gap-2 text-sm">
- <Loader2 className="h-4 w-4 animate-spin" /> Loading file…
- </div>
- );
- } else {
- editorContent = (
+ const editorContent = useMemo(() => {
+ if (content === undefined && fileContents.isError) {
+ return (
+ <div className="flex flex-col items-start gap-2 text-sm">
+ <p>{fileContents.error.message}</p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ refetch();
+ }}
+ >
+ Retry
+ </Button>
+ </div>
+ );
+ }
+ if (content === undefined) {
+ return (
+ <div role="status" className="flex items-center gap-2 text-sm">
+ <Loader2 className="h-4 w-4 animate-spin" /> Loading file…
+ </div>
+ );
+ }
+ return (
<CodeMirrorEditor
key={activePath}
value={content}
@@ -566,7 +575,15 @@ function SkillFileEditor({
className="h-full"
/>
);
- }
+ }, [
+ content,
+ fileContents.isError,
+ fileContents.error,
+ refetch,
+ activePath,
+ editable,
+ updateActiveFile,
+ ]);
return (
<section className="ph-no-capture flex h-full min-w-0 flex-col">
diff --git a/web/src/features/skills/components/SkillEditorPage.tsx b/web/src/features/skills/components/SkillEditorPage.tsx
index dcb36eeaa0..99728c1367 100644
--- a/web/src/features/skills/components/SkillEditorPage.tsx
+++ b/web/src/features/skills/components/SkillEditorPage.tsx
@@ -1,4 +1,4 @@
-import { type ComponentProps, useState } from "react";
+import { type ComponentProps, useMemo, useState } from "react";
import { useRouter } from "next/router";
import { useStore } from "zustand";
import Page from "@/src/components/layouts/page";
@@ -138,17 +138,28 @@ export function ExistingSkillPage() {
],
};
- let content = <div className="p-6 text-sm">Skill version not found.</div>;
- if (error) {
- content = <div className="ph-no-capture p-6 text-sm">{error.message}</div>;
- } else if (skill.isPending || history.isPending) {
- content = (
- <div className="grid gap-3 p-3">
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-[600px] w-full" />
- </div>
- );
- } else if (skill.data && history.data) {
+ const content = useMemo(() => {
+ if (error) {
+ return <div className="ph-no-capture p-6 text-sm">{error.message}</div>;
+ }
+ if (skill.isPending || history.isPending) {
+ return (
+ <div className="grid gap-3 p-3">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-[600px] w-full" />
+ </div>
+ );
+ }
+ return <div className="p-6 text-sm">Skill version not found.</div>;
+ }, [error, skill.isPending, history.isPending]);
+
+ if (
+ !error &&
+ !skill.isPending &&
+ !history.isPending &&
+ skill.data &&
+ history.data
+ ) {
return (
<SkillEditorForInitialValue
headerProps={headerProps}
diff --git a/web/src/features/skills/components/SkillMetadataSelect.tsx b/web/src/features/skills/components/SkillMetadataSelect.tsx
index ee85743cf4..790fad53ab 100644
--- a/web/src/features/skills/components/SkillMetadataSelect.tsx
+++ b/web/src/features/skills/components/SkillMetadataSelect.tsx
@@ -1,4 +1,4 @@
-import { useId, useState } from "react";
+import { useId, useMemo, useState } from "react";
import {
CircleCheckIcon,
CircleFadingArrowUp,
@@ -54,11 +54,11 @@ export function SkillLabelsSelect({
!value.includes("production") && pendingLabels.includes("production");
const isDemotingFromProduction =
value.includes("production") && !pendingLabels.includes("production");
- let saveButtonCopy = "Save labels";
- if (isPromotingToProduction)
- saveButtonCopy = "Save and promote to production";
- else if (isDemotingFromProduction)
- saveButtonCopy = "Save and remove from production";
+ const saveButtonCopy = useMemo(() => {
+ if (isPromotingToProduction) return "Save and promote to production";
+ if (isDemotingFromProduction) return "Save and remove from production";
+ return "Save labels";
+ }, [isPromotingToProduction, isDemotingFromProduction]);
const toggleLabel = (label: string) => {
setPendingLabels(
diff --git a/web/src/features/skills/components/SkillsPage.tsx b/web/src/features/skills/components/SkillsPage.tsx
index 4f2076ec82..75dca1804b 100644
--- a/web/src/features/skills/components/SkillsPage.tsx
+++ b/web/src/features/skills/components/SkillsPage.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from "react";
import Link from "next/link";
import { FileCode2, Plus, Trash } from "lucide-react";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
@@ -130,11 +131,11 @@ function SkillsList({
},
});
- let tableData: AsyncTableData<SkillRow[]> = { status: "loading" };
- if (skills.isError)
- tableData = { status: "error", error: skills.error.message };
- else if (skills.data)
- tableData = { status: "success", data: skills.data.data };
+ const tableData = useMemo<AsyncTableData<SkillRow[]>>(() => {
+ if (skills.isError) return { status: "error", error: skills.error.message };
+ if (skills.data) return { status: "success", data: skills.data.data };
+ return { status: "loading" };
+ }, [skills.isError, skills.error, skills.data]);
const hasFilters = Boolean(searchQuery) || queryFilter.filterState.length > 0;
const isEmptyProject =
skills.data?.meta.totalItems === 0 &&
diff --git a/web/src/features/traces/components/DeleteTraceDialogController.tsx b/web/src/features/traces/components/DeleteTraceDialogController.tsx
index 1c103ea4d6..18ebb5418f 100644
--- a/web/src/features/traces/components/DeleteTraceDialogController.tsx
+++ b/web/src/features/traces/components/DeleteTraceDialogController.tsx
@@ -1,5 +1,5 @@
import { useRouter } from "next/router";
-import { type ReactNode, useState } from "react";
+import { type ReactNode, useMemo, useState } from "react";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
import { useHasEntitlement } from "@/src/features/entitlements";
@@ -34,12 +34,15 @@ export function DeleteTraceDialogController({
const hasEntitlement = useHasEntitlement("trace-deletion");
const deleteMutation = api.traces.deleteMany.useMutation();
- let disabled: { reason: string } | undefined;
- if (!hasAccess) {
- disabled = { reason: "You don't have permission to delete this trace." };
- } else if (!hasEntitlement) {
- disabled = { reason: "Trace deletion is not available on your plan." };
- }
+ const disabled = useMemo(() => {
+ if (!hasAccess) {
+ return { reason: "You don't have permission to delete this trace." };
+ }
+ if (!hasEntitlement) {
+ return { reason: "Trace deletion is not available on your plan." };
+ }
+ return undefined;
+ }, [hasAccess, hasEntitlement]);
return (
<ConfirmationDialogController
diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
index a62e92673f..535b272507 100644
--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
@@ -98,21 +98,22 @@ export function AreaChartTimeSeries({
dimension,
color: seriesColor(index),
}));
- let chartLegend: LineChartLegend = { visibility: "hidden" };
- if (legendPosition !== "none" && legendInteraction === "toggle") {
- chartLegend = {
- visibility: legendPosition === "auto" ? "auto" : "visible",
- interaction: "toggle",
- summary: legendSummary,
- maxVisibleSeries,
- };
- } else if (legendPosition !== "none") {
- chartLegend = {
+ const chartLegend = useMemo<LineChartLegend>(() => {
+ if (legendPosition === "none") return { visibility: "hidden" };
+ if (legendInteraction === "toggle") {
+ return {
+ visibility: legendPosition === "auto" ? "auto" : "visible",
+ interaction: "toggle",
+ summary: legendSummary,
+ maxVisibleSeries,
+ };
+ }
+ return {
visibility: legendPosition === "auto" ? "auto" : "visible",
interaction: "highlight",
summary: legendSummary,
};
- }
+ }, [legendPosition, legendInteraction, legendSummary, maxVisibleSeries]);
const chart =
timeAxis.mode === "category" || hasNonTimestampBucket ? (
<DesignSystemAreaChart
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index 8cb85e2094..ae62b3b7ce 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -160,21 +160,22 @@ export function LineChartTimeSeries({
() => thresholds?.map(toDesignSystemThreshold),
[thresholds],
);
- let chartLegend: LineChartLegend = { visibility: "hidden" };
- if (legendPosition !== "none" && legendInteraction === "toggle") {
- chartLegend = {
- visibility: legendPosition === "auto" ? "auto" : "visible",
- interaction: "toggle",
- summary: legendSummary,
- maxVisibleSeries,
- };
- } else if (legendPosition !== "none") {
- chartLegend = {
+ const chartLegend = useMemo<LineChartLegend>(() => {
+ if (legendPosition === "none") return { visibility: "hidden" };
+ if (legendInteraction === "toggle") {
+ return {
+ visibility: legendPosition === "auto" ? "auto" : "visible",
+ interaction: "toggle",
+ summary: legendSummary,
+ maxVisibleSeries,
+ };
+ }
+ return {
visibility: legendPosition === "auto" ? "auto" : "visible",
interaction: "highlight",
summary: legendSummary,
};
- }
+ }, [legendPosition, legendInteraction, legendSummary, maxVisibleSeries]);
const chart =
timeAxis.mode === "category" || hasNonTimestampBucket ? (
<DesignSystemLineChart
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
index c5a2ff5d93..e76713ef61 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
@@ -77,21 +77,22 @@ export function VerticalBarChartTimeSeries({
})),
[visibleSeries, config],
);
- let chartLegend: LineChartLegend = { visibility: "hidden" };
- if (legendPosition !== "none" && legendInteraction === "toggle") {
- chartLegend = {
- visibility: legendPosition === "auto" ? "auto" : "visible",
- interaction: "toggle",
- summary: legendSummary,
- maxVisibleSeries,
- };
- } else if (legendPosition !== "none") {
- chartLegend = {
+ const chartLegend = useMemo<LineChartLegend>(() => {
+ if (legendPosition === "none") return { visibility: "hidden" };
+ if (legendInteraction === "toggle") {
+ return {
+ visibility: legendPosition === "auto" ? "auto" : "visible",
+ interaction: "toggle",
+ summary: legendSummary,
+ maxVisibleSeries,
+ };
+ }
+ return {
visibility: legendPosition === "auto" ? "auto" : "visible",
interaction: "highlight",
summary: legendSummary,
};
- }
+ }, [legendPosition, legendInteraction, legendSummary, maxVisibleSeries]);
return (
<div className="flex size-full min-w-0 flex-col">