enum TimelinePolicy { struct Visibility { let canShow: (Post) -> Bool let canShowRepostAuthor: (Post.Author?) -> Bool let follows: (Post.Author) -> Bool } static func filter( _ feedPosts: [Post], contexts: [String: [Post]], reposts: [String: Post.Author], includeUnfollowedReplies: Bool, visibility: Visibility ) -> [Post] { let feedByID = Dictionary(feedPosts.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) var seenThreads: Set = [] return feedPosts.filter { post in guard visibility.canShow(post), visibility.canShowRepostAuthor(reposts[post.id]) else { return false } let context = contexts[post.id] ?? [] let ids = [post.replyRootURI, post.replyParentURI].compactMap { $0 }.filter { $0 != post.id } let related = ids.compactMap { id in context.first { $0.id == id } ?? feedByID[id] } guard related.allSatisfy({ visibility.canShow($0) }) else { return false } if !includeUnfollowedReplies && (post.replyRootURI != nil || post.replyParentURI != nil) { guard visibility.follows(post.author) else { return false } let authors = related.map(\.author) + [post.replyGrandparentAuthor].compactMap { $0 } let isSelfThread = authors.allSatisfy { $0.id == post.author.id } let hasFollowedConnection = authors.contains { $0.id != post.author.id && visibility.follows($0) } guard isSelfThread || hasFollowedConnection else { return false } } return seenThreads.insert(post.replyRootURI ?? post.id).inserted } } }