From add01455fba91e6b96b6fe13c3be306773afc6bc Mon Sep 17 00:00:00 2001 From: Yury Kotov Date: Tue, 13 Jun 2023 00:42:15 +0200 Subject: [PATCH] Fix snippet generation 1) Current implementation simply removes the last word, without truncating up to limit length. 2) In case if even the first word (magnet link or some base64?) is too long don't add extra space. --- backend/app/store/comment.go | 6 +++++- backend/app/store/comment_test.go | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/backend/app/store/comment.go b/backend/app/store/comment.go index bd7c09f6..ad505163 100644 --- a/backend/app/store/comment.go +++ b/backend/app/store/comment.go @@ -146,7 +146,7 @@ func (c *Comment) Snippet(limit int) string { if size < limit { return cleanText } - snippet := []rune(cleanText)[:size] + snippet := []rune(cleanText)[:limit] // go back in snippet and found the first space for i := len(snippet) - 1; i >= 0; i-- { if snippet[i] == ' ' { @@ -154,6 +154,10 @@ func (c *Comment) Snippet(limit int) string { break } } + // Don't add a space if comment is just a one single word which has been truncated. + if len(snippet) == limit { + return string(snippet) + "..." + } return string(snippet) + " ..." } diff --git a/backend/app/store/comment_test.go b/backend/app/store/comment_test.go index f0043341..2716d056 100644 --- a/backend/app/store/comment_test.go +++ b/backend/app/store/comment_test.go @@ -196,8 +196,8 @@ func TestComment_Snippet(t *testing.T) { {0, "", ""}, {-1, "test\nblah", "test blah"}, {5, "test\nblah", "test ..."}, - {5, "xyz12345 xxx", "xyz12345 ..."}, - {10, "xyz12345 xxx\ntest 123456", "xyz12345 xxx test ..."}, + {5, "xyz12345 xxx", "xyz12..."}, + {10, "xyz12345 xxx\ntest 123456", "xyz12345 ..."}, } for i, tt := range tbl {