Skip to content

Commit

Permalink
Merge pull request #541 from systemli/Fix-TickerUsersForm
Browse files Browse the repository at this point in the history
🐛 Fix TickerUsersForm
  • Loading branch information
0x46616c6b authored Oct 24, 2023
2 parents fa3022c + 73b46a3 commit 1b4e20b
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 24 deletions.
2 changes: 1 addition & 1 deletion src/api/Ticker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export function useTickerApi(token: string) {
}).then(response => response.json())
}

const putTickerUsers = (ticker: Ticker, users: number[]): Promise<Response<TickerUsersResponseData>> => {
const putTickerUsers = (ticker: Ticker, users: User[]): Promise<Response<TickerUsersResponseData>> => {
return fetch(`${ApiUrl}/admin/tickers/${ticker.id}/users`, {
headers: headers,
method: 'put',
Expand Down
57 changes: 57 additions & 0 deletions src/components/ticker/TickerUsersForm.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Ticker } from '../../api/Ticker'
import { User } from '../../api/User'
import { fireEvent, render, screen } from '@testing-library/react'
import TickerUsersForm from './TickerUsersForm'

describe('TickerUsersForm', () => {
beforeEach(() => {
fetchMock.resetMocks()
})

function setup(defaultValue: Array<User>, ticker: Ticker, onSubmit: () => void) {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
})
return render(
<QueryClientProvider client={client}>
<TickerUsersForm defaultValue={defaultValue} onSubmit={onSubmit} ticker={ticker} />
</QueryClientProvider>
)
}

it('should renders correctly', async () => {
const ticker = {
id: 1,
title: 'Ticker 1',
} as Ticker
const user = {
id: 1,
email: '[email protected]',
} as User
fetchMock.mockResponseOnce(
JSON.stringify({
data: {
users: [user],
},
status: 'success',
})
)

const handleSubmit = jest.fn()
setup([user], ticker, handleSubmit)

fireEvent.mouseDown(screen.getByRole('button'))
const listbox = await screen.findByRole('listbox')
expect(listbox).toBeInTheDocument()
const option = await screen.findByRole('option')
expect(option).toBeInTheDocument()
fireEvent.click(option)
expect(fetchMock).toHaveBeenCalledTimes(1)
})
})
37 changes: 21 additions & 16 deletions src/components/ticker/TickerUsersForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import { Box, Chip, FormControl, InputLabel, MenuItem, OutlinedInput, Select, Se
interface Props {
ticker: Ticker
onSubmit: () => void
defaultValue: number[]
defaultValue: User[]
}

interface FormValues {
users: Array<number>
users: Array<User>
}

const TickerUsersForm: FC<Props> = ({ onSubmit, ticker, defaultValue }) => {
const [users, setUsers] = useState<Array<number>>(defaultValue)
const [users, setUsers] = useState<Array<User>>(defaultValue)
const [options, setOptions] = useState<Array<User>>([])
const { token } = useAuth()
const { getUsers } = useUserApi(token)
Expand All @@ -26,10 +26,12 @@ const TickerUsersForm: FC<Props> = ({ onSubmit, ticker, defaultValue }) => {
const { handleSubmit } = useForm<FormValues>()
const queryClient = useQueryClient()

const handleChange = (event: SelectChangeEvent<typeof users>) => {
if (typeof event.target.value !== 'string') {
setUsers(event.target.value)
}
const handleChange = (event: SelectChangeEvent<number[]>) => {
const userIds = event.target.value as Array<number>
const selectedUsers = options.filter(user => {
return userIds.includes(user.id)
})
setUsers(selectedUsers)
}

const updateTickerUsers: SubmitHandler<FormValues> = () => {
Expand Down Expand Up @@ -59,13 +61,13 @@ const TickerUsersForm: FC<Props> = ({ onSubmit, ticker, defaultValue }) => {

return (
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
{selectedUsers.map(user => (
{selectedUsers.map(selectedUser => (
<Chip
key={user.id}
label={user.email}
key={selectedUser.id}
label={selectedUser.email}
onDelete={() => {
const reduced = users.filter(id => {
return id !== user.id
const reduced = users.filter(user => {
return user.id !== selectedUser.id
})
setUsers(reduced)
}}
Expand All @@ -78,19 +80,22 @@ const TickerUsersForm: FC<Props> = ({ onSubmit, ticker, defaultValue }) => {
)
}

const getStyle = (value: number, users: number[]) => {
const getStyle = (value: User, users: User[]) => {
const userIds = users.map(user => user.id)
return {
fontWeight: users.indexOf(value) === -1 ? theme.typography.fontWeightRegular : theme.typography.fontWeightMedium,
fontWeight: userIds.indexOf(value.id) === -1 ? theme.typography.fontWeightRegular : theme.typography.fontWeightMedium,
}
}

const userIds = users.map(user => user.id)

return (
<form id="tickerUsersForm" onSubmit={handleSubmit(updateTickerUsers)}>
<FormControl sx={{ width: '100%', mt: 1 }}>
<InputLabel>Users</InputLabel>
<Select input={<OutlinedInput label="Users" />} label="Users" multiple name="users" onChange={handleChange} renderValue={renderValue} value={users}>
<Select input={<OutlinedInput label="Users" />} label="Users" multiple name="users" onChange={handleChange} renderValue={renderValue} value={userIds}>
{options.map(user => (
<MenuItem key={user.id} selected={users.includes(user.id)} style={getStyle(user.id, users)} value={user.id}>
<MenuItem key={user.id} selected={users.includes(user)} style={getStyle(user, users)} value={user.id}>
{user.email}
</MenuItem>
))}
Expand Down
8 changes: 1 addition & 7 deletions src/components/ticker/TickerUsersModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,7 @@ interface Props {
const TickerUsersModal: FC<Props> = ({ onClose, open, ticker, users }) => {
return (
<Modal fullWidth={true} onClose={onClose} open={open} submitForm="tickerUsersForm" title="Manage User Access">
<TickerUsersForm
defaultValue={users.map(user => {
return user.id
})}
onSubmit={onClose}
ticker={ticker}
/>
<TickerUsersForm defaultValue={users} onSubmit={onClose} ticker={ticker} />
</Modal>
)
}
Expand Down

0 comments on commit 1b4e20b

Please sign in to comment.