Skip to content

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

refactor(web): Remove unused components and hooks (#13148)

Ben Bachemb5bada7b21c7
diff --git a/web/src/components/Slider.tsx b/web/src/components/Slider.tsx
deleted file mode 100644
index 2d688dab90..0000000000
--- a/web/src/components/Slider.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import * as React from "react";
-import { Switch } from "@headlessui/react";
-import { cn } from "@/src/utils/tailwind";
-
-export const Slider = (props: {
- disabled: boolean; // whether the slider is clickable in the UI
- loading?: boolean;
- onChecked?: (checked: boolean) => void;
- isChecked?: boolean; // whether the slider is active
-}) => (
- <Switch
- checked={props.isChecked}
- disabled={props.loading || props.disabled}
- onChange={props.onChecked}
- className={cn(
- props.isChecked ? "bg-background" : "bg-input",
- "focus:ring-foreground relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:ring-2 focus:ring-offset-2 focus:outline-hidden",
- )}
- >
- <span className="sr-only">Use setting</span>
- <span
- aria-hidden="true"
- className={cn(
- props.isChecked ? "translate-x-5" : "translate-x-0",
- "bg-background pointer-events-none inline-block h-5 w-5 transform rounded-full shadow-sm ring-0 transition duration-200 ease-in-out",
- )}
- />
- </Switch>
-);
diff --git a/web/src/components/date-range-dropdowns.tsx b/web/src/components/date-range-dropdowns.tsx
index c638b0d691..e126acba98 100644
--- a/web/src/components/date-range-dropdowns.tsx
+++ b/web/src/components/date-range-dropdowns.tsx
@@ -12,12 +12,8 @@ import {
dashboardDateRangeAggregationSettings,
DASHBOARD_AGGREGATION_PLACEHOLDER,
type DashboardDateRangeOptions,
- type TableDateRangeOptions,
DASHBOARD_AGGREGATION_OPTIONS,
type DashboardDateRange,
- TABLE_AGGREGATION_OPTIONS,
- getDateFromOption,
- isTableDataRangeOptionAvailable,
isDashboardDateRangeOptionAvailable,
getAbbreviatedTimeRange,
getTimeRangeLabel,
@@ -149,52 +145,3 @@ export const DashboardDateRangeDropdown: React.FC<
/>
);
};
-
-type TableDateRangeDropdownProps = {
- selectedOption: TableDateRangeOptions;
- setDateRangeAndOption: (
- option: TableDateRangeOptions,
- date?: DashboardDateRange,
- ) => void;
-};
-
-export const TableDateRangeDropdown: React.FC<TableDateRangeDropdownProps> = ({
- selectedOption,
- setDateRangeAndOption,
-}) => {
- const lookbackLimit = useEntitlementLimit("data-access-days");
- const disabledOptions = useMemo(() => {
- return TABLE_AGGREGATION_OPTIONS.filter(
- (option) =>
- !isTableDataRangeOptionAvailable({ option, limitDays: lookbackLimit }),
- );
- }, [lookbackLimit]);
-
- const onDropDownSelection = (value: TableDateRangeOptions) => {
- // Handle "custom" placeholder case
- if (value === "custom") {
- setDateRangeAndOption(value, undefined);
- return;
- }
-
- const dateFromOption = getDateFromOption({
- filterSource: "TABLE",
- option: value,
- });
-
- const initialDateRange = !!dateFromOption
- ? { from: dateFromOption, to: new Date() }
- : undefined;
-
- setDateRangeAndOption(value, initialDateRange);
- };
-
- return (
- <BaseDateRangeDropdown
- selectedOption={selectedOption}
- options={TABLE_AGGREGATION_OPTIONS}
- limitedOptions={disabledOptions}
- onSelectionChange={onDropDownSelection}
- />
- );
-};
diff --git a/web/src/components/projectNavigation.tsx b/web/src/components/projectNavigation.tsx
deleted file mode 100644
index 664fdb1c2f..0000000000
--- a/web/src/components/projectNavigation.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import React from "react";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-import { cn } from "@/src/utils/tailwind";
-import { useRouter } from "next/router";
-
-interface Project {
- id: string;
- name: string;
- role: string;
-}
-
-interface ProjectNavigationProps {
- currentProjectId: string;
- projects: Project[];
-}
-
-export const ProjectNavigation: React.FC<ProjectNavigationProps> = ({
- currentProjectId,
- projects,
-}) => {
- const router = useRouter();
- return (
- <Select
- value={currentProjectId}
- onValueChange={(value) => {
- router.push(`/project/${value}`);
- }}
- >
- <SelectTrigger className="text-primary h-8 ring-transparent focus:ring-0 focus:ring-offset-0">
- <SelectValue
- className="text-primary text-sm font-semibold"
- placeholder={currentProjectId}
- />
- </SelectTrigger>
- <SelectContent className="max-h-60 max-w-80">
- {projects.map((project) => (
- <SelectItem key={project.id} value={project.id}>
- <div className="text-primary flex items-center space-x-2 font-semibold">
- <span
- className={cn(
- "truncate",
- currentProjectId === project.id
- ? "border-primary text-primary"
- : "text-muted-foreground",
- )}
- >
- {project.name}
- </span>
- {project.role === "VIEWER" ? (
- <span
- className={cn(
- "self-center rounded-sm border px-1 py-0.5 text-xs break-keep whitespace-nowrap",
- currentProjectId === project.id
- ? "border-primary text-primary"
- : "border-border text-muted-foreground group-hover:border-primary group-hover:text-primary",
- )}
- >
- view-only
- </span>
- ) : null}
- </div>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- );
-};
diff --git a/web/src/components/stats-cards.tsx b/web/src/components/stats-cards.tsx
deleted file mode 100644
index 958c7fa3b3..0000000000
--- a/web/src/components/stats-cards.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-interface Statistic {
- name: string;
- stat: string;
-}
-
-export default function StatsCards({ stats }: { stats: Statistic[] }) {
- return (
- <div>
- <h3 className="text-primary text-base leading-6 font-semibold">
- Model configuration
- </h3>
- <dl className="mt-5 grid grid-cols-1 gap-5 sm:grid-cols-4">
- {stats.map((item) => (
- <div
- key={item.name}
- className="bg-background overflow-hidden rounded-lg px-4 py-5 shadow-sm sm:p-6"
- >
- <dt className="text-muted-foreground truncate text-sm font-medium">
- {item.name}
- </dt>
- <dd className="text-primary mt-1 text-3xl font-semibold tracking-tight">
- {item.stat}
- </dd>
- </div>
- ))}
- </dl>
- </div>
- );
-}
diff --git a/web/src/components/table/peek/hooks/usePeekCompareDetail.ts b/web/src/components/table/peek/hooks/usePeekCompareDetail.ts
deleted file mode 100644
index 2e4e01371e..0000000000
--- a/web/src/components/table/peek/hooks/usePeekCompareDetail.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useRouter } from "next/router";
-import { useState, useCallback } from "react";
-
-export function usePeekCompareDetail(projectId: string) {
- const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);
-
- const router = useRouter();
- const traceId = router.query.traceId as string;
-
- const toggleCollapsedNode = useCallback((id: string) => {
- setCollapsedNodes((prevNodes) => {
- if (prevNodes.includes(id)) {
- return prevNodes.filter((i) => i !== id);
- } else {
- return [...prevNodes, id];
- }
- });
- }, []);
-
- const handleSetCurrentObservationId = (id?: string) => {
- if (id && traceId) {
- // Only open observations in new tabs; root selection passes undefined
- const pathname = `/project/${projectId}/traces/${encodeURIComponent(traceId)}?observation=${encodeURIComponent(id)}`;
- const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank", "noopener noreferrer");
- }
- };
-
- const handleToggleTrace = (newTraceId: string) => {
- const pathname = window.location.pathname;
- if (newTraceId === router.query.traceId) {
- // remove traceId from query params
- router.push({
- pathname: pathname,
- query: {
- ...router.query,
- traceId: undefined,
- },
- });
- } else {
- // update traceId in query params
- router.push({
- pathname: pathname,
- query: {
- ...router.query,
- traceId: encodeURIComponent(newTraceId),
- },
- });
- }
-
- setCollapsedNodes([]); // Reset collapsed state for new trace
- };
-
- return {
- collapsedNodes,
- toggleCollapsedNode,
- handleSetCurrentObservationId,
- handleToggleTrace,
- };
-}
diff --git a/web/src/components/table/peek/hooks/usePeekRunsCompareData.ts b/web/src/components/table/peek/hooks/usePeekRunsCompareData.ts
deleted file mode 100644
index 5af428178c..0000000000
--- a/web/src/components/table/peek/hooks/usePeekRunsCompareData.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { api } from "@/src/utils/api";
-
-type UsePeekRunsCompareDataProps = {
- projectId: string;
- datasetId?: string;
- datasetItemId?: string;
- traceId?: string;
- timestamp?: Date;
- runs?: string[] | string;
-};
-
-// Ensure runs is always an array - handle case where URL param comes as string
-const safeParseUrlParamToArray = (
- runs?: string[] | string,
-): string[] | undefined => {
- if (!runs) return undefined;
- return Array.isArray(runs) ? runs : [runs];
-};
-
-export const usePeekRunsCompareData = ({
- projectId,
- traceId,
- timestamp,
- datasetId,
- datasetItemId,
- runs,
-}: UsePeekRunsCompareDataProps) => {
- const parsedRuns = safeParseUrlParamToArray(runs);
-
- const trace = api.traces.byIdWithObservationsAndScores.useQuery(
- {
- traceId: traceId as string,
- projectId,
- timestamp,
- },
- {
- enabled: !!traceId,
- retry(failureCount, error) {
- if (error.data?.code === "UNAUTHORIZED") return false;
- return failureCount < 3;
- },
- staleTime: 60 * 1000, // 1 minute
- },
- );
-
- const datasetItem = api.datasets.itemById.useQuery(
- {
- projectId,
- datasetId: datasetId as string,
- datasetItemId: datasetItemId as string,
- },
- {
- enabled: !!datasetId && !!datasetItemId,
- },
- );
-
- const runItems = api.datasets.runItemsByItemId.useQuery(
- {
- projectId,
- datasetId: datasetId as string,
- datasetItemId: datasetItemId as string,
- datasetRunIds: parsedRuns,
- },
- {
- enabled:
- !!datasetId && !!datasetItemId && !!parsedRuns && parsedRuns.length > 0,
- },
- );
-
- return {
- trace,
- datasetItem,
- runItems,
- };
-};
diff --git a/web/src/components/trace2/api/useAgentGraphData.ts b/web/src/components/trace2/api/useAgentGraphData.ts
deleted file mode 100644
index 0bb1144a77..0000000000
--- a/web/src/components/trace2/api/useAgentGraphData.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { useMemo } from "react";
-import { api } from "@/src/utils/api";
-import { type AgentGraphDataResponse } from "@/src/features/trace-graph-view/types";
-
-export type UseAgentGraphDataParams = {
- projectId: string;
- traceId: string;
- observations: Array<{ startTime: Date }>;
- enabled?: boolean;
-};
-
-/**
- * Hook to fetch agent graph data for visualization.
- * Calculates time bounds from observations and fetches graph data.
- *
- * @param projectId - Project ID
- * @param traceId - Trace ID
- * @param observations - Array of observations with startTime
- * @param enabled - Whether to enable the query (default: true)
- */
-export function useAgentGraphData({
- projectId,
- traceId,
- observations,
- enabled = true,
-}: UseAgentGraphDataParams) {
- // Calculate time bounds from observations
- const observationStartTimes = observations.map((o) => o.startTime.getTime());
- const minStartTime = new Date(
- Math.min(...observationStartTimes, Date.now()),
- ).toISOString();
- const maxStartTime = new Date(
- Math.max(...observationStartTimes, 0),
- ).toISOString();
-
- const query = api.traces.getAgentGraphData.useQuery(
- {
- projectId,
- traceId,
- minStartTime,
- maxStartTime,
- },
- {
- enabled: enabled && observations.length > 0,
- refetchOnWindowFocus: false,
- refetchOnMount: false,
- refetchOnReconnect: false,
- staleTime: 50 * 60 * 1000, // 50 minutes
- },
- );
-
- const data = useMemo(() => query.data ?? [], [query.data]);
-
- return {
- data,
- isLoading: query.isLoading,
- isError: query.isError,
- error: query.error,
- };
-}
-
-const MAX_NODES_FOR_GRAPH_UI = 5000;
-
-/**
- * Determines if graph view should be available based on observation data.
- */
-export function useIsGraphViewAvailable(
- agentGraphData: AgentGraphDataResponse[],
-): boolean {
- return useMemo(() => {
- if (agentGraphData.length === 0) {
- return false;
- }
-
- // Don't show graph UI for extremely large traces
- if (agentGraphData.length >= MAX_NODES_FOR_GRAPH_UI) {
- return false;
- }
-
- // Check if there are observations that would be included in the graph
- // (not SPAN, EVENT, or GENERATION)
- const hasGraphableObservations = agentGraphData.some(
- (obs) =>
- obs.observationType !== "SPAN" &&
- obs.observationType !== "EVENT" &&
- obs.observationType !== "GENERATION",
- );
-
- // Check for LangGraph data (has step != 0)
- const hasLangGraphData = agentGraphData.some(
- (obs) => obs.step != null && obs.step !== 0,
- );
-
- return hasGraphableObservations || hasLangGraphData;
- }, [agentGraphData]);
-}
diff --git a/web/src/components/trace2/api/useTraceData.ts b/web/src/components/trace2/api/useTraceData.ts
deleted file mode 100644
index e19f59d962..0000000000
--- a/web/src/components/trace2/api/useTraceData.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { api } from "@/src/utils/api";
-
-export type UseTraceDataParams = {
- traceId: string;
- projectId: string;
- timestamp?: Date;
-};
-
-export function useTraceData({
- traceId,
- projectId,
- timestamp,
-}: UseTraceDataParams) {
- const query = api.traces.byIdWithObservationsAndScores.useQuery(
- {
- traceId,
- timestamp,
- projectId,
- },
- {
- retry(failureCount, error) {
- if (
- error.data?.code === "UNAUTHORIZED" ||
- error.data?.code === "NOT_FOUND"
- )
- return false;
- return failureCount < 3;
- },
- },
- );
-
- return {
- trace: query.data,
- observations: query.data?.observations ?? [],
- scores: query.data?.scores ?? [],
- isLoading: query.isLoading,
- error: query.error,
- refetch: query.refetch,
- };
-}
diff --git a/web/src/components/trace2/components/IOPreview/components/hooks/index.ts b/web/src/components/trace2/components/IOPreview/components/hooks/index.ts
deleted file mode 100644
index 98133b6f67..0000000000
--- a/web/src/components/trace2/components/IOPreview/components/hooks/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export { useCorrectionData } from "./useCorrectionData";
-export { useCorrectionMutations } from "./useCorrectionMutations";
-export { useCorrectionEditor } from "./useCorrectionEditor";
diff --git a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx b/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx
deleted file mode 100644
index 73c243f121..0000000000
--- a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx
+++ /dev/null
@@ -1,456 +0,0 @@
-/**
- * AdvancedJsonSection - Wrapper for AdvancedJsonViewer with collapsible header
- *
- * Features:
- * - Collapsible section with header
- * - Integrated search bar in header
- * - Collapse all / expand all buttons
- * - Copy button in header
- * - JsonExpansionContext integration for state persistence
- * - Custom theme (fontSize: 0.7rem, lineHeight: 16px)
- */
-
-import { useState, useMemo, useCallback, useRef, useEffect } from "react";
-import {
- ChevronDown,
- ChevronUp,
- WrapText,
- Minus,
- ArrowRightToLine,
-} from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { Input } from "@/src/components/ui/input";
-import { AdvancedJsonSectionHeader } from "./AdvancedJsonSectionHeader";
-import { AdvancedJsonViewer } from "@/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer";
-import { useJsonViewPreferences } from "@/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewPreferences";
-import { type MediaReturnType } from "@/src/features/media/validation";
-import { type PartialJSONTheme } from "@/src/components/ui/AdvancedJsonViewer/types";
-import { buildTreeFromJSON } from "@/src/components/ui/AdvancedJsonViewer/utils/treeStructure";
-import { searchInTree } from "@/src/components/ui/AdvancedJsonViewer/utils/searchJson";
-
-export interface AdvancedJsonSectionProps {
- /** Section title */
- title: string;
-
- /** Data to display */
- data: unknown;
-
- /** Field name for JsonExpansionContext ("input", "output", "metadata", etc.) */
- field: string;
-
- /** Pre-parsed data (to avoid re-parsing) */
- parsedData?: unknown;
-
- /** Section collapse state (controlled) */
- collapsed?: boolean;
-
- /** Callback when section collapse state changes */
- onToggleCollapse?: () => void;
-
- /** Background color for the JSON viewer body */
- backgroundColor?: string;
-
- /** Background color for the header */
- headerBackgroundColor?: string;
-
- /** Custom CSS class */
- className?: string;
-
- /** Hide section if data is null/undefined */
- hideIfNull?: boolean;
-
- /** Enable search functionality */
- enableSearch?: boolean;
-
- /** Search placeholder text */
- searchPlaceholder?: string;
-
- /** Show line numbers */
- showLineNumbers?: boolean;
-
- /** Enable copy buttons */
- enableCopy?: boolean;
-
- /** Truncate strings longer than this */
- truncateStringsAt?: number | null;
-
- /** Loading state */
- isLoading?: boolean;
-
- /** Media attachments */
- media?: MediaReturnType[];
-
- /** Additional control buttons in header */
- controlButtons?: React.ReactNode;
-
- commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
-
- /** Force virtualization on/off (overrides auto-detection) */
- virtualized?: boolean;
-}
-
-export function AdvancedJsonSection({
- title,
- data,
- field,
- parsedData,
- collapsed: controlledCollapsed,
- onToggleCollapse,
- backgroundColor,
- headerBackgroundColor,
- className,
- hideIfNull = false,
- enableSearch = true,
- searchPlaceholder = "Search JSON...",
- showLineNumbers = true,
- enableCopy = true,
- truncateStringsAt = 100,
- isLoading = false,
- media: _media, // TODO: Implement media attachment support
- controlButtons,
- commentedPaths,
- virtualized,
-}: AdvancedJsonSectionProps) {
- // String wrap mode state (persisted in localStorage)
- const { stringWrapMode, setStringWrapMode } = useJsonViewPreferences();
-
- // Section collapse state (different from JSON tree expansion)
- const [internalCollapsed, setInternalCollapsed] = useState(false);
- const isCollapseControlled =
- controlledCollapsed !== undefined && onToggleCollapse !== undefined;
- const sectionCollapsed = isCollapseControlled
- ? controlledCollapsed
- : internalCollapsed;
-
- // When virtualized=false (continuous scroll mode), ignore collapse state - always expanded
- const effectiveCollapsed = virtualized === false ? false : sectionCollapsed;
-
- const handleToggleSectionCollapse = () => {
- // Don't allow toggling in non-virtualized mode
- if (virtualized === false) return;
-
- if (isCollapseControlled) {
- onToggleCollapse();
- } else {
- setInternalCollapsed(!internalCollapsed);
- }
- };
-
- // No more context - AdvancedJsonViewer handles storage directly via field prop
-
- // Search state (managed in this component, not in AdvancedJsonViewer)
- const [searchQuery, setSearchQuery] = useState("");
- const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");
- const [currentMatchIndex, setCurrentMatchIndex] = useState(0);
-
- // Debounce search query
- useEffect(() => {
- const timer = setTimeout(() => {
- setDebouncedSearchQuery(searchQuery);
- setCurrentMatchIndex(0); // Reset to first match when query changes
- }, 300);
-
- return () => clearTimeout(timer);
- }, [searchQuery]);
-
- // Build tree ONCE on mount for row counting only
- // Expansion state is managed by AdvancedJsonViewer internally
- const initialTree = useMemo(() => {
- const effectiveData = parsedData ?? data;
- if (!effectiveData) {
- return null;
- }
- const tree = buildTreeFromJSON(effectiveData, {
- rootKey: "root",
- initialExpansion: true, // Fully expanded for counting
- });
- return tree;
- }, [parsedData, data]);
-
- // Compute total row count (when fully expanded)
- const totalRowCount = useMemo(() => {
- const count = initialTree ? initialTree.totalNodeCount : 0;
- return count;
- }, [initialTree]);
-
- // Compute search matches using the initial tree
- const searchMatches = useMemo(() => {
- if (
- !debouncedSearchQuery ||
- debouncedSearchQuery.trim() === "" ||
- !initialTree
- ) {
- return [];
- }
- const matches = searchInTree(initialTree, debouncedSearchQuery, {
- caseSensitive: false,
- });
- return matches;
- }, [initialTree, debouncedSearchQuery]);
-
- // Handle search navigation (controlled via AdvancedJsonViewer)
- const handleNextMatch = useCallback(() => {
- if (searchMatches.length === 0) return;
- const nextIndex = (currentMatchIndex + 1) % searchMatches.length;
- setCurrentMatchIndex(nextIndex);
- }, [searchMatches, currentMatchIndex]);
-
- const handlePreviousMatch = useCallback(() => {
- if (searchMatches.length === 0) return;
- const prevIndex =
- currentMatchIndex === 0
- ? searchMatches.length - 1
- : currentMatchIndex - 1;
- setCurrentMatchIndex(prevIndex);
- }, [searchMatches, currentMatchIndex]);
-
- const handleClearSearch = useCallback(() => {
- setSearchQuery("");
- setDebouncedSearchQuery("");
- setCurrentMatchIndex(0);
- }, []);
-
- // TODO: Expand all / collapse all functionality currently disabled
- // The expandAllDescendants/collapseAllDescendants utilities cause tree offset
- // validation errors. Needs investigation into offset recalculation in treeExpansion.ts
- // before this can be re-enabled.
- //
- // Previous implementation attempted to:
- // 1. Write expansion state to storage
- // 2. Trigger tree rebuild to read new state
- // But this caused childOffsets corruption in the tree structure.
-
- // Handle string wrap mode cycling: truncate → wrap → nowrap → truncate
- const handleCycleWrapMode = () => {
- if (stringWrapMode === "truncate") {
- setStringWrapMode("wrap");
- } else if (stringWrapMode === "wrap") {
- setStringWrapMode("nowrap");
- } else {
- setStringWrapMode("truncate");
- }
- };
-
- // Handle copy
- const handleCopy = useCallback(
- (event?: React.MouseEvent<HTMLButtonElement>) => {
- event?.preventDefault();
- const jsonString = JSON.stringify(parsedData ?? data, null, 2);
- void navigator.clipboard.writeText(jsonString);
- },
- [parsedData, data],
- );
-
- // Custom theme for AdvancedJsonViewer
- const customTheme: PartialJSONTheme = useMemo(
- () => ({
- fontSize: "0.7rem",
- lineHeight: 16,
- indentSize: 20,
- background: headerBackgroundColor || backgroundColor || "transparent",
- }),
- [headerBackgroundColor, backgroundColor],
- );
-
- // Determine if virtualization is being used
- // Auto-virtualize for 500+ rows (when fully expanded)
- const isVirtualized = useMemo(() => {
- const virtualized = totalRowCount >= 500;
- return virtualized;
- }, [totalRowCount]);
-
- // Ref for scroll container (the body wrapper div)
- const scrollContainerRef = useRef<HTMLDivElement>(null);
-
- // Hide section if data is null/undefined
- if (hideIfNull && (data === null || data === undefined)) {
- return null;
- }
-
- // If data is still being loaded/parsed, show header but not body
- const hasData = (parsedData ?? data) !== undefined;
- const effectiveData = parsedData ?? data;
-
- return (
- <div
- className={`flex flex-col border-t border-b ${effectiveCollapsed ? "" : virtualized !== false ? "min-h-0 overflow-hidden" : ""} ${className || ""}`}
- style={{
- backgroundColor: headerBackgroundColor || backgroundColor,
- }}
- >
- {/* Header with fixed height */}
- <div
- className="border-b"
- style={{
- backgroundColor: headerBackgroundColor,
- minHeight: "32px", // Fixed height for header
- }}
- >
- <AdvancedJsonSectionHeader
- title={
- <div className="flex items-center gap-2">
- <span>{title}</span>
- <span className="text-muted-foreground text-xs font-normal">
- {totalRowCount} rows{isVirtualized ? " (virtualized)" : ""}
- </span>
- </div>
- }
- handleOnCopy={handleCopy}
- backgroundColor={headerBackgroundColor}
- onToggleCollapse={handleToggleSectionCollapse}
- sectionCollapsed={effectiveCollapsed}
- controlButtons={
- <>
- {/* Search */}
- {!effectiveCollapsed && enableSearch && (
- <div className="flex items-center gap-1">
- <div className="relative">
- <Input
- type="text"
- placeholder={searchPlaceholder}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- if (e.shiftKey) {
- handlePreviousMatch();
- } else {
- handleNextMatch();
- }
- } else if (e.key === "Escape") {
- handleClearSearch();
- }
- }}
- className="h-6 w-[180px] pr-16 text-xs"
- aria-label="Search JSON"
- />
- {searchQuery && (
- <span
- className="text-muted-foreground pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 text-xs whitespace-nowrap"
- aria-live="polite"
- >
- {searchMatches.length > 0
- ? `${currentMatchIndex + 1} of ${searchMatches.length}`
- : "No matches"}
- </span>
- )}
- </div>
- {searchQuery && searchMatches.length > 0 && (
- <>
- <button
- type="button"
- onClick={handlePreviousMatch}
- className="hover:bg-accent hover:text-accent-foreground inline-flex items-center justify-center rounded-md p-1 transition-colors"
- aria-label="Previous match (Shift+Enter)"
- title="Previous match (Shift+Enter)"
- >
- <ChevronUp size={14} />
- </button>
- <button
- type="button"
- onClick={handleNextMatch}
- className="hover:bg-accent hover:text-accent-foreground inline-flex items-center justify-center rounded-md p-1 transition-colors"
- aria-label="Next match (Enter)"
- title="Next match (Enter)"
- >
- <ChevronDown size={14} />
- </button>
- </>
- )}
- </div>
- )}
-
- {/* Custom control buttons */}
- {!effectiveCollapsed && controlButtons}
-
- {/* String wrap mode toggle */}
- {!effectiveCollapsed && (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={handleCycleWrapMode}
- className="hover:bg-border"
- title={
- stringWrapMode === "truncate"
- ? "Truncate long strings (click to wrap)"
- : stringWrapMode === "wrap"
- ? "Wrap long strings (click for single line)"
- : "Single line (click to truncate)"
- }
- >
- {stringWrapMode === "truncate" ? (
- <Minus className="h-3 w-3" />
- ) : stringWrapMode === "wrap" ? (
- <WrapText className="h-3 w-3" />
- ) : (
- <ArrowRightToLine className="h-3 w-3" />
- )}
- </Button>
- )}
-
- {/* TODO: Collapse/Expand All button hidden - see comment above for details
- {!sectionCollapsed && (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={handleToggleExpandAll}
- className="-mr-2 hover:bg-border"
- title={allExpanded ? "Collapse all" : "Expand all"}
- >
- {allExpanded ? (
- <FoldVertical className="h-3 w-3" />
- ) : (
- <UnfoldVertical className="h-3 w-3" />
- )}
- </Button>
- )}
- */}
- </>
- }
- />
- </div>
-
- {/* Body */}
- {!effectiveCollapsed && (
- <div
- ref={scrollContainerRef}
- className={
- virtualized !== false
- ? "min-h-0 flex-1 overflow-auto"
- : "min-h-48 overflow-x-auto"
- }
- style={{
- backgroundColor: headerBackgroundColor || backgroundColor,
- }}
- >
- {!hasData ? (
- <div className="text-muted-foreground flex h-full items-center justify-center p-4 text-sm">
- {isLoading ? "Loading..." : "No data"}
- </div>
- ) : (
- <AdvancedJsonViewer
- data={effectiveData}
- field={field}
- theme={customTheme}
- enableSearch={false} // Search is handled in header
- searchQuery={debouncedSearchQuery}
- onSearchQueryChange={setSearchQuery}
- currentMatchIndex={currentMatchIndex}
- onCurrentMatchIndexChange={setCurrentMatchIndex}
- showLineNumbers={showLineNumbers}
- enableCopy={enableCopy}
- stringWrapMode={stringWrapMode}
- truncateStringsAt={truncateStringsAt}
- isLoading={isLoading}
- scrollContainerRef={scrollContainerRef}
- virtualized={virtualized}
- className={virtualized !== false ? "h-full" : ""}
- commentedPaths={commentedPaths}
- />
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSectionHeader.tsx b/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSectionHeader.tsx
deleted file mode 100644
index 5a97a11e6b..0000000000
--- a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSectionHeader.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * JsonSectionHeader - Self-contained header for AdvancedJsonSection
- *
- * A simplified version of MarkdownJsonViewHeader specifically for JSON sections.
- * Includes:
- * - Title with optional icon
- * - Copy button
- * - Custom control buttons (search, expand/collapse, etc.)
- */
-
-import { useState } from "react";
-import { Button } from "@/src/components/ui/button";
-import { Check, ChevronDown, ChevronRight, Copy } from "lucide-react";
-
-export interface AdvancedJsonSectionHeaderProps {
- /** Section title (can be string or React node for custom rendering) */
- title: string | React.ReactNode;
-
- /** Optional icon to display next to title */
- titleIcon?: React.ReactNode;
-
- /** Callback when copy button is clicked */
- handleOnCopy: (event?: React.MouseEvent<HTMLButtonElement>) => void;
-
- /** Additional control buttons to render (search, expand/collapse, etc.) */
- controlButtons?: React.ReactNode;
-
- /** Background color for the header */
- backgroundColor?: string;
-
- /** Callback when header title area is clicked (for expand/collapse) */
- onToggleCollapse?: () => void;
-
- /** Whether the section is currently collapsed */
- sectionCollapsed?: boolean;
-}
-
-export function AdvancedJsonSectionHeader({
- title,
- titleIcon,
- handleOnCopy,
- controlButtons,
- backgroundColor,
- onToggleCollapse,
- sectionCollapsed,
-}: AdvancedJsonSectionHeaderProps) {
- const [isCopied, setIsCopied] = useState(false);
-
- return (
- <div
- className="io-message-header group-hover:bg-muted/80 flex flex-row items-center justify-between px-1 py-1 text-sm font-medium capitalize transition-colors"
- style={{ backgroundColor }}
- >
- <div
- className="flex flex-1 cursor-pointer items-center gap-2"
- onClick={onToggleCollapse}
- role="button"
- tabIndex={0}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- onToggleCollapse?.();
- }
- }}
- >
- {onToggleCollapse && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- onToggleCollapse();
- }}
- className="hover:bg-accent inline-flex items-center justify-center rounded-sm p-0.5 transition-colors"
- aria-label={
- sectionCollapsed ? "Expand section" : "Collapse section"
- }
- >
- {sectionCollapsed ? (
- <ChevronRight className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- )}
- </button>
- )}
- {titleIcon}
- {title}
- </div>
- <div className="mr-1 flex min-w-0 shrink flex-row items-center gap-1">
- {controlButtons}
- <Button
- title="Copy to clipboard"
- variant="ghost"
- size="icon-xs"
- type="button"
- onClick={(event) => {
- setIsCopied(true);
- handleOnCopy(event);
- setTimeout(() => setIsCopied(false), 1000);
- }}
- className="hover:bg-border -mr-2"
- >
- {isCopied ? (
- <Check className="h-3 w-3" />
- ) : (
- <Copy className="h-3 w-3" />
- )}
- </Button>
- </div>
- </div>
- );
-}
diff --git a/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx
deleted file mode 100644
index 88530680e5..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx
+++ /dev/null
@@ -1,297 +0,0 @@
-/**
- * AdvancedJsonViewer - Main JSON viewer component
- *
- * Self-contained JSON viewer with zero external dependencies (except TanStack Virtual and Radix UI).
- * Combines all sub-components and hooks to provide a complete JSON viewing experience.
- *
- * Features:
- * - Virtualized rendering for large datasets
- * - Search with highlighting and navigation
- * - Expand/collapse with state management
- * - Type-aware syntax highlighting
- * - String truncation with popovers
- * - Copy to clipboard
- * - Optional line numbers
- * - Theme customization
- */
-
-import { useState, useMemo, useCallback, useEffect } from "react";
-import { type AdvancedJsonViewerProps } from "./types";
-import { searchInTree, getMatchCountsPerNode } from "./utils/searchJson";
-import { useJsonTheme } from "./hooks/useJsonTheme";
-import { useSearchNavigationTree } from "./hooks/useSearchNavigationTree";
-import { useTreeState } from "./hooks/useTreeState";
-import { SearchBar } from "./components/SearchBar";
-import { SimpleJsonViewer } from "./SimpleJsonViewer";
-import { VirtualizedJsonViewer } from "./VirtualizedJsonViewer";
-import { debugLog } from "./utils/debug";
-
-/**
- * AdvancedJsonViewer - Self-contained JSON viewer
- */
-export function AdvancedJsonViewer({
- data,
- field = null,
- virtualized: virtualizedProp,
- theme: userTheme,
- initialExpansion = true,
- enableSearch = true,
- searchPlaceholder = "Search JSON...",
- searchQuery: controlledSearchQuery,
- onSearchQueryChange,
- currentMatchIndex: controlledCurrentMatchIndex,
- onCurrentMatchIndexChange,
- matchCounts,
- showLineNumbers = false,
- enableCopy = true,
- stringWrapMode = "wrap",
- onStringWrapModeChange: _onStringWrapModeChange,
- truncateStringsAt = 100,
- className,
- isLoading = false,
- error,
- scrollContainerRef,
- commentedPaths,
-}: AdvancedJsonViewerProps) {
- debugLog("[AdvancedJsonViewer] RENDER");
- // Resolve theme
- const theme = useJsonTheme(userTheme);
-
- // Search state management
- const [internalSearchQuery, setInternalSearchQuery] = useState("");
- const [internalCurrentMatchIndex, setInternalCurrentMatchIndex] = useState(0);
-
- const isSearchControlled =
- controlledSearchQuery !== undefined && onSearchQueryChange !== undefined;
- const searchQuery = isSearchControlled
- ? controlledSearchQuery
- : internalSearchQuery;
-
- const isMatchIndexControlled =
- controlledCurrentMatchIndex !== undefined &&
- onCurrentMatchIndexChange !== undefined;
- const currentMatchIndex = isMatchIndexControlled
- ? controlledCurrentMatchIndex
- : internalCurrentMatchIndex;
-
- // Build tree from JSON data (sync for <10K, worker for >10K)
- // JIT expansion: reads from storage directly, no context subscription
- // Tree building uses FULL untruncated widths (data layer)
- const {
- tree,
- isBuilding,
- buildError,
- expansionVersion,
- handleToggleExpansion: treeHandleToggleExpansion,
- } = useTreeState(data, field, initialExpansion, {
- rootKey: "root",
- indentSizePx: theme.indentSize,
- });
-
- // Search matches
- const searchMatches = useMemo(() => {
- debugLog("[AdvancedJsonViewer] Computing searchMatches");
- return tree
- ? searchInTree(tree, searchQuery, { caseSensitive: false })
- : [];
- }, [tree, searchQuery]);
-
- // Calculate match counts for collapsed nodes
- const calculatedMatchCounts = useMemo(() => {
- debugLog("[AdvancedJsonViewer] Computing calculatedMatchCounts");
- return tree && searchMatches.length > 0
- ? getMatchCountsPerNode(tree, searchMatches)
- : matchCounts;
- }, [tree, searchMatches, matchCounts]);
-
- // Reset match index when matches change
- useEffect(() => {
- if (searchMatches.length > 0 && currentMatchIndex >= searchMatches.length) {
- if (isMatchIndexControlled) {
- onCurrentMatchIndexChange(0);
- } else {
- setInternalCurrentMatchIndex(0);
- }
- }
- }, [
- searchMatches,
- currentMatchIndex,
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- ]);
-
- // Determine if virtualization should be used
- // Use initial tree size (totalNodeCount) rather than current visible rows
- // This decision should be stable regardless of expansion state
- const shouldUseVirtualization = useMemo(() => {
- if (virtualizedProp !== undefined) return virtualizedProp;
- if (!tree) return false;
-
- // Virtualize if tree has more than 500 nodes total
- // This is based on the initial data structure size, not current expansion
- return tree.totalNodeCount > 500;
- }, [virtualizedProp, tree]);
-
- // Use tree's built-in toggle (already O(log n), no spinner needed)
- const handleToggleExpansion = treeHandleToggleExpansion;
-
- // Search navigation
- const {
- handleNextMatch,
- handlePreviousMatch,
- handleClearSearch,
- scrollToIndex,
- } = useSearchNavigationTree({
- searchMatches,
- currentMatchIndex,
- tree,
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- setInternalCurrentMatchIndex,
- onToggleExpansion: treeHandleToggleExpansion,
- });
-
- // Handle search
- const handleSearch = useCallback(
- (query: string) => {
- if (isSearchControlled) {
- onSearchQueryChange(query);
- } else {
- setInternalSearchQuery(query);
- }
-
- // Reset match index to 0 when search query changes
- if (isMatchIndexControlled) {
- onCurrentMatchIndexChange(0);
- } else {
- setInternalCurrentMatchIndex(0);
- }
- },
- [
- isSearchControlled,
- onSearchQueryChange,
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- ],
- );
-
- // Wrap handleClearSearch to pass required params
- const handleClearSearchWrapped = useCallback(() => {
- handleClearSearch(
- isSearchControlled,
- onSearchQueryChange,
- setInternalSearchQuery,
- );
- }, [handleClearSearch, isSearchControlled, onSearchQueryChange]);
-
- // Common viewer props - memoized to prevent unnecessary re-renders
- // MUST be defined before early returns to satisfy React Hooks rules
- const viewerProps = useMemo(() => {
- debugLog("[AdvancedJsonViewer] Creating viewerProps object");
- return {
- tree,
- expansionVersion,
- theme,
- searchMatches,
- currentMatchIndex,
- matchCounts: calculatedMatchCounts,
- showLineNumbers,
- enableCopy,
- stringWrapMode,
- truncateStringsAt,
- onToggleExpansion: handleToggleExpansion,
- scrollToIndex,
- scrollContainerRef,
- totalLineCount: tree?.totalNodeCount,
- commentedPaths,
- };
- }, [
- tree,
- expansionVersion,
- theme,
- searchMatches,
- currentMatchIndex,
- calculatedMatchCounts,
- showLineNumbers,
- enableCopy,
- stringWrapMode,
- truncateStringsAt,
- handleToggleExpansion,
- scrollToIndex,
- scrollContainerRef,
- commentedPaths,
- ]);
-
- // Early returns for special states
- // Loading state
- if (isLoading) {
- return (
- <div className={className} style={{ padding: "16px" }}>
- <div className="text-muted-foreground text-sm">Loading...</div>
- </div>
- );
- }
-
- // Error state
- if (error) {
- const errorMessage = typeof error === "string" ? error : error.message;
- return (
- <div className={className} style={{ padding: "16px" }}>
- <div className="text-destructive text-sm">Error: {errorMessage}</div>
- </div>
- );
- }
-
- // Build error state
- if (buildError) {
- return (
- <div className={className} style={{ padding: "16px" }}>
- <div className="text-destructive text-sm">
- Error building tree: {buildError}
- </div>
- </div>
- );
- }
-
- // Building state (show ONLY during initial load)
- if (isBuilding && !tree) {
- return (
- <div className={className} style={{ padding: "16px" }}>
- <div className="text-muted-foreground text-sm">Processing JSON...</div>
- </div>
- );
- }
-
- return (
- <div
- className={className}
- style={{
- display: "flex",
- flexDirection: "column",
- ...(shouldUseVirtualization && { height: "100%" }),
- }}
- >
- {/* Search bar */}
- {enableSearch && (
- <SearchBar
- onSearch={handleSearch}
- matches={searchMatches}
- currentIndex={currentMatchIndex}
- onNext={handleNextMatch}
- onPrevious={handlePreviousMatch}
- onClear={handleClearSearchWrapped}
- placeholder={searchPlaceholder}
- />
- )}
-
- {/* Viewer - conditionally render without creating new component references */}
- <div style={{ flex: 1, minHeight: 0 }}>
- {shouldUseVirtualization ? (
- <VirtualizedJsonViewer {...viewerProps} />
- ) : (
- <SimpleJsonViewer {...viewerProps} />
- )}
- </div>
- </div>
- );
-}
diff --git a/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx
deleted file mode 100644
index a9cbf325d5..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx
+++ /dev/null
@@ -1,217 +0,0 @@
-/**
- * SimpleJsonViewer - Non-virtualized JSON viewer
- *
- * Renders all rows without virtualization.
- * Best for small datasets (<500 rows) where virtualization overhead isn't worth it.
- */
-
-import { useEffect, useMemo, useRef, memo, type RefObject } from "react";
-import { type SearchMatch, type JSONTheme, type StringWrapMode } from "./types";
-import type { TreeState } from "./utils/treeStructure";
-import { getAllVisibleNodes, treeNodeToFlatRow } from "./utils/treeNavigation";
-import { JsonRowFixed } from "./components/JsonRowFixed";
-import { JsonRowScrollable } from "./components/JsonRowScrollable";
-import { useJsonSearch } from "./hooks/useJsonSearch";
-import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";
-import { pathArrayToJsonPath } from "./utils/pathUtils";
-import { debugLog } from "./utils/debug";
-
-interface SimpleJsonViewerProps {
- tree: TreeState | null;
- expansionVersion: number; // Triggers re-render on expansion changes
- theme: JSONTheme;
- searchMatches?: SearchMatch[];
- currentMatchIndex?: number;
- matchCounts?: Map<string, number>; // Row ID -> count of matches in row and descendants
- showLineNumbers?: boolean;
- enableCopy?: boolean;
- stringWrapMode?: StringWrapMode;
- truncateStringsAt?: number | null;
- onToggleExpansion?: (rowId: string) => void;
- className?: string;
- scrollToIndex?: number; // For search navigation
- scrollContainerRef?: RefObject<HTMLDivElement | null>; // Parent scroll container
- totalLineCount?: number; // Total number of lines when fully expanded (for line number width calculation)
- commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
-}
-
-export const SimpleJsonViewer = memo(function SimpleJsonViewer({
- tree,
- expansionVersion,
- theme,
- searchMatches = [],
- currentMatchIndex = 0,
- matchCounts,
- showLineNumbers = false,
- enableCopy = false,
- stringWrapMode = "wrap",
- truncateStringsAt = null,
- onToggleExpansion,
- className,
- scrollToIndex,
- scrollContainerRef: _scrollContainerRef,
- totalLineCount,
- commentedPaths,
-}: SimpleJsonViewerProps) {
- debugLog("[SimpleJsonViewer] RENDER");
-
- // Get rows from tree
- const effectiveRows = useMemo(() => {
- if (!tree) return [];
- const visibleNodes = getAllVisibleNodes(tree.rootNode);
- return visibleNodes.map((node, index) => treeNodeToFlatRow(node, index));
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [tree, expansionVersion]); // expansionVersion forces re-computation on expand/collapse
-
- // Refs for scroll-to-match functionality
- const containerRef = useRef<HTMLDivElement>(null);
- const rowRefs = useRef<Map<string, HTMLDivElement>>(new Map());
-
- // Layout calculations (widths, heights, column sizes)
- const {
- maxLineNumberDigits,
- fixedColumnWidth,
- scrollableMinWidth,
- scrollableMaxWidth,
- } = useJsonViewerLayout({
- tree,
- expansionVersion,
- theme,
- showLineNumbers,
- totalLineCount,
- stringWrapMode,
- truncateStringsAt,
- });
-
- // Search-related calculations
- const { matchMap, currentMatch, currentMatchIndexInRow } = useJsonSearch(
- searchMatches,
- currentMatchIndex,
- );
-
- // Scroll to match when search navigation occurs
- useEffect(() => {
- if (
- scrollToIndex !== undefined &&
- scrollToIndex >= 0 &&
- scrollToIndex < effectiveRows.length
- ) {
- const row = effectiveRows[scrollToIndex];
- if (row) {
- const element = rowRefs.current.get(row.id);
- if (element) {
- element.scrollIntoView({
- behavior: "auto",
- block: "center",
- inline: "nearest",
- });
- }
- }
- }
- }, [scrollToIndex, effectiveRows]);
- // Note: rowRefs is a stable ref from useScrollPreservation hook, doesn't need to be in deps
-
- return (
- <div
- ref={containerRef}
- className={className}
- style={{
- width: stringWrapMode === "wrap" ? "100%" : "fit-content",
- minWidth: "100%",
- backgroundColor: theme.background,
- color: theme.foreground,
- fontFamily: "monospace",
- }}
- >
- <div style={{ position: "relative" }}>
- {effectiveRows.map((row, index) => {
- const searchMatch = matchMap.get(row.id);
- const isCurrentMatch = currentMatch?.rowId === row.id;
- const matchCount = matchCounts?.get(row.id);
- const rowJsonPath = pathArrayToJsonPath(row.pathArray);
- const commentRanges = commentedPaths?.get(rowJsonPath);
-
- return (
- <div
- key={row.id}
- ref={(el) => {
- if (el) {
- rowRefs.current.set(row.id, el);
- } else {
- rowRefs.current.delete(row.id);
- }
- }}
- style={{
- display: "grid",
- gridTemplateColumns: `${fixedColumnWidth}px auto`,
- width: stringWrapMode === "nowrap" ? undefined : "100%",
- }}
- >
- {/* Fixed column (line numbers + expand buttons) - sticky within row */}
- <div
- style={{
- position: "sticky",
- left: 0,
- zIndex: 1,
- width: `${fixedColumnWidth}px`,
- backgroundColor: theme.background,
- }}
- >
- <JsonRowFixed
- row={row}
- theme={theme}
- showLineNumber={showLineNumbers}
- lineNumber={row.absoluteLineNumber ?? index + 1}
- maxLineNumberDigits={maxLineNumberDigits}
- searchMatch={searchMatch}
- isCurrentMatch={isCurrentMatch}
- matchCount={matchCount}
- currentMatchIndexInRow={
- isCurrentMatch ? currentMatchIndexInRow : undefined
- }
- onToggleExpansion={onToggleExpansion}
- stringWrapMode={stringWrapMode}
- />
- </div>
-
- {/* Scrollable column (indent + key + value + copy) */}
- <div
- style={{
- width: "fit-content",
- minWidth: scrollableMinWidth
- ? `${scrollableMinWidth}px`
- : undefined,
- maxWidth: scrollableMaxWidth
- ? `${scrollableMaxWidth}px`
- : undefined,
- }}
- >
- <JsonRowScrollable
- row={row}
- theme={theme}
- stringWrapMode={stringWrapMode}
- truncateStringsAt={truncateStringsAt}
- enableCopy={enableCopy}
- searchMatch={searchMatch}
- isCurrentMatch={isCurrentMatch}
- jsonPath={rowJsonPath}
- commentRanges={commentRanges}
- />
- </div>
- </div>
- );
- })}
- </div>
-
- {/* Empty state */}
- {effectiveRows.length === 0 && (
- <div
- className="text-muted-foreground flex items-center justify-center p-8"
- style={{ fontSize: theme.fontSize }}
- >
- No data to display
- </div>
- )}
- </div>
- );
-});
diff --git a/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx
deleted file mode 100644
index 3d88d8c813..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx
+++ /dev/null
@@ -1,262 +0,0 @@
-/**
- * VirtualizedJsonViewer - Virtualized JSON viewer using TanStack Virtual
- *
- * Renders only visible rows for optimal performance with large datasets.
- * Uses @tanstack/react-virtual which is already in project dependencies.
- */
-
-import { useRef, useEffect, useMemo, memo, type RefObject } from "react";
-import { useVirtualizer } from "@tanstack/react-virtual";
-import { type SearchMatch, type JSONTheme, type StringWrapMode } from "./types";
-import type { TreeState } from "./utils/treeStructure";
-import { getNodeByIndex, treeNodeToFlatRow } from "./utils/treeNavigation";
-import { JsonRowFixed } from "./components/JsonRowFixed";
-import { JsonRowScrollable } from "./components/JsonRowScrollable";
-import { useJsonSearch } from "./hooks/useJsonSearch";
-import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";
-import { pathArrayToJsonPath } from "./utils/pathUtils";
-import { useMonospaceCharWidth } from "./hooks/useMonospaceCharWidth";
-
-interface VirtualizedJsonViewerProps {
- tree: TreeState | null;
- expansionVersion: number; // Triggers re-render on expansion changes
- theme: JSONTheme;
- searchMatches?: SearchMatch[];
- currentMatchIndex?: number;
- matchCounts?: Map<string, number>; // Row ID -> count of matches in row and descendants
- showLineNumbers?: boolean;
- enableCopy?: boolean;
- stringWrapMode?: StringWrapMode;
- truncateStringsAt?: number | null;
- onToggleExpansion?: (rowId: string) => void;
- className?: string;
- scrollToIndex?: number; // For search navigation
- scrollContainerRef?: RefObject<HTMLDivElement | null>; // Parent scroll container
- totalLineCount?: number; // Total number of lines when fully expanded (for line number width calculation)
- commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
-}
-
-export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({
- tree,
- expansionVersion,
- theme,
- searchMatches = [],
- currentMatchIndex = 0,
- matchCounts,
- showLineNumbers = false,
- enableCopy = false,
- stringWrapMode = "wrap",
- truncateStringsAt = null,
- onToggleExpansion,
- className,
- scrollToIndex,
- scrollContainerRef,
- totalLineCount,
- commentedPaths,
-}: VirtualizedJsonViewerProps) {
- const parentRef = useRef<HTMLDivElement>(null);
-
- // Measure actual monospace character width for accurate height estimation
- const charWidth = useMonospaceCharWidth();
-
- // Determine row count
- // NOTE: Must recalculate when expansionVersion changes because tree is mutated in place
- const rowCount = tree ? 1 + tree.rootNode.visibleDescendantCount : 0;
-
- // Layout calculations (widths, heights, column sizes)
- const {
- maxLineNumberDigits,
- fixedColumnWidth,
- scrollableMinWidth,
- scrollableMaxWidth,
- estimateSize,
- } = useJsonViewerLayout({
- tree,
- expansionVersion,
- theme,
- showLineNumbers,
- totalLineCount,
- stringWrapMode,
- truncateStringsAt,
- charWidth,
- });
-
- // Search-related calculations
- const { matchMap, currentMatch, currentMatchIndexInRow } = useJsonSearch(
- searchMatches,
- currentMatchIndex,
- );
-
- // Initialize virtualizer
- // NOTE: We provide getItemKey using node IDs so the virtualizer can detect when
- // the content at a given index changes (e.g., after expand/collapse).
- // This ensures cached measurements are invalidated when different nodes move to the same index.
- const rowVirtualizer = useVirtualizer({
- count: rowCount,
- getScrollElement: () => scrollContainerRef?.current || parentRef.current,
- estimateSize,
- overscan: 500, // Render 500 extra rows above/below viewport
- measureElement:
- typeof window !== "undefined"
- ? (element) => element.getBoundingClientRect().height
- : undefined,
- getItemKey: (index) => {
- if (!tree) return index;
- const node = getNodeByIndex(tree.rootNode, index);
- return node ? node.id : index;
- },
- });
-
- // Use tree toggle directly (scroll restoration is handled by tree expansion logic)
- const finalHandleToggleExpansion = onToggleExpansion;
-
- // Scroll to match when search navigation occurs
- useEffect(() => {
- if (
- scrollToIndex !== undefined &&
- scrollToIndex >= 0 &&
- scrollToIndex < rowCount
- ) {
- rowVirtualizer.scrollToIndex(scrollToIndex, {
- align: "center",
- behavior: "auto", // Use "auto" instead of "smooth" for dynamic sizing
- });
- }
- }, [scrollToIndex, rowVirtualizer, rowCount]);
-
- const virtualRows = rowVirtualizer.getVirtualItems();
-
- // Calculate total content width (PRESENTATION LAYER)
- const totalContentWidth = useMemo(() => {
- if (!tree) return undefined;
-
- // For nowrap mode: use full untruncated width from tree
- if (stringWrapMode === "nowrap") {
- return fixedColumnWidth + tree.maxContentWidth;
- }
-
- // For wrap/truncate: use constrained width from scrollableMaxWidth
- if (scrollableMaxWidth) {
- return fixedColumnWidth + scrollableMaxWidth;
- }
-
- return undefined;
- }, [tree, fixedColumnWidth, stringWrapMode, scrollableMaxWidth]);
-
- return (
- <div
- ref={parentRef}
- className={className}
- style={{
- height: "100%",
- width: stringWrapMode === "wrap" ? "100%" : "fit-content",
- minWidth: "100%",
- backgroundColor: theme.background,
- color: theme.foreground,
- }}
- >
- <div
- style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- position: "relative",
- width: totalContentWidth ? `${totalContentWidth}px` : "max-content",
- }}
- >
- {virtualRows.map((virtualRow) => {
- // Get row from tree
- if (!tree) return null;
-
- const node = getNodeByIndex(tree.rootNode, virtualRow.index);
- if (!node) return null;
-
- const row = treeNodeToFlatRow(node, virtualRow.index);
-
- const searchMatch = matchMap.get(row.id);
- const isCurrentMatch = currentMatch?.rowId === row.id;
- const matchCount = matchCounts?.get(row.id);
- const rowJsonPath = pathArrayToJsonPath(row.pathArray);
- const commentRanges = commentedPaths?.get(rowJsonPath);
-
- return (
- <div
- key={row.id}
- data-index={virtualRow.index}
- ref={rowVirtualizer.measureElement}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: totalContentWidth ? `${totalContentWidth}px` : "100%",
- transform: `translateY(${virtualRow.start}px)`,
- display: "grid",
- gridTemplateColumns: `${fixedColumnWidth}px auto`,
- }}
- >
- {/* Fixed column (line numbers + expand buttons) - sticky within row */}
- <div
- style={{
- position: "sticky",
- left: 0,
- zIndex: 1,
- width: `${fixedColumnWidth}px`,
- backgroundColor: theme.background,
- }}
- >
- <JsonRowFixed
- row={row}
- theme={theme}
- showLineNumber={showLineNumbers}
- lineNumber={row.absoluteLineNumber ?? virtualRow.index + 1}
- maxLineNumberDigits={maxLineNumberDigits}
- searchMatch={searchMatch}
- isCurrentMatch={isCurrentMatch}
- matchCount={matchCount}
- currentMatchIndexInRow={
- isCurrentMatch ? currentMatchIndexInRow : undefined
- }
- onToggleExpansion={finalHandleToggleExpansion}
- stringWrapMode={stringWrapMode}
- />
- </div>
-
- {/* Scrollable column (indent + key + value + copy) */}
- <div
- style={{
- width: "fit-content",
- minWidth: scrollableMinWidth
- ? `${scrollableMinWidth}px`
- : undefined,
- maxWidth: scrollableMaxWidth
- ? `${scrollableMaxWidth}px`
- : undefined,
- }}
- >
- <JsonRowScrollable
- row={row}
- theme={theme}
- stringWrapMode={stringWrapMode}
- truncateStringsAt={truncateStringsAt}
- enableCopy={enableCopy}
- searchMatch={searchMatch}
- isCurrentMatch={isCurrentMatch}
- jsonPath={rowJsonPath}
- commentRanges={commentRanges}
- />
- </div>
- </div>
- );
- })}
- </div>
-
- {/* Empty state */}
- {rowCount === 0 && (
- <div
- className="text-muted-foreground flex items-center justify-center p-8"
- style={{ fontSize: theme.fontSize }}
- >
- No data to display
- </div>
- )}
- </div>
- );
-});
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/SearchBar.tsx b/web/src/components/ui/AdvancedJsonViewer/components/SearchBar.tsx
deleted file mode 100644
index 23f3565858..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/components/SearchBar.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * SearchBar - Search UI component
- *
- * Provides search input with match navigation (prev/next).
- * Shows match count and current match index.
- */
-
-import { useState, useEffect } from "react";
-import { ChevronUp, ChevronDown, X } from "lucide-react";
-import { type SearchMatch } from "../types";
-
-interface SearchBarProps {
- onSearch: (query: string) => void;
- matches: SearchMatch[];
- currentIndex: number;
- onNext: () => void;
- onPrevious: () => void;
- onClear: () => void;
- placeholder?: string;
- /** Controlled query value (for external state management) */
- value?: string;
- /** Callback for immediate query changes (no debounce) */
- onValueChange?: (value: string) => void;
-}
-
-export function SearchBar({
- onSearch,
- matches,
- currentIndex,
- onNext,
- onPrevious,
- onClear,
- placeholder = "Search JSON...",
- value: controlledValue,
- onValueChange,
-}: SearchBarProps) {
- const [internalQuery, setInternalQuery] = useState("");
-
- const isControlled =
- controlledValue !== undefined && onValueChange !== undefined;
- const query = isControlled ? controlledValue : internalQuery;
-
- // Debounced search (only when uncontrolled)
- useEffect(() => {
- if (isControlled) return; // Skip debouncing for controlled mode
-
- const timer = setTimeout(() => {
- onSearch(internalQuery);
- }, 300);
-
- return () => clearTimeout(timer);
- }, [internalQuery, onSearch, isControlled]);
-
- const handleClear = () => {
- if (isControlled) {
- onValueChange("");
- onSearch("");
- } else {
- setInternalQuery("");
- }
- onClear();
- };
-
- const handleChange = (value: string) => {
- if (isControlled) {
- onValueChange(value);
- // In controlled mode, parent handles debouncing, so call onSearch immediately
- onSearch(value);
- } else {
- setInternalQuery(value);
- }
- };
-
- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
- if (e.key === "Enter") {
- e.preventDefault();
- if (matches.length > 0) {
- if (e.shiftKey) {
- onPrevious();
- } else {
- onNext();
- }
- }
- } else if (e.key === "Escape") {
- handleClear();
- }
- };
-
- const hasMatches = matches.length > 0;
- const showControls = query.trim() !== "";
-
- return (
- <div className="bg-background flex items-center gap-2 border-b px-3 py-2">
- {/* Search input */}
- <div className="bg-background flex min-w-0 flex-1 items-center gap-1 rounded-md border px-2 py-1">
- <input
- type="text"
- placeholder={placeholder}
- value={query}
- onChange={(e) => handleChange(e.target.value)}
- onKeyDown={handleKeyDown}
- className="min-w-0 flex-1 border-none bg-transparent text-sm focus:ring-0 focus:outline-hidden"
- aria-label="Search JSON"
- />
-
- {/* Match counter */}
- {showControls && (
- <span
- className="text-muted-foreground min-w-[70px] text-right text-xs whitespace-nowrap"
- aria-live="polite"
- >
- {hasMatches
- ? `${currentIndex + 1} of ${matches.length}`
- : "No matches"}
- </span>
- )}
- </div>
-
- {/* Navigation buttons */}
- {showControls && (
- <div className="flex items-center gap-1">
- <button
- type="button"
- onClick={onPrevious}
- disabled={!hasMatches}
- className="hover:bg-accent hover:text-accent-foreground inline-flex items-center justify-center rounded-md p-1 transition-colors disabled:cursor-not-allowed disabled:opacity-30"
- aria-label="Previous match (Shift+Enter)"
- title="Previous match (Shift+Enter)"
- >
- <ChevronUp size={16} />
- </button>
-
- <button
- type="button"
- onClick={onNext}
- disabled={!hasMatches}
- className="hover:bg-accent hover:text-accent-foreground inline-flex items-center justify-center rounded-md p-1 transition-colors disabled:cursor-not-allowed disabled:opacity-30"
- aria-label="Next match (Enter)"
- title="Next match (Enter)"
- >
- <ChevronDown size={16} />
- </button>
-
- <button
- type="button"
- onClick={handleClear}
- className="hover:bg-accent hover:text-accent-foreground inline-flex items-center justify-center rounded-md p-1 transition-colors"
- aria-label="Clear search (Escape)"
- title="Clear search (Escape)"
- >
- <X size={16} />
- </button>
- </div>
- )}
- </div>
- );
-}
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/SimpleSectionHeader.tsx b/web/src/components/ui/AdvancedJsonViewer/components/SimpleSectionHeader.tsx
deleted file mode 100644
index 2244abc162..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/components/SimpleSectionHeader.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { ChevronRight, ChevronDown } from "lucide-react";
-import { useSectionContext } from "../contexts/SectionContext";
-
-export interface SimpleSectionHeaderProps {
- title: string;
- sectionKey: string;
-}
-
-/**
- * Simple collapsible section header
- *
- * Shows: [ChevronRight/ChevronDown] Title (N rows)
- *
- * Uses useSectionContext to access section state and toggle function
- */
-export function SimpleSectionHeader({
- title,
- sectionKey,
-}: SimpleSectionHeaderProps) {
- const context = useSectionContext(sectionKey);
-
- return (
- <div
- style={{
- display: "flex",
- alignItems: "center",
- padding: "6px 8px",
- cursor: "pointer",
- userSelect: "none",
- fontSize: "0.875rem",
- fontWeight: 500,
- }}
- onClick={() => context.setExpanded(!context.isExpanded)}
- >
- <span
- style={{
- marginRight: "8px",
- width: "16px",
- display: "inline-flex",
- alignItems: "center",
- justifyContent: "center",
- opacity: 0.5,
- }}
- >
- {context.isExpanded ? (
- <ChevronDown size={14} />
- ) : (
- <ChevronRight size={14} />
- )}
- </span>
- <span>{title}</span>
- <span style={{ marginLeft: "8px", color: "#6b7280", fontWeight: 400 }}>
- {context.rowCount} rows
- </span>
- </div>
- );
-}
diff --git a/web/src/components/ui/AdvancedJsonViewer/hooks/useSearchNavigationTree.ts b/web/src/components/ui/AdvancedJsonViewer/hooks/useSearchNavigationTree.ts
deleted file mode 100644
index a442c23ebb..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/hooks/useSearchNavigationTree.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * useSearchNavigationTree - Tree-based search navigation hook
- *
- * Handles:
- * - Navigating to next/previous search matches in tree mode
- * - Clearing search
- * - Auto-expanding ancestors to show matches
- * - Computing scroll-to index using tree navigation
- *
- * Tree-compatible version of useSearchNavigation
- */
-
-import { useMemo, useCallback } from "react";
-import type { SearchMatch } from "../types";
-import type { TreeState } from "../utils/treeStructure";
-import { expandToMatch_Tree, findNodeVisibleIndex } from "../utils/searchJson";
-
-interface UseSearchNavigationTreeParams {
- searchMatches: SearchMatch[];
- currentMatchIndex: number;
- tree: TreeState | null;
- isMatchIndexControlled: boolean;
- onCurrentMatchIndexChange?: (index: number) => void;
- setInternalCurrentMatchIndex: (index: number) => void;
- onToggleExpansion: (nodeId: string) => void; // Tree-based toggle (unused but kept for future)
-}
-
-export function useSearchNavigationTree({
- searchMatches,
- currentMatchIndex,
- tree,
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- setInternalCurrentMatchIndex,
- onToggleExpansion: _onToggleExpansion,
-}: UseSearchNavigationTreeParams) {
- // Navigate to next match
- const handleNextMatch = useCallback(() => {
- if (searchMatches.length === 0 || !tree) return;
-
- const nextIndex = (currentMatchIndex + 1) % searchMatches.length;
-
- if (isMatchIndexControlled) {
- onCurrentMatchIndexChange?.(nextIndex);
- } else {
- setInternalCurrentMatchIndex(nextIndex);
- }
-
- // Expand ancestors to show the match
- const match = searchMatches[nextIndex];
- if (match) {
- expandToMatch_Tree(tree, match);
- // Trigger re-render by toggling (expansion is already done, this is just for UI sync)
- // Note: expandToMatch_Tree mutates tree in place, caller needs to handle expansionVersion increment
- }
- }, [
- searchMatches,
- currentMatchIndex,
- tree,
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- setInternalCurrentMatchIndex,
- ]);
-
- // Navigate to previous match
- const handlePreviousMatch = useCallback(() => {
- if (searchMatches.length === 0 || !tree) return;
-
- const prevIndex =
- (currentMatchIndex - 1 + searchMatches.length) % searchMatches.length;
-
- if (isMatchIndexControlled) {
- onCurrentMatchIndexChange?.(prevIndex);
- } else {
- setInternalCurrentMatchIndex(prevIndex);
- }
-
- // Expand ancestors to show the match
- const match = searchMatches[prevIndex];
- if (match) {
- expandToMatch_Tree(tree, match);
- }
- }, [
- searchMatches,
- currentMatchIndex,
- tree,
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- setInternalCurrentMatchIndex,
- ]);
-
- // Clear search
- const handleClearSearch = useCallback(
- (
- isSearchControlled: boolean,
- onSearchQueryChange?: (query: string) => void,
- setInternalSearchQuery?: (query: string) => void,
- ) => {
- if (isSearchControlled) {
- onSearchQueryChange?.("");
- } else {
- setInternalSearchQuery?.("");
- }
-
- // Reset match index
- if (isMatchIndexControlled) {
- onCurrentMatchIndexChange?.(0);
- } else {
- setInternalCurrentMatchIndex(0);
- }
- },
- [
- isMatchIndexControlled,
- onCurrentMatchIndexChange,
- setInternalCurrentMatchIndex,
- ],
- );
-
- // Compute scroll-to index for current match
- const scrollToIndex = useMemo(() => {
- if (searchMatches.length === 0 || !tree) return undefined;
-
- const currentMatch = searchMatches[currentMatchIndex];
- if (!currentMatch) return undefined;
-
- // Find visible index of matched node
- return findNodeVisibleIndex(tree, currentMatch.rowId);
- }, [searchMatches, currentMatchIndex, tree]);
-
- return {
- handleNextMatch,
- handlePreviousMatch,
- handleClearSearch,
- scrollToIndex: scrollToIndex !== -1 ? scrollToIndex : undefined,
- };
-}
diff --git a/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.ts b/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.ts
deleted file mode 100644
index 400bf3058f..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.ts
+++ /dev/null
@@ -1,323 +0,0 @@
-/**
- * React hook for tree state management
- *
- * Manages tree building, expansion state, and synchronization with context.
- * Implements the 10K threshold for sync vs Web Worker build.
- *
- * Key features:
- * - Tree is source of truth after initialization
- * - Uses expansionVersion counter to trigger virtualizer updates
- * - Syncs expansion state back to context without causing re-renders
- * - Handles both small (sync) and large (worker) datasets
- */
-
-import { useState, useMemo, useRef, useCallback, useEffect } from "react";
-import { useQuery } from "@tanstack/react-query";
-import type { ExpansionState } from "../types";
-import type { TreeState } from "../utils/treeStructure";
-import {
- buildTreeFromJSON,
- estimateNodeCount,
- TREE_BUILD_THRESHOLD,
-} from "../utils/treeStructure";
-import {
- toggleNodeExpansion,
- exportExpansionState,
-} from "../utils/treeExpansion";
-import { debugLog, debugError } from "../utils/debug";
-import {
- readFormattedExpansion,
- writeFormattedExpansion,
-} from "@/src/components/trace2/contexts/JsonExpansionContext";
-import { useDebounce } from "@/src/hooks/useDebounce";
-import { useMonospaceCharWidth } from "./useMonospaceCharWidth";
-
-/**
- * Configuration for tree building
- */
-interface UseTreeStateConfig {
- rootKey?: string;
- expandDepth?: number;
- indentSizePx?: number; // Theme indent size for width calculation (data layer only)
-}
-
-/**
- * Return value from useTreeState
- */
-interface UseTreeStateReturn {
- tree: TreeState | null;
- isBuilding: boolean;
- isReady: boolean;
- buildTime: number | undefined;
- buildError: string | null;
- expansionVersion: number; // Counter that increments on every expansion change
- handleToggleExpansion: (nodeId: string) => void;
-}
-
-/**
- * Build tree in Web Worker (for large datasets)
- */
-async function buildTreeInWorker(
- data: unknown,
- config: Parameters<typeof buildTreeFromJSON>[1],
- dataSize: number,
-): Promise<{ tree: TreeState; buildTime: number }> {
- debugLog(
- `[buildTreeInWorker] Building tree with ${dataSize} nodes in Web Worker`,
- );
-
- return new Promise((resolve, reject) => {
- try {
- // Create Web Worker
- const worker = new Worker(
- new URL("../workers/tree-builder.worker.ts", import.meta.url),
- { type: "module" },
- );
-
- // Send build request
- worker.postMessage({
- type: "build",
- data,
- config,
- });
-
- // Handle response
- worker.onmessage = (event) => {
- if (event.data.type === "success") {
- debugLog(
- `[buildTreeInWorker] Worker completed in ${event.data.buildTime.toFixed(2)}ms`,
- );
- resolve({
- tree: event.data.tree,
- buildTime: event.data.buildTime,
- });
- worker.terminate();
- } else if (event.data.type === "error") {
- debugError("[buildTreeInWorker] Worker error:", event.data.error);
- reject(new Error(event.data.error));
- worker.terminate();
- }
- };
-
- // Handle worker errors
- worker.onerror = (error) => {
- debugError("[buildTreeInWorker] Worker error:", error);
- reject(error);
- worker.terminate();
- };
- } catch (error) {
- debugError(
- "[buildTreeInWorker] Failed to create worker, falling back to sync:",
- error,
- );
- // Fallback to sync build if worker creation fails
- const startTime = performance.now();
- const tree = buildTreeFromJSON(data, config);
- const buildTime = performance.now() - startTime;
- resolve({ tree, buildTime });
- }
- });
-}
-
-/**
- * Hook for managing tree state
- *
- * Handles tree building (sync or worker), expansion state, and storage sync.
- * Uses direct sessionStorage access to avoid context re-renders.
- *
- * @param data - JSON data to build tree from
- * @param field - Field name for storage key (e.g., "input", "output"). If null, no storage persistence.
- * @param initialExpansion - Initial expansion state (only used if field is null)
- * @param config - Tree building configuration
- * @returns Tree state and controls
- */
-export function useTreeState(
- data: unknown,
- field: string | null,
- initialExpansion: ExpansionState = true,
- config: UseTreeStateConfig = {},
-): UseTreeStateReturn {
- const { rootKey = "root", expandDepth, indentSizePx = 16 } = config;
-
- // Measure actual monospace character width for accurate width estimation
- const charWidth = useMonospaceCharWidth();
-
- // Estimate data size once
- const dataSize = useMemo(() => estimateNodeCount(data), [data]);
-
- // Track expansion version (increments on every toggle)
- const [expansionVersion, setExpansionVersion] = useState(0);
-
- // Read expansion state from storage (JIT - only when needed, no context subscription)
- const expansionFromStorage = useMemo(() => {
- if (!field) return initialExpansion;
-
- debugLog(
- `[useTreeState] Reading expansion state from storage for field: ${field}`,
- );
- return readFormattedExpansion(field);
- }, [field, initialExpansion]);
-
- // For small datasets, use direct useMemo (sync build)
- const syncTree = useMemo(() => {
- if (dataSize > TREE_BUILD_THRESHOLD) return null;
-
- debugLog(
- `[useTreeState] Small dataset (${dataSize} nodes), using sync build`,
- );
- const startTime = performance.now();
- const tree = buildTreeFromJSON(data, {
- rootKey,
- initialExpansion: expansionFromStorage,
- expandDepth,
- widthEstimator: {
- charWidthPx: charWidth,
- indentSizePx,
- extraBufferPx: 50,
- },
- });
- const buildTime = performance.now() - startTime;
-
- debugLog(
- `[useTreeState] Sync build completed in ${buildTime.toFixed(2)}ms`,
- );
-
- return { tree, buildTime };
- }, [
- data,
- dataSize,
- rootKey,
- expandDepth,
- expansionFromStorage,
- indentSizePx,
- charWidth,
- ]);
-
- // For large datasets, use React Query + Web Worker
- const asyncTreeQuery = useQuery({
- queryKey: [
- "tree-build",
- data,
- rootKey,
- expandDepth,
- expansionFromStorage,
- indentSizePx,
- charWidth,
- ],
- queryFn: () =>
- buildTreeInWorker(
- data,
- {
- rootKey,
- initialExpansion: expansionFromStorage,
- expandDepth,
- widthEstimator: {
- charWidthPx: charWidth,
- indentSizePx,
- extraBufferPx: 50,
- },
- },
- dataSize,
- ),
- enabled: dataSize > TREE_BUILD_THRESHOLD,
- staleTime: Infinity, // Tree build results don't go stale
- gcTime: 30 * 60 * 1000, // Keep in cache for 30 minutes
- });
-
- // Determine which tree to use
- const treeResult = syncTree || asyncTreeQuery.data;
- const tree = treeResult?.tree ?? null;
- const buildTime = treeResult?.buildTime;
- const isBuilding =
- dataSize > TREE_BUILD_THRESHOLD ? asyncTreeQuery.isLoading : false;
- const isReady = tree !== null;
- const buildError =
- dataSize > TREE_BUILD_THRESHOLD && asyncTreeQuery.error
- ? String(asyncTreeQuery.error)
- : null;
-
- // Store tree in ref for mutation (expand/collapse)
- const treeRef = useRef<TreeState | null>(null);
- useEffect(() => {
- treeRef.current = tree;
- }, [tree]);
-
- // Debounced save to storage (no context, no re-renders)
- const saveExpansionToStorage = useDebounce(
- () => {
- if (!field || !treeRef.current) return;
-
- debugLog(
- `[useTreeState] Saving expansion state to storage for field: ${field}`,
- );
- const state = exportExpansionState(treeRef.current);
- writeFormattedExpansion(field, state);
- },
- 1000, // 1 second debounce
- false, // Don't execute first call immediately
- );
-
- // Handle expansion toggle (JIT - fast O(log n) mutation, debounced storage write)
- const handleToggleExpansion = useCallback(
- (nodeId: string) => {
- if (!treeRef.current) return;
-
- debugLog("[useTreeState] Toggling expansion for node:", nodeId);
- const startTime = performance.now();
-
- // Toggle expansion (mutates tree in place - O(log n), ~0.1ms)
- toggleNodeExpansion(treeRef.current, nodeId);
-
- const toggleTime = performance.now() - startTime;
- debugLog(`[useTreeState] Toggle completed in ${toggleTime.toFixed(2)}ms`);
-
- // Increment expansion version to trigger React re-render (no tree rebuild)
- setExpansionVersion((v) => v + 1);
-
- // Debounced save to storage (after user stops clicking)
- saveExpansionToStorage();
- },
- [saveExpansionToStorage],
- );
-
- return {
- tree,
- isBuilding,
- isReady,
- buildTime,
- buildError,
- expansionVersion,
- handleToggleExpansion,
- };
-}
-
-/**
- * Hook for getting row data from tree (JIT rendering)
- *
- * This hook provides a getNodeByIndex function that can be memoized
- * and used with the virtualizer.
- *
- * @param tree - Tree state
- * @param expansionVersion - Expansion version counter (for cache invalidation)
- * @returns getNodeByIndex function
- */
-export function useTreeRowGetter(
- tree: TreeState | null,
- expansionVersion: number,
-) {
- const getNodeByIndex = useCallback(
- (index: number) => {
- if (!tree) return null;
-
- // Lazy import to avoid circular dependencies
- const { getNodeByIndex: getNode } = require("../utils/treeNavigation");
- return getNode(tree.rootNode, index);
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [tree, expansionVersion], // expansionVersion ensures cache invalidation on expand/collapse
- );
-
- const visibleRowCount = tree ? 1 + tree.rootNode.visibleDescendantCount : 0;
-
- return { getNodeByIndex, visibleRowCount };
-}
diff --git a/web/src/components/ui/AdvancedJsonViewer/workers/tree-builder.worker.ts b/web/src/components/ui/AdvancedJsonViewer/workers/tree-builder.worker.ts
deleted file mode 100644
index fdf0b30b90..0000000000
--- a/web/src/components/ui/AdvancedJsonViewer/workers/tree-builder.worker.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Web Worker for building trees from large JSON datasets
- *
- * Runs tree building off the main thread to prevent UI blocking.
- * Uses the same iterative buildTreeFromJSON function as sync builds.
- *
- * Message protocol:
- * - Input: { type: "build", data: unknown, config: {...} }
- * - Output: { type: "success", tree: TreeState } | { type: "error", error: string }
- */
-
-import type { TreeState } from "../utils/treeStructure";
-import { buildTreeFromJSON } from "../utils/treeStructure";
-
-/**
- * Message types for worker communication
- */
-interface BuildTreeMessage {
- type: "build";
- data: unknown;
- config: Parameters<typeof buildTreeFromJSON>[1];
-}
-
-interface SuccessMessage {
- type: "success";
- tree: TreeState;
- buildTime: number;
-}
-
-interface ErrorMessage {
- type: "error";
- error: string;
-}
-
-type WorkerMessage = BuildTreeMessage;
-type _WorkerResponse = SuccessMessage | ErrorMessage;
-
-/**
- * Handle incoming messages
- */
-self.onmessage = (event: MessageEvent<WorkerMessage>) => {
- const message = event.data;
-
- if (message.type === "build") {
- try {
- const startTime = performance.now();
-
- const tree = buildTreeFromJSON(message.data, message.config);
-
- const buildTime = performance.now() - startTime;
-
- // Send success response
- const response: SuccessMessage = {
- type: "success",
- tree,
- buildTime,
- };
-
- self.postMessage(response);
- } catch (error) {
- console.error("[tree-builder.worker] Build failed:", error);
-
- // Send error response
- const response: ErrorMessage = {
- type: "error",
- error: error instanceof Error ? error.message : String(error),
- };
-
- self.postMessage(response);
- }
- }
-};
-
-// Export empty object to make this a module
-export {};
diff --git a/web/src/features/dashboard/utils/getColorsForCategories.tsx b/web/src/features/dashboard/utils/getColorsForCategories.tsx
deleted file mode 100644
index abbcad9c53..0000000000
--- a/web/src/features/dashboard/utils/getColorsForCategories.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-type Color =
- | "indigo"
- | "cyan"
- | "zinc"
- | "purple"
- | "slate"
- | "gray"
- | "neutral"
- | "stone"
- | "red"
- | "orange"
- | "amber"
- | "yellow"
- | "lime"
- | "green"
- | "emerald"
- | "teal"
- | "sky"
- | "blue"
- | "violet"
- | "fuchsia"
- | "pink"
- | "rose";
-
-const predefinedColors: Color[] = [
- "indigo",
- "cyan",
- "zinc",
- "purple",
- "yellow",
- "red",
- "lime",
- "pink",
- "emerald",
- "teal",
- "fuchsia",
- "sky",
- "blue",
- "orange",
- "violet",
- "rose",
- "green",
- "amber",
- "slate",
- "gray",
- "neutral",
- "stone",
-];
-
-export function getRandomColor() {
- return predefinedColors[Math.floor(Math.random() * predefinedColors.length)];
-}
-
-export function getColorsForCategories(categories: string[]): Color[] {
- if (categories.length <= predefinedColors.length) {
- return predefinedColors.slice(0, categories.length);
- }
- const colors: Color[] = [...predefinedColors];
- while (colors.length < categories.length) {
- colors.push(getRandomColor());
- }
- return colors;
-}
diff --git a/web/src/features/datasets/components/DatasetItemSchemaErrors.tsx b/web/src/features/datasets/components/DatasetItemSchemaErrors.tsx
deleted file mode 100644
index a710b962cc..0000000000
--- a/web/src/features/datasets/components/DatasetItemSchemaErrors.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
-import { AlertCircle } from "lucide-react";
-
-type DatasetError = {
- datasetId: string;
- datasetName: string;
- field: "input" | "expectedOutput";
- errors: Array<{
- path: string;
- message: string;
- }>;
-};
-
-type DatasetItemSchemaErrorsProps = {
- errors: DatasetError[];
-};
-
-export const DatasetItemSchemaErrors: React.FC<
- DatasetItemSchemaErrorsProps
-> = ({ errors }) => {
- if (errors.length === 0) return null;
-
- // Group errors by dataset
- const errorsByDataset = errors.reduce(
- (acc, error) => {
- const key = error.datasetId;
- if (!acc[key]) {
- acc[key] = {
- datasetName: error.datasetName,
- errors: [],
- };
- }
- acc[key].errors.push(error);
- return acc;
- },
- {} as Record<string, { datasetName: string; errors: DatasetError[] }>,
- );
-
- return (
- <Alert variant="destructive" className="mt-4">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle className="text-base font-semibold">
- Schema Validation Failed
- </AlertTitle>
- <AlertDescription className="mt-2 space-y-4">
- <p className="text-sm">
- The data does not match the required schema for this dataset.
- </p>
- {Object.entries(errorsByDataset).map(([datasetId, datasetErrors]) => (
- <div key={datasetId} className="space-y-3">
- {Object.keys(errorsByDataset).length > 1 && (
- <div className="text-sm font-semibold">
- {datasetErrors.datasetName}
- </div>
- )}
- {datasetErrors.errors.map((error, idx) => (
- <div key={idx} className="space-y-2">
- <div className="text-sm font-semibold">
- {error.field === "input" ? "Input" : "Expected Output"}
- </div>
- <ul className="ml-4 space-y-1.5 text-sm">
- {error.errors.map((err, errIdx) => (
- <li key={errIdx} className="list-disc">
- {err.path === "/" ? (
- <span>{err.message}</span>
- ) : (
- <span>
- <span className="font-mono text-xs">
- {err.path.replace(/^\//, "")}
- </span>
- : {err.message}
- </span>
- )}
- </li>
- ))}
- </ul>
- </div>
- ))}
- </div>
- ))}
- </AlertDescription>
- </Alert>
- );
-};
diff --git a/web/src/features/datasets/components/EditDatasetItem.tsx b/web/src/features/datasets/components/EditDatasetItem.tsx
deleted file mode 100644
index 7954d8ff65..0000000000
--- a/web/src/features/datasets/components/EditDatasetItem.tsx
+++ /dev/null
@@ -1,304 +0,0 @@
-import { api } from "@/src/utils/api";
-import * as z from "zod";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useForm } from "react-hook-form";
-import { useEffect, useState, useMemo } from "react";
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/src/components/ui/form";
-import { Button } from "@/src/components/ui/button";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { CodeMirrorEditor } from "@/src/components/editor";
-import { DatasetSchemaHoverCard } from "./DatasetSchemaHoverCard";
-import { useDatasetItemValidation } from "../hooks/useDatasetItemValidation";
-import type { DatasetItemDomain, Prisma } from "@langfuse/shared";
-import { DatasetItemFieldSchemaErrors } from "./DatasetItemFieldSchemaErrors";
-
-const formSchema = z.object({
- input: z.string().refine(
- (value) => {
- if (value === "") return true;
- try {
- JSON.parse(value);
- return true;
- } catch {
- return false;
- }
- },
- {
- message:
- "Invalid input. Please provide a JSON object or double-quoted string.",
- },
- ),
- expectedOutput: z.string().refine(
- (value) => {
- if (value === "") return true;
- try {
- JSON.parse(value);
- return true;
- } catch {
- return false;
- }
- },
- {
- message:
- "Invalid input. Please provide a JSON object or double-quoted string.",
- },
- ),
- metadata: z.string().refine(
- (value) => {
- if (value === "") return true;
- try {
- JSON.parse(value);
- return true;
- } catch {
- return false;
- }
- },
- {
- message:
- "Invalid input. Please provide a JSON object or double-quoted string.",
- },
- ),
-});
-
-type Dataset = {
- id: string;
- name: string;
- inputSchema: Prisma.JsonValue | null;
- expectedOutputSchema: Prisma.JsonValue | null;
-};
-
-export const EditDatasetItem = ({
- projectId,
- datasetItem,
- dataset,
-}: {
- projectId: string;
- datasetItem: DatasetItemDomain | null;
- dataset: Dataset | null;
-}) => {
- const [formError, setFormError] = useState<string | null>(null);
- const [hasChanges, setHasChanges] = useState(false);
- const hasAccess = useHasProjectAccess({
- projectId: projectId,
- scope: "datasets:CUD",
- });
- const utils = api.useUtils();
-
- useEffect(() => {
- if (datasetItem) {
- form.reset({
- input: datasetItem.input
- ? JSON.stringify(datasetItem.input, null, 2)
- : "",
- expectedOutput: datasetItem.expectedOutput
- ? JSON.stringify(datasetItem.expectedOutput, null, 2)
- : "",
- metadata: datasetItem.metadata
- ? JSON.stringify(datasetItem.metadata, null, 2)
- : "",
- });
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [datasetItem?.id]);
-
- const form = useForm({
- resolver: zodResolver(formSchema),
- defaultValues: {
- input: "",
- expectedOutput: "",
- metadata: "",
- },
- });
-
- const inputValue = form.watch("input");
- const expectedOutputValue = form.watch("expectedOutput");
-
- // Track if fields have been touched or modified
- const { touchedFields, dirtyFields } = form.formState;
- const hasInteractedWithInput = touchedFields.input || dirtyFields.input;
- const hasInteractedWithExpectedOutput =
- touchedFields.expectedOutput || dirtyFields.expectedOutput;
-
- // Create dataset array for validation hook
- const datasets = useMemo(() => {
- if (!dataset) return [];
- return [dataset];
- }, [dataset]);
-
- // Validate against dataset schemas
- const validation = useDatasetItemValidation(
- inputValue,
- expectedOutputValue,
- datasets,
- );
-
- // Filter validation errors by field
- const inputErrors = validation.errors.filter((e) => e.field === "input");
- const expectedOutputErrors = validation.errors.filter(
- (e) => e.field === "expectedOutput",
- );
-
- const updateDatasetItemMutation = api.datasets.updateDatasetItem.useMutation({
- onSuccess: () => utils.datasets.invalidate(),
- onError: (error) => setFormError(error.message),
- });
-
- function onSubmit(values: z.infer<typeof formSchema>) {
- if (!!!datasetItem) return;
- updateDatasetItemMutation.mutate({
- projectId: projectId,
- datasetId: datasetItem.datasetId,
- datasetItemId: datasetItem.id,
- input: values.input,
- expectedOutput: values.expectedOutput,
- metadata: values.metadata,
- });
- setHasChanges(false);
- }
-
- return (
- <div className="flex h-full flex-col">
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="flex h-full flex-col"
- onChange={() => setHasChanges(true)}
- >
- <div className="flex items-center justify-end gap-4">
- {formError ? (
- <p className="text-red text-center">
- <span className="font-bold">Error:</span> {formError}
- </p>
- ) : null}
- <Button
- type="submit"
- loading={updateDatasetItemMutation.isPending}
- disabled={
- !hasChanges ||
- !hasAccess ||
- (validation.hasSchemas && !validation.isValid)
- }
- variant={hasChanges ? "default" : "ghost"}
- >
- {hasChanges ? "Save changes" : "Saved"}
- </Button>
- </div>
- <div className="mt-4 flex-1 overflow-auto">
- <div className="space-y-4">
- <div className="grid gap-4 md:grid-cols-2">
- <FormField
- control={form.control}
- name="input"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <FormLabel>Input</FormLabel>
- {dataset?.inputSchema && (
- <DatasetSchemaHoverCard
- schema={dataset.inputSchema}
- schemaType="input"
- showLabel
- />
- )}
- </div>
- <FormControl>
- <CodeMirrorEditor
- mode="json"
- value={field.value}
- onChange={(v) => {
- setHasChanges(true);
- field.onChange(v);
- }}
- editable={hasAccess}
- minHeight={200}
- />
- </FormControl>
- <FormMessage />
- {validation.hasSchemas &&
- inputErrors.length > 0 &&
- hasInteractedWithInput && (
- <DatasetItemFieldSchemaErrors
- errors={inputErrors}
- showDatasetName={false}
- />
- )}
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="expectedOutput"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <FormLabel>Expected output</FormLabel>
- {dataset?.expectedOutputSchema && (
- <DatasetSchemaHoverCard
- schema={dataset.expectedOutputSchema}
- schemaType="expectedOutput"
- showLabel
- />
- )}
- </div>
- <FormControl>
- <CodeMirrorEditor
- mode="json"
- value={field.value}
- onChange={(v) => {
- setHasChanges(true);
- field.onChange(v);
- }}
- editable={hasAccess}
- minHeight={200}
- />
- </FormControl>
- <FormMessage />
- {validation.hasSchemas &&
- expectedOutputErrors.length > 0 &&
- hasInteractedWithExpectedOutput && (
- <DatasetItemFieldSchemaErrors
- errors={expectedOutputErrors}
- showDatasetName={false}
- />
- )}
- </FormItem>
- )}
- />
- </div>
-
- <FormField
- control={form.control}
- name="metadata"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Metadata</FormLabel>
- <FormControl>
- <CodeMirrorEditor
- mode="json"
- value={field.value}
- onChange={(v) => {
- setHasChanges(true);
- field.onChange(v);
- }}
- editable={hasAccess}
- minHeight={100}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- </form>
- </Form>
- </div>
- );
-};
diff --git a/web/src/features/datasets/components/ImportCard.tsx b/web/src/features/datasets/components/ImportCard.tsx
deleted file mode 100644
index 5006779a7e..0000000000
--- a/web/src/features/datasets/components/ImportCard.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import DocPopup from "@/src/components/layouts/doc-popup";
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from "@/src/components/ui/card";
-import { cn } from "@/src/utils/tailwind";
-import { useDraggable, useDroppable } from "@dnd-kit/core";
-import { type UniqueIdentifier } from "@dnd-kit/core";
-import type { CsvColumnPreview } from "@/src/features/datasets/lib/csv/types";
-
-type ImportCardProps = {
- title: string;
- columns: CsvColumnPreview[];
- onColumnSelect: (columnName: string) => void;
- onColumnRemove: (columnName: string) => void;
- id: UniqueIdentifier;
- className?: string;
- info?: string;
- schemaKeys?: string[]; // Schema-driven mode
- schemaKeyMapping?: Map<string, string>; // {schemaKey: csvColumn}
- onSchemaKeyMap?: (schemaKey: string, csvColumn: string) => void;
-};
-
-function DraggableColumn({
- column,
- parentId,
-}: {
- column: CsvColumnPreview;
- parentId: UniqueIdentifier;
-}) {
- const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
- id: column.name,
- data: {
- column,
- fromCardId: parentId,
- },
- });
-
- return (
- <div
- ref={setNodeRef}
- {...listeners}
- {...attributes}
- className={cn(
- "hover:bg-accent cursor-grab rounded-md border p-2 active:cursor-grabbing",
- isDragging && "opacity-30",
- )}
- >
- <div className="flex flex-wrap items-center justify-between space-x-1">
- <span className="text-sm">{column.name}</span>
- <span className="text-muted-foreground text-xs">
- {column.inferredType}
- </span>
- </div>
- </div>
- );
-}
-
-function SchemaKeyDropZone({
- schemaKey,
- mappedColumn,
- parentId,
-}: {
- schemaKey: string;
- mappedColumn?: string;
- parentId: UniqueIdentifier;
-}) {
- const dropId = `${parentId}:${schemaKey}`;
- const { setNodeRef, isOver } = useDroppable({ id: dropId });
-
- return (
- <div
- ref={setNodeRef}
- className={cn(
- "rounded-md border border-dashed p-2 text-sm",
- isOver && "border-primary bg-accent/50",
- mappedColumn ? "bg-accent/20" : "bg-background",
- )}
- >
- <div className="flex items-center justify-between">
- <span className="font-medium">{schemaKey}</span>
- {mappedColumn && (
- <span className="text-muted-foreground text-xs">{mappedColumn}</span>
- )}
- </div>
- </div>
- );
-}
-
-export function ImportCard({
- title,
- columns,
- id,
- className,
- info,
- schemaKeys,
- schemaKeyMapping,
-}: ImportCardProps) {
- const { setNodeRef, isOver } = useDroppable({
- id,
- });
-
- const isSchemaMode = schemaKeys && schemaKeys.length > 0;
-
- return (
- <Card
- ref={setNodeRef}
- className={cn(
- "flex h-full flex-col overflow-hidden",
- !isSchemaMode && isOver && "ring-primary ring-2",
- className,
- )}
- >
- <CardHeader className="shrink-0 p-4 pb-2">
- <CardTitle className="text-lg font-semibold">
- {title}
- {info && <DocPopup description={info} />}
- </CardTitle>
- </CardHeader>
- <CardContent className="min-h-0 flex-1 space-y-1 overflow-y-auto p-4 pt-2">
- {isSchemaMode ? (
- // Schema-driven mode: show schema keys as drop zones
- <>
- {schemaKeys.map((schemaKey) => (
- <SchemaKeyDropZone
- key={schemaKey}
- schemaKey={schemaKey}
- mappedColumn={schemaKeyMapping?.get(schemaKey)}
- parentId={id}
- />
- ))}
- </>
- ) : (
- // Freeform mode: show draggable columns
- <>
- {columns.length === 0 && id !== "unmapped" ? (
- <div className="text-muted-foreground flex h-full items-center justify-center text-sm">
- Drag columns here
- </div>
- ) : (
- columns.map((column) => (
- <DraggableColumn
- key={column.name}
- column={column}
- parentId={id}
- />
- ))
- )}
- </>
- )}
- </CardContent>
- </Card>
- );
-}
diff --git a/web/src/features/datasets/lib/calculateScoreDiff.ts b/web/src/features/datasets/lib/calculateScoreDiff.ts
deleted file mode 100644
index d11da5fa2d..0000000000
--- a/web/src/features/datasets/lib/calculateScoreDiff.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { type BaselineDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";
-import { type AggregatedScoreData } from "@langfuse/shared";
-
-/**
- * Calculate diff between current and baseline score aggregate
- * Returns null if diff cannot be calculated
- */
-export function calculateScoreDiff(
- current: AggregatedScoreData | null,
- baseline: AggregatedScoreData | null,
-): BaselineDiff {
- // Missing data → no diff
- if (!current || !baseline) return null;
-
- // Aggregate scores (no id) → skip
- if (!current.id || !baseline.id) return null;
-
- // Type mismatch → no diff
- if (current.type !== baseline.type) return null;
-
- if (current.type === "NUMERIC" && baseline.type === "NUMERIC") {
- const diff = current.average - baseline.average;
-
- // Same value → no diff
- if (diff === 0) return null;
-
- return {
- type: "NUMERIC",
- absoluteDifference: Math.abs(diff),
- direction: diff > 0 ? "+" : "-",
- };
- }
-
- if (current.type === "CATEGORICAL" && baseline.type === "CATEGORICAL") {
- const currentValue = current.values[0];
- const baselineValue = baseline.values[0];
-
- // Same value → no diff
- if (currentValue === baselineValue) return null;
-
- return {
- type: "CATEGORICAL",
- isDifferent: true,
- };
- }
-
- return null;
-}
diff --git a/web/src/features/events/components/EventsViewModeToggle.tsx b/web/src/features/events/components/EventsViewModeToggle.tsx
deleted file mode 100644
index f844e68d9b..0000000000
--- a/web/src/features/events/components/EventsViewModeToggle.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/src/components/ui/dropdown-menu";
-import { Button } from "@/src/components/ui/button";
-import { ChevronDown } from "lucide-react";
-import { type EventsViewMode } from "@/src/features/events/hooks/useEventsViewMode";
-
-export interface EventsViewModeToggleProps {
- viewMode: EventsViewMode;
- onViewModeChange: (mode: EventsViewMode) => void;
-}
-
-const VIEW_MODE_OPTIONS: Record<
- EventsViewMode,
- { label: string; description: string }
-> = {
- trace: {
- label: "Traces",
- description: "Root-level observations, the top nodes in a trace.",
- },
- observation: {
- label: "Observations",
- description: "All observations of all trace trees.",
- },
-};
-
-export function EventsViewModeToggle({
- viewMode,
- onViewModeChange,
-}: EventsViewModeToggleProps) {
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline" size="sm" className="h-8 gap-1">
- {VIEW_MODE_OPTIONS[viewMode].label}
- <ChevronDown className="h-4 w-4 opacity-50" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {(
- Object.entries(VIEW_MODE_OPTIONS) as [
- EventsViewMode,
- { label: string; description: string },
- ][]
- ).map(([key, { label, description }]) => (
- <DropdownMenuItem
- key={key}
- onClick={() => onViewModeChange(key)}
- className="flex flex-col items-start"
- >
- <span>{label}</span>
- <span className="text-muted-foreground text-xs">{description}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/web/src/features/events/hooks/useEventsViewMode.ts b/web/src/features/events/hooks/useEventsViewMode.ts
deleted file mode 100644
index dd9ace9e71..0000000000
--- a/web/src/features/events/hooks/useEventsViewMode.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useQueryParams, StringParam, withDefault } from "use-query-params";
-import { useMemo } from "react";
-import useSessionStorage from "@/src/components/useSessionStorage";
-
-export type EventsViewMode = "observation" | "trace";
-
-export interface UseEventsViewModeOutput {
- viewMode: EventsViewMode;
- setViewMode: (mode: EventsViewMode) => void;
-}
-
-export function useEventsViewMode(projectId: string): UseEventsViewModeOutput {
- const defaultMode: EventsViewMode = "trace";
-
- const [storedViewMode, setStoredViewMode] = useSessionStorage<EventsViewMode>(
- `eventsViewMode-${projectId}`,
- defaultMode,
- );
-
- const [queryParams, setQueryParams] = useQueryParams({
- viewMode: withDefault(StringParam, storedViewMode),
- });
-
- return useMemo(() => {
- const rawMode = queryParams.viewMode;
- const viewMode: EventsViewMode =
- rawMode === "observation" || rawMode === "trace" ? rawMode : defaultMode;
-
- const setViewMode = (mode: EventsViewMode) => {
- setQueryParams({ viewMode: mode });
- setStoredViewMode(mode);
- };
-
- return {
- viewMode,
- setViewMode,
- };
- }, [queryParams.viewMode, setQueryParams, setStoredViewMode]);
-}
diff --git a/web/src/features/events/hooks/useObservationCountCheck.ts b/web/src/features/events/hooks/useObservationCountCheck.ts
deleted file mode 100644
index 5176257ba6..0000000000
--- a/web/src/features/events/hooks/useObservationCountCheck.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { api } from "@/src/utils/api";
-import { type FilterState } from "@langfuse/shared";
-
-/**
- * Checks if there are root observations for current filter conditions.
- * If no, default to the observation view mode instead.
- */
-export function useObservationCountCheck({
- projectId,
- filterStateWithoutViewMode,
- enabled,
-}: {
- projectId: string;
- filterStateWithoutViewMode: FilterState;
- enabled: boolean;
-}) {
- const query = api.events.countAll.useQuery(
- {
- projectId,
- filter: filterStateWithoutViewMode,
- searchQuery: null,
- searchType: ["id", "content"],
- page: 1,
- limit: 1,
- orderBy: null,
- },
- {
- enabled,
- staleTime: 60_000, // 1 minute stale time to prevent spam
- },
- );
-
- return {
- observationCount: query.data?.totalCount ?? null,
- isSuccess: query.isSuccess,
- isPending: query.isPending,
- };
-}
diff --git a/web/src/features/notifications/Notification.tsx b/web/src/features/notifications/Notification.tsx
deleted file mode 100644
index a49d92595a..0000000000
--- a/web/src/features/notifications/Notification.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { X } from "lucide-react";
-
-import type { JSX } from "react";
-
-export interface TNotification {
- id: number;
- releaseDate: Date;
- message: string | JSX.Element;
- description?: JSX.Element | string;
-}
-
-interface NotificationProps {
- notification: TNotification;
- setLastSeenId: (id: number) => void;
- dismissToast: (t?: string | number | undefined) => void;
- toast: string | number;
-}
-
-export const Notification: React.FC<NotificationProps> = ({
- notification,
- setLastSeenId,
- dismissToast,
- toast,
-}) => {
- const capture = usePostHogClientCapture();
- return (
- <div className="flex justify-between">
- <div className="flex min-w-[300px] flex-1 flex-col justify-center">
- <div className="text-primary m-0 text-sm leading-tight font-medium">
- {notification.message}
- </div>
- {notification.description && (
- <div className="text-primary mt-2 flex-1 text-sm leading-tight">
- {notification.description}
- </div>
- )}
- </div>
- <button
- className="text-primary flex h-6 w-6 cursor-pointer items-start justify-end border-none bg-transparent p-0 transition-colors duration-200"
- onClick={() => {
- capture("notification:dismiss_notification", {
- notificationId: notification.id,
- });
- setLastSeenId(notification.id);
- dismissToast(toast);
- }}
- aria-label="Close"
- >
- <X size={14} />
- </button>
- </div>
- );
-};
diff --git a/web/src/features/playground/page/components/CollapsibleSection.tsx b/web/src/features/playground/page/components/CollapsibleSection.tsx
deleted file mode 100644
index f0501d12dd..0000000000
--- a/web/src/features/playground/page/components/CollapsibleSection.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import React, { useState } from "react";
-import { Button } from "@/src/components/ui/button";
-import { Badge } from "@/src/components/ui/badge";
-import { ChevronRight, ChevronDown } from "lucide-react";
-import { cn } from "@/src/utils/tailwind";
-
-interface CollapsibleSectionProps {
- title: string;
- badge?: string;
- count?: number;
- defaultExpanded?: boolean;
- actionButton?: React.ReactNode;
- children: React.ReactNode;
- isEmpty?: boolean;
- emptyMessage?: string;
- className?: string;
- summaryContent?: string | React.ReactNode;
-}
-
-export const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({
- title,
- badge,
- count,
- defaultExpanded = false,
- actionButton,
- children,
- isEmpty = false,
- emptyMessage,
- className,
- summaryContent,
-}) => {
- const [isExpanded, setIsExpanded] = useState(defaultExpanded);
-
- const toggleExpanded = () => {
- setIsExpanded(!isExpanded);
- };
-
- const hasContent = count !== undefined ? count > 0 : !isEmpty;
-
- return (
- <div className={cn("space-y-1", className)}>
- {/* Header */}
- <div className="flex items-center justify-between">
- <Button
- variant="ghost"
- size="sm"
- onClick={toggleExpanded}
- className="h-8 gap-2 px-1 hover:bg-transparent"
- >
- {isExpanded ? (
- <ChevronDown className="h-3 w-3" />
- ) : (
- <ChevronRight className="h-3 w-3" />
- )}
- <span className="text-sm font-semibold">{title}</span>
- {badge && (
- <Badge variant="secondary" className="h-4 text-xs">
- {badge}
- </Badge>
- )}
- {count !== undefined && count > 0 && (
- <Badge variant="outline" className="h-4 text-xs">
- {count}
- </Badge>
- )}
- </Button>
- {actionButton && (
- <div className="flex items-center gap-1">{actionButton}</div>
- )}
- </div>
-
- {/* Content */}
- {isExpanded && (
- <div className="space-y-2">
- {hasContent ? (
- children
- ) : (
- <div className="px-2 py-1">
- <p className="text-muted-foreground text-xs">
- {emptyMessage || "No items configured."}
- </p>
- </div>
- )}
- </div>
- )}
-
- {/* Compact summary when collapsed */}
- {!isExpanded && (hasContent || summaryContent) && (
- <div className="px-2 py-0.5">
- <p className="text-muted-foreground text-xs">
- {summaryContent ||
- (count !== undefined && count > 0
- ? `${count} item${count === 1 ? "" : "s"} configured`
- : "Configured")}
- </p>
- </div>
- )}
- </div>
- );
-};
diff --git a/web/src/features/prompts/components/auto-complete.tsx b/web/src/features/prompts/components/auto-complete.tsx
deleted file mode 100644
index 8c5446bfe7..0000000000
--- a/web/src/features/prompts/components/auto-complete.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-"use client";
-
-import {
- InputCommandGroup,
- InputCommandItem,
- InputCommandList,
- InputCommandInput,
-} from "@/src/components/ui/input-command";
-import { Command as CommandPrimitive } from "cmdk";
-import { useState, useRef, useCallback, type KeyboardEvent } from "react";
-
-import { Check } from "lucide-react";
-import { cn } from "@/src/utils/tailwind";
-
-export type AutoCompleteOption = {
- value: string;
- label: string;
-};
-
-type AutoCompleteProps = {
- options: AutoCompleteOption[];
- value: AutoCompleteOption;
- onValueChange?: (value: AutoCompleteOption) => void;
- disabled?: boolean;
- placeholder?: string;
- createLabel: string;
-};
-
-export const AutoComplete = ({
- options,
- placeholder,
- value,
- onValueChange,
- disabled,
- createLabel,
-}: AutoCompleteProps) => {
- const inputRef = useRef<HTMLInputElement>(null);
- const [isOpen, setOpen] = useState(false);
- const [selected, setSelected] = useState<AutoCompleteOption>(value);
- const [inputValue, setInputValue] = useState<string>(value.label || "");
-
- const handleKeyDown = useCallback(
- (event: KeyboardEvent<HTMLDivElement>) => {
- const input = inputRef.current;
- if (!input) {
- return;
- }
-
- // Keep the options displayed when the user is typing
- if (!isOpen) {
- setOpen(true);
- }
-
- // This is not a default behavior of the <input /> field
- if (event.key === "Enter" && input.value !== "") {
- const optionToSelect = options.find(
- (option) => option.label === input.value,
- );
- if (optionToSelect) {
- setSelected(optionToSelect);
- onValueChange?.(optionToSelect);
- }
- }
-
- if (event.key === "Escape") {
- input.blur();
- }
- },
- [isOpen, options, onValueChange],
- );
-
- const handleBlur = useCallback(() => {
- setOpen(false);
- setInputValue(selected.label);
- }, [selected]);
-
- const handleSelectOption = useCallback(
- (selectedOption: AutoCompleteOption) => {
- setInputValue(selectedOption.label);
-
- setSelected(selectedOption);
- onValueChange?.(selectedOption);
-
- // This is a hack to prevent the input from being focused after the user selects an option
- // We can call this hack: "The next tick"
- setTimeout(() => {
- inputRef.current?.blur();
- }, 0);
- },
- [onValueChange],
- );
-
- return (
- <CommandPrimitive onKeyDown={handleKeyDown}>
- <div>
- <InputCommandInput
- ref={inputRef}
- value={inputValue}
- onValueChange={setInputValue}
- onBlur={handleBlur}
- onFocus={() => setOpen(true)}
- placeholder={placeholder}
- disabled={disabled}
- />
- </div>
- <div className="relative mt-1">
- {isOpen ? (
- <div className="bg-background animate-in fade-in-0 zoom-in-95 absolute top-0 z-10 w-full rounded-xl outline-hidden">
- <InputCommandList className="ring-border rounded-lg ring-1">
- {options.length > 0 ? (
- <InputCommandGroup>
- {options.map((option) => {
- const isSelected = selected.value === option.value;
- return (
- <InputCommandItem
- key={option.value}
- value={option.label}
- onMouseDown={(event) => {
- event.preventDefault();
- event.stopPropagation();
- }}
- onSelect={() => handleSelectOption(option)}
- className={cn(
- "flex w-full items-center gap-2",
- !isSelected ? "pl-8" : null,
- )}
- >
- {isSelected ? <Check className="w-4" /> : null}
- {option.label}
- </InputCommandItem>
- );
- })}
- </InputCommandGroup>
- ) : null}
- <InputCommandItemCreate
- onMouseDown={(event) => {
- event.preventDefault();
- event.stopPropagation();
- }}
- onSelect={() =>
- handleSelectOption({ value: inputValue, label: inputValue })
- }
- createLabel={createLabel}
- {...{ inputValue, options }}
- />
- </InputCommandList>
- </div>
- ) : (
- <InputCommandList /> // CommandPrimitive expects a InputCommandList child, fix to prevent errors introduced in cmdk v1.0.0
- )}
- </div>
- </CommandPrimitive>
- );
-};
-
-const InputCommandItemCreate = ({
- inputValue,
- options,
- createLabel,
- onSelect,
- onMouseDown,
-}: {
- inputValue: string;
- options: AutoCompleteOption[];
- createLabel: string;
- onSelect: () => void;
- onMouseDown: (event: React.MouseEvent<HTMLElement>) => void;
-}) => {
- const hasNoOption = !options
- .map(({ value }) => value)
- .includes(inputValue.toLowerCase());
-
- const render = inputValue !== "" && hasNoOption;
-
- if (!render) return null;
-
- return (
- <InputCommandItem
- key={inputValue}
- value={inputValue}
- className="text-muted-foreground"
- onSelect={onSelect}
- onMouseDown={onMouseDown}
- >
- <div className={cn("m-2 h-4 w-4")} />
- {createLabel}: &quot;{inputValue}&quot;
- </InputCommandItem>
- );
-};
diff --git a/web/src/features/score-analytics/components/charts/HeatmapPlaceholder.tsx b/web/src/features/score-analytics/components/charts/HeatmapPlaceholder.tsx
deleted file mode 100644
index 2e9005eaa9..0000000000
--- a/web/src/features/score-analytics/components/charts/HeatmapPlaceholder.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { Skeleton } from "@/src/components/ui/skeleton";
-
-/**
- * HeatmapPlaceholder component displays a skeleton grid placeholder
- * when only one score is selected, indicating that a heatmap will appear
- * when a second score is selected.
- */
-export function HeatmapPlaceholder() {
- return (
- <div className="relative flex h-[300px] items-center justify-center">
- {/* Skeleton grid pattern (5x5) */}
- <div className="absolute inset-0 flex flex-col gap-2 p-4">
- {Array.from({ length: 5 }).map((_, rowIndex) => (
- <div key={rowIndex} className="flex flex-1 gap-2">
- {Array.from({ length: 5 }).map((_, colIndex) => (
- <Skeleton key={colIndex} className="flex-1" />
- ))}
- </div>
- ))}
- </div>
-
- {/* Overlay message */}
- <div className="bg-background/90 relative z-10 rounded-lg px-6 py-4 text-center shadow-xs">
- <p className="text-muted-foreground text-sm">
- Select a second score to view comparison heatmap
- </p>
- </div>
- </div>
- );
-}
diff --git a/web/src/features/scores/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.ts
deleted file mode 100644
index a2405b4247..0000000000
--- a/web/src/features/scores/lib/getDefaultScoreData.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import {
- type ScoreTarget,
- type ScoreTargetTrace,
- type ScoreTargetSession,
- ScoreSourceEnum,
-} from "@langfuse/shared";
-import { type ScoreConfigDomain } from "@langfuse/shared";
-import { isTraceScore } from "@/src/features/scores/lib/helpers";
-import { type AnnotationScoreDataSchema } from "@/src/features/scores/schema";
-import { type z } from "zod";
-import { type AnnotationScore } from "@/src/features/scores/types";
-
-const isAnnotationScore = (score: AnnotationScore) =>
- score.source === ScoreSourceEnum.ANNOTATION;
-
-const filterTraceAnnotationScores =
- ({ traceId, observationId }: ScoreTargetTrace) =>
- (s: AnnotationScore) =>
- isAnnotationScore(s) &&
- s.traceId === traceId &&
- (observationId !== undefined
- ? s.observationId === observationId
- : s.observationId === null);
-
-const filterSessionAnnotationScores =
- ({ sessionId }: ScoreTargetSession) =>
- (s: AnnotationScore) =>
- isAnnotationScore(s) && s.sessionId === sessionId;
-
-export const getDefaultAnnotationScoreData = ({
- scores,
- emptySelectedConfigIds,
- configs,
- scoreTarget,
-}: {
- scores: AnnotationScore[];
- emptySelectedConfigIds: string[];
- configs: ScoreConfigDomain[];
- scoreTarget: ScoreTarget;
-}): z.infer<typeof AnnotationScoreDataSchema>[] => {
- const isValidScore = isTraceScore(scoreTarget)
- ? filterTraceAnnotationScores(scoreTarget)
- : filterSessionAnnotationScores(scoreTarget);
-
- const populatedScores = scores
- .filter(isValidScore)
- .map(({ id, name, value, dataType, stringValue, configId, comment }) => ({
- scoreId: id ?? undefined,
- name,
- value,
- dataType,
- stringValue: stringValue ?? undefined,
- configId: configId ?? undefined,
- comment: comment ?? undefined,
- }));
-
- const populatedScoresConfigIds = new Set(
- populatedScores.map((s) => s.configId),
- );
-
- const emptyScores = configs
- .filter(
- (c) =>
- !populatedScoresConfigIds.has(c.id) &&
- emptySelectedConfigIds.includes(c.id),
- )
- .map(({ name, dataType, id }) => ({
- scoreId: undefined,
- name,
- value: undefined,
- dataType,
- stringValue: undefined,
- configId: id,
- comment: undefined,
- }));
-
- return [...populatedScores, ...emptyScores];
-};
diff --git a/web/src/hooks/use-element-visibility.tsx b/web/src/hooks/use-element-visibility.tsx
deleted file mode 100644
index 59b2738a63..0000000000
--- a/web/src/hooks/use-element-visibility.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * This hook is used to determine if an element is or was visible in the viewport.
- * It is useful for determining if a component is visible in the viewport, or if it was visible in the viewport at any point in time.
- */
-
-import { type RefObject, useEffect, useMemo, useState } from "react";
-
-export function useElementIsVisible<T extends HTMLElement>(
- ref: RefObject<T | null>,
-) {
- const [isVisible, setIsVisible] = useState(false);
-
- const observer = useMemo(
- () =>
- new IntersectionObserver((entries) => {
- let visible = false;
- entries.forEach((entry) => {
- if (entry.isIntersecting) {
- visible = true;
- }
- });
- setIsVisible(visible);
- }),
- [],
- );
-
- useEffect(() => {
- if (ref.current && observer) {
- observer.observe(ref.current);
- return () => observer.disconnect();
- }
- }, [observer, ref]);
-
- return isVisible;
-}
-
-export function useElementWasVisible<T extends HTMLElement>(
- ref: RefObject<T | null>,
-) {
- const [hasBeenVisible, setHasBeenVisible] = useState(false);
-
- const observer = useMemo(
- () =>
- new IntersectionObserver((entries) => {
- let visible = false;
- entries.forEach((entry) => {
- if (entry.isIntersecting) {
- visible = true;
- }
- });
- setHasBeenVisible(visible);
- }),
- [],
- );
-
- useEffect(() => {
- if (ref.current && observer) {
- if (!hasBeenVisible) {
- observer.observe(ref.current);
- } else {
- observer.disconnect();
- }
- return () => observer.disconnect();
- }
- }, [observer, ref, hasBeenVisible]);
-
- return hasBeenVisible;
-}