Task.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // Task.swift
  3. // Todos
  4. //
  5. // Created by Sam Jaffe on 2/28/26.
  6. //
  7. import Foundation
  8. import SwiftData
  9. import SwiftUI
  10. @Model
  11. final class Task: Codable {
  12. var sortOrder: Int = 0
  13. var name: String = ""
  14. var project: Project?
  15. var category: String = ""
  16. @Relationship(deleteRule: .cascade, inverse: \Tag.task)
  17. var tags: [Tag] = []
  18. @Relationship(deleteRule: .cascade, inverse: \SubTask.task)
  19. var subtasks: [SubTask] = []
  20. var notes: String = ""
  21. var status: Status = Status.todo
  22. init(parent: Project? = nil) {
  23. self.project = parent
  24. self.category = parent?.category ?? ""
  25. self.sortOrder = parent?.tasks.count ?? 0
  26. }
  27. func yaml(_ indent: Int = 0) -> String {
  28. let hdr = String(repeating: " ", count: indent)
  29. let subhdr = hdr + " # "
  30. var rval = hdr + "[\(status.rawValue)] \(name) "
  31. rval += "(\(tags.map(\.id).joined(separator: " ")))\n"
  32. if !notes.isEmpty {
  33. rval += subhdr + notes.replacingOccurrences(of: "\n", with: "\n" + subhdr) + "\n"
  34. }
  35. rval += subtasks.map({ $0.yaml(indent + 1) }).joined()
  36. return rval
  37. }
  38. enum CodingKeys: CodingKey { case name, category, tags, subtasks, notes, status }
  39. required init(from decoder: any Decoder) throws {
  40. let container = try decoder.container(keyedBy: CodingKeys.self)
  41. name = try container.decode(String.self, forKey: .name)
  42. category = try container.decode(String.self, forKey: .category)
  43. tags = try container.decode([Tag].self, forKey: .tags)
  44. subtasks = try container.decode([SubTask].self, forKey: .subtasks)
  45. notes = try container.decode(String.self, forKey: .notes)
  46. status = try container.decode(Status.self, forKey: .status)
  47. tags.forEach({ $0.task = self })
  48. for (index, item) in subtasks.enumerated() {
  49. item.task = self
  50. item.sortOrder = index
  51. }
  52. }
  53. func encode(to encoder: any Encoder) throws {
  54. var container = encoder.container(keyedBy: CodingKeys.self)
  55. try container.encode(name, forKey: .name)
  56. try container.encode(category, forKey: .category)
  57. try container.encode(tags, forKey: .tags)
  58. try container.encode(subtasks, forKey: .subtasks)
  59. try container.encode(notes, forKey: .notes)
  60. try container.encode(status, forKey: .status)
  61. }
  62. }