@rasamjs/tools
v0.4.2
Published
Opt-in editing tools for rasam SVG drawings.
Readme
@rasamjs/tools
Optional editor adapters package path editing, ruler and measurement coordination through structural capabilities.
Opt-in editing tools for rasam drawings. The first entry is @rasamjs/tools/snapping;
the package has no main entry yet. Its only runtime peer is @rasamjs/core ^0.2.0.
Snapping
While a shape is moved or resized, its edges and centers line up with other shapes, its edges land on an optional grid, and its gaps match its neighbors. Red guides and gap markers show what it snapped to. Holding Ctrl (Cmd on macOS) bypasses snapping while held.
import { SVG } from '@rasamjs/core';
import { Transformer } from '@rasamjs/transformer';
import { Snapper } from '@rasamjs/tools/snapping';
const drawing = SVG(document.querySelector<HTMLElement>('#drawing')!, {
width: 600,
height: 400,
});
const snapper = new Snapper(drawing, { grid: 10 });
const transformer = new Transformer(drawing, { snap: snapper });
snapper.enabled = false; // a toolbar toggle
snapper.enabled = true;The transformer takes any structural snap provider and never imports this package.
Snapping runs during pointer moves and resizes of frames that are axis-aligned in
drawing space. Keyboard nudges, rotation and pivot edits keep their existing behavior.
Ratio, minimum-size, boundBox and commit-precision rules keep priority over snapping,
and guides only show alignments the accepted geometry still has.
Targets
Targets default to the moving nodes' siblings, combined across parents in document
order. Moving subtrees, their ancestor containers, hidden nodes and unavailable bounds
are skipped. targets(nodes) replaces the list, for example to limit snapping to an
artboard or skip locked layers. Targets are measured once per drag, in drawing units.
The tolerance is six client pixels by default and follows the current zoom, so snapping feels the same at every zoom level and keeps working when the view changes mid-drag. Shape lines win equal-distance ties with the grid, and the grid wins ties with spacing.
Grid
The grid is off by default. grid: 10 or grid: { size: 10, origin: { x: 5, y: 5 } }
snaps edges, not centers, to grid lines in drawing units. The snapper does not draw the
grid. Draw it with GridOverlay from @rasamjs/tools/grid, or with your own, as the
example does with a CSS background. Drawing and snapping stay separate: pass the overlay
as grid to snap to the lines it draws, and hiding the overlay does not stop snapping.
The snapper reads grid when each gesture begins, so setting the overlay's size or
origin moves both the drawn lines and snapping, from the next gesture on.
Equal spacing
Spacing is on by default and independent of shapes. A move can center a shape between
two neighbors, or put it one existing gap away from a neighbor; existing gaps may come
from another row or column. Neighbors must overlap the shape on the other axis.
Backgrounds and panels that contain the shape are not neighbors, while partial overlaps
block a gap. Resizing corrects only the dragged edge. spacing: false turns it off;
turn off both shapes and spacing for grid-only snapping.
Guides
Guides and gap markers live in their own SVG overlay beside the drawing, so they never
appear in exports, queries or history. Strokes stay one client pixel wide at every zoom.
style: { stroke, gapStroke } sets their colors (default #f00), and style.gridGuides: false
hides guides for grid snaps when the grid itself is visible. The overlay redraws
once per animation frame while dragging; snapper.update() redraws it immediately.
With a viewport, list the snapper beside the transformer:
import { Viewport } from '@rasamjs/viewport';
const viewport = new Viewport(drawing, { overlays: [transformer, snapper] });Lifecycle
Construct the snapper with a live, mounted rasam SVG drawing. It starts enabled. Options
are fixed at construction; to change them, destroy the snapper and create another
behind a small provider object, as the example does. Destroying the drawing destroys its
snappers. destroy() ends an active drag session, removes the overlay and can be
repeated safely.
Other tools
Drawing tools and the path editor can snap single points with the same engine:
const client = drawing.toClient({ x: 8, y: 8 })!;
const session = snapper.begin({ kind: 'point', client });
const corrected = session?.snap(client, { ignore: false }) ?? client;
session?.end();session.snap(client, { ignore: ctrlKey || metaKey }) implements the bypass;
modifier: 'none' ignores that flag.
Example
Run bun run --filter @rasamjs/tools dev and open the snapping example.
It combines selection, transformer, viewport and snapper, with toggles for snapping,
shapes, grid and spacing. The server uses port 4179 and refuses an occupied port.
See API.md, RELEASING.md and CHANGELOG.md.
Complete editor snapping
The optional @rasamjs/tools/snapping/advanced entry adds oblique resize handles,
matching other shapes' rotation angles, curve/segment targets, ruler guides and
keyboard nudges. The original /snapping entry retains its 6 KiB budget and behavior.
import { AdvancedSnapper } from '@rasamjs/tools/snapping/advanced';
import { GridOverlay } from '@rasamjs/tools/grid';
import { RulerGuides } from '@rasamjs/tools/rulers';
import { DrawTool, PathEditor } from '@rasamjs/tools/drawing';
const rulers = new RulerGuides(drawing);
const grid = new GridOverlay(drawing, { size: 10 });
const snapper = new AdvancedSnapper(drawing, {
grid, // Snap to the lines the overlay draws.
guides: () => rulers.guides,
curves: true,
});
const transformer = new Transformer(drawing, { snap: snapper });
const draw = new DrawTool(drawing, { kind: 'rect', snapper });
draw.enabled = false; // Enable while the rectangle tool is selected.
draw.kind = 'pencil'; // Also rect, ellipse, line, path and click-by-click pen.
draw.paint = { fill: '#8bbbf4', stroke: '#2563a6', 'stroke-width': 2 };
const pathEditor = new PathEditor(drawing, { snapper });
pathEditor.attach(drawing.path({ d: 'M 10 10 Q 80 100 160 10' }));Use a positioned, isolated host (position: relative; isolation: isolate) for these
native overlays. Include grid, rulers, snapper and pathEditor in the viewport's
overlays list, or call their update() methods after outside mapping changes.
All overlays stay outside SVG exports and history. Every tool owns its listeners,
observers and pointer capture and cleans them up on destruction of the drawing.
Drawing commits one labelled edit on completion. Forward keydown and keyup to
draw.key(event) when the drawing owns keyboard input, for live Shift/Alt constraints
and pen finish/delete keys. See the drawing API.
Run the focused drawing and guides example with
bun run --filter @rasamjs/tools dev, then open
http://127.0.0.1:4179/examples/advanced.html. It demonstrates drawing tools, grid
snapping, ruler guides and editable Bezier controls. Run bun run playground for
the complete editor built on @rasamjs/editor, including selection, camera controls
and undo/redo. The full tools integration matrix remains a browser test fixture.
Inline text
import { TextEditor } from '@rasamjs/tools/text';
const text = new TextEditor(drawing, { selection, fill: '#1c4e80' });
text.create({ x: 40, y: 60 });
text.on('commit', ({ node }) => console.log(node.text()));Text editing uses one labelled core change group per session. Double-click edits text;
Enter or blur commits, and Escape cancels. Blank new text and unchanged edits leave
history untouched. Add the editor to viewport's overlays list to keep the input
aligned with the camera. See the text API.
The optional measure API displays drawing-unit distances while
Alt-hovering a shape, with labels that remain readable while zooming:
import { Measure } from '@rasamjs/tools/measure';
const measure = new Measure(drawing, { selection });