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

Feature/search results page #2

Merged
merged 6 commits into from
Apr 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions bin/record-http-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ const recordConfig = {
baseURL: process.env.REACT_APP_NPMS_IO_API_BASE_URL
},
requests: [
"/v2/search?q=react",
"/v2/search?q=%40angular",
{
url: "/v2/search/suggestions?q=react",
match: "/v2/search/suggestions\\?q=react(\\.*)"
Expand Down
2 changes: 2 additions & 0 deletions src/Routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import MainLayout from "./components/MainLayout";
// Containers that will be loaded by the router
import HomeContainer from "./containers/HomeContainer";
import PackageContainer from "./containers/PackageContainer";
import SearchResultsContainer from "./containers/SearchResultsContainer";

/**
* Compiles a render method to pass to a Route that will redirect to "latest" version
Expand Down Expand Up @@ -53,6 +54,7 @@ const Routes = () => (
path="/package/:name"
render={compileRedirectToLatest(false)}
/>
<Route exact path="/search" component={SearchResultsContainer} />
</Switch>
</MainLayout>
</HashRouter>
Expand Down
16 changes: 13 additions & 3 deletions src/components/Gravatar.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,22 @@ import Avatar from "material-ui/Avatar";

import md5 from "js-md5";

const Gravatar = ({ email, ...props }) => (
<Avatar src={`https://s.gravatar.com/avatar/${md5(email)}`} {...props} />
const Gravatar = ({ email, size, ...props }) => (
<Avatar
src={`https://s.gravatar.com/avatar/${md5(email)}${
size ? `?s=${size}` : ""
}`}
{...props}
/>
);

Gravatar.propTypes = {
email: PropTypes.string.isRequired
email: PropTypes.string.isRequired,
size: PropTypes.number
};

Gravatar.defaultProps = {
size: undefined
};

export default Gravatar;
68 changes: 68 additions & 0 deletions src/components/KeywordsList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/* eslint-disable react/no-array-index-key */
import React from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import { withStyles } from "material-ui/styles";

import LocalOfferIcon from "@material-ui/icons/LocalOffer";

const styles = {
root: {
margin: "5px 0",
"& > svg": {
fill: "grey",
width: "15px",
height: "15px",
marginRight: "5px",
marginBottom: "-4px"
},
"& > a": {
fontSize: "0.9rem",
color: "grey",
textDecoration: "none"
},
"& > a:hover": {
textDecoration: "underline"
},
// style separating "," to avoid conditional in loops inside render
"& > a:after": {
content: "','",
display: "inline-block", // avoid underline on hover
textDecoration: "none",
paddingRight: "3px"
},
"& > a:last-child:after": {
content: "''"
}
}
};

const KeywordsList = ({ keywords, classes }) => {
if (keywords && keywords.length > 0) {
return (
<div className={classes.root}>
<LocalOfferIcon />
{keywords.map((keyword, index) => (
<Link
to={`/search?q=keywords:"${keyword}"`}
key={`${keyword}-${index}`}
>
{keyword}
</Link>
))}
</div>
);
}
return null;
};

KeywordsList.propTypes = {
classes: PropTypes.object.isRequired,
keywords: PropTypes.array
};

KeywordsList.defaultProps = {
keywords: []
};

export default withStyles(styles)(KeywordsList);
10 changes: 9 additions & 1 deletion src/components/Package/Package.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Paper from "material-ui/Paper";
import Typography from "material-ui/Typography";

import Title from "./Title";
import KeywordsList from "../KeywordsList";
import Readme from "./Readme";
import VersionsTab from "./VersionsTab";
import DependenciesTab from "./DependenciesTab";
Expand Down Expand Up @@ -44,7 +45,9 @@ const styles = theme => ({
},
areaHeader: {
gridArea: "header",
paddingLeft: 0
paddingLeft: 0,
paddingBottom: 0,
marginBottom: 0
},
areaAside: {
gridArea: "aside"
Expand Down Expand Up @@ -99,6 +102,11 @@ const Package = ({
packageInfos.versions[version].description) ||
"\u00A0"}
</Typography>
{packageInfos &&
packageInfos.versions[version] &&
packageInfos.versions[version].keywords && (
<KeywordsList keywords={packageInfos.versions[version].keywords} />
)}
</Fragment>
</header>
<aside className={classes.areaAside}>
Expand Down
136 changes: 97 additions & 39 deletions src/components/Search.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ const styles = theme => ({
fontSize: "1.1rem",
fontWeight: 500,
fontFamily: `"Roboto", "Arial", sans-serif`,
borderRadius: 5,
outline: "none"
borderRadius: "5px",
outline: "none",
"-webkit-appearance": "none" // remove weird border radius on iOs devices
},
itemsWrapper: {
padding: 0,
Expand All @@ -50,6 +51,7 @@ const styles = theme => ({
// maxHeight: 450, // this style is set inline based on props.isMobile
},
item: {
listStyle: "none",
padding: "8px 16px",
borderBottom: "1px solid #ececec",
cursor: "pointer"
Expand Down Expand Up @@ -87,6 +89,22 @@ const styles = theme => ({
});

class Search extends Component {
/**
* That way, state.inputValue can have its own internal state and sometimes,
* when props.searchQuery changes from the parent, it can change with it.
*
* Track props.searchQuery and update our internal state.searchQuery
* that way, if we have state.searchQuery in componentDidUpdate,
* we need to update the state.inputValue
*/
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.searchQuery !== prevState.searchQuery) {
return {
searchQuery: nextProps.searchQuery
};
}
return null; // the new props do not require state updates
}
constructor(props) {
super(props);
this.state = { items: [], inputValue: "" };
Expand All @@ -95,9 +113,21 @@ class Search extends Component {
componentDidMount() {
window.addEventListener("touchstart", this.blurInputOnTouchOut, false);
}
componentDidUpdate() {
// update state.inputValue when props.searchQuery changes (see getDerivedStateFromProps above)
if (this.state.searchQuery !== null) {
this.updateInputeValueWithSearchQuery();
}
}
componentWillUnmount() {
window.removeEventListener("touchstart", this.blurInputOnTouchOut);
}
updateInputeValueWithSearchQuery() {
this.setState({
inputValue: this.state.searchQuery,
searchQuery: null
});
}
/**
* On iOs, clicking out doesn't blur the search field (neither close the search dropdown)
* This fixes it
Expand Down Expand Up @@ -131,7 +161,14 @@ class Search extends Component {
300
);
render() {
const { goToPackage, windowInfos, classes, theme, isMobile } = this.props;
const {
goToPackage,
goToSearchResults,
windowInfos,
classes,
theme,
isMobile
} = this.props;
const { inputValue, items, state } = this.state;
return (
<Downshift
Expand All @@ -150,52 +187,72 @@ class Search extends Component {
getInputProps,
getItemProps,
highlightedIndex,
isOpen
isOpen,
closeMenu
}) => (
<div className={classes.rootWrapper}>
<input
data-testid="search-input"
ref={node => {
this.inputEl = node;
}}
className={classes.input}
{...getInputProps({
value: inputValue,
placeholder: "Search packages",
onChange: event => {
const value = event.target.value;
// the API only answer to queries with 2 chars or more
if (value.length > 1) {
this.setState(
{
{/* To have a "Search" button on mobile virtual keyboards */}
<form action=".">
<input
data-testid="search-input"
ref={node => {
this.inputEl = node;
}}
className={classes.input}
{...getInputProps({
type: "search",
value: inputValue,
placeholder: "Search packages",
onKeyDown: event => {
// when type enter inside text input : go to search results and close menu
if (event.key === "Enter" && highlightedIndex === null) {
event.preventDefault(); // prevent submitting the form
// only go to search results if any value is set
if (event.target.value !== "") {
if (isMobile) {
event.target.blur();
}
closeMenu();
goToSearchResults(event.target.value);
}
}
},
onChange: event => {
const value = event.target.value;
// the API only answer to queries with 2 chars or more
if (value.length > 1) {
this.setState(
{
inputValue: value, // keep track of the value of the input
state: "loading"
},
() => this.debouncedSearch(value)
);
} else {
this.setState({
inputValue: value, // keep track of the value of the input
state: "loading"
},
() => this.debouncedSearch(value)
);
} else {
this.setState({
inputValue: value, // keep track of the value of the input
items: []
});
}
},
onFocus: () => {
// on mobile, the keyboard will pop up. Give it some space
if (windowInfos.windowWidth < theme.breakpoints.values.sm) {
setTimeout(() => {
animatedScrollTo(document.body, 75, 400);
}, 75);
items: []
});
}
},
onFocus: () => {
// on mobile, the keyboard will pop up. Give it some space
if (windowInfos.windowWidth < theme.breakpoints.values.sm) {
setTimeout(() => {
animatedScrollTo(document.body, 75, 400);
}, 75);
}
}
}
})}
/>
})}
/>
</form>
{["loading", "error"].includes(state) && (
<ul className={classes.itemsWrapper} data-type="search-results">
<li
data-testid="search-loading-indicator"
className={classes.item}
style={{
marginTop: "20px",
backgroundColor: "white"
}}
>
Expand Down Expand Up @@ -272,6 +329,7 @@ Search.propTypes = {
isMobile: PropTypes.bool.isRequired,
fetchInfos: PropTypes.func.isRequired,
goToPackage: PropTypes.func.isRequired,
goToSearchResults: PropTypes.func.isRequired,
windowInfos: PropTypes.object.isRequired
};

Expand Down
Loading