86 lines · 3.3 KB · SwiftRaw
// Local calendar keys and the shared month face. The clock is supplied by the caller.import CottonKitimport CottonValuesimport Foundationpublic struct MonthGridCell: Equatable, Sendable, Identifiable { public let key: String public let dayOfMonth: Int public let inMonth: Bool public var id: String { key } public init(key: String, dayOfMonth: Int, inMonth: Bool) { self.key = key self.dayOfMonth = dayOfMonth self.inMonth = inMonth }}public enum CalendarDates { public static func toDateKey(_ at: Date, calendar: Calendar = .current) -> String { CottonDate.string(at, pattern: "yyyy-MM-dd", calendar: calendar) } public static func parseDateKey(_ key: String, calendar: Calendar = .current) -> Date? { guard CottonDate.isDayOnly(key) else { return nil } return CottonDate.parse(key, calendar: calendar) } public static func todayKey(now: Date, calendar: Calendar = .current) -> String { toDateKey(now, calendar: calendar) } public static func isTodayKey(_ key: String, now: Date, calendar: Calendar = .current) -> Bool { key == todayKey(now: now, calendar: calendar) } public static func buildMonthGrid(_ key: String, calendar: Calendar = .current) -> [[MonthGridCell]] { guard let anchor = parseDateKey(key, calendar: calendar) else { return [] } let parts = calendar.dateComponents([.year, .month], from: anchor) guard let year = parts.year, let month = parts.month, let first = calendar.date(from: DateComponents(year: year, month: month, day: 1)) else { return [] } // Monday = 0. `weekday` is 1…7 with Sunday = 1, whatever the locale's // own first day is — which is exactly why the offset is computed rather // than read off `calendar.firstWeekday`: the grid is Monday-start // because the ENGINE is, not because the phone's locale says so. let weekday = calendar.component(.weekday, from: first) let backToMonday = (weekday + 5) % 7 guard var cursor = calendar.date(byAdding: .day, value: -backToMonday, to: first) else { return [] } var weeks: [[MonthGridCell]] = [] repeat { var week: [MonthGridCell] = [] for _ in 0..<7 { week.append( MonthGridCell( key: toDateKey(cursor, calendar: calendar), dayOfMonth: calendar.component(.day, from: cursor), inMonth: calendar.component(.month, from: cursor) == month && calendar.component(.year, from: cursor) == year ) ) guard let next = calendar.date(byAdding: .day, value: 1, to: cursor) else { return weeks + [week] } cursor = next } weeks.append(week) } while calendar.component(.month, from: cursor) == month && calendar.component(.year, from: cursor) == year return weeks } public static func formatFullDate(_ key: String, calendar: Calendar = .current) -> String { guard let at = parseDateKey(key, calendar: calendar) else { return "" } return DateFormats.longDate(at, calendar: calendar) }}