manifold/web/components/contract-prob-graph.tsx

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-12-13 01:10:28 +00:00
import { DatumValue } from '@nivo/core'
import { ResponsiveLine } from '@nivo/line'
2021-12-13 06:55:28 +00:00
import dayjs from 'dayjs'
2021-12-12 22:14:52 +00:00
import { useBets } from '../hooks/use-bets'
import { Contract } from '../lib/firebase/contracts'
export function ContractProbGraph(props: { contract: Contract }) {
const { contract } = props
const { id, seedAmounts } = contract
let bets = useBets(id)
if (bets === 'loading') bets = []
const seedProb =
seedAmounts.YES ** 2 / (seedAmounts.YES ** 2 + seedAmounts.NO ** 2)
2021-12-13 06:55:28 +00:00
const times = [
contract.createdTime,
...bets.map((bet) => bet.createdTime),
].map((time) => new Date(time))
2021-12-12 22:14:52 +00:00
const probs = [seedProb, ...bets.map((bet) => bet.probAfter)]
2021-12-13 06:55:28 +00:00
const points = probs.map((prob, i) => ({ x: times[i], y: prob * 100 }))
2021-12-13 01:10:28 +00:00
const data = [{ id: 'Yes', data: points, color: '#11b981' }]
2021-12-13 06:55:28 +00:00
const lessThanAWeek =
times[times.length - 1].getTime() - times[0].getTime() <
1000 * 60 * 60 * 24 * 7
2021-12-13 01:10:28 +00:00
const tickValues = [0, 25, 50, 75, 100]
return (
<div className="w-full" style={{ height: 400 }}>
<ResponsiveLine
data={data}
yScale={{ min: 0, max: 100, type: 'linear' }}
yFormat={formatPercent}
gridYValues={tickValues}
axisLeft={{
tickValues,
format: formatPercent,
}}
2021-12-13 06:55:28 +00:00
xScale={{ type: 'time' }}
xFormat={(d) => formatTime(+d.valueOf(), lessThanAWeek)}
2021-12-13 01:10:28 +00:00
axisBottom={{
2021-12-13 06:55:28 +00:00
format: (time) => formatTime(+time, lessThanAWeek),
2021-12-13 01:10:28 +00:00
}}
colors={{ datum: 'color' }}
2021-12-13 06:55:28 +00:00
pointSize={10}
pointBorderWidth={1}
2021-12-13 01:10:28 +00:00
pointBorderColor="#fff"
enableSlices="x"
enableArea
2021-12-13 06:55:28 +00:00
margin={{ top: 20, right: 22, bottom: 22, left: 40 }}
2021-12-13 01:10:28 +00:00
/>
</div>
)
}
2021-12-12 22:14:52 +00:00
2021-12-13 01:10:28 +00:00
function formatPercent(y: DatumValue) {
return `${Math.round(+y.toString())}%`
2021-12-12 22:14:52 +00:00
}
2021-12-13 06:55:28 +00:00
function formatTime(time: number, includeTime: boolean) {
const d = dayjs(time)
if (d.isSame(Date.now(), 'day')) return d.format('ha')
if (includeTime) return dayjs(time).format('MMM D, ha')
return dayjs(time).format('MMM D')
}