From 8e8e94258608b8bf2f57635f050b130b270a045d Mon Sep 17 00:00:00 2001 From: Leslie Owusu-Appiah Date: Sun, 1 Nov 2026 18:28:18 +0100 Subject: [PATCH] feat(renderer): a right-click or Control-click on a node tells the host, for its menu (macOS) onNodeContextMenu is the Mac's twin of onNodeLongPress: a right-click or Control-click on a node reports the node, where the click was, the card's frame on screen and what a preview of it draws. A click on empty canvas reports nothing. The click comes from the same source as the trackpad double-tap: a host's ScrollWheelBridge, as onContextClick in the canvas's own coordinates, when it has one; otherwise the library's bridge, which watches context clicks window-wide only while a canvas has a host listening, and never consumes them, so anything else in the window keeps its own menu. Refs: #74 Co-Authored-By: Claude Opus 5.5 --- ios/WorkspaceJsonCanvasGesture.swift | 55 +++++++++++++++++++- ios/WorkspaceJsonCanvasGestureBridge.m | 3 ++ src/renderer/CanvasView.tsx | 72 ++++++++++++++++++++++---- src/renderer/NativeScrollWheelView.tsx | 18 ++++++- 4 files changed, 137 insertions(+), 11 deletions(-) diff --git a/ios/WorkspaceJsonCanvasGesture.swift b/ios/WorkspaceJsonCanvasGesture.swift index 9d7f9c7..048c45c 100644 --- a/ios/WorkspaceJsonCanvasGesture.swift +++ b/ios/WorkspaceJsonCanvasGesture.swift @@ -11,6 +11,11 @@ // wheel). Forwarded as `onScrollWheel` with `deltaX`/`deltaY`. RNGH's // `Gesture.Pan()` on macOS only sees click-and-drag mouse events. // +// - A right-click, or a Control-click (the Mac's context click). Forwarded +// as `onContextClick` with the same window-coord contract as +// `onSmartMagnify`, for a host's menu on a node (`onNodeContextMenu`). +// Opt-in, like hover. +// // - `NSEvent.EventType.mouseMoved` (pointer position, for hover). Forwarded // as `onMouseMoved` with the same window-coord contract as // `onSmartMagnify`. RNGH's macOS hover handler reports only @@ -58,6 +63,12 @@ class WorkspaceJsonCanvasGesture: RCTEventEmitter { // the window, where the other two fire only on deliberate gestures. A // consumer that never reveals anything on hover shouldn't pay for that. private var mouseMovedMonitor: Any? + + // Context clicks: opt-in (`setContextClickTracking`), counted, since every + // canvas on screen with a host's menu asks for them and one leaving must + // not stop them for the rest. + private var contextClickMonitor: Any? + private var contextClickUsers = 0 private var lastHoverEmit: TimeInterval = 0 // Explicit CGFloat: NSPoint's initialisers are overloaded, so a bare // `.greatestFiniteMagnitude` is ambiguous and fails to compile. @@ -84,7 +95,7 @@ class WorkspaceJsonCanvasGesture: RCTEventEmitter { @objc override static func requiresMainQueueSetup() -> Bool { true } override func supportedEvents() -> [String] { - ["onSmartMagnify", "onScrollWheel", "onMouseMoved"] + ["onSmartMagnify", "onScrollWheel", "onMouseMoved", "onContextClick"] } /// Start / stop forwarding pointer positions as `onMouseMoved`. @@ -105,6 +116,45 @@ class WorkspaceJsonCanvasGesture: RCTEventEmitter { } } + /// Start / stop forwarding context clicks as `onContextClick`. Each call + /// with `true` is matched by one with `false`; the monitor stays while any + /// canvas wants it. + @objc func setContextClickTracking(_ enabled: Bool) { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + self.contextClickUsers = max(0, self.contextClickUsers + (enabled ? 1 : -1)) + if self.contextClickUsers > 0 { + self.installContextClickMonitor() + } else if let monitor = self.contextClickMonitor { + NSEvent.removeMonitor(monitor) + self.contextClickMonitor = nil + } + } + } + + private func installContextClickMonitor() { + guard contextClickMonitor == nil else { return } + contextClickMonitor = NSEvent.addLocalMonitorForEvents( + matching: [.rightMouseDown, .leftMouseDown] + ) { [weak self] event in + guard let self = self, self.hasListeners else { return event } + // A Control-click is the Mac's other context click; a plain click isn't one. + if event.type == .leftMouseDown && !event.modifierFlags.contains(.control) { return event } + // The main window only: a click in a panel or sheet is over something + // else, whatever its coordinates say. + guard let window = event.window, window.isMainWindow, + let windowHeight = window.contentView?.bounds.height else { return event } + let pointInWindow = event.locationInWindow + self.sendEvent(withName: "onContextClick", body: [ + "x": pointInWindow.x, + "y": windowHeight - pointInWindow.y, + ]) + // Never consume: the canvas decides in JS whether a node is under the + // click, and anything else in the window keeps its own context menu. + return event + } + } + // `RCTEventEmitter` calls these as JS-side `addListener` / `removeListener` // calls arrive. Tracks observer count so we don't waste cycles maintaining // a global event monitor when no JS listener is attached. @@ -286,6 +336,9 @@ class WorkspaceJsonCanvasGesture: RCTEventEmitter { deinit { removeMonitors() + if let monitor = contextClickMonitor { + NSEvent.removeMonitor(monitor) + } } } diff --git a/ios/WorkspaceJsonCanvasGestureBridge.m b/ios/WorkspaceJsonCanvasGestureBridge.m index 620ebe5..f15c6e8 100644 --- a/ios/WorkspaceJsonCanvasGestureBridge.m +++ b/ios/WorkspaceJsonCanvasGestureBridge.m @@ -18,6 +18,9 @@ @interface RCT_EXTERN_MODULE(WorkspaceJsonCanvasGesture, RCTEventEmitter) // class for why it isn't tied to the emitter's listener lifecycle. RCT_EXTERN_METHOD(setHoverTracking:(BOOL)enabled) +// Context clicks (`onContextClick`) are opt-in too, for a host's node menu. +RCT_EXTERN_METHOD(setContextClickTracking:(BOOL)enabled) + @end #endif diff --git a/src/renderer/CanvasView.tsx b/src/renderer/CanvasView.tsx index a2eca44..b8621fc 100644 --- a/src/renderer/CanvasView.tsx +++ b/src/renderer/CanvasView.tsx @@ -18,6 +18,8 @@ import { jsonCanvasGestureEvents, scrollWheelEvents, setHoverTracking, + setContextClickTracking, + type ContextClickEvent, type MouseMovedEvent, type ScrollWheelEvent, type SmartMagnifyEvent, @@ -156,6 +158,15 @@ interface Props { * itself: the menu says it. Without one, a long-press reveals the name. */ onNodeLongPress?: (node: CanvasNode, press: NodeLongPress) => void; + /** + * A node was right-clicked or Control-clicked (the Mac): where a host + * shows its own context menu for the node, told as `onNodeLongPress` is. + * A click on empty canvas, or over the left overlay, reports nothing. A + * host with its own `ScrollWheelBridge` sends the clicks itself, as + * `onContextClick` in the canvas's coordinates; otherwise the library's + * bridge watches the window for them. + */ + onNodeContextMenu?: (node: CanvasNode, press: NodeLongPress) => void; /** * A strip along the view's left edge, in points, where a drag doesn't pan * the canvas but is left to the system: iOS's swipe back, when the canvas @@ -224,7 +235,7 @@ const CAMERA_ANIM_DURATION_MS = 300; * break rendering). Content changes flow through React reconciliation via * useMemo/useLayoutEffect on the content prop. */ -export function CanvasView({content, basePath, initialViewState, onViewStateChange, onReady, doubleTapMaxDelayMs, minimap = 'bottom-right', minimapBottomInset = 0, safeAreaInsets, leftOverlayWidth, minimapBackground, minimapCornerRadius, minimapSize, imageNames = 'onReveal', onNodeLongPress, systemEdge = 0}: Props) { +export function CanvasView({content, basePath, initialViewState, onViewStateChange, onReady, doubleTapMaxDelayMs, minimap = 'bottom-right', minimapBottomInset = 0, safeAreaInsets, leftOverlayWidth, minimapBackground, minimapCornerRadius, minimapSize, imageNames = 'onReveal', onNodeLongPress, onNodeContextMenu, systemEdge = 0}: Props) { // `useWindowDimensions` returns the whole application window — on desktop // that includes the sidebar pane that sits to the left of the canvas // viewport. Computing "centre" against full-window dimensions lands the @@ -901,25 +912,68 @@ export function CanvasView({content, basePath, initialViewState, onViewStateChan const nameRevealed = useSharedValue(false); const onNodeLongPressRef = useRef(onNodeLongPress); onNodeLongPressRef.current = onNodeLongPress; - const revealAt = useCallback((x: number, y: number) => { + /** The node under a point in the view (smallest-area-wins, as double-tap and hover: a file node in a group means the file node). */ + const nodeAt = useCallback((x: number, y: number): CanvasNode | null => { const wx = (x - translateX.value) / scale.value; const wy = (y - translateY.value) / scale.value; const hits = canvasState?.hitTest(wx, wy) ?? []; - // Smallest-area-wins, as double-tap and hover: a file node in a group means the file node. - const hit = hits.length > 0 ? hits.reduce((a, b) => (a.width * a.height < b.width * b.height ? a : b)) : null; + return hits.length > 0 ? hits.reduce((a, b) => (a.width * a.height < b.width * b.height ? a : b)) : null; + }, [canvasState, translateX, translateY, scale]); + /** A press on `node` at a point in the view, as a host is told it. */ + const pressOn = useCallback((node: CanvasNode, x: number, y: number): NodeLongPress | null => { + if (!canvasState) return null; + const s = scale.value; + const frame = {x: node.x * s + translateX.value, y: node.y * s + translateY.value, width: node.width * s, height: node.height * s}; + return {at: {x, y}, frame, contents: nodeContents(node, canvasState)}; + }, [canvasState, translateX, translateY, scale]); + const revealAt = useCallback((x: number, y: number) => { + const hit = nodeAt(x, y); const host = onNodeLongPressRef.current; if (host) { - if (!hit || !canvasState) return; - const s = scale.value; - const frame = {x: hit.x * s + translateX.value, y: hit.y * s + translateY.value, width: hit.width * s, height: hit.height * s}; - host(hit, {at: {x, y}, frame, contents: nodeContents(hit, canvasState)}); + const press = hit ? pressOn(hit, x, y) : null; + if (hit && press) host(hit, press); return; } const fileId = hit?.type === 'file' ? hit.id : null; hoveredFileNodeIdRef.current = fileId; setHoveredFileNodeId(fileId); nameRevealed.value = fileId !== null; - }, [canvasState, translateX, translateY, scale, nameRevealed]); + }, [nodeAt, pressOn, nameRevealed]); + + // Right-click or Control-click, on the Mac: tells the host (its own + // context menu), as a long-press does on a touch screen. From the same + // source as the trackpad double-tap: a host's `ScrollWheelBridge` if it + // has one, in the canvas's own coordinates and only for clicks on it; + // else the library's bridge, window-wide (asked for only while a host + // listens), less the canvas's place in the window. + const onNodeContextMenuRef = useRef(onNodeContextMenu); + onNodeContextMenuRef.current = onNodeContextMenu; + const wantsContextClicks = onNodeContextMenu !== undefined; + useEffect(() => { + const source = scrollWheelEvents ?? jsonCanvasGestureEvents; + if (!source || !wantsContextClicks) return; + const isLibraryBridge = source === jsonCanvasGestureEvents; + if (isLibraryBridge) setContextClickTracking(true); + const sub = source.addListener('onContextClick', (raw: unknown) => { + const event = raw as ContextClickEvent; + let x = event.x; + let y = event.y; + if (isLibraryBridge) { + const origin = canvasOriginRef.current; + x -= origin.x; + y -= origin.y; + if (x < (leftOverlayWidth?.value ?? 0) || y < 0 || x > origin.width || y > origin.height) return; + } + const host = onNodeContextMenuRef.current; + const hit = nodeAt(x, y); + const press = hit ? pressOn(hit, x, y) : null; + if (host && hit && press) host(hit, press); + }); + return () => { + sub.remove(); + if (isLibraryBridge) setContextClickTracking(false); + }; + }, [wantsContextClicks, nodeAt, pressOn, leftOverlayWidth]); const hideRevealed = useCallback(() => { if (Platform.OS === 'macos') return; // the Mac's chip follows the pointer hoveredFileNodeIdRef.current = null; diff --git a/src/renderer/NativeScrollWheelView.tsx b/src/renderer/NativeScrollWheelView.tsx index 4c948c1..906a22b 100644 --- a/src/renderer/NativeScrollWheelView.tsx +++ b/src/renderer/NativeScrollWheelView.tsx @@ -71,7 +71,8 @@ export const scrollWheelEvents = ScrollWheelBridge ? new NativeEventEmitter(ScrollWheelBridge) : null; -// Library-shipped gesture bridge. Emits two events: +// Library-shipped gesture bridge. Emits these events (and `onMouseMoved` and +// `onContextClick` while asked for, below): // // - `onSmartMagnify` — trackpad two-finger double-tap (Safari Smart Zoom), // consumed by the canvas to drive zoom-to-node. @@ -99,3 +100,18 @@ export const jsonCanvasGestureEvents = JsonCanvasGestureModule export function setHoverTracking(enabled: boolean): void { JsonCanvasGestureModule?.setHoverTracking(enabled); } + +/** + * Start / stop `onContextClick` delivery (a right-click or a Control-click, + * in window coordinates with a top-left origin). No-op off macOS. Counted: + * each `true` is matched by a `false`. + */ +export function setContextClickTracking(enabled: boolean): void { + JsonCanvasGestureModule?.setContextClickTracking?.(enabled); +} + +/** A context click, as `onContextClick` sends it: window coordinates, top-left origin. */ +export interface ContextClickEvent { + x: number; + y: number; +}