SPB Git

Repository Public

AuraGestures.swift 8.2 KB 200 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Browser9// File             : SPBrowser/Shared/Aura/Features/AuraGestures.swift10// Module           : SPBrowser11// Repository       : https://git.spboucher.ai/sp-browser12// Created          : 2026-11-1913// Last Modified    : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import SwiftUI88#if os(macOS)89import AppKit90#endif9192/// Pan and zoom state shared by the spatial surfaces (Constellation, Canvas). Gestures track the fingers directly;93/// when they end the viewport settles with the `interactive` spring.94struct AuraViewport: Equatable {95    var scale: CGFloat = 196    var offset: CGSize = .zero97    /// Values at the start of the gesture in progress.98    var baseScale: CGFloat?99    var baseOffset: CGSize?100101    mutating func pan(by translation: CGSize) {102        if baseOffset == nil { baseOffset = offset }103        offset = CGSize(width: baseOffset!.width + translation.width, height: baseOffset!.height + translation.height)104    }105106    mutating func endPan() { baseOffset = nil }107108    /// Zooms around `anchor` (a point of the view, relative to its centre) so the content under the fingers stays put.109    mutating func zoom(by factor: CGFloat, anchor: CGPoint = .zero, range: ClosedRange<CGFloat>) {110        if baseScale == nil { baseScale = scale; baseOffset = offset }111        let target = min(max(baseScale! * factor, range.lowerBound), range.upperBound)112        let ratio = target / baseScale!113        offset = CGSize(width: anchor.x - (anchor.x - baseOffset!.width) * ratio, height: anchor.y - (anchor.y - baseOffset!.height) * ratio)114        scale = target115    }116117    mutating func endZoom() { baseScale = nil; baseOffset = nil }118119    mutating func step(_ factor: CGFloat, range: ClosedRange<CGFloat>) {120        let target = min(max(scale * factor, range.lowerBound), range.upperBound)121        let ratio = target / scale122        offset = CGSize(width: offset.width * ratio, height: offset.height * ratio)123        scale = target124    }125}126127#if os(macOS)128/// Two-finger scrolling and ⌘-scroll over a SwiftUI view. SwiftUI has no scroll-wheel event, so a local monitor is installed129/// while the view is on screen; events outside the view's frame are left alone.130private struct ScrollWheelReader: NSViewRepresentable {131    let handler: (CGSize, Bool) -> Void132133    func makeNSView(context: Context) -> ProbeView { ProbeView() }134    func updateNSView(_ view: ProbeView, context: Context) { view.handler = handler }135    static func dismantleNSView(_ view: ProbeView, coordinator: ()) { view.stop() }136137    final class ProbeView: NSView {138        var handler: ((CGSize, Bool) -> Void)?139        private var monitor: Any?140141        override func viewDidMoveToWindow() {142            super.viewDidMoveToWindow()143            stop()144            guard window != nil else { return }145            monitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in146                guard let self, let window = self.window, event.window === window else { return event }147                let point = self.convert(event.locationInWindow, from: nil)148                guard self.bounds.contains(point) else { return event }149                let precise = event.hasPreciseScrollingDeltas150                self.handler?(CGSize(width: event.scrollingDeltaX * (precise ? 1 : 8), height: event.scrollingDeltaY * (precise ? 1 : 8)),151                              event.modifierFlags.contains(.command))152                return nil153            }154        }155156        func stop() { if let monitor { NSEvent.removeMonitor(monitor) }; monitor = nil }157        override func hitTest(_ point: NSPoint) -> NSView? { nil }158    }159}160#endif161162extension View {163    /// Reports trackpad / wheel scrolling over the view (Mac only). The Boolean is true while ⌘ is held (zoom).164    @ViewBuilder func onScrollWheel(_ handler: @escaping (CGSize, Bool) -> Void) -> some View {165        #if os(macOS)166        background(ScrollWheelReader(handler: handler))167        #else168        self169        #endif170    }171}172173/// A dotted grid that scales with the viewport: gives the eye something to hold on to while panning.174struct AuraGrid: View {175    var viewport: AuraViewport176    var spacing: CGFloat = 32177178    var body: some View {179        Canvas(opaque: false, rendersAsynchronously: true) { context, size in180            var step = spacing * viewport.scale181            while step < 18 { step *= 2 }182            let originX = (size.width / 2 + viewport.offset.width).truncatingRemainder(dividingBy: step)183            let originY = (size.height / 2 + viewport.offset.height).truncatingRemainder(dividingBy: step)184            var path = Path()185            var x = originX - step186            while x < size.width + step {187                var y = originY - step188                while y < size.height + step {189                    path.addEllipse(in: CGRect(x: x - 1, y: y - 1, width: 2, height: 2))190                    y += step191                }192                x += step193            }194            context.fill(path, with: .color(Color.primary.opacity(0.10)))195        }196        .accessibilityHidden(true)197        .allowsHitTesting(false)198    }199}200
Files main
Menu

Theme