Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sorting functionality and refactor table components #445

Open
wants to merge 13 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@tanstack/react-query": "^5.56.2",
"@tanstack/react-table": "^8.20.5",
"axios": "^1.7.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
Expand Down
196 changes: 134 additions & 62 deletions src/app/proposals/LatestProposalsTable.tsx
Original file line number Diff line number Diff line change
@@ -1,81 +1,153 @@
import { useFetchAllProposals } from '@/app/proposals/hooks/useFetchLatestProposals'
import { EventArgumentsParameter, getEventArguments } from '@/app/proposals/shared/utils'
import { StatusColumn } from '@/app/proposals/StatusColumn'
import { Table } from '@/components/Table'
import { useMemo, memo, useState } from 'react'
import {
createColumnHelper,
type SortingState,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from '@tanstack/react-table'
import { type LatestProposalResponse } from './hooks/useFetchLatestProposals'
import { StatusColumn } from '@/app/proposals/table-columns/StatusColumn'
import { StatefulTable } from '@/components/Table'
import { HeaderTitle, Typography } from '@/components/Typography'
import { SharedProposalsTableContextProvider } from '@/app/proposals/SharedProposalsTableContext'
import { ProposalsContextProvider } from '@/app/proposals/ProposalsContext'
import { SentimentColumn } from '@/app/proposals/SentimentColumn'
import { VotesColumn } from '@/app/proposals/VotesColumn'
import { ProposalNameColumn } from '@/app/proposals/ProposalNameColumn'
import { ReactNode, useMemo, memo, useState } from 'react'
import { TimeRemainingColumn } from '@/app/proposals/TimeRemainingColumn'
import { SentimentColumn } from '@/app/proposals/table-columns/SentimentColumn'
import { ProposalNameColumn } from '@/app/proposals/table-columns/ProposalNameColumn'
import { VotesColumn } from './table-columns/VotesColumn'
import { TimeColumn } from './table-columns/TimeColumn'
import { DebounceSearch } from '../../components/DebounceSearch/DebounceSearch'
import { useProposalListData } from './hooks/useProposalListData'

interface LatestProposalsTableProps {
latestProposals: ReturnType<typeof useFetchAllProposals>['latestProposals']
proposals: LatestProposalResponse[]
}

const latestProposalsTransformer = (proposals: ReturnType<typeof getEventArguments>[]) =>
proposals.map((proposal, i) => {
// Create the withContext function to wrap components in ProposalsProvider
const withContext = (component: ReactNode) => (
<ProposalsContextProvider {...proposal} index={i}>
{component}
</ProposalsContextProvider>
)
return {
Proposal: withContext(<ProposalNameColumn />),
'Quorum Votes': withContext(<VotesColumn />),
Date: proposal.Starts.format('MM-DD-YYYY'),
'Time Remaining': withContext(<TimeRemainingColumn />),
Sentiment: withContext(<SentimentColumn key={`${proposal.proposalId}_${i}`} />),
Status: withContext(<StatusColumn />),
}
})

const LatestProposalsTable = ({ latestProposals }: LatestProposalsTableProps) => {
const LatestProposalsTable = ({ proposals }: LatestProposalsTableProps) => {
// search textfield
const [searchedProposal, setSearchedProposal] = useState('')

const latestProposalsMapped = useMemo(() => {
if (!latestProposals?.length) return []
const proposalsWithEventArgs = latestProposals?.map(proposal =>
getEventArguments(proposal as unknown as EventArgumentsParameter),
)
const parsedProposals = latestProposalsTransformer(proposalsWithEventArgs)
const searchResultsProposals = parsedProposals?.filter(({ Proposal }) => {
try {
const proposalName = String(Proposal?.props?.name).toLowerCase()
if (!proposalName) return false
return proposalName.includes(searchedProposal.toLowerCase())
} catch (e) {
return false
}
})

return searchResultsProposals ?? []
}, [latestProposals, searchedProposal])
// React-table sorting state
const [sorting, setSorting] = useState<SortingState>([])
// query all proposals parameters at the Governor after receiving proposal list
const proposalListData = useProposalListData({ proposals })
// filter all proposals after user typed text in the search field
const filteredProposalList = useMemo(
() =>
proposalListData.filter(({ name }) => {
try {
const proposalName = String(name).toLowerCase()
return proposalName.includes(searchedProposal.toLowerCase())
} catch (e) {
return false
}
}),
[proposalListData, searchedProposal],
)

const onSearchSubmit = (searchValue: string) => {
setSearchedProposal(searchValue)
}
// Table data definition helper
const { accessor } = createColumnHelper<(typeof proposalListData)[number]>()
// Table columns definition
const columns = [
accessor('name', {
id: 'name',
header: 'Proposal',
cell: info => (
<ProposalNameColumn name={info.row.original.name} proposalId={info.row.original.proposalId} />
),
}),
accessor('votes.quorum', {
id: 'votes',
header: 'Quorum Votes',
cell: info => {
const { forVotes, abstainVotes } = info.row.original.votes
return (
<VotesColumn
forVotes={forVotes}
abstainVotes={abstainVotes}
quorumAtSnapshot={info.row.original.quorumAtSnapshot}
/>
)
},
}),
accessor(row => row.Starts.unix(), {
id: 'date',
header: 'Date',
cell: info => <Typography tagVariant="p">{info.row.original.Starts.format('MM-DD-YYYY')}</Typography>,
}),
accessor('blocksUntilClosure', {
id: 'timeRemaining',
header: 'Time Remaining',
cell: info => {
const { blocksUntilClosure, proposalDeadline, blockNumber } = info.row.original
return (
<TimeColumn
blocksUntilClosure={blocksUntilClosure}
proposalDeadline={proposalDeadline}
proposalBlockNumber={Number(blockNumber)}
/>
)
},
}),
accessor(row => row.votes, {
id: 'sentiment',
header: 'Sentiment',
cell: info => (
<SentimentColumn
index={info.row.index}
againstVotes={info.row.original.votes?.againstVotes}
forVotes={info.row.original.votes?.forVotes}
abstainVotes={info.row.original.votes?.abstainVotes}
/>
),
sortingFn: (rowA, rowB) => {
const getDominantVoteType = (votesData: typeof rowA.original.votes) => {
const { againstVotes, forVotes, abstainVotes } = votesData
const maxCount = Math.max(againstVotes, forVotes, abstainVotes)
if (maxCount === forVotes) return { type: 'for', count: maxCount, priority: 1 }
if (maxCount === againstVotes) return { type: 'against', count: maxCount, priority: 2 }
else return { type: 'abstain', count: maxCount, priority: 3 }
}
const dominantA = getDominantVoteType(rowA.original.votes)
const dominantB = getDominantVoteType(rowB.original.votes)
if (dominantA.type === dominantB.type) {
return dominantB.count - dominantA.count
}
return dominantA.priority - dominantB.priority
},
}),
accessor('proposalState', {
id: 'status',
header: 'Status',
cell: info => <StatusColumn proposalState={info.row.original.proposalState} />,
}),
]
// create table data model which is passed to the Table UI component
const table = useReactTable({
columns,
data: filteredProposalList,
state: {
sorting,
},
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
})

return (
<div>
<HeaderTitle className="mb-4">Latest Proposals</HeaderTitle>
<DebounceSearch placeholder="Search a proposal" onSearchSubmit={onSearchSubmit} />
{latestProposalsMapped.length > 0 ? (
<SharedProposalsTableContextProvider>
<Table
key={latestProposalsMapped.length}
data={latestProposalsMapped}
data-testid="TableProposals"
tbodyProps={{
'data-testid': 'TableProposalsTbody',
}}
className="overflow-visible"
/>
</SharedProposalsTableContextProvider>
{filteredProposalList.length > 0 ? (
<StatefulTable
equalColumns
table={table}
data-testid="TableProposals"
tbodyProps={{
'data-testid': 'TableProposalsTbody',
}}
className="overflow-visible"
/>
) : (
<Typography tagVariant="p">No proposals found &#x1F622;</Typography>
)}
Expand Down
18 changes: 0 additions & 18 deletions src/app/proposals/ProposalNameColumn.tsx

This file was deleted.

64 changes: 0 additions & 64 deletions src/app/proposals/ProposalsContext.tsx

This file was deleted.

31 changes: 0 additions & 31 deletions src/app/proposals/SharedProposalsTableContext.tsx

This file was deleted.

Loading
Loading