Editing
Edit data with markers, background gestures, selection, and custom overlays.
Editing the plot background
import {
Button,
DropdownMenu,
Menu,
Plot,
Popover,
type PopupRegion,
} from '@soundor/components';
import { textStyle, useTheme } from '@soundor/components/theme';
import { Text, View } from '@soundor/react';
import { useRef, useState } from 'react';
import type { UiNode } from 'soundor:ui';
const unitDomain = [0, 1] as const;
const clampToDomain = (value: number) =>
Math.min(unitDomain[1], Math.max(unitDomain[0], value));
export default function Demo() {
const theme = useTheme();
const [points, setPoints] = useState<readonly (readonly [number, number])[]>([
[0.5, 0.5],
]);
const [menu, setMenu] = useState<PopupRegion | null>(null);
const [cursor, setCursor] = useState('');
const [selected, setSelected] = useState<number | null>(null);
const [selectedIds, setSelectedIds] = useState<readonly string[]>([]);
const [aux, setAux] = useState(1);
const anchor = useRef<UiNode | null>(null);
return (
<View style={{ gap: theme.spacing.spaceSm }}>
<Plot
width={360}
height={180}
accessibilityLabel="Point editor"
selection={{
selectedIds,
onSelectionChange: setSelectedIds,
multiple: true,
rectangle: true,
}}
onBackgroundDoubleClick={({ data: [x, y] }) =>
setPoints((prev) => [...prev, [clampToDomain(x), clampToDomain(y)]])
}
onBackgroundPointerMove={({ data: [x, y] }) =>
setCursor(`${x.toFixed(2)}, ${y.toFixed(2)}`)
}
onBackgroundPointerLeave={() => setCursor('')}
onBackgroundContextMenu={({ event }) => {
event.preventDefault();
setMenu({ x: event.pageX, y: event.pageY });
}}
>
<Plot.XAxis domain={unitDomain} />
<Plot.YAxis domain={unitDomain} />
<Plot.Grid />
{points.map(([x, y], index) => (
<Plot.Marker
key={index}
id={String(index)}
label={String(index + 1)}
accessibilityLabel={`Point ${index + 1}`}
ref={index === selected ? anchor : undefined}
movement={index === 0 ? 'x' : 'both'}
hitRadius={14}
onSelect={() => setSelected(index)}
onWheel={(event) => {
event.preventDefault();
setAux((value) =>
Math.max(0, value - Math.sign(event.deltaY) * 0.1),
);
}}
x={x}
y={y}
onMove={(point) =>
setPoints((prev) => prev.map((p, i) => (i === index ? point : p)))
}
/>
))}
</Plot>
<Popover open={selected !== null} onOpenChange={() => setSelected(null)}>
<Popover.Content
anchor={anchor}
side="top"
accessibilityLabel="Point controls"
autoFocus={false}
dismissOnOutside={false}
>
<Text style={{ color: theme.color.text }}>
Auxiliary value: {aux.toFixed(1)}
</Text>
<Button onPress={() => setSelected(null)}>
Close point controls
</Button>
</Popover.Content>
</Popover>
<Text style={textStyle(theme, 'body', theme.color.textSecondary)}>
{selectedIds.length} selected.{' '}
{cursor || 'Double-click to add; drag empty space to select.'}
</Text>
<Button onPress={() => setPoints((prev) => [...prev, [0.25, 0.75]])}>
Add point
</Button>
<DropdownMenu open={menu !== null} onOpenChange={() => setMenu(null)}>
<DropdownMenu.Content
anchor={menu ?? undefined}
accessibilityLabel="Graph actions"
>
<Menu.Item
onPress={() => {
setPoints([]);
setSelected(null);
setSelectedIds([]);
}}
>
Clear points
</Menu.Item>
</DropdownMenu.Content>
</DropdownMenu>
</View>
);
}plot-edit.tsx, running in the web runtime.SourceBackground callbacks are for the empty plotting area. The hit layer sits below markers and custom interactive children, and excludes the axis margins. Decorative custom views can opt out with pointerEvents: 'none'. Provide a keyboard alternative for actions such as adding a point.
The background includes the padding reserved for handles, so data can fall outside the axis domains. Clamp it before adding a point to keep insertion within the same bounds as dragging.
const clampToDomain = (value: number) => Math.min(1, Math.max(0, value));
<Plot
width={360}
height={180}
onBackgroundDoubleClick={({ data: [x, y] }) =>
addPoint([clampToDomain(x), clampToDomain(y)])
}
>
<Plot.XAxis domain={[0, 1]} />
<Plot.YAxis domain={[0, 1]} />
</Plot>;Each background event supplies the Soundor pointer event, the plot-local logical pixel point, default-scale data, and coordinates with bounds and conversions. Use coordinatesFor({ yAxis: 'other' }) for named axes. onBackgroundDrag reports start, move, end, and cancel with a fixed origin, and handles cancellation on unmount. The caller owns graph edits.
Interactive markers
Plot.Marker draws a point. Add onMove to make it draggable, movement="x" or movement="y" to lock it to an axis, and constrain to snap or bound emitted data-space values. A cancelled gesture reports the starting point without calling constrain, then calls onMoveCancel and onMoveEnd. Close host edit gestures in onMoveEnd.
hitRadius is independent of the canvas marker's radius. Set selected or disabled, or provide render(state) to draw a non-interactive custom face. Styles use the PlotMarker.root theme slot. Set accessibilityLabel and describeValue to identify the point and describe its values.
onSelect handles a primary press, Enter, Space or an assistive activation. onRemove requests removal on Delete or Backspace; the caller owns the collection. onWheel, onDoubleClick and onContextMenu receive the Soundor event. Wrap a marker in ContextMenu.Trigger for built-in accessibility actions, or pass the marker's ref to a Popover.
Selection and grouped movement
Pass selection={{ selectedIds, onSelectionChange, multiple: true, rectangle: true }} to Plot and a stable id to each selectable marker. The caller owns the selected IDs.
| Interaction | Result |
|---|---|
| Click empty space | Clear the selection unless clearOnBackgroundPress is false |
| Drag empty space | Replace selection with the enclosed markers |
| Shift + drag empty space | Add the enclosed markers |
| Ctrl/Cmd + drag empty space | Toggle the enclosed markers |
| Click a marker | Select only that marker |
| Shift + click a marker | Add it to the selection |
| Ctrl/Cmd + click a marker | Toggle it |
| Drag a marker | Move it, or move its existing selection |
| Shift + drag a marker | Move it or its group at one-tenth speed |
Use Ctrl on Windows and Linux, or Cmd on macOS. The primary modifier wins over Shift for selection. Rectangle selection uses the modifiers and selection at the start of the drag, after a small movement threshold. It updates as the rectangle changes and restores the initial selection if the pointer is cancelled. With rectangle selection enabled in multiple mode, background drags belong to selection rather than onBackgroundDrag. Turn off rectangle to use a custom background drag. Background double-click and context menus still work.
Click modifiers do not add or toggle selection during a marker drag. A plain drag on an unselected marker selects it; a modified drag on an unselected marker moves it independently. Press or release Shift mid-drag to change speed without jumping, including on logarithmic axes. Enter or Space also selects a focused marker.
By default, a group drag calls the move handlers of each movable, selected marker with one shared displacement, bounded by the first axis edge the group reaches. Each marker keeps its movement settings and constraints. On a log axis, a common pixel displacement preserves frequency ratios. Use functional state updates when several marker handlers write to the same collection.
Use onGroupDrag to own the edit yourself, for example to apply a group-wide constraint or record one undo transaction. It reports the captured IDs and start, move, end, and cancel phases instead of calling individual onMove handlers. Capture starting values on start, then use each marker's scale to map its original value to pixels, add delta, and invert. Restore the original values on cancel and close host gestures on end or cancel.
Handles at the ends of an axis
A plot with draggable markers insets the data mapping by the handle radius and halo, so handles stay whole at the ends. The axes and grid still run edge to edge; set extend on a series to make the data reach them too. Where the axes' room already keeps handles whole, as a full-frame EQ graph's labels do, set autoSafeZone={false} on Plot to map the data all the way to the frame instead; its own safeZone still applies.
Render custom handle views inside Plot to layer them over the canvas. Use safeZone on Plot to keep them whole at the ends. EnvelopeEditor is built this way.
usePlotCoordinates
Call usePlotCoordinates() from a component inside Plot for the default coordinate mapping. x.map(value) gives the logical pixel position across the plot, and inner is the area the axes map to. Pass axis references, such as { yAxis: 'spectrum' }, to map against named axes. The named form returns undefined until those axes are available.
Keyboard and accessibility
A marker with onMove is a tab stop. The arrow keys move it, and Shift makes the step ten times finer. Double-click or Alt-click (Option-click on a Mac) resets it, as do Delete and Backspace when onRemove is not supplied. Escape cancels a drag. The marker is announced by its label (or “Point 1”, “Point 2”… in draw order) with both values, such as “X 1.20 kHz, Y 4.0 dB”.
Props
Plot.Marker
Prop
Type
PlotMarkerState
The state passed to the marker's render callback:
Prop
Type
PlotBackgroundProps
Pass these callbacks directly to Plot:
Prop
Type
PlotBackgroundEvent and PlotBackgroundDragEvent
The drag payload adds phase and origin to the basic background event. origin is the starting point in logical pixels relative to the plot.
Prop
Type
PlotSelection
Pass these options via the selection prop on Plot:
Prop
Type
PlotGroupDrag
The payload passed to selection.onGroupDrag:
Prop
Type