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

feat: Depart away from react-windowed-select #1498

Merged
merged 5 commits into from
Jan 2, 2025
Merged
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
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"printWidth": 120
"printWidth": 120,
"trailingComma": "es5"
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
"jscodeshift": "^0.11.0",
"mockdate": "^3.0.2",
"plop": "^2.4.0",
"prettier": "^3.4.2",
"react": "17.0.2",
"react-color": "^2.18.1",
"react-dom": "17.0.2",
Expand Down Expand Up @@ -151,6 +152,7 @@
"@styled-system/prop-types": "^5.1.4",
"@styled-system/theme-get": "^5.1.2",
"@types/react-router-dom": "5.3.0",
"@types/react-window": "^1.8.8",
"@types/styled-system": "5.1.22",
"body-scroll-lock": "^3.1.5",
"core-js": "3",
Expand All @@ -169,7 +171,7 @@
"react-popper-2": "npm:[email protected]",
"react-resize-detector": "^9.1.0",
"react-select": "^5.8.0",
"react-windowed-select": "^5.2.0",
"react-window": "^1.8.11",
"smoothscroll-polyfill": "^0.4.4",
"styled-system": "^5.1.4",
"stylis": "^4.0.0"
Expand Down
2 changes: 0 additions & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const PEER_DEPENDENCIES = {

const GLOBALS = {
...PEER_DEPENDENCIES,
"react-windowed-select": "components",
"@babel/runtime/helpers/typeof": "typeof",
"@babel/runtime/helpers/defineProperty": "defineProperty",
"@babel/runtime/helpers/classCallCheck": "classCallCheck",
Expand Down Expand Up @@ -57,7 +56,6 @@ const CORE_PLUGINS = [
in those cases, it needs to be added as ["package-name"]: "exportName" here */
namedExports: {
debounce: ["debounce"],
"react-windowed-select": ["components"],
},
}),
/* babel: transiles the bundle according to babel.config */
Expand Down
2 changes: 1 addition & 1 deletion src/Alert/Alert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const NotificationTypes = {
warning: "warning",
} as const;

export type NotificationType = typeof NotificationTypes[keyof typeof NotificationTypes];
export type NotificationType = (typeof NotificationTypes)[keyof typeof NotificationTypes];

export type AlertProps = FlexProps & {
isCloseable?: boolean;
Expand Down
3 changes: 2 additions & 1 deletion src/AsyncSelect/AsyncSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ const AsyncSelect = forwardRef(
defaultOptions,
loadOptions,
isClearable,
variant,
iconLeft,
...props
}: AsyncSelectProps<Option, IsMulti, Group>,
Expand All @@ -91,6 +90,7 @@ const AsyncSelect = forwardRef(
| null
) => {
const { t } = useTranslation();
const variant = useComponentVariant();
const theme = useTheme();
const spaceProps = getSubset(props, propTypes.space);
const error = !!(errorMessage || errorList);
Expand All @@ -112,6 +112,7 @@ const AsyncSelect = forwardRef(
hasIcon: Boolean(iconLeft),
theme,
error,
variant,
maxHeight,
windowed: false,
hasDefaultOptions: Boolean(defaultOptions),
Expand Down
14 changes: 3 additions & 11 deletions src/AsyncSelect/AsyncSelectComponents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ import {
MultiValueProps,
} from "react-select";
import { components, GroupBase } from "react-select";
import type { OptionProps } from "react-windowed-select";
import { useComponentVariant } from "../NDSProvider/ComponentVariantContext";
import { OptionProps } from "react-select";
import { IconName } from "@nulogy/icons";
import type { ComponentVariant } from "../NDSProvider/ComponentVariantContext";
import { StyledOption } from "../Select/SelectOption";
import { IconName } from "@nulogy/icons";
import { InputIcon } from "../Icon/Icon";

export const SelectControl = <Option, IsMulti extends boolean, Group extends GroupBase<Option>>({
Expand Down Expand Up @@ -106,15 +105,8 @@ export const SelectMenu = <Option, IsMulti extends boolean, Group extends GroupB
export function SelectOption<Option, IsMulti extends boolean, Group extends GroupBase<Option>>(
props: OptionProps<Option, IsMulti, Group> & { variant?: ComponentVariant }
) {
const variant = useComponentVariant(props.variant);

return (
<StyledOption
isSelected={props.isSelected}
isFocused={props.isFocused}
variant={variant}
data-testid="select-option"
>
<StyledOption isSelected={props.isSelected} isFocused={props.isFocused} data-testid="select-option">
<components.Option {...props}>{props.children}</components.Option>
</StyledOption>
);
Expand Down
188 changes: 188 additions & 0 deletions src/Select/MenuList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
Copied as is from: https://github.com/jacobworrel/react-windowed-select/blob/master/src/MenuList.tsx
MIT License
Copyright (c) 2019 Jacob Worrel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import * as React from "react";
import { ListChildComponentProps, VariableSizeList as List } from "react-window";
import { OptionProps, GroupBase } from "react-select";
import { createGetHeight, flattenGroupedChildren, getCurrentIndex } from "./lib";

interface Style extends React.CSSProperties {
top: number;
}

interface ListChildProps extends ListChildComponentProps {
style: Style;
}

interface OptionTypeBase {
[key: string]: any;
}

function MenuList(props) {
const children = React.useMemo(() => {
const children = React.Children.toArray(props.children);

const head = children[0] || {};

if (React.isValidElement<OptionProps<OptionTypeBase, boolean, GroupBase<OptionTypeBase>>>(head)) {
const { props: { data: { options = [] } = {} } = {} } = head;
const groupedChildrenLength = options.length;
const isGrouped = groupedChildrenLength > 0;
const flattenedChildren = isGrouped && flattenGroupedChildren(children);

return isGrouped ? flattenedChildren : children;
} else {
return [];
}
}, [props.children]);

const { getStyles } = props;
const groupHeadingStyles = getStyles("groupHeading", props);
const loadingMsgStyles = getStyles("loadingMessage", props);
const noOptionsMsgStyles = getStyles("noOptionsMessage", props);
const optionStyles = getStyles("option", props);
const getHeight = createGetHeight({
groupHeadingStyles,
noOptionsMsgStyles,
optionStyles,
loadingMsgStyles,
});

const heights = React.useMemo(() => children.map(getHeight), [children]);
const currentIndex = React.useMemo(() => getCurrentIndex(children), [children]);

const itemCount = children.length;

const [measuredHeights, setMeasuredHeights] = React.useState({});

// calc menu height
const { maxHeight, paddingBottom = 0, paddingTop = 0, ...menuListStyle } = getStyles("menuList", props);
const totalHeight = React.useMemo(() => {
return heights.reduce((sum, height, idx) => {
if (measuredHeights[idx]) {
return sum + measuredHeights[idx];
} else {
return sum + height;
}
}, 0);
}, [heights, measuredHeights]);
const totalMenuHeight = totalHeight + paddingBottom + paddingTop;
const menuHeight = Math.min(maxHeight, totalMenuHeight);
const estimatedItemSize = Math.floor(totalHeight / itemCount);

const { innerRef, selectProps } = props;

const { classNamePrefix, isMulti } = selectProps || {};
const list = React.useRef<List>(null);

React.useEffect(() => {
setMeasuredHeights({});
}, [props.children]);

// method to pass to inner item to set this items outer height
const setMeasuredHeight = ({ index, measuredHeight }) => {
if (measuredHeights[index] !== undefined && measuredHeights[index] === measuredHeight) {
return;
}

setMeasuredHeights((measuredHeights) => ({
...measuredHeights,
[index]: measuredHeight,
}));

// this forces the list to rerender items after the item positions resizing
if (list.current) {
list.current.resetAfterIndex(index);
}
};

React.useEffect(() => {
/**
* enables scrolling on key down arrow
*/
if (currentIndex >= 0 && list.current !== null) {
list.current.scrollToItem(currentIndex);
}
}, [currentIndex, children, list]);

return (
<List
className={
classNamePrefix
? `${classNamePrefix}__menu-list${isMulti ? ` ${classNamePrefix}__menu-list--is-multi` : ""}`
: ""
}
style={menuListStyle}
ref={list}
outerRef={innerRef}
estimatedItemSize={estimatedItemSize}
innerElementType={React.forwardRef(({ style, ...rest }, ref) => (
<div
ref={ref}
style={{
...style,
height: `${parseFloat(style.height) + paddingBottom + paddingTop}px`,
}}
{...rest}
/>
))}
height={menuHeight}
width="100%"
itemCount={itemCount}
itemData={children}
itemSize={(index) => measuredHeights[index] || heights[index]}
>
{/*@ts-ignore*/}
{({ data, index, style }: ListChildProps) => {
return (
<div
style={{
...style,
top: `${parseFloat(style.top.toString()) + paddingTop}px`,
}}
>
<MenuItem data={data[index]} index={index} setMeasuredHeight={setMeasuredHeight} />
</div>
);
}}
</List>
);
}

function MenuItem({ data, index, setMeasuredHeight }) {
const ref = React.useRef<HTMLDivElement>(null);

// using useLayoutEffect prevents bounciness of options of re-renders
React.useLayoutEffect(() => {
if (ref.current) {
const measuredHeight = ref.current.getBoundingClientRect().height;

setMeasuredHeight({ index, measuredHeight });
}
}, [ref.current]);

return (
<div key={`option-${index}`} ref={ref}>
{data}
</div>
);
}
export default MenuList;
10 changes: 1 addition & 9 deletions src/Select/Select.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react";
import { fireEvent } from "@testing-library/react";
import { renderWithNDSProvider } from "../NDSProvider/renderWithNDSProvider.spec-utils";
import { selectOption } from "./Select.spec-utils";
import { UsingRefToControlFocus, WithCustomProps, WithMultiselect, WithState } from "./Select.story";
import { UsingRefToControlFocus, WithMultiselect, WithState } from "./Select.story";
import { Select } from ".";

describe("select", () => {
Expand Down Expand Up @@ -38,14 +38,6 @@ describe("select", () => {
expect(container).toHaveTextContent("Three");
});

it("passes along the custom props to custom components", () => {
const { container, queryByText } = renderWithNDSProvider(<WithCustomProps />);

selectOption("custom prop value", container, queryByText);

expect(container).toHaveTextContent("custom prop value");
});

describe("with state", () => {
it("clears the selected option", () => {
const { container, queryByText } = renderWithNDSProvider(<WithState />);
Expand Down
Loading
Loading