Sources/OrgstarWidgets/HabitsWidget.swift

490f2b3917087e2e986e8581ec3c526ebf43f64a
orgstar/Sources/OrgstarWidgets/HabitsWidget.swift

218 lines · 9615 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 = 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. With Differentiate Without Colour, the state is also
108/// how solid the bar is, from clear (faintest) to overdue (solid), and days to come are
109/// outlined.
110struct HabitCells: View {
111    let cells: [Habit.Cell]
112    let colors: [String: AgendaSnapshot.Hex]
113    let width: CGFloat
114    let height: CGFloat
115    @Environment(\.colorScheme) private var scheme
116    @Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor
117
118    private var stepped: Bool { differentiateWithoutColor }
119
120    var body: some View {
121        HStack(spacing: 1) {
122            ForEach(cells, id: \.day) { cell in
123                if stepped {
124                    steppedCell(cell)
125                } else {
126                    RoundedRectangle(cornerRadius: 1.5)
127                        .fill(color(cell.face))
128                        .frame(width: width, height: height)
129                        .overlay {
130                            if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: min(width, height) * 0.6) }
131                        }
132                        .overlay {
133                            if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
134                        }
135                }
136            }
137        }
138        .accessibilityElement(children: .ignore)
139        .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of \(cells.count) days")
140    }
141
142    /// A filled bar for past days and an outline for days to come, at the state's step; a
143    /// done day has a dot, cut out of the darker steps.
144    private func steppedCell(_ cell: Habit.Cell) -> some View {
145        let (key, fallback, step, future) = Self.state(cell.face)
146        let color = (colors[key]?.color(scheme) ?? fallback).opacity(step)
147        let shape = RoundedRectangle(cornerRadius: 1.5)
148        let dot = Circle().frame(width: min(width, height) * 0.6)
149        return ZStack {
150            if future { shape.strokeBorder(color, lineWidth: 1) } else { shape.fill(color) }
151            if cell.glyph == "*" {
152                if step >= 0.75 { dot.blendMode(.destinationOut) } else { dot.foregroundStyle(Color.primary) }
153            }
154            if cell.glyph == "!" { shape.strokeBorder(Color.primary, lineWidth: 1) }
155        }
156        .compositingGroup()
157        .frame(width: width, height: height)
158    }
159
160    /// The theme key, its fallback, the opacity step and whether the day is to come.
161    private static func state(_ face: Habit.Face) -> (String, Color, Double, Bool) {
162        switch face {
163        case .clear: ("habit-clear", .blue, 0.25, false)
164        case .clearFuture: ("habit-clear", .blue, 0.25, true)
165        case .ready: ("habit-ready", .green, 0.5, false)
166        case .readyFuture: ("habit-ready", .green, 0.5, true)
167        case .alert: ("habit-alert", .yellow, 0.75, false)
168        case .alertFuture: ("habit-alert", .yellow, 0.75, true)
169        case .overdue: ("habit-overdue", .red, 1, false)
170        case .overdueFuture: ("habit-overdue", .red, 1, true)
171        }
172    }
173
174    private func color(_ face: Habit.Face) -> Color {
175        func themed(_ key: String, _ fallback: Color) -> Color { colors[key]?.color(scheme) ?? fallback }
176        switch face {
177        case .clear: return themed("habit-clear", .blue).opacity(0.7)
178        case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
179        case .ready: return themed("habit-ready", .green).opacity(0.8)
180        case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
181        case .alert: return themed("habit-alert", .yellow).opacity(0.85)
182        case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
183        case .overdue: return themed("habit-overdue", .red).opacity(0.8)
184        case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
185        }
186    }
187}
188
189extension HabitSnapshot {
190    /// Habits for the gallery and previews.
191    static func sample(_ now: Date) -> HabitSnapshot {
192        let today = Days.absolute(now, calendar: .current)
193        func habit(_ every: Int, done: [Int]) -> Habit {
194            Habit(scheduled: today, scheduledRepeat: every, doneDates: done.map { today - $0 }.sorted())
195        }
196        return HabitSnapshot(
197            habits: [
198                Entry(title: "Stretch", path: "", offset: 0, habit: habit(1, done: [1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 14])),
199                Entry(title: "Read 20 pages", path: "", offset: 0, habit: habit(1, done: [1, 3, 4, 8, 11, 15])),
200                Entry(title: "Water plants", path: "", offset: 0, habit: habit(3, done: [2, 5, 8, 11, 14, 17])),
201                Entry(title: "Review the week", path: "", offset: 0, habit: habit(7, done: [6, 13, 20])),
202            ],
203            colors: [:]
204        )
205    }
206}
207
208#Preview("Small", as: .systemSmall) {
209    HabitsWidget()
210} timeline: {
211    HabitEntry(date: .now, snapshot: .sample(.now))
212}
213
214#Preview("Medium", as: .systemMedium) {
215    HabitsWidget()
216} timeline: {
217    HabitEntry(date: .now, snapshot: .sample(.now))
218}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form