Open platform to collect and prioritize feedback
enhancement: home page improvements (#416)
Guilherme Oenning2b81fd76e070
diff --git a/app/handlers/idea.go b/app/handlers/idea.goindex 16c638f53..1971b6cb9 100644--- a/app/handlers/idea.go+++ b/app/handlers/idea.go@@ -15,6 +15,7 @@ func Index() web.HandlerFunc {ideas, err := c.Services().Ideas.Search(c.QueryParam("q"),c.QueryParam("f"),+ c.QueryParam("l"),c.QueryParamAsArray("t"),)if err != nil {@@ -55,6 +56,7 @@ func SearchIdeas() web.HandlerFunc {ideas, err := c.Services().Ideas.Search(c.QueryParam("q"),c.QueryParam("f"),+ c.QueryParam("l"),c.QueryParamAsArray("t"),)if err != nil {diff --git a/app/storage/inmemory/idea.go b/app/storage/inmemory/idea.goindex 4ca492bc6..17ed43242 100644--- a/app/storage/inmemory/idea.go+++ b/app/storage/inmemory/idea.go@@ -90,7 +90,7 @@ func (s *IdeaStorage) CountPerStatus() (map[int]int, error) {}// Search existing ideas based on input-func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Idea, error) {+func (s *IdeaStorage) Search(query, filter, limit string, tags []string) ([]*models.Idea, error) {return s.ideas, nil}diff --git a/app/storage/postgres/common.go b/app/storage/postgres/common.goindex 1f7dc6856..d8c7bc92d 100644--- a/app/storage/postgres/common.go+++ b/app/storage/postgres/common.go@@ -16,8 +16,11 @@ func ToTSQuery(input string) string {return strings.Join(strings.Fields(input), "|")}-func getFilterData(filter string) ([]int, string) {- var sort string+func getFilterData(filter string) (string, []int, string) {+ var (+ condition string+ sort string+ )statuses := []int{models.IdeaOpen,models.IdeaStarted,@@ -26,6 +29,9 @@ func getFilterData(filter string) ([]int, string) {switch filter {case "recent":sort = "id"+ case "my-votes":+ condition = "AND viewer_supported = true"+ sort = "id"case "most-wanted":sort = "supporters"case "most-discussed":@@ -56,5 +62,5 @@ func getFilterData(filter string) ([]int, string) {default:sort = "((COALESCE(recent_supporters, 0)*5 + COALESCE(recent_comments, 0) *3)-1) / pow((EXTRACT(EPOCH FROM current_timestamp - created_on)/3600) + 2, 1.4)"}- return statuses, sort+ return condition, statuses, sort}diff --git a/app/storage/postgres/idea.go b/app/storage/postgres/idea.goindex eac9eb380..2ef63b9d1 100644--- a/app/storage/postgres/idea.go+++ b/app/storage/postgres/idea.go@@ -250,7 +250,7 @@ func (s *IdeaStorage) GetByNumber(number int) (*models.Idea, error) {// GetAll returns all tenant ideasfunc (s *IdeaStorage) GetAll() ([]*models.Idea, error) {- ideas, err := s.Search("", "all", []string{})+ ideas, err := s.Search("", "all", "all", []string{})if err != nil {return nil, errors.Wrap(err, "failed to get all ideas")}@@ -272,9 +272,15 @@ func (s *IdeaStorage) CountPerStatus() (map[int]int, error) {}// Search existing ideas based on input-func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Idea, error) {+func (s *IdeaStorage) Search(query, filter, limit string, tags []string) ([]*models.Idea, error) {innerQuery := s.getIdeaQuery("i.tenant_id = $1 AND i.status = ANY($2)")+ if limit != "all" {+ if _, err := strconv.Atoi(limit); err != nil {+ limit = "30"+ }+ }+var (ideas []*dbIdeaerr error@@ -283,9 +289,10 @@ func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.IdescoreField := "ts_rank(setweight(to_tsvector(title), 'A') || setweight(to_tsvector(description), 'B'), to_tsquery('english', $3)) + similarity(title, $4) + similarity(description, $4)"sql := fmt.Sprintf(`SELECT * FROM (%s) AS q- WHERE %s > 0.1+ WHERE %s > 0.1ORDER BY %s DESC- `, innerQuery, scoreField, scoreField)+ LIMIT %s+ `, innerQuery, scoreField, scoreField, limit)err = s.trx.Select(&ideas, sql, s.tenant.ID, pq.Array([]int{models.IdeaOpen,models.IdeaStarted,@@ -294,12 +301,13 @@ func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Idemodels.IdeaDeclined,}), ToTSQuery(query), query)} else {- statuses, sort := getFilterData(filter)+ condition, statuses, sort := getFilterData(filter)sql := fmt.Sprintf(`SELECT * FROM (%s) AS q- WHERE tags @> $3+ WHERE tags @> $3 %sORDER BY %s DESC- `, innerQuery, sort)+ LIMIT %s+ `, innerQuery, condition, sort, limit)err = s.trx.Select(&ideas, sql, s.tenant.ID, pq.Array(statuses), pq.Array(tags))}diff --git a/app/storage/postgres/idea_test.go b/app/storage/postgres/idea_test.goindex f1707c614..535fed36c 100644--- a/app/storage/postgres/idea_test.go+++ b/app/storage/postgres/idea_test.go@@ -41,10 +41,14 @@ func TestIdeaStorage_GetAll(t *testing.T) {Expect(dbIdeas[1].TotalSupporters).Equals(0)Expect(dbIdeas[1].Status).Equals(models.IdeaStarted)- dbIdeas, err = ideas.Search("twitter", "trending", []string{})+ dbIdeas, err = ideas.Search("twitter", "trending", "10", []string{})Expect(err).IsNil()Expect(dbIdeas).HasLen(1)Expect(dbIdeas[0].Slug).Equals("add-twitter-integration")++ dbIdeas, err = ideas.Search("twitter", "trending", "0", []string{})+ Expect(err).IsNil()+ Expect(dbIdeas).HasLen(0)}func TestIdeaStorage_AddAndGet(t *testing.T) {diff --git a/app/storage/storage.go b/app/storage/storage.goindex 621ec4ac6..582923c7c 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -19,7 +19,7 @@ type Idea interface {GetBySlug(slug string) (*models.Idea, error)GetByNumber(number int) (*models.Idea, error)GetCommentsByIdea(idea *models.Idea) ([]*models.Comment, error)- Search(query, filter string, tags []string) ([]*models.Idea, error)+ Search(query, filter, limit string, tags []string) ([]*models.Idea, error)GetAll() ([]*models.Idea, error)CountPerStatus() (map[int]int, error)Add(title, description string) (*models.Idea, error)diff --git a/public/pages/Home/Home.page.tsx b/public/pages/Home/Home.page.tsxindex 7f3b08300..bb5148024 100644--- a/public/pages/Home/Home.page.tsx+++ b/public/pages/Home/Home.page.tsx@@ -5,6 +5,7 @@ import { Idea, Tag, IdeaStatus, CurrentUser, Tenant } from "@fider/models";import { MultiLineText } from "@fider/components";import { IdeaInput, ListIdeas, IdeasContainer } from "./";import { page, actions } from "@fider/services";+import { SimilarIdeas } from "./components/SimilarIdeas";export interface HomePageProps {user?: CurrentUser;@@ -54,7 +55,7 @@ export class HomePage extends React.Component<HomePageProps, HomePageState> {return false;}- private setTitle = (title: string) => {+ private setTitle = async (title: string) => {this.setState({ title });};@@ -77,13 +78,14 @@ export class HomePage extends React.Component<HomePageProps, HomePageState> {<div className="col-md-8">{this.isLonely() ? (<Lonely />+ ) : this.state.title ? (+ <SimilarIdeas title={this.state.title} user={this.props.user} tags={this.props.tags} />) : (<IdeasContaineruser={this.props.user}ideas={this.props.ideas}tags={this.props.tags}countPerStatus={this.props.countPerStatus}- newIdeaTitle={this.state.title}/>)}</div>diff --git a/public/pages/Home/components/IdeaFilter.tsx b/public/pages/Home/components/IdeaFilter.tsxindex 56e4e257b..7d7853a2f 100644--- a/public/pages/Home/components/IdeaFilter.tsx+++ b/public/pages/Home/components/IdeaFilter.tsx@@ -1,8 +1,9 @@import * as React from "react";-import { Idea, IdeaStatus } from "@fider/models";+import { Idea, IdeaStatus, CurrentUser } from "@fider/models";import { Dropdown, DropdownItemProps, DropdownProps } from "@fider/components";interface IdeaFilterProps {+ user?: CurrentUser;activeFilter: string;countPerStatus: { [key: string]: number };filterChanged: (name: string) => void;@@ -25,6 +26,10 @@ export class IdeaFilter extends React.Component<IdeaFilterProps, {}> {{ text: "most discussed", value: "most-discussed", content: "Most Discussed" }];+ if (this.props.user) {+ options.push({ text: "my votes", value: "my-votes", content: "My Votes" });+ }+IdeaStatus.All.filter(s => s.filterable && this.props.countPerStatus[s.value]).forEach(s => {options.push({text: s.title.toLowerCase(),diff --git a/public/pages/Home/components/IdeaInput.tsx b/public/pages/Home/components/IdeaInput.tsxindex e9eee5983..07298fb5f 100644--- a/public/pages/Home/components/IdeaInput.tsx+++ b/public/pages/Home/components/IdeaInput.tsx@@ -32,7 +32,8 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {focused: false,showSignIn: false};- if (this.state) {++ if (this.state.title) {this.props.onTitleChanged(this.state.title);}}diff --git a/public/pages/Home/components/IdeasContainer.tsx b/public/pages/Home/components/IdeasContainer.tsxindex 1e55b89f0..645769c13 100644--- a/public/pages/Home/components/IdeasContainer.tsx+++ b/public/pages/Home/components/IdeasContainer.tsx@@ -10,49 +10,35 @@ interface IdeasContainerProps {user?: CurrentUser;ideas: Idea[];tags: Tag[];- newIdeaTitle: string;countPerStatus: { [key: string]: number };}interface IdeasContainerState {loading: boolean;- ideas: Idea[];+ ideas?: Idea[];filter: string;tags: string[];query: string;+ limit?: number;}export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasContainerState> {- private timer?: number;-constructor(props: IdeasContainerProps) {super(props);- const query = page.getQueryString("q");- const tags = page.getQueryStringArray("t");- const filter = page.getQueryString("f");this.state = {- ideas: [],+ ideas: this.props.ideas,loading: false,- filter,- query,- tags+ filter: page.getQueryString("f"),+ query: page.getQueryString("q"),+ tags: page.getQueryStringArray("t"),+ limit: page.getQueryStringAsNumber("l")};}- public componentWillReceiveProps(nextProps: IdeasContainerProps) {- if (nextProps.newIdeaTitle) {- this.searchIdeas(nextProps.newIdeaTitle, "", [], 200);- } else if (this.state.query || this.state.filter || this.state.tags.length > 0) {- this.searchIdeas(this.state.query, this.state.filter, this.state.tags);- } else {- this.setState({ loading: false, ideas: nextProps.ideas });- }- }-private changeFilterCriteria<K extends keyof IdeasContainerState>(obj: Pick<IdeasContainerState, K>,- delay: number = 0+ reset: boolean): void {this.setState(obj, () => {const query = this.state.query.trim().toLowerCase();@@ -60,71 +46,58 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCopage.toQueryString({t: this.state.tags,q: query,- f: this.state.filter+ f: this.state.filter,+ l: this.state.limit}));- this.searchIdeas(query, this.state.filter, this.state.tags, delay);+ this.searchIdeas(query, this.state.filter, this.state.limit, this.state.tags, reset);});}- private async searchIdeas(query: string, filter: string, tags: string[], delay: number = 0) {+ private timer?: number;+ private async searchIdeas(query: string, filter: string, limit: number | undefined, tags: string[], reset: boolean) {window.clearTimeout(this.timer);- this.setState({ loading: true });+ this.setState({ ideas: reset ? undefined : this.state.ideas, loading: true });this.timer = window.setTimeout(() => {- actions.searchIdeas(query, filter, tags).then(response => {+ actions.searchIdeas({ query, filter, limit, tags }).then(response => {if (this.state.loading) {this.setState({ loading: false, ideas: response.data });}});- }, delay);+ }, 200);}private handleFilterChanged = (filter: string) => {- this.changeFilterCriteria({ filter });+ this.changeFilterCriteria({ filter }, true);};private handleTagsFilterChanged = (tags: string[]) => {- this.changeFilterCriteria({ tags });+ this.changeFilterCriteria({ tags }, true);};private handleSearchFilterChanged = (query: string) => {- this.changeFilterCriteria({ query }, 200);+ this.changeFilterCriteria({ query }, true);};private handleSearchClick = (query: string) => {- this.changeFilterCriteria({ query }, 200);+ this.changeFilterCriteria({ query }, true);};private clearSearch = () => {- this.changeFilterCriteria({ query: "" });+ this.changeFilterCriteria({ query: "" }, true);};- public render() {- if (this.props.newIdeaTitle) {- return (- <>- <Heading- title="Similar ideas"- subtitle="Consider voting on existing ideas before posting a new one."- icon="lightbulb"- size="small"- dividing={true}- />- {this.state.loading ? (- <Loader />- ) : (- <ListIdeas- ideas={this.state.ideas}- tags={this.props.tags}- user={this.props.user}- emptyText={`No similar ideas matched '${this.props.newIdeaTitle}'.`}- />- )}- </>- );- }+ private showMore = (event: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>): void => {+ event.preventDefault();+ this.changeFilterCriteria({ limit: (this.state.limit || 30) + 10 }, false);+ };+ private canShowMore = (): boolean => {+ return this.state.ideas ? this.state.ideas.length >= (this.state.limit || 30) : false;+ };++ public render() {return (<><div className="row">@@ -132,6 +105,7 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCo<div className="l-filter-col col-sm-7 col-md-8 col-lg-9 mb-2"><Field><IdeaFilter+ user={this.props.user}activeFilter={this.state.filter}filterChanged={this.handleFilterChanged}countPerStatus={this.props.countPerStatus}@@ -155,15 +129,17 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCo/></div></div>- {this.state.loading ? (- <Loader />- ) : (- <ListIdeas- ideas={this.state.ideas}- tags={this.props.tags}- user={this.props.user}- emptyText={"No results matched your search, try something different."}- />+ <ListIdeas+ ideas={this.state.ideas}+ tags={this.props.tags}+ user={this.props.user}+ emptyText={"No results matched your search, try something different."}+ />+ {this.state.loading && <Loader />}+ {this.canShowMore() && (+ <h5 className="c-idea-list-show-more" onTouchEnd={this.showMore} onClick={this.showMore}>+ View more ideas+ </h5>)}</>);diff --git a/public/pages/Home/components/ListIdeas.scss b/public/pages/Home/components/ListIdeas.scssindex b64c9861a..922fe116b 100644--- a/public/pages/Home/components/ListIdeas.scss+++ b/public/pages/Home/components/ListIdeas.scss@@ -31,10 +31,10 @@margin-bottom: 10px;}}+}- .c-idea-list-show-more {- cursor: pointer;- color: $main-color;- margin-left: 55px;- }+.c-idea-list-show-more {+ cursor: pointer;+ color: $main-color;+ margin-left: 55px;}\ No newline at end of filediff --git a/public/pages/Home/components/ListIdeas.tsx b/public/pages/Home/components/ListIdeas.tsxindex 07b58855d..188ff9956 100644--- a/public/pages/Home/components/ListIdeas.tsx+++ b/public/pages/Home/components/ListIdeas.tsx@@ -13,19 +13,13 @@ import {List} from "@fider/components";-const defaultShowCount = 20;-interface ListIdeasProps {user?: CurrentUser;- ideas: Idea[];+ ideas?: Idea[];tags: Tag[];emptyText: string;}-interface ListIdeasState {- showCount: number;-}-const ListIdeaItem = (props: { idea: Idea; user?: CurrentUser; tags: Tag[] }) => {return (<ListItem>@@ -47,30 +41,23 @@ const ListIdeaItem = (props: { idea: Idea; user?: CurrentUser; tags: Tag[] }) =>);};-export class ListIdeas extends React.Component<ListIdeasProps, ListIdeasState> {+export class ListIdeas extends React.Component<ListIdeasProps, {}> {constructor(props: ListIdeasProps) {super(props);- this.state = {- showCount: defaultShowCount- };}- private showMore = (event: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>): void => {- event.preventDefault();- this.setState({- showCount: this.state.showCount + defaultShowCount- });- };-public render() {+ if (!this.props.ideas) {+ return null;+ }+if (this.props.ideas.length === 0) {return <p className="center">{this.props.emptyText}</p>;}- const ideasToList = this.props.ideas.slice(0, this.state.showCount);return (<List className="c-idea-list" divided={true}>- {ideasToList.map(idea => (+ {this.props.ideas.map(idea => (<ListIdeaItemkey={idea.id}user={this.props.user}@@ -78,11 +65,6 @@ export class ListIdeas extends React.Component<ListIdeasProps, ListIdeasState> {tags={this.props.tags.filter(tag => idea.tags.indexOf(tag.slug) >= 0)}/>))}- {this.props.ideas.length > this.state.showCount && (- <h5 className="c-idea-list-show-more" onTouchEnd={this.showMore} onClick={this.showMore}>- View {this.props.ideas.length - this.state.showCount} more ideas- </h5>- )}</List>);}diff --git a/public/pages/Home/components/SimilarIdeas.tsx b/public/pages/Home/components/SimilarIdeas.tsxnew file mode 100644index 000000000..a9789f57f--- /dev/null+++ b/public/pages/Home/components/SimilarIdeas.tsx@@ -0,0 +1,79 @@+import * as React from "react";+import { Idea, Tag, CurrentUser } from "@fider/models";+import { Heading, Loader } from "@fider/components";+import { ListIdeas } from "./ListIdeas";+import { actions } from "@fider/services";++interface SimilarIdeasProps {+ title: string;+ tags: Tag[];+ user?: CurrentUser;+}++interface SimilarIdeasState {+ title: string;+ ideas: Idea[];+ loading: boolean;+}++export class SimilarIdeas extends React.Component<SimilarIdeasProps, SimilarIdeasState> {+ constructor(props: SimilarIdeasProps) {+ super(props);+ this.state = {+ title: props.title,+ loading: !!props.title,+ ideas: []+ };+ }++ public static getDerivedStateFromProps(nextProps: SimilarIdeasProps, prevState: SimilarIdeasState) {+ if (nextProps.title !== prevState.title) {+ return {+ loading: true,+ title: nextProps.title+ };+ }+ return null;+ }+ public componentDidMount() {+ this.loadSimilarIdeas();+ }++ private timer?: number;+ public componentDidUpdate() {+ window.clearTimeout(this.timer);+ this.timer = window.setTimeout(this.loadSimilarIdeas, 200);+ }++ private loadSimilarIdeas = () => {+ if (this.state.loading) {+ actions.searchIdeas({ query: this.state.title }).then(x => {+ this.setState({ loading: false, ideas: x.data });+ });+ }+ };++ public render() {+ return (+ <>+ <Heading+ title="Similar ideas"+ subtitle="Consider voting on existing ideas before posting a new one."+ icon="lightbulb"+ size="small"+ dividing={true}+ />+ {this.state.loading ? (+ <Loader />+ ) : (+ <ListIdeas+ ideas={this.state.ideas}+ tags={this.props.tags}+ user={this.props.user}+ emptyText={`No similar ideas matched '${this.props.title}'.`}+ />+ )}+ </>+ );+ }+}diff --git a/public/pages/ShowIdea/components/IdeaSearch.tsx b/public/pages/ShowIdea/components/IdeaSearch.tsxindex 008ff7089..67c6ef14f 100644--- a/public/pages/ShowIdea/components/IdeaSearch.tsx+++ b/public/pages/ShowIdea/components/IdeaSearch.tsx@@ -34,7 +34,7 @@ export class IdeaSearch extends React.Component<IdeaSearchProps, IdeaSearchStateprivate search = (searchQuery: string) => {window.clearTimeout(this.timer);this.timer = window.setTimeout(() => {- actions.searchIdeas(searchQuery, "", []).then(res => {+ actions.searchIdeas({ query: searchQuery }).then(res => {const ideas =this.props.exclude && this.props.exclude.length > 0? res.data.filter(i => this.props.exclude!.indexOf(i.number) === -1)diff --git a/public/services/actions/idea.ts b/public/services/actions/idea.tsindex e65ea751c..ed6fa1ead 100644--- a/public/services/actions/idea.ts+++ b/public/services/actions/idea.ts@@ -1,12 +1,26 @@-import { http, Result } from "@fider/services";+import { http, Result, page } from "@fider/services";import { Idea } from "@fider/models";export const getAllIdeas = async (): Promise<Result<Idea[]>> => {return await http.get<Idea[]>("/api/ideas/search");};-export const searchIdeas = async (query: string, filter: string, tags: string[]): Promise<Result<Idea[]>> => {- return await http.get<Idea[]>(`/api/ideas/search?q=${encodeURIComponent(query)}&f=${filter}&t=${tags.join(",")}`);+export interface SearchIdeasParams {+ query?: string;+ filter?: string;+ limit?: number;+ tags?: string[];+}++export const searchIdeas = async (params: SearchIdeasParams): Promise<Result<Idea[]>> => {+ return await http.get<Idea[]>(+ `/api/ideas/search${page.toQueryString({+ t: params.tags,+ q: params.query,+ f: params.filter,+ l: params.limit+ })}`+ );};export const deleteIdea = async (ideaNumber: number, text: string): Promise<Result> => {diff --git a/public/services/page.ts b/public/services/page.tsindex 91fb5f090..dbf4b771e 100644--- a/public/services/page.ts+++ b/public/services/page.ts@@ -28,6 +28,10 @@ export interface ModalOptions {closable: boolean;}+export const getQueryStringAsNumber = (name: string): number | undefined => {+ return parseInt(getQueryString(name), 10) || undefined;+};+export const getQueryString = (name: string): string => {const url = window.location.href;name = name.replace(/[\[\]]/g, "\\$&");@@ -51,7 +55,7 @@ export const getQueryStringArray = (name: string): string[] => {};export interface QueryString {- [key: string]: string | string[];+ [key: string]: string | string[] | number | undefined;}export const toQueryString = (object: QueryString): string => {@@ -69,7 +73,7 @@ export const toQueryString = (object: QueryString): string => {qs += `${symbol}${key}=${value.join(",")}`;}} else if (value) {- qs += `${symbol}${key}=${encodeURIComponent(value).replace(/%20/g, "+")}`;+ qs += `${symbol}${key}=${encodeURIComponent(value.toString()).replace(/%20/g, "+")}`;}}