@mongodb-js/mongodb-ui-components
Version:
A collection of frequently used functional UI components found on mongodb properties
73 lines (63 loc) • 1.72 kB
JavaScript
'use strict';
import {h, Component} from 'preact';
import { searchIcon } from '../nav-icons';
export default class SearchInput extends Component {
constructor(props) {
super(props);
this.state = { isOpen: false };
this.onBtnPress = this.onBtnPress.bind(this);
this.open = this.toggle.bind(this, true);
this.close = this.toggle.bind(this, false);
}
componentDidMount() {
this.links = document.querySelector('.m-nav-top-links');
}
onSearch() {
const value = encodeURIComponent(this.inputEl.value);
window.location.href = `${this.props.searchUrl}${value}`;
}
onBtnPress(e) {
e.preventDefault();
e.stopPropagation();
if (!this.state.isOpen) {
this.inputEl.focus();
this.open();
} else if (!this.inputEl.value) {
this.close();
} else {
this.onSearch();
}
}
toggle(isOpen) {
this.setState({ isOpen });
this.links.classList.toggle('m-nav-top-links-hidden', isOpen);
}
render() {
const { isOpen } = this.state;
return h(
'span',
{ className: 'm-nav-search m-nav-flex-x' },
h('input', {
className: `m-nav-search-input ${isOpen ? 'm-nav-search-input-open' : ''}`,
onBlur: () => {
setTimeout(this.close, 50);
},
onKeyUp: e => {
if (e.keyCode === 13) this.onSearch();
},
ref: c => {
this.inputEl = c;
},
placeholder: 'search' }),
h(
'button',
{
className: `m-nav-flex-xy m-nav-search-btn ${isOpen ? 'm-nav-search-btn-active' : ''}`,
onClick: this.onBtnPress,
onTouchStart: this.onBtnPress
},
searchIcon
)
);
}
}