import AppKit import HelderCore import SwiftUI enum MenuCursor { static func first(in entries: [ContextMenuEntry]) -> Int? { entries.firstIndex { $0 != .separator } } /// The next selectable entry in `step` direction, wrapping around and skipping separators. static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int { guard !entries.isEmpty else { return current } var index = current for _ in entries.indices { index = (index + step + entries.count) % entries.count if entries[index] != .separator { return index } } return current } } /// The colour an action's icon carries at rest. enum MenuIconTint: Equatable { /// text-4, amber when highlighted. case plain case add, modify, rename, danger var color: Color? { switch self { case .plain: nil case .add: Palette.menuIconAdd case .modify: Palette.menuIconModify case .rename: Palette.menuIconRename case .danger: Palette.removedText } } } /// When a mouse-down closes the menu: anywhere in the menu's window outside the menu itself. enum MenuDismissal { static func closes(clickAt point: CGPoint, menuBounds: CGRect, sameWindow: Bool) -> Bool { sameWindow && !menuBounds.contains(point) } } /// A right-click menu at the pointer: path header, then the actions; the first one is pre-highlighted. /// A click outside closes it and still reaches whatever was clicked. /// `onPerform` alone runs an item: the model closes the menu itself and reads its anchor to place what opens next. struct ContextMenuOverlay: View { let request: ContextMenuRequest var onPerform: (ContextAction) -> Void var onClose: () -> Void @State private var highlighted: Int? init(request: ContextMenuRequest, onPerform: @escaping (ContextAction) -> Void, onClose: @escaping () -> Void) { self.request = request self.onPerform = onPerform self.onClose = onClose _highlighted = State(initialValue: MenuCursor.first(in: request.entries)) } var body: some View { GeometryReader { proxy in menu .background(OverlayKeyCatcher(onKey: handle)) .background(OutsideClickMonitor(onOutside: onClose)) .offset(position(in: proxy.size)) } } private var menu: some View { ContextMenuPanel { if !request.header.isEmpty { ContextMenuHeader(request.header) } ForEach(Array(request.entries.enumerated()), id: \.offset) { index, entry in switch entry { case .separator: ContextMenuSeparator() case let .action(action, label): ContextMenuRow(label, systemImage: Self.symbol(for: action), iconTint: Self.tint(for: action).color, isHighlighted: highlighted == index, isDestructive: action.isDestructive) .onHover { inside in if inside { highlighted = index } } .onTapGesture { onPerform(action) } } } } } /// Keeps the menu inside the window. private func position(in size: CGSize) -> CGSize { let height = CGFloat(request.entries.count) * 34 + 60 let x = min(request.anchor.x, size.width - Metrics.contextMenuWidth - 8) let y = min(request.anchor.y, size.height - height) return CGSize(width: max(8, x), height: max(8, y)) } private func handle(_ key: OverlayKey) -> Bool { switch key { case .up, .commandUp: highlighted = MenuCursor.step(highlighted ?? -1, by: -1, in: request.entries) case .down, .commandDown: highlighted = MenuCursor.step(highlighted ?? -1, by: 1, in: request.entries) case .enter: if let highlighted, case let .action(action, _) = request.entries[highlighted] { onPerform(action) } case .escape: onClose() default: return false } return true } nonisolated static func tint(for action: ContextAction) -> MenuIconTint { switch action { case .copyReference, .copyTerminalSelection, .pasteIntoTerminal: .plain case .newFile, .newFolder, .stage: .add case .copyFileName, .unstage, .revealInFinder: .modify case .passOnReference, .passOnFileName, .bouwen, .openDiff, .showDiff, .rename: .rename case .discard, .delete: .danger } } nonisolated static func symbol(for action: ContextAction) -> String { switch action { case .passOnReference, .passOnFileName: ContextMenuRow.spark case .bouwen: "hammer" case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc" case .pasteIntoTerminal: "doc.on.clipboard" case .newFile: "doc.badge.plus" case .newFolder: "folder.badge.plus" case .stage: "plus" case .unstage: "minus" case .openDiff, .showDiff: "arrow.left.arrow.right" case .discard: "arrow.uturn.backward" case .rename: "pencil" case .revealInFinder: "folder" case .delete: "trash" } } } /// Watches mouse-downs in its window without consuming them; one outside its own bounds calls `onOutside`. private struct OutsideClickMonitor: NSViewRepresentable { var onOutside: () -> Void func makeNSView(context: Context) -> MonitorView { let view = MonitorView() view.onOutside = onOutside return view } func updateNSView(_ view: MonitorView, context: Context) { view.onOutside = onOutside } static func dismantleNSView(_ view: MonitorView, coordinator: ()) { view.stop() } final class MonitorView: NSView { var onOutside: () -> Void = {} private var monitor: Any? override func hitTest(_ point: NSPoint) -> NSView? { nil } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() stop() guard window != nil else { return } monitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]) { [weak self] event in guard let self else { return event } let point = self.convert(event.locationInWindow, from: nil) if MenuDismissal.closes(clickAt: point, menuBounds: self.bounds, sameWindow: event.window === self.window) { self.onOutside() } return event } } func stop() { if let monitor { NSEvent.removeMonitor(monitor) } monitor = nil } } }