Skip to content

Instantly share code, notes, and snippets.

@duemunk
Last active February 16, 2023 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duemunk/f949190c9fa91e747776021c7197f737 to your computer and use it in GitHub Desktop.
Save duemunk/f949190c9fa91e747776021c7197f737 to your computer and use it in GitHub Desktop.
import SwiftUI
struct Cursor: Equatable {
let ns: NSCursor?
let id: String
}
struct CursorPreference: PreferenceKey {
typealias Value = [Cursor]
static var defaultValue: Value = []
static func reduce(value: inout Value, nextValue: () -> Value) {
let newCursors = nextValue()
guard let newCursor = newCursors.first else { return }
value.removeAll {
$0.id == newCursor.id
}
if newCursor.ns != nil {
value.append(newCursor)
}
}
}
extension View {
func cursor(type ns: NSCursor?, id: String) -> some View {
preference(key: CursorPreference.self, value: [Cursor(ns: ns, id: id)])
}
}
struct CursorReader: ViewModifier {
@State private var cursors: [Cursor] = [] {
didSet {
handle(current: oldValue.last, new: cursors.last)
}
}
func body(content: Content) -> some View {
content
.onPreferenceChange(CursorPreference.self) {
cursors = $0
}
}
private func handle(current: Cursor?, new: Cursor?) {
if let current = current?.ns {
current.pop()
}
if let new = new?.ns {
NSApp.windows.forEach { $0.disableCursorRects() }
new.push()
}
if new?.ns == nil {
NSApp.windows.forEach { $0.enableCursorRects() }
}
}
}
extension View {
func enableCursors() -> some View {
modifier(CursorReader())
}
}
//struct CursorModifier: ViewModifier {
//
// struct IdCursor: Equatable {
// let cursor: NSCursor
// let id: Int
// }
//
// var cursor: IdCursor?
//
// func body(content: Content) -> some View {
// content
// .onChange(of: cursor) { [current = cursor] new in
// if let current = current {
// current.cursor.pop()
// }
// if let new = new {
// NSApp.windows.forEach { $0.disableCursorRects() }
// new.cursor.push()
// }
// if new == nil, current?.cursor == NSCursor.current {
// NSApp.windows.forEach { $0.enableCursorRects() }
// }
// }
// }
//}
//extension View {
// func cursor(_ cursor: NSCursor?, id: Int) -> some View {
// modifier(CursorModifier(cursor: cursor.flatMap { .init(cursor: $0, id: id) }))
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment