react-swarm-rebuild
v0.4.2
Published
A swarm of multiplayer-style cursors rebuilds your React UI with drawing, typing, guides and flocking animations.
Maintainers
Readme
react-swarm-rebuild
A swarm of colorful cursors reconstructs your React UI. React 18 / 19, TypeScript, ESM and CommonJS. MIT, Nguyễn Quốc Cường.

Source code · npm · Report an issue
Quick start
import { useRef } from 'react';
import { SwarmRebuild } from 'react-swarm-rebuild';
export function Dashboard({ loading, children }) {
const content = useRef<HTMLDivElement>(null);
return <>
<div ref={content}>{children}</div>
<SwarmRebuild target={content} ready={!loading} />
</>;
}By default (preset="studio"), a boids swarm orbits your site emblem while your UI loads, then reconstructs it with full multiplayer design-tool choreography: gray wireframe placeholders morphing into real fills, top-to-bottom media sweeps, #0D99FF 4-handle selection boxes with W × H badges, auto-sliding dark Figma-style rulers, cursor-dragged red alignment guides with magnetic text snapping, inline blinking carets with stepped heading growth, pen-tool vector borders with anchor dots, subtree Alt-drag duplication with red pixel spacing and double-click select-all retyping, dynamic agent scaling (8–48), procedural Web Audio, and a floating studio HUD. When finished, the swarm flocks around your pointer until you click Go live, tap the canvas, or press Esc.
Pass preset="minimal" for the lightweight, HUD-free component loader experience (measured colored carets, parallel drawing, auto radial exit, no rulers/guides/sound). Component targets only cover their own visible area; the surrounding header, sidebar and controls remain interactive.
Loading and the transition into reconstruction
- The overlay covers the target immediately. Cursors fade in while your original React tree stays mounted and loads underneath.
ready={false}keeps the cursors orbiting. Set it totrueafter your data and fonts have settled; this does not restart the orbit.- Once ready and the minimum intro has elapsed, the library measures the DOM cooperatively across animation frames. The cursors keep floating during this work.
- A short handoff slows the orbit. Workers depart with staggered timing and retain their departure velocity instead of snapping to a new trajectory.
- Boxes/media are drawn and text is typed. Idle workers gently drift near their previous position while waiting for their next assignment.
- All cursors leave directly from their current positions in a radial burst. They do not regroup at the center. The cover fades back to the live UI and is removed.
snapshotBudget controls the approximate measurement budget per frame. Smaller budgets leave more time for cursor movement but take more frames to prepare the snapshot. A single DOM/media operation may exceed that budget. It is a scheduling budget, not a guaranteed frame-time limit.
For an application entrance with no initial content flash, start the imperative controller in useLayoutEffect, after the DOM has mounted and before the first browser paint:
import { useLayoutEffect, useRef } from 'react';
import { createSwarmRebuild } from 'react-swarm-rebuild';
import type { SwarmController } from 'react-swarm-rebuild';
export function Overview({ ready, children }) {
const target = useRef<HTMLDivElement>(null);
const controller = useRef<SwarmController | null>(null);
useLayoutEffect(() => {
const swarm = createSwarmRebuild({ target, ready: false });
controller.current = swarm;
swarm.start();
return () => {
swarm.destroy();
controller.current = null;
};
}, []);
useLayoutEffect(() => {
let cancelled = false;
controller.current?.setReady(false);
if (!ready) return;
Promise.resolve(document.fonts?.ready).then(() => {
if (!cancelled) controller.current?.setReady(true);
});
return () => { cancelled = true; };
}, [ready]);
return <div ref={target}>{children}</div>;
}The declarative SwarmRebuild component uses useEffect for server-rendering compatibility. The opaque cover is installed synchronously by start(). fadeIn fades the cursors/decorations over that cover, so the real page does not flash through while it loads.
Studio defaults & minimal preset
On this branch, preset="studio" is the default. Switch back to the lightweight loader defaults with preset="minimal", or override any individual option directly:
// Full studio choreography (default)
<SwarmRebuild target={content} />
// Lightweight loader mode
<SwarmRebuild target={content} preset="minimal" />| Option | 'studio' (default) | 'minimal' preset | Behavior |
| --- | --- | --- | --- |
| wireframe | true | false | Two-stage gray placeholder (+ media icon) → fill/border/radius reveal & top-down image sweep |
| headingGrow | true | false | Type large headings (>= 28px) at 18px scale, then step up through typographic stops |
| duplicateGroups | true | false | Detect repeated sibling subtrees; Alt-drag copy from master with red pixel spacing, then double-click select-all & retype / blur-swap / restyle |
| penTool | true | false | Extract <hr> and partial 1–3 side borders as pen-tool vector polylines with live rubber-band & anchor nodes |
| caretStyle | 'inline' | 'cursor' | 'inline' uses a blinking inline caret + offset I-beam & baseline underline; 'cursor' tracks colored I-beam per grapheme |
| selectionStyle | 'studio' | 'worker' | 'studio' renders #0D99FF 4-handle selection boxes + dotted ruler projection lines & #F24822 guides/spacing |
| boids | true | false | Organic boids steering physics with neighbor alignment, velocity-aligned rotation, and pointer repulsion |
| dynamicAgents | true (unless cursorCount pinned) | false | Dynamically scales agents (8–48) with scroll velocity and backlog |
| showRulers | 'auto' | false | 'auto' (dark Figma-style SVG rulers slide in during guide drags), true (always mounted), or false |
| showGuides | true | false | Cursors drag red guides from rulers; aligned text snaps magnetically with overshoot & glow |
| controls | true | false | Floating dark glass HUD pill (avatars, layer count, progress bar, Pause, Tour, Speed, Sound, Hide, Go live, Replay) |
| sound | true | false | Procedural Web Audio synthesizer (convolver reverb, E-major pentatonic glass piano, mechanical keyboard clack, clicks, snaps, sweeps) |
| finishBehavior | 'flock' | 'live' | Keep cursors flocking around your pointer until Go live / skip, or auto-exit on completion |
| introLogo | 'favicon' | 'glyph' | Site favicon with monogram fallback, '↗' glyph, or 'none' |
Motion options
All of these work as React props or imperative/hook options, and any individual option overrides the selected preset ('studio' by default, or 'minimal'):
| Option | 'studio' (default) | 'minimal' | Behavior |
| --- | --- | --- | --- |
| showRulers | 'auto' | false | Dark SVG rulers: 'auto' (slide in for guide drags), true (always visible), or false |
| showGuides | true | false | Dragged red alignment guides with magnetic text snapping and red duplicate-distance measurements |
| clickToSkip | true | true | Click/tap the covered area to reveal the UI immediately |
| floatingIntro | true | true | Slowly rotating orbit with independent bobbing and breathing motion (non-boids mode) |
| floatingIdle | false | true | Idle workers drift locally near their last position or next queued task |
| floatAmplitude | 1 | 1 | Intro/idle movement amplitude multiplier, 0.25–3 |
| floatSpeed | 1 | 1 | Intro/idle movement speed multiplier, 0.25–3 |
| parallelDrawing | false | true | Start child/duplicate tasks while backing surfaces are underway; false waits for complete ancestors/masters |
| smoothTransition | false | true | Soft orbit-to-work handoff ('studio' fans straight out of boids orbit into work) |
| transitionDuration | 0 | 480 | Handoff duration, real milliseconds, 0–3,000 |
| fadeIn | true | true | Fade in cursors, the intro emblem and optional controls |
| fadeInDuration | 360 | 360 | Entrance duration, real milliseconds, 0–3,000 |
| typing | true | true | Reveal text by grapheme instead of fading whole text in |
| typingSpeed | 45 | 45 | Graphemes per animation second (cursor-caret mode), 5–300, multiplied by speed |
| burstOnComplete | true | true | Radial cursor exit when finishBehavior is 'live' |
| exitDuration | 700 | 700 | Exit duration, real milliseconds, 0–3,000 |
| snapshotBudget | 4 | 4 | Approximate DOM measurement budget per frame, milliseconds, 1–12 |
Where Intl.Segmenter is available, combining marks, Vietnamese accents and emoji sequences are typed as complete graphemes in both 'inline' and 'cursor' caret modes. Other browsers fall back to Unicode code points. With typing={false}, text appears without typing.
Auto-exiting studio configuration (no floating HUD, cursors scatter radially when done — used in the Lexor Admin dashboard):
<SwarmRebuild
target={content}
ready={!loading}
preset="studio"
controls={false}
sound={false}
finishBehavior="live"
burstOnComplete
/>Or switch to the lightweight loader preset and customize individual options:
const swarm = createSwarmRebuild({
target: '#overview',
preset: 'minimal',
showRulers: true,
showGuides: true,
floatingIntro: false, // Uniform orbit.
floatingIdle: false, // Follow the user's mouse while idle.
smoothTransition: false, // Skip the handoff and staggered delays.
fadeIn: false, // Cursors appear immediately.
typing: false, // Reveal complete text instead of typing.
burstOnComplete: false, // Remove the overlay immediately on completion.
clickToSkip: false, // Esc and imperative goLive() still work.
});A component-scoped burst is clipped at the component's boundary. Cursors never fly across its header/sidebar or block other components. With finishBehavior: 'flock' (the 'studio' default), cursors flock around your pointer after completion until you click Go live, click/tap the canvas, press Esc, or call goLive().
Concurrent work and cursor count
cursorCount sets the worker-pool size, independently of playback speed. It is available on SwarmRebuild, useSwarmRebuild, and createSwarmRebuild. The default is 16; values are constrained to whole numbers from 2 to 48.
<SwarmRebuild
target={content}
ready={!loading}
cursorCount={24}
parallelDrawing
floatAmplitude={1.2}
floatSpeed={1.15}
/>const swarm = createSwarmRebuild({ target: '#overview', cursorCount: 24 });
swarm.start();
swarm.setCursorCount(32); // Add workers without restarting the overlay.
swarm.setCursorCount(8); // Free workers leave; busy excess workers finish first.Changing the React cursorCount prop also resizes the existing pool. Growing the pool fades in the new workers. Shrinking it preserves any drawings already in flight, so the actual state.agents count can temporarily exceed the requested count until those workers finish. Changes during the radial exit apply to the next run.
The scheduler preserves DOM stacking order while allowing more work to overlap. With parallelDrawing: true, a child becomes eligible after its backing surface reaches 15% draw progress; duplicate tasks become eligible after their source reaches 35%. Text and media still remain hidden until their own cursor reaches them and starts drawing. Set parallelDrawing: false to restore strict parent/source completion ordering.
The number actually drawing at once depends on available tasks and their dependencies. Workers with no eligible task stage near distinct upcoming tasks, with wider, faster, independently phased floating motion. They do not paint fake content while waiting. floatAmplitude and floatSpeed tune the waiting motion independently of reconstruction playback speed.
In the Lexor Admin integration, Theme → Swarm preset switches between Studio (default) and Minimal, and Theme → Concurrent cursors chooses 2–48 workers (default 24), saved locally in localStorage.
Other options
| Option | Default ('studio') | Purpose |
| --- | --- | --- |
| preset | 'studio' | 'studio' (full design-tool choreography) or 'minimal' (lightweight loader) |
| target | document.body | Selector, HTMLElement or React ref |
| scope | target for components, viewport for body | Component clipping or full-viewport effect |
| ready | true | Wait for application content before measuring |
| finishBehavior | 'flock' ('live' in minimal) | Keep flocking until Go live/skip, or burst and remove automatically |
| controls | true (false in minimal) | true for the dark floating HUD; 'minimal' for status only; false to hide |
| cursorCount | 18 (16 in minimal) | 2–48 workers; passing it pins pool size and disables dynamic scaling |
| speed | 1 | Reconstruction/typing multiplier, 0.25–8 |
| introDuration | 1500 (1600 in minimal) | Minimum orbit time in animation milliseconds; also waits for ready |
| sound | true (false in minimal) | Procedural Web Audio synthesizer; unlocks automatically on user gesture |
| tour | false | Auto-scroll viewport or target's scrolling container while building below-the-fold layers |
| showNames | false | Optional collaborator name badges |
| names, colors | Built-in 12-color palette | Custom nonempty arrays |
| maxLayers | 4000 (2500 in minimal) | Snapshot limit, 1–10,000 |
| background | Nearest opaque ancestor | Cover background color |
| zIndex | 2147483000 | Overlay stacking order |
| respectReducedMotion | true | Skip all motion when the user requests reduced motion |
| active | true | React component only: start/stop when this changes |
Entrance, handoff, floating motion and radial exit use real time. speed affects reconstruction, typing and the minimum intro clock; it does not make the buoyant drift or radial exit abruptly faster.
ready, cursorCount, speed, sound, and tour update an existing React instance. Other options apply to the next start/replay. Use one active instance per target.
Scope, skipping and cleanup
A component target is intersected with its viewport and scrolling/clipping ancestors. The cover intercepts clicks only inside that area. Header/sidebar clicks outside it keep their normal behavior and do not skip the effect. Clicking the cover removes it on the click event, so the same click cannot activate a covered application link/button.
With clickToSkip, the covered area is also keyboard-focusable and supports Enter/Space. Esc always closes the effect. There is no focus trap for component-scoped effects. Full-toolbar buttons still perform their own actions rather than triggering click-to-skip.
Offscreen content is omitted from component snapshots, so an inner scrolling container cannot prevent completion. Scrolling, changing the viewport width, removing the target, or changing scoped geometry during reconstruction reveals the live UI or disposes the run. This avoids stale geometry. The next start captures the new layout.
stop(), goLive(), destroy(), React unmount and active={false} cancel measurement and animation, including an in-progress handoff or radial exit. Reduced motion skips directly to the live UI without creating an overlay.
Controller and callbacks
const swarm = createSwarmRebuild({ target: '#overview', ready: false });
swarm.start();
// Render/load data in parallel, then:
swarm.setReady(true);
// On navigation:
swarm.destroy();useSwarmRebuild(options) exposes the same controller plus reactive state. Methods: start, replay, stop, goLive, pause, resume, setReady, setCursorCount, setSpeed, setSound, setTour, getState, destroy. A destroyed imperative instance cannot be restarted. The React hook handles Strict Mode and unmount cleanup.
Callbacks:
onStateChange(state): phase/progress updates, limited to roughly seven per second during animation, plus phase transitions.onComplete(): called once when all captured layers have been reconstructed, before the radial exit. Also called when reduced motion skips reconstruction.onError(error): target or snapshot errors. The overlay is removed on snapshot failure.
State fields: phase, progress, completed, total, agents, speed, sound, tour. Phases: idle, scanning, intro, transition, building, paused, complete, exiting, live.
Watch phase === 'live' to know that the automatic exit has finished and the overlay is gone. A skipped run does not call onComplete(). pause() freezes the animation, including a handoff or exit; resume() continues it.
0.4.1
- Support
tour: trueauto-scrolling insidescope: 'target'and inner scrolling containers (such as dashboard app shells), capturing offscreen target content and advancing the scroll frontier smoothly without aborting on vertical scroll.
0.4.0
- New
presetoption supporting both'studio'(default) and'minimal'(lightweight v0.3.x loader mode), plus granular toggles (wireframe,headingGrow,duplicateGroups,penTool,caretStyle,selectionStyle,boids,dynamicAgents,introLogo). - Full clean-room multiplayer design-tool choreography: two-stage gray wireframe placeholders (+ media icon) morphing into real fills and top-down image sweeps,
#0D99FF4-handle selection boxes with liveW × Hbadges and dotted ruler lines, auto-sliding dark Figma-style SVG rulers, cursor-dragged red alignment guides with magnetic text snapping (overshoot + glow), inline blinking carets with stepped heading growth, pen-tool vector borders/dividers with live rubber-band and anchor vertices, and subtree Alt-drag component duplication with red pixel spacing, double-click select-all retyping, blur-swap media and restyle transitions. - 9 original vector SVG cursor shapes (
arrow,dup,cross,ibeam,pen,pen-add,pen-close,ew,ns) with click-press squash and velocity-aligned flight rotation. - Organic boids steering physics with neighbor alignment, pointer repulsion, dynamic 8–48 agent scaling, scroll-reactive tempo, and
under/world/overlayer planes (::before/::after, float shims, Shadow-DOM SVG<use>/url(#id)inlining, frosted sticky backdrops). - Upgraded procedural Web Audio synthesizer: stereo room convolver reverb, compressor, E-major pentatonic glass-piano chimes quantized to a beat grid, dual-layer mechanical keyboard clacks, press/release clicks, guide snaps, rising heading-grow ticks, and lifecycle sweeps.
- Updated
assets/demo.gifpreview and Lexor Admin Theme preset selector (Studio/Minimal).
0.3.0
- Fix SVG/media descendants escaping hidden snapshot layers before their own drawing starts.
- Preserve CSS
rotate,scaleand 2D/3Dtransformgroups during reconstruction so tilted/scaled elements and their text are drawn and typed in place without snapping at completion. - Merge inline formatting flows (
<strong>,<em>,<a>,<br>, adjacent JSX text nodes), gradient-clipped text (background-clip: text), ellipsis clipping and form field values into cohesive typing tasks. - Curved cursor flight paths with velocity banking, diagonal 2D surface reveal, human typing cadence, and randomized scatter trajectories on completion.
- Resize the cursor pool during a run with
setCursorCountor the React prop. - Parallelize work across partially drawn surfaces and stage waiting cursors near upcoming tasks.
- Stronger, faster floating motion with
floatAmplitudeandfloatSpeedcontrols. - Lexor Admin adds a local-only concurrent cursor count in Theme.
0.2.0
- Rulers/red guides are opt-in; toolbar is hidden by default.
- Click/tap the effect to skip, without a visible skip button or click-through.
- Buoyant intro and local idle drift; smooth, staggered handoff with cooperative snapshots.
- Grapheme-aware typewriter text and colored carets that follow actual line geometry.
- Fade-in entrance and radial cursor exit, with independent options and durations.
0.1.1
- Component-scoped overlays preserve surrounding layout and interactions.
- Orbit before snapshot; readiness can change while data renders in parallel.
- Automatic cleanup on completion, including inner scrolling containers.
Inspired by Swarm by Joel Califa and Swarm Cursors by Dhvanil Patel. This is an independent implementation; no upstream code or artwork is bundled. See NOTICE.md.
