Sources/OrgstarWidgets/HabitsWidget.swift

design-themes-widgets
orgstar/Sources/OrgstarWidgets/HabitsWidget.swift history · blame · raw

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