Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 54 additions & 1 deletion ios/WorkspaceJsonCanvasGesture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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`.
Expand All @@ -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.
Expand Down Expand Up @@ -286,6 +336,9 @@ class WorkspaceJsonCanvasGesture: RCTEventEmitter {

deinit {
removeMonitors()
if let monitor = contextClickMonitor {
NSEvent.removeMonitor(monitor)
}
}
}

Expand Down
3 changes: 3 additions & 0 deletions ios/WorkspaceJsonCanvasGestureBridge.m
Original file line number Diff line number Diff line change
Expand Up @@ -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
72 changes: 63 additions & 9 deletions src/renderer/CanvasView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
jsonCanvasGestureEvents,
scrollWheelEvents,
setHoverTracking,
setContextClickTracking,
type ContextClickEvent,
type MouseMovedEvent,
type ScrollWheelEvent,
type SmartMagnifyEvent,
Expand Down Expand Up @@ -156,6 +158,15 @@
* 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
Expand Down Expand Up @@ -224,7 +235,7 @@
* 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
Expand Down Expand Up @@ -536,7 +547,7 @@
// (handleDoubleTap, tapGesture) does NOT recompose when the sidebar
// changes. That's load-bearing for #154 — earlier attempts that put
// sidebar state in deps regressed double-tap.
const fitToViewport = useCallback((leftOverlayWidth: number = 0) => {

Check warning on line 550 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 238 column 181
lastActionRef.current = 'fit';
const sw = viewportWidth;
const sh = viewportHeight;
Expand Down Expand Up @@ -570,7 +581,7 @@
// from `leftOverlayWidth` and passes it here per call. Kept as a parameter, not
// a closure dep, to preserve callback identity — see the matching
// discussion above `fitToViewport`.
const zoomToNode = useCallback((node: CanvasNode, leftOverlayWidth: number = 0) => {

Check warning on line 584 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 238 column 181
const sw = viewportWidth;
const sh = viewportHeight;
const visibleW = Math.max(1, sw - leftOverlayWidth);
Expand Down Expand Up @@ -643,7 +654,7 @@

// Recenter content at current zoom level, against the visible canvas pane.
// See `fitToViewport` for the leftOverlayWidth rationale.
const recenter = useCallback((leftOverlayWidth: number = 0) => {

Check warning on line 657 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 238 column 181
lastActionRef.current = 'recenter';
const sw = viewportWidth;
const sh = viewportHeight;
Expand Down Expand Up @@ -713,8 +724,8 @@

useEffect(() => {
onReady?.({
fitToViewport: (leftOverlayWidth?: number) => fitRef.current(leftOverlayWidth),

Check warning on line 727 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 238 column 181
recenter: (leftOverlayWidth?: number) => recenterRef.current(leftOverlayWidth),

Check warning on line 728 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 238 column 181
getLastAction: () => lastActionRef.current,
camera: {translateX, translateY, scale, isPinching},
find,
Expand Down Expand Up @@ -901,25 +912,68 @@
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;
Expand Down
18 changes: 17 additions & 1 deletion src/renderer/NativeScrollWheelView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
Loading