Skip to main content
Introducing packages.sweber.dev
Lagrangian overview

LagrangianLive demo. Click, throw, drop.

Everything on this page moves with real physics from @sweberdev/lagrangian: springs solved exactly, friction, gravity, collisions. Nothing has a fixed duration. Interrupt anything and it continues from where it is and how fast it moves.

Springs

Click faster than CSS can keep up.A transition restarts. A spring keeps its momentum.

Both dots go to the other side when you click. The upper one uses a CSS transition, the lower one a Lagrangian spring. Click several times in a row and watch the plot: the transition stops dead and starts again, the spring turns around smoothly because it knows its velocity.

The spring

import { animate } from "@sweberdev/lagrangian"

dot.addEventListener("click", () => {
  open = !open
  // Interrupting keeps the current velocity.
  animate(dot, { x: open ? 320 : 0 }, { duration: 0.6, bounce: 0.25 })
})

Throw

Throws that land where they should.Velocity, friction, snap points and soft edges.

Swipe the cards. Lagrangian measures how fast you let go, lets the strip glide with friction like iOS scrolling and adjusts the glide so it ends exactly on a card. Pull past the first or last card and it resists, then springs back. The puck on the right has no snap points, only walls.

Cards

01Mass
02Velocity
03Friction
04Gravity
05Restitution

Drag and let go

Free throw

Drag and let go

The cards

import { draggable, nearest } from "@sweberdev/lagrangian"

draggable(strip, {
  axis: "x",
  bounds: { left: -4 * step, right: 0 },
  snap: { x: [0, -step, -2 * step, -3 * step, -4 * step] },
})

draggable(puck, { bounds: box })

World

Drop things. Grab them. Throw them.Gravity, collisions, friction and rolling.

Pick up any ball and throw it. Bigger balls are heavier, collisions keep momentum, and friction at the contact point makes balls roll. Switch to the Moon or turn gravity off. When everything rests for a second the world stops computing, so an idle page costs nothing.

Gravity
Material

0 bodies · at rest, no CPU used

The playground

import { World } from "@sweberdev/lagrangian"

const world = new World({ bounds: box }).start()

for (const el of box.querySelectorAll(".ball")) {
  world.add({ x: 120, y: 0, radius: 24, restitution: 0.85, element: el })
}

world.bindPointer() // grab and throw
world.gravity = { x: 0, y: 1.62 } // the Moon

Double pendulum

Write your own equations of motion.Chaos from one Lagrangian.

Two double pendulums, started one thousandth of a radian apart. Their equations of motion come straight from the Lagrangian L = T − V and are stepped with RK4 at 240 Hz. For a few seconds they move as one, then they go completely different ways. The energy readout shows how little the integrator drifts.

Time 0.0 s · Energy drift 0.0000 %

The equations

import { loop, system } from "@sweberdev/lagrangian"

// State [θ1, θ2, ω1, ω2]; the accelerations follow
// from the Euler-Lagrange equations of L = T − V.
const pendulum = system(([a1, a2, w1, w2]) => {
  const d = a1 - a2, den = 3 - Math.cos(2 * d)
  return [
    w1,
    w2,
    (-3 * g * Math.sin(a1) - g * Math.sin(a1 - 2 * a2)
      - 2 * Math.sin(d) * (w2 * w2 + w1 * w1 * Math.cos(d))) / den,
    (2 * Math.sin(d) * (2 * w1 * w1 + 2 * g * Math.cos(a1)
      + w2 * w2 * Math.cos(d))) / den,
  ]
}, [angle, angle, 0, 0])

loop.add((dt) => draw(pendulum.advance(dt)))

Pro

Finished pieces on the same physics.Sheet, drawer, dialog, carousel, pull to refresh, swipe stack, sortable lists, toasts, tab indicator, page effects, board, zoom, jelly, ropes and sounds.

Lagrangian Pro turns the physics into interface parts you would otherwise build yourself: a sheet that lands where the throw would carry it, cards that tilt around your finger, lists that make room as you drag, and objects that squash, swing and clack. Each is a few lines. Here is what they look like in code.

Bottom sheet

import { sheet } from "@weber-development/lagrangian-pro"

const filters = sheet(element, {
  detents: [0.4, 1], // 40 % and full height
  backdrop: shade,
  onChange: (index) => console.log(index), // -1 is closed
})

openButton.onclick = () => filters.open()

Swipe stack

import { swipeStack } from "@weber-development/lagrangian-pro"

const stack = swipeStack(cards, {
  directions: ["left", "right"],
  onSwipe: (card, direction) => save(card.dataset.id, direction),
})

likeButton.onclick = () => stack.swipe("right")
undoButton.onclick = () => stack.undo()

Sortable list in React

import { arrayMove, useSortable } from "@weber-development/lagrangian-pro-react"

const list = useSortable<HTMLUListElement>({
  onReorder: (from, to) => setItems((x) => arrayMove(x, from, to)),
})

return (
  <ul ref={list.ref}>
    {items.map((item) => <li key={item.id}>{item.title}</li>)}
  </ul>
)

Drawer, dialog, carousel, pull to refresh

import { carousel, dialog, drawer, pullToRefresh } from "@weber-development/lagrangian-pro"

pullToRefresh(scroller, { onRefresh: () => reload() })
carousel(viewport, { align: "center", label: "Photos" })

const menu = drawer(nav, { side: "left", backdrop: shade })
menuButton.onclick = () => menu.toggle()

const confirm = dialog(box, { backdrop: shade })
deleteButton.onclick = () => confirm.show()

Jelly, rope and sound

import { impactSound, jelly, rope } from "@weber-development/lagrangian-pro"

// Squash and stretch from the ball's real velocity
const drag = draggable(ball)
jelly(ball.querySelector(".skin"), { source: drag })

// A cable you can grab and swing
rope({ from: { x: 160, y: 0 }, length: 240, onFrame: (r) => path.setAttribute("d", r.path()) })
  .start()
  .bindPointer(svg)

// Impact sounds for the world
new World({ bounds: box, onCollide: impactSound({ material: "wood" }).collide })

Toasts, tabs, falling page, board, zoom

import { fall, indicator, toasts } from "@weber-development/lagrangian-pro"

const stack = toasts(corner, { edge: "bottom", max: 4 })
saveButton.onclick = () => stack.show("Saved")

indicator(tabs, bar, { itemSelector: "button", onSelect: (i) => showPanel(i) })

const effect = fall(section)
effect.start()
effect.explode({ x: 400, y: 600 })
await effect.restore()

board([todo, doing, done], { onMove: ({ item, to }) => save(item, to) })
zoom(viewport, { max: 6 })

Free 2.0

A physics world that repeats exactlyLagrangian, free.

Lagrangian 2.0 makes the world deterministic: the same bodies, inputs and seed give the same numbers at any frame rate and on any machine. It also adds snapshots, a state hash and the Vue adapter on npm, all MIT.

Seeded, repeatable runs

Give the world a seed and use world.random() instead of Math.random(). Two runs with the same seed end in the same state, so tests and replays are reliable.

Run it twice with the same seed

const run = (seed) => {
  const world = new World({ seed, bounds });
  for (let i = 0; i < 5; i++)
    world.add({ x: 100 + world.random() * 400, y: 40, radius: 20 });
  world.advance(4); // simulate 4 seconds now
  return world.hash();
};
console.log("run 1:", run(7));
console.log("run 2:", run(7));
console.log("seed 8:", run(8));

Real output (Node 22, @sweberdev/lagrangian 2.0.0)

run 1: af530c07
run 2: af530c07
seed 8: f254a889

Same result at every frame rate

The world always simulates in fixed steps, and sleeping and sensors are decided in every step. A 30 Hz, 60 Hz or 144 Hz display no longer changes the outcome.

Advance the same world in frames of different length

for (const hz of [30, 60, 144]) {
  const world = makeWorld(); // seed 7, five circles
  for (let i = 0; i < hz * 4; i++) world.advance(1 / hz);
  console.log(hz + " Hz frames, 4 s:", world.hash(), "time", world.time);
}

Real output

30 Hz frames, 4 s: af530c07 time 4
60 Hz frames, 4 s: af530c07 time 4
144 Hz frames, 4 s: af530c07 time 4

Snapshot, restore and replay

world.snapshot() returns plain JSON for bodies, clock and random generator. Restore it later and the run continues exactly as before, handy for undo, saved scenes and regression tests.

Save at 2 s, run on, rewind, run again

world.advance(2);
const saved = world.snapshot(); // plain JSON, safe to store
world.advance(3);
const after = world.hash();

world.restore(saved);
console.log("time after restore:", world.time);
world.advance(3);
console.log("replayed hash matches:", world.hash() === after);

Real output

time after restore: 2
replayed hash matches: true

Keep the 1.x timing while you update

Fixed steps change when a body falls asleep or a sensor fires by a frame or two in some scenes. legacyStepping restores the 1.x behaviour as a bridge. It is removed in 2.1.

Opt back into 1.x timing

const world = new World({ bounds, legacyStepping: true });

Same scene with legacyStepping: true (hash differs from the 2.0 run above)

legacyStepping: true: 11de78f4

Vue adapter is on npm

@sweberdev/lagrangian-vue, the composables for springs, dragging, scrolling and the world in Vue 3, is now published at 2.0.0 next to the core, React and Svelte packages.

Install

pnpm add @sweberdev/lagrangian @sweberdev/lagrangian-vue

npm view @sweberdev/lagrangian-vue name version license

name = '@sweberdev/lagrangian-vue'
version = '2.0.0'
license = 'MIT'

Node 22 or newer is needed to build. world.step(dt) now also settles and senses, so a hand-stepped world matches a running one.

Read the docs

Pro 2.1.0

Ready-made recipesLagrangian Pro.

Pro 2.1.0 adds finished building blocks for the screens you build again and again: forms in a sheet, photo galleries and swipeable list rows. It also adds a spring editor to tune a spring by eye.

Form in a bottom sheet

formSheet wraps a form in a sheet that handles focus, the Tab trap, the on-screen keyboard, submit and error state, and a guard against losing unsaved changes.

Import

import { formSheet } from "@weber-development/lagrangian-pro";

// React
import { useFormSheet } from "@weber-development/lagrangian-pro-react";
// returns [ref, formSheet]

Photo gallery that opens from its thumbnail

lightbox turns a grid of thumbnails into a viewer. The picture grows out of its thumbnail, you swipe between pictures and drag down to close, and the keyboard and focus behave as in a dialog.

Import

import { lightbox } from "@weber-development/lagrangian-pro";

// React: viewer and backdrop are refs
import { useLightbox } from "@weber-development/lagrangian-pro-react";
// returns [ref, lightbox]

List rows with swipe actions

swipeRows slides a row aside to show actions like delete or archive. A vertical drag still scrolls the page, and the actions work with the keyboard: Alt+ArrowLeft opens a row, Escape or Alt+ArrowRight closes it.

Import

import { swipeRows } from "@weber-development/lagrangian-pro";

// React
import { useSwipeRows } from "@weber-development/lagrangian-pro-react";
// returns [ref, swipeRows]

Spring editorBeta

springEditor gives you sliders, a curve, a preview ball and copy-ready code to tune a spring. springCurve samples a spring. The editor is in beta: its markup and class names may still change.

Import

import { springEditor, springCurve } from "@weber-development/lagrangian-pro";

// React
import { useSpringEditor } from "@weber-development/lagrangian-pro-react";
// returns [ref, editor]

Adapters for Vue and Svelte

The new recipes come with composables for Vue and actions for Svelte, next to the React hooks. All Pro packages share one version number.

Vue and Svelte

// Vue 3
useFormSheet(el, options)
useLightbox(grid, () => ({ viewer: viewerEl.value }))
useSwipeRows(el, options)
useSpringEditor(el, options)

// Svelte
formSheetAction, gallery, swipeRows, springLab
// e.g. use:gallery, use:springLab

Pro code is not shipped in a browser demo. The recipes are tested in jsdom and Chromium, not yet on a real mobile keyboard or in Safari and Firefox.

Read the docs

Get it

About 12 kB of physics.The core is free and open source under the MIT licence.

Springs, throws, dragging and the world work with any framework. React hooks are in @sweberdev/lagrangian-react. The docs explain every option and the maths behind it.

pnpm add @sweberdev/lagrangian
Read the docs