Skip to content

Instantly share code, notes, and snippets.

@bogdansoare
Created August 20, 2019 07:22
Show Gist options
  • Save bogdansoare/be69d723e0b09f520b5def2ea3ff3e77 to your computer and use it in GitHub Desktop.
Save bogdansoare/be69d723e0b09f520b5def2ea3ff3e77 to your computer and use it in GitHub Desktop.
/** @jsx jsx */
import {jsx} from '@emotion/core'
import styled from '@emotion/styled'
import React from 'react'
import Logo from './components/logo'
import VisuallyHidden from '@reach/visually-hidden'
import {Dialog} from '@reach/dialog'
import {
CircleButton,
Button,
Spinner,
FormGroup,
Centered,
} from './components/lib'
import {useAuth} from './context/auth-context'
import {useAsync} from 'react-async';
function LoginForm({onSubmit, buttonText}) {
const {isPending, isRejected, error, run} = useAsync({
deferFn: args => onSubmit(args[0])
})
function handleSubmit(event) {
event.preventDefault()
const {username, password} = event.target.elements
run({
username: username.value,
password: password.value,
})
}
return (
<form
onSubmit={handleSubmit}
css={{
display: 'flex',
flexDirection: 'column',
alignItems: 'stretch',
'> div': {
margin: '10px auto',
width: '100%',
maxWidth: '300px',
},
}}
>
<FormGroup>
<label htmlFor="username">Username</label>
<input id="username" />
</FormGroup>
<FormGroup>
<label htmlFor="password">Password</label>
<input id="password" type="password" />
</FormGroup>
<div>
<Button type="submit">
{buttonText} {isPending ? <Spinner css={{marginLeft: 5}} /> : null}
</Button>
</div>
{isRejected ? (
<div css={{color: 'red'}}>{error ? error.message : null}</div>
) : null}
</form>
)
}
function Modal({button, children}) {
const [isOpen, setIsOpen] = React.useState(false)
return (
<>
{React.cloneElement(button, {onClick: () => setIsOpen(true)})}
<Dialog isOpen={isOpen}>
<div css={{display: 'flex', justifyContent: 'flex-end'}}>
<CircleButton onClick={() => setIsOpen(false)}>
<VisuallyHidden>Close</VisuallyHidden>
<span aria-hidden>×</span>
</CircleButton>
</div>
{children}
</Dialog>
</>
)
}
const ModalTitle = styled.h3({
textAlign: 'center',
fontSize: '2em',
})
function UnauthenticatedApp() {
const {login, register} = useAuth()
return (
<Centered>
<Logo width="80" height="80" />
<h1>Bookshelf</h1>
<div css={{display: 'flex'}}>
<Modal button={<Button css={{marginRight: 6}}>Login</Button>}>
<ModalTitle>Login</ModalTitle>
<LoginForm onSubmit={login} buttonText="Login" />
</Modal>
<Modal button={<Button variant="secondary">Register</Button>}>
<ModalTitle>Register</ModalTitle>
<LoginForm onSubmit={register} buttonText="Register" />
</Modal>
</div>
</Centered>
)
}
export default UnauthenticatedApp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment