Floating Shelf: a macOS shelf at the edge of the screen for holding files, images and text while you move between apps.

0 downloads

dbbasic-floating-shelf/FloatingShelf/FloatingShelfWindow.swift
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-floating-shelf.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-floating-shelf.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-floating-shelf.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add MIT License 76c5d29 1 year ago History
FloatingShelfWindow.swift · 2.1 KB · 73 lines
1import SwiftUI
2import AppKit
3
4class FloatingShelfWindow: NSObject {
5 private var window: NSWindow?
6 private var shelfController: ShelfViewController?
7
8 override init() {
9 super.init()
10 setupWindow()
11 }
12
13 private func setupWindow() {
14 // Create a borderless, floating window
15 let window = NSWindow(
16 contentRect: NSRect(x: 0, y: 0, width: 400, height: 500),
17 styleMask: [.borderless, .nonactivatingPanel],
18 backing: .buffered,
19 defer: false
20 )
21
22 window.isOpaque = false
23 window.backgroundColor = .clear
24 window.level = .floating
25 window.collectionBehavior = [.canJoinAllSpaces, .stationary]
26 window.isMovableByWindowBackground = false
27 window.hasShadow = true
28
29 // Create and set the content view
30 shelfController = ShelfViewController()
31 window.contentView = NSHostingView(rootView: ShelfView(controller: shelfController!))
32
33 self.window = window
34 }
35
36 func show(at location: CGPoint) {
37 guard let window = window else { return }
38
39 // Position window near the mouse
40 let windowFrame = window.frame
41 var origin = location
42 origin.x -= windowFrame.width / 2
43 origin.y -= windowFrame.height / 2
44
45 // Ensure window stays on screen
46 if let screen = NSScreen.main {
47 let screenFrame = screen.visibleFrame
48 origin.x = max(screenFrame.minX, min(origin.x, screenFrame.maxX - windowFrame.width))
49 origin.y = max(screenFrame.minY, min(origin.y, screenFrame.maxY - windowFrame.height))
50 }
51
52 window.setFrameOrigin(origin)
53 window.orderFrontRegardless()
54 }
55
56 func hide() {
57 window?.orderOut(nil)
58 }
59
60 func toggle() {
61 if window?.isVisible == true {
62 hide()
63 } else {
64 if let screen = NSScreen.main {
65 let center = CGPoint(
66 x: screen.frame.midX,
67 y: screen.frame.midY
68 )
69 show(at: center)
70 }
71 }
72 }
73}