From ad138c3017832f14ae452969816f9e4e7ce5237e Mon Sep 17 00:00:00 2001 From: Nazar Kanaev Date: Wed, 4 Dec 2024 21:36:44 +0000 Subject: [PATCH] show article content in the list if the title is missing --- src/content/htmlutil/utils.go | 14 ++++++++++++++ src/content/htmlutil/utils_test.go | 18 ++++++++++++++++++ src/server/routes.go | 9 ++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/content/htmlutil/utils.go b/src/content/htmlutil/utils.go index 5f66ae8..10918e7 100644 --- a/src/content/htmlutil/utils.go +++ b/src/content/htmlutil/utils.go @@ -4,6 +4,7 @@ import ( "bytes" "regexp" "strings" + "unicode" "golang.org/x/net/html" ) @@ -61,3 +62,16 @@ func ExtractText(content string) string { text = whitespaceRegex.ReplaceAllLiteralString(text, " ") return text } + +func TruncateText(input string, size int) string { + runes := []rune(input) + if len(runes) <= size { + return input + } + for i := size - 1; i > 0; i-- { + if unicode.IsSpace(runes[i]) { + return string(runes[:i]) + " ..." + } + } + return input +} diff --git a/src/content/htmlutil/utils_test.go b/src/content/htmlutil/utils_test.go index eb9e522..0d86f5e 100644 --- a/src/content/htmlutil/utils_test.go +++ b/src/content/htmlutil/utils_test.go @@ -24,3 +24,21 @@ func TestExtractText(t *testing.T) { } } } + +func TestTruncateText(t *testing.T) { + input := "Lorem ipsum — классический текст-«рыба»" + + size := 30 + want := "Lorem ipsum — классический ..." + have := TruncateText(input, size) + if want != have { + t.Errorf("\nsize: %d\nwant: %#v\nhave: %#v", size, want, have) + } + + size = 1000 + want = input + have = TruncateText(input, size) + if want != have { + t.Errorf("\nsize: %d\nwant: %#v\nhave: %#v", size, want, have) + } +} diff --git a/src/server/routes.go b/src/server/routes.go index 6d05320..aa810be 100644 --- a/src/server/routes.go +++ b/src/server/routes.go @@ -371,12 +371,19 @@ func (s *Server) handleItemList(c *router.Context) { } newestFirst := query.Get("oldest_first") != "true" - items := s.db.ListItems(filter, perPage+1, newestFirst, false) + items := s.db.ListItems(filter, perPage+1, newestFirst, true) hasMore := false if len(items) == perPage+1 { hasMore = true items = items[:perPage] } + + for i, item := range items { + if item.Title == "" { + text := htmlutil.ExtractText(item.Content) + items[i].Title = htmlutil.TruncateText(text, 140) + } + } c.JSON(http.StatusOK, map[string]interface{}{ "list": items, "has_more": hasMore,