Branchwell

Jotley / app / macOS / Views / NoteListRowView.swift

1import SwiftUI
2import CoreData
3import AppKit
4
5// MARK: - Note List Row View
6
7struct NoteListRowView: View {
8 @ObservedObject private var themeManager = ThemeManager.shared
9 @ObservedObject var note: Note
10 let isSelected: Bool
11 let onDelete: () -> Void
12
13 @State private var isHovering = false
14 @State private var showContextMenu = false
15 @State private var contextMenuScale: CGFloat = 0.92
16 @State private var contextMenuOpacity: Double = 0
17
18 private var trimmedSummary: String {
19 note.summary?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
20 }
21
22 private var trimmedTranscription: String {
23 note.transcription?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
24 }
25
26 private var hasRenderedSummary: Bool {
27 !trimmedSummary.isEmpty &&
28 trimmedSummary != "Generating summary..." &&
29 trimmedSummary != "Transcription in progress..."
30 }
31
32 private var hasUsableTranscription: Bool {
33 guard !trimmedTranscription.isEmpty else { return false }
34
35 return trimmedTranscription != "Transcribing audio..." &&
36 trimmedTranscription != "Loading transcript..." &&
37 trimmedTranscription != "Loading content..." &&
38 trimmedTranscription != "Transcription in progress..." &&
39 !trimmedTranscription.hasPrefix("Transcription failed:")
40 }
41
42 private var isGenerating: Bool {
43 let summaryIsGenerating = trimmedSummary == "Generating summary..." ||
44 trimmedSummary == "Transcription in progress..."
45 let transcriptionIsGenerating = trimmedTranscription == "Transcribing audio..." ||
46 trimmedTranscription == "Loading transcript..." ||
47 trimmedTranscription == "Loading content..." ||
48 trimmedTranscription == "Transcription in progress..."
49
50 return summaryIsGenerating || transcriptionIsGenerating
51 }
52
53 @ViewBuilder
54 private var statusIconView: some View {
55 if isGenerating {
56 Image(systemName: "arrow.triangle.2.circlepath")
57 .font(.system(size: 10, weight: .semibold))
58 .foregroundColor(.themePrimaryAccent)
59 .accessibilityIdentifier("noteRowGeneratingIcon")
60 .help("Processing note")
61 }
62 }
63
64 private var previewText: String {
65 if hasRenderedSummary, let summary = note.summary {
66 return summary.previewSnippet()
67 } else if hasUsableTranscription, let transcription = note.transcription {
68 return transcription.previewSnippet()
69 }
70 return ""
71 }
72
73 var body: some View {
74 // Compute the preview once per body pass — it was previously evaluated twice
75 // (the `!isEmpty` guard and the `Text`), doubling the per-row string work.
76 let preview = previewText
77 ZStack {
78 // Main row content
79 VStack(alignment: .leading, spacing: 2) {
80 Text(note.titleOrUntitled)
81 .font(.system(size: 13, weight: .semibold))
82 .foregroundColor(Color.themeTextPrimary)
83 .lineLimit(2)
84 .truncationMode(.tail)
85 .fixedSize(horizontal: false, vertical: true)
86
87 HStack(spacing: 6) {
88 Text(note.timestampOrNow, style: hasRenderedSummary ? .time : .date)
89 .font(.system(size: 11))
90 .foregroundColor(Color.themeTextSecondary)
91
92 statusIconView
93
94 if !preview.isEmpty {
95 Text(preview)
96 .font(.system(size: 11))
97 .foregroundColor(Color.themeTextSecondary.opacity(0.8))
98 .lineLimit(1)
99 }
100 }
101 }
102 .padding(.vertical, 10)
103 .padding(.horizontal, 12)
104 .frame(maxWidth: .infinity, alignment: .leading)
105 .jotleyNoteSelection(isSelected,
106 unselectedBackground: isHovering ? Color.themeAccent.opacity(0.1) : Color.themeContentBackground)
107 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
108 .contentShape(Rectangle())
109 .background(
110 ReliableHoverTracker(isHovering: $isHovering)
111 )
112 .animation(.easeInOut(duration: 0.15), value: isHovering)
113 .onDisappear {
114 // LazyVStack recycles rows; ensure hover state doesn't get stuck
115 // when AppKit skips a mouseExited event during reorder or scroll.
116 isHovering = false
117 }
118 .overlay(
119 RightClickHandler {
120 showContextMenu = true
121 withAnimation(.spring(response: 0.25, dampingFraction: 0.8)) {
122 contextMenuScale = 1.0
123 contextMenuOpacity = 1.0
124 }
125 }
126 )
127
128 // Context menu overlay - aligned right
129 if showContextMenu {
130 Color.black.opacity(0.001) // Invisible tap catcher
131 .frame(maxWidth: .infinity, maxHeight: .infinity)
132 .onTapGesture {
133 dismissContextMenu()
134 }
135
136 HStack {
137 Spacer()
138 NoteContextMenuView(
139 onDelete: {
140 dismissContextMenu()
141 DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
142 onDelete()
143 }
144 }
145 )
146 .scaleEffect(contextMenuScale, anchor: .trailing)
147 .opacity(contextMenuOpacity)
148 .padding(.trailing, 8)
149 }
150 }
151 }
152 .tint(Color.themePrimaryAccent)
153 .listRowInsets(EdgeInsets(top: 2, leading: 8, bottom: 2, trailing: 4))
154 .listRowSeparator(.hidden)
155 .onChange(of: showContextMenu) { _, newValue in
156 if !newValue {
157 contextMenuScale = 0.92
158 contextMenuOpacity = 0
159 }
160 }
161 }
162
163 private func dismissContextMenu() {
164 withAnimation(.easeOut(duration: 0.15)) {
165 contextMenuScale = 0.92
166 contextMenuOpacity = 0
167 }
168 DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
169 showContextMenu = false
170 }
171 }
172}
173
174// MARK: - Context Menu View
175
176struct NoteContextMenuView: View {
177 let onDelete: () -> Void
178
179 @State private var isHovering = false
180 @Environment(\.colorScheme) private var colorScheme
181
182 var body: some View {
183 Button {
184 onDelete()
185 } label: {
186 Text("Move to Trash")
187 .font(.system(size: 13, weight: .medium))
188 .foregroundColor(isHovering ? .white : .primary)
189 .padding(.horizontal, 16)
190 .padding(.vertical, 8)
191 .background(
192 RoundedRectangle(cornerRadius: 6)
193 .fill(isHovering ? Color.themePrimaryAccent : Color.clear)
194 )
195 }
196 .buttonStyle(.plain)
197 .onHover { hovering in
198 withAnimation(.easeInOut(duration: 0.15)) {
199 isHovering = hovering
200 }
201 }
202 .padding(4)
203 .background(
204 RoundedRectangle(cornerRadius: 8, style: .continuous)
205 .fill(.ultraThinMaterial)
206 .shadow(color: Color.black.opacity(colorScheme == .dark ? 0.3 : 0.12), radius: 8, x: 0, y: 4)
207 )
208 }
209}
210
211// MARK: - Reliable Hover Tracker
212//
213// SwiftUI's `.onHover` can miss `mouseExited` when rows are recycled by
214// LazyVStack (scroll, reorder, CloudKit re-fetch), leaving a row visually
215// "stuck" as hovered. This uses an NSTrackingArea with `.inVisibleRect` so
216// macOS always recomputes tracking against the current frame, and actively
217// re-checks the cursor position whenever tracking areas update.
218
219struct ReliableHoverTracker: NSViewRepresentable {
220 @Binding var isHovering: Bool
221
222 func makeNSView(context: Context) -> HoverNSView {
223 let view = HoverNSView()
224 view.onHoverChange = { hovering in
225 if isHovering != hovering { isHovering = hovering }
226 }
227 return view
228 }
229
230 func updateNSView(_ nsView: HoverNSView, context: Context) {
231 nsView.onHoverChange = { hovering in
232 if isHovering != hovering { isHovering = hovering }
233 }
234 }
235
236 final class HoverNSView: NSView {
237 var onHoverChange: ((Bool) -> Void)?
238 private var trackingArea: NSTrackingArea?
239
240 override func updateTrackingAreas() {
241 super.updateTrackingAreas()
242 if let ta = trackingArea { removeTrackingArea(ta) }
243 let ta = NSTrackingArea(
244 rect: .zero,
245 options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect],
246 owner: self,
247 userInfo: nil
248 )
249 addTrackingArea(ta)
250 trackingArea = ta
251
252 // Reconcile with the actual cursor position — fixes the case where
253 // the view just moved out from under the mouse (scroll/reorder) and
254 // the system never fired mouseExited.
255 if let window = self.window {
256 let mouseLocWindow = window.mouseLocationOutsideOfEventStream
257 let localPoint = convert(mouseLocWindow, from: nil)
258 onHoverChange?(bounds.contains(localPoint))
259 } else {
260 onHoverChange?(false)
261 }
262 }
263
264 override func mouseEntered(with event: NSEvent) {
265 onHoverChange?(true)
266 }
267
268 override func mouseExited(with event: NSEvent) {
269 onHoverChange?(false)
270 }
271
272 override func viewDidMoveToWindow() {
273 super.viewDidMoveToWindow()
274 if window == nil { onHoverChange?(false) }
275 }
276
277 override func hitTest(_ point: NSPoint) -> NSView? {
278 // Pass clicks through to the SwiftUI button underneath.
279 return nil
280 }
281 }
282}
283
284// MARK: - Right Click Handler
285
286struct RightClickHandler: NSViewRepresentable {
287 let onRightClick: () -> Void
288
289 func makeNSView(context: Context) -> RightClickNSView {
290 let view = RightClickNSView()
291 view.onRightClick = onRightClick
292 return view
293 }
294
295 func updateNSView(_ nsView: RightClickNSView, context: Context) {
296 nsView.onRightClick = onRightClick
297 }
298
299 class RightClickNSView: NSView {
300 var onRightClick: (() -> Void)?
301
302 override func rightMouseDown(with event: NSEvent) {
303 onRightClick?()
304 }
305
306 override func hitTest(_ point: NSPoint) -> NSView? {
307 return frame.contains(point) ? self : nil
308 }
309 }
310}