Files
jarvis/Jarvis/Views/Home/SignalFeedView.swift
Robin Kutesa feee58748c
Some checks failed
CI / Build · macos-14 · Debug (push) Has been cancelled
CI / Build · macos-15 · Debug (push) Has been cancelled
CI / Build · macos-14 · Release (push) Has been cancelled
CI / Build · macos-15 · Release (push) Has been cancelled
Sink seen/read stories, fix F1 matching, drop East Africa pill
- Sink already-seen and read stories to the bottom of the feed (new SeenStory
  model + per-load snapshot so order is stable while scrolling and refreshes
  sink what you've seen) so fresh content surfaces.
- F1 matching: clear F1 headline OR a majority of F1-feed sources, replacing the
  broad keyword list that leaked crypto in (fia -> "deFIAnt"). Dropped unused
  matchSources path.
- Remove the East Africa pill.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 14:17:32 +03:00

441 lines
17 KiB
Swift

// SignalFeedView.swift
// Jarvis home screen. Stories ranked by signal score, live connection state,
// topic filters, pull-to-refresh, infinite scroll.
import SwiftUI
import SwiftData
// Reusable wordmark: J in KisaniOrange, the rest white, weight 800, kerning -2.
struct JarvisWordmark: View {
var size: CGFloat = 30
var body: some View {
(Text("J").foregroundColor(Palette.orange) + Text("arvis").foregroundColor(.white))
.font(.system(size: size, weight: .heavy))
.kerning(-2)
}
}
struct SignalFeedView: View {
@EnvironmentObject var store: StoryStore
@EnvironmentObject var ws: WebSocketManager
@EnvironmentObject var settings: ServerSettings
@Environment(\.modelContext) private var modelContext
@Query private var cachedStories: [CachedStory]
@Query private var cachedArticles: [CachedArticle]
@Query private var readStories: [ReadStory]
@Query private var savedStories: [SavedStory]
@Query private var seenStories: [SeenStory]
@State private var showFeeds = false
@State private var showSettings = false
@State private var selectedInterest: Interest? = nil
@State private var shareStory: StorySummary?
/// Snapshot of already-seen story ids, captured per load so the order stays
/// stable while scrolling (and refreshes to sink newly-seen ones).
@State private var seenSnapshot: Set<String> = []
/// Stories that have full article content cached eligible for the green dot.
private var cachedStoryIds: Set<String> { Set(cachedArticles.map(\.storyId)) }
private var readStoryIds: Set<String> { Set(readStories.map(\.id)) }
private var savedStoryIds: Set<String> { Set(savedStories.map(\.id)) }
/// Live stories when online; cached fallback when the feed is empty & offline.
private var displayStories: [StorySummary] {
let base: [StorySummary]
if !store.stories.isEmpty {
base = store.stories.sorted(by: StorySummary.feedOrder)
} else if !ws.connectionState.isLive {
base = cachedStories.map(StorySummary.init(cached:)).sorted(by: StorySummary.feedOrder)
} else {
base = []
}
let filtered: [StorySummary]
if let interest = selectedInterest {
if interest.id == "f1" {
filtered = base.filter(interest.matches)
} else {
// Other pills (incl. Tech/Finance) exclude F1 (backend mis-tags it).
filtered = base.filter { interest.matches($0) && !Interest.f1.matches($0) }
}
} else {
// "All" is news-only: F1 lives solely under its own pill.
filtered = base.filter { !Interest.f1.matches($0) }
}
// Sink stories you've already read or seen (in a prior load) so fresh
// content surfaces and you stop seeing the same articles. Uses a per-load
// snapshot so the order is stable while you scroll.
let demoted = readStoryIds.union(seenSnapshot)
let fresh = filtered.filter { !demoted.contains($0.id) }
let old = filtered.filter { demoted.contains($0.id) }
return fresh + old
}
private func captureSeenSnapshot() { seenSnapshot = Set(seenStories.map(\.id)) }
private func markSeen(_ s: StorySummary) {
let id = s.id
guard !seenStories.contains(where: { $0.id == id }) else { return }
modelContext.insert(SeenStory(id: id))
try? modelContext.save()
}
var body: some View {
NavigationStack {
ZStack {
Color.black.ignoresSafeArea()
VStack(spacing: 0) {
header
syncBar
topicPills
columnHeaders
Divider().overlay(Palette.hairline)
feedList
}
}
.navigationBarHidden(true)
.navigationDestination(for: StorySummary.self) { story in
StoryDetailView(story: story)
}
.navigationDestination(for: ArticleRoute.self) { route in
ArticleReaderView(route: route)
}
.sheet(isPresented: $showFeeds) {
FeedManagerView()
}
.sheet(isPresented: $showSettings) {
SettingsView()
}
.sheet(item: $shareStory) { story in
ShareSheet(items: shareItems(story))
}
}
.preferredColorScheme(.dark)
.onChange(of: store.stories) { _, newValue in
cacheStories(newValue)
}
.task(id: selectedInterest?.id) {
// A filter active but nothing matched in the loaded set pull a few
// more pages so sparse interests still populate.
guard selectedInterest != nil else { return }
var pages = 0
while displayStories.isEmpty && store.hasMore && pages < 8 {
await store.loadMore()
pages += 1
}
}
}
// MARK: - Header
private var header: some View {
HStack(alignment: .center) {
JarvisWordmark(size: 30)
Spacer()
ConnectionBanner(state: ws.connectionState)
Button {
showFeeds = true
} label: {
Image(systemName: "dot.radiowaves.up.forward")
.font(.system(size: 17, weight: .semibold))
.foregroundStyle(Color(hex: "888888"))
.frame(width: 44, height: 44)
}
Button {
showSettings = true
} label: {
Image(systemName: "gearshape")
.font(.system(size: 17, weight: .semibold))
.foregroundStyle(Color(hex: "888888"))
.frame(width: 44, height: 44)
}
}
.padding(.horizontal, 16)
.padding(.top, 8)
}
// MARK: - Sync bar
private var syncBar: some View {
Text(syncText)
.font(.system(size: 11, weight: .regular, design: .monospaced))
.foregroundStyle(Color(hex: "5A5A5A"))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 16)
.padding(.bottom, 12)
}
private var syncText: String {
let ago = syncedMinutesAgo(store.lastSyncedAt)
let phrase = (ago == "just now" || ago == "never") ? ago : "\(ago) ago"
if ws.connectionState.isLive {
return "Synced \(phrase) · \(cachedStoryIds.count) cached"
} else {
return "Last synced \(phrase)"
}
}
// MARK: - Pinned interest pills
private var topicPills: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
pill("All", selected: selectedInterest == nil) { selectedInterest = nil }
ForEach(Interest.pinned) { interest in
pill(interest.label, selected: selectedInterest?.id == interest.id) {
selectedInterest = (selectedInterest?.id == interest.id) ? nil : interest
}
}
}
.padding(.horizontal, 16)
}
.padding(.bottom, 14)
}
private func pill(_ label: String, selected: Bool, action: @escaping () -> Void) -> some View {
Button(action: action) {
Text(label)
.font(.system(size: 13, weight: .bold))
.foregroundStyle(selected ? .black : Color(hex: "AAAAAA"))
.padding(.horizontal, 14)
.frame(height: 32)
.background(selected ? Palette.orange : Palette.surface)
.clipShape(Capsule())
}
}
// MARK: - Column headers
private var columnHeaders: some View {
HStack {
Text("STORY")
.kerning(0.8)
Spacer()
Text("SIGNAL ↓")
.kerning(0.8)
}
.font(.system(size: 10, weight: .bold, design: .monospaced))
.foregroundStyle(Color(hex: "555555"))
.padding(.horizontal, 16)
.padding(.bottom, 8)
}
// MARK: - Feed list
private var feedList: some View {
List {
if displayStories.isEmpty {
emptyState
.listRowInsets(EdgeInsets())
.listRowBackground(Color.black)
.listRowSeparator(.hidden)
} else {
ForEach(displayStories) { story in
NavigationLink(value: story) {
StoryRowView(story: story,
isCached: cachedStoryIds.contains(story.id),
isRead: readStoryIds.contains(story.id))
}
.listRowInsets(EdgeInsets())
.listRowBackground(Color.black)
.listRowSeparator(.hidden)
.onAppear {
markSeen(story)
if story.id == displayStories.last?.id {
Task { await store.loadMore() }
}
}
// Swipe left Save · swipe right Share + mark read
.swipeActions(edge: .trailing, allowsFullSwipe: true) {
Button { toggleSave(story) } label: {
Label(isSaved(story) ? "Saved" : "Save",
systemImage: isSaved(story) ? "bookmark.fill" : "bookmark")
}
.tint(Palette.healthActive)
}
.swipeActions(edge: .leading, allowsFullSwipe: true) {
Button {
markRead(story)
shareStory = story
} label: {
Label("Share", systemImage: "square.and.arrow.up")
}
.tint(Palette.orange)
}
}
if store.isLoadingMore {
ProgressView()
.tint(Palette.orange)
.frame(maxWidth: .infinity)
.padding(.vertical, 20)
.listRowInsets(EdgeInsets())
.listRowBackground(Color.black)
.listRowSeparator(.hidden)
}
}
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
.background(Color.black)
.onAppear { captureSeenSnapshot() }
.refreshable {
captureSeenSnapshot() // sink what you've already seen
await store.loadStories(refresh: true)
}
}
private var emptyState: some View {
VStack(spacing: 12) {
if store.isLoading {
// Actively polling the server.
ProgressView().tint(Palette.orange)
Text("Polling signals…")
.font(.system(size: 14, weight: .heavy))
.foregroundStyle(Color(hex: "AAAAAA"))
hostLine
} else if let error = store.error {
// Reached the empty state because the fetch failed.
emptyIcon("exclamationmark.triangle", color: Color(hex: "C25555"))
Text("Couldn't reach the server")
.font(.system(size: 15, weight: .heavy)).foregroundStyle(.white)
Text(error.errorDescription ?? "Unknown error")
.font(.system(size: 12)).foregroundStyle(Color(hex: "888888"))
.multilineTextAlignment(.center)
hostLine
refreshButton("Retry")
} else if !ws.connectionState.isLive {
emptyIcon("wifi.slash")
Text("Offline").font(.system(size: 15, weight: .heavy)).foregroundStyle(.white)
Text("No cached stories to show")
.font(.system(size: 12)).foregroundStyle(Color(hex: "888888"))
refreshButton("Retry")
} else if let interest = selectedInterest {
emptyIcon("line.3.horizontal.decrease.circle")
Text("No \(interest.label) stories yet")
.font(.system(size: 15, weight: .heavy)).foregroundStyle(.white)
if store.isLoadingMore || store.hasMore {
Text("Pulling more to find them…")
.font(.system(size: 12)).foregroundStyle(Color(hex: "888888"))
ProgressView().tint(Palette.orange)
} else {
Text("Nothing in the feed matched")
.font(.system(size: 12)).foregroundStyle(Color(hex: "888888"))
refreshButton("Refresh")
}
} else {
// Connected, loaded, genuinely nothing yet.
emptyIcon("antenna.radiowaves.left.and.right")
Text("No signals yet").font(.system(size: 15, weight: .heavy)).foregroundStyle(.white)
Text("Pull to refresh")
.font(.system(size: 12)).foregroundStyle(Color(hex: "888888"))
refreshButton("Refresh")
}
}
.frame(maxWidth: .infinity)
.padding(.horizontal, 32)
.padding(.top, 80)
}
private func emptyIcon(_ name: String, color: Color = Color(hex: "333333")) -> some View {
Image(systemName: name).font(.system(size: 30)).foregroundStyle(color)
}
@ViewBuilder private var hostLine: some View {
if let host = settings.host {
Text(host)
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(Color(hex: "555555"))
}
}
private func refreshButton(_ title: String) -> some View {
Button {
Task { await store.loadStories(refresh: true) }
} label: {
Text(title)
.font(.system(size: 14, weight: .bold)).foregroundStyle(.black)
.padding(.horizontal, 22).frame(height: 44)
.background(Palette.orange).clipShape(Capsule())
}
.padding(.top, 6)
}
// MARK: - Swipe actions
private func isSaved(_ s: StorySummary) -> Bool { savedStoryIds.contains(s.id) }
/// Swipe left toggle Save (bookmarks the story to the Saved tab).
private func toggleSave(_ s: StorySummary) {
let id = s.id
if let row = (try? modelContext.fetch(
FetchDescriptor<SavedStory>(predicate: #Predicate { $0.id == id })))?.first {
modelContext.delete(row)
} else {
cacheStories([s]) // keep metadata so it renders in Saved
modelContext.insert(SavedStory(id: id))
}
try? modelContext.save()
}
private func markRead(_ s: StorySummary) {
let id = s.id
let existing = try? modelContext.fetch(
FetchDescriptor<ReadStory>(predicate: #Predicate { $0.id == id }))
if existing?.first == nil {
modelContext.insert(ReadStory(id: id))
try? modelContext.save()
}
}
private func shareItems(_ s: StorySummary) -> [Any] {
var items: [Any] = ["\(s.headline)\n\n\(s.summary)\n\nvia Jarvis"]
if let first = s.sources.first, let url = URL(string: first.url) {
items.append(url)
}
return items
}
// MARK: - Caching
private func cacheStories(_ stories: [StorySummary]) {
for summary in stories {
let id = summary.id
let existing = try? modelContext.fetch(
FetchDescriptor<CachedStory>(predicate: #Predicate { $0.id == id })
)
if let found = existing?.first {
found.signalScore = summary.signalScore
found.sourceCount = summary.sourceCount
found.updatedAt = summary.updatedAt
} else {
modelContext.insert(CachedStory(from: summary))
}
}
try? modelContext.save()
}
}
// Map a cached story back into a StorySummary for offline rendering.
extension StorySummary {
init(cached: CachedStory) {
self.init(
id: cached.id,
headline: cached.headline,
summary: cached.summary,
topic: cached.topic,
signalScore: cached.signalScore,
scoreBreakdown: ScoreBreakdown(sourceAuthority: 0, freshness: 0, localRelevance: 0,
crossSourceConfirmation: 0, topicImportance: 0),
sourceCount: cached.sourceCount,
sources: [],
consensus: cached.consensus,
conflict: cached.conflict,
updatedAt: cached.updatedAt,
createdAt: cached.updatedAt
)
}
}