stacker.news/components/item-act.js

88 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-09-11 21:52:19 +00:00
import { InputGroup, Modal } from 'react-bootstrap'
2021-09-10 18:55:36 +00:00
import React, { useState, useCallback, useContext, useRef, useEffect } from 'react'
import * as Yup from 'yup'
import { Form, Input, SubmitButton } from './form'
2021-09-12 16:55:38 +00:00
import { useMe } from './me'
2021-09-10 18:55:36 +00:00
export const ItemActContext = React.createContext({
item: null,
setItem: () => {}
})
export function ItemActProvider ({ children }) {
const [item, setItem] = useState(null)
const contextValue = {
item,
setItem: useCallback(i => setItem(i), [])
}
return (
<ItemActContext.Provider value={contextValue}>
{children}
</ItemActContext.Provider>
)
}
export function useItemAct () {
const { item, setItem } = useContext(ItemActContext)
return { item, setItem }
}
export const ActSchema = Yup.object({
amount: Yup.number().typeError('must be a number').required('required')
.positive('must be positive').integer('must be whole')
})
export function ItemActModal () {
const { item, setItem } = useItemAct()
const inputRef = useRef(null)
2021-09-12 16:55:38 +00:00
const me = useMe()
2021-09-10 18:55:36 +00:00
useEffect(() => {
inputRef.current?.focus()
}, [item])
return (
<Modal
show={!!item}
onHide={() => {
setItem(null)
}}
>
2022-03-10 19:51:26 +00:00
<div className='modal-close' onClick={() => setItem(null)}>X</div>
2021-09-10 18:55:36 +00:00
<Modal.Body>
<Form
initial={{
amount: me?.tipDefault,
2021-09-12 16:55:38 +00:00
default: false
2021-09-10 18:55:36 +00:00
}}
schema={ActSchema}
onSubmit={async ({ amount }) => {
2021-09-12 16:55:38 +00:00
await item.act({
variables: {
id: item.itemId,
sats: Number(amount)
2021-09-12 16:55:38 +00:00
}
})
2021-09-10 18:55:36 +00:00
await item.strike()
setItem(null)
}}
>
<Input
label='amount'
name='amount'
innerRef={inputRef}
required
autoFocus
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
2021-09-11 21:52:19 +00:00
<div className='d-flex'>
<SubmitButton variant='success' className='ml-auto mt-1 px-4' value='TIP'>tip</SubmitButton>
2021-09-10 18:55:36 +00:00
</div>
</Form>
</Modal.Body>
</Modal>
)
}