All 42 libraries

SugarMouse

Mark/Scan/Get (tag the output, scan the frame, look up the id) mouse hit-testing primitives plus the bubblezone-style Zones manager layer, in one package

inspired by lrstanley/bubblezone mouse hit-testing zones click dedupe

SugarMouse code coverage

Own your own Scanner instance — no global wiring required. Wrap rendered chunks with private-use sentinel tags (zero-width to this lib's scanner; not guaranteed invisible on every host), scan to discover bounding boxes, then hit-test mouse events. ZoneClickTracker deduplicates Press/Release pairs so each logical click emits once. The Zones\Manager layer of the same package adds prefixed managers plus hover, drag, and multi-click trackers.

Install

composer require sugarcraft/sugar-mouse

Requires PHP ^8.3; the only package dependency is sugarcraft/sugar-core.

Quickstart

use SugarCraft\Mouse\Mark;
use SugarCraft\Mouse\Scanner;
use SugarCraft\Mouse\ZoneClickTracker;
use SugarCraft\Mouse\MouseEvent;

// 1. Wrap interactive content with private-use sentinel tags.
$rendered = Mark::zone('btn-ok', '  OK  ')
              . Mark::zone('btn-cancel', 'Cancel');

// 2. Scan after rendering to populate the zone registry.
$scanner = Scanner::new()->scan($rendered);

// Never echo marked bytes — print the stripped frame: echo Scan::strip($rendered);

// 3. Reverse-lookup on mouse events ('  OK  ' spans cols 1-6 on row 1).
$zone = $scanner->hit(4, 1); // Zone 'btn-ok'

// 4. A click fires only when the release's fresh re-hit agrees with the
//    press zone on id AND box — resolve each event against the frame it
//    arrived in.
$tracker = new ZoneClickTracker();
$tracker->track(MouseEvent::press(4, 1), $scanner->hit(4, 1));
$click = $tracker->track(MouseEvent::release(4, 1), $scanner->hit(4, 1));
if ($click !== null) {
    echo "Clicked zone: " . $click->zone->id;
}

What's in the box

Mark sentinel wrapMark::zone($id, $content) wraps content in U+E000/U+E001 tags — zero-width to this lib's scanner, never in ANSI escape payloads; sweep untrusted text with Mark::untrusted() before marking it. Mark::new() / Mark::disabled() build an instance for wrap(); Mark::isValidId() is the id predicate encoder and decoder share.
Strict scan grammarScan::parse() decodes exactly what Mark encodes and every tag byte is zero-width; a lone sentinel or malformed id skips only its 3 sentinel bytes, so a stray marker can never swallow the span after it. Orphan closes/unclosed opens are dropped, a zone that paints no cell yields no zone, and a duplicate id throws.
Row accounting\n and \r\n start a new row; a lone \r returns to column 1 like a terminal. A zone that painted nothing before a leading newline or \r starts where it first paints, instead of inverted or over-wide boxes; only rows the zone painted extend its box, so trailing blank lines inside the tags add nothing.
Selection / SelectionRangePress → drag → release text-selection state machine over a selectable region, plus a normalized inclusive stream range whose extract() copies the selected text out of a frame.
Scanner hit-testingScanner::new()->scan($rendered) parses sentinels; hit(col, row) reverse-lookup by coordinates; get(id) lookup by zone id.
Zone bounding boxZone readonly value object with 1-based start/end col/row coordinates matching terminal cell space.
ZoneClickTracker dedupZoneClickTracker state machine per button — suppresses drag spurious presses and mismatched Press+Release on different zones.
Instance-owned primitivesScanner is owned by each consumer — no shared state across components. The Zones\Manager layer of the same package adds per-component isolation via id prefixes.
ANSI-disjoint sentinelsOrdinary ASCII UI text cannot carry U+E000/U+E001, and well-behaved renderers never emit them inside CSI/OSC escape payloads — a policy of honest output, not a property of the wire grammar: escape payloads are arbitrary bytes, so sweep untrusted text with Mark::untrusted() before composing it into a marked frame. Foreign private-use glyphs remain a width concern — see the README trust section.
CJK column accountingScanning uses Width::string() from sugar-core so wide East-Asian characters account for 2 cell columns each.
Press+Release pairing (bubblezone #10)Press+Release agreement per zone per button — the pairing upstream tracked in bubblezone issue #10.

Source & demos

Try the quickstart →

API

ClassMethodDescription
Mark::zone(id, content)Wrap content with private-use sentinel tags
Mark::untrusted(text) / ::escapeForMessage(id)Sweep foreign framing bytes off untrusted text; printable-ASCII repr for hostile ids in errors
Mark::new() / ::disabled() / ->withEnabled(bool) / ->wrap(id, content)Instance form; a disabled Mark returns content unwrapped
Mark::isValidId(id)Whether an id is one Mark encodes and Scan decodes (≤ MAX_ID_BYTES, no spaces/escapes/non-ASCII)
Scan->parse(rendered, ?width)Stateless, reentrant decoder behind Scanner; returns id => Zone
Scan::strip(rendered)Public byte-wise tag remover — same tag rule parse decodes
Scanner::new()Create empty scanner
Scanner->scan(rendered)Parse sentinels, build zone registry
Scanner->get(id)Get Zone by id
Scanner->hit(col, row)Reverse-lookup Zone at coordinates
Scanner->all() / ->prefixed(prefix) / ->clear()Every zone, zones whose id starts with a prefix, reset
Zone$idZone identifier
Zone$startCol / $startRow / $endCol / $endRow1-based bounding box
MouseEvent::press(x, y, button)Factory for press event
MouseEvent::release(x, y, button)Factory for release event
MouseEvent::drag(x, y, button) / ::scroll(x, y, button)Factories for drag and scroll events
MouseActionPress / Release / Drag / ScrollMouse action enum
ZoneClickTracker->track(event, ?Zone $hitZone = null)Feed event, receive ClickResult or null
ZoneClickTracker->setPressZone(Zone, button)Legacy two-call form for a pending press; the preferred one-call form is track(event, zone)
ClickResult$zone / $buttonCompleted click result
Selection::new(rowFrom, rowTo, colFrom, colTo) / ->begin(row, col) / ->dragTo(row, col) / ->range() / ->clear()Text-selection state machine bounded to a selectable region
SelectionRange::new(rowA, colA, rowB, colB) / ->spanOnRow(row) / ->cellContains(row, col) / ->cells() / ->extract(lines)Normalized, inclusive selected range and its text

Zones (bubblezone Manager layer)

Wrap rendered chunks with named markers, let SugarMouse discover their bounding boxes, then ask zones whether a MouseMsg fell inside them. Markers are sugar-mouse's private-use sentinel tags (U+E000 / U+E001) — zero-width to the scanner — and scan() strips them before the frame is printed, so the printed frame matches the measured one. Sweep untrusted labels with Mark::untrusted() first.

use SugarCraft\Core\MouseButton;
use SugarCraft\Core\MouseAction;   // the WIRE enum (Press / Release / Motion)
use SugarCraft\Core\Msg\MouseMsg;
use SugarCraft\Mouse\Zones\Manager;

$z = Manager::newGlobal();

// mark() wraps whatever rendered string you already have — plain text,
// or styled bytes from whatever renderer you use.
$btnOk     = $z->mark('btn:ok',     '  OK  ');
$btnCancel = $z->mark('btn:cancel', 'Cancel');
$frame     = $btnOk . '   ' . $btnCancel;

// Scan once before printing — Manager records marker positions and strips them.
$displayable = $z->scan($frame);
echo $displayable;

// Later, when a MouseMsg arrives (1-based col, row — the same grid get()
// measures; here col 5 lands inside the six-cell "  OK  " button):
$click = new MouseMsg(5, 1, MouseButton::Left, MouseAction::Press);
if ($z->get('btn:ok')?->inBounds($click)) {
    // ...
}
Marker injection$z->mark('btn:ok', $rendered) wraps the chunk in private-use sentinel tags via Mark::wrap(); the id is validated even on a disabled manager.
One-call scan$z->scan($frame) records every marker's 1-based cell bounding box and strips them in one call (parse + strip); the implementation walks the string more than once. It strips exactly the tags sugar-mouse's Scan::parse() decodes (ids that pass Mark::isValidId()); any other stray sentinel loses only its own 3 bytes and the text after it is kept, so the printed frame matches the measured one.
Bounds query$z->get('btn:ok')?->inBounds($mouseMsg) — clean predicate, no coordinate math.
ANSI-awareWidth calculation honors SGR + Unicode grapheme widths; emojis, CJK, combining marks all account correctly.
Manager isolationOne package, two layers: Manager::newGlobal() builds a fresh un-prefixed manager independent of every other instance — NOT the shared default (that is Zones::defaultManager()); Manager::newPrefix() builds per-component managers whose ids namespace every marker for nested mouse handling.
Plays with SugarCraftDrop into your Model — every view() call rescans, every MouseMsg routes.
Hover trackingZoneHoverTracker emits ZoneEnterMsg / ZoneExitMsg on cursor boundary crossings.
Drag trackingDragTracker tracks press → move → release drags across zones; emits ZoneDragStartMsg / ZoneDragMoveMsg / ZoneDragEndMsg.
Click trackingClickCounter detects double / triple click streaks; emits DoubleClickMsg / TripleClickMsg within a configurable interval.
Motion tracking CSIManager::setMotionTracking(true) returns the all-motion pair \x1b[?1003h\x1b[?1006h (mode 1003 plus the SGR 1006 coordinate companion); false returns the LIFO disable. Whichever code enables a mode owns disabling it. The decimal extended-coordinate siblings of 1006 — mode 1015 (urxvt style, CSI b;x;y M) and mode 1016 (xterm, the SGR report shape carrying pixel coordinates) — are emitted and parsed by neither this lib nor sugar-core; decoding them is sugar-input's opt-in path, so swapping 1006 for either is a host-layer decision.

Zones API

ClassMethodDescription
ManagernewGlobal()Build a fresh un-prefixed manager independent of every other instance — NOT the shared default (that is Zones::defaultManager())
ManagernewPrefix(prefix = '')Create prefixed manager for isolation
Managermark(id, content)Wrap output with zone marker
Managerscan(rendered, ?width)Record this namespace's positions, strip markers (delegates to Scan::strip); zones merge by id and persist until replaced or cleared
ManagerzoneAt(col, row)Geometric smallest-area hit without a MouseMsg
ManageranyInBounds(msg) / allInBounds(msg)anyInBounds: smallest-area zone under the event, ties to the first recorded; allInBounds: every covering zone, smallest area first
ManageranyInBoundsAndUpdate(model, msg)Route the hit into a Model — the sole emitter of MsgZoneInBounds, dispatched into update() when a zone matches, the raw event forwarded otherwise
Managerall() / clear(?id) / close() / setEnabled(bool)Every zone, reset one or all, disable
Managerget(name)Get zone by name
ManagersetMotionTracking(bool)Return the 1003+1006 enable (or LIFO disable) escape bytes
ZoneinBounds(mouseMsg)Test if mouse is inside zone
ZoneHoverTrackernew(manager)Track hover state over a manager
ZoneHoverTrackerupdate(mouseMsg)Process mouse event, return enter/exit msg
ZoneHoverTrackercurrentZone()Get the hovered Zone or null
ZoneEnterMsgzoneZone the cursor just entered
ZoneExitMsgzoneZone the cursor just left
DragTrackernew(manager)Track drag sequences over a manager
DragTrackerupdate(mouseMsg)Process mouse event, return drag msg
DragTrackeroriginZone()Get the origin Zone or null
DragTrackercurrentZone()Get the current Zone or null
ZoneDragStartMsgoriginZone / currentZoneZone where drag started; zone at current cursor
ZoneDragMoveMsgoriginZone / currentZoneFixed origin zone; zone cursor just crossed into
ZoneDragEndMsgoriginZone / currentZoneZone drag started from; zone under the release cursor, null outside every zone
ClickCounternew(manager, clickIntervalMs, ?clock)Track double/triple click streaks; the clock seam steps time in tests
ClickCounterupdate(mouseMsg)Process press event, return double/triple msg
ClickCounterclickCount()Current streak count (0 = no streak)
DoubleClickMsgzoneZone of the second press
TripleClickMsgzoneZone of the third press

Accessibility

Zone tags are private-use-area codepoints: screen readers announce them as dotted-circle placeholder glyphs or "unknown character" noise, and the mouse trackers (hover, drag, multi-click) are pointer-only affordances. Ship a keyboard path for every zone-driven action. Print only the stripped frame: at the Zones\Manager layer, scan() returns it display-ready; at the primitive layer, the standalone tag remover is Scan::strip(). Never echo marked bytes. Tab/Shift+Tab (or arrows) across zones with Enter to fire, focus-revealed twins for hover affordances, a select-then-choose fallback for drag, and never gate a command on tracker state alone.

Mode lifecycle. This lib never touches the TTY, so it cannot undo what it never wrote: whoever enables 1000/1002/1003/1006 owns the disable on every exit path — including crashes (a register_shutdown hook or the frame runner's finally). A leaked ?1003 streams every mouse move into the session for its remaining lifetime, a continuous byte flood that hits assistive tech hardest (Orca and brltty users cannot wave it away).

Interop floor. 1002/1003 are the xterm family — Konsole ships no 1003 and tmux re-encodes reports — so design for 1000-only degradation when motion reports never arrive.

Demos.

VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.

Two clickable buttons

Two clickable buttons

Zone bounding boxes around rendered buttons via Manager::mark()/scan().
List with zones

List with zones

Wrapping every list row in a Zone for click targeting.
Nested components

Nested components

Zones composed across nested rendered components.