import { useEffect, useId, useState, type InputHTMLAttributes } from "react";
import { num } from "./code";
import type { Control, OptionValue, Options, Point, Rect } from "./types";
interface ControlsProps {
controls: Control[];
values: Options;
/** `live` changes (slider drags) are debounced by the playground. */
onChange(key: string, value: OptionValue, live?: boolean): void;
/** Start picking a point or region on the image. */
onPick(key: string): void;
picking: string | null;
}
export function Controls({ controls, values, onChange, onPick, picking }: ControlsProps) {
const visible = controls.filter((control) => !control.when || control.when(values));
if (!visible.length) {
return
This method has no options.
;
}
return (
{visible.map((control) => (
onChange(control.key, value, live)}
onPick={() => onPick(control.key)}
picking={picking === control.key}
/>
))}
);
}
interface RowProps {
control: Control;
value: OptionValue | undefined;
onChange(value: OptionValue, live?: boolean): void;
onPick(): void;
picking: boolean;
}
function ControlRow({ control, value, onChange, onPick, picking }: RowProps) {
const id = useId();
const label = control.label ?? control.key;
switch (control.type) {
case "slider": {
const n = Number(value);
return (
{label}
onChange(Number(e.target.value), true)}
/>
{num(n)}
{control.unit}
);
}
case "number":
return (
{label}
onChange(n, true)}
/>
);
case "toggle":
return (
{label}
onChange(!value)}
>
{String(Boolean(value))}
);
case "select":
return (
{label}
onChange(e.target.value)}>
{control.options.map((option) => {
const { value: v, label: l } =
typeof option === "string" ? { value: option, label: option } : option;
return (
{l}
);
})}
);
case "color":
return (
{label}
onChange(e.target.value, true)}
/>
{String(value)}
);
case "xy": {
const point = value as Point;
const set = (patch: Partial) => onChange({ ...point, ...patch }, true);
return (
{label}
{picking ? "Click the image…" : "Pick on image"}
set({ x })} />
set({ y })} />
);
}
case "rect": {
const rect = value as Rect;
const set = (patch: Partial) => onChange({ ...rect, ...patch }, true);
return (
{label}
{picking ? "Drag on the image…" : "Drag on image"}
set({ x })} />
set({ y })} />
set({ w })} />
set({ h })} />
);
}
}
}
function NumberField({
label,
value,
onChange,
}: {
label: string;
value: number;
onChange(value: number): void;
}) {
return (
{label}
);
}
type NumberInputProps = Omit, "value" | "type"> & {
value: number;
onValue(value: number): void;
};
/** A number input that lets you type freely ("-", "") without losing the last valid value. */
function NumberInput({ value, onValue, ...props }: NumberInputProps) {
const [text, setText] = useState(String(value));
useEffect(() => {
setText((current) => (Number(current) === value ? current : String(value)));
}, [value]);
return (
{
setText(e.target.value);
if (!Number.isNaN(e.target.valueAsNumber)) onValue(e.target.valueAsNumber);
}}
/>
);
}