feat: upload files with postage stamps (#126)

* chore: release 0.3.0

* feat: added postage stamp table to list all stamps

* feat: postage stamp modal to purchase stamps

* feat: postage stamps provider

* chore: added formik

* chore: proper form state handling

* chore: revert accidental release inclusion

* chore: polishing identified when developing the upload functionality

* feat: upload files with postage stamps

* style: tabs styles are defined in theme now, addressed other PR comments

* style: removed unused styles

* fix: enable encrypted hashes to download

Co-authored-by: bee-worker <70210089+bee-worker@users.noreply.github.com>
This commit is contained in:
Vojtech Simetka
2021-06-02 13:25:49 +02:00
committed by GitHub
parent 4074a9de5d
commit 92c727e5f5
7 changed files with 365 additions and 74 deletions
+3 -2
View File
@@ -7,9 +7,10 @@ function truncStringPortion(str: string, firstCharCount = 10, endCharCount = 10)
interface Props {
peerId: string
characterLength?: number
}
export default function PeerDetail(props: Props): ReactElement {
export default function PeerDetail({ peerId, characterLength }: Props): ReactElement {
return (
<Typography
variant="button"
@@ -17,7 +18,7 @@ export default function PeerDetail(props: Props): ReactElement {
fontFamily: 'monospace, monospace',
}}
>
{truncStringPortion(props.peerId)}
{truncStringPortion(peerId, characterLength, characterLength)}
</Typography>
)
}
+71
View File
@@ -0,0 +1,71 @@
import React, { ReactElement, ReactNode } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Tabs from '@material-ui/core/Tabs'
import Tab from '@material-ui/core/Tab'
import Typography from '@material-ui/core/Typography'
import Box from '@material-ui/core/Box'
interface TabPanelProps {
children?: ReactNode
index: number
value: number
}
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
<Typography>{children}</Typography>
</Box>
)}
</div>
)
}
const useStyles = makeStyles(() => ({
root: {
flexGrow: 1,
},
}))
interface TabsValues {
component: ReactNode
label: string
}
interface Props {
values: TabsValues[]
}
export default function SimpleTabs({ values }: Props): ReactElement {
const classes = useStyles()
const [value, setValue] = React.useState<number>(0)
const handleChange = (event: React.ChangeEvent<Record<string, never>>, newValue: number) => {
setValue(newValue)
}
return (
<div className={classes.root}>
<Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
{values.map(({ label }, index) => (
<Tab key={index} label={label} />
))}
</Tabs>
{values.map(({ component }, index) => (
<TabPanel key={index} value={value} index={index}>
{component}
</TabPanel>
))}
</div>
)
}
+65
View File
@@ -0,0 +1,65 @@
import { ReactElement, useState } from 'react'
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles'
import { Paper, InputBase, IconButton, FormHelperText } from '@material-ui/core'
import { Search } from '@material-ui/icons'
import { apiHost } from '../../constants'
import { Utils } from '@ethersphere/bee-js'
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
padding: theme.spacing(0.25),
display: 'flex',
alignItems: 'center',
},
input: {
marginLeft: theme.spacing(1),
flex: 1,
},
iconButton: {
padding: 10,
},
divider: {
height: 28,
margin: 4,
},
}),
)
export default function Files(): ReactElement {
const classes = useStyles()
const [referenceInput, setReferenceInput] = useState('')
const [referenceError, setReferenceError] = useState<Error | null>(null)
const handleReferenceChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setReferenceInput(e.target.value)
if (Utils.Hex.isHexString(e.target.value, 64) || Utils.Hex.isHexString(e.target.value, 128)) setReferenceError(null)
else setReferenceError(new Error('Incorrect format of swarm hash'))
}
return (
<>
<Paper className={classes.root}>
<InputBase
className={classes.input}
placeholder="Enter swarm reference e.g. 0773a91efd6547c754fc1d95fb1c62c7d1b47f959c2caa685dfec8736da95c1c"
inputProps={{ 'aria-label': 'retrieve file from swarm' }}
value={referenceInput}
onChange={handleReferenceChange}
/>
<IconButton
href={`${apiHost}/bzz/${referenceInput}`}
target="_blank"
disabled={referenceError !== null || !referenceInput}
className={classes.iconButton}
aria-label="download"
>
<Search />
</IconButton>
</Paper>
{referenceError && <FormHelperText error>{referenceError.message}</FormHelperText>}
</>
)
}
+48
View File
@@ -0,0 +1,48 @@
import React, { ReactElement } from 'react'
import Button from '@material-ui/core/Button'
import Menu from '@material-ui/core/Menu'
import MenuItem from '@material-ui/core/MenuItem'
import ListItemIcon from '@material-ui/core/ListItemIcon'
import { PostageBatch } from '@ethersphere/bee-js'
import PeerDetailDrawer from '../../components/PeerDetail'
interface Props {
stamps: PostageBatch[] | null
selectedStamp: PostageBatch | null
setSelected: (stamp: PostageBatch) => void
}
export default function SimpleMenu({ stamps, selectedStamp, setSelected }: Props): ReactElement | null {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
if (!stamps) return null
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget)
}
const handleClose = () => setAnchorEl(null)
return (
<div>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
Change
</Button>
<Menu id="simple-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose}>
{stamps.map(stamp => (
<MenuItem
key={stamp.batchID}
onClick={() => {
setSelected(stamp)
handleClose()
}}
selected={stamp.batchID === selectedStamp?.batchID}
>
<ListItemIcon>{stamp.utilization}</ListItemIcon>
<PeerDetailDrawer peerId={stamp.batchID} />
</MenuItem>
))}
</Menu>
</div>
)
}
+101
View File
@@ -0,0 +1,101 @@
import { ReactElement, useContext, useEffect, useState } from 'react'
import { beeApi } from '../../services/bee'
import { Button, Container, CircularProgress, FormHelperText } from '@material-ui/core'
import { DropzoneArea } from 'material-ui-dropzone'
import ClipboardCopy from '../../components/ClipboardCopy'
import { PostageBatch } from '@ethersphere/bee-js'
import { Context } from '../../providers/Stamps'
import PeerDetailDrawer from '../../components/PeerDetail'
import Chip from '@material-ui/core/Chip'
import Avatar from '@material-ui/core/Avatar'
import SelectStamp from './SelectStamp'
import CreatePostageStamp from '../stamps/CreatePostageStampModal'
export default function Files(): ReactElement {
const [file, setFile] = useState<File | null>(null)
const [uploadReference, setUploadReference] = useState('')
const [uploadError, setUploadError] = useState<Error | null>(null)
const [isUploadingFile, setIsUploadingFile] = useState(false)
const [selectedStamp, setSelectedStamp] = useState<PostageBatch | null>(null)
const { isLoading, error, stamps } = useContext(Context)
// Choose a postage stamp that has the lowest utilization
useEffect(() => {
if (!selectedStamp && stamps && stamps.length > 0) {
const stamp = stamps.reduce((prev, curr) => {
if (curr.utilization < prev.utilization) return curr
return prev
}, stamps[0])
setSelectedStamp(stamp)
}
}, [isLoading, error, stamps, selectedStamp])
const uploadFile = () => {
if (file === null || selectedStamp === null) return
setIsUploadingFile(true)
setUploadError(null)
beeApi.files
.uploadFile(selectedStamp.batchID, file)
.then(hash => {
setUploadReference(hash)
setFile(null)
})
.catch(setUploadError) // FIXME: should instead trigger notification
.finally(() => {
setIsUploadingFile(false)
})
}
const handleChange = (files?: File[]) => {
if (files) {
setFile(files[0])
setUploadReference('')
}
}
return (
<div>
<div>
<DropzoneArea onChange={handleChange} filesLimit={1} />
<div style={{ marginTop: '15px' }}>
{selectedStamp && (
<div style={{ display: 'flex' }}>
<small>
with Postage Stamp{' '}
<Chip
avatar={<Avatar>{selectedStamp.utilization}</Avatar>}
label={<PeerDetailDrawer peerId={selectedStamp.batchID} characterLength={6} />}
deleteIcon={<ClipboardCopy value={selectedStamp.batchID} />}
onDelete={() => {} /* eslint-disable-line*/}
variant="outlined"
/>
</small>
<SelectStamp stamps={stamps} selectedStamp={selectedStamp} setSelected={setSelectedStamp} />
</div>
)}
{!selectedStamp && <CreatePostageStamp />}
<Button disabled={!file && isUploadingFile && !selectedStamp} onClick={() => uploadFile()}>
Upload
</Button>
{isUploadingFile && (
<Container style={{ textAlign: 'center', padding: '50px' }}>
<CircularProgress />
</Container>
)}
{uploadReference && (
<div style={{ marginBottom: '15px', display: 'flex' }}>
<span>{uploadReference}</span>
<ClipboardCopy value={uploadReference} />
</div>
)}
{uploadError && <FormHelperText error>{uploadError.message}</FormHelperText>}
</div>
</div>
</div>
)
}
+17 -70
View File
@@ -1,58 +1,17 @@
import { ReactElement, useState } from 'react'
import { ReactElement } from 'react'
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles'
import {
Paper,
InputBase,
IconButton,
Typography,
Container,
CircularProgress,
FormHelperText,
} from '@material-ui/core'
import { Search } from '@material-ui/icons'
import { Container, CircularProgress } from '@material-ui/core'
import TroubleshootConnectionCard from '../../components/TroubleshootConnectionCard'
import { useApiHealth, useDebugApiHealth } from '../../hooks/apiHooks'
import { apiHost } from '../../constants'
import { Utils } from '@ethersphere/bee-js'
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
padding: '2px 4px',
display: 'flex',
alignItems: 'center',
},
input: {
marginLeft: theme.spacing(1),
flex: 1,
},
iconButton: {
padding: 10,
},
divider: {
height: 28,
margin: 4,
},
}),
)
import Download from './Download'
import Upload from './Upload'
import TabsContainer from '../../components/TabsContainer'
export default function Files(): ReactElement {
const classes = useStyles()
const [referenceInput, setReferenceInput] = useState('')
const [referenceError, setReferenceError] = useState<Error | null>(null)
const { health, isLoadingHealth } = useApiHealth()
const { nodeHealth, isLoadingNodeHealth } = useDebugApiHealth()
const handleReferenceChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setReferenceInput(e.target.value)
if (Utils.Hex.isHexString(e.target.value, 64)) setReferenceError(null)
else setReferenceError(new Error('Incorrect format of swarm hash'))
}
if (isLoadingHealth || isLoadingNodeHealth) {
return (
<Container style={{ textAlign: 'center', padding: '50px' }}>
@@ -65,30 +24,18 @@ export default function Files(): ReactElement {
return (
<Container maxWidth="sm">
<div style={{ marginBottom: '7px' }}>
<Typography variant="button" color="primary" style={{ marginRight: '7px' }}>
Download
</Typography>
</div>
<Paper className={classes.root}>
<InputBase
className={classes.input}
placeholder="Enter swarm reference e.g. 0773a91efd6547c754fc1d95fb1c62c7d1b47f959c2caa685dfec8736da95c1c"
inputProps={{ 'aria-label': 'retrieve file from swarm' }}
value={referenceInput}
onChange={handleReferenceChange}
/>
<IconButton
href={`${apiHost}/files/${referenceInput}`}
target="_blank"
disabled={referenceError !== null || !referenceInput}
className={classes.iconButton}
aria-label="download"
>
<Search />
</IconButton>
</Paper>
{referenceError && <FormHelperText error>{referenceError.message}</FormHelperText>}
<TabsContainer
values={[
{
label: 'download',
component: <Download />,
},
{
label: 'upload',
component: <Upload />,
},
]}
/>
</Container>
)
}
+60 -2
View File
@@ -1,4 +1,5 @@
import { createMuiTheme } from '@material-ui/core/styles'
import { createMuiTheme, Theme } from '@material-ui/core/styles'
import { orange } from '@material-ui/core/colors'
declare module '@material-ui/core/styles/createPalette' {
interface TypeBackground {
@@ -6,6 +7,54 @@ declare module '@material-ui/core/styles/createPalette' {
}
}
// Overwriting default components styles
const componentsOverrides = (theme: Theme) => ({
MuiTab: {
root: {
backgroundColor: 'transparent',
fontWeight: theme.typography.fontWeightRegular,
marginRight: theme.spacing(4),
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
'&:hover': {
color: theme.palette.secondary,
opacity: 1,
},
'&$selected': {
color: theme.palette.secondary,
fontWeight: theme.typography.fontWeightMedium,
},
'&:focus': {
color: theme.palette.secondary,
},
},
},
MuiTabs: {
root: {
borderBottom: 'none',
},
indicator: {
backgroundColor: theme.palette.primary.main,
},
},
})
const propsOverrides = {
MuiTab: {
disableRipple: true,
},
}
export const lightTheme = createMuiTheme({
palette: {
type: 'light',
@@ -13,7 +62,9 @@ export const lightTheme = createMuiTheme({
default: '#fafafa',
},
primary: {
main: '#6a6a6a',
light: orange.A200,
main: '#dd7700',
dark: orange[800],
},
secondary: {
main: '#333333',
@@ -32,7 +83,9 @@ export const darkTheme = createMuiTheme({
paper: '#161b22',
},
primary: {
light: orange.A200,
main: '#dd7700',
dark: orange[800],
},
secondary: {
main: '#1f2937',
@@ -42,3 +95,8 @@ export const darkTheme = createMuiTheme({
fontFamily: ['Work Sans', 'Montserrat', 'Nunito', 'Roboto', '"Helvetica Neue"', 'Arial', 'sans-serif'].join(','),
},
})
darkTheme.overrides = componentsOverrides(darkTheme)
darkTheme.props = propsOverrides
lightTheme.overrides = componentsOverrides(lightTheme)
lightTheme.props = propsOverrides