PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasOnboarding.swift
| 1 | import SwiftUI |
| 2 | import StoreKit |
| 3 | #if os(macOS) |
| 4 | import AppKit |
| 5 | #else |
| 6 | import UIKit |
| 7 | #endif |
| 8 | |
| 9 | extension Notification.Name { |
| 10 | static let pulseCanvasOnboarding = Notification.Name("PulseCanvas.showOnboarding") |
| 11 | } |
| 12 | |
| 13 | #if os(visionOS) |
| 14 | private struct PulseCanvasOnboardingActiveKey: EnvironmentKey { |
| 15 | static let defaultValue = false |
| 16 | } |
| 17 | |
| 18 | extension EnvironmentValues { |
| 19 | var pulseCanvasOnboardingActive: Bool { |
| 20 | get { self[PulseCanvasOnboardingActiveKey.self] } |
| 21 | set { self[PulseCanvasOnboardingActiveKey.self] = newValue } |
| 22 | } |
| 23 | } |
| 24 | #endif |
| 25 | |
| 26 | enum PulseCanvasOnboarding { |
| 27 | static let completedKey = "PulseCanvas.onboarding.completed.v1" |
| 28 | static var initialStep: Int { |
| 29 | #if DEBUG |
| 30 | let args = ProcessInfo.processInfo.arguments |
| 31 | if let index = args.firstIndex(of: "-PCOnboardingStep"), args.indices.contains(index + 1) { |
| 32 | return min(PulseCanvasOnboardingView.lastStep, max(0, Int(args[index + 1]) ?? 0)) |
| 33 | } |
| 34 | #endif |
| 35 | return 0 |
| 36 | } |
| 37 | static var forced: Bool { |
| 38 | #if DEBUG |
| 39 | return ProcessInfo.processInfo.arguments.contains("-PCOnboardingQA") |
| 40 | #else |
| 41 | return false |
| 42 | #endif |
| 43 | } |
| 44 | static var fixture: Bool { |
| 45 | #if DEBUG |
| 46 | let args = ProcessInfo.processInfo.arguments |
| 47 | return !forced && (args.contains("-PCMobileQA") || args.contains("-PCUITesting")) |
| 48 | #else |
| 49 | return false |
| 50 | #endif |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Owns the entire root surface; onboarding is never presented in a sheet or popover. |
| 55 | struct PulseCanvasOnboardingPresentation: ViewModifier { |
| 56 | var onReplay: () -> Void = {} |
| 57 | @AppStorage(PulseCanvasOnboarding.completedKey) private var completed = false |
| 58 | @State private var replay = false |
| 59 | @State private var presentationID = UUID() |
| 60 | @State private var force = PulseCanvasOnboarding.forced |
| 61 | private var showingOnboarding: Bool { |
| 62 | replay || force || (!completed && !PulseCanvasOnboarding.fixture) |
| 63 | } |
| 64 | func body(content: Content) -> some View { |
| 65 | Group { |
| 66 | #if os(visionOS) |
| 67 | // Keep the established spatial editor attached to its window during |
| 68 | // replay. Removing and reinserting it can leave its controls unhittable. |
| 69 | ZStack { |
| 70 | if (completed || PulseCanvasOnboarding.fixture) && !force { |
| 71 | content.opacity(showingOnboarding ? 0 : 1) |
| 72 | .environment(\.pulseCanvasOnboardingActive, showingOnboarding) |
| 73 | .allowsHitTesting(!showingOnboarding) |
| 74 | .accessibilityElement(children: showingOnboarding ? .ignore : .contain) |
| 75 | .accessibilityHidden(showingOnboarding) |
| 76 | } |
| 77 | if showingOnboarding { onboarding } |
| 78 | } |
| 79 | #else |
| 80 | if showingOnboarding { onboarding } else { content } |
| 81 | #endif |
| 82 | } |
| 83 | .onReceive(NotificationCenter.default.publisher(for: .pulseCanvasOnboarding)) { _ in |
| 84 | onReplay() |
| 85 | presentationID = UUID() |
| 86 | replay = true |
| 87 | } |
| 88 | } |
| 89 | private var onboarding: some View { |
| 90 | PulseCanvasOnboardingView(initialStep: replay ? 0 : PulseCanvasOnboarding.initialStep) { |
| 91 | completed = true |
| 92 | replay = false |
| 93 | force = false |
| 94 | }.id(presentationID) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | struct PulseCanvasOnboardingView: View { |
| 99 | let finish: () -> Void |
| 100 | @State private var step: Int |
| 101 | init(initialStep: Int = PulseCanvasOnboarding.initialStep, finish: @escaping () -> Void) { |
| 102 | self.finish = finish |
| 103 | _step = State(initialValue: min(Self.lastStep, max(0, initialStep))) |
| 104 | } |
| 105 | static let pageCount = 4 |
| 106 | static let lastStep = pageCount - 1 |
| 107 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 108 | @ScaledMetric(relativeTo: .largeTitle) private var titleSize = 42 |
| 109 | @ScaledMetric(relativeTo: .largeTitle) private var tabletTitleSize = 56 |
| 110 | @ScaledMetric(relativeTo: .body) private var tabletBodySize = 24 |
| 111 | @ScaledMetric(relativeTo: .headline) private var tabletLessonTitleSize = 23 |
| 112 | @ScaledMetric(relativeTo: .subheadline) private var tabletDetailSize = 20 |
| 113 | @ScaledMetric(relativeTo: .footnote) private var tabletNoteSize = 18 |
| 114 | private let accent = Color(red: 0.95, green: 0.68, blue: 0.55) |
| 115 | private let background = Color(red: 50.0 / 255, green: 44.0 / 255, blue: 55.0 / 255) |
| 116 | private let ink = Color.white |
| 117 | private var names: [String] { |
| 118 | [String(localized: "Welcome"), String(localized: "Visualizers"), String(localized: "Studio"), |
| 119 | String(localized: "Play & share")] |
| 120 | } |
| 121 | private let assets = ["welcome", "visuals", "studio", "share"] |
| 122 | #if os(iOS) |
| 123 | private let locksTextPositions = true |
| 124 | #else |
| 125 | private let locksTextPositions = false |
| 126 | #endif |
| 127 | private func title(for step: Int) -> String { |
| 128 | switch step { |
| 129 | case 0: return String(localized: "Your music.\nYour visual world.") |
| 130 | case 1: return String(localized: "Find a look.\nMake it yours.") |
| 131 | case 2: |
| 132 | return String(localized: "Give your song\na visual story.") |
| 133 | default: |
| 134 | #if os(visionOS) |
| 135 | return String(localized: "Make room\nfor your music.") |
| 136 | #else |
| 137 | return String(localized: "From your canvas\nto any screen.") |
| 138 | #endif |
| 139 | } |
| 140 | } |
| 141 | private func subtitle(for step: Int) -> String { |
| 142 | switch step { |
| 143 | case 0: return String(localized: "Turn sound into moving art with PulseCanvas Studio. A few basics, then the canvas is yours.") |
| 144 | case 1: return String(localized: "Explore the visualizer library, save your favorites, and shape the colors and motion to suit your music.") |
| 145 | case 2: |
| 146 | return String(localized: "Choose music or import a soundtrack. Studio finds the beat so your scenes can change with the song.") |
| 147 | default: |
| 148 | #if os(visionOS) |
| 149 | return String(localized: "Open the immersive screen to surround yourself with the visuals, or export your Studio project as an MP4.") |
| 150 | #else |
| 151 | return String(localized: "Enjoy your visuals full screen, or export an MP4 with your soundtrack, ready to save and share.") |
| 152 | #endif |
| 153 | } |
| 154 | } |
| 155 | private func lessons(for step: Int) -> [(String, String, String)] { |
| 156 | switch step { |
| 157 | case 0: return [("waveform", String(localized: "Start with a song"), String(localized: "Try the included music or discover a station in Radio.")), |
| 158 | ("sparkles", String(localized: "Watch the music move"), String(localized: "Visuals respond to the rhythm as you listen."))] |
| 159 | case 1: return [("square.grid.2x2", String(localized: "Explore the library"), String(localized: "Browse categories and heart the looks you love.")), |
| 160 | ("slider.horizontal.3", String(localized: "Shape your style"), String(localized: "Adjust palettes, motion, and Chaos for a different feel."))] |
| 161 | case 2: |
| 162 | return [("rectangle.stack", String(localized: "Build scenes in Studio"), String(localized: "Choose a visualizer and a bar length for each scene.")), |
| 163 | ("shuffle", String(localized: "Try a new sequence"), String(localized: "Randomize the timeline, then fine-tune your favorite moments."))] |
| 164 | default: |
| 165 | #if os(visionOS) |
| 166 | return [("vision.pro", String(localized: "Open the immersive screen"), String(localized: "Choose Hide room for full immersion before entering.")), |
| 167 | ("film", String(localized: "Save your creation"), String(localized: "Export MP4 renders the Studio timeline with your soundtrack."))] |
| 168 | #elseif os(macOS) |
| 169 | return [("arrow.up.left.and.arrow.down.right", String(localized: "Press Present"), String(localized: "Space pauses playback. Escape returns to the editor.")), |
| 170 | ("film", String(localized: "Save a video"), String(localized: "In Project settings, choose a canvas and quality. Then choose Save video."))] |
| 171 | #else |
| 172 | return [("arrow.up.left.and.arrow.down.right", String(localized: "Open full-screen viewing"), String(localized: "Tap to reveal the controls while you listen.")), |
| 173 | ("film", String(localized: "Export your video"), String(localized: "Open Project actions → Export MP4. Render, then Save video to Files."))] |
| 174 | #endif |
| 175 | } |
| 176 | } |
| 177 | var body: some View { |
| 178 | GeometryReader { geometry in |
| 179 | let wide = geometry.size.width >= 760 || geometry.size.width > geometry.size.height |
| 180 | let short = geometry.size.height < 500 && wide |
| 181 | #if os(iOS) |
| 182 | let largeTablet = UIDevice.current.userInterfaceIdiom == .pad && min(geometry.size.width, geometry.size.height) >= 900 |
| 183 | #else |
| 184 | let largeTablet = false |
| 185 | #endif |
| 186 | VStack(spacing: 0) { |
| 187 | header(wide: wide).zIndex(2) |
| 188 | GeometryReader { pageGeometry in |
| 189 | OnboardingFittedContent(alignment: locksTextPositions && !largeTablet ? .topLeading : .center) { |
| 190 | page(wide: wide, size: pageGeometry.size, compact: pageGeometry.size.height < 480, largeTablet: largeTablet) |
| 191 | } |
| 192 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 193 | .contentShape(Rectangle()) |
| 194 | .clipped() |
| 195 | }.id(step) |
| 196 | footer(wide: wide, short: short).zIndex(2) |
| 197 | } |
| 198 | .padding(.horizontal, wide ? 48 : 24) |
| 199 | .padding(.top, 16) |
| 200 | .padding(.bottom, 18) |
| 201 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 202 | .background(background.ignoresSafeArea()) |
| 203 | .contentShape(Rectangle()) |
| 204 | // A recognized drag takes precedence over button taps so swiping |
| 205 | // across Continue cannot also activate it. Ordinary taps still work. |
| 206 | .highPriorityGesture(DragGesture(minimumDistance: 20).onEnded { value in |
| 207 | let distance = value.translation |
| 208 | #if os(iOS) |
| 209 | // Accept a deliberate short flick as well as a longer drag. |
| 210 | // Require real horizontal travel before consulting momentum. |
| 211 | let projected = value.predictedEndTranslation |
| 212 | guard abs(distance.width) >= 24, |
| 213 | abs(distance.width) > abs(distance.height) * 1.25, |
| 214 | abs(distance.width) >= 44 || (distance.width * projected.width > 0 && abs(projected.width) >= 80) else { return } |
| 215 | #else |
| 216 | guard abs(distance.width) >= 44, |
| 217 | abs(distance.width) > abs(distance.height) * 1.25 else { return } |
| 218 | #endif |
| 219 | changeStep(step + (distance.width < 0 ? 1 : -1)) |
| 220 | }) |
| 221 | #if os(macOS) |
| 222 | .background(OnboardingTrackpadNavigation { direction in |
| 223 | changeStep(step + direction) |
| 224 | }) |
| 225 | #endif |
| 226 | } |
| 227 | .dynamicTypeSize(.xSmall ... .xxxLarge) |
| 228 | .foregroundStyle(ink).tint(accent).preferredColorScheme(.dark).environment(\.colorScheme, .dark) |
| 229 | #if DEBUG |
| 230 | .task(id: step) { |
| 231 | // A capture waits for the actual page to appear before taking its screenshot. |
| 232 | guard PulseCanvasOnboarding.forced else { return } |
| 233 | try? await Task.sleep(for: .seconds(1)) |
| 234 | guard !Task.isCancelled else { return } |
| 235 | let file = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("onboarding-capture-ready.txt") |
| 236 | try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 237 | try? String(step).write(to: file, atomically: true, encoding: .utf8) |
| 238 | } |
| 239 | #endif |
| 240 | } |
| 241 | @ViewBuilder private func page(wide: Bool, size: CGSize, compact: Bool, largeTablet: Bool) -> some View { |
| 242 | if wide { |
| 243 | HStack(alignment: locksTextPositions && !largeTablet ? .top : .center, spacing: compact ? 28 : 54) { |
| 244 | illustration |
| 245 | .frame(width: min(size.width * 0.44, largeTablet ? 620 : 510), |
| 246 | height: min(size.height * (compact ? 0.75 : 0.94), largeTablet ? 620 : 510)) |
| 247 | copy(wide: true, compact: compact, largeTablet: largeTablet).frame(maxWidth: largeTablet ? 600 : 490) |
| 248 | }.frame(maxWidth: largeTablet ? 1280 : 1120) |
| 249 | .accessibilityElement(children: .contain) |
| 250 | .accessibilityIdentifier("onboardingContent") |
| 251 | } else { |
| 252 | VStack(alignment: .leading, spacing: compact ? 12 : 20) { |
| 253 | illustration.frame(height: min(compact ? 110 : 220, size.height * (compact ? 0.22 : 0.32))) |
| 254 | .frame(maxWidth: .infinity) |
| 255 | copy(wide: false, compact: compact, largeTablet: false) |
| 256 | }.frame(maxWidth: 500) |
| 257 | } |
| 258 | } |
| 259 | private var startTitle: String { |
| 260 | String(localized: "Start creating") |
| 261 | } |
| 262 | private func header(wide: Bool) -> some View { |
| 263 | HStack(spacing: 10) { |
| 264 | if let logo = onboardingImage(named: "logo") { |
| 265 | logo.resizable().interpolation(.high).scaledToFit() |
| 266 | .frame(width: 36, height: 36) |
| 267 | .clipShape(RoundedRectangle(cornerRadius: 8)).accessibilityHidden(true) |
| 268 | } |
| 269 | VStack(alignment: .leading, spacing: 1) { |
| 270 | Text("PulseCanvas").font(.system(size: 19, weight: .semibold, design: .rounded)).lineLimit(1).minimumScaleFactor(0.8) |
| 271 | Text("Studio").font(.caption).foregroundStyle(ink.opacity(0.92)) |
| 272 | } |
| 273 | Spacer() |
| 274 | Button("Skip onboarding", action: finish).lineLimit(1).minimumScaleFactor(0.8).buttonStyle(OnboardingButtonStyle(primary: false, compact: true)) |
| 275 | .accessibilityIdentifier("onboardingSkip") |
| 276 | }.frame(minHeight: 48) |
| 277 | } |
| 278 | private var illustration: some View { |
| 279 | Group { |
| 280 | if let image = onboardingImage(named: assets[step]) { |
| 281 | image.resizable().interpolation(.high).scaledToFit() |
| 282 | } |
| 283 | } |
| 284 | .accessibilityHidden(true) |
| 285 | } |
| 286 | private func onboardingImage(named name: String) -> Image? { |
| 287 | let directories = ["Resources/Onboarding", "Onboarding"] |
| 288 | guard let url = directories.compactMap({ Bundle.module.url(forResource: name, withExtension: "png", subdirectory: $0) }).first else { return nil } |
| 289 | #if os(macOS) |
| 290 | guard let image = NSImage(contentsOf: url) else { return nil } |
| 291 | return Image(nsImage: image) |
| 292 | #else |
| 293 | guard let image = UIImage(contentsOfFile: url.path) else { return nil } |
| 294 | return Image(uiImage: image) |
| 295 | #endif |
| 296 | } |
| 297 | private func copy(wide: Bool, compact: Bool, largeTablet: Bool) -> some View { |
| 298 | VStack(alignment: .leading, spacing: compact ? 12 : 20) { |
| 299 | copySection { index in |
| 300 | Text(title(for: index)).font(.system(size: largeTablet ? tabletTitleSize : min(titleSize, wide ? 52 : 38) * (compact ? 0.88 : 1), weight: .bold, design: .rounded)) |
| 301 | .tracking(-1.2).fixedSize(horizontal: false, vertical: true) |
| 302 | .accessibilityIdentifier("onboardingTitle").accessibilityAddTraits(.isHeader) |
| 303 | } |
| 304 | copySection { index in |
| 305 | Text(subtitle(for: index)).font(largeTablet ? .system(size: tabletBodySize) : (compact ? .callout : .body)).foregroundStyle(ink.opacity(0.92)) |
| 306 | .fixedSize(horizontal: false, vertical: true).lineSpacing(3) |
| 307 | .accessibilityIdentifier("onboardingSubtitle") |
| 308 | } |
| 309 | #if os(iOS) |
| 310 | VStack(alignment: .leading, spacing: compact ? 12 : 18) { |
| 311 | ForEach(0..<2) { row in |
| 312 | copySection { index in |
| 313 | lessonRow(lessons(for: index)[row], compact: compact, largeTablet: largeTablet) |
| 314 | }.accessibilityIdentifier("onboardingLesson\(row)") |
| 315 | } |
| 316 | } |
| 317 | #else |
| 318 | copySection { index in |
| 319 | details(for: index, compact: compact) |
| 320 | } |
| 321 | #endif |
| 322 | }.frame(maxWidth: locksTextPositions ? .infinity : nil, alignment: .topLeading) |
| 323 | } |
| 324 | @ViewBuilder private func copySection<Content: View>(@ViewBuilder content: @escaping (Int) -> Content) -> some View { |
| 325 | #if os(iOS) |
| 326 | // Reserve the largest section across all slides in this layout pass. |
| 327 | // Titles, descriptions and details therefore keep the same top/left |
| 328 | // origins, including after rotation and Dynamic Type changes. |
| 329 | ZStack(alignment: .topLeading) { |
| 330 | ZStack(alignment: .topLeading) { |
| 331 | ForEach(0..<Self.pageCount, id: \.self) { index in |
| 332 | content(index).hidden() |
| 333 | } |
| 334 | }.accessibilityElement(children: .ignore).accessibilityHidden(true) |
| 335 | content(step) |
| 336 | }.frame(maxWidth: .infinity, alignment: .topLeading) |
| 337 | #else |
| 338 | content(step) |
| 339 | #endif |
| 340 | } |
| 341 | @ViewBuilder private func details(for step: Int, compact: Bool) -> some View { |
| 342 | VStack(alignment: .leading, spacing: compact ? 12 : 18) { |
| 343 | ForEach(lessons(for: step), id: \.0) { lesson in |
| 344 | lessonRow(lesson, compact: compact) |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | private func lessonRow(_ lesson: (String, String, String), compact: Bool, largeTablet: Bool = false) -> some View { |
| 349 | HStack(alignment: .onboardingLessonTitle, spacing: 14) { |
| 350 | Image(systemName: lesson.0).font(.system(size: largeTablet ? 28 : 22)).foregroundStyle(accent) |
| 351 | .frame(width: largeTablet ? 40 : 28).accessibilityHidden(true) |
| 352 | VStack(alignment: .leading, spacing: 5) { |
| 353 | Text(lesson.1).font(largeTablet ? .system(size: tabletLessonTitleSize, weight: .semibold) : (compact ? .subheadline.weight(.semibold) : .headline)) |
| 354 | .alignmentGuide(.onboardingLessonTitle) { $0[VerticalAlignment.center] } |
| 355 | Text(lesson.2).font(largeTablet ? .system(size: tabletDetailSize) : (compact ? .caption : .subheadline)).foregroundStyle(ink.opacity(0.92)) |
| 356 | .fixedSize(horizontal: false, vertical: true) |
| 357 | } |
| 358 | }.accessibilityElement(children: .combine) |
| 359 | } |
| 360 | @ViewBuilder private func footer(wide: Bool, short: Bool) -> some View { |
| 361 | if short { |
| 362 | HStack(spacing: 24) { |
| 363 | progress(compact: true) |
| 364 | navigation.frame(maxWidth: 360) |
| 365 | }.frame(maxWidth: .infinity).padding(.top, 10) |
| 366 | } else { |
| 367 | VStack(spacing: 18) { |
| 368 | progress(compact: false) |
| 369 | navigation.frame(maxWidth: 420) |
| 370 | }.frame(maxWidth: .infinity).padding(.top, 14) |
| 371 | } |
| 372 | } |
| 373 | private func progress(compact: Bool) -> some View { |
| 374 | HStack(spacing: 7) { |
| 375 | if !compact { |
| 376 | ForEach(0..<Self.pageCount, id: \.self) { index in |
| 377 | Capsule().fill(index == step ? accent : ink.opacity(0.18)) |
| 378 | .frame(width: index == step ? 26 : 7, height: 6) |
| 379 | } |
| 380 | } |
| 381 | Text("\(step + 1) of \(Self.pageCount) · \(names[step])").font(.caption) |
| 382 | .foregroundStyle(ink.opacity(0.92)).padding(.leading, 7) |
| 383 | } |
| 384 | .accessibilityElement(children: .ignore) |
| 385 | .accessibilityLabel("Step \(step + 1) of \(Self.pageCount), \(names[step])") |
| 386 | .accessibilityIdentifier("onboardingProgress") |
| 387 | .accessibilityHint("Adjust to move between onboarding pages") |
| 388 | .accessibilityAdjustableAction { direction in |
| 389 | switch direction { |
| 390 | case .increment: changeStep(step + 1) |
| 391 | case .decrement: changeStep(step - 1) |
| 392 | @unknown default: break |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | private var navigation: some View { |
| 397 | HStack(spacing: 12) { |
| 398 | if step > 0 { |
| 399 | Button { changeStep(step - 1) } label: { Image(systemName: "chevron.left").frame(width: 20) } |
| 400 | .buttonStyle(OnboardingButtonStyle(primary: false)).accessibilityLabel("Back") |
| 401 | .accessibilityIdentifier("onboardingBack") |
| 402 | } |
| 403 | Button { |
| 404 | if step == Self.lastStep { finish() } else { changeStep(step + 1) } |
| 405 | } label: { |
| 406 | HStack(spacing: 12) { |
| 407 | Text(step == Self.lastStep ? startTitle : "Continue").lineLimit(1).minimumScaleFactor(0.7) |
| 408 | Image(systemName: "arrow.right") |
| 409 | }.frame(maxWidth: .infinity) |
| 410 | }.buttonStyle(OnboardingButtonStyle(primary: true)).accessibilityIdentifier("onboardingContinue") |
| 411 | } |
| 412 | } |
| 413 | private func changeStep(_ value: Int) { |
| 414 | let next = min(names.count - 1, max(0, value)) |
| 415 | guard next != step else { return } |
| 416 | withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) { step = next } |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | private extension VerticalAlignment { |
| 421 | struct OnboardingLessonTitleAlignment: AlignmentID { |
| 422 | static func defaultValue(in dimensions: ViewDimensions) -> CGFloat { dimensions[VerticalAlignment.center] } |
| 423 | } |
| 424 | static let onboardingLessonTitle = VerticalAlignment(OnboardingLessonTitleAlignment.self) |
| 425 | } |
| 426 | |
| 427 | #if os(macOS) |
| 428 | /// SwiftUI's DragGesture covers click-and-drag. AppKit delivers two-finger |
| 429 | /// trackpad navigation as scroll events, so observe those only while this |
| 430 | /// onboarding surface is visible in its own window. |
| 431 | private struct OnboardingTrackpadNavigation: NSViewRepresentable { |
| 432 | var navigate: (Int) -> Void |
| 433 | |
| 434 | func makeNSView(context: Context) -> TrackpadView { |
| 435 | let view = TrackpadView() |
| 436 | view.navigate = navigate |
| 437 | return view |
| 438 | } |
| 439 | func updateNSView(_ view: TrackpadView, context: Context) { view.navigate = navigate } |
| 440 | static func dismantleNSView(_ view: TrackpadView, coordinator: ()) { view.stopObserving() } |
| 441 | |
| 442 | final class TrackpadView: NSView { |
| 443 | var navigate: (Int) -> Void = { _ in } |
| 444 | private var monitor: Any? |
| 445 | private var travel = CGSize.zero |
| 446 | |
| 447 | override func hitTest(_ point: NSPoint) -> NSView? { nil } |
| 448 | |
| 449 | override func viewDidMoveToWindow() { |
| 450 | super.viewDidMoveToWindow() |
| 451 | stopObserving() |
| 452 | guard window != nil else { return } |
| 453 | monitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .swipe]) { [weak self] event in |
| 454 | self?.handle(event) |
| 455 | return event |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | func stopObserving() { |
| 460 | if let monitor { NSEvent.removeMonitor(monitor) } |
| 461 | monitor = nil |
| 462 | travel = .zero |
| 463 | } |
| 464 | |
| 465 | private func handle(_ event: NSEvent) { |
| 466 | guard let window, event.window === window, window.isKeyWindow, |
| 467 | !isHiddenOrHasHiddenAncestor, |
| 468 | bounds.contains(convert(event.locationInWindow, from: nil)) else { |
| 469 | travel = .zero |
| 470 | return |
| 471 | } |
| 472 | if event.type == .swipe { |
| 473 | // NSEvent uses +1 for a left swipe and -1 for a right swipe. |
| 474 | if abs(event.deltaX) > abs(event.deltaY) { navigate(event.deltaX > 0 ? 1 : -1) } |
| 475 | travel = .zero |
| 476 | return |
| 477 | } |
| 478 | guard event.hasPreciseScrollingDeltas, event.momentumPhase.isEmpty, |
| 479 | !event.phase.isEmpty else { return } |
| 480 | if event.phase.contains(.began) { travel = .zero } |
| 481 | if event.phase.contains(.cancelled) { travel = .zero; return } |
| 482 | travel.width += event.scrollingDeltaX |
| 483 | travel.height += event.scrollingDeltaY |
| 484 | if event.phase.contains(.ended) { |
| 485 | defer { travel = .zero } |
| 486 | guard abs(travel.width) >= 44, |
| 487 | abs(travel.width) > abs(travel.height) * 1.25 else { return } |
| 488 | navigate(travel.width < 0 ? 1 : -1) |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | #endif |
| 494 | |
| 495 | private struct OnboardingButtonStyle: ButtonStyle { |
| 496 | var primary: Bool |
| 497 | var compact = false |
| 498 | var fontSize: CGFloat? = nil |
| 499 | @Environment(\.isEnabled) private var enabled |
| 500 | func makeBody(configuration: Configuration) -> some View { |
| 501 | configuration.label |
| 502 | .font(fontSize.map { .system(size: $0, weight: .semibold) } ?? (compact ? .subheadline.weight(.medium) : .headline)) |
| 503 | .padding(.horizontal, compact ? 16 : 22).padding(.vertical, compact ? 12 : 17) |
| 504 | .foregroundStyle(primary ? Color(red: 0.16, green: 0.12, blue: 0.20) : .white) |
| 505 | .background(primary ? Color(red: 0.95, green: 0.68, blue: 0.55) : .white.opacity(configuration.isPressed ? 0.12 : 0.065), in: Capsule()) |
| 506 | .overlay(Capsule().strokeBorder(.white.opacity(primary ? 0 : 0.12), lineWidth: 1)) |
| 507 | .opacity(enabled ? (configuration.isPressed ? 0.8 : 1) : 0.4) |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | /// Fit lesson artwork and copy to the available space without scrolling or |
| 512 | /// covering the header and navigation. Measure and transform in one layout pass. |
| 513 | private struct OnboardingFittedContent<Content: View>: View { |
| 514 | var alignment: Alignment |
| 515 | @ViewBuilder var content: () -> Content |
| 516 | var body: some View { |
| 517 | GeometryReader { available in |
| 518 | content() |
| 519 | .frame(width: available.size.width) |
| 520 | .fixedSize(horizontal: false, vertical: true) |
| 521 | .visualEffect { effect, measured in |
| 522 | effect.scaleEffect(min(1, available.size.height / max(1, measured.size.height)), anchor: alignment == .topLeading ? .topLeading : .center) |
| 523 | } |
| 524 | .frame(width: available.size.width, height: available.size.height, alignment: alignment) |
| 525 | .clipped() |
| 526 | } |
| 527 | } |
| 528 | } |