how to make a buddy window that follows your mouse swiftui in swift

To create a buddy window that follows your mouse in SwiftUI on macOS, you can use an NSPanel as a floating window and track the mouse movements to update its position.

Here is a sample implementation:

main.swift
import SwiftUI

struct ContentView: View {
    @State private var isPanelVisible = false
    @State private var mouseLocation = CGPoint.zero
    
    var body: some View {
        VStack {
            Text("Move your mouse around")
            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
        .onHover(perform: { hovering in
            self.isPanelVisible = hovering
        })
        .onMove(perform: { location in
            self.mouseLocation = location
        })
        .overlay(BuddyWindow(isVisible: self.$isPanelVisible, mouseLocation: self.mouseLocation))
    }
}

struct BuddyWindow: NSViewRepresentable {
    @Binding var isVisible: Bool
    var mouseLocation: CGPoint
    
    func makeNSView(context: Context) -> NSView {
        let view = NSView(frame: .zero)
        view.wantsLayer = true
        return view
    }
    
    func updateNSView(_ nsView: NSView, context: Context) {
        if self.isVisible {
            let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 100, height: 100),
                                styleMask: .nonactivatingPanel,
                                backing: .buffered,
                                defer: false)
            panel.level = .floating
            panel.collectionBehavior = .stationary
            panel.contentViewController = NSViewController()
            panel.contentViewController?.view = NSView(frame: NSRect(x: 0, y: 0, width: 50, height: 50))
            panel.contentView?.wantsLayer = true
            panel.contentView?.layer?.backgroundColor = NSColor.yellow.cgColor
            panel.setFrameOrigin(NSPoint(x: self.mouseLocation.x + 20, y: self.mouseLocation.y + 20))
            panel.orderFront(nil)
        }
    }
}
1785 chars
51 lines

In this implementation, the ContentView displays some text and sets up mouse tracking with the onHover and onMove modifiers. The isPanelVisible state variable controls the visibility of the BuddyWindow overlay.

The BuddyWindow is an NSViewRepresentable that creates and configures an NSPanel with a yellow layer background. The isVisible and mouseLocation properties are used to show or hide and position the panel based on the current mouse location.

You can customize the panel size, color, and content view as needed.

gistlibby LogSnag