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