Skip to content

Commit

Permalink
refactor(frontend): made the states name more meaningful
Browse files Browse the repository at this point in the history
  • Loading branch information
ashrafchowdury committed Dec 3, 2024
1 parent 9e08567 commit a822c66
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {convertToCsv, downloadCsv} from "@/lib/helpers/fileManipulations"
import {useUpdateEffect} from "usehooks-ts"
import {getStringOrJson} from "@/lib/helpers/utils"
import ObservabilityContextProvider, {useObservabilityData} from "@/contexts/observability.context"
import TestsetDrawer from "./drawer/TestsetDrawer"
import TestsetDrawer, {TestsetTraceData} from "./drawer/TestsetDrawer"

const useStyles = createUseStyles((theme: JSSTheme) => ({
title: {
Expand Down Expand Up @@ -80,11 +80,8 @@ const ObservabilityDashboard = () => {
const [selectedTraceId, setSelectedTraceId] = useQueryParam("trace", "")
const [editColumns, setEditColumns] = useState<string[]>(["span_type", "key", "usage"])
const [isFilterColsDropdownOpen, setIsFilterColsDropdownOpen] = useState(false)
const [isTestsetDrawerOpen, setIsTestsetDrawerOpen] = useState(false)
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
const [testsetDrawerData, setTestsetDrawerData] = useState<
{key: string; data: KeyValuePair; id: number}[]
>([])
const [testsetDrawerData, setTestsetDrawerData] = useState<TestsetTraceData[]>([])
const [columns, setColumns] = useState<ColumnsType<_AgentaRootsResponse>>([
{
title: "ID",
Expand Down Expand Up @@ -499,16 +496,18 @@ const ObservabilityDashboard = () => {
setSort({type, sorted, customRange})
}, [])

const getMatchingTracesByDataKeys = () => {
const getTestsetTraceData = () => {
if (!traces?.length) return []

const extractData = traces
.filter((trace) => selectedRowKeys.includes(trace.key))
.flatMap((trace, idx) => ({data: trace.data, key: trace.key, id: idx + 1}))
const extractData = traces.reduce<TestsetTraceData[]>((acc, trace, idx) => {
if (selectedRowKeys.includes(trace.key)) {
acc.push({data: trace.data as KeyValuePair, key: trace.key, id: idx + 1})
}
return acc
}, [])

if (extractData.length > 0) {
setTestsetDrawerData(extractData as any)
setIsTestsetDrawerOpen(true)
setTestsetDrawerData(extractData)
}
}

Expand Down Expand Up @@ -562,7 +561,7 @@ const ObservabilityDashboard = () => {
Export as CSV
</Button>
<Button
onClick={() => getMatchingTracesByDataKeys()}
onClick={() => getTestsetTraceData()}
icon={<Database size={14} />}
disabled={traces.length === 0 || selectedRowKeys.length === 0}
>
Expand Down Expand Up @@ -653,14 +652,13 @@ const ObservabilityDashboard = () => {
/>
</div>

{isTestsetDrawerOpen && (
{testsetDrawerData.length > 0 && (
<TestsetDrawer
open={isTestsetDrawerOpen}
open={testsetDrawerData.length > 0}
data={testsetDrawerData}
onClose={() => {
setSelectedRowKeys([])
setTestsetDrawerData([])
setIsTestsetDrawerOpen(false)
setSelectedRowKeys([])
}}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {useEffect, useMemo, useState} from "react"
import {useMemo, useState} from "react"
import GenericDrawer from "@/components/GenericDrawer"
import {ArrowRight, PencilSimple, Plus, Trash} from "@phosphor-icons/react"
import {
Expand Down Expand Up @@ -55,11 +55,11 @@ const useStyles = createUseStyles((theme: JSSTheme) => ({
}))

type Mapping = {data: string; column: string; newColumn?: string}
type TraceData = {key: string; data: KeyValuePair; id: number}
type Preview = {key: string; data: KeyValuePair[]}
export type TestsetTraceData = {key: string; data: KeyValuePair; id: number}
type Props = {
onClose: () => void
data: TraceData[]
data: TestsetTraceData[]
} & React.ComponentProps<typeof Drawer>

const TestsetDrawer = ({onClose, data, ...props}: Props) => {
Expand All @@ -74,17 +74,18 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
const [isLoading, setIsLoading] = useState(false)
const [traceData, setTraceData] = useState(data.length > 0 ? data : [])
const [testset, setTestset] = useState({name: "", id: ""})
const [testsetName, setTestsetName] = useState("")
const [newTestsetName, setNewTestsetName] = useState("")
const [editorFormat, setEditorFormat] = useState("JSON")
const [tableColumns, setTableColumns] = useState<string[]>([])
const [tableRows, setTableRows] = useState<KeyValuePair[]>([])
const [selectedTestsetColumns, setSelectedTestsetColumns] = useState<string[]>([])
const [selectedTestsetRows, setSelectedTestsetRows] = useState<KeyValuePair[]>([])
const [showLastFiveRows, setShowLastFiveRows] = useState(false)
const [dataPreview, setDataPreview] = useState(traceData[0]?.key || "")
const [rowDataPreview, setRowDataPreview] = useState(traceData[0]?.key || "")
const [mappingData, setMappingData] = useState<Mapping[]>([])
const [preview, setPreview] = useState<Preview>({key: traceData[0]?.key || "", data: []})

const isNewTestset = testset.id === "create"
const elementWidth = isDrawerExtended ? 200 * 2 : 200
const selectedTestsetTestCases = selectedTestsetRows.slice(-5)
const isMapColumnExist = mappingData.some((mapping) =>
mapping.column === "create" || !mapping.column ? !!mapping?.newColumn : !!mapping.column,
)
Expand Down Expand Up @@ -113,8 +114,8 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
if (value && value !== "create") {
const data = await fetchTestset(value)
if (data?.csvdata?.length) {
setTableColumns(Object.keys(data.csvdata[0]))
setTableRows(data.csvdata)
setSelectedTestsetColumns(Object.keys(data.csvdata[0]))
setSelectedTestsetRows(data.csvdata)
}
}

Expand All @@ -132,30 +133,32 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
}

const onRemoveTraceData = () => {
const removeTrace = traceData.filter((trace) => trace.key !== dataPreview)
const removeTrace = traceData.filter((trace) => trace.key !== rowDataPreview)
setTraceData(removeTrace)

if (removeTrace.length > 0) {
const currentIndex = traceData.findIndex((trace) => trace.key === dataPreview)
const currentIndex = traceData.findIndex((trace) => trace.key === rowDataPreview)
// [currentIndex]: Next option in list | [currentIndex - 1]: Previous option if next doesn't exist | [0]: Default to first option
const nextPreview =
removeTrace[currentIndex] || removeTrace[currentIndex - 1] || removeTrace[0]

setDataPreview(nextPreview.key)
setRowDataPreview(nextPreview.key)

if (dataPreview === preview.key) {
if (rowDataPreview === preview.key) {
onPreviewOptionChange(nextPreview.key)
}
} else {
setDataPreview("")
setRowDataPreview("")
}
}

const formatDataPreview = useMemo(() => {
if (!traceData?.length) return ""

const jsonObject = {
data: traceData.find((trace) => trace?.key === dataPreview)?.data || traceData[0]?.data,
data:
traceData.find((trace) => trace?.key === rowDataPreview)?.data ||
traceData[0]?.data,
}
if (!jsonObject) return ""

Expand All @@ -165,7 +168,7 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
message.error("Failed to convert JSON to YAML. Please ensure the data is valid.")
return getStringOrJson(jsonObject)
}
}, [editorFormat, traceData, dataPreview])
}, [editorFormat, traceData, rowDataPreview])

const mappingOptions = useMemo(() => {
const uniquePaths = new Set<string>()
Expand All @@ -176,14 +179,14 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
})

return Array.from(uniquePaths).map((item) => ({value: item}))
}, [data])
}, [traceData])

const columnOptions = useMemo(() => {
const selectedColumns = mappingData
.map((item) => item.column)
.filter((col) => col !== "create")
return tableColumns.filter((column) => !selectedColumns.includes(column))
}, [mappingData, tableColumns])
return selectedTestsetColumns.filter((column) => !selectedColumns.includes(column))
}, [mappingData, selectedTestsetColumns])

const onMappingOptionChange = ({
pathName,
Expand Down Expand Up @@ -220,15 +223,15 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
}, [mappingData])

const resetStates = () => {
setTableColumns([])
setTableRows([])
setSelectedTestsetColumns([])
setSelectedTestsetRows([])
setShowLastFiveRows(false)
setMappingData((prev) => prev.map((item) => ({...item, column: "", newColumn: ""})))
setPreview({key: traceData[0]?.key || "", data: []})
setTestsetName("")
setNewTestsetName("")
}

const mapAndConvertDataInCsvFormat = (traceData: TraceData[]) => {
const mapAndConvertDataInCsvFormat = (traceData: TestsetTraceData[]) => {
return traceData.map((item) => {
const formattedItem: Record<string, any> = {}

Expand Down Expand Up @@ -262,17 +265,17 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
const newTestsetData = mapAndConvertDataInCsvFormat(traceData)

if (isNewTestset) {
if (!testsetName) {
if (!newTestsetName) {
message.error("Please add a Test set name before saving it")
return
}

await createNewTestset(testsetName, newTestsetData)
await createNewTestset(newTestsetName, newTestsetData)
message.success("Test set created successfully")
} else {
await updateTestset(testset.id as string, testset.name, [
...newTestsetData,
...tableRows,
...selectedTestsetRows,
])
message.success("Test set updated successfully")
}
Expand Down Expand Up @@ -348,8 +351,8 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
<div className="relative">
<Input
style={{width: elementWidth}}
value={testsetName}
onChange={(e) => setTestsetName(e.target.value)}
value={newTestsetName}
onChange={(e) => setNewTestsetName(e.target.value)}
placeholder="Test set name"
/>
<PencilSimple
Expand All @@ -369,8 +372,8 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
<div className="flex justify-between items-center mb-2">
<Select
style={{width: elementWidth}}
value={dataPreview}
onChange={(value) => setDataPreview(value)}
value={rowDataPreview}
onChange={(value) => setRowDataPreview(value)}
options={traceData.map((trace) => ({
value: trace?.key,
label: `Span ${trace.id}`,
Expand All @@ -386,8 +389,9 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
>
Remove span{" "}
{
traceData.find((trace) => trace.key === dataPreview)
?.id
traceData.find(
(trace) => trace.key === rowDataPreview,
)?.id
}
</Button>
)}
Expand Down Expand Up @@ -564,8 +568,8 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
setShowLastFiveRows(!showLastFiveRows)
}
>
Show last {tableRows.slice(-5).length} test cases in
test set
Show last {selectedTestsetTestCases.length} test
cases in test set
</Checkbox>
)}
</div>
Expand All @@ -590,17 +594,19 @@ const TestsetDrawer = ({onClose, data, ...props}: Props) => {
})}
dataSource={[
...preview.data,
...(showLastFiveRows ? tableRows.slice(-5) : []),
...(showLastFiveRows
? selectedTestsetTestCases
: []),
]}
rowClassName={(_, index) => {
if (showLastFiveRows) {
const totalRows =
preview.data.length +
tableRows.slice(-5).length
selectedTestsetTestCases.length

if (
index >=
totalRows - tableRows.slice(-5).length
totalRows - selectedTestsetTestCases.length
) {
return "!bg-[#fafafa]"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ResultTag from "@/components/ResultTag/ResultTag"
import {JSSTheme} from "@/lib/Types"
import {JSSTheme, KeyValuePair} from "@/lib/Types"
import {ArrowRight, Database, PlusCircle, Rocket, Timer} from "@phosphor-icons/react"
import {Button, Divider, Space, Tabs, TabsProps, Typography} from "antd"
import React, {useState} from "react"
Expand Down Expand Up @@ -88,10 +88,6 @@ const TraceContent = ({activeTrace}: TraceContentProps) => {
const {icon, bgColor, color} = statusMapper(activeTrace.node.type)
const [isTestsetDrawerOpen, setIsTestsetDrawerOpen] = useState(false)

const testsetDrawerData = () => {
return [{data: activeTrace.data, key: activeTrace.key, id: 1}]
}

const transformDataInputs = (data: any) => {
return Object.keys(data).reduce((acc, curr) => {
if (curr === "prompt") {
Expand Down Expand Up @@ -279,6 +275,7 @@ const TraceContent = ({activeTrace}: TraceContentProps) => {
<Button
className="flex items-center"
onClick={() => setIsTestsetDrawerOpen(true)}
disabled={!activeTrace.key}
>
<Database size={14} />
Add to testset
Expand Down Expand Up @@ -368,7 +365,7 @@ const TraceContent = ({activeTrace}: TraceContentProps) => {
{isTestsetDrawerOpen && (
<TestsetDrawer
open={isTestsetDrawerOpen}
data={testsetDrawerData() as any}
data={[{data: activeTrace.data as KeyValuePair, key: activeTrace.key, id: 1}]}
onClose={() => setIsTestsetDrawerOpen(false)}
/>
)}
Expand Down

0 comments on commit a822c66

Please sign in to comment.