Skip to content

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

fix(webv2): make the layer curves editor visible and correctly mapped

joshistoast252f8a10ea36
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx
new file mode 100644
index 0000000000..10ef172109
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx
@@ -0,0 +1,186 @@
+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { applyThemeToRoot } from '@theme/applyTheme';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act, useMemo, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { AdjustmentsPopover } from './AdjustmentsPopover';
+import { CURVE_SIZE } from './curveEditorMath';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });
+
+// The popover calls this hook for its no-engine fallback path. The harness
+// drives edits through a stand-in engine instead, so the dispatch is never used
+// and can stay a stable no-op rather than something reassigned during render.
+const noopDispatch = (): void => undefined;
+vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({
+ useCanvasProjectMutationDispatch: () => noopDispatch,
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+const createLayer = (): CanvasRasterLayerContractV2 =>
+ ({
+ blendMode: 'normal',
+ id: 'layer-1',
+ isEnabled: true,
+ isLocked: false,
+ name: 'Layer 1',
+ opacity: 1,
+ source: { bitmap: null, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ }) as unknown as CanvasRasterLayerContractV2;
+
+const Harness = () => {
+ const [layer, setLayer] = useState(createLayer);
+
+ // Stands in for the canvas engine: both the live preview and the committed
+ // edit land back on the layer prop, which is what the editor re-renders from.
+ const engine = useMemo(() => {
+ const apply = (mutation: CanvasProjectMutation): boolean => {
+ const candidate = mutation as { type: string; config?: { adjustments?: unknown } };
+ if (candidate.type === 'updateCanvasLayerConfig') {
+ setLayer(
+ (current) => ({ ...current, adjustments: candidate.config?.adjustments }) as CanvasRasterLayerContractV2
+ );
+ }
+ return true;
+ };
+
+ return {
+ layers: {
+ applyStructuralPreview: apply,
+ commitStructural: (_label: string, forward: CanvasProjectMutation) => apply(forward),
+ },
+ } as unknown as CanvasStructuralEngine;
+ }, []);
+
+ return <AdjustmentsPopover engine={engine} layer={layer} />;
+};
+
+const settle = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 30);
+ });
+ });
+
+const render = async () => {
+ applyThemeToRoot('classic');
+ host = document.createElement('div');
+ // Narrower than the editor's intrinsic size, so the square-fit path is real.
+ host.style.width = '260px';
+ document.body.append(host);
+ root = createRoot(host);
+
+ await settle(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ return host.querySelector<SVGSVGElement>(`svg[viewBox="0 0 ${CURVE_SIZE} ${CURVE_SIZE}"]`)!;
+};
+
+const handles = (svg: SVGSVGElement): SVGCircleElement[] => Array.from(svg.querySelectorAll('circle'));
+
+const centreOf = (element: Element): { x: number; y: number } => {
+ const rect = element.getBoundingClientRect();
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
+};
+
+const pointer = (target: Element, type: string, x: number, y: number): void => {
+ target.dispatchEvent(
+ new PointerEvent(type, { bubbles: true, button: 0, clientX: x, clientY: y, isPrimary: true, pointerId: 1 })
+ );
+};
+
+afterEach(async () => {
+ await settle(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('curves editor', () => {
+ it('paints its chrome from resolved theme tokens', async () => {
+ // Hand-written `var(--chakra-colors-bg-inset)` did not exist (Chakra emits
+ // `--chakra-colors-bg.inset`), so `fill` fell back to black and `stroke` to
+ // `none` — the whole editor rendered as a black box.
+ const svg = await render();
+ const area = svg.querySelector('rect')!;
+ const curve = svg.querySelector('path')!;
+
+ for (const [label, value] of [
+ ['area fill', getComputedStyle(area).fill],
+ ['curve stroke', getComputedStyle(curve).stroke],
+ ['handle fill', getComputedStyle(handles(svg)[0]!).fill],
+ ] as const) {
+ expect(value, label).not.toBe('none');
+ expect(value, label).not.toBe('rgb(0, 0, 0)');
+ }
+
+ expect(getComputedStyle(svg).backgroundColor).not.toBe('rgba(0, 0, 0, 0)');
+ });
+
+ it('keeps the drawing square so pointer coordinates map onto the viewBox', async () => {
+ const svg = await render();
+ const rect = svg.getBoundingClientRect();
+
+ expect(rect.width).toBeCloseTo(rect.height, 0);
+ });
+
+ it('moves a handle while dragging it', async () => {
+ const svg = await render();
+ const target = handles(svg).at(-1)!;
+ const before = Number(target.getAttribute('cy'));
+ const start = centreOf(target);
+
+ await settle(() => pointer(target, 'pointerdown', start.x, start.y));
+ await settle(() => pointer(target, 'pointermove', start.x, start.y + 40));
+
+ const during = Number(handles(svg).at(-1)!.getAttribute('cy'));
+ expect(during).toBeGreaterThan(before);
+
+ await settle(() => pointer(target, 'pointerup', start.x, start.y + 40));
+ expect(Number(handles(svg).at(-1)!.getAttribute('cy'))).toBeCloseTo(during, 5);
+ });
+
+ it('adds a point under the pointer rather than offset from it', async () => {
+ // Guards the letterboxing bug: a non-square box mapped pointer x across the
+ // whole element while the viewBox only occupied part of it.
+ const svg = await render();
+ const rect = svg.getBoundingClientRect();
+ // Deliberately off centre: a letterboxed viewBox still maps the midpoint
+ // correctly, because the dead space either side cancels out there.
+ const targetX = rect.left + rect.width * 0.25;
+
+ await settle(() =>
+ svg.dispatchEvent(
+ new MouseEvent('dblclick', { bubbles: true, clientX: targetX, clientY: rect.top + rect.height * 0.5 })
+ )
+ );
+
+ expect(handles(svg)).toHaveLength(3);
+ const added = centreOf(handles(svg)[1]!);
+ expect(added.x).toBeCloseTo(targetX, 0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx
index c6d4e32ce9..4bcb9a08a1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx
@@ -3,7 +3,7 @@ import type { CanvasAdjustmentsContract, CanvasRasterLayerContractV2 } from '@wo
import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';
import type { PointerEvent as ReactPointerEvent } from 'react';
-import { createListCollection, HStack, Stack, Text } from '@chakra-ui/react';
+import { chakra, createListCollection, HStack, Stack, Text } from '@chakra-ui/react';
import { Button, Field, Select, Slider } from '@platform/ui';
import { DEFAULT_ADJUSTMENTS, buildCurveLut } from '@workbench/canvas-engine/api';
import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
@@ -22,6 +22,44 @@ import { applyStructural, applyStructuralPreview } from './layerOps';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
+/**
+ * The curve editor's SVG goes through the Chakra factory so `fill`/`stroke` take
+ * semantic tokens.
+ *
+ * Hand-written `var(--chakra-colors-bg-inset)` silently produced a solid black
+ * box: Chakra emits these custom properties with the token path intact
+ * (`--chakra-colors-bg.inset`, dot and all), so the hyphenated guess resolved to
+ * nothing — and an unresolvable `fill` falls back to its initial value, black,
+ * while `stroke` falls back to `none`. That took the grid, the border, the
+ * diagonal, the curve, and the handle outlines with it.
+ */
+const CurveSvg = chakra('svg');
+const CurveRect = chakra('rect');
+const CurveLine = chakra('line');
+const CurveGroup = chakra('g');
+const CurvePath = chakra('path');
+const CurveHandle = chakra('circle');
+
+/**
+ * Square, so the `0 0 180 180` viewBox maps 1:1 onto the element box.
+ *
+ * With a full-width box and a fixed height the default `preserveAspectRatio`
+ * letterboxed the drawing — it rendered centred with dead space either side,
+ * while `svgPointFromEvent` still mapped pointer x across the *whole* element.
+ * Every horizontal hit test was therefore offset, so grabbing an interior point
+ * missed it and dropping one landed at the wrong input level.
+ */
+const CURVE_SVG_CSS = {
+ aspectRatio: '1',
+ borderRadius: 'l2',
+ maxWidth: `${CURVE_SIZE}px`,
+ touchAction: 'none',
+ width: 'full',
+};
+const CURVE_HANDLE_CSS = { cursor: 'grab', _active: { cursor: 'grabbing' } };
+
+const preventDefault = (event: { preventDefault: () => void }): void => event.preventDefault();
+
type CurveChannel = 'r' | 'g' | 'b';
const CURVE_CHANNELS: readonly CurveChannel[] = ['r', 'g', 'b'];
@@ -276,7 +314,9 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
[t]
);
- const svgPointFromEvent = (event: ReactPointerEvent<SVGElement>): { px: number; py: number } => {
+ // Relies on the SVG being square (see CURVE_SVG_CSS): the viewBox then maps
+ // linearly onto the element box, so a plain ratio is the whole conversion.
+ const svgPointFromEvent = useCallback((event: { clientX: number; clientY: number }): { px: number; py: number } => {
const svg = svgRef.current;
if (!svg) {
return { px: 0, py: 0 };
@@ -286,7 +326,7 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
px: ((event.clientX - rect.left) / rect.width) * CURVE_SIZE,
py: ((event.clientY - rect.top) / rect.height) * CURVE_SIZE,
};
- };
+ }, []);
const lutPath = useMemo(() => {
const lut = buildCurveLut(points);
@@ -304,96 +344,115 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
[]
);
- const handlePointDown = (index: number) => (event: ReactPointerEvent<SVGCircleElement>) => {
- event.stopPropagation();
- event.currentTarget.setPointerCapture(event.pointerId);
- dragIndexRef.current = index;
- dragTargetRef.current = event.currentTarget;
- // Snapshot the pre-drag state once, for a single whole-drag history entry.
- beforeRef.current = adjustments;
- latestPointsRef.current = null;
- };
-
- const handleMove = (event: ReactPointerEvent<SVGSVGElement>) => {
- const index = dragIndexRef.current;
- if (index === null) {
- return;
- }
- const { px, py } = svgPointFromEvent(event);
- const [nx, ny] = curvePointFromSvg(px, py);
- const isEndpoint = index === 0 || index === points.length - 1;
- const next = points.map((p, i) => {
- if (i !== index) {
- return p;
+ // Handlers read their point index off the element rather than closing over it,
+ // so each handle gets one stable callback instead of a fresh closure per
+ // render (these sit on a `chakra()` component, which re-renders on new props).
+ const handlePointDown = useCallback(
+ (event: ReactPointerEvent<SVGCircleElement>) => {
+ event.stopPropagation();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ dragIndexRef.current = Number(event.currentTarget.dataset.index);
+ dragTargetRef.current = event.currentTarget;
+ // Snapshot the pre-drag state once, for a single whole-drag history entry.
+ beforeRef.current = adjustments;
+ latestPointsRef.current = null;
+ },
+ [adjustments]
+ );
+
+ const handleMove = useCallback(
+ (event: ReactPointerEvent<SVGSVGElement>) => {
+ const index = dragIndexRef.current;
+ if (index === null) {
+ return;
}
- // Endpoints keep their x anchored (0 / 255); only y moves.
- return isEndpoint ? ([p[0], ny] as [number, number]) : ([nx, ny] as [number, number]);
- });
- // Keep interior x within its neighbours to preserve monotonic ordering.
- if (!isEndpoint) {
- const lo = next[index - 1][0] + 1;
- const hi = next[index + 1][0] - 1;
- next[index] = [Math.max(lo, Math.min(hi, next[index][0])), next[index][1]];
- }
- latestPointsRef.current = next;
- onLive(channel, next);
- };
-
- const finishDrag = (event: ReactPointerEvent<SVGSVGElement>, cancelled: boolean) => {
- const wasDragging = dragIndexRef.current !== null;
- const dragTarget = dragTargetRef.current;
- if (dragTarget?.hasPointerCapture(event.pointerId)) {
- dragTarget.releasePointerCapture(event.pointerId);
- }
- dragIndexRef.current = null;
- dragTargetRef.current = null;
- // Commit the whole drag as one history entry (only if the point actually
- // moved — a click with no move streams no previews and needs no commit).
- const before = beforeRef.current;
- const finalPoints = latestPointsRef.current;
- beforeRef.current = null;
- latestPointsRef.current = null;
- if (wasDragging && before && finalPoints) {
- finishCurveDragResult({
- before,
- cancelled,
- current: withCurve(before, channel, finalPoints),
- onCommit: (current) => onCommit(current, before),
- onPreview: onCancel,
+ const { px, py } = svgPointFromEvent(event);
+ const [nx, ny] = curvePointFromSvg(px, py);
+ const isEndpoint = index === 0 || index === points.length - 1;
+ const next = points.map((p, i) => {
+ if (i !== index) {
+ return p;
+ }
+ // Endpoints keep their x anchored (0 / 255); only y moves.
+ return isEndpoint ? ([p[0], ny] as [number, number]) : ([nx, ny] as [number, number]);
});
- }
- };
+ // Keep interior x within its neighbours to preserve monotonic ordering.
+ if (!isEndpoint) {
+ const lo = next[index - 1][0] + 1;
+ const hi = next[index + 1][0] - 1;
+ next[index] = [Math.max(lo, Math.min(hi, next[index][0])), next[index][1]];
+ }
+ latestPointsRef.current = next;
+ onLive(channel, next);
+ },
+ [channel, onLive, points, svgPointFromEvent]
+ );
- const handleUp = (event: ReactPointerEvent<SVGSVGElement>) => finishDrag(event, false);
- const handleCancel = (event: ReactPointerEvent<SVGSVGElement>) => finishDrag(event, true);
+ const finishDrag = useCallback(
+ (event: ReactPointerEvent<SVGSVGElement>, cancelled: boolean) => {
+ const wasDragging = dragIndexRef.current !== null;
+ const dragTarget = dragTargetRef.current;
+ if (dragTarget?.hasPointerCapture(event.pointerId)) {
+ dragTarget.releasePointerCapture(event.pointerId);
+ }
+ dragIndexRef.current = null;
+ dragTargetRef.current = null;
+ // Commit the whole drag as one history entry (only if the point actually
+ // moved — a click with no move streams no previews and needs no commit).
+ const before = beforeRef.current;
+ const finalPoints = latestPointsRef.current;
+ beforeRef.current = null;
+ latestPointsRef.current = null;
+ if (wasDragging && before && finalPoints) {
+ finishCurveDragResult({
+ before,
+ cancelled,
+ current: withCurve(before, channel, finalPoints),
+ onCommit: (current) => onCommit(current, before),
+ onPreview: onCancel,
+ });
+ }
+ },
+ [channel, onCancel, onCommit]
+ );
- const handleAdd = (event: ReactPointerEvent<SVGSVGElement>) => {
- if (dragIndexRef.current !== null) {
- return;
- }
- const { px, py } = svgPointFromEvent(event);
- const [nx, ny] = curvePointFromSvg(px, py);
- if (nx <= 0 || nx >= 255) {
- return;
- }
- const next = [...points, [nx, ny] as [number, number]].sort((a, b) => a[0] - b[0]);
- onCommit(withCurve(adjustments, channel, next), adjustments);
- };
-
- const handleRemove = (index: number) => (event: ReactPointerEvent<SVGCircleElement>) => {
- event.stopPropagation();
- if (index === 0 || index === points.length - 1 || points.length <= 2) {
- return;
- }
- onCommit(
- withCurve(
- adjustments,
- channel,
- points.filter((_, i) => i !== index)
- ),
- adjustments
- );
- };
+ const handleUp = useCallback((event: ReactPointerEvent<SVGSVGElement>) => finishDrag(event, false), [finishDrag]);
+ const handleCancel = useCallback((event: ReactPointerEvent<SVGSVGElement>) => finishDrag(event, true), [finishDrag]);
+
+ const handleAdd = useCallback(
+ (event: ReactPointerEvent<SVGSVGElement>) => {
+ if (dragIndexRef.current !== null) {
+ return;
+ }
+ const { px, py } = svgPointFromEvent(event);
+ const [nx, ny] = curvePointFromSvg(px, py);
+ if (nx <= 0 || nx >= 255) {
+ return;
+ }
+ const next = [...points, [nx, ny] as [number, number]].sort((a, b) => a[0] - b[0]);
+ onCommit(withCurve(adjustments, channel, next), adjustments);
+ },
+ [adjustments, channel, onCommit, points, svgPointFromEvent]
+ );
+
+ const handleRemove = useCallback(
+ (event: ReactPointerEvent<SVGCircleElement>) => {
+ event.stopPropagation();
+ const index = Number(event.currentTarget.dataset.index);
+ if (index === 0 || index === points.length - 1 || points.length <= 2) {
+ return;
+ }
+ onCommit(
+ withCurve(
+ adjustments,
+ channel,
+ points.filter((_, i) => i !== index)
+ ),
+ adjustments
+ );
+ },
+ [adjustments, channel, onCommit, points]
+ );
const channelValue = useMemo(() => [channel], [channel]);
@@ -414,29 +473,24 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
onValueChange={handleChannelChange}
/>
</HStack>
- <svg
- height={CURVE_SIZE}
+ <CurveSvg
+ bg="bg.inset"
+ css={CURVE_SVG_CSS}
onDoubleClick={handleAdd}
onPointerCancel={handleCancel}
onPointerMove={handleMove}
onPointerUp={handleUp}
ref={svgRef}
- style={{
- background: 'var(--chakra-colors-bg-inset)',
- borderRadius: 4,
- touchAction: 'none',
- width: '100%',
- }}
viewBox={`0 0 ${CURVE_SIZE} ${CURVE_SIZE}`}
>
- <rect
- fill="var(--chakra-colors-bg-inset)"
+ <CurveRect
+ fill="bg.inset"
height={CURVE_SIZE - CURVE_PADDING * 2}
width={CURVE_SIZE - CURVE_PADDING * 2}
x={CURVE_PADDING}
y={CURVE_PADDING}
/>
- <g stroke="var(--chakra-colors-fg-grid)">
+ <CurveGroup stroke="fg.grid">
{gridCoordinates.map((coordinate) => (
<g key={coordinate}>
<line
@@ -455,18 +509,18 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
/>
</g>
))}
- </g>
- <rect
+ </CurveGroup>
+ <CurveRect
fill="none"
height={CURVE_SIZE - CURVE_PADDING * 2}
- stroke="var(--chakra-colors-border-emphasized)"
+ stroke="border.emphasized"
vectorEffect="non-scaling-stroke"
width={CURVE_SIZE - CURVE_PADDING * 2}
x={CURVE_PADDING}
y={CURVE_PADDING}
/>
- <line
- stroke="var(--chakra-colors-fg-muted)"
+ <CurveLine
+ stroke="fg.subtle"
strokeDasharray="4 4"
vectorEffect="non-scaling-stroke"
x1={CURVE_PADDING}
@@ -474,10 +528,10 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
y1={CURVE_SIZE - CURVE_PADDING}
y2={CURVE_PADDING}
/>
- <path
+ <CurvePath
d={lutPath}
fill="none"
- stroke="var(--chakra-colors-accent-solid)"
+ stroke="accent.solid"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
@@ -486,23 +540,24 @@ const CurvesEditor = ({ adjustments, onCancel, onCommit, onLive }: CurvesEditorP
{points.map((p, i) => {
const { cx, cy } = curvePointToSvg(p[0], p[1]);
return (
- <circle
+ <CurveHandle
cx={cx}
cy={cy}
- fill="var(--chakra-colors-accent-solid)"
+ css={CURVE_HANDLE_CSS}
+ data-index={i}
+ fill="accent.solid"
key={i}
- onContextMenu={(e) => e.preventDefault()}
- onDoubleClick={handleRemove(i)}
- onPointerDown={handlePointDown(i)}
+ onContextMenu={preventDefault}
+ onDoubleClick={handleRemove}
+ onPointerDown={handlePointDown}
r={5}
- stroke="var(--chakra-colors-bg-inset)"
+ stroke="bg.inset"
strokeWidth={2}
- style={{ cursor: 'pointer' }}
vectorEffect="non-scaling-stroke"
/>
);
})}
- </svg>
+ </CurveSvg>
<Text color="fg.muted" fontSize="2xs">
{t('widgets.layers.adjustments.curvesHint')}
</Text>