Skip to content

feat: Add filter on Users page #2653

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions site/src/api/api.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios from "axios"
import { getApiKey, getWorkspacesURL, login, logout } from "./api"
import { getApiKey, getURLWithSearchParams, login, logout } from "./api"
import * as TypesGen from "./typesGenerated"

describe("api.ts", () => {
@@ -114,16 +114,26 @@ describe("api.ts", () => {
})
})

describe("getWorkspacesURL", () => {
it.each<[TypesGen.WorkspaceFilter | undefined, string]>([
[undefined, "/api/v2/workspaces"],
describe("getURLWithSearchParams - workspaces", () => {
it.each<[string, TypesGen.WorkspaceFilter | undefined, string]>([
["/api/v2/workspaces", undefined, "/api/v2/workspaces"],

[{ q: "" }, "/api/v2/workspaces"],
[{ q: "owner:1" }, "/api/v2/workspaces?q=owner%3A1"],
["/api/v2/workspaces", { q: "" }, "/api/v2/workspaces"],
["/api/v2/workspaces", { q: "owner:1" }, "/api/v2/workspaces?q=owner%3A1"],

[{ q: "owner:me" }, "/api/v2/workspaces?q=owner%3Ame"],
])(`getWorkspacesURL(%p) returns %p`, (filter, expected) => {
expect(getWorkspacesURL(filter)).toBe(expected)
["/api/v2/workspaces", { q: "owner:me" }, "/api/v2/workspaces?q=owner%3Ame"],
])(`Workspaces - getURLWithSearchParams(%p, %p) returns %p`, (basePath, filter, expected) => {
expect(getURLWithSearchParams(basePath, filter)).toBe(expected)
})
})

describe("getURLWithSearchParams - users", () => {
it.each<[string, TypesGen.UsersRequest | undefined, string]>([
["/api/v2/users", undefined, "/api/v2/users"],
["/api/v2/users", { q: "status:active" }, "/api/v2/users?q=status%3Aactive"],
["/api/v2/users", { q: "" }, "/api/v2/users"],
])(`Users - getURLWithSearchParams(%p, %p) returns %p`, (basePath, filter, expected) => {
expect(getURLWithSearchParams(basePath, filter)).toBe(expected)
})
})
})
13 changes: 8 additions & 5 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
@@ -72,8 +72,9 @@ export const getApiKey = async (): Promise<TypesGen.GenerateAPIKeyResponse> => {
return response.data
}

export const getUsers = async (): Promise<TypesGen.User[]> => {
const response = await axios.get<TypesGen.User[]>("/api/v2/users?q=status:active,suspended")
export const getUsers = async (filter?: TypesGen.UsersRequest): Promise<TypesGen.User[]> => {
const url = getURLWithSearchParams("/api/v2/users", filter)
const response = await axios.get<TypesGen.User[]>(url)
return response.data
}

@@ -144,8 +145,10 @@ export const getWorkspace = async (
return response.data
}

export const getWorkspacesURL = (filter?: TypesGen.WorkspaceFilter): string => {
const basePath = "/api/v2/workspaces"
export const getURLWithSearchParams = (
basePath: string,
filter?: TypesGen.WorkspaceFilter | TypesGen.UsersRequest,
): string => {
const searchParams = new URLSearchParams()

if (filter?.q && filter.q !== "") {
@@ -160,7 +163,7 @@ export const getWorkspacesURL = (filter?: TypesGen.WorkspaceFilter): string => {
export const getWorkspaces = async (
filter?: TypesGen.WorkspaceFilter,
): Promise<TypesGen.Workspace[]> => {
const url = getWorkspacesURL(filter)
const url = getURLWithSearchParams("/api/v2/workspaces", filter)
const response = await axios.get<TypesGen.Workspace[]>(url)
return response.data
}
56 changes: 55 additions & 1 deletion site/src/api/errors.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isApiError, mapApiErrorToFieldErrors } from "./errors"
import { getValidationErrorMessage, isApiError, mapApiErrorToFieldErrors } from "./errors"

describe("isApiError", () => {
it("returns true when the object is an API Error", () => {
@@ -36,3 +36,57 @@ describe("mapApiErrorToFieldErrors", () => {
})
})
})

describe("getValidationErrorMessage", () => {
it("returns multiple validation messages", () => {
expect(
getValidationErrorMessage({
response: {
data: {
message: "Invalid user search query.",
validations: [
{
field: "status",
detail: `Query param "status" has invalid value: "inactive" is not a valid user status`,
},
{
field: "q",
detail: `Query element "role:a:e" can only contain 1 ':'`,
},
],
},
},
isAxiosError: true,
}),
).toEqual(
`Query param "status" has invalid value: "inactive" is not a valid user status\nQuery element "role:a:e" can only contain 1 ':'`,
)
})

it("non-API error returns empty validation message", () => {
expect(
getValidationErrorMessage({
response: {
data: {
error: "Invalid user search query.",
},
},
isAxiosError: true,
}),
).toEqual("")
})

it("no validations field returns empty validation message", () => {
expect(
getValidationErrorMessage({
response: {
data: {
message: "Invalid user search query.",
detail: `Query element "role:a:e" can only contain 1 ':'`,
},
},
isAxiosError: true,
}),
).toEqual("")
})
})
12 changes: 12 additions & 0 deletions site/src/api/errors.ts
Original file line number Diff line number Diff line change
@@ -71,3 +71,15 @@ export const getErrorMessage = (
: error instanceof Error
? error.message
: defaultMessage

/**
*
* @param error
* @returns a combined validation error message if the error is an ApiError
* and contains validation messages for different form fields.
*/
export const getValidationErrorMessage = (error: Error | ApiError | unknown): string => {
const validationErrors =
isApiError(error) && error.response.data.validations ? error.response.data.validations : []
return validationErrors.map((error) => error.detail).join("\n")
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ComponentMeta, Story } from "@storybook/react"
import { workspaceFilterQuery } from "../../util/workspace"
import { userFilterQuery, workspaceFilterQuery } from "../../util/filters"
import { SearchBarWithFilter, SearchBarWithFilterProps } from "./SearchBarWithFilter"

export default {
@@ -23,3 +23,26 @@ WithPresetFilters.args = {
{ query: "random query", name: "Random query" },
],
}

export const WithError = Template.bind({})
WithError.args = {
filter: "status:inactive",
presetFilters: [
{ query: userFilterQuery.active, name: "Active users" },
{ query: "random query", name: "Random query" },
],
error: {
response: {
data: {
message: "Invalid user search query.",
validations: [
{
field: "status",
detail: `Query param "status" has invalid value: "inactive" is not a valid user status`,
},
],
},
},
isAxiosError: true,
},
}
121 changes: 67 additions & 54 deletions site/src/components/SearchBarWithFilter/SearchBarWithFilter.tsx
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@ import TextField from "@material-ui/core/TextField"
import SearchIcon from "@material-ui/icons/Search"
import { FormikErrors, useFormik } from "formik"
import { useState } from "react"
import { getValidationErrorMessage } from "../../api/errors"
import { getFormHelpers, onChangeTrimmed } from "../../util/formUtils"
import { CloseDropdown, OpenDropdown } from "../DropdownArrows/DropdownArrows"
import { Stack } from "../Stack/Stack"
@@ -20,6 +21,7 @@ export interface SearchBarWithFilterProps {
filter?: string
onFilter: (query: string) => void
presetFilters?: PresetFilter[]
error?: unknown
}

export interface PresetFilter {
@@ -37,6 +39,7 @@ export const SearchBarWithFilter: React.FC<SearchBarWithFilterProps> = ({
filter,
onFilter,
presetFilters,
error,
}) => {
const styles = useStyles()

@@ -68,69 +71,76 @@ export const SearchBarWithFilter: React.FC<SearchBarWithFilterProps> = ({
handleClose()
}

const errorMessage = getValidationErrorMessage(error)

return (
<Stack direction="row" spacing={0} className={styles.filterContainer}>
{presetFilters && presetFilters.length > 0 && (
<Button
aria-controls="filter-menu"
aria-haspopup="true"
onClick={handleClick}
className={styles.buttonRoot}
>
{Language.filterName} {anchorEl ? <CloseDropdown /> : <OpenDropdown />}
</Button>
)}

<form onSubmit={form.handleSubmit} className={styles.filterForm}>
<TextField
{...getFieldHelpers("query")}
className={styles.textFieldRoot}
onChange={onChangeTrimmed(form)}
fullWidth
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon fontSize="small" />
</InputAdornment>
),
}}
/>
</form>

{presetFilters && presetFilters.length > 0 && (
<Menu
id="filter-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
TransitionComponent={Fade}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
transformOrigin={{
vertical: "top",
horizontal: "left",
}}
>
{presetFilters.map((presetFilter) => (
<MenuItem key={presetFilter.name} onClick={setPresetFilter(presetFilter.query)}>
{presetFilter.name}
</MenuItem>
))}
</Menu>
)}
<Stack spacing={1} className={styles.root}>
<Stack direction="row" spacing={0} className={styles.filterContainer}>
{presetFilters && presetFilters.length > 0 && (
<Button
aria-controls="filter-menu"
aria-haspopup="true"
onClick={handleClick}
className={styles.buttonRoot}
>
{Language.filterName} {anchorEl ? <CloseDropdown /> : <OpenDropdown />}
</Button>
)}

<form onSubmit={form.handleSubmit} className={styles.filterForm}>
<TextField
{...getFieldHelpers("query")}
className={styles.textFieldRoot}
onChange={onChangeTrimmed(form)}
fullWidth
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon fontSize="small" />
</InputAdornment>
),
}}
/>
</form>

{presetFilters && presetFilters.length > 0 && (
<Menu
id="filter-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
TransitionComponent={Fade}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
transformOrigin={{
vertical: "top",
horizontal: "left",
}}
>
{presetFilters.map((presetFilter) => (
<MenuItem key={presetFilter.name} onClick={setPresetFilter(presetFilter.query)}>
{presetFilter.name}
</MenuItem>
))}
</Menu>
)}
</Stack>
{errorMessage && <Stack className={styles.errorRoot}>{errorMessage}</Stack>}
</Stack>
)
}

const useStyles = makeStyles((theme) => ({
root: {
marginBottom: theme.spacing(2),
},
filterContainer: {
border: `1px solid ${theme.palette.divider}`,
borderRadius: theme.shape.borderRadius,
marginBottom: theme.spacing(2),
},
filterForm: {
width: "100%",
@@ -146,4 +156,7 @@ const useStyles = makeStyles((theme) => ({
border: "none",
},
},
errorRoot: {
color: theme.palette.error.dark,
},
}))
10 changes: 10 additions & 0 deletions site/src/components/UsersTable/UsersTable.stories.tsx
Original file line number Diff line number Diff line change
@@ -28,3 +28,13 @@ Empty.args = {
users: [],
roles: MockSiteRoles,
}

export const Loading = Template.bind({})
Loading.args = {
users: [],
roles: MockSiteRoles,
isLoading: true,
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this story since it tests a particular behavior of the component, but I am not sure if it is a good UI snapshot since the loader is spinning and the snapshot may change across different builds. 🤔

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good thought. I haven't read through this in detail, but could we pause the animation for the loader? Or introduce a slight delay? https://www.chromatic.com/docs/animations

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing to this, I used

Loading.parameters = {
  chromatic: { pauseAnimationAtEnd: true },
}

and it seems to be constant for at least 3 builds.

Loading.parameters = {
chromatic: { pauseAnimationAtEnd: true },
}
Loading