Skip to content

Commit

Permalink
fix(select): recalc options-list width when open (#640)
Browse files Browse the repository at this point in the history
  • Loading branch information
reme3d2y committed May 18, 2021
1 parent b139c46 commit 1a7a3c2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
3 changes: 2 additions & 1 deletion packages/select/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"classnames": "^2.2.6",
"downshift": "5.4.7",
"react-merge-refs": "^1.1.0",
"react-virtual": "^2.2.0"
"react-virtual": "^2.2.0",
"resize-observer": "^1.0.0"
}
}
2 changes: 2 additions & 0 deletions packages/select/src/Component.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const options = [
{ key: '13', content: 'Dubnium' },
{ key: '14', content: 'Seaborgium' },
{ key: '15', content: 'Bohrium' },
{ key: '16', content: 'Очень длинный текст Очень длинный текст Очень длинный текст' },
];

export const groups = [
Expand Down Expand Up @@ -124,6 +125,7 @@ export const POSITION_OPTIONS = [
onChange={action('change')}
onOpen={action('open')}
popoverPosition={selectKnob('popoverPosition', POSITION_OPTIONS, 'bottom-start')}
optionsListWidth={selectKnob('optionsListWidth', ['field', 'content'], 'field')}
/>
</Story>

Expand Down
15 changes: 13 additions & 2 deletions packages/select/src/components/base-select/Component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import React, {
useEffect,
useLayoutEffect,
} from 'react';
import { ResizeObserver } from 'resize-observer';
import mergeRefs from 'react-merge-refs';
import cn from 'classnames';
import { Popover } from '@alfalab/core-components-popover';
Expand Down Expand Up @@ -283,7 +284,7 @@ export const BaseSelect = forwardRef(
if (defaultOpen) openMenu();
}, [defaultOpen, openMenu]);

useLayoutEffect(() => {
const calcOptionsListWidth = () => {
if (listRef.current) {
const widthAttr = optionsListWidth === 'field' ? 'width' : 'minWidth';

Expand All @@ -293,7 +294,17 @@ export const BaseSelect = forwardRef(

listRef.current.style[widthAttr] = `${optionsListMinWidth}px`;
}
}, [open, optionsListWidth, options, selectedItems]);
};

const resizeObserver = useRef(new ResizeObserver(calcOptionsListWidth));

useEffect(() => {
if (!rootRef.current || !resizeObserver.current) return;

resizeObserver.current[open ? 'observe' : 'unobserve'](rootRef.current);
}, [open]);

useLayoutEffect(calcOptionsListWidth, [open, optionsListWidth, options, selectedItems]);

const renderValue = useCallback(
() =>
Expand Down

0 comments on commit 1a7a3c2

Please sign in to comment.