From c68ff54e775d5d9a869d1174a29c0ad509b03cef Mon Sep 17 00:00:00 2001 From: sean-brydon <55134778+sean-brydon@users.noreply.github.com> Date: Mon, 13 Feb 2023 14:14:23 +0000 Subject: [PATCH] Feat/full custom select (#6865) * Inital Setup - refactors/optimise * Escape clears focus * A11y and optimisations * A11y enter fix * Sort out flatternt list indexing * Fix spacing - fix single selected state * Solves group highlights breaking things * Fix selecting while filtering list * Remove styles and rename story * Hide labels while searching for now * Remove group item * move onclick hook to hooks * Fix typo * Use check icon on single select * scroll into view when keyboard navigating * add comment explaining dropdown close * Remove tenery and make disabled easier to read * Typo * remove log * Remove destructing of classNames props * Refactor callbacks + hooks * Style updates with ciaran * Final style changes * center icon * Add darkmode --- packages/lib/hooks/useKeyPress.ts | 46 ++++ packages/lib/hooks/useOnclickOutside.ts | 24 ++ .../form/selectimproved/components/Item.tsx | 88 ++++++ .../selectimproved/components/Options.tsx | 136 ++++++++++ .../selectimproved/components/SearchInput.tsx | 52 ++++ .../form/selectimproved/components/Select.tsx | 256 ++++++++++++++++++ .../components/SelectProvider.tsx | 44 +++ .../form/selectimproved/components/type.ts | 26 ++ .../components/form/selectimproved/index.tsx | 3 + .../selectimproved/selectimproved.stories.mdx | 86 ++++++ 10 files changed, 761 insertions(+) create mode 100644 packages/lib/hooks/useKeyPress.ts create mode 100644 packages/lib/hooks/useOnclickOutside.ts create mode 100755 packages/ui/components/form/selectimproved/components/Item.tsx create mode 100755 packages/ui/components/form/selectimproved/components/Options.tsx create mode 100755 packages/ui/components/form/selectimproved/components/SearchInput.tsx create mode 100755 packages/ui/components/form/selectimproved/components/Select.tsx create mode 100644 packages/ui/components/form/selectimproved/components/SelectProvider.tsx create mode 100644 packages/ui/components/form/selectimproved/components/type.ts create mode 100644 packages/ui/components/form/selectimproved/index.tsx create mode 100644 packages/ui/components/form/selectimproved/selectimproved.stories.mdx diff --git a/packages/lib/hooks/useKeyPress.ts b/packages/lib/hooks/useKeyPress.ts new file mode 100644 index 0000000000..c025367d81 --- /dev/null +++ b/packages/lib/hooks/useKeyPress.ts @@ -0,0 +1,46 @@ +import { useState, useEffect, RefObject, useRef } from "react"; + +export function useKeyPress( + targetKey: string, + ref?: RefObject, + handler?: () => void +): boolean { + // State for keeping track of whether key is pressed + const [keyPressed, setKeyPressed] = useState(false); + const placeHolderRef = ref?.current; + // If pressed key is our target key then set to true + function downHandler({ key }: { key: string }) { + if (key === targetKey) { + setKeyPressed(true); + handler && handler(); + } + } + // If released key is our target key then set to false + const upHandler = ({ key }: { key: string }) => { + if (key === targetKey) { + setKeyPressed(false); + } + }; + // Add event listeners + useEffect(() => { + if (ref && placeHolderRef) { + placeHolderRef.addEventListener("keydown", downHandler); + placeHolderRef.addEventListener("keyup", upHandler); + return () => { + placeHolderRef?.removeEventListener("keydown", downHandler); + placeHolderRef?.removeEventListener("keyup", upHandler); + }; + } else { + window.addEventListener("keydown", downHandler); + window.addEventListener("keyup", upHandler); + // Remove event listeners on cleanup + return () => { + window.removeEventListener("keydown", downHandler); + window.removeEventListener("keyup", upHandler); + }; + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); // Empty array ensures that effect is only run on mount and unmount + + return keyPressed; +} diff --git a/packages/lib/hooks/useOnclickOutside.ts b/packages/lib/hooks/useOnclickOutside.ts new file mode 100644 index 0000000000..ad7872aa98 --- /dev/null +++ b/packages/lib/hooks/useOnclickOutside.ts @@ -0,0 +1,24 @@ +import React, { useEffect } from "react"; + +export default function useOnClickOutside( + ref: React.RefObject, + handler: (e?: MouseEvent | TouchEvent) => void +) { + useEffect(() => { + const listener = (event: MouseEvent | TouchEvent) => { + if (!ref.current || ref.current.contains(event.target as Node)) { + return; + } + + handler(event); + }; + + document.addEventListener("mousedown", listener); + document.addEventListener("touchstart", listener); + + return () => { + document.removeEventListener("mousedown", listener); + document.removeEventListener("touchstart", listener); + }; + }, [ref, handler]); +} diff --git a/packages/ui/components/form/selectimproved/components/Item.tsx b/packages/ui/components/form/selectimproved/components/Item.tsx new file mode 100755 index 0000000000..a1ac1715ce --- /dev/null +++ b/packages/ui/components/form/selectimproved/components/Item.tsx @@ -0,0 +1,88 @@ +import React from "react"; +import { FiCheck } from "react-icons/fi"; + +import { classNames as cn } from "@calcom/lib"; + +import { useSelectContext } from "./SelectProvider"; +import { Option } from "./type"; + +interface ItemProps { + item: Option; + index?: number; + focused: boolean; +} + +const Item: React.FC = ({ item, index, focused }) => { + const { classNames, selectedItems, handleValueChange } = useSelectContext(); + const isMultiple = Array.isArray(selectedItems); + const isSelected = + (isMultiple && selectedItems?.some((selection) => selection.value === item.value)) || + (!isMultiple && selectedItems?.value === item.value); + + if (item.disabled) { + return ( +
  • + <> +
    + {item.leftNode && item.leftNode} +

    {item.label}

    +
    + {isMultiple ? ( +
    + {isSelected && } +
    + ) : ( + isSelected && + )} + +
  • + ); + } + + return ( +
  • handleValueChange(item)} + className={cn( + "block flex cursor-pointer select-none items-center justify-between truncate border-transparent px-3 py-2 transition duration-200", + isSelected + ? "dark:bg-darkgray-200 dark:text-darkgray-900 bg-gray-100 text-gray-900" + : "dark:text-darkgray-700 dark:hover:bg-darkgray-200 text-gray-700 hover:bg-gray-100", + focused && "dark:bg-darkgray-200 bg-gray-50", + classNames?.listItem + )}> +
    + {item.leftNode && item.leftNode} +

    {item.label}

    +
    + + {isMultiple ? ( +
    + {isSelected && } +
    + ) : ( + isSelected && + )} +
  • + ); +}; + +export default Item; diff --git a/packages/ui/components/form/selectimproved/components/Options.tsx b/packages/ui/components/form/selectimproved/components/Options.tsx new file mode 100755 index 0000000000..456dc406bd --- /dev/null +++ b/packages/ui/components/form/selectimproved/components/Options.tsx @@ -0,0 +1,136 @@ +import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; + +import classNames from "@calcom/lib/classNames"; +import { useKeyPress } from "@calcom/lib/hooks/useKeyPress"; + +import { Label } from "../../inputs/Label"; +import Item from "./Item"; +import { SelectContext } from "./SelectProvider"; +import { Option } from "./type"; + +interface OptionsProps { + list: T[]; + inputValue: string; + isMultiple: boolean; + selected: T | T[] | null; + searchBoxRef: React.RefObject; +} + +type FlattenedOption = Option & { current: number; groupedIndex?: number }; + +const flattenOptions = (options: Option[], groupCount?: number): FlattenedOption[] => { + return options.reduce((acc, option, current) => { + if (option.options) { + return [...acc, ...flattenOptions(option.options, current + (groupCount || 0))]; + } + return [...acc, { ...option, current, groupedIndex: groupCount }]; + }, [] as FlattenedOption[]); +}; + +function FilteredItem({ + index, + keyboardFocus, + item, + inputValue, + list, +}: { + index: number; + keyboardFocus: number; + item: FlattenedOption; + inputValue: string; + list: T[]; +}) { + const focused = index === keyboardFocus; + const ref = useRef(null); + + useEffect(() => { + if (ref.current && focused) { + ref.current.scrollIntoView({ behavior: "smooth" }); + } + }, [ref, focused]); + + return ( +
    + {item.current === 0 && item.groupedIndex !== undefined && !inputValue && ( +
    + {index !== 0 &&
    } + +
    + )} + +
    + ); +} + +function Options({ list, inputValue, searchBoxRef }: OptionsProps) { + const { classNames, handleValueChange } = useContext(SelectContext); + const [keyboardFocus, setKeyboardFocus] = useState(-1); + const enterPress = useKeyPress("Enter", searchBoxRef); + + const flattenedList = useMemo(() => flattenOptions(list), [list]); + + const totalOptionsLength = useMemo(() => { + return flattenedList.length; + }, [flattenedList]); + + useKeyPress("ArrowDown", searchBoxRef, () => setKeyboardFocus((prev) => (prev + 1) % totalOptionsLength)); + useKeyPress("ArrowUp", searchBoxRef, () => + setKeyboardFocus((prev) => (prev - 1 + totalOptionsLength) % totalOptionsLength) + ); + + useEffect(() => { + if (enterPress) { + const item = filteredList[keyboardFocus]; + if (!item || item.disabled) return; + handleValueChange(item); + } + // We don't want to re-run this effect when handleValueChange changes + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [enterPress, keyboardFocus, list]); + + const search = useCallback((optionsArray: FlattenedOption[], searchTerm: string) => { + // search options by label, or group label or options.options + return optionsArray.reduce((acc: FlattenedOption[], option: FlattenedOption) => { + // @TODO: add search by lavbel group gets awkward as it doesnt exist in the flattened list + if (option.label.toLowerCase().includes(searchTerm.toLowerCase())) { + acc.push(option); + } + + return acc; + }, [] as FlattenedOption[]); + }, []); + + const filteredList = useMemo(() => { + if (inputValue.length > 0) { + return search(flattenedList, inputValue); + } + + return flattenedList; + }, [inputValue, flattenedList, search]); + + return ( +
    + {filteredList?.map((item, index) => ( + + ))} +
    + ); +} + +export default Options; diff --git a/packages/ui/components/form/selectimproved/components/SearchInput.tsx b/packages/ui/components/form/selectimproved/components/SearchInput.tsx new file mode 100755 index 0000000000..5d636a988c --- /dev/null +++ b/packages/ui/components/form/selectimproved/components/SearchInput.tsx @@ -0,0 +1,52 @@ +import React, { useContext } from "react"; + +import { FiSearch } from "../../../icon"; +import { SelectContext } from "./SelectProvider"; + +interface SearchInputProps { + placeholder?: string; + value: string; + onChange: (e: React.ChangeEvent) => void; + name?: string; + searchInputRef?: React.RefObject; +} + +const SearchInput: React.FC = ({ + placeholder = "", + value = "", + onChange, + name = "", + searchInputRef, +}) => { + const { classNames } = useContext(SelectContext); + return ( +
    + + +
    + ); +}; + +export default SearchInput; diff --git a/packages/ui/components/form/selectimproved/components/Select.tsx b/packages/ui/components/form/selectimproved/components/Select.tsx new file mode 100755 index 0000000000..9364818457 --- /dev/null +++ b/packages/ui/components/form/selectimproved/components/Select.tsx @@ -0,0 +1,256 @@ +import React, { useCallback, useEffect, useRef, useState } from "react"; + +import { classNames as cn } from "@calcom/lib"; +import { useKeyPress } from "@calcom/lib/hooks/useKeyPress"; +import useOnClickOutside from "@calcom/lib/hooks/useOnclickOutside"; + +import { FiX, FiChevronDown } from "../../../icon"; +import Options from "./Options"; +import SearchInput from "./SearchInput"; +import SelectProvider from "./SelectProvider"; +import { Option } from "./type"; + +interface SelectProps { + options: T[]; + selectedItems: T | T[] | null; + onChange: (value?: Option | Option[] | null) => void; + placeholder?: string; + isMultiple?: boolean; + isClearable?: boolean; + isSearchable?: boolean; + isDisabled?: boolean; + loading?: boolean; + menuIsOpen?: boolean; + searchInputPlaceholder?: string; + noOptionsMessage?: string; + classNames?: { + menuButton?: ({ isDisabled }: { isDisabled: boolean }) => string; + menu?: string; + tagItem?: ({ isDisabled }: { isDisabled: boolean }) => string; + tagItemText?: string; + tagItemIconContainer?: string; + tagItemIcon?: string; + list?: string; + listGroupLabel?: string; + listItem?: ({ isSelected }: { isSelected: boolean }) => string; + listDisabledItem?: string; + ChevronIcon?: ({ open }: { open: boolean }) => string; + searchContainer?: string; + searchBox?: string; + searchIcon?: string; + closeIcon?: string; + }; +} + +function Select({ + options = [], + selectedItems = null, + onChange, + placeholder = "Select...", + searchInputPlaceholder = "Search...", + isMultiple = false, + isClearable = false, + isSearchable = false, + isDisabled = false, + menuIsOpen = false, + classNames, +}: SelectProps) { + const [open, setOpen] = useState(menuIsOpen); + const [inputValue, setInputValue] = useState(""); + const ref = useRef(null); + const searchBoxRef = useRef(null); + + const isMultipleValue = Array.isArray(selectedItems) && isMultiple; + + const toggle = useCallback(() => { + if (!isDisabled) { + setOpen(!open); + } + }, [isDisabled, open]); + + const closeDropDown = useCallback(() => { + if (open) setOpen(false); + }, [open]); + + useOnClickOutside(ref, () => { + closeDropDown(); + }); + + useKeyPress("Escape", undefined, () => { + closeDropDown(); + }); + + const onPressEnterOrSpace = useCallback( + (e: React.KeyboardEvent) => { + e.preventDefault(); + if ((e.code === "Enter" || e.code === "Space") && !isDisabled) { + toggle(); + } + }, + [isDisabled, toggle] + ); + + const removeItem = useCallback( + (item: Option) => { + // remove the item from the selected items + if (Array.isArray(selectedItems)) { + const newSelectedItems = selectedItems.filter((selectedItem) => selectedItem.value !== item.value); + onChange(newSelectedItems); + } else { + onChange(null); + } + }, + [onChange, selectedItems] + ); + + const handleValueChange = useCallback( + (selected: Option) => { + function update() { + if (!isMultiple && !Array.isArray(selectedItems)) { + // Close dropdown when you select an item when we are on single select + closeDropDown(); + onChange(selected); + return; + } + + // check if the selected item is already selected + if (Array.isArray(selectedItems)) { + const isAlreadySelected = selectedItems.some((item) => item.value === selected.value); + if (isAlreadySelected) { + removeItem(selected); + return; + } + onChange(selectedItems === null ? [selected] : [...selectedItems, selected]); + } + } + + if (selected.disabled) return; + + if (selected !== selectedItems) { + update(); + } + }, + [closeDropDown, isMultiple, onChange, selectedItems, removeItem] + ); + + const clearValue = useCallback( + (e: React.MouseEvent) => { + e.stopPropagation(); + onChange(isMultiple ? [] : null); + }, + [onChange, isMultiple] + ); + + return ( + +
    +
    +
    + <> + {((isMultipleValue && selectedItems.length === 0) || selectedItems === null) && ( +
    +

    {placeholder}

    +
    + )} + + {Array.isArray(selectedItems) ? ( +
    + {selectedItems.map((item, index) => ( +
    +

    + {item.label} +

    + {!isDisabled && ( + + )} +
    + ))} +
    + ) : ( +
    +

    {selectedItems?.label}

    +
    + )} + +
    + +
    + {isClearable && !isDisabled && selectedItems !== null && ( +
    + +
    + )} + + +
    +
    + + {open && !isDisabled && ( +
    + {isSearchable && ( + setInputValue(e.target.value)} + /> + )} + + +
    + )} +
    +
    + ); +} + +export default Select; diff --git a/packages/ui/components/form/selectimproved/components/SelectProvider.tsx b/packages/ui/components/form/selectimproved/components/SelectProvider.tsx new file mode 100644 index 0000000000..d8648da86f --- /dev/null +++ b/packages/ui/components/form/selectimproved/components/SelectProvider.tsx @@ -0,0 +1,44 @@ +import React, { createContext, useContext, useMemo } from "react"; + +import { ClassNames, Option } from "./type"; + +interface Store { + selectedItems: Option | Option[] | null; + handleValueChange: (selected: Option) => void; + classNames?: ClassNames; +} + +interface Props { + selectedItems: Option | Option[] | null; + handleValueChange: (selected: Option) => void; + children: JSX.Element; + options: { + classNames?: ClassNames; + }; +} + +export const SelectContext = createContext({ + selectedItems: null, + handleValueChange: (selected) => { + return selected; + }, + classNames: undefined, +}); + +export const useSelectContext = (): Store => { + return useContext(SelectContext); +}; + +const SelectProvider: React.FC = ({ selectedItems, handleValueChange, options, children }) => { + const store = useMemo(() => { + return { + selectedItems, + handleValueChange, + classNames: options?.classNames, + } as Store; + }, [handleValueChange, options, selectedItems]); + + return {children}; +}; + +export default SelectProvider; diff --git a/packages/ui/components/form/selectimproved/components/type.ts b/packages/ui/components/form/selectimproved/components/type.ts new file mode 100644 index 0000000000..d8d6a52a8a --- /dev/null +++ b/packages/ui/components/form/selectimproved/components/type.ts @@ -0,0 +1,26 @@ +export interface Option { + value?: string; + label: string; + disabled?: boolean; + isSelected?: boolean; + options?: Option[]; + leftNode?: React.ReactNode; +} + +export interface ClassNames { + menuButton?: (args: { isDisabled: boolean }) => string; + menu?: string; + tagItem?: (args: { isDisabled: boolean }) => string; + tagItemText?: string; + tagItemIconContainer?: string; + tagItemIcon?: string; + list?: string; + listGroupLabel?: string; + listItem?: (args: { isSelected: boolean }) => string; + listDisabledItem?: string; + ChevronIcon?: (args: { open: boolean }) => string; + searchContainer?: string; + searchBox?: string; + searchIcon?: string; + closeIcon?: string; +} diff --git a/packages/ui/components/form/selectimproved/index.tsx b/packages/ui/components/form/selectimproved/index.tsx new file mode 100644 index 0000000000..948d811236 --- /dev/null +++ b/packages/ui/components/form/selectimproved/index.tsx @@ -0,0 +1,3 @@ +import Select from "./components/Select"; + +export default Select; diff --git a/packages/ui/components/form/selectimproved/selectimproved.stories.mdx b/packages/ui/components/form/selectimproved/selectimproved.stories.mdx new file mode 100644 index 0000000000..2a6c4a8367 --- /dev/null +++ b/packages/ui/components/form/selectimproved/selectimproved.stories.mdx @@ -0,0 +1,86 @@ +import { Canvas, Meta, Story, ArgsTable } from "@storybook/addon-docs"; + +import { + Examples, + Example, + Note, + Title, + CustomArgsTable, + VariantRow, + VariantsTable, +} from "@calcom/storybook/components"; + +import { FiPlus } from "../../icon"; +import Select from "./components/Select"; + + + + + +export const options = [ + { + //4 + label: "Cal.com Inc", + options: [ + { value: "UserA", label: "Pro" }, // 5 + { value: "UserB", label: "Teampro" }, // 6 + { value: "UserC", label: "Example" }, + { value: "UserD", label: "Admin", disabled: true }, + ], + }, + { + // 5 + label: "Acme Inc", + options: [ + { value: "UserE", label: "Acme Pro" }, // 1 == 6 + { value: "UserF", label: "Acme Teampro" }, + { value: "UserG", label: "Acme example" }, + { value: "UserH", label: "Acme Admin", disabled: true }, + ], + }, +]; + +export const SelectWithState = (...args) => { + const [value, setValue] = React.useState(options[0].options[0]); + return <Select options={options} selectedItems={value} onChange={(e) => setValue(e)} isClearable />; +}; + +export const MultiWithState = (...args) => { + const [value, setValue] = React.useState([options[0].options[0]]); + return ( + <Select + options={options} + selectedItems={value} + onChange={(e) => { + setValue(e); + }} + isSearchable + isMultiple + isClearable + /> + ); +}; + +<Examples title="State"> + <Example title="Single" isFullWidth> + <SelectWithState /> + </Example> + <Example title="Multi" isFullWidth> + <MultiWithState /> + </Example> +</Examples> + +<Canvas> + <Story name="Default"> + <div className="flex flex-col space-y-4"> + <VariantsTable titles={[]} columnMinWidth={300}> + <VariantRow variant="Single"> + <SelectWithState /> + </VariantRow> + <VariantRow variant="Multi"> + <MultiWithState /> + </VariantRow> + </VariantsTable> + </div> + </Story> +</Canvas>