-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathNotchViewModel.swift
More file actions
338 lines (286 loc) · 10.7 KB
/
Copy pathNotchViewModel.swift
File metadata and controls
338 lines (286 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//
// NotchViewModel.swift
// ClaudeIsland
//
// State management for the dynamic island
//
import AppKit
import Combine
import SwiftUI
enum NotchStatus: Equatable {
case closed
case opened
case popping
}
enum NotchOpenReason {
case click
case hover
case notification
case boot
case unknown
}
enum NotchContentType: Equatable {
case instances
case menu
case chat(SessionState)
var id: String {
switch self {
case .instances: return "instances"
case .menu: return "menu"
case .chat(let session): return "chat-\(session.sessionId)"
}
}
}
@MainActor
class NotchViewModel: ObservableObject {
// MARK: - Published State
@Published var status: NotchStatus = .closed
@Published var openReason: NotchOpenReason = .unknown
@Published var contentType: NotchContentType = .instances
@Published var isHovering: Bool = false
/// Set by NotchView — prevents auto-dismiss when permissions need attention
@Published var hasPendingPermissions: Bool = false
/// The session ID currently targeted by keyboard shortcuts
@Published var selectedPendingSessionId: String?
// MARK: - Dependencies
private let screenSelector = ScreenSelector.shared
private let soundSelector = SoundSelector.shared
// MARK: - Geometry
let geometry: NotchGeometry
let spacing: CGFloat = 12
let hasPhysicalNotch: Bool
var deviceNotchRect: CGRect { geometry.deviceNotchRect }
var screenRect: CGRect { geometry.screenRect }
var windowHeight: CGFloat { geometry.windowHeight }
/// Number of instances, set externally by NotchView to drive dynamic sizing
@Published var instanceCount: Int = 0
/// Dynamic opened size based on content type
var openedSize: CGSize {
switch contentType {
case .chat:
// Large size for chat view
return CGSize(
width: min(screenRect.width * 0.5, 600),
height: 580
)
case .menu:
// Compact size for settings menu
return CGSize(
width: min(screenRect.width * 0.4, 480),
height: 420 + screenSelector.expandedPickerHeight + soundSelector.expandedPickerHeight
)
case .instances:
// Dynamic height: ~52pt per row + 60pt for header/padding, clamped
let rowHeight: CGFloat = 52
let chrome: CGFloat = 60
let contentHeight = CGFloat(max(instanceCount, 1)) * rowHeight + chrome
return CGSize(
width: min(screenRect.width * 0.4, 480),
height: min(max(contentHeight, 120), 400)
)
}
}
// MARK: - Pending Selection
/// Keep selection in sync when pending sessions change.
/// Auto-selects first if current selection is no longer valid.
func reconcilePendingSelection(pendingSessionIds: [String]) {
if pendingSessionIds.isEmpty {
selectedPendingSessionId = nil
return
}
if let selected = selectedPendingSessionId, pendingSessionIds.contains(selected) {
return
}
selectedPendingSessionId = pendingSessionIds.first
}
/// Cycle selection through pending sessions. direction: +1 = next, -1 = prev.
func cyclePendingSelection(direction: Int, pendingSessionIds: [String]) {
guard pendingSessionIds.count > 1 else { return }
guard let current = selectedPendingSessionId,
let currentIndex = pendingSessionIds.firstIndex(of: current) else {
selectedPendingSessionId = pendingSessionIds.first
return
}
let nextIndex = (currentIndex + direction + pendingSessionIds.count) % pendingSessionIds.count
selectedPendingSessionId = pendingSessionIds[nextIndex]
}
// MARK: - Animation
var animation: Animation {
.easeOut(duration: 0.25)
}
// MARK: - Private
private var cancellables = Set<AnyCancellable>()
private let events = EventMonitors.shared
private var hoverTimer: DispatchWorkItem?
// MARK: - Initialization
init(deviceNotchRect: CGRect, screenRect: CGRect, windowHeight: CGFloat, hasPhysicalNotch: Bool) {
self.geometry = NotchGeometry(
deviceNotchRect: deviceNotchRect,
screenRect: screenRect,
windowHeight: windowHeight
)
self.hasPhysicalNotch = hasPhysicalNotch
setupEventHandlers()
observeSelectors()
}
private func observeSelectors() {
screenSelector.$isPickerExpanded
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
soundSelector.$isPickerExpanded
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
}
// MARK: - Event Handling
private func setupEventHandlers() {
events.mouseLocation
.throttle(for: .milliseconds(50), scheduler: DispatchQueue.main, latest: true)
.sink { [weak self] location in
self?.handleMouseMove(location)
}
.store(in: &cancellables)
events.mouseDown
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.handleMouseDown()
}
.store(in: &cancellables)
}
/// Whether we're in chat mode (sticky behavior)
private var isInChatMode: Bool {
if case .chat = contentType { return true }
return false
}
/// The chat session we're viewing (persists across close/open)
private var currentChatSession: SessionState?
private func handleMouseMove(_ location: CGPoint) {
let inNotch = geometry.isPointInNotch(location)
let inOpened = status == .opened && geometry.isPointInOpenedPanel(location, size: openedSize)
let newHovering = inNotch || inOpened
// Only update if changed to prevent unnecessary re-renders
guard newHovering != isHovering else { return }
isHovering = newHovering
// Cancel any pending hover timer
hoverTimer?.cancel()
hoverTimer = nil
// Start hover timer to auto-expand after 1 second
if isHovering && (status == .closed || status == .popping) {
let workItem = DispatchWorkItem { [weak self] in
guard let self = self, self.isHovering else { return }
self.notchOpen(reason: .hover)
}
hoverTimer = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: workItem)
}
}
private func handleMouseDown() {
let location = NSEvent.mouseLocation
switch status {
case .opened:
if geometry.isPointOutsidePanel(location, size: openedSize) {
// Stay open if there are pending permissions — the user
// needs to approve/deny before the island can dismiss
if hasPendingPermissions {
repostClickAt(location)
} else {
notchClose()
repostClickAt(location)
}
} else if geometry.notchScreenRect.contains(location) {
// Clicking notch while opened - only close if NOT in chat mode
if !isInChatMode {
notchClose()
}
}
case .closed, .popping:
if geometry.isPointInNotch(location) {
notchOpen(reason: .click)
}
}
}
/// Re-posts a mouse click at the given screen location so it reaches windows behind us
private func repostClickAt(_ location: CGPoint) {
// Small delay to let the window's ignoresMouseEvents update
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
// Convert to CGEvent coordinate system (screen coordinates with Y from top-left)
guard let screen = NSScreen.main else { return }
let screenHeight = screen.frame.height
let cgPoint = CGPoint(x: location.x, y: screenHeight - location.y)
// Create and post mouse down event
if let mouseDown = CGEvent(
mouseEventSource: nil,
mouseType: .leftMouseDown,
mouseCursorPosition: cgPoint,
mouseButton: .left
) {
mouseDown.post(tap: .cghidEventTap)
}
// Create and post mouse up event
if let mouseUp = CGEvent(
mouseEventSource: nil,
mouseType: .leftMouseUp,
mouseCursorPosition: cgPoint,
mouseButton: .left
) {
mouseUp.post(tap: .cghidEventTap)
}
}
}
// MARK: - Actions
func notchOpen(reason: NotchOpenReason = .unknown) {
openReason = reason
status = .opened
// Don't restore chat on notification - show instances list instead
if reason == .notification {
currentChatSession = nil
return
}
// Restore chat session if we had one open before
if let chatSession = currentChatSession {
// Avoid unnecessary updates if already showing this chat
if case .chat(let current) = contentType, current.sessionId == chatSession.sessionId {
return
}
contentType = .chat(chatSession)
}
}
func notchClose() {
// Save chat session before closing if in chat mode
if case .chat(let session) = contentType {
currentChatSession = session
}
status = .closed
contentType = .instances
}
func notchPop() {
guard status == .closed else { return }
status = .popping
}
func notchUnpop() {
guard status == .popping else { return }
status = .closed
}
func toggleMenu() {
contentType = contentType == .menu ? .instances : .menu
}
func showChat(for session: SessionState) {
// Avoid unnecessary updates if already showing this chat
if case .chat(let current) = contentType, current.sessionId == session.sessionId {
return
}
contentType = .chat(session)
}
/// Go back to instances list and clear saved chat state
func exitChat() {
currentChatSession = nil
contentType = .instances
}
/// Perform boot animation: expand briefly then collapse
func performBootAnimation() {
notchOpen(reason: .boot)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
guard let self = self, self.openReason == .boot else { return }
self.notchClose()
}
}
}