@rasamjs/transformer
v0.6.2
Published
Interactive editing overlays for rasam SVG drawings.
Readme
@rasamjs/transformer
An editing overlay for rasam. Move, resize and rotate one shape or a shared selection with pointer and keyboard controls.
import { SVG } from '@rasamjs/core';
import { Transformer } from '@rasamjs/transformer';
const drawing = SVG(document.querySelector<HTMLElement>('#drawing')!, {
width: 600,
height: 400,
});
const shape = drawing.rect({ x: 80, y: 60, width: 160, height: 90 }).rotate(20);
const transformer = new Transformer(drawing, {
rotateHandle: 'top',
style: { stroke: '#1e88e5', strokeWidth: 1, dash: [4, 4] },
});
transformer.attach(shape);The drawing must be mounted. Targets must be live shapes, groups or SVG viewports inside that drawing. The owning drawing root, resources, targets from other drawings and unavailable screen mappings are rejected. Empty targets are accepted with the box hidden; flat lines expose only anchors for their nonzero axis.
The overlay is a separate SVG beside the outermost drawing SVG. It does not enter
drawing exports, bounds, managed queries or clones. Only its controls intercept pointers.
Its frame follows target and ancestor transforms, scroll, viewport resize and drawing
resize, with updates coalesced per animation frame. After changing geometry,
reparenting or changing surrounding layout/CSS, call transformer.update(). A viewport
that only moved the camera calls update({ viewOnly: true }), which reuses model results.
Snapping
Pass an optional structural snap provider to align pointer moves and eligible resizes.
@rasamjs/tools/snapping supplies one; the transformer does not import that package.
import { Snapper } from '@rasamjs/tools/snapping';
const snapper = new Snapper(drawing, { grid: 10 });
const snappingTransformer = new Transformer(drawing, { snap: snapper });Ctrl/Cmd temporarily bypasses snapping, including changes while the pointer stays still.
Snap samples also carry the current centered-resize policy, including live Alt changes.
Keyboard nudges, rotation and pivot edits keep their existing behavior. Snapping begins
after pointer capture and ends on release, cancellation, Escape, detach or destruction.
Resizes snap only when the frame is aligned in drawing space. Ratio, minimum-size,
boundBox and commit-precision rules retain priority and can alter final alignment.
See the provider contract.
API
new Transformer(drawing, options?): create an overlay. Style acceptsstroke, nonnegativestrokeWidthand nonnegativedashlengths. Usedash: []for a solid box.attach(nodeOrNodes),attachMany(nodes),detach()andupdate()return the transformer.focus()focuses the selected overlay for keyboard editing and returns the transformer.targetis the single attached node ornullfor zero/multiple nodes.targetsis a frozen membership snapshot in document order;isDestroyedreports disposal.on('attach' | 'detach', ({ node, nodes }) => ...)returns an unsubscribe function. The scalar node is null for multiple members; the nodes array always contains the membership.destroy()releases observers, listeners, animation frames and overlay elements. Repeated destruction is safe. Destroying the drawing destroys its transformer; removing or destroying a target or ancestor detaches it.
The 0.2.0 candidate accepts arrays and displays a shared
frame. Duplicate nodes are ignored; ancestor/descendant pairs and invalid members
reject the whole request. A one-element array keeps single-shape editing. Multiple
members move together by dragging any member or using focused overlay arrow keys.
Shared rotation uses the frame center and supports pointer snapping and keyboard
steps. Component members under skewed or non-uniform parents keep movement but
hide rotation controls; existing matrix-mode members retain affine rotation.
Group resizing preserves component editing: corners constrain proportions when
independent-axis scaling would introduce skew, and unavailable side handles are
hidden. Aligned members and existing matrix-mode members support independent axes.
Connect @rasamjs/selection with connectTransformer(selection, transformer) to
forward complete membership and drag the group with the selecting press. Legacy
single-target bridge objects keep their existing behavior.
rotateHandle accepts 'top' (default), 'corners' (with a pivot marker) or 'none'.
Controls have 8 pixel faces and 20 pixel hit areas at any drawing zoom or CSS scale.
Rotation snaps near rotationSnaps (default [0, 90, 180, 270]) within
rotationSnapTolerance degrees (default 5). Hold Shift for shiftRotationStep
increments (default 15). Set rotationSnaps: [] to turn off proximity snapping.
Single-target angles use the target's parent coordinates; group angles use the
owning drawing coordinates.
transformstart and transform provide { node, nodes, kind }, where kind is 'move',
'resize', 'rotate' or 'pivot'. transformend adds { before, after, states, cancelled }.
The scalar node, before and after are null for multiple members; states always contains
frozen per-member snapshots. History records the whole gesture automatically:
transformer.on('transformend', ({ states, cancelled }) => {
if (!cancelled) console.log('Applied to', states.length, 'shapes');
});
// Custom undo: restore each member's before snapshot, then transformer.update().Gestures use pointer capture for mouse, pen and touch. Pointer moves are coalesced
per animation frame; pointer release flushes the final sample. Escape, pointer
cancellation, lost capture, window blur and detach restore the start state. Removing
or destroying the target or an ancestor cancels and detaches. A cancelled end event
is emitted once; if the node has been destroyed, its after is the saved before.
The outer drawing container temporarily uses touch-action: none while selected;
the previous value is restored on detach. Drawing markup stays unchanged on attach.
Resize calculations preserve the opposite anchor, including through reflections, skewed parents, nested viewports and root viewBox zoom. Single-target circles retain their aspect ratio. Applications should not animate, reparent or edit geometry on the same target during a gesture.
Keyboard and pivot editing
Tab reaches the overlay and each labelled control; applications can call
transformer.focus() after selecting a shape. Overlay arrows move by 1 client
pixel, or 10 with Shift. Focus a resize/pivot control to move it by the same step.
Rotation controls use 1 degree, or 10 with Shift. Arrow release commits a quick
edit. Enter/Space starts a longer edit mode; Enter/Space applies and Escape cancels.
Leaving an active control or blurring the window cancels uncommitted keyboard edits.
Shortcuts apply only inside the focused overlay. Arrow steps are client pixels; set
keyboardStep: 'drawing' to step in drawing units at any zoom.
Set keyboard: false to disable shortcuts, tab stops and automatic pointer focus;
focus() then leaves application focus unchanged. Only an accepted primary-pointer
edit takes focus when keyboard handling is enabled. Held arrow repeats stay cancelled
until the key is released. Scrolling preserves the nudge step, and size constraints
do not accumulate rejected keyboard steps.
Controls omit button roles and pressed states when keyboard handling is disabled.
The corner look's pivot can be dragged from its center, ring or crosshair, or edited
with arrows. Drag the surrounding artwork to move the shape. Moving the pivot
changes the explicit origin while keeping the artwork in place. Pointer drags snap the
pivot to the frame's anchors (corners and edge midpoints) and center within pivotSnapTolerance client pixels
(default 6; 0 turns snapping off). While an edited pivot rests on a corner or the
center, red guide lines run through it along the client axes, spanning the frame.
Arrow-key pivot steps never snap. Resizing keeps an explicit pivot at the same relative
position in the shape, so a pivot on a corner stays on that corner. Pointer edits that take focus draw no focus outline; keyboard
focus does. Matrix-mode targets
keep center-based rotation and have no editable pivot control. Set ariaLabel to
identify an overlay (default 'Shape transformer'). Controls have labels, focus
outlines, pressed edit state and completion announcements.
Unchanged edits are not announced as applied. Focus outlines require no inline
stylesheet, including under a strict Content-Security-Policy.
See the API reference for the full contract and tested accessibility limits.
Resize and commit options
| Option | Default | Behavior |
| ------------------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| anchors | 'all' | Or a list of the eight names: top-left, top, top-right, right, bottom-right, bottom, bottom-left, left. An empty list hides resize controls. |
| keepRatio | 'shift' | true, false or 'shift'; circles always keep their starting aspect ratio. |
| centeredScaling | 'alt' | true, false or 'alt'; otherwise the opposite anchor stays fixed. |
| minSize | 4 | Minimum nonzero dimensions in the target's local size units. Flat axes remain flat. A tiny positive scale prevents a singular transform when the minimum is zero. |
| flip | false | Stop at the minimum, or permit crossing an opposite edge and mirroring when true. Existing reflections are preserved. |
| boundBox | unset | Constrain a proposed box or return the previous accepted box to reject it. |
| bake | 'size' | Bake supported geometric sizing on resize release; 'none' retains the sizing matrix. |
| precision | 3 | Decimal places for changed values only, from 0 to 12. Extra precision is kept if rounding violates the minimum or moves the client frame over 0.5 px. |
| nonScalingStroke | false | Temporarily set vector-effect: non-scaling-stroke on the target and its managed descendants during a gesture, restoring original values or absence on release/cancel. |
Shift and Alt changes take effect during a drag even when the pointer is stationary.
Ratio locking, centered scaling, the minimum and flip policy run before boundBox.
Its arguments are immutable boxes in the start frame's local size units: the start
top-left is (0, 0) and negative width/height indicate flips. The callback has final
control over position, ratio and size; results must be finite, preserve flat axes,
avoid collapsed nonzero axes and respect flip: false. Keep the callback free of
drawing mutations.
Ellipses, uniformly sized circles, lines, point lists and paths can bake their
sizing. Text, groups and unsupported sizing retain a matrix. Commit checks preserve
the preview's geometric frame within 0.5 client pixels, and before retains original
geometry and transform syntax for exact undo. Geometric baking can change stroke
scaling because the sizing transform is removed. To keep artwork strokes constant
through both preview and commit, set vector-effect: non-scaling-stroke on that
artwork itself; the temporary preview option restores the previous paint policy.
Overlay styling
style.anchorSize defaults to 8 pixels and style.anchorFill to '#fff'.
style.anchorCornerRadius (default 0) rounds resize anchors; half of anchorSize
draws circles. style.dashStroke paints the box dashes in a second color over a solid
stroke line, for a two-tone outline. style.pivotFill (default 'none') fills the
pivot ring and style.pivotStroke (default stroke) colors its ring, crosshair and center dot.
style.guideStroke (default '#f00') colors the pivot guides; 'none' hides them.
hitSize defaults to 20 pixels (at least the face size). padding defaults to 0
and adds client-pixel spacing along the frame axes without changing geometry.
When resize hit areas overlap on a small selection, pointer presses select the
nearest resize handle.
className adds classes to the overlay root. Stable CSS selectors are
.rasam-transformer, .rasam-transformer-box, .rasam-transformer-anchor,
.rasam-transformer-rotate, .rasam-transformer-connector,
.rasam-transformer-pivot, .rasam-transformer-guides and
.rasam-transformer-line-hit. These elements all live
outside the drawing.
A two-tone corner look with round handles, a filled pivot and red pivot guides:
new Transformer(drawing, {
rotateHandle: 'corners',
hitSize: 18,
style: {
stroke: '#6495ed',
dash: [3, 3],
dashStroke: '#ef4179',
anchorSize: 9,
anchorCornerRadius: 4.5,
pivotFill: '#4bb0ff',
pivotStroke: '#2c3e50',
},
});Workspace development
From the repository root:
bun install --frozen-lockfile
bun run build
bun run --filter @rasamjs/transformer dev
# http://127.0.0.1:4174/examples/look-a.html
# http://127.0.0.1:4174/examples/look-b.html
# http://127.0.0.1:4174/examples/look-c.html
bun run --filter @rasamjs/transformer test
bun run --filter @rasamjs/transformer test:browser
bun run --filter @rasamjs/transformer bench:pointer
bun run release:checkVite, Vitest and the development TypeScript check opt into rasam's rasam-source
export condition. Editing rasam source therefore needs no rasam rebuild for these
tools. There are no path aliases or deep imports. Normal Node imports, the strict
transformer declaration build and packed consumers use rasam's dist exports.
The development check uses rasam's permissive compiler setting while checking its
imported source; the transformer package build itself uses strict: true.
Acceptance and packaging
The package gate runs formatting, typechecking, unit tests, build, three-engine
browser tests, documentation, a consumer installed from both package tarballs,
a 17,536-byte gzip budget and 1,000-input pointer measurements on a 1,000-node group.
The size check keeps rasam external. The consumer checks document-free
imports, default dist resolution, blocked deep imports, declarations and maps.
Results go to reports/release-readiness.json and reports/size.json.
Shared gate, source tracking, metadata and packaging helpers live in
tools/release.
@rasamjs/core is a peer dependency (^0.2.0); there are no runtime dependencies.
@rasamjs/[email protected] is published and works with core 0.2.0 and later and
history 0.2.0. See the
release procedure for acceptance and separate publication.
Upgrade event listeners using the 0.1.0 migration notes.
