SPB Git

Repository Public License

IntensityCurveViews.swift 9.6 KB 208 lines swift

1// ORIX Alarm2// File: App/Features/Editor/IntensityCurveViews.swift3// Description: Live plot of a progressive-wake intensity curve, curve picker and the draggable five-point custom curve editor.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910extension IntensityCurve {11    static let customPointCount = 51213    var title: String {14        switch self {15        case .linear: String(localized: "Linear")16        case .exponential: String(localized: "Exponential")17        case .smoothstep: String(localized: "Smooth")18        case .multiStage: String(localized: "Multi-stage")19        case .custom: String(localized: "Custom")20        }21    }22    var symbol: String {23        switch self {24        case .linear: "line.diagonal"25        case .exponential: "arrow.up.right"26        case .smoothstep: "point.topleft.down.to.point.bottomright.curvepath"27        case .multiStage: "stairs"28        case .custom: "hand.draw"29        }30    }31    var explanation: String {32        switch self {33        case .linear: String(localized: "Rises at a constant rate.")34        case .exponential: String(localized: "Stays very low for a long time, then rises quickly at the end.")35        case .smoothstep: String(localized: "Eases in gently, rises, then eases out before the alarm.")36        case .multiStage: String(localized: "Three plateaus: 20 %, 55 %, then full intensity.")37        case .custom: String(localized: "Drag the five points to shape your own rise.")38        }39    }40    /// Five control points sampled from this curve, used when switching to the custom editor.41    var sampledPoints: [Double] {42        if case .custom(let p) = self, p.count == Self.customPointCount { return p }43        return (0..<Self.customPointCount).map { value(at: Double($0) / Double(Self.customPointCount - 1)) }44    }4546    /// Path of the curve inside `rect` (origin at the bottom-left), optionally closed down to the baseline.47    func path(in rect: CGRect, closed: Bool = false, samples: Int = 64) -> Path {48        var path = Path()49        for i in 0...samples {50            let t = Double(i) / Double(samples)51            let point = CGPoint(x: rect.minX + rect.width * t, y: rect.maxY - rect.height * value(at: t))52            if i == 0 { path.move(to: point) } else { path.addLine(to: point) }53        }54        if closed {55            path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))56            path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))57            path.closeSubpath()58        }59        return path60    }61}6263/// Small non-interactive drawing of a curve (timeline, chips, gallery).64struct CurveSparkline: View {65    let curve: IntensityCurve66    var lineWidth: CGFloat = 26768    var body: some View {69        GeometryReader { geo in70            let rect = CGRect(origin: .zero, size: geo.size).insetBy(dx: lineWidth / 2, dy: lineWidth / 2)71            ZStack {72                curve.path(in: rect, closed: true)73                    .fill(LinearGradient(colors: [Theme.sunrise.opacity(0.45), Theme.ember.opacity(0.05)], startPoint: .top, endPoint: .bottom))74                curve.path(in: rect)75                    .stroke(LinearGradient(colors: [Theme.violet, Theme.ember, Theme.gold], startPoint: .leading, endPoint: .trailing),76                            style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round))77            }78        }79        .accessibilityHidden(true)80    }81}8283/// Plot with axes. When the curve is `.custom`, the five control points can be dragged.84struct IntensityCurveEditor: View {85    @Binding var curve: IntensityCurve86    let leadMinutes: Int87    @State private var activePoint: Int?8889    private var customPoints: [Double]? {90        if case .custom = curve { return curve.sampledPoints }91        return nil92    }9394    var body: some View {95        VStack(alignment: .leading, spacing: 12) {96            ScrollView(.horizontal, showsIndicators: false) {97                HStack(spacing: 8) {98                    ForEach(options, id: \.kindName) { option in99                        Chip(title: option.title, symbol: option.symbol, isSelected: option.kindName == curve.kindName) {100                            guard option.kindName != curve.kindName else { return }101                            Haptics.play(.selection)102                            withAnimation(.smooth(duration: 0.35)) {103                                if case .custom = option { curve = .custom(curve.sampledPoints) } else { curve = option }104                            }105                        }106                        .accessibilityIdentifier("editor.curve.\(option.kindName)")107                    }108                }109                .padding(.horizontal, 18)110            }111            .padding(.horizontal, -18)112113            plot.frame(height: 150)114115            HStack {116                Text("−\(leadMinutes) min")117                Spacer()118                Text("Intensity of light and sound").foregroundStyle(Theme.textTertiary)119                Spacer()120                Text("Alarm")121            }122            .font(.system(size: 11, weight: .semibold, design: .rounded)).monospacedDigit().foregroundStyle(Theme.textSecondary)123            .accessibilityHidden(true)124125            Text(curve.explanation).font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)126        }127    }128129    private var options: [IntensityCurve] { [.linear, .exponential, .smoothstep, .multiStage, .custom([])] }130131    private var plot: some View {132        GeometryReader { geo in133            let rect = CGRect(origin: .zero, size: geo.size).insetBy(dx: 14, dy: 12)134            ZStack {135                RoundedRectangle(cornerRadius: 16, style: .continuous).fill(Theme.midnight.opacity(0.45))136                RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Theme.hairline)137                // Grid: 0 / 50 / 100 %.138                Path { p in139                    for fraction in [0.0, 0.5, 1.0] {140                        let y = rect.maxY - rect.height * fraction141                        p.move(to: CGPoint(x: rect.minX, y: y)); p.addLine(to: CGPoint(x: rect.maxX, y: y))142                    }143                }144                .stroke(Color.white.opacity(0.10), style: StrokeStyle(lineWidth: 1, dash: [3, 4]))145                curve.path(in: rect, closed: true)146                    .fill(LinearGradient(colors: [Theme.sunrise.opacity(0.50), Theme.ember.opacity(0.04)], startPoint: .top, endPoint: .bottom))147                curve.path(in: rect)148                    .stroke(LinearGradient(colors: [Theme.violet, Theme.ember, Theme.gold], startPoint: .leading, endPoint: .trailing),149                            style: StrokeStyle(lineWidth: 3, lineCap: .round, lineJoin: .round))150                Text("100 %").font(.system(size: 9, weight: .bold, design: .rounded)).foregroundStyle(Theme.textTertiary)151                    .position(x: rect.minX + 16, y: rect.minY + 8)152                if let points = customPoints {153                    ForEach(points.indices, id: \.self) { i in154                        Circle().fill(.white)155                            .overlay(Circle().strokeBorder(Theme.sunrise, lineWidth: 3))156                            .frame(width: 22, height: 22)157                            .scaleEffect(activePoint == i ? 1.3 : 1)158                            .shadow(color: Theme.sunrise.opacity(0.7), radius: activePoint == i ? 10 : 4)159                            .position(x: rect.minX + rect.width * Double(i) / Double(points.count - 1), y: rect.maxY - rect.height * points[i])160                    }161                }162            }163            .contentShape(Rectangle())164            .gesture(customPoints == nil ? nil : DragGesture(minimumDistance: 0)165                .onChanged { value in166                    guard var points = customPoints else { return }167                    if activePoint == nil {168                        let fraction = (value.startLocation.x - rect.minX) / rect.width169                        activePoint = min(max(Int((fraction * Double(points.count - 1)).rounded()), 0), points.count - 1)170                        Haptics.play(.selection)171                    }172                    guard let i = activePoint else { return }173                    let raw = (rect.maxY - value.location.y) / rect.height174                    let snapped = (min(max(raw, 0), 1) * 20).rounded() / 20175                    if snapped != points[i] {176                        points[i] = snapped177                        curve = .custom(points)178                        Haptics.play(.tick)179                    }180                }181                .onEnded { _ in activePoint = nil })182            .animation(.snappy(duration: 0.15), value: activePoint)183        }184        .accessibilityElement(children: .ignore)185        .accessibilityLabel("Intensity curve, \(curve.title)")186        .accessibilityValue(curve.explanation)187        .accessibilityChildren {188            if let points = customPoints {189                ForEach(points.indices, id: \.self) { i in190                    Rectangle()191                        .accessibilityLabel("Control point \(i + 1) of \(points.count)")192                        .accessibilityValue("\(Int((points[i] * 100).rounded())) percent")193                        .accessibilityAdjustableAction { direction in194                            var next = points195                            switch direction {196                            case .increment: next[i] = min(1, next[i] + 0.1)197                            case .decrement: next[i] = max(0, next[i] - 0.1)198                            @unknown default: break199                            }200                            curve = .custom(next)201                        }202                }203            }204        }205        .accessibilityIdentifier("editor.curvePlot")206    }207}208
Files main
Menu

Theme