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.

fix(webv2): enter batch generator settings as typed and flag what cannot run

Josh Corbett3d5ab8a05448
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 94f407009e..036383e1ba 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -3515,6 +3515,7 @@
"source:src/features/workflow/ui/editor/useLasso.tsx",
"source:src/features/workflow/ui/editor/workflowViewportStore.ts",
"source:src/features/workflow/ui/fields/FieldDescriptionPopover.tsx",
+ "source:src/features/workflow/ui/fields/NumericInput.tsx",
"source:src/features/workflow/ui/fields/WorkflowFieldInput.tsx",
"source:src/features/workflow/ui/fields/mediaFieldDnd.ts",
"source:src/features/workflow/ui/graph-preview/FlowMiniMap.tsx",
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts
index e7c6f41858..43cc7d030e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts
@@ -12,6 +12,8 @@ import {
createSeededRandom,
getDefaultWorkflowGeneratorValue,
getWorkflowBatchGroupId,
+ getWorkflowGeneratorInvalidReason,
+ getWorkflowGeneratorPropertyInvalidReason,
getWorkflowGeneratorKey,
getWorkflowGeneratorVariantDefaults,
isRandomWorkflowGeneratorValue,
@@ -98,9 +100,15 @@ describe('generator values', () => {
type: 'integer_generator_arithmetic_sequence',
})
).toBeNull();
+ // Numbers are kept as entered, even off their rule; the reason check says whether they can run.
expect(
- parseWorkflowGeneratorValue('IntegerGeneratorField', { count: 0, type: 'integer_generator_arithmetic_sequence' })
- ).toBeNull();
+ parseWorkflowGeneratorValue('IntegerGeneratorField', {
+ count: 0,
+ start: null,
+ step: 1.5,
+ type: 'integer_generator_arithmetic_sequence',
+ })
+ ).toEqual({ count: 0, start: null, step: 1.5, type: 'integer_generator_arithmetic_sequence' });
expect(parseWorkflowGeneratorValue('IntegerGeneratorField', { type: 'float_generator_parse_string' })).toBeNull();
expect(parseWorkflowGeneratorValue('FloatGeneratorField', 'nope')).toBeNull();
// Optional properties recover from bad input instead.
@@ -113,6 +121,77 @@ describe('generator values', () => {
).toMatchObject({ seed: null });
});
+ it('names the first setting that keeps a readable generator from running, and yields nothing for it', () => {
+ const arithmetic = (overrides: Record<string, unknown>) =>
+ parseWorkflowGeneratorValue('IntegerGeneratorField', {
+ count: 3,
+ start: 0,
+ step: 1,
+ type: 'integer_generator_arithmetic_sequence',
+ ...overrides,
+ })!;
+ const reason = (value: WorkflowGeneratorValue) => getWorkflowGeneratorInvalidReason(value);
+
+ expect(reason(arithmetic({}))).toBeNull();
+ expect(reason(arithmetic({ start: null }))).toBe('Start is empty.');
+ expect(reason(arithmetic({ step: 1.5 }))).toBe('Step must be a whole number.');
+ expect(reason(arithmetic({ count: 0 }))).toBe('Count must be at least 1.');
+ expect(reason(arithmetic({ count: 2.5 }))).toBe('Count must be a whole number.');
+ expect(getWorkflowGeneratorPropertyInvalidReason(arithmetic({ count: 0, start: null }), 'count')).toBe(
+ 'Count must be at least 1.'
+ );
+ // Floats may be fractional; a seed is optional but must be a whole number of at least 0 when pinned.
+ expect(
+ reason(
+ parseWorkflowGeneratorValue('FloatGeneratorField', {
+ count: 2,
+ max: 1,
+ min: 0.5,
+ seed: 2.5,
+ type: 'float_generator_random_distribution_uniform',
+ })!
+ )
+ ).toBe('Seed must be a whole number.');
+ expect(
+ reason(
+ parseWorkflowGeneratorValue('FloatGeneratorField', {
+ count: 2,
+ max: 1,
+ min: 0.5,
+ seed: -1,
+ type: 'float_generator_random_distribution_uniform',
+ })!
+ )
+ ).toBe('Seed must be at least 0.');
+ expect(
+ reason(
+ parseWorkflowGeneratorValue('StringGeneratorField', {
+ count: 1001,
+ input: 'a',
+ seed: null,
+ type: 'string_generator_dynamic_prompts_random',
+ })!
+ )
+ ).toBe('Count can be at most 1000.');
+
+ // A legacy resolved override stands in for its settings, whatever they say.
+ expect(
+ reason(
+ parseWorkflowGeneratorValue('FloatGeneratorField', {
+ count: 0,
+ start: 0,
+ step: 1,
+ type: 'float_generator_arithmetic_sequence',
+ values: [4, 5],
+ })!
+ )
+ ).toBeNull();
+
+ // An off-rule generator resolves to no items rather than a broken sequence.
+ expect(resolveWorkflowGeneratorValue(arithmetic({ count: 0 }))).toEqual({ items: [], kind: 'items' });
+ expect(resolveWorkflowGeneratorValue(arithmetic({ start: null }))).toEqual({ items: [], kind: 'items' });
+ });
+
it('fingerprints a value independently of key order and spots unseeded random variants', () => {
expect(
getWorkflowGeneratorKey({ count: 2, start: 0, step: 1, type: 'integer_generator_arithmetic_sequence' })
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/batch.ts b/invokeai/frontend/webv2/src/features/workflow/core/batch.ts
index b338ed9a90..3ced8bb4c7 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/batch.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/batch.ts
@@ -70,25 +70,25 @@ export const getWorkflowBatchGroupId = (node: WorkflowInvocationNode): WorkflowB
export interface FloatGeneratorArithmeticSequence {
type: 'float_generator_arithmetic_sequence';
- start: number;
- step: number;
- count: number;
+ start: number | null;
+ step: number | null;
+ count: number | null;
values?: number[];
}
export interface FloatGeneratorLinearDistribution {
type: 'float_generator_linear_distribution';
- start: number;
- end: number;
- count: number;
+ start: number | null;
+ end: number | null;
+ count: number | null;
values?: number[];
}
export interface FloatGeneratorUniformRandom {
type: 'float_generator_random_distribution_uniform';
- min: number;
- max: number;
- count: number;
+ min: number | null;
+ max: number | null;
+ count: number | null;
seed: number | null;
values?: number[];
}
@@ -108,23 +108,23 @@ export type FloatGeneratorValue =
export interface IntegerGeneratorArithmeticSequence {
type: 'integer_generator_arithmetic_sequence';
- start: number;
- step: number;
- count: number;
+ start: number | null;
+ step: number | null;
+ count: number | null;
}
export interface IntegerGeneratorLinearDistribution {
type: 'integer_generator_linear_distribution';
- start: number;
- end: number;
- count: number;
+ start: number | null;
+ end: number | null;
+ count: number | null;
}
export interface IntegerGeneratorUniformRandom {
type: 'integer_generator_random_distribution_uniform';
- min: number;
- max: number;
- count: number;
+ min: number | null;
+ max: number | null;
+ count: number | null;
seed: number | null;
}
@@ -149,14 +149,14 @@ export interface StringGeneratorParseString {
export interface StringGeneratorDynamicPromptsRandom {
type: 'string_generator_dynamic_prompts_random';
input: string;
- count: number;
+ count: number | null;
seed: number | null;
}
export interface StringGeneratorDynamicPromptsCombinatorial {
type: 'string_generator_dynamic_prompts_combinatorial';
input: string;
- maxPrompts: number;
+ maxPrompts: number | null;
}
export type StringGeneratorValue =
@@ -294,7 +294,9 @@ export const getDefaultWorkflowGeneratorValue = (fieldTypeName: string): Workflo
const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
-/** `undefined` means the property is omitted; `null` means the stored value is unusable. */
+const UNUSABLE = Symbol('unusable');
+
+/** `undefined` means the property is omitted; `UNUSABLE` means the stored value cannot be read at all. */
const readProperty = (spec: PropertySpec, raw: unknown, fallback: unknown): unknown => {
if (raw === undefined) {
return fallback;
@@ -302,15 +304,14 @@ const readProperty = (spec: PropertySpec, raw: unknown, fallback: unknown): unkn
switch (spec) {
case 'number':
- return isFiniteNumber(raw) ? raw : null;
case 'integer':
- return Number.isInteger(raw) ? raw : null;
case 'count':
- return Number.isInteger(raw) && (raw as number) >= 1 ? raw : null;
+ // Kept as entered: `null` is a cleared setting, an off-rule number a readable one that cannot run yet.
+ return raw === null || isFiniteNumber(raw) ? raw : UNUSABLE;
case 'string':
- return typeof raw === 'string' ? raw : null;
+ return typeof raw === 'string' ? raw : UNUSABLE;
case 'seed':
- return raw === null ? null : Number.isInteger(raw) ? raw : undefined;
+ return raw === null || isFiniteNumber(raw) ? raw : undefined;
case 'category':
return raw === 'images' || raw === 'assets' ? raw : undefined;
case 'boardId':
@@ -322,7 +323,8 @@ const readProperty = (spec: PropertySpec, raw: unknown, fallback: unknown): unkn
/**
* Reads a stored generator value the way the legacy schemas did: missing properties take their defaults, a missing
- * variant is the field's first one, and a wrong-typed property makes the whole value unusable (null).
+ * variant is the field's first one, and a wrong-typed property makes the whole value unusable (null). Numbers are
+ * kept as entered; `getWorkflowGeneratorInvalidReason` says whether they can run.
*/
export const parseWorkflowGeneratorValue = (fieldTypeName: string, raw: unknown): WorkflowGeneratorValue | null => {
if (!isWorkflowGeneratorFieldTypeName(fieldTypeName) || typeof raw !== 'object' || raw === null) {
@@ -344,7 +346,7 @@ export const parseWorkflowGeneratorValue = (fieldTypeName: string, raw: unknown)
const read = readProperty(spec, source[key], defaults[key]);
// Optional properties (seed, board, override values, category) recover from bad input; required ones do not.
- if (read === null && spec !== 'seed') {
+ if (read === UNUSABLE) {
return null;
}
@@ -381,6 +383,91 @@ export const getWorkflowGeneratorKey = (value: WorkflowGeneratorValue): string =
export const isWorkflowGeneratorVariant = (type: string): type is WorkflowGeneratorVariant =>
Object.hasOwn(VARIANT_PROPERTIES, type);
+/** Dynamic prompt expansion is bounded server-side; the legacy editor capped a request at this. */
+export const WORKFLOW_DYNAMIC_PROMPTS_MAX = 1000;
+
+const PROPERTY_LABELS: Record<string, string> = {
+ count: 'Count',
+ end: 'End',
+ max: 'Max',
+ maxPrompts: 'Max prompts',
+ min: 'Min',
+ seed: 'Seed',
+ start: 'Start',
+ step: 'Step',
+};
+
+/** Why one numeric setting cannot run, or null. Text, board, and category settings always can. */
+export const getWorkflowGeneratorPropertyInvalidReason = (
+ value: WorkflowGeneratorValue,
+ key: string
+): string | null => {
+ const spec = VARIANT_PROPERTIES[value.type][key];
+
+ if (spec !== 'number' && spec !== 'integer' && spec !== 'count' && spec !== 'seed') {
+ return null;
+ }
+
+ const raw = (value as unknown as Record<string, unknown>)[key];
+ const label = PROPERTY_LABELS[key] ?? key;
+
+ if (raw === null) {
+ return spec === 'seed' ? null : `${label} is empty.`;
+ }
+
+ if (!isFiniteNumber(raw)) {
+ return `${label} is invalid.`;
+ }
+
+ if (spec === 'number') {
+ return null;
+ }
+
+ if (!Number.isInteger(raw)) {
+ return `${label} must be a whole number.`;
+ }
+
+ if (spec === 'count' && raw < 1) {
+ return `${label} must be at least 1.`;
+ }
+
+ if (spec === 'seed' && raw < 0) {
+ return `${label} must be at least 0.`;
+ }
+
+ if (
+ spec === 'count' &&
+ value.type.startsWith('string_generator_dynamic_prompts') &&
+ raw > WORKFLOW_DYNAMIC_PROMPTS_MAX
+ ) {
+ return `${label} can be at most ${WORKFLOW_DYNAMIC_PROMPTS_MAX}.`;
+ }
+
+ return null;
+};
+
+/** The first setting that keeps a readable generator from running, or null when it can. */
+export const getWorkflowGeneratorInvalidReason = (value: WorkflowGeneratorValue): string | null => {
+ // A legacy resolved override stands in for the settings, as it does when resolving.
+ if ('values' in value && value.values) {
+ return null;
+ }
+
+ for (const key of Object.keys(VARIANT_PROPERTIES[value.type])) {
+ const reason = getWorkflowGeneratorPropertyInvalidReason(value, key);
+
+ if (reason !== null) {
+ return reason;
+ }
+ }
+
+ return null;
+};
+
+/** A generator whose settings all pass `getWorkflowGeneratorInvalidReason`: numbers present, seeds still optional. */
+type Runnable<T> = T extends unknown ? { [K in keyof T]: K extends 'seed' ? T[K] : Exclude<T[K], null> } : never;
+export type RunnableWorkflowGeneratorValue = Runnable<WorkflowGeneratorValue>;
+
/**
* How many items a generator asks for, before any are built: a stored count can be arbitrarily large, and the
* queue accepts at most `WORKFLOW_BATCH_MAX_ITEMS`, so callers refuse oversized requests without materializing them.
@@ -466,15 +553,22 @@ const sequence = (count: number, at: (index: number) => number): number[] =>
/** Turns a stored generator into its items, or into the request an async source needs. */
export const resolveWorkflowGeneratorValue = (
- value: WorkflowGeneratorValue,
+ stored: WorkflowGeneratorValue,
random: () => number = Math.random
): WorkflowGeneratorResolution => {
const items = (list: WorkflowBatchItem[]): WorkflowGeneratorResolution => ({ items: list, kind: 'items' });
- if ('values' in value && value.values) {
- return items(value.values);
+ if ('values' in stored && stored.values) {
+ return items(stored.values);
}
+ // A setting that cannot run yields nothing; the field check names it.
+ if (getWorkflowGeneratorInvalidReason(stored) !== null) {
+ return items([]);
+ }
+
+ const value = stored as RunnableWorkflowGeneratorValue;
+
switch (value.type) {
case 'float_generator_arithmetic_sequence':
case 'integer_generator_arithmetic_sequence':
@@ -631,21 +725,22 @@ export const planWorkflowBatch = (
source.data.inputs.generator?.value
);
- // An unreadable generator is reported by the field check; here it only leaves the size unknown.
- const requested = value ? getWorkflowGeneratorRequestedCount(value) : null;
+ // An unreadable or off-rule generator is reported by the field check; here it only leaves the size unknown.
+ const runnable = value !== null && getWorkflowGeneratorInvalidReason(value) === null ? value : null;
+ const requested = runnable ? getWorkflowGeneratorRequestedCount(runnable) : null;
if (requested !== null && requested > WORKFLOW_BATCH_MAX_ITEMS) {
// Refused by its count alone: building the list would cost memory in every readiness pass.
oversizedGenerator = true;
- } else if (value?.type === 'image_generator_images_from_board' && value.board_id === undefined) {
+ } else if (runnable?.type === 'image_generator_images_from_board' && runnable.board_id === undefined) {
reasons.push(`Image generator "${getNodeDisplayName(source, templates)}" has no board selected.`);
- } else if (value) {
- const resolution = resolveWorkflowGeneratorValue(value, random);
+ } else if (runnable) {
+ const resolution = resolveWorkflowGeneratorValue(runnable, random);
if (resolution.kind === 'items') {
items = resolution.items;
} else {
- const key = getWorkflowGeneratorKey(value);
+ const key = getWorkflowGeneratorKey(runnable);
const resolved = generators[source.id];
if (resolved && resolved.key === key) {
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
index e136b5354f..513c93ffb2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
@@ -1029,6 +1029,15 @@ describe('batch nodes', () => {
canInvoke: true,
reasons: [],
});
+
+ // A cleared or off-rule setting is readable, so the field names it and the planner reports nothing more.
+ const cleared = build([], { count: null, start: 1, step: 1, type: 'float_generator_arithmetic_sequence' });
+
+ expect(getProjectGraphReadiness(cleared.doc, snapshot)).toEqual({
+ batch: { size: null },
+ canInvoke: false,
+ reasons: ['"float_generator" has invalid input "generator".'],
+ });
});
it("compiles the executable graph without batch or generator nodes and keeps the fed input's static value", () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index cfa3dce7da..dd79730584 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -269,6 +269,28 @@ describe('workflow field validation', () => {
expect(getWorkflowFieldInvalidReason({ isConnected: false, template: loras, value: [] })).toBe(null);
});
+ it('reports a generator setting that cannot run through the field, as the widget shows it', () => {
+ const generator = input({
+ type: { batch: false, cardinality: 'SINGLE', name: 'FloatGeneratorField' },
+ });
+ const reasonFor = (value: unknown) =>
+ getWorkflowFieldInvalidReason({ isConnected: false, template: generator, value });
+
+ expect(reasonFor({ count: 3, start: 0, step: 0.5, type: 'float_generator_arithmetic_sequence' })).toBeNull();
+ expect(reasonFor({ count: null, start: 0, step: 0.5, type: 'float_generator_arithmetic_sequence' })).toBe(
+ 'Count is empty.'
+ );
+ expect(reasonFor({ count: 3, start: 'x', type: 'float_generator_arithmetic_sequence' })).toBe('Invalid value.');
+ expect(
+ isWorkflowFieldValueValid(generator, {
+ count: 0,
+ start: 0,
+ step: 0.5,
+ type: 'float_generator_arithmetic_sequence',
+ })
+ ).toBe(false);
+ });
+
it('keeps a cleared or out-of-range LoRA weight as a readable entry that names its own reason', () => {
const loras = input({
required: false,
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index d6546d7ace..aa28f89ced 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -2,7 +2,11 @@ import { SEED_MAX } from '@platform/core/seed';
import type { FieldInputTemplate, FieldType, WorkflowFieldInstance } from './types';
-import { isWorkflowGeneratorFieldTypeName, parseWorkflowGeneratorValue } from './batch';
+import {
+ getWorkflowGeneratorInvalidReason,
+ isWorkflowGeneratorFieldTypeName,
+ parseWorkflowGeneratorValue,
+} from './batch';
export const getEffectiveWorkflowFieldDescription = (
instance: WorkflowFieldInstance | undefined,
@@ -322,7 +326,9 @@ const isColorValueValid = (value: unknown): boolean => {
export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {
if (isWorkflowGeneratorFieldTypeName(template.type.name)) {
- return parseWorkflowGeneratorValue(template.type.name, value) !== null;
+ const generator = parseWorkflowGeneratorValue(template.type.name, value);
+
+ return generator !== null && getWorkflowGeneratorInvalidReason(generator) === null;
}
if (
@@ -425,6 +431,16 @@ export const getWorkflowFieldInvalidReason = ({
return getLoraCollectionInvalidReason(toLoraFieldCollectionList(value));
}
+ if (
+ isWorkflowGeneratorFieldTypeName(template.type.name) &&
+ isDirectInputField(template) &&
+ !isEmptyOptionalValue(value)
+ ) {
+ const generator = parseWorkflowGeneratorValue(template.type.name, value);
+
+ return generator === null ? 'Invalid value.' : getWorkflowGeneratorInvalidReason(generator);
+ }
+
if (!template.required) {
return isDirectInputField(template) && !isWorkflowFieldValueValid(template, value) ? 'Invalid value.' : null;
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx
index 3a107896a0..d95f2c5f32 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx
@@ -1,15 +1,18 @@
-import type { ChangeEvent, WheelEvent } from 'react';
+import type { ChangeEvent } from 'react';
-import { Box, chakra, Checkbox, createListCollection, HStack, Input, Stack, Textarea } from '@chakra-ui/react';
+import { Box, chakra, Checkbox, createListCollection, Field, HStack, Input, Stack, Textarea } from '@chakra-ui/react';
import { galleryBoardsOptions } from '@features/gallery/queries';
import { getWorkflowGeneratorQueryOptions, type WorkflowGeneratorQueryResult } from '@features/workflow/generators';
import {
getDefaultWorkflowGeneratorValue,
+ getWorkflowGeneratorInvalidReason,
+ getWorkflowGeneratorPropertyInvalidReason,
getWorkflowGeneratorRequestedCount,
getWorkflowGeneratorVariantDefaults,
isRandomWorkflowGeneratorValue,
isWorkflowGeneratorVariant,
WORKFLOW_BATCH_MAX_ITEMS,
+ WORKFLOW_DYNAMIC_PROMPTS_MAX,
parseWorkflowGeneratorValue,
resolveWorkflowGeneratorValue,
WORKFLOW_GENERATOR_VARIANTS,
@@ -26,6 +29,8 @@ import { useTranslation } from 'react-i18next';
import type { WorkflowFieldInputProps } from './WorkflowFieldInput';
+import { NumericInput, type NumericInputTemplate } from './NumericInput';
+
const VARIANT_LABEL_KEYS: Record<WorkflowGeneratorVariant, string> = {
float_generator_arithmetic_sequence: 'nodes.arithmeticSequence',
float_generator_linear_distribution: 'nodes.linearDistribution',
@@ -41,8 +46,6 @@ const VARIANT_LABEL_KEYS: Record<WorkflowGeneratorVariant, string> = {
string_generator_parse_string: 'nodes.parseString',
};
-/** Dynamic prompt expansion is bounded server-side; the legacy editor capped the request at this. */
-const DYNAMIC_PROMPTS_MAX = 1000;
const FILE_SIZE_LIMIT = 128 * 1024;
const PREVIEW_ITEM_LIMIT = 200;
const PREVIEW_DEBOUNCE_MS = 300;
@@ -53,28 +56,16 @@ const CATEGORY_OPTIONS = [
{ labelKey: 'nodes.generatorCategoryAssets', value: 'assets' },
] as const;
-const toFiniteNumber = (raw: string): number | undefined => {
- if (raw.trim() === '') {
- return undefined;
- }
-
- const parsed = Number(raw);
-
- return Number.isFinite(parsed) ? parsed : undefined;
-};
-
-/** Chromium steps a focused number input on wheel and swallows the scroll; unfocused, the panel scrolls instead. */
-const blurOnWheel = (event: WheelEvent<HTMLInputElement>) => event.currentTarget.blur();
-
/**
- * One labelled number in a settings row. Committed as typed, like the scalar field inputs: an empty or partial
- * entry keeps the last committed number, so a setting never silently becomes NaN.
+ * One labelled number in a settings row, on the shared numeric control: committed as typed, `null` when cleared,
+ * and marked by the generator's own rule for that setting rather than corrected here.
*/
const NumberSetting = ({
ariaLabel,
disabled,
id,
integer,
+ invalid,
label,
max,
min,
@@ -86,57 +77,47 @@ const NumberSetting = ({
disabled?: boolean;
id: string;
integer: boolean;
+ invalid: boolean;
label: string;
max?: number;
min?: number;
- value: number;
- onCommit: (value: number) => void;
+ value: number | null;
+ onCommit: (value: number | null) => void;
}) => {
- const [draft, setDraft] = useState<string | null>(null);
- const onChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const text = event.currentTarget.value;
- const next = toFiniteNumber(text);
-
- setDraft(text);
-
- // Out-of-range entries stay on screen as a draft but never commit: a count of 0 would make the stored
- // value unreadable and the widget would lose the variant.
- if (
- next !== undefined &&
- (!integer || Number.isInteger(next)) &&
- (min === undefined || next >= min) &&
- (max === undefined || next <= max)
- ) {
- onCommit(next);
- }
- },
- [integer, max, min, onCommit]
+ const template = useMemo<NumericInputTemplate>(
+ () => ({
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ maximum: max ?? null,
+ minimum: min ?? null,
+ multipleOf: null,
+ title: label || ariaLabel || '',
+ type: { batch: false, cardinality: 'SINGLE', name: integer ? 'IntegerField' : 'FloatField' },
+ }),
+ [ariaLabel, integer, label, max, min]
);
- const onBlur = useCallback(() => setDraft(null), []);
+ const onChange = useCallback((next: number | undefined) => onCommit(next ?? null), [onCommit]);
return (
- <HStack gap="1" minW="0">
+ <HStack flex="1" gap="1" minW="0">
{label ? (
- <chakra.label color="fg.subtle" flexShrink={0} fontSize="2xs" htmlFor={id} minW="10">
+ <chakra.label color="fg.subtle" flexShrink={0} fontSize="2xs" htmlFor={`${id}-number-input`} minW="10">
{label}
</chakra.label>
) : null}
- <Input
- aria-label={ariaLabel}
- className="nodrag"
- disabled={disabled}
- id={id}
- max={max}
- min={min}
- size="2xs"
- step={integer ? 1 : 'any'}
- type="number"
- value={draft ?? String(value)}
- onBlur={onBlur}
- onChange={onChange}
- onWheel={blurOnWheel}
- />
+ {/* The host's Field.Root marks every control inside it invalid; each setting scopes its own validity. */}
+ <Field.Root flex="1" invalid={invalid} minW="12">
+ <NumericInput
+ ariaLabel={ariaLabel}
+ disabled={disabled}
+ id={id}
+ invalid={invalid}
+ size="2xs"
+ template={template}
+ value={value ?? undefined}
+ onChange={onChange}
+ />
+ </Field.Root>
</HStack>
);
};
@@ -144,10 +125,12 @@ const NumberSetting = ({
/** The seed row: unchecked draws fresh values every time, checked pins them to a seed. */
const SeedSetting = ({
id,
+ invalid,
seed,
onCommit,
}: {
id: string;
+ invalid: boolean;
seed: number | null;
onCommit: (seed: number | null) => void;
}) => {
@@ -156,23 +139,36 @@ const SeedSetting = ({
(event: { checked: boolean | 'indeterminate' }) => onCommit(event.checked === true ? 0 : null),
[onCommit]
);
+ // `null` already means "unseeded" here, so a cleared input keeps the pinned seed instead of unchecking the box.
+ const onSeedCommit = useCallback(
+ (next: number | null) => {
+ if (next !== null) {
+ onCommit(next);
+ }
+ },
+ [onCommit]
+ );
return (
<HStack gap="2" minW="0">
- <Checkbox.Root checked={seed !== null} colorPalette="accent" size="xs" onCheckedChange={onCheckedChange}>
- <Checkbox.HiddenInput />
- <Checkbox.Control />
- <Checkbox.Label fontSize="2xs">{t('nodes.generatorSeed')}</Checkbox.Label>
- </Checkbox.Root>
+ {/* Ark controls take the enclosing field's control id; a field of their own keeps ids unique in the widget. */}
+ <Field.Root flexShrink={0} gap="0" w="auto">
+ <Checkbox.Root checked={seed !== null} colorPalette="accent" size="xs" onCheckedChange={onCheckedChange}>
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label fontSize="2xs">{t('nodes.generatorSeed')}</Checkbox.Label>
+ </Checkbox.Root>
+ </Field.Root>
<NumberSetting
ariaLabel={t('nodes.generatorSeed')}
disabled={seed === null}
id={`${id}-seed`}
integer
+ invalid={invalid}
label=""
min={0}
value={seed ?? 0}
- onCommit={onCommit}
+ onCommit={onSeedCommit}
/>
</HStack>
);
@@ -263,17 +259,19 @@ const BoardSetting = ({
const onValueChange = useCallback((value: string) => onCommit(value), [onCommit]);
return (
- <Combobox
- aria-label={t('nodes.generatorBoard')}
- className="nodrag nowheel"
- id={id}
- invalid={isMissing}
- noResultsText={t('nodes.generatorSelectBoard')}
- options={options}
- searchPlaceholder={boards.isLoading ? t('nodes.recordListLoading') : t('nodes.generatorSelectBoard')}
- value={boardId ?? null}
- onValueChange={onValueChange}
- />
+ <Field.Root gap="0" invalid={isMissing} minW="0" w="full">
+ <Combobox
+ aria-label={t('nodes.generatorBoard')}
+ className="nodrag nowheel"
+ id={id}
+ invalid={isMissing}
+ noResultsText={t('nodes.generatorSelectBoard')}
+ options={options}
+ searchPlaceholder={boards.isLoading ? t('nodes.recordListLoading') : t('nodes.generatorSelectBoard')}
+ value={boardId ?? null}
+ onValueChange={onValueChange}
+ />
+ </Field.Root>
);
};
@@ -353,6 +351,12 @@ const GeneratorPreview = ({
settled: WorkflowGeneratorValue;
}) => {
const { t } = useTranslation();
+ const invalidReason = getWorkflowGeneratorInvalidReason(generator);
+
+ if (invalidReason !== null) {
+ return <PreviewBox tone="fg.error">{invalidReason}</PreviewBox>;
+ }
+
const requested = getWorkflowGeneratorRequestedCount(settled);
// Never build an oversized list for a preview; readiness refuses it on the same rule.
@@ -365,7 +369,7 @@ const GeneratorPreview = ({
}
if (isRandomWorkflowGeneratorValue(generator)) {
- const count = 'count' in generator ? generator.count : 0;
+ const count = 'count' in generator && generator.count !== null ? generator.count : 0;
return <PreviewBox>{`<${t('nodes.generatorNRandomValues', { count })}>`}</PreviewBox>;
}
@@ -482,7 +486,9 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
[setProperty]
);
const onSeedChange = useCallback((seed: number | null) => setProperty('seed', seed), [setProperty]);
- const number = (key: string) => (next: number) => setProperty(key, next, true);
+ const number = (key: string) => (next: number | null) => setProperty(key, next, true);
+ const isOff = (key: string) =>
+ generator !== undefined && getWorkflowGeneratorPropertyInvalidReason(generator, key) !== null;
const variantType = generator?.type ?? '';
const variantValue = useMemo(() => [variantType], [variantType]);
const category = generator?.type === 'image_generator_images_from_board' ? generator.category : 'images';
@@ -510,6 +516,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
<HStack gap="2">
<NumberSetting
id={`${prefix}-start`}
+ invalid={isOff('start')}
integer={generator.type.startsWith('integer')}
label={t('nodes.generatorStart')}
value={generator.start}
@@ -517,6 +524,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
/>
<NumberSetting
id={`${prefix}-step`}
+ invalid={isOff('step')}
integer={generator.type.startsWith('integer')}
label={t('nodes.generatorStep')}
value={generator.step}
@@ -524,6 +532,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
/>
<NumberSetting
id={`${prefix}-count`}
+ invalid={isOff('count')}
integer
label={t('nodes.generatorCount')}
min={1}
@@ -537,6 +546,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
<HStack gap="2">
<NumberSetting
id={`${prefix}-start`}
+ invalid={isOff('start')}
integer={generator.type.startsWith('integer')}
label={t('nodes.generatorStart')}
value={generator.start}
@@ -544,6 +554,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
/>
<NumberSetting
id={`${prefix}-end`}
+ invalid={isOff('end')}
integer={generator.type.startsWith('integer')}
label={t('nodes.generatorEnd')}
value={generator.end}
@@ -551,6 +562,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
/>
<NumberSetting
id={`${prefix}-count`}
+ invalid={isOff('count')}
integer
label={t('nodes.generatorCount')}
min={1}
@@ -565,6 +577,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
<HStack gap="2">
<NumberSetting
id={`${prefix}-min`}
+ invalid={isOff('min')}
integer={generator.type.startsWith('integer')}
label={t('nodes.generatorMin')}
value={generator.min}
@@ -572,6 +585,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
/>
<NumberSetting
id={`${prefix}-max`}
+ invalid={isOff('max')}
integer={generator.type.startsWith('integer')}
label={t('nodes.generatorMax')}
value={generator.max}
@@ -579,6 +593,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
/>
<NumberSetting
id={`${prefix}-count`}
+ invalid={isOff('count')}
integer
label={t('nodes.generatorCount')}
min={1}
@@ -586,7 +601,7 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
onCommit={number('count')}
/>
</HStack>
- <SeedSetting id={prefix} seed={generator.seed} onCommit={onSeedChange} />
+ <SeedSetting id={prefix} invalid={isOff('seed')} seed={generator.seed} onCommit={onSeedChange} />
</Stack>
) : null}
{generator.type === 'float_generator_parse_string' ||
@@ -613,14 +628,15 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
<HStack gap="2">
<NumberSetting
id={`${prefix}-count`}
+ invalid={isOff('count')}
integer
label={t('nodes.generatorCount')}
- max={DYNAMIC_PROMPTS_MAX}
+ max={WORKFLOW_DYNAMIC_PROMPTS_MAX}
min={1}
value={generator.count}
onCommit={number('count')}
/>
- <SeedSetting id={prefix} seed={generator.seed} onCommit={onSeedChange} />
+ <SeedSetting id={prefix} invalid={isOff('seed')} seed={generator.seed} onCommit={onSeedChange} />
</HStack>
<InputSetting id={`${prefix}-input`} value={generator.input} onCommit={onInputChange} />
</Stack>
@@ -629,9 +645,10 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
<Stack gap="1.5">
<NumberSetting
id={`${prefix}-max-prompts`}
+ invalid={isOff('maxPrompts')}
integer
label={t('nodes.generatorMaxPrompts')}
- max={DYNAMIC_PROMPTS_MAX}
+ max={WORKFLOW_DYNAMIC_PROMPTS_MAX}
min={1}
value={generator.maxPrompts}
onCommit={number('maxPrompts')}
@@ -642,16 +659,18 @@ export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }:
{generator.type === 'image_generator_images_from_board' ? (
<Stack gap="1.5">
<BoardSetting boardId={generator.board_id} id={`${prefix}-board`} onCommit={onBoardChange} />
- <Select
- aria-label={t('nodes.generatorImagesCategory')}
- className="nodrag"
- collection={categoryCollection}
- size="xs"
- value={categoryValue}
- valueTextProps={SELECT_VALUE_TEXT_PROPS}
- w="full"
- onValueChange={onCategoryChange}
- />
+ <Field.Root gap="0" minW="0" w="full">
+ <Select
+ aria-label={t('nodes.generatorImagesCategory')}
+ className="nodrag"
+ collection={categoryCollection}
+ size="xs"
+ value={categoryValue}
+ valueTextProps={SELECT_VALUE_TEXT_PROPS}
+ w="full"
+ onValueChange={onCategoryChange}
+ />
+ </Field.Root>
</Stack>
) : null}
<GeneratorPreview generator={generator} settled={held ?? generator} />
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/NumericInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/NumericInput.tsx
new file mode 100644
index 0000000000..ab9562295c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/NumericInput.tsx
@@ -0,0 +1,173 @@
+import type { FieldInputTemplate } from '@features/workflow/contracts';
+
+import { Input } from '@chakra-ui/react';
+import {
+ useCallback,
+ useRef,
+ useState,
+ type ChangeEvent,
+ type FocusEvent,
+ type MouseEvent,
+ type WheelEvent,
+} from 'react';
+
+export const invalidProps = (invalid: boolean | undefined) => (invalid ? { 'aria-invalid': true } : {});
+
+const toFiniteNumber = (raw: string): number | undefined => {
+ if (raw.trim() === '') {
+ return undefined;
+ }
+
+ const parsed = Number(raw);
+
+ return Number.isFinite(parsed) ? parsed : undefined;
+};
+
+export const finiteNumberOrUndefined = (value: number | null | undefined): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+const positiveFiniteNumberOrUndefined = (value: number | null | undefined): number | undefined => {
+ const normalized = finiteNumberOrUndefined(value);
+
+ return normalized !== undefined && normalized > 0 ? normalized : undefined;
+};
+
+/**
+ * The text exactly as typed, held while the control is focused and dropped on blur. Rendering the committed value
+ * instead lets its echo rewrite the input under the caret (dropping a trailing `.` or `0`, moving the caret to the
+ * end), and the Canvas rebuilds its flow model in a transition, so the echo can lag a keystroke behind.
+ */
+export const useFocusedDraft = () => {
+ const [draft, setDraft] = useState<string | null>(null);
+ const clearDraft = useCallback(() => setDraft(null), []);
+
+ return [draft, setDraft, clearDraft] as const;
+};
+
+/** The slice of a field template the control reads: its kind, name, and the bounds it reports to the browser. */
+export type NumericInputTemplate = Pick<
+ FieldInputTemplate,
+ 'exclusiveMaximum' | 'exclusiveMinimum' | 'maximum' | 'minimum' | 'multipleOf' | 'title' | 'type'
+>;
+
+export interface NumericInputProps {
+ /** The accessible name when the visible label lives elsewhere; defaults to the template title. */
+ ariaLabel?: string;
+ disabled?: boolean;
+ id?: string;
+ invalid?: boolean;
+ onChange: (value: number | undefined) => void;
+ size?: 'xs' | '2xs';
+ /** The arrow-key increment when the template declares no `multipleOf`. */
+ step?: number;
+ template: NumericInputTemplate;
+ value: unknown;
+}
+
+/** A double-click anywhere in the box selects the whole value, not just the word under the pointer. */
+const selectInputText = (event: MouseEvent<HTMLInputElement>) => event.currentTarget.select();
+
+/**
+ * The one numeric entry control for workflow values: the text stays as typed while focused, every parseable entry
+ * commits unchanged, and the host marks what cannot run instead of the control correcting it.
+ */
+export const NumericInput = ({
+ ariaLabel,
+ disabled,
+ id,
+ invalid,
+ onChange,
+ size = 'xs',
+ step,
+ template,
+ value,
+}: NumericInputProps) => {
+ const isInteger = template.type.name === 'IntegerField';
+ const [draft, setDraft, clearDraft] = useFocusedDraft();
+ // Set while a wheel event passes through: the blur it causes must not end the draft.
+ const wheelRefocus = useRef(false);
+ // Chromium keeps an unparseable partial entry (`-`, `1e`) on screen but reports it as empty, so the empty commit
+ // alone cannot tell the field apart from a cleared one.
+ const [hasBadInput, setHasBadInput] = useState(false);
+ const text = draft ?? (typeof value === 'number' && Number.isFinite(value) ? String(value) : '');
+ const min = finiteNumberOrUndefined(template.minimum) ?? finiteNumberOrUndefined(template.exclusiveMinimum);
+ const max = finiteNumberOrUndefined(template.maximum) ?? finiteNumberOrUndefined(template.exclusiveMaximum);
+ const multipleOf = positiveFiniteNumberOrUndefined(template.multipleOf);
+ const onInputChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const { validity, value: nextText } = event.currentTarget;
+
+ setDraft(nextText);
+ setHasBadInput(validity.badInput);
+ // Committed as typed: rounding, clamping, or dropping a sign would change what is on screen. The host marks
+ // fractional integers, out-of-range values, and an empty required field invalid instead.
+ onChange(toFiniteNumber(nextText));
+ },
+ [onChange, setDraft]
+ );
+ const onBlur = useCallback(
+ (event: FocusEvent<HTMLInputElement>) => {
+ if (wheelRefocus.current) {
+ return;
+ }
+
+ setHasBadInput(event.currentTarget.validity.badInput);
+ clearDraft();
+ },
+ [clearDraft]
+ );
+ // Chromium steps a focused number input on wheel and swallows the scroll. Dropping focus for the event lets the
+ // panel scroll instead; focus returns, with the draft and caret, once the scroll has been dispatched.
+ const onWheel = useCallback(
+ (event: WheelEvent<HTMLInputElement>) => {
+ const input = event.currentTarget;
+
+ if (document.activeElement !== input || wheelRefocus.current) {
+ return;
+ }
+
+ wheelRefocus.current = true;
+ input.blur();
+ requestAnimationFrame(() => {
+ wheelRefocus.current = false;
+
+ if (input.isConnected && document.activeElement === document.body) {
+ input.focus({ preventScroll: true });
+ } else {
+ // Focus went elsewhere within the frame (momentum wheel plus a click): finish the blur that was skipped.
+ setHasBadInput(input.validity.badInput);
+ clearDraft();
+ }
+ });
+ },
+ [clearDraft]
+ );
+
+ // Any non-empty text React writes replaces the bad entry on screen (a reset or undo landing a number), so the
+ // flag cannot outlive it; while the entry is held the text is empty, so a lagging Canvas echo leaves it alone.
+ if (hasBadInput && text !== '') {
+ setHasBadInput(false);
+ }
+
+ return (
+ <Input
+ aria-label={ariaLabel ?? template.title}
+ className="nodrag"
+ disabled={disabled}
+ id={id ? `${id}-number-input` : undefined}
+ max={max !== undefined ? String(max) : undefined}
+ min={min !== undefined ? String(min) : undefined}
+ fontVariantNumeric="tabular-nums"
+ size={size}
+ step={multipleOf !== undefined ? String(multipleOf) : step !== undefined ? String(step) : isInteger ? '1' : 'any'}
+ type="number"
+ value={text}
+ w="full"
+ {...invalidProps(invalid || hasBadInput)}
+ onBlur={onBlur}
+ onChange={onInputChange}
+ onDoubleClick={selectInputText}
+ onWheel={onWheel}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
index bd386bb715..0b017593a4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
@@ -1245,7 +1245,12 @@ const StatefulField = ({
);
const invalid = getWorkflowFieldInvalidReason({ isConnected: false, template, value }) !== null;
- return <WorkflowFieldInput invalid={invalid} template={template} value={value} onChange={onChange} />;
+ // Both editors wrap the control in a Field.Root that marks everything inside it invalid.
+ return (
+ <Field.Root invalid={invalid}>
+ <WorkflowFieldInput invalid={invalid} template={template} value={value} onChange={onChange} />
+ </Field.Root>
+ );
};
describe('WorkflowFieldInput text and number entry', () => {
@@ -2086,7 +2091,7 @@ describe('WorkflowFieldInput generators', () => {
return { onCommit };
};
const numberInput = (suffix: string) =>
- host.querySelector<HTMLInputElement>(`input[type="number"][id$="${suffix}"]`)!;
+ host.querySelector<HTMLInputElement>(`input[type="number"][id$="${suffix}-number-input"]`)!;
const selectVariant = async (label: string) => {
await act(() => userEvent.click(host.querySelector('[data-scope="select"][data-part="trigger"]')!));
const item = Array.from(document.querySelectorAll<HTMLElement>('[data-scope="select"][data-part="item"]')).find(
@@ -2137,11 +2142,20 @@ describe('WorkflowFieldInput generators', () => {
expect(numberInput('-seed').disabled).toBe(true);
expect(numberInput('-seed').getAttribute('aria-label')).toBe('nodes.generatorSeed');
- // A count below its minimum stays a draft: nothing commits, so the variant and its settings survive.
+ // A count below its minimum commits as typed, is flagged, and names its rule; the other settings survive.
await act(() => numberInput('-count').focus());
await act(() => userEvent.keyboard('{Control>}a{/Control}0'));
expect(numberInput('-count').value).toBe('0');
- expect(onCommit).not.toHaveBeenCalled();
+ expect(onCommit).toHaveBeenLastCalledWith({
+ count: 0,
+ max: 9,
+ min: 2,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ });
+ expect(numberInput('-count').getAttribute('aria-invalid')).toBe('true');
+ expect(numberInput('-min').getAttribute('aria-invalid')).toBeNull();
+ expect(host.textContent).toContain('Count must be at least 1.');
expect(numberInput('-min').value).toBe('2');
await act(() => userEvent.keyboard('5'));
expect(onCommit).toHaveBeenLastCalledWith({
@@ -2167,6 +2181,27 @@ describe('WorkflowFieldInput generators', () => {
await act(() => numberInput('-count').focus());
await act(() => userEvent.keyboard('{Control>}a{/Control}20000'));
await vi.waitFor(() => expect(host.textContent).toContain('nodes.generatorTooMany'), { timeout: 2000 });
+
+ // Clearing leaves the setting empty and flagged, on blur too, instead of restoring the last count.
+ await act(() => userEvent.keyboard('{Control>}a{/Control}{Backspace}'));
+ expect(onCommit).toHaveBeenLastCalledWith({
+ count: null,
+ max: 9,
+ min: 2,
+ seed: 0,
+ type: 'float_generator_random_distribution_uniform',
+ });
+ expect(host.textContent).toContain('Count is empty.');
+ await act(() => numberInput('-count').blur());
+ expect(numberInput('-count').value).toBe('');
+ expect(numberInput('-count').getAttribute('aria-invalid')).toBe('true');
+
+ // A fractional pinned seed is kept and flagged rather than dropped back to a random draw.
+ await act(() => numberInput('-seed').focus());
+ await act(() => userEvent.keyboard('{Control>}a{/Control}2.5'));
+ expect(onCommit).toHaveBeenLastCalledWith(expect.objectContaining({ seed: 2.5 }));
+ expect(numberInput('-seed').getAttribute('aria-invalid')).toBe('true');
+ expect(numberInput('-seed').disabled).toBe(false);
});
it('loads a parse-string source from a file and previews the split values', async () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 53b7fafcc5..d6a9654977 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -58,6 +58,12 @@ import {
getWorkflowMediaFieldDropItems,
type WorkflowMediaKind,
} from '@features/workflow/ui/fields/mediaFieldDnd';
+import {
+ finiteNumberOrUndefined,
+ invalidProps,
+ NumericInput,
+ useFocusedDraft,
+} from '@features/workflow/ui/fields/NumericInput';
import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
import {
getResolvedWorkflowEdges,
@@ -106,9 +112,6 @@ import {
useRef,
useState,
type ChangeEvent,
- type FocusEvent,
- type MouseEvent,
- type WheelEvent,
} from 'react';
import { useTranslation } from 'react-i18next';
@@ -151,47 +154,11 @@ export interface WorkflowFieldInputProps {
onSeedModeChange?: (seedMode: SeedMode) => void;
}
-const invalidProps = (invalid: boolean | undefined) => (invalid ? { 'aria-invalid': true } : {});
-
// The media well's hover, matching DropZone's pointer-hover accent preview.
const MEDIA_INPUT_HOVER_PROPS = { borderColor: 'accent.solid' };
-const toFiniteNumber = (raw: string): number | undefined => {
- if (raw.trim() === '') {
- return undefined;
- }
-
- const parsed = Number(raw);
-
- return Number.isFinite(parsed) ? parsed : undefined;
-};
-
-const finiteNumberOrUndefined = (value: number | null | undefined): number | undefined =>
- typeof value === 'number' && Number.isFinite(value) ? value : undefined;
-
-const positiveFiniteNumberOrUndefined = (value: number | null | undefined): number | undefined => {
- const normalized = finiteNumberOrUndefined(value);
-
- return normalized !== undefined && normalized > 0 ? normalized : undefined;
-};
-
-/**
- * The text exactly as typed, held while the control is focused and dropped on blur. Rendering the committed value
- * instead lets its echo rewrite the input under the caret (dropping a trailing `.` or `0`, moving the caret to the
- * end), and the Canvas rebuilds its flow model in a transition, so the echo can lag a keystroke behind.
- */
-const useFocusedDraft = () => {
- const [draft, setDraft] = useState<string | null>(null);
- const clearDraft = useCallback(() => setDraft(null), []);
-
- return [draft, setDraft, clearDraft] as const;
-};
-
-/**
- * A row of a list names itself by position; a scalar field is named by its title. `step` is the arrow-key
- * increment when the template declares no `multipleOf`.
- */
-type ScalarInputProps = WorkflowFieldInputProps & { ariaLabel?: string; step?: number };
+/** A row of a list names itself by position; a scalar field is named by its title. */
+type ScalarInputProps = WorkflowFieldInputProps & { ariaLabel?: string };
const StringInput = ({ ariaLabel, id, invalid, onChange, template, value }: ScalarInputProps) => {
const [draft, setDraft, clearDraft] = useFocusedDraft();
@@ -239,99 +206,6 @@ const StringInput = ({ ariaLabel, id, invalid, onChange, template, value }: Scal
);
};
-/** A double-click anywhere in the box selects the whole value, not just the word under the pointer. */
-const selectInputText = (event: MouseEvent<HTMLInputElement>) => event.currentTarget.select();
-
-const NumericInput = ({ ariaLabel, id, invalid, onChange, step, template, value }: ScalarInputProps) => {
- const isInteger = template.type.name === 'IntegerField';
- const [draft, setDraft, clearDraft] = useFocusedDraft();
- // Set while a wheel event passes through: the blur it causes must not end the draft.
- const wheelRefocus = useRef(false);
- // Chromium keeps an unparseable partial entry (`-`, `1e`) on screen but reports it as empty, so the empty commit
- // alone cannot tell the field apart from a cleared one.
- const [hasBadInput, setHasBadInput] = useState(false);
- const text = draft ?? (typeof value === 'number' && Number.isFinite(value) ? String(value) : '');
- const min = finiteNumberOrUndefined(template.minimum) ?? finiteNumberOrUndefined(template.exclusiveMinimum);
- const max = finiteNumberOrUndefined(template.maximum) ?? finiteNumberOrUndefined(template.exclusiveMaximum);
- const multipleOf = positiveFiniteNumberOrUndefined(template.multipleOf);
- const onInputChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const { validity, value: nextText } = event.currentTarget;
-
- setDraft(nextText);
- setHasBadInput(validity.badInput);
- // Committed as typed: rounding, clamping, or dropping a sign would change what is on screen. The host marks
- // fractional integers, out-of-range values, and an empty required field invalid instead.
- onChange(toFiniteNumber(nextText));
- },
- [onChange, setDraft]
- );
- const onBlur = useCallback(
- (event: FocusEvent<HTMLInputElement>) => {
- if (wheelRefocus.current) {
- return;
- }
-
- setHasBadInput(event.currentTarget.validity.badInput);
- clearDraft();
- },
- [clearDraft]
- );
- // Chromium steps a focused number input on wheel and swallows the scroll. Dropping focus for the event lets the
- // panel scroll instead; focus returns, with the draft and caret, once the scroll has been dispatched.
- const onWheel = useCallback(
- (event: WheelEvent<HTMLInputElement>) => {
- const input = event.currentTarget;
-
- if (document.activeElement !== input || wheelRefocus.current) {
- return;
- }
-
- wheelRefocus.current = true;
- input.blur();
- requestAnimationFrame(() => {
- wheelRefocus.current = false;
-
- if (input.isConnected && document.activeElement === document.body) {
- input.focus({ preventScroll: true });
- } else {
- // Focus went elsewhere within the frame (momentum wheel plus a click): finish the blur that was skipped.
- setHasBadInput(input.validity.badInput);
- clearDraft();
- }
- });
- },
- [clearDraft]
- );
-
- // Any non-empty text React writes replaces the bad entry on screen (a reset or undo landing a number), so the
- // flag cannot outlive it; while the entry is held the text is empty, so a lagging Canvas echo leaves it alone.
- if (hasBadInput && text !== '') {
- setHasBadInput(false);
- }
-
- return (
- <Input
- aria-label={ariaLabel ?? template.title}
- className="nodrag"
- id={id ? `${id}-number-input` : undefined}
- max={max !== undefined ? String(max) : undefined}
- min={min !== undefined ? String(min) : undefined}
- size="xs"
- fontVariantNumeric="tabular-nums"
- step={multipleOf !== undefined ? String(multipleOf) : step !== undefined ? String(step) : isInteger ? '1' : 'any'}
- type="number"
- value={text}
- w="full"
- {...invalidProps(invalid || hasBadInput)}
- onBlur={onBlur}
- onChange={onInputChange}
- onDoubleClick={selectInputText}
- onWheel={onWheel}
- />
- );
-};
-
/**
* Plan stepping previews from workflow iterations and template defaults; nokey prevents node shortcuts inside the
* row and portalled menu.
@@ -1559,7 +1433,7 @@ const LoRACollectionRow = ({
<MiddleTruncate color={entry ? undefined : 'fg.error'} flex="1" fontSize="2xs" minW="0" text={label} />
</Tooltip>
{entry ? (
- <Box flexShrink="0" w="16">
+ <Field.Root flexShrink="0" invalid={!isLoraFieldWeightValid(entry.weight)} w="16">
<NumericInput
ariaLabel={`${label} weight`}
id={id ? `${id}-lora-${index}` : undefined}
@@ -1569,7 +1443,7 @@ const LoRACollectionRow = ({
value={entry.weight ?? undefined}
onChange={onValueChange}
/>
- </Box>
+ </Field.Root>
) : null}
<IconButton
aria-label={`Remove ${label}`}