Skip to content
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

Update label in SingleSelect and MultiSelect #2354

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/thirty-shirts-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@khanacademy/wonder-blocks-dropdown": patch
---

Allow use of JSX Element as label in SingleSelect and MultiSelect
55 changes: 54 additions & 1 deletion __docs__/wonder-blocks-dropdown/multi-select.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ import ComponentInfo from "../../.storybook/components/component-info";
import packageConfig from "../../packages/wonder-blocks-dropdown/package.json";
import multiSelectArgtypes from "./multi-select.argtypes";
import {defaultLabels} from "../../packages/wonder-blocks-dropdown/src/util/constants";
import {allCountries, allProfilesWithPictures} from "./option-item-examples";
import {
allCountries,
allProfilesWithPictures,
locales,
chatIcon,
} from "./option-item-examples";
import {OpenerProps} from "../../packages/wonder-blocks-dropdown/src/util/types";
import Strut from "../../packages/wonder-blocks-layout/src/components/strut";

Expand Down Expand Up @@ -650,3 +655,51 @@ export const CustomOptionItems: StoryComponentType = {
),
],
};

/**
* This example illustrates how a JSX Element can appear as the label when only
* one option is selected and `labelAsText` is undefined.
* **Note** this is only supported for SingleSelect and MultiSelect, not Combobox.
*/
export const CustomOptionItemsWithNodeLabel: StoryComponentType = {
render: function Render() {
const [opened, setOpened] = React.useState(true);
const [selectedValues, setSelectedValues] = React.useState<
Array<string>
>([]);

const handleChange = (selectedValues: Array<string>) => {
setSelectedValues(selectedValues);
};

const handleToggle = (opened: boolean) => {
setOpened(opened);
};

return (
<MultiSelect
Copy link
Member

Choose a reason for hiding this comment

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

I played around with the changes and found if we set isFilterable in this story, the filtering functionality doesn't work as expected! However, if we add a labelAsText prop to the OptionItem components with the content (ie. the locale in this example), filtering works as expected.

I'm wondering, should we use labelAsText prop when we use a node label? And if so, would that solve for the original issue where the select opener is labeled with an empty string? Let me know though if there's some context I'm missing!

cc: @jandrade , I think he was running into similar things when he worked on the combobox!

Copy link
Author

@daniellewhyte daniellewhyte Nov 12, 2024

Choose a reason for hiding this comment

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

That's a good callout, and the proposed solution does solve the original issue.

Copy link
Author

Choose a reason for hiding this comment

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

@beaesguerra Actually I don't think this works. If you add labelAsText to the option item, you see plain text as the label for the menu.
Screenshot 2024-11-13 at 9 07 33 AM

That said, my specific use case does not use filtering.

Copy link
Member

Choose a reason for hiding this comment

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

Ah I see, we want to include the icon in the field! Thanks for trying that out!

For other use cases that would need filtering, the labelAsText prop would fix the filtering issue (with the drawback that the menu opener would show the labelAsText instead of the custom option). With that said, the changes look good to me, though I would also like to get @jandrade's thoughts since he has more context around this!

Copy link
Member

Choose a reason for hiding this comment

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

I understand that the specific use case in this PR doesn't need filtering, but I worry that adding this feature while introducing a known issue might be counterproductive if there's another call site that needs both things (custom options + filtering).

I'd really recommend applying the fix/change in this PR before landing this change.

I was thinking that it might be solved by changing the filter logic to use .toString() after the getSelectOpenerLabel invocation. I'm not fully sure if this is the right solution but it might be worth trying it out for both MultiSelect and SingleSelect.

onChange={handleChange}
selectedValues={selectedValues}
onToggle={handleToggle}
opened={opened}
>
{locales.map((locale, index) => (
<OptionItem
key={index}
value={String(index)}
label={
<span>
{chatIcon} {locale}
</span>
}
/>
))}
</MultiSelect>
);
},
decorators: [
(Story): React.ReactElement<React.ComponentProps<typeof View>> => (
<View style={styles.wrapper}>{Story()}</View>
),
],
};
25 changes: 25 additions & 0 deletions __docs__/wonder-blocks-dropdown/option-item-examples.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import * as React from "react";
import userCircleIcon from "@phosphor-icons/core/duotone/user-circle-duotone.svg";
import chatBubbleIcon from "@phosphor-icons/core/regular/chats.svg";
import bitcoinIcon from "@phosphor-icons/core/regular/currency-btc.svg";
import euroIcon from "@phosphor-icons/core/regular/currency-eur.svg";
import dollarIcon from "@phosphor-icons/core/regular/currency-dollar.svg";
import yenIcon from "@phosphor-icons/core/regular/currency-jpy.svg";
import {PhosphorIcon} from "@khanacademy/wonder-blocks-icon";

export const allCountries = [
Expand Down Expand Up @@ -301,3 +306,23 @@ export const allProfilesWithPictures = [
picture: icon,
},
];

export const currencies = [
{name: "Bitcoin", icon: bitcoinIcon},
{name: "Dollars", icon: dollarIcon},
{name: "Yen", icon: yenIcon},
{name: "Euros", icon: euroIcon},
];

export const locales = [
"অসমীয়া",
"Azərbaycanca",
"čeština",
"dansk",
"Ελληνικά",
"ગુજરાતી",
"magyar",
"Bahasa Indonesia",
];

export const chatIcon = <PhosphorIcon icon={chatBubbleIcon} size={"small"} />;
55 changes: 54 additions & 1 deletion __docs__/wonder-blocks-dropdown/single-select.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ import ComponentInfo from "../../.storybook/components/component-info";
import singleSelectArgtypes from "./single-select.argtypes";
import {IconMappings} from "../wonder-blocks-icon/phosphor-icon.argtypes";
import {defaultLabels} from "../../packages/wonder-blocks-dropdown/src/util/constants";
import {allCountries, allProfilesWithPictures} from "./option-item-examples";
import {
allCountries,
allProfilesWithPictures,
currencies,
} from "./option-item-examples";
import {OpenerProps} from "../../packages/wonder-blocks-dropdown/src/util/types";

type StoryComponentType = StoryObj<typeof SingleSelect>;
Expand Down Expand Up @@ -884,6 +888,55 @@ export const CustomOptionItems: StoryComponentType = {
},
};

/**
* This example illustrates how a JSX Element can appear as the label if
* `labelAsText` is undefined.
* **Note** this is only supported for SingleSelect and MultiSelect, not Combobox.
*/
export const CustomOptionItemWithNodeLabel: StoryComponentType = {
render: function Render() {
const [opened, setOpened] = React.useState(true);
const [selectedValue, setSelectedValue] = React.useState("");

const handleChange = (selectedValue: string) => {
setSelectedValue(selectedValue);
};

const handleToggle = (opened: boolean) => {
setOpened(opened);
};

return (
<View style={styles.wrapper}>
<SingleSelect
placeholder="Select your currency"
onChange={handleChange}
selectedValue={selectedValue}
onToggle={handleToggle}
opened={opened}
>
{currencies.map((currency, index) => (
<OptionItem
key={index}
value={String(index)}
horizontalRule="full-width"
label={
<span>
Copy link
Member

Choose a reason for hiding this comment

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

This tested well in VoiceOver! I couldn't get my Windows VM to load the local Storybook environment for NVDA but I'm pretty sure it will be fine.

<PhosphorIcon
icon={currency.icon}
size={"small"}
/>
{currency.name}
</span>
}
/>
))}
</SingleSelect>
</View>
);
},
};

/**
* This example illustrates how you can use the `OptionItem` component to
* display a virtualized list with custom option items. Note that in this
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ describe("MultiSelect", () => {

// Assert
expect(await screen.findByRole("button")).toHaveTextContent(
"1 student",
Copy link
Member

Choose a reason for hiding this comment

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

Wow, that's a pretty confusing test result looking at this older code. Where did "student" even come from? Your change seems way more intuitive.

Copy link
Member

Choose a reason for hiding this comment

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

I was wondering the same thing! Looks like "1 student" was coming from the defaultLabels that are passed in!

const defaultLabels: Labels = {
...builtinLabels,
selectAllLabel: (numOptions: any) => `Select all (${numOptions})`,
noneSelected: "Choose",
someSelected: (numSelectedValues: any) =>
numSelectedValues > 1 ? `${numSelectedValues} students` : "1 student",
allSelected: "All students",
};

Copy link
Member

Choose a reason for hiding this comment

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

Bea's assumption is correct. This is part of what Danielle fixed with this PR. Previously, we used the label associated for that, but from now on we'll be using whatever it is passed in as a custom option item label. This means that if we don't use a custom label, then someSelected(1) should be used in this case. @daniellewhyte I'm not sure if there's an existing unit test for this case, but if not, it would be good adding one here to prevent possible regressions in the future.

"custom item 1",
);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import type {
OptionItemComponent,
OptionItemComponentArray,
} from "../util/types";
import {getLabel} from "../util/helpers";
import {getLabel, getSelectOpenerLabel} from "../util/helpers";

export type Labels = {
/**
Expand Down Expand Up @@ -315,7 +315,7 @@ export default class MultiSelect extends React.Component<Props, State> {
onChange([]);
};

getMenuText(children: OptionItemComponentArray): string {
getMenuText(children: OptionItemComponentArray): string | JSX.Element {
const {implicitAllEnabled, selectedValues} = this.props;
const {noneSelected, someSelected, allSelected} = this.state.labels;
const numSelectedAll = children.filter(
Expand Down Expand Up @@ -345,7 +345,7 @@ export default class MultiSelect extends React.Component<Props, State> {
// we fallback to, the default label for the case where only
// one item is selected.
} else {
return someSelected(1);
return getSelectOpenerLabel(selectedItem?.props);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type {
OpenerProps,
OptionItemComponentArray,
} from "../util/types";
import {getLabel} from "../util/helpers";
import {getLabel, getSelectOpenerLabel} from "../util/helpers";

export type SingleSelectLabels = {
/**
Expand Down Expand Up @@ -418,7 +418,7 @@ export default class SingleSelect extends React.Component<Props, State> {
// If nothing is selected, or if the selectedValue doesn't match any
// item in the menu, use the placeholder.
const menuText = selectedItem
? getLabel(selectedItem.props)
? getSelectOpenerLabel(selectedItem.props)
: placeholder;

const dropdownOpener = (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import * as React from "react";
import {PropsFor} from "@khanacademy/wonder-blocks-core";
import OptionItem from "../../components/option-item";
import {debounce, getLabel, getStringForKey} from "../helpers";
import {
debounce,
getLabel,
getSelectOpenerLabel,
getStringForKey,
} from "../helpers";

describe("getStringForKey", () => {
it("should get a valid string", () => {
Expand Down Expand Up @@ -119,3 +124,49 @@ describe("getLabel", () => {
expect(label).toBe("");
});
});

describe("getSelectOpenerLabel", () => {
it("should return the label if the label is a Node and labelAsText is not defined", () => {
// Arrange
const props: PropsFor<typeof OptionItem> = {
label: <div>a custom node</div>,
labelAsText: undefined,
value: "foo",
};

// Act
const label = getSelectOpenerLabel(props);

// Assert
expect(label).toStrictEqual(<div>a custom node</div>);
});

it("should return a string if the label is a string", () => {
// Arrange
const props: PropsFor<typeof OptionItem> = {
label: "option 1",
value: "foo",
};

// Act
const label = getSelectOpenerLabel(props);

// Assert
expect(label).toBe("option 1");
});

it("should return a string if the label is a Node and labelAsText is defined", () => {
// Arrange
const props: PropsFor<typeof OptionItem> = {
label: <div>a custom node</div>,
labelAsText: "plain text",
value: "foo",
};

// Act
const label = getSelectOpenerLabel(props);

// Assert
expect(label).toBe("plain text");
});
});
14 changes: 14 additions & 0 deletions packages/wonder-blocks-dropdown/src/util/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,17 @@ export function getLabel(props: OptionItemProps): string {

return "";
}

/**
* Returns the label for the SelectOpener in the SingleSelect and MultiSelect.
* If the label is a Node, and `labelAsText` is undefined, returns the label.
*/
export function getSelectOpenerLabel(
props: OptionItemProps,
): string | JSX.Element {
const labelText = getLabel(props);
if (labelText === "") {
return props.label;
}
return labelText;
}