stacker.news/components/pay-bounty.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-12-26 22:51:47 +00:00
import React, { useCallback } from 'react'
2023-07-24 18:35:05 +00:00
import Button from 'react-bootstrap/Button'
2023-01-26 16:11:55 +00:00
import styles from './pay-bounty.module.css'
import ActionTooltip from './action-tooltip'
import { useMe } from './me'
import { numWithUnits } from '../lib/format'
2023-01-26 16:11:55 +00:00
import { useShowModal } from './modal'
2023-05-06 21:51:17 +00:00
import { useRoot } from './root'
2023-10-06 20:01:51 +00:00
import { payOrLoginError, useInvoiceModal } from './invoice'
2023-12-26 22:51:47 +00:00
import { useAct } from './item-act'
2023-01-26 16:11:55 +00:00
export default function PayBounty ({ children, item }) {
const me = useMe()
const showModal = useShowModal()
2023-05-06 21:51:17 +00:00
const root = useRoot()
2023-01-26 16:11:55 +00:00
2023-12-26 22:51:47 +00:00
const onUpdate = useCallback((cache, { data: { act: { id, path } } }) => {
// update root bounty status
const root = path.split('.')[0]
cache.modify({
id: `Item:${root}`,
fields: {
bountyPaidTo (existingPaidTo = []) {
return [...(existingPaidTo || []), Number(id)]
2023-01-26 16:11:55 +00:00
}
2023-12-26 22:51:47 +00:00
}
})
}, [])
2023-01-26 16:11:55 +00:00
2023-12-26 22:51:47 +00:00
const [act] = useAct({ onUpdate })
2023-01-26 16:11:55 +00:00
2023-10-06 20:01:51 +00:00
const showInvoiceModal = useInvoiceModal(async ({ hash, hmac }, { variables }) => {
await act({ variables: { ...variables, hash, hmac } })
}, [act])
2023-01-26 16:11:55 +00:00
const handlePayBounty = async onComplete => {
2023-12-26 22:51:47 +00:00
const variables = { id: item.id, sats: root.bounty, act: 'TIP', path: item.path }
2023-01-26 16:11:55 +00:00
try {
await act({
2023-12-26 22:51:47 +00:00
variables,
2023-01-26 16:11:55 +00:00
optimisticResponse: {
2023-12-26 22:51:47 +00:00
act: variables
2023-01-26 16:11:55 +00:00
}
})
onComplete()
2023-01-26 16:11:55 +00:00
} catch (error) {
if (payOrLoginError(error)) {
2023-12-26 22:51:47 +00:00
showInvoiceModal({ amount: root.bounty }, { variables })
2023-01-26 16:11:55 +00:00
return
}
throw new Error({ message: error.toString() })
}
}
2023-05-06 21:51:17 +00:00
if (!me || item.mine || root.user.name !== me.name) {
2023-01-26 16:11:55 +00:00
return null
}
return (
<ActionTooltip
notForm
overlayText={numWithUnits(root.bounty)}
2023-01-26 16:11:55 +00:00
>
<div
className={styles.pay} onClick={() => {
showModal(onClose => (
<>
2023-07-24 18:35:05 +00:00
<div className='text-center fw-bold text-muted'>
Pay this bounty to {item.user.name}?
</div>
<div className='text-center'>
<Button className='mt-4' variant='primary' onClick={() => handlePayBounty(onClose)}>
pay <small>{numWithUnits(root.bounty)}</small>
</Button>
</div>
</>
))
}}
2023-01-26 16:11:55 +00:00
>
pay bounty
</div>
2023-01-26 16:11:55 +00:00
</ActionTooltip>
)
}