Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: search similar ideas as you type a new one (#267)

Guilherme Oenningf32111aa9337
diff --git a/.travis.yml b/.travis.yml
index 0abfc05f5..c05798add 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -12,8 +12,9 @@ install:
- go get github.com/joho/godotenv/cmd/godotenv &
- go get github.com/dave/courtney &
- nvm use 8.9
- - psql -c 'CREATE DATABASE fider_ci;' -U postgres
- - psql -c "CREATE USER fider_ci WITH PASSWORD 'fider_ci_pw';" -U postgres
+ - psql -U postgres -c 'CREATE DATABASE fider_ci;'
+ - psql -U postgres -c "CREATE USER fider_ci WITH PASSWORD 'fider_ci_pw';"
+ - psql -U postgres -c "ALTER ROLE fider_ci SUPERUSER;"
script:
- npm install
diff --git a/app/handlers/idea.go b/app/handlers/idea.go
index b08ca2f3b..9be859e12 100644
--- a/app/handlers/idea.go
+++ b/app/handlers/idea.go
@@ -11,7 +11,11 @@ import (
// Index is the default home page
func Index() web.HandlerFunc {
return func(c web.Context) error {
- ideas, err := c.Services().Ideas.GetAll()
+ ideas, err := c.Services().Ideas.Search(
+ c.QueryParam("q"),
+ c.QueryParam("f"),
+ c.QueryParamAsArray("t"),
+ )
if err != nil {
return c.Failure(err)
}
@@ -21,17 +25,27 @@ func Index() web.HandlerFunc {
return c.Failure(err)
}
+ stats, err := c.Services().Ideas.CountPerStatus()
+ if err != nil {
+ return c.Failure(err)
+ }
+
return c.Page(web.Map{
- "ideas": ideas,
- "tags": tags,
+ "ideas": ideas,
+ "tags": tags,
+ "countPerStatus": stats,
})
}
}
-// GetIdeas return basic model of all tenant ideas
-func GetIdeas() web.HandlerFunc {
+// SearchIdeas return existing ideas based on search criteria
+func SearchIdeas() web.HandlerFunc {
return func(c web.Context) error {
- ideas, err := c.Services().Ideas.GetAllBasic()
+ ideas, err := c.Services().Ideas.Search(
+ c.QueryParam("q"),
+ c.QueryParam("f"),
+ c.QueryParamAsArray("t"),
+ )
if err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/idea_test.go b/app/handlers/idea_test.go
index d12fadc17..27efa3e06 100644
--- a/app/handlers/idea_test.go
+++ b/app/handlers/idea_test.go
@@ -21,22 +21,6 @@ func TestIndexHandler(t *testing.T) {
Expect(code).To(Equal(http.StatusOK))
}
-func TestGetIdeasHandler(t *testing.T) {
- RegisterTestingT(t)
-
- server, services := mock.NewServer()
- services.Ideas.Add("My Idea", "My Idea Description", mock.JonSnow.ID)
- services.Ideas.Add("My Idea 2", "My Idea 2 Description", mock.JonSnow.ID)
-
- code, query := server.OnTenant(mock.DemoTenant).
- AsUser(mock.JonSnow).
- ExecuteAsJSON(handlers.GetIdeas())
-
- Expect(code).To(Equal(http.StatusOK))
- Expect(query.IsArray()).To(BeTrue())
- Expect(query.ArrayLength()).To(Equal(2))
-}
-
func TestDetailsHandler(t *testing.T) {
RegisterTestingT(t)
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 27b5abdd4..3e2f4908f 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -54,12 +54,12 @@ func WorkerSetup(logger log.Logger) worker.MiddlewareFunc {
}()
start := time.Now()
- c.Logger().Infof("Task '%s' started on worker '%s'", log.Magenta(c.TaskName()), log.Magenta(c.WorkerID()))
+ c.Logger().Debugf("Task '%s' started on worker '%s'", log.Magenta(c.TaskName()), log.Magenta(c.WorkerID()))
if err = next(c); err != nil {
panic(err)
}
trx.Commit()
- c.Logger().Infof("Task '%s' finished in %s", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
+ c.Logger().Debugf("Task '%s' finished in %s", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
return err
}
}
@@ -75,7 +75,7 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {
path := log.Magenta(c.Request.Method + " " + c.Request.URL.String())
start := time.Now()
- c.Logger().Infof("%s started", path)
+ c.Logger().Debugf("%s started", path)
trx, err := db.Begin()
if err != nil {
@@ -97,7 +97,7 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {
if r := recover(); r != nil {
err := fmt.Errorf("%v\n%v", r, string(debug.Stack()))
c.Failure(err)
- c.Logger().Infof("%s finished in %s", path, log.Magenta(time.Since(start).String()))
+ c.Logger().Debugf("%s finished in %s", path, log.Magenta(time.Since(start).String()))
if trx != nil {
trx.Rollback()
}
@@ -105,15 +105,14 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {
}()
if err = next(c); err != nil {
- panic(err)
+ return err
}
if err = trx.Commit(); err != nil {
- panic(err)
+ return err
}
- c.Logger().Infof("%s finished in %s", path, log.Magenta(time.Since(start).String()))
- c.Logger().Debugf("Transaction committed")
+ c.Logger().Debugf("%s finished in %s", path, log.Magenta(time.Since(start).String()))
return err
}
}
diff --git a/app/models/feedback.go b/app/models/feedback.go
index ec7a0ad82..ed2e95f7f 100644
--- a/app/models/feedback.go
+++ b/app/models/feedback.go
@@ -19,8 +19,7 @@ type Idea struct {
TotalComments int `json:"totalComments"`
Status int `json:"status"`
Response *IdeaResponse `json:"response"`
- Tags []int64 `json:"tags"`
- Ranking float64 `json:"ranking"`
+ Tags []string `json:"tags"`
}
// CanBeSupported returns true if this idea can be Supported/UnSupported
@@ -28,16 +27,6 @@ func (i *Idea) CanBeSupported() bool {
return i.Status != IdeaCompleted && i.Status != IdeaDeclined && i.Status != IdeaDuplicate
}
-//BasicIdea is a subset of Idea with few fields
-type BasicIdea struct {
- ID int `json:"id"`
- Number int `json:"number"`
- Title string `json:"title"`
- Slug string `json:"slug"`
- TotalSupporters int `json:"totalSupporters"`
- Status int `json:"status"`
-}
-
// NewIdea represents a new idea
type NewIdea struct {
Title string `json:"title"`
diff --git a/app/pkg/dbx/dbx.go b/app/pkg/dbx/dbx.go
index 7955228d1..1a6bc9077 100644
--- a/app/pkg/dbx/dbx.go
+++ b/app/pkg/dbx/dbx.go
@@ -90,7 +90,7 @@ func (db Database) Migrate() {
}
if err != nil && err != migrate.ErrNoChange {
- db.logger.Infof("Error: %s.", err)
+ db.logger.Errorf("Error: %s.", err)
panic("Migrations failed.")
} else {
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 75f2f21c0..d4c6a68c5 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -333,6 +333,15 @@ func (ctx *Context) QueryParam(key string) string {
return ctx.Request.URL.Query().Get(key)
}
+//QueryParamAsArray returns querystring parameter for given key as an array
+func (ctx *Context) QueryParamAsArray(key string) []string {
+ param := ctx.QueryParam(key)
+ if param != "" {
+ return strings.Split(param, ",")
+ }
+ return []string{}
+}
+
//Param returns parameter as string
func (ctx *Context) Param(name string) string {
if ctx.params == nil {
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index 33959824c..0f4127bc7 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -179,10 +179,7 @@ func (g *Group) handler(handler HandlerFunc) httprouter.Handle {
params[p.Key] = p.Value
}
ctx := g.engine.NewContext(res, req, params)
- err := next(ctx)
- if err != nil {
- ctx.Failure(err)
- }
+ next(ctx)
}
return h
}
diff --git a/app/storage/inmemory/idea.go b/app/storage/inmemory/idea.go
index a8a7eab28..4e700b8a4 100644
--- a/app/storage/inmemory/idea.go
+++ b/app/storage/inmemory/idea.go
@@ -85,20 +85,14 @@ func (s *IdeaStorage) GetAll() ([]*models.Idea, error) {
return s.ideas, nil
}
-// GetAllBasic returns all tenant ideas in a Basic model
-func (s *IdeaStorage) GetAllBasic() ([]*models.BasicIdea, error) {
- var result = make([]*models.BasicIdea, len(s.ideas))
- for i, idea := range s.ideas {
- result[i] = &models.BasicIdea{
- ID: idea.ID,
- Number: idea.Number,
- Title: idea.Title,
- Slug: idea.Slug,
- TotalSupporters: idea.TotalSupporters,
- Status: idea.Status,
- }
- }
- return result, nil
+// CountPerStatus returns total number of ideas per status
+func (s *IdeaStorage) CountPerStatus() (map[int]int, error) {
+ return make(map[int]int, 0), nil
+}
+
+// Search existing ideas based on input
+func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Idea, error) {
+ return s.ideas, nil
}
// GetCommentsByIdea returns all coments from given idea
diff --git a/app/storage/postgres/idea.go b/app/storage/postgres/idea.go
index 5c2d29140..b79afbc21 100644
--- a/app/storage/postgres/idea.go
+++ b/app/storage/postgres/idea.go
@@ -3,7 +3,7 @@ package postgres
import (
"errors"
"fmt"
- "math"
+ "strings"
"time"
"database/sql"
@@ -35,15 +35,10 @@ type dbIdea struct {
OriginalTitle sql.NullString `db:"original_title"`
OriginalSlug sql.NullString `db:"original_slug"`
OriginalStatus sql.NullInt64 `db:"original_status"`
- Tags []int64 `db:"tags"`
+ Tags []string `db:"tags"`
}
func (i *dbIdea) toModel() *models.Idea {
- ranking := float64((i.RecentSupporters*5)+(i.RecentComments*3)-1) / math.Pow((time.Since(i.CreatedOn).Hours()+2), 1.4)
- if math.IsNaN(ranking) {
- ranking = 0
- }
-
idea := &models.Idea{
ID: i.ID,
Number: i.Number,
@@ -57,7 +52,6 @@ func (i *dbIdea) toModel() *models.Idea {
Status: i.Status,
User: i.User.toModel(),
Tags: i.Tags,
- Ranking: ranking,
}
if i.Response.Valid {
@@ -78,17 +72,6 @@ func (i *dbIdea) toModel() *models.Idea {
return idea
}
-func (i *dbIdea) toBasic() *models.BasicIdea {
- return &models.BasicIdea{
- ID: i.ID,
- Number: i.Number,
- Title: i.Title,
- Slug: i.Slug,
- TotalSupporters: i.TotalSupporters,
- Status: i.Status,
- }
-}
-
type dbComment struct {
ID int `db:"id"`
Content string `db:"content"`
@@ -105,6 +88,11 @@ func (c *dbComment) toModel() *models.Comment {
}
}
+type dbStatusCount struct {
+ Status int `db:"status"`
+ Count int `db:"count"`
+}
+
// IdeaStorage contains read and write operations for ideas
type IdeaStorage struct {
trx *dbx.Trx
@@ -130,7 +118,8 @@ func (s *IdeaStorage) SetCurrentUser(user *models.User) {
}
var (
- sqlSelectIdeasWhere = ` WITH agg_comments AS (
+ sqlSelectIdeasWhere = ` WITH
+ agg_comments AS (
SELECT
idea_id,
COUNT(CASE WHEN comments.created_on > CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as recent,
@@ -161,7 +150,7 @@ var (
i.supporters,
COALESCE(agg_c.all, 0) as comments,
COALESCE(agg_s.recent, 0) AS recent_supporters,
- COALESCE(agg_c.recent, 0) AS recent_comments,
+ COALESCE(agg_c.recent, 0) AS recent_comments,
i.status,
u.id AS user_id,
u.name AS user_name,
@@ -177,7 +166,7 @@ var (
d.title AS original_title,
d.slug AS original_slug,
d.status AS original_status,
- array_remove(array_agg(t.id), NULL) AS tags,
+ array_remove(array_agg(t.slug), NULL) AS tags,
COALESCE(%s, false) AS viewer_supported
FROM ideas i
INNER JOIN users u
@@ -238,32 +227,107 @@ func (s *IdeaStorage) GetByNumber(number int) (*models.Idea, error) {
// GetAll returns all tenant ideas
func (s *IdeaStorage) GetAll() ([]*models.Idea, error) {
- var ideas []*dbIdea
- err := s.trx.Select(&ideas, s.getIdeaQuery("i.tenant_id = $1 AND i.status != $2"), s.tenant.ID, models.IdeaDuplicate)
+ return s.Search("", "all", []string{})
+}
+
+// CountPerStatus returns total number of ideas per status
+func (s *IdeaStorage) CountPerStatus() (map[int]int, error) {
+ stats := []*dbStatusCount{}
+ err := s.trx.Select(&stats, "SELECT status, COUNT(*) AS count FROM ideas WHERE tenant_id = $1 GROUP BY status", s.tenant.ID)
if err != nil {
return nil, err
}
-
- var result = make([]*models.Idea, len(ideas))
- for i, idea := range ideas {
- result[i] = idea.toModel()
+ result := make(map[int]int, len(stats))
+ for _, v := range stats {
+ result[v.Status] = v.Count
}
return result, nil
}
-// GetAllBasic returns all tenant ideas in a Basic model
-func (s *IdeaStorage) GetAllBasic() ([]*models.BasicIdea, error) {
- var ideas []*dbIdea
- innerQuery := s.getIdeaQuery("i.tenant_id = $1 AND i.status != $2")
- query := fmt.Sprintf("SELECT id, number, title, slug, supporters, status FROM (%s) AS q", innerQuery)
- err := s.trx.Select(&ideas, query, s.tenant.ID, models.IdeaDuplicate)
+func getFilterData(filter string) ([]int, string) {
+ var sort string
+ statuses := []int{
+ models.IdeaOpen,
+ models.IdeaStarted,
+ models.IdeaPlanned,
+ }
+ switch filter {
+ case "recent":
+ sort = "id"
+ case "most-wanted":
+ sort = "supporters"
+ case "most-discussed":
+ sort = "comments"
+ case "planned":
+ sort = "response_date"
+ statuses = []int{models.IdeaPlanned}
+ case "started":
+ sort = "response_date"
+ statuses = []int{models.IdeaStarted}
+ case "completed":
+ sort = "response_date"
+ statuses = []int{models.IdeaCompleted}
+ case "declined":
+ sort = "response_date"
+ statuses = []int{models.IdeaDeclined}
+ case "all":
+ sort = "id"
+ statuses = []int{
+ models.IdeaOpen,
+ models.IdeaStarted,
+ models.IdeaPlanned,
+ models.IdeaCompleted,
+ models.IdeaDeclined,
+ }
+ case "trending":
+ fallthrough
+ 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
+}
+
+// Search existing ideas based on input
+func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Idea, error) {
+ innerQuery := s.getIdeaQuery("i.tenant_id = $1 AND i.status = ANY($2)")
+
+ var (
+ ideas []*dbIdea
+ err error
+ )
+ if query != "" {
+ scoreField := "ts_rank(setweight(to_tsvector(title), 'A') || setweight(to_tsvector(description), 'B'), to_tsquery('english', $4)) + similarity(title, $5) + similarity(description, $5)"
+ sql := fmt.Sprintf(`
+ SELECT * FROM (%s) AS q
+ WHERE %s > 0.3
+ AND tags @> $3
+ ORDER BY %s DESC
+ `, innerQuery, scoreField, scoreField)
+ tsQuery := strings.Join(strings.Fields(query), "|")
+ err = s.trx.Select(&ideas, sql, s.tenant.ID, pq.Array([]int{
+ models.IdeaOpen,
+ models.IdeaStarted,
+ models.IdeaPlanned,
+ models.IdeaCompleted,
+ models.IdeaDeclined,
+ }), pq.Array(tags), tsQuery, query)
+ } else {
+ statuses, sort := getFilterData(filter)
+ sql := fmt.Sprintf(`
+ SELECT * FROM (%s) AS q
+ WHERE tags @> $3
+ ORDER BY %s DESC
+ `, innerQuery, sort)
+ err = s.trx.Select(&ideas, sql, s.tenant.ID, pq.Array(statuses), pq.Array(tags))
+ }
+
if err != nil {
return nil, err
}
- var result = make([]*models.BasicIdea, len(ideas))
+ var result = make([]*models.Idea, len(ideas))
for i, idea := range ideas {
- result[i] = idea.toBasic()
+ result[i] = idea.toModel()
}
return result, nil
}
diff --git a/app/storage/postgres/idea_test.go b/app/storage/postgres/idea_test.go
index 160ed950d..451a11df9 100644
--- a/app/storage/postgres/idea_test.go
+++ b/app/storage/postgres/idea_test.go
@@ -15,8 +15,8 @@ func TestIdeaStorage_GetAll(t *testing.T) {
now := time.Now()
- trx.Execute("INSERT INTO ideas (title, slug, number, description, created_on, tenant_id, user_id, supporters, status) VALUES ('Idea #1', 'idea-1', 1, 'Description #1', $1, 1, 1, 0, 1)", now)
- trx.Execute("INSERT INTO ideas (title, slug, number, description, created_on, tenant_id, user_id, supporters, status) VALUES ('Idea #2', 'idea-2', 2, 'Description #2', $1, 1, 2, 5, 2)", now)
+ trx.Execute("INSERT INTO ideas (title, slug, number, description, created_on, tenant_id, user_id, supporters, status) VALUES ('add twitter integration', 'add-twitter-integration', 1, 'Would be great to see it integrated with twitter', $1, 1, 1, 0, 1)", now)
+ trx.Execute("INSERT INTO ideas (title, slug, number, description, created_on, tenant_id, user_id, supporters, status) VALUES ('this is my idea', 'this-is-my-idea', 2, 'no description', $1, 1, 2, 5, 2)", now)
ideas.SetCurrentTenant(demoTenant)
@@ -24,37 +24,26 @@ func TestIdeaStorage_GetAll(t *testing.T) {
Expect(err).To(BeNil())
Expect(dbIdeas).To(HaveLen(2))
- Expect(dbIdeas[0].Title).To(Equal("Idea #1"))
- Expect(dbIdeas[0].Slug).To(Equal("idea-1"))
- Expect(dbIdeas[0].Number).To(Equal(1))
- Expect(dbIdeas[0].Description).To(Equal("Description #1"))
- Expect(dbIdeas[0].User.Name).To(Equal("Jon Snow"))
- Expect(dbIdeas[0].TotalSupporters).To(Equal(0))
- Expect(dbIdeas[0].Status).To(Equal(models.IdeaStarted))
-
- Expect(dbIdeas[1].Title).To(Equal("Idea #2"))
- Expect(dbIdeas[1].Slug).To(Equal("idea-2"))
- Expect(dbIdeas[1].Number).To(Equal(2))
- Expect(dbIdeas[1].Description).To(Equal("Description #2"))
- Expect(dbIdeas[1].User.Name).To(Equal("Arya Stark"))
- Expect(dbIdeas[1].TotalSupporters).To(Equal(5))
- Expect(dbIdeas[1].Status).To(Equal(models.IdeaCompleted))
-
- dbBasicIdeas, err := ideas.GetAllBasic()
+ Expect(dbIdeas[0].Title).To(Equal("this is my idea"))
+ Expect(dbIdeas[0].Slug).To(Equal("this-is-my-idea"))
+ Expect(dbIdeas[0].Number).To(Equal(2))
+ Expect(dbIdeas[0].Description).To(Equal("no description"))
+ Expect(dbIdeas[0].User.Name).To(Equal("Arya Stark"))
+ Expect(dbIdeas[0].TotalSupporters).To(Equal(5))
+ Expect(dbIdeas[0].Status).To(Equal(models.IdeaCompleted))
+
+ Expect(dbIdeas[1].Title).To(Equal("add twitter integration"))
+ Expect(dbIdeas[1].Slug).To(Equal("add-twitter-integration"))
+ Expect(dbIdeas[1].Number).To(Equal(1))
+ Expect(dbIdeas[1].Description).To(Equal("Would be great to see it integrated with twitter"))
+ Expect(dbIdeas[1].User.Name).To(Equal("Jon Snow"))
+ Expect(dbIdeas[1].TotalSupporters).To(Equal(0))
+ Expect(dbIdeas[1].Status).To(Equal(models.IdeaStarted))
+
+ dbIdeas, err = ideas.Search("twitter", "trending", []string{})
Expect(err).To(BeNil())
- Expect(dbBasicIdeas).To(HaveLen(2))
-
- Expect(dbBasicIdeas[0].Title).To(Equal("Idea #1"))
- Expect(dbBasicIdeas[0].Slug).To(Equal("idea-1"))
- Expect(dbBasicIdeas[0].Number).To(Equal(1))
- Expect(dbBasicIdeas[0].TotalSupporters).To(Equal(0))
- Expect(dbBasicIdeas[0].Status).To(Equal(models.IdeaStarted))
-
- Expect(dbBasicIdeas[1].Title).To(Equal("Idea #2"))
- Expect(dbBasicIdeas[1].Slug).To(Equal("idea-2"))
- Expect(dbBasicIdeas[1].Number).To(Equal(2))
- Expect(dbBasicIdeas[1].TotalSupporters).To(Equal(5))
- Expect(dbBasicIdeas[1].Status).To(Equal(models.IdeaCompleted))
+ Expect(dbIdeas).To(HaveLen(1))
+ Expect(dbIdeas[0].Slug).To(Equal("add-twitter-integration"))
}
func TestIdeaStorage_AddAndGet(t *testing.T) {
@@ -387,11 +376,11 @@ func TestIdeaStorage_WithTags(t *testing.T) {
idea, _ = ideas.GetByID(idea.ID)
Expect(len(idea.Tags)).To(Equal(1))
- Expect(idea.Tags[0]).To(Equal(int64(bug.ID)))
+ Expect(idea.Tags[0]).To(Equal(bug.Slug))
ideas.SetCurrentUser(jonSnow)
idea, _ = ideas.GetByID(idea.ID)
Expect(len(idea.Tags)).To(Equal(2))
- Expect(idea.Tags[0]).To(Equal(int64(bug.ID)))
- Expect(idea.Tags[1]).To(Equal(int64(featureRequest.ID)))
+ Expect(idea.Tags[0]).To(Equal(bug.Slug))
+ Expect(idea.Tags[1]).To(Equal(featureRequest.Slug))
}
diff --git a/app/storage/storage.go b/app/storage/storage.go
index 989c3531c..a5eb43d6d 100644
--- a/app/storage/storage.go
+++ b/app/storage/storage.go
@@ -19,8 +19,9 @@ type Idea interface {
GetBySlug(slug string) (*models.Idea, error)
GetByNumber(number int) (*models.Idea, error)
GetCommentsByIdea(number int) ([]*models.Comment, error)
+ Search(query, filter string, tags []string) ([]*models.Idea, error)
GetAll() ([]*models.Idea, error)
- GetAllBasic() ([]*models.BasicIdea, error)
+ CountPerStatus() (map[int]int, error)
Add(title, description string, userID int) (*models.Idea, error)
Update(number int, title, description string) (*models.Idea, error)
AddComment(number int, content string, userID int) (int, error)
diff --git a/migrations/201802231910_add_pg_trgm.up.sql b/migrations/201802231910_add_pg_trgm.up.sql
new file mode 100644
index 000000000..b2b1f68da
--- /dev/null
+++ b/migrations/201802231910_add_pg_trgm.up.sql
@@ -0,0 +1 @@
+CREATE EXTENSION pg_trgm;
\ No newline at end of file
diff --git a/public/components/common/Loader.tsx b/public/components/common/Loader.tsx
new file mode 100644
index 000000000..a73e42bbc
--- /dev/null
+++ b/public/components/common/Loader.tsx
@@ -0,0 +1,33 @@
+import * as React from 'react';
+
+interface LoaderState {
+ show: boolean;
+}
+
+export class Loader extends React.Component<{}, LoaderState> {
+ private unmounted: boolean;
+ constructor(props: {}) {
+ super(props);
+ this.unmounted = false;
+ this.state = {
+ show: false,
+ };
+ }
+
+ public componentDidMount() {
+ setTimeout(() => {
+ if (!this.unmounted) {
+ this.setState({
+ show: true
+ });
+ }
+ }, 500);
+ }
+ public componentWillUnmount() {
+ this.unmounted = true;
+ }
+
+ public render() {
+ return this.state.show && <div className="ui active centered inline loader"/>;
+ }
+}
diff --git a/public/components/common/index.tsx b/public/components/common/index.tsx
index 19e7201f0..85e4a2de5 100644
--- a/public/components/common/index.tsx
+++ b/public/components/common/index.tsx
@@ -10,5 +10,6 @@ export * from './SocialSignInButton';
export * from './SignInControl';
export * from './Moment';
export * from './UserName';
+export * from './Loader';
import Textarea from 'react-textarea-autosize';
export { Textarea };
diff --git a/public/index.tsx b/public/index.tsx
index c199bc2f7..384e04545 100644
--- a/public/index.tsx
+++ b/public/index.tsx
@@ -18,6 +18,7 @@ import 'semantic-ui-css/components/dimmer.min.js';
import 'semantic-ui-css/components/reset.min.css';
import 'semantic-ui-css/components/site.min.css';
import 'semantic-ui-css/components/segment.min.css';
+import 'semantic-ui-css/components/loader.min.css';
import 'semantic-ui-css/components/table.min.css';
import 'semantic-ui-css/components/checkbox.min.css';
import 'semantic-ui-css/components/transition.min.css';
diff --git a/public/models/idea.ts b/public/models/idea.ts
index 539faeffc..4f5ef96b5 100644
--- a/public/models/idea.ts
+++ b/public/models/idea.ts
@@ -13,17 +13,7 @@ export interface Idea {
response: IdeaResponse;
totalSupporters: number;
totalComments: number;
- tags: number[];
- ranking: number;
-}
-
-export interface BasicIdea {
- id: number;
- number: number;
- slug: string;
- title: string;
- status: number;
- totalSupporters: number;
+ tags: string[];
}
export class IdeaStatus {
diff --git a/public/pages/site/HomePage/HomePage.tsx b/public/pages/site/HomePage/HomePage.tsx
index 71b7d7825..4dae1e302 100644
--- a/public/pages/site/HomePage/HomePage.tsx
+++ b/public/pages/site/HomePage/HomePage.tsx
@@ -1,30 +1,24 @@
import * as React from 'react';
import { Idea, Tag, IdeaStatus, CurrentUser, Tenant } from '@fider/models';
-import { ShowTag, ShowIdeaResponse, SupportCounter, Gravatar, MultiLineText, Moment } from '@fider/components';
-import { IdeaInput, TagsFilter, IdeaFilter, IdeaFilterFunction } from './';
-import { page } from '@fider/services';
+import { MultiLineText } from '@fider/components';
+import { IdeaInput, ListIdeas, IdeasView } from './';
+import { page, actions } from '@fider/services';
import './HomePage.scss';
-const defaultShowCount = 20;
-
export interface HomePageProps {
user?: CurrentUser;
tenant: Tenant;
ideas: Idea[];
tags: Tag[];
+ countPerStatus: { [key: string]: number };
}
-interface HomePageState {
- ideas: Idea[];
- search?: string;
- showCount: number;
- searching: boolean;
- activeFilter: string;
- tags: string[];
+export interface HomePageState {
+ title: string;
}
-const EmptyList = () => {
+const Lonely = () => {
return (
<div className="center">
<p><i className="icon lightbulb" aria-hidden="true" /></p>
@@ -33,225 +27,42 @@ const EmptyList = () => {
);
};
-const ListIdeaItem = (props: { idea: Idea, user?: CurrentUser, tags: Tag[] }) => {
- return (
- <div className="item">
- <SupportCounter user={props.user} idea={props.idea} />
- <div className="content">
- {
- props.idea.totalComments > 0 &&
- <div className="info right">
- {props.idea.totalComments} <i className="comments outline icon"/>
- </div>
- }
- <a className="title" href={`/ideas/${props.idea.number}/${props.idea.slug}`}>
- {props.idea.title}
- </a>
- <MultiLineText className="description" text={props.idea.description} style="simple" />
- <ShowIdeaResponse status={props.idea.status} response={props.idea.response} />
- {
- props.tags.map((tag) => (
- <ShowTag key={tag.id} size="tiny" tag={tag} />
- ))
- }
- </div>
- </div>
- );
-};
+const defaultWelcomeMessage = `## Welcome to our feedback forum!
+
+We'd love to hear what you're thinking about. What can we do better? This is the place for you to vote, discuss and share ideas.`;
export class HomePage extends React.Component<HomePageProps, HomePageState> {
- private filter: HTMLDivElement;
constructor(props: HomePageProps) {
super(props);
-
- const search = page.getQueryString('q');
- const tags = page.getQueryStringArray('t');
- const activeFilter = window.location.hash.substring(1);
this.state = {
- ideas: this.filterIdeas(activeFilter, search, tags),
- showCount: defaultShowCount,
- activeFilter,
- searching: !!search,
- search,
- tags
+ title: '',
};
}
- private containsAll(str: string, substrings: string[]): boolean {
- for (let i = 0; i !== substrings.length; i++) {
- if (str.indexOf(substrings[i]) === - 1) {
- return false;
- }
- }
- return true;
- }
-
- private selectedTagsChanged(tags: string[]): void {
- const ideas = this.filterIdeas(this.state.activeFilter, this.state.search, tags);
- this.setState({
- ideas,
- tags,
- });
- }
-
- private filterIdeas(activeFilter: string, search: string | undefined, tags: string[]): Idea[] {
- let path = '';
- let ideas = [];
-
- if (search) {
- const s = search.trim().toLowerCase();
- path += `?q=${encodeURIComponent(s).replace(/%20/g, '+')}`;
- ideas = this.props.ideas.filter((idea) => {
- const terms = s.split(' ').filter((x) => x.length >= 2);
- return (
- this.containsAll(idea.title.toLowerCase(), terms) ||
- this.containsAll(idea.description.toLowerCase(), terms) ||
- (idea.response && this.containsAll(idea.response.text.toLowerCase(), terms))
- );
- });
- } else {
- path += activeFilter ? `#${activeFilter}` : '';
- ideas = IdeaFilter.getFilter(activeFilter)(this.props.ideas);
- }
-
- if (tags.length > 0) {
- const prefix = (!path) ? '?' : '&';
- path += `${prefix}t=${tags.join(',')}`;
- }
-
- if (history.replaceState) {
- const newUrl = page.getBaseUrl() + path;
- window.history.replaceState({ path: newUrl }, '', newUrl);
- }
-
- if (tags.length > 0) {
- const tagsToFilter = this.props.tags.filter((x) => tags.indexOf(x.slug) >= 0).map((x) => x.id);
- ideas = ideas.filter(
- (i) => i.tags.filter(
- (t) => tagsToFilter.indexOf(t) >= 0
- ).length === tagsToFilter.length
- );
- }
-
- return ideas;
- }
-
- private filterChanged(name: string) {
- this.setState({
- ideas: this.filterIdeas(name, this.state.search, this.state.tags),
- showCount: defaultShowCount,
- activeFilter: name,
- });
- }
-
- private showMore(event: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>): void {
- event.preventDefault();
- this.setState({
- showCount: this.state.showCount + defaultShowCount
- });
- }
-
- private resetSearch() {
- this.setState({
- search: '',
- searching: false,
- ideas: this.filterIdeas(this.state.activeFilter, '', this.state.tags),
- });
- }
-
- private searchIdea(input: string): void {
- this.setState({
- search: input,
- ideas: this.filterIdeas(this.state.activeFilter, input, this.state.tags)
- });
- }
-
public render() {
- const ideasToList = this.state.ideas.slice(0, this.state.showCount);
-
- const displayIdeas = (ideasToList.length > 0)
- ? (
- <div className="ui divided unstackable items fdr-idea-list">
- {
- ideasToList.map((idea) =>
- <ListIdeaItem
- key={idea.id}
- user={this.props.user}
- idea={idea}
- tags={this.props.tags.filter((tag) => idea.tags.indexOf(tag.id) >= 0)}
- />)}
- {
- this.state.ideas.length > this.state.showCount &&
- <h5
- className="ui blue header show-more"
- onTouchEnd={(e) => this.showMore(e)}
- onClick={(e) => this.showMore(e)}
- >
- View {this.state.ideas.length - this.state.showCount} more ideas
- </h5>
- }
- </div>
- )
- : <p className="no-ideas-found">No ideas found for given filter.</p>;
-
- const welcomeMessage = this.props.tenant.welcomeMessage ||
- `## Welcome to our feedback forum!
-
-We'd love to hear what you're thinking about. What can we do better? This is the place for you to vote, discuss and share ideas.`;
-
return (
<div className="page ui container">
<div className="ui grid stackable">
<div className="six wide column">
- <MultiLineText className="welcome-message" text={welcomeMessage} style="full" />
+ <MultiLineText className="welcome-message" text={this.props.tenant.welcomeMessage || defaultWelcomeMessage} style="full" />
<IdeaInput
user={this.props.user}
placeholder={this.props.tenant.invitation || 'I suggest you...'}
+ onTitleChanged={(title) => this.setState({ title })}
/>
</div>
<div className="ten wide column">
{
this.props.ideas.length === 0
- ? <EmptyList />
- : <div>
- <div className="ui grid">
- {
- !this.state.searching && <div className="ten wide mobile ten wide tablet twelve wide computer column filter-column">
- <IdeaFilter
- ideas={this.props.ideas}
- activeFilter={this.state.activeFilter}
- filterChanged={(name) => this.filterChanged(name)}
- />
- </div>
- }
- <div className={!this.state.searching ? `six wide mobile six wide tablet four wide computer column` : 'column'}>
- <div className="ui search">
- <div className="ui icon fluid input">
- <input
- onFocus={() => this.setState({ searching: true })}
- onBlur={(x) => this.setState({ searching: !!this.state.search })}
- onChange={(x) => this.searchIdea(x.currentTarget.value)}
- value={this.state.search}
- type="text"
- placeholder="Search..."
- />
- {
- this.state.searching
- ? <i onClick={() => this.resetSearch()} className="cancel link icon" />
- : <i className="search icon" />
- }
- </div>
- </div>
- </div>
- </div>
- <TagsFilter
- tags={this.props.tags}
- selectionChanged={(selected) => this.selectedTagsChanged(selected)}
- defaultSelection={this.state.tags}
- />
- {displayIdeas}
- </div>
+ ? <Lonely />
+ : <IdeasView
+ user={this.props.user}
+ ideas={this.props.ideas}
+ tags={this.props.tags}
+ countPerStatus={this.props.countPerStatus}
+ newIdeaTitle={this.state.title}
+ />
}
</div>
</div>
diff --git a/public/pages/site/HomePage/IdeaFilter.tsx b/public/pages/site/HomePage/IdeaFilter.tsx
index 3033c79a6..a865b3953 100644
--- a/public/pages/site/HomePage/IdeaFilter.tsx
+++ b/public/pages/site/HomePage/IdeaFilter.tsx
@@ -4,22 +4,11 @@ import { Idea, IdeaStatus } from '@fider/models';
export type IdeaFilterFunction = (ideas: Idea[]) => Idea[];
interface IdeaFilterProps {
- ideas: Idea[];
activeFilter: string;
+ countPerStatus: { [key: string]: number };
filterChanged: (name: string) => void;
}
-const filterers: {[key: string]: (idea: Idea) => boolean} = {
- 'trending': (idea: Idea) => IdeaStatus.Get(idea.status).closed === false,
- 'recent': (idea: Idea) => IdeaStatus.Get(idea.status).closed === false,
- 'most-wanted': (idea: Idea) => IdeaStatus.Get(idea.status).closed === false,
- 'most-discussed': (idea: Idea) => IdeaStatus.Get(idea.status).closed === false,
- 'planned': (idea: Idea) => idea.status === IdeaStatus.Planned.value,
- 'started': (idea: Idea) => idea.status === IdeaStatus.Started.value,
- 'completed': (idea: Idea) => idea.status === IdeaStatus.Completed.value,
- 'declined': (idea: Idea) => idea.status === IdeaStatus.Declined.value
-};
-
const names: {[key: string]: string} = {
'trending': 'trending',
'recent': 'recent',
@@ -31,32 +20,13 @@ const names: {[key: string]: string} = {
'declined': 'declined'
};
-const sorterers: {[key: string]: (left: Idea, right: Idea) => number} = {
- 'trending': (left: Idea, right: Idea) => right.ranking !== left.ranking ? right.ranking - left.ranking : new Date(right.createdOn).getTime() - new Date(left.createdOn).getTime(),
- 'recent': (left: Idea, right: Idea) => new Date(right.createdOn).getTime() - new Date(left.createdOn).getTime(),
- 'most-wanted': (left: Idea, right: Idea) => right.totalSupporters - left.totalSupporters,
- 'most-discussed': (left: Idea, right: Idea) => right.totalComments - left.totalComments,
- 'planned': (left: Idea, right: Idea) => new Date(right.response.respondedOn).getTime() - new Date(left.response.respondedOn).getTime(),
- 'started': (left: Idea, right: Idea) => new Date(right.response.respondedOn).getTime() - new Date(left.response.respondedOn).getTime(),
- 'completed': (left: Idea, right: Idea) => new Date(right.response.respondedOn).getTime() - new Date(left.response.respondedOn).getTime(),
- 'declined': (left: Idea, right: Idea) => new Date(right.response.respondedOn).getTime() - new Date(left.response.respondedOn).getTime()
-};
-
export class IdeaFilter extends React.Component<IdeaFilterProps, {}> {
- private element: HTMLDivElement;
+ private element?: HTMLDivElement;
constructor(props: IdeaFilterProps) {
super(props);
}
- public static getFilter(value: string): IdeaFilterFunction {
- if (!filterers[value]) {
- value = 'trending';
- }
-
- return (ideas: Idea[]) => ideas.filter(filterers[value]).sort(sorterers[value]);
- }
-
public componentDidMount() {
$(this.element).dropdown({
onChange: (value: string) => {
@@ -71,15 +41,10 @@ export class IdeaFilter extends React.Component<IdeaFilterProps, {}> {
activeFilter = 'trending';
}
- const grouped = this.props.ideas.reduce<{ [status: number]: number }>((group, idea) => {
- group[idea.status] = (group[idea.status] || 0) + 1;
- return group;
- }, {});
-
- const statusFilterItems = IdeaStatus.All.filter((s) => s.filterable && grouped[s.value]).map((s) => (
+ const statusFilterItems = IdeaStatus.All.filter((s) => s.filterable && this.props.countPerStatus[s.value]).map((s) => (
<div key={s.value} className={`item ${activeFilter === s.slug && 'active'}`} data-value={s.slug} data-text={s.title.toLowerCase()}>
{s.title}
- <a className="ui mini circular label">{grouped[s.value]}</a>
+ <a className="ui mini circular label">{this.props.countPerStatus[s.value]}</a>
</div>
));
diff --git a/public/pages/site/HomePage/IdeaInput.tsx b/public/pages/site/HomePage/IdeaInput.tsx
index a2b8f0e29..076d064fb 100644
--- a/public/pages/site/HomePage/IdeaInput.tsx
+++ b/public/pages/site/HomePage/IdeaInput.tsx
@@ -6,6 +6,7 @@ import { CurrentUser } from '@fider/models';
interface IdeaInputProps {
user?: CurrentUser;
placeholder: string;
+ onTitleChanged: (title: string) => void;
}
interface IdeaInputState {
@@ -18,8 +19,8 @@ const CACHE_TITLE_KEY = 'IdeaInput-Title';
const CACHE_DESCRIPTION_KEY = 'IdeaInput-Description';
export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {
- private title: HTMLInputElement;
- private form: Form;
+ private title?: HTMLInputElement;
+ private form?: Form;
constructor(props: IdeaInputProps) {
super(props);
@@ -28,16 +29,19 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {
description: cache.get(CACHE_DESCRIPTION_KEY) || '',
focused: false
};
+ if (this.state) {
+ this.props.onTitleChanged(this.state.title);
+ }
}
public componentDidMount() {
- if (this.props.user) {
+ if (this.props.user && this.title) {
this.title.focus();
}
}
private onTitleFocused() {
- if (!this.props.user) {
+ if (!this.props.user && this.title) {
this.title.blur();
page.showSignIn();
}
@@ -46,6 +50,7 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {
private onTitleChanged(title: string) {
cache.set(CACHE_TITLE_KEY, title);
this.setState({ title });
+ this.props.onTitleChanged(title);
}
private onDescriptionChanged(description: string) {
@@ -57,11 +62,13 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {
if (this.state.title) {
const result = await actions.createIdea(this.state.title, this.state.description);
if (result.ok) {
+ if (this.form) {
+ this.form.clearFailure();
+ }
cache.remove(CACHE_TITLE_KEY, CACHE_DESCRIPTION_KEY);
- this.form.clearFailure();
location.href = `/ideas/${result.data.number}/${result.data.slug}`;
event.preventEnable();
- } else if (result.error) {
+ } else if (result.error && this.form) {
this.form.setFailure(result.error);
}
}
diff --git a/public/pages/site/HomePage/IdeasView.tsx b/public/pages/site/HomePage/IdeasView.tsx
new file mode 100644
index 000000000..c6af105fc
--- /dev/null
+++ b/public/pages/site/HomePage/IdeasView.tsx
@@ -0,0 +1,147 @@
+import * as React from 'react';
+import { Idea, Tag, IdeaStatus, CurrentUser } from '@fider/models';
+import { Loader, MultiLineText } from '@fider/components';
+import { IdeaInput, ListIdeas, TagsFilter, IdeaFilter } from './';
+import { page, actions } from '@fider/services';
+
+interface IdeasViewProps {
+ user?: CurrentUser;
+ ideas: Idea[];
+ tags: Tag[];
+ newIdeaTitle: string;
+ countPerStatus: { [key: string]: number };
+}
+
+interface IdeasViewState {
+ loading: boolean;
+ ideas: Idea[];
+ filter: string;
+ tags: string[];
+ query: string;
+}
+
+export class IdeasView extends React.Component<IdeasViewProps, IdeasViewState> {
+ private timer: any;
+
+ constructor(props: IdeasViewProps) {
+ super(props);
+ const query = page.getQueryString('q');
+ const tags = page.getQueryStringArray('t');
+ const filter = page.getQueryString('f');
+
+ this.state = {
+ ideas: [],
+ loading: false,
+ filter,
+ query,
+ tags
+ };
+ }
+
+ public componentWillReceiveProps(nextProps: IdeasViewProps) {
+ 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({ ideas: nextProps.ideas });
+ }
+ }
+
+ private changeFilterCriteria<K extends keyof IdeasViewState>(obj: Pick<IdeasViewState, K>, delay: number = 0): void {
+ this.setState(obj, () => {
+ const query = this.state.query.trim().toLowerCase();
+ page.replaceState(page.toQueryString({
+ t: this.state.tags,
+ q: query,
+ f: this.state.filter,
+ }));
+
+ this.searchIdeas(query, this.state.filter, this.state.tags, delay);
+ });
+ }
+
+ private async searchIdeas(query: string, filter: string, tags: string[], delay: number = 0) {
+ clearTimeout(this.timer);
+ this.setState({ loading: true });
+ this.timer = setTimeout(() => {
+ actions.searchIdeas(query, filter, tags).then((response) => {
+ this.setState({ loading: false, ideas: response.data });
+ });
+ }, delay);
+ }
+
+ public render() {
+ if (this.props.newIdeaTitle) {
+ return (
+ <>
+ <h3 className="ui dividing header">
+ <i className="lightbulb icon blue" />
+ <div className="content">
+ Similar ideas
+ <div className="sub header">Consider voting on existing ideas before posting a new one.</div>
+ </div>
+ </h3>
+ {
+ 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}'.`}
+ />
+ }
+ </>
+ );
+ }
+
+ return (
+ <>
+ <div className="ui grid">
+ {
+ !this.state.query && <div className="ten wide mobile ten wide tablet twelve wide computer column filter-column">
+ <IdeaFilter
+ activeFilter={this.state.filter}
+ filterChanged={(filter) => this.changeFilterCriteria({ filter })}
+ countPerStatus={this.props.countPerStatus}
+ />
+ </div>
+ }
+ <div className={!this.state.query ? `six wide mobile six wide tablet four wide computer column` : 'column'}>
+ <div className="ui search">
+ <div className="ui icon fluid input">
+ <input
+ onChange={(x) => this.changeFilterCriteria({ query: x.currentTarget.value }, 200)}
+ value={this.state.query}
+ type="text"
+ placeholder="Search..."
+ />
+ {
+ this.state.query
+ ? <i onClick={() => this.changeFilterCriteria({ query: '' })} className="cancel link icon" />
+ : <i className="search icon" />
+ }
+ </div>
+ </div>
+ </div>
+ </div>
+ <TagsFilter
+ tags={this.props.tags}
+ selectionChanged={(tags) => this.changeFilterCriteria({ tags })}
+ defaultSelection={this.state.tags}
+ />
+ {
+ 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.'}
+ />
+ }
+ </>
+ );
+ }
+}
diff --git a/public/pages/site/HomePage/ListIdeas.tsx b/public/pages/site/HomePage/ListIdeas.tsx
new file mode 100644
index 000000000..eb18ff9ce
--- /dev/null
+++ b/public/pages/site/HomePage/ListIdeas.tsx
@@ -0,0 +1,89 @@
+import * as React from 'react';
+import { Idea, Tag, IdeaStatus, CurrentUser } from '@fider/models';
+import { ShowTag, ShowIdeaResponse, SupportCounter, Gravatar, MultiLineText, Moment } from '@fider/components';
+
+const defaultShowCount = 20;
+
+interface ListIdeasProps {
+ user?: CurrentUser;
+ ideas: Idea[];
+ tags: Tag[];
+ emptyText: string;
+}
+
+interface ListIdeasState {
+ showCount: number;
+}
+
+const ListIdeaItem = (props: { idea: Idea, user?: CurrentUser, tags: Tag[] }) => {
+ return (
+ <div className="item">
+ <SupportCounter user={props.user} idea={props.idea} />
+ <div className="content">
+ {
+ props.idea.totalComments > 0 &&
+ <div className="info right">
+ {props.idea.totalComments} <i className="comments outline icon"/>
+ </div>
+ }
+ <a className="title" href={`/ideas/${props.idea.number}/${props.idea.slug}`}>
+ {props.idea.title}
+ </a>
+ <MultiLineText className="description" text={props.idea.description} style="simple" />
+ <ShowIdeaResponse status={props.idea.status} response={props.idea.response} />
+ {
+ props.tags.map((tag) => (
+ <ShowTag key={tag.id} size="tiny" tag={tag} />
+ ))
+ }
+ </div>
+ </div>
+ );
+};
+
+export class ListIdeas extends React.Component<ListIdeasProps, ListIdeasState> {
+ 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.length === 0) {
+ return <p className="no-ideas-found">{this.props.emptyText}</p>;
+ }
+
+ const ideasToList = this.props.ideas.slice(0, this.state.showCount);
+ return (
+ <div className="ui divided unstackable items fdr-idea-list">
+ {
+ ideasToList.map((idea) =>
+ <ListIdeaItem
+ key={idea.id}
+ user={this.props.user}
+ idea={idea}
+ tags={this.props.tags.filter((tag) => idea.tags.indexOf(tag.slug) >= 0)}
+ />)
+ }
+ {
+ this.props.ideas.length > this.state.showCount &&
+ <h5
+ className="ui blue header show-more"
+ onTouchEnd={(e) => this.showMore(e)}
+ onClick={(e) => this.showMore(e)}
+ >
+ View {this.props.ideas.length - this.state.showCount} more ideas
+ </h5>
+ }
+ </div>
+ );
+ }
+}
diff --git a/public/pages/site/HomePage/TagsFilter.tsx b/public/pages/site/HomePage/TagsFilter.tsx
index 543bc35eb..4916e2a84 100644
--- a/public/pages/site/HomePage/TagsFilter.tsx
+++ b/public/pages/site/HomePage/TagsFilter.tsx
@@ -13,7 +13,7 @@ interface TagsFilterState {
}
export class TagsFilter extends React.Component<TagsFilterProps, TagsFilterState> {
- private element: HTMLDivElement;
+ private element?: HTMLDivElement;
constructor(props: TagsFilterProps) {
super(props);
diff --git a/public/pages/site/HomePage/index.ts b/public/pages/site/HomePage/index.ts
index a110bc3db..df39a3042 100644
--- a/public/pages/site/HomePage/index.ts
+++ b/public/pages/site/HomePage/index.ts
@@ -3,3 +3,5 @@ export * from './TagsFilter';
export * from './IdeaFilter';
export * from './HomePage';
export * from './IdeaInput';
+export * from './ListIdeas';
+export * from './IdeasView';
diff --git a/public/pages/site/ShowIdeaPage/IdeaSearch.tsx b/public/pages/site/ShowIdeaPage/IdeaSearch.tsx
index affea5db3..9b457557f 100644
--- a/public/pages/site/ShowIdeaPage/IdeaSearch.tsx
+++ b/public/pages/site/ShowIdeaPage/IdeaSearch.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { BasicIdea, IdeaStatus } from '@fider/models';
+import { Idea, IdeaStatus } from '@fider/models';
import { actions } from '@fider/services';
interface IdeaSearchProps {
@@ -8,7 +8,7 @@ interface IdeaSearchProps {
}
interface IdeaSearchState {
- ideas?: BasicIdea[];
+ ideas?: Idea[];
}
export class IdeaSearch extends React.Component<IdeaSearchProps, IdeaSearchState> {
@@ -17,7 +17,7 @@ export class IdeaSearch extends React.Component<IdeaSearchProps, IdeaSearchState
constructor(props: IdeaSearchProps) {
super(props);
this.state = { };
- actions.getIdeas().then((res) => {
+ actions.getAllIdeas().then((res) => {
const ideas = this.props.exclude && this.props.exclude.length > 0
? res.data.filter((i) => this.props.exclude!.indexOf(i.number) === -1)
: res.data;
diff --git a/public/pages/site/ShowIdeaPage/TagsPanel.tsx b/public/pages/site/ShowIdeaPage/TagsPanel.tsx
index 48c68022b..b4cd9d364 100644
--- a/public/pages/site/ShowIdeaPage/TagsPanel.tsx
+++ b/public/pages/site/ShowIdeaPage/TagsPanel.tsx
@@ -22,7 +22,7 @@ export class TagsPanel extends React.Component<TagsPanelProps, TagsPanelState> {
this.state = {
canEdit: !!this.props.user && this.props.user.isCollaborator && this.props.tags.length > 0,
isEditing: false,
- assignedTags: this.props.tags.filter((t) => this.props.idea.tags.indexOf(t.id) >= 0),
+ assignedTags: this.props.tags.filter((t) => this.props.idea.tags.indexOf(t.slug) >= 0),
};
}
diff --git a/public/services/actions/idea.ts b/public/services/actions/idea.ts
index 8deb69e82..be782a373 100644
--- a/public/services/actions/idea.ts
+++ b/public/services/actions/idea.ts
@@ -1,8 +1,12 @@
import { http, Result } from '@fider/services';
-import { Idea, BasicIdea } from '@fider/models';
+import { Idea } from '@fider/models';
-export const getIdeas = async (): Promise<Result<BasicIdea[]>> => {
- return await http.get<BasicIdea[]>('/api/ideas');
+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=${query}&f=${filter}&t=${tags.join(',')}`);
};
export const addSupport = async (ideaNumber: number): Promise<Result> => {
diff --git a/public/services/page.ts b/public/services/page.ts
index f3f078883..b760d379e 100644
--- a/public/services/page.ts
+++ b/public/services/page.ts
@@ -52,3 +52,36 @@ export const getQueryStringArray = (name: string): string[] => {
return [];
};
+
+export interface QueryString {
+ [key: string]: string | string[];
+}
+
+export const toQueryString = (object: QueryString): string => {
+ if (!object) {
+ return '';
+ }
+
+ let qs = '';
+
+ for (const key of Object.keys(object)) {
+ const symbol = qs ? '&' : '?';
+ const value = object[key];
+ if (value instanceof Array) {
+ if (value.length > 0) {
+ qs += `${symbol}${key}=${value.join(',')}`;
+ }
+ } else if (value) {
+ qs += `${symbol}${key}=${encodeURIComponent(value).replace(/%20/g, '+')}`;
+ }
+ }
+
+ return qs;
+};
+
+export const replaceState = (path: string): void => {
+ if (history.replaceState) {
+ const newUrl = getBaseUrl() + path;
+ window.history.replaceState({ path: newUrl }, '', newUrl);
+ }
+};
diff --git a/routes.go b/routes.go
index d7076dbab..077f34913 100644
--- a/routes.go
+++ b/routes.go
@@ -78,7 +78,7 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
private.Get("/settings", handlers.UserSettings())
private.Get("/change-email/verify", handlers.VerifyChangeEmailKey())
- private.Get("/api/ideas", handlers.GetIdeas())
+ private.Get("/api/ideas/search", handlers.SearchIdeas())
private.Post("/api/ideas", handlers.PostIdea())
private.Post("/api/ideas/:number", handlers.UpdateIdea())
private.Post("/api/ideas/:number/comments", handlers.PostComment())