import SwiftUI import CoreText import ImageIO import WidgetKit /// Quello che il widget mostra in un certo momento. struct Snapshot { var count: Int? var today: Int? var week: [Int] var username: String? var connected: Bool /// Il traguardo appena superato, da festeggiare. var milestone: Int? = nil /// La foto profilo dell'account, se è già stata scaricata. var avatar: CGImage? = nil static func current() -> Snapshot { let store = FollowerStore.shared var avatar: CGImage? if let file = store.avatarFile, let source = CGImageSourceCreateWithURL(file as CFURL, nil) { avatar = CGImageSourceCreateImageAtIndex(source, 0, nil) } return Snapshot( count: store.latest, today: store.todayDelta(), week: store.weekDeltas(), username: store.username, connected: store.token != nil, milestone: store.activeMilestone(), avatar: avatar ) } static let sample = Snapshot(count: 1323, today: 12, week: [9, 14, 6, 11, 17, 8, 12], username: "bg_perspective", connected: true) } // MARK: - Stile "Stazione" enum Stazione { static let background = Color(hex: 0x151515) // Sulla scrivania macOS schiarisce lo sfondo del widget: le palette devono restare ben più chiare. static let tileTop = Color(hex: 0x404040) static let tileBottom = Color(hex: 0x353535) static let seam = Color(hex: 0x0A0A0A) static let digit = Color(hex: 0xF3EFE4) static let label = Color(hex: 0xA8A8A8) static let muted = Color(hex: 0x8D8D8D) static let bar = Color(hex: 0x444444) static let accent = Color(hex: 0xF2B33D) static let goldTop = Color(hex: 0xF2B33D) static let goldBottom = Color(hex: 0xE3A22C) private static let fontsRegistered: Void = { for name in ["BarlowCondensed-SemiBold", "BarlowCondensed-Medium"] { if let url = Bundle.main.url(forResource: name, withExtension: "ttf") { CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil) } } }() static func font(_ size: CGFloat, medium: Bool = false) -> Font { _ = fontsRegistered return .custom(medium ? "BarlowCondensed-Medium" : "BarlowCondensed-SemiBold", size: size) } } extension Color { init(hex: UInt32) { self.init(red: Double((hex >> 16) & 0xFF) / 255, green: Double((hex >> 8) & 0xFF) / 255, blue: Double(hex & 0xFF) / 255) } } /// Una paletta del tabellone con la sua cifra. struct FlapTile: View { let character: String let width: CGFloat var gold = false @Environment(\.widgetRenderingMode) private var renderingMode var body: some View { let height = width * 1.56 let vibrant = renderingMode != .fullColor ZStack { VStack(spacing: 0) { if vibrant { Color.primary.opacity(gold ? 0.5 : 0.16) Color.primary.opacity(gold ? 0.4 : 0.10) } else { gold ? Stazione.goldTop : Stazione.tileTop gold ? Stazione.goldBottom : Stazione.tileBottom } } Text(character) .font(Stazione.font(width * 1.25)) .foregroundStyle(vibrant ? Color.primary : (gold ? Stazione.background : Stazione.digit)) .contentTransition(.numericText()) .offset(y: -width * 0.04) Rectangle().fill(Stazione.seam).frame(height: 1) HStack { Rectangle().fill(Stazione.seam).frame(width: 2, height: height * 0.12) Spacer() Rectangle().fill(Stazione.seam).frame(width: 2, height: height * 0.12) } } .frame(width: width, height: height) .clipShape(RoundedRectangle(cornerRadius: width * 0.15, style: .continuous)) } } /// La fila di palette. Le cifre sono identificate da destra, così quando si aggiunge una cifra le altre non si rimescolano. struct FlapRow: View { let count: Int? let available: CGFloat let maxTile: CGFloat var gold = false var gap: CGFloat = 4 static func characters(for count: Int?) -> [String] { count.map { Array(String($0)).map(String.init) } ?? ["-", "-", "-", "-"] } /// Quanto è larga la fila con palette al massimo di `maxTile`, senza superare `available`. static func width(for count: Int?, available: CGFloat, maxTile: CGFloat, gap: CGFloat = 4) -> CGFloat { let n = CGFloat(characters(for: count).count) let tile = min(maxTile, (available - gap * (n - 1)) / n) return tile * n + gap * (n - 1) } var body: some View { let characters = FlapRow.characters(for: count) let n = CGFloat(characters.count) let width = min(maxTile, (available - gap * (n - 1)) / n) HStack(spacing: gap) { ForEach(Array(characters.enumerated()), id: \.offset) { index, character in FlapTile(character: character, width: width, gold: gold) .id(characters.count - index) } } // Quando si supera un traguardo tutta la fila gira e diventa gialla. .id(gold) .transition(.push(from: .bottom)) } } struct WeekBars: View { let values: [Int] /// Altezza delle sole barre (le iniziali dei giorni stanno sotto). var height: CGFloat = 56 /// Linee di riferimento tratteggiate, in follower al giorno. private let guides = [50, 100] static let dayRow: CGFloat = 15 /// I giorni a cui si riferiscono `count` valori, dal più vecchio a oggi. static func days(_ count: Int, now: Date = Date()) -> [Date] { let calendar = Calendar.current let today = calendar.startOfDay(for: now) return (0.. Path { Path { path in path.move(to: CGPoint(x: rect.minX, y: rect.midY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY)) } } } } /// Nell'app: gli ultimi 7 giorni uno sotto l'altro, con barra orizzontale e numero preciso. struct WeekList: View { let values: [Int] private let guides = [50, 100] private static let dayFormat: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "it_IT") formatter.dateFormat = "EEEE d" return formatter }() var body: some View { // Come nel widget: la linea dei 50 c'è sempre, quella dei 100 solo se raggiunta. let best = max(values.max() ?? 0, 50) let shown = guides.filter { $0 <= best } let days = WeekBars.days(values.count) VStack(alignment: .leading, spacing: 10) { Text("ULTIMI 7 GIORNI") .font(Stazione.font(13)) .tracking(2) .foregroundStyle(Stazione.label) VStack(spacing: 0) { ForEach(Array(values.enumerated()), id: \.offset) { index, value in let today = index == values.count - 1 HStack(spacing: 10) { Text(today ? "Oggi" : WeekList.dayFormat.string(from: days[index]).capitalized) .font(Stazione.font(15, medium: true)) .foregroundStyle(today ? Stazione.accent : Stazione.label) .frame(width: 86, alignment: .leading) GeometryReader { geo in ZStack(alignment: .leading) { ForEach(shown, id: \.self) { guide in Path { path in let x = CGFloat(guide) / CGFloat(best) * geo.size.width path.move(to: CGPoint(x: x, y: 0)) path.addLine(to: CGPoint(x: x, y: geo.size.height)) } .stroke(Color.white.opacity(0.22), style: StrokeStyle(lineWidth: 1, dash: [2, 3])) } RoundedRectangle(cornerRadius: 2) .fill(today ? Stazione.accent : Stazione.bar) .frame(width: max(4, CGFloat(max(value, 0)) / CGFloat(best) * geo.size.width), height: 12) } .frame(maxHeight: .infinity) } Text(value >= 0 ? "+\(value)" : "\(value)") .font(Stazione.font(16)) .foregroundStyle(today ? Stazione.accent : Stazione.digit) .frame(width: 40, alignment: .trailing) } .frame(height: 26) } } if !shown.isEmpty { HStack(spacing: 10) { Color.clear.frame(width: 86, height: 1) GeometryReader { geo in ZStack(alignment: .topLeading) { ForEach(shown, id: \.self) { guide in Text("\(guide)") .font(Stazione.font(10, medium: true)) .foregroundStyle(Stazione.muted) .fixedSize() .frame(width: 30) .offset(x: CGFloat(guide) / CGFloat(best) * geo.size.width - 15) } } } .frame(height: 12) Color.clear.frame(width: 40, height: 1) } } } } } /// "FOLLOWER", oppure "TRAGUARDO 1500" in giallo quando c'è da festeggiare. struct MainLabel: View { let milestone: Int? var body: some View { Text(milestone.map { "TRAGUARDO \($0)" } ?? "FOLLOWER") .font(Stazione.font(13)) .tracking(2) .foregroundStyle(milestone == nil ? Stazione.label : Stazione.accent) .lineLimit(1) .minimumScaleFactor(0.7) } } private func deltaText(_ value: Int?) -> String { guard let value else { return "+0" } return value >= 0 ? "+\(value)" : "\(value)" } struct SmallStazione: View { let snapshot: Snapshot var body: some View { GeometryReader { geo in VStack(alignment: .leading, spacing: 0) { MainLabel(milestone: snapshot.milestone) Spacer(minLength: 0) FlapRow(count: snapshot.count, available: geo.size.width, maxTile: 34, gold: snapshot.milestone != nil) .frame(maxWidth: .infinity) Spacer(minLength: 0) if snapshot.connected { Text("\(deltaText(snapshot.today)) oggi") .font(Stazione.font(16)) .foregroundStyle(Stazione.accent) .contentTransition(.numericText()) } else { Text("Apri Tabellone") .font(Stazione.font(15, medium: true)) .foregroundStyle(Stazione.muted) } } } } } struct MediumStazione: View { let snapshot: Snapshot /// Spazio minimo per la colonna di destra (variazione e barre con i numeri delle linee). private let minSide: CGFloat = 112 var body: some View { GeometryReader { geo in // La colonna di sinistra è larga quanto le palette: il resto va alla colonna di destra. let rowWidth = FlapRow.width(for: snapshot.count, available: geo.size.width - minSide - 33, maxTile: 44) HStack(spacing: 16) { VStack(alignment: .leading, spacing: 0) { HStack(spacing: 5) { if let avatar = snapshot.avatar { Image(decorative: avatar, scale: 1) .resizable() .frame(width: 15, height: 15) .clipShape(Circle()) } Text(snapshot.username.map { "@\($0)" } ?? "Instagram") .font(Stazione.font(14)) .tracking(1) .foregroundStyle(Stazione.label) .lineLimit(1) .minimumScaleFactor(0.7) } Spacer(minLength: 0) FlapRow(count: snapshot.count, available: rowWidth, maxTile: 44, gold: snapshot.milestone != nil) Spacer(minLength: 0) MainLabel(milestone: snapshot.milestone) } .frame(width: rowWidth, alignment: .leading) Rectangle().fill(Color.white.opacity(0.1)).frame(width: 1) .padding(.trailing, -4) VStack(alignment: .leading, spacing: 0) { if snapshot.connected { HStack(alignment: .firstTextBaseline) { Text(deltaText(snapshot.today)) .font(Stazione.font(32)) .foregroundStyle(Stazione.accent) .contentTransition(.numericText()) Spacer(minLength: 4) Text("oggi") .font(Stazione.font(13, medium: true)) .foregroundStyle(Stazione.label) } Spacer(minLength: 6) // Le barre prendono tutto lo spazio rimasto sotto la riga di "oggi". WeekBars(values: snapshot.week, height: max(40, geo.size.height - 38 - 6 - WeekBars.dayRow)) } else { Spacer(minLength: 0) Text("Apri Tabellone per collegare Instagram") .font(Stazione.font(15, medium: true)) .foregroundStyle(Stazione.muted) Spacer(minLength: 0) } } .frame(maxWidth: .infinity, alignment: .leading) } } } }