npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dirtytalk/spatial

v0.2.0

Published

Rect-based damage-tracking instantiation of @dirtytalk/engine, for canvas/GPU renderers and any 2D scene graph.

Readme

@dirtytalk/spatial

Rect-based damage-tracking instantiation of @dirtytalk/engine, for canvas/GPU renderers and any 2D scene graph.

[!WARNING] BlaC v2 is in pre-release (beta). While in beta, breaking API changes may ship in patch releases without a major version bump. Pin an exact version and check the changelog before upgrading. Strict semver resumes once v2 is officially out of beta.

Why this exists

Two libraries — a WebGPU renderer and a state container — solve the same problem in different domains: after a mutation, what changed, who cares, and when do we tell them? Today both answer this at the consumer: the renderer repaints the whole canvas because it has no rect-level damage info; the state container re-walks state N times for N subscribers. The shared move is to compute "what changed" once at the source, in a format every subscriber can intersect cheaply. This package is that compute layer for the 2D spatial domain.

Single-dirty-bit invalidation is the root of the problem. Once you record only whether something changed, you've lost the information you need to do less work. This package replaces the dirty bit with a damage list: each entry carries a Rect and a DamageKind. kind tells the render pipeline which stages to run (data → layout → paint); rect tells the renderer exactly what area to rasterise. A v1 renderer may repaint the bounding rect of all damage entries — the same work as before. In v2 a scissor/tile partial-redraw path uses the individual entries. No API change to scene nodes or callers either way.

What's in the box

  • Rect / min-max RectBounds types + helpers: rectOverlaps, rectEquals, rectArea, rectsNear, unionRects, in-place unionInto, rectClamp, pointInRect, and rectFromBounds / boundsFromRect converters (optional caller-owned output).
  • Damage entry record + DamageKind type ('paint' | 'layout' | 'data').
  • RectSpace — the Space<Damage[]> implementation that wires the engine to the 2D rect algebra.
  • planRegions — a standalone repaint planner (rects/bounds/full strategies, configurable region budget, opt-in nearest-centre cap reduction, disjoint/slack merging and area promotion).
  • diffBoxes — keyed box diffing: compare two Maps of box snapshots and get the raw damage footprints of what was added, removed, moved, or restyled.
  • diffAlignedBoxes — Float32 min/max boxes + Uint32 content-token snapshots, matched by index, with a synchronous change visitor and early stop; no per-entry object allocation.
  • SceneNode<Ctx> — abstract base class for any painted object; owns bounds, parent chain, markDamaged, paintChildren and visualBounds.
  • SceneRoot<Ctx> — concrete subclass that owns the DirtyChannel<Damage[]> and scheduler, drives the data → layout → paint pipeline, and calls the Renderer2D contract. Accepts plan options, exposes repaint(), and runs a prepareFrame preparation seam before the paint cull.
  • Renderer2D<Ctx> interface — the contract a real GPU renderer plugs into (beginFrame returns the paint context, endFrame always follows it, plus an optional prepareFrame for repair/full-frame decisions); this package ships the interface, not an implementation.
  • PointerRouter<Ctx> — pointer dispatch via hit-testing the scene tree; accepts the surface-agnostic SpatialPointerEvent shape.
  • SpatialPointerEvent + PointerHandler — the framework-agnostic event types.

Install

pnpm add @dirtytalk/spatial @dirtytalk/engine

Quick example — minimal scene

import { SceneNode, SceneRoot } from '@dirtytalk/spatial';
import type { Renderer2D, Rect } from '@dirtytalk/spatial';
import { SyncScheduler } from '@dirtytalk/engine';

// --- Stub renderer (logs the paint region instead of rasterising) ---
const stubRenderer: Renderer2D = {
  beginFrame(regions: readonly Rect[]): void {
    console.log('beginFrame', regions);
  },
  endFrame(): void {
    console.log('endFrame');
  },
};

// --- A simple button node ---
class Button extends SceneNode {
  private _label = '';

  get label(): string {
    return this._label;
  }

  setValue(label: string): void {
    if (this._label === label) return;
    this._label = label;
    this.markDamaged('paint');
  }

  paint(): void {
    // Draw the button into the context beginFrame returned.
  }
}

// --- Wire it up ---
const root = new SceneRoot(stubRenderer, {
  scheduler: new SyncScheduler(),
  bounds: { x: 0, y: 0, w: 800, h: 600 },
});

const btn = new Button({ bounds: { x: 10, y: 10, w: 120, h: 40 } });
root.adoptChild(btn);

// Mutate — damage flows to the renderer automatically.
btn.setValue('Click me');
// => beginFrame [ { x: 10, y: 10, w: 120, h: 40 } ]
// => endFrame

A real renderer — such as a WebGPU layer that wraps a GPUDevice — would plug in via the same Renderer2D<Ctx> interface: beginFrame sets up the render pass, applies the scissor rect and returns the context (Ctx, here a render pass) that every node's paint(ctx, regions) receives; endFrame submits the command encoder and is called even when a paint throws.

Quick example — pointer routing

import { PointerRouter } from '@dirtytalk/spatial';
import type { SpatialPointerEvent } from '@dirtytalk/spatial';

const router = new PointerRouter(root);

// Translate a DOM PointerEvent to SpatialPointerEvent and dispatch.
canvas.addEventListener('pointerdown', (e) => {
  const spatialEvent: SpatialPointerEvent = {
    type: 'down',
    x: e.offsetX,
    y: e.offsetY,
    buttons: e.buttons,
    pointerId: e.pointerId,
  };
  const handled = router.dispatch(spatialEvent);
  // `handled` is the node whose handler ran, or null.
});

PointerRouter.dispatch hit-tests the scene (topmost, deepest node whose bounds contain the point) and delivers the event to that node's PointerHandler method, or to the nearest ancestor that implements it. It returns the node that handled the event, or null. A down captures the handling node: later move, up and cancel events for that pointer go to it until up or cancel, or until it leaves the scene, after which move routes by hit again. Hover is handled the same way as clicks — route pointermove events through the same dispatch call and let nodes call markDamaged('paint') in their onPointerMove if they change appearance on hover.

API surface — public exports

| Export | File | Role | | ------------------------------------------------------------------- | --------------------- | ------------------------------------------------------------ | | Rect | types.ts | 2D axis-aligned rectangle (CSS pixels) | | DamageKind | types.ts | 'paint' \| 'layout' \| 'data' | | Damage | types.ts | Single damage entry: { rect, kind, node? } | | DirtyRegion | types.ts | readonly Damage[] — the channel's Region type | | rectOverlaps | rect.ts | True if two rects share any area | | rectEquals | rect.ts | Deep equality for rects | | unionRects | rect.ts | Bounding rect of a list of rects | | rectClamp | rect.ts | Clamp inner rect to outer rect | | rectArea, rectsNear | rect.ts | Non-negative area and per-axis slack comparison | | unionInto | rect.ts | Mutate and return destination bounding rect | | RectBounds | rect.ts | Structural min/max corner bounds | | rectFromBounds, boundsFromRect | rect.ts | Convert corners/extents, optionally into caller output | | RectSpace | rect-space.ts | Space<Damage[]> for the engine | | planRegions | region-plan.ts | Configurable repaint planner (rects/bounds/full) | | RepaintStrategy | region-plan.ts | 'rects' \| 'bounds' \| 'full' | | RegionPlan | region-plan.ts | { kind: 'partial' } \| { kind: 'full' } result | | RegionPlanOptions | region-plan.ts | strategy, maxRegions, capStrategy, disjoint, promoteFraction | | RegionCapStrategy | region-plan.ts | 'bounds' (default) or 'nearest' | | diffBoxes | box-diff.ts | Keyed box diff → raw damage footprints | | BoxSnapshot | box-diff.ts | { rect, content } keyed by identity | | BoxDiffOptions | box-diff.ts | Custom equalsContent comparator | | diffAlignedBoxes | aligned-box-diff.ts | Visit aligned geometry/content changes and tails | | AlignedBoxes | aligned-box-diff.ts | { boxes: Float32Array, tokens: Uint32Array, count } | | AlignedBoxChangeKind, AlignedBoxVisitor, AlignedBoxDiffResult | aligned-box-diff.ts | Change visitor and completion status | | SceneNode<Ctx> | scene-node.ts | Abstract base for paintable nodes | | SceneNodeOptions | scene-node.ts | { bounds?, clipsOverflow? } constructor options | | SceneRoot<Ctx> | scene-root.ts | Root node; owns channel + render pipeline | | Renderer2D<Ctx> | scene-root.ts | Interface for the renderer contract | | PrepareFrameContext | scene-root.ts | Context handed to a renderer's prepareFrame | | PrepareFrameResult | scene-root.ts | Extra repair regions and/or a full-frame request | | PointerRouter<Ctx> | pointer-router.ts | Hit-test-based pointer dispatch with bubbling and capture | | SpatialPointerEvent | pointer-router.ts | Surface-agnostic pointer event shape | | PointerHandler | pointer-router.ts | Interface nodes implement to receive events |

Packed-array comparison and sparse cap reduction

import { diffAlignedBoxes, planRegions } from '@dirtytalk/spatial';

// Independently retained snapshots; boxes use minX, minY, maxX, maxY per entry.
const prev = {
  boxes: new Float32Array([0, 0, 10, 10]),
  tokens: new Uint32Array([1]),
  count: 1,
};
const next = {
  boxes: new Float32Array([5, 0, 15, 10]),
  tokens: new Uint32Array([1]),
  count: 1,
};
diffAlignedBoxes(prev, next, (index, kind) => {
  // Project/copy conservative old/new footprints only for changed entries here.
  // Return false to stop (for example when a renderer requires full repaint).
  console.log(index, kind); // 0, 'geometry'
});

planRegions(
  [{ x: 0, y: 0, w: 15, h: 10 }],
  { x: 0, y: 0, w: 800, h: 600 },
  {
    capStrategy: 'nearest',
    maxRegions: 12,
    disjoint: { slack: 4 },
    promoteFraction: 0.6,
  },
);

Aligned identity is position, not a stable key. Order/composition changes invisible to boxes/tokens need external invalidation; equal tokens are not a hash-collision guarantee. Counts and capacities are validated, and every entry that will be visited is checked for finite geometry before the first visit; unchanged entries are not checked and trailing capacity is ignored. Visits are ordered overlap then added/removed tail, with kinds geometry, content, geometry+content, add, remove. Zero/inverted AABBs are ordinary finite geometry, not renderer-specific raw-span sentinels. The result's completed is false only when visiting stopped; snapshots are neither mutated nor retained.

Nearest mode near-merges before applying the cap when disjoint, then merges nearest centres through twice the cap, rechecking disjointness after each union. Above twice the cap it collapses. Without disjoint it reduces raw clipped rects and skips near/area-aware merging. Ties are deterministic. Near-merging is a sort-and-sweep on left edges, so only x-overlapping pairs are tested. A shared 100,000 pair-comparison safety budget bounds near/nearest searches; exhaustion (hundreds of regions sharing an x range) collapses all clipped damage, possibly before a near fixpoint. Coverage and region budget remain conservative, but exact partitions are not promised. The existing bounds-collapse default is unchanged; neither mode is an adaptive cost model. Promotion remains inclusive (>=).

Geometry helpers are unchecked and assume finite valid geometry (near-test slack >= 0). rectArea clamps non-positive extents to zero. unionInto mutates its destination; a zero-size rect contributes its origin, so seed accumulation with the first rect, not an empty sentinel. Rects you pass to a node constructor, setBounds, markDamaged or repaint are copied, so later mutation of your rect does not affect the scene. Converters preserve signed extents. rectsNear includes touching at zero slack and compares per-axis gaps, not Euclidean distance.

Damage kinds

| Kind | When to emit | Pipeline stages triggered | | -------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------- | | paint | A visual-only field changed (colour, label, pressed state). | Paint only. | | layout | The node's bounds changed. setBounds emits this automatically. | Layout pass for the parent, then paint for old and new bounds. | | data | The node's input data set changed (e.g., a plot layer received new samples). | Data rebuild → layout → paint. All downstream stages run. |

Render pipeline

The SceneRoot processes a flush in three ordered stages:

Stage 1 — data. For each node with data damage, call node.rebuildData() if defined. This is where expensive operations like re-binning or recomputing mark geometry live.

Stage 2 — layout. For each node with data or layout damage, call node.doLayout() if defined. A data change always implies a layout pass for that node.

Each node runs each of these stages at most once per frame, however often it was marked. data and layout damage is not filtered by area, so a zero-size or off-screen node still gets its passes.

Stage 3 — paint. The frame's damage rects are clamped to the root bounds, then planned through planRegions with the root's plan options (defaults preserve the original rect-oriented policy: area-aware merging and a 16-region budget that collapses to the bounding rect past that). plan can select a bounds or full strategy, request pairwise-disjoint regions, or promote a mostly-full frame to a full repaint via promoteFraction. Before the cull, SceneRoot.prepareFrame (which delegates to Renderer2D.prepareFrame) may contribute extra repair regions or force a full repaint (first frame, resize, surface loss). The resulting regions are frozen: renderer.beginFrame(regions) and the culled paint walk use the exact same list, and the renderer must not widen the clear. renderer.beginFrame(regions) receives the result (never empty; a frame with nothing to repaint skips stage 3) and returns the paint context. The root's paint(ctx, regions) calls paintChildren, which paints the children whose visualBounds overlap a region, in adoption order; a container node's own paint does the same for its children. renderer.endFrame() is then always called, also when a paint throws. SceneRoot.repaint(region?) queues an explicit repaint. Subclasses can override protected paintFrame(regions) (returns the painted-node count) to replace this stage, e.g. with a deeper cull or their own renderer.

SceneRoot.dispose() cancels a pending frame and ignores later damage.

A node's visualBounds are its own bounds plus those of its descendants, unless the node sets clipsOverflow. Culling and hit-testing use them, so a child may sit outside its parent's bounds and is still repainted and hit. bounds, parent and children are read-only; change bounds with setBounds. Adding or removing a child damages its whole subtree. RectSpace compacts the accumulated damage list past 1024 entries (one entry per kind and node, holding the union rect), so damage that piles up while no frame runs, such as in a hidden tab, stays bounded.

A single state change — for example, button.setValue('Save') — emits one paint damage entry, skips stages 1 and 2, and goes directly to stage 3.

Repaint planning

planRegions(rects, bounds, options?) is a pure, standalone planner you can use without SceneRoot:

import { planRegions } from '@dirtytalk/spatial';

const plan = planRegions(
  [
    { x: 0, y: 0, w: 10, h: 10 },
    { x: 2, y: 0, w: 10, h: 10 },
  ],
  { x: 0, y: 0, w: 800, h: 600 },
  { disjoint: true, promoteFraction: 0.6 },
);
// plan.kind === 'partial' ? plan.regions : plan.reason
  • strategy: 'rects' | 'bounds' | 'full' — default 'rects' (area-aware merge).
  • maxRegions — region budget (default 16); overflow collapses to one bounding rect.
  • disjoint: boolean | { slack } — merge touching/overlapping pairs to a fixpoint so the output is pairwise disjoint (required for overlap-sensitive renderers such as OIT partial redraw).
  • promoteFraction — promote to a full repaint once planned coverage reaches this fraction of the bounds.

It rejects non-finite geometry and invalid options, clamps to the bounds, drops empty marks, and never mutates its inputs. A { kind: 'full' } plan is materialized as [bounds] by SceneRoot.

Keyed box diffing

diffBoxes(prev, next, options?) compares two Maps of box snapshots keyed by entity identity and returns the raw damage footprints (old and new) of what changed:

import { diffBoxes } from '@dirtytalk/spatial';
import type { BoxSnapshot } from '@dirtytalk/spatial';

const prev = new Map<string, BoxSnapshot<number>>();
const next = new Map<string, BoxSnapshot<number>>();
// …populate prev/next with { rect, content } snapshots…

const damage = diffBoxes(prev, next, {
  equalsContent: (a, b) => a === b,
});
const plan = planRegions(damage, bounds);

Keys are identity, not position: reordering the collection produces no damage, so z-order changes need explicit invalidation. Snapshots must be independently retained. Output is raw damage — feed it to planRegions for clipping, merging and budgeting.

What it is not

  • No GPU renderer included. SceneRoot calls renderer.beginFrame(regions) and renderer.endFrame() as abstract hooks; the real rasterisation lives in the renderer you provide.
  • No spatial index. v1 uses a plain array for the damage list; marks append in place, intersection is O(N×M). A coarse occupancy-grid spatial index is planned for v2 when tile-based partial redraw lands.
  • No auto-tracked reads. paint() is invoked because the node was damaged, not because its fields were read. There is no hidden dependency graph. This is a different model from React or MobX.
  • No virtual scene diff. Nodes mutate their own state and declare their own damage. The renderer trusts the declaration.
  • No animation primitive. Animation integrates by calling markDamaged('paint') each step. The engine does not know what an animation is.
  • Not coupled to any browser API. SpatialPointerEvent is a plain object; you translate DOM events to it at the boundary. The package has no window, document, or HTMLCanvasElement dependency.

License

MIT — see LICENSE.