Branchwell

Jotley / app · jotley.ai / iOS / Views / MainTabView.swift

Raw 16.1 KB on c22c50f3614b055549c1ecbf54af0165e0bc8df1
1import SwiftUI
2import UIKit
3import CoreData
4
5struct MainTabView: View {
6 private let minimumSidebarWidth: CGFloat = 280
7 @EnvironmentObject var persistenceController: SharedPersistenceController
8 @EnvironmentObject var transcriptionManager: LiveTranscriptionManager
9 @ObservedObject private var summaryNotifications = JotleySummaryNotifications.shared
10 @State private var summaryNavigationID = UUID()
11 @State private var duoFooterHeight: CGFloat = 92
12 @State private var windowBounds: CGRect = .zero
13 @State private var windowContentBounds: CGRect = .zero
14 @State private var detailBounds: CGRect = .zero
15 @State private var preferredCompactColumn: NavigationSplitViewColumn = .sidebar
16 @State private var showingSettings = false
17 @State private var showingWelcome = false
18 @State private var replayAfterSettings = false
19 private var onboardingInProgress: Bool {
20 showingWelcome || replayAfterSettings || (!onboardingCompleted && !JotleyOnboarding.bypassForFixture)
21 }
22 @AppStorage(JotleyOnboarding.completedKey) private var onboardingCompleted = false
23 @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.timestamp, ascending: false)],
24 predicate: SharedPersistenceController.activeNotesPredicate)
25 private var notes: FetchedResults<Note>
26 @State private var selectedNoteId: UUID?
27 @State private var hasInitializedNoteSelection = false
28 @State private var columnVisibility: NavigationSplitViewVisibility = .all
29 @State private var showingTranscriptionModal = false
30 @State private var newTranscriptionNote: Note?
31 @State private var pendingWidgetAction: MobileTranscriptionAction?
32 @ObservedObject private var themeManager = ThemeManager.shared
33 @Environment(\.horizontalSizeClass) private var horizontalSizeClass
34
35 private var usesExpandedPhoneLayout: Bool {
36 horizontalSizeClass == .regular && UIDevice.current.userInterfaceIdiom == .phone
37 }
38
39 private var usesThemedSidebarToggle: Bool {
40 UIDevice.current.userInterfaceIdiom == .pad && horizontalSizeClass == .regular
41 }
42
43 private var usesCornerCaptureButton: Bool {
44 UIDevice.current.userInterfaceIdiom == .phone
45 }
46
47 private var usesSideBySideFooter: Bool {
48 usesExpandedPhoneLayout && detailBounds.minX >= windowBounds.minX + minimumSidebarWidth
49 }
50
51 private var usesWindowFooter: Bool {
52 // Keep the native overlay-drawer route on Duo. A landscape phone's
53 // leading safe area also needs the window host, without being a sidebar.
54 usesCornerCaptureButton && (!usesExpandedPhoneLayout || detailBounds.minX > windowBounds.minX + 1)
55 }
56
57 private var footerBounds: CGRect {
58 // A persistent sidebar owns its own space. Only single-column screens
59 // and overlay drawers use controls centered on the whole window.
60 guard usesSideBySideFooter else { return windowBounds }
61 // The detail's trailing safe area reserves the system toolbar above.
62 // Bottom actions can extend below that rail to the actual window edge.
63 return CGRect(x: detailBounds.minX, y: windowBounds.minY,
64 width: windowBounds.maxX - detailBounds.minX, height: windowBounds.height)
65 }
66
67 var body: some View {
68 // One navigation container survives folds, rotations and window resizing.
69 // Replacing a split view with a separate stack loses the current detail's
70 // tab, editor and sheet state when iPhone Duo changes displays.
71 NavigationSplitView(columnVisibility: $columnVisibility, preferredCompactColumn: $preferredCompactColumn) {
72 notesList
73 .navigationSplitViewColumnWidth(min: minimumSidebarWidth, ideal: 320, max: 420)
74 .toolbar(removing: usesThemedSidebarToggle ? .sidebarToggle : nil)
75 .overlay(alignment: .trailing) {
76 if !usesExpandedPhoneLayout {
77 Rectangle()
78 .fill(Color.primary.opacity(0.2))
79 .frame(width: 1)
80 .ignoresSafeArea()
81 .allowsHitTesting(false)
82 .accessibilityHidden(true)
83 }
84 }
85 } detail: {
86 Group {
87 if let selectedNoteId {
88 NoteDetailByIdView(noteId: selectedNoteId, newTranscriptionAction: usesCornerCaptureButton ? { handleWidgetAction(.start) } : nil).id(selectedNoteId).id(summaryNavigationID)
89 } else {
90 JotleyLibraryWelcome(hasNotes: !notes.isEmpty,
91 canStart: transcriptionManager.canStart || transcriptionManager.isTranscribing) {
92 handleWidgetAction(.start)
93 }
94 .frame(maxHeight: .infinity)
95 .background(Color.themeBackground)
96 }
97 }
98 .toolbar(.visible, for: .navigationBar)
99 .toolbar(removing: usesThemedSidebarToggle ? .sidebarToggle : nil)
100 .toolbar {
101 ToolbarItem(placement: .topBarLeading) {
102 if usesThemedSidebarToggle && columnVisibility == .detailOnly {
103 JotleySidebarToggle(visibility: $columnVisibility)
104 }
105 }
106 .sharedBackgroundVisibility(.hidden)
107 }
108 .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { detailBounds = $0 }
109 // Keep the footer inside the native detail presentation. The Notes
110 // drawer and its dimming layer must cover all detail controls.
111 .overlayPreferenceValue(NoteFooterContentKey.self, alignment: .bottomTrailing) { footers in
112 if usesCornerCaptureButton && !usesWindowFooter {
113 Group {
114 if let selectedNoteId, let footer = footers[selectedNoteId] { footer }
115 else { cornerCaptureFooter }
116 }
117 .frame(width: windowBounds.isEmpty ? nil : windowBounds.width)
118 .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { duoFooterHeight = $0 }
119 // The overlay aligns the footer's trailing edge with the
120 // detail. Translate that edge to the current window edge,
121 // retaining natural height as the device folds or rotates.
122 .offset(x: windowBounds.isEmpty || detailBounds.isEmpty ? 0 : windowBounds.maxX - detailBounds.maxX)
123 .ignoresSafeArea(.container, edges: .bottom)
124 }
125 }
126 .ignoresSafeArea(.container, edges: usesCornerCaptureButton ? .bottom : [])
127 }
128 .navigationSplitViewStyle(.balanced)
129 .tint(Color.themeActionText)
130 .overlayPreferenceValue(NoteFooterContentKey.self, alignment: .bottom) { footers in
131 if usesWindowFooter {
132 Group {
133 if let selectedNoteId,
134 usesExpandedPhoneLayout || preferredCompactColumn == .detail,
135 let footer = footers[selectedNoteId] { footer }
136 else { cornerCaptureFooter }
137 }
138 .frame(width: footerBounds.isEmpty ? nil : footerBounds.width)
139 .offset(x: footerBounds.isEmpty ? 0 : footerBounds.midX - windowContentBounds.midX)
140 .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { duoFooterHeight = $0 }
141 .ignoresSafeArea(.container, edges: .bottom)
142 }
143 }
144 .ignoresSafeArea(.container, edges: usesWindowFooter ? .bottom : [])
145 .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { windowContentBounds = $0 }
146 .onGeometryChange(for: CGRect.self) { geometry in
147 let frame = geometry.frame(in: .global)
148 let insets = geometry.safeAreaInsets
149 return CGRect(x: frame.minX - insets.leading, y: frame.minY - insets.top,
150 width: frame.width + insets.leading + insets.trailing,
151 height: frame.height + insets.top + insets.bottom)
152 } action: { bounds in
153 let becameWide = !windowBounds.isEmpty && windowBounds.width <= windowBounds.height && bounds.width > bounds.height
154 windowBounds = bounds
155 if usesExpandedPhoneLayout && becameWide { columnVisibility = .automatic }
156 }
157 .preferredColorScheme(themeManager.effectiveColorScheme)
158 .observeThemeChanges()
159 .modifier(JotleyOnboardingPresentation(replay: $showingWelcome, onDismiss: {
160 if let action = pendingWidgetAction { pendingWidgetAction = nil; handleWidgetAction(action) }
161 openNotifiedSummary()
162 }))
163 .sheet(isPresented: $showingTranscriptionModal, onDismiss: {
164 if let id = newTranscriptionNote?.id {
165 openNote(id)
166 }
167 newTranscriptionNote = nil
168 openNotifiedSummary()
169 }) {
170 LiveTranscriptionView(isPresented: $showingTranscriptionModal, existingNote: newTranscriptionNote, isNewTranscription: newTranscriptionNote != nil, transcriptionManager: transcriptionManager)
171 }
172 .onChange(of: notes.map(\.objectID), initial: true) { _, _ in selectFirstNoteIfNeeded() }
173 .onChange(of: selectedNoteId) { _, _ in selectFirstNoteIfNeeded() }
174 .onChange(of: horizontalSizeClass) { _, _ in selectFirstNoteIfNeeded() }
175 .onChange(of: summaryNotifications.noteToOpen, initial: true) { _, _ in openNotifiedSummary() }
176 .onOpenURL { url in
177 guard let action = MobileTranscriptionAction(url: url) else { return }
178 if onboardingInProgress { pendingWidgetAction = action }
179 else if showingSettings { pendingWidgetAction = action; showingSettings = false }
180 else { handleWidgetAction(action) }
181 }
182 .sheet(isPresented: $showingSettings, onDismiss: {
183 if replayAfterSettings { replayAfterSettings = false; showingWelcome = true; return }
184 if let action = pendingWidgetAction { pendingWidgetAction = nil; handleWidgetAction(action) }
185 openNotifiedSummary()
186 }) {
187 NavigationStack {
188 SettingsView(onShowWelcome: {
189 replayAfterSettings = true
190 showingSettings = false
191 })
192 }
193 .presentationDetents([.large]).presentationDragIndicator(.visible)
194 }
195 .alert("Jotley", isPresented: Binding(get: { transcriptionManager.errorMessage != nil && !transcriptionManager.captureScreenVisible && newTranscriptionNote == nil && !showingTranscriptionModal && !transcriptionManager.isTranscribing && !transcriptionManager.busy }, set: { if !$0 { Task { @MainActor in transcriptionManager.errorMessage = nil } } })) {
196 Button("OK", role: .cancel) { transcriptionManager.errorMessage = nil }
197 } message: { Text(transcriptionManager.errorMessage ?? "") }
198 }
199 private func selectFirstNoteIfNeeded() {
200 if let selectedNoteId, notes.contains(where: { !$0.isDeleted && $0.id == selectedNoteId }) {
201 hasInitializedNoteSelection = true
202 return
203 }
204 // Once a compact phone's selected note is deleted, leave the user in the
205 // list. Initial launch and layouts with room for a detail still select a note.
206 if hasInitializedNoteSelection,
207 UIDevice.current.userInterfaceIdiom == .phone,
208 horizontalSizeClass != .regular {
209 selectedNoteId = nil
210 preferredCompactColumn = .sidebar
211 return
212 }
213 guard let first = notes.first(where: { !$0.isDeleted }) else { selectedNoteId = nil; return }
214 hasInitializedNoteSelection = true
215 if first.id == nil { first.id = UUID(); transcriptionManager.saveEdits() }
216 selectedNoteId = first.id
217 preferredCompactColumn = .detail
218 }
219
220 private func handleWidgetAction(_ action: MobileTranscriptionAction) {
221 switch action {
222 case .start:
223 if transcriptionManager.isTranscribing { showingTranscriptionModal = true; return }
224 guard transcriptionManager.canStart, !showingTranscriptionModal else { return }
225 do { newTranscriptionNote = try transcriptionManager.createNote(); showingTranscriptionModal = true }
226 catch { transcriptionManager.errorMessage = error.localizedDescription }
227 case .pause(let id):
228 guard transcriptionManager.activeNoteID == id, !transcriptionManager.busy else { return }
229 if transcriptionManager.transcriptionState == .listening { transcriptionManager.pauseTranscription() }
230 else if transcriptionManager.transcriptionState == .paused { Task { await transcriptionManager.resumeTranscription() } }
231 case .stop(let id):
232 guard transcriptionManager.activeNoteID == id else { return }
233 Task {
234 await transcriptionManager.stopTranscription()
235 newTranscriptionNote = nil
236 showingTranscriptionModal = false
237 openNote(id)
238 }
239 case .open(let id):
240 if transcriptionManager.activeNoteID == id, transcriptionManager.isTranscribing { showingTranscriptionModal = true }
241 else { openNote(id) }
242 }
243 }
244 private func openNotifiedSummary() {
245 guard !onboardingInProgress,
246 !showingSettings, !showingTranscriptionModal, let id = summaryNotifications.noteToOpen else { return }
247 summaryNavigationID = UUID()
248 openNote(id)
249 summaryNotifications.noteToOpen = nil
250 }
251 private func openNote(_ id: UUID) {
252 guard (try? persistenceController.notes().contains { $0.localNoteID == id }) == true else { return }
253 selectedNoteId = id
254 preferredCompactColumn = .detail
255 if usesExpandedPhoneLayout && !usesSideBySideFooter {
256 withAnimation { columnVisibility = .detailOnly }
257 }
258 }
259 private var cornerCaptureFooter: some View {
260 HStack {
261 Spacer()
262 NotesNewTranscriptionButton { handleWidgetAction(.start) }
263 }
264 .padding(.horizontal, 24).padding(.top, 8).padding(.bottom, MobileNoteFooterInsets.phoneBottom)
265 }
266
267 private var notesList: some View {
268 NotesListView(onSelectNote: openNote, showsNewTranscriptionButton: !usesCornerCaptureButton, usesSplitView: horizontalSizeClass == .regular, bottomContentInset: usesWindowFooter ? duoFooterHeight : 0, showingSettings: $showingSettings,
269 selectedNoteId: $selectedNoteId,
270 showingTranscriptionModal: $showingTranscriptionModal, columnVisibility: $columnVisibility, newTranscriptionNote: $newTranscriptionNote)
271 }
272}
273
274struct JotleySidebarToggle: View {
275 @Binding var visibility: NavigationSplitViewVisibility
276
277 var body: some View {
278 let isHidden = visibility == .detailOnly
279 Button {
280 visibility = isHidden ? .all : .detailOnly
281 } label: {
282 JotleyFloatingMenuIcon(systemImage: "sidebar.left")
283 }
284 .buttonStyle(.plain)
285 .accessibilityLabel(isHidden ? "Show Sidebar" : "Hide Sidebar")
286 .accessibilityIdentifier("notesSidebarToggle")
287 }
288}
289
290/// Reject malformed links and stale session IDs before starting transcription.
291enum MobileTranscriptionAction: Equatable {
292 case start, pause(UUID), stop(UUID), open(UUID)
293 init?(url: URL) {
294 guard url.scheme?.lowercased() == "jotley", url.path.isEmpty || url.path == "/",
295 let host = url.host?.lowercased(), let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }
296 if host == "starttranscription" || host == "startrecording" { self = .start; return }
297 let ids = components.queryItems?.filter { $0.name == "id" } ?? []
298 guard ids.count == 1, let value = ids.first?.value, let id = UUID(uuidString: value) else { return nil }
299 switch host {
300 case "pausetranscription", "pauserecording": self = .pause(id)
301 case "stoptranscription", "stoprecording": self = .stop(id)
302 case "transcription", "recording": self = .open(id)
303 default: return nil
304 }
305 }
306}