soundor:history
Opt-in undo/redo for parameter and persistent-state edits, with gestures and synchronous buffered transactions.
History records edits to Soundor-managed parameters and persistent state. Each plugin instance owns one manager, shared by JavaScript and the Rust controller. It works with the editor closed and survives editor recreation. Each standalone Web application owns one equivalent manager. Plugin instances have independent History.
import { parameters } from 'soundor:parameters';
import { state } from 'soundor:state';
import { history } from 'soundor:history';Discrete edits
History is opt-in. Ordinary setters retain their existing behavior. Supply
{ history: true } to record one changed value, or a label to name the edit:
parameters.enabled.set((current) => !current, { history: true });
state.selectedPreset.set('Warm Vocal', {
history: { label: 'Select Preset' },
});
state.bands.set((current) => [...current, newBand], {
history: { label: 'Add EQ Band' },
});A direct value and a synchronous functional updater use the same setter. The updater runs exactly once against the current store value, including a staged value inside a transaction. React render values remain subscription snapshots; reading them in a closure does not replace an updater.
Values are validated and normalized before recording. Unchanged writes,
including writes that snap back to the same parameter value, create no entry
and leave the redo branch intact. The default label is Change followed by
the parameter label or state field name.
Continuous interactions
Parameter gestures delimit host automation. State gestures are Soundor-only editing boundaries. Neither records History by default. Enable History on the outermost gesture to group immediate edits:
parameters.frequency.beginGesture({
history: { label: 'Adjust Frequency' },
});
try {
parameters.frequency.set(500);
parameters.frequency.set(800);
} finally {
parameters.frequency.endGesture();
}
state.bands.beginGesture({ history: { label: 'Move EQ Band' } });
try {
state.bands.set((current) => updateBand(current, id, position));
} finally {
state.bands.endGesture();
}A gesture captures its initial value at the outermost start and its final value at the outermost end. Nested starts retain the outer configuration and label, including when the outer gesture has History disabled. Inside a History-enabled gesture, setter-level History options join that gesture. Inside an ordinary gesture, each history-enabled setter creates its own entry. A gesture with no user edit, or one ending at its initial value, creates none. Balance gestures during component cleanup. Closing the plugin's editor cancels that editor's unfinished recordings and ends its host gestures; committed entries survive. A second native/editor owner cannot acquire a field already owned by another History-enabled gesture.
Atomic transactions
Transactions buffer synchronous writes to several fields and create one entry:
history.transaction('Load Preset', () => {
parameters.frequency.set(1200);
parameters.gain.set(-3);
state.selectedPreset.set('Warm Vocal');
state.bands.set(newBands);
parameters.gain.set((current) => current + 1);
// get() sees the staged -2 value here.
});During the callback, getters and updaters see staged values. Live parameter storage, snapshots, host notifications and subscriptions remain unchanged. On success, Soundor prepares all values and the entry, installs the complete change, then delivers notifications. Observers see the complete committed state. The host receives parameter notifications sequentially: DAWs cannot be guaranteed to see several parameter atomics change at exactly the same instant. Real-time DSP reads continue reading the live parameter atomics.
A thrown callback or failed setter discards all staged writes. Async callbacks and Promise/thenable results are rejected. Transactions cannot undo external side effects such as file writes or application callbacks; keep their bodies to synchronous Soundor edits and ordinary computation.
Nested transactions reuse the outer buffer and label. There are no savepoints.
A failed nested transaction or Soundor staged operation poisons the whole
transaction even if caught. If the outer callback then returns normally,
Soundor throws TransactionAbortedError with code TRANSACTION_ABORTED and
the original cause. An application exception handled entirely within the
callback does not poison it.
Starting or ending any gesture inside a transaction is rejected and poisons it. A transaction may edit an unrelated field while a gesture is active. It cannot edit a field owned by a History-enabled gesture; rejection leaves that gesture available to finish normally. Setter History options within a transaction join the outer transaction.
Undo, redo and subscriptions
history.undo();
history.redo();
const unsubscribe = history.subscribe((status) => {
console.log(status.canUndo, status.undoLabel);
console.log(status.canRedo, status.redoLabel);
});canUndo(), canRedo(), undoLabel() and redoLabel() read availability;
labels are null when unavailable. snapshot() returns a stable immutable
status object. Subscriptions report commits, replay and clearing, without
notifications for no-op edits. They do not call immediately on subscription.
clear() discards both stacks and invalidates unfinished recordings.
Replay validates and prepares all affected values before installing them, uses the existing parameter host-notification pathway, and never records itself. State subscribers receive the restored values. A new committed Soundor edit after undo clears redo, including a changed setter without History. A History gesture defers that decision until its final net change is known. Undo/redo rejects entries touching fields currently owned by History gestures, and is not allowed inside a transaction. A failed replay leaves the stacks intact.
React
import {
Pressable,
Text,
View,
useParameter,
useHistory,
} from '@soundor/react';
import { useEffect, useRef, useState } from 'react';
import { history } from 'soundor:history';
import { parameters } from 'soundor:parameters';
function Button({
label,
onPress,
disabled = false,
selected = false,
}: {
label: string;
onPress: () => void;
disabled?: boolean;
selected?: boolean;
}) {
return (
<Pressable
onPress={onPress}
disabled={disabled}
accessibilityState={{ selected }}
style={({ pressed }) => ({
paddingVertical: 7,
paddingHorizontal: 12,
borderRadius: 6,
backgroundColor: selected || pressed ? '#315da8' : '#2a2c33',
opacity: disabled ? 0.4 : 1,
})}
>
<Text style={{ color: '#e6e7ea' }}>{label}</Text>
</Pressable>
);
}
export default function History() {
const gain = useParameter(parameters.gain);
const voices = useParameter(parameters.voices);
const bypass = useParameter(parameters.bypass);
const mode = useParameter(parameters.mode);
const historyStatus = useHistory();
const dragging = useRef(false);
const [isDragging, setDragging] = useState(false);
const endGesture = () => {
if (!dragging.current) return;
dragging.current = false;
parameters.gain.endGesture();
setDragging(false);
};
useEffect(
() => () => {
// Also balance the gesture if the example is replaced while dragging.
if (dragging.current) parameters.gain.endGesture();
},
[],
);
const stepGain = (by: number) =>
parameters.gain.set((current) => current + by, {
history: { label: 'Adjust Gain' },
});
const loadPreset = (warm: boolean) => {
// Four edits publish together and undo as one entry.
history.transaction(warm ? 'Load Warm Preset' : 'Load Clean Preset', () => {
parameters.gain.set(warm ? 0.75 : 0.5);
parameters.voices.set(warm ? 6 : 4);
parameters.mode.set(warm ? 'warm' : 'clean');
parameters.bypass.set(false);
});
};
return (
<View style={{ width: 340, maxWidth: '100%', gap: 12 }}>
<Text style={{ color: '#e6e7ea', fontSize: 18 }}>
Gain {gain.toFixed(2)} · Voices {voices}
</Text>
<View
accessibilityRole="adjustable"
accessibilityLabel="Gain"
accessibilityValue={{ min: 0, max: 1, now: gain }}
accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}
onAccessibilityAction={(event) => {
if (event.actionName === 'increment') stepGain(0.05);
if (event.actionName === 'decrement') stepGain(-0.05);
}}
focusable
onKeyDown={(event) => {
if (
['ArrowRight', 'ArrowUp', 'ArrowLeft', 'ArrowDown'].includes(
event.key,
)
) {
event.preventDefault();
stepGain(
event.key === 'ArrowRight' || event.key === 'ArrowUp'
? 0.05
: -0.05,
);
}
}}
onPointerDown={(event) => {
if (event.button !== 0 || dragging.current) return;
// Moves update immediately; release records the entire drag as
// one entry, alongside the parameter's host automation gesture.
parameters.gain.beginGesture({ history: { label: 'Adjust Gain' } });
dragging.current = true;
setDragging(true);
}}
onPointerMove={(event) => {
if (dragging.current)
parameters.gain.set((current) => current + event.movementX / 340);
}}
onPointerUp={endGesture}
onPointerCancel={endGesture}
style={{
height: 28,
borderRadius: 6,
backgroundColor: '#2a2c33',
cursor: 'ew-resize',
}}
>
<View
style={{
width: `${gain * 100}%`,
height: '100%',
borderRadius: 6,
backgroundColor: '#5489e8',
}}
/>
</View>
<Text style={{ color: '#8b8f98' }}>
Drag gain: one gesture, one undo. Arrow keys step gain.
</Text>
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
<Text style={{ color: '#8b8f98' }}>Voices</Text>
<Button
label="Fewer"
disabled={voices === 1}
onPress={() =>
parameters.voices.set((current) => current - 1, {
history: { label: 'Remove Voice' },
})
}
/>
<Button
label="More"
disabled={voices === 8}
onPress={() =>
parameters.voices.set((current) => current + 1, {
history: { label: 'Add Voice' },
})
}
/>
<Button
label={bypass ? 'Bypass On' : 'Bypass Off'}
selected={bypass}
onPress={() =>
parameters.bypass.set((current) => !current, {
history: { label: 'Toggle Bypass' },
})
}
/>
</View>
<View style={{ flexDirection: 'row', gap: 8 }}>
{parameters.mode.info.options.map((option) => (
<Button
key={option.value}
label={option.label}
selected={mode === option.value}
onPress={() =>
parameters.mode.set(option.value, {
history: { label: 'Change Mode' },
})
}
/>
))}
</View>
<View style={{ flexDirection: 'row', gap: 8 }}>
<Button
label="Load Warm Preset"
disabled={isDragging}
onPress={() => loadPreset(true)}
/>
<Button
label="Load Clean Preset"
disabled={isDragging}
onPress={() => loadPreset(false)}
/>
</View>
<View style={{ flexDirection: 'row', gap: 8 }}>
<Button
label="Undo"
disabled={isDragging || !historyStatus.canUndo}
onPress={historyStatus.undo}
/>
<Button
label="Redo"
disabled={isDragging || !historyStatus.canRedo}
onPress={historyStatus.redo}
/>
<Button
label="Clear history"
disabled={
isDragging || (!historyStatus.canUndo && !historyStatus.canRedo)
}
onPress={history.clear}
/>
</View>
<Text style={{ color: '#8b8f98' }}>
{isDragging
? 'Recording gain gesture…'
: `Undo: ${historyStatus.undoLabel ?? 'none'}`}
</Text>
<Text style={{ color: '#8b8f98' }}>
Redo: {historyStatus.redoLabel ?? 'none'}
</Text>
</View>
);
}history.tsxSourceDrag gain to group its updates with beginGesture() and endGesture().
Voices, bypass and mode record discrete edits. Loading a preset changes all
four parameters in one transaction; Undo restores them together. The labels
show the next undo and redo actions, and Clear history discards both stacks.
useParameter() and
useStateValue() keep returning values. Pass
History options to the field's setter or gesture start explicitly. Merely
subscribing to a field never configures how other components edit it.
const frequency = useParameter(parameters.frequency);
<Slider
value={frequency}
onSlidingStart={() =>
parameters.frequency.beginGesture({
history: { label: 'Adjust Frequency' },
})
}
onValueChange={(value) => parameters.frequency.set(value)}
onSlidingComplete={() => parameters.frequency.endGesture()}
/>;Use useHistory() for reactive buttons.
It exposes canUndo, canRedo, undoLabel, redoLabel and stable undo and
redo callbacks, without polling or field-wide hook configuration.
The Rust controller
The plugin's Rust controller reaches the same History
as the UI: its parameter and state edits take the same options, gestures and
transactions, and record into the same entries. All History work belongs on
the control thread, never in process(). History adds no locks or
allocations to audio-thread parameter reads or DAW automation callbacks.
JavaScript callbacks are delivered on the UI thread through runtime dispatch.
Automation and restoration
DAW automation is external input and never creates History entries. A History-enabled gesture records the observed effective value at its end, provided a Soundor user edit occurred. If the user changes 200 Hz to 500 Hz and automation then changes it to 600 Hz before the gesture ends, the entry records 200 Hz to 600 Hz. Automation alone creates none.
Later automation does not invalidate committed entries. Undo/redo applies the stored values through the normal host-aware setter; the DAW may overwrite them again. History does not replace the DAW's automation or undo systems, change automation timelines, or model Read/Touch/Latch/Write modes.
Accepted project restoration restores parameter and state values, invalidates
unfinished History recordings, clears both stacks, and then calls the
application's existing native stateRestored() hook. JS History status is
delivered through the next runtime dispatch. History is never serialized or
saved to IndexedDB. Editor reopening alone does not clear it.
Limits
Managers retain at most 100 entries and approximately 16 MiB of accounted value data by default, evicting the oldest entries first. Before/after values are stored in full; there is no structural diffing. A single entry exceeding the budget is not retained and clears older undo and redo entries, so replay cannot cross that unrecordable edit. Allocation and validation happen before transaction publication. Arbitrary host/plugin callback side effects cannot be rolled back. The Web and simulated runtimes use the same public semantics without introducing another value store or persisting History.