Glimmer / app · glimmertoday.ai / native / Glimmer / Journal.swift
| 1 | import Foundation |
| 2 | |
| 3 | enum CalendarDay { |
| 4 | static func key(_ date: Date, calendar: Calendar = .current) -> String { |
| 5 | let day = calendar.dateComponents([.year, .month, .day], from: date) |
| 6 | return String(format: "%04d-%02d-%02d", day.year ?? 0, day.month ?? 0, day.day ?? 0) |
| 7 | } |
| 8 | |
| 9 | static func distance(_ start: Date, _ end: Date, calendar: Calendar = .current) -> Int { |
| 10 | calendar.dateComponents([.day], from: calendar.startOfDay(for: start), to: calendar.startOfDay(for: end)).day ?? 0 |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | enum Decision: String, CaseIterable, Codable, Identifiable { |
| 15 | case less, same, more |
| 16 | var id: Self { self } |
| 17 | var title: String { ["Less", "Same", "More"][Self.allCases.firstIndex(of: self) ?? 0] } |
| 18 | } |
| 19 | |
| 20 | enum Cadence: String, CaseIterable, Codable, Identifiable { |
| 21 | case daily = "Daily", weekly = "Weekly", monthly = "Monthly" |
| 22 | var id: Self { self } |
| 23 | } |
| 24 | |
| 25 | enum Tracker: String, CaseIterable, Codable, Identifiable { |
| 26 | case checklist = "Checklist", ring = "Ring" |
| 27 | var id: Self { self } |
| 28 | } |
| 29 | |
| 30 | struct PlanTask: Codable, Identifiable, Hashable { |
| 31 | var id = UUID().uuidString |
| 32 | /// An SF Symbol name. Older tasks may hold an emoji, which Glyph shows as its symbol. |
| 33 | var icon = "" |
| 34 | var name = "" |
| 35 | var category = "custom" |
| 36 | var anchor = Date() |
| 37 | var repeats = true |
| 38 | var cadence: Cadence = .daily |
| 39 | var every = 1 |
| 40 | var weekdays: Set<Int> = [] |
| 41 | |
| 42 | init() {} |
| 43 | |
| 44 | init(template: TaskTemplate, category: String? = nil, date: Date) { |
| 45 | id = template.id |
| 46 | icon = template.icon |
| 47 | name = template.name |
| 48 | self.category = category ?? template.cat ?? "custom" |
| 49 | anchor = date |
| 50 | repeats = template.freq != "Once" |
| 51 | cadence = template.freq == "Weekly" ? .weekly : template.freq == "Monthly" ? .monthly : .daily |
| 52 | } |
| 53 | |
| 54 | var coins: Int { |
| 55 | ["easy": 5, "focus": 15, "move": 10, "wind": 10, "offline": 15, "calm": 5][category] ?? 10 |
| 56 | } |
| 57 | |
| 58 | var schedule: String { |
| 59 | if !repeats { return anchor.formatted(.dateTime.month(.abbreviated).day()) } |
| 60 | if every <= 1 { return cadence.rawValue } |
| 61 | let unit = cadence == .daily ? "days" : cadence == .weekly ? "weeks" : "months" |
| 62 | return "Every \(every) \(unit)" |
| 63 | } |
| 64 | |
| 65 | func occurs(on date: Date, calendar: Calendar = .current) -> Bool { |
| 66 | let days = CalendarDay.distance(anchor, date, calendar: calendar) |
| 67 | guard days >= 0 else { return false } |
| 68 | if !repeats { return days == 0 } |
| 69 | let interval = max(1, every) |
| 70 | switch cadence { |
| 71 | case .daily: |
| 72 | return days.isMultiple(of: interval) |
| 73 | case .weekly: |
| 74 | guard let start = calendar.dateInterval(of: .weekOfYear, for: anchor)?.start, |
| 75 | let end = calendar.dateInterval(of: .weekOfYear, for: date)?.start else { return false } |
| 76 | let week = CalendarDay.distance(start, end, calendar: calendar) / 7 |
| 77 | let weekday = calendar.component(.weekday, from: date) |
| 78 | let valid = weekdays.isEmpty ? [calendar.component(.weekday, from: anchor)] : Array(weekdays) |
| 79 | return week.isMultiple(of: interval) && valid.contains(weekday) |
| 80 | case .monthly: |
| 81 | guard let start = calendar.dateInterval(of: .month, for: anchor)?.start, |
| 82 | let end = calendar.dateInterval(of: .month, for: date)?.start, |
| 83 | let daysInMonth = calendar.range(of: .day, in: .month, for: date)?.count else { return false } |
| 84 | let months = calendar.dateComponents([.month], from: start, to: end).month ?? 0 |
| 85 | let target = min(calendar.component(.day, from: anchor), daysInMonth) |
| 86 | return months.isMultiple(of: interval) && calendar.component(.day, from: date) == target |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | struct PersonalTodo: Codable, Identifiable, Equatable { |
| 92 | static let titleLimit = 160 |
| 93 | let id: UUID |
| 94 | var title: String |
| 95 | var dueDay: String? |
| 96 | var reminderAt: Date? |
| 97 | var completed = false |
| 98 | |
| 99 | init(id: UUID = UUID(), title: String = "", dueDay: String? = nil, reminderAt: Date? = nil) { |
| 100 | self.id = id |
| 101 | self.title = title |
| 102 | self.dueDay = dueDay |
| 103 | self.reminderAt = reminderAt |
| 104 | } |
| 105 | |
| 106 | var isValid: Bool { |
| 107 | (1...Self.titleLimit).contains(title.trimmingCharacters(in: .whitespacesAndNewlines).count) |
| 108 | && (dueDay.map { PracticeDate.parse($0) != nil } ?? true) |
| 109 | && (reminderAt?.timeIntervalSinceReferenceDate.isFinite ?? true) |
| 110 | } |
| 111 | |
| 112 | func isDue(by day: String) -> Bool { |
| 113 | !completed && (dueDay.map { $0 <= day } ?? false) |
| 114 | } |
| 115 | |
| 116 | static func ordered(_ tasks: [Self]) -> [Self] { |
| 117 | tasks.sorted { ($0.dueDay ?? "~") < ($1.dueDay ?? "~") } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// One step of a personal to-do. Steps are their own records so edits to different steps on two |
| 122 | /// devices both survive a sync, and older app versions that don't know steps can't erase them. |
| 123 | struct TodoStep: Codable, Identifiable, Equatable { |
| 124 | static let titleLimit = 160 |
| 125 | /// A step can be broken down once more. Deeper levels are not stored. |
| 126 | static let maxLevels = 2 |
| 127 | let id: UUID |
| 128 | let todoID: UUID |
| 129 | var parentID: UUID? |
| 130 | var title: String |
| 131 | var done = false |
| 132 | var order: Double |
| 133 | |
| 134 | init(id: UUID = UUID(), todoID: UUID, parentID: UUID? = nil, title: String, done: Bool = false, order: Double) { |
| 135 | self.id = id |
| 136 | self.todoID = todoID |
| 137 | self.parentID = parentID |
| 138 | self.title = title |
| 139 | self.done = done |
| 140 | self.order = order |
| 141 | } |
| 142 | |
| 143 | var isValid: Bool { |
| 144 | (1...Self.titleLimit).contains(title.trimmingCharacters(in: .whitespacesAndNewlines).count) && order.isFinite |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// A time estimate for a personal to-do, keyed by the to-do's ID. |
| 149 | struct TodoEstimate: Codable, Identifiable, Equatable { |
| 150 | static let range = 1...1440 |
| 151 | /// The to-do this estimate belongs to. |
| 152 | let id: UUID |
| 153 | var minutes: Int |
| 154 | /// Where the estimate came from: `ToolkitSource` raw values, or "person" when typed by hand. |
| 155 | var source: String |
| 156 | |
| 157 | var isValid: Bool { Self.range.contains(minutes) && !source.isEmpty && source.count <= 40 } |
| 158 | } |
| 159 | |
| 160 | struct Moment: Codable, Identifiable, Hashable { |
| 161 | static let words = ["Drained", "Off", "Neutral", "Lighter", "Nourished"] |
| 162 | var id = UUID() |
| 163 | var source: String |
| 164 | var kind: String |
| 165 | var tags: [String] |
| 166 | var value: Double |
| 167 | var decision: Decision |
| 168 | var date: Date |
| 169 | var day: String |
| 170 | var score: Int { Self.step(value) - 2 } |
| 171 | var word: String { Self.words[Self.step(value)] } |
| 172 | |
| 173 | static func step(_ value: Double) -> Int { |
| 174 | Int((min(1, max(0, value.isFinite ? value : 0.5)) * 4).rounded()) |
| 175 | } |
| 176 | |
| 177 | /// The general category a source belongs to. Summaries group by this, never by the source itself. |
| 178 | static func kind(of source: String, catalog: Catalog) -> String { |
| 179 | let name = source.lowercased() |
| 180 | if catalog.activities.contains(source) { return "Activity" } |
| 181 | if catalog.people.contains(source) { return "People" } |
| 182 | if ["chatgpt", "claude", "gemini", "perplexity", "copilot"].contains(where: { name.contains($0) }) { return "AI" } |
| 183 | if ["slack", "discord", "whatsapp", "telegram", "messages"].contains(where: { name.contains($0) }) { return "Messages" } |
| 184 | if ["vs code", "xcode", "github", "figma"].contains(where: { name.contains($0) }) { return "Work" } |
| 185 | if ["netflix", "twitch", "disney", "hulu"].contains(where: { name.contains($0) }) { return "Streaming" } |
| 186 | if ["news", "podcast"].contains(where: { name.contains($0) }) { return "News" } |
| 187 | return "Feed" |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | struct EnergyCheck: Codable { |
| 192 | let level: String |
| 193 | let value: Double |
| 194 | } |
| 195 | |
| 196 | struct ChallengeRecord: Codable { |
| 197 | let choice: String |
| 198 | let date: Date |
| 199 | var feedback: String? |
| 200 | } |
| 201 | |
| 202 | struct LessonRecord: Codable { |
| 203 | var page = 0 |
| 204 | var choices: [String: String] = [:] |
| 205 | var completed = false |
| 206 | } |
| 207 | |
| 208 | struct Experiment: Codable, Identifiable { |
| 209 | enum Outcome: String, CaseIterable, Codable, Identifiable { |
| 210 | case held = "Held it", slip = "Slipped a bit" |
| 211 | var id: Self { self } |
| 212 | } |
| 213 | |
| 214 | enum Review: String, CaseIterable, Codable, Identifiable { |
| 215 | case keep = "Keep it", adjust = "Adjust it", drop = "Drop it" |
| 216 | var id: Self { self } |
| 217 | } |
| 218 | |
| 219 | var id = UUID() |
| 220 | var suggestion: Suggestion |
| 221 | var start: Date |
| 222 | var checkins: [String: Outcome] = [:] |
| 223 | var review: Review? |
| 224 | let duration = 7 |
| 225 | |
| 226 | enum CodingKeys: String, CodingKey { case id, suggestion, start, checkins, review } |
| 227 | var readyToReview: Bool { checkins.count >= duration } |
| 228 | } |
| 229 | |
| 230 | struct Engagement: Codable { |
| 231 | var count = 0 |
| 232 | var requestedReview = false |
| 233 | var actions: Set<String> = [] |
| 234 | var shouldRequestReview: Bool { count >= 5 && !requestedReview && !actions.contains("review") } |
| 235 | } |
| 236 | |
| 237 | struct Journal: Codable { |
| 238 | var version = 1 |
| 239 | var started: Date? |
| 240 | var name = "" |
| 241 | var answers: [String: [String]] = [:] |
| 242 | var onboardingIndex = 0 |
| 243 | var tracker: Tracker = .checklist |
| 244 | var tasks: [PlanTask] = [] |
| 245 | // Optional for journals and backup files written before personal to-dos existed. |
| 246 | var personalTodos: [PersonalTodo]? |
| 247 | // Toolkit details for personal to-dos. Optional so older journals and backups still load. |
| 248 | var todoSteps: [TodoStep]? |
| 249 | var todoEstimates: [TodoEstimate]? |
| 250 | var completions: [String: Set<String>] = [:] |
| 251 | var rewards: [String: Int] = [:] |
| 252 | var moments: [Moment] = [] |
| 253 | var customSources: [String] = [] |
| 254 | /// Starred apps, activities and people. Optional so journals saved before favourites existed still load. |
| 255 | var favoriteSources: [String]? |
| 256 | var energy: [String: EnergyCheck] = [:] |
| 257 | var challenges: [String: ChallengeRecord] = [:] |
| 258 | var coffeeUnlocked = false |
| 259 | var habits: [String: Set<String>] = [:] |
| 260 | var moods: [String: Int] = [:] |
| 261 | var cleaningChecks: [String: Set<Int>] = [:] |
| 262 | var cleaningLast: [String: String] = [:] |
| 263 | var favoriteChores: Set<String>? |
| 264 | var recentChores: [String: Set<String>]? |
| 265 | var seasonalChecks: [String: Set<String>]? |
| 266 | var lessons: [String: LessonRecord] = [:] |
| 267 | /// Actual days of personal practice, retained as older checklist and activity records change. |
| 268 | var readerDays: Set<String>? |
| 269 | var experiment: Experiment? |
| 270 | var history: [Experiment] = [] |
| 271 | var queued: [Suggestion] = [] |
| 272 | var engagement = Engagement() |
| 273 | |
| 274 | var coins: Int { rewards.values.reduce(0, +) } |
| 275 | var onboardingComplete: Bool { started != nil } |
| 276 | |
| 277 | mutating func toggleSeasonalCheck(_ item: String, in checklist: String) { |
| 278 | var checks = seasonalChecks ?? [:] |
| 279 | if checks[checklist, default: []].remove(item) == nil { checks[checklist, default: []].insert(item) } |
| 280 | seasonalChecks = checks |
| 281 | } |
| 282 | |
| 283 | mutating func toggleFavoriteChore(_ id: String) { |
| 284 | var favorites = favoriteChores ?? [] |
| 285 | if favorites.remove(id) == nil { favorites.insert(id) } |
| 286 | favoriteChores = favorites |
| 287 | } |
| 288 | |
| 289 | mutating func toggleCleaningChore(_ list: CleaningList, at index: Int, on date: Date) { |
| 290 | let id = list.choreID(at: index) |
| 291 | let day = CalendarDay.key(date) |
| 292 | if cleaningChecks[list.id, default: []].remove(index) != nil { |
| 293 | recentChores?[id]?.remove(day) |
| 294 | return |
| 295 | } |
| 296 | cleaningChecks[list.id, default: []].insert(index) |
| 297 | var recent = recentChores ?? [:] |
| 298 | recent[id, default: []].insert(day) |
| 299 | recentChores = recent |
| 300 | if cleaningChecks[list.id]?.count == list.items.count { |
| 301 | cleaningLast[list.id] = day |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | mutating func toggleMaintenanceChore(_ id: String, on date: Date) { |
| 306 | let day = CalendarDay.key(date) |
| 307 | var recent = recentChores ?? [:] |
| 308 | if recent[id, default: []].remove(day) == nil { recent[id, default: []].insert(day) } |
| 309 | recentChores = recent |
| 310 | } |
| 311 | |
| 312 | func activeReaderDays(asOf date: Date) -> Set<String> { |
| 313 | var days = readerDays ?? [] |
| 314 | days.formUnion(moments.map(\.day)) |
| 315 | days.formUnion(energy.keys) |
| 316 | days.formUnion(moods.keys) |
| 317 | days.formUnion(cleaningLast.values) |
| 318 | for (day, tasks) in completions where !tasks.isEmpty { days.insert(day) } |
| 319 | for dates in habits.values { days.formUnion(dates) } |
| 320 | for challenge in challenges.values { days.insert(PracticeDate.key(challenge.date)) } |
| 321 | for experiment in history + [experiment].compactMap({ $0 }) { |
| 322 | days.insert(PracticeDate.key(experiment.start)) |
| 323 | days.formUnion(experiment.checkins.keys) |
| 324 | } |
| 325 | let latest = PracticeDate.key(date) |
| 326 | return days.filter { $0 <= latest && PracticeDate.parse($0) != nil } |
| 327 | } |
| 328 | |
| 329 | mutating func preserveReaderDays(asOf date: Date) { |
| 330 | let observed = activeReaderDays(asOf: date) |
| 331 | if !observed.isEmpty { readerDays = observed } |
| 332 | } |
| 333 | |
| 334 | mutating func award(_ amount: Int, key: String) { |
| 335 | if rewards[key] == nil { rewards[key] = amount } |
| 336 | if coins >= 80 { coffeeUnlocked = true } |
| 337 | } |
| 338 | |
| 339 | func planDay(on date: Date) -> Int { |
| 340 | max(1, CalendarDay.distance(started ?? date, date) + 1) |
| 341 | } |
| 342 | |
| 343 | func lessonIsOpen(_ number: Int, on date: Date) -> Bool { |
| 344 | planDay(on: date) >= number |
| 345 | } |
| 346 | |
| 347 | mutating func toggleTask(_ task: PlanTask, on date: Date) { |
| 348 | let day = CalendarDay.key(date) |
| 349 | let key = "task:\(day):\(task.id)" |
| 350 | if completions[day, default: []].remove(task.id) != nil { |
| 351 | rewards.removeValue(forKey: key) |
| 352 | } else { |
| 353 | completions[day, default: []].insert(task.id) |
| 354 | award(task.coins, key: key) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /// Checks a habit on or off for a day. The first check-off of a habit on a day earns coins, so the |
| 359 | /// coin celebration plays; unchecking takes them back. |
| 360 | mutating func toggleHabit(_ id: String, on date: Date) { |
| 361 | let day = CalendarDay.key(date) |
| 362 | let key = "habit:\(day):\(id)" |
| 363 | if habits[id, default: []].remove(day) != nil { |
| 364 | rewards.removeValue(forKey: key) |
| 365 | } else { |
| 366 | habits[id, default: []].insert(day) |
| 367 | award(5, key: key) |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | /// Marks a personal to-do done or open. Finishing one earns coins once; reopening takes them back. |
| 372 | mutating func setPersonalTodo(_ id: UUID, done: Bool) -> Bool { |
| 373 | guard let index = personalTodos?.firstIndex(where: { $0.id == id }) else { return false } |
| 374 | personalTodos?[index].completed = done |
| 375 | let key = "todo:\(id.uuidString)" |
| 376 | if done { award(5, key: key) } else { rewards.removeValue(forKey: key) } |
| 377 | return true |
| 378 | } |
| 379 | |
| 380 | mutating func record(_ moment: Moment) { |
| 381 | guard !moments.contains(where: { $0.id == moment.id }) else { return } |
| 382 | moments.append(moment) |
| 383 | award(10, key: "log:\(moment.day)") |
| 384 | engagement.count += 1 |
| 385 | } |
| 386 | |
| 387 | mutating func recordEnergy(_ check: EnergyCheck, on date: Date) { |
| 388 | let key = CalendarDay.key(date) |
| 389 | energy[key] = check |
| 390 | award(5, key: "energy:\(key)") |
| 391 | } |
| 392 | |
| 393 | mutating func completeChallenge(_ challenge: Challenge, choice: String, on date: Date) { |
| 394 | guard challenges[challenge.id] == nil else { return } |
| 395 | challenges[challenge.id] = ChallengeRecord(choice: choice, date: date) |
| 396 | award(challenge.coins, key: "challenge:\(challenge.id)") |
| 397 | } |
| 398 | |
| 399 | mutating func completeLesson(_ lesson: Lesson, on date: Date) { |
| 400 | guard lessonIsOpen(lesson.number, on: date), lessons[lesson.id]?.completed != true else { return } |
| 401 | lessons[lesson.id, default: LessonRecord()].completed = true |
| 402 | readerDays = (readerDays ?? []).union([PracticeDate.key(date)]) |
| 403 | award(15, key: "lesson:\(lesson.id)") |
| 404 | } |
| 405 | |
| 406 | mutating func checkIn(_ outcome: Experiment.Outcome, on date: Date) { |
| 407 | guard let active = experiment, !active.readyToReview, date >= Calendar.current.startOfDay(for: active.start) else { return } |
| 408 | let day = CalendarDay.key(date) |
| 409 | guard active.checkins[day] == nil else { return } |
| 410 | experiment?.checkins[day] = outcome |
| 411 | } |
| 412 | |
| 413 | mutating func reviewExperiment(_ review: Experiment.Review, on date: Date) { |
| 414 | guard var active = experiment, active.readyToReview else { return } |
| 415 | active.review = review |
| 416 | history.append(active) |
| 417 | experiment = nil |
| 418 | award(60, key: "experiment:\(active.id)") |
| 419 | if review == .adjust { |
| 420 | let suggestion = Suggestion(type: "Adjustment", title: active.suggestion.title, |
| 421 | sub: "Try a smaller version of this experiment for another week.") |
| 422 | experiment = Experiment(suggestion: suggestion, start: date) |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | // MARK: - To-do steps and estimates |
| 428 | |
| 429 | extension Journal { |
| 430 | /// Steps directly under a to-do (parent nil) or under one step, in their saved order. |
| 431 | func steps(for todoID: UUID, parent: UUID? = nil) -> [TodoStep] { |
| 432 | (todoSteps ?? []).filter { $0.todoID == todoID && $0.parentID == parent } |
| 433 | .sorted { ($0.order, $0.id.uuidString) < ($1.order, $1.id.uuidString) } |
| 434 | } |
| 435 | |
| 436 | /// Every step of a to-do in reading order: each step followed by its own smaller steps. |
| 437 | func flatSteps(for todoID: UUID) -> [TodoStep] { |
| 438 | steps(for: todoID).flatMap { [$0] + steps(for: todoID, parent: $0.id) } |
| 439 | } |
| 440 | |
| 441 | /// The step to work on now: the first unfinished step, or its first unfinished smaller step. |
| 442 | func nextStep(for todoID: UUID, skipping skipped: Set<UUID> = []) -> TodoStep? { |
| 443 | for step in steps(for: todoID) where !step.done && !skipped.contains(step.id) { |
| 444 | let children = steps(for: todoID, parent: step.id).filter { !$0.done && !skipped.contains($0.id) } |
| 445 | return children.first ?? step |
| 446 | } |
| 447 | return nil |
| 448 | } |
| 449 | |
| 450 | func estimate(for todoID: UUID) -> TodoEstimate? { |
| 451 | todoEstimates?.first { $0.id == todoID } |
| 452 | } |
| 453 | |
| 454 | /// Replaces the steps at one level. Smaller steps of removed steps go with them. |
| 455 | mutating func replaceSteps(for todoID: UUID, parent: UUID? = nil, with titles: [String]) { |
| 456 | let clean = titles.map { String($0.trimmingCharacters(in: .whitespacesAndNewlines).prefix(TodoStep.titleLimit)) } |
| 457 | .filter { !$0.isEmpty } |
| 458 | let old = steps(for: todoID, parent: parent) |
| 459 | let removed = Set(old.map(\.id)) |
| 460 | var all = (todoSteps ?? []).filter { !removed.contains($0.id) && !removed.contains($0.parentID ?? UUID()) } |
| 461 | for (index, title) in clean.enumerated() { |
| 462 | // Keep a step's identity and done state when its text is unchanged. |
| 463 | if let kept = old.first(where: { $0.title == title && !all.contains($0) }) { |
| 464 | var step = kept |
| 465 | step.order = Double(index) |
| 466 | all.append(step) |
| 467 | all += (todoSteps ?? []).filter { $0.parentID == kept.id } |
| 468 | } else { |
| 469 | all.append(TodoStep(todoID: todoID, parentID: parent, title: title, order: Double(index))) |
| 470 | } |
| 471 | } |
| 472 | todoSteps = all |
| 473 | } |
| 474 | |
| 475 | mutating func setStepDone(_ id: UUID, done: Bool) { |
| 476 | guard let index = todoSteps?.firstIndex(where: { $0.id == id }) else { return } |
| 477 | todoSteps?[index].done = done |
| 478 | // Finishing a step finishes its smaller steps too. |
| 479 | guard done, let step = todoSteps?[index] else { return } |
| 480 | for child in steps(for: step.todoID, parent: step.id) where !child.done { setStepDone(child.id, done: true) } |
| 481 | // Finishing the last smaller step finishes the step it belongs to. |
| 482 | if let parent = step.parentID, steps(for: step.todoID, parent: parent).allSatisfy(\.done), |
| 483 | todoSteps?.first(where: { $0.id == parent })?.done == false { |
| 484 | setStepDone(parent, done: true) |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | mutating func setEstimate(_ minutes: Int?, source: String, for todoID: UUID) { |
| 489 | var estimates = (todoEstimates ?? []).filter { $0.id != todoID } |
| 490 | if let minutes { estimates.append(TodoEstimate(id: todoID, minutes: min(max(minutes, 1), 1440), source: source)) } |
| 491 | todoEstimates = estimates |
| 492 | } |
| 493 | |
| 494 | /// Removes a to-do with its steps and estimate. |
| 495 | mutating func removePersonalTodo(_ id: UUID) { |
| 496 | personalTodos?.removeAll { $0.id == id } |
| 497 | todoSteps?.removeAll { $0.todoID == id } |
| 498 | todoEstimates?.removeAll { $0.id == id } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | extension Journal { |
| 503 | /// Built-in activity and people names that carried an emoji before 1.1.4. |
| 504 | static let emojiBuiltInNames: Set<String> = [ |
| 505 | "🚶 Walk", "🏋️ Workout", "🍳 Cooked", "📖 Read", "🎮 Gaming", "🧹 Tidied up", "🎧 Music", "🛌 Rested", "🧘 Meditated", "🤸 Stretched", "🌳 Time outside", "😴 Napped", "✍️ Journaled", "🎨 Made something", "🎸 Played music", "🎙️ Podcast", "📚 Studied", "💻 Deep work", "🛒 Errands", "🚿 Shower", "☕ Coffee break", "🌱 Gardened", "📞 Called a friend", "💛 Time with partner", "🍽️ Family dinner", "💬 Coworker chat", "👋 Saw a friend", "🎉 Group hangout" |
| 506 | ] |
| 507 | |
| 508 | /// Renames moments and favourites logged under an older emoji built-in name, such as "💻 Deep work", |
| 509 | /// to the plain name the catalog now uses. Names people typed themselves are left as they wrote them. |
| 510 | func droppingBuiltInEmoji() -> Journal { |
| 511 | func plain(_ name: String) -> String { Self.emojiBuiltInNames.contains(name) ? Glyph.plainName(name) : name } |
| 512 | var journal = self |
| 513 | for index in journal.moments.indices { journal.moments[index].source = plain(journal.moments[index].source) } |
| 514 | if let favorites = journal.favoriteSources { |
| 515 | var seen = Set<String>() |
| 516 | journal.favoriteSources = favorites.map(plain).filter { seen.insert($0).inserted } |
| 517 | } |
| 518 | return journal |
| 519 | } |
| 520 | } |