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(generation): saved aspect ratios and a ratio picker (#10101)

Josh Corbett25e82a3c470b
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
index 042db225f1..05648e134e 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
@@ -15,13 +15,14 @@ This page describes each section of the **Generate** panel in detail. For a firs
The **Size** section sets the width and height of the image.
* **Width** and **Height** can be set by dragging, by typing a value, or by dragging the corner of the small size preview. Sizes run from 64 to 4096 pixels and snap to a multiple the model requires, usually 8, 16 or 32.
-* **Aspect ratio** offers common shapes: 21:9, 16:9, 3:2, 4:3, 1:1, 3:4, 2:3, 9:16 and 9:21, or **Free**. Choosing a ratio locks it, so changing the width changes the height to match. The lock button between the two fields locks or unlocks the current ratio.
+* **Aspect ratio** opens a picker with common shapes: 21:9, 16:9, 3:2, 4:3, 1:1, 3:4, 2:3, 9:16 and 9:21, or **Free**. Choosing a ratio locks it and keeps the current pixel count, so changing the width changes the height to match. The lock button between the two fields locks or unlocks the current ratio. Arrow keys move between the shapes.
+* **Your ratios** in the same picker holds ratios you name yourself, such as *Cinema* at 2.39:1. **Add ratio** starts from the locked ratio when the lock is on, otherwise from the current size's ratio; each saved ratio shows the size picking it would set, and can be edited or deleted (with Undo). You can keep up to 50. Saved ratios are only shapes, never sizes, so they work with every model, and they belong to your account, shared by every project and by the canvas frame tool. A locked ratio you have not named shows as its terms, such as 12:5.
* **Swap width and height** turns a landscape image into a portrait one and back.
* Each model has an optimal image area, typically about one megapixel for newer models and less for SD 1.5. The line under the fields shows the image's size in megapixels, marks the recommended size, and estimates the run time from your recent runs.
* **Reset size**, the button beside **Swap width and height**, opens a menu. Each item shows the size it sets, and the item matching the current size is checked; choosing it again changes nothing:
+ * **Optimal size for** the current ratio — the model's optimal area at the current aspect ratio, named by its saved name when it has one. It is absent at 1:1, where it would be the native square.
+ * **Model defaults** — the size set in the model's default settings. It appears only when the model sets one. A locked ratio stays locked and takes the default size's ratio; an unlocked one stays unlocked.
* **Square at native size** — a 1:1 square at the model's native size, such as 1024×1024 for SDXL and FLUX or 512×512 for SD 1.5, with the ratio locked.
- * **Optimal size for** the current ratio — the model's optimal area at the current aspect ratio. It is absent at 1:1, where it would be the native square.
- * **Model defaults** — the size set in the model's default settings. It appears only when the model sets one.
Right-clicking the width and height and choosing **Reset to model default** also resets the size this way.
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index 21d6da68ba..0706085592 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -97,7 +97,7 @@ The generation frame is the area that is generated. With the **Generation frame*
<Image src={frameProps} alt="The Generation frame tool's options: Position X and Y, and the Frame's Size and Aspect with a lock button." width={420} />
-The tool's options show the frame's **Position** and **Size**, and an **Aspect** menu for common aspect ratios, with a lock. While the Canvas is where you generate, the frame and the Generate panel's **Size** section are one size: the section says *Linked to the canvas frame*, the aspect lock is shared, and a width or height typed in either place resizes the frame around its center. A frame resize made from the Generate panel is a canvas step, so **Ctrl+Z** on the canvas puts the frame and the size back together. The size snaps to the sizes the selected model supports.
+The tool's options show the frame's **Position** and **Size**, and an **Aspect** picker with the common aspect ratios and your saved ratios, with a lock. Picking a ratio keeps the frame's pixel count and resizes it around its center, as picking it in the Generate panel does; the lock alone keeps the frame's size. While the Canvas is where you generate, the frame and the Generate panel's **Size** section are one size: the section says *Linked to the canvas frame*, the aspect lock is shared, and a width or height typed in either place resizes the frame around its center. A frame resize made from the Generate panel is a canvas step, so **Ctrl+Z** on the canvas puts the frame and the size back together. The size snaps to the sizes the selected model supports.
### What the model sees
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index bd4fc4e560..4673d9e909 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -565,6 +565,7 @@
"source:src/features/gallery/ui/useGalleryUploadInput.ts",
"source:src/features/gallery/utility.ts",
"source:src/features/generation/core/architectureCapabilities.ts",
+ "source:src/features/generation/core/aspectRatioPresets.ts",
"source:src/features/generation/core/baseGenerationPolicies.ts",
"source:src/features/generation/core/batch.ts",
"source:src/features/generation/core/canvas/addRegionalGuidance.ts",
@@ -1036,6 +1037,7 @@
"source:src/workbench/settings/SettingsDialogHost.tsx",
"source:src/workbench/settings/WidgetSettingsButton.tsx",
"source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/aspectRatioPresets.ts",
"source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
"source:src/workbench/settings/dialogResource.ts",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 021d645e18..92cae0f241 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1000,6 +1000,7 @@
"source:src/features/gallery/utility.ts",
"source:src/features/gallery/widget.ts",
"source:src/features/generation/core/architectureCapabilities.ts",
+ "source:src/features/generation/core/aspectRatioPresets.ts",
"source:src/features/generation/core/baseGenerationPolicies.ts",
"source:src/features/generation/core/batch.ts",
"source:src/features/generation/core/canvas/addRegionalGuidance.ts",
@@ -1106,8 +1107,8 @@
"source:src/features/generation/ui/reference-images/ReferenceImageControls.tsx",
"source:src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx",
"source:src/features/generation/ui/reference-images/referenceImageConfig.ts",
+ "source:src/features/generation/ui/shared/AspectRatioPicker.tsx",
"source:src/features/generation/ui/shared/AspectRatioPreview.tsx",
- "source:src/features/generation/ui/shared/AspectRatioSelect.tsx",
"source:src/features/generation/ui/shared/CapabilitiesGate.tsx",
"source:src/features/generation/ui/shared/ConceptRow.tsx",
"source:src/features/generation/ui/shared/ConditioningRebalanceBars.tsx",
@@ -1770,6 +1771,7 @@
"source:src/workbench/settings/SettingsDialogHost.tsx",
"source:src/workbench/settings/WidgetSettingsButton.tsx",
"source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/aspectRatioPresets.ts",
"source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
"source:src/workbench/settings/dialogResource.ts",
@@ -2164,6 +2166,7 @@
"source:src/features/generation/canvasProcessingSize.ts",
"source:src/features/generation/components.ts",
"source:src/features/generation/core/architectureCapabilities.ts",
+ "source:src/features/generation/core/aspectRatioPresets.ts",
"source:src/features/generation/core/baseGenerationPolicies.ts",
"source:src/features/generation/core/batch.ts",
"source:src/features/generation/core/canvas/addControlLayers.ts",
@@ -2274,8 +2277,8 @@
"source:src/features/generation/ui/reference-images/ReferenceImageControls.tsx",
"source:src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx",
"source:src/features/generation/ui/reference-images/referenceImageConfig.ts",
+ "source:src/features/generation/ui/shared/AspectRatioPicker.tsx",
"source:src/features/generation/ui/shared/AspectRatioPreview.tsx",
- "source:src/features/generation/ui/shared/AspectRatioSelect.tsx",
"source:src/features/generation/ui/shared/CapabilitiesGate.tsx",
"source:src/features/generation/ui/shared/ConceptRow.tsx",
"source:src/features/generation/ui/shared/ConditioningRebalanceBars.tsx",
@@ -2950,6 +2953,7 @@
"source:src/workbench/settings/SettingsDialogHost.tsx",
"source:src/workbench/settings/WidgetSettingsButton.tsx",
"source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/aspectRatioPresets.ts",
"source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
"source:src/workbench/settings/dialogResource.ts",
@@ -3509,6 +3513,7 @@
"source:src/features/gallery/utility.ts",
"source:src/features/gallery/widget.ts",
"source:src/features/generation/core/architectureCapabilities.ts",
+ "source:src/features/generation/core/aspectRatioPresets.ts",
"source:src/features/generation/core/baseGenerationPolicies.ts",
"source:src/features/generation/core/batch.ts",
"source:src/features/generation/core/canvas/addRegionalGuidance.ts",
@@ -3615,8 +3620,8 @@
"source:src/features/generation/ui/reference-images/ReferenceImageControls.tsx",
"source:src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx",
"source:src/features/generation/ui/reference-images/referenceImageConfig.ts",
+ "source:src/features/generation/ui/shared/AspectRatioPicker.tsx",
"source:src/features/generation/ui/shared/AspectRatioPreview.tsx",
- "source:src/features/generation/ui/shared/AspectRatioSelect.tsx",
"source:src/features/generation/ui/shared/CapabilitiesGate.tsx",
"source:src/features/generation/ui/shared/ConceptRow.tsx",
"source:src/features/generation/ui/shared/ConditioningRebalanceBars.tsx",
@@ -4351,6 +4356,7 @@
"source:src/workbench/settings/SettingsDialogHost.tsx",
"source:src/workbench/settings/WidgetSettingsButton.tsx",
"source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/aspectRatioPresets.ts",
"source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
"source:src/workbench/settings/dialogResource.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 5c443021bb..e93fefbc26 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2992,6 +2992,27 @@
"addReferenceImage": "Add reference image",
"advanced": "Advanced",
"aspectRatio": "Aspect ratio",
+ "aspectRatioAdd": "Add ratio",
+ "aspectRatioBuiltIns": "Ratios",
+ "aspectRatioDeleteNamed": "Delete ratio {{name}} ({{ratio}})",
+ "aspectRatioEdit": "Edit ratio",
+ "aspectRatioEditNamed": "Edit ratio {{name}} ({{ratio}})",
+ "aspectRatioFree": "Free",
+ "aspectRatioHeightTerm": "Ratio height",
+ "aspectRatioListFull": "You can keep up to {{count}} ratios. Delete one to add another.",
+ "aspectRatioListFullNotice": "Your ratios list is full.",
+ "aspectRatioName": "Ratio name",
+ "aspectRatioNameRequired": "Enter a name.",
+ "aspectRatioOutOfRange": "Use a ratio between 1:8 and 8:1.",
+ "aspectRatioPresetDeleted": "Deleted ratio {{name}}",
+ "aspectRatioPresetOption": "{{name}}, {{ratio}}, {{size}}",
+ "aspectRatioRestoreFailed": "Couldn't bring back ratio {{name}}",
+ "aspectRatioTermDecimals": "Use up to two decimals.",
+ "aspectRatioTermsInvalid": "Enter two numbers above 0.",
+ "aspectRatioWidthTerm": "Ratio width",
+ "aspectRatioWouldSetSize": "Picking it sets {{size}}",
+ "aspectRatioYourRatios": "Your ratios",
+ "aspectRatioYourRatiosEmpty": "Name a ratio you use often to pick it here at any size.",
"capabilitiesLoadFailed": "Could not load model capabilities from the backend.",
"capabilitiesUnavailableForRecall": "Model capabilities are not loaded, so settings that depend on the model cannot be applied yet. Prompts and seed can. If loading failed, retry from the Generate panel.",
"capabilitiesUnavailableForSetup": "Model capabilities are not loaded, so this project cannot be set up for Generate yet. If loading failed, retry from the Generate panel.",
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index c2e0adc0a3..da183563a6 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -37,6 +37,7 @@ import { shallowEqual } from '@platform/state/selectors';
import { createActionToast } from '@platform/ui/toaster';
import { type QueryClient, QueryObserver, useQueryClient } from '@tanstack/react-query';
import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
+import { useAspectRatioPresets } from '@workbench/settings/aspectRatioPresets';
import {
getWorkbenchPreferences,
patchWorkbenchPreferences,
@@ -364,6 +365,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
}),
[session.multiuserEnabled, session.user?.user_id]
);
+ const aspectRatioPresets = useAspectRatioPresets();
const krea2RebalancePresets = useWorkbenchPreferenceSelector((preferences) => preferences.krea2RebalancePresets);
const rebalancePresetsGroup = useMemo<GenerationUiAdapter['rebalancePresets']>(
() => ({
@@ -464,6 +466,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
CanvasGenerationSections: GenerateCanvasSections,
CanvasRenderSize: GenerateCanvasRenderSize,
account: accountGroup,
+ aspectRatioPresets,
capabilities: capabilitiesGroup,
gallery: galleryGroup,
generateValues,
@@ -479,6 +482,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
}),
[
accountGroup,
+ aspectRatioPresets,
capabilitiesGroup,
galleryGroup,
generateValues,
diff --git a/invokeai/frontend/webv2/src/features/generation/components.ts b/invokeai/frontend/webv2/src/features/generation/components.ts
index b101986f9c..29acfb22f7 100644
--- a/invokeai/frontend/webv2/src/features/generation/components.ts
+++ b/invokeai/frontend/webv2/src/features/generation/components.ts
@@ -1,9 +1,9 @@
export {
AspectRatioLockButton,
- AspectRatioSelect,
+ AspectRatioPicker,
type AspectRatioLockButtonProps,
- type AspectRatioSelectProps,
-} from './ui/shared/AspectRatioSelect';
+ type AspectRatioPickerProps,
+} from './ui/shared/AspectRatioPicker';
export { NegativePromptField } from './ui/promptFields/NegativePromptField';
export { PositivePromptField } from './ui/promptFields/PositivePromptField';
export { PromptTextarea } from './ui/promptFields/PromptTextarea';
diff --git a/invokeai/frontend/webv2/src/features/generation/contracts.ts b/invokeai/frontend/webv2/src/features/generation/contracts.ts
index ff3a979ea4..24c0fc7288 100644
--- a/invokeai/frontend/webv2/src/features/generation/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/contracts.ts
@@ -1,5 +1,6 @@
export type * from './core/contracts';
export type * from './core/types';
+export type { AspectRatioPreset, AspectRatioPresetDraft, AspectRatioPresetsPort } from './core/aspectRatioPresets';
export type { CanvasScaleMethod, CanvasScalingSettings } from './core/canvas/types';
export type {
GenerateSectionId,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/aspectRatioPresets.test.ts b/invokeai/frontend/webv2/src/features/generation/core/aspectRatioPresets.test.ts
new file mode 100644
index 0000000000..0e1d1a1901
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/aspectRatioPresets.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatAspectRatio,
+ formatAspectRatioTerms,
+ getAspectRatioTerms,
+ getAspectRatioTermsError,
+ getLockedAspectRatioSettings,
+ matchAspectRatio,
+ MAX_ASPECT_RATIO_PRESETS,
+ normalizeAspectRatioPresets,
+} from './aspectRatioPresets';
+
+const cinema = { height: 1, id: 'cinema', label: 'Cinema', width: 2.39 };
+
+describe('normalizeAspectRatioPresets', () => {
+ it('keeps valid ratios in order with trimmed labels, including decimal terms and the 1:8 and 8:1 bounds', () => {
+ expect(
+ normalizeAspectRatioPresets([
+ { ...cinema, label: ' Cinema ' },
+ { height: 5, id: 'banner', label: 'Banner', width: 12 },
+ { height: 8, id: 'tall', label: 'Tall', width: 1 },
+ { height: 1, id: 'wide', label: 'Wide', width: 8 },
+ ])
+ ).toEqual([
+ cinema,
+ { height: 5, id: 'banner', label: 'Banner', width: 12 },
+ { height: 8, id: 'tall', label: 'Tall', width: 1 },
+ { height: 1, id: 'wide', label: 'Wide', width: 8 },
+ ]);
+ });
+
+ it('drops malformed entries, out-of-range ratios, blank labels and repeated ids', () => {
+ expect(
+ normalizeAspectRatioPresets([
+ null,
+ 'cinema',
+ { height: 1, id: 'zero', label: 'Zero', width: 0 },
+ { height: -2, id: 'negative', label: 'Negative', width: 3 },
+ { height: 1, id: 'infinite', label: 'Infinite', width: Number.POSITIVE_INFINITY },
+ { height: '1', id: 'text', label: 'Text', width: 2 },
+ { height: 1, id: 'too-wide', label: 'Too wide', width: 9 },
+ { height: 10, id: 'too-tall', label: 'Too tall', width: 1 },
+ { height: 1, id: 'blank', label: ' ', width: 2 },
+ { height: 1, id: '', label: 'No id', width: 2 },
+ cinema,
+ { ...cinema, label: 'Duplicate' },
+ ])
+ ).toEqual([cinema]);
+ expect(normalizeAspectRatioPresets(undefined)).toEqual([]);
+ expect(normalizeAspectRatioPresets({ cinema })).toEqual([]);
+ });
+
+ it('cuts a label to 40 characters', () => {
+ const long = 'A ratio named at far greater length than the list can show';
+
+ expect(normalizeAspectRatioPresets([{ ...cinema, label: long }])[0]?.label).toBe(
+ 'A ratio named at far greater length than'
+ );
+ });
+
+ it('keeps the first ratios up to the cap', () => {
+ const many = Array.from({ length: MAX_ASPECT_RATIO_PRESETS + 5 }, (_, index) => ({
+ height: 1,
+ id: `ratio-${index}`,
+ label: `Ratio ${index}`,
+ width: 2,
+ }));
+
+ const kept = normalizeAspectRatioPresets(many);
+
+ expect(kept).toHaveLength(MAX_ASPECT_RATIO_PRESETS);
+ expect(kept.at(-1)?.id).toBe(`ratio-${MAX_ASPECT_RATIO_PRESETS - 1}`);
+ });
+});
+
+describe('getAspectRatioTermsError', () => {
+ it('names a non-positive term before an out-of-range ratio', () => {
+ expect(getAspectRatioTermsError(16, 9)).toBeNull();
+ expect(getAspectRatioTermsError(0, 9)).toBe('terms');
+ expect(getAspectRatioTermsError(Number.NaN, 9)).toBe('terms');
+ expect(getAspectRatioTermsError(9, 1)).toBe('range');
+ expect(getAspectRatioTermsError(1, 8.5)).toBe('range');
+ });
+});
+
+describe('matchAspectRatio', () => {
+ const widescreen = { height: 9, id: 'widescreen', label: 'Widescreen', width: 16 };
+
+ it('names a locked ratio by the saved ratio equal to it, before a built-in equal to it', () => {
+ expect(matchAspectRatio(16 / 9, [cinema, widescreen])).toEqual({ kind: 'preset', preset: widescreen });
+ expect(matchAspectRatio(16 / 9, [cinema])).toEqual({ id: '16:9', kind: 'builtin' });
+ expect(matchAspectRatio(2.39, [cinema])).toEqual({ kind: 'preset', preset: cinema });
+ });
+
+ it('tolerates float error but not a different ratio', () => {
+ expect(matchAspectRatio(2.39 + 0.00005, [cinema])).toEqual({ kind: 'preset', preset: cinema });
+ expect(matchAspectRatio(2.4, [cinema])).toBeNull();
+ expect(matchAspectRatio(0, [cinema])).toBeNull();
+ });
+});
+
+describe('getAspectRatioTerms', () => {
+ it('finds small whole terms, so a size prefills the ratio it has', () => {
+ expect(getAspectRatioTerms(1536 / 640)).toEqual({ height: 5, width: 12 });
+ expect(getAspectRatioTerms(1024 / 576)).toEqual({ height: 9, width: 16 });
+ expect(getAspectRatioTerms(640 / 1536)).toEqual({ height: 12, width: 5 });
+ expect(getAspectRatioTerms(1)).toEqual({ height: 1, width: 1 });
+ });
+
+ it('falls back to the ratio against 1, to two decimals, when no small whole terms fit', () => {
+ expect(getAspectRatioTerms(2.39)).toEqual({ height: 1, width: 2.39 });
+ expect(getAspectRatioTerms(1 / Math.SQRT2)).toEqual({ height: 1.41, width: 1 });
+ // 1224 × 512 is 153:64, past the 32 limit on the second term.
+ expect(getAspectRatioTerms(1224 / 512)).toEqual({ height: 1, width: 2.39 });
+ });
+});
+
+describe('formatAspectRatio', () => {
+ it('writes the terms in the locale', () => {
+ expect(formatAspectRatio(2.4, 'en')).toBe('12:5');
+ expect(formatAspectRatio(2.39, 'en')).toBe('2.39:1');
+ expect(formatAspectRatio(1 / Math.SQRT2, 'en')).toBe('1:1.41');
+ expect(formatAspectRatio(2.39, 'de')).toBe('2,39:1');
+ expect(formatAspectRatioTerms({ height: 1, width: 2.395 }, 'en')).toBe('2.4:1');
+ });
+});
+
+describe('getLockedAspectRatioSettings', () => {
+ it('stores a ratio equal to a built-in under its id and exact value, any other as locked Free', () => {
+ expect(getLockedAspectRatioSettings(16 / 9 + 0.00001)).toEqual({
+ aspectRatioId: '16:9',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 16 / 9,
+ });
+ expect(getLockedAspectRatioSettings(2.39)).toEqual({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 2.39,
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/aspectRatioPresets.ts b/invokeai/frontend/webv2/src/features/generation/core/aspectRatioPresets.ts
new file mode 100644
index 0000000000..146ae335f5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/aspectRatioPresets.ts
@@ -0,0 +1,178 @@
+import type { AspectRatioId, GenerateSettings } from './types';
+
+import { ASPECT_RATIO_MAP, ASPECT_RATIO_TOLERANCE, deriveAspectRatioId } from './settings';
+
+/**
+ * A user-named aspect ratio. Only the ratio is saved, never a size: models differ in the size they work best at, so
+ * picking one keeps the current pixel count. The terms are as the user wrote them and may be decimals (2.39 : 1).
+ */
+export interface AspectRatioPreset {
+ id: string;
+ label: string;
+ width: number;
+ height: number;
+}
+
+export type AspectRatioPresetDraft = Omit<AspectRatioPreset, 'id'>;
+
+/** The account's saved ratios, from whichever surface edits them. */
+export interface AspectRatioPresetsPort {
+ /** Valid saved ratios in save order; built-ins are not included. */
+ presets: readonly AspectRatioPreset[];
+ /** Whether the list is full: {@link save} then adds nothing. */
+ isFull: boolean;
+ /** Adds a ratio under a new id and returns it; null when the list is full. */
+ save(draft: AspectRatioPresetDraft): AspectRatioPreset | null;
+ /** Rewrites a saved ratio; does nothing once it is gone. */
+ update(presetId: string, draft: AspectRatioPresetDraft): void;
+ /** Removes a ratio and reports it with Undo, which puts it back where it was, or says why it cannot (a full list). */
+ remove(presetId: string): void;
+}
+
+export interface AspectRatioTerms {
+ width: number;
+ height: number;
+}
+
+/** The range the built-ins span (1:8 to 8:1); generation sizes outside it are not useful. */
+const MIN_ASPECT_RATIO = 1 / 8;
+const MAX_ASPECT_RATIO = 8;
+/** Keeps the synced preferences blob and the picker's list bounded. */
+export const MAX_ASPECT_RATIO_PRESETS = 50;
+export const MAX_ASPECT_RATIO_PRESET_LABEL_LENGTH = 40;
+/** The largest second term {@link getAspectRatioTerms} tries before falling back to decimals. */
+const MAX_INTEGER_TERM_DENOMINATOR = 32;
+
+const isPositiveFinite = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0;
+
+type AspectRatioTermsError = 'terms' | 'range';
+
+/** `terms` when a term is not a positive number, `range` when the ratio falls outside 1:8 to 8:1. */
+export const getAspectRatioTermsError = (width: unknown, height: unknown): AspectRatioTermsError | null => {
+ if (!isPositiveFinite(width) || !isPositiveFinite(height)) {
+ return 'terms';
+ }
+
+ const ratio = width / height;
+
+ // The tolerance keeps 1:8 and 8:1 themselves in range whatever the float error of the division.
+ return ratio < MIN_ASPECT_RATIO - ASPECT_RATIO_TOLERANCE || ratio > MAX_ASPECT_RATIO + ASPECT_RATIO_TOLERANCE
+ ? 'range'
+ : null;
+};
+
+/** Valid saved ratios in their saved order, labels trimmed; drops malformed entries and repeated ids. */
+export const normalizeAspectRatioPresets = (value: unknown): AspectRatioPreset[] => {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+
+ const seen = new Set<string>();
+ const presets: AspectRatioPreset[] = [];
+
+ for (const entry of value) {
+ if (presets.length >= MAX_ASPECT_RATIO_PRESETS) {
+ break;
+ }
+
+ if (!entry || typeof entry !== 'object') {
+ continue;
+ }
+
+ const { height, id, label, width } = entry as Partial<AspectRatioPreset>;
+ const trimmed = typeof label === 'string' ? label.trim().slice(0, MAX_ASPECT_RATIO_PRESET_LABEL_LENGTH) : '';
+
+ if (
+ typeof id !== 'string' ||
+ id === '' ||
+ seen.has(id) ||
+ trimmed === '' ||
+ getAspectRatioTermsError(width, height) !== null
+ ) {
+ continue;
+ }
+
+ seen.add(id);
+ presets.push({ height: height as number, id, label: trimmed, width: width as number });
+ }
+
+ return presets;
+};
+
+export const getAspectRatioPresetRatio = (preset: AspectRatioTerms): number => preset.width / preset.height;
+
+type AspectRatioMatch =
+ | { kind: 'preset'; preset: AspectRatioPreset }
+ | { kind: 'builtin'; id: Exclude<AspectRatioId, 'Free'> }
+ | null;
+
+/**
+ * What a locked ratio is called: the first saved ratio equal to it, else the built-in equal to it, else nothing. A
+ * saved ratio wins over a built-in, since the user named it.
+ */
+export const matchAspectRatio = (ratio: number, presets: readonly AspectRatioPreset[]): AspectRatioMatch => {
+ if (!isPositiveFinite(ratio)) {
+ return null;
+ }
+
+ const preset = presets.find(
+ (candidate) => Math.abs(getAspectRatioPresetRatio(candidate) - ratio) < ASPECT_RATIO_TOLERANCE
+ );
+
+ if (preset) {
+ return { kind: 'preset', preset };
+ }
+
+ const id = deriveAspectRatioId(ratio, 1);
+
+ return id === 'Free' ? null : { id, kind: 'builtin' };
+};
+
+const roundToHundredths = (value: number): number => Math.round(value * 100) / 100;
+
+/**
+ * Terms that describe a ratio: the smallest whole terms when the second is at most 32 (2.4 is 12 : 5), else the ratio
+ * against 1 to two decimals (2.39 : 1, 1 : 1.41). Also the Add ratio form's prefill for a size, as `width / height`.
+ */
+export const getAspectRatioTerms = (ratio: number): AspectRatioTerms => {
+ if (!isPositiveFinite(ratio)) {
+ return { height: 1, width: 1 };
+ }
+
+ for (let height = 1; height <= MAX_INTEGER_TERM_DENOMINATOR; height += 1) {
+ const width = Math.round(ratio * height);
+
+ if (width > 0 && Math.abs(width / height - ratio) < ASPECT_RATIO_TOLERANCE) {
+ return { height, width };
+ }
+ }
+
+ return ratio >= 1
+ ? { height: 1, width: roundToHundredths(ratio) }
+ : { height: roundToHundredths(1 / ratio), width: 1 };
+};
+
+/** `W:H` with each term to at most two decimals in the locale's digits. */
+export const formatAspectRatioTerms = (terms: AspectRatioTerms, locale?: string): string => {
+ const format = new Intl.NumberFormat(locale, { maximumFractionDigits: 2, useGrouping: false });
+
+ return `${format.format(terms.width)}:${format.format(terms.height)}`;
+};
+
+/** A ratio no saved ratio or built-in names, written as {@link getAspectRatioTerms} describes it. */
+export const formatAspectRatio = (ratio: number, locale?: string): string =>
+ formatAspectRatioTerms(getAspectRatioTerms(ratio), locale);
+
+/** The Generate fields a chosen ratio is stored as: a built-in under its id and exact value, any other as locked Free. */
+export const getLockedAspectRatioSettings = (
+ ratio: number
+): Pick<GenerateSettings, 'aspectRatioId' | 'aspectRatioIsLocked' | 'aspectRatioValue'> => {
+ const id = deriveAspectRatioId(ratio, 1);
+
+ return {
+ aspectRatioId: id,
+ aspectRatioIsLocked: true,
+ aspectRatioValue: id === 'Free' ? ratio : ASPECT_RATIO_MAP[id].ratio,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
index 245fe2bbab..8ca69d2373 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
@@ -777,6 +777,27 @@ describe('dimension helpers', () => {
expect(wide.width / wide.height).toBeCloseTo(16 / 9, 1);
});
+ it('keeps the ratio at the size limits, scaling both sides instead of clamping one', () => {
+ // 6144² at 16:9 is 8192×4608; halved to fit 4096.
+ expect(calculateNewSize(16 / 9, 6144 * 6144)).toEqual({ height: 2304, width: 4096 });
+ // 2048² at 8:1 is 5792.6×724.1; scaled to fit 4096 wide, the height is exactly 512.
+ expect(calculateNewSize(8, 2048 * 2048)).toEqual({ height: 512, width: 4096 });
+ // 32² is below the 64px minimum on both sides.
+ expect(calculateNewSize(1, 32 * 32)).toEqual({ height: 64, width: 64 });
+ // 48² at 4:1 is 96×24; scaled so the short side is 64, then 256×64.
+ expect(calculateNewSize(4, 48 * 48)).toEqual({ height: 64, width: 256 });
+ // 64:1 is the widest ratio both limits allow: 4096×64 exactly.
+ expect(calculateNewSize(64, 1024 * 1024)).toEqual({ height: 64, width: 4096 });
+ });
+
+ it('caps the long side and holds the short side at the minimum for a ratio past 64:1', () => {
+ // 2000:1 at 1024² would be about 45795×23; no in-range size has that ratio, so the result is the closest corner.
+ expect(calculateNewSize(2000, 1024 * 1024)).toEqual({ height: 64, width: 4096 });
+ expect(calculateNewSize(1 / 2000, 1024 * 1024)).toEqual({ height: 4096, width: 64 });
+ // A tiny area goes up the same way: the short side reaches 64 and the long side stops at 4096.
+ expect(calculateNewSize(2000, 16 * 16)).toEqual({ height: 64, width: 4096 });
+ });
+
it('moves a reference image one step through the stack, and no-ops at the ends', () => {
const referenceImages = ['a', 'b', 'c'].map((id) => ({
config: { image: null, model: null, type: 'flux_kontext_reference_image' as const },
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index d2e61ac181..5b8930a415 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -181,15 +181,24 @@ export const DEFAULT_LORA_WEIGHT_CONFIG = {
export const clampDimension = (value: number, grid = DIMENSION_GRID): number =>
Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, Math.round(value / grid) * grid));
-/** Fit a width/height of the given ratio into approximately the given pixel area, snapped to the grid. */
+/**
+ * Fit a width/height of the given ratio into approximately the given pixel area, snapped to the grid. At the dimension
+ * limits both sides scale together (the larger side down to the maximum, else the smaller up to the minimum), so for a
+ * ratio within MAX_DIMENSION / MIN_DIMENSION (64:1) only grid snapping moves it. A ratio past that cannot fit both
+ * limits: the long side is capped at the maximum and the short side held at the minimum.
+ */
export const calculateNewSize = (
ratio: number,
area: number,
grid = DIMENSION_GRID
): { width: number; height: number } => {
const exactWidth = Math.sqrt(area * ratio);
+ const exactHeight = exactWidth / ratio;
+ const larger = Math.max(exactWidth, exactHeight);
+ const smaller = Math.min(exactWidth, exactHeight);
+ const scale = larger > MAX_DIMENSION ? MAX_DIMENSION / larger : smaller < MIN_DIMENSION ? MIN_DIMENSION / smaller : 1;
- return { height: clampDimension(exactWidth / ratio, grid), width: clampDimension(exactWidth, grid) };
+ return { height: clampDimension(exactHeight * scale, grid), width: clampDimension(exactWidth * scale, grid) };
};
/** A preset ratio implies the lock; Free holds its ratio only while the lock is on. */
@@ -197,6 +206,9 @@ export const isAspectRatioLocked = (
settings: Pick<GenerateSettings, 'aspectRatioId' | 'aspectRatioIsLocked'>
): boolean => settings.aspectRatioId !== 'Free' || settings.aspectRatioIsLocked;
+/** How far apart two ratios may be and still count as the same one. */
+export const ASPECT_RATIO_TOLERANCE = 0.0001;
+
/** Best-matching preset for existing dimensions, falling back to Free. */
export const deriveAspectRatioId = (width: number, height: number): AspectRatioId => {
if (height <= 0) {
@@ -206,7 +218,7 @@ export const deriveAspectRatioId = (width: number, height: number): AspectRatioI
const ratio = width / height;
for (const [id, entry] of Object.entries(ASPECT_RATIO_MAP)) {
- if (Math.abs(entry.ratio - ratio) < 0.0001) {
+ if (Math.abs(entry.ratio - ratio) < ASPECT_RATIO_TOLERANCE) {
return id as AspectRatioId;
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index c27ae156fd..85d867d07c 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -118,6 +118,11 @@ export {
isVaeCompatibleWithGenerateModel,
isZImageQwen3Encoder,
} from './core/componentCompatibility';
+export {
+ getLockedAspectRatioSettings,
+ MAX_ASPECT_RATIO_PRESETS,
+ normalizeAspectRatioPresets,
+} from './core/aspectRatioPresets';
export {
isValidKrea2RebalanceWeights,
normalizeRebalancePresets,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx
index 9799e2e42b..1760ac5f20 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx
@@ -15,13 +15,16 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { userEvent } from 'vitest/browser';
+import { page, userEvent } from 'vitest/browser';
import type { CanvasRenderSizeProps } from './GenerationUiContext';
import { GenerateDimensionFields } from './GenerateDimensionFields';
-const harness = vi.hoisted(() => ({ invocationSourceId: 'generate' }));
+const harness = vi.hoisted(() => ({
+ aspectRatioPresets: [] as { height: number; id: string; label: string; width: number }[],
+ invocationSourceId: 'generate',
+}));
vi.mock('./GenerationUiContext', () => ({
useGenerationQueueInsights: (select: (insights: unknown) => unknown) =>
@@ -33,6 +36,13 @@ vi.mock('./GenerationUiContext', () => ({
controls: <div data-testid="render-size-controls" />,
size: { height: frame.height * 2, width: frame.width * 2 },
}),
+ aspectRatioPresets: {
+ isFull: false,
+ presets: harness.aspectRatioPresets,
+ remove: vi.fn(),
+ save: vi.fn(),
+ update: vi.fn(),
+ },
project: { invocationSourceId: harness.invocationSourceId },
sectionPreferences: { sectionsOpen: { dimensions: true }, setSectionOpen: vi.fn() },
}),
@@ -50,6 +60,8 @@ void i18n.use(initReactI18next).init({
widgets: {
generate: {
aspectRatio: 'Aspect ratio',
+ aspectRatioFree: 'Free',
+ aspectRatioPresetOption: '{{name}}, {{ratio}}, {{size}}',
height: 'Height',
lockAspectRatio: 'Lock aspect ratio',
megapixelsValue: '{{value}} MP',
@@ -59,6 +71,7 @@ void i18n.use(initReactI18next).init({
resetSizeOptimalForCurrentRatio: 'Optimal size for current ratio',
resetSizeOptimalForRatio: 'Optimal size for {{ratio}}',
resetSizeSquareNative: 'Square at native size',
+ resetToModelDefault: 'Reset to model default',
size: 'Size',
sizePreviewHandle: 'Resize',
swapWidthAndHeight: 'Swap width and height',
@@ -98,15 +111,17 @@ const render = async (settings: Partial<GenerateSettings>, model: GenerateModelC
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
- const onCommit = vi.fn();
- const onResetSize = vi.fn();
+ const draft = createExternalStoreCore({ ...getDefaultGenerateSettings(model), ...settings });
+ // Commits and resets land in the draft, as the panel's draft would show them.
+ const onCommit = vi.fn((patch: Partial<GenerateSettings>) => draft.patchSnapshot(patch));
+ const onResetSize = vi.fn((patch: Partial<GenerateSettings>) => draft.patchSnapshot(patch));
await settle(() => {
root?.render(
<ChakraProvider value={system}>
<I18nextProvider i18n={i18n}>
<GenerateDimensionFields
- draft={createExternalStoreCore({ ...getDefaultGenerateSettings(model), ...settings })}
+ draft={draft}
projectId="project"
selectedModel={model}
onCommit={onCommit}
@@ -125,7 +140,12 @@ const lockButton = () =>
'button[aria-label="Lock aspect ratio"], button[aria-label="Unlock aspect ratio"]'
) ?? null;
const bracket = () => host?.querySelector('[data-part="bracket"]')?.parentElement ?? null;
-const presetTrigger = () => host?.querySelector<HTMLButtonElement>('[role="combobox"]') ?? null;
+const ratioTrigger = () => page.getByRole('button', { name: /^Aspect ratio/ });
+const chooseRatio = async (name: string) => {
+ await userEvent.click(ratioTrigger());
+ // Built-ins are radios in the ratio grid; saved ratios are rows named "name, ratio, size".
+ await userEvent.click(page.getByRole(name.includes(',') ? 'button' : 'radio', { exact: true, name }));
+};
const unmountAndReset = async () => {
await settle(() => root?.unmount());
@@ -135,6 +155,7 @@ const unmountAndReset = async () => {
};
afterEach(async () => {
+ harness.aspectRatioPresets = [];
harness.invocationSourceId = 'generate';
await unmountAndReset();
});
@@ -247,8 +268,7 @@ describe('GenerateDimensionFields aspect ratio', () => {
expect(lockButton()?.getAttribute('aria-label')).toBe('Lock aspect ratio');
expect(bracket()?.hasAttribute('data-locked')).toBe(false);
- await settle(() => presetTrigger()?.click());
- await settle(() => document.querySelector<HTMLElement>('[role="option"][data-value="16:9"]')?.click());
+ await chooseRatio('16:9');
expect(onCommit).toHaveBeenCalledWith({
aspectRatioId: '16:9',
@@ -269,7 +289,7 @@ describe('GenerateDimensionFields aspect ratio', () => {
width: 1368,
});
- expect(presetTrigger()?.textContent).toContain('16:9');
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio 16:9');
expect(lockButton()?.getAttribute('aria-label')).toBe('Unlock aspect ratio');
expect(bracket()?.hasAttribute('data-locked')).toBe(true);
@@ -331,6 +351,67 @@ describe('GenerateDimensionFields aspect ratio', () => {
width: 768,
});
});
+ it('keeps the pixel count when choosing a saved ratio and stores it as a locked Free ratio', async () => {
+ harness.aspectRatioPresets = [{ height: 1, id: 'cinema', label: 'Cinema', width: 2.39 }];
+ const { onCommit } = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 1024, width: 1024 });
+
+ // 1024² at 2.39:1 is 1583.1×662.4, snapped to 1584×664: the same pixel count, never the model's optimum.
+ await chooseRatio('Cinema, 2.39:1, 1584×664');
+
+ expect(onCommit).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 2.39,
+ height: 664,
+ width: 1584,
+ });
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio Cinema 2.39:1');
+ });
+
+ it('stores a saved ratio equal to a built-in under the built-in id, still named by the saved ratio', async () => {
+ harness.aspectRatioPresets = [{ height: 9, id: 'wide', label: 'Wide', width: 16 }];
+ const { onCommit } = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 1024, width: 1024 });
+
+ await chooseRatio('Wide, 16:9, 1368×768');
+
+ expect(onCommit).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: '16:9',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 16 / 9,
+ height: 768,
+ width: 1368,
+ });
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio Wide 16:9');
+ });
+
+ it('keeps a locked extreme ratio at the size limit, scaling both sides', async () => {
+ harness.aspectRatioPresets = [{ height: 1, id: 'banner', label: 'Banner', width: 7 }];
+ const { onCommit } = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 2048, width: 2048 });
+
+ // 2048² at 7:1 is 5418.6×774.1; scaled to fit 4096 wide it is 4096×585.1, snapped to 4096×584 (7.01:1).
+ await chooseRatio('Banner, 7:1, 4096×584');
+
+ expect(onCommit).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 7,
+ height: 584,
+ width: 4096,
+ });
+ });
+
+ it('swaps a saved ratio into the saved ratio that is its inverse', async () => {
+ harness.aspectRatioPresets = [
+ { height: 5, id: 'banner', label: 'Banner', width: 12 },
+ { height: 12, id: 'skyscraper', label: 'Skyscraper', width: 5 },
+ ];
+ await render({ aspectRatioId: 'Free', aspectRatioIsLocked: true, aspectRatioValue: 2.4, height: 640, width: 1536 });
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio Banner 12:5');
+
+ await settle(() => host?.querySelector<HTMLButtonElement>('button[aria-label="Swap width and height"]')?.click());
+
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio Skyscraper 5:12');
+ });
});
describe('GenerateDimensionFields Reset size', () => {
@@ -368,9 +449,10 @@ describe('GenerateDimensionFields Reset size', () => {
await openMenu();
// SD 1.5 is native at 512 on an 8px grid: 512² reshaped to 2:3 is 418×627, snapped to 416×624.
+ // The optimal size for the ratio comes first, as the choice most reached for; this model sets no size of its own.
expect(menuItems().map((item) => item.textContent)).toEqual([
- 'Square at native size512×512',
'Optimal size for 2:3416×624',
+ 'Square at native size512×512',
]);
await choose('Square at native size');
@@ -402,26 +484,41 @@ describe('GenerateDimensionFields Reset size', () => {
expect(onResetSize).toHaveBeenCalledExactlyOnceWith({ height: 360, width: 728 });
});
- it('names a locked free ratio in the app locale', async () => {
+ it('names a locked free ratio by small whole terms, else by decimals in the app locale', async () => {
+ await render({ aspectRatioId: 'Free', aspectRatioIsLocked: true, aspectRatioValue: 2.5, height: 400, width: 1000 });
+ await openMenu();
+ // 512² at 5:2 is 809.5×323.8, snapped to 808×320.
+ expect(menuItem('Optimal size for 5:2')?.textContent).toBe('Optimal size for 5:2808×320');
+ await unmountAndReset();
+
i18n.addResourceBundle('de', 'translation', i18n.getResourceBundle('en', 'translation'));
await i18n.changeLanguage('de');
try {
await render({
aspectRatioId: 'Free',
aspectRatioIsLocked: true,
- aspectRatioValue: 2.5,
+ aspectRatioValue: 2.39,
height: 400,
- width: 1000,
+ width: 960,
});
await openMenu();
- // 512² at 5:2 is 809.5×323.8, snapped to 808×320.
- expect(menuItem('Optimal size for 2,5:1')?.textContent).toBe('Optimal size for 2,5:1808×320');
+ // 512² at 2.39:1 is 791.5×331.2, snapped to 792×328.
+ expect(menuItem('Optimal size for 2,39:1')?.textContent).toBe('Optimal size for 2,39:1792×328');
} finally {
await i18n.changeLanguage('en');
}
});
+ it('names a locked ratio by the saved ratio it matches', async () => {
+ harness.aspectRatioPresets = [{ height: 5, id: 'banner', label: 'Banner', width: 12 }];
+ await render({ aspectRatioId: 'Free', aspectRatioIsLocked: true, aspectRatioValue: 2.4, height: 640, width: 1536 });
+ await openMenu();
+
+ // 512² at 12:5 is 793.3×330.5, snapped to 792×328.
+ expect(menuItem('Optimal size for Banner')?.textContent).toBe('Optimal size for Banner792×328');
+ });
+
it('checks the applied choice, keeps it reachable, and drops an optimal size that is the native square', async () => {
await render({ aspectRatioId: '1:1', aspectRatioIsLocked: true, aspectRatioValue: 1, height: 512, width: 512 });
@@ -478,7 +575,94 @@ describe('GenerateDimensionFields Reset size', () => {
await choose('Model defaults');
- expect(onResetSize).toHaveBeenCalledExactlyOnceWith({ height: 768, width: 640 });
+ // An unlocked ratio stays unlocked, at the default size's ratio.
+ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: false,
+ aspectRatioValue: 640 / 768,
+ height: 768,
+ width: 640,
+ });
+ });
+
+ const squareModel: MainModelConfig = { ...sd1Model, default_settings: { height: 1024, width: 1024 } };
+ const widescreen = {
+ aspectRatioId: '16:9',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 16 / 9,
+ height: 768,
+ width: 1368,
+ } as const;
+
+ it('locks a square model default at 1:1 when a non-square ratio was locked', async () => {
+ const { onResetSize } = await render(widescreen, squareModel);
+ await openMenu();
+
+ await choose('Model defaults');
+
+ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 1,
+ height: 1024,
+ width: 1024,
+ });
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio 1:1');
+ expect(lockButton()?.getAttribute('aria-label')).toBe('Unlock aspect ratio');
+ expect(host?.textContent).toContain('1024×1024');
+ });
+
+ it('leaves the ratio unlocked when resetting an unlocked size to a square model default', async () => {
+ const { onResetSize } = await render(
+ { aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: 16 / 9, height: 768, width: 1368 },
+ squareModel
+ );
+ await openMenu();
+
+ await choose('Model defaults');
+
+ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: false,
+ aspectRatioValue: 1,
+ height: 1024,
+ width: 1024,
+ });
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio Free');
+ expect(lockButton()?.getAttribute('aria-label')).toBe('Lock aspect ratio');
+ });
+
+ it('locks the default size ratio from the size field Reset to model default', async () => {
+ const portraitModel: MainModelConfig = { ...sd1Model, default_settings: { height: 768, width: 640 } };
+ const { onResetSize } = await render(widescreen, portraitModel);
+
+ await userEvent.click(page.getByRole('slider', { name: 'Width' }), { button: 'right' });
+ await userEvent.click(page.getByRole('menuitem', { name: 'Reset to model default' }));
+
+ // 640×768 is 5:6, no built-in: a locked Free ratio.
+ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 640 / 768,
+ height: 768,
+ width: 640,
+ });
+ await expect.element(ratioTrigger()).toHaveAccessibleName('Aspect ratio 5:6');
+ });
+
+ it('orders the optimal size first, then the model defaults, then the native square', async () => {
+ const sizedModel: MainModelConfig = { ...sd1Model, default_settings: { height: 768, width: 640 } };
+ await render(
+ { aspectRatioId: '2:3', aspectRatioIsLocked: true, aspectRatioValue: 2 / 3, height: 768, width: 512 },
+ sizedModel
+ );
+ await openMenu();
+
+ expect(menuItems().map((item) => item.textContent)).toEqual([
+ 'Optimal size for 2:3416×624',
+ 'Model defaults640×768',
+ 'Square at native size512×512',
+ ]);
});
it('opens from the keyboard and applies the highlighted choice', async () => {
@@ -493,11 +677,23 @@ describe('GenerateDimensionFields Reset size', () => {
resetSizeButton()?.focus();
await userEvent.keyboard('{Enter}');
await vi.waitFor(() => expect(document.activeElement?.getAttribute('role')).toBe('menu'));
- await userEvent.keyboard('{ArrowDown}');
- await userEvent.keyboard('{ArrowDown}');
+ // Arrows down to the native square by its name, wherever the menu lists it.
+ const square = menuItem('Square at native size');
+ for (let step = 0; step < menuItems().length && !square?.hasAttribute('data-highlighted'); step += 1) {
+ await userEvent.keyboard('{ArrowDown}');
+ }
+ expect(square?.hasAttribute('data-highlighted')).toBe(true);
await userEvent.keyboard('{Enter}');
- await vi.waitFor(() => expect(onResetSize).toHaveBeenCalledExactlyOnceWith({ height: 624, width: 416 }));
+ await vi.waitFor(() =>
+ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 1,
+ height: 512,
+ width: 512,
+ })
+ );
});
it('has no footer optimal-size button', async () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx
index 015330db02..1ab5298857 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx
@@ -2,6 +2,11 @@
import type { AspectRatioId, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';
import { Badge, Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';
+import {
+ formatAspectRatio,
+ getLockedAspectRatioSettings,
+ matchAspectRatio,
+} from '@features/generation/core/aspectRatioPresets';
import { getDefaultGenerateSettings, getGenerationDimensions } from '@features/generation/core/baseGenerationPolicies';
import { MAX_DIMENSION, MIN_DIMENSION } from '@features/generation/core/dimensionLimits';
import {
@@ -27,7 +32,7 @@ import {
useGenerationQueueInsights,
useGenerationUi,
} from './GenerationUiContext';
-import { AspectRatioLockButton, AspectRatioSelect } from './shared/AspectRatioSelect';
+import { AspectRatioLockButton, AspectRatioPicker } from './shared/AspectRatioPicker';
import { ExternalSizeSelect } from './shared/ExternalSizeSelect';
import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';
import { GenerateFieldContextMenu } from './shared/GenerateFieldContextMenu';
@@ -142,7 +147,7 @@ const ResetSizeMenu = ({ choices }: { choices: readonly ResetSizeChoice[] }) =>
<Menu.Root ids={ids} positioning={RESET_SIZE_MENU_POSITIONING}>
<Menu.Trigger asChild>
<Tooltip content={label} ids={ids}>
- <IconButton aria-label={label} size="sm" variant="outline">
+ <IconButton aria-label={label} variant="outline">
<RotateCcwIcon />
</IconButton>
</Tooltip>
@@ -374,7 +379,7 @@ export const GenerateDimensionFields = ({
selectedModel,
}: GenerateDimensionFieldsProps) => {
const { i18n, t } = useTranslation();
- const { CanvasRenderSize: CanvasRenderSizeSlot, project } = useGenerationUi();
+ const { aspectRatioPresets, CanvasRenderSize: CanvasRenderSizeSlot, project } = useGenerationUi();
const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectDimensionSettings);
const secondsPerRun = useGenerationQueueInsights(selectSecondsPerRun);
const [draftDimensions, setDraftDimensions] = useState<Dimensions | null>(null);
@@ -459,8 +464,9 @@ export const GenerateDimensionFields = ({
onCommit(patch);
};
- const setAspectRatioId = (id: AspectRatioId) => {
- if (id === 'Free') {
+ // Any ratio keeps the current pixel count, as a built-in always has; Reset size is where the model's optimum lives.
+ const applyAspectRatio = (ratio: number | null) => {
+ if (ratio === null) {
commitSettings({
aspectRatioId: 'Free',
aspectRatioIsLocked: false,
@@ -470,12 +476,8 @@ export const GenerateDimensionFields = ({
return;
}
- const ratio = ASPECT_RATIO_MAP[id].ratio;
-
commitSettings({
- aspectRatioId: id,
- aspectRatioIsLocked: true,
- aspectRatioValue: ratio,
+ ...getLockedAspectRatioSettings(ratio),
...calculateNewSize(ratio, displayDimensions.width * displayDimensions.height, dimensionGrid),
});
};
@@ -521,27 +523,50 @@ export const GenerateDimensionFields = ({
};
const nativeSide = clampDimension(dimensions.optimal, dimensionGrid);
- const optimalRatio = isRatioConstrained
- ? getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions })
- : dimensionRatio;
+ // The ratio the lock holds; a built-in's own value, so a drifted stored value cannot unmatch it.
+ const lockedRatio = isRatioConstrained
+ ? settings.aspectRatioId !== 'Free'
+ ? ASPECT_RATIO_MAP[settings.aspectRatioId].ratio
+ : getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions })
+ : null;
// The model's pixel budget reshaped to the ratio the section holds.
- const optimalSize = calculateNewSize(optimalRatio, dimensions.optimal * dimensions.optimal, dimensionGrid);
+ const optimalSize = calculateNewSize(
+ lockedRatio ?? dimensionRatio,
+ dimensions.optimal * dimensions.optimal,
+ dimensionGrid
+ );
const isAtSize = (size: Dimensions) =>
displayDimensions.width === size.width && displayDimensions.height === size.height;
- // A preset by its name and a locked free ratio as `W:1`; an unlocked free ratio is just whatever the size is now.
+ // A locked ratio by its saved name, built-in id or terms; an unlocked ratio is just whatever the size is now.
+ const lockedMatch = lockedRatio === null ? null : matchAspectRatio(lockedRatio, aspectRatioPresets.presets);
const optimalLabel =
- settings.aspectRatioId !== 'Free'
- ? t('widgets.generate.resetSizeOptimalForRatio', { ratio: settings.aspectRatioId })
- : settings.aspectRatioIsLocked
- ? t('widgets.generate.resetSizeOptimalForRatio', {
- ratio: `${new Intl.NumberFormat(i18n.resolvedLanguage, { maximumFractionDigits: 2 }).format(optimalRatio)}:1`,
- })
- : t('widgets.generate.resetSizeOptimalForCurrentRatio');
-
+ lockedRatio === null
+ ? t('widgets.generate.resetSizeOptimalForCurrentRatio')
+ : t('widgets.generate.resetSizeOptimalForRatio', {
+ ratio:
+ lockedMatch?.kind === 'preset'
+ ? lockedMatch.preset.label
+ : lockedMatch?.kind === 'builtin'
+ ? lockedMatch.id
+ : formatAspectRatio(lockedRatio, i18n.resolvedLanguage),
+ });
+
+ // The ratio follows the size: a lock stays on and holds the default size's ratio, an unlocked ratio stays unlocked.
const resetToModelDefaults = () => {
- if (modelDefaults) {
- resetSize({ height: modelDefaults.height, width: modelDefaults.width });
+ if (!modelDefaults) {
+ return;
}
+
+ const { height, width } = modelDefaults;
+ const ratio = height > 0 ? width / height : 1;
+
+ resetSize({
+ ...(isRatioConstrained
+ ? getLockedAspectRatioSettings(ratio)
+ : { aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: ratio }),
+ height,
+ width,
+ });
};
// Only a size the model sets itself is worth offering; otherwise its defaults are the native square.
const modelDefaultSize =
@@ -550,25 +575,8 @@ export const GenerateDimensionFields = ({
: null;
const resetSizeChoices: readonly ResetSizeChoice[] = [
- {
- isCurrent:
- isAtSize({ height: nativeSide, width: nativeSide }) &&
- settings.aspectRatioId === '1:1' &&
- settings.aspectRatioIsLocked,
- label: t('widgets.generate.resetSizeSquareNative'),
- // The field set choosing the 1:1 preset writes.
- onSelect: () =>
- resetSize({
- aspectRatioId: '1:1',
- aspectRatioIsLocked: true,
- aspectRatioValue: 1,
- height: nativeSide,
- width: nativeSide,
- }),
- size: { height: nativeSide, width: nativeSide },
- value: 'square-native',
- },
- // A square ratio's optimal size is the native square, which the first choice already sets.
+ // First, as the choice most reached for. A square ratio's optimal size is the native square, which the square choice
+ // below sets, so it is left out there.
...(optimalSize.width === nativeSide && optimalSize.height === nativeSide
? []
: [
@@ -591,6 +599,24 @@ export const GenerateDimensionFields = ({
},
]
: []),
+ {
+ isCurrent:
+ isAtSize({ height: nativeSide, width: nativeSide }) &&
+ settings.aspectRatioId === '1:1' &&
+ settings.aspectRatioIsLocked,
+ label: t('widgets.generate.resetSizeSquareNative'),
+ // The field set choosing the 1:1 preset writes.
+ onSelect: () =>
+ resetSize({
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 1,
+ height: nativeSide,
+ width: nativeSide,
+ }),
+ size: { height: nativeSide, width: nativeSide },
+ value: 'square-native',
+ },
];
// The recommendation reshapes the model's pixel budget to the live aspect ratio.
@@ -709,17 +735,20 @@ export const GenerateDimensionFields = ({
/>
) : null}
<HStack alignItems="center" gap="1">
- <AspectRatioSelect
- fallbackRatio={dimensionRatio}
- value={settings.aspectRatioId}
- onChange={setAspectRatioId}
+ <AspectRatioPicker
+ currentSize={displayDimensions}
+ getSizeForRatio={(ratio) =>
+ calculateNewSize(ratio, displayDimensions.width * displayDimensions.height, dimensionGrid)
+ }
+ lockedRatio={lockedRatio}
+ presets={aspectRatioPresets}
+ onChange={applyAspectRatio}
/>
<ResetSizeMenu choices={resetSizeChoices} />
<Box css={SWAP_COLUMN_CSS}>
<Tooltip content={t('widgets.generate.swapWidthAndHeight')}>
<IconButton
aria-label={t('widgets.generate.swapWidthAndHeight')}
- size="sm"
variant="outline"
onClick={swapDimensions}
>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx
index 83490db9cf..76d51044a1 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx
@@ -188,6 +188,7 @@ const createStableGroups = () => ({
CanvasGenerationSections: () => null,
CanvasRenderSize: () => null,
account: { currentUserId: null, multiuserEnabled: false },
+ aspectRatioPresets: { isFull: false, presets: [], remove: noop, save: () => null, update: noop },
capabilities: { canManagePromptTemplates: false, canManageSharedSystemPrompts: false },
gallery: { findImage: noop, getUploadBoardId: () => Promise.resolve('none'), selectedImage: null, touchImages: noop },
models: {
@@ -643,8 +644,12 @@ describe('GenerateSettingsForm render isolation', () => {
host!.querySelector<HTMLButtonElement>('button[aria-label="widgets.generate.resetSize"]')?.click()
);
const menu = document.querySelector<HTMLElement>('[role="menu"]');
- // Highlights the first choice, Square at native size.
- await settle(() => menu?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })));
+ const highlighted = () => menu?.querySelector('[role="menuitemradio"][data-highlighted]')?.textContent ?? '';
+ // Arrows down to Square at native size by its name, wherever the menu lists it.
+ for (let step = 0; step < 3 && !highlighted().startsWith('widgets.generate.resetSizeSquareNative'); step += 1) {
+ await settle(() => menu?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })));
+ }
+ expect(highlighted()).toMatch(/^widgets\.generate\.resetSizeSquareNative/);
// A width step still inside its debounce window, then the reset.
await settle(() => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
index 701b8bc3c6..aa5b61dfe7 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
@@ -1,4 +1,5 @@
import type { GenerationModelCatalogItem, PromptHistoryItem } from '@features/generation/contracts';
+import type { AspectRatioPresetsPort } from '@features/generation/core/aspectRatioPresets';
import type { RebalancePreset } from '@features/generation/core/conditioningRebalance';
import type { GenerateSettings } from '@features/generation/core/types';
import type { ReadableExternalStore } from '@platform/state/projectedExternalStore';
@@ -89,6 +90,8 @@ export interface GenerationUiAdapter {
currentUserId: string | null;
multiuserEnabled: boolean;
};
+ /** The account's saved aspect ratios, shared with the canvas Frame tool. */
+ aspectRatioPresets: AspectRatioPresetsPort;
capabilities: {
/** Bulk import/export of prompt templates; the backend routes are admin-only. */
canManagePromptTemplates: boolean;
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPicker.browser.test.tsx
new file mode 100644
index 0000000000..b4c4341a00
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPicker.browser.test.tsx
@@ -0,0 +1,538 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop */
+import '@fontsource/inter/index.css';
+import type {
+ AspectRatioPreset,
+ AspectRatioPresetDraft,
+ AspectRatioPresetsPort,
+} from '@features/generation/core/aspectRatioPresets';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { calculateNewSize } from '@features/generation/core/settings';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+import { AspectRatioPicker } from './AspectRatioPicker';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const i18n = createInstance();
+let root: Root | null = null;
+let host: HTMLDivElement | null = null;
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ root = null;
+ host = null;
+ await page.viewport(1280, 720);
+});
+
+const cinema: AspectRatioPreset = { height: 1, id: 'cinema', label: 'Cinema', width: 2.39 };
+const square: AspectRatioPreset = { height: 1, id: 'square', label: 'Square', width: 1 };
+
+/** An in-memory port: what the account's preference would hold, without the toast the real one adds on delete. */
+const Harness = ({
+ currentSize,
+ initial,
+ lockedRatio,
+ removed,
+ savesNothing,
+ onChange,
+}: {
+ currentSize: { height: number; width: number };
+ initial: AspectRatioPreset[];
+ lockedRatio: number | null;
+ removed: string[];
+ /** The list filled up elsewhere (another tab) after the form opened. */
+ savesNothing: boolean;
+ onChange: (ratio: number | null) => void;
+}) => {
+ const [presets, setPresets] = useState(initial);
+ const port: AspectRatioPresetsPort = {
+ isFull: false,
+ presets,
+ remove: (id) => {
+ removed.push(id);
+ setPresets((current) => current.filter((preset) => preset.id !== id));
+ },
+ save: (draft: AspectRatioPresetDraft) => {
+ if (savesNothing) {
+ return null;
+ }
+ const preset = { ...draft, id: `saved-${presets.length}` };
+ setPresets((current) => [...current, preset]);
+ return preset;
+ },
+ update: (id, draft) =>
+ setPresets((current) => current.map((preset) => (preset.id === id ? { ...preset, ...draft } : preset))),
+ };
+
+ return (
+ <AspectRatioPicker
+ currentSize={currentSize}
+ getSizeForRatio={(ratio) => calculateNewSize(ratio, currentSize.width * currentSize.height, 8)}
+ lockedRatio={lockedRatio}
+ presets={port}
+ onChange={onChange}
+ />
+ );
+};
+
+const render = async ({
+ currentSize = { height: 640, width: 1536 },
+ initial = [cinema],
+ lockedRatio = null,
+ savesNothing = false,
+}: {
+ currentSize?: { height: number; width: number };
+ initial?: AspectRatioPreset[];
+ lockedRatio?: number | null;
+ savesNothing?: boolean;
+} = {}) => {
+ host = document.createElement('div');
+ host.style.width = '280px';
+ document.body.append(host);
+ root = createRoot(host);
+ const onChange = vi.fn();
+ const removed: string[] = [];
+
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness
+ currentSize={currentSize}
+ initial={initial}
+ lockedRatio={lockedRatio}
+ removed={removed}
+ savesNothing={savesNothing}
+ onChange={onChange}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+
+ return { onChange, removed };
+};
+
+const trigger = () => page.getByRole('button', { name: /^Aspect ratio/ });
+const dialog = () => document.querySelector<HTMLElement>('[data-scope="popover"][data-part="content"]');
+const isOpen = () => dialog()?.getAttribute('data-state') === 'open';
+const openPicker = async () => {
+ await userEvent.click(trigger());
+ await expect.poll(isOpen).toBe(true);
+};
+const nameInput = () => page.getByRole('textbox', { name: 'Ratio name' });
+const widthTerm = () => page.getByRole('textbox', { name: 'Ratio width' });
+const heightTerm = () => page.getByRole('textbox', { name: 'Ratio height' });
+
+describe('AspectRatioPicker trigger', () => {
+ it('names the locked ratio by its saved name, built-in id or terms, and reads Free while unlocked', async () => {
+ await render({ lockedRatio: 2.39 });
+ await expect.element(trigger()).toHaveAccessibleName('Aspect ratio Cinema 2.39:1');
+ await act(() => root!.unmount());
+
+ await render({ lockedRatio: 16 / 9 });
+ await expect.element(trigger()).toHaveAccessibleName('Aspect ratio 16:9');
+ await act(() => root!.unmount());
+
+ // A locked ratio no saved ratio or built-in names reads as its terms, not as Free.
+ await render({ lockedRatio: 2.4 });
+ await expect.element(trigger()).toHaveAccessibleName('Aspect ratio 12:5');
+ await act(() => root!.unmount());
+
+ await render({ lockedRatio: null });
+ await expect.element(trigger()).toHaveAccessibleName('Aspect ratio Free');
+ });
+
+ it('prefers a saved ratio over the built-in it equals', async () => {
+ await render({ initial: [square], lockedRatio: 1 });
+
+ await expect.element(trigger()).toHaveAccessibleName('Aspect ratio Square 1:1');
+ });
+});
+
+describe('AspectRatioPicker choosing', () => {
+ it('moves through the ratio grid with the arrow keys, chooses with Enter, then closes back on the trigger', async () => {
+ const { onChange } = await render({ lockedRatio: 16 / 9 });
+
+ await openPicker();
+ // Opening lands on the current ratio.
+ await expect.element(page.getByRole('radio', { name: '16:9', exact: true })).toHaveFocus();
+
+ await userEvent.keyboard('{ArrowRight}');
+ await expect.element(page.getByRole('radio', { name: '3:2', exact: true })).toHaveFocus();
+ // Down a row of five: 3:2 sits above 9:16.
+ await userEvent.keyboard('{ArrowDown}');
+ await expect.element(page.getByRole('radio', { name: '9:16', exact: true })).toHaveFocus();
+ await userEvent.keyboard('{Home}');
+ await expect.element(page.getByRole('radio', { name: 'Free', exact: true })).toHaveFocus();
+ await userEvent.keyboard('{ArrowRight}{Enter}');
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(21 / 9);
+ await expect.poll(isOpen).toBe(false);
+ await expect.element(trigger()).toHaveFocus();
+ });
+
+ it('chooses a saved ratio from its row, which names its ratio and the size it sets', async () => {
+ const { onChange } = await render();
+
+ await openPicker();
+ // 1536×640 holds 983,040 pixels; at 2.39:1 that is 1532.8×641.3, snapped to 1536×640.
+ await userEvent.click(page.getByRole('button', { name: 'Cinema, 2.39:1, 1536×640' }));
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(2.39);
+ await expect.poll(isOpen).toBe(false);
+ });
+
+ it('chooses Free as null and leaves the current ratio alone when chosen again', async () => {
+ const { onChange } = await render({ lockedRatio: 1 });
+
+ await openPicker();
+ await userEvent.click(page.getByRole('radio', { name: '1:1', exact: true }));
+ expect(onChange).not.toHaveBeenCalled();
+
+ await openPicker();
+ await userEvent.click(page.getByRole('radio', { name: 'Free', exact: true }));
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(null);
+ });
+});
+
+describe('AspectRatioPicker current choice', () => {
+ it('checks the built-in a saved ratio equals, and choosing either only closes', async () => {
+ const { onChange } = await render({ initial: [square], lockedRatio: 1 });
+
+ await openPicker();
+ await expect.element(page.getByRole('radio', { exact: true, name: '1:1' })).toBeChecked();
+ await expect.element(page.getByRole('radio', { exact: true, name: 'Free' })).not.toBeChecked();
+ await userEvent.click(page.getByRole('radio', { exact: true, name: '1:1' }));
+ await expect.poll(isOpen).toBe(false);
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: /^Square, 1:1, / }));
+ await expect.poll(isOpen).toBe(false);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
+
+describe('AspectRatioPicker saved ratios', () => {
+ it('invites a first ratio while none are saved', async () => {
+ await render({ initial: [] });
+ await openPicker();
+
+ await expect.element(page.getByText('Name a ratio you use often to pick it here at any size.')).toBeVisible();
+ });
+
+ it.each([1280, 320])('fits an 18-character name with its ratio, size and visible actions at %ipx', async (width) => {
+ await page.viewport(width, 720);
+ // Current, so the name is bold: its widest form.
+ await render({
+ initial: [{ height: 1, id: 'insta', label: 'Instagram portrait', width: 2.39 }],
+ lockedRatio: 2.39,
+ });
+ await openPicker();
+
+ const row = page.getByRole('button', { name: 'Instagram portrait, 2.39:1, 1536×640' });
+ await row.hover();
+ await expect.element(page.getByRole('button', { name: 'Delete ratio Instagram portrait (2.39:1)' })).toBeVisible();
+ const name = row.getByText('Instagram portrait', { exact: true }).element() as HTMLElement;
+
+ await expect
+ .poll(() => getComputedStyle(page.getByRole('button', { name: /^Delete ratio/ }).element()).opacity)
+ .toBe('1');
+ await document.fonts.ready;
+ expect(name.scrollWidth).toBeLessThanOrEqual(name.clientWidth);
+ const bounds = dialog()!.getBoundingClientRect();
+ expect(bounds.left).toBeGreaterThanOrEqual(0);
+ expect(bounds.right).toBeLessThanOrEqual(width);
+ for (const text of ['2.39:1', '1536×640']) {
+ const element = row.getByText(text, { exact: true }).element() as HTMLElement;
+ expect(element.scrollWidth).toBeLessThanOrEqual(element.clientWidth);
+ expect(element.getBoundingClientRect().right).toBeLessThanOrEqual(row.element().getBoundingClientRect().right);
+ }
+ for (const action of ['Edit', 'Delete']) {
+ const element = page.getByRole('button', { name: `${action} ratio Instagram portrait (2.39:1)` }).element();
+ expect(element.getBoundingClientRect().left).toBeGreaterThanOrEqual(row.element().getBoundingClientRect().right);
+ expect(element.getBoundingClientRect().right).toBeLessThanOrEqual(bounds.right);
+ }
+ });
+
+ it('adds a ratio prefilled from the current size, with Enter, and focuses its new row', async () => {
+ const { onChange } = await render({ initial: [] });
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+
+ await expect.element(nameInput()).toHaveFocus();
+ await expect.element(widthTerm()).toHaveValue('12');
+ await expect.element(heightTerm()).toHaveValue('5');
+ await expect.element(widthTerm()).toHaveAccessibleDescription('Picking it sets 1536×640');
+
+ await userEvent.keyboard('Banner{Enter}');
+
+ const row = page.getByRole('button', { name: 'Banner, 12:5, 1536×640' });
+ await expect.element(row).toHaveFocus();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(isOpen()).toBe(true);
+ });
+
+ it('prefills a locked ratio, not the size snapped to it, and names the size the typed terms set', async () => {
+ // 1368×768 is exactly 57:32, the 16:9 lock snapped to the grid.
+ await render({ currentSize: { height: 768, width: 1368 }, initial: [], lockedRatio: 16 / 9 });
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+
+ await expect.element(widthTerm()).toHaveValue('16');
+ await expect.element(heightTerm()).toHaveValue('9');
+ await expect.element(page.getByText('Picking it sets 1368×768')).toBeVisible();
+
+ // 1368×768 at 2.39:1 is 1584.6×663.0, snapped to 1584×664.
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '2.39');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '1');
+ await expect.element(heightTerm()).toHaveAccessibleDescription('Picking it sets 1584×664');
+
+ // Terms that make no ratio leave the line blank and describe nothing.
+ await userEvent.clear(widthTerm());
+ await expect.element(page.getByText(/^Picking it sets/)).not.toBeInTheDocument();
+ await expect.element(heightTerm()).toHaveAccessibleDescription('');
+ });
+
+ it('keeps focus in the popover when a full list saves nothing', async () => {
+ await render({ savesNothing: true });
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.keyboard('Banner{Enter}');
+
+ await expect.element(page.getByRole('button', { name: 'Cinema, 2.39:1, 1536×640' })).toHaveFocus();
+ });
+
+ it('previews the ratio as its terms are typed, and a dashed square while they make none', async () => {
+ await render();
+ await openPicker();
+ const shape = (form: string) =>
+ page.getByRole('form', { name: form }).element().querySelector<HTMLElement>('[data-shape]')!;
+ const aspect = (form: string) => {
+ const rect = shape(form).getBoundingClientRect();
+ return rect.width / rect.height;
+ };
+
+ // Add starts from the current size, 1536×640 (12:5).
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.keyboard('Wide');
+ expect(aspect('Add ratio')).toBeCloseTo(2.4, 1);
+ expect(shape('Add ratio').getBoundingClientRect().width).toBeGreaterThan(60);
+ // Its framed well spans the name field and the terms row beside it.
+ const well = page.getByRole('form', { name: 'Add ratio' }).element().querySelector('[data-preview-well]')!;
+ const wellRect = well.getBoundingClientRect();
+ expect(wellRect.top).toBeLessThanOrEqual((nameInput().element() as HTMLElement).getBoundingClientRect().top);
+ expect(wellRect.bottom).toBeGreaterThanOrEqual(
+ (widthTerm().element() as HTMLElement).getBoundingClientRect().bottom
+ );
+ // A square well.
+ expect(wellRect.width).toBeCloseTo(wellRect.height, 0);
+ await expect.element(nameInput()).toHaveAttribute('placeholder', 'Ratio name');
+
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '4');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '5');
+ expect(aspect('Add ratio')).toBeCloseTo(0.8, 1);
+
+ // A comma decimal reads as a decimal.
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '2,39');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '1');
+ expect(aspect('Add ratio')).toBeCloseTo(2.39, 1);
+
+ const formHeight = page.getByRole('form', { name: 'Add ratio' }).element().getBoundingClientRect().height;
+ for (const invalid of ['0', '9']) {
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), invalid);
+ expect(shape('Add ratio').hasAttribute('data-placeholder')).toBe(true);
+ expect(getComputedStyle(shape('Add ratio')).borderStyle).toBe('dashed');
+ expect(aspect('Add ratio')).toBeCloseTo(1, 2);
+ }
+ // Neither the shape nor the terms error on submit changes the form's height.
+ await userEvent.click(page.getByRole('button', { name: 'Add', exact: true }));
+ await expect.element(page.getByText('Use a ratio between 1:8 and 8:1.')).toBeVisible();
+ expect(page.getByRole('form', { name: 'Add ratio' }).element().getBoundingClientRect().height).toBe(formHeight);
+
+ // Edit starts from the saved ratio.
+ await userEvent.keyboard('{Escape}');
+ await userEvent.click(page.getByRole('button', { name: 'Edit ratio Cinema (2.39:1)' }));
+ expect(aspect('Edit ratio')).toBeCloseTo(2.39, 1);
+ });
+
+ it('keeps the form open with inline errors for a missing name, a zero term and a ratio past 8:1', async () => {
+ await render({ initial: [] });
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '0');
+ await userEvent.click(page.getByRole('button', { name: 'Add', exact: true }));
+
+ await expect.element(page.getByText('Enter a name.')).toBeVisible();
+ await expect.element(page.getByText('Enter two numbers above 0.')).toBeVisible();
+ await expect.element(nameInput()).toHaveFocus();
+ // Only the zero is marked; the 5 beside it is fine.
+ await expect.element(widthTerm()).toBeInvalid();
+ await expect.element(heightTerm()).toBeValid();
+
+ await userEvent.type(nameInput(), 'Strip');
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '9');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '1');
+ await userEvent.keyboard('{Enter}');
+
+ await expect.element(page.getByText('Use a ratio between 1:8 and 8:1.')).toBeVisible();
+ await expect.element(page.getByText('Enter a name.')).not.toBeInTheDocument();
+ await expect.element(widthTerm()).toHaveFocus();
+ // The range is the pair's, so both terms are marked.
+ await expect.element(widthTerm()).toBeInvalid();
+ await expect.element(heightTerm()).toBeInvalid();
+ expect(page.getByRole('button', { name: /^Strip,/ }).elements()).toHaveLength(0);
+
+ // Only plain decimals read as terms, never what `Number` would also accept.
+ for (const unreadable of ['1e1', '0x10']) {
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), unreadable);
+ await expect.element(page.getByText('Enter two numbers above 0.')).toBeVisible();
+ await expect.element(heightTerm()).toBeValid();
+ }
+
+ // A third decimal is past the precision a term keeps; a comma is a decimal separator, never a thousands one.
+ for (const precise of ['1.234', '1,000']) {
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), precise);
+ await expect.element(page.getByText('Use up to two decimals.')).toBeVisible();
+ await expect.element(widthTerm()).toBeInvalid();
+ await expect.element(widthTerm()).toHaveAccessibleDescription('Use up to two decimals.');
+ await expect.element(heightTerm()).toBeValid();
+ await expect.element(heightTerm()).toHaveAccessibleDescription('');
+ }
+
+ // Submitting focuses the term that is wrong, here the second.
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '2');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '0.125');
+ await userEvent.click(page.getByRole('button', { name: 'Add', exact: true }));
+ await expect.element(heightTerm()).toHaveFocus();
+ await expect.element(widthTerm()).toBeValid();
+
+ // With a different error in each term, only the term the message is about is marked; the other's comes next.
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '0');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '1.234');
+ await expect.element(page.getByText('Enter two numbers above 0.')).toBeVisible();
+ await expect.element(widthTerm()).toBeInvalid();
+ await expect.element(heightTerm()).toBeValid();
+ await expect.element(heightTerm()).toHaveAccessibleDescription('');
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '2');
+ await expect.element(page.getByText('Use up to two decimals.')).toBeVisible();
+ await expect.element(widthTerm()).toBeValid();
+ await expect.element(heightTerm()).toBeInvalid();
+
+ // A trailing separator reads as the whole number.
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '1.');
+
+ // A comma decimal reads as a decimal.
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '2,5');
+ await userEvent.keyboard('{Enter}');
+
+ await expect.element(page.getByRole('button', { name: 'Strip, 2.5:1, 1568×624' })).toHaveFocus();
+ });
+
+ it('edits a row in place and saves the new name and ratio', async () => {
+ await render();
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Edit ratio Cinema (2.39:1)' }));
+ await expect.element(nameInput()).toHaveValue('Cinema');
+ await expect.element(widthTerm()).toHaveValue('2.39');
+ // The terms come from the saved ratio, so the hint names the size they set, as they change.
+ await expect.element(page.getByText('Picking it sets 1536×640')).toBeVisible();
+ await expect.element(page.getByText(/^From the current size/)).not.toBeInTheDocument();
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '4');
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '5');
+ // 1536×640 at 4:5 is 886.8×1108.5, snapped to 888×1112.
+ await expect.element(page.getByText('Picking it sets 888×1112')).toBeVisible();
+ await userEvent.clear(heightTerm());
+ await userEvent.type(heightTerm(), '1');
+
+ await userEvent.clear(nameInput());
+ await userEvent.type(nameInput(), 'Scope');
+ await userEvent.clear(widthTerm());
+ await userEvent.type(widthTerm(), '2.4');
+ await userEvent.click(page.getByRole('button', { name: 'Save', exact: true }));
+
+ await expect.element(page.getByRole('button', { name: 'Scope, 2.4:1, 1536×640' })).toHaveFocus();
+ });
+
+ it('moves focus to the next row Delete after a delete', async () => {
+ await render({ initial: [cinema, square] });
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Delete ratio Cinema (2.39:1)' }));
+
+ await expect.element(page.getByRole('button', { name: 'Delete ratio Square (1:1)' })).toHaveFocus();
+ });
+
+ it('deletes a row without asking and moves focus to Add ratio once none are left', async () => {
+ const { onChange, removed } = await render();
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Delete ratio Cinema (2.39:1)' }));
+
+ expect(removed).toEqual(['cinema']);
+ await expect.element(page.getByRole('button', { name: 'Add ratio' })).toHaveFocus();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(isOpen()).toBe(true);
+ });
+
+ it('cancels the form with Escape, keeping the popover open, and returns focus to the button that opened it', async () => {
+ await render();
+
+ await openPicker();
+ await userEvent.click(page.getByRole('button', { name: 'Edit ratio Cinema (2.39:1)' }));
+ await expect.element(nameInput()).toHaveFocus();
+ await userEvent.keyboard('{Escape}');
+
+ expect(isOpen()).toBe(true);
+ await expect.element(page.getByRole('button', { name: 'Edit ratio Cinema (2.39:1)' })).toHaveFocus();
+
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.keyboard('Discarded{Escape}');
+ await expect.element(page.getByRole('button', { name: 'Add ratio' })).toHaveFocus();
+ expect(page.getByRole('button', { name: /^Discarded,/ }).elements()).toHaveLength(0);
+
+ // With no form open, Escape closes the popover.
+ await userEvent.keyboard('{Escape}');
+ await expect.poll(isOpen).toBe(false);
+ await expect.element(trigger()).toHaveFocus();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPicker.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPicker.tsx
new file mode 100644
index 0000000000..b64c4b55cf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPicker.tsx
@@ -0,0 +1,748 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-jsx-as-prop */
+import type {
+ AspectRatioPreset,
+ AspectRatioPresetDraft,
+ AspectRatioPresetsPort,
+ AspectRatioTerms,
+} from '@features/generation/core/aspectRatioPresets';
+import type { AspectRatioId } from '@features/generation/core/types';
+import type { FormEvent, KeyboardEvent, ReactNode } from 'react';
+
+import {
+ Flex,
+ Grid,
+ HStack,
+ Icon,
+ Input,
+ Popover,
+ Portal,
+ Separator,
+ Stack,
+ Text,
+ type TextProps,
+} from '@chakra-ui/react';
+import {
+ formatAspectRatio,
+ formatAspectRatioTerms,
+ getAspectRatioPresetRatio,
+ getAspectRatioTerms,
+ getAspectRatioTermsError,
+ getLockedAspectRatioSettings,
+ matchAspectRatio,
+ MAX_ASPECT_RATIO_PRESET_LABEL_LENGTH,
+ MAX_ASPECT_RATIO_PRESETS,
+} from '@features/generation/core/aspectRatioPresets';
+import { ASPECT_RATIO_MAP, ASPECT_RATIO_OPTIONS } from '@features/generation/core/settings';
+import { Button, IconButton } from '@platform/ui/Button';
+import { PopoverContent } from '@platform/ui/Popover';
+import { Row } from '@platform/ui/Row';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { ClippedTooltip, Tooltip } from '@platform/ui/Tooltip';
+import { dropdownContent, dropdownGroupLabel, formControlInteraction } from '@theme/recipes';
+import { CheckIcon, ChevronDownIcon, LockIcon, LockOpenIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
+import { useCallback, useId, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AspectRatioPreview } from './AspectRatioPreview';
+
+type ControlSize = 'md' | 'lg';
+
+interface Size {
+ width: number;
+ height: number;
+}
+
+export interface AspectRatioPickerProps {
+ /** The live size: the Free thumbnail's shape and the Add ratio form's prefill. */
+ currentSize: Size;
+ /** The ratio the lock holds, or null while unlocked (Free). */
+ lockedRatio: number | null;
+ presets: AspectRatioPresetsPort;
+ /** The size choosing `ratio` would set, shown beside each saved ratio. */
+ getSizeForRatio: (ratio: number) => Size;
+ /** A ratio to lock, or null for Free. Not called for the ratio already chosen. */
+ onChange: (ratio: number | null) => void;
+}
+
+type FormSubject = { mode: 'add' } | { mode: 'edit'; preset: AspectRatioPreset };
+
+const POSITIONING = { placement: 'bottom-start' } as const;
+const GRID_COLUMNS = 5;
+// A gutter for the overlay scrollbar, which a long list would otherwise draw over the Delete column.
+const SAVED_LIST_CONTENT_PROPS = { pe: '2.5' } as const;
+// A literal of references, not a spread: a module-scope property read would make this barrel-exported module impure.
+const TRIGGER_CSS = [formControlInteraction, { _expanded: { borderColor: 'accent.solid' } }];
+const TILE_CSS = { flexDirection: 'column', gap: '0.5', justifyContent: 'center', px: '0.5', py: '1' } as const;
+/** Edit and delete stay in the tab order; they show on hover and whenever focus is in the row (or with no hover). */
+const PRESET_ROW_CSS = {
+ '& [data-row-action]': { opacity: 0, transitionDuration: 'fast', transitionProperty: 'opacity' },
+ '&:hover [data-row-action], &:focus-within [data-row-action]': { opacity: 1 },
+ '@media (hover: none)': { '& [data-row-action]': { opacity: 1 } },
+} as const;
+
+const formatSize = (size: Size): string => `${Math.round(size.width)}×${Math.round(size.height)}`;
+
+/** Text that truncates, with its whole text in a tooltip while it is cut short. */
+const ClippedText = ({ children, ...props }: TextProps & { children: string }) => {
+ const ref = useRef<HTMLParagraphElement>(null);
+ const isClipped = useCallback(() => !!ref.current && ref.current.scrollWidth > ref.current.clientWidth, []);
+
+ return (
+ <ClippedTooltip content={children} isClipped={isClipped}>
+ <Text ref={ref} as="span" minW="0" truncate {...props}>
+ {children}
+ </Text>
+ </ClippedTooltip>
+ );
+};
+
+/**
+ * Digits with decimals after either separator; a trailing separator (`5.`) reads as the whole number. Nothing else
+ * `Number` reads (`0x10`, `1e1`), and no thousands separator: `1,000` reads as a decimal with too many places.
+ */
+const TERM_PATTERN = /^\d*(?:[.,](\d*))?$/;
+/** The precision a term keeps: saved terms come back to the edit form at two decimals. */
+const MAX_TERM_DECIMALS = 2;
+
+type TermError = 'number' | 'decimals';
+
+/** A typed term above 0, or why it is not one: blank, unreadable or 0 (`number`), or too precise (`decimals`). */
+const readTerm = (value: string): number | TermError => {
+ const trimmed = value.trim();
+ const match = trimmed === '' ? null : TERM_PATTERN.exec(trimmed);
+ const term = match ? Number(trimmed.replace(',', '.')) : Number.NaN;
+
+ if (!match || !Number.isFinite(term) || term <= 0) {
+ return 'number';
+ }
+
+ return (match[1]?.length ?? 0) > MAX_TERM_DECIMALS ? 'decimals' : term;
+};
+
+/** Focus targets are keyed, so a control that mounts after the change that needs it can still take focus. */
+const useDeferredFocus = () => {
+ const pendingRef = useRef<string | null>(null);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+
+ const focus = useCallback((key: string) => {
+ const target = containerRef.current?.querySelector<HTMLElement>(`[data-focus-key="${CSS.escape(key)}"]`);
+
+ if (target) {
+ pendingRef.current = null;
+ target.focus();
+ } else {
+ pendingRef.current = key;
+ }
+ }, []);
+
+ // Stable, so React calls it only as a target mounts: the moment a pending focus can land on it.
+ const registerTarget = useCallback((element: HTMLElement | null) => {
+ if (element && element.dataset.focusKey === pendingRef.current) {
+ pendingRef.current = null;
+ element.focus();
+ }
+ }, []);
+
+ return { containerRef, focus, registerTarget };
+};
+
+type DeferredFocus = ReturnType<typeof useDeferredFocus>;
+
+const PresetForm = ({
+ getSizeForRatio,
+ registerFocusTarget,
+ initial,
+ submitLabel,
+ title,
+ onCancel,
+ onSubmit,
+}: {
+ /** Names the size the entered ratio would set, on the line under the terms while no error shows. */
+ getSizeForRatio: (ratio: number) => Size;
+ registerFocusTarget: DeferredFocus['registerTarget'];
+ initial: { label: string; terms: AspectRatioTerms };
+ submitLabel: string;
+ title: string;
+ onCancel: () => void;
+ onSubmit: (draft: AspectRatioPresetDraft) => void;
+}) => {
+ const { i18n, t } = useTranslation();
+ const nameErrorId = useId();
+ const termsErrorId = useId();
+ const hintId = useId();
+ const formatTerm = (term: number) =>
+ new Intl.NumberFormat(i18n.resolvedLanguage, { maximumFractionDigits: 2, useGrouping: false }).format(term);
+ const [label, setLabel] = useState(initial.label);
+ const [width, setWidth] = useState(() => formatTerm(initial.terms.width));
+ const [height, setHeight] = useState(() => formatTerm(initial.terms.height));
+ // Errors wait for the first submit, then follow every edit.
+ const [hasSubmitted, setHasSubmitted] = useState(false);
+ const nameError = label.trim() === '' ? t('widgets.generate.aspectRatioNameRequired') : null;
+ const widthTerm = readTerm(width);
+ const heightTerm = readTerm(height);
+ // Each term is checked on its own, so only the offending field is marked; the range is the pair's.
+ const termsErrorKind =
+ widthTerm === 'number' || heightTerm === 'number'
+ ? 'number'
+ : widthTerm === 'decimals' || heightTerm === 'decimals'
+ ? 'decimals'
+ : getAspectRatioTermsError(widthTerm, heightTerm);
+ const termsError =
+ termsErrorKind === 'decimals'
+ ? t('widgets.generate.aspectRatioTermDecimals')
+ : termsErrorKind === 'range'
+ ? t('widgets.generate.aspectRatioOutOfRange')
+ : termsErrorKind
+ ? t('widgets.generate.aspectRatioTermsInvalid')
+ : null;
+ // Follows the terms as they are typed; a dashed square until they make a ratio this build accepts.
+ const previewRatio = termsErrorKind === null ? (widthTerm as number) / (heightTerm as number) : null;
+ const showsTermsError = hasSubmitted && termsError !== null;
+ // Marked only where the shown message applies: a term with another error waits until this one is fixed.
+ const isTermInvalid = (term: number | TermError) =>
+ showsTermsError && (term === termsErrorKind || termsErrorKind === 'range');
+ const isWidthInvalid = isTermInvalid(widthTerm);
+ const isHeightInvalid = isTermInvalid(heightTerm);
+ const hintText =
+ previewRatio === null
+ ? ''
+ : t('widgets.generate.aspectRatioWouldSetSize', { size: formatSize(getSizeForRatio(previewRatio)) });
+ const describeTerm = (isInvalid: boolean) =>
+ isInvalid ? termsErrorId : !showsTermsError && hintText ? hintId : undefined;
+
+ const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ // The popover is portalled, so a submit would otherwise reach forms around the picker in the React tree.
+ event.stopPropagation();
+ setHasSubmitted(true);
+
+ if (nameError || termsError) {
+ // The name, else the first term the message is about; both are for a ratio out of range.
+ const target = nameError
+ ? '[data-focus-key="form-name"]'
+ : widthTerm === termsErrorKind || termsErrorKind === 'range'
+ ? '[data-term="width"]'
+ : '[data-term="height"]';
+
+ event.currentTarget.querySelector<HTMLElement>(target)?.focus();
+ return;
+ }
+
+ onSubmit({ height: heightTerm as number, label: label.trim(), width: widthTerm as number });
+ };
+
+ return (
+ <Stack asChild gap="2" py="1">
+ <form aria-label={title} noValidate onSubmit={handleSubmit}>
+ {/* A square preview well as tall as the fields beside it (name, terms and the line under them: 88px), at a fixed size
+ so a name error's extra line moves nothing sideways. The line under the terms always holds the hint or the
+ error, so neither the shape nor a terms error changes the form's height. */}
+ <HStack alignItems="flex-start" gap="2">
+ <Flex
+ alignItems="center"
+ borderColor="border.muted"
+ borderWidth="1px"
+ boxSize="5.5rem"
+ data-preview-well=""
+ flexShrink={0}
+ justifyContent="center"
+ p="1.5"
+ rounded="l2"
+ >
+ <AspectRatioPreview boxSize="full" ratio={previewRatio} />
+ </Flex>
+ <Stack flex="1" gap="2" minW="0">
+ <Stack gap="1">
+ <Input
+ ref={registerFocusTarget}
+ aria-describedby={hasSubmitted && nameError ? nameErrorId : undefined}
+ aria-invalid={(hasSubmitted && nameError !== null) || undefined}
+ aria-label={t('widgets.generate.aspectRatioName')}
+ autoComplete="off"
+ data-focus-key="form-name"
+ maxLength={MAX_ASPECT_RATIO_PRESET_LABEL_LENGTH}
+ placeholder={t('widgets.generate.aspectRatioName')}
+ value={label}
+ onChange={(event) => setLabel(event.currentTarget.value)}
+ />
+ {hasSubmitted && nameError ? (
+ <Text color="fg.error" fontSize="xs" id={nameErrorId} role="alert">
+ {nameError}
+ </Text>
+ ) : null}
+ </Stack>
+ <Stack gap="1">
+ <HStack alignItems="center" gap="1.5">
+ <Input
+ aria-describedby={describeTerm(isWidthInvalid)}
+ aria-invalid={isWidthInvalid || undefined}
+ aria-label={t('widgets.generate.aspectRatioWidthTerm')}
+ data-term="width"
+ flex="1"
+ inputMode="decimal"
+ minW="0"
+ textAlign="end"
+ value={width}
+ onChange={(event) => setWidth(event.currentTarget.value)}
+ />
+ <Text aria-hidden color="fg.muted" fontSize="md">
+ :
+ </Text>
+ <Input
+ aria-describedby={describeTerm(isHeightInvalid)}
+ aria-invalid={isHeightInvalid || undefined}
+ aria-label={t('widgets.generate.aspectRatioHeightTerm')}
+ data-term="height"
+ flex="1"
+ inputMode="decimal"
+ minW="0"
+ value={height}
+ onChange={(event) => setHeight(event.currentTarget.value)}
+ />
+ </HStack>
+ {showsTermsError ? (
+ <Text color="fg.error" fontSize="xs" id={termsErrorId} role="alert">
+ {termsError}
+ </Text>
+ ) : (
+ // A blank line keeps its height while the terms make no ratio to describe.
+ <Text color="fg.muted" fontSize="xs" id={hintId} minH="1lh">
+ {hintText}
+ </Text>
+ )}
+ </Stack>
+ </Stack>
+ </HStack>
+ <HStack gap="1.5" justifyContent="end">
+ <Button type="button" variant="ghost" onClick={onCancel}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit">{submitLabel}</Button>
+ </HStack>
+ </form>
+ </Stack>
+ );
+};
+
+const PresetRow = ({
+ registerFocusTarget,
+ isCurrent,
+ preset,
+ ratioText,
+ sizeText,
+ onChoose,
+ onDelete,
+ onEdit,
+}: {
+ registerFocusTarget: DeferredFocus['registerTarget'];
+ isCurrent: boolean;
+ preset: AspectRatioPreset;
+ ratioText: string;
+ sizeText: string;
+ onChoose: () => void;
+ onDelete: () => void;
+ onEdit: () => void;
+}) => {
+ const { t } = useTranslation();
+ const names = { name: preset.label, ratio: ratioText };
+
+ return (
+ <HStack css={PRESET_ROW_CSS} gap="0.5">
+ <Row active={isCurrent ? 'emphasized' : 'none'} asChild flex="1" gap="1.5" minH="10" minW="0" px="1.5" py="1">
+ <button
+ ref={registerFocusTarget}
+ data-focus-key={`choose:${preset.id}`}
+ aria-current={isCurrent || undefined}
+ aria-label={t('widgets.generate.aspectRatioPresetOption', { ...names, size: sizeText })}
+ data-picker-current={isCurrent || undefined}
+ type="button"
+ onClick={onChoose}
+ >
+ <AspectRatioPreview boxSize="5" ratio={getAspectRatioPresetRatio(preset)} />
+ <Stack as="span" flex="1" gap="0" minW="0" textAlign="start">
+ <ClippedText fontWeight={isCurrent ? '600' : undefined} textStyle="md">
+ {preset.label}
+ </ClippedText>
+ <HStack as="span" gap="1.5" fontVariantNumeric="tabular-nums" textStyle="sm">
+ <Text as="span" color="fg.muted" flexShrink={0}>
+ {ratioText}
+ </Text>
+ <Text as="span" color="fg.subtle" flexShrink={0}>
+ {sizeText}
+ </Text>
+ </HStack>
+ </Stack>
+ <Icon as={CheckIcon} aria-hidden boxSize="3" color="accent.fg" flexShrink={0} opacity={isCurrent ? 1 : 0} />
+ </button>
+ </Row>
+ <IconButton
+ ref={registerFocusTarget}
+ data-focus-key={`edit:${preset.id}`}
+ aria-label={t('widgets.generate.aspectRatioEditNamed', names)}
+ data-row-action=""
+ tooltip={t('widgets.generate.aspectRatioEdit')}
+ variant="ghost"
+ onClick={onEdit}
+ >
+ <PencilIcon />
+ </IconButton>
+ <IconButton
+ ref={registerFocusTarget}
+ data-focus-key={`delete:${preset.id}`}
+ aria-label={t('widgets.generate.aspectRatioDeleteNamed', names)}
+ colorPalette="red"
+ data-row-action=""
+ tooltip={t('common.delete')}
+ variant="ghost"
+ onClick={onDelete}
+ >
+ <Trash2Icon />
+ </IconButton>
+ </HStack>
+ );
+};
+
+const GroupLabel = ({ children, id }: { children: ReactNode; id: string }) => (
+ <Text css={dropdownGroupLabel} id={id} px="1">
+ {children}
+ </Text>
+);
+
+/**
+ * The aspect ratio control: built-in ratios as a grid of shapes, the account's saved ratios as rows, and an inline
+ * form to add or edit one. Choosing applies at once and closes; callers own what a ratio does to the size.
+ */
+export const AspectRatioPicker = ({
+ currentSize,
+ getSizeForRatio,
+ lockedRatio,
+ presets,
+ onChange,
+}: AspectRatioPickerProps) => {
+ const { i18n, t } = useTranslation();
+ const locale = i18n.resolvedLanguage;
+ const [isOpen, setIsOpen] = useState(false);
+ const [form, setForm] = useState<FormSubject | null>(null);
+ const { containerRef, focus: focusKey, registerTarget } = useDeferredFocus();
+ const labelId = useId();
+ const valueId = useId();
+ const builtInsId = useId();
+ const savedId = useId();
+ const tileRefs = useRef<(HTMLButtonElement | null)[]>([]);
+
+ const currentRatio = currentSize.height > 0 ? currentSize.width / currentSize.height : 1;
+ const match = lockedRatio === null ? null : matchAspectRatio(lockedRatio, presets.presets);
+ const builtIns = ASPECT_RATIO_OPTIONS.map((id) => ({ id, ratio: id === 'Free' ? null : ASPECT_RATIO_MAP[id].ratio }));
+ // The built-in equal to the locked ratio is current even while a saved ratio names it, so choosing either closes.
+ const lockedBuiltInId = lockedRatio === null ? 'Free' : getLockedAspectRatioSettings(lockedRatio).aspectRatioId;
+ const currentTileIndex =
+ lockedRatio === null
+ ? 0
+ : lockedBuiltInId === 'Free'
+ ? -1
+ : builtIns.findIndex((tile) => tile.id === lockedBuiltInId);
+ const currentPresetId = match?.kind === 'preset' ? match.preset.id : null;
+ const [focusedTile, setFocusedTile] = useState(Math.max(currentTileIndex, 0));
+
+ const formatPresetRatio = (preset: AspectRatioTerms) => formatAspectRatioTerms(preset, locale);
+ const freeLabel = t('widgets.generate.aspectRatioFree');
+ const tileLabel = (id: AspectRatioId) => (id === 'Free' ? freeLabel : id);
+
+ const valueText =
+ match?.kind === 'preset' ? (
+ <>
+ <ClippedText>{match.preset.label}</ClippedText>{' '}
+ <Text as="span" color="fg.muted" flexShrink={0}>
+ {formatPresetRatio(match.preset)}
+ </Text>
+ </>
+ ) : (
+ <Text as="span" minW="0" truncate>
+ {match?.kind === 'builtin'
+ ? match.id
+ : lockedRatio !== null
+ ? formatAspectRatio(lockedRatio, locale)
+ : freeLabel}
+ </Text>
+ );
+
+ const handleOpenChange = ({ open }: { open: boolean }) => {
+ setIsOpen(open);
+
+ if (!open) {
+ setForm(null);
+ } else {
+ setFocusedTile(Math.max(currentTileIndex, 0));
+ }
+ };
+
+ const choose = (ratio: number | null, isCurrent: boolean) => {
+ if (!isCurrent) {
+ onChange(ratio);
+ }
+
+ setIsOpen(false);
+ setForm(null);
+ };
+
+ const openForm = (subject: FormSubject) => {
+ setForm(subject);
+ focusKey('form-name');
+ };
+
+ const closeForm = () => {
+ if (!form) {
+ return;
+ }
+
+ setForm(null);
+ focusKey(form.mode === 'edit' ? `edit:${form.preset.id}` : 'add');
+ };
+
+ const submitForm = (draft: AspectRatioPresetDraft) => {
+ if (form?.mode === 'edit') {
+ presets.update(form.preset.id, draft);
+ setForm(null);
+ focusKey(`choose:${form.preset.id}`);
+ return;
+ }
+
+ const saved = presets.save(draft);
+ // A full list saves nothing and shows no Add button; focus goes to its last row instead.
+ const last = presets.presets.at(-1);
+
+ setForm(null);
+ focusKey(saved ? `choose:${saved.id}` : last ? `choose:${last.id}` : 'add');
+ };
+
+ // Deleting is undoable (the port reports it with Undo), so it asks nothing. Focus moves to the next row's delete,
+ // the previous one's after the last row, or Add ratio once none are left.
+ const deletePreset = (preset: AspectRatioPreset) => {
+ const index = presets.presets.findIndex((candidate) => candidate.id === preset.id);
+ const neighbour = presets.presets[index + 1] ?? presets.presets[index - 1];
+
+ focusKey(neighbour ? `delete:${neighbour.id}` : 'add');
+ presets.remove(preset.id);
+ };
+
+ const handleTileKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const last = builtIns.length - 1;
+ const moves: Record<string, number> = {
+ ArrowDown: Math.min(focusedTile + GRID_COLUMNS, last),
+ ArrowLeft: Math.max(focusedTile - 1, 0),
+ ArrowRight: Math.min(focusedTile + 1, last),
+ ArrowUp: Math.max(focusedTile - GRID_COLUMNS, 0),
+ End: last,
+ Home: 0,
+ };
+ const next = moves[event.key];
+
+ if (next === undefined) {
+ return;
+ }
+
+ event.preventDefault();
+ setFocusedTile(next);
+ tileRefs.current[next]?.focus();
+ };
+
+ const getInitialFocus = () =>
+ containerRef.current?.querySelector<HTMLElement>('[data-focus-key][data-picker-current]') ??
+ containerRef.current?.querySelector<HTMLElement>('[data-picker-current]') ??
+ tileRefs.current[0] ??
+ null;
+
+ // A new ratio starts from the locked ratio (a snapped size is only close to it), else from the size itself.
+ const addTerms = getAspectRatioTerms(lockedRatio ?? currentRatio);
+
+ const formFor = (subject: FormSubject) =>
+ subject.mode === 'edit' ? (
+ <PresetForm
+ key={subject.preset.id}
+ getSizeForRatio={getSizeForRatio}
+ registerFocusTarget={registerTarget}
+ initial={{ label: subject.preset.label, terms: subject.preset }}
+ submitLabel={t('common.save')}
+ title={t('widgets.generate.aspectRatioEdit')}
+ onCancel={closeForm}
+ onSubmit={submitForm}
+ />
+ ) : (
+ <PresetForm
+ getSizeForRatio={getSizeForRatio}
+ registerFocusTarget={registerTarget}
+ initial={{ label: '', terms: addTerms }}
+ submitLabel={t('common.add')}
+ title={t('widgets.generate.aspectRatioAdd')}
+ onCancel={closeForm}
+ onSubmit={submitForm}
+ />
+ );
+
+ return (
+ <Popover.Root
+ initialFocusEl={getInitialFocus}
+ lazyMount
+ open={isOpen}
+ positioning={POSITIONING}
+ unmountOnExit
+ // Escape inside the form cancels the form, not the popover.
+ onEscapeKeyDown={(event) => {
+ if (form) {
+ event.preventDefault();
+ closeForm();
+ }
+ }}
+ onOpenChange={handleOpenChange}
+ >
+ <Text hidden id={labelId}>
+ {t('widgets.generate.aspectRatio')}
+ </Text>
+ <Popover.Trigger asChild>
+ <Button
+ aria-labelledby={`${labelId} ${valueId}`}
+ css={TRIGGER_CSS}
+ flex="1"
+ justifyContent="space-between"
+ minW="0"
+ px="2"
+ variant="outline"
+ w="full"
+ >
+ <HStack as="span" gap="2" id={valueId} minW="0">
+ <AspectRatioPreview boxSize="5" ratio={lockedRatio ?? currentRatio} />
+ {valueText}
+ </HStack>
+ <Icon as={ChevronDownIcon} aria-hidden boxSize="3" color="fg.muted" flexShrink={0} />
+ </Button>
+ </Popover.Trigger>
+ <Portal>
+ <Popover.Positioner>
+ <PopoverContent
+ ref={containerRef}
+ aria-labelledby={labelId}
+ css={dropdownContent}
+ maxW="calc(100vw - 1rem)"
+ p="0"
+ showArrow={false}
+ w="21.5rem"
+ >
+ <Popover.Body p="1.5">
+ <Stack gap="1.5">
+ <GroupLabel id={builtInsId}>{t('widgets.generate.aspectRatioBuiltIns')}</GroupLabel>
+ <Grid
+ aria-labelledby={builtInsId}
+ gap="0.5"
+ role="radiogroup"
+ templateColumns={`repeat(${GRID_COLUMNS}, minmax(0, 1fr))`}
+ onKeyDown={handleTileKeyDown}
+ >
+ {builtIns.map((tile, index) => {
+ const isCurrent = index === currentTileIndex;
+
+ return (
+ <Row key={tile.id} active={isCurrent ? 'emphasized' : 'none'} asChild css={TILE_CSS}>
+ <button
+ ref={(element) => {
+ tileRefs.current[index] = element;
+ }}
+ aria-checked={isCurrent}
+ data-picker-current={isCurrent || undefined}
+ // Arrows move focus without choosing; Enter or Space chooses and closes.
+ role="radio"
+ tabIndex={index === focusedTile ? 0 : -1}
+ type="button"
+ onClick={() => choose(tile.ratio, isCurrent)}
+ onFocus={() => setFocusedTile(index)}
+ >
+ <AspectRatioPreview boxSize="6" ratio={tile.ratio ?? currentRatio} />
+ <Text
+ as="span"
+ color={isCurrent ? 'fg' : 'fg.muted'}
+ fontSize="xs"
+ fontVariantNumeric="tabular-nums"
+ fontWeight={isCurrent ? '600' : undefined}
+ >
+ {tileLabel(tile.id)}
+ </Text>
+ </button>
+ </Row>
+ );
+ })}
+ </Grid>
+ <Separator borderColor="border.subtle" />
+ <GroupLabel id={savedId}>{t('widgets.generate.aspectRatioYourRatios')}</GroupLabel>
+ {presets.presets.length === 0 && form?.mode !== 'add' ? (
+ <Text color="fg.subtle" fontSize="sm" px="1">
+ {t('widgets.generate.aspectRatioYourRatiosEmpty')}
+ </Text>
+ ) : presets.presets.length > 0 ? (
+ <Scrollable contentProps={SAVED_LIST_CONTENT_PROPS} maxH="12rem">
+ <Stack aria-labelledby={savedId} gap="0.5" role="group">
+ {presets.presets.map((preset) =>
+ form?.mode === 'edit' && form.preset.id === preset.id ? (
+ formFor(form)
+ ) : (
+ <PresetRow
+ key={preset.id}
+ registerFocusTarget={registerTarget}
+ isCurrent={preset.id === currentPresetId}
+ preset={preset}
+ ratioText={formatPresetRatio(preset)}
+ sizeText={formatSize(getSizeForRatio(getAspectRatioPresetRatio(preset)))}
+ onChoose={() => choose(getAspectRatioPresetRatio(preset), preset.id === currentPresetId)}
+ onDelete={() => deletePreset(preset)}
+ onEdit={() => openForm({ mode: 'edit', preset })}
+ />
+ )
+ )}
+ </Stack>
+ </Scrollable>
+ ) : null}
+ {form?.mode === 'add' ? (
+ formFor(form)
+ ) : presets.isFull ? (
+ <Text color="fg.subtle" fontSize="sm" px="1">
+ {t('widgets.generate.aspectRatioListFull', { count: MAX_ASPECT_RATIO_PRESETS })}
+ </Text>
+ ) : (
+ <Button
+ ref={registerTarget}
+ data-focus-key="add"
+ justifyContent="start"
+ px="1.5"
+ variant="ghost"
+ onClick={() => openForm({ mode: 'add' })}
+ >
+ <PlusIcon />
+ {t('widgets.generate.aspectRatioAdd')}
+ </Button>
+ )}
+ </Stack>
+ </Popover.Body>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
+
+export interface AspectRatioLockButtonProps {
+ isLocked: boolean;
+ size?: 'sm' | ControlSize;
+ onToggle: () => void;
+}
+
+/** Companion lock for {@link AspectRatioPicker}: a labelled icon button, not a bare dot. */
+export const AspectRatioLockButton = ({ isLocked, size = 'md', onToggle }: AspectRatioLockButtonProps) => {
+ const { t } = useTranslation();
+ const label = isLocked ? t('widgets.generate.unlockAspectRatio') : t('widgets.generate.lockAspectRatio');
+
+ return (
+ <Tooltip content={label}>
+ <IconButton aria-label={label} size={size} variant={isLocked ? 'solid' : 'outline'} onClick={onToggle}>
+ {isLocked ? <LockIcon /> : <LockOpenIcon />}
+ </IconButton>
+ </Tooltip>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPreview.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPreview.tsx
index ee688186b9..d2d0904c13 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPreview.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPreview.tsx
@@ -1,22 +1,27 @@
import { Box, Flex } from '@chakra-ui/react';
type Props = {
- ratio: number; // e.g. 16 / 9
+ /** Width over height, e.g. 16 / 9; null draws a dashed square standing in for a ratio not yet valid. */
+ ratio: number | null;
boxSize?: string | number;
};
+/** A ratio's shape, fitted inside a square; decorative, since its ratio is always named beside it. */
export const AspectRatioPreview = ({ boxSize = '8', ratio }: Props) => {
- const normalizedRatio = Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
+ const isPlaceholder = ratio === null || !Number.isFinite(ratio) || ratio <= 0;
+ const normalizedRatio = isPlaceholder ? 1 : ratio;
const isWide = normalizedRatio >= 1;
return (
- <Flex as="span" alignItems="center" boxSize={boxSize} flexShrink={0} justifyContent="center" p="0.5">
+ <Flex aria-hidden as="span" alignItems="center" boxSize={boxSize} flexShrink={0} justifyContent="center" p="0.5">
<Box
as="span"
- aria-hidden="true"
- bg="bg.subtle"
- borderColor="fg.muted"
+ bg={isPlaceholder ? 'transparent' : 'bg.subtle'}
+ borderColor={isPlaceholder ? 'border.emphasized' : 'fg.muted'}
+ borderStyle={isPlaceholder ? 'dashed' : 'solid'}
borderWidth="1px"
+ data-placeholder={isPlaceholder || undefined}
+ data-shape=""
display="block"
h={isWide ? `${100 / normalizedRatio}%` : 'full'}
minH="1px"
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsx
deleted file mode 100644
index 8ca0f1abb6..0000000000
--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-/* eslint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-object-as-prop */
-import type { SelectTriggerProps, SelectValueChangeDetails } from '@chakra-ui/react';
-import type { AspectRatioId } from '@features/generation/core/types';
-
-import { createListCollection, HStack, Text } from '@chakra-ui/react';
-import { ASPECT_RATIO_MAP, ASPECT_RATIO_OPTIONS, isAspectRatioId } from '@features/generation/core/settings';
-import { IconButton, Select, Tooltip } from '@platform/ui';
-import { LockIcon, LockOpenIcon } from 'lucide-react';
-import { useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { AspectRatioPreview } from './AspectRatioPreview';
-
-type ControlSize = 'md' | 'lg';
-
-type AspectRatioOption = { id: AspectRatioId; ratio: number };
-
-const SELECT_CONTENT_PROPS = { maxH: '18rem' } as const;
-
-/** `Free` has no fixed ratio, so its thumbnail mirrors whatever the caller is currently showing. */
-const getAspectRatioOptionRatio = (id: AspectRatioId, fallbackRatio: number): number =>
- id === 'Free' ? fallbackRatio : ASPECT_RATIO_MAP[id].ratio;
-
-export interface AspectRatioSelectProps {
- /** Ratio used to draw the `Free` thumbnail — normally the live width/height. */
- fallbackRatio: number;
- size?: ControlSize;
- triggerProps?: SelectTriggerProps;
- value: AspectRatioId;
- onChange: (id: AspectRatioId) => void;
-}
-
-/** Callers own dimension changes. */
-export const AspectRatioSelect = ({
- fallbackRatio,
- size = 'md',
- triggerProps,
- value,
- onChange,
-}: AspectRatioSelectProps) => {
- const { t } = useTranslation();
- const options = useMemo<AspectRatioOption[]>(
- () => ASPECT_RATIO_OPTIONS.map((id) => ({ id, ratio: getAspectRatioOptionRatio(id, fallbackRatio) })),
- [fallbackRatio]
- );
- const collection = useMemo(
- () =>
- createListCollection({
- itemToString: (item: AspectRatioOption) => item.id,
- itemToValue: (item: AspectRatioOption) => item.id,
- items: options,
- }),
- [options]
- );
- const activePreviewRatio = getAspectRatioOptionRatio(value, fallbackRatio);
- const selectValue = useMemo(() => [value], [value]);
-
- const handleValueChange = ({ value: next }: SelectValueChangeDetails<AspectRatioOption>) => {
- const id = next[0];
-
- if (isAspectRatioId(id)) {
- onChange(id);
- }
- };
-
- return (
- <Select
- aria-label={t('widgets.generate.aspectRatio')}
- collection={collection}
- contentProps={SELECT_CONTENT_PROPS}
- flex="1"
- renderItem={(option) => (
- <HStack as="span" gap="2">
- <AspectRatioPreview boxSize="6" ratio={option.ratio} />
- <Text as="span">{option.id}</Text>
- </HStack>
- )}
- size={size}
- triggerProps={triggerProps}
- value={selectValue}
- valueText={
- <HStack as="span" gap="2" minW="0">
- <AspectRatioPreview boxSize="5" ratio={activePreviewRatio} />
- <Text as="span" truncate>
- {value}
- </Text>
- </HStack>
- }
- onValueChange={handleValueChange}
- />
- );
-};
-
-export interface AspectRatioLockButtonProps {
- isLocked: boolean;
- size?: 'sm' | ControlSize;
- onToggle: () => void;
-}
-
-/** Companion lock for {@link AspectRatioSelect}: a labelled icon button, not a bare dot. */
-export const AspectRatioLockButton = ({ isLocked, size = 'md', onToggle }: AspectRatioLockButtonProps) => {
- const { t } = useTranslation();
- const label = isLocked ? t('widgets.generate.unlockAspectRatio') : t('widgets.generate.lockAspectRatio');
-
- return (
- <Tooltip content={label}>
- <IconButton aria-label={label} size={size} variant={isLocked ? 'solid' : 'outline'} onClick={onToggle}>
- {isLocked ? <LockIcon /> : <LockOpenIcon />}
- </IconButton>
- </Tooltip>
- );
-};
diff --git a/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx
index 682bb336b0..9080e94c7f 100644
--- a/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx
@@ -3,10 +3,11 @@ import { system } from '@theme/system';
import { CameraIcon } from 'lucide-react';
import { act, useCallback, useRef, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, expect, it } from 'vitest';
+import { afterEach, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
import { Toolbar, ToolbarButton } from './Toolbar';
-import { ClippedTooltip } from './Tooltip';
+import { ClippedTooltip, Tooltip } from './Tooltip';
let host: HTMLDivElement | null = null;
let root: Root | null = null;
@@ -134,3 +135,39 @@ it('shows a clipped name on keyboard focus and nothing for a name that fits', as
});
expect(openTooltipText()).toBeUndefined();
});
+
+it('lets a click through an open tip to the control under it, such as the next row of a dense list', async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ const onNextClick = vi.fn();
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <div style={{ display: 'grid', gap: '2px', left: '200px', position: 'absolute', top: '200px' }}>
+ <Tooltip content="Delete" openDelay={0} placement="bottom">
+ <button style={{ height: '28px', width: '28px' }} type="button">
+ A
+ </button>
+ </Tooltip>
+ <button aria-label="Next" style={{ height: '28px', width: '28px' }} type="button" onClick={onNextClick}>
+ B
+ </button>
+ </div>
+ </ChakraProvider>
+ )
+ );
+ const [first, next] = host.querySelectorAll('button');
+
+ await focusWithKeyboard(first!);
+ await expect.poll(openTooltipText).toBe('Delete');
+ const target = next!.getBoundingClientRect();
+ const centre = target.top + target.height / 2;
+ const tip = () => document.querySelector('[role="tooltip"][data-state="open"]')!.getBoundingClientRect();
+ // Once placed, the tip covers the next button's centre: the case this guards.
+ await expect.poll(() => tip().top < centre && tip().bottom > centre).toBe(true);
+
+ await userEvent.click(next!);
+
+ expect(onNextClick).toHaveBeenCalledOnce();
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
index 5122080c6b..1e931896a8 100644
--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
@@ -61,6 +61,10 @@ export const tooltipSlotRecipe = defineSlotRecipe({
// would fade out. Default off-screen, as Zag does for a positioner with no placement.
'--x': '0px',
'--y': '-100vh',
+ // Zag lets the pointer through a non-interactive tip's content but not its positioner, the box around it: an open
+ // tip over a neighbouring control (the next row's button in a dense list) would take that control's click.
+ // Interactive content sets its own `pointer-events: auto`, which this does not override.
+ pointerEvents: 'none',
},
},
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 6542091d4d..99b6dd9191 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -952,7 +952,7 @@ export {
type InpaintMaskMergeEligibility,
} from './document/mergeVisible';
export { documentToExportLocalSamPoint } from './samCoordinates';
-export { bboxEquals, constrainBboxToRatio, roundBbox } from './tools/bboxHitTest';
+export { bboxEquals, bboxMinSize, roundBbox } from './tools/bboxHitTest';
export { isEmpty, union } from './math/rect';
export { ZOOM_PRESETS } from './math/snapping';
export { isLeafPixelEditEligible } from './editing/controlPixelEdit';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts
index 592b0f5bb2..4c153306ba 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts
@@ -2,16 +2,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { describe, expect, it } from 'vitest';
-import {
- clampZoom,
- constrainAspect,
- snapMovedPoint,
- snapRectToGrid,
- snapToGrid,
- ZOOM_MAX,
- ZOOM_MIN,
- ZOOM_PRESETS,
-} from './snapping';
+import { clampZoom, snapMovedPoint, snapRectToGrid, snapToGrid, ZOOM_MAX, ZOOM_MIN, ZOOM_PRESETS } from './snapping';
describe('ZOOM_PRESETS', () => {
it('exports the default candidates as a stable list', () => {
@@ -83,48 +74,3 @@ describe('snapRectToGrid', () => {
expect(snapRectToGrid(r, 16)).toEqual(r);
});
});
-
-describe('constrainAspect', () => {
- const square: Rect = { x: 10, y: 10, width: 20, height: 20 };
-
- it('keeps the nw corner fixed', () => {
- const result = constrainAspect(square, 2, 'nw');
- expect(result).toEqual({ x: 10, y: 10, width: 40, height: 20 });
- });
-
- it('keeps the ne corner fixed', () => {
- const result = constrainAspect(square, 2, 'ne');
- // right edge (30) stays fixed, width grows to 40, so x = 30 - 40 = -10
- expect(result).toEqual({ x: -10, y: 10, width: 40, height: 20 });
- });
-
- it('keeps the sw corner fixed', () => {
- const result = constrainAspect(square, 0.5, 'sw');
- // Keep width 20 and bottom edge 30; aspect 0.5 requires height 40.
- expect(result).toEqual({ x: 10, y: -10, width: 20, height: 40 });
- });
-
- it('keeps the se corner fixed', () => {
- const result = constrainAspect(square, 2, 'se');
- expect(result).toEqual({ x: -10, y: 10, width: 40, height: 20 });
- });
-
- it('keeps the center fixed', () => {
- const result = constrainAspect(square, 2, 'center');
- expect(result).toEqual({ x: 0, y: 10, width: 40, height: 20 });
- });
-
- it('is a no-op-ish passthrough for a non-positive aspect or empty rect', () => {
- expect(constrainAspect(square, 0, 'nw')).toEqual(square);
- expect(constrainAspect(square, -1, 'nw')).toEqual(square);
- const empty: Rect = { x: 0, y: 0, width: 0, height: 10 };
- expect(constrainAspect(empty, 2, 'nw')).toEqual(empty);
- });
-
- it('leaves an already-matching aspect rect unchanged in size', () => {
- const wide: Rect = { x: 0, y: 0, width: 40, height: 20 };
- const result = constrainAspect(wide, 2, 'center');
- expect(result.width).toBeCloseTo(40, 8);
- expect(result.height).toBeCloseTo(20, 8);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts
index 5c972cc54f..4a0823a713 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts
@@ -38,46 +38,5 @@ export const snapRectToGrid = (rect: Rect, grid: number): Rect => {
return { x, y, width: right - x, height: bottom - y };
};
-/** The corner or center kept fixed when `constrainAspect` resizes a rect. */
-export type AspectAnchor = 'nw' | 'ne' | 'sw' | 'se' | 'center';
-
-/** Resizes to width/height aspect while keeping the named anchor fixed. */
-export const constrainAspect = (rect: Rect, aspect: number, anchor: AspectAnchor): Rect => {
- if (aspect <= 0 || rect.width <= 0 || rect.height <= 0) {
- return rect;
- }
-
- const currentAspect = rect.width / rect.height;
- let width: number;
- let height: number;
-
- if (currentAspect > aspect) {
- // Too wide for the target aspect: keep width, shrink/grow height to match.
- width = rect.width;
- height = width / aspect;
- } else {
- // Too tall (or exact): keep height, shrink/grow width to match.
- height = rect.height;
- width = height * aspect;
- }
-
- const left = rect.x;
- const top = rect.y;
- const right = rect.x + rect.width;
- const bottom = rect.y + rect.height;
- const centerX = rect.x + rect.width / 2;
- const centerY = rect.y + rect.height / 2;
-
- switch (anchor) {
- case 'nw':
- return { x: left, y: top, width, height };
- case 'ne':
- return { x: right - width, y: top, width, height };
- case 'sw':
- return { x: left, y: bottom - height, width, height };
- case 'se':
- return { x: right - width, y: bottom - height, width, height };
- case 'center':
- return { x: centerX - width / 2, y: centerY - height / 2, width, height };
- }
-};
+/** The corner a corner-handle resize keeps fixed. */
+export type AspectAnchor = 'nw' | 'ne' | 'sw' | 'se';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts
index 2f2dab39bb..057e91b14b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts
@@ -11,7 +11,6 @@ import {
bboxHandleAt,
bboxHandlePoint,
bboxTargetAt,
- constrainBboxToRatio,
isInsideRect,
moveBbox,
resizeBbox,
@@ -409,17 +408,6 @@ describe('moveBbox', () => {
});
});
-describe('constrainBboxToRatio', () => {
- it('re-fits to the ratio around the center and snaps the width', () => {
- const out = constrainBboxToRatio(rect(0, 0, 100, 100), 2, 8);
- expect(out.width / out.height).toBeCloseTo(2, 5);
- expect(out.width % 8).toBe(0);
- // Center preserved.
- expect(out.x + out.width / 2).toBeCloseTo(50, 5);
- expect(out.y + out.height / 2).toBeCloseTo(50, 5);
- });
-});
-
describe('roundBbox / bboxEquals', () => {
it('rounds to integer document px with a ≥1 size', () => {
expect(roundBbox(rect(1.4, 2.6, 0.2, 10.5))).toEqual(rect(1, 3, 1, 11));
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts
index 5d039c2dc3..5b3399d2e4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts
@@ -5,7 +5,7 @@
import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
-import { type AspectAnchor, constrainAspect, snapMovedPoint, snapToGrid } from '@workbench/canvas-engine/math/snapping';
+import { type AspectAnchor, snapMovedPoint, snapToGrid } from '@workbench/canvas-engine/math/snapping';
/** The eight resize handles: four corners + four edge midpoints. */
export type BboxHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
@@ -363,20 +363,6 @@ export const resizeBbox = (p: ResizeBboxParams): Rect => {
return p.snap ? resized : pixelAlignResize(resized, p);
};
-/** Re-fits `rect` to `ratio`, keeping its center fixed, then snaps to `grid` and clamps min size. */
-export const constrainBboxToRatio = (rect: Rect, ratio: number, grid: number): Rect => {
- if (ratio <= 0) {
- return rect;
- }
- const fitted = constrainAspect(rect, ratio, 'center');
- const min = bboxMinSize(grid);
- const width = Math.max(min, snapToGrid(fitted.width, grid));
- const height = Math.max(1, width / ratio);
- const centerX = rect.x + rect.width / 2;
- const centerY = rect.y + rect.height / 2;
- return { height, width, x: centerX - width / 2, y: centerY - height / 2 };
-};
-
/** Rounds a rect's fields to integers (document px), enforcing a ≥1px size. */
export const roundBbox = (rect: Rect): Rect => ({
height: Math.max(1, Math.round(rect.height)),
diff --git a/invokeai/frontend/webv2/src/workbench/settings/README.md b/invokeai/frontend/webv2/src/workbench/settings/README.md
index 8d8f077ebd..5472c52497 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/README.md
+++ b/invokeai/frontend/webv2/src/workbench/settings/README.md
@@ -8,6 +8,8 @@ Workbench composes widget and application contributions into a metadata-only cat
Each field declares a scope: `preference` (account, or install when nobody is signed in), `project` (layered, below), `server` (server configuration, admins only), or `none` (actions, not values). Section placement does not determine storage lifetime. Every surface lists every section this account can edit; only Server needs `canManageAppConfig`.
+Account preferences (`WorkbenchPreferences`), the saved lists among them (aspect ratios, Generate presets, rebalance presets), are stored as one blob: each write sends the whole of it, and the last writer wins. An older build, or a tab still holding an older snapshot, drops the keys it does not know, or the list as it last read it, on its next preference write.
+
A `project` field resolves as the project's pin, then the user's default, then the owner's built-in. Pins are the keys present in the widget instance's `state.values`, or the optional generation flags in `ProjectSettings`; persistence keeps them raw. The generation flags (CPU noise, NSFW checker, watermark) are the Generate widget's settings, behind its cog, but they are project settings: every generation in the project reads them, and they pin on the project whichever widgets it has. Defaults live in `WorkbenchPreferences.scopedDefaults`, keyed by widget type id (`gallery`, `canvas`, `preview`, `image-map`, and `generate`, whose record layers over `ProjectSettings`, never over the Generate widget's values), each holding only keys the user chose (a default equal to the built-in is removed). `getLayeredSettings` in `projectSettings.ts` is the one list of layerable keys: resolution merges only those, the settings store drops any other, and the document codec reads its frozen built-ins (see `projects/README.md`). The workbench store seeds the mirror of the defaults when it is created and the runtime keeps it current; reads resolve at the generic seams (`getResolvedProjectWidgetValues`, `getEffectiveProjectSettings`), a project without the widget reading the defaults alone. A widget's runtime `getSnapshot` returns resolved values while `set` replaces raw pins, so widgets write with `patch`. Inside a project the dialog and gear popover edit pins. A widget owner's pins live on the project's instance of its type (`getProjectWidgetInstance`), the one every reader resolves, since layered widgets allow one instance and aliases such as `gallery:center` share it; a requested instance target only fences, staying editable while it exists with the owner's type. Without one (the Launchpad, or a project lacking that widget) the same field edits the default (never for the Generate section, which pins on the project), and its section says "Defaults for every project. A project can pin its own value." There is no unavailable state: search results are always editable. `useLayeredSetting(ownerId, key, target, read, builtIn, field)` is the one binding seam for layered fields: it returns value, layer, setter and disabled state, fences pin writes against stale account/project/instance, and disables a requested target that is no longer current. Shell disposes target-bound editing when projects change.
Settings host owns dialog's presence lifecycle and keeps its root mounted through closing. Body deferred until first opening, stays present during exit, unmounts afterward. Quick-popover handoff carries both instance target and original gear for focus restoration.
diff --git a/invokeai/frontend/webv2/src/workbench/settings/aspectRatioPresets.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/aspectRatioPresets.browser.test.tsx
new file mode 100644
index 0000000000..3e3daca11b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/aspectRatioPresets.browser.test.tsx
@@ -0,0 +1,198 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop */
+import type { AspectRatioPresetsPort } from '@features/generation/contracts';
+import type { StoredAspectRatioPreset } from '@workbench/settings/contracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { AspectRatioPicker } from '@features/generation/components';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { AppToaster, toaster } from '@platform/ui/toaster';
+import { system } from '@theme/system';
+import { getWorkbenchPreferences, patchWorkbenchPreferences } from '@workbench/settings/store';
+import i18next from 'i18next';
+import { act, createRef, type Ref, useImperativeHandle } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+import { useAspectRatioPresets } from './aspectRatioPresets';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+// The account's synced preferences live in the backend's client state; this keeps them in memory.
+vi.mock('@workbench/projects/api', async (importOriginal) => {
+ const clientState = new Map<string, string>();
+ return {
+ ...(await importOriginal<object>()),
+ deleteClientStateValue: (key: string) => Promise.resolve(void clientState.delete(key)),
+ getClientStateValue: (key: string) => Promise.resolve(clientState.get(key) ?? null),
+ setClientStateValue: (key: string, value: string) => Promise.resolve(void clientState.set(key, value)),
+ };
+});
+
+let root: Root | null = null;
+let host: HTMLDivElement | null = null;
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ // The global instance: the Undo toast reads its button label from it.
+ await i18next.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+beforeEach(() => {
+ accountLifecycle.activate('aspect-ratio-presets');
+});
+
+afterEach(async () => {
+ await act(() => toaster.remove());
+ await act(() => root?.unmount());
+ host?.remove();
+ root = null;
+ host = null;
+ // Clears the account's settings with the rest of its resources.
+ accountLifecycle.invalidate();
+});
+
+const preset = (id: string, label: string, width: number, height: number): StoredAspectRatioPreset => ({
+ height,
+ id,
+ label,
+ width,
+});
+
+/** The port the picker was last rendered with, for writes the picker cannot reach. */
+const port = createRef<AspectRatioPresetsPort>();
+
+const Picker = ({ portRef }: { portRef: Ref<AspectRatioPresetsPort> }) => {
+ const presets = useAspectRatioPresets();
+
+ useImperativeHandle(portRef, () => presets, [presets]);
+
+ return (
+ <AspectRatioPicker
+ currentSize={{ height: 640, width: 1536 }}
+ getSizeForRatio={() => ({ height: 640, width: 1536 })}
+ lockedRatio={null}
+ presets={presets}
+ onChange={() => undefined}
+ />
+ );
+};
+
+const render = async (stored: StoredAspectRatioPreset[]) => {
+ await patchWorkbenchPreferences({ aspectRatioPresets: stored });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18next}>
+ <ChakraProvider value={system}>
+ <Picker portRef={port} />
+ <AppToaster />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ await userEvent.click(page.getByRole('button', { name: /^Aspect ratio/ }));
+};
+
+/** The saved rows' names, in the order the picker lists them. */
+const rowNames = () =>
+ [...document.querySelectorAll<HTMLButtonElement>('button[aria-label$="1536×640"]')].map(
+ (row) => row.getAttribute('aria-label')?.split(',')[0]
+ );
+
+const ratios = (count: number) =>
+ Array.from({ length: count }, (_, index) => preset(`p${index}`, `Ratio ${index}`, 2, 1));
+
+describe('useAspectRatioPresets', () => {
+ it('deletes a saved ratio with an Undo that puts it back where it was', async () => {
+ const stored = [preset('a', 'Banner', 12, 5), preset('b', 'Cinema', 2.39, 1), preset('c', 'Tall', 2, 3)];
+ await render(stored);
+
+ await userEvent.click(page.getByRole('button', { name: 'Delete ratio Cinema (2.39:1)' }));
+
+ await expect.poll(rowNames).toEqual(['Banner', 'Tall']);
+ expect(getWorkbenchPreferences().aspectRatioPresets).toEqual([stored[0], stored[2]]);
+
+ await expect.element(page.getByText('Deleted ratio Cinema')).toBeVisible();
+ await userEvent.click(page.getByRole('button', { name: 'Undo' }));
+
+ await expect.poll(() => getWorkbenchPreferences().aspectRatioPresets).toEqual(stored);
+ });
+
+ it('adds and edits through the account preference, keeping entries only a newer build can use', async () => {
+ // 20:1 is past this build's 8:1, so it is not listed, but a newer build's ratio must survive this build's edits.
+ const wide = preset('wide', 'Panorama', 20, 1);
+ await render([preset('a', 'Banner', 12, 5), wide]);
+
+ expect(rowNames()).toEqual(['Banner']);
+
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.keyboard('Same{Enter}');
+ await userEvent.click(page.getByRole('button', { name: 'Edit ratio Banner (12:5)' }));
+ await userEvent.clear(page.getByRole('textbox', { name: 'Ratio name' }));
+ await userEvent.keyboard('Header{Enter}');
+
+ await expect.poll(rowNames).toEqual(['Header', 'Same']);
+ const [edited, kept, added] = getWorkbenchPreferences().aspectRatioPresets;
+ expect(edited).toEqual(preset('a', 'Header', 12, 5));
+ expect(kept).toEqual(wide);
+ expect(added).toMatchObject({ height: 5, label: 'Same', width: 12 });
+ });
+
+ it('offers no Add ratio once the list is full', async () => {
+ await render(ratios(50));
+
+ await expect.element(page.getByText('You can keep up to 50 ratios. Delete one to add another.')).toBeVisible();
+ expect(page.getByRole('button', { name: 'Add ratio' }).elements()).toHaveLength(0);
+ });
+
+ it('counts stored ratios this build does not list toward the limit', async () => {
+ // A newer build's ratio is stored and synced like any other, so it takes a place in the list.
+ const wide = preset('wide', 'Panorama', 20, 1);
+ await render([...ratios(48), wide]);
+
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.keyboard('Last{Enter}');
+
+ await expect.element(page.getByText('You can keep up to 50 ratios. Delete one to add another.')).toBeVisible();
+ expect(page.getByRole('button', { name: 'Add ratio' }).elements()).toHaveLength(0);
+ expect(rowNames()).toHaveLength(49);
+ expect(port.current!.save({ height: 1, label: 'More', width: 3 })).toBeNull();
+ expect(getWorkbenchPreferences().aspectRatioPresets).toHaveLength(50);
+ expect(getWorkbenchPreferences().aspectRatioPresets).toContainEqual(wide);
+ });
+
+ it('says why an Undo cannot bring a ratio back into a list that filled up again', async () => {
+ await render(ratios(50));
+
+ await userEvent.click(page.getByRole('button', { name: 'Delete ratio Ratio 0 (2:1)' }));
+ await userEvent.click(page.getByRole('button', { name: 'Add ratio' }));
+ await userEvent.keyboard('Refill{Enter}');
+ await expect.poll(() => getWorkbenchPreferences().aspectRatioPresets).toHaveLength(50);
+
+ await userEvent.click(page.getByRole('button', { name: 'Undo' }));
+
+ const notice = page.getByText("Couldn't bring back ratio Ratio 0");
+ await expect.element(notice).toBeVisible();
+ expect(notice.element().closest('[data-scope="toast"][data-part="root"]')?.textContent).toContain(
+ 'Your ratios list is full.'
+ );
+ const kept = getWorkbenchPreferences().aspectRatioPresets;
+ expect(kept).toHaveLength(50);
+ expect(kept.map(({ id }) => id)).not.toContain('p0');
+ });
+
+ it('leaves the stored list alone when the ratio being edited is already gone', async () => {
+ await render([preset('a', 'Banner', 12, 5)]);
+ // Deleted in another tab while this one still held it.
+ await patchWorkbenchPreferences({ aspectRatioPresets: [] });
+ const before = getWorkbenchPreferences();
+
+ port.current!.update('a', { height: 5, label: 'Header', width: 12 });
+
+ expect(getWorkbenchPreferences()).toBe(before);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/aspectRatioPresets.ts b/invokeai/frontend/webv2/src/workbench/settings/aspectRatioPresets.ts
new file mode 100644
index 0000000000..0e822bfd72
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/aspectRatioPresets.ts
@@ -0,0 +1,97 @@
+import type { AspectRatioPresetsPort } from '@features/generation/contracts';
+import type { StoredAspectRatioPreset } from '@workbench/settings/contracts';
+
+import { MAX_ASPECT_RATIO_PRESETS, normalizeAspectRatioPresets } from '@features/generation/settings';
+import { createUuid } from '@platform/browser/randomUuid';
+import {
+ getWorkbenchPreferences,
+ patchWorkbenchPreferences,
+ useWorkbenchPreferenceSelector,
+} from '@workbench/settings/store';
+import { useNotify } from '@workbench/useNotify';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const writePresets = (aspectRatioPresets: StoredAspectRatioPreset[]): void => {
+ void patchWorkbenchPreferences({ aspectRatioPresets });
+};
+
+/**
+ * The account's saved aspect ratios, for Generate's Size section (through the Generation UI adapter) and the canvas
+ * Frame tool alike. Reads are generation-normalized; writes edit the stored list, so an entry this build cannot use
+ * (a newer build's) is kept.
+ *
+ * The cap counts every stored entry, listed or not: it bounds the synced blob, and an entry past it would be stored but
+ * never listed, so nothing could remove it. Settings already drops records without a usable shape or with a repeated
+ * id; what remains unlisted here is a ratio this build rejects, which a newer build may list.
+ */
+export const useAspectRatioPresets = (): AspectRatioPresetsPort => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const stored = useWorkbenchPreferenceSelector((preferences) => preferences.aspectRatioPresets);
+
+ return useMemo<AspectRatioPresetsPort>(() => {
+ const read = () => getWorkbenchPreferences().aspectRatioPresets;
+ const restore = (preset: StoredAspectRatioPreset, index: number) => {
+ const current = read();
+
+ if (current.some((candidate) => candidate.id === preset.id)) {
+ return;
+ }
+
+ if (current.length >= MAX_ASPECT_RATIO_PRESETS) {
+ notify.error(
+ t('widgets.generate.aspectRatioRestoreFailed', { name: preset.label.trim() }),
+ t('widgets.generate.aspectRatioListFullNotice')
+ );
+ return;
+ }
+
+ const next = [...current];
+
+ next.splice(Math.min(index, next.length), 0, preset);
+ writePresets(next);
+ };
+
+ return {
+ isFull: stored.length >= MAX_ASPECT_RATIO_PRESETS,
+ presets: normalizeAspectRatioPresets(stored),
+ remove: (presetId) => {
+ const current = read();
+ const index = current.findIndex((candidate) => candidate.id === presetId);
+ const preset = current[index];
+
+ if (!preset) {
+ return;
+ }
+
+ writePresets(current.filter((candidate) => candidate.id !== presetId));
+ notify.undoable(t('widgets.generate.aspectRatioPresetDeleted', { name: preset.label.trim() }), {
+ onUndo: () => restore(preset, index),
+ });
+ },
+ save: (draft) => {
+ const current = read();
+
+ if (current.length >= MAX_ASPECT_RATIO_PRESETS) {
+ return null;
+ }
+
+ const preset = { ...draft, id: createUuid() };
+
+ writePresets([...current, preset]);
+ return preset;
+ },
+ update: (presetId, draft) => {
+ const current = read();
+
+ // Deleted meanwhile (in another tab, say): writing would only send back a list read before that.
+ if (!current.some((preset) => preset.id === presetId)) {
+ return;
+ }
+
+ writePresets(current.map((preset) => (preset.id === presetId ? { ...preset, ...draft } : preset)));
+ },
+ };
+ }, [notify, stored, t]);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
index 0754d770cf..62566f4a34 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
@@ -68,6 +68,17 @@ export interface StoredRebalancePreset {
multiplier: number;
}
+/**
+ * A user-named aspect ratio as it is persisted, kept local for the same bundle reason as {@link StoredRebalancePreset}.
+ * Generation owns the ratio rules and revalidates the terms on read.
+ */
+export interface StoredAspectRatioPreset {
+ id: string;
+ label: string;
+ width: number;
+ height: number;
+}
+
/**
* A named Generate settings snapshot ("recipe") as it is persisted. `values` is
* opaque to Settings for the same bundle reason as {@link StoredRebalancePreset}:
@@ -147,6 +158,8 @@ export interface WorkbenchPreferences {
launchpadProjectsSort: ProjectSortId;
/** Projects pinned to the top of the library, oldest pin first. */
launchpadPinnedProjectIds: string[];
+ /** User-named aspect ratios (ratios only, never sizes), in the order they were saved. */
+ aspectRatioPresets: StoredAspectRatioPreset[];
/** User-saved Krea-2 conditioning rebalance curves, in the order they were saved. */
krea2RebalancePresets: StoredRebalancePreset[];
/** User-saved Generate settings snapshots ("recipes"), in the order they were saved. */
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
index b9e20bac93..1d552e1d40 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
@@ -677,3 +677,36 @@ describe('antialiasProgressImages preference', () => {
expect(store.normalizeWorkbenchPreferences({ antialiasProgressImages: true }).antialiasProgressImages).toBe(true);
});
});
+
+describe('aspectRatioPresets preference', () => {
+ const cinema = { height: 1, id: 'cinema', label: 'Cinema', width: 2.39 };
+
+ it('starts empty for older preferences and keeps well-shaped entries, a clean list as is', () => {
+ expect(store.normalizeWorkbenchPreferences({}).aspectRatioPresets).toEqual([]);
+ expect(store.normalizeWorkbenchPreferences({ aspectRatioPresets: 'cinema' as never }).aspectRatioPresets).toEqual(
+ []
+ );
+
+ const clean = [cinema, { height: 5, id: 'banner', label: 'Banner', width: 12 }];
+
+ expect(store.normalizeWorkbenchPreferences({ aspectRatioPresets: clean }).aspectRatioPresets).toBe(clean);
+ });
+
+ it('drops malformed entries and repeated ids but leaves ratio rules to generation', () => {
+ // 20:1 is outside this build's range; a newer build may allow it, so storage keeps it for that build.
+ const wide = { height: 1, id: 'wide', label: 'Wide', width: 20 };
+
+ expect(
+ store.normalizeWorkbenchPreferences({
+ aspectRatioPresets: [
+ cinema,
+ null,
+ { height: 1, id: 'no-label', label: ' ', width: 2 },
+ { height: '1', id: 'text', label: 'Text', width: 2 },
+ { ...cinema, label: 'Repeat' },
+ wide,
+ ] as never,
+ }).aspectRatioPresets
+ ).toEqual([cinema, wide]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.ts
index 37279f194c..8d2521a5e6 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts
@@ -3,6 +3,7 @@ import type {
ProjectSortId,
ProjectsViewId,
ScopedDefaults,
+ StoredAspectRatioPreset,
StoredGeneratePreset,
StoredRebalancePreset,
WorkbenchPreferences,
@@ -40,6 +41,7 @@ export const DEVELOPER_LOG_NAMESPACES: readonly LogNamespace[] = LOG_NAMESPACES;
export const DEFAULT_PREFERENCES: WorkbenchPreferences = {
alphaNoticeAcknowledged: false,
antialiasProgressImages: false,
+ aspectRatioPresets: [],
autoSwitchInvocationRoute: true,
canvasToolMemory: {},
confirmImageDeletion: true,
@@ -275,6 +277,48 @@ const CONTROL_MODEL_KEY_MAX_LENGTH = 255;
const isPlainRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
+const isStoredAspectRatioPreset = (entry: unknown): entry is StoredAspectRatioPreset => {
+ if (!isPlainRecord(entry)) {
+ return false;
+ }
+
+ const { height, id, label, width } = entry;
+
+ return (
+ typeof id === 'string' &&
+ id !== '' &&
+ typeof label === 'string' &&
+ label.trim() !== '' &&
+ typeof width === 'number' &&
+ Number.isFinite(width) &&
+ typeof height === 'number' &&
+ Number.isFinite(height)
+ );
+};
+
+/**
+ * Shape-only, like {@link normalizeRebalancePresets}: generation drops ratios it cannot use when reading them, so a
+ * newer build's wider rules survive this one's writes. An already-valid list comes back as is, keeping its identity
+ * across unrelated preference patches.
+ */
+const normalizeAspectRatioPresetRecords = (values: unknown): StoredAspectRatioPreset[] => {
+ if (!Array.isArray(values)) {
+ return DEFAULT_PREFERENCES.aspectRatioPresets;
+ }
+
+ const seen = new Set<string>();
+ const kept = values.filter((entry): entry is StoredAspectRatioPreset => {
+ if (!isStoredAspectRatioPreset(entry) || seen.has(entry.id)) {
+ return false;
+ }
+
+ seen.add(entry.id);
+ return true;
+ });
+
+ return kept.length === values.length ? (values as StoredAspectRatioPreset[]) : kept;
+};
+
/** The tools `canvasToolMemory` may hold; canvas normalizes each one's fields on read. */
const CANVAS_TOOL_MEMORY_KEYS = ['brush', 'eraser', 'shape', 'text'] as const;
@@ -371,6 +415,7 @@ type WorkbenchPreferencesInput = Omit<
export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencesInput): WorkbenchPreferences => ({
antialiasProgressImages: preferences?.antialiasProgressImages === true,
+ aspectRatioPresets: normalizeAspectRatioPresetRecords(preferences?.aspectRatioPresets),
autoSwitchInvocationRoute:
typeof preferences?.autoSwitchInvocationRoute === 'boolean'
? preferences.autoSwitchInvocationRoute
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx
index cbc01e8e2f..fa41eba3fc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx
@@ -63,6 +63,13 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>
useGenerationQueueInsights: (select: (insights: unknown) => unknown) =>
select({ secondsPerRun: null, seedHistory: [] }),
useGenerationUi: () => ({
+ aspectRatioPresets: {
+ isFull: false,
+ presets: [],
+ remove: () => undefined,
+ save: () => null,
+ update: () => undefined,
+ },
CanvasRenderSize: harness.slot,
project: { invocationSourceId: harness.invocationSourceId },
sectionPreferences: { sectionsOpen: { dimensions: true }, setSectionOpen: () => undefined },
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts
index 920e6df512..fbf3dc2ff7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts
@@ -48,3 +48,22 @@ export const resizeBboxAroundCentre = (bbox: Bbox, size: Pick<Bbox, 'height' | '
x: Math.round(bbox.x + (bbox.width - size.width) / 2) + 0,
y: Math.round(bbox.y + (bbox.height - size.height) / 2) + 0,
});
+
+/**
+ * The frame size a ratio sets: the frame's pixel count at `ratio`, snapped to `grid`, with both sides scaled up together
+ * when the smaller would fall below `minSide`. Unlike Generate's size the frame has no maximum, so a large frame keeps
+ * its pixel count and only snapping moves the ratio.
+ */
+export const getBboxSizeForRatio = (
+ area: number,
+ ratio: number,
+ grid: number,
+ minSide: number
+): Pick<Bbox, 'height' | 'width'> => {
+ const exactWidth = Math.sqrt(area * ratio);
+ const exactHeight = exactWidth / ratio;
+ const scale = Math.max(1, minSide / Math.min(exactWidth, exactHeight));
+ const snap = (value: number) => Math.max(minSide, Math.round((value * scale) / grid) * grid);
+
+ return { height: snap(exactHeight), width: snap(exactWidth) };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
index 08e075cc77..d45cea4b2d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
@@ -1,16 +1,41 @@
-import type { CanvasInteractionState } from '@workbench/canvas-engine/api';
+import type { CanvasInteractionState, Rect } from '@workbench/canvas-engine/api';
import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { system } from '@theme/system';
+import { patchWorkbenchPreferences } from '@workbench/settings/store';
import { createInstance } from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
-import { page } from 'vitest/browser';
+import { page, userEvent } from 'vitest/browser';
-import { transformForm } from './geometryForm';
+import { bboxForm, transformForm } from './geometryForm';
+
+const frame = vi.hoisted(() => ({
+ bbox: { height: 1024, width: 1024, x: 0, y: 0 },
+ patchSettings: vi.fn(),
+ sourceId: 'canvas',
+}));
+
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useActiveProjectSelector: (selector: (project: unknown) => unknown) =>
+ selector({ canvas: { document: { bbox: frame.bbox } }, invocation: { sourceId: frame.sourceId } }),
+ useOptionalWorkbenchCommands: () => null,
+ useWorkbenchCommands: () => ({ generation: { patchSettings: frame.patchSettings } }),
+}));
+// Saved ratios are account preferences, synced through the backend's client state; this keeps them in memory.
+vi.mock('@workbench/projects/api', async (importOriginal) => {
+ const clientState = new Map<string, string>();
+ return {
+ ...(await importOriginal<object>()),
+ getClientStateValue: (key: string) => Promise.resolve(clientState.get(key) ?? null),
+ setClientStateValue: (key: string, value: string) => Promise.resolve(void clientState.set(key, value)),
+ };
+});
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -105,3 +130,166 @@ describe('Transform footer', () => {
await expect.element(page.getByRole('tooltip')).toHaveTextContent('Waiting for the stroke to save…');
});
});
+
+/** The Frame tool's engine: its bbox options and grid as the form reads and writes them, and the frame commit. */
+const createFrameEngine = (bboxOptions = { aspectLocked: false, aspectRatio: 1 }) => {
+ const state: Partial<CanvasInteractionState> = { bboxGrid: 8, bboxOptions };
+ const listeners = new Map<string, Set<() => void>>();
+ const commits: Rect[] = [];
+ const engine = {
+ interaction: {
+ get: (key: keyof CanvasInteractionState) => state[key],
+ set: (key: keyof CanvasInteractionState, value: never) => {
+ state[key] = value;
+ listeners.get(key)?.forEach((listener) => listener());
+ },
+ subscribe: (key: string, listener: () => void) => {
+ const keyListeners = listeners.get(key) ?? new Set();
+ keyListeners.add(listener);
+ listeners.set(key, keyListeners);
+ return () => keyListeners.delete(listener);
+ },
+ },
+ layers: { commitStructural: (_label: string, change: { bbox: Rect }) => commits.push(change.bbox) },
+ };
+ return { commits, engine: engine as unknown as ToolFormProps['engine'], state };
+};
+
+describe('Frame aspect ratio', () => {
+ const FrameSize = bboxForm.groups.find((group) => group.id === 'frame-size')!.body;
+
+ const renderFrame = async (bboxOptions?: { aspectLocked: boolean; aspectRatio: number }) => {
+ accountLifecycle.activate('frame-aspect-ratio');
+ await patchWorkbenchPreferences({
+ aspectRatioPresets: [{ height: 1, id: 'cinema', label: 'Cinema', width: 2.39 }],
+ });
+ const frameEngine = createFrameEngine(bboxOptions);
+ host = document.createElement('div');
+ host.style.width = '320px';
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <FrameSize engine={frameEngine.engine} />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ await userEvent.click(page.getByRole('button', { name: /^Aspect ratio/ }));
+ return frameEngine;
+ };
+
+ afterEach(() => {
+ frame.bbox = { height: 1024, width: 1024, x: 0, y: 0 };
+ frame.patchSettings.mockReset();
+ accountLifecycle.invalidate();
+ });
+
+ // 1024×1024 holds 1,048,576 pixels. At 2.39:1 that is 1583.1×662.4, snapped to the 8px grid as 1584×664 (what
+ // Generate sets), centred on the old frame's centre (512, 512).
+ const CINEMA_FRAME = { height: 664, width: 1584, x: -280, y: 180 };
+
+ it('keeps the pixel count when a saved ratio is picked, locking it on the frame and on Generate', async () => {
+ const { commits, state } = await renderFrame();
+
+ // The size column shows the size the pick sets.
+ await userEvent.click(page.getByRole('button', { name: 'Cinema, 2.39:1, 1584×664' }));
+
+ expect(commits).toEqual([CINEMA_FRAME]);
+ expect(state.bboxOptions).toEqual({ aspectLocked: true, aspectRatio: 2.39 });
+ expect(frame.patchSettings).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 2.39,
+ });
+ await expect
+ .element(page.getByRole('button', { name: /^Aspect ratio/ }))
+ .toHaveAccessibleName('Aspect ratio Cinema 2.39:1');
+ });
+
+ it('resizes the same way when the canvas does not drive Generate, leaving Generate alone', async () => {
+ frame.sourceId = 'generate';
+ try {
+ const { commits, state } = await renderFrame();
+
+ await userEvent.click(page.getByRole('button', { name: 'Cinema, 2.39:1, 1584×664' }));
+
+ expect(commits).toEqual([CINEMA_FRAME]);
+ expect(state.bboxOptions).toEqual({ aspectLocked: true, aspectRatio: 2.39 });
+ expect(frame.patchSettings).not.toHaveBeenCalled();
+ } finally {
+ frame.sourceId = 'canvas';
+ }
+ });
+
+ it('keeps the pixel count for a built-in ratio too', async () => {
+ const { commits, state } = await renderFrame();
+
+ await userEvent.click(page.getByRole('radio', { exact: true, name: '16:9' }));
+
+ // 1024² at 16:9 is 1365.3×768, snapped to 1368×768, centred on (512, 512).
+ expect(commits).toEqual([{ height: 768, width: 1368, x: -172, y: 128 }]);
+ expect(state.bboxOptions).toEqual({ aspectLocked: true, aspectRatio: 16 / 9 });
+ expect(frame.patchSettings).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: '16:9',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 16 / 9,
+ });
+ });
+
+ it('keeps the ratio and pixel count of a frame larger than any one generation', async () => {
+ frame.bbox = { height: 6144, width: 6144, x: 0, y: 0 };
+ const { commits } = await renderFrame();
+
+ await userEvent.click(page.getByRole('radio', { exact: true, name: '16:9' }));
+
+ // 6144² at 16:9 is exactly 8192×4608: no 4096 cap on the frame, centred on (3072, 3072).
+ expect(commits).toEqual([{ height: 4608, width: 8192, x: -1024, y: 768 }]);
+ });
+
+ it('keeps a tiny frame at least one grid step on each side', async () => {
+ frame.bbox = { height: 8, width: 8, x: 0, y: 0 };
+ const { commits } = await renderFrame();
+
+ await userEvent.click(page.getByRole('radio', { exact: true, name: '9:21' }));
+
+ // 8² at 9:21 is 5.2×12.2; scaled up so the narrow side is 8, then 18.7 snaps to 16. Centred on (4, 4).
+ expect(commits).toEqual([{ height: 16, width: 8, x: 0, y: -4 }]);
+ });
+
+ it('unlocks with Free, leaving the frame as it is', async () => {
+ const { commits, state } = await renderFrame({ aspectLocked: true, aspectRatio: 16 / 9 });
+
+ await userEvent.click(page.getByRole('radio', { exact: true, name: 'Free' }));
+
+ expect(commits).toEqual([]);
+ expect(state.bboxOptions).toEqual({ aspectLocked: false, aspectRatio: 1 });
+ expect(frame.patchSettings).toHaveBeenCalledExactlyOnceWith({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: false,
+ aspectRatioValue: 1,
+ });
+ });
+
+ it('unlocks from the lock button, leaving the frame as it is', async () => {
+ const { commits, state } = await renderFrame({ aspectLocked: true, aspectRatio: 16 / 9 });
+ await userEvent.keyboard('{Escape}');
+
+ await userEvent.click(page.getByRole('button', { name: 'Unlock aspect ratio' }));
+
+ expect(commits).toEqual([]);
+ expect(state.bboxOptions).toEqual({ aspectLocked: false, aspectRatio: 1 });
+ });
+
+ it('locks the ratio the frame has without resizing it', async () => {
+ const { commits, state } = await renderFrame();
+ await userEvent.keyboard('{Escape}');
+
+ await userEvent.click(page.getByRole('button', { name: 'Lock aspect ratio' }));
+
+ expect(commits).toEqual([]);
+ expect(state.bboxOptions).toEqual({ aspectLocked: true, aspectRatio: 1 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
index 4097a6c7af..888ade008c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
@@ -1,4 +1,3 @@
-import type { AspectRatioId } from '@features/generation/contracts';
import type { LayerTransform } from '@workbench/canvas-engine/api';
import type {
ToolFormProps,
@@ -7,10 +6,12 @@ import type {
} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
import { Flex, Text } from '@chakra-ui/react';
-import { AspectRatioLockButton, AspectRatioSelect } from '@features/generation/components';
-import { ASPECT_RATIO_MAP, deriveAspectRatioId } from '@features/generation/settings';
+import { AspectRatioLockButton, AspectRatioPicker } from '@features/generation/components';
+import { getLockedAspectRatioSettings } from '@features/generation/settings';
import { Tooltip } from '@platform/ui/Tooltip';
-import { constrainBboxToRatio, lookupDocumentLeaf } from '@workbench/canvas-engine/api';
+import { bboxMinSize, lookupDocumentLeaf } from '@workbench/canvas-engine/api';
+import { useAspectRatioPresets } from '@workbench/settings/aspectRatioPresets';
+import { getBboxSizeForRatio, resizeBboxAroundCentre } from '@workbench/widgets/canvas/bboxGrid';
import {
useCanvasActiveTool,
useCanvasHasFloatingSelection,
@@ -25,7 +26,7 @@ import {
import { PropertyControlRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';
import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useBboxEditor } from './useBboxEditor';
@@ -33,7 +34,6 @@ import { useBboxEditor } from './useBboxEditor';
const RAD_TO_DEG = 180 / Math.PI;
const DEG_TO_RAD = Math.PI / 180;
const MIN_SCALE_PERCENT = 1;
-const ASPECT_TRIGGER_PROPS = { minW: '7.5rem' } as const;
export const round2 = (n: number): number => Math.round(n * 100) / 100;
/** Degrees in (-180, 180], so 270 reads and stores as -90. */
@@ -189,56 +189,57 @@ export const TransformScaleSettings = ({ engine }: ToolFormProps) => {
const FrameSizeSettings = ({ engine }: ToolFormProps) => {
const { t } = useTranslation();
const { generation } = useWorkbenchCommands();
+ const aspectRatioPresets = useAspectRatioPresets();
const isLinked = useActiveProjectSelector((project) => project.invocation.sourceId === 'canvas');
const { bbox, commitBbox, grid, options, setHeight, setWidth } = useBboxEditor(engine);
const onWidth = useNumberCommit(setWidth);
const onHeight = useNumberCommit(setHeight);
const bboxRatio = bbox.height > 0 ? bbox.width / bbox.height : 1;
- // Derived from the live frame so a lock captured from a hand-drawn bbox reports the preset it matches.
- const selectedId: AspectRatioId = options.aspectLocked ? deriveAspectRatioId(bbox.width, bbox.height) : 'Free';
+ // The lock's own ratio, not the frame's: a grid-snapped frame is only close to the ratio it holds.
+ const lockedRatio = options.aspectLocked ? (options.aspectRatio > 0 ? options.aspectRatio : bboxRatio) : null;
+ const currentSize = useMemo(() => ({ height: bbox.height, width: bbox.width }), [bbox.height, bbox.width]);
- const setLock = useCallback(
- (aspectLocked: boolean, aspectRatio: number) => {
+ /** Locks the Frame tool (and Generate, while linked) to `aspectRatio`, or unlocks; returns the ratio stored. */
+ const applyLock = useCallback(
+ (aspectRatio: number | null): number | null => {
+ const locked = aspectRatio === null ? null : getLockedAspectRatioSettings(aspectRatio);
if (isLinked) {
// Generate's fields; the feed brings the lock back to the Frame tool.
- generation.patchSettings({
- aspectRatioId: aspectLocked ? deriveAspectRatioId(bbox.width, bbox.height) : 'Free',
- aspectRatioIsLocked: aspectLocked,
- aspectRatioValue: aspectRatio,
- });
+ generation.patchSettings(
+ locked ?? { aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: bboxRatio }
+ );
}
- engine.interaction.set('bboxOptions', { aspectLocked, aspectRatio });
+ engine.interaction.set('bboxOptions', {
+ aspectLocked: locked !== null,
+ aspectRatio: locked?.aspectRatioValue ?? bboxRatio,
+ });
+ return locked?.aspectRatioValue ?? null;
},
- [bbox.height, bbox.width, engine, generation, isLinked]
+ [bboxRatio, engine, generation, isLinked]
);
- const onAspectPresetChange = useCallback(
- (id: AspectRatioId) => {
- if (id === 'Free') {
- setLock(false, bboxRatio);
- return;
- }
- const ratio = ASPECT_RATIO_MAP[id].ratio;
- if (isLinked) {
- generation.patchSettings({ aspectRatioId: id, aspectRatioIsLocked: true, aspectRatioValue: ratio });
+ // The size a ratio sets keeps the frame's pixel count on its grid, as choosing it in Generate does, without
+ // Generate's maximum: the frame may be larger than any one generation.
+ const getSizeForRatio = useCallback(
+ (ratio: number) => getBboxSizeForRatio(bbox.width * bbox.height, ratio, grid, bboxMinSize(grid)),
+ [bbox.height, bbox.width, grid]
+ );
+
+ const onAspectRatioChange = useCallback(
+ (ratio: number | null) => {
+ const locked = applyLock(ratio);
+ if (locked !== null) {
+ commitBbox(resizeBboxAroundCentre(bbox, getSizeForRatio(locked)));
}
- engine.interaction.set('bboxOptions', { aspectLocked: true, aspectRatio: ratio });
- commitBbox(constrainBboxToRatio(bbox, ratio, grid));
},
- [bbox, bboxRatio, commitBbox, engine, generation, grid, isLinked, setLock]
+ [applyLock, bbox, commitBbox, getSizeForRatio]
);
- const onLockToggle = useCallback(() => {
- const checked = !options.aspectLocked;
- // Locking a frame that matches no preset captures its current ratio.
- const aspectRatio =
- checked && bbox.height > 0 && deriveAspectRatioId(bbox.width, bbox.height) === 'Free'
- ? bboxRatio
- : options.aspectRatio > 0
- ? options.aspectRatio
- : 1;
- setLock(checked, checked ? aspectRatio : bboxRatio);
- }, [bbox, bboxRatio, options.aspectLocked, options.aspectRatio, setLock]);
+ // Locking captures the frame's current ratio (a built-in's exact value when it matches one).
+ const onLockToggle = useCallback(
+ () => applyLock(options.aspectLocked ? null : bboxRatio),
+ [applyLock, bboxRatio, options.aspectLocked]
+ );
return (
<>
@@ -262,12 +263,15 @@ const FrameSizeSettings = ({ engine }: ToolFormProps) => {
</PropertyControlRow>
<PropertyControlRow label={t('widgets.properties.rows.aspect')}>
<Flex align="center" gap="2" gridColumn="2 / -1">
- <AspectRatioSelect
- fallbackRatio={bboxRatio}
- triggerProps={ASPECT_TRIGGER_PROPS}
- value={selectedId}
- onChange={onAspectPresetChange}
- />
+ <Flex flex="1" minW="7.5rem">
+ <AspectRatioPicker
+ currentSize={currentSize}
+ getSizeForRatio={getSizeForRatio}
+ lockedRatio={lockedRatio}
+ presets={aspectRatioPresets}
+ onChange={onAspectRatioChange}
+ />
+ </Flex>
<AspectRatioLockButton isLocked={options.aspectLocked} onToggle={onLockToggle} />
</Flex>
</PropertyControlRow>
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 8dd89bbe24..72ca9e845f 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -195,6 +195,9 @@ const EDITOR_BOOT_SHARED_MODULES = [
'/workbench/widgets/canvas/invoke/canvasScaling.ts',
// The canvas dims sync and the lazy Canvas widget and Frame tool share the model grid and the centred resize.
'/workbench/widgets/canvas/bboxGrid.ts',
+ // Generate's UI adapter (editor boot) and the lazy canvas Frame tool share the saved aspect ratios; alone they cost a
+ // boot request.
+ '/workbench/settings/aspectRatioPresets.ts',
// The Preview (open at boot) and the Canvas staging bar share the Auto-switch menu; alone it costs a boot request.
'/workbench/widgets/shared/AutoSwitchMenu.tsx',
// The Gallery, the Preview filmstrip and the Canvas staging bar share the progress badge; alone it costs a boot