SPB Git

Repository Public License

AlarmComponents.swift 10.5 KB 237 lines swift

1// ORIX Alarm2// File: App/Features/Alarms/AlarmComponents.swift3// Description: Building blocks shared by the alarm list and the Today dashboard: time text, status badge, mission glyphs, template shortcuts.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// Display strings derived from an alarm.11enum AlarmText {12    static func name(_ alarm: AlarmDefinition) -> String { alarm.name.isEmpty ? String(localized: "Alarm") : alarm.name }1314    /// "Today", "Tomorrow" or "Mon 23 Nov".15    static func dayLabel(for date: Date, now: Date, calendar: Calendar) -> String {16        if calendar.isDate(date, inSameDayAs: now) { return String(localized: "Today") }17        if let tomorrow = calendar.date(byAdding: .day, value: 1, to: now), calendar.isDate(date, inSameDayAs: tomorrow) { return String(localized: "Tomorrow") }18        return date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))19    }2021    /// "Snooze 9 min × 3", "Snooze from 6 min, shorter each time × 2", "No snooze".22    static func snooze(_ policy: SnoozePolicy) -> String {23        guard policy.isAllowed else { return String(localized: "No snooze") }24        switch policy.mode {25        case .fixed: return String(localized: "Snooze \(policy.baseMinutes) min × \(policy.maxCount)")26        case .decreasing: return String(localized: "Snooze from \(policy.baseMinutes) min, shorter each time × \(policy.maxCount)")27        }28    }2930    static func time(of date: Date, calendar: Calendar) -> ClockTime {31        let c = calendar.dateComponents([.hour, .minute], from: date)32        return ClockTime(hour: c.hour ?? 0, minute: c.minute ?? 0)33    }34}3536/// Icon and title close together, identical inside and outside a `List` (which otherwise widens the icon column).37struct CompactLabelStyle: LabelStyle {38    var spacing: CGFloat = 639    func makeBody(configuration: Configuration) -> some View {40        HStack(alignment: .firstTextBaseline, spacing: spacing) {41            configuration.icon42            configuration.title43        }44    }45}4647/// Big alarm time: digits plus a small AM/PM marker.48struct AlarmTimeText: View {49    let time: ClockTime50    var size: CGFloat = 5251    var isDimmed = false52    @Environment(AppModel.self) private var model5354    var body: some View {55        let t = Fmt.time(time, use24h: model.settings.use24HourClock)56        HStack(alignment: .firstTextBaseline, spacing: 5) {57            Text(t.digits).font(.clock(size, weight: .regular))58            if !t.period.isEmpty {59                Text(t.period).font(.system(size: size * 0.32, weight: .semibold, design: .rounded)).foregroundStyle(isDimmed ? Theme.textTertiary : Theme.gold)60            }61        }62        .foregroundStyle(isDimmed ? Theme.textTertiary : Theme.textPrimary)63        .lineLimit(1).minimumScaleFactor(0.6)64        .accessibilityElement(children: .ignore)65        .accessibilityLabel(Fmt.timeString(time, use24h: model.settings.use24HourClock))66    }67}6869/// Verified system status of an alarm. A scheduling error always wins: an alarm that is not scheduled never looks fine.70struct AlarmStatusBadge: View {71    let status: SystemAlarmStatus72    var hasError = false7374    var body: some View {75        let shown: SystemAlarmStatus = hasError && status != .mismatched ? .missing : status76        Label(shown.title, systemImage: shown.symbol)77            .labelStyle(CompactLabelStyle())78            .font(.orixCaption)79            .foregroundStyle(shown.tint)80            .padding(.horizontal, 10).frame(minHeight: 26)81            .background(shown.tint.opacity(0.14), in: Capsule())82            .accessibilityElement(children: .ignore)83            .accessibilityLabel(String(localized: "System status: \(shown.title)"))84    }85}8687/// Compact row of mission symbols (one disc per step).88struct MissionGlyphRow: View {89    let missions: [MissionStep]90    var isDimmed = false9192    var body: some View {93        if !missions.isEmpty {94            HStack(spacing: -6) {95                ForEach(missions) { step in96                    Image(systemName: step.kind.symbol)97                        .font(.system(size: 12, weight: .semibold))98                        .foregroundStyle(isDimmed ? Theme.textTertiary : step.kind.tint)99                        .frame(width: 28, height: 28)100                        .background(Theme.deepIndigo, in: Circle())101                        .overlay(Circle().strokeBorder(Color.white.opacity(0.18)))102                }103            }104            .accessibilityElement(children: .ignore)105            .accessibilityLabel(String(localized: "Missions: \(missions.map(\.kind.title).joined(separator: ", "))"))106        }107    }108}109110/// Mission chips with their names, wrapping on several lines.111struct MissionChipFlow: View {112    let missions: [MissionStep]113114    var body: some View {115        AlarmFlowLayout(spacing: 8) {116            ForEach(missions) { step in117                Label(step.kind.title, systemImage: step.kind.symbol)118                    .font(.orixCaption)119                    .foregroundStyle(Theme.textPrimary)120                    .padding(.horizontal, 11).frame(minHeight: 30)121                    .background(step.kind.tint.opacity(0.20), in: Capsule())122                    .overlay(Capsule().strokeBorder(step.kind.tint.opacity(0.45)))123            }124        }125        .accessibilityElement(children: .ignore)126        .accessibilityLabel(String(localized: "Missions: \(missions.map(\.kind.title).joined(separator: ", "))"))127    }128}129130/// Left-aligned wrapping layout.131struct AlarmFlowLayout: Layout {132    var spacing: CGFloat = 8133134    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {135        arrange(width: proposal.width ?? .infinity, subviews: subviews).size136    }137138    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {139        let result = arrange(width: bounds.width, subviews: subviews)140        for (index, origin) in result.origins.enumerated() {141            subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)142        }143    }144145    private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint]) {146        var origins: [CGPoint] = []147        var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0148        for view in subviews {149            let size = view.sizeThatFits(.unspecified)150            if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }151            origins.append(CGPoint(x: x, y: y))152            x += size.width + spacing153            rowHeight = max(rowHeight, size.height)154            maxX = max(maxX, x - spacing)155        }156        return (CGSize(width: maxX, height: y + rowHeight), origins)157    }158}159160/// Scheduling failure of one alarm, with a retry action. Used wherever the alarm is shown.161struct SchedulingErrorNote: View {162    let alarm: AlarmDefinition163    let message: String164    var identifier: String = "alarms.retry"165    @Environment(AppModel.self) private var model166    @State private var isRetrying = false167168    var body: some View {169        VStack(alignment: .leading, spacing: 10) {170            Label {171                Text("Not scheduled: \(message)")172            } icon: {173                Image(systemName: "exclamationmark.triangle.fill")174            }175            .labelStyle(CompactLabelStyle())176            .font(.orixCaption).foregroundStyle(Theme.danger)177            .fixedSize(horizontal: false, vertical: true)178            Button {179                isRetrying = true180                Task {181                    let error = await model.save(alarm)182                    Haptics.play(error == nil ? .alarmSet : .failure)183                    isRetrying = false184                }185            } label: {186                Label(isRetrying ? "Retrying…" : "Retry", systemImage: "arrow.clockwise").labelStyle(CompactLabelStyle())187                    .font(.orixCaption).foregroundStyle(Theme.textPrimary)188                    .padding(.horizontal, 16).frame(minHeight: 44)189                    .background(Theme.danger.opacity(0.22), in: Capsule())190                    .overlay(Capsule().strokeBorder(Theme.danger.opacity(0.5)))191            }192            .buttonStyle(.plain).disabled(isRetrying)193            .accessibilityLabel(String(localized: "Retry scheduling \(AlarmText.name(alarm))"))194            .accessibilityIdentifier(identifier)195        }196        .frame(maxWidth: .infinity, alignment: .leading)197    }198}199200/// Horizontal strip of scenario templates; a tap opens the editor with an alarm built from the template.201struct TemplateShortcuts: View {202    var identifierPrefix = "alarms.template"203    @Environment(AppModel.self) private var model204205    var body: some View {206        ScrollView(.horizontal, showsIndicators: false) {207            HStack(spacing: 12) {208                ForEach(Array(ScenarioTemplates.all.enumerated()), id: \.element.id) { index, template in209                    Button {210                        Haptics.play(.selection)211                        model.editingAlarm = template.makeAlarm(now: model.now())212                    } label: {213                        VStack(alignment: .leading, spacing: 8) {214                            Image(systemName: template.symbol).font(.title3).foregroundStyle(Theme.sunriseGradient)215                                .frame(height: 26, alignment: .leading)216                            Text(template.name).font(.orixHeadline).foregroundStyle(Theme.textPrimary).lineLimit(1)217                            Text(template.tagline).font(.orixCaption).foregroundStyle(Theme.textSecondary)218                                .lineLimit(3).multilineTextAlignment(.leading)219                            Spacer(minLength: 0)220                            Text(Fmt.timeString(template.suggestedTime, use24h: model.settings.use24HourClock) + " · " + Fmt.recurrence(template.suggestedWeekdays))221                                .font(.orixCaption).foregroundStyle(Theme.gold).lineLimit(1).minimumScaleFactor(0.8)222                        }223                        .frame(width: 168, height: 150, alignment: .topLeading)224                        .glassCard(padding: 14, radius: 20)225                    }226                    .buttonStyle(.plain)227                    .accessibilityLabel(String(localized: "Template \(template.name). \(template.tagline)"))228                    .accessibilityHint(Text("Opens the alarm editor"))229                    .accessibilityIdentifier("\(identifierPrefix).\(index)")230                }231            }232            .padding(.horizontal, Theme.spacing)233        }234        .scrollClipDisabled()235    }236}237
Files main
Menu

Theme