fix combo box in glass

This commit is contained in:
hamid zarghami
2026-06-21 15:30:08 +03:30
parent ed5df3d7b7
commit 97b1cddf85
4 changed files with 234 additions and 204 deletions
+124 -60
View File
@@ -4,7 +4,8 @@ import clsx from "clsx";
import { motion, Variants } from "framer-motion";
import { Icon, SearchNormal } from "iconsax-react";
import { ChevronDown } from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
export interface ComboboxOption {
id: string;
@@ -28,6 +29,12 @@ type Props = {
) => void;
} & React.HTMLAttributes<HTMLDivElement>;
type DropdownPosition = {
top: number;
left: number;
width: number;
};
function Combobox({
title,
options,
@@ -37,17 +44,53 @@ function Combobox({
selectedId,
searchable = true,
onSelectionChange,
className,
...props
}: Props) {
const [expand, setExpand] = useState(expanded);
const [searchValue, setSearchValue] = useState("");
const [dropdownPosition, setDropdownPosition] = useState<DropdownPosition | null>(null);
const boxRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLDivElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const updateDropdownPosition = useCallback(() => {
if (!triggerRef.current) return;
const rect = triggerRef.current.getBoundingClientRect();
setDropdownPosition({
top: rect.bottom + 4,
left: rect.left,
width: rect.width,
});
}, []);
useEffect(() => {
if (!expand) {
setDropdownPosition(null);
return;
}
updateDropdownPosition();
window.addEventListener("scroll", updateDropdownPosition, true);
window.addEventListener("resize", updateDropdownPosition);
return () => {
window.removeEventListener("scroll", updateDropdownPosition, true);
window.removeEventListener("resize", updateDropdownPosition);
};
}, [expand, updateDropdownPosition]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (boxRef.current && !boxRef.current.contains(event.target as Node)) {
setExpand(false);
const target = event.target as Node;
if (
boxRef.current?.contains(target) ||
dropdownRef.current?.contains(target)
) {
return;
}
setExpand(false);
};
if (expand) {
@@ -72,12 +115,14 @@ function Combobox({
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
index: number,
) => {
e.stopPropagation(); // prevent toggle
e.stopPropagation();
onSelectionChange(e, index);
setExpand(false);
};
const selectedOption = options.find((x) => x.id === selectedId);
const filteredOptions = options.filter((v) => v.title?.includes(searchValue));
const activeIcon =
selectedOption?.icon &&
React.createElement(selectedOption.icon, {
@@ -93,7 +138,7 @@ function Combobox({
collapse: {
opacity: 0,
scale: 0.95,
pointerEvents: "none", // disable clicks
pointerEvents: "none",
transition: {
duration: 0.1,
ease: "easeInOut",
@@ -102,7 +147,7 @@ function Combobox({
expand: {
opacity: 1,
scale: 1,
pointerEvents: "auto", // re-enable clicks
pointerEvents: "auto",
transition: {
duration: 0.1,
ease: "easeInOut",
@@ -110,13 +155,84 @@ function Combobox({
},
};
const dropdown =
expand &&
dropdownPosition &&
typeof document !== "undefined"
? createPortal(
<motion.div
ref={dropdownRef}
data-expand={expand}
aria-hidden={!expand}
className="fixed text-foreground bg-container rounded-xl border border-border shadow-lg z-9999"
style={{
top: dropdownPosition.top,
left: dropdownPosition.left,
width: dropdownPosition.width,
}}
role="listbox"
aria-label={`${title} options`}
onClick={(e) => e.stopPropagation()}
initial="collapse"
animate="expand"
variants={variants}
>
{searchable && (
<div className="w-full flex gap-2 border-b border-border px-3 items-center">
<SearchNormal size={16} className="stroke-gray-400" />
<input
placeholder="جستجو ..."
className="w-full outline-none text-sm2 pb-2 pt-3"
onChange={searchChanged}
value={searchValue}
/>
</div>
)}
<div className="flex flex-col p-1">
{filteredOptions.map((v) => {
const originalIndex = options.findIndex((o) => o.id === v.id);
return (
<div
onClick={(e) => setSelection(e, originalIndex)}
key={v.id}
data-selected={v.id === selectedId}
className="flex gap-3 items-center justify-end px-2 py-2 cursor-pointer hover:bg-current/10 rounded-md last:rounded-b-xl"
tabIndex={0}
role="option"
aria-selected={v.id === selectedId}
>
{v?.imagePath ? (
<span className="icon-delivery shrink-0" aria-hidden />
) : (
v?.icon &&
React.createElement(v.icon, {
size: 16,
color: "currentColor",
className:
"inline-block shrink-0 text-primary dark:text-foreground",
})
)}
<span className="text-sm2 tracking-[0.13px] leading-5 flex-1 text-right">
{v.title}
</span>
</div>
);
})}
</div>
</motion.div>,
document.body,
)
: null;
return (
<div
ref={boxRef}
className={clsx("relative", props.className ?? "")}
className={clsx("relative", className)}
{...props}
>
<div
ref={triggerRef}
className="flex w-full h-11 items-center justify-end gap-2 px-3 py-4 relative bg-container/29 rounded-xl border border-solid border-border cursor-pointer"
tabIndex={0}
onClick={toggleExpand}
@@ -163,59 +279,7 @@ function Combobox({
/>
</div>
<motion.div
data-expand={expand}
aria-hidden={!expand}
className="absolute top-full left-0 w-full mt-1 text-foreground bg-container rounded-xl outline outline-solid outline-border shadow-lg z-10"
role="listbox"
aria-label={`${title} options`}
onClick={(e) => e.stopPropagation()}
initial="collapse"
animate={expand ? "expand" : "collapse"}
variants={variants}
>
{searchable && (
<div className="w-full flex gap-2 border-b border-border px-3 items-center">
<SearchNormal size={16} className="stroke-gray-400" />
<input
placeholder="جستجو ..."
className="w-full outline-none text-sm2 pb-2 pt-3"
onChange={searchChanged}
value={searchValue}
/>
</div>
)}
<div className="p-1">
{options
.filter((v) => v.title?.includes(searchValue))
.map((v, i) => (
<div
onClick={(e) => setSelection(e, i)}
key={v.id}
data-selected={v.id === selectedId}
className="flex gap-3 items-center justify-end px-2 py-1 cursor-pointer hover:bg-current/10 rounded-md last:rounded-b-xl"
tabIndex={0}
role="option"
aria-selected
>
{v?.imagePath ? (
<span className="icon-delivery mr-1" aria-hidden />
) : (
v?.icon &&
React.createElement(v.icon, {
size: 16,
color: "currentColor",
className:
"inline-block mr-1 text-primary dark:text-foreground",
})
)}
<span className="text-sm2 tracking-[0.13px] leading-5 w-full mt-1">
{v.title}
</span>
</div>
))}
</div>
</motion.div>
{dropdown}
</div>
);
}
+30 -40
View File
@@ -1,48 +1,38 @@
'use client';
"use client";
import React from 'react'
import Tooltip from '../utils/Tooltip';
import clsx from 'clsx';
import clsx from "clsx";
import React from "react";
import Tooltip from "../utils/Tooltip";
type Props = {
htmlFor: string;
labelText?: React.ReactNode;
value?: string;
valid?: boolean
inputClassName?: string;
htmlFor: string;
labelText?: React.ReactNode;
value?: string;
valid?: boolean;
inputClassName?: string;
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, "id">;
const InputField = React.forwardRef<HTMLInputElement, Props>(({ onChange, htmlFor, labelText, children, valid = true, className, inputClassName, ...inputProps }, ref) => {
return (
<div spellCheck={false} className={`${className} ${valid ? "border-border" : "border-invalid"} h-11 inline-flex relative border px-3 w-full rounded-normal group focus-within:border`}>
<label className="absolute start-2 -top-2.5 px-2 text-[12px] text-foreground bg-container" htmlFor={htmlFor}>
{labelText}
</label>
const InputField = React.forwardRef<HTMLInputElement, Props>(
({ onChange, htmlFor, labelText, children, valid = true, className, inputClassName, ...inputProps }, ref) => {
return (
<div
spellCheck={false}
className={`${className} ${valid ? 'border-border' : 'border-invalid'} h-11 inline-flex relative border px-3 w-full rounded-normal group focus-within:border`}>
<label
className='absolute start-2 -top-2.5 px-2 text-[12px] text-foreground bg-container'
htmlFor={htmlFor}>
{labelText}
</label>
<Tooltip content={inputProps["aria-errormessage"]} hidden={!inputProps["aria-errormessage"]}>
<input
ref={ref}
onChange={onChange}
className={clsx(inputProps["aria-errormessage"] && "text-red-300!", "py-2.5 pt-3.5 text-sm2 w-full outline-0 leading-6!", inputClassName)}
name={htmlFor}
{...inputProps}
/>
{children}
</Tooltip>
</div>
);
});
<Tooltip content={inputProps['aria-errormessage']} hidden={!inputProps['aria-errormessage']}>
<input
ref={ref}
onChange={onChange}
className={clsx(
inputProps['aria-errormessage'] && 'text-red-300!',
'py-2.5 pt-3.5 text-sm2 w-full outline-0 leading-6!',
inputClassName
)}
name={htmlFor}
{...inputProps} />
{children}
</Tooltip>
</div>
)
}
)
InputField.displayName = "InputField";
InputField.displayName = 'InputField'
export default InputField
export default InputField;