Partial Fix: Parallax Effect

This commit is contained in:
Hariharan Mudaliar 2025-12-29 20:06:16 +05:30
commit 8b5b60efc6
No known key found for this signature in database
GPG key ID: 025583EB0BE5640E
3 changed files with 56 additions and 27 deletions

View file

@ -6,51 +6,57 @@
//
import SwiftUI
import AppKit
import Defaults
struct ParallaxMotionModifier: ViewModifier {
var magnitude: Double
var enableOverride: Bool?
var isSuspended: Bool
@Default(.enableParallaxEffect) var enableParallaxEffect
@State private var offset: CGSize = .zero
@State private var isHovering = false
@State private var viewSize: CGSize = .zero
func body(content: Content) -> some View {
if !(enableOverride ?? enableParallaxEffect) {
if isSuspended || !(enableOverride ?? enableParallaxEffect) {
content
} else {
content
.contentShape(Rectangle())
.overlay(
GeometryReader { proxy in
Color.clear
.onContinuousHover { phase in
switch phase {
case .active(let location):
let width = proxy.size.width
let height = proxy.size.height
// Normalize -1 to 1
// (0,0) is top left, so we want center (width/2, height/2) to be (0,0)
let x = (location.x / width) * 2 - 1
let y = (location.y / height) * 2 - 1
// Animate the transition to the new hover position
withAnimation(.interactiveSpring(response: 0.1, dampingFraction: 0.5)) {
offset = CGSize(width: x, height: y)
isHovering = true
}
case .ended:
// Return to center when hover ends
withAnimation(.spring(response: 0.35, dampingFraction: 0.6)) {
offset = .zero
isHovering = false
}
}
.allowsHitTesting(false)
.onAppear {
viewSize = proxy.size
}
.onChange(of: proxy.size) { _, newSize in
viewSize = newSize
}
}
)
.onContinuousHover { phase in
switch phase {
case .active(let location):
guard viewSize.width > 0, viewSize.height > 0 else { return }
guard NSEvent.pressedMouseButtons == 0 else { return } // Skip hover math while clicking to avoid lag
let x = (location.x / viewSize.width) * 2 - 1
let y = (location.y / viewSize.height) * 2 - 1
withAnimation(.interactiveSpring(response: 0.1, dampingFraction: 0.5)) {
offset = CGSize(width: x, height: y)
isHovering = true
}
case .ended:
withAnimation(.spring(response: 0.35, dampingFraction: 0.6)) {
offset = .zero
isHovering = false
}
}
}
.rotation3DEffect(
.degrees(offset.height * magnitude), // Y movement rotates around X axis
axis: (x: 1, y: 0, z: 0)
@ -65,7 +71,11 @@ struct ParallaxMotionModifier: ViewModifier {
}
extension View {
func parallax3D(magnitude: Double = 10) -> some View {
modifier(ParallaxMotionModifier(magnitude: magnitude, enableOverride: nil))
func parallax3D(
magnitude: Double = 10,
enableOverride: Bool? = nil,
suspended: Bool = false
) -> some View {
modifier(ParallaxMotionModifier(magnitude: magnitude, enableOverride: enableOverride, isSuspended: suspended))
}
}