Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
feat: redesign game pages with Steam screenshot galleries
Matias G.f6508c1825b3
diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex d280323..c89a160 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -1,12 +1,16 @@import SwiftUIimport HighballKit-/// A game's page (UX plan §3.5): a verdict written as a sentence, Play as the only button, an-/// honest list of what Play will do, and every identifier behind one Advanced triangle.+/// Media and store copy alongside the existing launch plan; game settings stay inline below.struct GameDetailView: View {@Environment(AppState.self) private var statelet passedItem: LibraryItem- @State private var coverDropTargeted = false+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var storeDetails: SteamGameDetails?+ @State private var loadingDetails = false+ @State private var expandedDescription = false+ @State private var selectedGalleryURL: URL?+ @State private var choseGalleryImage = false/// The launch arguments being typed; saved on Return and when the page closes, so a space/// typed between two arguments is not normalised away mid-word.@State private var argsText = ""@@ -42,65 +46,159 @@ struct GameDetailView: View {}private var engineName: String? { bottle.flatMap { state.engine(for: $0) }?.displayName }+ private var storeAppID: Int? { item.steamAppID ?? entry?.steam_appid }+var body: some View {- ScrollView {- VStack(alignment: .leading, spacing: 18) {- hero- if let macBuild { macBlock(macBuild) }- verdictBlock- playRow- if item.installed, !blocked { willDoCard }- advanced- Spacer(minLength: 0)+ GeometryReader { geometry in+ ScrollViewReader { scroll in+ ScrollView {+ VStack(alignment: .leading, spacing: 32) {+ let width = max(0, min(geometry.size.width - 64, 1320))+ if width >= 860 {+ HStack(alignment: .top, spacing: 32) {+ GameMediaGallery(item: item, details: storeDetails, width: (width - 32) * 0.58,+ selectedURL: $selectedGalleryURL, choseImage: $choseGalleryImage)+ .frame(width: (width - 32) * 0.58)+ overview(scroll: scroll)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ } else {+ GameMediaGallery(item: item, details: storeDetails, width: width,+ selectedURL: $selectedGalleryURL, choseImage: $choseGalleryImage)+ overview(scroll: scroll)+ }+ aboutGame+ if bottle != nil {+ advanced.id("game-settings")+ }+ }+ .padding(32)+ .frame(maxWidth: 1384, alignment: .leading)+ .frame(maxWidth: .infinity)+ }}- .padding(.horizontal, 28).padding(.vertical, 20)- .frame(maxWidth: 680, alignment: .leading)- .frame(maxWidth: .infinity, alignment: .leading)}.background(BottleBackdrop()).navigationTitle(state.displayTitle(item))+ .task(id: storeAppID) {+ storeDetails = nil+ expandedDescription = false+ guard let appID = storeAppID else { loadingDetails = false; return }+ loadingDetails = true+ let language: SteamGameDetailsStore.Language = Locale.preferredLanguages.first?.hasPrefix("fr") == true ? .french : .english+ let details = await SteamGameDetailsStore.shared.details(appID: appID, language: language)+ guard !Task.isCancelled else { return }+ storeDetails = details+ loadingDetails = false+ }}- // MARK: Pieces-- private var hero: some View {- ZStack(alignment: .bottomLeading) {- Color.clear- .aspectRatio(460 / 215, contentMode: .fit)- .frame(maxWidth: 640)- .overlay {- // A chosen cover wins here as it does on the tile (#64: it never reached- // the page, which read the store's artwork only).- if let custom = state.coverStore.coverURL(for: item.id), let image = NSImage(contentsOf: custom) {- Image(nsImage: image).resizable().scaledToFill().id(state.coverVersion)- } else {- AsyncImage(url: item.artworkWide ?? item.artworkTall) { phase in- if case .success(let image) = phase {- image.resizable().scaledToFill()- } else {- ZStack {- LinearGradient(colors: [HB.card, HB.ground], startPoint: .top, endPoint: .bottom)- Image(systemName: "gamecontroller").font(.largeTitle).foregroundStyle(.quaternary)- }- }+ private func overview(scroll: ScrollViewProxy) -> some View {+ VStack(alignment: .leading, spacing: 20) {+ Text(state.displayTitle(item))+ .font(.system(size: 30, weight: .bold, design: .rounded))+ .fixedSize(horizontal: false, vertical: true)+ .textSelection(.enabled)+ HStack(alignment: .top, spacing: 10) {+ playRow.frame(maxWidth: .infinity, alignment: .leading)+ if bottle != nil {+ Button {+ withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.2)) {+ showAdvanced = true+ scroll.scrollTo("game-settings", anchor: .top)}+ } label: {+ Image(systemName: "gearshape.fill").font(.title3)+ .frame(width: 24, height: 30).padding(8)}+ .buttonStyle(.bordered)+ .accessibilityLabel(L("Game settings"))+ .help(L("Game settings"))}- .clipped()- LinearGradient(colors: [.black.opacity(0.8), .clear], startPoint: .bottom, endPoint: .center)- .frame(maxWidth: 640)- Text(state.displayTitle(item))- .font(.system(size: 24, weight: .bold, design: .rounded))- .foregroundStyle(.white).shadow(radius: 4)- .padding(14)+ }+ verdictBlock+ if item.installed, !blocked { willDoCard }+ libraryInfo+ if let macBuild { macBlock(macBuild) }}- .clipShape(RoundedRectangle(cornerRadius: 12))- // Same as the tile: an image dropped on the hero becomes this game's cover (#175).- .onDrop(of: [.image], isTargeted: $coverDropTargeted) { providers in- state.acceptCoverDrop(providers, for: item)+ }++ private var libraryInfo: some View {+ VStack(alignment: .leading, spacing: 12) {+ row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games" : L("Windows program"))+ if item.sizeOnDisk > 0 {+ row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))+ }+ if let played = item.lastPlayed {+ row(L("Last played"), played.formatted(date: .abbreviated, time: .shortened))+ }+ }+ .padding(18).frame(maxWidth: .infinity, alignment: .leading)+ .background(HB.card, in: RoundedRectangle(cornerRadius: 16))+ .overlay(RoundedRectangle(cornerRadius: 16).stroke(HB.cardStroke))+ }++ @ViewBuilder private var aboutGame: some View {+ if let details = storeDetails {+ VStack(alignment: .leading, spacing: 18) {+ HStack {+ Text(L("About this game")).font(.title2.bold())+ Spacer()+ Link(destination: details.storeURL) { Label(L("View on Steam"), systemImage: "arrow.up.right") }+ .font(.callout)+ }+ if !details.summary.isEmpty {+ Text(verbatim: details.summary).font(.body).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)+ }+ if !details.description.isEmpty, details.description != details.summary {+ DisclosureGroup(L("Read more"), isExpanded: $expandedDescription) {+ Text(verbatim: details.description).font(.body).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading).padding(.top, 10)+ }+ }+ if !details.genres.isEmpty {+ Text(verbatim: details.genres.joined(separator: " · "))+ .font(.callout.weight(.medium)).foregroundStyle(HB.amber)+ }+ ViewThatFits(in: .horizontal) {+ HStack(alignment: .top, spacing: 40) { storeFacts(details) }+ VStack(alignment: .leading, spacing: 16) { storeFacts(details) }+ }+ Text(L("Game information and screenshots from Steam.")).font(.caption).foregroundStyle(.tertiary)+ }+ .padding(24).frame(maxWidth: .infinity, alignment: .leading)+ .background(HB.card, in: RoundedRectangle(cornerRadius: 18))+ .overlay(RoundedRectangle(cornerRadius: 18).stroke(HB.cardStroke))+ } else if storeAppID != nil {+ HStack(spacing: 10) {+ if loadingDetails {+ ProgressView().controlSize(.small)+ Text(L("Loading game information…")).font(.callout).foregroundStyle(.secondary)+ } else {+ Text(L("Steam information is unavailable. You can still play and manage this game."))+ .font(.callout).foregroundStyle(.secondary)+ Spacer()+ if let appID = storeAppID, let url = URL(string: "https://store.steampowered.com/app/\(appID)/") {+ Link(L("View on Steam"), destination: url).font(.callout)+ }+ }+ }}- .overlay(RoundedRectangle(cornerRadius: 12)- .stroke(coverDropTargeted ? HB.amber : HB.cardStroke, lineWidth: coverDropTargeted ? 2 : 1))+ }++ @ViewBuilder private func storeFacts(_ details: SteamGameDetails) -> some View {+ if !details.developers.isEmpty { storeFact(L("Developer"), details.developers.joined(separator: ", ")) }+ if !details.publishers.isEmpty { storeFact(L("Publisher"), details.publishers.joined(separator: ", ")) }+ if let date = details.releaseDate { storeFact(L("Release date"), date) }+ }++ private func storeFact(_ label: String, _ value: String) -> some View {+ VStack(alignment: .leading, spacing: 4) {+ Text(label).font(.caption).foregroundStyle(.tertiary)+ Text(verbatim: value).font(.callout).textSelection(.enabled)+ }.fixedSize(horizontal: false, vertical: true)}private var verdictColor: Color {@@ -165,10 +263,15 @@ struct GameDetailView: View {}}+ private func primaryActionLabel(_ title: String, symbol: String) -> some View {+ Label(title, systemImage: symbol).font(.title3.weight(.semibold))+ .frame(maxWidth: .infinity).padding(.vertical, 8)+ }+private var playRow: some View {- HStack(spacing: 14) {+ VStack(alignment: .leading, spacing: 10) {if let running {- Button(L("Stop")) { state.stopSession(running) }.buttonStyle(.bordered).controlSize(.large)+ Button { state.stopSession(running) } label: { primaryActionLabel(L("Stop"), symbol: "stop.fill") }.buttonStyle(.bordered).controlSize(.large)TimelineView(.periodic(from: .now, by: 15)) { ctx inText(ActivityText.minutes(since: running.started, now: ctx.date).map { String(format: L("Running for %d min"), $0) } ?? L("Running"))@@ -177,7 +280,7 @@ struct GameDetailView: View {} else if state.prefersMacBuild(item) {// The native build first; a Windows copy in a bottle stays one click away.Button { state.playOnMac(item) } label: {- Label(L("Play on Mac"), systemImage: "play.fill").frame(minWidth: 96)+ primaryActionLabel(L("Play on Mac"), symbol: "play.fill")}.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber)if item.installed {@@ -188,7 +291,7 @@ struct GameDetailView: View {}} else if item.installed {Button { state.play(item) } label: {- Label(L("Play"), systemImage: "play.fill").frame(minWidth: 96)+ primaryActionLabel(L("Play"), symbol: "play.fill")}.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy || blocked)@@ -202,16 +305,16 @@ struct GameDetailView: View {.font(.callout).foregroundStyle(.secondary)}} else if item.source == .epic {- Button(L("Install")) { state.install(item) }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber)+ Button { state.install(item) } label: { primaryActionLabel(L("Install"), symbol: "arrow.down") }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy)Text(String(format: L("Installs into %@."), state.defaultBottle?.name ?? L("your environment"))).font(.callout).foregroundStyle(.secondary)} else if item.source == .steam, !steamHasManifest, state.macSteamBuild(for: item) != nil {// A native build exists: that's the install on offer; the Windows one is the// way around it, not the default.VStack(alignment: .leading, spacing: 6) {- HStack(spacing: 14) {+ VStack(alignment: .leading, spacing: 10) {Button { state.installOnMac(item) } label: {- Label(state.steamForMacInstalled ? L("Install on Mac") : L("Get Steam for Mac"), systemImage: "apple.logo")+ primaryActionLabel(state.steamForMacInstalled ? L("Install on Mac") : L("Get Steam for Mac"), symbol: "apple.logo")}.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber)Text(state.steamForMacInstalled ? L("Steam for Mac asks where to put it.")@@ -224,7 +327,7 @@ struct GameDetailView: View {}} else if item.source == .steam, !steamHasManifest {// Owned, never installed here (highball#199): Steam's own dialog takes it from here.- Button(L("Install")) { state.install(item) }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber)+ Button { state.install(item) } label: { primaryActionLabel(L("Install"), symbol: "arrow.down") }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy)Text(L("Steam asks where to put it.")).font(.callout).foregroundStyle(.secondary)} else if item.source == .steam {@@ -266,20 +369,20 @@ struct GameDetailView: View {Text(entry == nil ? L("No row in the compatibility database yet.") : L("From the open compatibility database.")).font(.caption).foregroundStyle(.secondary)if entry != nil {- Button(L("Why these settings?")) { showWhy.toggle() }+ Button(L("Why these settings?")) { withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.15)) { showWhy.toggle() } }.buttonStyle(.link).font(.caption)- .popover(isPresented: $showWhy, arrowEdge: .bottom) { whyPopover }}}+ if showWhy { whyExplanation }}- .padding(14)+ .padding(18).frame(maxWidth: .infinity, alignment: .leading)- .background(RoundedRectangle(cornerRadius: 10).fill(HB.card))- .overlay(RoundedRectangle(cornerRadius: 10).stroke(HB.cardStroke))+ .background(RoundedRectangle(cornerRadius: 16).fill(HB.card))+ .overlay(RoundedRectangle(cornerRadius: 16).stroke(HB.cardStroke))}/// The explanation, and the way out: the environment's own settings are one click away.- private var whyPopover: some View {+ private var whyExplanation: some View {VStack(alignment: .leading, spacing: 10) {Text(L("Why these settings")).font(.headline)if let notes = entry?.notes { Text(notes).font(.callout) }@@ -296,10 +399,10 @@ struct GameDetailView: View {}}Divider()- Text(L("To play with the environment's own graphics mode instead, change it under Advanced below; Highball then leaves it alone for every game in that environment."))+ Text(L("To play with the environment's own graphics mode instead, change it under Game settings below; Highball then leaves it alone for every game in that environment.")).font(.caption).foregroundStyle(.secondary)}- .padding(16).frame(width: 420)+ .padding(.top, 8).frame(maxWidth: .infinity, alignment: .leading)}private var advanced: some View {@@ -456,9 +559,9 @@ struct GameDetailView: View {.padding(.top, 10)} label: {// The whole row toggles, not only the chevron.- Button { withAnimation(.easeInOut(duration: 0.15)) { showAdvanced.toggle() } } label: {+ Button { withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.15)) { showAdvanced.toggle() } } label: {HStack(spacing: 8) {- Text(L("Advanced")).font(.callout.weight(.medium))+ Text(L("Game settings")).font(.headline)Text(L("graphics mode · engine · environment · files")).font(.caption.monospaced()).foregroundStyle(.tertiary)Spacer(minLength: 0)}@@ -466,16 +569,6 @@ struct GameDetailView: View {}.buttonStyle(.plain)}- Divider()- VStack(alignment: .leading, spacing: 8) {- row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games" : L("Windows program"))- if item.sizeOnDisk > 0 {- row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))- }- if let played = item.lastPlayed {- row(L("Last played"), played.formatted(date: .abbreviated, time: .shortened))- }- }}.padding(.top, 6)}diff --git a/Sources/HighballApp/GameMediaGallery.swift b/Sources/HighballApp/GameMediaGallery.swiftnew file mode 100644index 0000000..bd4f314--- /dev/null+++ b/Sources/HighballApp/GameMediaGallery.swift@@ -0,0 +1,136 @@+import SwiftUI+import HighballKit++/// A single full-size image and lazy thumbnails: no web view, video player, or slideshow timer.+struct GameMediaGallery: View {+ @Environment(AppState.self) private var state+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ let item: LibraryItem+ let details: SteamGameDetails?+ let width: CGFloat+ @Binding var selectedURL: URL?+ @Binding var choseImage: Bool+ @State private var coverDropTargeted = false++ private var screenshots: [SteamGameDetails.Screenshot] { details?.screenshots ?? [] }+ private var customCover: NSImage? {+ guard let url = state.coverStore.coverURL(for: item.id) else { return nil }+ return NSImage(contentsOf: url)+ }+ private var artworkURL: URL? { item.artworkWide ?? details?.header ?? item.artworkTall }+ private var selection: Int { selectedURL.flatMap { url in screenshots.firstIndex { $0.full == url }.map { $0 + 1 } } ?? 0 }++ var body: some View {+ VStack(spacing: 12) {+ Color.black.opacity(0.24)+ .frame(height: width * 9 / 16)+ .overlay {+ GalleryImage(url: selectedURL ?? artworkURL, local: selectedURL == nil ? customCover : nil)+ .id("\(selectedURL?.absoluteString ?? "cover")-\(state.coverVersion)")+ .transition(.opacity)+ .accessibilityElement(children: .ignore)+ .accessibilityLabel(selectedURL == nil ? L("Game artwork") : String(format: L("Screenshot %d"), selection))+ }+ .overlay(alignment: .bottomTrailing) {+ if !screenshots.isEmpty {+ HStack(spacing: 10) {+ Button { select((selection + screenshots.count) % (screenshots.count + 1)) } label: {+ Image(systemName: "chevron.left").frame(width: 28, height: 28)+ }.accessibilityLabel(L("Previous image"))+ Text("\(selection + 1) / \(screenshots.count + 1)").font(.caption.monospacedDigit())+ Button { select((selection + 1) % (screenshots.count + 1)) } label: {+ Image(systemName: "chevron.right").frame(width: 28, height: 28)+ }.accessibilityLabel(L("Next image"))+ }+ .buttonStyle(.plain).foregroundStyle(.white)+ .padding(4).padding(.horizontal, 4)+ .background(.ultraThinMaterial, in: Capsule())+ .padding(14)+ }+ }+ .clipShape(RoundedRectangle(cornerRadius: 20))+ .overlay(RoundedRectangle(cornerRadius: 20)+ .stroke(coverDropTargeted ? HB.amber : HB.cardStroke, lineWidth: coverDropTargeted ? 2 : 1))+ .onDrop(of: [.image], isTargeted: $coverDropTargeted) { providers in+ let accepted = state.acceptCoverDrop(providers, for: item)+ if accepted { selectedURL = nil; choseImage = true }+ return accepted+ }++ if !screenshots.isEmpty {+ ScrollViewReader { scroll in+ ScrollView(.horizontal, showsIndicators: false) {+ LazyHStack(spacing: 10) {+ thumbnail(index: 0, url: artworkURL, local: customCover)+ ForEach(Array(screenshots.enumerated()), id: \.element.full) { index, screenshot in+ thumbnail(index: index + 1, url: screenshot.thumbnail)+ }+ }.padding(2)+ }+ .frame(height: 76)+ .onChange(of: selection) { _, index in+ withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) { scroll.scrollTo(index, anchor: .center) }+ }+ }+ }+ }+ .onAppear { pickInitialImage() }+ .onChange(of: details?.appID) { _, _ in+ pickInitialImage()+ }+ .onChange(of: state.coverVersion) { _, _ in selectedURL = nil; choseImage = true }+ }++ private func pickInitialImage() {+ if !choseImage, customCover == nil { selectedURL = screenshots.first?.full }+ }++ private func thumbnail(index: Int, url: URL?, local: NSImage? = nil) -> some View {+ Button { select(index) } label: {+ Color.black.opacity(0.24)+ .frame(width: 128, height: 72)+ .overlay { GalleryImage(url: url, local: local, thumbnail: true) }+ .clipShape(RoundedRectangle(cornerRadius: 9))+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(index == selection ? HB.amber : HB.cardStroke, lineWidth: index == selection ? 2 : 1))+ }+ .buttonStyle(.plain)+ .id(index)+ .accessibilityLabel(index == 0 ? L("Game artwork") : String(format: L("Screenshot %d"), index))+ .accessibilityAddTraits(index == selection ? .isSelected : [])+ }++ private func select(_ index: Int) {+ choseImage = true+ withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) {+ selectedURL = index == 0 ? nil : screenshots[index - 1].full+ }+ }+}++private struct GalleryImage: View {+ let url: URL?+ var local: NSImage? = nil+ var thumbnail = false++ var body: some View {+ if let local = local ?? url.flatMap({ $0.isFileURL ? NSImage(contentsOf: $0) : nil }) {+ Image(nsImage: local).resizable().scaledToFit()+ } else if let url {+ AsyncImage(url: url) { phase in+ switch phase {+ case .success(let image): image.resizable().scaledToFit()+ case .empty:+ if thumbnail { placeholder } else { ProgressView().controlSize(.small) }+ default: placeholder+ }+ }+ } else { placeholder }+ }++ private var placeholder: some View {+ VStack(spacing: 8) {+ Image(systemName: "gamecontroller").font(thumbnail ? .body : .system(size: 40, weight: .light))+ if !thumbnail { Text(L("No image available")).font(.callout) }+ }.foregroundStyle(.secondary).frame(maxWidth: .infinity, maxHeight: .infinity)+ }+}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex a130964..66b4d2f 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -9,6 +9,22 @@ func L(_ en: String) -> String {enum L10n {static let fr: [String: String] = [+ "Game settings": "Réglages du jeu",+ "About this game": "À propos de ce jeu",+ "View on Steam": "Voir sur Steam",+ "Read more": "Lire la suite",+ "Developer": "Développeur",+ "Publisher": "Éditeur",+ "Release date": "Date de sortie",+ "Game information and screenshots from Steam.": "Informations et captures d’écran fournies par Steam.",+ "Loading game information…": "Chargement des informations du jeu…",+ "Steam information is unavailable. You can still play and manage this game.": "Les informations Steam sont indisponibles. Vous pouvez toujours jouer et gérer ce jeu.",+ "Previous image": "Image précédente",+ "Next image": "Image suivante",+ "Game artwork": "Visuel du jeu",+ "Screenshot %d": "Capture d’écran %d",+ "No image available": "Aucune image disponible",+ "To play with the environment's own graphics mode instead, change it under Game settings below; Highball then leaves it alone for every game in that environment.": "Pour jouer avec le mode graphique de l’environnement, modifiez-le dans les Réglages du jeu ci-dessous ; Highball le conserve alors pour tous les jeux de cet environnement.","Back": "Retour","Display": "Affichage","Changes save automatically": "Les modifications sont enregistrées automatiquement",diff --git a/Sources/HighballKit/SteamGameDetails.swift b/Sources/HighballKit/SteamGameDetails.swiftnew file mode 100644index 0000000..a534017--- /dev/null+++ b/Sources/HighballKit/SteamGameDetails.swift@@ -0,0 +1,136 @@+import Foundation++/// Presentation data from the Steam store. This never changes compatibility or launch settings.+public struct SteamGameDetails: Codable, Sendable, Equatable {+ public struct Screenshot: Codable, Sendable, Equatable {+ public let thumbnail: URL+ public let full: URL+ }++ public let appID: Int+ public let summary: String+ public let description: String+ public let header: URL?+ public let screenshots: [Screenshot]+ public let developers: [String]+ public let publishers: [String]+ public let genres: [String]+ public let releaseDate: String?++ public var storeURL: URL { URL(string: "https://store.steampowered.com/app/\(appID)/")! }++ /// Delisted games, malformed replies and replies for another app are unavailable, not empty games.+ static func parse(_ data: Data, appID: Int) -> Self? {+ guard let response = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let app = response[String(appID)] as? [String: Any], app["success"] as? Bool == true,+ let fields = app["data"] as? [String: Any], fields["steam_appid"] as? Int == appID else { return nil }+ let screenshots = (fields["screenshots"] as? [[String: Any]] ?? []).compactMap { screenshot -> Screenshot? in+ guard let thumbnail = imageURL(screenshot["path_thumbnail"] as? String),+ let full = imageURL(screenshot["path_full"] as? String) else { return nil }+ return Screenshot(thumbnail: thumbnail, full: full)+ }+ var seen = Set<URL>()+ let release = fields["release_date"] as? [String: Any]+ let date = (release?["date"] as? String).map(plainText)+ return Self(appID: appID,+ summary: plainText(fields["short_description"] as? String ?? ""),+ description: plainText(fields["about_the_game"] as? String ?? ""),+ header: imageURL(fields["header_image"] as? String),+ screenshots: Array(screenshots.filter { seen.insert($0.full).inserted }.prefix(20)),+ developers: (fields["developers"] as? [String] ?? []).map(plainText),+ publishers: (fields["publishers"] as? [String] ?? []).map(plainText),+ genres: (fields["genres"] as? [[String: Any]] ?? []).compactMap { ($0["description"] as? String).map(plainText) },+ releaseDate: date?.isEmpty == false ? date : nil)+ }++ private static func imageURL(_ text: String?) -> URL? {+ guard let text, let url = URL(string: text), url.scheme == "https", let host = url.host,+ host == "steamstatic.com" || host.hasSuffix(".steamstatic.com") ||+ host == "steamusercontent.com" || host.hasSuffix(".steamusercontent.com") else { return nil }+ return url+ }++ /// Render store copy as text, without a web view or HTML's remote image/script loading.+ static func plainText(_ html: String) -> String {+ var text = html.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")+ text = text.replacingOccurrences(of: "(?is)<(script|style)\\b[^>]*>.*?</\\1>", with: "", options: .regularExpression)+ text = text.replacingOccurrences(of: "(?i)<br\\s*/?>|</(?:p|div|h[1-6]|ul|ol)\\s*>", with: "\n\n", options: .regularExpression)+ text = text.replacingOccurrences(of: "(?i)<li\\b[^>]*>", with: "\n• ", options: .regularExpression)+ text = text.replacingOccurrences(of: "<[^>]*>", with: "", options: .regularExpression)+ let entities = ["nbsp": " ", "quot": "\"", "apos": "'", "lt": "<", "gt": ">", "amp": "&",+ "ndash": "–", "mdash": "—", "rsquo": "’", "lsquo": "‘", "rdquo": "”", "ldquo": "“", "hellip": "…", "trade": "™", "reg": "®", "copy": "©"]+ if let regex = try? NSRegularExpression(pattern: "&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);") {+ for match in regex.matches(in: text, range: NSRange(text.startIndex..., in: text)).reversed() {+ guard let range = Range(match.range, in: text), let keyRange = Range(match.range(at: 1), in: text) else { continue }+ let key = String(text[keyRange])+ let number = key.hasPrefix("#x") ? UInt32(key.dropFirst(2), radix: 16) : key.hasPrefix("#") ? UInt32(key.dropFirst()) : nil+ let value = number.flatMap(UnicodeScalar.init).map(String.init) ?? entities[key]+ if let value { text.replaceSubrange(range, with: value) }+ }+ }+ return text.replacingOccurrences(of: "[ \\t]+", with: " ", options: .regularExpression)+ .replacingOccurrences(of: " *\\n *", with: "\n", options: .regularExpression)+ .replacingOccurrences(of: "\\n{3,}", with: "\n\n", options: .regularExpression)+ .trimmingCharacters(in: .whitespacesAndNewlines)+ }+}++/// One request when a page is opened, cached for a week. A failed refresh retains the old copy;+/// failures are backed off for five minutes and overlapping requests share one task.+public actor SteamGameDetailsStore {+ public enum Language: String, Sendable { case english, french }+ public static let shared = SteamGameDetailsStore()+ static let maxAge: TimeInterval = 7 * 24 * 3600+ private struct Record: Codable { let version: Int; let checked: Date; let details: SteamGameDetails }+ private let directory: URL+ private let fetch: @Sendable (URL) async throws -> (Data, Int)+ private var pending: [String: Task<SteamGameDetails?, Never>] = [:]+ private var failed: [String: Date] = [:]++ public init(directory: URL? = nil) {+ self.directory = directory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]+ .appending(path: "Highball/SteamDetails", directoryHint: .isDirectory)+ let configuration = URLSessionConfiguration.ephemeral+ configuration.timeoutIntervalForRequest = 15+ configuration.timeoutIntervalForResource = 20+ let session = URLSession(configuration: configuration)+ fetch = { url in+ let (data, response) = try await session.data(from: url)+ return (data, (response as? HTTPURLResponse)?.statusCode ?? 0)+ }+ }++ init(directory: URL, fetch: @escaping @Sendable (URL) async throws -> (Data, Int)) {+ self.directory = directory; self.fetch = fetch+ }++ public func details(appID: Int, language: Language = .english, now: Date = Date()) async -> SteamGameDetails? {+ guard appID > 0 else { return nil }+ let key = "\(appID)-\(language.rawValue)"+ let file = directory.appending(path: "\(key).json")+ let record = (try? Data(contentsOf: file)).flatMap { try? JSONDecoder().decode(Record.self, from: $0) }+ let cached = record?.version == 1 && record?.details.appID == appID ? record : nil+ if let cached, now.timeIntervalSince(cached.checked) < Self.maxAge { return cached.details }+ if let failure = failed[key], now.timeIntervalSince(failure) < 300 { return cached?.details }+ if let task = pending[key] { return await task.value ?? cached?.details }+ let url = URL(string: "https://store.steampowered.com/api/appdetails?appids=\(appID)&l=\(language.rawValue)")!+ let fetch = self.fetch+ let task = Task<SteamGameDetails?, Never> {+ guard let (data, status) = try? await fetch(url), status == 200, data.count <= 2_000_000 else { return nil }+ return SteamGameDetails.parse(data, appID: appID)+ }+ pending[key] = task+ let result = await task.value+ pending[key] = nil+ if let result {+ failed[key] = nil+ if let data = try? JSONEncoder().encode(Record(version: 1, checked: now, details: result)) {+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try? data.write(to: file, options: .atomic)+ }+ return result+ }+ failed[key] = now+ return cached?.details+ }+}diff --git a/Tests/HighballKitTests/SteamGameDetailsTests.swift b/Tests/HighballKitTests/SteamGameDetailsTests.swiftnew file mode 100644index 0000000..fbabcda--- /dev/null+++ b/Tests/HighballKitTests/SteamGameDetailsTests.swift@@ -0,0 +1,135 @@+import XCTest+@testable import HighballKit++final class SteamGameDetailsTests: XCTestCase {+ private let sample = Data(#"""+ {"42":{"success":true,"data":{"steam_appid":42,+ "short_description":"Explore & survive — together.",+ "about_the_game":"<h2>A world</h2><p>Play <your way>.</p><script>hidden()</script><ul><li>Explore</li><li>Build</li></ul>",+ "header_image":"https://shared.akamai.steamstatic.com/header.jpg",+ "screenshots":[+ {"path_thumbnail":"https://shared.akamai.steamstatic.com/thumb.jpg","path_full":"https://shared.akamai.steamstatic.com/full.jpg"},+ {"path_thumbnail":"https://shared.akamai.steamstatic.com/thumb.jpg","path_full":"https://shared.akamai.steamstatic.com/full.jpg"},+ {"path_thumbnail":"https://example.com/thumb.jpg","path_full":"file:///tmp/image.jpg"}],+ "developers":["Studio"],"publishers":["Publisher"],"genres":[{"description":"Action"}],+ "release_date":{"date":"6 Oct, 2026","coming_soon":false}}}}+ """#.utf8)++ private func cacheDirectory() throws -> URL {+ let dir = FileManager.default.temporaryDirectory.appending(path: "highball-steam-details-\(UUID())")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ addTeardownBlock { try? FileManager.default.removeItem(at: dir) }+ return dir+ }++ func testParsesStoreCopyWithoutHTMLAndRejectsUnsafeOrDuplicateImages() throws {+ let details = try XCTUnwrap(SteamGameDetails.parse(sample, appID: 42))+ XCTAssertEqual(details.summary, "Explore & survive — together.")+ XCTAssertEqual(details.description, "A world\n\nPlay <your way>.\n\n• Explore\n• Build")+ XCTAssertEqual(details.screenshots.count, 1)+ XCTAssertEqual(details.developers, ["Studio"])+ XCTAssertEqual(details.genres, ["Action"])+ XCTAssertEqual(details.releaseDate, "6 Oct, 2026")+ XCTAssertEqual(details.storeURL.absoluteString, "https://store.steampowered.com/app/42/")+ }++ func testDelistedMalformedAndMismatchedRepliesAreUnavailable() {+ XCTAssertNil(SteamGameDetails.parse(Data(#"{"42":{"success":false}}"#.utf8), appID: 42))+ XCTAssertNil(SteamGameDetails.parse(Data("not JSON".utf8), appID: 42))+ XCTAssertNil(SteamGameDetails.parse(sample, appID: 43))+ let mismatch = Data(#"{"42":{"success":true,"data":{"steam_appid":43}}}"#.utf8)+ XCTAssertNil(SteamGameDetails.parse(mismatch, appID: 42))+ }++ func testEntityDecodingDoesNotInterpretEscapedMarkupOrLoadImages() {+ XCTAssertEqual(SteamGameDetails.plainText("<p><script> 🎮 &quot;</p><img src='https://example.com/a'>"), "<script> 🎮 "")+ XCTAssertEqual(SteamGameDetails.plainText("a b<br> c"), "a b\n\nc")+ XCTAssertEqual(SteamGameDetails.plainText("<p>A</p>\r\n<br><br>\r\n<p>B</p>"), "A\n\nB")+ }++ func testSparseStoreReplyStillHasAUsablePage() throws {+ let empty = Data(#"{"42":{"success":true,"data":{"steam_appid":42}}}"#.utf8)+ let details = try XCTUnwrap(SteamGameDetails.parse(empty, appID: 42))+ XCTAssertEqual(details.summary, "")+ XCTAssertEqual(details.screenshots, [])+ XCTAssertNil(details.header)+ XCTAssertNil(details.releaseDate)+ }++ func testCacheSurvivesRelaunchAndLanguagesHaveSeparateCopies() async throws {+ let directory = try cacheDirectory(), now = Date(timeIntervalSince1970: 1000)+ let probe = FetchProbe(data: sample)+ let store = SteamGameDetailsStore(directory: directory, fetch: { await probe.fetch($0) })+ let first = await store.details(appID: 42, now: now)+ let second = await store.details(appID: 42, now: now.addingTimeInterval(60))+ XCTAssertEqual(first, second)+ let relaunched = SteamGameDetailsStore(directory: directory, fetch: { await probe.fetch($0) })+ let persisted = await relaunched.details(appID: 42, now: now.addingTimeInterval(120))+ XCTAssertEqual(first, persisted)+ let englishCalls = await probe.calls+ XCTAssertEqual(englishCalls.count, 1)+ _ = await relaunched.details(appID: 42, language: .french, now: now)+ let allCalls = await probe.calls+ XCTAssertEqual(allCalls.count, 2)+ XCTAssertTrue(allCalls.last?.query?.contains("l=french") == true)+ }++ func testExpiredCopyRemainsAvailableWhenSteamRateLimitsAndRetryIsBackedOff() async throws {+ let directory = try cacheDirectory(), now = Date(timeIntervalSince1970: 1000)+ let probe = FetchProbe(data: sample)+ let store = SteamGameDetailsStore(directory: directory, fetch: { await probe.fetch($0) })+ let original = await store.details(appID: 42, now: now)+ await probe.setStatus(429)+ let later = now.addingTimeInterval(SteamGameDetailsStore.maxAge + 1)+ let stale = await store.details(appID: 42, now: later)+ let backedOff = await store.details(appID: 42, now: later.addingTimeInterval(60))+ XCTAssertEqual(stale, original)+ XCTAssertEqual(backedOff, original)+ let calls = await probe.calls+ XCTAssertEqual(calls.count, 2)+ await probe.setStatus(200)+ let recovered = await store.details(appID: 42, now: later.addingTimeInterval(301))+ XCTAssertEqual(recovered, original)+ let afterRetry = await probe.calls+ XCTAssertEqual(afterRetry.count, 3)+ }++ func testOverlappingPagesShareOneRequest() async throws {+ let probe = FetchProbe(data: sample, delay: true)+ let store = SteamGameDetailsStore(directory: try cacheDirectory(), fetch: { await probe.fetch($0) })+ async let first = store.details(appID: 42)+ async let second = store.details(appID: 42)+ let (a, b) = await (first, second)+ XCTAssertNotNil(a)+ XCTAssertEqual(a, b)+ let calls = await probe.calls+ XCTAssertEqual(calls.count, 1)+ }++ func testCorruptCacheRefetchesAndInvalidAppDoesNotRequest() async throws {+ let directory = try cacheDirectory()+ try Data("bad cache".utf8).write(to: directory.appending(path: "42-english.json"))+ let probe = FetchProbe(data: sample)+ let store = SteamGameDetailsStore(directory: directory, fetch: { await probe.fetch($0) })+ let invalid = await store.details(appID: -1)+ XCTAssertNil(invalid)+ let recovered = await store.details(appID: 42)+ XCTAssertNotNil(recovered)+ let calls = await probe.calls+ XCTAssertEqual(calls.count, 1)+ }+}++private actor FetchProbe {+ let data: Data+ let delay: Bool+ var status = 200+ var calls: [URL] = []+ init(data: Data, delay: Bool = false) { self.data = data; self.delay = delay }+ func setStatus(_ status: Int) { self.status = status }+ func fetch(_ url: URL) async -> (Data, Int) {+ calls.append(url)+ if delay { try? await Task.sleep(for: .milliseconds(50)) }+ return (data, status)+ }+}