Jotley / app · jotley.ai / Shared / Services / JotleyDefaults.swift
| 1 | import SwiftUI |
| 2 | import FoundationModels |
| 3 | import Combine |
| 4 | import UserNotifications |
| 5 | import AVFoundation |
| 6 | import UniformTypeIdentifiers |
| 7 | #if os(iOS) |
| 8 | import UIKit |
| 9 | #else |
| 10 | import AppKit |
| 11 | #endif |
| 12 | |
| 13 | // Local alerts only: no APNs registration, network request or note content. |
| 14 | @MainActor final class JotleySummaryNotifications: NSObject, ObservableObject, UNUserNotificationCenterDelegate { |
| 15 | static let shared = JotleySummaryNotifications(defaults: .standard, center: .current()) |
| 16 | static let enabledKey = "jotleySummaryNotificationsEnabled" |
| 17 | static let enabledByDefault = true |
| 18 | static let requestPrefix = "jotley.summary." |
| 19 | @Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined |
| 20 | @Published private(set) var deliveryError: String? |
| 21 | @Published var noteToOpen: UUID? |
| 22 | private let defaults: UserDefaults |
| 23 | private let authorization: () async -> UNAuthorizationStatus |
| 24 | private let requestAuthorization: () async throws -> Bool |
| 25 | private let enqueue: (UNNotificationRequest) async throws -> Void |
| 26 | private let isActive: () -> Bool |
| 27 | private var center: UNUserNotificationCenter? |
| 28 | private var permissionTask: Task<Void, Never>? |
| 29 | private var pending = Set<UUID>() |
| 30 | private var delivered = Set<UUID>() |
| 31 | var isEnabled: Bool { defaults.object(forKey: Self.enabledKey) as? Bool ?? Self.enabledByDefault } |
| 32 | |
| 33 | init(defaults: UserDefaults, authorization: @escaping () async -> UNAuthorizationStatus, |
| 34 | requestAuthorization: @escaping () async throws -> Bool, |
| 35 | enqueue: @escaping (UNNotificationRequest) async throws -> Void, isActive: @escaping () -> Bool) { |
| 36 | self.defaults = defaults; self.authorization = authorization |
| 37 | self.requestAuthorization = requestAuthorization; self.enqueue = enqueue; self.isActive = isActive |
| 38 | super.init() |
| 39 | } |
| 40 | convenience init(defaults: UserDefaults, center: UNUserNotificationCenter) { |
| 41 | self.init(defaults: defaults, authorization: { await center.notificationSettings().authorizationStatus }, |
| 42 | requestAuthorization: { try await center.requestAuthorization(options: [.alert, .sound]) }, |
| 43 | enqueue: { try await center.add($0) }, isActive: { |
| 44 | #if os(iOS) |
| 45 | return UIApplication.shared.applicationState == .active |
| 46 | #else |
| 47 | return NSApp?.isActive == true |
| 48 | #endif |
| 49 | }) |
| 50 | self.center = center |
| 51 | } |
| 52 | func install() { center?.delegate = self } |
| 53 | func refreshAuthorization() async { authorizationStatus = await authorization() } |
| 54 | // Ask during onboarding, from Settings, or when a summary is requested. |
| 55 | func prepareForSummary() { |
| 56 | guard isEnabled, permissionTask == nil else { return } |
| 57 | permissionTask = Task { |
| 58 | await refreshAuthorization() |
| 59 | if authorizationStatus == .notDetermined, isActive(), isEnabled { |
| 60 | do { _ = try await requestAuthorization(); await refreshAuthorization() } |
| 61 | catch { deliveryError = "Notifications could not be enabled. Your summaries still work normally." } |
| 62 | } |
| 63 | permissionTask = nil |
| 64 | } |
| 65 | } |
| 66 | static func request(noteID: UUID, generationID: UUID) -> UNNotificationRequest { |
| 67 | let content = UNMutableNotificationContent() |
| 68 | content.title = "Summary ready" |
| 69 | content.body = "Your summary is saved. Open Jotley to read it." |
| 70 | content.sound = .default |
| 71 | content.userInfo = ["noteID": noteID.uuidString] |
| 72 | return UNNotificationRequest(identifier: requestPrefix + generationID.uuidString, content: content, trigger: nil) |
| 73 | } |
| 74 | // Call only after a completed summary has been committed to the note store. |
| 75 | func summarySaved(noteID: UUID?, generationID: UUID = UUID()) async { |
| 76 | guard let noteID, isEnabled, !pending.contains(generationID), !delivered.contains(generationID) else { return } |
| 77 | pending.insert(generationID); defer { pending.remove(generationID) } |
| 78 | if let permissionTask { await permissionTask.value } |
| 79 | await refreshAuthorization() |
| 80 | guard isEnabled, [.authorized, .provisional].contains(authorizationStatus) else { return } |
| 81 | do { |
| 82 | try await enqueue(Self.request(noteID: noteID, generationID: generationID)) |
| 83 | if delivered.count >= 128 { delivered.removeAll() } |
| 84 | delivered.insert(generationID); deliveryError = nil |
| 85 | } catch { deliveryError = "The summary was saved, but its notification could not be shown." } |
| 86 | } |
| 87 | @discardableResult func openSummary(from request: UNNotificationRequest) -> Bool { |
| 88 | guard request.identifier.hasPrefix(Self.requestPrefix), |
| 89 | let value = request.content.userInfo["noteID"] as? String, let id = UUID(uuidString: value) else { return false } |
| 90 | noteToOpen = id |
| 91 | #if os(macOS) |
| 92 | NSApp?.activate(ignoringOtherApps: true) |
| 93 | #endif |
| 94 | return true |
| 95 | } |
| 96 | nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, |
| 97 | withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { |
| 98 | Task { @MainActor in completionHandler(isEnabled ? [.banner, .sound] : []) } |
| 99 | } |
| 100 | nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, |
| 101 | withCompletionHandler completionHandler: @escaping () -> Void) { |
| 102 | Task { @MainActor in |
| 103 | if response.actionIdentifier == UNNotificationDefaultActionIdentifier { openSummary(from: response.notification.request) } |
| 104 | completionHandler() |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | struct JotleyNoteOrganizationSettings: View { |
| 110 | @AppStorage(LocalNoteOrganizationSettings.autoTagsKey) private var autoTags = true |
| 111 | @AppStorage(LocalNoteOrganizationSettings.autoFoldersKey) private var autoFolders = true |
| 112 | |
| 113 | var body: some View { |
| 114 | Toggle("Auto Tags", isOn: $autoTags) |
| 115 | .tint(.themePrimaryAccent) |
| 116 | .accessibilityIdentifier("settingsAutoTags") |
| 117 | Toggle("Auto File Notes", isOn: $autoFolders) |
| 118 | .tint(.themePrimaryAccent) |
| 119 | .accessibilityIdentifier("settingsAutoFolders") |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | struct JotleySummaryNotificationSettings: View { |
| 124 | @AppStorage(JotleySummaryNotifications.enabledKey) private var enabled = JotleySummaryNotifications.enabledByDefault |
| 125 | @ObservedObject private var notifications = JotleySummaryNotifications.shared |
| 126 | @Environment(\.scenePhase) private var scenePhase |
| 127 | var body: some View { |
| 128 | VStack(alignment: .leading, spacing: 10) { |
| 129 | Toggle("Notify when a summary is ready", isOn: $enabled) |
| 130 | .tint(.themePrimaryAccent).accessibilityIdentifier("settingsSummaryNotificationsToggle") |
| 131 | Text("Local alerts contain no note text and work offline. A notification is sent only after a completed summary is saved.") |
| 132 | .font(.caption).foregroundStyle(.secondary) |
| 133 | if enabled && notifications.authorizationStatus == .notDetermined { |
| 134 | Button("Allow Notifications") { notifications.prepareForSummary() } |
| 135 | .foregroundStyle(Color.themeActionText) |
| 136 | .accessibilityIdentifier("settingsAllowSummaryNotifications") |
| 137 | Text("You can also allow notifications when you next generate a summary.").font(.caption).foregroundStyle(.secondary) |
| 138 | } else if enabled && notifications.authorizationStatus == .denied { |
| 139 | Text("Notifications are blocked in system Settings. Allow Jotley notifications there to receive alerts.") |
| 140 | .font(.caption).foregroundStyle(.secondary) |
| 141 | } |
| 142 | if let error = notifications.deliveryError { Text(error).font(.caption).foregroundStyle(.secondary) } |
| 143 | } |
| 144 | .task { await notifications.refreshAuthorization() } |
| 145 | .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await notifications.refreshAuthorization() } } } |
| 146 | .onChange(of: enabled) { _, value in if value { notifications.prepareForSummary() } } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // Hardware eligibility is distinct from enabling Apple Intelligence or preparing |
| 151 | // its models. Apple's API supports all eligible devices without guessed model IDs. |
| 152 | enum JotleyAppleIntelligenceEligibility { |
| 153 | static func supports(availability: SystemLanguageModel.Availability) -> Bool { |
| 154 | switch availability { |
| 155 | case .available: return true |
| 156 | case .unavailable(let reason): |
| 157 | switch reason { |
| 158 | case .deviceNotEligible: return false |
| 159 | case .appleIntelligenceNotEnabled, .modelNotReady: return true |
| 160 | @unknown default: return false |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | static var unsupportedReason: String? { |
| 165 | guard !supports(availability: SystemLanguageModel.default.availability) else { return nil } |
| 166 | #if os(iOS) |
| 167 | return "Jotley requires Apple Intelligence-capable hardware and iOS or iPadOS 27 or later. Supported devices include iPhone 15 Pro/Pro Max, iPhone 16 or newer, iPhone Air, iPad with M1 or later, and iPad mini with A17 Pro. This device does not support Apple Intelligence." |
| 168 | #else |
| 169 | return "Jotley requires an Apple Intelligence-capable Mac running macOS 27 or later. This Mac does not support Apple Intelligence." |
| 170 | #endif |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Neutral glass for transcript and Ask AI bubbles. |
| 175 | struct JotleyTranscriptCard: ViewModifier { |
| 176 | var accentOutline = false |
| 177 | var cornerRadius: CGFloat = 12 |
| 178 | @ObservedObject private var theme = ThemeManager.shared |
| 179 | @Environment(\.accessibilityReduceTransparency) private var reduceTransparency |
| 180 | @Environment(\.colorScheme) private var colorScheme |
| 181 | |
| 182 | func body(content: Content) -> some View { |
| 183 | let shape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) |
| 184 | let accent = theme.currentThemeColor.color(in: colorScheme) |
| 185 | return content.background { |
| 186 | shape.fill(Color(white: colorScheme == .dark ? 0.18 : 0.95)) |
| 187 | .shadow(color: .black.opacity(reduceTransparency ? 0 : 0.08), radius: 3, y: 1) |
| 188 | } |
| 189 | .overlay { |
| 190 | shape.strokeBorder( |
| 191 | accentOutline ? accent : Color.primary.opacity(colorScheme == .dark ? 0.22 : 0.16), |
| 192 | lineWidth: 1 |
| 193 | ) |
| 194 | .allowsHitTesting(false) |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | /// Feather only the edges with more transcript offscreen. Keep the first and |
| 200 | /// newest lines fully visible when the scroll view is at either end. |
| 201 | struct JotleyTranscriptEdgeFade: ViewModifier { |
| 202 | private struct Edges: Equatable { var top = false; var bottom = false } |
| 203 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 204 | @State private var edges = Edges() |
| 205 | var topFadeHeight: CGFloat = 64 |
| 206 | var showsBottomFade = true |
| 207 | var isEnabled = true |
| 208 | |
| 209 | func body(content: Content) -> some View { |
| 210 | content |
| 211 | .onScrollGeometryChange(for: Edges.self) { geometry in |
| 212 | let offset = geometry.contentOffset.y |
| 213 | return Edges(top: offset + geometry.contentInsets.top > 1, |
| 214 | // A remaining safe-area inset alone shouldn't dim the newest line. |
| 215 | bottom: offset + geometry.containerSize.height < |
| 216 | geometry.contentSize.height - 12) |
| 217 | } action: { _, newEdges in |
| 218 | edges = newEdges |
| 219 | } |
| 220 | .mask { |
| 221 | if isEnabled { |
| 222 | GeometryReader { geometry in |
| 223 | VStack(spacing: 0) { |
| 224 | fade(toward: .bottom, height: min(topFadeHeight, geometry.size.height * 0.44), |
| 225 | visible: edges.top) |
| 226 | Color.black |
| 227 | if showsBottomFade { |
| 228 | fade(toward: .top, height: min(18, geometry.size.height * 0.1), |
| 229 | visible: edges.bottom) |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | } else { |
| 234 | Color.black |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | private static let smoothStops: [Gradient.Stop] = (0...12).map { step in |
| 240 | let position = CGFloat(step) / 12 |
| 241 | let opacity = position * position * position * (position * (6 * position - 15) + 10) |
| 242 | return .init(color: .black.opacity(Double(opacity)), location: position) |
| 243 | } |
| 244 | |
| 245 | private func fade(toward endPoint: UnitPoint, height: CGFloat, visible: Bool) -> some View { |
| 246 | LinearGradient(stops: Self.smoothStops, |
| 247 | startPoint: endPoint == .bottom ? .top : .bottom, endPoint: endPoint) |
| 248 | .overlay { Color.black.opacity(visible ? 0 : 1) } |
| 249 | .frame(height: height) |
| 250 | .animation(reduceMotion ? nil : .easeInOut(duration: 0.20), value: visible) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | struct JotleyAskComposerSurface: ViewModifier { |
| 255 | @Environment(\.colorScheme) private var colorScheme |
| 256 | var isFocused: Bool |
| 257 | |
| 258 | func body(content: Content) -> some View { |
| 259 | let outline = RoundedRectangle(cornerRadius: 20, style: .continuous) |
| 260 | content.background(Color(white: colorScheme == .dark ? 0.17 : 0.96), in: outline) |
| 261 | .overlay { |
| 262 | outline.strokeBorder( |
| 263 | isFocused ? Color.themePrimaryAccent : Color.themeTextSecondary.opacity(0.24), |
| 264 | lineWidth: isFocused ? 2 : 1 |
| 265 | ).allowsHitTesting(false) |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Let the presentation own the corners and shadow so the background follows |
| 271 | /// the sheet's outline as its size, safe area, and platform change. |
| 272 | struct JotleyGlassPanel: ViewModifier { |
| 273 | @Environment(\.accessibilityReduceTransparency) private var reduceTransparency |
| 274 | @Environment(\.colorScheme) private var colorScheme |
| 275 | func body(content: Content) -> some View { |
| 276 | content.presentationBackground { |
| 277 | if reduceTransparency { |
| 278 | Color.themeBackground |
| 279 | } else { |
| 280 | Rectangle().fill(.ultraThinMaterial) |
| 281 | .overlay { Color.themeBackground.opacity(colorScheme == .dark ? 0.92 : 0.80) } |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | /// A neutral drop shadow for brand marks and other standalone artwork. |
| 288 | struct JotleyControlShadow: ViewModifier { |
| 289 | @Environment(\.colorScheme) private var colorScheme |
| 290 | |
| 291 | func body(content: Content) -> some View { |
| 292 | content.shadow(color: .black.opacity(colorScheme == .dark ? 0.40 : 0.17), radius: 4, y: 2) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// Keep glass controls consistent across the Mac and mobile custom headers. |
| 297 | struct JotleyGlassButtonStyle: ButtonStyle { |
| 298 | @ObservedObject private var themeManager = ThemeManager.shared |
| 299 | @Environment(\.isEnabled) private var isEnabled |
| 300 | @Environment(\.colorScheme) private var colorScheme |
| 301 | var circular = false |
| 302 | var diameter: CGFloat? = nil |
| 303 | var keepsDisabledSurfaceVisible = false |
| 304 | var floatsOverContent = false |
| 305 | var usesTranslucentMaterial = false |
| 306 | var usesAccentForeground = false |
| 307 | |
| 308 | private var theme: ThemeColor { themeManager.currentThemeColor } |
| 309 | private var glassInk: Color { |
| 310 | if circular || usesAccentForeground { return theme.color(in: colorScheme) } |
| 311 | return .primary |
| 312 | } |
| 313 | |
| 314 | private var controlHeight: CGFloat { |
| 315 | if let diameter { return diameter } |
| 316 | #if os(macOS) |
| 317 | return 36 |
| 318 | #else |
| 319 | return 44 |
| 320 | #endif |
| 321 | } |
| 322 | func makeBody(configuration: Configuration) -> some View { |
| 323 | Group { |
| 324 | if circular { |
| 325 | configuration.label.frame(width: controlHeight, height: controlHeight) |
| 326 | .contentShape(Circle()).background { background(in: Circle()) } |
| 327 | } else { |
| 328 | configuration.label.padding(.horizontal, 16).frame(minHeight: controlHeight) |
| 329 | .contentShape(Capsule()).background { background(in: Capsule()) } |
| 330 | } |
| 331 | } |
| 332 | .foregroundStyle((configuration.role == .destructive ? Color.red : glassInk) |
| 333 | .opacity(isEnabled ? 1 : keepsDisabledSurfaceVisible ? 0.82 : floatsOverContent ? 0.55 : 1)) |
| 334 | .opacity(isEnabled || keepsDisabledSurfaceVisible || floatsOverContent ? 1 : 0.45) |
| 335 | .scaleEffect(configuration.isPressed ? 0.97 : 1) |
| 336 | .animation(.easeOut(duration: 0.12), value: configuration.isPressed) |
| 337 | } |
| 338 | |
| 339 | private func background<S: InsettableShape>(in shape: S) -> some View { |
| 340 | JotleyFloatingGlassSurface( |
| 341 | shape: shape, |
| 342 | usesTranslucentMaterial: usesTranslucentMaterial |
| 343 | ) |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// Draw Auto's soft backdrop from the outline alone. Menus and buttons |
| 348 | /// composite their labels differently, so neither the label nor the material |
| 349 | /// should be used as the source of the shadow. |
| 350 | struct JotleyFloatingGlassSurface<Outline: InsettableShape>: View { |
| 351 | @Environment(\.colorScheme) private var colorScheme |
| 352 | @Environment(\.accessibilityReduceTransparency) private var reduceTransparency |
| 353 | let shape: Outline |
| 354 | var usesTranslucentMaterial = false |
| 355 | |
| 356 | var body: some View { |
| 357 | let dark = colorScheme == .dark |
| 358 | let surface = Color(white: dark ? 0.18 : 0.96) |
| 359 | ZStack { |
| 360 | if reduceTransparency { |
| 361 | shape.fill(surface) |
| 362 | } else if usesTranslucentMaterial { |
| 363 | Color.clear.glassEffect(.regular.interactive(), in: shape) |
| 364 | } else { |
| 365 | Color.clear.glassEffect(.clear, in: shape) |
| 366 | .overlay { shape.fill(surface.opacity(0.85)) } |
| 367 | } |
| 368 | } |
| 369 | .overlay { shape.strokeBorder(.white.opacity(dark ? 0.16 : 0.70), lineWidth: 1) } |
| 370 | .background { |
| 371 | ZStack { |
| 372 | shape.fill(.black) |
| 373 | .shadow(color: .black.opacity(dark ? 0.28 : 0.14), radius: 4, y: 2) |
| 374 | shape.fill(.black).blendMode(.destinationOut) |
| 375 | } |
| 376 | .compositingGroup() |
| 377 | } |
| 378 | .allowsHitTesting(false) |
| 379 | .accessibilityHidden(true) |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | /// Menus render their own surface so native menu styles can't replace it. |
| 384 | struct JotleyGlassMenuLabel<Outline: InsettableShape>: ViewModifier { |
| 385 | @Environment(\.colorScheme) private var colorScheme |
| 386 | @Environment(\.isEnabled) private var isEnabled |
| 387 | @ObservedObject private var theme = ThemeManager.shared |
| 388 | let shape: Outline |
| 389 | |
| 390 | func body(content: Content) -> some View { |
| 391 | let color = theme.currentThemeColor |
| 392 | let ink = color.color(in: colorScheme) |
| 393 | content |
| 394 | .foregroundStyle(ink.opacity(isEnabled ? 1 : 0.55)) |
| 395 | .background { JotleyFloatingGlassSurface(shape: shape) } |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | #if os(iOS) |
| 400 | struct JotleyFloatingMenuIcon: View { |
| 401 | let systemImage: String |
| 402 | var verticalIconOffset: CGFloat = 0 |
| 403 | |
| 404 | var body: some View { |
| 405 | Image(systemName: systemImage) |
| 406 | .resizable() |
| 407 | .scaledToFit() |
| 408 | .frame(width: 16, height: 16) |
| 409 | .fontWeight(.semibold) |
| 410 | .offset(y: verticalIconOffset) |
| 411 | .frame(width: 32, height: 32) |
| 412 | .modifier(JotleyGlassMenuLabel(shape: Circle())) |
| 413 | // Reserve space inside the native toolbar for the shadow and touch target. |
| 414 | .frame(width: 44, height: 44) |
| 415 | .contentShape(Rectangle()) |
| 416 | } |
| 417 | } |
| 418 | #endif |
| 419 | |
| 420 | struct JotleyAboutLogo: View { |
| 421 | var size: CGFloat = 56 |
| 422 | @Environment(\.colorScheme) private var colorScheme |
| 423 | |
| 424 | var body: some View { |
| 425 | Image("jotley-brand-mark") |
| 426 | .renderingMode(.original) |
| 427 | .resizable().interpolation(.high).scaledToFit() |
| 428 | .frame(width: size, height: size) |
| 429 | .shadow(color: .black.opacity(colorScheme == .dark ? 0.24 : 0.16), radius: 2, y: 1) |
| 430 | .accessibilityLabel("Jotley") |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | struct JotleyLibraryWelcome: View { |
| 435 | var hasNotes = false |
| 436 | var canStart = true |
| 437 | let onStart: () -> Void |
| 438 | |
| 439 | var body: some View { |
| 440 | VStack(spacing: 20) { |
| 441 | if hasNotes { |
| 442 | Image(systemName: "doc.text.magnifyingglass") |
| 443 | .font(.system(size: 36, weight: .light)) |
| 444 | .foregroundStyle(Color.themeTextSecondary) |
| 445 | .accessibilityHidden(true) |
| 446 | } else { |
| 447 | JotleyAboutLogo() |
| 448 | .accessibilityHidden(true) |
| 449 | } |
| 450 | VStack(spacing: 10) { |
| 451 | Text(hasNotes ? LocalizedStringKey("Select a note") : LocalizedStringKey("Your words. Your device.")) |
| 452 | .font(.custom("Comfortaa-Bold", size: 27, relativeTo: .title)) |
| 453 | .foregroundStyle(.primary) |
| 454 | .accessibilityAddTraits(.isHeader) |
| 455 | .accessibilityIdentifier("libraryWelcomeHeading") |
| 456 | Text(hasNotes |
| 457 | ? LocalizedStringKey("Choose a note to read or edit the transcript, see the summary, or ask a question.") |
| 458 | : LocalizedStringKey("Capture thoughts and meetings. Edit transcripts and get key points with Apple Intelligence on your device.")) |
| 459 | .font(.body) |
| 460 | .foregroundStyle(.secondary) |
| 461 | .lineSpacing(3) |
| 462 | } |
| 463 | Button(action: onStart) { |
| 464 | Label("Start Transcription", systemImage: "waveform") |
| 465 | .font(.subheadline.weight(.semibold)) |
| 466 | } |
| 467 | .buttonStyle(JotleyGlassButtonStyle(floatsOverContent: true)) |
| 468 | .disabled(!canStart) |
| 469 | .accessibilityIdentifier("libraryWelcomeStartButton") |
| 470 | } |
| 471 | .multilineTextAlignment(.center) |
| 472 | .frame(maxWidth: 380) |
| 473 | .padding(.horizontal, 24) |
| 474 | .padding(.vertical, 28) |
| 475 | .frame(maxWidth: .infinity) |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | struct NoteFindReplace: View { |
| 480 | private enum Field { case find, replacement } |
| 481 | private enum Target { |
| 482 | case transcript(Binding<TranscriptEditDraft>) |
| 483 | case summary(Binding<String>) |
| 484 | } |
| 485 | private let target: Target |
| 486 | @State private var query = TranscriptFindQuery() |
| 487 | @State private var replacement = "" |
| 488 | @State private var replacedCount: Int? |
| 489 | @State private var isExpanded = false |
| 490 | @FocusState private var focus: Field? |
| 491 | |
| 492 | init(transcript: Binding<TranscriptEditDraft>) { |
| 493 | target = .transcript(transcript) |
| 494 | } |
| 495 | |
| 496 | init(summary: Binding<String>) { |
| 497 | target = .summary(summary) |
| 498 | } |
| 499 | |
| 500 | private var identifierPrefix: String { |
| 501 | if case .summary = target { return "summary" } |
| 502 | return "transcript" |
| 503 | } |
| 504 | |
| 505 | private var matchCount: Int { |
| 506 | switch target { |
| 507 | case .transcript(let draft): draft.wrappedValue.matchCount(for: query) |
| 508 | case .summary(let text): query.matchCount(in: text.wrappedValue) |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | private func replaceAll() { |
| 513 | switch target { |
| 514 | case .transcript(let draft): draft.wrappedValue.replaceAll(query, with: replacement) |
| 515 | case .summary(let text): text.wrappedValue = query.replacingMatches(in: text.wrappedValue, with: replacement) |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | var body: some View { |
| 520 | let matches = matchCount |
| 521 | VStack(alignment: .leading, spacing: 10) { |
| 522 | Button { |
| 523 | isExpanded.toggle() |
| 524 | } label: { |
| 525 | HStack { |
| 526 | Label("Find and Replace", systemImage: "magnifyingglass") |
| 527 | Spacer() |
| 528 | Image(systemName: isExpanded ? "chevron.up" : "chevron.down").accessibilityHidden(true) |
| 529 | } |
| 530 | .font(.body.weight(.semibold)) |
| 531 | .frame(minHeight: 44) |
| 532 | .contentShape(Rectangle()) |
| 533 | } |
| 534 | .buttonStyle(.plain) |
| 535 | .accessibilityIdentifier("\(identifierPrefix)FindReplace") |
| 536 | .accessibilityValue(isExpanded ? "Expanded" : "Collapsed") |
| 537 | if isExpanded { |
| 538 | VStack(alignment: .leading, spacing: 14) { |
| 539 | ViewThatFits(in: .horizontal) { |
| 540 | HStack(alignment: .top, spacing: 12) { |
| 541 | findField.frame(minWidth: 200) |
| 542 | replacementField.frame(minWidth: 200) |
| 543 | } |
| 544 | VStack(alignment: .leading, spacing: 12) { |
| 545 | findField |
| 546 | replacementField |
| 547 | } |
| 548 | } |
| 549 | #if os(macOS) |
| 550 | HStack(spacing: 18) { matchOptions } |
| 551 | .toggleStyle(.checkbox) |
| 552 | #else |
| 553 | VStack(alignment: .leading, spacing: 6) { matchOptions } |
| 554 | #endif |
| 555 | HStack(spacing: 12) { |
| 556 | if let replacedCount { |
| 557 | Text("Replaced \(replacedCount) \(replacedCount == 1 ? "match" : "matches").") |
| 558 | } else if case .summary = target { |
| 559 | Text("\(matches) \(matches == 1 ? "match" : "matches") in this summary") |
| 560 | } else { |
| 561 | Text("\(matches) \(matches == 1 ? "match" : "matches") in this transcript") |
| 562 | } |
| 563 | Spacer() |
| 564 | Button("Replace All") { |
| 565 | replaceAll() |
| 566 | replacedCount = matches |
| 567 | focus = nil |
| 568 | } |
| 569 | .buttonStyle(JotleyGlassButtonStyle()) |
| 570 | .disabled(matches == 0) |
| 571 | .accessibilityIdentifier("\(identifierPrefix)ReplaceAllButton") |
| 572 | } |
| 573 | .font(.callout) |
| 574 | .foregroundStyle(Color.themeTextSecondary) |
| 575 | } |
| 576 | .padding(.bottom, 4) |
| 577 | } |
| 578 | } |
| 579 | .padding(.horizontal, 14) |
| 580 | .padding(.vertical, 4) |
| 581 | .background(Color.themeContentBackground, in: RoundedRectangle(cornerRadius: 12)) |
| 582 | .overlay { |
| 583 | RoundedRectangle(cornerRadius: 12).strokeBorder(Color.themeTextSecondary.opacity(0.22)) |
| 584 | .allowsHitTesting(false) |
| 585 | } |
| 586 | .onChange(of: query.text) { replacedCount = nil } |
| 587 | .onChange(of: query.matchCase) { replacedCount = nil } |
| 588 | .onChange(of: query.wholeWords) { replacedCount = nil } |
| 589 | .onChange(of: replacement) { replacedCount = nil } |
| 590 | } |
| 591 | |
| 592 | private var findField: some View { |
| 593 | field("Find", prompt: "Text to find", text: $query.text, target: .find, id: "\(identifierPrefix)FindField") |
| 594 | } |
| 595 | |
| 596 | private var replacementField: some View { |
| 597 | field("Replace with", prompt: "Replacement text", text: $replacement, target: .replacement, id: "\(identifierPrefix)ReplaceField") |
| 598 | } |
| 599 | |
| 600 | private func field(_ title: String, prompt: String, text: Binding<String>, target: Field, id: String) -> some View { |
| 601 | VStack(alignment: .leading, spacing: 6) { |
| 602 | Text(title).font(.subheadline.weight(.semibold)).accessibilityHidden(true) |
| 603 | TextField(title, text: text, prompt: Text(prompt)) |
| 604 | .font(.body) |
| 605 | .textFieldStyle(.plain) |
| 606 | .autocorrectionDisabled() |
| 607 | .focused($focus, equals: target) |
| 608 | .padding(.horizontal, 12) |
| 609 | .frame(minHeight: 44) |
| 610 | .modifier(JotleyEditorField(isFocused: focus == target)) |
| 611 | .contentShape(Rectangle()) |
| 612 | .simultaneousGesture(TapGesture().onEnded { focus = target }) |
| 613 | .accessibilityIdentifier(id) |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | @ViewBuilder private var matchOptions: some View { |
| 618 | Toggle("Whole words", isOn: $query.wholeWords) |
| 619 | Toggle("Match case", isOn: $query.matchCase) |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | struct CustomSpeechWordsButton: View { |
| 624 | @AppStorage(CustomSpeechWords.defaultsKey) private var savedWords = "" |
| 625 | @State private var showingEditor = false |
| 626 | |
| 627 | var body: some View { |
| 628 | Button { showingEditor = true } label: { |
| 629 | Label("Custom Words", systemImage: "character.book.closed") |
| 630 | } |
| 631 | .accessibilityIdentifier("settingsCustomWordsButton") |
| 632 | .sheet(isPresented: $showingEditor) { |
| 633 | CustomSpeechWordsEditor(words: $savedWords) |
| 634 | .preferredColorScheme(ThemeManager.shared.effectiveColorScheme) |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | private struct CustomSpeechWordsEditor: View { |
| 640 | @Binding var words: String |
| 641 | @State private var draft: String |
| 642 | @State private var original: String |
| 643 | @State private var showingConflict = false |
| 644 | @State private var showingImport = false |
| 645 | @State private var importStatus: String? |
| 646 | @Environment(\.dismiss) private var dismiss |
| 647 | |
| 648 | init(words: Binding<String>) { |
| 649 | _words = words |
| 650 | _draft = State(initialValue: words.wrappedValue) |
| 651 | _original = State(initialValue: words.wrappedValue) |
| 652 | } |
| 653 | |
| 654 | var body: some View { |
| 655 | let entries = CustomSpeechWords.entries(in: draft) |
| 656 | let hasLongEntry = entries.contains { $0.count > CustomSpeechWords.entryLengthLimit } |
| 657 | VStack(alignment: .leading, spacing: 16) { |
| 658 | Text("Custom Words").font(.title2.bold()).accessibilityAddTraits(.isHeader) |
| 659 | Text("Add names, brands, and short phrases you say often, one per line. For example, add Jason if it keeps coming out as JSON.") |
| 660 | .font(.callout) |
| 661 | TextEditor(text: $draft) |
| 662 | .font(.body) |
| 663 | .scrollContentBackground(.hidden) |
| 664 | .padding(8) |
| 665 | .frame(minHeight: 160) |
| 666 | .background(Color.themeContentBackground, in: RoundedRectangle(cornerRadius: 12)) |
| 667 | .accessibilityLabel("Custom words, one per line") |
| 668 | .accessibilityIdentifier("customWordsEditor") |
| 669 | HStack { |
| 670 | Button { showingImport = true } label: { |
| 671 | Label("Import Word List", systemImage: "square.and.arrow.down") |
| 672 | } |
| 673 | .buttonStyle(JotleyGlassButtonStyle()) |
| 674 | .accessibilityIdentifier("customWordsImportButton") |
| 675 | Spacer() |
| 676 | Text("\(entries.count) of \(CustomSpeechWords.limit) entries") |
| 677 | .font(.caption) |
| 678 | .foregroundStyle(entries.count > CustomSpeechWords.limit ? .red : Color.themeTextSecondary) |
| 679 | } |
| 680 | if let importStatus { Text(importStatus).font(.caption).foregroundStyle(Color.themeTextSecondary) } |
| 681 | if hasLongEntry { |
| 682 | Text("Keep each entry to \(CustomSpeechWords.entryLengthLimit) characters or fewer.") |
| 683 | .font(.caption).foregroundStyle(.red) |
| 684 | } |
| 685 | Text("Saved on this device. Custom words guide new transcriptions and don’t change existing notes.") |
| 686 | .font(.caption).foregroundStyle(Color.themeTextSecondary) |
| 687 | HStack { |
| 688 | Button("Cancel") { dismiss() } |
| 689 | .jotleyDismissButtonStyle() |
| 690 | .keyboardShortcut(.cancelAction) |
| 691 | .accessibilityIdentifier("customWordsCancelButton") |
| 692 | Spacer() |
| 693 | Button("Save") { |
| 694 | guard words == original else { showingConflict = true; return } |
| 695 | words = entries.joined(separator: "\n") |
| 696 | dismiss() |
| 697 | } |
| 698 | .keyboardShortcut(.defaultAction) |
| 699 | .disabled(entries.count > CustomSpeechWords.limit || hasLongEntry) |
| 700 | .accessibilityIdentifier("customWordsSaveButton") |
| 701 | }.buttonStyle(JotleyGlassButtonStyle()) |
| 702 | } |
| 703 | .padding(24) |
| 704 | #if os(macOS) |
| 705 | .frame(width: 490, height: 460) |
| 706 | #endif |
| 707 | .background(Color.themeBackground) |
| 708 | .interactiveDismissDisabled(draft != original) |
| 709 | .fileImporter(isPresented: $showingImport, allowedContentTypes: [.plainText, .commaSeparatedText, .tabSeparatedText]) { result in |
| 710 | do { try importWords(from: result.get()) } |
| 711 | catch { importStatus = "Couldn’t import the list. \(error.localizedDescription)" } |
| 712 | } |
| 713 | .alert("Custom Words changed", isPresented: $showingConflict) { |
| 714 | Button("Reload List") { original = words; draft = words } |
| 715 | Button("Keep Editing", role: .cancel) {} |
| 716 | } message: { |
| 717 | Text("Another edit was saved while this editor was open. Reload the list before saving your changes.") |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | private func importWords(from url: URL) throws { |
| 722 | let scoped = url.startAccessingSecurityScopedResource() |
| 723 | defer { if scoped { url.stopAccessingSecurityScopedResource() } } |
| 724 | let file = try FileHandle(forReadingFrom: url) |
| 725 | defer { try? file.close() } |
| 726 | let sizeLimit = 64 * 1024 |
| 727 | let data = try file.read(upToCount: sizeLimit + 1) ?? Data() |
| 728 | guard data.count <= sizeLimit else { throw LocalError.message("Choose a word list smaller than 64 KB.") } |
| 729 | guard let text = String(data: data, encoding: .utf8), !text.contains("\0") else { |
| 730 | throw LocalError.message("Save the list as UTF-8 text, CSV, or TSV and try again.") |
| 731 | } |
| 732 | let imported = try CustomSpeechWords.importedEntries(in: text, fileExtension: url.pathExtension) |
| 733 | guard !imported.isEmpty else { throw LocalError.message("The file has no words or phrases.") } |
| 734 | let current = CustomSpeechWords.entries(in: draft) |
| 735 | let merged = CustomSpeechWords.entries(in: (current + imported).joined(separator: "\n")) |
| 736 | draft = merged.joined(separator: "\n") |
| 737 | let added = merged.count - current.count |
| 738 | importStatus = added == 0 ? "Those words are already on the list." : "Added \(added) \(added == 1 ? "entry" : "entries"). Review the list, then tap Save." |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | /// In-app confirmation keeps chat controls consistent without changing what |
| 743 | /// clearing removes. Escape preserves the conversation. |
| 744 | struct JotleyClearChatConfirmation: View { |
| 745 | let onCancel: () -> Void |
| 746 | let onClear: () -> Void |
| 747 | var body: some View { |
| 748 | ZStack { |
| 749 | Color.black.opacity(0.12).contentShape(Rectangle()).onTapGesture(perform: onCancel) |
| 750 | VStack(alignment: .leading, spacing: 16) { |
| 751 | Image(systemName: "trash") |
| 752 | .font(.system(size: 22, weight: .medium)).foregroundStyle(Color.themePrimaryAccent) |
| 753 | .frame(width: 44, height: 44).glassEffect(.clear, in: Circle()) |
| 754 | .accessibilityHidden(true) |
| 755 | Text("Clear chat history?") |
| 756 | .font(.system(size: 21, weight: .semibold)).foregroundStyle(Color.themeTextPrimary) |
| 757 | Text("This clears only this conversation. Your note, transcript and summary stay saved.") |
| 758 | .font(.system(size: 14)).foregroundStyle(Color.themeTextSecondary) |
| 759 | .fixedSize(horizontal: false, vertical: true).lineSpacing(3) |
| 760 | HStack(spacing: 12) { |
| 761 | Button(action: onCancel) { Text("Cancel").frame(maxWidth: .infinity) } |
| 762 | .jotleyDismissButtonStyle(expandsHorizontally: true) |
| 763 | .keyboardShortcut(.cancelAction) |
| 764 | .accessibilityIdentifier("askAIClearCancelButton") |
| 765 | Button(role: .destructive, action: onClear) { Text("Clear Chat").frame(maxWidth: .infinity) } |
| 766 | .accessibilityIdentifier("askAIClearConfirmButton") |
| 767 | } |
| 768 | .font(.system(size: 14, weight: .semibold)) |
| 769 | .buttonStyle(JotleyGlassButtonStyle()) |
| 770 | .padding(.top, 4) |
| 771 | } |
| 772 | .padding(24).frame(maxWidth: 350) |
| 773 | .background { |
| 774 | RoundedRectangle(cornerRadius: 24, style: .continuous) |
| 775 | .fill(.regularMaterial) |
| 776 | .glassEffect(.clear, in: RoundedRectangle(cornerRadius: 24, style: .continuous)) |
| 777 | } |
| 778 | .shadow(color: .black.opacity(0.18), radius: 24, y: 10) |
| 779 | .padding(24) |
| 780 | .accessibilityElement(children: .contain) |
| 781 | .accessibilityAddTraits(.isModal) |
| 782 | .accessibilityIdentifier("askAIClearConfirmation") |
| 783 | } |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | // Counts summaries in progress so updates wait until they finish. |
| 788 | @MainActor final class JotleyProcessing { |
| 789 | static let shared = JotleyProcessing() |
| 790 | private(set) var count = 0 |
| 791 | func begin() { count += 1 } |
| 792 | func end() { count = max(0, count - 1) } |
| 793 | } |
| 794 | |
| 795 | // One local completion flag across windows; replay never changes notes or permissions. |
| 796 | enum JotleyOnboarding { |
| 797 | static let completedKey = "jotleyWelcomeCompleted.v1" |
| 798 | static var bypassForFixture: Bool { |
| 799 | #if DEBUG |
| 800 | let environment = ProcessInfo.processInfo.environment |
| 801 | return environment["JOTLEY_SCREENSHOT_DATA"] != nil && environment["JOTLEY_TEST_ONBOARDING"] != "1" |
| 802 | #else |
| 803 | return false |
| 804 | #endif |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | extension EnvironmentValues { |
| 809 | /// True while setup covers the window, so toolbar items behind it can step aside. |
| 810 | @Entry var jotleyOnboardingActive = false |
| 811 | } |
| 812 | |
| 813 | struct JotleyOnboardingPresentation: ViewModifier { |
| 814 | @Binding var replay: Bool |
| 815 | var onDismiss: () -> Void |
| 816 | init(replay: Binding<Bool> = .constant(false), onDismiss: @escaping () -> Void = {}) { |
| 817 | _replay = replay |
| 818 | self.onDismiss = onDismiss |
| 819 | } |
| 820 | @AppStorage(JotleyOnboarding.completedKey) private var completed = false |
| 821 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 822 | private var showing: Bool { replay || (!completed && !JotleyOnboarding.bypassForFixture) } |
| 823 | func body(content: Content) -> some View { |
| 824 | ZStack { |
| 825 | // Preserve the open note and navigation state while setup owns the window. |
| 826 | content.opacity(showing ? 0 : 1) |
| 827 | .disabled(showing).accessibilityHidden(showing) |
| 828 | .environment(\.jotleyOnboardingActive, showing) |
| 829 | if showing { |
| 830 | JotleyOnboardingView { replay = false; onDismiss() } |
| 831 | .transition(.opacity).zIndex(1) |
| 832 | } |
| 833 | } |
| 834 | .animation(reduceMotion ? nil : .easeInOut(duration: 0.2), value: showing) |
| 835 | #if os(macOS) |
| 836 | .toolbarBackgroundVisibility(showing ? .hidden : .automatic, for: .windowToolbar) |
| 837 | #endif |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | #if os(iOS) |
| 842 | /// Bias the shared page block toward the screen's center without allowing |
| 843 | /// its tallest page to overlap the footer on shorter windows. |
| 844 | private struct JotleyOnboardingContentLayout: Layout { |
| 845 | func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { |
| 846 | proposal.replacingUnspecifiedDimensions() |
| 847 | } |
| 848 | func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { |
| 849 | guard let content = subviews.first else { return } |
| 850 | let contentProposal = ProposedViewSize(width: bounds.width, height: bounds.height) |
| 851 | let size = content.sizeThatFits(contentProposal) |
| 852 | let spareHeight = max(0, bounds.height - size.height) |
| 853 | let lowerBy = min(72, spareHeight / 2) |
| 854 | content.place(at: CGPoint(x: bounds.midX, y: bounds.minY + spareHeight / 2 + lowerBy), |
| 855 | anchor: .top, proposal: contentProposal) |
| 856 | } |
| 857 | } |
| 858 | #endif |
| 859 | |
| 860 | struct JotleyOnboardingView: View { |
| 861 | let onFinish: () -> Void |
| 862 | @AppStorage(JotleyOnboarding.completedKey) private var completed = false |
| 863 | @AppStorage("transcriptionLanguage") private var language = "en-US" |
| 864 | @AppStorage(JotleySummaryNotifications.enabledKey) private var summaryNotificationsEnabled = JotleySummaryNotifications.enabledByDefault |
| 865 | @ObservedObject private var theme = ThemeManager.shared |
| 866 | @ScaledMetric(relativeTo: .largeTitle) private var regularIconSize: CGFloat = 88 |
| 867 | @ScaledMetric(relativeTo: .title2) private var denseIconSize: CGFloat = 68 |
| 868 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 869 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 870 | @Environment(\.scenePhase) private var scenePhase |
| 871 | @Environment(\.layoutDirection) private var layoutDirection |
| 872 | @Environment(\.colorScheme) private var colorScheme |
| 873 | @State private var showingLanguages = false |
| 874 | @State private var step = 0 |
| 875 | @State private var languages: [LocalSpeech.Language] = [] |
| 876 | @State private var speechReady = false |
| 877 | @State private var speechCanSetUp = false |
| 878 | @State private var checkingSpeech = true |
| 879 | @State private var summaryReason: String? = "Checking Apple Intelligence…" |
| 880 | @State private var settingUpSpeech = false |
| 881 | @State private var setupProgress = 0.0 |
| 882 | @State private var setupError: String? |
| 883 | @State private var setupTask: Task<Void, Never>? |
| 884 | @State private var microphoneAllowed = false |
| 885 | @State private var microphoneDenied = false |
| 886 | @State private var requestingMicrophone = false |
| 887 | #if os(macOS) |
| 888 | @AppStorage("recordSystemAudio") private var includeSystemAudio = true |
| 889 | @State private var systemAudioProbe: JotleySystemAudioPermissionProbe? |
| 890 | @State private var systemAudioRequested = false |
| 891 | @State private var systemAudioMessage: String? |
| 892 | @State private var systemAudioTimeout: Task<Void, Never>? |
| 893 | #endif |
| 894 | private var steps: [String] { |
| 895 | #if os(macOS) |
| 896 | ["Welcome", "Intelligence", "Language", "Microphone", "System audio", "Notifications"] |
| 897 | #else |
| 898 | ["Welcome", "Intelligence", "Language", "Microphone", "Notifications"] |
| 899 | #endif |
| 900 | } |
| 901 | private var notificationsStep: Int { steps.count - 1 } |
| 902 | private var accent: Color { theme.currentThemeColor.color(in: colorScheme) } |
| 903 | private var ink: Color { colorScheme == .dark ? Color(white: 0.94) : Color(red: 0.14, green: 0.11, blue: 0.19) } |
| 904 | private var actionInk: Color { .primary } |
| 905 | private var muted: Color { ink.opacity(colorScheme == .dark ? 0.76 : 0.68) } |
| 906 | private var onboardingBackground: Color { colorScheme == .dark ? .themeDarkBackground : .themeLightBackground } |
| 907 | private func title(for page: Int, twoLines: Bool = false) -> String { |
| 908 | if page == notificationsStep { return "Summary notifications" } |
| 909 | if twoLines { |
| 910 | return switch page { |
| 911 | case 0: "Stay in the\nconversation." |
| 912 | case 1: "Find clarity in\nevery conversation." |
| 913 | case 2: "Start with\nyour language." |
| 914 | case 3: "Give your words\na place." |
| 915 | default: "Bring app audio along." |
| 916 | } |
| 917 | } |
| 918 | return switch page { |
| 919 | case 0: "Stay in the conversation." |
| 920 | case 1: "Find the useful parts." |
| 921 | case 2: "Start with your language." |
| 922 | case 3: "Give your words a place." |
| 923 | default: "Bring app audio along." |
| 924 | } |
| 925 | } |
| 926 | private func subtitle(for page: Int) -> String { |
| 927 | if page == notificationsStep { return "Get a local alert when your summary is saved." } |
| 928 | return switch page { |
| 929 | case 0: "Your thoughts become clear notes.\nYou get to be there for the moment." |
| 930 | case 1: "Summaries, useful titles and answers.\nPowered by Apple Intelligence on your device." |
| 931 | case 2: "Choose your Apple Intelligence language.\nTranscription, summaries and Ask AI stay on-device." |
| 932 | case 3: "Allow microphone access for live transcription.\nYou can change this later in Settings." |
| 933 | default: "Meetings, videos and the apps you listen to.\nmacOS controls access to system audio." |
| 934 | } |
| 935 | } |
| 936 | var body: some View { |
| 937 | GeometryReader { geometry in |
| 938 | let wide = geometry.size.width >= 620 |
| 939 | let scale = onboardingScale(in: geometry.size) |
| 940 | let artWidth = min(300 * scale, geometry.size.width * 0.3) |
| 941 | let compact = !dynamicTypeSize.isAccessibilitySize && (geometry.size.height < 800 || (!wide && geometry.size.width < 390)) |
| 942 | VStack(spacing: 16) { |
| 943 | header(scale: scale) |
| 944 | #if os(macOS) |
| 945 | pageLayout(wide: wide, dense: compact, artWidth: artWidth) |
| 946 | .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) |
| 947 | .padding(.vertical, 12) |
| 948 | #else |
| 949 | JotleyOnboardingContentLayout { |
| 950 | ViewThatFits(in: .vertical) { |
| 951 | mobilePageLayout(wide: wide, dense: compact, artWidth: artWidth, scale: scale) |
| 952 | .fixedSize(horizontal: false, vertical: true).padding(.vertical, 12) |
| 953 | if !wide && !compact && !dynamicTypeSize.isAccessibilitySize { |
| 954 | mobilePageLayout(wide: false, dense: true, artWidth: artWidth, scale: scale) |
| 955 | .fixedSize(horizontal: false, vertical: true).padding(.vertical, 12) |
| 956 | } |
| 957 | ScrollView { |
| 958 | mobilePageLayout(wide: wide, dense: !dynamicTypeSize.isAccessibilitySize, artWidth: artWidth, scale: scale) |
| 959 | .padding(.vertical, 8) |
| 960 | } |
| 961 | .scrollIndicators(.never).scrollBounceBehavior(.basedOnSize) |
| 962 | .accessibilityIdentifier("onboardingFallbackScroll") |
| 963 | } |
| 964 | } |
| 965 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 966 | .id(step) |
| 967 | #endif |
| 968 | if wide { |
| 969 | HStack(spacing: 24 * scale) { |
| 970 | Color.clear.frame(width: artWidth, height: 0) |
| 971 | footer(wide: true, scale: scale).frame(maxWidth: wideFooterWidth * scale) |
| 972 | .frame(maxWidth: 380 * scale, alignment: .leading) |
| 973 | } |
| 974 | .dynamicTypeSize(onboardingTextSize(scale: scale)) |
| 975 | } else { |
| 976 | footer(wide: false).frame(maxWidth: 480) |
| 977 | .frame(maxWidth: .infinity) |
| 978 | } |
| 979 | } |
| 980 | .padding(.horizontal, 24) |
| 981 | .padding(.top, 18) |
| 982 | #if os(macOS) |
| 983 | .padding(.bottom, 18) |
| 984 | #else |
| 985 | .padding(.bottom, 12) |
| 986 | #endif |
| 987 | #if os(macOS) |
| 988 | .frame(maxWidth: wide ? 820 : .infinity) |
| 989 | #endif |
| 990 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 991 | .background { |
| 992 | onboardingBackground.ignoresSafeArea() |
| 993 | } |
| 994 | } |
| 995 | #if os(iOS) |
| 996 | .ignoresSafeArea(.container, edges: .bottom) |
| 997 | #endif |
| 998 | .contentShape(Rectangle()) |
| 999 | .simultaneousGesture( |
| 1000 | DragGesture(minimumDistance: 36).onEnded { value in |
| 1001 | guard abs(value.translation.width) > abs(value.translation.height) * 1.5 else { return } |
| 1002 | let forward = layoutDirection == .rightToLeft ? value.translation.width > 0 : value.translation.width < 0 |
| 1003 | swipePage(forward: forward) |
| 1004 | } |
| 1005 | ) |
| 1006 | .foregroundStyle(ink) |
| 1007 | .preferredColorScheme(theme.effectiveColorScheme) |
| 1008 | .observeThemeChanges() |
| 1009 | .task(id: language) { await refreshModels() } |
| 1010 | .onAppear { |
| 1011 | refreshMicrophone() |
| 1012 | #if DEBUG |
| 1013 | // Screenshot checks can open a specific setup page. |
| 1014 | if let page = ProcessInfo.processInfo.environment["JOTLEY_ONBOARDING_STEP"].flatMap(Int.init), |
| 1015 | steps.indices.contains(page) { step = page } |
| 1016 | #endif |
| 1017 | } |
| 1018 | .onChange(of: scenePhase) { _, phase in |
| 1019 | if phase == .active { refreshMicrophone(); summaryReason = intelligenceReadiness() } |
| 1020 | } |
| 1021 | .onDisappear { |
| 1022 | setupTask?.cancel() |
| 1023 | #if os(macOS) |
| 1024 | stopSystemAudioSetup() |
| 1025 | #endif |
| 1026 | } |
| 1027 | } |
| 1028 | // Enlarge only roomy iPad windows; phones and narrow multitasking windows |
| 1029 | // retain the compact layout. Never reduce the user's Dynamic Type choice. |
| 1030 | private func onboardingScale(in size: CGSize) -> CGFloat { |
| 1031 | #if os(iOS) |
| 1032 | guard UIDevice.current.userInterfaceIdiom == .pad, size.width >= 800, size.height >= 700 else { return 1 } |
| 1033 | return max(1, min(1.3, (size.width - 48) / 720, (size.height - 200) / 620)) |
| 1034 | #else |
| 1035 | return 1 |
| 1036 | #endif |
| 1037 | } |
| 1038 | private func onboardingTextSize(scale: CGFloat) -> DynamicTypeSize { |
| 1039 | guard scale > 1 else { return dynamicTypeSize } |
| 1040 | let minimum: DynamicTypeSize = scale >= 1.24 ? .xxLarge : .xLarge |
| 1041 | return max(dynamicTypeSize, minimum) |
| 1042 | } |
| 1043 | @ViewBuilder private func pageLayout(wide: Bool, dense: Bool, artWidth: CGFloat, smallArtwork: Bool = false) -> some View { |
| 1044 | if wide { |
| 1045 | HStack(alignment: .top, spacing: 24) { |
| 1046 | largeIllustration(height: smallArtwork ? 240 : nil).frame(width: artWidth) |
| 1047 | pageContent(page: step, dense: dense).frame(maxWidth: 380, alignment: .leading) |
| 1048 | } |
| 1049 | } else { |
| 1050 | pageContent(page: step, dense: dense, inlineArtwork: true).frame(maxWidth: 480) |
| 1051 | } |
| 1052 | } |
| 1053 | #if os(iOS) |
| 1054 | /// Every page reserves the tallest page's size. Center this shared block, |
| 1055 | /// keeping its children top-aligned so headings and artwork never jump. |
| 1056 | private func mobilePageLayout(wide: Bool, dense: Bool, artWidth: CGFloat, scale: CGFloat) -> some View { |
| 1057 | HStack(alignment: .top, spacing: wide ? 24 * scale : 0) { |
| 1058 | if wide { largeIllustration(height: artWidth).frame(width: artWidth) } |
| 1059 | ZStack(alignment: .topLeading) { |
| 1060 | ForEach(steps.indices, id: \.self) { page in |
| 1061 | if page == step { |
| 1062 | pageContent(page: page, dense: dense, inlineArtwork: !wide, scale: scale, twoLineTitle: wide && UIDevice.current.userInterfaceIdiom == .pad) |
| 1063 | } else { |
| 1064 | pageContent(page: page, dense: dense, inlineArtwork: !wide, scale: scale, twoLineTitle: wide && UIDevice.current.userInterfaceIdiom == .pad) |
| 1065 | .hidden() |
| 1066 | .allowsHitTesting(false) |
| 1067 | .accessibilityElement(children: .ignore) |
| 1068 | .accessibilityHidden(true) |
| 1069 | } |
| 1070 | } |
| 1071 | } |
| 1072 | .frame(maxWidth: wide ? 380 * scale : 480, alignment: .leading) |
| 1073 | } |
| 1074 | .dynamicTypeSize(onboardingTextSize(scale: scale)) |
| 1075 | .accessibilityElement(children: .contain) |
| 1076 | .accessibilityIdentifier("onboardingContentBlock") |
| 1077 | } |
| 1078 | #endif |
| 1079 | |
| 1080 | private func header(scale: CGFloat) -> some View { |
| 1081 | HStack(spacing: 10) { |
| 1082 | Text("Jotley").font(.system(size: 23 * scale, weight: .semibold, design: .rounded)) |
| 1083 | .accessibilityIdentifier("onboardingBrand") |
| 1084 | Spacer() |
| 1085 | Button { finish() } label: { Text("Skip setup").foregroundStyle(actionInk) } |
| 1086 | .font(.subheadline.weight(.medium)).buttonStyle(JotleyGlassButtonStyle(diameter: 36)) |
| 1087 | .controlSize(.small).frame(minHeight: 36 * scale) |
| 1088 | .disabled(settingUpSpeech || requestingMicrophone) |
| 1089 | .accessibilityIdentifier("onboardingSkip") |
| 1090 | } |
| 1091 | .frame(minHeight: 44 * scale) |
| 1092 | .dynamicTypeSize(onboardingTextSize(scale: scale)) |
| 1093 | .accessibilityElement(children: .contain) |
| 1094 | .accessibilityIdentifier("onboardingHeader") |
| 1095 | } |
| 1096 | private func pageContent(page: Int, dense: Bool, inlineArtwork: Bool = false, scale: CGFloat = 1, twoLineTitle: Bool = false) -> some View { |
| 1097 | let stackedArtwork = inlineArtwork && !dense |
| 1098 | let headingLayout = stackedArtwork |
| 1099 | ? AnyLayout(VStackLayout(alignment: .leading, spacing: 8 * scale)) |
| 1100 | : AnyLayout(HStackLayout(alignment: .top, spacing: 12 * scale)) |
| 1101 | return VStack(alignment: .leading, spacing: (dense ? 10 : 22) * scale) { |
| 1102 | VStack(alignment: .leading, spacing: 10) { |
| 1103 | headingLayout { |
| 1104 | if inlineArtwork { |
| 1105 | let artworkSize = (stackedArtwork ? 116 : 88) * scale |
| 1106 | Image(illustrationAsset(for: page)).resizable().interpolation(.high).antialiased(true).scaledToFit() |
| 1107 | .frame(width: artworkSize, height: artworkSize) |
| 1108 | .accessibilityHidden(true) |
| 1109 | } |
| 1110 | Text(LocalizedStringKey(title(for: page, twoLines: twoLineTitle))).font(.system(inlineArtwork ? .title2 : .largeTitle, design: .rounded).weight(.bold)) |
| 1111 | .fixedSize(horizontal: false, vertical: true) |
| 1112 | .frame(height: (stackedArtwork ? 58 : 88) * scale, alignment: .topLeading) |
| 1113 | .accessibilityIdentifier("onboardingTitle") |
| 1114 | } |
| 1115 | .accessibilityElement(children: .contain) |
| 1116 | .accessibilityIdentifier("onboardingHeading") |
| 1117 | Text(LocalizedStringKey(dense && page == 2 ? "Choose your Apple Intelligence language." : subtitle(for: page))).font(dense ? .callout : .body).foregroundStyle(muted) |
| 1118 | .fixedSize(horizontal: false, vertical: true) |
| 1119 | .frame(minHeight: (dense ? 48 : 64) * scale, alignment: .topLeading) |
| 1120 | } |
| 1121 | switch page { |
| 1122 | case 0: |
| 1123 | feature("Private by design", detail: "Speech and AI run on this device. Optional private iCloud sync is yours to control.", icon: "lock.shield", dense: dense, scale: scale) |
| 1124 | feature("Free note-taking. No account needed.", detail: "Every feature is free, with no subscription.", icon: "heart", dense: dense, scale: scale) |
| 1125 | case 1: |
| 1126 | status(summaryReason == nil ? "Apple Intelligence is ready" : "Apple Intelligence needs setup", |
| 1127 | detail: summaryReason ?? "Your summaries and Ask AI answers are processed on this device.", |
| 1128 | ready: summaryReason == nil, dense: dense, scale: scale) |
| 1129 | .accessibilityIdentifier("onboardingIntelligenceStatus") |
| 1130 | feature("From thoughts to next steps", detail: "Pull out decisions, action items and topic tags. Ask a question when you need more.", icon: "sparkles", dense: dense, scale: scale) |
| 1131 | if summaryReason != nil { |
| 1132 | Text("Enable Apple Intelligence in your device’s Settings and let its model finish downloading. You can continue now and return to setup later.") |
| 1133 | .font(.callout).foregroundStyle(muted) |
| 1134 | } |
| 1135 | case 2: |
| 1136 | languageSelection(dense: dense) |
| 1137 | if checkingSpeech { |
| 1138 | ProgressView("Checking Apple speech…").tint(accent) |
| 1139 | } else { |
| 1140 | status(setupError != nil ? "Finish setup when you’re ready" : (speechReady ? "Ready to transcribe offline" : (speechCanSetUp ? "One-time speech setup" : "Choose another language")), |
| 1141 | detail: setupError ?? (speechReady ? "The selected language’s Apple speech model is installed." : |
| 1142 | (speechCanSetUp ? (dense ? "Download Apple’s speech model once to transcribe offline." : "Speech uses a separate Apple model. Setup needs internet access; transcription then works offline.") : "Choose an Apple Intelligence language supported by this device. You can also change it later in Settings.")), |
| 1143 | ready: speechReady, dense: dense, scale: scale) |
| 1144 | .accessibilityIdentifier(setupError == nil ? "onboardingSpeechStatus" : "onboardingSpeechError") |
| 1145 | } |
| 1146 | if settingUpSpeech { |
| 1147 | ProgressView("Setting up Apple speech…", value: setupProgress).tint(accent) |
| 1148 | Button("Cancel setup") { setupTask?.cancel() } |
| 1149 | .jotleyDismissButtonStyle() |
| 1150 | .accessibilityIdentifier("onboardingCancelSpeechSetup") |
| 1151 | } else if speechCanSetUp && !speechReady { |
| 1152 | Button("Set Up On-Device Speech") { setUpSpeech() } |
| 1153 | .buttonStyle(JotleyGlassButtonStyle()).foregroundStyle(actionInk) |
| 1154 | .accessibilityIdentifier("onboardingSpeechSetup") |
| 1155 | } |
| 1156 | Text(LocalizedStringKey(dense ? "Change your language or finish setup later in Settings." : "You can change your language or finish setup in Settings at any time.")).font(.footnote).foregroundStyle(muted).fixedSize(horizontal: false, vertical: true) |
| 1157 | .accessibilityIdentifier("onboardingLanguageHint") |
| 1158 | case 3: |
| 1159 | status(microphoneAllowed ? "Microphone access is enabled" : (microphoneDenied ? "Microphone access is off" : "You’re in control"), |
| 1160 | detail: microphoneAllowed ? "Tap + in your notes list whenever you want to start transcribing." : |
| 1161 | (microphoneDenied ? "Enable Microphone for Jotley in your device’s privacy settings when you’re ready." : "Jotley listens only when you start a transcription. Browsing your notes doesn’t need microphone access."), |
| 1162 | ready: microphoneAllowed, dense: dense, scale: scale) |
| 1163 | .accessibilityIdentifier("onboardingMicrophoneStatus") |
| 1164 | #if os(iOS) |
| 1165 | feature("Words worth keeping", detail: "Save your transcript without saving an audio file.", icon: "text.alignleft", dense: dense, scale: scale) |
| 1166 | #else |
| 1167 | feature("Bring your meetings along", detail: "Mac can also transcribe audio from apps, without saving an audio file. macOS asks for any extra access when you use that feature.", icon: "desktopcomputer", dense: dense, scale: scale) |
| 1168 | #endif |
| 1169 | case notificationsStep: |
| 1170 | VStack(alignment: .leading, spacing: 10) { |
| 1171 | Toggle("Notify when a summary is ready", isOn: $summaryNotificationsEnabled) |
| 1172 | .toggleStyle(.switch) |
| 1173 | .tint(accent) |
| 1174 | .accessibilityIdentifier("onboardingSummaryNotificationsToggle") |
| 1175 | Text("Local alerts contain no note text and work offline. You can change this in Settings.") |
| 1176 | .font(.footnote) |
| 1177 | .foregroundStyle(muted) |
| 1178 | .fixedSize(horizontal: false, vertical: true) |
| 1179 | } |
| 1180 | .padding(dense ? 12 : 16) |
| 1181 | .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 18)) |
| 1182 | default: |
| 1183 | #if os(macOS) |
| 1184 | status("A separate macOS permission", |
| 1185 | detail: "Let Jotley hear other apps. This is separate from microphone access and does not capture your screen.", |
| 1186 | ready: false, dense: dense, scale: scale) |
| 1187 | feature(systemAudioMessage == nil ? "Nothing is saved during setup" : "macOS manages your access", |
| 1188 | detail: systemAudioMessage ?? "Request access now, or keep transcription microphone-only. Your choice can be changed in Settings.", icon: "lock.shield", dense: dense, scale: scale) |
| 1189 | .accessibilityIdentifier("onboardingSystemAudioStatus") |
| 1190 | Button("Open Audio Privacy Settings") { |
| 1191 | NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")!) |
| 1192 | }.buttonStyle(JotleyGlassButtonStyle()) |
| 1193 | .accessibilityIdentifier("onboardingAudioPrivacySettings") |
| 1194 | #endif |
| 1195 | } |
| 1196 | } |
| 1197 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1198 | } |
| 1199 | private func languageSelection(dense: Bool) -> some View { |
| 1200 | Button { showingLanguages = true } label: { |
| 1201 | HStack(spacing: 12) { |
| 1202 | Image(systemName: "globe").font(.title2).foregroundStyle(accent) |
| 1203 | VStack(alignment: .leading, spacing: 4) { |
| 1204 | Text("Transcription Language").font(dense ? .footnote : .callout).foregroundStyle(muted) |
| 1205 | Text(languages.first(where: { $0.id == language })?.name ?? "Choose a supported language").font((dense ? Font.callout : .body).weight(.semibold)).foregroundStyle(ink) |
| 1206 | } |
| 1207 | Spacer() |
| 1208 | Image(systemName: "chevron.up.chevron.down").font(.caption).foregroundStyle(muted) |
| 1209 | }.padding(dense ? 12 : 16).background(.thinMaterial, in: RoundedRectangle(cornerRadius: 18)) |
| 1210 | } |
| 1211 | .buttonStyle(.plain) |
| 1212 | .disabled(settingUpSpeech || checkingSpeech) |
| 1213 | .accessibilityIdentifier("onboardingLanguagePicker") |
| 1214 | .popover(isPresented: $showingLanguages, arrowEdge: .bottom) { |
| 1215 | VStack(alignment: .leading, spacing: 10) { |
| 1216 | Text("Transcription Language").font(.headline).foregroundStyle(ink) |
| 1217 | ScrollView { |
| 1218 | LazyVStack(spacing: 3) { |
| 1219 | ForEach(languages) { item in |
| 1220 | Button { language = item.id; showingLanguages = false } label: { |
| 1221 | HStack { |
| 1222 | Text(item.name).foregroundStyle(ink) |
| 1223 | Spacer() |
| 1224 | if item.id == language { |
| 1225 | Image(systemName: "checkmark").foregroundStyle(accent).accessibilityHidden(true) |
| 1226 | } |
| 1227 | } |
| 1228 | .font(.body).padding(.horizontal, 12).padding(.vertical, 10) |
| 1229 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1230 | .background(item.id == language ? Color.primary.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 10)) |
| 1231 | .contentShape(Rectangle()) |
| 1232 | } |
| 1233 | .buttonStyle(.plain).accessibilityLabel(item.name) |
| 1234 | } |
| 1235 | } |
| 1236 | } |
| 1237 | .scrollIndicators(.never).frame(maxHeight: 310) |
| 1238 | } |
| 1239 | .padding(16).frame(width: 290) |
| 1240 | .background(onboardingBackground) |
| 1241 | .presentationCompactAdaptation(.popover) |
| 1242 | } |
| 1243 | } |
| 1244 | private func feature(_ title: String, detail: String, icon: String, dense: Bool, scale: CGFloat = 1) -> some View { |
| 1245 | HStack(alignment: .top, spacing: 13) { |
| 1246 | Image(systemName: icon).font(.system(size: 21 * scale, weight: .medium)).foregroundStyle(accent).frame(width: 28 * scale) |
| 1247 | .accessibilityHidden(true) |
| 1248 | VStack(alignment: .leading, spacing: 5) { |
| 1249 | Text(LocalizedStringKey(title)).font(dense ? .subheadline.weight(.semibold) : .headline) |
| 1250 | Text(LocalizedStringKey(detail)).font(dense ? .footnote : .callout).foregroundStyle(muted).fixedSize(horizontal: false, vertical: true) |
| 1251 | } |
| 1252 | }.accessibilityElement(children: .combine) |
| 1253 | } |
| 1254 | private func status(_ title: String, detail: String, ready: Bool, dense: Bool, scale: CGFloat = 1) -> some View { |
| 1255 | HStack(alignment: .top, spacing: 12) { |
| 1256 | Image(systemName: ready ? "checkmark.circle.fill" : "info.circle").foregroundStyle(ready ? .green : accent) |
| 1257 | .font(.title3).accessibilityHidden(true) |
| 1258 | VStack(alignment: .leading, spacing: 5) { |
| 1259 | Text(LocalizedStringKey(title)).font(dense ? .subheadline.weight(.semibold) : .headline) |
| 1260 | Text(LocalizedStringKey(detail)).font(dense ? .footnote : .callout).foregroundStyle(muted).fixedSize(horizontal: false, vertical: true) |
| 1261 | } |
| 1262 | }.padding((dense ? 12 : 16) * scale).frame(maxWidth: .infinity, alignment: .leading) |
| 1263 | .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 18)) |
| 1264 | .accessibilityElement(children: .combine) |
| 1265 | } |
| 1266 | private func illustrationAsset(for page: Int) -> String { |
| 1267 | if page == notificationsStep { return "onboarding-intelligence" } |
| 1268 | return switch page { |
| 1269 | case 0: "onboarding-welcome" |
| 1270 | case 1: "onboarding-intelligence" |
| 1271 | case 2: "onboarding-language" |
| 1272 | case 3: "onboarding-microphone" |
| 1273 | default: "onboarding-system-audio" |
| 1274 | } |
| 1275 | } |
| 1276 | private func largeIllustration(height: CGFloat? = nil) -> some View { |
| 1277 | Image(illustrationAsset(for: step)) |
| 1278 | .resizable().interpolation(.high).antialiased(true).scaledToFit() |
| 1279 | .frame(maxWidth: height ?? 300) |
| 1280 | .frame(height: height ?? 300) |
| 1281 | .accessibilityHidden(true) |
| 1282 | } |
| 1283 | private var wideFooterWidth: CGFloat { |
| 1284 | #if os(macOS) |
| 1285 | 278 |
| 1286 | #else |
| 1287 | 314 |
| 1288 | #endif |
| 1289 | } |
| 1290 | private var onboardingBackButton: some View { |
| 1291 | Button { changeStep(step - 1) } label: { |
| 1292 | Image(systemName: "chevron.left").font(.system(size: 14, weight: .medium)).foregroundStyle(actionInk) |
| 1293 | } |
| 1294 | .buttonStyle(JotleyGlassButtonStyle(circular: true)).frame(width: 54) |
| 1295 | .accessibilityLabel("Back").accessibilityIdentifier("onboardingBack") |
| 1296 | .disabled(settingUpSpeech || requestingMicrophone) |
| 1297 | } |
| 1298 | private func footer(wide: Bool, scale: CGFloat = 1) -> some View { |
| 1299 | // Wide layouts align the primary action with the copy; Back sits outside that column. |
| 1300 | let actionInset: CGFloat = !wide ? 66 : 0 |
| 1301 | return VStack(spacing: 13) { |
| 1302 | HStack(spacing: 6) { |
| 1303 | ForEach(0..<steps.count, id: \.self) { index in |
| 1304 | Capsule().fill(index == step ? accent : ink.opacity(0.13)).frame(width: index == step ? 25 : 6, height: 6) |
| 1305 | } |
| 1306 | Text("\(step + 1) of \(steps.count) · \(String(localized: String.LocalizationValue(steps[step])))").font(.caption).foregroundStyle(muted).padding(.leading, 5) |
| 1307 | .frame(width: 130 * scale, alignment: .leading) |
| 1308 | } |
| 1309 | .padding(.leading, actionInset) |
| 1310 | .accessibilityElement(children: .ignore).accessibilityLabel("Step \(step + 1) of \(steps.count), \(steps[step])") |
| 1311 | .accessibilityIdentifier("onboardingProgress") |
| 1312 | HStack(spacing: 12) { |
| 1313 | if !wide { |
| 1314 | onboardingBackButton.opacity(step > 0 ? 1 : 0) |
| 1315 | .allowsHitTesting(step > 0).accessibilityHidden(step == 0) |
| 1316 | } |
| 1317 | Button { |
| 1318 | if step == notificationsStep { |
| 1319 | if !completed && summaryNotificationsEnabled { |
| 1320 | JotleySummaryNotifications.shared.prepareForSummary() |
| 1321 | } |
| 1322 | finish() |
| 1323 | } |
| 1324 | else if step == 3 { |
| 1325 | if microphoneAllowed || microphoneDenied { advancePastMicrophone() } |
| 1326 | else { allowMicrophone() } |
| 1327 | } else if step == 4 { |
| 1328 | #if os(macOS) |
| 1329 | if systemAudioRequested { changeStep(notificationsStep) } else { requestSystemAudio() } |
| 1330 | #endif |
| 1331 | } else { changeStep(step + 1) } |
| 1332 | } label: { |
| 1333 | HStack(spacing: 9) { |
| 1334 | if requestingMicrophone { ProgressView().controlSize(.small).tint(actionInk) } |
| 1335 | Text(LocalizedStringKey(primaryTitle)) |
| 1336 | .font(.body.weight(.semibold)) |
| 1337 | }.frame(maxWidth: .infinity).foregroundStyle(actionInk) |
| 1338 | } |
| 1339 | .buttonStyle(JotleyGlassButtonStyle()).tint(accent) |
| 1340 | .disabled(settingUpSpeech || requestingMicrophone) |
| 1341 | .accessibilityIdentifier("onboardingContinue") |
| 1342 | } |
| 1343 | .overlay(alignment: .leading) { |
| 1344 | if wide && step > 0 { onboardingBackButton.offset(x: -66) } |
| 1345 | } |
| 1346 | onboardingSecondaryAction.frame(maxWidth: .infinity, minHeight: 36, maxHeight: 36) |
| 1347 | .padding(.leading, actionInset) |
| 1348 | } |
| 1349 | .frame(height: 128, alignment: .top) |
| 1350 | } |
| 1351 | private var onboardingSecondaryAction: some View { |
| 1352 | Group { |
| 1353 | if step == 3 && !microphoneAllowed && !microphoneDenied { |
| 1354 | Button("Not now") { advancePastMicrophone() } |
| 1355 | .accessibilityIdentifier("onboardingNotNow") |
| 1356 | } else { |
| 1357 | #if os(macOS) |
| 1358 | if step == 4 { |
| 1359 | Button("Use Microphone Only") { includeSystemAudio = false; changeStep(notificationsStep) } |
| 1360 | .accessibilityLabel("Use Microphone Only") |
| 1361 | .accessibilityIdentifier("onboardingMicrophoneOnly") |
| 1362 | } else { Color.clear.allowsHitTesting(false).accessibilityHidden(true) } |
| 1363 | #else |
| 1364 | Color.clear.allowsHitTesting(false).accessibilityHidden(true) |
| 1365 | #endif |
| 1366 | } |
| 1367 | } |
| 1368 | .buttonStyle(JotleyGlassButtonStyle(diameter: 36)) |
| 1369 | .font(.subheadline.weight(.medium)).controlSize(.small).foregroundStyle(actionInk) |
| 1370 | } |
| 1371 | private var primaryTitle: String { |
| 1372 | if step == notificationsStep { return "Open Jotley" } |
| 1373 | if step == 3 { |
| 1374 | #if os(macOS) |
| 1375 | return microphoneAllowed || microphoneDenied ? "Continue" : "Allow Microphone" |
| 1376 | #else |
| 1377 | return microphoneAllowed || microphoneDenied ? "Continue" : "Allow Microphone" |
| 1378 | #endif |
| 1379 | } |
| 1380 | #if os(macOS) |
| 1381 | if step == 4 { return systemAudioRequested ? "Continue" : "Request System Audio Access" } |
| 1382 | #endif |
| 1383 | return "Continue" |
| 1384 | } |
| 1385 | private func advancePastMicrophone() { |
| 1386 | #if os(macOS) |
| 1387 | changeStep(4) |
| 1388 | #else |
| 1389 | changeStep(notificationsStep) |
| 1390 | #endif |
| 1391 | } |
| 1392 | private func swipePage(forward: Bool) { |
| 1393 | guard !settingUpSpeech, !requestingMicrophone, !showingLanguages else { return } |
| 1394 | let next = step + (forward ? 1 : -1) |
| 1395 | guard steps.indices.contains(next) else { return } |
| 1396 | // Swiping only navigates. Permission requests and finishing setup stay explicit. |
| 1397 | changeStep(next) |
| 1398 | } |
| 1399 | private func changeStep(_ next: Int) { |
| 1400 | #if os(macOS) |
| 1401 | stopSystemAudioSetup() |
| 1402 | #endif |
| 1403 | withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.2)) { step = next } |
| 1404 | } |
| 1405 | private func finish() { |
| 1406 | #if os(macOS) |
| 1407 | stopSystemAudioSetup() |
| 1408 | #endif |
| 1409 | completed = true; onFinish() |
| 1410 | } |
| 1411 | #if os(macOS) |
| 1412 | private func requestSystemAudio() { |
| 1413 | let probe = JotleySystemAudioPermissionProbe() |
| 1414 | do { |
| 1415 | try probe.start() |
| 1416 | systemAudioProbe = probe |
| 1417 | includeSystemAudio = true |
| 1418 | systemAudioRequested = true |
| 1419 | systemAudioMessage = "Check the macOS prompt. If access is off, enable it in Privacy & Security. You can also continue with microphone-only transcription." |
| 1420 | systemAudioTimeout = Task { @MainActor in |
| 1421 | do { try await Task.sleep(for: .seconds(60)) } catch { return } |
| 1422 | systemAudioProbe?.stop(); systemAudioProbe = nil |
| 1423 | } |
| 1424 | } catch { |
| 1425 | probe.stop() |
| 1426 | systemAudioMessage = error.localizedDescription |
| 1427 | } |
| 1428 | } |
| 1429 | private func stopSystemAudioSetup() { |
| 1430 | systemAudioTimeout?.cancel(); systemAudioTimeout = nil |
| 1431 | systemAudioProbe?.stop(); systemAudioProbe = nil |
| 1432 | } |
| 1433 | #endif |
| 1434 | private func refreshMicrophone() { |
| 1435 | #if os(iOS) |
| 1436 | microphoneAllowed = AVAudioApplication.shared.recordPermission == .granted |
| 1437 | microphoneDenied = AVAudioApplication.shared.recordPermission == .denied |
| 1438 | #else |
| 1439 | microphoneAllowed = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized |
| 1440 | microphoneDenied = [.denied, .restricted].contains(AVCaptureDevice.authorizationStatus(for: .audio)) |
| 1441 | #endif |
| 1442 | } |
| 1443 | private func allowMicrophone() { |
| 1444 | guard !requestingMicrophone else { return } |
| 1445 | requestingMicrophone = true |
| 1446 | Task { @MainActor in |
| 1447 | #if os(iOS) |
| 1448 | _ = await AVAudioApplication.requestRecordPermission() |
| 1449 | #else |
| 1450 | _ = await AVCaptureDevice.requestAccess(for: .audio) |
| 1451 | #endif |
| 1452 | refreshMicrophone(); requestingMicrophone = false |
| 1453 | } |
| 1454 | } |
| 1455 | private func refreshModels() async { |
| 1456 | checkingSpeech = true |
| 1457 | summaryReason = intelligenceReadiness() |
| 1458 | let available = await LocalSpeech.languages() |
| 1459 | let ready = await LocalSpeech.readiness(locale: Locale(identifier: language)) |
| 1460 | guard !Task.isCancelled else { return } |
| 1461 | languages = available |
| 1462 | // Keep the same canonical language used by Settings and live transcription. |
| 1463 | if let matched = LocalSpeech.selectedLanguage(locale: Locale(identifier: language), in: available)?.id, matched != language { |
| 1464 | language = matched |
| 1465 | return |
| 1466 | } |
| 1467 | speechReady = ready.status == .installed && setupError == nil |
| 1468 | speechCanSetUp = ready.needsSetup || setupError != nil |
| 1469 | checkingSpeech = false |
| 1470 | } |
| 1471 | private func setUpSpeech() { |
| 1472 | guard !settingUpSpeech else { return } |
| 1473 | settingUpSpeech = true; setupProgress = 0; setupError = nil |
| 1474 | setupTask = Task { @MainActor in |
| 1475 | defer { settingUpSpeech = false; setupTask = nil } |
| 1476 | do { |
| 1477 | try await LocalSpeech.setUp(locale: Locale(identifier: language)) { progress in |
| 1478 | await MainActor.run { setupProgress = progress } |
| 1479 | } |
| 1480 | } catch is CancellationError { |
| 1481 | setupError = "Setup paused. You can finish it later in Settings." |
| 1482 | } catch { |
| 1483 | LocalSpeech.recordFailure(error, locale: Locale(identifier: language), details: "Onboarding speech setup") |
| 1484 | #if targetEnvironment(simulator) |
| 1485 | setupError = "Speech setup couldn’t finish in this simulator. Try on a supported iPhone or iPad, or continue setup for now." |
| 1486 | #else |
| 1487 | setupError = "Speech setup couldn’t finish. Check your connection and try again, or continue and set it up later in Settings." |
| 1488 | #endif |
| 1489 | } |
| 1490 | await Task { @MainActor in await refreshModels() }.value |
| 1491 | } |
| 1492 | } |
| 1493 | private func intelligenceReadiness() -> String? { |
| 1494 | let model = SystemLanguageModel.default |
| 1495 | switch model.availability { |
| 1496 | case .available: |
| 1497 | return model.supportsLocale(Locale(identifier: language)) ? nil : "Apple Intelligence does not support the selected language for summaries. You can choose another language in Settings." |
| 1498 | case .unavailable(let reason): |
| 1499 | switch reason { |
| 1500 | case .appleIntelligenceNotEnabled: return "Turn on Apple Intelligence in your device’s Settings to use summaries and Ask AI." |
| 1501 | case .modelNotReady: return "Apple is still preparing its on-device model. Connect to Wi-Fi and check Apple Intelligence in Settings." |
| 1502 | case .deviceNotEligible: return "Summaries and Ask AI require a device that supports Apple Intelligence." |
| 1503 | @unknown default: return "Apple Intelligence is unavailable right now. Check its status in your device’s Settings." |
| 1504 | } |
| 1505 | } |
| 1506 | } |
| 1507 | } |