Skip to content

Commit

Permalink
Convert LanguageDropdownMenu to functional component (#33704)
Browse files Browse the repository at this point in the history
  • Loading branch information
ClearlyClaire authored Jan 24, 2025
1 parent a1d9c3f commit 9a0166c
Showing 1 changed file with 118 additions and 152 deletions.
270 changes: 118 additions & 152 deletions app/javascript/mastodon/features/compose/components/language_dropdown.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import PropTypes from 'prop-types';
import { useCallback, useRef, useState, useEffect, PureComponent } from 'react';
import { useCallback, useRef, useState, useEffect, useMemo } from 'react';

import { useIntl, defineMessages } from 'react-intl';

Expand Down Expand Up @@ -30,109 +30,37 @@ const messages = defineMessages({

const listenerOptions = supportsPassiveEvents ? { passive: true, capture: true } : true;

class LanguageDropdownMenu extends PureComponent {

static propTypes = {
value: PropTypes.string.isRequired,
guess: PropTypes.string,
frequentlyUsedLanguages: PropTypes.arrayOf(PropTypes.string).isRequired,
onClose: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
languages: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.string)),
intl: PropTypes.object,
};

static defaultProps = {
languages: preloadedLanguages,
};

state = {
searchValue: '',
};

handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
e.stopPropagation();
}
};

componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, { capture: true });
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);

// Because of https://github.com/react-bootstrap/react-bootstrap/issues/2614 we need
// to wait for a frame before focusing
requestAnimationFrame(() => {
if (this.node) {
const element = this.node.querySelector('input[type="search"]');
if (element) element.focus();
}
});
}

componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, { capture: true });
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}

setRef = c => {
this.node = c;
};

setListRef = c => {
this.listNode = c;
};

handleSearchChange = ({ target }) => {
this.setState({ searchValue: target.value });
};

search () {
const { languages, value, frequentlyUsedLanguages, guess } = this.props;
const { searchValue } = this.state;

if (searchValue === '') {
return [...languages].sort((a, b) => {

if (guess && a[0] === guess) { // Push guessed language higher than current selection
return -1;
} else if (guess && b[0] === guess) {
return 1;
} else if (a[0] === value) { // Push current selection to the top of the list
return -1;
} else if (b[0] === value) {
return 1;
} else {
// Sort according to frequently used languages
const getFrequentlyUsedLanguages = createSelector([
state => state.getIn(['settings', 'frequentlyUsedLanguages'], ImmutableMap()),
], languageCounters => (
languageCounters.keySeq()
.sort((a, b) => languageCounters.get(a) - languageCounters.get(b))
.reverse()
.toArray()
));

const indexOfA = frequentlyUsedLanguages.indexOf(a[0]);
const indexOfB = frequentlyUsedLanguages.indexOf(b[0]);
const LanguageDropdownMenu = ({ value, guess, onClose, onChange, languages = preloadedLanguages, intl }) => {
const [searchValue, setSearchValue] = useState('');
const nodeRef = useRef(null);
const listNodeRef = useRef(null);

return ((indexOfA > -1 ? indexOfA : Infinity) - (indexOfB > -1 ? indexOfB : Infinity));
}
});
}
const frequentlyUsedLanguages = useAppSelector(getFrequentlyUsedLanguages);

return fuzzysort.go(searchValue, languages, {
keys: ['0', '1', '2'],
limit: 5,
threshold: -10000,
}).map(result => result.obj);
}
const handleSearchChange = useCallback(({ target }) => {
setSearchValue(target.value);
}, [setSearchValue]);

handleClick = e => {
const handleClick = useCallback((e) => {
const value = e.currentTarget.getAttribute('data-index');

e.preventDefault();

this.props.onClose();
this.props.onChange(value);
};
onClose();
onChange(value);
}, [onClose, onChange]);

handleKeyDown = e => {
const { onClose } = this.props;
const index = Array.from(this.listNode.childNodes).findIndex(node => node === e.currentTarget);
const handleKeyDown = useCallback(e => {
const index = Array.from(listNodeRef.current.childNodes).findIndex(node => node === e.currentTarget);

let element = null;

Expand All @@ -142,26 +70,26 @@ class LanguageDropdownMenu extends PureComponent {
break;
case ' ':
case 'Enter':
this.handleClick(e);
handleClick(e);
break;
case 'ArrowDown':
element = this.listNode.childNodes[index + 1] || this.listNode.firstChild;
element = listNodeRef.current.childNodes[index + 1] || listNodeRef.current.firstChild;
break;
case 'ArrowUp':
element = this.listNode.childNodes[index - 1] || this.listNode.lastChild;
element = listNodeRef.current.childNodes[index - 1] || listNodeRef.current.lastChild;
break;
case 'Tab':
if (e.shiftKey) {
element = this.listNode.childNodes[index - 1] || this.listNode.lastChild;
element = listNodeRef.current.childNodes[index - 1] || listNodeRef.current.lastChild;
} else {
element = this.listNode.childNodes[index + 1] || this.listNode.firstChild;
element = listNodeRef.current.childNodes[index + 1] || listNodeRef.current.firstChild;
}
break;
case 'Home':
element = this.listNode.firstChild;
element = listNodeRef.current.firstChild;
break;
case 'End':
element = this.listNode.lastChild;
element = listNodeRef.current.lastChild;
break;
}

Expand All @@ -170,18 +98,15 @@ class LanguageDropdownMenu extends PureComponent {
e.preventDefault();
e.stopPropagation();
}
};

handleSearchKeyDown = e => {
const { onChange, onClose } = this.props;
const { searchValue } = this.state;
}, [onClose, handleClick]);

const handleSearchKeyDown = useCallback(e => {
let element = null;

switch(e.key) {
case 'Tab':
case 'ArrowDown':
element = this.listNode.firstChild;
element = listNodeRef.current.firstChild;

if (element) {
element.focus();
Expand All @@ -191,7 +116,7 @@ class LanguageDropdownMenu extends PureComponent {

break;
case 'Enter':
element = this.listNode.firstChild;
element = listNodeRef.current.firstChild;

if (element) {
onChange(element.getAttribute('data-index'));
Expand All @@ -206,52 +131,96 @@ class LanguageDropdownMenu extends PureComponent {

break;
}
};
}, [onChange, onClose, searchValue]);

handleClear = () => {
this.setState({ searchValue: '' });
};
const handleClear = useCallback(() => {
setSearchValue('');
}, [setSearchValue]);

renderItem = lang => {
const { value } = this.props;
const isSearching = searchValue !== '';

return (
<div key={lang[0]} role='option' tabIndex={0} data-index={lang[0]} className={classNames('language-dropdown__dropdown__results__item', { active: lang[0] === value })} aria-selected={lang[0] === value} onClick={this.handleClick} onKeyDown={this.handleKeyDown}>
<span className='language-dropdown__dropdown__results__item__native-name' lang={lang[0]}>{lang[2]}</span> <span className='language-dropdown__dropdown__results__item__common-name'>({lang[1]})</span>
</div>
);
};

render () {
const { intl } = this.props;
const { searchValue } = this.state;
const isSearching = searchValue !== '';
const results = this.search();

return (
<div ref={this.setRef}>
<div className='emoji-mart-search'>
<input type='search' value={searchValue} onChange={this.handleSearchChange} onKeyDown={this.handleSearchKeyDown} placeholder={intl.formatMessage(messages.search)} />
<button type='button' className='emoji-mart-search-icon' disabled={!isSearching} aria-label={intl.formatMessage(messages.clear)} onClick={this.handleClear}><Icon icon={!isSearching ? SearchIcon : CancelIcon} /></button>
</div>

<div className='language-dropdown__dropdown__results emoji-mart-scroll' role='listbox' ref={this.setListRef}>
{results.map(this.renderItem)}
</div>
useEffect(() => {
const handleDocumentClick = (e) => {
if (nodeRef.current && !nodeRef.current.contains(e.target)) {
onClose();
e.stopPropagation();
}
};

document.addEventListener('click', handleDocumentClick, { capture: true });
document.addEventListener('touchend', handleDocumentClick, listenerOptions);

// Because of https://github.com/react-bootstrap/react-bootstrap/issues/2614 we need
// to wait for a frame before focusing
requestAnimationFrame(() => {
if (nodeRef.current) {
const element = nodeRef.current.querySelector('input[type="search"]');
if (element) element.focus();
}
});

return () => {
document.removeEventListener('click', handleDocumentClick, { capture: true });
document.removeEventListener('touchend', handleDocumentClick, listenerOptions);
};
}, [onClose]);

const results = useMemo(() => {
if (searchValue === '') {
return [...languages].sort((a, b) => {

if (guess && a[0] === guess) { // Push guessed language higher than current selection
return -1;
} else if (guess && b[0] === guess) {
return 1;
} else if (a[0] === value) { // Push current selection to the top of the list
return -1;
} else if (b[0] === value) {
return 1;
} else {
// Sort according to frequently used languages

const indexOfA = frequentlyUsedLanguages.indexOf(a[0]);
const indexOfB = frequentlyUsedLanguages.indexOf(b[0]);

return ((indexOfA > -1 ? indexOfA : Infinity) - (indexOfB > -1 ? indexOfB : Infinity));
}
});
}

return fuzzysort.go(searchValue, languages, {
keys: ['0', '1', '2'],
limit: 5,
threshold: -10000,
}).map(result => result.obj);
}, [searchValue, languages, guess, frequentlyUsedLanguages, value]);

return (
<div ref={nodeRef}>
<div className='emoji-mart-search'>
<input type='search' value={searchValue} onChange={handleSearchChange} onKeyDown={handleSearchKeyDown} placeholder={intl.formatMessage(messages.search)} />
<button type='button' className='emoji-mart-search-icon' disabled={!isSearching} aria-label={intl.formatMessage(messages.clear)} onClick={handleClear}><Icon icon={!isSearching ? SearchIcon : CancelIcon} /></button>
</div>
);
}

}
<div className='language-dropdown__dropdown__results emoji-mart-scroll' role='listbox' ref={listNodeRef}>
{results.map((lang) => (
<div key={lang[0]} role='option' tabIndex={0} data-index={lang[0]} className={classNames('language-dropdown__dropdown__results__item', { active: lang[0] === value })} aria-selected={lang[0] === value} onClick={handleClick} onKeyDown={handleKeyDown}>
<span className='language-dropdown__dropdown__results__item__native-name' lang={lang[0]}>{lang[2]}</span> <span className='language-dropdown__dropdown__results__item__common-name'>({lang[1]})</span>
</div>
))}
</div>
</div>
);
};

const getFrequentlyUsedLanguages = createSelector([
state => state.getIn(['settings', 'frequentlyUsedLanguages'], ImmutableMap()),
], languageCounters => (
languageCounters.keySeq()
.sort((a, b) => languageCounters.get(a) - languageCounters.get(b))
.reverse()
.toArray()
));
LanguageDropdownMenu.propTypes = {
value: PropTypes.string.isRequired,
guess: PropTypes.string,
onClose: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
languages: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.string)),
intl: PropTypes.object,
};

export const LanguageDropdown = () => {
const [open, setOpen] = useState(false);
Expand All @@ -263,7 +232,6 @@ export const LanguageDropdown = () => {
const intl = useIntl();

const dispatch = useAppDispatch();
const frequentlyUsedLanguages = useAppSelector(getFrequentlyUsedLanguages);
const value = useAppSelector((state) => state.compose.get('language'));
const text = useAppSelector((state) => state.compose.get('text'));

Expand Down Expand Up @@ -319,10 +287,8 @@ export const LanguageDropdown = () => {
<LanguageDropdownMenu
value={value}
guess={guess}
frequentlyUsedLanguages={frequentlyUsedLanguages}
onClose={handleClose}
onChange={handleChange}
intl={intl}
/>
</div>
</div>
Expand Down

0 comments on commit 9a0166c

Please sign in to comment.