Skip to content

chore(site): refactor filter component to be more extendable #13688

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 16 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
9 changes: 6 additions & 3 deletions site/src/components/Avatar/Avatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,23 @@
xs: {
width: 16,
height: 16,
fontSize: 8,
// Should never be overrided

Check warning on line 21 in site/src/components/Avatar/Avatar.tsx

View workflow job for this annotation

GitHub Actions / lint

"overrided" should be "overrode" or "overridden".
fontSize: "8px !important",
fontWeight: 700,
},
sm: {
width: 24,
height: 24,
fontSize: 12,
// Should never be overrided

Check warning on line 28 in site/src/components/Avatar/Avatar.tsx

View workflow job for this annotation

GitHub Actions / lint

"overrided" should be "overrode" or "overridden".
fontSize: "12px !important",
fontWeight: 600,
},
md: {},
xl: {
width: 48,
height: 48,
fontSize: 24,
// Should never be overrided

Check warning on line 36 in site/src/components/Avatar/Avatar.tsx

View workflow job for this annotation

GitHub Actions / lint

"overrided" should be "overrode" or "overridden".
fontSize: "24px !important",
},
} satisfies Record<string, Interpolation<Theme>>;

Expand Down
39 changes: 0 additions & 39 deletions site/src/components/Filter/OptionItem.stories.tsx

This file was deleted.

146 changes: 146 additions & 0 deletions site/src/components/Filter/SelectFilter.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { action } from "@storybook/addon-actions";
import type { Meta, StoryObj } from "@storybook/react";
import { userEvent, within, expect } from "@storybook/test";
import { useState } from "react";
import { UserAvatar } from "components/UserAvatar/UserAvatar";
import { withDesktopViewport } from "testHelpers/storybook";
import {
SelectFilter,
SelectFilterSearch,
type SelectFilterOption,
} from "./SelectFilter";

const options: SelectFilterOption[] = Array.from({ length: 50 }, (_, i) => ({
startIcon: <UserAvatar username={`username ${i}`} size="xs" />,
label: `Option ${i + 1}`,
value: `option-${i + 1}`,
}));

const meta: Meta<typeof SelectFilter> = {
title: "components/SelectFilter",
component: SelectFilter,
args: {
options,
placeholder: "All options",
},
decorators: [withDesktopViewport],
render: function SelectFilterWithState(args) {
const [selectedOption, setSelectedOption] = useState<
SelectFilterOption | undefined
>(args.selectedOption);
return (
<SelectFilter
{...args}
selectedOption={selectedOption}
onSelect={setSelectedOption}
/>
);
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const button = canvas.getByRole("button");
await userEvent.click(button);
},
};

export default meta;
type Story = StoryObj<typeof SelectFilter>;

export const Closed: Story = {
play: undefined,
};

export const Open: Story = {};

export const Selected: Story = {
args: {
selectedOption: options[25],
},
};

export const WithSearch: Story = {
args: {
selectedOption: options[25],
search: (
<SelectFilterSearch
value=""
onChange={action("onSearch")}
placeholder="Search options..."
/>
),
},
};

export const LoadingOptions: Story = {
args: {
options: undefined,
},
};

export const NoOptionsFound: Story = {
args: {
options: [],
},
};

export const SelectingOption: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const button = canvas.getByRole("button");
await userEvent.click(button);
const option = canvas.getByText("Option 25");
await userEvent.click(option);
await expect(button).toHaveTextContent("Option 25");
},
};

export const UnselectingOption: Story = {
args: {
selectedOption: options[25],
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const button = canvas.getByRole("button");
await userEvent.click(button);
const menu = canvasElement.querySelector<HTMLElement>("[role=menu]")!;
const option = within(menu).getByText("Option 26");
await userEvent.click(option);
await expect(button).toHaveTextContent("All options");
},
};

export const SearchingOption: Story = {
render: function SelectFilterWithSearch(args) {
const [selectedOption, setSelectedOption] = useState<
SelectFilterOption | undefined
>(args.selectedOption);
const [search, setSearch] = useState("");
const visibleOptions = options.filter((option) =>
option.value.includes(search),
);

return (
<SelectFilter
{...args}
selectedOption={selectedOption}
onSelect={setSelectedOption}
options={visibleOptions}
search={
<SelectFilterSearch
value={search}
onChange={setSearch}
placeholder="Search options..."
inputProps={{ "aria-label": "Search options" }}
/>
}
/>
);
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const button = canvas.getByRole("button");
await userEvent.click(button);
const search = canvas.getByLabelText("Search options");
await userEvent.type(search, "option-2");
},
};
117 changes: 117 additions & 0 deletions site/src/components/Filter/SelectFilter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import visuallyHidden from "@mui/utils/visuallyHidden";
import { useState, type FC, type ReactNode } from "react";
import { Loader } from "components/Loader/Loader";
import {
SelectMenu,
SelectMenuTrigger,
SelectMenuButton,
SelectMenuContent,
SelectMenuSearch,
SelectMenuList,
SelectMenuItem,
SelectMenuIcon,
} from "components/SelectMenu/SelectMenu";

const BASE_WIDTH = 200;
const POPOVER_WIDTH = 320;

export type SelectFilterOption = {
startIcon?: ReactNode;
label: string;
value: string;
};

export type SelectFilterProps = {
options: SelectFilterOption[] | undefined;
selectedOption?: SelectFilterOption;
// Used to add a accessibility label to the select
label: string;
// Used when there is no option selected
placeholder: string;
// Used to customize the empty state message
emptyText?: string;
onSelect: (option: SelectFilterOption | undefined) => void;
// SelectFilterSearch element
search?: ReactNode;
Copy link
Member

Choose a reason for hiding this comment

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

Could this prop be renamed to make it more clear that it's meant to be used with SelectFilterSearch? It doesn't feel obvious right now, especially with the comment being a private comment

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

When using SelectFilterSearch I feel I have to pass the component and not a React Node 🤔 Maybe selectFilterSearch?

};

export const SelectFilter: FC<SelectFilterProps> = ({
label,
options,
selectedOption,
onSelect,
placeholder,
emptyText,
search,
}) => {
const [open, setOpen] = useState(false);

return (
<SelectMenu open={open} onOpenChange={setOpen}>
<SelectMenuTrigger>
<SelectMenuButton
startIcon={selectedOption?.startIcon}
css={{ width: BASE_WIDTH }}
>
{selectedOption?.label ?? placeholder}
<span css={{ ...visuallyHidden }}>{label}</span>
Copy link
Member

@Parkreiner Parkreiner Jun 27, 2024

Choose a reason for hiding this comment

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

Can you explain what you were going for with this? From how I'm reading it, if the selectedOption has a label, then both it and the visually-hidden label in the span will be exposed through the button as an accessible name value. So in that case, a screen-reader user might get double/redundant labels

If it's okay for the main visual label text to be hidden from screen readers, this could be rewritten as

<span aria-hidden>{selectedOption?.label ?? placeholder}</span>

This hides it from screen readers, but keeps the content on the page. Normally this is a really bad idea, but as long as we have the backup label guaranteed to be defined, I think it's okay

Edit: aria-hidden, not hidden

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I didn't notice it 🤦 My idea is, since this is a select component, I think having a label like "Select a user" is better than having the selected value as the label "User 2" for example.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I used aria-label in the button directly.

</SelectMenuButton>
</SelectMenuTrigger>
<SelectMenuContent
horizontal="right"
css={{
"& .MuiPaper-root": {
// When including search, we aim for the width to be as wide as
// possible.
width: search ? "100%" : undefined,
maxWidth: POPOVER_WIDTH,
minWidth: BASE_WIDTH,
},
}}
>
{search}
{options ? (
options.length > 0 ? (
<SelectMenuList>
{options.map((o) => {
const isSelected = o.value === selectedOption?.value;
return (
<SelectMenuItem
key={o.value}
selected={isSelected}
onClick={() => {
setOpen(false);
onSelect(isSelected ? undefined : o);
}}
>
{o.startIcon && (
<SelectMenuIcon>{o.startIcon}</SelectMenuIcon>
)}
{o.label}
</SelectMenuItem>
);
})}
</SelectMenuList>
) : (
<div
css={(theme) => ({
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 32,
color: theme.palette.text.secondary,
lineHeight: 1,
})}
>
{emptyText ?? "No options found"}
</div>
)
) : (
<Loader size={16} />
)}
</SelectMenuContent>
</SelectMenu>
);
};

export const SelectFilterSearch = SelectMenuSearch;
Loading
Loading