From b325e249a371a9d5e3cab05f38a6a6906bb83efc Mon Sep 17 00:00:00 2001 From: Arnaud Date: Wed, 28 Aug 2024 10:03:09 +0200 Subject: [PATCH] Improve dropdown component --- src/components/Dropdown/Dropdown.tsx | 100 +++++++++++++++++---------- src/components/Dropdown/dropdown.css | 10 ++- 2 files changed, 73 insertions(+), 37 deletions(-) diff --git a/src/components/Dropdown/Dropdown.tsx b/src/components/Dropdown/Dropdown.tsx index 1cac863..576e6ae 100644 --- a/src/components/Dropdown/Dropdown.tsx +++ b/src/components/Dropdown/Dropdown.tsx @@ -1,4 +1,10 @@ -import { ChangeEvent, ComponentType, useState } from "react"; +import { + ChangeEvent, + ComponentType, + useState, + KeyboardEvent, + useRef, +} from "react"; import "./dropdown.css"; import { attributes } from "../utils/attributes"; import { Backdrop } from "../Backdrop/Backdrop"; @@ -67,12 +73,20 @@ type Props = { * --codex-dropdown-option-background-hover */ style?: CustomStyleCSS; + + label: string; + + id: string; + + Component?: ComponentType; }; export function Dropdown({ placeholder, style, options, + label, + id, onMouseEnter, onMouseLeave, onFocus, @@ -82,6 +96,7 @@ export function Dropdown({ value = "", className = "", }: Props) { + const inputRef = useRef(null); const lower = value.toLocaleLowerCase(); const filtered = options.filter( (o) => @@ -105,48 +120,63 @@ export function Dropdown({ setFocused(false); }; + const onKeyUp = (e: KeyboardEvent) => { + if (e.key === "Escape") { + onClose(); + inputRef.current?.blur(); + } + }; + const onClose = () => setFocused(false); const attr = attributes({ "aria-expanded": focused }); return ( -
- + <> + - +
+ -
- {filtered.length ? ( - filtered.map((o) => ( -
onSelect(o)} - key={o.title} - > - {o.Icon && } -
- {o.title} - {o.subtitle && ( - {o.subtitle} - )} + + +
+ {filtered.length ? ( + filtered.map((o) => ( +
onSelect(o)} + key={o.title} + > + {o.Icon && } +
+ {o.title} + {o.subtitle && ( + {o.subtitle} + )} +
-
- )) - ) : ( -

No results found

- )} + )) + ) : ( +

No results found

+ )} +
-
+ ); } diff --git a/src/components/Dropdown/dropdown.css b/src/components/Dropdown/dropdown.css index d74e010..986e123 100644 --- a/src/components/Dropdown/dropdown.css +++ b/src/components/Dropdown/dropdown.css @@ -24,11 +24,17 @@ z-index: -1; } +.dropdown-label { + margin-bottom: 0.5rem; + font-weight: 500; + display: block; + color: var(--codex-color); +} + .dropdown-panel[aria-expanded] { - z-index: 2; transform: translateY(0.5rem); opacity: 1; - z-index: 2; + z-index: 10; } .dropdown-input {