SPB Git

Repository Public License

ORIXAlarmWidgets.swift 19.4 KB 371 lines swift

1// ORIX Alarm2// File: Widgets/ORIXAlarmWidgets.swift3// Description: Widget bundle: Next Alarm, Countdown to Wake, Weekly Schedule, Quick Alarm, Wake Progress and the AlarmKit Live Activity.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI9import WidgetKit1011@main12struct ORIXAlarmWidgetBundle: WidgetBundle {13    var body: some Widget {14        NextAlarmWidget()15        CountdownWidget()16        WeeklyScheduleWidget()17        QuickAlarmWidget()18        WakeProgressWidget()19        AlarmLiveActivity()20    }21}2223/// Palette of the widgets (mirrors the app's design system, which is not compiled into the extension).24enum WidgetTheme {25    static let midnight = Color(red: 0.027, green: 0.035, blue: 0.086)26    static let indigo = Color(red: 0.180, green: 0.160, blue: 0.450)27    static let violet = Color(red: 0.478, green: 0.361, blue: 0.980)28    static let ember = Color(red: 0.980, green: 0.360, blue: 0.290)29    static let sunrise = Color(red: 1.000, green: 0.560, blue: 0.260)30    static let gold = Color(red: 1.000, green: 0.790, blue: 0.420)31    static let success = Color(red: 0.360, green: 0.880, blue: 0.640)32    static let sunriseGradient = LinearGradient(colors: [ember, sunrise, gold], startPoint: .bottomLeading, endPoint: .topTrailing)33    static let background = LinearGradient(colors: [indigo, midnight], startPoint: .top, endPoint: .bottom)34}3536// MARK: - Timeline3738struct AlarmEntry: TimelineEntry {39    let date: Date40    let snapshot: WidgetSnapshot41    var upcoming: [(entry: WidgetSnapshot.Entry, date: Date)] { snapshot.upcoming(after: date) }42    var next: (entry: WidgetSnapshot.Entry, date: Date)? { upcoming.first }4344    static let preview: AlarmEntry = {45        let now = Date.now46        let c = Calendar.current.dateComponents([.hour, .minute], from: now.addingTimeInterval(7.5 * 3600))47        return AlarmEntry(date: now, snapshot: WidgetSnapshot(generatedAt: now, alarms: [48            .init(id: UUID(), name: "Workday", hour: c.hour ?? 6, minute: c.minute ?? 30, weekdays: [2, 3, 4, 5, 6], isEnabled: true, missionCount: 3, symbol: "bolt.fill"),49            .init(id: UUID(), name: "Weekend", hour: 9, minute: 0, weekdays: [1, 7], isEnabled: true, missionCount: 1, symbol: "cup.and.saucer.fill"),50        ], confirmedDays: (1...4).compactMap { Calendar.current.date(byAdding: .day, value: -$0, to: Calendar.current.startOfDay(for: now)) }, currentStreak: 4))51    }()52}5354/// One entry now and one right after each of the next alarms, so the widget moves on to the following alarm by itself.55struct AlarmTimelineProvider: TimelineProvider {56    func placeholder(in context: Context) -> AlarmEntry { .preview }57    func getSnapshot(in context: Context, completion: @escaping (AlarmEntry) -> Void) {58        completion(context.isPreview ? .preview : AlarmEntry(date: .now, snapshot: .load()))59    }60    func getTimeline(in context: Context, completion: @escaping (Timeline<AlarmEntry>) -> Void) {61        let snapshot = WidgetSnapshot.load()62        let now = Date.now63        var dates = [now]64        var cursor = now65        for _ in 0..<12 {66            guard let next = snapshot.upcoming(after: cursor).first?.date else { break }67            cursor = next.addingTimeInterval(60)68            dates.append(cursor)69        }70        // Also refresh at midnight so "today/tomorrow" labels and the weekly view stay right.71        if let midnight = Calendar.current.nextDate(after: now, matching: DateComponents(hour: 0, minute: 0, second: 5), matchingPolicy: .nextTime) { dates.append(midnight) }72        let entries = Array(Set(dates)).sorted().map { AlarmEntry(date: $0, snapshot: snapshot) }73        completion(Timeline(entries: entries, policy: .atEnd))74    }75}7677// MARK: - Shared pieces7879enum WidgetFormat {80    static func time(hour: Int, minute: Int) -> String {81        var c = DateComponents(); c.hour = hour; c.minute = minute82        guard let d = Calendar.current.date(from: c) else { return String(format: "%02d:%02d", hour, minute) }83        return d.formatted(date: .omitted, time: .shortened)84    }85    static func day(_ date: Date, relativeTo now: Date) -> String {86        let cal = Calendar.current87        if cal.isDate(date, inSameDayAs: now) { return String(localized: "Today") }88        if let t = cal.date(byAdding: .day, value: 1, to: now), cal.isDate(date, inSameDayAs: t) { return String(localized: "Tomorrow") }89        return date.formatted(.dateTime.weekday(.wide))90    }91}9293struct NoAlarmView: View {94    var compact = false95    var body: some View {96        VStack(alignment: .leading, spacing: 4) {97            Image(systemName: "moon.zzz.fill").font(compact ? .body : .title2).foregroundStyle(WidgetTheme.violet)98            Text("No alarm set").font(.system(compact ? .caption : .headline, design: .rounded, weight: .semibold))99            if !compact { Text("Tap to create one").font(.caption2).foregroundStyle(.secondary) }100        }101        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)102        .accessibilityElement(children: .combine)103    }104}105106// MARK: - Next Alarm107108struct NextAlarmWidget: Widget {109    var body: some WidgetConfiguration {110        StaticConfiguration(kind: "NextAlarm", provider: AlarmTimelineProvider()) { entry in111            NextAlarmView(entry: entry).containerBackground(for: .widget) { WidgetTheme.background }112                .widgetURL(URL(string: entry.next == nil ? "orixalarm://new" : "orixalarm://alarms"))113        }114        .configurationDisplayName("Next Alarm").description("The next alarm that will ring.")115        .supportedFamilies([.systemSmall, .accessoryRectangular, .accessoryInline, .accessoryCircular])116    }117}118119struct NextAlarmView: View {120    @Environment(\.widgetFamily) private var family121    let entry: AlarmEntry122    var body: some View {123        switch family {124        case .accessoryInline:125            if let next = entry.next { Label("\(WidgetFormat.time(hour: next.entry.hour, minute: next.entry.minute)) \(WidgetFormat.day(next.date, relativeTo: entry.date))", systemImage: "alarm") }126            else { Label("No alarm", systemImage: "alarm") }127        case .accessoryCircular:128            ZStack {129                AccessoryWidgetBackground()130                if let next = entry.next {131                    VStack(spacing: 0) {132                        Image(systemName: "alarm.fill").font(.caption2)133                        Text(WidgetFormat.time(hour: next.entry.hour, minute: next.entry.minute).replacingOccurrences(of: " ", with: "\n"))134                            .font(.system(size: 12, weight: .semibold, design: .rounded)).multilineTextAlignment(.center).minimumScaleFactor(0.6)135                    }136                } else { Image(systemName: "moon.zzz.fill") }137            }138            .accessibilityLabel(entry.next.map { "Next alarm at \(WidgetFormat.time(hour: $0.entry.hour, minute: $0.entry.minute))" } ?? "No alarm set")139        case .accessoryRectangular:140            if let next = entry.next {141                VStack(alignment: .leading, spacing: 1) {142                    Label(next.entry.name.isEmpty ? "Alarm" : next.entry.name, systemImage: "alarm.fill").font(.caption2).widgetAccentable()143                    Text(WidgetFormat.time(hour: next.entry.hour, minute: next.entry.minute)).font(.system(.title2, design: .rounded, weight: .semibold))144                    Text(WidgetFormat.day(next.date, relativeTo: entry.date)).font(.caption2).foregroundStyle(.secondary)145                }146                .frame(maxWidth: .infinity, alignment: .leading).accessibilityElement(children: .combine)147            } else { NoAlarmView(compact: true) }148        default:149            if let next = entry.next {150                VStack(alignment: .leading, spacing: 2) {151                    HStack {152                        Image(systemName: next.entry.symbol).foregroundStyle(WidgetTheme.sunriseGradient)153                        Spacer()154                        if next.entry.missionCount > 0 {155                            Label("\(next.entry.missionCount)", systemImage: "puzzlepiece.extension.fill").font(.caption2).foregroundStyle(.secondary)156                                .accessibilityLabel("\(next.entry.missionCount) wake missions")157                        }158                    }159                    Spacer(minLength: 0)160                    Text(next.entry.name.isEmpty ? "Alarm" : next.entry.name).font(.system(.caption, design: .rounded, weight: .medium)).foregroundStyle(.secondary).lineLimit(1)161                    Text(WidgetFormat.time(hour: next.entry.hour, minute: next.entry.minute))162                        .font(.system(size: 34, weight: .light, design: .rounded)).monospacedDigit().minimumScaleFactor(0.6).lineLimit(1)163                    Text(WidgetFormat.day(next.date, relativeTo: entry.date)).font(.system(.caption2, design: .rounded, weight: .semibold)).foregroundStyle(WidgetTheme.gold)164                }165                .foregroundStyle(.white)166                .accessibilityElement(children: .combine)167            } else { NoAlarmView().foregroundStyle(.white) }168        }169    }170}171172// MARK: - Countdown to Wake173174struct CountdownWidget: Widget {175    var body: some WidgetConfiguration {176        StaticConfiguration(kind: "CountdownToWake", provider: AlarmTimelineProvider()) { entry in177            CountdownView(entry: entry).containerBackground(for: .widget) { WidgetTheme.background }178                .widgetURL(URL(string: "orixalarm://today"))179        }180        .configurationDisplayName("Countdown to Wake").description("Time left before your next alarm.")181        .supportedFamilies([.systemSmall, .systemMedium])182    }183}184185struct CountdownView: View {186    @Environment(\.widgetFamily) private var family187    let entry: AlarmEntry188    var body: some View {189        if let next = entry.next {190            HStack(spacing: 14) {191                VStack(alignment: .leading, spacing: 4) {192                    Label("Wake in", systemImage: "sunrise.fill").font(.system(.caption, design: .rounded, weight: .semibold)).foregroundStyle(WidgetTheme.gold)193                    Spacer(minLength: 0)194                    // Self-updating relative text: the widget does not need to be refreshed every minute.195                    Text(next.date, style: .relative).font(.system(size: family == .systemSmall ? 26 : 32, weight: .semibold, design: .rounded))196                        .monospacedDigit().minimumScaleFactor(0.5).lineLimit(2)197                    Text("\(WidgetFormat.day(next.date, relativeTo: entry.date)) · \(WidgetFormat.time(hour: next.entry.hour, minute: next.entry.minute))")198                        .font(.caption2).foregroundStyle(.secondary).lineLimit(1)199                }200                if family == .systemMedium {201                    Spacer(minLength: 0)202                    ZStack {203                        Circle().stroke(.white.opacity(0.12), lineWidth: 8)204                        // Share of the 24 hours before the alarm that has elapsed at this entry.205                        Circle().trim(from: 0, to: max(0.02, 1 - min(1, next.date.timeIntervalSince(entry.date) / 86_400)))206                            .stroke(WidgetTheme.sunriseGradient, style: StrokeStyle(lineWidth: 8, lineCap: .round)).rotationEffect(.degrees(-90))207                        Image(systemName: next.entry.symbol).font(.title2).foregroundStyle(WidgetTheme.gold)208                    }209                    .frame(width: 92, height: 92).accessibilityHidden(true)210                }211            }212            .foregroundStyle(.white)213            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)214        } else { NoAlarmView().foregroundStyle(.white) }215    }216}217218// MARK: - Weekly Schedule219220struct WeeklyScheduleWidget: Widget {221    var body: some WidgetConfiguration {222        StaticConfiguration(kind: "WeeklySchedule", provider: AlarmTimelineProvider()) { entry in223            WeeklyScheduleView(entry: entry).containerBackground(for: .widget) { WidgetTheme.background }224                .widgetURL(URL(string: "orixalarm://alarms"))225        }226        .configurationDisplayName("Weekly Schedule").description("The first alarm of each of the next seven days.")227        .supportedFamilies([.systemMedium])228    }229}230231struct WeeklyScheduleView: View {232    let entry: AlarmEntry233    /// First alarm ringing on each of the next seven days (today first).234    private var days: [(day: Date, time: String?)] {235        let cal = Calendar.current236        let start = cal.startOfDay(for: entry.date)237        return (0..<7).compactMap { offset -> (day: Date, time: String?)? in238            guard let day = cal.date(byAdding: .day, value: offset, to: start), let end = cal.date(byAdding: .day, value: 1, to: day) else { return nil }239            let from = offset == 0 ? entry.date : day.addingTimeInterval(-1)240            let first = entry.snapshot.upcoming(after: from).first { $0.date < end }241            return (day, first.map { WidgetFormat.time(hour: $0.entry.hour, minute: $0.entry.minute) })242        }243    }244    var body: some View {245        VStack(alignment: .leading, spacing: 8) {246            Label("This week", systemImage: "calendar").font(.system(.caption, design: .rounded, weight: .semibold)).foregroundStyle(WidgetTheme.gold)247            HStack(spacing: 4) {248                ForEach(Array(days.enumerated()), id: \.offset) { index, item in249                    VStack(spacing: 6) {250                        Text(item.day.formatted(.dateTime.weekday(.narrow))).font(.system(.caption2, design: .rounded, weight: .bold))251                            .foregroundStyle(index == 0 ? WidgetTheme.sunrise : .secondary)252                        ZStack {253                            RoundedRectangle(cornerRadius: 8, style: .continuous)254                                .fill(item.time == nil ? AnyShapeStyle(.white.opacity(0.06)) : AnyShapeStyle(WidgetTheme.violet.opacity(0.45)))255                            if let time = item.time {256                                Text(time.replacingOccurrences(of: " ", with: "\n")).font(.system(size: 10, weight: .semibold, design: .rounded))257                                    .multilineTextAlignment(.center).minimumScaleFactor(0.6).padding(2)258                            } else {259                                Image(systemName: "minus").font(.caption2).foregroundStyle(.tertiary)260                            }261                        }262                    }263                    .frame(maxWidth: .infinity)264                    .accessibilityElement()265                    .accessibilityLabel("\(item.day.formatted(.dateTime.weekday(.wide))): \(item.time ?? String(localized: "no alarm"))")266                }267            }268        }269        .foregroundStyle(.white)270    }271}272273// MARK: - Quick Alarm274275struct QuickAlarmWidget: Widget {276    var body: some WidgetConfiguration {277        StaticConfiguration(kind: "QuickAlarm", provider: AlarmTimelineProvider()) { entry in278            QuickAlarmView(entry: entry).containerBackground(for: .widget) { WidgetTheme.background }279        }280        .configurationDisplayName("Quick Alarm").description("Open ORIX Alarm straight on a new alarm.")281        .supportedFamilies([.systemSmall, .systemMedium])282    }283}284285struct QuickAlarmView: View {286    @Environment(\.widgetFamily) private var family287    let entry: AlarmEntry288    var body: some View {289        if family == .systemSmall {290            // A small widget is a single tap target.291            VStack(spacing: 8) {292                Image(systemName: "plus").font(.system(size: 30, weight: .bold)).foregroundStyle(WidgetTheme.midnight)293                    .frame(width: 64, height: 64).background(WidgetTheme.sunriseGradient, in: Circle())294                Text("New alarm").font(.system(.subheadline, design: .rounded, weight: .semibold)).foregroundStyle(.white)295            }296            .frame(maxWidth: .infinity, maxHeight: .infinity)297            .widgetURL(URL(string: "orixalarm://new"))298        } else {299            HStack(spacing: 10) {300                tile("New alarm", "plus", "orixalarm://new", prominent: true)301                tile("Alarms", "alarm.fill", "orixalarm://alarms", prominent: false)302                tile("Sleep", "moon.stars.fill", "orixalarm://sleep", prominent: false)303            }304        }305    }306    private func tile(_ title: LocalizedStringKey, _ symbol: String, _ url: String, prominent: Bool) -> some View {307        Link(destination: URL(string: url)!) {308            VStack(spacing: 8) {309                Image(systemName: symbol).font(.title2.weight(.semibold)).foregroundStyle(prominent ? WidgetTheme.midnight : .white)310                    .frame(width: 52, height: 52)311                    .background(prominent ? AnyShapeStyle(WidgetTheme.sunriseGradient) : AnyShapeStyle(.white.opacity(0.12)), in: Circle())312                Text(title).font(.system(.caption, design: .rounded, weight: .semibold)).foregroundStyle(.white)313            }314            .frame(maxWidth: .infinity, maxHeight: .infinity)315        }316    }317}318319// MARK: - Wake Progress320321struct WakeProgressWidget: Widget {322    var body: some WidgetConfiguration {323        StaticConfiguration(kind: "WakeProgress", provider: AlarmTimelineProvider()) { entry in324            WakeProgressView(entry: entry).containerBackground(for: .widget) { WidgetTheme.background }325                .widgetURL(URL(string: "orixalarm://insights"))326        }327        .configurationDisplayName("Wake Progress").description("Days of the last week on which you confirmed your wake-up.")328        .supportedFamilies([.systemSmall, .systemMedium])329    }330}331332struct WakeProgressView: View {333    let entry: AlarmEntry334    private var week: [(day: Date, confirmed: Bool)] {335        let cal = Calendar.current336        let today = cal.startOfDay(for: entry.date)337        let confirmed = Set(entry.snapshot.confirmedDays.map { cal.startOfDay(for: $0) })338        return (0..<7).reversed().compactMap { offset in cal.date(byAdding: .day, value: -offset, to: today).map { ($0, confirmed.contains($0)) } }339    }340    var body: some View {341        let count = week.filter(\.confirmed).count342        VStack(alignment: .leading, spacing: 6) {343            Label("Wake progress", systemImage: "checkmark.seal.fill").font(.system(.caption, design: .rounded, weight: .semibold)).foregroundStyle(WidgetTheme.gold)344            Spacer(minLength: 0)345            HStack(alignment: .firstTextBaseline, spacing: 4) {346                Text("\(count)").font(.system(size: 34, weight: .semibold, design: .rounded)).monospacedDigit()347                Text("of 7 days").font(.system(.caption, design: .rounded)).foregroundStyle(.secondary)348            }349            HStack(spacing: 4) {350                ForEach(Array(week.enumerated()), id: \.offset) { _, item in351                    VStack(spacing: 3) {352                        ZStack {353                            Circle().fill(item.confirmed ? AnyShapeStyle(WidgetTheme.sunriseGradient) : AnyShapeStyle(.white.opacity(0.10)))354                            if item.confirmed { Image(systemName: "checkmark").font(.system(size: 8, weight: .heavy)).foregroundStyle(WidgetTheme.midnight) }355                        }356                        .frame(maxWidth: 22, maxHeight: 22)357                        Text(item.day.formatted(.dateTime.weekday(.narrow))).font(.system(size: 8, weight: .semibold, design: .rounded)).foregroundStyle(.secondary)358                    }359                    .frame(maxWidth: .infinity)360                }361            }362            if entry.snapshot.currentStreak > 1 {363                Text("\(entry.snapshot.currentStreak)-day streak").font(.caption2).foregroundStyle(.secondary)364            }365        }366        .foregroundStyle(.white)367        .accessibilityElement()368        .accessibilityLabel("Wake-up confirmed on \(count) of the last 7 days")369    }370}371
Files main
Menu

Theme