Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): add ScrubberField numeric control

Josh Corbett7d54689d1c43
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 7361441384..a1ee79a9de 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -185,6 +185,9 @@
"saturationValue": "Saturation and value",
"saturationValueText": "Saturation {{saturation}}%, value {{value}}%"
},
+ "scrubber": {
+ "editValue": "Edit {{label}}"
+ },
"configure": "Configure",
"copy": "Copy",
"crop": "Crop",
diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx
new file mode 100644
index 0000000000..c5c7145ad5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx
@@ -0,0 +1,380 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { ScrubberField, type ScrubberFieldProps } from './ScrubberField';
+
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: { en: { translation: { common: { scrubber: { editValue: 'Edit {{label}}' } } } } },
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+const TRACK_INSET_PX = 10;
+const HOST_WIDTH_PX = 400;
+
+const mount = async (props: Partial<ScrubberFieldProps> = {}) => {
+ const onChange = vi.fn();
+
+ host = document.createElement('div');
+ host.style.width = `${HOST_WIDTH_PX}px`;
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <ScrubberField label="Steps" max={100} min={0} step={1} value={30} onChange={onChange} {...props} />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ const frame = host.querySelector<HTMLDivElement>('[data-scope="scrubber"]');
+ const slider = host.querySelector<HTMLDivElement>('[role="slider"]');
+
+ if (!frame || !slider) {
+ throw new Error('ScrubberField did not render');
+ }
+
+ return { frame, onChange, slider };
+};
+
+/** Client X for a fraction of the track, which is inset from the frame edges. */
+const trackX = (frame: HTMLElement, fraction: number): number => {
+ const rect = frame.getBoundingClientRect();
+
+ return rect.left + TRACK_INSET_PX + fraction * (rect.width - TRACK_INSET_PX * 2);
+};
+
+const pointer = (
+ target: EventTarget,
+ type: 'pointercancel' | 'pointerdown' | 'pointermove' | 'pointerup',
+ init: PointerEventInit
+) => act(() => target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, ...init })));
+
+const valueButton = () => host?.querySelector<HTMLButtonElement>('button[data-part="value"]') ?? null;
+const editor = () => host?.querySelector<HTMLInputElement>('input[data-part="value"]') ?? null;
+
+describe('ScrubberField', () => {
+ it('exposes a labelled slider with the formatted value as its text', async () => {
+ const { slider } = await mount({ formatValue: (value) => `${value}%` });
+ const label = host?.querySelector(`#${CSS.escape(slider.getAttribute('aria-labelledby') ?? '')}`);
+
+ expect(label?.textContent).toBe('Steps');
+ expect(slider.getAttribute('aria-valuenow')).toBe('30');
+ expect(slider.getAttribute('aria-valuetext')).toBe('30%');
+ expect(valueButton()?.textContent).toBe('30%');
+ expect(valueButton()?.getAttribute('aria-label')).toBe('Edit Steps');
+ });
+
+ it('jumps to the pressed position, then follows the drag snapped to the step', async () => {
+ const { frame, onChange } = await mount({ step: 5 });
+
+ await pointer(frame, 'pointerdown', { clientX: trackX(frame, 0.5) });
+
+ expect(onChange).toHaveBeenLastCalledWith(50);
+ expect(frame.hasAttribute('data-dragging')).toBe(true);
+
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.73) });
+
+ expect(onChange).toHaveBeenLastCalledWith(75);
+
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 2) });
+
+ expect(onChange).toHaveBeenLastCalledWith(100);
+
+ await pointer(window, 'pointerup', { clientX: trackX(frame, 2) });
+
+ expect(frame.hasAttribute('data-dragging')).toBe(false);
+
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0) });
+
+ expect(onChange).toHaveBeenLastCalledWith(100);
+ });
+
+ it('scrubs relative to the current value at a tenth of the sensitivity while Shift is held', async () => {
+ const { frame, onChange } = await mount();
+
+ await pointer(frame, 'pointerdown', { clientX: trackX(frame, 0.9), shiftKey: true });
+
+ expect(onChange).not.toHaveBeenCalled();
+
+ // A full-track sweep in fine mode covers a tenth of the range.
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.4), shiftKey: true });
+
+ expect(onChange).toHaveBeenLastCalledWith(25);
+ await pointer(window, 'pointerup', { clientX: trackX(frame, 0.4) });
+ });
+
+ it('snaps to the nearest stop while Alt is held', async () => {
+ const { frame, onChange } = await mount({ marks: [0, 20, 50, 100] });
+
+ await pointer(frame, 'pointerdown', { altKey: true, clientX: trackX(frame, 0.62) });
+
+ expect(onChange).toHaveBeenLastCalledWith(50);
+
+ await pointer(window, 'pointermove', { altKey: true, clientX: trackX(frame, 0.8) });
+
+ expect(onChange).toHaveBeenLastCalledWith(100);
+ await pointer(window, 'pointerup', { clientX: trackX(frame, 0.8) });
+ });
+
+ it('ignores the value region and secondary buttons when scrubbing', async () => {
+ const { frame, onChange } = await mount();
+ const button = valueButton();
+
+ await pointer(frame, 'pointerdown', { button: 2, clientX: trackX(frame, 0.1) });
+
+ if (button) {
+ await pointer(button, 'pointerdown', { clientX: trackX(frame, 0.1) });
+ }
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(frame.hasAttribute('data-dragging')).toBe(false);
+ });
+
+ it('steps from the keyboard, ×10 with Shift or Page keys, and clamps typed-range bounds', async () => {
+ const { onChange, slider } = await mount({ inputMax: 1000, step: 0.5, value: 99.5 });
+
+ await act(async () => {
+ slider.focus();
+ await userEvent.keyboard('{ArrowRight}');
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith(100);
+
+ await act(() => userEvent.keyboard('{Shift>}{ArrowUp}{/Shift}'));
+
+ expect(onChange).toHaveBeenLastCalledWith(104.5);
+
+ await act(() => userEvent.keyboard('{PageDown}'));
+
+ expect(onChange).toHaveBeenLastCalledWith(94.5);
+
+ await act(() => userEvent.keyboard('{Home}'));
+
+ expect(onChange).toHaveBeenLastCalledWith(0);
+
+ await act(() => userEvent.keyboard('{End}'));
+
+ expect(onChange).toHaveBeenLastCalledWith(100);
+ });
+
+ it('opens the editor from the value button, commits on Enter, and returns focus to the slider', async () => {
+ const { onChange, slider } = await mount({ inputMax: 500 });
+
+ await act(() => {
+ valueButton()?.click();
+ });
+
+ const input = editor();
+
+ expect(document.activeElement).toBe(input);
+ expect(input?.value).toBe('30');
+ expect(valueButton()).toBeNull();
+ expect(host?.querySelector('[data-part="label"]')?.checkVisibility()).toBe(true);
+
+ await act(() => userEvent.keyboard('250{Enter}'));
+
+ expect(onChange).toHaveBeenLastCalledWith(250);
+ expect(editor()).toBeNull();
+ expect(document.activeElement).toBe(slider);
+ });
+
+ it('discards the draft on Escape and ignores unparseable input', async () => {
+ const { onChange, slider } = await mount();
+
+ await act(async () => {
+ slider.focus();
+ await userEvent.keyboard('{Enter}');
+ });
+ await act(() => userEvent.keyboard('77{Escape}'));
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(editor()).toBeNull();
+ expect(document.activeElement).toBe(slider);
+
+ await act(() => userEvent.keyboard('{Enter}'));
+ await act(() => userEvent.keyboard('abc{Enter}'));
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('starts typing from a digit key and commits on blur, clamped to the typed range', async () => {
+ const { onChange, slider } = await mount({ inputMax: 150 });
+
+ await act(async () => {
+ slider.focus();
+ await userEvent.keyboard('9');
+ });
+
+ expect(editor()?.value).toBe('9');
+
+ await act(() => userEvent.keyboard('99'));
+ await act(() => {
+ editor()?.blur();
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith(150);
+ expect(editor()).toBeNull();
+ });
+
+ it('restores the default on double-click or Backspace, and only when one is given', async () => {
+ const { frame, onChange, slider } = await mount({ defaultValue: 20 });
+
+ await act(() => frame.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, clientX: trackX(frame, 0.5) })));
+
+ expect(onChange).toHaveBeenLastCalledWith(20);
+
+ await act(async () => {
+ slider.focus();
+ await userEvent.keyboard('{Backspace}');
+ });
+
+ expect(onChange).toHaveBeenCalledTimes(2);
+ expect(onChange).toHaveBeenLastCalledWith(20);
+
+ await act(() => root?.unmount());
+ host?.remove();
+
+ const noDefault = await mount();
+
+ await act(() =>
+ noDefault.frame.dispatchEvent(
+ new MouseEvent('dblclick', { bubbles: true, clientX: trackX(noDefault.frame, 0.5) })
+ )
+ );
+
+ expect(noDefault.onChange).not.toHaveBeenCalled();
+ });
+
+ it('marks stops as under, over, or at the value, adds the default, and skips the implied end stops', async () => {
+ await mount({ defaultValue: 30, marks: [0, 10, 30, 60, 100], value: 30 });
+
+ const states = [...(host?.querySelectorAll('[data-part="mark"]') ?? [])].map((mark) =>
+ mark.getAttribute('data-state')
+ );
+
+ expect(states).toEqual(['over-value', 'at-value', 'under-value']);
+ });
+
+ it('keeps the slider range valid around a typed value beyond the track', async () => {
+ const { slider } = await mount({ inputMax: 1000, value: 150 });
+
+ expect(slider.getAttribute('aria-valuenow')).toBe('150');
+ expect(slider.getAttribute('aria-valuemax')).toBe('150');
+ const thumb = host?.querySelector<HTMLElement>('[data-part="thumb"]')?.getBoundingClientRect();
+ const frame = host?.querySelector('[data-scope="scrubber"]')?.getBoundingClientRect();
+
+ // Clamped to the track end rather than drawn past the frame (±1px for the frame border).
+ expect(
+ thumb && frame ? Math.abs(frame.right - (thumb.left + thumb.width / 2) - TRACK_INSET_PX) : NaN
+ ).toBeLessThanOrEqual(1);
+ });
+
+ it('stays relative once Shift has been pressed mid-drag, in both directions', async () => {
+ const { frame, onChange } = await mount();
+
+ await pointer(frame, 'pointerdown', { clientX: trackX(frame, 0.5) });
+
+ expect(onChange).toHaveBeenLastCalledWith(50);
+
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.5), shiftKey: true });
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.6), shiftKey: true });
+
+ expect(onChange).toHaveBeenLastCalledWith(51);
+
+ // Releasing Shift re-anchors at full sensitivity rather than jumping to the pointer.
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.6) });
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.7) });
+
+ expect(onChange).toHaveBeenLastCalledWith(61);
+ await pointer(window, 'pointercancel', {});
+
+ expect(frame.hasAttribute('data-dragging')).toBe(false);
+ });
+
+ it('lets a touch pan the panel until it moves sideways', async () => {
+ const { frame, onChange } = await mount();
+
+ await pointer(frame, 'pointerdown', { clientX: trackX(frame, 0.5), pointerType: 'touch' });
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.5) + 4, pointerType: 'touch' });
+
+ expect(onChange).not.toHaveBeenCalled();
+
+ await pointer(window, 'pointermove', { clientX: trackX(frame, 0.7), pointerType: 'touch' });
+
+ expect(onChange).toHaveBeenLastCalledWith(70);
+ await pointer(window, 'pointerup', { pointerType: 'touch' });
+ });
+
+ it('keeps one tab stop per field', async () => {
+ await mount();
+
+ expect(valueButton()?.getAttribute('tabindex')).toBe('-1');
+ });
+
+ it('hides the stops that would sit under the label or the value', async () => {
+ // Label "Steps" spans roughly the first 15% of a 400px frame; the value the last ~10%.
+ await mount({ marks: [3, 50, 97], value: 50 });
+ await act(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ })
+ );
+
+ const hidden = [...(host?.querySelectorAll('[data-part="mark"]') ?? [])].map((mark) =>
+ mark.hasAttribute('data-hidden')
+ );
+
+ expect(hidden).toEqual([true, false, true]);
+ });
+
+ it('does nothing while disabled', async () => {
+ const { frame, onChange, slider } = await mount({ defaultValue: 10, disabled: true });
+
+ await pointer(frame, 'pointerdown', { clientX: trackX(frame, 0.5) });
+ await act(() => frame.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
+ await act(async () => {
+ slider.focus();
+ await userEvent.keyboard('{ArrowRight}');
+ });
+ await act(() => {
+ valueButton()?.click();
+ });
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(editor()).toBeNull();
+ expect(slider.getAttribute('tabindex')).toBe('-1');
+ expect(valueButton()?.disabled).toBe(true);
+ });
+
+ it('describes the slider with the error line and flags the frame invalid', async () => {
+ const { frame, slider } = await mount({ error: 'Too high', helpText: 'Ignored while erroring' });
+ const described = host?.querySelector(`#${CSS.escape(slider.getAttribute('aria-describedby') ?? '')}`);
+
+ expect(described?.textContent).toBe('Too high');
+ expect(described?.getAttribute('role')).toBe('alert');
+ expect(frame.hasAttribute('data-invalid')).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx
new file mode 100644
index 0000000000..7b04acbd8c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx
@@ -0,0 +1,620 @@
+import type { StackProps } from '@chakra-ui/react';
+import type { FeatureHintId } from '@platform/ui/hints';
+import type {
+ ChangeEvent,
+ KeyboardEvent,
+ PointerEvent as ReactPointerEvent,
+ MouseEvent as ReactMouseEvent,
+} from 'react';
+
+import { Box, chakra, Stack, Text } from '@chakra-ui/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { FeatureHint } from '@platform/ui/hints';
+import { fieldLabelRecipe, scrubberInteraction } from '@theme/recipes';
+import { useCallback, useId, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/** Track inset from the frame edge; the text padding clears it so the thumb never crosses a glyph. */
+const TRACK_INSET_PX = 10;
+/** Shift-drag moves the value this fraction of the pointer's track distance. */
+const FINE_DRAG_RATIO = 0.1;
+/** Shift/PageUp/PageDown step multiplier. */
+const COARSE_STEP_MULTIPLIER = 10;
+/** Marks land as `at-value` when within this fraction of a step. */
+const MARK_EPSILON_RATIO = 1e-6;
+/** Clearance between a stop and the label or value text before the stop hides. */
+const TEXT_CLEARANCE_PX = 6;
+/** A touch must travel this far horizontally before it scrubs; until then the panel may pan. */
+const TOUCH_INTENT_PX = 8;
+
+type ScrubberMarkState = 'at-value' | 'over-value' | 'under-value';
+
+/** Where the label ends and the value begins, in px from the frame's left edge. */
+type TextExtents = { labelEnd: number; valueStart: number; width: number };
+
+type OwnProps = {
+ label: string;
+ value: number;
+ min: number;
+ max: number;
+ step: number;
+ /** Stops along the track; Alt-drag snaps to them. `defaultValue` is always a stop; stops at `min`/`max` are implied by the track ends and not drawn. */
+ marks?: number[];
+ /** Looser clamps for typed and keyboard values (the track bounds apply to scrubbing). */
+ inputMin?: number;
+ inputMax?: number;
+ /** Double-click or Backspace/Delete restores this value. No reset without it. */
+ defaultValue?: number;
+ disabled?: boolean;
+ hint?: FeatureHintId;
+ /** Validation error, shown in place of `helpText`; also marks the field invalid. */
+ error?: string | null;
+ helpText?: string;
+ /** Formats the displayed value and its `aria-valuetext`; typing always edits the raw number. */
+ formatValue?: (value: number) => string;
+ /** Fires per step of a gesture. A drag keeps the handler it started with, so patch-style handlers only. */
+ onChange: (value: number) => void;
+};
+
+export type ScrubberFieldProps = OwnProps & Omit<StackProps, keyof OwnProps | 'children' | 'defaultValue' | 'onChange'>;
+
+const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
+
+const countDecimals = (value: number): number => {
+ const text = String(value);
+ const dot = text.indexOf('.');
+
+ return dot === -1 ? 0 : text.length - dot - 1;
+};
+
+const roundTo = (value: number, decimals: number): number => Number(value.toFixed(decimals));
+
+const nearestMark = (raw: number, marks: readonly number[]): number =>
+ marks.reduce((best, mark) => (Math.abs(mark - raw) < Math.abs(best - raw) ? mark : best));
+
+const isValueTarget = (target: EventTarget | null): boolean =>
+ target instanceof Element && target.closest('[data-part="value"]') !== null;
+
+const ROOT_CSS = {
+ ...scrubberInteraction,
+ alignItems: 'center',
+ borderColor: 'border',
+ borderRadius: 'control',
+ borderWidth: '1px',
+ cursor: 'ew-resize',
+ display: 'flex',
+ h: '7',
+ minW: '0',
+ overflow: 'hidden',
+ position: 'relative',
+ textStyle: 'xs',
+ touchAction: 'pan-y',
+ userSelect: 'none',
+ w: 'full',
+ _disabled: { cursor: 'not-allowed', opacity: 0.5 },
+ '&[data-dragging]': { borderColor: 'border.emphasized' },
+ '& [data-part="fill"]': {
+ bg: 'bg.emphasized',
+ insetBlock: 0,
+ insetInlineStart: 0,
+ pointerEvents: 'none',
+ position: 'absolute',
+ transitionDuration: 'var(--wb-motion-duration-fast)',
+ transitionProperty: 'width',
+ },
+ // Stops share the centerline with the text; one under a glyph hides rather than colliding.
+ '& [data-part="mark"]': {
+ borderRadius: 'full',
+ boxSize: '5px',
+ pointerEvents: 'none',
+ position: 'absolute',
+ top: '50%',
+ transform: 'translate(-50%, -50%)',
+ transitionDuration: 'var(--wb-motion-duration-fast)',
+ transitionProperty: 'opacity',
+ '&[data-hidden]': { opacity: 0 },
+ '&[data-state="under-value"]': { borderColor: 'border.emphasized', borderWidth: '1px' },
+ '&[data-state="over-value"]': { bg: 'border.emphasized' },
+ '&[data-state="at-value"]': { bg: 'accent.solid' },
+ },
+ '& [data-part="thumb"]': {
+ bg: 'fg.muted',
+ borderRadius: 'full',
+ h: '3.5',
+ pointerEvents: 'none',
+ position: 'absolute',
+ top: '50%',
+ transform: 'translate(-50%, -50%)',
+ transitionDuration: 'var(--wb-motion-duration-fast)',
+ transitionProperty: 'left, background',
+ w: '2px',
+ },
+ '&:hover [data-part="thumb"]': { bg: 'fg' },
+ '&[data-dragging] [data-part="thumb"], &:has([data-part="slider"]:focus-visible) [data-part="thumb"]': {
+ bg: 'accent.solid',
+ },
+ '&[data-dragging] [data-part="fill"], &[data-dragging] [data-part="thumb"]': { transitionProperty: 'none' },
+ '& [data-part="slider"]': { inset: 0, outline: 'none', position: 'absolute' },
+ '& [data-part="label"]': {
+ ...fieldLabelRecipe.base,
+ flexShrink: 1,
+ minW: '0',
+ overflow: 'hidden',
+ ps: '3',
+ position: 'relative',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ '& [data-part="value"]': {
+ alignSelf: 'stretch',
+ appearance: 'none',
+ bg: 'transparent',
+ border: 0,
+ color: 'fg',
+ cursor: 'text',
+ flexShrink: 0,
+ font: 'inherit',
+ fontVariantNumeric: 'tabular-nums',
+ marginInlineStart: 'auto',
+ minW: '0',
+ outline: 'none',
+ p: 0,
+ pe: '3',
+ position: 'relative',
+ ps: '2',
+ textAlign: 'end',
+ whiteSpace: 'nowrap',
+ },
+ '& input[data-part="value"]': { flex: 1, userSelect: 'text', w: 'full' },
+};
+
+const readTextExtents = (root: HTMLElement): TextExtents | null => {
+ const label = root.querySelector('[data-part="label"]');
+ const value = root.querySelector('[data-part="value"]');
+
+ if (!label || !value) {
+ return null;
+ }
+
+ const rootRect = root.getBoundingClientRect();
+
+ return {
+ labelEnd: label.getBoundingClientRect().right - rootRect.left,
+ valueStart: value.getBoundingClientRect().left - rootRect.left,
+ width: rootRect.width,
+ };
+};
+
+const isSameExtents = (a: TextExtents | null, b: TextExtents): boolean =>
+ a !== null && a.labelEnd === b.labelEnd && a.valueStart === b.valueStart && a.width === b.width;
+
+/**
+ * One-row numeric parameter: label left, value right, the whole frame is the
+ * track. Pointer down anywhere but the value scrubs (Shift: fine, Alt: stops
+ * only); the value is a button that swaps in a text editor; arrows step
+ * (Shift/PageUp/PageDown: ×10, Home/End: bounds); double-click or
+ * Backspace/Delete restores `defaultValue`. Owns its label, hint, and help or
+ * error line, so it replaces a `Field` + slider pairing outright. Debouncing
+ * stays with the caller.
+ */
+export const ScrubberField = ({
+ defaultValue,
+ disabled = false,
+ error,
+ formatValue,
+ helpText,
+ hint,
+ inputMax,
+ inputMin,
+ label,
+ marks,
+ max,
+ min,
+ onChange,
+ step,
+ value,
+ ...stackProps
+}: ScrubberFieldProps) => {
+ const { t } = useTranslation();
+ const id = useId();
+ const labelId = `${id}-label`;
+ const messageId = `${id}-message`;
+ const sliderRef = useRef<HTMLDivElement>(null);
+ const pointerSessionRef = useRef<AbortController | null>(null);
+ // `finished` guards the editor's blur, which fires while focus returns to the slider.
+ const editSessionRef = useRef<{ finished: boolean } | null>(null);
+ const [edit, setEdit] = useState<{ draft: string; selectAll: boolean } | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const [textExtents, setTextExtents] = useState<TextExtents | null>(null);
+
+ useMountEffect(() => () => pointerSessionRef.current?.abort());
+
+ // Stops hide under the text, so the label's and value's extents are tracked
+ // as they resize (value digits, localized labels, the editor swapping in).
+ const measureText = useCallback((root: HTMLElement) => {
+ const next = readTextExtents(root);
+
+ if (next) {
+ setTextExtents((current) => (isSameExtents(current, next) ? current : next));
+ }
+ }, []);
+ const observeText = useCallback(
+ (element: HTMLElement | null) => {
+ const root = element?.closest<HTMLElement>('[data-scope="scrubber"]');
+
+ if (!element || !root) {
+ return undefined;
+ }
+
+ const observer = new ResizeObserver(() => measureText(root));
+
+ observer.observe(element);
+
+ return () => observer.disconnect();
+ },
+ [measureText]
+ );
+
+ const range = max - min;
+ const decimals = Math.max(countDecimals(step), countDecimals(min));
+ const typedMin = inputMin ?? min;
+ const typedMax = inputMax ?? max;
+ const snapToStep = useCallback(
+ (raw: number): number => clamp(roundTo(min + Math.round((raw - min) / step) * step, decimals), min, max),
+ [decimals, max, min, step]
+ );
+ const fractionOf = useCallback(
+ (target: number): number => (range > 0 ? clamp((target - min) / range, 0, 1) : 0),
+ [min, range]
+ );
+ const trackPosition = (fraction: number): string =>
+ `calc(${TRACK_INSET_PX}px + ${fraction} * (100% - ${TRACK_INSET_PX * 2}px))`;
+ const isUnderText = (fraction: number): boolean => {
+ if (!textExtents) {
+ return true;
+ }
+
+ const x = TRACK_INSET_PX + fraction * (textExtents.width - TRACK_INSET_PX * 2);
+
+ return x < textExtents.labelEnd + TEXT_CLEARANCE_PX || x > textExtents.valueStart - TEXT_CLEARANCE_PX;
+ };
+ const thumbPosition = trackPosition(fractionOf(value));
+ const formatted = formatValue ? formatValue(value) : String(value);
+ const markEpsilon = step * MARK_EPSILON_RATIO;
+ const markValues = useMemo(() => {
+ const stops = defaultValue === undefined ? marks : [...(marks ?? []), defaultValue];
+
+ return stops ? [...new Set(stops.filter((mark) => mark >= min && mark <= max))] : undefined;
+ }, [defaultValue, marks, max, min]);
+ const markEntries = useMemo(
+ () =>
+ markValues
+ ?.filter((mark) => mark > min && mark < max)
+ .map((mark) => {
+ const state: ScrubberMarkState =
+ Math.abs(mark - value) <= markEpsilon ? 'at-value' : mark < value ? 'over-value' : 'under-value';
+
+ return { mark, state };
+ }),
+ [markEpsilon, markValues, max, min, value]
+ );
+
+ const emit = useCallback(
+ (next: number) => {
+ if (next !== value) {
+ onChange(next);
+ }
+ },
+ [onChange, value]
+ );
+
+ const startEditing = useCallback((draft: string, selectAll: boolean) => {
+ editSessionRef.current = { finished: false };
+ setEdit({ draft, selectAll });
+ }, []);
+
+ const finishEditing = useCallback(
+ (commit: boolean) => {
+ const session = editSessionRef.current;
+
+ if (!session || session.finished) {
+ return;
+ }
+
+ session.finished = true;
+ setEdit(null);
+ sliderRef.current?.focus({ preventScroll: true });
+
+ if (commit && edit) {
+ const parsed = Number(edit.draft.trim());
+
+ if (edit.draft.trim() !== '' && Number.isFinite(parsed)) {
+ emit(clamp(parsed, typedMin, typedMax));
+ }
+ }
+ },
+ [edit, emit, typedMax, typedMin]
+ );
+
+ const handlePointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (disabled || event.button !== 0 || edit || isValueTarget(event.target)) {
+ return;
+ }
+
+ event.preventDefault();
+ sliderRef.current?.focus({ preventScroll: true });
+ pointerSessionRef.current?.abort();
+
+ const root = event.currentTarget;
+ const rect = root.getBoundingClientRect();
+ const trackLeft = rect.left + TRACK_INSET_PX;
+ const trackWidth = Math.max(1, rect.width - TRACK_INSET_PX * 2);
+ const valueAt = (clientX: number): number => min + clamp((clientX - trackLeft) / trackWidth, 0, 1) * range;
+ const session = new AbortController();
+ let latest = value;
+ let isPendingTouch = event.pointerType === 'touch';
+ // Once Shift enters a gesture it stays relative (re-anchored on each ratio
+ // change), so neither pressing nor releasing Shift mid-drag jumps.
+ let anchor: { clientX: number; ratio: number; value: number } | null = event.shiftKey
+ ? { clientX: event.clientX, ratio: FINE_DRAG_RATIO, value }
+ : null;
+
+ pointerSessionRef.current = session;
+ setIsDragging(true);
+
+ // Keeps hover states elsewhere quiet and the resize cursor stable while
+ // the pointer roams. Throws for an already-released pointer; the window
+ // listeners still carry the gesture.
+ try {
+ root.setPointerCapture(event.pointerId);
+ } catch {
+ // No capture available — fall through to the window listeners.
+ }
+
+ const resolve = (pointer: { altKey: boolean; clientX: number; shiftKey: boolean }): number => {
+ let raw: number;
+
+ if (pointer.shiftKey || anchor) {
+ const ratio = pointer.shiftKey ? FINE_DRAG_RATIO : 1;
+
+ if (anchor?.ratio !== ratio) {
+ anchor = { clientX: pointer.clientX, ratio, value: latest };
+ }
+
+ raw = anchor.value + (valueAt(pointer.clientX) - valueAt(anchor.clientX)) * ratio;
+ } else {
+ raw = valueAt(pointer.clientX);
+ }
+
+ return pointer.altKey && markValues?.length ? nearestMark(raw, markValues) : snapToStep(raw);
+ };
+ const apply = (pointer: { altKey: boolean; clientX: number; shiftKey: boolean }) => {
+ if (isPendingTouch) {
+ if (Math.abs(pointer.clientX - event.clientX) < TOUCH_INTENT_PX) {
+ return;
+ }
+
+ isPendingTouch = false;
+ }
+
+ const next = resolve(pointer);
+
+ if (next !== latest) {
+ latest = next;
+ onChange(next);
+ }
+ };
+ const end = () => {
+ session.abort();
+ pointerSessionRef.current = null;
+ setIsDragging(false);
+ };
+
+ // A fine gesture starts from the current value, never from the press position.
+ if (!event.shiftKey) {
+ apply(event);
+ }
+
+ window.addEventListener('pointermove', apply, { signal: session.signal });
+ window.addEventListener('pointerup', end, { signal: session.signal });
+ window.addEventListener('pointercancel', end, { signal: session.signal });
+ },
+ [disabled, edit, markValues, min, onChange, range, snapToStep, value]
+ );
+
+ const handleDoubleClick = useCallback(
+ (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (!disabled && defaultValue !== undefined && !isValueTarget(event.target)) {
+ emit(defaultValue);
+ }
+ },
+ [defaultValue, disabled, emit]
+ );
+
+ const handleSliderKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (disabled || event.ctrlKey || event.metaKey) {
+ return;
+ }
+
+ const coarse = step * COARSE_STEP_MULTIPLIER;
+ const stepBy = event.shiftKey ? coarse : step;
+ let next: number | undefined;
+
+ switch (event.key) {
+ case 'ArrowRight':
+ case 'ArrowUp':
+ next = value + stepBy;
+ break;
+ case 'ArrowLeft':
+ case 'ArrowDown':
+ next = value - stepBy;
+ break;
+ case 'PageUp':
+ next = value + coarse;
+ break;
+ case 'PageDown':
+ next = value - coarse;
+ break;
+ case 'Home':
+ next = min;
+ break;
+ case 'End':
+ next = max;
+ break;
+ case 'Enter':
+ case 'F2':
+ event.preventDefault();
+ startEditing(String(value), true);
+ return;
+ case 'Backspace':
+ case 'Delete':
+ if (defaultValue !== undefined) {
+ event.preventDefault();
+ emit(defaultValue);
+ }
+ return;
+ default:
+ // A digit (or sign/point) starts typing straight away, like a spreadsheet cell.
+ if (!event.altKey && /^[\d.-]$/.test(event.key)) {
+ event.preventDefault();
+ startEditing(event.key, false);
+ }
+ return;
+ }
+
+ event.preventDefault();
+ emit(clamp(roundTo(next, decimals), typedMin, typedMax));
+ },
+ [decimals, defaultValue, disabled, emit, max, min, startEditing, step, typedMax, typedMin, value]
+ );
+
+ const handleValueClick = useCallback(() => {
+ if (!disabled) {
+ startEditing(String(value), true);
+ }
+ }, [disabled, startEditing, value]);
+
+ const handleInputChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
+ const draft = event.target.value;
+
+ setEdit((current) => (current ? { ...current, draft } : current));
+ }, []);
+ // Focus on attach: the editor mounts in response to the user's own click or keypress.
+ const selectAll = edit?.selectAll ?? false;
+ const attachEditor = useCallback(
+ (input: HTMLInputElement | null) => {
+ if (input) {
+ input.focus();
+
+ if (selectAll) {
+ input.select();
+ }
+ }
+
+ return observeText(input);
+ },
+ [observeText, selectAll]
+ );
+ const handleInputBlur = useCallback(() => finishEditing(true), [finishEditing]);
+ const handleInputKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ finishEditing(true);
+ } else if (event.key === 'Escape') {
+ event.preventDefault();
+ finishEditing(false);
+ }
+ },
+ [finishEditing]
+ );
+
+ const message = error ?? helpText;
+ const labelContent = hint ? (
+ <FeatureHint hint={hint}>
+ <chakra.span>{label}</chakra.span>
+ </FeatureHint>
+ ) : (
+ label
+ );
+
+ return (
+ <Stack gap="1.5" minW="0" w="full" {...stackProps}>
+ <Box
+ ref={observeText}
+ css={ROOT_CSS}
+ data-disabled={disabled ? '' : undefined}
+ data-dragging={isDragging ? '' : undefined}
+ data-editing={edit ? '' : undefined}
+ data-invalid={error ? '' : undefined}
+ data-scope="scrubber"
+ onDoubleClick={handleDoubleClick}
+ onPointerDown={handlePointerDown}
+ >
+ <div data-part="fill" style={{ width: thumbPosition }} />
+ {markEntries?.map(({ mark, state }) => (
+ <div
+ key={mark}
+ data-hidden={isUnderText(fractionOf(mark)) ? '' : undefined}
+ data-part="mark"
+ data-state={state}
+ style={{ left: trackPosition(fractionOf(mark)) }}
+ />
+ ))}
+ <div data-part="thumb" style={{ left: thumbPosition }} />
+ <div
+ ref={sliderRef}
+ aria-describedby={message ? messageId : undefined}
+ aria-disabled={disabled || undefined}
+ aria-invalid={error ? true : undefined}
+ aria-labelledby={labelId}
+ aria-orientation="horizontal"
+ aria-valuemax={Math.max(max, value)}
+ aria-valuemin={Math.min(min, value)}
+ aria-valuenow={value}
+ aria-valuetext={formatted}
+ data-part="slider"
+ role="slider"
+ tabIndex={disabled ? -1 : 0}
+ onKeyDown={handleSliderKeyDown}
+ />
+ <span ref={observeText} data-part="label" id={labelId}>
+ {labelContent}
+ </span>
+ {edit ? (
+ <input
+ ref={attachEditor}
+ aria-label={label}
+ data-part="value"
+ inputMode="decimal"
+ type="text"
+ value={edit.draft}
+ onBlur={handleInputBlur}
+ onChange={handleInputChange}
+ onKeyDown={handleInputKeyDown}
+ />
+ ) : (
+ <button
+ ref={observeText}
+ aria-label={t('common.scrubber.editValue', { label })}
+ data-part="value"
+ disabled={disabled}
+ // One tab stop per field: the slider opens the editor with Enter or a digit.
+ tabIndex={-1}
+ type="button"
+ onClick={handleValueClick}
+ >
+ {formatted}
+ </button>
+ )}
+ </Box>
+ {message ? (
+ <Text color={error ? 'fg.error' : 'fg.muted'} fontSize="2xs" id={messageId} role={error ? 'alert' : undefined}>
+ {message}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
index 0a07861162..446bcc13f2 100644
--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
@@ -355,6 +355,21 @@ export const inputShellInteraction = {
_hover: { ...formControlInteraction._hover, _focusWithin: formControlFocused },
};
+/**
+ * `formControlInteraction` for `platform/ui/ScrubberField`: the frame is the
+ * pointer target and clicks focus an inner layer programmatically, so the
+ * accent border keys on keyboard focus (`:focus-visible`) or the inline editor,
+ * never on a plain click, which shows the dragging state instead.
+ */
+export const scrubberInteraction = {
+ ...formControlInteraction,
+ '&:has(:focus-visible), &[data-editing]': formControlFocused,
+ _hover: {
+ ...formControlInteraction._hover,
+ '&:has(:focus-visible), &[data-editing]': formControlFocused,
+ },
+};
+
export const inputRecipe = defineRecipe({
...chakraRecipes.input,
variants: {