Branchwell

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

Raw 9.0 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1import SwiftUI
2import CoreData
3
4struct NoteDetailByIdView: View {
5 @FetchRequest private var notes: FetchedResults<Note>
6 private let newTranscriptionAction: (() -> Void)?
7 init(noteId: UUID, newTranscriptionAction: (() -> Void)? = nil) {
8 self.newTranscriptionAction = newTranscriptionAction
9 _notes = FetchRequest(sortDescriptors: [], predicate: NSPredicate(format: "id == %@ AND trashedAt == nil", noteId as CVarArg))
10 }
11 var body: some View {
12 if let note = notes.first { NoteDetailView(note: note, newTranscriptionAction: newTranscriptionAction) }
13 else { ContentUnavailableView("Note Unavailable", systemImage: "note.text") }
14 }
15}
16
17struct NoteDetailView: View {
18 @ObservedObject private var themeManager = ThemeManager.shared
19 @Environment(\.colorScheme) private var colorScheme
20 var headerIconColor: Color { themeManager.currentThemeColor.color(in: colorScheme) }
21 @ObservedObject var note: Note
22 var newTranscriptionAction: (() -> Void)? = nil
23 @EnvironmentObject var transcriptionManager: LiveTranscriptionManager
24 @Environment(\.dismiss) var dismiss
25 @Environment(\.accessibilityReduceMotion) var reduceMotion
26 @State var actionsFooterHeight: CGFloat = 150
27 @State var followsLiveSummary = true
28 @State var summaryScrollPosition = ScrollPosition()
29 @State var jumpScrollPhase: ScrollPhase = .idle
30 @State var jumpScrollAnchor: CGFloat = 0
31 @State var jumpDestination: VerticalEdge?
32 @State var selectedTab = "Transcript"
33 @State var isEditingTitle = false
34 @State var editedTitle = ""
35 @FocusState var isTitleFieldFocused: Bool
36 @State var showingTranscription = false
37 @State var showingDelete = false
38 @State var exportPayload: LocalSharePayload?
39 @State var exportDirectory: URL?
40 @State var showingAddTag = false
41 @State var isTagsExpanded = false
42 @State var newTagText = ""
43 @State var currentTags: [String] = []
44 @State var showingTranscriptEditor = false
45 @State var showingSummaryEditor = false
46 @State var showingAskAI = false
47 @ObservedObject var templateCatalog = SummaryTemplateStore.shared
48 @State var templatePresentation: SummaryTemplatePresentation?
49 var selectedTemplateTitle: String { templateCatalog.title(for: note.summaryType) }
50 func selectTemplate(_ template: SummaryTemplateDefinition) {
51 guard note.summaryType != template.key, transcriptionManager.canStart else { return }
52 if Note.isMeaningfulSummaryText(note.summary) && hasTranscript {
53 selectedTab = "Summary"
54 transcriptionManager.summarize(note, template: template)
55 } else {
56 note.summaryType = template.key
57 transcriptionManager.saveEdits()
58 }
59 }
60
61 func generateSummary() {
62 guard let template = try? templateCatalog.resolve(note.summaryType) else {
63 transcriptionManager.errorMessage = "This template is unavailable. Choose another template to regenerate the summary."
64 return
65 }
66 selectedTab = "Summary"
67 transcriptionManager.summarize(note, template: template)
68 }
69 var summaryIsRunning: Bool { transcriptionManager.summaryNoteID == note.id }
70 var noteIsTranscribing: Bool { transcriptionManager.activeNoteID == note.id && transcriptionManager.isTranscribing }
71 var hasTranscript: Bool { !transcript.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
72 var hasSummary: Bool { Note.isMeaningfulSummaryText(note.summary) || summaryIsRunning }
73 var transcript: String { note.transcription ?? "" }
74
75 func shareAsText() {
76 exportPayload = LocalSharePayload(items: [LocalNoteExport.content(note: note, format: .plainText)])
77 }
78 func export(_ format: LocalNoteExport.Format) {
79 do {
80 let file = try LocalNoteExport.file(note: note, format: format)
81 exportDirectory = file.deletingLastPathComponent()
82 exportPayload = LocalSharePayload(items: [file])
83 } catch { transcriptionManager.errorMessage = "Export failed: \(error.localizedDescription). Your note remains saved in Jotley." }
84 }
85 func shareSummaryPDF() {
86 do {
87 let file = try LocalNoteExport.summaryPDF(note: note)
88 exportDirectory = file.deletingLastPathComponent()
89 exportPayload = LocalSharePayload(items: [file])
90 } catch { transcriptionManager.errorMessage = "The PDF could not be created: \(error.localizedDescription). Your note remains saved in Jotley." }
91 }
92 func clearExport() {
93 exportPayload = nil
94 if let exportDirectory { try? FileManager.default.removeItem(at: exportDirectory) }
95 exportDirectory = nil
96 }
97}
98
99struct MobileNoteTextEditor: View {
100 enum Field {
101 case transcript, summary
102 var title: String { self == .transcript ? "Transcript" : "Summary" }
103 var key: String { self == .transcript ? "transcript" : "summary" }
104 }
105 @ObservedObject var note: Note
106 let field: Field
107 @EnvironmentObject var transcriptionManager: LiveTranscriptionManager
108 @EnvironmentObject var store: SharedPersistenceController
109 @Environment(\.dismiss) private var dismiss
110 @State private var text: String
111 @State private var transcriptDraft: TranscriptEditDraft
112 @State private var error: String?
113 @FocusState private var editorFocused: Bool
114 private let original: String
115 init(note: Note, field: Field) {
116 self.note = note
117 self.field = field
118 original = (field == .transcript ? note.transcription : note.summary) ?? ""
119 _text = State(initialValue: original)
120 _transcriptDraft = State(initialValue: TranscriptEditDraft(text: note.transcription ?? "", utterances: note.storedTranscriptUtterances))
121 }
122 var body: some View {
123 NavigationStack {
124 Group {
125 if field == .transcript {
126 VStack(alignment: .leading, spacing: 12) {
127 NoteFindReplace(transcript: $transcriptDraft)
128 if !transcriptDraft.hasTimestamps {
129 Text("Timing is unavailable for this transcript.").font(.caption).foregroundStyle(Color.themeTextSecondary)
130 }
131 editor(text: $transcriptDraft.editorText)
132 }
133 } else {
134 VStack(alignment: .leading, spacing: 12) {
135 NoteFindReplace(summary: $text)
136 editor(text: $text)
137 }
138 }
139 }
140 .font(.body).foregroundStyle(Color.themeTextPrimary)
141 .scrollContentBackground(.hidden).padding()
142 .background(Color.themeBackground)
143 .navigationTitle("Edit \(field.title)")
144 .navigationBarTitleDisplayMode(.inline)
145 .toolbar {
146 ToolbarItem(placement: .cancellationAction) {
147 Button("Cancel") { dismiss() }
148 .jotleyDismissButtonStyle(inToolbar: true)
149 .accessibilityIdentifier("\(field.key)EditorCancelButton")
150 }
151 .sharedBackgroundVisibility(.hidden)
152 ToolbarItem(placement: .confirmationAction) {
153 Button("Save") {
154 do {
155 guard transcriptionManager.canStart else { throw LocalError.message("Finish transcribing or processing before saving edits.") }
156 switch field {
157 case .transcript: try note.saveEditedTranscript(transcriptDraft, in: store)
158 case .summary: try note.saveEditedSummary(text, original: original, in: store)
159 }
160 dismiss()
161 } catch { self.error = error.localizedDescription }
162 }
163 .jotleyDismissButtonStyle(inToolbar: true)
164 .disabled(!transcriptionManager.canStart || note.isDeleted)
165 .accessibilityIdentifier("\(field.key)EditorSaveButton")
166 }
167 .sharedBackgroundVisibility(.hidden)
168 }
169 .alert("Couldn’t Save \(field.title)", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
170 Button("OK", role: .cancel) { error = nil }
171 } message: { Text(error ?? "") }
172 }
173 .tint(Color.themeActionText)
174 .preferredColorScheme(ThemeManager.shared.effectiveColorScheme)
175 .observeThemeChanges()
176 .interactiveDismissDisabled(field == .transcript ? transcriptDraft.hasChanges : text != original)
177 }
178
179 private func editor(text: Binding<String>) -> some View {
180 TextEditor(text: text)
181 .focused($editorFocused)
182 .scrollContentBackground(.hidden)
183 .padding(8)
184 .modifier(JotleyEditorField(isFocused: editorFocused))
185 .accessibilityLabel(field.title)
186 .accessibilityIdentifier("\(field.key)EditorText")
187 }
188}