import SwiftUI import StoreKit #if os(macOS) import AppKit #else import UIKit #endif extension Notification.Name { static let pulseCanvasOnboarding = Notification.Name("PulseCanvas.showOnboarding") } #if os(visionOS) private struct PulseCanvasOnboardingActiveKey: EnvironmentKey { static let defaultValue = false } extension EnvironmentValues { var pulseCanvasOnboardingActive: Bool { get { self[PulseCanvasOnboardingActiveKey.self] } set { self[PulseCanvasOnboardingActiveKey.self] = newValue } } } #endif enum PulseCanvasOnboarding { static let completedKey = "PulseCanvas.onboarding.completed.v1" static var initialStep: Int { #if DEBUG let args = ProcessInfo.processInfo.arguments if let index = args.firstIndex(of: "-PCOnboardingStep"), args.indices.contains(index + 1) { return min(PulseCanvasOnboardingView.lastStep, max(0, Int(args[index + 1]) ?? 0)) } #endif return 0 } static var forced: Bool { #if DEBUG return ProcessInfo.processInfo.arguments.contains("-PCOnboardingQA") #else return false #endif } static var fixture: Bool { #if DEBUG let args = ProcessInfo.processInfo.arguments return !forced && (args.contains("-PCMobileQA") || args.contains("-PCUITesting")) #else return false #endif } } /// Owns the entire root surface; onboarding is never presented in a sheet or popover. struct PulseCanvasOnboardingPresentation: ViewModifier { var onReplay: () -> Void = {} @AppStorage(PulseCanvasOnboarding.completedKey) private var completed = false @State private var replay = false @State private var presentationID = UUID() @State private var force = PulseCanvasOnboarding.forced private var showingOnboarding: Bool { replay || force || (!completed && !PulseCanvasOnboarding.fixture) } func body(content: Content) -> some View { Group { #if os(visionOS) // Keep the established spatial editor attached to its window during // replay. Removing and reinserting it can leave its controls unhittable. ZStack { if (completed || PulseCanvasOnboarding.fixture) && !force { content.opacity(showingOnboarding ? 0 : 1) .environment(\.pulseCanvasOnboardingActive, showingOnboarding) .allowsHitTesting(!showingOnboarding) .accessibilityElement(children: showingOnboarding ? .ignore : .contain) .accessibilityHidden(showingOnboarding) } if showingOnboarding { onboarding } } #else if showingOnboarding { onboarding } else { content } #endif } .onReceive(NotificationCenter.default.publisher(for: .pulseCanvasOnboarding)) { _ in onReplay() presentationID = UUID() replay = true } } private var onboarding: some View { PulseCanvasOnboardingView(initialStep: replay ? 0 : PulseCanvasOnboarding.initialStep) { completed = true replay = false force = false }.id(presentationID) } } struct PulseCanvasOnboardingView: View { let finish: () -> Void @State private var step: Int init(initialStep: Int = PulseCanvasOnboarding.initialStep, finish: @escaping () -> Void) { self.finish = finish _step = State(initialValue: min(Self.lastStep, max(0, initialStep))) } static let pageCount = 4 static let lastStep = pageCount - 1 @Environment(\.accessibilityReduceMotion) private var reduceMotion @ScaledMetric(relativeTo: .largeTitle) private var titleSize = 42 @ScaledMetric(relativeTo: .largeTitle) private var tabletTitleSize = 56 @ScaledMetric(relativeTo: .body) private var tabletBodySize = 24 @ScaledMetric(relativeTo: .headline) private var tabletLessonTitleSize = 23 @ScaledMetric(relativeTo: .subheadline) private var tabletDetailSize = 20 @ScaledMetric(relativeTo: .footnote) private var tabletNoteSize = 18 private let accent = Color(red: 0.95, green: 0.68, blue: 0.55) private let background = Color(red: 50.0 / 255, green: 44.0 / 255, blue: 55.0 / 255) private let ink = Color.white private var names: [String] { [String(localized: "Welcome"), String(localized: "Visualizers"), String(localized: "Studio"), String(localized: "Play & share")] } private let assets = ["welcome", "visuals", "studio", "share"] #if os(iOS) private let locksTextPositions = true #else private let locksTextPositions = false #endif private func title(for step: Int) -> String { switch step { case 0: return String(localized: "Your music.\nYour visual world.") case 1: return String(localized: "Find a look.\nMake it yours.") case 2: return String(localized: "Give your song\na visual story.") default: #if os(visionOS) return String(localized: "Make room\nfor your music.") #else return String(localized: "From your canvas\nto any screen.") #endif } } private func subtitle(for step: Int) -> String { switch step { case 0: return String(localized: "Turn sound into moving art with PulseCanvas Studio. A few basics, then the canvas is yours.") case 1: return String(localized: "Explore the visualizer library, save your favorites, and shape the colors and motion to suit your music.") case 2: return String(localized: "Choose music or import a soundtrack. Studio finds the beat so your scenes can change with the song.") default: #if os(visionOS) return String(localized: "Open the immersive screen to surround yourself with the visuals, or export your Studio project as an MP4.") #else return String(localized: "Enjoy your visuals full screen, or export an MP4 with your soundtrack, ready to save and share.") #endif } } private func lessons(for step: Int) -> [(String, String, String)] { switch step { case 0: return [("waveform", String(localized: "Start with a song"), String(localized: "Try the included music or discover a station in Radio.")), ("sparkles", String(localized: "Watch the music move"), String(localized: "Visuals respond to the rhythm as you listen."))] case 1: return [("square.grid.2x2", String(localized: "Explore the library"), String(localized: "Browse categories and heart the looks you love.")), ("slider.horizontal.3", String(localized: "Shape your style"), String(localized: "Adjust palettes, motion, and Chaos for a different feel."))] case 2: return [("rectangle.stack", String(localized: "Build scenes in Studio"), String(localized: "Choose a visualizer and a bar length for each scene.")), ("shuffle", String(localized: "Try a new sequence"), String(localized: "Randomize the timeline, then fine-tune your favorite moments."))] default: #if os(visionOS) return [("vision.pro", String(localized: "Open the immersive screen"), String(localized: "Choose Hide room for full immersion before entering.")), ("film", String(localized: "Save your creation"), String(localized: "Export MP4 renders the Studio timeline with your soundtrack."))] #elseif os(macOS) return [("arrow.up.left.and.arrow.down.right", String(localized: "Press Present"), String(localized: "Space pauses playback. Escape returns to the editor.")), ("film", String(localized: "Save a video"), String(localized: "In Project settings, choose a canvas and quality. Then choose Save video."))] #else return [("arrow.up.left.and.arrow.down.right", String(localized: "Open full-screen viewing"), String(localized: "Tap to reveal the controls while you listen.")), ("film", String(localized: "Export your video"), String(localized: "Open Project actions → Export MP4. Render, then Save video to Files."))] #endif } } var body: some View { GeometryReader { geometry in let wide = geometry.size.width >= 760 || geometry.size.width > geometry.size.height let short = geometry.size.height < 500 && wide #if os(iOS) let largeTablet = UIDevice.current.userInterfaceIdiom == .pad && min(geometry.size.width, geometry.size.height) >= 900 #else let largeTablet = false #endif VStack(spacing: 0) { header(wide: wide).zIndex(2) GeometryReader { pageGeometry in OnboardingFittedContent(alignment: locksTextPositions && !largeTablet ? .topLeading : .center) { page(wide: wide, size: pageGeometry.size, compact: pageGeometry.size.height < 480, largeTablet: largeTablet) } .frame(maxWidth: .infinity, maxHeight: .infinity) .contentShape(Rectangle()) .clipped() }.id(step) footer(wide: wide, short: short).zIndex(2) } .padding(.horizontal, wide ? 48 : 24) .padding(.top, 16) .padding(.bottom, 18) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(background.ignoresSafeArea()) .contentShape(Rectangle()) // A recognized drag takes precedence over button taps so swiping // across Continue cannot also activate it. Ordinary taps still work. .highPriorityGesture(DragGesture(minimumDistance: 20).onEnded { value in let distance = value.translation #if os(iOS) // Accept a deliberate short flick as well as a longer drag. // Require real horizontal travel before consulting momentum. let projected = value.predictedEndTranslation guard abs(distance.width) >= 24, abs(distance.width) > abs(distance.height) * 1.25, abs(distance.width) >= 44 || (distance.width * projected.width > 0 && abs(projected.width) >= 80) else { return } #else guard abs(distance.width) >= 44, abs(distance.width) > abs(distance.height) * 1.25 else { return } #endif changeStep(step + (distance.width < 0 ? 1 : -1)) }) #if os(macOS) .background(OnboardingTrackpadNavigation { direction in changeStep(step + direction) }) #endif } .dynamicTypeSize(.xSmall ... .xxxLarge) .foregroundStyle(ink).tint(accent).preferredColorScheme(.dark).environment(\.colorScheme, .dark) #if DEBUG .task(id: step) { // A capture waits for the actual page to appear before taking its screenshot. guard PulseCanvasOnboarding.forced else { return } try? await Task.sleep(for: .seconds(1)) guard !Task.isCancelled else { return } let file = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("onboarding-capture-ready.txt") try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) try? String(step).write(to: file, atomically: true, encoding: .utf8) } #endif } @ViewBuilder private func page(wide: Bool, size: CGSize, compact: Bool, largeTablet: Bool) -> some View { if wide { HStack(alignment: locksTextPositions && !largeTablet ? .top : .center, spacing: compact ? 28 : 54) { illustration .frame(width: min(size.width * 0.44, largeTablet ? 620 : 510), height: min(size.height * (compact ? 0.75 : 0.94), largeTablet ? 620 : 510)) copy(wide: true, compact: compact, largeTablet: largeTablet).frame(maxWidth: largeTablet ? 600 : 490) }.frame(maxWidth: largeTablet ? 1280 : 1120) .accessibilityElement(children: .contain) .accessibilityIdentifier("onboardingContent") } else { VStack(alignment: .leading, spacing: compact ? 12 : 20) { illustration.frame(height: min(compact ? 110 : 220, size.height * (compact ? 0.22 : 0.32))) .frame(maxWidth: .infinity) copy(wide: false, compact: compact, largeTablet: false) }.frame(maxWidth: 500) } } private var startTitle: String { String(localized: "Start creating") } private func header(wide: Bool) -> some View { HStack(spacing: 10) { if let logo = onboardingImage(named: "logo") { logo.resizable().interpolation(.high).scaledToFit() .frame(width: 36, height: 36) .clipShape(RoundedRectangle(cornerRadius: 8)).accessibilityHidden(true) } VStack(alignment: .leading, spacing: 1) { Text("PulseCanvas").font(.system(size: 19, weight: .semibold, design: .rounded)).lineLimit(1).minimumScaleFactor(0.8) Text("Studio").font(.caption).foregroundStyle(ink.opacity(0.92)) } Spacer() Button("Skip onboarding", action: finish).lineLimit(1).minimumScaleFactor(0.8).buttonStyle(OnboardingButtonStyle(primary: false, compact: true)) .accessibilityIdentifier("onboardingSkip") }.frame(minHeight: 48) } private var illustration: some View { Group { if let image = onboardingImage(named: assets[step]) { image.resizable().interpolation(.high).scaledToFit() } } .accessibilityHidden(true) } private func onboardingImage(named name: String) -> Image? { let directories = ["Resources/Onboarding", "Onboarding"] guard let url = directories.compactMap({ Bundle.module.url(forResource: name, withExtension: "png", subdirectory: $0) }).first else { return nil } #if os(macOS) guard let image = NSImage(contentsOf: url) else { return nil } return Image(nsImage: image) #else guard let image = UIImage(contentsOfFile: url.path) else { return nil } return Image(uiImage: image) #endif } private func copy(wide: Bool, compact: Bool, largeTablet: Bool) -> some View { VStack(alignment: .leading, spacing: compact ? 12 : 20) { copySection { index in Text(title(for: index)).font(.system(size: largeTablet ? tabletTitleSize : min(titleSize, wide ? 52 : 38) * (compact ? 0.88 : 1), weight: .bold, design: .rounded)) .tracking(-1.2).fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("onboardingTitle").accessibilityAddTraits(.isHeader) } copySection { index in Text(subtitle(for: index)).font(largeTablet ? .system(size: tabletBodySize) : (compact ? .callout : .body)).foregroundStyle(ink.opacity(0.92)) .fixedSize(horizontal: false, vertical: true).lineSpacing(3) .accessibilityIdentifier("onboardingSubtitle") } #if os(iOS) VStack(alignment: .leading, spacing: compact ? 12 : 18) { ForEach(0..<2) { row in copySection { index in lessonRow(lessons(for: index)[row], compact: compact, largeTablet: largeTablet) }.accessibilityIdentifier("onboardingLesson\(row)") } } #else copySection { index in details(for: index, compact: compact) } #endif }.frame(maxWidth: locksTextPositions ? .infinity : nil, alignment: .topLeading) } @ViewBuilder private func copySection(@ViewBuilder content: @escaping (Int) -> Content) -> some View { #if os(iOS) // Reserve the largest section across all slides in this layout pass. // Titles, descriptions and details therefore keep the same top/left // origins, including after rotation and Dynamic Type changes. ZStack(alignment: .topLeading) { ZStack(alignment: .topLeading) { ForEach(0.. some View { VStack(alignment: .leading, spacing: compact ? 12 : 18) { ForEach(lessons(for: step), id: \.0) { lesson in lessonRow(lesson, compact: compact) } } } private func lessonRow(_ lesson: (String, String, String), compact: Bool, largeTablet: Bool = false) -> some View { HStack(alignment: .onboardingLessonTitle, spacing: 14) { Image(systemName: lesson.0).font(.system(size: largeTablet ? 28 : 22)).foregroundStyle(accent) .frame(width: largeTablet ? 40 : 28).accessibilityHidden(true) VStack(alignment: .leading, spacing: 5) { Text(lesson.1).font(largeTablet ? .system(size: tabletLessonTitleSize, weight: .semibold) : (compact ? .subheadline.weight(.semibold) : .headline)) .alignmentGuide(.onboardingLessonTitle) { $0[VerticalAlignment.center] } Text(lesson.2).font(largeTablet ? .system(size: tabletDetailSize) : (compact ? .caption : .subheadline)).foregroundStyle(ink.opacity(0.92)) .fixedSize(horizontal: false, vertical: true) } }.accessibilityElement(children: .combine) } @ViewBuilder private func footer(wide: Bool, short: Bool) -> some View { if short { HStack(spacing: 24) { progress(compact: true) navigation.frame(maxWidth: 360) }.frame(maxWidth: .infinity).padding(.top, 10) } else { VStack(spacing: 18) { progress(compact: false) navigation.frame(maxWidth: 420) }.frame(maxWidth: .infinity).padding(.top, 14) } } private func progress(compact: Bool) -> some View { HStack(spacing: 7) { if !compact { ForEach(0.. 0 { Button { changeStep(step - 1) } label: { Image(systemName: "chevron.left").frame(width: 20) } .buttonStyle(OnboardingButtonStyle(primary: false)).accessibilityLabel("Back") .accessibilityIdentifier("onboardingBack") } Button { if step == Self.lastStep { finish() } else { changeStep(step + 1) } } label: { HStack(spacing: 12) { Text(step == Self.lastStep ? startTitle : "Continue").lineLimit(1).minimumScaleFactor(0.7) Image(systemName: "arrow.right") }.frame(maxWidth: .infinity) }.buttonStyle(OnboardingButtonStyle(primary: true)).accessibilityIdentifier("onboardingContinue") } } private func changeStep(_ value: Int) { let next = min(names.count - 1, max(0, value)) guard next != step else { return } withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) { step = next } } } private extension VerticalAlignment { struct OnboardingLessonTitleAlignment: AlignmentID { static func defaultValue(in dimensions: ViewDimensions) -> CGFloat { dimensions[VerticalAlignment.center] } } static let onboardingLessonTitle = VerticalAlignment(OnboardingLessonTitleAlignment.self) } #if os(macOS) /// SwiftUI's DragGesture covers click-and-drag. AppKit delivers two-finger /// trackpad navigation as scroll events, so observe those only while this /// onboarding surface is visible in its own window. private struct OnboardingTrackpadNavigation: NSViewRepresentable { var navigate: (Int) -> Void func makeNSView(context: Context) -> TrackpadView { let view = TrackpadView() view.navigate = navigate return view } func updateNSView(_ view: TrackpadView, context: Context) { view.navigate = navigate } static func dismantleNSView(_ view: TrackpadView, coordinator: ()) { view.stopObserving() } final class TrackpadView: NSView { var navigate: (Int) -> Void = { _ in } private var monitor: Any? private var travel = CGSize.zero override func hitTest(_ point: NSPoint) -> NSView? { nil } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() stopObserving() guard window != nil else { return } monitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .swipe]) { [weak self] event in self?.handle(event) return event } } func stopObserving() { if let monitor { NSEvent.removeMonitor(monitor) } monitor = nil travel = .zero } private func handle(_ event: NSEvent) { guard let window, event.window === window, window.isKeyWindow, !isHiddenOrHasHiddenAncestor, bounds.contains(convert(event.locationInWindow, from: nil)) else { travel = .zero return } if event.type == .swipe { // NSEvent uses +1 for a left swipe and -1 for a right swipe. if abs(event.deltaX) > abs(event.deltaY) { navigate(event.deltaX > 0 ? 1 : -1) } travel = .zero return } guard event.hasPreciseScrollingDeltas, event.momentumPhase.isEmpty, !event.phase.isEmpty else { return } if event.phase.contains(.began) { travel = .zero } if event.phase.contains(.cancelled) { travel = .zero; return } travel.width += event.scrollingDeltaX travel.height += event.scrollingDeltaY if event.phase.contains(.ended) { defer { travel = .zero } guard abs(travel.width) >= 44, abs(travel.width) > abs(travel.height) * 1.25 else { return } navigate(travel.width < 0 ? 1 : -1) } } } } #endif private struct OnboardingButtonStyle: ButtonStyle { var primary: Bool var compact = false var fontSize: CGFloat? = nil @Environment(\.isEnabled) private var enabled func makeBody(configuration: Configuration) -> some View { configuration.label .font(fontSize.map { .system(size: $0, weight: .semibold) } ?? (compact ? .subheadline.weight(.medium) : .headline)) .padding(.horizontal, compact ? 16 : 22).padding(.vertical, compact ? 12 : 17) .foregroundStyle(primary ? Color(red: 0.16, green: 0.12, blue: 0.20) : .white) .background(primary ? Color(red: 0.95, green: 0.68, blue: 0.55) : .white.opacity(configuration.isPressed ? 0.12 : 0.065), in: Capsule()) .overlay(Capsule().strokeBorder(.white.opacity(primary ? 0 : 0.12), lineWidth: 1)) .opacity(enabled ? (configuration.isPressed ? 0.8 : 1) : 0.4) } } /// Fit lesson artwork and copy to the available space without scrolling or /// covering the header and navigation. Measure and transform in one layout pass. private struct OnboardingFittedContent: View { var alignment: Alignment @ViewBuilder var content: () -> Content var body: some View { GeometryReader { available in content() .frame(width: available.size.width) .fixedSize(horizontal: false, vertical: true) .visualEffect { effect, measured in effect.scaleEffect(min(1, available.size.height / max(1, measured.size.height)), anchor: alignment == .topLeading ? .topLeading : .center) } .frame(width: available.size.width, height: available.size.height, alignment: alignment) .clipped() } } }