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

fix: NDS Select props are broken #1408

Merged
merged 8 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
}
],
"react/display-name": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
// rules below are to override nulogy config
"react/jsx-filename-extension": [
1,
Expand Down
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@
"@nulogy/tokens": "^5.4.0",
"@styled-system/prop-types": "^5.1.4",
"@styled-system/theme-get": "^5.1.2",
"@types/react-window": "^1.8.8",
"@types/styled-system": "5.1.22",
"body-scroll-lock": "^3.1.5",
"core-js": "3",
"create-react-context": "^0.3.0",
Expand All @@ -160,11 +162,10 @@
"react-popper": "1.3.11",
"react-popper-2": "npm:react-popper@2.2.4",
"react-resize-detector": "^9.1.0",
"react-windowed-select": "^5.2.0",
"smoothscroll-polyfill": "^0.4.4",
"react-select": "^5.8.0",
"styled-system": "^5.1.4",
"@types/styled-system": "5.1.22"
"react-window": "^1.8.10",
"smoothscroll-polyfill": "^0.4.4",
haideralsh marked this conversation as resolved.
Show resolved Hide resolved
"styled-system": "^5.1.4"
},
"husky": {
"hooks": {
Expand Down
1 change: 0 additions & 1 deletion src/AsyncSelect/AsyncSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ const AsyncSelect = forwardRef(
onMenuClose={onMenuClose}
menuPosition={menuPosition}
onInputChange={onInputChange}
theme={theme as any}
components={{
Option: (props) => (
<SelectOption size={componentSize} {...props}>
Expand Down
2 changes: 1 addition & 1 deletion src/AsyncSelect/AsyncSelectComponents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
MultiValueProps,
} from "react-select";
import { components, GroupBase } from "react-select";
import { OptionProps } from "react-windowed-select";
import { OptionProps } from "react-select";
import { ComponentSize, useComponentSize } from "../NDSProvider/ComponentSizeContext";
import { StyledOption } from "../Select/SelectOption";

Expand Down
171 changes: 171 additions & 0 deletions src/Select/MenuList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/*
Copied as is from: https://github.com/jacobworrel/react-windowed-select/blob/master/src/MenuList.tsx
haideralsh marked this conversation as resolved.
Show resolved Hide resolved
*/

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]);
haideralsh marked this conversation as resolved.
Show resolved Hide resolved

// 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
76 changes: 76 additions & 0 deletions src/Select/Select.story.fixture.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React from "react";
import styled from "styled-components";
import { SelectOption, SelectOptionProps } from "./SelectOption";
import { NDSOption } from "./Select";

export const errorList = ["Error message 1", "Error message 2"];

export const options: NDSOption[] = [
{ value: "accepted", label: "Accepted" },
{ value: "assigned", label: "Assigned to a line" },
{ value: "hold", label: "On hold" },
{ value: "rejected", label: "Rejected" },
{ value: "open", label: "Open" },
{ value: "progress", label: "In progress" },
{ value: "quarantine", label: "In quarantine" },
];

export const partnerCompanyName = [
{ value: "2", label: "PCN2 12387387484895884957848576867587685780" },
{ value: "4", label: "PCN4 12387387484895884957848576867587685780" },
{ value: "1", label: "PCN1 12387387484895884957848576867587685780" },
{ value: "9", label: "PCN9 12387387484895884957848576867587685780" },
{ value: "7", label: "PCN7 12387387484895884957848576867587685780" },
{ value: "6", label: "PCN6 12387387484895884957848576867587685780" },
{ value: "3", label: "PCN3 12387387484895884957848576867587685780e" },
];

export const wrappingOptions = [
{
value: "onestring",
label:
"Onelongstringonelongstringonelongstringonelongstringonelongstringonelongstringonelongstringonelongstringonelongstringonelongstringonelongstring",
},
{
value: "manywords",
label:
"Many words many words many words many words many words many words many words many words many words many words many words many words many words",
},
];

export const PCNList = [
{ value: "2", label: "PCN2" },
{ value: "4", label: "PCN4" },
{ value: "1", label: "PCN1" },
{ value: "9", label: "PCN9" },
];

export const getPhotos = async () => {
// returns 5000 items
const data = await fetch("https://jsonplaceholder.typicode.com/photos");
const json = await data.json();
return json.map(({ title, id }) => ({
label: title,
value: id,
}));
};

const Indicator = styled.span(() => ({
borderRadius: "25%",
background: "green",
lineHeight: "0",
display: "inline-block",
width: "10px",
height: "10px",
marginRight: "5px",
}));

export const CustomOption = ({ children, ...props }: SelectOptionProps) => {
const newChildren = (
<>
<Indicator />
{children}
</>
);
return <SelectOption {...props}>{newChildren}</SelectOption>;
};
Loading
Loading