Skip to content

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

feat: pivot table sorting (#8214)

Thorsten Spieker0eb5d1c3c0f5
diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.ts
index 140d2d372b..797cbc3c36 100644
--- a/packages/shared/src/server/services/DashboardService/types.ts
+++ b/packages/shared/src/server/services/DashboardService/types.ts
@@ -35,6 +35,12 @@ export const HistogramChartConfig = BaseTotalValueChartConfig.extend({
export const PivotTableChartConfig = BaseTotalValueChartConfig.extend({
type: z.literal("PIVOT_TABLE"),
+ defaultSort: z
+ .object({
+ column: z.string(),
+ order: z.enum(["ASC", "DESC"]),
+ })
+ .optional(),
});
// Define dimension schema
diff --git a/web/src/__tests__/pivot-table-utils.servertest.ts b/web/src/__tests__/pivot-table-utils.servertest.ts
index 8c3aa5c249..2d83e30d8d 100644
--- a/web/src/__tests__/pivot-table-utils.servertest.ts
+++ b/web/src/__tests__/pivot-table-utils.servertest.ts
@@ -30,6 +30,7 @@ import {
type PivotTableConfig,
type DatabaseRow,
type PivotTableRow,
+ getNextSortState,
} from "@/src/features/widgets/utils/pivot-table-utils";
describe("pivot-table-utils", () => {
@@ -1014,4 +1015,113 @@ describe("pivot-table-utils", () => {
});
});
});
+ describe("getNextSortState", () => {
+ const defaultSort = { column: "avg_cost", order: "DESC" as const };
+
+ describe("no current sort", () => {
+ test("returns DESC when no current sort", () => {
+ const next = getNextSortState(null, null, "count");
+ expect(next).toEqual({ column: "count", order: "DESC" });
+ });
+
+ test("returns DESC when no current sort with default sort defined", () => {
+ const next = getNextSortState(defaultSort, null, "count");
+ expect(next).toEqual({ column: "count", order: "DESC" });
+ });
+ });
+
+ describe("different column", () => {
+ test("returns DESC when different column", () => {
+ const next = getNextSortState(
+ null,
+ { column: "metric", order: "ASC" },
+ "count",
+ );
+ expect(next).toEqual({ column: "count", order: "DESC" });
+ });
+
+ test("returns DESC when different column with default sort", () => {
+ const next = getNextSortState(
+ defaultSort,
+ { column: "metric", order: "ASC" },
+ "count",
+ );
+ expect(next).toEqual({ column: "count", order: "DESC" });
+ });
+ });
+
+ describe("non-default column cycling", () => {
+ test("non-default column: DESC -> ASC", () => {
+ const next = getNextSortState(
+ defaultSort,
+ { column: "count", order: "DESC" },
+ "count",
+ );
+ expect(next).toEqual({ column: "count", order: "ASC" });
+ });
+
+ test("non-default column: ASC -> default sort", () => {
+ const next = getNextSortState(
+ defaultSort,
+ { column: "count", order: "ASC" },
+ "count",
+ );
+ expect(next).toEqual(defaultSort);
+ });
+
+ test("non-default column: ASC -> null when no default sort", () => {
+ const next = getNextSortState(
+ null,
+ { column: "count", order: "ASC" },
+ "count",
+ );
+ expect(next).toBeNull();
+ });
+ });
+
+ describe("default column cycling", () => {
+ test("default column: DESC -> ASC", () => {
+ const next = getNextSortState(
+ defaultSort,
+ { column: "avg_cost", order: "DESC" },
+ "avg_cost",
+ );
+ expect(next).toEqual({ column: "avg_cost", order: "ASC" });
+ });
+
+ test("default column: ASC -> DESC (infinite cycle)", () => {
+ const next = getNextSortState(
+ defaultSort,
+ { column: "avg_cost", order: "ASC" },
+ "avg_cost",
+ );
+ expect(next).toEqual({ column: "avg_cost", order: "DESC" });
+ });
+ });
+
+ describe("edge cases", () => {
+ test("handles undefined default sort", () => {
+ const next = getNextSortState(
+ undefined as any,
+ { column: "count", order: "ASC" },
+ "count",
+ );
+ expect(next).toBeNull();
+ });
+
+ test("handles null default sort", () => {
+ const next = getNextSortState(
+ null,
+ { column: "count", order: "ASC" },
+ "count",
+ );
+ expect(next).toBeNull();
+ });
+
+ test("handles null current sort with defined default", () => {
+ const next = getNextSortState(defaultSort, null, "count");
+ expect(next).toEqual({ column: "count", order: "DESC" });
+ });
+ });
+ });
});
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 9c46295f65..bf8953c8d5 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -12,12 +12,16 @@ import { Button } from "@/src/components/ui/button";
import { AlertCircle } from "lucide-react";
import { BigNumber } from "@/src/features/widgets/chart-library/BigNumber";
import { PivotTable } from "@/src/features/widgets/chart-library/PivotTable";
+import { type OrderByState } from "@langfuse/shared";
export const Chart = ({
chartType,
data,
rowLimit,
chartConfig,
+ sortState,
+ onSortChange,
+ isLoading = false,
}: {
chartType: DashboardWidgetChartType;
data: DataPoint[];
@@ -28,7 +32,11 @@ export const Chart = ({
bins?: number;
dimensions?: string[];
metrics?: string[];
+ defaultSort?: OrderByState;
};
+ sortState?: OrderByState | null;
+ onSortChange?: (sortState: OrderByState | null) => void;
+ isLoading?: boolean;
}) => {
const [forceRender, setForceRender] = useState(false);
const shouldWarn = data.length > 2000 && !forceRender;
@@ -73,8 +81,17 @@ export const Chart = ({
dimensions: chartConfig?.dimensions ?? [],
metrics: chartConfig?.metrics ?? ["metric"], // Use metrics from chartConfig
rowLimit: chartConfig?.row_limit ?? rowLimit,
+ defaultSort: chartConfig?.defaultSort,
};
- return <PivotTable data={renderedData} config={pivotConfig} />;
+ return (
+ <PivotTable
+ data={renderedData}
+ config={pivotConfig}
+ sortState={sortState}
+ onSortChange={onSortChange}
+ isLoading={isLoading}
+ />
+ );
}
default:
return <HorizontalBarChart data={renderedData.slice(0, rowLimit)} />;
diff --git a/web/src/features/widgets/chart-library/PivotTable.tsx b/web/src/features/widgets/chart-library/PivotTable.tsx
index 40071c851d..535960553a 100644
--- a/web/src/features/widgets/chart-library/PivotTable.tsx
+++ b/web/src/features/widgets/chart-library/PivotTable.tsx
@@ -12,13 +12,14 @@
* - Responsive design within dashboard grid
* - Consistent styling with Langfuse design system
* - Row limiting to prevent performance issues
+ * - Interactive sorting with hierarchical behavior
*
* Usage:
* Used as part of the dashboard widget system to display tabular data
* visualizations with grouping and aggregation capabilities.
*/
-import React, { useMemo } from "react";
+import React, { useMemo, useCallback, useState, useEffect } from "react";
import { cn } from "@/src/utils/tailwind";
import {
Table,
@@ -32,6 +33,8 @@ import {
transformToPivotTable,
extractDimensionValues,
extractMetricValues,
+ sortPivotTableRows,
+ getNextSortState,
type PivotTableRow,
type PivotTableConfig,
type DatabaseRow,
@@ -40,6 +43,8 @@ import {
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import { numberFormatter } from "@/src/utils/numbers";
import { formatMetricName } from "@/src/features/widgets/utils";
+import { type OrderByState } from "@langfuse/shared";
+import { Loader2 } from "lucide-react";
/**
* Props interface for the PivotTable component
@@ -57,8 +62,89 @@ export interface PivotTableProps {
/** Accessibility layer flag */
accessibilityLayer?: boolean;
+
+ /** Current sort state */
+ sortState?: OrderByState;
+
+ /** Callback for sort state changes */
+ onSortChange?: (sortState: OrderByState | null) => void;
+
+ /** Loading state for when data is being refreshed */
+ isLoading?: boolean;
}
+/**
+ * Non-sortable column header component
+ * Simple header without sorting functionality
+ */
+const StaticHeader: React.FC<{
+ label: string;
+ className?: string;
+}> = ({ label, className }) => {
+ return (
+ <TableHead className={cn("p-1", className)}>
+ <div className="flex select-none items-center">
+ <span className="truncate">{label}</span>
+ </div>
+ </TableHead>
+ );
+};
+
+/**
+ * Sortable column header component
+ * Handles click events and visual indicators for sorting
+ */
+const SortableHeader: React.FC<{
+ column: string;
+ label: string;
+ sortState?: OrderByState;
+ onSort: (column: string) => void;
+ className?: string;
+ rightAlign?: boolean;
+}> = ({ column, label, sortState, onSort, className, rightAlign = false }) => {
+ const isSorted = sortState?.column === column;
+ const sortDirection = isSorted ? sortState.order : null;
+
+ const handleClick = useCallback(
+ (event: React.MouseEvent) => {
+ event.preventDefault();
+ onSort(column);
+ },
+ [column, onSort],
+ );
+
+ return (
+ <TableHead
+ className={cn("group/header cursor-pointer select-none p-1", className)}
+ onClick={handleClick}
+ >
+ <div
+ className={cn(
+ "flex select-none items-center",
+ rightAlign ? "justify-end" : "justify-start",
+ )}
+ >
+ <span className="truncate">{label}</span>
+ {isSorted && (
+ <span
+ className="ml-1"
+ title={
+ sortDirection === "ASC"
+ ? "Sorted ascending"
+ : "Sort by this column"
+ }
+ >
+ {sortDirection === "ASC" ? "â–²" : "â–¼"}
+ </span>
+ )}
+
+ {/* Visual indicator that appears on hover - matches traces table behavior */}
+ <div className="pointer-events-none absolute right-0 top-0 h-full w-1.5 touch-none select-none bg-secondary opacity-0 group-hover/header:opacity-100" />
+ </div>
+ </TableHead>
+ );
+};
+
/**
* Individual row component for the pivot table
* Handles styling, indentation, and content display for each row type
@@ -143,8 +229,16 @@ function formatColumnHeader(metricName: string): string {
*
* @param data - Array of data points from the chart query
* @param config - Pivot table configuration including dimensions and metrics
+ * @param sortState - Current sort state
+ * @param onSortChange - Callback for sort state changes
*/
-export const PivotTable: React.FC<PivotTableProps> = ({ data, config }) => {
+export const PivotTable: React.FC<PivotTableProps> = ({
+ data,
+ config,
+ sortState,
+ onSortChange,
+ isLoading = false,
+}) => {
// Transform chart data into pivot table structure
const pivotTableRows = useMemo(() => {
if (!data || data.length === 0) {
@@ -156,6 +250,7 @@ export const PivotTable: React.FC<PivotTableProps> = ({ data, config }) => {
dimensions: config?.dimensions ?? [],
metrics: config?.metrics ?? ["metric"], // Default to 'metric' field from DataPoint
rowLimit: config?.rowLimit ?? DEFAULT_ROW_LIMIT,
+ defaultSort: config?.defaultSort,
};
// Transform DataPoint[] to DatabaseRow[] format using utility functions
@@ -206,11 +301,59 @@ export const PivotTable: React.FC<PivotTableProps> = ({ data, config }) => {
}
}, [data, config]);
+ // Apply sorting to pivot table rows
+ const sortedRows = useMemo(() => {
+ // Use user sort state if available, otherwise fall back to default sort
+
+ if (!sortState || !sortState.column) {
+ return pivotTableRows;
+ }
+
+ try {
+ return sortPivotTableRows(pivotTableRows, sortState);
+ } catch (error) {
+ console.error("Error sorting pivot table rows:", error);
+ return pivotTableRows;
+ }
+ }, [pivotTableRows, sortState]);
+
// Extract metrics from configuration or fallback to default
const metrics = useMemo(() => {
return config?.metrics ?? ["metric"];
}, [config?.metrics]);
+ // Handle sort click events - simple cycling
+ const handleSort = useCallback(
+ (column: string) => {
+ if (!onSortChange) return;
+ const nextSort = getNextSortState(
+ config?.defaultSort || null,
+ sortState || null,
+ column,
+ );
+ onSortChange(nextSort);
+ },
+ [sortState, onSortChange, config?.defaultSort],
+ );
+
+ // Track the last known defaultSort to detect changes
+ const [lastDefaultSort, setLastDefaultSort] = useState(config?.defaultSort);
+
+ // Reset to defaultSort when it changes
+ useEffect(() => {
+ const currentDefaultSort = config?.defaultSort;
+
+ // If defaultSort changed, reset the sorting
+ if (currentDefaultSort !== lastDefaultSort) {
+ setLastDefaultSort(currentDefaultSort);
+
+ // Reset to the new default sort
+ if (onSortChange) {
+ onSortChange(currentDefaultSort || null);
+ }
+ }
+ }, [config?.defaultSort, onSortChange, lastDefaultSort]);
+
// Handle empty data state
if (!data || data.length === 0) {
return (
@@ -236,28 +379,45 @@ export const PivotTable: React.FC<PivotTableProps> = ({ data, config }) => {
}
return (
- <div className="h-full overflow-auto px-5 pb-2">
+ <div className="relative h-full overflow-auto px-5 pb-2">
+ {isLoading && (
+ <div className="absolute inset-0 z-10 flex items-center justify-center bg-background/80 backdrop-blur-sm">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>Refreshing data...</span>
+ </div>
+ </div>
+ )}
<Table>
- <TableHeader>
- <TableRow className="border-b bg-muted/50">
+ <TableHeader className="sticky top-0 z-10">
+ <TableRow>
{/* Dimension column header */}
- <TableHead className="p-2 text-left font-medium">
- {config?.dimensions && config.dimensions.length > 0
- ? config.dimensions.map(formatColumnHeader).join(" / ") // Show all dimensions
- : "Dimension"}
- </TableHead>
+ <StaticHeader
+ label={
+ config?.dimensions && config.dimensions.length > 0
+ ? config.dimensions.map(formatColumnHeader).join(" / ") // Show all dimensions
+ : "Dimension"
+ }
+ className="p-2 text-left font-medium first:pl-2"
+ />
{/* Metric column headers */}
{metrics.map((metric) => (
- <TableHead key={metric} className="p-2 text-right font-medium">
- {formatColumnHeader(metric)}
- </TableHead>
+ <SortableHeader
+ key={metric}
+ column={metric}
+ label={formatColumnHeader(metric)}
+ sortState={sortState}
+ onSort={handleSort}
+ className="p-2 font-medium"
+ rightAlign={true}
+ />
))}
</TableRow>
</TableHeader>
<TableBody>
- {pivotTableRows.map((row) => (
+ {sortedRows.map((row) => (
<PivotTableRowComponent key={row.id} row={row} metrics={metrics} />
))}
</TableBody>
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index dd51cb2d96..7bb3df2d1c 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -1,4 +1,4 @@
-import { useMemo } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/src/utils/api";
import {
type views,
@@ -7,7 +7,7 @@ import {
} from "@/src/features/query";
import { type z } from "zod/v4";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, type OrderByState } from "@langfuse/shared";
import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";
import {
PencilIcon,
@@ -69,6 +69,28 @@ export function DashboardWidget({
: new Date(new Date().getTime() - 1000);
const toTimestamp = dateRange ? dateRange.to : new Date();
+ // Initialize sort state for pivot tables
+ const defaultSort =
+ widget.data?.chartConfig.type === "PIVOT_TABLE"
+ ? widget.data?.chartConfig.defaultSort
+ : undefined;
+
+ const [sortState, setSortState] = useState<OrderByState | null>(() => {
+ return defaultSort || null;
+ });
+
+ // Apply defaultSort when it becomes available (after widget data loads)
+ // but only if user hasn't interacted yet
+ useEffect(() => {
+ if (defaultSort && sortState === null) {
+ setSortState(defaultSort);
+ }
+ }, [defaultSort, sortState]);
+
+ const updateSort = useCallback((newSort: OrderByState | null) => {
+ setSortState(newSort);
+ }, []);
+
const queryResult = api.dashboard.executeQuery.useQuery(
{
projectId,
@@ -94,7 +116,15 @@ export function DashboardWidget({
: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
- orderBy: null,
+ orderBy:
+ widget.data?.chartConfig.type === "PIVOT_TABLE" && sortState
+ ? [
+ {
+ field: sortState.column,
+ direction: sortState.order.toLowerCase() as "asc" | "desc",
+ },
+ ]
+ : null,
chartConfig: widget.data?.chartConfig,
},
},
@@ -301,6 +331,13 @@ export function DashboardWidget({
),
}),
}}
+ sortState={
+ widget.data.chartType === "PIVOT_TABLE" ? sortState : undefined
+ }
+ onSortChange={
+ widget.data.chartType === "PIVOT_TABLE" ? updateSort : undefined
+ }
+ isLoading={queryResult.isLoading}
/>
</div>
</div>
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 6395c22f5c..980648ead0 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -249,6 +249,14 @@ export function WidgetForm({
initialValues.chartConfig?.bins ?? 10,
);
+ // Default sort configuration for pivot tables
+ const [defaultSortColumn, setDefaultSortColumn] = useState<string>(
+ initialValues.chartConfig?.defaultSort?.column ?? "none",
+ );
+ const [defaultSortOrder, setDefaultSortOrder] = useState<"ASC" | "DESC">(
+ initialValues.chartConfig?.defaultSort?.order ?? "DESC",
+ );
+
// Filter state
const { selectedOption, dateRange, setDateRangeAndOption } =
useDashboardDateRange({ defaultRelativeAggregation: "7 days" });
@@ -270,6 +278,17 @@ export function WidgetForm({
}) ?? [],
);
+ // Static sort state for pivot table preview (non-interactive)
+ const previewSortState = useMemo(
+ () =>
+ selectedChartType === "PIVOT_TABLE" &&
+ defaultSortColumn &&
+ defaultSortColumn !== "none"
+ ? { column: defaultSortColumn, order: defaultSortOrder }
+ : null,
+ [selectedChartType, defaultSortColumn, defaultSortOrder],
+ );
+
// Helper function to update pivot table dimensions
const updatePivotDimension = (index: number, value: string) => {
const newDimensions = [...pivotDimensions];
@@ -733,7 +752,17 @@ export function WidgetForm({
: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
- orderBy: null,
+ orderBy:
+ selectedChartType === "PIVOT_TABLE" && previewSortState
+ ? [
+ {
+ field: previewSortState.column,
+ direction: previewSortState.order.toLowerCase() as
+ | "asc"
+ | "desc",
+ },
+ ]
+ : null,
chartConfig:
selectedChartType === "HISTOGRAM"
? { type: selectedChartType, bins: histogramBins }
@@ -742,6 +771,13 @@ export function WidgetForm({
type: selectedChartType,
dimensions: pivotDimensions,
row_limit: rowLimit,
+ defaultSort:
+ defaultSortColumn && defaultSortColumn !== "none"
+ ? {
+ column: defaultSortColumn,
+ order: defaultSortOrder,
+ }
+ : undefined,
}
: { type: selectedChartType },
};
@@ -757,6 +793,9 @@ export function WidgetForm({
histogramBins,
pivotDimensions,
rowLimit,
+ defaultSortColumn,
+ defaultSortOrder,
+ previewSortState,
]);
const queryResult = api.dashboard.executeQuery.useQuery(
@@ -875,6 +914,13 @@ export function WidgetForm({
? {
type: selectedChartType as DashboardWidgetChartType,
row_limit: rowLimit,
+ defaultSort:
+ defaultSortColumn && defaultSortColumn !== "none"
+ ? {
+ column: defaultSortColumn,
+ order: defaultSortOrder,
+ }
+ : undefined,
}
: {
type: selectedChartType as DashboardWidgetChartType,
@@ -1400,6 +1446,70 @@ export function WidgetForm({
)}
</div>
)}
+
+ {/* Pivot Table Default Sort Configuration */}
+ {selectedChartType === "PIVOT_TABLE" && (
+ <div className="space-y-4">
+ <div>
+ <h4 className="mb-2 text-sm font-semibold">
+ Default Sort Configuration
+ </h4>
+ <p className="mb-3 text-xs text-muted-foreground">
+ Configure the default sort order for the pivot table. This
+ will be applied when the widget is first loaded.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <Label htmlFor="default-sort-column">Sort Column</Label>
+ <Select
+ value={defaultSortColumn}
+ onValueChange={setDefaultSortColumn}
+ >
+ <SelectTrigger id="default-sort-column">
+ <SelectValue placeholder="Select a column to sort by" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">No default sort</SelectItem>
+ {/* Show available metrics as sort options */}
+ {selectedMetrics
+ .filter(
+ (metric) =>
+ metric.measure && metric.measure !== "",
+ )
+ .map((metric) => (
+ <SelectItem key={metric.id} value={metric.id}>
+ {formatMetricName(metric.id)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="default-sort-order">Sort Order</Label>
+ <Select
+ value={defaultSortOrder}
+ onValueChange={(value: "ASC" | "DESC") =>
+ setDefaultSortOrder(value)
+ }
+ disabled={
+ !defaultSortColumn || defaultSortColumn === "none"
+ }
+ >
+ <SelectTrigger id="default-sort-order">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="ASC">Ascending (A-Z)</SelectItem>
+ <SelectItem value="DESC">Descending (Z-A)</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ </div>
+ )}
</div>
{/* Visualization Section */}
@@ -1569,6 +1679,13 @@ export function WidgetForm({
dimensions: pivotDimensions,
row_limit: rowLimit,
metrics: selectedMetrics.map((metric) => metric.id), // Pass metric field names
+ defaultSort:
+ defaultSortColumn && defaultSortColumn !== "none"
+ ? {
+ column: defaultSortColumn,
+ order: defaultSortOrder,
+ }
+ : undefined,
}
: selectedChartType === "HISTOGRAM"
? {
@@ -1580,6 +1697,12 @@ export function WidgetForm({
row_limit: rowLimit,
}
}
+ sortState={
+ selectedChartType === "PIVOT_TABLE"
+ ? previewSortState
+ : undefined
+ }
+ onSortChange={undefined}
/>
) : (
<CardContent>
diff --git a/web/src/features/widgets/utils.ts b/web/src/features/widgets/utils.ts
index a9fd622271..760ee103a4 100644
--- a/web/src/features/widgets/utils.ts
+++ b/web/src/features/widgets/utils.ts
@@ -7,6 +7,10 @@ export type WidgetChartConfig = {
type: DashboardWidgetChartType;
row_limit?: number;
bins?: number;
+ defaultSort?: {
+ column: string;
+ order: "ASC" | "DESC";
+ };
};
/**
diff --git a/web/src/features/widgets/utils/pivot-table-utils.ts b/web/src/features/widgets/utils/pivot-table-utils.ts
index 2b631e68ef..0b69b477f3 100644
--- a/web/src/features/widgets/utils/pivot-table-utils.ts
+++ b/web/src/features/widgets/utils/pivot-table-utils.ts
@@ -17,6 +17,7 @@
* - Supports future expansion beyond current 2-dimension limit
*/
import { isNotNullOrUndefined } from "@/src/utils/types";
+import { type OrderByState } from "@langfuse/shared";
/**
* Default dimension limit for pivot table data rows
@@ -81,6 +82,8 @@ export interface PivotTableConfig {
/** Maximum number of data rows to display (before totals) */
rowLimit?: number;
+
+ defaultSort?: OrderByState;
}
/**
@@ -608,3 +611,196 @@ export function createGrandTotalRow(
dimensionValues,
};
}
+
+/**
+ * Sorts pivot table rows hierarchically based on sort configuration
+ *
+ * Hierarchical sorting behavior:
+ * 1. Sort groups (subtotal rows) by their total values first
+ * 2. Sort individual items within each group
+ * 3. Maintain grand total at the top
+ * 4. Preserve group hierarchy and indentation
+ *
+ * @param rows - Array of pivot table rows to sort
+ * @param sortConfig - Sort configuration with column and order
+ * @returns Sorted array of pivot table rows
+ */
+export function sortPivotTableRows(
+ rows: PivotTableRow[],
+ sortConfig: { column: string; order: "ASC" | "DESC" },
+): PivotTableRow[] {
+ if (!sortConfig || !sortConfig.column) {
+ return rows;
+ }
+
+ const { column, order } = sortConfig;
+ const isAscending = order === "ASC";
+
+ // Helper function to get sortable value from a row
+ const getSortValue = (row: PivotTableRow): number => {
+ const value = row.values[column];
+ if (typeof value === "number") {
+ return value;
+ }
+ if (typeof value === "string") {
+ // Try to parse as number, fallback to 0
+ const parsed = parseFloat(value);
+ return isNaN(parsed) ? 0 : parsed;
+ }
+ return 0;
+ };
+
+ // Helper function to compare two values
+ const compareValues = (a: number, b: number): number => {
+ if (isAscending) {
+ return a - b;
+ }
+ return b - a;
+ };
+
+ // Helper function to compare strings (for equal numeric values)
+ const compareLabels = (a: string, b: string): number => {
+ if (isAscending) {
+ return a.localeCompare(b);
+ }
+ return b.localeCompare(a);
+ };
+
+ // Separate different row types for processing
+ const grandTotalRows = rows.filter(isTotalRow);
+ const subtotalRows = rows.filter(isSubtotalRow);
+ const dataRows = rows.filter(isDataRow);
+
+ // Sort subtotal rows (groups) by their total values
+ const sortedSubtotalRows = subtotalRows.sort((a, b) => {
+ const aValue = getSortValue(a);
+ const bValue = getSortValue(b);
+
+ const valueComparison = compareValues(aValue, bValue);
+ if (valueComparison !== 0) {
+ return valueComparison;
+ }
+
+ // For equal values, sort by label
+ return compareLabels(a.label, b.label);
+ });
+
+ // Group data rows by their parent subtotal
+ const dataRowsByGroup: Record<string, PivotTableRow[]> = {};
+
+ for (const row of dataRows) {
+ // Find the parent subtotal for this data row
+ const parentGroup = findParentGroup(row, subtotalRows);
+ const groupKey = parentGroup?.label || "ungrouped";
+
+ if (!dataRowsByGroup[groupKey]) {
+ dataRowsByGroup[groupKey] = [];
+ }
+ dataRowsByGroup[groupKey].push(row);
+ }
+
+ // Sort data rows within each group
+ for (const groupKey in dataRowsByGroup) {
+ dataRowsByGroup[groupKey].sort((a, b) => {
+ const aValue = getSortValue(a);
+ const bValue = getSortValue(b);
+
+ const valueComparison = compareValues(aValue, bValue);
+ if (valueComparison !== 0) {
+ return valueComparison;
+ }
+
+ // For equal values, sort by label
+ return compareLabels(a.label, b.label);
+ });
+ }
+
+ // Reconstruct the sorted rows maintaining hierarchy
+ const sortedRows: PivotTableRow[] = [];
+
+ // Add grand total at the top
+ sortedRows.push(...grandTotalRows);
+
+ // Add sorted subtotal rows with their sorted data rows
+ for (const subtotalRow of sortedSubtotalRows) {
+ sortedRows.push(subtotalRow);
+
+ // Add sorted data rows for this group
+ const groupKey = subtotalRow.label;
+ const groupDataRows = dataRowsByGroup[groupKey] || [];
+ sortedRows.push(...groupDataRows);
+ }
+
+ // Add any ungrouped data rows at the end
+ const ungroupedRows = dataRowsByGroup["ungrouped"] || [];
+ sortedRows.push(...ungroupedRows);
+
+ return sortedRows;
+}
+
+/**
+ * Finds the parent subtotal group for a data row
+ *
+ * @param dataRow - The data row to find parent for
+ * @param subtotalRows - Array of all subtotal rows
+ * @returns The parent subtotal row or null if not found
+ */
+function findParentGroup(
+ dataRow: PivotTableRow,
+ subtotalRows: PivotTableRow[],
+): PivotTableRow | null {
+ // For now, use a simple approach: find subtotal row with matching level
+ // This can be enhanced later for more complex grouping logic
+ const parentLevel = dataRow.level - 1;
+
+ return (
+ subtotalRows.find(
+ (subtotal) =>
+ subtotal.level === parentLevel &&
+ subtotal.label.includes(dataRow.label.split(" - ")[0]), // Simple matching
+ ) || null
+ );
+}
+
+/**
+ * Gets the next sort state in the simple cycle: DESC → ASC → unsorted
+ *
+ * @param defaultSort - Default sort state (OrderByState or null for unsorted)
+ * @param currentSort - Current sort state (OrderByState or null for unsorted)
+ * @param column - Column to sort by
+ * @returns Next sort state in the cycle
+ */
+export function getNextSortState(
+ defaultSort: OrderByState,
+ currentSort: OrderByState,
+ column: string,
+): OrderByState | null {
+ // Different column or no current sort → start with DESC
+ if (!currentSort || currentSort.column !== column) {
+ return { column, order: "DESC" };
+ }
+
+ // Same column: DESC → ASC → null (unsorted)
+ if (currentSort.order === "DESC") {
+ return { column, order: "ASC" };
+ }
+
+ // Column other than the default column, go back to default
+ if (
+ currentSort.order === "ASC" &&
+ currentSort.column !== defaultSort?.column
+ ) {
+ return defaultSort || null;
+ }
+
+ // Default column, flip back to DESC
+ if (
+ currentSort.order === "ASC" &&
+ currentSort.column === defaultSort?.column
+ ) {
+ return { column, order: "DESC" };
+ }
+
+ // Fallback (shouldn't happen)
+ return null;
+}