feat(TypeaheadInput): implement portal-based dropdown for suggestions with dynamic positioning
This commit is contained in:
parent
e32dc05999
commit
95adee9710
1 changed files with 173 additions and 45 deletions
|
@ -1,4 +1,5 @@
|
||||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
import { WikidataSuggestion } from '@/types/database';
|
import { WikidataSuggestion } from '@/types/database';
|
||||||
|
|
||||||
interface TypeaheadInputProps {
|
interface TypeaheadInputProps {
|
||||||
|
@ -12,6 +13,12 @@ interface TypeaheadInputProps {
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DropdownPosition {
|
||||||
|
top: number;
|
||||||
|
left: number;
|
||||||
|
width: number;
|
||||||
|
}
|
||||||
|
|
||||||
export function TypeaheadInput({
|
export function TypeaheadInput({
|
||||||
value,
|
value,
|
||||||
onInput,
|
onInput,
|
||||||
|
@ -28,11 +35,44 @@ export function TypeaheadInput({
|
||||||
const [selectedIndex, setSelectedIndex] = useState(-1);
|
const [selectedIndex, setSelectedIndex] = useState(-1);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isExternalUpdate, setIsExternalUpdate] = useState(false);
|
const [isExternalUpdate, setIsExternalUpdate] = useState(false);
|
||||||
|
const [dropdownPosition, setDropdownPosition] = useState<DropdownPosition>({ top: 0, left: 0, width: 0 });
|
||||||
|
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const suggestionsRef = useRef<HTMLDivElement>(null);
|
const suggestionsRef = useRef<HTMLDivElement>(null);
|
||||||
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
|
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
|
||||||
|
|
||||||
|
// Calculate dropdown position relative to viewport
|
||||||
|
const calculateDropdownPosition = useCallback((): DropdownPosition => {
|
||||||
|
if (!inputRef.current) {
|
||||||
|
return { top: 0, left: 0, width: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputRect = inputRef.current.getBoundingClientRect();
|
||||||
|
const viewportHeight = window.innerHeight;
|
||||||
|
const dropdownHeight = 384; // max-h-96 = 24rem = 384px
|
||||||
|
|
||||||
|
// Calculate if dropdown should appear above or below input
|
||||||
|
const spaceBelow = viewportHeight - inputRect.bottom;
|
||||||
|
const spaceAbove = inputRect.top;
|
||||||
|
const shouldShowAbove = spaceBelow < dropdownHeight && spaceAbove > spaceBelow;
|
||||||
|
|
||||||
|
return {
|
||||||
|
top: shouldShowAbove
|
||||||
|
? inputRect.top - Math.min(dropdownHeight, spaceAbove) + window.scrollY
|
||||||
|
: inputRect.bottom + window.scrollY,
|
||||||
|
left: inputRect.left + window.scrollX,
|
||||||
|
width: inputRect.width
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Update dropdown position when showing suggestions
|
||||||
|
const updateDropdownPosition = useCallback(() => {
|
||||||
|
if (showSuggestions) {
|
||||||
|
const position = calculateDropdownPosition();
|
||||||
|
setDropdownPosition(position);
|
||||||
|
}
|
||||||
|
}, [showSuggestions, calculateDropdownPosition]);
|
||||||
|
|
||||||
// Update local value when prop changes (including external updates)
|
// Update local value when prop changes (including external updates)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (value !== localValue) {
|
if (value !== localValue) {
|
||||||
|
@ -55,6 +95,22 @@ export function TypeaheadInput({
|
||||||
}
|
}
|
||||||
}, [isExternalUpdate]);
|
}, [isExternalUpdate]);
|
||||||
|
|
||||||
|
// Update dropdown position on scroll and resize
|
||||||
|
useEffect(() => {
|
||||||
|
if (showSuggestions) {
|
||||||
|
const handleScroll = () => updateDropdownPosition();
|
||||||
|
const handleResize = () => updateDropdownPosition();
|
||||||
|
|
||||||
|
window.addEventListener('scroll', handleScroll, true);
|
||||||
|
window.addEventListener('resize', handleResize);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('scroll', handleScroll, true);
|
||||||
|
window.removeEventListener('resize', handleResize);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, [showSuggestions, updateDropdownPosition]);
|
||||||
|
|
||||||
// Debounced suggestion fetching
|
// Debounced suggestion fetching
|
||||||
const debouncedFetchSuggestions = useCallback(async (query: string) => {
|
const debouncedFetchSuggestions = useCallback(async (query: string) => {
|
||||||
if (timeoutRef.current) {
|
if (timeoutRef.current) {
|
||||||
|
@ -74,7 +130,12 @@ export function TypeaheadInput({
|
||||||
console.log('Fetching suggestions for:', query);
|
console.log('Fetching suggestions for:', query);
|
||||||
const results = await fetchSuggestions(query);
|
const results = await fetchSuggestions(query);
|
||||||
setSuggestions(results);
|
setSuggestions(results);
|
||||||
setShowSuggestions(results.length > 0);
|
if (results.length > 0) {
|
||||||
|
setShowSuggestions(true);
|
||||||
|
// Calculate position when showing suggestions
|
||||||
|
const position = calculateDropdownPosition();
|
||||||
|
setDropdownPosition(position);
|
||||||
|
}
|
||||||
setSelectedIndex(-1);
|
setSelectedIndex(-1);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching suggestions:', error);
|
console.error('Error fetching suggestions:', error);
|
||||||
|
@ -84,7 +145,7 @@ export function TypeaheadInput({
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
}, 300); // 300ms debounce
|
}, 300); // 300ms debounce
|
||||||
}, [fetchSuggestions]);
|
}, [fetchSuggestions, calculateDropdownPosition]);
|
||||||
|
|
||||||
// Handle input changes
|
// Handle input changes
|
||||||
const handleInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
@ -181,8 +242,10 @@ export function TypeaheadInput({
|
||||||
// Show suggestions if we have them and there's a value
|
// Show suggestions if we have them and there's a value
|
||||||
if (suggestions.length > 0 && localValue.trim().length >= 2) {
|
if (suggestions.length > 0 && localValue.trim().length >= 2) {
|
||||||
setShowSuggestions(true);
|
setShowSuggestions(true);
|
||||||
|
const position = calculateDropdownPosition();
|
||||||
|
setDropdownPosition(position);
|
||||||
}
|
}
|
||||||
}, [onFocus, suggestions.length, localValue]);
|
}, [onFocus, suggestions.length, localValue, calculateDropdownPosition]);
|
||||||
|
|
||||||
// Handle blur
|
// Handle blur
|
||||||
const handleBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
|
const handleBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
|
||||||
|
@ -234,11 +297,112 @@ export function TypeaheadInput({
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const baseInputClassName = `
|
const baseInputClassName = `
|
||||||
w-full px-2 py-1 border border-gray-300 rounded
|
w-full px-3 py-2 border border-gray-300 rounded-lg
|
||||||
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
|
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500
|
||||||
|
transition-all duration-200 ease-in-out
|
||||||
${className}
|
${className}
|
||||||
`.trim();
|
`.trim();
|
||||||
|
|
||||||
|
// Portal-based dropdown component
|
||||||
|
const DropdownPortal = () => {
|
||||||
|
if (!showSuggestions || suggestions.length === 0) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
ref={suggestionsRef}
|
||||||
|
className="fixed bg-white border-2 border-gray-300 rounded-xl shadow-2xl max-h-96 overflow-y-auto"
|
||||||
|
style={{
|
||||||
|
top: dropdownPosition.top + 8, // 8px gap below input
|
||||||
|
left: dropdownPosition.left,
|
||||||
|
width: dropdownPosition.width,
|
||||||
|
zIndex: 9999, // Higher than table headers (z-index: 10)
|
||||||
|
backgroundColor: 'rgba(255, 255, 255, 1)',
|
||||||
|
boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04), 0 0 0 1px rgba(0, 0, 0, 0.05)'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="py-2">
|
||||||
|
{suggestions.map((suggestion, index) => {
|
||||||
|
const isSelected = index === selectedIndex;
|
||||||
|
const label = suggestion.label || '';
|
||||||
|
const description = suggestion.description || '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={suggestion.id}
|
||||||
|
className={`
|
||||||
|
relative px-4 py-4 cursor-pointer transition-all duration-200 ease-in-out
|
||||||
|
border-l-4 mx-2 my-1 rounded-lg
|
||||||
|
${isSelected
|
||||||
|
? 'bg-blue-50 border-l-blue-500 shadow-md'
|
||||||
|
: 'border-l-transparent hover:bg-gray-50 hover:border-l-gray-300 hover:shadow-sm'
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
onClick={() => handleSuggestionClick(suggestion)}
|
||||||
|
onMouseEnter={() => setSelectedIndex(index)}
|
||||||
|
style={{
|
||||||
|
backgroundColor: isSelected ? 'rgba(239, 246, 255, 1)' : 'rgba(255, 255, 255, 1)'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex-1 min-w-0 space-y-2">
|
||||||
|
{/* Main label */}
|
||||||
|
<div className={`font-semibold text-base leading-tight ${
|
||||||
|
isSelected ? 'text-blue-900' : 'text-gray-900'
|
||||||
|
}`}>
|
||||||
|
{label}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
{description && (
|
||||||
|
<div className={`text-sm leading-relaxed ${
|
||||||
|
isSelected ? 'text-blue-700' : 'text-gray-600'
|
||||||
|
}`}>
|
||||||
|
{description}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Wikidata ID */}
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
|
||||||
|
isSelected
|
||||||
|
? 'bg-blue-100 text-blue-800 border border-blue-200'
|
||||||
|
: 'bg-gray-100 text-gray-700 border border-gray-200'
|
||||||
|
}`}>
|
||||||
|
<svg className="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M4 4a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2H4zm2 6a2 2 0 104 0 2 2 0 00-4 0zm8-2a2 2 0 11-4 0 2 2 0 014 0z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
{suggestion.id}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Selection indicator */}
|
||||||
|
<div className="ml-4 flex-shrink-0">
|
||||||
|
<div className={`w-6 h-6 rounded-full flex items-center justify-center transition-all duration-200 ${
|
||||||
|
isSelected
|
||||||
|
? 'bg-blue-500 text-white shadow-lg'
|
||||||
|
: 'bg-gray-200 text-gray-400'
|
||||||
|
}`}>
|
||||||
|
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Subtle bottom border for separation */}
|
||||||
|
{index < suggestions.length - 1 && (
|
||||||
|
<div className="absolute bottom-0 left-4 right-4 h-px bg-gray-200"></div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<input
|
<input
|
||||||
|
@ -256,49 +420,13 @@ export function TypeaheadInput({
|
||||||
|
|
||||||
{/* Loading indicator */}
|
{/* Loading indicator */}
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="absolute right-2 top-1/2 transform -translate-y-1/2">
|
<div className="absolute right-3 top-1/2 transform -translate-y-1/2 z-10">
|
||||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"></div>
|
<div className="animate-spin rounded-full h-4 w-4 border-2 border-blue-500 border-t-transparent"></div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Suggestions dropdown */}
|
{/* Portal-based suggestions dropdown */}
|
||||||
{showSuggestions && suggestions.length > 0 && (
|
<DropdownPortal />
|
||||||
<div
|
|
||||||
ref={suggestionsRef}
|
|
||||||
className="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto"
|
|
||||||
>
|
|
||||||
{suggestions.map((suggestion, index) => {
|
|
||||||
const isSelected = index === selectedIndex;
|
|
||||||
const label = suggestion.label || '';
|
|
||||||
const description = suggestion.description || '';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={suggestion.id}
|
|
||||||
className={`
|
|
||||||
px-3 py-2 cursor-pointer border-b border-gray-100 last:border-b-0
|
|
||||||
${isSelected
|
|
||||||
? 'bg-blue-100 text-blue-900'
|
|
||||||
: 'hover:bg-gray-50'
|
|
||||||
}
|
|
||||||
`}
|
|
||||||
onClick={() => handleSuggestionClick(suggestion)}
|
|
||||||
onMouseEnter={() => setSelectedIndex(index)}
|
|
||||||
>
|
|
||||||
<div className="font-medium text-sm">{label}</div>
|
|
||||||
{description && (
|
|
||||||
<div className="text-xs text-gray-600 mt-1 truncate">
|
|
||||||
{description}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="text-xs text-gray-400 mt-1">
|
|
||||||
ID: {suggestion.id}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
Loading…
Add table
Reference in a new issue