Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework combobox.jsx to functional component #3854

Draft
wants to merge 21 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
270 changes: 154 additions & 116 deletions client/components/combobox.jsx
Original file line number Diff line number Diff line change
@@ -1,128 +1,166 @@
const React = require('react');
const createClass = require('create-react-class');
const _ = require('lodash');
require('./combobox.less');
import React, { useState, useRef, useEffect } from 'react';
const _ = require('lodash');

const Combobox = createClass({
displayName : 'Combobox',
getDefaultProps : function() {
return {
className : '',
trigger : 'hover',
default : '',
placeholder : '',
autoSuggest : {
clearAutoSuggestOnClick : true,
suggestMethod : 'includes',
filterOn : [] // should allow as array to filter on multiple attributes, or even custom filter
},
};
},
getInitialState : function() {
return {
showDropdown : false,
value : '',
options : [...this.props.options],
inputFocused : false
const Combobox = ({ onSelect, onEntry, autoSuggest = { filterOn: ['data-value'], suggestMethod: 'includes', clearAutoSuggestOnClick: false }, ...props })=>{
const [inputValue, setInputValue] = useState(props.value || '');
const [showDropdown, setShowDropdown] = useState(false);
const [inputFocused, setInputFocused] = useState(false);
const [currentOption, setCurrentOption] = useState(-1);
const [filteredOptions, setFilteredOptions] = useState(React.Children.toArray(props.children));
const inputRef = useRef(null);
const optionRefs = useRef([]);
const componentRef = useRef(null);

useEffect(()=>{
const handleClickOutside = (evt)=>{
if(showDropdown && componentRef.current && !componentRef.current.contains(evt.target)) {
setShowDropdown(false);
}
};
},
componentDidMount : function() {
if(this.props.trigger == 'click')
document.addEventListener('click', this.handleClickOutside);
this.setState({
value : this.props.default
});
},
componentWillUnmount : function() {
if(this.props.trigger == 'click')
document.removeEventListener('click', this.handleClickOutside);
},
handleClickOutside : function(e){
// Close dropdown when clicked outside
if(this.refs.dropdown && !this.refs.dropdown.contains(e.target)) {
this.handleDropdown(false);

document.addEventListener('pointerdown', handleClickOutside);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is also adding a new event listener every time showDropdown changes.

If you want to add a listener once when the component first mounts, change the [showDropdown] to an empty array []

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If just change this to onMount [], it doesn't work. But it works if i remove the showDropdown condition in the handler:

const handleClickOutside = (evt)=>{
		console.log(componentRef.current, showDropdown)
		if(componentRef.current && !componentRef.current.contains(evt.target)) {
			setShowDropdown(false);
		}
	};

So that's what i'll do.

return ()=>{document.removeEventListener('pointerdown', handleClickOutside);};
}, [showDropdown]);

useEffect(()=>{
onSelect(inputValue);
// handleInputChange({ target: { value: inputValue } });
}, [inputValue]);
Copy link
Member

@calculuschild calculuschild Oct 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useEffect is not usually not needed for this type of case. Here, we trigger two renders, first when inputValue state changes, and then again when onSelect() changes some state of the parent metaDataEditor.

Instead of setting inputValue and then handling side effects later in useEffect, both setInputValue and calling onSelect() should happen together in a handler function, probably in your handleInputChange() function.


useEffect(()=>{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar comment here. Changing currentOption and the side effect of focusing the element should happen inside of a handler function, not inside useEffect.

See https://react.dev/learn/you-might-not-need-an-effect

if(currentOption >= 0 && optionRefs.current[currentOption]) {
optionRefs.current[currentOption].focus();
}
},
handleDropdown : function(show){
this.setState({
showDropdown : show,
inputFocused : this.props.autoSuggest.clearAutoSuggestOnClick ? show : false
});
},
handleInput : function(e){
e.persist();
this.setState({
value : e.target.value,
inputFocused : false
}, ()=>{
this.props.onEntry(e);
}, [currentOption]);

const handleInputChange = (evt)=>{
const newValue = evt.target.value;
setInputValue(newValue);
setCurrentOption(-1);

const filtered = React.Children.toArray(props.children).filter((option)=>{
return autoSuggest.filterOn.some((filterAttr)=>{
return option.props[filterAttr]?.toLowerCase().startsWith(newValue.toLowerCase());
});
});
},
handleSelect : function(e){
this.setState({
value : e.currentTarget.getAttribute('data-value')
}, ()=>{this.props.onSelect(this.state.value);});
;
},
renderTextInput : function(){
return (
<div className='dropdown-input item'
onMouseEnter={this.props.trigger == 'hover' ? ()=>{this.handleDropdown(true);} : undefined}
onClick= {this.props.trigger == 'click' ? ()=>{this.handleDropdown(true);} : undefined}>
<input
type='text'
onChange={(e)=>this.handleInput(e)}
value={this.state.value || ''}
placeholder={this.props.placeholder}
onBlur={(e)=>{
if(!e.target.checkValidity()){
this.setState({
value : this.props.default
}, ()=>this.props.onEntry(e));
}
}}
/>
</div>
);
},
renderDropdown : function(dropdownChildren){
if(!this.state.showDropdown) return null;
if(this.props.autoSuggest && !this.state.inputFocused){
const suggestMethod = this.props.autoSuggest.suggestMethod;
const filterOn = _.isString(this.props.autoSuggest.filterOn) ? [this.props.autoSuggest.filterOn] : this.props.autoSuggest.filterOn;
const filteredArrays = filterOn.map((attr)=>{
const children = dropdownChildren.filter((item)=>{
if(suggestMethod === 'includes'){
return item.props[attr]?.toLowerCase().includes(this.state.value.toLowerCase());
} else if(suggestMethod === 'startsWith'){
return item.props[attr]?.toLowerCase().startsWith(this.state.value.toLowerCase());
}
setFilteredOptions(filtered);
};

/* eslint-disable brace-style */

// Handle keyboard navigation
const handleKeyDown = (evt)=>{
const modifiers = ['Meta', 'Shift', 'Alt', 'Control', 'Tab'];
if(inputFocused || (currentOption >= 0)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are already focused, why do we need to keep setting focus for the different keys below?

const optionsLength = filteredOptions.length;

if((evt.key === ' ') && (inputValue === '')){
evt.preventDefault();
setShowDropdown(!showDropdown);
}

// ArrowDown moves to the next option
else if(evt.key === 'ArrowDown') {
evt.preventDefault();
if((currentOption === -1) && (showDropdown === false)){
setShowDropdown(true);
};
const nextIndex = currentOption + 1;
if(nextIndex < optionsLength) {
setCurrentOption(nextIndex);
} else {
setCurrentOption(0);
}
}

// ArrowUp moves to the previous option
else if(evt.key === 'ArrowUp') {
evt.preventDefault();
const prevIndex = currentOption - 1;
if(prevIndex >= 0) {
setCurrentOption(prevIndex);
} else {
setCurrentOption(-1);
inputRef.current.focus();
}
}

// Escape key closes the dropdown
else if(evt.key === 'Escape'){
setCurrentOption(-1);
inputRef.current.focus();
setShowDropdown(false);
}

// Backspace key while menu is open still deletes characters in input
else if((evt.key === 'Backspace') && showDropdown){
inputRef.current.focus();
}

else if((evt.key === 'Tab')){
setCurrentOption(-1);
setShowDropdown(false);
}

// Prevent modifier keys from triggering dropdown (example, shift+tab or tab to move focus)
else if(!modifiers.includes(evt.key)) {
setShowDropdown(true);
}
}


};
/* eslint-enable brace-style */

const handleOptionClick = (evt)=>{
setInputValue(evt.currentTarget.dataset.value);
};

// Render the filtered options
const renderChildren = ()=>{
optionRefs.current = []; // Reset refs for each render cycle

if(filteredOptions.length < 1){
return <span className='no-matches'>no matches</span>;
} else {
// Add refs and event handlers for filtered options
return filteredOptions.map((child, i)=>{
return React.cloneElement(child, {
onClick : (evt)=>handleOptionClick(evt),
onKeyDown : (evt)=>handleKeyDown(evt),
ref : (node)=>{ optionRefs.current[i] = node; },
tabIndex : -1,
});
return children;
});
dropdownChildren = _.uniq(filteredArrays.flat(1));

}
};

return (
<div className='dropdown-options'>
{dropdownChildren}
</div>
);
},
render : function () {
const dropdownChildren = this.state.options.map((child, i)=>{
const clone = React.cloneElement(child, { onClick: (e)=>this.handleSelect(e) });
return clone;
});
return (
<div className={`dropdown-container ${this.props.className}`}
ref='dropdown'
onMouseLeave={this.props.trigger == 'hover' ? ()=>{this.handleDropdown(false);} : undefined}>
{this.renderTextInput()}
{this.renderDropdown(dropdownChildren)}
return (
<div className='combobox' ref={componentRef}>
<input
type='text'
ref={inputRef}
value={inputValue}
placeholder={props.placeholder}
onClick={()=>{
setShowDropdown(true);
setInputFocused(true);
autoSuggest.clearAutoSuggestOnClick && setInputValue('');
}}
onChange={(evt)=>handleInputChange(evt)}
onKeyDown={(evt)=>handleKeyDown(evt)}
onFocus={()=>{setInputFocused(true);}}
onBlur={()=>{
setInputFocused(false);
}}
/>
<div className={`dropdown-options${showDropdown ? ' open' : ''}`}>
{renderChildren()}
</div>
);
}
});
</div>
);
};

module.exports = Combobox;
51 changes: 35 additions & 16 deletions client/components/combobox.less
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
.dropdown-container {
position:relative;
input {
width: 100%;
}
.dropdown-options {
position:absolute;
.combobox {
position: relative;
width: max(200px, fit-content);
input {
display: block;
width: 100%;
}
.dropdown-options {
display: none;
position:absolute;
background-color: white;
z-index: 100;
z-index: 1000;
width: 100%;
border: 1px solid gray;
overflow-y: auto;
max-height: 200px;
padding: 3px;

&::-webkit-scrollbar {
width: 14px;
Expand All @@ -23,16 +27,26 @@
border-radius: 10px;
border: 3px solid #ffffff;
}

.item {
position:relative;
&.open {
display: unset;
}
> * {
all: unset;
display: block;
width: 100%;
position:relative;
font-size: 11px;
font-family: Open Sans;
padding: 5px;
cursor: default;
margin: 0 3px;
box-sizing: border-box;
margin: 0;
//border-bottom: 1px solid darkgray;
&:hover {
background-color: rgb(223, 221, 221);
}
&:focus {
filter: brightness(120%);
background-color: rgb(163, 163, 163);
}
Expand All @@ -43,8 +57,13 @@
font-style:italic;
font-size: 9px;
}
}

}

}
&.no-matches {
width:100%;
text-align: center;
color: rgb(124, 124, 124);
font-style:italic;
font-size: 9px;
}
}
}
}
Loading