Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 9 additions & 22 deletions frontend/__tests__/ios/browseFeaturedHubOrder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,38 +94,25 @@ describe("#6444 — the grid orders the hubs on the clock", () => {
expect(body.match(/Date\(\)/g) ?? []).toHaveLength(1);
});

it("draws BOTH arms", () => {
// The positive half. Every "is not at the top" assertion below is also
// satisfied by a hub that is nowhere at all — and "nowhere" is a worse
// answer than the defect, because the hub keeps results and title odds all
// year. This asserts the surface is still a surface.
const body = featuredGridBody();
expect(body).toMatch(/ForEach\(hubs\.leading\)/);
expect(body).toMatch(/ForEach\(hubs\.trailing\)/);
});

it("puts the evergreen destinations BETWEEN the two arms", () => {
// The mutant this kills: both `ForEach`es adjacent at the head of the grid,
// which computes the partition, ignores it, and restores 16 September.
it("omits finished hubs.trailing and places only active hubs.leading above evergreen destinations (#13671)", () => {
// Supersedes #6444's finished-hub retention on Browse (#13662 item 8 / #13671):
// Browse removes links to finished tournaments (US Open after its edition ends)
// while active hubs still lead above the evergreen destinations.
const body = featuredGridBody();
const leading = body.indexOf("ForEach(hubs.leading)");
const trailing = body.indexOf("ForEach(hubs.trailing)");
const evergreen = body.indexOf('title: "Futures Markets"');

expect(body).toMatch(/ForEach\(hubs\.leading\)/);
expect(body).not.toMatch(/ForEach\(hubs\.trailing\)/);
expect(leading).toBeGreaterThanOrEqual(0);
expect(evergreen).toBeGreaterThan(leading);
expect(trailing).toBeGreaterThan(evergreen);
});
});

describe("#6444 — the two placements draw the same card", () => {
it("both arms render through one card builder", () => {
// A reader who finds the US Open lower down gets the tile they would have
// got at the top; the clock moves it, it does not restyle it. Two inlined
// `BrowseFeatureCard` literals would drift apart the first time either is
// touched.
describe("#6444 — active featured placements use the shared card builder", () => {
it("renders hubs through featuredHubCard and the shared clock subtitle", () => {
const body = featuredGridBody();
expect(body.match(/featuredHubCard\(/g) ?? []).toHaveLength(2);
expect(body.match(/featuredHubCard\(/g) ?? []).toHaveLength(1);

const source = stripComments(readFileSync(LEAGUES_VIEW, "utf8"));
expect(source).toMatch(/private func featuredHubCard\(/);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,18 @@ nonisolated struct ContainerDiscoveryRequest: Sendable {
["league": league.rawValue, "season": String(season), "limit": "20"]
}

private static let finishedStatuses: Set<String> = [
"final", "completed", "closed", "resolved", "settled", "finished"
]

/// The producer remains the publication authority. These checks refuse a
/// mismatched/unsupported edition or dead destination instead of guessing.
/// mismatched/unsupported edition, finished collection (#13671), or dead destination instead of guessing.
func entries(in response: ContainerDiscoveryResponse) -> [ContainerDiscoveryEntry] {
var seen = Set<String>()
return response.collections.compactMap { card in
let normalizedStatus = (card.status ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard card.canOpen, card.id > 0, card.revision >= 1,
!Self.finishedStatuses.contains(normalizedStatus),
!card.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
card.edition.league == league.rawValue, card.edition.season == season,
card.gameCount >= 0, card.questionCount >= 0,
Expand Down
10 changes: 2 additions & 8 deletions ios/Bain Luck/Bain Luck/Views/LeaguesView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -221,14 +221,8 @@ struct LeaguesView: View {
route: .dailyChallenge
)
}
// A hub whose edition is over, or that nobody dated. It sits below
// the destinations that are useful in any week and above "About",
// which is the grid's footer rather than a place to go — a finished
// tournament's results and title odds are still content, so last
// place would be a demotion further than the defect warranted.
ForEach(hubs.trailing) { tournament in
featuredHubCard(tournament, asOf: now)
}
// Finished featured hubs (`hubs.trailing`, e.g. finished US Open) are no longer
// promoted on Browse (#13662 item 8 / #13671); only live/active hubs appear above.
BrowseFeatureCard(
title: "About Bain Luck",
subtitle: "Sources and methodology",
Expand Down
11 changes: 6 additions & 5 deletions ios/Bain Luck/Bain Luck/Views/SearchView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -497,10 +497,11 @@ struct SearchView: View {
.padding(.vertical, 4)
}

// Tournaments with a hub screen. These navigate straight to the
// hub rather than seeding a text query, because the query is the
// thing that does not work: "US Open" matches no event text.
if !featuredTournaments.isEmpty {
// Tournaments currently being played, with a hub screen (#13671: omit
// finished tournaments from Browse/empty-state discovery while typed search
// below can still surface their archive hub when queried directly).
let activeTournaments = featuredTournaments.filter { $0.isBeingPlayed() }
if !activeTournaments.isEmpty {
VStack(alignment: .leading, spacing: 10) {
Text("Tournaments")
.font(.subheadline)
Expand All @@ -509,7 +510,7 @@ struct SearchView: View {
.padding(.horizontal, 4)

FlowLayout(spacing: 8) {
ForEach(featuredTournaments) { hub in
ForEach(activeTournaments) { hub in
quickSearchChip(icon: hub.icon, label: hub.title) {
path.append(Route.tournamentHub(slug: hub.slug, name: hub.title))
}
Expand Down
199 changes: 199 additions & 0 deletions ios/Bain Luck/BainLuckTests/BrowseNoFinishedEventLinks13662Tests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import SwiftUI
import UIKit
import Vision
import XCTest
@testable import Bain_Luck

@MainActor
final class BrowseNoFinishedEventLinks13662Tests: XCTestCase {

private func decodeDiscovery(_ collections: [[String: Any]]) throws -> ContainerDiscoveryResponse {
let data = try JSONSerialization.data(withJSONObject: ["collections": collections])
let d = JSONDecoder()
d.keyDecodingStrategy = .convertFromSnakeCase
return try d.decode(ContainerDiscoveryResponse.self, from: data)
}

private func nflCard(week: Int, status: String, name: String) -> [String: Any] {
[
"type": "collection",
"id": 100 + week,
"slug": "nfl-2026-week-\(week)",
"name": name,
"text": name,
"state": "published",
"revision": 10,
"edition": [
"kind": "nfl_week",
"league": "nfl",
"season": 2026,
"stage": "Regular Season",
"week": week,
],
"status": status,
"game_count": 13,
"question_count": 2100,
"matched_event_ids": [],
"destination": [
"kind": "container",
"slug": "nfl-2026-week-\(week)",
"api": "/api/containers/nfl-2026-week-\(week)",
],
]
}

private func captureWindow<V: View>(
_ view: V,
width: CGFloat = 390,
height: CGFloat = 760,
scheme: ColorScheme = .light
) -> UIImage {
let style: UIUserInterfaceStyle = scheme == .dark ? .dark : .light
let root = view
.environment(\.colorScheme, scheme)
.environment(\.horizontalSizeClass, .compact)
.environmentObject(NavigationCoordinator())
.environmentObject(AuthManager(restoreOnInit: false))
.environmentObject(PinManager(defaults: UserDefaults(suiteName: "Browse13671.\(UUID().uuidString)")!, allowLegacyGuestPins: true))

let host = hostForMeasurement(root, at: .large)
host.overrideUserInterfaceStyle = style
let rect = CGRect(x: 0, y: 0, width: width, height: height)
host.view.frame = rect

let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
let window: UIWindow = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: rect)
window.frame = rect
window.overrideUserInterfaceStyle = style
window.rootViewController = host
window.makeKeyAndVisible()
defer {
window.isHidden = true
window.rootViewController = nil
}

for _ in 0..<8 {
host.view.setNeedsLayout()
host.view.layoutIfNeeded()
RunLoop.current.run(until: Date().addingTimeInterval(0.03))
}

let fmt = UIGraphicsImageRendererFormat()
fmt.scale = 2.0
fmt.opaque = true
return UIGraphicsImageRenderer(size: rect.size, format: fmt).image { _ in
_ = window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
}
}

private func ocrLines(_ image: UIImage) throws -> [String] {
let req = VNRecognizeTextRequest()
req.recognitionLevel = .accurate
req.usesLanguageCorrection = false
try VNImageRequestHandler(cgImage: XCTUnwrap(image.cgImage)).perform([req])
return (req.results ?? []).compactMap { $0.topCandidates(1).first?.string }
}

func testContainerDiscoveryDropsFinishedNFLWeeksAndKeepsActiveWeeks() throws {
let response = try decodeDiscovery([
nflCard(week: 12, status: "scheduled", name: "NFL 2026 · Week 12 · Nov 25–30"),
nflCard(week: 11, status: "final", name: "NFL 2026 · Week 11 · Nov 19–23"),
nflCard(week: 10, status: "completed", name: "NFL 2026 · Week 10 · Nov 12–16"),
nflCard(week: 9, status: "closed", name: "NFL 2026 · Week 9 · Nov 5–9"),
])
let request = ContainerDiscoveryRequest(league: .nfl, season: 2026)
let entries = request.entries(in: response)
XCTAssertEqual(entries.map(\.id), ["nfl-2026-week-12"])
}

func testBrowseTabOmitsUSOpenAndFinishedCollectionsAt390pt() throws {
let sampleCollections = try decodeDiscovery([
nflCard(week: 12, status: "scheduled", name: "NFL 2026 · Week 12 · Nov 25–30"),
nflCard(week: 11, status: "final", name: "NFL 2026 · Week 11 · Nov 19–23"),
nflCard(week: 10, status: "final", name: "NFL 2026 · Week 10 · Nov 12–16"),
])

struct StaticDiscoveryService: ContainerDiscoveryLoading {
let nflResponse: ContainerDiscoveryResponse
func load(_ request: ContainerDiscoveryRequest) async throws -> ContainerDiscoveryResponse {
if request.league == .nfl { return nflResponse }
let data = try JSONSerialization.data(withJSONObject: ["collections": []])
let d = JSONDecoder()
d.keyDecodingStrategy = .convertFromSnakeCase
return try d.decode(ContainerDiscoveryResponse.self, from: data)
}
}

// Also test actual LeaguesView directly (verifying US Open is absent in featuredGrid)
let pureBrowseLight = captureWindow(LeaguesView(), height: 820, scheme: .light)
let pureBrowseDark = captureWindow(LeaguesView(), height: 820, scheme: .dark)
let collectionsOnly = captureWindow(
NavigationStack {
BrowseCollectionsView(service: StaticDiscoveryService(nflResponse: sampleCollections))
.padding(22)
.background(Color.groupedBackground.opacity(0.35))
},
height: 220,
scheme: .light
)

let browseLines = try ocrLines(pureBrowseLight)
XCTAssertFalse(browseLines.joined(separator: " ").contains("US Open"), "Browse must omit finished US Open card: \(browseLines)")
XCTAssertTrue(browseLines.joined(separator: " ").contains("Futures Markets"))
XCTAssertTrue(browseLines.joined(separator: " ").contains("About Bain Luck"))

let colLines = try ocrLines(collectionsOnly).joined(separator: " ")
XCTAssertTrue(colLines.contains("Week 12"), "Scheduled NFL Week 12 must stay on Browse: \(colLines)")
XCTAssertFalse(colLines.contains("Week 11"), "Finished NFL Week 11 must be filtered off Browse: \(colLines)")
XCTAssertFalse(colLines.contains("Week 10"), "Finished NFL Week 10 must be filtered off Browse: \(colLines)")

// Check SearchView empty-state omits finished US Open pill
let searchEmpty = captureWindow(SearchView(), height: 640, scheme: .light)
let searchLines = try ocrLines(searchEmpty).joined(separator: " ")
XCTAssertFalse(searchLines.contains("US Open"), "Empty Search must omit finished US Open tournament pill: \(searchLines)")

if let outDir = ProcessInfo.processInfo.environment["SHEET_13662_ITEM8_DIR"], !outDir.isEmpty {
let dir = URL(fileURLWithPath: outDir, isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)

// Composite after view (LeaguesView top + filtered Collections strip)
let combinedAfterLight = VStack(alignment: .leading, spacing: 12) {
Image(uiImage: pureBrowseLight).resizable().aspectRatio(contentMode: .fit)
Text("Filtered Collections (after #13671)").font(.caption.bold()).padding(.horizontal, 16)
Image(uiImage: collectionsOnly).resizable().aspectRatio(contentMode: .fit)
}
.frame(width: 390)
let afterLightSheet = captureWindow(combinedAfterLight, height: 1040, scheme: .light)

let panels: [(String, UIImage)] = [
("After Light (390pt · no US Open / only scheduled Week 12) · simulator results, not phone results", afterLightSheet),
("After Dark (390pt · Browse featuredGrid) · simulator results, not phone results", pureBrowseDark),
]
let padding: CGFloat = 16
let gap: CGFloat = 16
let headerH: CGFloat = 28
let totalW = panels.map { $0.1.size.width }.reduce(0, +) + gap * CGFloat(panels.count - 1) + padding * 2
let totalH = (panels.map { $0.1.size.height }.max() ?? 820) + headerH + padding * 2
let fmt = UIGraphicsImageRendererFormat()
fmt.scale = 2.0
fmt.opaque = true
let sheet = UIGraphicsImageRenderer(size: CGSize(width: totalW, height: totalH), format: fmt).image { ctx in
UIColor.systemGray6.setFill()
ctx.fill(CGRect(origin: .zero, size: CGSize(width: totalW, height: totalH)))
var x = padding
for (title, img) in panels {
let para = NSMutableParagraphStyle()
para.lineBreakMode = .byTruncatingTail
NSString(string: title).draw(
in: CGRect(x: x, y: padding, width: img.size.width, height: 22),
withAttributes: [.font: UIFont.systemFont(ofSize: 11, weight: .bold), .foregroundColor: UIColor.label, .paragraphStyle: para]
)
img.draw(at: CGPoint(x: x, y: padding + headerH))
x += img.size.width + gap
}
}
let data = try XCTUnwrap(sheet.pngData())
try data.write(to: dir.appendingPathComponent("sheet-13662-item8-browse-finished-390.png"))
}
}
}
Loading