aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Sources/bar/Views/BlockView.swift38
1 files changed, 20 insertions, 18 deletions
diff --git a/Sources/bar/Views/BlockView.swift b/Sources/bar/Views/BlockView.swift
index 85d6e6e..4158f85 100644
--- a/Sources/bar/Views/BlockView.swift
+++ b/Sources/bar/Views/BlockView.swift
@@ -4,6 +4,7 @@ struct BlockView: View {
@ObservedObject var block: Block
@State private var hovering = false
+ @State private var eventsMonitor: Any?
var body: some View {
HStack(spacing: 0) {
@@ -13,43 +14,44 @@ struct BlockView: View {
}
.onHover { hovering = $0 }
.onAppear {
- NSEvent.addLocalMonitorForEvents(matching: [
+ let monitor = NSEvent.addLocalMonitorForEvents(matching: [
.leftMouseDown,
.rightMouseDown,
.otherMouseDown,
.scrollWheel,
- ]) { event in
- handle(event: event)
+ ]) { [weak block] event in
+ guard let block else { return event }
+ return handle(event: event, block: block)
+ }
+ self.eventsMonitor = monitor as Any
+ }
+ .onDisappear {
+ if let eventsMonitor {
+ NSEvent.removeMonitor(eventsMonitor)
+ self.eventsMonitor = nil
}
}
}
- private func handle(event: NSEvent) -> NSEvent {
+ /// Processes an event when the block is hovered, re-running the script
+ /// with the appropriate environment variable.
+ ///
+ /// - Returns: The original event so the system continues normal delivery.
+ private func handle(event: NSEvent, block: Block) -> NSEvent {
guard hovering else { return event }
switch event.type {
case .leftMouseDown, .rightMouseDown, .otherMouseDown:
block.runScript(env: ["BUTTON": String(event.buttonNumber)])
- break
case .scrollWheel:
if event.scrollingDeltaY > 0 {
block.runScript(env: ["SCROLL": "UP"])
- break
- }
-
- if event.scrollingDeltaY < 0 {
+ } else if event.scrollingDeltaY < 0 {
block.runScript(env: ["SCROLL": "DOWN"])
- break
- }
-
- if event.scrollingDeltaX > 0 {
+ } else if event.scrollingDeltaX > 0 {
block.runScript(env: ["SCROLL": "RIGHT"])
- break
- }
-
- if event.scrollingDeltaX < 0 {
+ } else if event.scrollingDeltaX < 0 {
block.runScript(env: ["SCROLL": "LEFT"])
- break
}
default:
break