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 all 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
292 changes: 175 additions & 117 deletions client/components/combobox.jsx
Original file line number Diff line number Diff line change
@@ -1,128 +1,186 @@
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
};
},
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);
const [inputValue, setInputValue] = useState(props.value || '');
const Combobox = (props)=>{
props = {
id : null,
onSelect : ()=>{},
multiSelect : false,
autoSuggest : {
filterOn : ['data-value'],
suggestMethod : 'includes',
clearAutoSuggestOnClick : false
},
...props
};

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(()=>{
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);};
}, []);

useEffect(()=>{
props.onSelect(inputValue);
// handleInputChange({ target: { value: inputValue } });
}, [inputValue]);

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 handleClickOutside = (evt)=>{
console.log(componentRef.current, showDropdown)
if(componentRef.current && !componentRef.current.contains(evt.target)) {
setShowDropdown(false);
}
};

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

const filtered = React.Children.toArray(props.children).filter((option)=>{
return props.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 === '' || (inputRef.current.selectionStart === 0 && inputRef.current.selectionEnd === inputValue.length))){
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,
role : 'option'
});
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 id={props.id} className='combobox' ref={componentRef}>
<input
id={`${props.id}-input`}
type='text'
role='combobox'
aria-controls={`${props.id}-menu`}
aria-expanded={showDropdown ? true : false}
ref={inputRef}
value={inputValue}
placeholder={props.placeholder}
onClick={()=>{
setShowDropdown(true);
setInputFocused(true);
props.autoSuggest.clearAutoSuggestOnClick && setInputValue([]);
}}
onChange={(evt)=>handleInputChange(evt)}
onKeyDown={(evt)=>handleKeyDown(evt)}
onFocus={()=>{setInputFocused(true);}}
onBlur={()=>{
setInputFocused(false);
}}
/>
<button tabIndex={-1} onClick={()=>setShowDropdown(!showDropdown)} aria-controls={`${props.id}-menu`} aria-expanded={showDropdown ? true : false}><i className='fas fa-caret-down' /></button>
<div id={`${props.id}-menu`} className={`dropdown-options${showDropdown ? ' open' : ''}`} role='listbox'>
{renderChildren()}
</div>
);
}
});
</div>
);
};

module.exports = Combobox;
Loading