Skip to content

Commit 334fb58

Browse files
committed
refactor stories and hooks
1 parent d592bfb commit 334fb58

File tree

7 files changed

+56
-59
lines changed

7 files changed

+56
-59
lines changed

__stories__/helpers/components/OptionsCountButton.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ type OptionsCountButtonProps = Readonly<{
1010
}>;
1111

1212
const StyledButton = styled(Button)<{ isActive?: boolean }>`
13-
width: 6.25rem;
13+
width: 6rem;
14+
min-width: 6rem !important;
1415
transition: none;
1516
1617
${({ isActive }) =>

__stories__/helpers/utils/index.ts

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import type { Option } from '../../types';
22

3+
export const numberWithCommas = (value: number): string => {
4+
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
5+
};
6+
7+
export const getRandomInt = (min: number, max: number): number => {
8+
return Math.floor(Math.random() * (max - min + 1)) + min;
9+
};
10+
311
export const stringifyJavaScriptObj = (data: any = {}): string => {
412
return JSON.stringify(data, null, 2).replace(/"(\w+)"\s*:/g, '$1:');
513
};
@@ -22,27 +30,21 @@ export const createSelectOptions = (optionCount: number): Option[] => {
2230
return results;
2331
};
2432

25-
export const createAsyncOptions = (
26-
optionCount: number,
27-
lblSuffix: string
28-
): Option[] => {
29-
const options = createSelectOptions(optionCount);
33+
export const createThemeOptions = (ThemeEnum: any): Option[] => {
34+
return Object.keys(ThemeEnum).map((key) => ({
35+
value: ThemeEnum[key],
36+
label: ThemeEnum[key]
37+
}));
38+
};
3039

40+
export const createAsyncOptions = (optionCount: number, lblSuffix: string): Option[] => {
41+
const options = createSelectOptions(optionCount);
3142
return options.map(({ value, label }: Option) => ({
3243
value,
3344
label: `${label} - ${lblSuffix}`
3445
}));
3546
};
3647

37-
export const createThemeOptions = (ThemeEnum: any): Option[] => {
38-
const keys = Object.keys(ThemeEnum);
39-
40-
return keys.map((key) => ({
41-
value: ThemeEnum[key],
42-
label: ThemeEnum[key]
43-
}));
44-
};
45-
4648
export const hexToRgba = (hex: string, alpha: number = 1): string => {
4749
const hexReplacer: string = hex.replace(
4850
/^#?([a-f\d])([a-f\d])([a-f\d])$/i,
@@ -54,7 +56,4 @@ export const hexToRgba = (hex: string, alpha: number = 1): string => {
5456
const rgbaParts: number[] = [...rgbParts, alphaValid];
5557

5658
return `rgba(${rgbaParts.join(',')})`;
57-
};
58-
59-
export const numberWithCommas = (value: number): string => value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
60-
export const getRandomInt = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;
59+
};

__stories__/index.stories.tsx

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -292,11 +292,6 @@ export const Styling = () => {
292292
const [themeConfig, setThemeConfig] = useState<Theme | undefined>(undefined);
293293
const [selectedOption, setSelectedOption] = useCallbackState<SelectedOption | null>(null);
294294

295-
const selectWrapperStyle = { marginTop: '1rem' };
296-
const noteStyle = { fontSize: 'inherit', fontWeight: 700 };
297-
const noteCodeStyle = { fontWeight: 500 };
298-
const menuItemSize = selectedOption?.value === ThemeEnum.LARGE_TEXT ? 44 : 35;
299-
300295
const memoizedMarkupNode = useMemo(() => (
301296
<CodeMarkup
302297
language='markup'
@@ -308,10 +303,15 @@ export const Styling = () => {
308303
useEffect(() => {
309304
if (selectedOption) {
310305
const { value } = selectedOption;
311-
setThemeConfig(ThemeConfigMap[value as string | number]);
306+
setThemeConfig(ThemeConfigMap[value!]);
312307
}
313308
}, [selectedOption]);
314309

310+
const noteCodeStyle = { fontWeight: 500 };
311+
const selectWrapperStyle = { marginTop: '1rem' };
312+
const noteStyle = { fontSize: 'inherit', fontWeight: 700 };
313+
const menuItemSize = selectedOption?.value === ThemeEnum.LARGE_TEXT ? 44 : 35;
314+
315315
return (
316316
<Container>
317317
<Title>Styling</Title>
@@ -590,7 +590,7 @@ export const Methods = () => {
590590
<Button onClick={blurSelect}>Blur</Button>
591591
<Button onClick={toggleMenuOpen}>Open Menu</Button>
592592
<Button onClick={clearValue}>Clear Value</Button>
593-
<Button onClick={updateSelectedOption}>Set Value (1st Option)</Button>
593+
<Button onClick={updateSelectedOption}>Set Value</Button>
594594
</Buttons>
595595
</CardHeader>
596596
<CardBody>
@@ -699,10 +699,10 @@ export const Filtering = () => {
699699
};
700700

701701
export const Virtualization = () => {
702-
const optionCountList = useMemo<number[]>(() => [100, 1000, 10000, 25000, 50000, 100000], []);
703-
const selectRef = useRef<SelectRef | null>(null);
704-
const [options, setOptions] = useState<Option[]>([]);
702+
const optionCountList = useMemo(() => [100, 1000, 10000, 25000, 50000, 100000], []);
705703
const [optionsCount, setOptionsCount] = useState(optionCountList[0]);
704+
const [options, setOptions] = useState<Option[]>([]);
705+
const selectRef = useRef<SelectRef | null>(null);
706706

707707
useUpdateEffect(() => {
708708
selectRef.current?.clearValue();
@@ -789,19 +789,19 @@ export const Virtualization = () => {
789789

790790
export const Advanced = () => {
791791
const getOptionValue = useCallback(({ id }: PackageOption): number => id, []);
792-
const getIsOptionDisabled = useCallback((opt: PackageOption): boolean => opt.name === PACKAGE_OPTIONS[3].name, []);
792+
const getIsOptionDisabled = useCallback(({ name }: PackageOption): boolean => name === PACKAGE_OPTIONS[3].name, []);
793793

794794
const renderOptionLabel = useCallback(
795-
(opt: PackageOption) => (
795+
(option: PackageOption) => (
796796
<OptionContainer>
797797
<ReactSvg
798798
{...REACT_SVG_PROPS}
799-
isDisabled={getIsOptionDisabled(opt)}
799+
isDisabled={getIsOptionDisabled(option)}
800800
>
801801
<path {...REACT_SVG_PATH_PROPS} />
802802
<circle {...REACT_SVG_CIRCLE_PROPS} />
803803
</ReactSvg>
804-
<OptionName>{opt.name}</OptionName>
804+
<OptionName>{option.name}</OptionName>
805805
</OptionContainer>
806806
),
807807
[getIsOptionDisabled]
@@ -878,19 +878,18 @@ export const Advanced = () => {
878878
};
879879

880880
export const Portaling = () => {
881-
const menuPortalElId = 'menu-portal-test';
881+
const portalId = 'menu-portal-test';
882882
const options = useMemo<Option[]>(() => createSelectOptions(3), []);
883883

884884
const [menuOpen, setMenuOpen] = useState(false);
885-
const [menuPortalTarget, setMenuPortalTarget] = useState<Element | undefined>(undefined);
886-
885+
const [menuPortalTarget, setMenuPortalTarget] = useState<Element | undefined>();
887886
const onMenuOpen = useCallback(() => setMenuOpen(true), []);
888887
const onMenuClose = useCallback(() => setMenuOpen(false), []);
889888

890889
useEffect(() => {
891-
const portalEl = document.getElementById(menuPortalElId) as HTMLElement;
890+
const portalEl = document.getElementById(portalId) as HTMLElement;
892891
setMenuPortalTarget(portalEl);
893-
}, [menuPortalElId]);
892+
}, [portalId]);
894893

895894
return (
896895
<Container>
@@ -908,10 +907,10 @@ export const Portaling = () => {
908907
<CardHeader>
909908
<Label>Menu component portaled to an element below this text.</Label>
910909
<MenuPortalElement
910+
id={portalId}
911911
menuOpen={menuOpen}
912-
id={menuPortalElId}
913912
>
914-
<span>Portal {'<'}div /{'>'}</span>
913+
<span>portal {'<'}div /{'>'}</span>
915914
</MenuPortalElement>
916915
</CardHeader>
917916
<CardBody>
@@ -935,15 +934,13 @@ export const Async = () => {
935934
const selectRef = useRef<SelectRef | null>(null);
936935
const [isLoading, setIsLoading] = useState(false);
937936
const [options, setOptions] = useState<Option[]>(() => createAsyncOptions(5, 'Initial'));
938-
939937
const onInputChange = useCallback(() => setIsLoading(true), []);
940938

941939
const onSearchChange = useCallback(
942940
async (value: string = 'Initial') => {
943941
try {
944942
await mockHttpRequest();
945-
const count = getRandomInt(1, 5);
946-
const nextOptions = createAsyncOptions(count, `Search text: ${value}`);
943+
const nextOptions = createAsyncOptions(getRandomInt(1, 5), `Search text: ${value}`);
947944
selectRef.current?.clearValue();
948945
setOptions(nextOptions);
949946
setIsLoading(false);

src/Select.tsx

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -531,13 +531,12 @@ const Select = forwardRef<SelectRef, SelectProps>((
531531
const handleOnKeyDown = (e: KeyboardEvent<HTMLElement>): void => {
532532
if (isDisabled) return;
533533

534-
const { key, shiftKey, defaultPrevented } = e;
535-
if (onKeyDown) {
536-
onKeyDown(e, inputValue, focusedOption);
537-
if (defaultPrevented) return;
534+
if (isFunction(onKeyDown)) {
535+
onKeyDown(e.key, inputValue, focusedOption);
536+
if (e.defaultPrevented) return;
538537
}
539538

540-
switch (key) {
539+
switch (e.key) {
541540
case 'ArrowDown': {
542541
menuOpen ? focusOptionOnArrowKey(OptionIndexEnum.DOWN) : openMenuAndFocusOption(OptionIndexEnum.FIRST);
543542
break;
@@ -549,7 +548,7 @@ const Select = forwardRef<SelectRef, SelectProps>((
549548
case 'ArrowLeft':
550549
case 'ArrowRight': {
551550
if (!isMulti || inputValue || renderMultiOptions) return;
552-
focusValueOnArrowKey(key);
551+
focusValueOnArrowKey(e.key);
553552
break;
554553
}
555554
case 'PageUp': {
@@ -589,7 +588,9 @@ const Select = forwardRef<SelectRef, SelectProps>((
589588
break;
590589
}
591590
case 'Tab': {
592-
if (shiftKey || !menuOpen || !tabSelectsOption || !focusedOption.data) return;
591+
if (e.shiftKey || !menuOpen || !tabSelectsOption || !focusedOption.data) {
592+
return;
593+
}
593594
selectOptionFromFocused();
594595
break;
595596
}

src/hooks/useLatestRef.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import { useRef, type MutableRefObject } from "react"
66
* @param value the value to persist
77
*/
88
const useLatestRef = <T>(value: T): MutableRefObject<T> => {
9-
const ref = useRef<T>();
9+
const ref = useRef<T>(value);
1010
ref.current = value;
11-
return ref as MutableRefObject<T>;
11+
return ref;
1212
};
1313

1414
export default useLatestRef;

src/hooks/useMenuOptions.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ const useMenuOptions = (
5858
: menuOption;
5959
};
6060

61-
return options.reduce((acc: MenuOption[], option: OptionData) => {
62-
const menuOption = parseMenuOption(option);
61+
return options.reduce((acc: MenuOption[], data: OptionData) => {
62+
const menuOption = parseMenuOption(data);
6363
menuOption && acc.push(menuOption);
6464
return acc;
6565
}, []);

src/utils/menu.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,14 @@ function isDocumentElement(el: HTMLElement | typeof window): boolean {
3838
*/
3939
function getScrollParent(el: HTMLElement): HTMLElement {
4040
let style = getComputedStyle(el);
41-
const isParentAbs = style.position === 'absolute';
42-
const overflowRegExp = /(auto|scroll)/;
4341

4442
if (style.position === 'fixed') {
4543
return document.documentElement;
4644
}
4745

46+
const overflowRegExp = /(auto|scroll)/;
47+
const isParentAbs = style.position === 'absolute';
48+
4849
for (let parent: HTMLElement | null = el; (parent = parent?.parentElement);) {
4950
style = getComputedStyle(parent);
5051
if (
@@ -96,9 +97,7 @@ export const calculateMenuTop = (
9697
const controlHeight = controlEl?.getBoundingClientRect().height ?? 0;
9798
const menuHeightCalc = menuHeight > 0 ? menuHeight : (menuEl?.getBoundingClientRect().height ?? 0);
9899
const basePx = -Math.abs(menuHeightCalc + controlHeight);
99-
const adjustPx = marginBottom + marginTop;
100-
101-
return `calc(${basePx}px + ${adjustPx}px)`;
100+
return `calc(${basePx}px + ${marginBottom + marginTop}px)`;
102101
};
103102

104103
export const menuFitsBelowControl = (el: HTMLElement | null): boolean => {

0 commit comments

Comments
 (0)