import { useLayoutEffect, useRef, useState } from "react"; import { cnm, IconChevronDown, Skeleton } from "@humansignal/ui"; import type { Header } from "@tanstack/react-table"; import { useQuery } from "@tanstack/react-query"; import type { RawResult } from "../../stores/types"; import { Chip } from "./Chip"; import type { AnnotationSummary, ControlTag } from "./types"; import { getLabelCounts } from "./utils"; import { isActive, FF_FIT_720_LAZY_LOAD_ANNOTATIONS } from "@humansignal/core/lib/utils/feature-flags"; import styles from "./TaskSummary.module.css"; type DistributionData = { total_annotations: number; distributions: Record< string, { type: string; labels: Record; average?: number; count?: number; } >; }; const fetchDistribution = async (taskId: number | string): Promise => { const response = await fetch(`/api/tasks/${taskId}/agreement/`); if (!response.ok) { throw new Error("Failed to load distribution"); } return response.json(); }; /** Wrapper to prevent caching lexical scopes in React Query */ const fetchTaskAgreement = async ({ queryKey }: any): Promise => { return fetchDistribution(queryKey[1] as string | number); }; const resultValue = (result: RawResult) => { if (result.type === "textarea") { return result.value.text; } return result.value[result.type]; }; /** * Renders the aggregated data for a single control tag in the distribution row. * Shows statistics like label counts, averages, or choices across all annotations. */ export const AggregationCell = ({ control, annotations, isExpanded, }: { control: ControlTag; annotations: AnnotationSummary[]; isExpanded: boolean; }) => { const allResults = annotations.flatMap((ann) => ann.results.filter((r) => r.from_name === control.name)); // Exclude predictions for percentage denominator to match backend TaskAgreementAPI const totalAnnotations = annotations.filter((a) => a.type === "annotation").length; if (!allResults.length) { return N/A; } // Handle labels-type controls (rectanglelabels, polygonlabels, labels, etc.) if (control.type.endsWith("labels")) { const allLabels = allResults.flatMap((r) => resultValue(r)).flat(); const labelCounts = getLabelCounts(allLabels, control.label_attrs); // Sort by count descending const sortedLabels = Object.entries(labelCounts) .filter(([_, data]) => data.count > 0) .sort(([, a], [, b]) => b.count - a.count); return (
{sortedLabels.map(([label, data]) => ( {label} ))}
); } // Handle pairwise; similar to choices but produce only `left` or `right` values if (control.type === "pairwise") { const allPairwise = allResults.flatMap((r) => resultValue(r)).flat(); const pairwiseCounts: Record = {}; allPairwise.forEach((pairwise) => { pairwiseCounts[pairwise] = (pairwiseCounts[pairwise] || 0) + 1; }); const sortedPairwise = Object.entries(pairwiseCounts).sort(([, a], [, b]) => b - a); return (
{sortedPairwise.map(([pairwise, count]) => ( {pairwise} ))}
); } // Handle choices - show percentage of annotations that selected each choice if (control.type === "choices") { const allChoices = allResults.flatMap((r) => resultValue(r)).flat(); const choiceCounts: Record = {}; allChoices.forEach((choice) => { choiceCounts[choice] = (choiceCounts[choice] || 0) + 1; }); const sortedChoices = Object.entries(choiceCounts).sort(([, a], [, b]) => b - a); return (
{sortedChoices.map(([choice, count]) => ( {choice} ))}
); } // Handle taxonomy - show leaf nodes with percentage if (control.type === "taxonomy") { const values = allResults.flatMap((r) => resultValue(r)?.map((r: string[]) => r.at(-1))); const pathCounts: Record = {}; values.filter(Boolean).forEach((path: string | string[]) => { const pathStr = Array.isArray(path) ? path.join(" / ") : path; pathCounts[pathStr] = (pathCounts[pathStr] || 0) + 1; }); const sortedPaths = Object.entries(pathCounts).sort(([, a], [, b]) => b - a); return (
{sortedPaths.map(([path, count]) => ( {path} ))}
); } // Handle rating - average over annotations that have a value (matches backend TaskAgreementAPI) if (control.type === "rating") { const ratings = allResults.map((r) => resultValue(r)).filter(Boolean); if (!ratings.length) return No ratings; const avgRating = ratings.reduce((sum, val) => sum + val, 0) / ratings.length; return ( Avg: {avgRating.toFixed(1)} ★ ); } // Handle number - average over annotations that have a value (matches backend TaskAgreementAPI) if (control.type === "number") { const numbers = allResults.map((r) => resultValue(r)).filter((v) => v !== null && v !== undefined); if (!numbers.length) return No data; const avg = numbers.reduce((sum, val) => sum + Number(val), 0) / numbers.length; return ( Avg: {avg.toFixed(1)} ); } // Default: show N/A return N/A; }; const DistributionSkeleton = () => (
); const ApiAggregationCell = ({ control, distribution, totalAnnotations, isExpanded, }: { control: ControlTag; distribution?: { type: string; labels: Record; average?: number; count?: number }; totalAnnotations: number; isExpanded: boolean; }) => { if (!distribution || Object.keys(distribution.labels).length === 0) { // Check if it's a numeric type with average if (distribution?.average !== undefined) { return ( Avg: {distribution.average.toFixed(1)} {distribution.type === "rating" && ★} ); } return N/A; } // Sort labels by count descending const sortedLabels = Object.entries(distribution.labels).sort(([, a], [, b]) => b - a); // Handle choices/taxonomy with percentages if (distribution.type === "choices" || distribution.type === "taxonomy") { return (
{sortedLabels.map(([label, count]) => ( {label} ))}
); } // Handle labels and other types with counts return (
{sortedLabels.map(([label, count]) => ( {label} ))}
); }; /** * Renders the complete aggregation/distribution row across all columns. * Includes a toggle button in the first cell that only appears when content overflows. * The toggle expands/collapses the cells to show full content. * * With lazy loading, fetches distribution from dedicated API endpoint * for efficient aggregation without N+1 queries. */ export const AggregationTableRow = ({ headers, controls, annotations, taskId, }: { headers: Header[]; controls: ControlTag[]; annotations: AnnotationSummary[]; taskId?: number | string; }) => { const [isExpanded, setIsExpanded] = useState(false); const [hasOverflow, setHasOverflow] = useState(false); const rowRef = useRef(null); // For non-lazy loading mode, compute from annotations as before const useApiData = isActive(FF_FIT_720_LAZY_LOAD_ANNOTATIONS) && taskId; const { data: distributionData, isLoading, error, } = useQuery({ queryKey: ["task-agreement", taskId], queryFn: fetchTaskAgreement, enabled: useApiData && !!taskId, staleTime: 30000, // Consider data fresh for 30 seconds cacheTime: 5 * 60 * 1000, // Keep in cache for 5 minutes }); useLayoutEffect(() => { if (!rowRef.current) return; const tr = rowRef.current; const hasOverflowingCells = [...tr.childNodes].some((td) => { const node = td as HTMLElement; return node.firstChild && (node.firstChild as HTMLElement).scrollHeight > tr.scrollHeight; }); setHasOverflow(hasOverflowingCells); }, [annotations, controls, distributionData]); return ( {headers.map((header, index) => index === 0 ? (
{hasOverflow ? ( ) : ( Distribution )} {/* Show total count from API */} {useApiData && distributionData && ( {distributionData.total_annotations} annotations )}
) : ( {useApiData && isLoading ? ( ) : useApiData && error ? ( Failed to load ) : useApiData && distributionData ? ( ) : ( )} ), )} ); };