krz/hutch
an ios client for sourcehut
clone: git clone https://gitbay.org/krz/hutch.git
v2.15.1: HutchWidgetExtension/ContributionGraphWidget.swift · raw
1import SwiftUI
2import WidgetKit
3
4struct ContributionGraphEntry: TimelineEntry {
5 let date: Date
6 let actor: String?
7 let state: State
8 let weeks: [ContributionGraphWeek]
9
10 enum State {
11 case placeholder
12 case disabled
13 case unavailable
14 case empty
15 case indexing
16 case populated
17 }
18}
19
20struct ContributionGraphTimelineProvider: TimelineProvider {
21 func placeholder(in _: Context) -> ContributionGraphEntry {
22 ContributionGraphEntry(
23 date: .now,
24 actor: "~ccleberg",
25 state: .placeholder,
26 weeks: ContributionGraphSampleData.placeholderWeeks
27 )
28 }
29
30 func getSnapshot(in _: Context, completion: @escaping (ContributionGraphEntry) -> Void) {
31 Task {
32 completion(await loadEntry())
33 }
34 }
35
36 func getTimeline(in _: Context, completion: @escaping (Timeline<ContributionGraphEntry>) -> Void) {
37 Task {
38 let entry = await loadEntry()
39 let refreshDate = Calendar.contributionCalendar.date(byAdding: .hour, value: 1, to: Date()) ?? Date().addingTimeInterval(3600)
40 completion(Timeline(entries: [entry], policy: .after(refreshDate)))
41 }
42 }
43
44 private func loadEntry() async -> ContributionGraphEntry {
45 guard ContributionWidgetContextStore.isEnabled() else {
46 return ContributionGraphEntry(date: .now, actor: nil, state: .disabled, weeks: [])
47 }
48
49 guard let actor = ContributionWidgetContextStore.loadActor(), !actor.isEmpty else {
50 return ContributionGraphEntry(date: .now, actor: nil, state: .unavailable, weeks: [])
51 }
52
53 do {
54 let response = try await ContributionGraphWidgetService().fetchCalendar(actor: actor)
55 let state: ContributionGraphEntry.State
56 if response.totalCount > 0 {
57 state = .populated
58 } else {
59 switch response.indexingState {
60 case .pending:
61 state = .indexing
62 case .error:
63 state = .unavailable
64 case .indexed:
65 state = .empty
66 }
67 }
68
69 return ContributionGraphEntry(
70 date: .now,
71 actor: actor,
72 state: state,
73 weeks: ContributionGraphLayout.weekColumns(from: response.days)
74 )
75 } catch {
76 return ContributionGraphEntry(date: .now, actor: actor, state: .unavailable, weeks: [])
77 }
78 }
79}
80
81struct ContributionGraphWidget: Widget {
82 static let kind = ContributionGraphWidgetConfiguration.kind
83
84 var body: some WidgetConfiguration {
85 StaticConfiguration(kind: Self.kind, provider: ContributionGraphTimelineProvider()) { entry in
86 ContributionGraphWidgetView(entry: entry)
87 }
88 .configurationDisplayName("Contribution Graph")
89 .description("A trailing 365-day SourceHut contribution heatmap for your current profile.")
90 .supportedFamilies([.systemSmall, .systemMedium])
91 }
92}
93
94private struct ContributionGraphWidgetView: View {
95 let entry: ContributionGraphEntry
96 @Environment(\.widgetFamily) private var family
97
98 var body: some View {
99 Group {
100 switch entry.state {
101 case .disabled:
102 messageView(
103 title: "Contributions Disabled",
104 detail: "Enable contribution graphs in Hutch settings to use this widget."
105 )
106 case .unavailable:
107 messageView(
108 title: "Open Hutch",
109 detail: "Sign in and open your profile to load contribution data."
110 )
111 default:
112 graphView
113 }
114 }
115 .widgetURL(URL(string: "hutch://home"))
116 .containerBackground(for: .widget) {
117 Color(.systemBackground)
118 }
119 }
120
121 private var graphView: some View {
122 GeometryReader { geometry in
123 let cellSize = ContributionGraphSizing.baseCellSize(availableHeight: geometry.size.height)
124 let layout = ContributionGraphSizing.layout(availableSize: geometry.size, cellSize: cellSize)
125 let weeks = displayedWeeks(columnCount: layout.columns)
126
127 let actualSize = ContributionGraphSizing.contentSize(
128 columns: weeks.count, cellSize: layout.cellSize, spacing: layout.spacing
129 )
130
131 ContributionGraphGridView(
132 weeks: weeks,
133 squareSize: layout.cellSize,
134 spacing: layout.spacing
135 )
136 .frame(width: actualSize.width, height: actualSize.height)
137 .frame(maxWidth: .infinity, maxHeight: .infinity)
138 }
139 }
140
141 private func messageView(title: String, detail: String) -> some View {
142 VStack(spacing: 6) {
143 Text(title)
144 .font(family == .systemSmall ? .headline : .title3.weight(.semibold))
145 .multilineTextAlignment(.center)
146 Text(detail)
147 .font(.caption)
148 .foregroundStyle(.secondary)
149 .multilineTextAlignment(.center)
150 }
151 .padding()
152 .frame(maxWidth: .infinity, maxHeight: .infinity)
153 }
154
155 private func displayedWeeks(columnCount: Int) -> [ContributionGraphWeek] {
156 var baseWeeks = switch entry.state {
157 case .populated, .indexing, .empty:
158 entry.weeks
159 case .placeholder, .disabled, .unavailable:
160 ContributionGraphSampleData.placeholderWeeks
161 }
162
163 // Drop any trailing week where every day has zero contributions
164 while let last = baseWeeks.last, last.days.allSatisfy({ $0.count == 0 }) {
165 baseWeeks.removeLast()
166 }
167
168 return Array(baseWeeks.suffix(columnCount))
169 }
170}
171
172private struct ContributionGraphGridView: View {
173 let weeks: [ContributionGraphWeek]
174 let squareSize: CGFloat
175 let spacing: CGFloat
176
177 var body: some View {
178 HStack(alignment: .top, spacing: spacing) {
179 ForEach(weeks, id: \.startDate) { week in
180 VStack(spacing: spacing) {
181 ForEach(Array(week.slots.enumerated()), id: \.offset) { _, day in
182 RoundedRectangle(cornerRadius: squareSize * 0.2, style: .continuous)
183 .fill((day?.intensity ?? .empty).color)
184 .frame(width: squareSize, height: squareSize)
185 }
186 }
187 }
188 }
189 }
190}
191
192private enum ContributionGraphSizing {
193 static let rowCount = 7
194 static let cellSpacing: CGFloat = 3
195
196 struct GridLayout {
197 let rows: Int
198 let columns: Int
199 let cellSize: CGFloat
200 let spacing: CGFloat
201
202 var contentSize: CGSize {
203 let w = CGFloat(columns) * cellSize + CGFloat(max(0, columns - 1)) * spacing
204 let h = CGFloat(rows) * cellSize + CGFloat(max(0, rows - 1)) * spacing
205 return CGSize(width: w, height: h)
206 }
207 }
208
209 /// Cell size derived from available height so 7 rows fill it exactly.
210 static func baseCellSize(availableHeight: CGFloat) -> CGFloat {
211 floor((availableHeight - cellSpacing * CGFloat(rowCount - 1)) / CGFloat(rowCount))
212 }
213
214 /// Compute layout for any family: 7 rows, as many columns as fit at the given cell size.
215 static func layout(availableSize: CGSize, cellSize: CGFloat) -> GridLayout {
216 let columns = max(1, Int(floor((availableSize.width + cellSpacing) / (cellSize + cellSpacing))))
217 return GridLayout(rows: rowCount, columns: columns, cellSize: cellSize, spacing: cellSpacing)
218 }
219
220 /// Content size for the actual number of displayed columns (may differ from layout max).
221 static func contentSize(columns: Int, cellSize: CGFloat, spacing: CGFloat) -> CGSize {
222 let w = CGFloat(columns) * cellSize + CGFloat(max(0, columns - 1)) * spacing
223 let h = CGFloat(rowCount) * cellSize + CGFloat(max(0, rowCount - 1)) * spacing
224 return CGSize(width: w, height: h)
225 }
226}
227
228private struct ContributionGraphWidgetService {
229 private let baseURL = URL(string: "https://hutch-stats.zerolabs.sh")!
230
231 func fetchCalendar(actor: String) async throws -> ContributionGraphResponse {
232 guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else {
233 throw URLError(.badURL)
234 }
235
236 components.path = "/api/contributions/\(actor)"
237 let range = trailingRange(endingOn: Date())
238 components.queryItems = [
239 URLQueryItem(name: "from", value: Self.rangeFormatter.string(from: range.lowerBound)),
240 URLQueryItem(name: "to", value: Self.rangeFormatter.string(from: range.upperBound))
241 ]
242
243 guard let url = components.url else {
244 throw URLError(.badURL)
245 }
246
247 let (data, response) = try await URLSession.shared.data(from: url)
248 if let httpResponse = response as? HTTPURLResponse, !(200...299).contains(httpResponse.statusCode) {
249 throw URLError(.badServerResponse)
250 }
251
252 return try JSONDecoder().decode(ContributionGraphResponse.self, from: data)
253 }
254
255 private func trailingRange(endingOn endDate: Date) -> ClosedRange<Date> {
256 let normalizedEndDate = Calendar.contributionCalendar.startOfDay(for: endDate)
257 let oneYearBack = Calendar.contributionCalendar.date(byAdding: .year, value: -1, to: normalizedEndDate) ?? normalizedEndDate
258 let normalizedStartDate = Calendar.contributionCalendar.date(byAdding: .day, value: 1, to: oneYearBack) ?? oneYearBack
259 return normalizedStartDate...normalizedEndDate
260 }
261
262 private static let rangeFormatter: DateFormatter = {
263 let formatter = DateFormatter()
264 formatter.calendar = .contributionCalendar
265 formatter.locale = Locale(identifier: "en_US_POSIX")
266 formatter.timeZone = TimeZone(secondsFromGMT: 0)
267 formatter.dateFormat = "yyyy-MM-dd"
268 return formatter
269 }()
270}
271
272private struct ContributionGraphResponse: Decodable {
273 let actor: String
274 let indexingState: ContributionGraphIndexingState
275 let days: [ContributionGraphDay]
276
277 enum CodingKeys: String, CodingKey {
278 case actor
279 case indexingState = "indexing_state"
280 case days
281 }
282
283 var totalCount: Int {
284 days.reduce(0) { $0 + $1.count }
285 }
286}
287
288struct ContributionGraphDay: Decodable, Identifiable {
289 var id: Date { date }
290
291 let date: Date
292 let count: Int
293
294 enum CodingKeys: String, CodingKey {
295 case date
296 case count
297 }
298
299 var intensity: ContributionGraphIntensity {
300 ContributionGraphIntensity(count: count)
301 }
302
303 init(from decoder: Decoder) throws {
304 let container = try decoder.container(keyedBy: CodingKeys.self)
305 date = try ContributionGraphDateParser.decodeDateString(from: container, forKey: .date)
306 count = try container.decode(Int.self, forKey: .count)
307 }
308}
309
310private enum ContributionGraphIndexingState: String, Decodable {
311 case pending
312 case indexed
313 case error
314}
315
316enum ContributionGraphIntensity: Int, CaseIterable {
317 case empty = 0
318 case level1 = 1
319 case level2 = 2
320 case level3 = 3
321 case level4 = 4
322
323 init(count: Int) {
324 switch count {
325 case ..<1:
326 self = .empty
327 case 1:
328 self = .level1
329 case 2...3:
330 self = .level2
331 case 4...6:
332 self = .level3
333 default:
334 self = .level4
335 }
336 }
337
338 var color: Color {
339 switch self {
340 case .empty:
341 Color(uiColor: .secondarySystemFill)
342 case .level1:
343 Color(red: 0.82, green: 0.92, blue: 0.83)
344 case .level2:
345 Color(red: 0.58, green: 0.83, blue: 0.61)
346 case .level3:
347 Color(red: 0.25, green: 0.69, blue: 0.36)
348 case .level4:
349 Color(red: 0.12, green: 0.47, blue: 0.21)
350 }
351 }
352}
353
354struct ContributionGraphWeek {
355 let startDate: Date
356 let days: [ContributionGraphDay]
357
358 var slots: [ContributionGraphDay?] {
359 let calendar = Calendar.contributionCalendar
360 let indexedDays = Dictionary(uniqueKeysWithValues: days.map { day in
361 (calendar.component(.weekday, from: day.date), day)
362 })
363
364 return (1...7).map { weekday in
365 indexedDays[weekday]
366 }
367 }
368}
369
370private enum ContributionGraphLayout {
371 static func weekColumns(from days: [ContributionGraphDay]) -> [ContributionGraphWeek] {
372 let groupedDays = Dictionary(grouping: days) { day in
373 Calendar.contributionCalendar.startOfWeek(for: day.date)
374 }
375
376 return groupedDays.keys.sorted().map { weekStart in
377 ContributionGraphWeek(
378 startDate: weekStart,
379 days: groupedDays[weekStart, default: []].sorted { $0.date < $1.date }
380 )
381 }
382 }
383}
384
385private enum ContributionGraphDateParser {
386 static func parse(_ rawValue: String) -> Date? {
387 let parts = rawValue.split(separator: "-", omittingEmptySubsequences: false)
388 guard
389 parts.count == 3,
390 let year = Int(parts[0]),
391 let month = Int(parts[1]),
392 let day = Int(parts[2])
393 else {
394 return nil
395 }
396
397 var components = DateComponents()
398 components.calendar = .contributionCalendar
399 components.timeZone = TimeZone(secondsFromGMT: 0)
400 components.year = year
401 components.month = month
402 components.day = day
403 return components.date
404 }
405
406 static func decodeDateString<Key: CodingKey>(
407 from container: KeyedDecodingContainer<Key>,
408 forKey key: Key
409 ) throws -> Date {
410 let rawValue = try container.decode(String.self, forKey: key)
411 guard let date = parse(rawValue) else {
412 throw DecodingError.dataCorruptedError(
413 forKey: key,
414 in: container,
415 debugDescription: "Invalid contribution date: \(rawValue)"
416 )
417 }
418 return date
419 }
420}
421
422private enum ContributionGraphSampleData {
423 static let placeholderWeeks: [ContributionGraphWeek] = {
424 let startDate = Calendar.contributionCalendar.startOfDay(for: .now)
425 let days = (0..<150).compactMap { offset -> ContributionGraphDay? in
426 guard let date = Calendar.contributionCalendar.date(byAdding: .day, value: -offset, to: startDate) else {
427 return nil
428 }
429 return ContributionGraphDay(date: date, count: (offset % 8), score: 0)
430 }
431 return ContributionGraphLayout.weekColumns(from: days)
432 }()
433}
434
435private extension ContributionGraphDay {
436 init(date: Date, count: Int, score _: Double) {
437 self.date = date
438 self.count = count
439 }
440}
441
442private extension Calendar {
443 static var contributionCalendar: Calendar {
444 var calendar = Calendar(identifier: .gregorian)
445 calendar.firstWeekday = 1
446 calendar.timeZone = TimeZone(secondsFromGMT: 0)!
447 return calendar
448 }
449
450 func startOfWeek(for date: Date) -> Date {
451 dateInterval(of: .weekOfYear, for: date)?.start ?? startOfDay(for: date)
452 }
453}