///
import { Cell, Default, handler, recipe, str } from "commontools";
interface BoundedCounterArgs {
value: Default;
min: Default;
max: Default;
}
const clampValue = handler(
(
event: { amount?: number } | undefined,
context: { value: Cell; min: Cell; max: Cell },
) => {
const amount = typeof event?.amount === "number" ? event.amount : 1;
const minValue = context.min.get() ?? 0;
const maxValue = context.max.get() ?? minValue;
const current = context.value.get() ?? minValue;
const next = Math.min(Math.max(current + amount, minValue), maxValue);
context.value.set(next);
},
);
export const boundedCounter = recipe(
"Bounded Counter",
({ value, min, max }) => {
const label = str`Value ${value} (min ${min}, max ${max})`;
return {
value,
bounds: { min, max },
label,
adjust: clampValue({ value, min, max }),
};
},
);