Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasOnboarding.swift

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