Branchwell

Jotley / app / macOS / Views / NoteDetailComponents.swift

1//
2// NoteDetailComponents.swift
3// Jotley
4//
5// Small UI components extracted from NoteDetailPlaceholderView+Body.swift
6//
7
8import SwiftUI
9import AppKit
10
11// MARK: - Spinning Tab Icon
12
13
14struct LocalMacAskNoteView: View {
15 @ObservedObject var note: Note
16 @ObservedObject private var themeManager = ThemeManager.shared
17 @EnvironmentObject private var store: SharedPersistenceController
18 @Environment(\.dismiss) private var dismiss
19 @Environment(\.scenePhase) private var scenePhase
20 @FocusState private var inputFocused: Bool
21 @State private var messages: [LocalChatMessage] = []
22 @State private var input = ""
23 @State private var preview = ""
24 @State private var error: String?
25 @State private var task: Task<Void, Never>?
26 @State private var generation: UUID?
27 @State private var showingClear = false
28 private var source: String {
29 let transcript = (note.transcription ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
30 return transcript.isEmpty ? note.summary ?? "" : transcript
31 }
32 private var locale: Locale { Locale(identifier: UserDefaults.standard.string(forKey: "transcriptionLanguage") ?? "en-US") }
33 private var unavailable: String? {
34 LocalSummary.readiness(locale: locale)?.replacingOccurrences(of: "summaries", with: "Ask AI")
35 }
36 private var conversation: String { LocalNoteChat.conversationMarkdown(title: note.title, messages: messages) }
37 private var canSubmit: Bool { !showingClear && generation == nil && unavailable == nil }
38 private var canSend: Bool {
39 canSubmit && !input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
40 }
41 var body: some View {
42 VStack(spacing: 0) {
43 HStack(spacing: 16) {
44 Text("Ask AI").font(.system(size: 20, weight: .semibold)).foregroundStyle(Color.themeTextPrimary)
45 Spacer()
46 Button("Copy Conversation", systemImage: "doc.on.doc") {
47 NSPasteboard.general.clearContents(); NSPasteboard.general.setString(conversation, forType: .string)
48 }
49 .labelStyle(.iconOnly)
50 .buttonStyle(JotleyGlassButtonStyle(keepsDisabledSurfaceVisible: true))
51 .disabled(messages.isEmpty || generation != nil)
52 .help("Copy Conversation").accessibilityIdentifier("askAICopyConversationButton")
53 ShareLink(item: conversation) { Label("Share Conversation", systemImage: "square.and.arrow.up") }
54 .labelStyle(.iconOnly)
55 .buttonStyle(JotleyGlassButtonStyle(keepsDisabledSurfaceVisible: true))
56 .disabled(messages.isEmpty || generation != nil)
57 .help("Share Conversation").accessibilityIdentifier("askAIShareConversationButton")
58 Button("Clear Chat History", systemImage: "arrow.counterclockwise") { showingClear = true }
59 .labelStyle(.iconOnly)
60 .buttonStyle(JotleyGlassButtonStyle(keepsDisabledSurfaceVisible: true))
61 .disabled(messages.isEmpty || generation != nil)
62 .accessibilityIdentifier("askAIClearButton")
63 Button("Done") { dismiss() }
64 .jotleyDismissButtonStyle()
65 .accessibilityIdentifier("askAIDoneButton")
66 }.buttonStyle(JotleyGlassButtonStyle()).padding(16)
67 Divider()
68 VStack(spacing: 0) {
69 ScrollViewReader { proxy in
70 ScrollView {
71 LazyVStack(alignment: .leading, spacing: 16) {
72 if messages.isEmpty { welcome }
73 ForEach(messages) { message in
74 messageBubble(message).id(message.id)
75 }
76 if generation != nil {
77 VStack(alignment: .leading, spacing: 8) {
78 if preview.isEmpty { ProgressView("Thinking on this device…").progressViewStyle(MacThemedCircularProgressStyle()) }
79 else { MacChatAnswerText(content: preview) }
80 Button("Stop Answer") { cancel() }.buttonStyle(JotleyGlassButtonStyle())
81 .accessibilityIdentifier("askAIStopButton")
82 }.id("answer").padding().modifier(JotleyTranscriptCard())
83 }
84 }.padding()
85 }
86 .scrollDismissesKeyboard(.interactively)
87 .onChange(of: messages.count) { _, _ in
88 if let last = messages.last { proxy.scrollTo(last.id, anchor: .bottom) }
89 }
90 }
91 if let notice = error ?? unavailable {
92 HStack(alignment: .top) {
93 Image(systemName: "info.circle")
94 Text(notice).font(.system(size: 13))
95 if error != nil { Button("Dismiss") { error = nil }.buttonStyle(JotleyGlassButtonStyle()) }
96 }.foregroundStyle(Color.themeTextSecondary).padding()
97 .accessibilityIdentifier("askAIStatus")
98 }
99 Divider()
100 HStack(alignment: .center, spacing: 12) {
101 TextField("Ask about this note…", text: $input, axis: .vertical)
102 .textFieldStyle(.plain)
103 .tint(Color.themePrimaryAccent)
104 .accentColor(Color.themePrimaryAccent)
105 .lineLimit(1...5).padding(12).frame(minHeight: 44)
106 .modifier(JotleyAskComposerSurface(isFocused: inputFocused))
107 .focused($inputFocused).disabled(generation != nil)
108 .onKeyPress(keys: [.return, KeyEquivalent("\u{3}")], phases: .down) { press in
109 let editor = NSApp.keyWindow?.firstResponder as? NSTextView
110 // IME Return confirms composition before a question is sent.
111 guard editor?.hasMarkedText() != true else { return .ignored }
112 if !press.modifiers.isDisjoint(with: [.shift, .option]) {
113 guard let editor else { return .ignored }
114 editor.insertText("\n", replacementRange: editor.selectedRange())
115 return .handled
116 }
117 send()
118 return .handled
119 }
120 .accessibilityIdentifier("askAIQuestionField")
121 Button(action: send) {
122 Image(systemName: "arrow.up").font(.system(size: 20, weight: .semibold))
123 .frame(width: 44, height: 44)
124 }.buttonStyle(JotleyGlassButtonStyle(circular: true, diameter: 44, keepsDisabledSurfaceVisible: true))
125 .keyboardShortcut(.return, modifiers: .command)
126 .disabled(!canSend)
127 .accessibilityLabel("Send Question").accessibilityIdentifier("askAISendButton")
128 }.padding()
129 }
130
131 .task {
132 guard let id = note.id else { error = "This note is unavailable."; return }
133 do { messages = try store.chatMessages(noteID: id) }
134 catch { self.error = error.localizedDescription }
135 }
136 .onDisappear { cancel() }
137 .onChange(of: scenePhase) { _, phase in if phase == .background { cancel() } }
138 .onReceive(NotificationCenter.default.publisher(for: .processTapRecordingStateChanged)) { _ in cancel() }
139 .tint(.themePrimaryAccent).observeThemeChanges()
140 .font(.system(size: 15))
141 }.frame(width: 580, height: 650)
142 .foregroundStyle(Color.themeTextPrimary)
143 .modifier(JotleyGlassPanel())
144 .preferredColorScheme(themeManager.effectiveColorScheme)
145 .allowsHitTesting(!showingClear)
146 .accessibilityHidden(showingClear)
147 .overlay { clearConfirmation }
148 .onChange(of: showingClear) { _, showing in if showing { inputFocused = false } }
149 }
150 @ViewBuilder private var clearConfirmation: some View {
151 if showingClear {
152 JotleyClearChatConfirmation(onCancel: { showingClear = false }, onClear: clearConversation)
153 }
154 }
155 private func clearConversation() {
156 showingClear = false
157 guard let id = note.id else { return }
158 do { try store.clearChat(noteID: id); messages = []; error = nil }
159 catch { self.error = error.localizedDescription }
160 }
161 private var welcome: some View {
162 VStack(alignment: .leading, spacing: 16) {
163 Image(systemName: "bubble.left.and.bubble.right.fill").font(.system(size: 40)).foregroundStyle(Color.themePrimaryAccent)
164 Text("Ask about your note").font(.system(size: 24, weight: .bold)).foregroundStyle(Color.themeTextPrimary)
165 Text(note.title ?? "Untitled").font(.headline)
166 Text("Questions and answers are processed on this device using Apple Intelligence. No note content is sent to an AI service. Conversation history is saved with your notes and follows your optional iCloud setting.")
167 .font(.system(size: 15)).foregroundStyle(Color.themeTextSecondary)
168 if source.utf8.count > 2400 {
169 Text("For long notes, Ask AI selects relevant excerpts. Be specific about the topic you want to find.")
170 .font(.system(size: 13)).foregroundStyle(Color.themeTextSecondary)
171 }
172 ForEach(["Summarize the key points", "What are the main topics?", "List any action items"], id: \.self) { suggestion in
173 Button(suggestion) { submit(suggestion, fromComposer: false) }
174 .frame(minHeight: 44).buttonStyle(JotleyGlassButtonStyle()).disabled(!canSubmit)
175 }
176 }.padding(.vertical, 16)
177 }
178 private func messageBubble(_ message: LocalChatMessage) -> some View {
179 HStack {
180 if message.role == "user" { Spacer(minLength: 32) }
181 VStack(alignment: .leading, spacing: 8) {
182 HStack(spacing: 12) {
183 Text(message.role == "user" ? "You" : "Jotley").font(.caption.weight(.semibold))
184 Spacer(minLength: 8)
185 Text(message.timestamp, format: .dateTime.hour().minute())
186 .font(.caption2.monospacedDigit())
187 }.foregroundStyle(Color.themeTextSecondary)
188 if message.role == "assistant" { MacChatAnswerText(content: message.content) }
189 else { Text(message.content).textSelection(.enabled).foregroundStyle(Color.themeTextPrimary) }
190 }.padding().modifier(JotleyTranscriptCard(accentOutline: message.role == "user"))
191 if message.role == "assistant" { Spacer(minLength: 32) }
192 }
193 }
194 private func send() {
195 submit(input, fromComposer: true)
196 }
197 private func submit(_ text: String, fromComposer: Bool) {
198 let question = text.trimmingCharacters(in: .whitespacesAndNewlines)
199 guard canSubmit, !question.isEmpty, let id = note.id, !note.isDeleted else { return }
200 let source = source, history = messages
201 do {
202 _ = try LocalNoteChat.prompt(source: source, question: question, history: history)
203 let message = LocalChatMessage(role: "user", content: question)
204 try store.saveChatMessage(message, noteID: id); messages.append(message)
205 } catch { self.error = error.localizedDescription; return }
206 if fromComposer { input = "" }
207 inputFocused = false; preview = ""; error = nil
208 let token = UUID(); generation = token
209 let locale = locale
210 JotleyProcessing.shared.begin()
211 task = Task { @MainActor in
212 defer { JotleyProcessing.shared.end() }
213 defer { if generation == token { generation = nil; task = nil; preview = "" } }
214 do {
215 let answer = try await LocalNoteChat.answer(source: source, question: question, history: history, locale: locale) { value in
216 await MainActor.run { if generation == token { preview = value } }
217 }
218 try Task.checkCancellation()
219 guard generation == token, !note.isDeleted else { return }
220 let message = LocalChatMessage(role: "assistant", content: answer)
221 try store.saveChatMessage(message, noteID: id); messages.append(message)
222 } catch is CancellationError { }
223 catch {
224 if generation == token {
225 self.error = error.localizedDescription
226 if fromComposer { input = question }
227 }
228 }
229 }
230 }
231 private func cancel() {
232 task?.cancel(); task = nil; generation = nil; preview = ""
233 }
234}
235
236
237private struct MacChatAnswerText: View {
238 let content: String
239 var body: some View {
240 JotleyChatAnswerText(content: content, font: .system(size: 15))
241 }
242}
243
244
245/// AppKit's circular progress control can ignore a local tint. Draw the native
246/// activity symbol in the selected theme instead, retaining ProgressView labels.
247struct MacThemedCircularProgressStyle: ProgressViewStyle {
248 func makeBody(configuration: Configuration) -> some View {
249 HStack(spacing: 8) {
250 MacActivityIndicator()
251 configuration.label
252 }
253 }
254}
255
256private struct MacActivityIndicator: View {
257 @ObservedObject private var themeManager = ThemeManager.shared
258 @Environment(\.accessibilityReduceMotion) private var reduceMotion
259 var body: some View {
260 Image(systemName: "progress.indicator")
261 .font(.system(size: 14)).frame(width: 16, height: 16)
262 .foregroundStyle(themeManager.currentThemeColor.color)
263 .symbolEffect(.rotate, options: .repeating, isActive: !reduceMotion)
264 .accessibilityHidden(true)
265 }
266}