Skip to content

⚠ Early release: v0.3.2.sophistry is not ready for production use. Until 1.0, any minor release may break the API; expect missing features and bugs too.Stability and versioning

Dragging and input

A draggable or useMovablePoint writes a track, constraints shape where it may go, and every prop bound to that track (directly or through derive) follows it. Every draggable is also a keyboard tab stop. Start with DragConstraints, then KeyboardAccessible.

First scene: make it draggable

Step three of the first-scene tutorial: the same theta track that the animation writes is now also written by dragging the dot around the ring.

FirstSceneDraggable.tsx
20 collapsed lines
import {
angleParam,
derive,
draggable,
draw,
sequence,
track,
valueTo,
} from "@sophistry/core";
import {
Arc,
Circle,
Dot,
Line,
Stage,
Text,
usePlayer,
useTheme,
} from "@sophistry/solidjs";
import { onSettled } from "solid-js";
const R = 2.4;
function Scene() {
const theme = useTheme();
const palette = () => theme().palette;
const player = usePlayer();
const drawn = track(0);
const theta = track(0);
const tip = derive(theta, (angle) => ({
x: R * Math.cos(angle),
y: R * Math.sin(angle),
}));
const degrees = derive(theta, (angle) => Math.round((angle * 180) / Math.PI));
onSettled(() => {
void player.play(
sequence(
draw(drawn, { duration: 1.2 }),
valueTo(theta, 1.1, { duration: 1.6, easing: "smooth" }),
),
);
});
return (
<>
<Circle radius={R} stroke={palette().grid} progress={drawn} />
<Line from={{ x: 0, y: 0 }} to={tip} stroke={palette().series[0]} />
<Arc radius={0.8} angle={theta} stroke={palette().series[1]} />
<Dot
center={tip}
radius={0.16}
label="angle"
{...draggable(theta, {
param: angleParam({ x: 0, y: 0 }, { radius: R }),
})}
/>
{/* Beside the circle: below it would fall off the 16:9 stage. */}
<Text
text={derive(degrees, (value) => `θ = ${value}°`)}
x={3.8}
y={-2.2}
color={palette().muted}
/>
</>
);
}
export default function FirstSceneDraggable() {
return (
<Stage units={10}>
<Scene />
</Stage>
);
}

Drag constraints

Three dots with three rules: one moves freely, one is pinned to a circle, and one snaps to a grid of 0.5 units.

DragConstraints.tsx
2 collapsed lines
import { draggable, onCircle, snapToGrid, trackPoint } from "@sophistry/core";
import { Circle, Dot, Stage, Text, useTheme } from "@sophistry/solidjs";
export default function DragConstraints() {
const theme = useTheme();
const palette = () => theme().palette;
const free = trackPoint(-4, 0.5);
const ring = trackPoint(0, 1.5);
const grid = trackPoint(4, 0.5);
const freeDrag = draggable(free);
const ringDrag = draggable(ring, {
constrain: onCircle({ x: 0, y: 0 }, 1.5),
});
const gridDrag = draggable(grid, { constrain: snapToGrid(0.5) });
return (
<Stage units={12}>
<Circle
center={{ x: 0, y: 0 }}
radius={1.5}
stroke={palette().grid}
dash={[0.15, 0.15]}
/>
<Dot center={free} radius={0.2} label="free" {...freeDrag} />
<Dot
center={ring}
radius={0.2}
color={palette().series[1]}
label="on a circle"
{...ringDrag}
/>
<Dot
center={grid}
radius={0.2}
color={palette().series[2]}
label="snapped to a grid"
{...gridDrag}
/>
<Text text="free" x={-4} y={-2} color={palette().muted} fontSize={0.35} />
<Text
text="onCircle"
x={0}
y={-2}
color={palette().muted}
fontSize={0.35}
/>
<Text
text="snapToGrid"
x={4}
y={-2}
color={palette().muted}
fontSize={0.35}
/>
<Text
text="drag the dots"
y={-3}
color={palette().muted}
fontSize={0.3}
/>
</Stage>
);
}

Drag along a ring

A dot constrained to a circle, draggable with the pointer or the arrow keys.

RingDrag.tsx
9 collapsed lines
import { draggable, onCircle, trackPoint } from "@sophistry/core";
import {
Circle,
InteractionGroup,
LabeledDot,
Stage,
Text,
useTheme,
} from "@sophistry/solidjs";
export default function RingDrag() {
const theme = useTheme();
const position = trackPoint(0, 2);
const ring = draggable(position, { constrain: onCircle({ x: 0, y: 0 }, 2) });
return (
<Stage units={10}>
<Circle
center={{ x: 0, y: 0 }}
radius={2}
stroke={theme().palette.grid}
dash={[0.15, 0.15]}
strokeWidth={0.04}
/>
<InteractionGroup {...ring}>
<LabeledDot center={position} text="drag" />
</InteractionGroup>
<Text
text="drag the dot, or Tab to it and use the arrow keys"
y={-2.5}
color={theme().palette.muted}
fontSize={0.28}
/>
</Stage>
);
}

Keyboard-accessible dragging

Every draggable is also a tab stop. Tab to the dot, then use the arrow keys to move it by 0.5 units (hold Shift for 0.1), or Escape to cancel a drag in progress.

KeyboardAccessible.tsx
2 collapsed lines
import { derive, draggable, toBounds, trackPoint } from "@sophistry/core";
import { Dot, Rect, Stage, Text, useTheme } from "@sophistry/solidjs";
export default function KeyboardAccessible() {
const theme = useTheme();
const palette = () => theme().palette;
const box = { minX: -3, maxX: 3, minY: -1.5, maxY: 1.5 };
const position = trackPoint(0, 0);
const handle = draggable(position, {
constrain: toBounds(box, { half: 0.2 }),
step: 0.5,
fineStep: 0.1,
});
return (
<Stage units={10}>
<Rect width={6} height={3} stroke={palette().grid} />
<Dot center={position} radius={0.2} label="point" {...handle} />
<Text
text={derive(
position,
({ x, y }) => `(${x.toFixed(1)}, ${y.toFixed(1)})`,
)}
y={2.1}
color={palette().muted}
/>
<Text
text="Tab to focus, then arrow keys (Shift = fine)"
y={-2.4}
color={palette().muted}
fontSize={0.28}
/>
</Stage>
);
}

A slider that drives a graph

Drag the knob along a line to change the frequency of a sine wave. scalarParam turns the pointer position into a number, and the graph reads that number.

ParameterSlider.tsx
10 collapsed lines
import { derive, draggable, scalarParam, track } from "@sophistry/core";
import {
Axes,
Dot,
FunctionGraph,
Line,
Stage,
Text,
useTheme,
} from "@sophistry/solidjs";
export default function ParameterSlider() {
const theme = useTheme();
const palette = () => theme().palette;
const frequency = track(1);
const from = { x: -2, y: -1.9 };
const to = { x: 2, y: -1.9 };
const param = scalarParam(from, to, { range: [0.5, 3], step: 0.1 });
const knob = derive(frequency, (value) => ({
x: from.x + ((value - 0.5) / 2.5) * 4,
y: from.y,
}));
const wave = derive(frequency, (value) => (x: number) => Math.sin(value * x));
return (
<Stage units={10}>
<Axes
xRange={[-8, 8, 4]}
yRange={[-1, 1, 1]}
width={9}
height={2.8}
center={{ x: 0, y: 0.5 }}
>
<FunctionGraph function={wave} stroke={palette().series[0]} />
</Axes>
<Line from={from} to={to} stroke={palette().muted} />
<Dot
center={knob}
radius={0.2}
label="frequency"
{...draggable(frequency, { param })}
/>
<Text
text="frequency"
x={-3.6}
y={from.y}
fontSize={0.4}
color={palette().muted}
/>
<Text
text={derive(frequency, (value) => value.toFixed(1))}
x={3.2}
y={from.y}
fontSize={0.4}
/>
<Text
text="drag the knob"
y={-2.45}
color={palette().muted}
fontSize={0.26}
/>
</Stage>
);
}

Linked dots

Drag any corner of the triangle. The outline and the area readout are derived from the three dragged points, so they update on every move.

LinkedDots.tsx
2 collapsed lines
import { derive, draggable, trackPoint } from "@sophistry/core";
import { Dot, Polygon, Stage, Text, useTheme } from "@sophistry/solidjs";
export default function LinkedDots() {
const theme = useTheme();
const palette = () => theme().palette;
const corners = [trackPoint(-2, -1), trackPoint(2, -1), trackPoint(0, 1.5)];
const handles = corners.map((corner) => draggable(corner));
const points = derive(corners, (a, b, c) => [a, b, c]);
const area = derive(
corners,
(a, b, c) =>
Math.abs((b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)) / 2,
);
return (
<Stage units={10}>
<Polygon points={points} fill={palette().series[0]} fillOpacity={0.3} />
{corners.map((corner, i) => (
<Dot
center={corner}
radius={0.2}
label={`corner ${i + 1}`}
{...handles[i]}
/>
))}
<Text
text={derive(area, (value) => `area = ${value.toFixed(2)}`)}
y={-1.9}
/>
<Text
text="drag the corners"
y={-2.45}
color={palette().muted}
fontSize={0.26}
/>
</Stage>
);
}

Drop targets

Drag the token onto either box. Each box lights up while the token is over it, and the choice is reported when you let go.

DropTargets.tsx
3 collapsed lines
import { draggable, dropTarget, trackPoint } from "@sophistry/core";
import { Circle, Rect, Stage, Text, useTheme } from "@sophistry/solidjs";
import { createSignal } from "solid-js";
export default function DropTargets() {
const theme = useTheme();
const palette = () => theme().palette;
const home = { x: 0, y: -1.6 };
const token = trackPoint(home.x, home.y);
// Written by the drop targets on user input, so plain Solid signals.
const [overLeft, setOverLeft] = createSignal(false);
const [overRight, setOverRight] = createSignal(false);
const [chosen, setChosen] = createSignal("nothing yet");
const drag = draggable(token, { onDragEnd: () => token.set(home) });
const zone = (over: (value: boolean) => void, name: string) =>
dropTarget({ over, onDrop: () => setChosen(name) });
return (
<Stage units={10}>
<Rect
center={{ x: -2.5, y: 0.8 }}
width={3}
height={2}
cornerRadius={0.2}
fill={overLeft() ? palette().highlight : palette().surface}
{...zone(setOverLeft, "left box")}
/>
<Rect
center={{ x: 2.5, y: 0.8 }}
width={3}
height={2}
cornerRadius={0.2}
fill={overRight() ? palette().highlight : palette().surface}
{...zone(setOverRight, "right box")}
/>
<Text
text="left box"
x={-2.5}
y={0.8}
color={palette().muted}
fontSize={0.35}
/>
<Text
text="right box"
x={2.5}
y={0.8}
color={palette().muted}
fontSize={0.35}
/>
<Circle
center={token}
radius={0.3}
fill={palette().series[0]}
label="token"
{...drag}
/>
<Text
text={`dropped on: ${chosen()}`}
y={2.3}
color={palette().muted}
fontSize={0.4}
/>
<Text
text="drag the token onto a box"
y={-2.5}
color={palette().muted}
fontSize={0.28}
/>
</Stage>
);
}

Step-through lesson

Drag the token onto the right answer to unlock Next. Wrong drops bounce back; Tab to a box and press Enter to answer without a pointer.

StepThroughLesson.tsx
19 collapsed lines
import {
draggable,
dropTarget,
fadeIn,
indicate,
moveTo,
sequence,
track,
trackPoint,
} from "@sophistry/core";
import {
Circle,
Rect,
Stage,
Text,
usePlayer,
useTheme,
} from "@sophistry/solidjs";
import { createSignal } from "solid-js";
const QUESTIONS = [
{ prompt: "What is 2 + 3?", options: [4, 5, 6], answer: 5 },
{ prompt: "What is 3 × 3?", options: [6, 9, 12], answer: 9 },
{ prompt: "What is 10 − 7?", options: [2, 3, 4], answer: 3 },
];
const BOX_X = [-3.2, 0, 3.2];
const HOME = { x: 0, y: -1.8 };
export default function StepThroughLesson() {
const theme = useTheme();
const palette = () => theme().palette;
const { play } = usePlayer();
const [step, setStep] = createSignal(0);
const [solved, setSolved] = createSignal(false);
const [feedback, setFeedback] = createSignal(
"Drag the token onto an answer.",
);
const token = trackPoint(HOME.x, HOME.y);
const tokenScale = track(1);
const promptOpacity = track(1);
const over = QUESTIONS[0].options.map(() => createSignal(false));
const question = () => QUESTIONS[Math.min(step(), QUESTIONS.length - 1)];
const finished = () => step() >= QUESTIONS.length;
function answer(index: number) {
if (solved() || finished()) return;
const value = question().options[index];
if (value === question().answer) {
setSolved(true);
setFeedback(`Correct, ${value}! Press Next.`);
void play(
sequence(
moveTo(token, { x: BOX_X[index], y: 0.8 }, { duration: 0.3 }),
indicate(tokenScale, { factor: 1.4 }),
),
);
} else {
setFeedback(`${value} is not it. Try again.`);
void play(moveTo(token, HOME, { duration: 0.25 }));
}
}
function next() {
setStep((s) => s + 1);
setSolved(false);
token.set(HOME);
if (finished()) {
setFeedback("Lesson complete.");
return;
}
setFeedback("Drag the token onto an answer.");
promptOpacity.set(0);
void play(fadeIn(promptOpacity, { duration: 0.5 }));
}
const drag = draggable(token, {
disabled: solved,
onDragEnd: () => {
if (!solved()) token.set(HOME);
},
});
return (
<div>
<Stage units={10} aspect={1.75}>
{BOX_X.map((x, i) => (
<>
<Rect
center={{ x: x, y: 0.8 }}
width={2.6}
height={1.6}
cornerRadius={0.2}
fill={
solved() && question().options[i] === question().answer
? palette().series[1]
: over[i][0]()
? palette().highlight
: palette().surface
}
label={finished() ? undefined : `Answer ${question().options[i]}`}
onTap={() => answer(i)}
{...dropTarget({ over: over[i][1], onDrop: () => answer(i) })}
/>
<Text
text={finished() ? "" : String(question().options[i])}
x={x}
y={0.8}
fontSize={0.6}
/>
</>
))}
<Text
text={finished() ? "All done!" : question().prompt}
y={2.4}
fontSize={0.6}
opacity={promptOpacity}
/>
<Circle
center={token}
radius={0.35}
scale={tokenScale}
fill={palette().series[0]}
label="answer token"
{...drag}
/>
</Stage>
<div
style={{
display: "flex",
gap: "1rem",
"align-items": "center",
"margin-top": "0.5rem",
}}
>
<span style={{ flex: "1" }} role="status" aria-live="polite">
{feedback()}
</span>
<span>
{Math.min(step() + 1, QUESTIONS.length)} / {QUESTIONS.length}
</span>
<button type="button" disabled={!solved()} onClick={next}>
Next
</button>
</div>
</div>
);
}

Scroll-driven animation

Scroll the box: its scroll position is the timeline's time. A sticky stage stays pinned while the page behind it moves, and scrolling back rewinds the scene.

ScrollDrivenStage.tsx
12 collapsed lines
import {
createClock,
derive,
draw,
moveTo,
sequence,
timeline,
track,
trackPoint,
} from "@sophistry/core";
import { Circle, Line, Stage, Text } from "@sophistry/solidjs";
import { onCleanup } from "solid-js";
export default function ScrollDrivenStage() {
const clock = createClock();
const drawn = track(0);
const pos = trackPoint(-3, 0);
const progress = track(0);
const tl = timeline(
sequence(
draw(drawn, { duration: 1 }),
moveTo(pos, { x: 3, y: 0 }, { duration: 2 }),
moveTo(pos, { x: 0, y: 0 }, { duration: 1 }),
),
{ clock },
);
onCleanup(() => tl.dispose());
const readout = derive(
[progress, tl.time],
(p, time) => `scroll ${Math.round(p * 100)}% · t = ${time.toFixed(2)} s`,
);
// Scroll position (0..1) maps straight onto timeline time.
const onScroll = (el: HTMLElement) => {
const range = el.scrollHeight - el.clientHeight;
const p = range > 0 ? el.scrollTop / range : 0;
progress.set(p);
tl.seek(p * tl.duration);
};
return (
<section
aria-label="Scrollable demo: scroll to advance the animation"
tabindex={0}
style={{
height: "20rem",
"overflow-y": "auto",
border: "1px solid rgba(127,127,127,0.4)",
"border-radius": "0.5rem",
}}
onScroll={(e) => onScroll(e.currentTarget)}
>
<div style={{ height: "60rem", position: "relative" }}>
<div style={{ position: "sticky", top: "0" }}>
<Stage units={10} clock={clock} aspect={2.2}>
{/* A faint guide, so the stage reads before the first scroll. */}
<Line from={{ x: -3, y: 0 }} to={{ x: 3, y: 0 }} opacity={0.25} />
<Circle center={{ x: -3, y: 0 }} radius={1} opacity={0.25} />
<Circle center={{ x: 3, y: 0 }} radius={1} opacity={0.25} />
<Circle center={pos} radius={1} progress={drawn} />
<Text text={readout} y={-1.9} fontSize={0.35} />
</Stage>
</div>
</div>
</section>
);
}