Tug of Work loader
A progress bar where a tiny person drags a heavy stone to 100%, straining when it waits. Use it for uploads, exports and builds that take a while.
npx shadcn@latest add https://impeccableui.vercel.app/r/tug-of-work-loader.jsonRun it in a project set up with shadcn. No other packages needed. Or open and copy the file into components/ui/tug-of-work-loader.tsx.
Prompts
Paste one into Claude Code, Cursor or any AI coding tool. Install adds this exact loader and asks only where it goes. Blend asks four short questions (where and what it tracks, the support text, the color, and the size), then fits it to your product without changing how it moves.
# Tug of Work loader
A 1-file React component from Impeccable. Add it to this project so it works and looks exactly like the source below, in the one place I choose, and change nothing else.
A see-through progress bar where the filled part is a heavy slab of stone and a tiny person drags it. They lean back on a rope tied to the stone's chipped front and walk backwards; the stone lurches along behind them, rumbling and kicking up dust, until it reaches 100%. When the bar waits they keep heaving and the stone only budges. At 100% the stone shoves them out of the end of the bar and they tumble off and fall. Until then, nothing leaves the bar's border. Under the bar sits a support line, "Developers are working really hard.", and the percentage.
## Before you build: one question
Look through this project first: its uploads, exports, imports, build or deploy steps, setup or onboarding screens, and any spinner or progress bar it already shows while people wait. Then ask me this in one message and wait for my answer:
- **Where should it go, and what does it track?** Suggest the 1–3 spots it fits best from my code (for example a file upload with real progress, an export or build screen, or a first-run setup screen). For each one, say whether you would pass its real progress as `value` (0 to 100), or leave `value` out so it loops because the wait can't be measured. I can pick one or name another.
*Why: with real progress the person pulls the bar to the true number, which is honest and satisfying; a looping bar only suits waits you can't measure.*
Ask nothing else. If I say *skip*, use the best suggestion.
## Keep it as it is
The see-through bar, the stone slab with its lurch, rumble and dust, the tiny person leaning back on the rope and walking backwards, the straining while it waits, the hand-over-hand pull at the end and the fall off the end at 100%, with their timing, are the design. So is the support line "Developers are working really hard." Keep them exactly as in the source. If something doesn't fit my project, tell me instead of changing it.
- Add only the component file and the one place I picked. If it replaces an existing spinner or progress bar there, keep that spot's logic and remove only the old indicator. Don't add packages, change other files, or restyle anything.
- Don't add the demo parts from the Impeccable website: the dotted card behind the loader and the home page's TV.
## Fastest path
If this project has a `components.json` (shadcn), run `npx shadcn@latest add https://impeccableui.vercel.app/r/tug-of-work-loader.json`.
If the command succeeds, only fix import paths to match this project and skip ahead. If it fails or there is no `components.json`, build it by hand as below.
## Build it
- Stack: React 18 or 19 with TypeScript. No other packages: the bar is plain CSS and the person is drawn on one canvas inside it.
- JavaScript project? Name the file `tug-of-work-loader.jsx` and remove the type annotations; nothing else changes.
- Create this file, in this project's usual place for components:
- `components/ui/tug-of-work-loader.tsx`
- Keep these exports and their names: `TugOfWorkLoader`, `TugOfWorkLoaderProps`.
- Keep `"use client"` at the top in Next.js App Router projects. In other setups it is harmless.
- Keep the tuning values at the top exactly as written: `PAD`, `BODY`, `GROUND`, `LEAN`, `REACH`, `PULL_SPEED`, `CATCH_MS`, `STRIDE`, `MAX_STEPS`, `HEAVE_MS`, `SWEAT_MS`, `STUMBLE_MS`, `DROP_MS`, `DROP`, `HOLD_MS`, `FADE_MS`, `STONE`, `LAG`, `BUDGE`, `DUST`, the `RUN` list and the `CSS` block. They are the design and its timing.
- The bar stays see-through: a thin border, no solid background, and a stone that is only a tint. Everything on the canvas (the stone, the person, the rope, the sweat and the dust) is clipped to the inside of the bar, so nothing leaves its border while they pull. Keep that clip. Only the fall at 100 is drawn outside it.
- Keep the fallbacks: with `prefers-reduced-motion: reduce` the stone still moves but the person stands still, with no steps, heaves, lurches, dust or sweat, and at 100 they raise their arms instead of falling. When the tab is hidden or the bar is scrolled out of view, drawing stops and picks up where it left off. A theme switch redraws it in the new colors. It is a `role="progressbar"` with `aria-valuenow` when it has a value, and has no `aria-valuenow` while it loops (the progress is not real then).
## Use it
```tsx
"use client";
import { TugOfWorkLoader } from "@/components/ui/tug-of-work-loader";
// Real progress: pass a number from 0 to 100.
export function UploadProgress({ percent }: { percent: number }) {
return <TugOfWorkLoader value={percent} className="max-w-sm" />;
}
// A wait you can't measure: leave value out and it loops.
export function Building() {
return <TugOfWorkLoader className="max-w-sm" />;
}
```
- It fills the width it is given, so set a max width with `className` (about 280 to 480px reads best). It is 44px tall plus the line under it.
- Show it only while the wait lasts. `onComplete` runs when it reaches 100, if you want to move on. At 100 the person falls about three bar heights below the bar's right end, over whatever is there, for about a second.
## How the loader works
Read this before you touch anything, so you know what the code does and why it must stay as it is.
1. **The bar.** A pill (44px tall by default, `height`) with a 1px border at 26% of `color` and nothing behind it, so the page shows through. A canvas covers the inside, 3px in from the border, and everything below is drawn on it.
2. **The stone.** The filled part is a slab of stone in an 18% tint of `color` (`STONE`), with a darker underside, a chipped front edge (fixed chips, the middle left clean for the rope), and grain, pits and cracks laid out in fixed tiles counted back from the front, so they travel with it and read as one solid object being dragged.
3. **The person.** A stick figure in `color`, about three quarters of the bar's inner height. They face the stone and lean back about 29 degrees on a rope tied to the middle of its front edge; the rope runs taut to their hands and a short tail hangs behind.
4. **Pulling.** With a `value`, the stone moves to it, never faster than 30% of the bar a second, and settles softly. Without one, it loops through a fixed run (`RUN`, over `duration`, 8 seconds): pulls with pauses between them, like real work. The person stays a rope's length ahead and walks backwards with it; their steps follow the distance pulled (up to 2.8 pairs of steps a second), so their feet don't slide on slow pulls.
5. **Weight.** While it moves, the stone drags up to 1.4px behind on each step (`LAG`) and lurches forward when the next one lands, rumbles up and down a fraction of a pixel, and kicks up specks of dust at its front bottom corner (about one for every 3px it moves, `DUST`, plus a puff on each lurch). The dust drifts up and fades in about half a second.
6. **Waiting.** When the stone stops before 100, they keep heaving on the rope every 1.1 seconds, leaning further back, hands pumping. The stone budges 0.9px forward on each heave (`BUDGE`), shudders and puffs a little dust, then settles. After a moment they shake, and every 1.6 seconds a drop of sweat flies off the back of their head and falls.
7. **The end.** Near 100 they run out of room, so they stop where the bar is still full height (before its rounded end) and pull the rope in hand over hand as the stone comes to them. At 100 `onComplete` runs once and the stone shoves them backwards out of the end of the bar in 0.28 seconds (`STUMBLE_MS`): they scramble, the rope drops and their arms windmill. Then they fall about three bar heights (`DROP`) in 0.76 seconds (`DROP_MS`), tumbling backwards and drifting a little right, and fade out. In `value` mode they stay gone while it sits at 100, and fade back in at the start when the value drops again. When looping, the finished bar rests 1.5 seconds, fades out, starts again from 0 and fades in.
8. **Going back.** If the value drops (a new upload, a retry), the stone and the person jump straight there; they never walk the stone backwards.
9. **Drawing.** The canvas reaches past the bar's right end (only as far as the screen allows, so a full-width bar never makes the page scroll sideways) and three bar heights below it, for the fall. Until the fall, everything is clipped to the inside of the bar, so nothing leaves the border. A loop runs while anything moves and rests when nothing does. All motion runs on elapsed time, so it feels the same on slow phones and fast screens. The color is read from the page on every frame, so it follows light and dark mode.
## Check
- It type-checks and the page renders with no console errors.
- A see-through bar whose filled part is a stone slab, a tiny person ahead of it with a rope to their hands, and "Developers are working really hard." with the percentage under it. As the progress grows they walk backwards, dragging the stone, which lurches and kicks up dust; when it stops they heave and strain and the stone only budges; near the end they pull hand over hand; at 100 the stone shoves them out of the end of the bar and they tumble down and fade. Until then, nothing crosses the bar's border.
- It looks right in light and dark mode (check both): the border, the stone with its grain and the person all show.
- On a phone (375px wide) it fits with no sideways scroll, and the support line wraps under the bar.
- With `prefers-reduced-motion: reduce`, the stone still moves and the percentage counts, but the person stands still, no dust flies, and at 100 they raise their arms instead of falling.
- Nothing else on the site looks or behaves differently.
- Finish with a short report: the files you added or changed, where it's placed and what it tracks, and every place where you had to do something differently from the source, and why.
## Source
The reference implementation. Copy it as-is, then apply only the changes listed above.
### `components/ui/tug-of-work-loader.tsx`
```tsx
"use client";
/**
* Tug of Work loader, from Impeccable.
*
* A see-through progress bar where the fill is a heavy slab of stone and a
* tiny person drags it. They lean back on a rope tied to the stone's chipped
* front and walk backwards, and the stone grinds along behind them in small
* lurches, kicking up dust. When the bar waits, they keep heaving and the
* stone budges a hair. At 100% the stone shoves them out of the end of the
* bar and they tumble off and fall. Until then, everything stays inside the
* bar's border.
*
* Give it a `value` from 0 to 100 and the person pulls the fill to it. Leave
* `value` out and it loops on its own, with pulls and pauses like real work.
*
* No packages: the bar is plain CSS, and the stone and the person are drawn
* on one canvas inside it, by one requestAnimationFrame loop that rests when
* nothing moves.
*/
import { useEffect, useRef, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
export type TugOfWorkLoaderProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
/** Progress from 0 to 100. The person pulls the fill to it. Leave it out to loop on its own. */
value?: number;
/** The support text under the bar. Pass null to hide it. */
label?: ReactNode;
/** Show the percentage at the right, under the bar. */
showValue?: boolean;
/** The person, the rope, the border and the stone's tint. Any CSS color, including var(--…). Default: the text color around it. */
color?: string;
/** How tall the bar is in px, 28 to 64. The person grows with it. */
height?: number;
/** When looping (no value): how long one pull from 0 to 100 takes, in ms, 3000 to 30000. */
duration?: number;
/** Called each time the fill reaches 100. */
onComplete?: () => void;
};
/* ---------- tuning (the design: keep as written) ---------- */
const PAD = 3; // px between the border and the fill
const BODY = 0.76; // the person's height, as a share of the space inside the bar
const GROUND = 0.88; // where their feet stand, from the top of that space
const LEAN = 0.5; // radians they lean back on the rope
const REACH = 0.62; // rope between the fill and their hands, in body heights
const PULL_SPEED = 0.3; // the fastest the fill moves when following a value, share of the bar per second
const CATCH_MS = 220; // how softly the fill settles on a new value
const STRIDE = 0.6; // body heights travelled per pair of steps
const MAX_STEPS = 2.8; // pairs of steps per second at most (faster pulls slide the feet a little)
const HEAVE_MS = 1100; // one heave on the rope while the bar waits
const SWEAT_MS = 1600; // a drop of sweat flies off this often while they strain
const STUMBLE_MS = 280; // at 100% the stone shoves them backwards out of the end of the bar
const DROP_MS = 760; // then they tumble and fall, fading out
const DROP = 3; // how far they fall, in bar heights
const HOLD_MS = 1500; // looping: how long the finished bar stays before it starts over
const FADE_MS = 320; // looping: fade out, reset, fade in
const STONE = 0.18; // how strong the stone's tint is (it stays see-through)
const LAG = 1.4; // px the stone drags behind on each step before it lurches forward
const BUDGE = 0.9; // px the stone budges on each heave while the bar waits
const DUST = 0.35; // specks of dust kicked up per px the stone moves
/** The looping run: [share of the duration, progress]. Pulls, then pauses where they strain. */
const RUN: [number, number][] = [
[0, 0], [0.11, 0.14], [0.17, 0.15], [0.3, 0.34], [0.42, 0.36], [0.53, 0.53],
[0.59, 0.55], [0.71, 0.74], [0.79, 0.76], [0.9, 0.93], [0.95, 0.94], [1, 1],
];
/** Styles that can't be inline: the bar, the canvas and the label row. */
const CSS = `
.twl { display: block; width: 100%; min-width: 0; --twl-c: currentColor; }
.twl-track { position: relative; box-sizing: border-box; height: var(--twl-h, 40px); padding: ${PAD}px; border: 1px solid color-mix(in srgb, var(--twl-c) 26%, transparent); border-radius: 999px; background: transparent; }
.twl-inner { position: relative; height: 100%; }
.twl-canvas { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; color: var(--twl-c); }
.twl-row { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-top: 10px; font-size: 13px; line-height: 1.45; }
.twl-label { min-width: 0; overflow-wrap: anywhere; color: color-mix(in srgb, currentColor 64%, transparent); }
.twl-value { flex-shrink: 0; font-variant-numeric: tabular-nums; font-weight: 500; }`;
/* ---------- small helpers ---------- */
const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));
const num = (v: unknown, fallback: number, lo: number, hi: number) =>
typeof v === "number" && Number.isFinite(v) ? clamp(v, lo, hi) : fallback;
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
const inOut = (t: number) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
const smooth = (t: number) => t * t * (3 - 2 * t);
/** A fixed random number from 0 to 1 for each n, so the stone's grain and chips stay the same as it moves. */
const hash = (n: number) => {
const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
return x - Math.floor(x);
};
/** Moves `from` toward `to`, the same amount per second at any frame rate. */
const ease = (from: number, to: number, dt: number, ms: number) => to + (from - to) * Math.exp(-dt / ms);
/** Where the looping run is at a share t (0 to 1) of the duration. */
function runAt(t: number) {
for (let i = 1; i < RUN.length; i++) {
const [t1, p1] = RUN[i];
if (t <= t1) {
const [t0, p0] = RUN[i - 1];
return lerp(p0, p1, inOut((t - t0) / (t1 - t0)));
}
}
return 1;
}
type Pt = { x: number; y: number };
const pt = (x: number, y: number): Pt => ({ x, y });
const mix = (a: Pt, b: Pt, t: number) => pt(lerp(a.x, b.x, t), lerp(a.y, b.y, t));
/** The middle joint (knee or elbow) of a two-part limb, bent toward `side` (+1 or -1). */
function joint(a: Pt, b: Pt, len: number, side: number): [Pt, Pt] {
let dx = b.x - a.x;
let dy = b.y - a.y;
let d = Math.hypot(dx, dy) || 0.001;
if (d > len * 2) {
// Too far to reach: stretch the limb straight toward the target.
b = pt(a.x + (dx / d) * len * 2, a.y + (dy / d) * len * 2);
dx = b.x - a.x;
dy = b.y - a.y;
d = len * 2;
}
const h = Math.sqrt(Math.max(0, len * len - (d / 2) ** 2));
const m = pt(a.x + dx / 2, a.y + dy / 2);
return [pt(m.x + (-dy / d) * h * side, m.y + (dx / d) * h * side), b];
}
/* ---------- the component ---------- */
export function TugOfWorkLoader({
value,
label = "Developers are working really hard.",
showValue = true,
color,
height,
duration,
onComplete,
className,
style,
...rest
}: TugOfWorkLoaderProps) {
const looping = !(typeof value === "number" && Number.isFinite(value));
const target = looping ? 0 : clamp(value, 0, 100) / 100;
const h = num(height, 44, 28, 64);
const innerRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const valueRef = useRef<HTMLSpanElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
const kick = useRef<() => void>(() => {});
// The latest props, read by the running loop without restarting it.
const live = useRef({ looping, target, duration: num(duration, 8000, 3000, 30000), onComplete });
live.current = { looping, target, duration: num(duration, 8000, 3000, 30000), onComplete };
useEffect(() => {
kick.current();
}, [looping, target]);
useEffect(() => {
const inner = innerRef.current;
const canvas = canvasRef.current;
const root = rootRef.current;
if (!inner || !canvas || !root) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
let W = 0;
let H = 0;
let dpr = 1;
let raf = 0;
let last = 0;
let visible = true;
// Everything that moves.
let p = live.current.looping ? 0 : live.current.target; // where the fill is, 0 to 1
let runT = 0; // looping: ms into the current run
let personX = -1; // feet, in px from the left of the space inside the bar
let walk = 0; // 0 standing, 1 walking
let stepPhase = 0;
let pullPhase = 0;
let pullAmt = 0;
let strainMs = 0; // how long they have been straining without moving
let sweatAt = 0;
let cheer = 0; // reduced motion only: 1 = arms up at 100%
let fallMs = -1; // ms since the stone shoved them off the end, or -1
let fromX = 0; // where they stood when it did
let appear = 1; // fades them back in after a fall
let doneMs = -1; // ms since the fill reached 100, or -1
let fade = 1; // looping reset
let shown = -1; // last percentage written
let pulled = p < 0.999; // onComplete only fires after a pull, not when it mounts already full
let drops: { x: number; y: number; vx: number; vy: number; age: number }[] = [];
let dust: { x: number; y: number; vx: number; vy: number; r: number; age: number; life: number }[] = [];
let dustAcc = 0;
let lastLurch = 0;
let lastHeave = 0;
// The canvas reaches past the bar's right end and below it, for the fall. To the right only
// as far as the screen allows, so a full-width bar never makes the page scroll sideways.
let CW = 0;
let CH = 0;
const size = () => {
const r = inner.getBoundingClientRect();
W = inner.clientWidth || r.width;
H = inner.clientHeight || r.height;
const room = document.documentElement.clientWidth - r.right - 1;
CW = W + clamp(room, 0, H * BODY * 2.4 + PAD + 2);
CH = H * (1 + DROP);
dpr = Math.min(2, window.devicePixelRatio || 1);
canvas.style.width = `${CW}px`;
canvas.style.height = `${CH}px`;
canvas.width = Math.max(1, Math.round(CW * dpr));
canvas.height = Math.max(1, Math.round(CH * dpr));
kick.current();
};
const draw = (t: number, dt: number) => {
const reduce = motion.matches;
const L = live.current;
const body = H * BODY;
const ground = H * GROUND;
const lw = Math.max(1.4, body * 0.075);
/* 1. Where the fill should be. */
const before = p;
let settled = false;
if (L.looping) {
if (doneMs < 0) {
runT += dt;
p = runAt(clamp(runT / L.duration, 0, 1));
} else {
const after = doneMs - HOLD_MS;
fade = after < 0 ? 1 : after < FADE_MS ? 1 - after / FADE_MS : after < FADE_MS * 2 ? (after - FADE_MS) / FADE_MS : 1;
if (after >= FADE_MS && runT > 0) {
// Out of sight: start over from 0, with the person back at the start.
runT = 0;
p = 0;
personX = -1;
drops = [];
dust = [];
}
if (after >= FADE_MS * 2) doneMs = -1;
}
} else {
fade = 1;
const d = L.target - p;
if (Math.abs(d) < 0.0005) p = L.target;
else if (d < 0) {
// Progress went back (a new upload, a retry): start over there at once, no walking backwards.
p = L.target;
personX = -1;
drops = [];
dust = [];
} else {
const step = Math.sign(d) * Math.min(Math.abs(d), PULL_SPEED * (dt / 1000));
const soft = d * (1 - Math.exp(-dt / CATCH_MS));
p += Math.abs(soft) < Math.abs(step) ? soft : step;
}
settled = p === L.target;
}
if (reduce && L.looping && doneMs < 0) settled = false;
/* 2. Done? */
if (p < 0.999) pulled = true;
if (p >= 0.999 && doneMs < 0 && (L.looping ? runT > 0 : true)) {
doneMs = 0;
if (pulled) L.onComplete?.();
pulled = false;
} else if (doneMs >= 0) {
doneMs += dt;
if (!L.looping && p < 0.999) doneMs = -1;
}
const isDone = doneMs >= 0 && p >= 0.999;
// At 100 the stone shoves them off the end (with reduced motion they just raise their arms).
if (isDone && !reduce) {
if (fallMs < 0) {
fallMs = 0;
fromX = personX;
} else fallMs += dt;
} else if (fallMs >= 0) {
fallMs = -1;
personX = -1;
appear = 0;
}
cheer = reduce && isDone ? 1 : 0;
appear = Math.min(1, appear + dt / 250);
const shove = fallMs < 0 ? 0 : Math.min(1, fallMs / STUMBLE_MS);
const drop = fallMs < 0 ? 0 : Math.max(0, fallMs - STUMBLE_MS);
/* 3. The number. */
const pct = Math.round(p * 100);
if (pct !== shown) {
shown = pct;
if (valueRef.current) valueRef.current.textContent = `${pct}%`;
if (!L.looping) root.setAttribute("aria-valuenow", String(pct));
}
/* 4. Where the person stands. */
const nose = p * W;
const handsBack = body * 0.35; // hands sit this far in front of the feet
// Stop where the bar is still full height, before its rounded end, so the head never touches the border.
const maxX = W - H / 2 - body * 0.12;
let want = clamp(nose + handsBack + body * REACH, body * 0.3, maxX);
// Shoved: they stumble backwards until their feet are past the end of the bar.
if (fallMs >= 0) want = lerp(fromX, W + PAD + 2 + body * 0.15, 1 - (1 - shove) ** 3);
if (personX < 0) personX = want;
const moved = want - personX;
personX = want;
const pinned = fallMs < 0 && want >= maxX - 0.01;
const fillMoved = (p - before) * W;
// Steps follow the distance walked, so feet don't slide (up to MAX_STEPS a second).
const speed = dt > 0 ? Math.abs(moved) / dt : 0; // px per ms
const walking = !reduce && speed > 0.004;
walk = reduce ? 0 : ease(walk, walking ? 1 : 0, dt, 90);
if (!reduce) {
const cycles = moved / (STRIDE * body);
const cap = (MAX_STEPS * dt) / 1000;
stepPhase += clamp(cycles, -cap, cap);
}
// Hand over hand on the rope: while pinned at the end, or heaving while the bar waits.
const waiting = !isDone && Math.abs(fillMoved) < 0.01 && !(L.looping && doneMs >= 0);
strainMs = waiting ? strainMs + dt : 0;
const heave = reduce || !waiting ? 0 : Math.max(0, Math.sin((t / HEAVE_MS) * Math.PI * 2)) ** 2;
if (!reduce) {
if (pinned && Math.abs(fillMoved) > 0.01) pullPhase += Math.abs(fillMoved) / (body * 0.35);
else if (waiting) pullPhase += dt / HEAVE_MS;
}
pullAmt = reduce ? 0 : ease(pullAmt, isDone ? 0 : pinned && !waiting ? 1 : waiting ? 0.45 : 0.15, dt, 120);
// The stone is heavy: it drags a little behind on each step and lurches forward, rumbles as it
// grinds, and budges a hair on each heave while the bar waits.
const moving = reduce ? 0 : clamp(Math.abs(fillMoved) / Math.max(dt, 1) / 0.02, 0, 1);
const lurch = ((((pinned ? pullPhase : stepPhase) * 2) % 1) + 1) % 1;
const stone = nose - LAG * lurch * moving + BUDGE * heave;
const rumble = reduce ? 0 : Math.sin(t * 0.07) * 0.3 * moving + Math.sin(t * 0.13) * 0.25 * heave;
if (!reduce && fade > 0.5) {
dustAcc += Math.abs(fillMoved) * DUST;
if (lurch < lastLurch - 0.5 && moving > 0.3) dustAcc += 2;
if (heave > 0.85 && lastHeave <= 0.85) dustAcc += 3;
const u = H * 0.0006;
while (dustAcc >= 1 && dust.length < 40) {
dustAcc -= 1;
const life = 400 + Math.random() * 350;
dust.push({
x: stone - Math.random() * H * 0.25,
y: H * (0.9 + Math.random() * 0.08),
vx: (Math.random() * 0.9 - 0.6) * u,
vy: -(0.3 + Math.random() * 0.7) * u,
r: (0.45 + Math.random() * 0.65) * (H / 38),
age: 0,
life,
});
}
dustAcc = Math.min(dustAcc, 4);
}
lastLurch = lurch;
lastHeave = heave;
/* 5. The pose. Facing left, toward the fill, leaning back on the rope. */
const tremble = !reduce && strainMs > 300 ? Math.sin(t * 0.09) * 0.35 * Math.min(1, strainMs / 900) : 0;
const lean = lerp(lerp(LEAN - walk * 0.06 + heave * 0.12, 0.02, cheer), 0.95, shove);
const x = personX + tremble;
const sn = Math.sin(lean);
const cs = Math.cos(lean);
const bob = -Math.abs(Math.sin(stepPhase * Math.PI * 2)) * body * 0.025 * walk;
const hip = pt(x + sn * body * 0.12, ground - body * lerp(0.44, 0.5, cheer) + bob);
const up = (d: number) => pt(hip.x + sn * d * body, hip.y - cs * d * body);
const shoulder = up(0.27);
const neck = up(0.31);
const head = up(0.42);
const headR = body * 0.1;
// Feet: a braced stance, blended with a backwards walk.
const thigh = body * 0.28;
const feet: Pt[] = [0, 1].map((i) => {
const brace = i === 0 ? -0.36 : -0.1;
const cheerFoot = i === 0 ? -0.06 : 0.06;
let off = brace;
let lift = 0;
if (walk > 0.001) {
const ph = (((stepPhase + i / 2) % 1) + 1) % 1;
const s = 0.12;
let w: number;
if (ph < 0.6) w = lerp(s, -s, ph / 0.6);
else {
const k = (ph - 0.6) / 0.4;
w = lerp(-s, s, smooth(k));
lift = Math.sin(k * Math.PI) * 0.07;
}
off = lerp(brace, w - 0.22, walk);
lift *= walk;
}
off = lerp(off, cheerFoot, cheer);
return pt(x + off * body, ground - lift * body);
});
// Hands: on the rope in front of the chest, or up in the air at 100%.
const grip = pt(shoulder.x - body * 0.28, shoulder.y + body * 0.11);
const hands: Pt[] = [0, 1].map((i) => {
const swing = Math.sin((pullPhase + i / 2) * Math.PI * 2);
const pulled = pt(grip.x - body * 0.07 * (0.5 + 0.5 * swing) * pullAmt + i * body * 0.06, grip.y - body * 0.02 * swing * pullAmt);
const raised = pt(shoulder.x + (i === 0 ? -0.17 : 0.17) * body, shoulder.y - body * 0.27);
// Shoved off: arms windmill.
const spin = (fallMs < 0 ? 0 : fallMs) * 0.022 + i * Math.PI;
const flail = pt(shoulder.x + Math.cos(spin) * body * 0.3, shoulder.y + Math.sin(spin) * body * 0.3);
return mix(mix(pulled, raised, cheer), flail, fallMs < 0 ? 0 : Math.min(1, fallMs / 120));
});
/* 6. Draw. Everything is clipped to the inside of the bar, so nothing ever leaves its border. */
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, CW, CH);
ctx.save();
ctx.beginPath();
const r = H / 2;
ctx.moveTo(r, 0);
ctx.arcTo(W, 0, W, H, r);
ctx.arcTo(W, H, 0, H, r);
ctx.arcTo(0, H, 0, 0, r);
ctx.arcTo(0, 0, W, 0, r);
ctx.closePath();
ctx.clip();
ctx.globalAlpha = fade;
const ink = getComputedStyle(canvas).color;
ctx.strokeStyle = ink;
ctx.fillStyle = ink;
ctx.lineCap = "round";
ctx.lineJoin = "round";
// The stone: a heavy slab with a chipped front, grit, pits and cracks that travel with it.
if (stone > -H * 0.5) {
const r2 = H / 2;
const edge: Pt[] = [];
for (let j = 0; j <= 8; j++) {
const y = (j / 8) * H;
const round = r2 - Math.sqrt(Math.max(0, r2 * r2 - (y - r2) ** 2));
const chip = j === 4 ? 0 : hash(j * 7.13) * H * 0.1; // the middle stays clean: the rope is tied there
edge.push(pt(stone - round * 0.8 - chip, y + rumble));
}
ctx.save();
ctx.beginPath();
ctx.moveTo(-H, edge[0].y);
for (const e of edge) ctx.lineTo(e.x, e.y);
ctx.lineTo(-H, edge[8].y);
ctx.closePath();
ctx.globalAlpha = fade * STONE;
ctx.fill();
ctx.clip();
// Its weight: a darker underside.
for (let band = 0; band < 14; band++) {
ctx.globalAlpha = fade * 0.009;
ctx.fillRect(-H, H * (0.5 + band * 0.036) + rumble, stone + H, H);
}
// Grain, pits and cracks, laid out in fixed tiles counted back from the front, so they move with it.
const tile = H * 0.85;
const k = H / 38;
ctx.lineWidth = Math.max(0.8, H / 40);
for (let n = 0; n * tile < stone + H; n++) {
for (let g = 0; g < 4; g++) {
const gx = stone - (n + hash(n * 13 + g)) * tile;
const gy = (0.15 + hash(n * 29 + g * 3) * 0.7) * H + rumble;
ctx.globalAlpha = fade * (0.2 + hash(n * 37 + g) * 0.2);
ctx.beginPath();
ctx.arc(gx, gy, (0.5 + hash(n * 31 + g) * 0.8) * k, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = fade * 0.1;
ctx.beginPath();
ctx.ellipse(stone - (n + hash(n * 41)) * tile, (0.3 + hash(n * 43) * 0.4) * H + rumble, (1.8 + hash(n * 47) * 1.4) * k, (1.1 + hash(n * 53) * 0.8) * k, 0, 0, Math.PI * 2);
ctx.fill();
if (hash(n * 17) < 0.55) {
const fromTop = hash(n * 23) < 0.5;
let cx = stone - (n + hash(n * 19)) * tile;
let cy = (fromTop ? 0 : H) + rumble;
ctx.globalAlpha = fade * 0.32;
ctx.beginPath();
ctx.moveTo(cx, cy);
for (let c = 0; c < 3; c++) {
cx += (hash(n * 59 + c) - 0.5) * H * 0.28;
cy += (fromTop ? 1 : -1) * H * (0.12 + hash(n * 61 + c) * 0.1);
ctx.lineTo(cx, cy);
}
ctx.stroke();
}
}
ctx.restore();
// The chipped front edge.
ctx.globalAlpha = fade * 0.6;
ctx.lineWidth = Math.max(1.1, H / 30);
ctx.beginPath();
edge.forEach((e, i) => (i ? ctx.lineTo(e.x, e.y) : ctx.moveTo(e.x, e.y)));
ctx.stroke();
ctx.globalAlpha = fade;
}
// Dust kicked up where the stone grinds along the bottom.
dust = dust.filter((d) => d.age < d.life);
for (const d of dust) {
d.age += dt;
d.vy += H * 0.0000012 * dt;
d.x += d.vx * dt;
d.y += d.vy * dt;
ctx.globalAlpha = fade * 0.4 * (1 - d.age / d.life);
ctx.beginPath();
ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = fade;
// The rope: taut from the front of the stone to the front hand, then a short tail behind.
if (cheer < 0.98 && shove < 1) {
const front = hands[0].x < hands[1].x ? hands[0] : hands[1];
const rear = front === hands[0] ? hands[1] : hands[0];
ctx.globalAlpha = fade * appear * (1 - cheer) * (1 - shove);
ctx.lineWidth = lw * 0.75;
ctx.beginPath();
const ropeY = H / 2 + rumble;
if (stone < front.x - 0.5) {
ctx.moveTo(stone, ropeY);
const sag = waiting ? 0 : body * 0.015;
ctx.quadraticCurveTo((stone + front.x) / 2, (ropeY + front.y) / 2 + sag + tremble * 0.4, front.x, front.y);
} else ctx.moveTo(front.x, front.y);
ctx.lineTo(rear.x, rear.y);
ctx.quadraticCurveTo(rear.x + body * 0.1, rear.y + body * 0.02, rear.x + body * 0.14, rear.y + body * 0.12);
ctx.stroke();
ctx.globalAlpha = fade;
}
// Once shoved, they leave the bar: drawn without the clip, tumbling backwards as they fall.
ctx.globalAlpha = fade * appear;
if (fallMs >= 0) {
ctx.restore();
ctx.save();
ctx.strokeStyle = ink;
ctx.fillStyle = ink;
ctx.lineCap = "round";
ctx.lineJoin = "round";
const k = drop / DROP_MS;
ctx.globalAlpha = fade * (k < 0.55 ? 1 : Math.max(0, 1 - (k - 0.55) / 0.45));
ctx.translate(drop * 0.03 * (H / 38), DROP * H * Math.min(1, k) ** 2);
ctx.translate(hip.x, hip.y);
ctx.rotate(1.7 * Math.min(1, k) ** 1.2);
ctx.translate(-hip.x, -hip.y);
}
// Legs and arms.
ctx.lineWidth = lw;
ctx.beginPath();
for (const f of feet) {
const [knee, foot] = joint(hip, f, thigh, 1); // knees bend toward the fill
ctx.moveTo(hip.x, hip.y);
ctx.lineTo(knee.x, knee.y);
ctx.lineTo(foot.x, foot.y);
}
for (const hand of hands) {
const [elbow, reach] = joint(shoulder, hand, body * 0.165, cheer > 0.5 ? (hand.x < shoulder.x ? -1 : 1) : -1);
ctx.moveTo(shoulder.x, shoulder.y);
ctx.lineTo(elbow.x, elbow.y);
ctx.lineTo(reach.x, reach.y);
}
// Body.
ctx.moveTo(hip.x, hip.y);
ctx.lineTo(neck.x, neck.y);
ctx.stroke();
// Head.
ctx.beginPath();
ctx.arc(head.x, head.y, headR, 0, Math.PI * 2);
ctx.fill();
// Sweat: a drop flies off the back of the head while they strain.
if (!reduce && strainMs > 900 && t - sweatAt > SWEAT_MS) {
sweatAt = t;
drops.push({ x: head.x + headR * 0.9, y: head.y - headR * 0.5, vx: body * 0.0014, vy: -body * 0.0016, age: 0 });
}
drops = drops.filter((d) => d.age < 650);
for (const d of drops) {
d.age += dt;
d.vy += body * 0.000009 * dt;
d.x += d.vx * dt;
d.y += d.vy * dt;
ctx.globalAlpha = fade * 0.75 * (1 - d.age / 650);
ctx.beginPath();
ctx.arc(d.x, d.y, Math.max(0.9, body * 0.035), 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
// The loop can rest only when nothing on screen will change.
const busy = L.looping || !settled || drops.length > 0 || dust.length > 0 || (fallMs >= 0 && fallMs < STUMBLE_MS + DROP_MS) || appear < 1 || (!isDone && !reduce) || walk > 0.01;
return busy;
};
const frame = (t: number) => {
raf = 0;
if (!W || !H) return;
const dt = last ? Math.min(50, t - last) : 16;
last = t;
if (draw(t, dt) && visible && !document.hidden) raf = requestAnimationFrame(frame);
else last = 0;
};
kick.current = () => {
if (!raf && visible && !document.hidden) raf = requestAnimationFrame(frame);
};
const ro = new ResizeObserver(size);
ro.observe(inner);
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
if (visible) kick.current();
});
io.observe(root);
const onVis = () => {
last = 0;
kick.current();
};
document.addEventListener("visibilitychange", onVis);
window.addEventListener("resize", size);
motion.addEventListener?.("change", onVis);
// A theme switch changes the colors: redraw even when the loop is resting.
const scheme = window.matchMedia("(prefers-color-scheme: dark)");
scheme.addEventListener?.("change", onVis);
const mo = new MutationObserver(onVis);
mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] });
size();
return () => {
cancelAnimationFrame(raf);
raf = 0;
kick.current = () => {};
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", onVis);
window.removeEventListener("resize", size);
motion.removeEventListener?.("change", onVis);
scheme.removeEventListener?.("change", onVis);
mo.disconnect();
};
}, []);
const start = looping ? 0 : target;
const ariaLabel = typeof label === "string" && label ? label : "Loading";
const rootStyle = { ...style, "--twl-h": `${h}px`, ...(color ? { "--twl-c": color } : null) } as CSSProperties;
return (
<div
ref={rootRef}
role="progressbar"
aria-label={ariaLabel}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={looping ? undefined : Math.round(start * 100)}
aria-busy={looping || start < 1 ? true : undefined}
className={className ? `twl ${className}` : "twl"}
style={rootStyle}
{...rest}
>
<style>{CSS}</style>
<div className="twl-track">
<div ref={innerRef} className="twl-inner">
<canvas ref={canvasRef} className="twl-canvas" aria-hidden="true" />
</div>
</div>
{(label != null && label !== false && label !== "") || showValue ? (
<div className="twl-row" aria-hidden="true">
<span className="twl-label">{label}</span>
{showValue ? (
<span ref={valueRef} className="twl-value">
{Math.round(start * 100)}%
</span>
) : null}
</div>
) : null}
</div>
);
}
```
Usage
Pass your real progress as value. Without it the bar loops, which suits waits you can't measure.
"use client";
import { TugOfWorkLoader } from "@/components/ui/tug-of-work-loader";
export function UploadProgress({ percent }: { percent: number }) {
return (
<TugOfWorkLoader
value={percent} // 0 to 100; leave it out to loop on its own
label="Developers are working really hard." // optional: the support text under the bar
color="var(--foreground)" // optional: the person, rope, border and stone tint
onComplete={() => toast("Upload done")} // optional: runs when it reaches 100
className="max-w-sm"
/>
);
}At 100% the person falls about three bar heights below the bar's right end, over whatever sits there, for about a second.
How it moves
The fill is a slab of stone, see-through like the bar around it. The only solid thing in it is the person.
The filled part of the bar is a heavy slab of stone: grain, pits and cracks that travel with it, a darker underside and a chipped front edge. A tiny person stands ahead of it, leaning back on a rope tied to that edge. As the progress grows they walk backwards and drag it along, their steps matching the distance pulled. The stone is heavy, so it drags a little behind on each step, lurches forward, rumbles as it grinds and kicks up dust along the bottom. When the bar waits, they keep heaving on the rope, lean further back, shake a little and now and then a drop of sweat flies off, while the stone only budges a hair and puffs a little dust. Near the end they run out of room, so they stay put and pull the rope in hand over hand until the stone reaches them. At 100% the stone shoves them backwards out of the end of the bar: they scramble, let go of the rope, windmill their arms, then tumble off and fall about three bar heights, fading as they go. When looping, the finished bar rests for a moment, fades and starts over with them back at the start. Until that fall, everything, the stone, the person, the rope, the sweat and the dust, stays inside the border. With reduced motion, the stone still moves but the person stands still, with no steps, heaves, lurches or dust, and at 100% they raise their arms instead of falling.
Props
| Prop | Default | What it does |
|---|---|---|
value | — | Progress from 0 to 100. The person drags the stone to it, never faster than about a third of the bar a second. Leave it out and the bar loops on its own, pulling and pausing like real work. |
label | "Developers are working really hard." | The support text under the bar. It wraps on narrow screens. Pass null to hide it. |
showValue | true | Shows the percentage at the right, under the bar. |
color | the text color around it | The person, the rope, the border and the stone's tint. Any CSS color, including var(--…). The bar and the stone stay see-through. |
height | 44 | How tall the bar is in px, 28 to 64. The person grows with it, and so does their fall at 100%. |
duration | 8000 | Looping only: how long one pull from 0 to 100 takes, in ms, 3000 to 30000. |
onComplete | — | Runs each time the stone reaches 100. |
className / style, aria-*, … | — | On the outer box. It fills the width it is given, so set a max width here. |