r/javascript • • 27d ago

Porting SwiftUI's spring animation (duration + bounce) to plain JS

https://github.com/MF-DEEV/Openbar/blob/main/windows/src/island/motion.ts

This is the resize animation of Openbar's island on Windows (Tauri + React). The Mac app is SwiftUI, so I ported its spring math to get the same feel on both. Width and height each get their own spring: a growing side may swing past its target, capped at 12 px, and a shrinking side never does.

The app shows Claude Code and Codex sessions in a Dynamic Island. Free, GPL.

0 Upvotes

8 comments sorted by

1

u/ortegaj50 12d ago

Does the 12px cap scale with the resize? A fixed cap could feel stronger on small changes.

1

u/Significant-Sea-7238 11d ago

It scales. The overshoot is a share of the distance, about 3% for width and 2% for height, so small changes swing a few px. The 12 px cap only kicks in on big resizes, where it lowers the bounce so the swing stops at 12.

1

u/jjohnson-13233 4d ago

Is the 3% width / 2% height split from SwiftUI's behavior, or did you tune the axes separately? Curious whether that difference is part of the port or a visual adjustment.

1

u/Significant-Sea-7238 4d ago

Tuned separately, but on the Mac side, not in the port. SwiftUI doesn't split the axes by itself. The Mac app gives width and height their own springs (bounce 0.25 and 0.22), which comes out to about 3% and 2% overshoot. Windows copies those numbers and the 12 px cap as they are, so the difference isn't a port adjustment.

1

u/ma-i_274 11d ago

How does a second resize during the spring behave: retarget from the current size, or restart the motion?

1

u/Significant-Sea-7238 11d ago

Depends on direction. If a side keeps going the same way, it retargets: a new spring is added on top of the running one, so it keeps its momentum, and the 12 px cap holds for the sum. If a side turns back, it starts a fresh spring from the size on screen, at rest.

1

u/Discordbothost 27d ago

capping the overshoot only on the growing side is a nice call, a shrinking box that bounces past its target always reads as a glitch.

one thing to check if you're stepping the spring per requestAnimationFrame: with euler-ish integration the feel changes between 60hz and 120/144hz displays, and windows laptops are all over the place. either step it at a fixed dt (accumulate and run 1-2 substeps per frame) or use the closed-form underdamped solution since you already have stiffness/damping from duration + bounce (k = (2π/duration)², c = 4π(1 - bounce)/duration). then it's identical on any refresh rate.

would also respect prefers-reduced-motion and just snap

1

u/Significant-Sea-7238 26d ago

Thanks! Both are covered already: springProgress is the closed-form solution evaluated against performance.now(), so there's no per-frame stepping and it looks the same at 60 or 144 Hz. With prefers-reduced-motion the island skips the spring and snaps straight to the new size.