Sources/OrgstarWidgets/HabitsWidget.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgstarWidgets/HabitsWidget.swift history · blame · raw

177 lines · 7538 bytes

14 symbols in this file
  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 = widgetsLocked ? nil : 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 = widgetsLocked ? nil : 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 ? !widgetsLocked ? "Open orgstar to show your habits here." : "Widgets need orgstar+." : "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        #if os(macOS)
 64        .containerBackground(for: .widget) { Color(nsColor: .windowBackgroundColor) }
 65        #else
 66        .containerBackground(for: .widget) { Color(uiColor: .systemBackground) }
 67        #endif
 68    }
 69
 70    private func content(_ snapshot: HabitSnapshot) -> some View {
 71        let limit = family == .systemLarge ? 9 : family == .systemMedium ? 4 : 3
 72        let done = snapshot.habits.filter { $0.habit.doneDates.contains(today) }.count
 73        return VStack(alignment: .leading, spacing: family == .systemSmall ? 6 : 8) {
 74            HStack(alignment: .firstTextBaseline) {
 75                Text("Habits").font(.subheadline.weight(.semibold))
 76                Spacer(minLength: 0)
 77                Text("\(done)/\(snapshot.habits.count) today").font(.caption2.weight(.semibold)).foregroundStyle(.secondary)
 78            }
 79            ForEach(snapshot.habits.prefix(limit)) { habit in
 80                Link(destination: habit.link.url) { row(habit, snapshot) }
 81            }
 82            Spacer(minLength: 0)
 83        }
 84        .frame(maxWidth: .infinity, alignment: .leading)
 85    }
 86
 87    @ViewBuilder
 88    private func row(_ habit: HabitSnapshot.Entry, _ snapshot: HabitSnapshot) -> some View {
 89        if family == .systemSmall {
 90            // The last week, today last.
 91            let cells = habit.habit.graph(today: today, preceding: 6, following: 1)
 92            VStack(alignment: .leading, spacing: 2) {
 93                Text(habit.title).font(.caption).lineLimit(1)
 94                HabitCells(cells: cells, colors: snapshot.colors, width: 12, height: 8)
 95            }
 96        } else {
 97            HStack(spacing: 8) {
 98                Text(habit.title).font(.caption).lineLimit(1)
 99                Spacer(minLength: 4)
100                HabitCells(cells: habit.habit.graph(today: today), colors: snapshot.colors, width: 5, height: 12)
101            }
102        }
103    }
104}
105
106/// org-habit's graph: a bar per day in the due-state color, lighter for days to come, a dot
107/// where it was done, today outlined.
108struct HabitCells: View {
109    let cells: [Habit.Cell]
110    let colors: [String: AgendaSnapshot.Hex]
111    let width: CGFloat
112    let height: CGFloat
113    @Environment(\.colorScheme) private var scheme
114
115    var body: some View {
116        HStack(spacing: 1) {
117            ForEach(cells, id: \.day) { cell in
118                RoundedRectangle(cornerRadius: 1.5)
119                    .fill(color(cell.face))
120                    .frame(width: width, height: height)
121                    .overlay {
122                        if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: min(width, height) * 0.6) }
123                    }
124                    .overlay {
125                        if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
126                    }
127            }
128        }
129        .accessibilityElement(children: .ignore)
130        .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of \(cells.count) days")
131    }
132
133    private func color(_ face: Habit.Face) -> Color {
134        func themed(_ key: String, _ fallback: Color) -> Color { colors[key]?.color(scheme) ?? fallback }
135        switch face {
136        case .clear: return themed("habit-clear", .blue).opacity(0.7)
137        case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
138        case .ready: return themed("habit-ready", .green).opacity(0.8)
139        case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
140        case .alert: return themed("habit-alert", .yellow).opacity(0.85)
141        case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
142        case .overdue: return themed("habit-overdue", .red).opacity(0.8)
143        case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
144        }
145    }
146}
147
148extension HabitSnapshot {
149    /// Habits for the gallery and previews.
150    static func sample(_ now: Date) -> HabitSnapshot {
151        let today = Days.absolute(now, calendar: .current)
152        func habit(_ every: Int, done: [Int]) -> Habit {
153            Habit(scheduled: today, scheduledRepeat: every, doneDates: done.map { today - $0 }.sorted())
154        }
155        return HabitSnapshot(
156            habits: [
157                Entry(title: "Stretch", path: "", offset: 0, habit: habit(1, done: [1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 14])),
158                Entry(title: "Read 20 pages", path: "", offset: 0, habit: habit(1, done: [1, 3, 4, 8, 11, 15])),
159                Entry(title: "Water plants", path: "", offset: 0, habit: habit(3, done: [2, 5, 8, 11, 14, 17])),
160                Entry(title: "Review the week", path: "", offset: 0, habit: habit(7, done: [6, 13, 20])),
161            ],
162            colors: [:]
163        )
164    }
165}
166
167#Preview("Small", as: .systemSmall) {
168    HabitsWidget()
169} timeline: {
170    HabitEntry(date: .now, snapshot: .sample(.now))
171}
172
173#Preview("Medium", as: .systemMedium) {
174    HabitsWidget()
175} timeline: {
176    HabitEntry(date: .now, snapshot: .sample(.now))
177}