Sources/OrgstarWidgets/HabitsWidget.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgstarWidgets/HabitsWidget.swift history · blame · raw

173 lines · 7313 bytes

  1import OrgApp
  2import OrgCore
  3import SwiftUI
  4import WidgetKit
  5
  6/// The agenda's habits with org-habit's consistency graphs: the last week (small) or the last
  7/// three weeks and the next one (medium, large).
  8struct HabitsWidget: Widget {
  9    var body: some WidgetConfiguration {
 10        StaticConfiguration(kind: "sh.krz.orgstar.habits", provider: HabitProvider()) { entry in
 11            HabitsView(entry: entry)
 12        }
 13        .configurationDisplayName("Habits")
 14        .description("Your habits and how consistently you've kept them.")
 15        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
 16    }
 17}
 18
 19struct HabitEntry: TimelineEntry {
 20    let date: Date
 21    /// Nil until the app has written one.
 22    let snapshot: HabitSnapshot?
 23}
 24
 25/// The app's habits, drawn again at each midnight of the next week, when the graphs move on.
 26struct HabitProvider: TimelineProvider {
 27    func placeholder(in context: Context) -> HabitEntry {
 28        HabitEntry(date: .now, snapshot: .sample(.now))
 29    }
 30
 31    func getSnapshot(in context: Context, completion: @escaping (HabitEntry) -> Void) {
 32        let snapshot = HabitSnapshot.read()
 33        completion(HabitEntry(date: .now, snapshot: snapshot ?? (context.isPreview ? .sample(.now) : nil)))
 34    }
 35
 36    func getTimeline(in context: Context, completion: @escaping (Timeline<HabitEntry>) -> Void) {
 37        let snapshot = HabitSnapshot.read()
 38        let midnight = Calendar.current.startOfDay(for: .now)
 39        let dates = [Date.now] + (1...7).compactMap { Calendar.current.date(byAdding: .day, value: $0, to: midnight) }
 40        completion(Timeline(entries: dates.map { HabitEntry(date: $0, snapshot: snapshot) }, policy: .atEnd))
 41    }
 42}
 43
 44struct HabitsView: View {
 45    let entry: HabitEntry
 46    @Environment(\.widgetFamily) private var family
 47    @Environment(\.colorScheme) private var scheme
 48
 49    private var today: Int { Days.absolute(entry.date, calendar: .current) }
 50
 51    var body: some View {
 52        Group {
 53            if let snapshot = entry.snapshot, !snapshot.habits.isEmpty {
 54                content(snapshot)
 55            } else {
 56                Text(entry.snapshot == nil ? "Open orgstar to show your habits here." : "No habits in the agenda. Give an entry STYLE: habit.")
 57                    .font(.caption)
 58                    .foregroundStyle(.secondary)
 59                    .frame(maxWidth: .infinity, maxHeight: .infinity)
 60            }
 61        }
 62        .widgetURL(AppLink.agenda.url)
 63        .containerBackground(for: .widget) { Color(uiColor: .systemBackground) }
 64    }
 65
 66    private func content(_ snapshot: HabitSnapshot) -> some View {
 67        let limit = family == .systemLarge ? 9 : family == .systemMedium ? 4 : 3
 68        let done = snapshot.habits.filter { $0.habit.doneDates.contains(today) }.count
 69        return VStack(alignment: .leading, spacing: family == .systemSmall ? 6 : 8) {
 70            HStack(alignment: .firstTextBaseline) {
 71                Text("Habits").font(.subheadline.weight(.semibold))
 72                Spacer(minLength: 0)
 73                Text("\(done)/\(snapshot.habits.count) today").font(.caption2.weight(.semibold)).foregroundStyle(.secondary)
 74            }
 75            ForEach(snapshot.habits.prefix(limit)) { habit in
 76                Link(destination: habit.link.url) { row(habit, snapshot) }
 77            }
 78            Spacer(minLength: 0)
 79        }
 80        .frame(maxWidth: .infinity, alignment: .leading)
 81    }
 82
 83    @ViewBuilder
 84    private func row(_ habit: HabitSnapshot.Entry, _ snapshot: HabitSnapshot) -> some View {
 85        if family == .systemSmall {
 86            // The last week, today last.
 87            let cells = habit.habit.graph(today: today, preceding: 6, following: 1)
 88            VStack(alignment: .leading, spacing: 2) {
 89                Text(habit.title).font(.caption).lineLimit(1)
 90                HabitCells(cells: cells, colors: snapshot.colors, width: 12, height: 8)
 91            }
 92        } else {
 93            HStack(spacing: 8) {
 94                Text(habit.title).font(.caption).lineLimit(1)
 95                Spacer(minLength: 4)
 96                HabitCells(cells: habit.habit.graph(today: today), colors: snapshot.colors, width: 5, height: 12)
 97            }
 98        }
 99    }
100}
101
102/// org-habit's graph: a bar per day in the due-state color, lighter for days to come, a dot
103/// where it was done, today outlined.
104struct HabitCells: View {
105    let cells: [Habit.Cell]
106    let colors: [String: AgendaSnapshot.Hex]
107    let width: CGFloat
108    let height: CGFloat
109    @Environment(\.colorScheme) private var scheme
110
111    var body: some View {
112        HStack(spacing: 1) {
113            ForEach(cells, id: \.day) { cell in
114                RoundedRectangle(cornerRadius: 1.5)
115                    .fill(color(cell.face))
116                    .frame(width: width, height: height)
117                    .overlay {
118                        if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: min(width, height) * 0.6) }
119                    }
120                    .overlay {
121                        if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
122                    }
123            }
124        }
125        .accessibilityElement(children: .ignore)
126        .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of \(cells.count) days")
127    }
128
129    private func color(_ face: Habit.Face) -> Color {
130        func themed(_ key: String, _ fallback: Color) -> Color { colors[key]?.color(scheme) ?? fallback }
131        switch face {
132        case .clear: return themed("habit-clear", .blue).opacity(0.7)
133        case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
134        case .ready: return themed("habit-ready", .green).opacity(0.8)
135        case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
136        case .alert: return themed("habit-alert", .yellow).opacity(0.85)
137        case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
138        case .overdue: return themed("habit-overdue", .red).opacity(0.8)
139        case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
140        }
141    }
142}
143
144extension HabitSnapshot {
145    /// Habits for the gallery and previews.
146    static func sample(_ now: Date) -> HabitSnapshot {
147        let today = Days.absolute(now, calendar: .current)
148        func habit(_ every: Int, done: [Int]) -> Habit {
149            Habit(scheduled: today, scheduledRepeat: every, doneDates: done.map { today - $0 }.sorted())
150        }
151        return HabitSnapshot(
152            habits: [
153                Entry(title: "Stretch", path: "", offset: 0, habit: habit(1, done: [1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 14])),
154                Entry(title: "Read 20 pages", path: "", offset: 0, habit: habit(1, done: [1, 3, 4, 8, 11, 15])),
155                Entry(title: "Water plants", path: "", offset: 0, habit: habit(3, done: [2, 5, 8, 11, 14, 17])),
156                Entry(title: "Review the week", path: "", offset: 0, habit: habit(7, done: [6, 13, 20])),
157            ],
158            colors: [:]
159        )
160    }
161}
162
163#Preview("Small", as: .systemSmall) {
164    HabitsWidget()
165} timeline: {
166    HabitEntry(date: .now, snapshot: .sample(.now))
167}
168
169#Preview("Medium", as: .systemMedium) {
170    HabitsWidget()
171} timeline: {
172    HabitEntry(date: .now, snapshot: .sample(.now))
173}