Repository Public License
1// ORIX Alarm2// File: App/Features/Studio/StudioView.swift3// Description: Alarm Studio: gallery of scenario templates and the user's saved scenarios (create, edit, duplicate, delete, reorder, apply to alarms).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910extension ScenarioTemplate {11 /// Accent colour of the template in the gallery (from the design palette).12 var accent: Color {13 switch id {14 case "gentle-morning": Theme.sunrise15 case "deep-sleeper": Theme.ember16 case "early-workout": Theme.success17 case "workday-focus": Theme.azure18 case "weekend-wake": Theme.gold19 case "travel-morning": Theme.violet20 case "exam-day": Theme.peach21 default: Theme.azure22 }23 }24}2526extension SavedScenario {27 /// A copy with fresh mission identifiers, ready to be attached to an alarm.28 var detachedScenario: WakeScenario {29 var s = scenario30 s.missions = s.missions.map { var m = $0; m.id = UUID(); return m }31 return s32 }33}3435struct StudioView: View {36 @Environment(AppModel.self) private var model3738 @State private var editing: ScenarioEditorSheet.Target?39 @State private var deleting: SavedScenario?40 @State private var applying: SavedScenario?41 @State private var resultTitle = ""42 @State private var resultMessage: String?43 @State private var dragID: UUID?44 @State private var dragStartIndex = 045 @State private var dragTranslation: CGFloat = 04647 private let rowHeight: CGFloat = 10848 private let rowSpacing: CGFloat = 1049 private var rowStride: CGFloat { rowHeight + rowSpacing }5051 var body: some View {52 NavigationStack {53 ScrollView {54 VStack(alignment: .leading, spacing: 20) {55 Text("Design the whole morning, not only the ring: gentle wake, alarm, missions, snooze rules and confirmation.")56 .font(.orixBody).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)57 .padding(.horizontal, 18)5859 VStack(alignment: .leading, spacing: 12) {60 Overline("Templates").padding(.horizontal, 18)61 ScrollView(.horizontal, showsIndicators: false) {62 HStack(alignment: .top, spacing: 14) {63 ForEach(ScenarioTemplates.all) { template in64 NavigationLink(value: template) { TemplateCard(template: template, use24h: model.settings.use24HourClock) }65 .buttonStyle(.plain)66 .accessibilityIdentifier("studio.template.\(template.id)")67 }68 }69 .scrollTargetLayout()70 .padding(.horizontal, 18)71 }72 .scrollTargetBehavior(.viewAligned)73 }7475 myScenarios.padding(.horizontal, 18)76 }77 .padding(.top, 6)78 // The floating tab bar of iOS 26 covers the bottom of the scroll content.79 .padding(.bottom, 110)80 }81 .navigationTitle("Alarm Studio")82 .navigationDestination(for: ScenarioTemplate.self) { TemplateDetailView(template: $0) }83 .orixScreen(warmth: 0.18)84 }85 .sheet(item: $editing) { target in ScenarioEditorSheet(target: target) }86 .sheet(item: $applying) { scenario in87 ApplyScenarioSheet(scenario: scenario) { title, message in resultTitle = title; resultMessage = message }88 }89 .confirmationDialog("Delete this scenario?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible, presenting: deleting) { scenario in90 Button("Delete “\(scenario.name)”", role: .destructive) {91 withAnimation(.smooth) { model.deleteScenario(scenario.id) }92 Haptics.play(.warning)93 }94 .accessibilityIdentifier("studio.scenario.delete.confirm")95 Button("Keep", role: .cancel) {}96 } message: { _ in Text("Alarms that already use it keep their own copy and are not changed.") }97 .alert(resultTitle, isPresented: Binding(get: { resultMessage != nil }, set: { if !$0 { resultMessage = nil } })) {98 Button("OK") { resultMessage = nil }99 } message: { Text(resultMessage ?? "") }100 }101102 // MARK: My scenarios103 private var myScenarios: some View {104 VStack(alignment: .leading, spacing: 12) {105 HStack {106 Overline("My scenarios")107 Button {108 Haptics.play(.selection)109 var scenario = WakeScenario(); scenario.snooze = model.settings.defaultSnooze110 editing = .init(scenario: SavedScenario(name: "", scenario: scenario, soundID: model.settings.defaultSoundID), isNew: true)111 } label: {112 Label("New", systemImage: "plus").font(.orixCaption).foregroundStyle(Theme.midnight)113 .padding(.horizontal, 14).frame(minHeight: 36).background(Theme.sunriseGradient, in: Capsule())114 .frame(minHeight: 44)115 }116 .buttonStyle(.plain)117 .accessibilityLabel("New scenario")118 .accessibilityIdentifier("studio.newScenario")119 }120 if model.savedScenarios.isEmpty {121 VStack(alignment: .leading, spacing: 8) {122 Label("Nothing saved yet", systemImage: "square.stack.3d.up").font(.orixHeadline)123 Text("Create a scenario here, or use “Save as scenario” in the alarm editor. A saved scenario can be applied to any alarm in one tap.")124 .font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)125 }126 .frame(maxWidth: .infinity, alignment: .leading)127 .glassCard()128 } else {129 VStack(spacing: rowSpacing) {130 ForEach(Array(model.savedScenarios.enumerated()), id: \.element.id) { index, scenario in131 scenarioRow(scenario, index: index)132 .zIndex(dragID == scenario.id ? 1 : 0)133 .offset(y: dragID == scenario.id ? dragTranslation - CGFloat(index - dragStartIndex) * rowStride : 0)134 }135 }136 }137 }138 }139140 private func scenarioRow(_ scenario: SavedScenario, index: Int) -> some View {141 let count = model.savedScenarios.count142 return HStack(spacing: 12) {143 VStack(alignment: .leading, spacing: 8) {144 HStack(spacing: 10) {145 Image(systemName: scenario.symbol).font(.system(size: 16, weight: .semibold)).foregroundStyle(Theme.gold)146 .frame(width: 36, height: 36).background(Theme.gold.opacity(0.16), in: RoundedRectangle(cornerRadius: 11, style: .continuous))147 VStack(alignment: .leading, spacing: 2) {148 Text(scenario.name.isEmpty ? String(localized: "Untitled scenario") : scenario.name).font(.orixHeadline).lineLimit(1)149 Text(scenario.scenario.summaryText).font(.orixCaption).foregroundStyle(Theme.textSecondary).lineLimit(1).minimumScaleFactor(0.8)150 }151 }152 ScenarioMiniTimeline(scenario: scenario.scenario)153 }154 .frame(maxWidth: .infinity, alignment: .leading)155 .contentShape(Rectangle())156 .onTapGesture { Haptics.play(.selection); editing = .init(scenario: scenario, isNew: false) }157 .accessibilityElement(children: .ignore)158 .accessibilityLabel("\(scenario.name.isEmpty ? String(localized: "Untitled scenario") : scenario.name), \(scenario.scenario.summaryText)")159 .accessibilityHint("Opens the scenario editor")160 .accessibilityAddTraits(.isButton)161 .accessibilityAction { editing = .init(scenario: scenario, isNew: false) }162 .accessibilityIdentifier("studio.scenario.\(index)")163164 VStack(spacing: 0) {165 Menu {166 Button("Apply to a new alarm", systemImage: "plus.circle") { applyToNewAlarm(scenario) }167 Button("Apply to an existing alarm…", systemImage: "alarm") { applying = scenario }168 Divider()169 Button("Edit", systemImage: "pencil") { editing = .init(scenario: scenario, isNew: false) }170 Button("Duplicate", systemImage: "plus.square.on.square") { duplicate(scenario) }171 if index > 0 { Button("Move up", systemImage: "arrow.up") { move(index, by: -1) } }172 if index < count - 1 { Button("Move down", systemImage: "arrow.down") { move(index, by: 1) } }173 Divider()174 Button("Delete", systemImage: "trash", role: .destructive) { deleting = scenario }175 } label: {176 Image(systemName: "ellipsis.circle.fill").font(.title3).foregroundStyle(Theme.textSecondary).frame(width: 44, height: 44).contentShape(Rectangle())177 }178 .accessibilityLabel("Actions for \(scenario.name)")179 .accessibilityIdentifier("studio.scenario.\(index).menu")180 if count > 1 {181 Image(systemName: "line.3.horizontal").font(.system(size: 16, weight: .semibold)).foregroundStyle(Theme.textTertiary)182 .frame(width: 44, height: 44).contentShape(Rectangle())183 .gesture(reorderGesture(scenario, index: index))184 .accessibilityHidden(true)185 }186 }187 }188 .padding(.leading, 16).padding(.trailing, 6)189 .frame(height: rowHeight)190 .glassCard(padding: 0, radius: 22)191 .shadow(color: .black.opacity(dragID == scenario.id ? 0.45 : 0), radius: 14, y: 8)192 }193194 private func reorderGesture(_ scenario: SavedScenario, index: Int) -> some Gesture {195 DragGesture(minimumDistance: 1, coordinateSpace: .global)196 .onChanged { value in197 if dragID == nil { dragID = scenario.id; dragStartIndex = index; Haptics.play(.selection) }198 guard dragID == scenario.id, let current = model.savedScenarios.firstIndex(where: { $0.id == scenario.id }) else { return }199 dragTranslation = value.translation.height200 let target = min(max(dragStartIndex + Int((dragTranslation / rowStride).rounded()), 0), model.savedScenarios.count - 1)201 if target != current {202 withAnimation(.snappy(duration: 0.22)) { model.moveScenarios(from: IndexSet(integer: current), to: target > current ? target + 1 : target) }203 Haptics.play(.tick)204 }205 }206 .onEnded { _ in207 if let id = dragID, let current = model.savedScenarios.firstIndex(where: { $0.id == id }) {208 dragTranslation -= CGFloat(current - dragStartIndex) * rowStride209 dragStartIndex = current210 }211 withAnimation(.snappy(duration: 0.22)) { dragTranslation = 0 } completion: { dragID = nil }212 }213 }214215 // MARK: Actions216 private func move(_ index: Int, by delta: Int) {217 let target = index + delta218 guard model.savedScenarios.indices.contains(target) else { return }219 withAnimation(.snappy) { model.moveScenarios(from: IndexSet(integer: index), to: delta > 0 ? target + 1 : target) }220 Haptics.play(.tick)221 }222223 private func duplicate(_ scenario: SavedScenario) {224 let copy = SavedScenario(name: scenario.name.isEmpty ? "" : String(localized: "\(scenario.name) copy"), symbol: scenario.symbol,225 scenario: scenario.detachedScenario, soundID: scenario.soundID)226 withAnimation(.smooth) { model.saveScenario(copy) }227 Haptics.play(.success)228 }229230 private func applyToNewAlarm(_ scenario: SavedScenario) {231 var draft = model.makeDraftAlarm()232 draft.name = scenario.name; draft.scenario = scenario.detachedScenario; draft.soundID = scenario.soundID233 model.editingAlarm = draft234 }235}236237// MARK: - Template card238239struct TemplateCard: View {240 let template: ScenarioTemplate241 var use24h: Bool?242243 var body: some View {244 VStack(alignment: .leading, spacing: 12) {245 HStack(alignment: .top) {246 Image(systemName: template.symbol).font(.system(size: 22, weight: .semibold)).foregroundStyle(Theme.midnight)247 .frame(width: 52, height: 52)248 .background(LinearGradient(colors: [template.accent, template.accent.mix(with: Theme.gold, by: 0.5)], startPoint: .bottomLeading, endPoint: .topTrailing), in: RoundedRectangle(cornerRadius: 16, style: .continuous))249 .shadow(color: template.accent.opacity(0.5), radius: 10, y: 4)250 Spacer()251 VStack(alignment: .trailing, spacing: 2) {252 Text(Fmt.timeString(template.suggestedTime, use24h: use24h)).font(.system(size: 17, weight: .semibold, design: .rounded)).monospacedDigit()253 Text(Fmt.recurrence(template.suggestedWeekdays)).font(.system(size: 11, weight: .medium, design: .rounded)).foregroundStyle(Theme.textSecondary)254 }255 }256 VStack(alignment: .leading, spacing: 4) {257 Text(template.name).font(.orixTitle).lineLimit(1)258 Text(template.tagline).font(.orixCaption).foregroundStyle(Theme.textSecondary).lineLimit(2, reservesSpace: true).multilineTextAlignment(.leading)259 }260 MissionChips(missions: template.scenario.missions)261 .frame(height: 60, alignment: .topLeading)262 Spacer(minLength: 0)263 ScenarioMiniTimeline(scenario: template.scenario)264 }265 .frame(width: 262, height: 268, alignment: .topLeading)266 .glassCard(padding: 18, radius: 26, tint: template.accent)267 .contentShape(RoundedRectangle(cornerRadius: 26, style: .continuous))268 .accessibilityElement(children: .ignore)269 .accessibilityLabel("\(template.name). \(template.tagline) \(template.scenario.summaryText)")270 .accessibilityAddTraits(.isButton)271 }272}273274/// Small non-interactive chips naming the missions of a scenario.275struct MissionChips: View {276 let missions: [MissionStep]277278 var body: some View {279 FlowLayout(spacing: 6) {280 if missions.isEmpty {281 chip(String(localized: "No mission yet"), symbol: "puzzlepiece.extension", tint: Theme.textSecondary)282 }283 ForEach(missions) { step in chip(step.kind.title, symbol: step.kind.symbol, tint: step.kind.tint) }284 }285 }286287 private func chip(_ title: String, symbol: String, tint: Color) -> some View {288 HStack(spacing: 4) {289 Image(systemName: symbol).font(.system(size: 9, weight: .bold)).foregroundStyle(tint)290 Text(title).font(.system(size: 11, weight: .semibold, design: .rounded)).lineLimit(1)291 }292 .padding(.horizontal, 8).frame(height: 26)293 .background(Theme.midnight.opacity(0.35), in: Capsule())294 .overlay(Capsule().strokeBorder(tint.opacity(0.4)))295 }296}297298// MARK: - Template detail299300struct TemplateDetailView: View {301 let template: ScenarioTemplate302 @Environment(AppModel.self) private var model303 @State private var previewRun: MissionRun?304305 var body: some View {306 ScrollView {307 VStack(alignment: .leading, spacing: 18) {308 VStack(alignment: .leading, spacing: 14) {309 Image(systemName: template.symbol).font(.system(size: 30, weight: .semibold)).foregroundStyle(Theme.midnight)310 .frame(width: 68, height: 68)311 .background(LinearGradient(colors: [template.accent, template.accent.mix(with: Theme.gold, by: 0.5)], startPoint: .bottomLeading, endPoint: .topTrailing), in: RoundedRectangle(cornerRadius: 20, style: .continuous))312 .shadow(color: template.accent.opacity(0.55), radius: 14, y: 6)313 .accessibilityHidden(true)314 Text(template.name).font(.system(size: 32, weight: .bold, design: .rounded))315 Text(template.tagline).font(.orixBody).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)316 FlowLayout(spacing: 8) {317 fact("clock.fill", Fmt.timeString(template.suggestedTime, use24h: model.settings.use24HourClock))318 fact("repeat", Fmt.recurrence(template.suggestedWeekdays))319 fact("speaker.wave.2.fill", SoundCatalog.alarmSound(template.soundID).title)320 }321 }322323 VStack(spacing: 10) {324 Button {325 Haptics.play(.selection)326 model.editingAlarm = template.makeAlarm(now: model.now())327 } label: { Label("Create alarm from this template", systemImage: "plus") }328 .buttonStyle(PrimaryButtonStyle())329 .accessibilityIdentifier("studio.createFromTemplate")330 if !template.scenario.missions.isEmpty {331 Button {332 previewRun = model.makePreviewRun(template.scenario.missions, name: template.name)333 } label: { Label("Preview missions", systemImage: "play.fill") }334 .buttonStyle(SecondaryButtonStyle())335 .accessibilityIdentifier("studio.previewMissions")336 }337 Text("Time, days and every setting stay editable before you save the alarm.")338 .font(.orixCaption).foregroundStyle(Theme.textTertiary)339 }340341 EditorCard(title: "The morning, step by step", symbol: "timeline.selection", tint: template.accent) {342 ScenarioTimelineView(scenario: template.scenario, soundID: template.soundID, time: template.suggestedTime, use24h: model.settings.use24HourClock)343 }344 }345 .padding(.horizontal, 18).padding(.top, 8)346 .padding(.bottom, 110)347 }348 .navigationBarTitleDisplayMode(.inline)349 .orixScreen(warmth: 0.3)350 .fullScreenCover(item: $previewRun) { run in MissionRunnerView(run: run, onClose: { previewRun = nil }) }351 }352353 private func fact(_ symbol: String, _ text: String) -> some View {354 Label(text, systemImage: symbol).font(.orixCaption)355 .padding(.horizontal, 12).frame(minHeight: 32)356 .background(Theme.surfaceRaised, in: Capsule()).overlay(Capsule().strokeBorder(Theme.hairline))357 }358}359