Open platform to collect and prioritize feedback
Added the new posts filter
Matt Roberts24b49eb8bf5b
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex 19f2631cd..701015aa8 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -26,6 +26,8 @@ func SearchPosts() web.HandlerFunc {Limit: c.QueryParam("limit"),Tags: c.QueryParamAsArray("tags"),}+ searchPosts.SetStatusesFromStrings(c.QueryParamAsArray("statuses"))+if err := bus.Dispatch(c, searchPosts); err != nil {return c.Failure(err)}@@ -60,7 +62,7 @@ func CreatePost() web.HandlerFunc {if err = bus.Dispatch(c, setAttachments, addVote); err != nil {return c.Failure(err)}-+if env.Config.PostCreationWithTagsEnabled {for _, tag := range action.Tags {assignTag := &cmd.AssignTag{Tag: tag, Post: newPost.Result}diff --git a/app/handlers/post.go b/app/handlers/post.goindex 65769b452..ee246f8c2 100644--- a/app/handlers/post.go+++ b/app/handlers/post.go@@ -22,6 +22,7 @@ func Index() web.HandlerFunc {Limit: c.QueryParam("limit"),Tags: c.QueryParamAsArray("tags"),}+ searchPosts.SetStatusesFromStrings(c.QueryParamAsArray("statuses"))getAllTags := &query.GetAllTags{}countPerStatus := &query.CountPostPerStatus{}diff --git a/app/models/query/post.go b/app/models/query/post.goindex 7210bd9c5..6ef577cd6 100644--- a/app/models/query/post.go+++ b/app/models/query/post.go@@ -34,10 +34,11 @@ type GetPostByNumber struct {}type SearchPosts struct {- Query string- View string- Limit string- Tags []string+ Query string+ View string+ Limit string+ Statuses []enum.PostStatus+ Tags []stringResult []*entity.Post}@@ -45,3 +46,12 @@ type SearchPosts struct {type GetAllPosts struct {Result []*entity.Post}++func (q *SearchPosts) SetStatusesFromStrings(statuses []string) {+ for _, v := range statuses {+ var postStatus enum.PostStatus+ if err := postStatus.UnmarshalText([]byte(v)); err == nil {+ q.Statuses = append(q.Statuses, postStatus)+ }+ }+}diff --git a/app/pkg/assert/assert.go b/app/pkg/assert/assert.goindex 9c77bf841..1b6b432c3 100644--- a/app/pkg/assert/assert.go+++ b/app/pkg/assert/assert.go@@ -40,7 +40,7 @@ func describeProps(props dto.Props) string {return str}-//Fail the current test case with given message+// Fail the current test case with given messagefunc Fail(msg string, args ...any) {if currentT == nil {panic("Did you forget to call RegisterT(t)?")@@ -51,7 +51,7 @@ func Fail(msg string, args ...any) {var currentT *testing.Tvar envVariables map[string]string-//RegisterT saves current testing.T for further usage by Expect+// RegisterT saves current testing.T for further usage by Expectfunc RegisterT(t *testing.T) {bus.Reset()if currentT == nil {@@ -77,12 +77,12 @@ func restartEnv() {env.Reload()}-//AnyAssertions is used to assert any kind of value+// AnyAssertions is used to assert any kind of valuetype AnyAssertions struct {actual any}-//Expect starts new assertions on given value+// Expect starts new assertions on given valuefunc Expect(actual any) *AnyAssertions {if currentT == nil {panic("Did you forget to call RegisterT(t)?")@@ -92,7 +92,7 @@ func Expect(actual any) *AnyAssertions {}}-//Equals asserts that actual value equals expected value+// Equals asserts that actual value equals expected valuefunc (a *AnyAssertions) Equals(expected any) bool {if reflect.DeepEqual(expected, a.actual) {return true@@ -102,7 +102,7 @@ func (a *AnyAssertions) Equals(expected any) bool {return false}-//ContainsSubstring asserts that actual value contains given substring+// ContainsSubstring asserts that actual value contains given substringfunc (a *AnyAssertions) ContainsSubstring(substr string) bool {if strings.Contains(a.actual.(string), substr) {return true@@ -112,7 +112,7 @@ func (a *AnyAssertions) ContainsSubstring(substr string) bool {return false}-//NotEquals asserts that actual value is different than given value+// NotEquals asserts that actual value is different than given valuefunc (a *AnyAssertions) NotEquals(other any) bool {if !reflect.DeepEqual(other, a.actual) {return true@@ -122,27 +122,27 @@ func (a *AnyAssertions) NotEquals(other any) bool {return false}-//IsTrue asserts that actual value is true+// IsTrue asserts that actual value is truefunc (a *AnyAssertions) IsTrue() bool {return a.Equals(true)}-//IsFalse asserts that actual value is false+// IsFalse asserts that actual value is falsefunc (a *AnyAssertions) IsFalse() bool {return a.Equals(false)}-//IsEmpty asserts that actual value is empty+// IsEmpty asserts that actual value is emptyfunc (a *AnyAssertions) IsEmpty() bool {return a.Equals("")}-//IsNotEmpty asserts that actual value is not empty+// IsNotEmpty asserts that actual value is not emptyfunc (a *AnyAssertions) IsNotEmpty() bool {return a.NotEquals("")}-//IsNotNil asserts that actual value is not nil+// IsNotNil asserts that actual value is not nilfunc (a *AnyAssertions) IsNotNil() bool {if a.actual != nil && !reflect.ValueOf(a.actual).IsNil() {return true@@ -152,7 +152,7 @@ func (a *AnyAssertions) IsNotNil() bool {return false}-//IsNil asserts that actual value is nil+// IsNil asserts that actual value is nilfunc (a *AnyAssertions) IsNil() bool {if a.actual == nil || reflect.ValueOf(a.actual).IsNil() {return true@@ -162,7 +162,7 @@ func (a *AnyAssertions) IsNil() bool {return false}-//HasLen asserts that actual value has an expected length+// HasLen asserts that actual value has an expected lengthfunc (a *AnyAssertions) HasLen(expected int) bool {length := reflect.ValueOf(a.actual).Len()if expected == length {@@ -172,8 +172,30 @@ func (a *AnyAssertions) HasLen(expected int) bool {currentT.Error(errors.StackN(err, 1))return false}+func (a *AnyAssertions) ContainsOnly(expected []int) bool {+ actual := reflect.ValueOf(a.actual).Interface().([]int)++ contains := func(arr []int, value int) bool {+ for _, v := range arr {+ if v == value {+ return true+ }+ }+ return false+ }++ for _, v := range actual {+ if !contains(expected, v) {+ err := fmt.Errorf("ContainsOnly assertion failed. \n Expected: \n\t\t %v \n Actual: \n\t\t %v", expected, actual)+ currentT.Error(errors.StackN(err, 1))+ return false+ }+ }++ return true+}-//Panics asserts that actual value panics whenever called+// Panics asserts that actual value panics whenever calledfunc (a *AnyAssertions) Panics() (panicked bool) {mustBeFunction(a.actual)defer func() {@@ -189,7 +211,7 @@ func (a *AnyAssertions) Panics() (panicked bool) {return}-//EventuallyEquals asserts that, within 30 seconds, the actual function will return same value as expected value+// EventuallyEquals asserts that, within 30 seconds, the actual function will return same value as expected valuefunc (a *AnyAssertions) EventuallyEquals(expected any) bool {mustBeFunction(a.actual)@@ -213,7 +235,7 @@ func (a *AnyAssertions) EventuallyEquals(expected any) bool {}}-//TemporarilySimilar asserts that actual value is between a range of other time value+// TemporarilySimilar asserts that actual value is between a range of other time valuefunc (a *AnyAssertions) TemporarilySimilar(other time.Time, diff time.Duration) bool {actual, ok := a.actual.(time.Time)if !ok {diff --git a/app/services/sqlstore/postgres/common.go b/app/services/sqlstore/postgres/common.goindex 8a0437c87..a59ba9032 100644--- a/app/services/sqlstore/postgres/common.go+++ b/app/services/sqlstore/postgres/common.go@@ -7,6 +7,7 @@ import ("strings""github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/web")@@ -25,17 +26,22 @@ func SanitizeString(input string) string {return strings.ToValidUTF8(input, "")}-func getViewData(view string) (string, []enum.PostStatus, string) {+func getViewData(query query.SearchPosts) (string, []enum.PostStatus, string) {var (condition stringsort string)- statuses := []enum.PostStatus{- enum.PostOpen,- enum.PostStarted,- enum.PostPlanned,+ statusFilters := query.Statuses+ if len(statusFilters) == 0 {+ // Use a sensible default list of status filters+ statusFilters = []enum.PostStatus{+ enum.PostOpen,+ enum.PostStarted,+ enum.PostPlanned,+ }}- switch view {++ switch query.View {case "recent":sort = "id"case "my-votes":@@ -45,21 +51,25 @@ func getViewData(view string) (string, []enum.PostStatus, string) {sort = "votes_count"case "most-discussed":sort = "comments_count"+ // Depracted: Use status filters insteadcase "planned":sort = "response_date"- statuses = []enum.PostStatus{enum.PostPlanned}+ statusFilters = []enum.PostStatus{enum.PostPlanned}+ // Deprecated: Use status filters insteadcase "started":sort = "response_date"- statuses = []enum.PostStatus{enum.PostStarted}+ statusFilters = []enum.PostStatus{enum.PostStarted}+ // Deprecated: Use status filters insteadcase "completed":sort = "response_date"- statuses = []enum.PostStatus{enum.PostCompleted}+ statusFilters = []enum.PostStatus{enum.PostCompleted}+ // Deprecated: Use status filters insteadcase "declined":sort = "response_date"- statuses = []enum.PostStatus{enum.PostDeclined}+ statusFilters = []enum.PostStatus{enum.PostDeclined}case "all":sort = "id"- statuses = []enum.PostStatus{+ statusFilters = []enum.PostStatus{enum.PostOpen,enum.PostStarted,enum.PostPlanned,@@ -71,7 +81,11 @@ func getViewData(view string) (string, []enum.PostStatus, string) {default:sort = "((COALESCE(recent_votes_count, 0)*5 + COALESCE(recent_comments_count, 0) *3)-1) / pow((EXTRACT(EPOCH FROM current_timestamp - created_at)/3600) + 2, 1.4)"}- return condition, statuses, sort++ if len(query.Tags) > 0 {+ condition += " AND tags && $3"+ }+ return condition, statusFilters, sort}func buildAvatarURL(ctx context.Context, avatarType enum.AvatarType, id int, name, avatarBlobKey string) string {diff --git a/app/services/sqlstore/postgres/post.go b/app/services/sqlstore/postgres/post.goindex e6b86a839..ca11cad49 100644--- a/app/services/sqlstore/postgres/post.go+++ b/app/services/sqlstore/postgres/post.go@@ -368,6 +368,10 @@ func searchPosts(ctx context.Context, q *query.SearchPosts) error {q.Tags = []string{}}+ if q.Statuses == nil {+ q.Statuses = []enum.PostStatus{}+ }+if q.Limit != "all" {if _, err := strconv.Atoi(q.Limit); err != nil {q.Limit = "30"@@ -394,14 +398,18 @@ func searchPosts(ctx context.Context, q *query.SearchPosts) error {enum.PostDeclined,}), ToTSQuery(q.Query), SanitizeString(q.Query))} else {- condition, statuses, sort := getViewData(q.View)+ condition, statuses, sort := getViewData(*q)sql := fmt.Sprintf(`SELECT * FROM (%s) AS q- WHERE tags @> $3 %s+ WHERE 1 = 1 %sORDER BY %s DESCLIMIT %s`, innerQuery, condition, sort, q.Limit)- err = trx.Select(&posts, sql, tenant.ID, pq.Array(statuses), pq.Array(q.Tags))+ params := []interface{}{tenant.ID, pq.Array(statuses)}+ if len(q.Tags) > 0 {+ params = append(params, pq.Array(q.Tags))+ }+ err = trx.Select(&posts, sql, params...)}if err != nil {diff --git a/app/services/sqlstore/postgres/post_test.go b/app/services/sqlstore/postgres/post_test.goindex 81f2ab7f4..2b277db87 100644--- a/app/services/sqlstore/postgres/post_test.go+++ b/app/services/sqlstore/postgres/post_test.go@@ -513,6 +513,115 @@ func TestPostStorage_WithTags(t *testing.T) {Expect(getPost.Result.Tags[1]).Equals(addFeatureRequest.Result.Slug)}+func TestGetPosts_Different_Statuses(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ newPost := &cmd.AddNewPost{Title: "New Post, hello there.", Description: "with this description 3"}+ startedPost := &cmd.AddNewPost{Title: "Started Post, yes we're doing this", Description: "with this description"}+ completedPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description 2"}+ duplicatePost := &cmd.AddNewPost{Title: "New Post, hello there again", Description: "with this description 2"}+ declinedPost := &cmd.AddNewPost{Title: "Nope, not this", Description: "with this description 2"}+ plannedPost := &cmd.AddNewPost{Title: "Yes we're going to do this", Description: "with this description 2"}+ err := bus.Dispatch(aryaStarkCtx, startedPost, completedPost, newPost, duplicatePost, declinedPost, plannedPost)+ Expect(err).IsNil()++ addBug := &cmd.AddNewTag{Name: "Bug", Color: "FF0000", IsPublic: true}+ addFeatureRequest := &cmd.AddNewTag{Name: "Feature Request", Color: "00FF00", IsPublic: false}+ bus.MustDispatch(aryaStarkCtx, addBug, addFeatureRequest)+ bus.MustDispatch(aryaStarkCtx, &cmd.AssignTag{Tag: addBug.Result, Post: newPost.Result})+ bus.MustDispatch(aryaStarkCtx, &cmd.AssignTag{Tag: addFeatureRequest.Result, Post: newPost.Result})+ bus.MustDispatch(aryaStarkCtx, &cmd.AssignTag{Tag: addBug.Result, Post: completedPost.Result})+ bus.MustDispatch(aryaStarkCtx, &cmd.AssignTag{Tag: addFeatureRequest.Result, Post: completedPost.Result})++ completedPostResponse := &cmd.SetPostResponse{Post: completedPost.Result, Text: "We're doing this", Status: enum.PostCompleted}+ startedPostResponse := &cmd.SetPostResponse{Post: startedPost.Result, Text: "We're doing this", Status: enum.PostStarted}+ declinedPostResponse := &cmd.SetPostResponse{Post: declinedPost.Result, Text: "We're not doing this", Status: enum.PostDeclined}+ plannedPostResponse := &cmd.SetPostResponse{Post: plannedPost.Result, Text: "This is planned", Status: enum.PostPlanned}+ duplicatePostResponse := &cmd.SetPostResponse{Post: duplicatePost.Result, Text: "This is a dupe", Status: enum.PostDeclined}++ err = bus.Dispatch(aryaStarkCtx, startedPostResponse, completedPostResponse, duplicatePostResponse, declinedPostResponse, plannedPostResponse)+ Expect(err).IsNil()++ testCases := []struct {+ name string+ searchParams *query.SearchPosts+ expectedCount int+ expectedIDs []int+ }{+ {+ name: "Default Search (Everything except declined, completed and duplicate)",+ searchParams: &query.SearchPosts{},+ expectedCount: 3,+ expectedIDs: []int{startedPost.Result.ID, newPost.Result.ID, plannedPost.Result.ID},+ },+ {+ name: "Started and Completed",+ searchParams: &query.SearchPosts{+ Statuses: []enum.PostStatus{enum.PostStarted, enum.PostCompleted},+ },+ expectedCount: 2,+ expectedIDs: []int{startedPost.Result.ID, completedPost.Result.ID},+ },+ {+ name: "Only Started",+ searchParams: &query.SearchPosts{+ Statuses: []enum.PostStatus{enum.PostStarted},+ },+ expectedCount: 1,+ expectedIDs: []int{startedPost.Result.ID},+ },+ {+ name: "All statuses",+ searchParams: &query.SearchPosts{+ Statuses: []enum.PostStatus{+ enum.PostStarted,+ enum.PostCompleted,+ enum.PostDeclined,+ enum.PostDuplicate,+ enum.PostPlanned,+ enum.PostOpen,+ },+ },+ expectedCount: 6,+ expectedIDs: []int{startedPost.Result.ID, completedPost.Result.ID, newPost.Result.ID, duplicatePost.Result.ID, declinedPost.Result.ID, plannedPost.Result.ID},+ },+ {+ name: "Completed, with bug tag",+ searchParams: &query.SearchPosts{+ Statuses: []enum.PostStatus{enum.PostCompleted},+ Tags: []string{addBug.Result.Slug},+ },+ expectedCount: 1,+ expectedIDs: []int{completedPost.Result.ID},+ },+ {+ name: "Open and Completed, with bug tag",+ searchParams: &query.SearchPosts{+ Statuses: []enum.PostStatus{enum.PostCompleted, enum.PostOpen},+ Tags: []string{addBug.Result.Slug},+ },+ expectedCount: 2,+ expectedIDs: []int{completedPost.Result.ID, newPost.Result.ID},+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ err = bus.Dispatch(aryaStarkCtx, tc.searchParams)+ Expect(err).IsNil()+ Expect(tc.searchParams.Result).HasLen(tc.expectedCount)++ foundIDs := make([]int, len(tc.searchParams.Result))+ for i, post := range tc.searchParams.Result {+ foundIDs[i] = post.ID+ }+ Expect(foundIDs).ContainsOnly(tc.expectedIDs)+ })+ }++}+func TestPostStorage_IsReferenced(t *testing.T) {SetupDatabaseTest(t)defer TeardownDatabaseTest()diff --git a/locale/de/client.json b/locale/de/client.jsonindex 4cca59f92..dbf8a3411 100644--- a/locale/de/client.json+++ b/locale/de/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Die Seite wurde nicht gefunden","error.unauthorized.text": "Du bist nicht berechtigt, diese Seite anzuschauen.","error.unauthorized.title": "Nicht berechtigt",+ "home.filter.label": "","home.form.defaultinvitation": "Gib hier Deinen Vorschlag ein...","home.form.defaultwelcomemessage": "Wir würden gerne erfahren, worüber Du nachdenkst.\n\nWas können wir verbessern? Hier kannst Du abstimmen, diskutieren und neue Ideen vorschlagen.","home.lonely.suggestion": "Es wird empfohlen, dass Sie <0>mindestens 3</0> Vorschläge hier erstellen, bevor Sie diese Seite teilen. Der ursprüngliche Inhalt ist wichtig, um Ihr Publikum zu engagieren.",diff --git a/locale/el/client.json b/locale/el/client.jsonindex 9cd6f7331..65be49e14 100644--- a/locale/el/client.json+++ b/locale/el/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Η σελίδα δεν βρέθηκε","error.unauthorized.text": "Δεν έχετε δικαίωμα πρόσβασης σε αυτή τη σελίδα.","error.unauthorized.title": "Χωρίς Εξουσιοδότηση",+ "home.filter.label": "","home.form.defaultinvitation": "Εισάγετε εδώ την πρότασή σας...","home.form.defaultwelcomemessage": "Θα θέλαμε πολύ να ακούσουμε τι σκέφτεστε.\n\nΤι μπορούμε να κάνουμε καλύτερα; Αυτό είναι το μέρος για να ψηφίσετε, να συζητήσετε και να μοιραστείτε ιδέες.","home.lonely.suggestion": "Συνιστάται να δημιουργείσετε εδώ <0>τουλάχιστον 3</0> προτάσεις πριν από την κοινή χρήση αυτής της ιστοσελίδας. Το αρχικό περιεχόμενο είναι σημαντικό να αρχίσετε να προσελκύετε το κοινό σας.",diff --git a/locale/en/client.json b/locale/en/client.jsonindex 539f96172..a44d46975 100644--- a/locale/en/client.json+++ b/locale/en/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Page not found","error.unauthorized.text": "You are not authorized to view this page.","error.unauthorized.title": "Not Authorized",+ "home.filter.label": "Filter","home.form.defaultinvitation": "Enter your suggestion here...","home.form.defaultwelcomemessage": "We'd love to hear what you're thinking about.\n\nWhat can we do better? This is the place for you to vote, discuss and share ideas.","home.lonely.suggestion": "It's recommended that you create <0>at least 3</0> suggestions here before sharing this site. The initial content is important to start engaging your audience.",diff --git a/locale/es-ES/client.json b/locale/es-ES/client.jsonindex d7ecf2227..7564872a5 100644--- a/locale/es-ES/client.json+++ b/locale/es-ES/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Página no encontrada","error.unauthorized.text": "No estás autorizado para ver esta página.","error.unauthorized.title": "No está autorizado",+ "home.filter.label": "","home.form.defaultinvitation": "Escriba aquí su sugerencia...","home.form.defaultwelcomemessage": "Nos encantaría escuchar lo que estás pensando.\n\n¿Qué podemos hacer mejor? Este es el lugar para que votes, discutas y compartas ideas.","home.lonely.suggestion": "Se recomienda que cree <0>al menos 3</0> sugerencias aquí antes de compartir este sitio. El contenido inicial es importante para empezar a atraer a su audiencia.",diff --git a/locale/fr/client.json b/locale/fr/client.jsonindex 195274842..0d3b355f4 100644--- a/locale/fr/client.json+++ b/locale/fr/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Page non trouvée","error.unauthorized.text": "Vous n'êtes pas autorisé à accéder à cette page.","error.unauthorized.title": "Non autorisé",+ "home.filter.label": "","home.form.defaultinvitation": "Entrez votre suggestion ici...","home.form.defaultwelcomemessage": "Nous aimerions savoir ce que vous pensez.\n\nQue pouvons-nous faire de mieux ? C'est ici que vous pouvez voter, discuter et partager vos idées.","home.lonely.suggestion": "Il est recommandé de créer <0>au moins 3</0> suggestions avant de partager ce site. Le contenu initial est important pour commencer à engager votre public.",diff --git a/locale/it/client.json b/locale/it/client.jsonindex e86e1dea6..1d3d1d5e1 100644--- a/locale/it/client.json+++ b/locale/it/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Pagina non trovata","error.unauthorized.text": "Non sei autorizzato a visualizzare questa pagina.","error.unauthorized.title": "Non autorizzato",+ "home.filter.label": "","home.form.defaultinvitation": "Inserisci qui il tuo suggerimento...","home.form.defaultwelcomemessage": "Ci piacerebbe sentire quello che stai pensando.\n\nChe cosa possiamo fare meglio? Questo è il posto per voi per votare, discutere e condividere idee.","home.lonely.suggestion": "Si consiglia di creare <0>almeno 3</0> suggerimenti qui prima di condividere questo sito. Il contenuto iniziale è importante per iniziare ad coinvolgere il pubblico.",diff --git a/locale/nl/client.json b/locale/nl/client.jsonindex e3c0b89f1..fd08f08d0 100644--- a/locale/nl/client.json+++ b/locale/nl/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Pagina niet gevonden","error.unauthorized.text": "Je bent niet bevoegd om deze pagina te bekijken.","error.unauthorized.title": "Geen toegang",+ "home.filter.label": "","home.form.defaultinvitation": "Deel jouw suggesties hier...","home.form.defaultwelcomemessage": "We horen graag waar je aan denkt.\n\nWat kunnen we beter doen? Dit is de plek waar je op ideeën kunt stemmen en reageren, en ook je eigen ideeën kunt delen.","home.lonely.suggestion": "Het is aanbevolen om <0>tenminste 3 ideeën</0> aan te maken voor het delen van de site. De initiële inhoud is belangrijk om jouw publiek te motiveren om deel te nemen.",diff --git a/locale/pl/client.json b/locale/pl/client.jsonindex 3f19d7977..5721b1090 100644--- a/locale/pl/client.json+++ b/locale/pl/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Nie odnaleziono strony","error.unauthorized.text": "Nie masz uprawnień do przeglądania tej strony.","error.unauthorized.title": "Brak autoryzacji",+ "home.filter.label": "","home.form.defaultinvitation": "Wpisz swoją sugestię tutaj...","home.form.defaultwelcomemessage": "Chcemy się dowiedzieć o czym myślisz.\n\nCo możemy poprawić? To jest miejsce, w którym możesz głosować, dyskutować i dzielić się pomysłami.","home.lonely.suggestion": "Zaleca się stworzenie tutaj <0>co najmniej 3</0> sugestii przed udostępnieniem tej witryny. Początkowa zawartość jest ważna do zaangażowania swoich odbiorców.",diff --git a/locale/pt-BR/client.json b/locale/pt-BR/client.jsonindex e531e29e5..0cf9efad5 100644--- a/locale/pt-BR/client.json+++ b/locale/pt-BR/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Página não encontrada","error.unauthorized.text": "Você não está autorizado a visualizar esta página.","error.unauthorized.title": "Não autorizado",+ "home.filter.label": "","home.form.defaultinvitation": "Insira sua sugestão aqui...","home.form.defaultwelcomemessage": "Gostaríamos de ouvir sobre o que você está pensando.\n\nO que podemos fazer melhor? Este é o lugar para você votar, discutir e compartilhar ideias.","home.lonely.suggestion": "É recomendável que você crie <0>pelo menos 3</0> sugestões aqui antes de compartilhar este site. O conteúdo inicial é importante para começar a engajar seu público.",diff --git a/locale/ru/client.json b/locale/ru/client.jsonindex 57ddebc4a..d7a616184 100644--- a/locale/ru/client.json+++ b/locale/ru/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Страница не найдена","error.unauthorized.text": "Вы не можете просматривать эту страницу.","error.unauthorized.title": "Не авторизован",+ "home.filter.label": "","home.form.defaultinvitation": "Введите предложение здесь...","home.form.defaultwelcomemessage": "Мы хотели бы услышать ваше мнение. \n\nКак мы можем улучшиться? Здесь можно голосовать, обсуждать и делиться идеями.","home.lonely.suggestion": "Советуем создать <0>хотя бы 3</0> предложения перед публикацией этого сайта. Это важно для большего вовлечения аудитории.",diff --git a/locale/sk/client.json b/locale/sk/client.jsonindex 1b9312e7b..a9ff03f65 100644--- a/locale/sk/client.json+++ b/locale/sk/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Stránka nenájdená","error.unauthorized.text": "Nemáte oprávnenie na zobrazenie tejto stránky.","error.unauthorized.title": "Neautorizovaný",+ "home.filter.label": "","home.form.defaultinvitation": "Sem zadajte svoj návrh...","home.form.defaultwelcomemessage": "Radi by sme počuli, čo máte na mysli.\n\nČo môžeme urobiť lepšie? Tu môžete hlasovať, diskutovať a zdieľať nápady.","home.lonely.suggestion": "Pred zdieľaním tejto stránky tu odporúčame vytvoriť <0> aspoň 3 </0> návrhy. Počiatočný obsah je dôležitý, aby ste mohli zaujať publikum.",diff --git a/locale/sv-SE/client.json b/locale/sv-SE/client.jsonindex 08295b39b..1315bf657 100644--- a/locale/sv-SE/client.json+++ b/locale/sv-SE/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Sidan kunde inte hittas","error.unauthorized.text": "Du har inte behörighet att se den här sidan.","error.unauthorized.title": "Ej behörig",+ "home.filter.label": "","home.form.defaultinvitation": "Skriv ditt förslag här...","home.form.defaultwelcomemessage": "Vi vill gärna höra vad du tänker på.\n\nVad kan vi göra bättre? Detta är platsen för dig att rösta, diskutera och dela idéer.","home.lonely.suggestion": "Vi rekommenderar att du skapar <0>minst 3</0> förslag här innan du börjar dela den här webbplatsen. Det initiala innehållet är viktigt för att engagera dina besökare.",diff --git a/locale/tr/client.json b/locale/tr/client.jsonindex 9af0c41c1..c97e3f9a0 100644--- a/locale/tr/client.json+++ b/locale/tr/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "Sayfa bulunamadı","error.unauthorized.text": "Bu sayfayı görüntülemek için yetkiniz yok.","error.unauthorized.title": "Yetkili Değil",+ "home.filter.label": "","home.form.defaultinvitation": "Önerinizi buraya yazın...","home.form.defaultwelcomemessage": "Ne düşündüğünüzü öğrenmeyi çok isteriz.\n\nKendimizi nasıl geliştirebiliriz? Burada önerileri oylayabilir, tartışabilir ya da paylaşabilirsiniz.","home.lonely.suggestion": "Siteyi paylaşmadan önce buraya <0>en az 3</0> öneri girmenizi tavsiye ederiz. İlk içerikler, hedef kitlenizin etkileşime geçmesi için önemlidir.",diff --git a/locale/zh-CN/client.json b/locale/zh-CN/client.jsonindex 5c92eac5e..25b442634 100644--- a/locale/zh-CN/client.json+++ b/locale/zh-CN/client.json@@ -31,6 +31,7 @@"error.pagenotfound.title": "未找到页面","error.unauthorized.text": "您无权查看此页面.","error.unauthorized.title": "未经授权",+ "home.filter.label": "","home.form.defaultinvitation": "在此处输入您的建议...","home.form.defaultwelcomemessage": "我们很想听听你在想什么。\n\n我们能做得更好吗?这是您投票、讨论和分享想法的地方.","home.lonely.suggestion": "建议您在共享此网站之前,在此处创建<0>至少3个</0>建议。初始内容对于开始吸引观众很重要.",diff --git a/public/assets/images/heroicons-filter.svg b/public/assets/images/heroicons-filter.svgnew file mode 100644index 000000000..949a0acaf--- /dev/null+++ b/public/assets/images/heroicons-filter.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">+ <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75" />+</svg>diff --git a/public/assets/styles/variables/_text.scss b/public/assets/styles/variables/_text.scssindex 8d8ca00ef..015668900 100644--- a/public/assets/styles/variables/_text.scss+++ b/public/assets/styles/variables/_text.scss@@ -1,4 +1,4 @@-$font-base: 'Inter', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, "Noto Sans", sans-serif,+$font-base: "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, "Noto Sans", sans-serif,"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";$font-code: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;@@ -11,7 +11,7 @@ $font: ("2xs": 12px,xs: 13px,sm: 14px,- base: 15px,+ base: 16px,lg: 18px,xl: 22px,"2xl": 26px,diff --git a/public/models/post.ts b/public/models/post.tsindex 0f12c52af..0c461f6e1 100644--- a/public/models/post.ts+++ b/public/models/post.ts@@ -19,13 +19,13 @@ export interface Post {export class PostStatus {constructor(public title: string, public value: string, public show: boolean, public closed: boolean, public filterable: boolean) {}- public static Open = new PostStatus("Open", "open", false, false, false)+ public static Open = new PostStatus("Open", "open", false, false, true)public static Planned = new PostStatus("Planned", "planned", true, false, true)public static Started = new PostStatus("Started", "started", true, false, true)public static Completed = new PostStatus("Completed", "completed", true, true, true)public static Declined = new PostStatus("Declined", "declined", true, true, true)- public static Duplicate = new PostStatus("Duplicate", "duplicate", true, true, false)- public static Deleted = new PostStatus("Deleted", "deleted", false, true, false)+ public static Duplicate = new PostStatus("Duplicate", "duplicate", true, true, true)+ public static Deleted = new PostStatus("Deleted", "deleted", false, true, true)public static Get(value: string): PostStatus {for (const status of PostStatus.All) {diff --git a/public/pages/Home/components/PostFilter.tsx b/public/pages/Home/components/PostFilter.tsxindex 3aa418329..f20e4c87a 100644--- a/public/pages/Home/components/PostFilter.tsx+++ b/public/pages/Home/components/PostFilter.tsx@@ -1,37 +1,51 @@-import React, { useState } from "react"-import { PostStatus } from "@fider/models"-import { Dropdown } from "@fider/components"+import React from "react"+import { PostStatus, Tag } from "@fider/models"+import { Checkbox, Dropdown, Icon } from "@fider/components"import { HStack } from "@fider/components/layout"-import { useFider } from "@fider/hooks"-import { t, Trans } from "@lingui/macro"+import HeroIconFilter from "@fider/assets/images/heroicons-filter.svg"-interface PostFilterProps {- activeView: string- countPerStatus: { [key: string]: number }- viewChanged: (name: string) => void-}+import { useFider } from "@fider/hooks"+import { t } from "@lingui/macro"interface OptionItem {value: stringlabel: stringcount?: number+ tag?: Tag+}++interface PostFilterProps {+ activeFilter: FilterState+ countPerStatus: { [key: string]: number }+ filtersChanged: (filter: FilterState) => void+ tags: Tag[]+}+export interface FilterState {+ tags: string[]+ statuses: string[]}export const PostFilter = (props: PostFilterProps) => {const fider = useFider()- const [view, setView] = useState<string>(props.activeView)- const handleChangeView = (item: OptionItem) => () => {- setView(item.value)- props.viewChanged(item.value)+ const handleChangeFilter = (item: OptionItem) => () => {+ if (item.tag) {+ // Handle tag selection+ const newTags = props.activeFilter.tags.includes(item.value)+ ? props.activeFilter.tags.filter((t) => t !== item.value)+ : [...props.activeFilter.tags, item.value]+ const newFilters = { ...props.activeFilter, tags: newTags }+ props.filtersChanged(newFilters)+ } else {+ // Handle status selection+ const newStatuses = props.activeFilter.statuses.includes(item.value)+ ? props.activeFilter.statuses.filter((s) => s !== item.value)+ : [...props.activeFilter.statuses, item.value]+ const newFilters = { ...props.activeFilter, statuses: newStatuses }+ props.filtersChanged(newFilters)+ }}-- const options: OptionItem[] = [- { value: "trending", label: t({ id: "home.postfilter.option.trending", message: "Trending" }) },- { value: "recent", label: t({ id: "home.postfilter.option.recent", message: "Recent" }) },- { value: "most-wanted", label: t({ id: "home.postfilter.option.mostwanted", message: "Most Wanted" }) },- { value: "most-discussed", label: t({ id: "home.postfilter.option.mostdiscussed", message: "Most Discussed" }) },- ]+ const options: OptionItem[] = []if (fider.session.isAuthenticated) {options.push({ value: "my-votes", label: t({ id: "home.postfilter.option.myvotes", message: "My Votes" }) })@@ -46,23 +60,45 @@ export const PostFilter = (props: PostFilterProps) => {})})- const selectedItem = options.filter((x) => x.value === view)- const label = selectedItem.length > 0 ? selectedItem[0].label : options[0].label+ props.tags.forEach((t) => {+ options.push({+ label: t.name,+ value: t.slug,+ tag: t,+ })+ })++ const filterCount = props.activeFilter.tags.length + props.activeFilter.statuses.lengthreturn (- <HStack>- <span className="text-category">+ <HStack className="mr-4">+ {/* <span className="text-category"><Trans id="home.postfilter.label.view">View</Trans>- </span>- <Dropdown renderHandle={<div className="text-medium text-xs uppercase rounded-md uppercase bg-gray-100 px-2 py-1">{label}</div>}>- {options.map((o) => (- <Dropdown.ListItem onClick={handleChangeView(o)} key={o.value}>- <HStack spacing={2}>- <span className={view === o.value ? "text-semibold" : ""}>{o.label}</span>- <div>{o.count && o.count > 0 && <span className="bg-gray-200 inline-block rounded-full px-1 w-min-4 text-2xs text-center">{o.count}</span>}</div>- </HStack>- </Dropdown.ListItem>- ))}+ </span> */}+ <Dropdown+ renderHandle={+ <HStack className="h-10 text-medium text-xs rounded-md uppercase border border-gray-400 text-gray-800 p-2 px-3">+ <Icon sprite={HeroIconFilter} className="h-5 pr-1" />+ {t({ id: "home.filter.label", message: "Filter" })}+ {filterCount > 0 && <div className="bg-gray-200 inline-block rounded-full px-2 py-1 w-min-4 text-2xs text-center">{filterCount}</div>}+ </HStack>+ }+ >+ {options.map((o) => {+ const isChecked = o.tag ? props.activeFilter.tags.includes(o.value) : props.activeFilter.statuses.includes(o.value)+ return (+ <Dropdown.ListItem onClick={handleChangeFilter(o)} key={o.value}>+ <Checkbox field={o.value} checked={isChecked}>+ <HStack spacing={2}>+ <span className={isChecked ? "text-semibold" : ""}>{o.label}</span>+ <div className="">+ {o.count && o.count > 0 && <span className="bg-gray-200 inline-block rounded-full px-1 w-min-4 text-2xs text-center">{o.count}</span>}+ </div>+ </HStack>+ </Checkbox>+ </Dropdown.ListItem>+ )+ })}</Dropdown></HStack>)diff --git a/public/pages/Home/components/PostsContainer.scss b/public/pages/Home/components/PostsContainer.scssindex 859be367c..335c3c78b 100644--- a/public/pages/Home/components/PostsContainer.scss+++ b/public/pages/Home/components/PostsContainer.scss@@ -26,7 +26,7 @@}&__search-col {- grid-auto-columns: auto;+ grid-column: 4;&:first-child {grid-column: 1 / -1;}diff --git a/public/pages/Home/components/PostsContainer.tsx b/public/pages/Home/components/PostsContainer.tsxindex 9478ec749..efc78c160 100644--- a/public/pages/Home/components/PostsContainer.tsx+++ b/public/pages/Home/components/PostsContainer.tsx@@ -7,10 +7,10 @@ import { Loader, Input } from "@fider/components"import { actions, navigator, querystring } from "@fider/services"import IconSearch from "@fider/assets/images/heroicons-search.svg"import IconX from "@fider/assets/images/heroicons-x.svg"-import { PostFilter } from "./PostFilter"+import { PostFilter, FilterState } from "./PostFilter"import { ListPosts } from "./ListPosts"-import { TagsFilter } from "./TagsFilter"import { t, Trans } from "@lingui/macro"+import { PostsSort } from "./PostsSort"interface PostsContainerProps {user?: CurrentUser@@ -21,23 +21,28 @@ interface PostsContainerProps {interface PostsContainerState {loading: boolean- posts?: Post[]+ posts?: Post[] // All postsview: string- tags: string[]- query: string- limit?: number+ filterState: FilterState // Filter state+ query: string // Seach query+ limit?: number // Limit}export class PostsContainer extends React.Component<PostsContainerProps, PostsContainerState> {constructor(props: PostsContainerProps) {super(props)+ let view = querystring.get("view")+ if (!view) {+ view = "trending"+ }+this.state = {posts: this.props.posts,loading: false,- view: querystring.get("view"),+ view,query: querystring.get("query"),- tags: querystring.getArray("tags"),+ filterState: { tags: querystring.getArray("tags"), statuses: querystring.getArray("statuses") },limit: querystring.getNumber("limit"),}}@@ -47,23 +52,24 @@ export class PostsContainer extends React.Component<PostsContainerProps, PostsCoconst query = this.state.query.trim().toLowerCase()navigator.replaceState(querystring.stringify({- tags: this.state.tags,+ statuses: this.state.filterState.statuses,+ tags: this.state.filterState.tags,query,view: this.state.view,limit: this.state.limit,}))- this.searchPosts(query, this.state.view, this.state.limit, this.state.tags, reset)+ this.searchPosts(query, this.state.view, this.state.limit, this.state.filterState.tags, this.state.filterState.statuses, reset)})}private timer?: number- private async searchPosts(query: string, view: string, limit: number | undefined, tags: string[], reset: boolean) {+ private async searchPosts(query: string, view: string, limit: number | undefined, tags: string[], statuses: string[], reset: boolean) {window.clearTimeout(this.timer)this.setState({ posts: reset ? undefined : this.state.posts, loading: true })this.timer = window.setTimeout(() => {- actions.searchPosts({ query, view, limit, tags }).then((response) => {+ actions.searchPosts({ query, view: view, limit, tags, statuses }).then((response) => {if (response.ok && this.state.loading) {this.setState({ loading: false, posts: response.data })}@@ -71,18 +77,18 @@ export class PostsContainer extends React.Component<PostsContainerProps, PostsCo}, 500)}- private handleViewChanged = (view: string) => {- this.changeFilterCriteria({ view }, true)- }-- private handleTagsFilterChanged = (tags: string[]) => {- this.changeFilterCriteria({ tags }, true)+ private handleFilterChanged = (filterState: FilterState) => {+ this.changeFilterCriteria({ filterState }, true)}private handleSearchFilterChanged = (query: string) => {this.changeFilterCriteria({ query }, true)}+ private handleSortChanged = (view: string) => {+ this.changeFilterCriteria({ view }, true)+ }+private clearSearch = () => {this.changeFilterCriteria({ query: "" }, true)}@@ -103,11 +109,16 @@ export class PostsContainer extends React.Component<PostsContainerProps, PostsCoreturn (<div className="c-posts-container">- <div className="c-posts-container__header mb-4">+ <div className="c-posts-container__header mb-5">{!this.state.query && (<div className="c-posts-container__filter-col">- <PostFilter activeView={this.state.view} viewChanged={this.handleViewChanged} countPerStatus={this.props.countPerStatus} />- {this.props.tags.length > 0 && <TagsFilter tags={this.props.tags} selectionChanged={this.handleTagsFilterChanged} selected={this.state.tags} />}+ <PostFilter+ tags={this.props.tags}+ activeFilter={this.state.filterState}+ filtersChanged={this.handleFilterChanged}+ countPerStatus={this.props.countPerStatus}+ />+ <PostsSort onChange={this.handleSortChanged} value={this.state.view} /></div>)}<div className="c-posts-container__search-col">diff --git a/public/pages/Home/components/PostsSort.tsx b/public/pages/Home/components/PostsSort.tsxnew file mode 100644index 000000000..966fa69b3--- /dev/null+++ b/public/pages/Home/components/PostsSort.tsx@@ -0,0 +1,38 @@+import React from "react"+import { t } from "@lingui/macro"+import { Dropdown } from "@fider/components"+import { HStack } from "@fider/components/layout"++interface PostsSortProps {+ value: string+ onChange: (value: string) => void+}++export const PostsSort: React.FC<PostsSortProps> = ({ value = "trending", onChange }) => {+ const options = [+ { value: "trending", label: t({ id: "home.postfilter.option.trending", message: "Trending" }) },+ { value: "most-wanted", label: t({ id: "home.postfilter.option.mostwanted", message: "Most Wanted" }) },+ { value: "most-discussed", label: t({ id: "home.postfilter.option.mostdiscussed", message: "Most Discussed" }) },+ { value: "recent", label: t({ id: "home.postfilter.option.recent", message: "Recent" }) },+ ]++ const selectedItem = options.find((x) => x.value === value) || options[0]++ return (+ <HStack>+ <Dropdown+ renderHandle={+ <div className="h-10 flex flex-items-center text-medium text-xs rounded-md uppercase border border-gray-400 text-gray-800 p-2 px-3">+ {t({ id: "home.postsort.label", message: "Sort by:" })} {selectedItem.label}+ </div>+ }+ >+ {options.map((o) => (+ <Dropdown.ListItem key={o.value} onClick={() => onChange(o.value)}>+ <span className={value === o.value ? "text-semibold" : ""}>{o.label}</span>+ </Dropdown.ListItem>+ ))}+ </Dropdown>+ </HStack>+ )+}diff --git a/public/services/actions/post.ts b/public/services/actions/post.tsindex 39b382565..e434d7a0c 100644--- a/public/services/actions/post.ts+++ b/public/services/actions/post.ts@@ -10,12 +10,14 @@ export interface SearchPostsParams {view?: stringlimit?: numbertags?: string[]+ statuses?: string[]}export const searchPosts = async (params: SearchPostsParams): Promise<Result<Post[]>> => {return await http.get<Post[]>(`/api/v1/posts${querystring.stringify({tags: params.tags,+ statuses: params.statuses,query: params.query,view: params.view,limit: params.limit,diff --git a/public/services/querystring.ts b/public/services/querystring.tsindex 9b29fe959..08d5da4dc 100644--- a/public/services/querystring.ts+++ b/public/services/querystring.ts@@ -18,7 +18,8 @@ export const set = (name: string, value: any): string => {export const get = (name: string): string => {name = name.replace(/[[\]]/g, "\\$&")const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)")- const results = regex.exec(navigator.url())+ const url = navigator.url()+ const results = regex.exec(url)if (!results || !results[2]) {return ""