@rasamjs/selection
v0.5.2
Published
Pointer and keyboard selection for rasam SVG drawings.
Readme
@rasamjs/selection
Click, additive and marquee selection for rasam SVG drawings, with hover highlights,
selection outlines and keyboard shortcuts. Selection is application state and never
adds undo entries. The package has one runtime peer: @rasamjs/core version ^0.2.0.
@rasamjs/[email protected] is published.
import { SVG } from '@rasamjs/core';
import { History } from '@rasamjs/history';
import { Transformer } from '@rasamjs/transformer';
import { Selection, connectTransformer } from '@rasamjs/selection';
const drawing = SVG(document.querySelector<HTMLElement>('#drawing')!, {
width: 600,
height: 400,
});
drawing.rect({ x: 80, y: 60, width: 120, height: 80, fill: '#88c8ec' });
const history = new History(drawing);
const transformer = new Transformer(drawing);
const selection = new Selection(drawing, { marquee: 'intersect', hover: true });
const disconnect = connectTransformer(selection, transformer);
selection.on('change', ({ nodes, reason }) => {
history.breakMerge();
console.log(`${nodes.length} selected (${reason})`);
});
// When the selection UI is no longer needed:
disconnect();
selection.destroy();Position the drawing container with position: relative. Set touch-action: none
on that container if you want touch marquee gestures. Selection never changes the
application's touch-action value.
| Gesture | Result | | ----------------------------------------------- | ---------------------------------------------------------- | | Click a shape | Select it; drag to move it when connected to a transformer | | Double-click a group | Select the child under the pointer, one level deeper | | Shift-click | Add or remove the innermost shape under the pointer | | Ctrl-click on Windows/Linux, Cmd-click on macOS | Add or remove the shape at the current selection level | | Click empty space | Clear the selection | | Drag empty space | Preview a marquee and commit on release | | Additive modifier + marquee | Add hits to the selection from before the press | | Ctrl+A / Cmd+A | Select every selectable child in scope | | Escape | Cancel a gesture first; otherwise clear |
The default scope is the drawing root. A normal click initially selects a direct
drawable child, so clicking a group's child selects the whole group. Double-click
to go one level deeper, or Shift-click to pick the innermost shape directly. Once
selected, nested shapes remain clickable and draggable, and their siblings can be
selected at that level. Clearing selection returns clicks to the scope's top level.
Selecting a descendant replaces any selected ancestor (and vice versa), preserving
unrelated selections. For layer-based editors, pass the layer as scope.
Use a pure, fast selectable predicate to exclude locked or
otherwise ineligible shapes. Programmatic operations reject foreign, destroyed,
non-drawable and out-of-scope nodes atomically with TypeError. Descendants are
accepted only when every ancestor below the scope is also selectable and drawable.
nodes is a frozen snapshot in document order. change events contain frozen
nodes, added and removed snapshots and a reason. Changes requested inside a
listener run after the current dispatch. Removed, destroyed or reparented nodes
leave selection automatically; undo does not select them again.
The overlay lives beside the drawing, with pointer events disabled. It stays out of
SVG exports, queries, clones, bounds and model history. Redraws follow model edits,
ancestor transforms, replay, scrolling and resizing. Call selection.update() after
other outside layout changes. Style it through style, className, or the
rasam-selection, rasam-selection-marquee, rasam-selection-hover and
rasam-selection-outline CSS classes.
Marquee uses a shape's local bounding-box corners mapped into client pixels. Rotated boxes, nested SVG viewports, zoom and CSS transforms are supported. Curves and circles can be hit at an empty corner of their box; exact curved geometry is deferred, and lasso selection is outside the planned scope. Hidden shapes and unavailable/empty bounds are skipped by marquee; select all includes selectable nodes even when their bounds cannot be drawn.
connectTransformer() uses a structural interface and imports no transformer code.
Capable transformers expose targets and attachMany(nodes) and receive the complete
ordered selection. Dragging any selected member moves the whole set with the same
press; a release at the press point collapses it to that node. Any movement on a shape
counts as a drag, like the transformer's own moves; threshold applies to marquees.
Shared controls support rotation and resizing within the transformer's
representability restrictions. Outlines omit every attached member while the
transformer can draw its frame, and return when a member or the drawing loses its
screen mapping. Older TransformerLike objects still receive single selections and
detach for multiple selections. To keep that behavior with a capable transformer, pass
a wrapper without targets:
{ get target() { return t.target; }, attach: (node) => t.attach(node), detach: () => t.detach() }.
Disconnecting detaches its
transformer. Unavailable geometry keeps the whole selection without handles and
retries on selection.update() or automatic redraw. Marquee previews suspend all
bridges until commit/cancellation, including connections made during the gesture.
Keyboard shortcuts act from body focus or inside the drawing host, including its
transformer overlay. They ignore editable fields, focus elsewhere and events already
handled by the application. Set keyboard: false to manage shortcuts yourself.
Mouse and pen can show hover; touch hover is ignored. A polite live region announces
keyboard and marquee selection counts.
Group, ungroup and stacking-order commands are in the opt-in arrange entry. Each
command is one undo step in @rasamjs/history:
import { arrangeSelection, groupSelection, ungroupSelection } from '@rasamjs/selection/arrange';
groupSelection(selection); // Wrap the selection in a new group and select it.
ungroupSelection(selection); // Select the children of every selected group.
arrangeSelection(selection, 'front'); // Or 'back', 'forward', 'backward'.Run the example with bun run --filter @rasamjs/selection dev.
See API.md for the complete contract and RELEASING.md
for acceptance checks. The marquee benchmark
reports three-engine measurements over 1,000 nodes without a timing threshold.
Align and distribute
import { alignSelection, distributeSelection } from '@rasamjs/selection/arrange';
alignSelection(selection, 'left');
distributeSelection(selection, 'horizontal');Commands measure parent-space boxes, share one history step per command and need
at least two or three measurable nodes respectively. The arrange entry imports no
selection UI at runtime. selection.canSelect(node) checks a candidate without
changing membership. See the API.
For copy/cut/paste and duplicate/delete use @rasamjs/clipboard.
Layers
import { Layers } from '@rasamjs/selection/layers';
import { nudgeSelection } from '@rasamjs/selection/arrange';
const layers = new Layers(drawing, { names: { rect: 'Box' } });
const selection = new Selection(drawing, { selectable: layers.isSelectable });
layers.rename(node, layers.nextName('rect'));
layers.toggleLocked([node]);
layers.toggleHidden([node]);
layers.on('change', ({ rows }) => renderLayers(rows));
nudgeSelection(selection, 10, 0);The model describes the whole drawing tree, including collapsed groups. Names, locks and visibility remain in the saved document; expansion is view state. Metadata writes and reordering use labelled core groups. Geometry changes keep row snapshots stable and do not notify. Both optional entries remain independent of the main selection UI and import only core at runtime. See the layers API, including the selection adapter and caller-owned nudge scopes for merged edits.
Editing extras
Optional entries provide shared-center flips, freeform selection and paint/type matching:
import { flipSelection } from '@rasamjs/selection/flip';
import { lassoHits } from '@rasamjs/selection/lasso';
import { selectSimilar } from '@rasamjs/selection/similar';
const selection = new Selection(drawing, { lasso: lassoHits });
flipSelection(selection, 'horizontal');
selectSimilar(selection, 'fill');See API.md for geometry, scope and undo behavior.
