Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
AbhineetJain merged 6 commits intomainfromabhineetjain/users-filter-ui
Jun 28, 2022
Merged
Show file tree
Hide file tree
Changes fromall 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 deletionssite/src/api/api.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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", () => {
Expand DownExpand Up@@ -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 deletionssite/src/api/api.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -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
}

Expand DownExpand Up@@ -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 !== "") {
Expand All@@ -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
}
Expand Down
56 changes: 55 additions & 1 deletionsite/src/api/errors.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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", () => {
Expand DownExpand Up@@ -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 deletionssite/src/api/errors.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -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")
}
View file
Open in desktop
Original file line numberDiff line numberDiff 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 {
Expand All@@ -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 deletionssite/src/components/SearchBarWithFilter/SearchBarWithFilter.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -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"
Expand All@@ -20,6 +21,7 @@ export interface SearchBarWithFilterProps {
filter?: string
onFilter: (query: string) => void
presetFilters?: PresetFilter[]
error?: unknown
}

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

Expand DownExpand Up@@ -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%",
Expand All@@ -146,4 +156,7 @@ const useStyles = makeStyles((theme) => ({
border: "none",
},
},
errorRoot: {
color: theme.palette.error.dark,
},
}))
10 changes: 10 additions & 0 deletionssite/src/components/UsersTable/UsersTable.stories.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,3 +28,13 @@ Empty.args = {
users: [],
roles: MockSiteRoles,
}

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

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
ContributorAuthor

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

[8]ページ先頭

©2009-2025 Movatter.jp