diff --git a/Sources/WordPressData/Swift/Post.swift b/Sources/WordPressData/Swift/Post.swift index 46a0621b1e5b..add91a2e68ae 100644 --- a/Sources/WordPressData/Swift/Post.swift +++ b/Sources/WordPressData/Swift/Post.swift @@ -219,14 +219,14 @@ public class Post: AbstractPost { if let preview = PostPreviewCache.shared.excerpt[excerpt] { return preview } - let preview = excerpt.makePlainText().withCollapsedNewlines() + let preview = excerpt.makePlainText().withCollapsedNewlines().trimmedForPreview() PostPreviewCache.shared.excerpt[excerpt] = preview return preview } else if let content { if let preview = PostPreviewCache.shared.content[content] { return preview } - let preview = GutenbergExcerptGenerator.firstParagraph(from: content, maxLength: 200).withCollapsedNewlines() + let preview = GutenbergExcerptGenerator.firstParagraph(from: content, maxLength: 200).withCollapsedNewlines().trimmedForPreview() PostPreviewCache.shared.content[content] = preview return preview } else { @@ -253,6 +253,11 @@ private extension String { func withCollapsedNewlines() -> String { replacingOccurrences(of: "[\n]{2,}", with: "\n", options: .regularExpression) } + + // Remove leading/trailing line breaks to avoid rendering blank trailing lines in preview labels. + func trimmedForPreview() -> String { + trimmingCharacters(in: .whitespacesAndNewlines) + } } private final class PostPreviewCache { diff --git a/Tests/KeystoneTests/Tests/Models/PostTests.swift b/Tests/KeystoneTests/Tests/Models/PostTests.swift index bef189b9d973..af8a71bca73b 100644 --- a/Tests/KeystoneTests/Tests/Models/PostTests.swift +++ b/Tests/KeystoneTests/Tests/Models/PostTests.swift @@ -259,6 +259,15 @@ class PostTests: CoreDataTestCase { XCTAssertEqual(post.contentPreviewForDisplay(), "some contents\u{A0}go here") } + func testThatContentPreviewForDisplayTrimsLeadingAndTrailingNewlines() { + let post = newTestPost() + + post.content = "
Paragraph 1
Paragraph 2
" + let preview = post.contentPreviewForDisplay() + + XCTAssertEqual("Paragraph 1\nParagraph 2", preview) + } + func testThatEnablingDisablingPublicizeConnectionsWorks() { let post = newTestPost()