Reacting to change

Most of a VisQuill graphic is not drawing code. It is a set of relationships: this label shows the distance between these two points, this circle has that segment as its diameter. You write a relationship once, and VisQuill keeps it true when something changes. This chapter is about the tool for that, Reactive.do.

Run code when something changes

Drag the handles:

323 px
The label is placed and filled by one Reactive.do block.
// Runs now, and again whenever a or b changes
Reactive.do([a, b], () => {
    Points.midPoint(a, b, label)
    label.y -= 14
    label.value = `${Points.distanceToPoint(a, b).value.toFixed(0)} px`
})

Reactive.do(senders, action) runs action once right away, and again whenever one of the senders changes. Here the senders are the two handles: dragging one changes its position, and the block moves the label and writes the new distance.

Two things about when the block runs:

  • Right away, not later. When a.x = 200 returns, the block has already run and the label holds the new text. You can read the result on the next line.
  • The screen follows once per frame. VisQuill writes the changes to the SVG in the next animation frame, once, no matter how many updates happened before it.

If the block should only run on changes, not now, pass false as the third argument. That is rarely what you want: until the first change, whatever the block draws stays empty.

What can be a sender

Anything reactive that VisQuill created for you:

  • values from canvas.values: real, bool, string, item, point, pin
  • handles, and visuals such as segments, circles and labels
  • shapes, both from canvas.shapes and canvas.visuals
  • the reactive properties of visuals: visible, zIndex, mounted, and active of a handle

The block runs when one of them is written: .value of a value, x, y, dx or dy of a point or pin, and the geometry of a shape.

The block only knows about the senders you list. If it reads something that isn’t listed, it runs with a stale value when that something changes, and nothing warns you. List everything the block reads that can change.

Derived values

When several places need the same computed result, compute it once into a reactive object of its own. Then it’s a sender like any other:

mid is computed from a and b; the circle depends on mid and a.
// Created once, outside the block ...
const mid = canvas.visuals.point("dot")

// ... written inside it
Reactive.do([a, b], () => {
    Points.midPoint(a, b, mid)
})

// mid is a sender like any other
Reactive.do([mid, a], () => {
    Circles.circleAt(mid, Points.distanceToPoint(mid, a), circle)
})

The pattern is always the same: create the object outside the block, write into it inside. Geometry helpers take the object to write into as their last argument, here Points.midPoint(a, b, mid).

Shapes: depend on the shape, not on its points

A shape is two things at once: a list of points, and a reactive object of its own. It can change in two ways:

  1. One of its points moves, for example because it is a handle and gets dragged.
  2. It is written as a whole, by a helper like Rectangles.alongSegment(…, rect) or by an attachment. The shape gets new geometry; its points don’t announce anything one by one.

Reactive.do([shape], …) sees both. Reactive.do([...shape], …) lists the points and so only sees the first kind: it misses every helper and attachment that writes the shape. So: depend on the shape.

For case 1 to reach the shape, the points have to be linked to it. Shapes built from separate points, like segment(a, b) or circle(a, b, c), are linked when they are created. Polygons and polylines built from a list of vertices are not: they can have thousands of vertices, and most of them are only drawn, so the links would cost time on every change for nothing. You decide: call Reactive.linkVertices when something depends on the polygon as a whole. Drag the corners of both triangles:

Each label shows the area of its triangle, computed in a Reactive.do([shape], …) block. Only the right triangle is linked.
const corners = [
    canvas.handles.disk("handle", [x, 200]),
    canvas.handles.disk("handle", [x + 180, 200]),
    canvas.handles.disk("handle", [x + 90, 50]),
]
const shape = canvas.visuals.polygon("shape", corners)
if (linked) Reactive.linkVertices(shape)

// Depends on the polygon as a whole
const label = canvas.text.label("", "label")
Reactive.do([shape], () => {
    Polygons.centroid(shape, label)
    label.value = `${Math.round(Polygons.area(shape).value).toLocaleString("en")} px²`
})

On the left, the triangle is redrawn (drawing reads the points directly), but its area stays the same: the block depends on the polygon, and an unlinked polygon never changes when only its corners move. The same holds for everything else that depends on a polygon as a whole, such as an attachment.

One update at a time

A change starts an update: VisQuill runs every block that depends on it, then the blocks that depend on what those wrote, and so on. Within one update, each block runs at most once. That keeps updates finite even when relationships form a cycle, but it has a consequence: when a block writes to an object whose dependents have already run in this update, they don’t run again. They keep what they saw.

Most of the time you don’t notice. You do notice when a block corrects its own sender, the usual way to constrain a handle:

The handle snaps to the grid. The line and the label are registered after the constraint.
const handle = canvas.handles.disk("handle", [280, 160])

// The constraint comes first, right after the handle ...
Reactive.do([handle], () => {
    handle.x = Math.round(handle.x / grid) * grid
    handle.y = Math.round(handle.y / grid) * grid
})

// ... so everything registered later sees the snapped position
canvas.visuals.segment("line", [80, 240], handle)
const label = canvas.text.label("", "label")
Reactive.do([handle], () => {
    label.x = handle.x + 14
    label.y = handle.y - 14
    label.value = `(${handle.x}, ${handle.y})`
})

The constraint works because it is registered first, directly after the handle. Blocks registered after it see the snapped position. A block registered before it would already have run with the unsnapped position, and would keep it.

The same rule decides what a block sees when it depends on a value and on something derived from it. Say b follows a, c follows b, and a block combines a and c:

Reactive.do([a], () => b.value = a.value + 1)
Reactive.do([b], () => c.value = b.value + 1)
Reactive.do([a, c], () => d.value = a.value + c.value)   // can see the old c

When a changes, the last block can run before the change has reached c, and it doesn’t run again when c follows. d then combines the new a with the old c. If every change of a reaches c, as here, list only the end of the chain; the block can still read a:

Reactive.do([c], () => d.value = a.value + c.value)      // sees the new a and the new c

Several changes, one update

Every write is its own update. Moving a point with p.x = … and then p.y = … runs its dependents twice, and the first time they see a half-moved point. To make several writes one update, wrap them in Reactive.block:

p.x = 100        // one update ...
p.y = 50         // ... and a second one; in between, p was (100, 0)

Reactive.block(() => {
    p.x = 200    // both writes,
    p.y = 80     // one update
})

Changes VisQuill can’t see

An item holds any JavaScript object, but VisQuill only notices when .value gets a new object, not when you change a field inside it. Either assign a new object, or tell VisQuill yourself with Reactive.emit:

const stats = canvas.values.item({ count: 0, total: 10 })
Reactive.do([stats], () => {
    label.value = `${stats.value.count} of ${stats.value.total}`
})

stats.value.count = 3              // nobody notices
Reactive.emit(stats)               // now the label says "3 of 10"

stats.value = { count: 4, total: 10 }   // a new object is noticed by itself

Reactive.emit works on any reactive object: use it whenever you have changed something in a way VisQuill can’t see, so that its dependents run.

In short

  • Reactive.do(senders, action) runs now and on every change of a sender, synchronously.
  • List everything the block reads that can change. Plain objects can’t be senders.
  • Create objects outside the block, write into them inside.
  • Depend on a shape, not on its points. Link polygons and polylines with Reactive.linkVertices when something depends on them as a whole.
  • In one update each block runs once. Register constraints first.
  • Reactive.block turns several writes into one update; Reactive.emit announces a change VisQuill can’t see.