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.

31.9 KB
Raw Blame
import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';
import type {
  CanvasAdjustmentCurves,
  CanvasAdjustmentEntry,
  CanvasDocumentModel,
  CanvasRasterLayerContractV2,
} from '@workbench/canvas-engine/api';
import type { CanvasPreparedEngine } from '@workbench/widgets/canvas/useStructuralCommit';
import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';
import type { PointerEvent as ReactPointerEvent } from 'react';

import { chakra, createListCollection, HStack, Stack, Text } from '@chakra-ui/react';
import { Field, Select, Slider } from '@platform/ui';
import { IconButton } from '@platform/ui/Button';
import { ScrubberField } from '@platform/ui/ScrubberField';
import { SegmentedControl } from '@platform/ui/SegmentedControl';
import { Tooltip } from '@platform/ui/Tooltip';
import { buildCurveLut } from '@workbench/canvas-engine/api';
import { baselineConfig, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';
import { DicesIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import type { AdjustmentStatusEngine } from './AdjustmentStatusIcon';

import { AdjustmentStatusNotice } from './AdjustmentStatusIcon';
import {
  CURVE_PADDING,
  CURVE_SIZE,
  curvePointFromSvg,
  curvePointToSvg,
  finishCurveDragResult,
  getCurveGridCoordinates,
} from './curveEditorMath';
import {
  createNoiseSeed,
  DEFAULT_CLARITY_SIZE,
  DEFAULT_NOISE_AMOUNT,
  DEFAULT_NOISE_SIZE,
  DEFAULT_TEXTURE_SIZE,
} from './layerOps';

/** Edits subrows through whole-stack patch-config; gestures preview live and commit once. */

export type AdjustmentsEngine = CanvasStructuralEngine & CanvasPreparedEngine & AdjustmentStatusEngine;

const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const;

const CurveSvg = chakra('svg');
const CurveRect = chakra('rect');
const CurveLine = chakra('line');
const CurveGroup = chakra('g');
const CurvePath = chakra('path');
const CurveHandle = chakra('circle');

const CURVE_SVG_CSS = {
  aspectRatio: '1',
  borderRadius: 'l2',
  maxWidth: `${CURVE_SIZE}px`,
  touchAction: 'none',
  userSelect: 'none',
  width: 'full',
};

const CURVE_EDITOR_CSS = { userSelect: 'none' };
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'];

const IDENTITY_CURVE: [number, number][] = [
  [0, 0],
  [255, 255],
];

type EntryPatch = Record<string, unknown>;

const withPatch = (entries: readonly CanvasAdjustmentEntry[], id: string, patch: EntryPatch): CanvasAdjustmentEntry[] =>
  entries.map((candidate) => (candidate.id === id ? ({ ...candidate, ...patch } as CanvasAdjustmentEntry) : candidate));

/** An adjustment stack's owner: a raster layer or a raster-stack group. */
export type AdjustmentOwner = Pick<CanvasRasterLayerContractV2, 'id' | 'adjustments'> & {
  type: 'raster' | 'group';
};

export const AdjustmentSettings = ({
  engine,
  entryId,
  layer,
}: {
  engine: AdjustmentsEngine | null;
  entryId: string;
  layer: AdjustmentOwner;
}) => {
  const entry = layer.adjustments?.find((candidate) => candidate.id === entryId);
  if (!entry) {
    return null;
  }
  return <AdjustmentEntryEditor engine={engine} entry={entry} layer={layer} />;
};

const AdjustmentEntryEditor = ({
  engine,
  entry,
  layer,
}: {
  engine: AdjustmentsEngine | null;
  entry: CanvasAdjustmentEntry;
  layer: AdjustmentOwner;
}) => {
  const { cancel: cancelPreview, commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);
  const { t } = useTranslation();
  // Previews patch the gesture's fields onto the live stack.
  const configOf = useCallback(
    (adjustments: CanvasAdjustmentEntry[]) =>
      layer.type === 'group'
        ? { adjustments, layerType: 'group' as const }
        : { adjustments, layerType: 'raster' as const },
    [layer.type]
  );
  const liveEntries = useCallback(
    (model: CanvasDocumentModel | null | undefined): readonly CanvasAdjustmentEntry[] | null => {
      const owner = model?.getNode(layer.id);
      return owner && 'adjustments' in owner ? (owner.adjustments ?? []) : null;
    },
    [layer.id]
  );
  const currentEntries = useCallback(
    () => liveEntries(engine?.document.model()) ?? layer.adjustments ?? [],
    [engine, layer.adjustments, liveEntries]
  );

  const patchLive = useCallback(
    (patch: EntryPatch) => {
      previewStructural({
        config: configOf(withPatch(currentEntries(), entry.id, patch)),
        id: layer.id,
        type: 'updateCanvasLayerConfig',
      });
    },
    [configOf, currentEntries, entry.id, layer.id, previewStructural]
  );

  // A gesture that ends where it began prepares nothing, which drops its previews.
  const commitEntry = useCallback(
    (label: string, patch: EntryPatch) => {
      commitPrepared(label, (model, baseline) => {
        const entries = liveEntries(model);
        // The entry was removed mid-gesture: committing would resurrect it.
        if (!entries?.some((candidate) => candidate.id === entry.id)) {
          return { ids: [entry.id], status: 'missing' };
        }
        const config = configOf(withPatch(entries, entry.id, patch));
        return model.prepare({ before: baselineConfig(baseline, config), config, id: layer.id, type: 'patch-config' });
      });
    },
    [commitPrepared, configOf, entry.id, layer.id, liveEntries]
  );

  const handleScalarLive = useCallback((field: ScalarField, next: number) => patchLive({ [field]: next }), [patchLive]);
  const handleScalarCommit = useCallback(
    (field: ScalarField, next: number) => commitEntry(t(SCALAR_SPECS[field].labelKey), { [field]: next }),
    [commitEntry, t]
  );
  const handleLevelsCommit = useCallback(
    (patch: Partial<LevelsEntry>) => commitEntry(t('widgets.layers.adjustments.levels'), patch),
    [commitEntry, t]
  );
  const handleNoiseCommit = useCallback(
    (patch: Partial<NoiseEntry>) => commitEntry(t('widgets.layers.adjustments.noise'), patch),
    [commitEntry, t]
  );
  const handleSpatialCommit = useCallback(
    (patch: Partial<SpatialEntry>) => commitEntry(t(`widgets.layers.adjustments.${entry.type}`), patch),
    [commitEntry, entry.type, t]
  );
  const handleCurvesLive = useCallback((curves: CanvasAdjustmentCurves) => patchLive({ curves }), [patchLive]);
  const handleCurvesCommit = useCallback(
    (curves: CanvasAdjustmentCurves) => commitEntry(t('widgets.layers.adjustments.curves'), { curves }),
    [commitEntry, t]
  );

  switch (entry.type) {
    case 'brightness-contrast':
      return (
        <Stack gap="2">
          <ScalarScrubber
            field="brightness"
            value={entry.brightness}
            onCommit={handleScalarCommit}
            onLive={handleScalarLive}
          />
          <ScalarScrubber
            field="contrast"
            value={entry.contrast}
            onCommit={handleScalarCommit}
            onLive={handleScalarLive}
          />
        </Stack>
      );
    case 'exposure':
      return (
        <ScalarScrubber field="stops" value={entry.stops} onCommit={handleScalarCommit} onLive={handleScalarLive} />
      );
    case 'hsl':
      return (
        <ScalarScrubber
          field="saturation"
          value={entry.saturation}
          onCommit={handleScalarCommit}
          onLive={handleScalarLive}
        />
      );
    case 'hue':
      return (
        <ScalarScrubber
          field="rotation"
          value={entry.rotation}
          onCommit={handleScalarCommit}
          onLive={handleScalarLive}
        />
      );
    case 'levels':
      return <LevelsEditor entry={entry} onCommit={handleLevelsCommit} onLive={patchLive} />;
    case 'invert':
      return (
        <Text color="fg.muted" fontSize="md">
          {t('widgets.layers.adjustments.invertHint')}
        </Text>
      );
    case 'noise':
      return <NoiseEditor disabled={engine === null} entry={entry} onCommit={handleNoiseCommit} onLive={patchLive} />;
    case 'clarity':
    case 'texture':
    case 'dehaze':
      return (
        <SpatialEditor
          engine={engine}
          entry={entry}
          ownerId={layer.id}
          ownerType={layer.type}
          onCommit={handleSpatialCommit}
          onLive={patchLive}
        />
      );
    case 'curves':
      return (
        <CurvesEditor
          curves={entry.curves}
          onCancel={cancelPreview}
          onCommit={handleCurvesCommit}
          onLive={handleCurvesLive}
        />
      );
  }
};

type ScalarField = 'brightness' | 'contrast' | 'saturation' | 'rotation' | 'stops';
type LevelsEntry = Extract<CanvasAdjustmentEntry, { type: 'levels' }>;
type NoiseEntry = Extract<CanvasAdjustmentEntry, { type: 'noise' }>;
type SpatialEntry = Extract<CanvasAdjustmentEntry, { type: 'clarity' | 'texture' | 'dehaze' }>;

const formatSigned = (value: number): string => `${value > 0 ? '+' : ''}${value}`;
const formatDegrees = (value: number): string => `${Math.round(value)}°`;
const formatStops = (value: number): string => `${value > 0 ? '+' : ''}${value.toFixed(2)} EV`;

/** A scalar's scrubber range in display units (`scale` × stored); every scalar's identity value is 0. */
interface ScalarSpec {
  labelKey: string;
  min: number;
  max: number;
  step: number;
  scale: number;
  format: (value: number) => string;
}

const SIGNED_UNIT: Omit<ScalarSpec, 'labelKey'> = { format: formatSigned, max: 100, min: -100, scale: 100, step: 1 };

const SCALAR_SPECS: Record<ScalarField, ScalarSpec> = {
  brightness: { ...SIGNED_UNIT, labelKey: 'widgets.layers.adjustments.brightness' },
  contrast: { ...SIGNED_UNIT, labelKey: 'widgets.layers.adjustments.contrast' },
  rotation: {
    format: formatDegrees,
    labelKey: 'widgets.layers.adjustments.hue',
    max: 180,
    min: -180,
    scale: 1,
    step: 1,
  },
  saturation: { ...SIGNED_UNIT, labelKey: 'widgets.layers.adjustments.saturation' },
  stops: {
    format: formatStops,
    labelKey: 'widgets.layers.adjustments.exposure',
    max: 5,
    min: -5,
    scale: 1,
    step: 0.05,
  },
};

const LEVELS_CHANNELS = ['rgb', 'r', 'g', 'b'] as const;

const ScalarScrubber = ({
  field,
  onCommit,
  onLive,
  value,
}: {
  field: ScalarField;
  value: number;
  onLive: (field: ScalarField, next: number) => void;
  onCommit: (field: ScalarField, next: number) => void;
}) => {
  const { t } = useTranslation();
  const spec = SCALAR_SPECS[field];
  // Scaled values round to the step so stored fractions never show float noise.
  const shown = spec.scale === 1 ? value : Math.round(value * spec.scale);
  const handleChange = useCallback((next: number) => onLive(field, next / spec.scale), [field, onLive, spec.scale]);
  const handleChangeEnd = useCallback(
    (next: number) => onCommit(field, next / spec.scale),
    [field, onCommit, spec.scale]
  );

  return (
    <ScrubberField
      defaultValue={0}
      formatValue={spec.format}
      label={t(spec.labelKey)}
      max={spec.max}
      min={spec.min}
      step={spec.step}
      value={shown}
      onChange={handleChange}
      onChangeEnd={handleChangeEnd}
    />
  );
};

const formatGamma = (value: number): string => value.toFixed(2);

/** A pair-of-thumbs range plus a gamma midtone: the classic input/output levels remap. */
const LevelsEditor = ({
  entry,
  onCommit,
  onLive,
}: {
  entry: LevelsEntry;
  onLive: (patch: Partial<LevelsEntry>) => void;
  onCommit: (patch: Partial<LevelsEntry>) => void;
}) => {
  const { t } = useTranslation();
  const inputValue = useMemo(() => [entry.inBlack, entry.inWhite], [entry.inBlack, entry.inWhite]);
  const outputValue = useMemo(() => [entry.outBlack, entry.outWhite], [entry.outBlack, entry.outWhite]);
  const inputAria = useMemo(
    () => [t('widgets.layers.adjustments.inputBlack'), t('widgets.layers.adjustments.inputWhite')],
    [t]
  );
  const outputAria = useMemo(
    () => [t('widgets.layers.adjustments.outputBlack'), t('widgets.layers.adjustments.outputWhite')],
    [t]
  );

  const channelCollection = useMemo(
    () =>
      createListCollection({
        items: LEVELS_CHANNELS.map((channel) => ({
          label: t(`widgets.layers.adjustments.channels.${channel}`),
          value: channel,
        })),
      }),
    [t]
  );
  const channelValue = useMemo(() => [entry.channel ?? 'rgb'], [entry.channel]);
  const handleChannelChange = useCallback(
    ({ value: v }: SelectValueChangeDetails) => {
      const channel = v[0] as LevelsEntry['channel'] | undefined;
      if (channel && channel !== (entry.channel ?? 'rgb')) {
        onCommit({ channel });
      }
    },
    [entry.channel, onCommit]
  );

  const rangePatch = useCallback(
    (v: number[], black: 'inBlack' | 'outBlack', white: 'inWhite' | 'outWhite'): Partial<LevelsEntry> | null =>
      v[0] !== undefined && v[1] !== undefined ? { [black]: v[0], [white]: v[1] } : null,
    []
  );
  const handleInputChange = useCallback(
    ({ value: v }: SliderValueChangeDetails) => {
      const patch = rangePatch(v, 'inBlack', 'inWhite');
      if (patch) {
        onLive(patch);
      }
    },
    [onLive, rangePatch]
  );
  const handleInputCommit = useCallback(
    ({ value: v }: SliderValueChangeDetails) => {
      const patch = rangePatch(v, 'inBlack', 'inWhite');
      if (patch) {
        onCommit(patch);
      }
    },
    [onCommit, rangePatch]
  );
  const handleOutputChange = useCallback(
    ({ value: v }: SliderValueChangeDetails) => {
      const patch = rangePatch(v, 'outBlack', 'outWhite');
      if (patch) {
        onLive(patch);
      }
    },
    [onLive, rangePatch]
  );
  const handleOutputCommit = useCallback(
    ({ value: v }: SliderValueChangeDetails) => {
      const patch = rangePatch(v, 'outBlack', 'outWhite');
      if (patch) {
        onCommit(patch);
      }
    },
    [onCommit, rangePatch]
  );
  const handleGammaChange = useCallback((gamma: number) => onLive({ gamma }), [onLive]);
  const handleGammaCommit = useCallback((gamma: number) => onCommit({ gamma }), [onCommit]);

  return (
    <Stack gap="3">
      <Field label={t('widgets.layers.adjustments.channel')}>
        <Select
          aria-label={t('widgets.layers.adjustments.channel')}
          collection={channelCollection}
          positioning={SELECT_POSITIONING}
          value={channelValue}
          valueText={t(`widgets.layers.adjustments.channels.${entry.channel ?? 'rgb'}`)}
          onValueChange={handleChannelChange}
        />
      </Field>
      <Field label={t('widgets.layers.adjustments.inputLevels')}>
        <Slider
          aria-label={inputAria}
          max={255}
          min={0}
          minStepsBetweenThumbs={1}
          step={1}
          value={inputValue}
          withThumbTooltip
          onValueChange={handleInputChange}
          onValueChangeEnd={handleInputCommit}
        />
      </Field>
      <ScrubberField
        defaultValue={1}
        formatValue={formatGamma}
        label={t('widgets.layers.adjustments.gamma')}
        max={4}
        min={0.1}
        step={0.01}
        value={entry.gamma}
        onChange={handleGammaChange}
        onChangeEnd={handleGammaCommit}
      />
      <Field label={t('widgets.layers.adjustments.outputLevels')}>
        <Slider
          aria-label={outputAria}
          max={255}
          min={0}
          step={1}
          value={outputValue}
          withThumbTooltip
          onValueChange={handleOutputChange}
          onValueChangeEnd={handleOutputCommit}
        />
      </Field>
    </Stack>
  );
};

const NOISE_DISTRIBUTIONS = ['gaussian', 'uniform'] as const;
const NOISE_GRAINS = ['monochrome', 'color', 'chroma'] as const;
const NOISE_RESPONSES = ['flat', 'midtones'] as const;
const NOISE_MIN_SIZE = 1;
const NOISE_MAX_SIZE = 8;

const formatPercent = (value: number): string => `${value}%`;
const formatPixels = (value: number): string => `${value.toFixed(1)} px`;
/** Typed sizes keep their decimals (the field only clamps them); tenths of a pixel match the slider's grid. */
const toNoiseSize = (value: number): number => Math.round(value * 10) / 10;

/** One labelled segmented choice of the noise editor; picking the current option commits nothing. */
const NoiseChoice = <Value extends string>({
  disabled,
  label,
  labelKey,
  onCommit,
  options,
  value,
}: {
  disabled: boolean;
  label: string;
  /** The i18n key prefix of each option's label. */
  labelKey: string;
  onCommit: (value: Value) => void;
  options: readonly Value[];
  value: Value;
}) => {
  const { t } = useTranslation();
  const items = useMemo(
    () => options.map((option) => ({ label: t(`${labelKey}.${option}`), value: option })),
    [labelKey, options, t]
  );
  const handleChange = useCallback(
    (next: string) => {
      if (next !== value) {
        onCommit(next as Value);
      }
    },
    [onCommit, value]
  );
  return (
    <Field disabled={disabled} label={label}>
      <SegmentedControl ariaLabel={label} disabled={disabled} options={items} value={value} onChange={handleChange} />
    </Field>
  );
};

/** Distribution, grain, tonal response and size choices, an amount scrubber in percent, and a seed re-roll. */
const NoiseEditor = ({
  disabled,
  entry,
  onCommit,
  onLive,
}: {
  disabled: boolean;
  entry: NoiseEntry;
  onLive: (patch: Partial<NoiseEntry>) => void;
  onCommit: (patch: Partial<NoiseEntry>) => void;
}) => {
  const { t } = useTranslation();
  const handleDistributionCommit = useCallback(
    (distribution: NoiseEntry['distribution']) => onCommit({ distribution }),
    [onCommit]
  );
  const handleGrainCommit = useCallback((grain: NoiseEntry['grain']) => onCommit({ grain }), [onCommit]);
  const handleResponseCommit = useCallback((response: NoiseEntry['response']) => onCommit({ response }), [onCommit]);
  const handleSizeChange = useCallback((size: number) => onLive({ size: toNoiseSize(size) }), [onLive]);
  const handleSizeCommit = useCallback((size: number) => onCommit({ size: toNoiseSize(size) }), [onCommit]);
  const handleAmountChange = useCallback((percent: number) => onLive({ amount: percent / 100 }), [onLive]);
  const handleAmountCommit = useCallback((percent: number) => onCommit({ amount: percent / 100 }), [onCommit]);
  const handleNewPattern = useCallback(() => onCommit({ seed: createNoiseSeed() }), [onCommit]);
  const newPatternLabel = t('widgets.layers.adjustments.newNoisePattern');

  return (
    <Stack gap="3">
      <NoiseChoice
        disabled={disabled}
        label={t('widgets.layers.adjustments.noiseDistribution')}
        labelKey="widgets.layers.adjustments.noiseDistributions"
        options={NOISE_DISTRIBUTIONS}
        value={entry.distribution}
        onCommit={handleDistributionCommit}
      />
      <NoiseChoice
        disabled={disabled}
        label={t('widgets.layers.adjustments.noiseGrain')}
        labelKey="widgets.layers.adjustments.noiseGrains"
        options={NOISE_GRAINS}
        value={entry.grain}
        onCommit={handleGrainCommit}
      />
      <NoiseChoice
        disabled={disabled}
        label={t('widgets.layers.adjustments.noiseResponse')}
        labelKey="widgets.layers.adjustments.noiseResponses"
        options={NOISE_RESPONSES}
        value={entry.response}
        onCommit={handleResponseCommit}
      />
      <ScrubberField
        defaultValue={DEFAULT_NOISE_SIZE}
        disabled={disabled}
        formatValue={formatPixels}
        label={t('widgets.layers.adjustments.noiseSize')}
        max={NOISE_MAX_SIZE}
        min={NOISE_MIN_SIZE}
        step={0.1}
        value={entry.size}
        onChange={handleSizeChange}
        onChangeEnd={handleSizeCommit}
      />
      <HStack gap="1">
        <ScrubberField
          defaultValue={Math.round(DEFAULT_NOISE_AMOUNT * 100)}
          disabled={disabled}
          flex="1"
          formatValue={formatPercent}
          label={t('widgets.layers.adjustments.noiseAmount')}
          max={100}
          min={0}
          minW="0"
          step={1}
          value={Math.round(entry.amount * 100)}
          onChange={handleAmountChange}
          onChangeEnd={handleAmountCommit}
        />
        <Tooltip content={newPatternLabel}>
          <IconButton
            aria-label={newPatternLabel}
            color="fg.muted"
            disabled={disabled}
            flexShrink={0}
            variant="outline"
            onClick={handleNewPattern}
          >
            <DicesIcon />
          </IconButton>
        </Tooltip>
      </HStack>
    </Stack>
  );
};

/** The spatial amount's range, as on the backend nodes; 0 is identity. */
const SPATIAL_AMOUNT_LIMIT = 200;
/** Feature-size ranges in owner pixels, as on the backend nodes; Dehaze has none (it follows the content's size). */
const SPATIAL_SIZES = {
  clarity: { defaultValue: DEFAULT_CLARITY_SIZE, max: 1000, min: 4 },
  texture: { defaultValue: DEFAULT_TEXTURE_SIZE, max: 100, min: 1 },
} as const;

const formatWholePixels = (value: number): string => `${Math.round(value)} px`;

/** Clarity, Texture and Dehaze: a signed amount, a feature size for the first two, and why the canvas skips them. */
const SpatialEditor = ({
  engine,
  entry,
  onCommit,
  onLive,
  ownerId,
  ownerType,
}: {
  engine: AdjustmentStatusEngine | null;
  entry: SpatialEntry;
  ownerId: string;
  ownerType: AdjustmentOwner['type'];
  onLive: (patch: Partial<SpatialEntry>) => void;
  onCommit: (patch: Partial<SpatialEntry>) => void;
}) => {
  const { t } = useTranslation();
  const handleAmountChange = useCallback((amount: number) => onLive({ amount }), [onLive]);
  const handleAmountCommit = useCallback((amount: number) => onCommit({ amount }), [onCommit]);
  // Whole pixels: a typed fraction would show one size and store another.
  const handleSizeChange = useCallback((size: number) => onLive({ size: Math.round(size) }), [onLive]);
  const handleSizeCommit = useCallback((size: number) => onCommit({ size: Math.round(size) }), [onCommit]);
  const size = entry.type === 'dehaze' ? null : { ...SPATIAL_SIZES[entry.type], value: entry.size };

  return (
    <chakra.div>
      <AdjustmentStatusNotice engine={engine} ownerId={ownerId} />
      <Stack gap="3">
        <ScrubberField
          defaultValue={0}
          formatValue={formatSigned}
          helpText={entry.type === 'dehaze' ? t('widgets.layers.adjustments.dehazeHint') : undefined}
          label={t('widgets.layers.adjustments.amount')}
          max={SPATIAL_AMOUNT_LIMIT}
          min={-SPATIAL_AMOUNT_LIMIT}
          step={1}
          value={Math.round(entry.amount)}
          onChange={handleAmountChange}
          onChangeEnd={handleAmountCommit}
        />
        {size ? (
          <ScrubberField
            defaultValue={size.defaultValue}
            formatValue={formatWholePixels}
            helpText={t(
              ownerType === 'group'
                ? 'widgets.layers.adjustments.sizeHintGroup'
                : 'widgets.layers.adjustments.sizeHintLayer'
            )}
            label={t('widgets.layers.adjustments.size')}
            max={size.max}
            min={size.min}
            // Equal travel per ratio: the small sizes that matter most would otherwise share a sliver of the track.
            scale="log"
            step={1}
            value={size.value}
            onChange={handleSizeChange}
            onChangeEnd={handleSizeCommit}
          />
        ) : null}
      </Stack>
    </chakra.div>
  );
};

const sameChannel = (left: CanvasAdjustmentCurves, right: CanvasAdjustmentCurves, channel: CurveChannel): boolean =>
  JSON.stringify(left[channel] ?? IDENTITY_CURVE) === JSON.stringify(right[channel] ?? IDENTITY_CURVE);

const CurvesEditor = ({
  curves,
  onCancel,
  onCommit,
  onLive,
}: {
  curves: CanvasAdjustmentCurves;
  onLive: (curves: CanvasAdjustmentCurves) => void;
  onCancel: () => void;
  onCommit: (curves: CanvasAdjustmentCurves) => void;
}) => {
  const { t } = useTranslation();
  const [channel, setChannel] = useState<CurveChannel>('r');
  const dragIndexRef = useRef<number | null>(null);
  const svgRef = useRef<SVGSVGElement | null>(null);
  const beforeRef = useRef<CanvasAdjustmentCurves | null>(null);
  const latestPointsRef = useRef<[number, number][] | null>(null);
  const dragTargetRef = useRef<Element | null>(null);

  const points = useMemo<[number, number][]>(() => {
    const raw = curves[channel];
    return raw && raw.length >= 2 ? [...raw].map(([x, y]) => [x, y] as [number, number]) : [...IDENTITY_CURVE];
  }, [channel, curves]);

  const channelCollection = useMemo(
    () =>
      createListCollection({
        items: CURVE_CHANNELS.map((c) => ({ label: t(`widgets.layers.adjustments.channels.${c}`), value: c })),
      }),
    [t]
  );

  const svgPointFromEvent = useCallback((event: { clientX: number; clientY: number }): { px: number; py: number } => {
    const svg = svgRef.current;
    if (!svg) {
      return { px: 0, py: 0 };
    }
    const rect = svg.getBoundingClientRect();
    return {
      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);
    let d = '';
    for (let i = 0; i < 256; i += 4) {
      const { cx, cy } = curvePointToSvg(i, lut[i]);
      d += `${i === 0 ? 'M' : 'L'}${cx.toFixed(1)},${cy.toFixed(1)} `;
    }
    return d.trim();
  }, [points]);
  const gridCoordinates = getCurveGridCoordinates();

  const handleChannelChange = useCallback(
    ({ value }: { value: string[] }) => setChannel((value[0] as CurveChannel) ?? 'r'),
    []
  );

  const handlePointDown = useCallback(
    (event: ReactPointerEvent<SVGCircleElement>) => {
      event.stopPropagation();
      event.preventDefault();
      event.currentTarget.setPointerCapture(event.pointerId);
      dragIndexRef.current = Number(event.currentTarget.dataset.index);
      dragTargetRef.current = event.currentTarget;
      beforeRef.current = curves;
      latestPointsRef.current = null;
    },
    [curves]
  );

  const handleMove = useCallback(
    (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;
        }
        return isEndpoint ? ([p[0], ny] as [number, number]) : ([nx, ny] as [number, number]);
      });
      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({ ...curves, [channel]: next });
    },
    [channel, curves, onLive, points, svgPointFromEvent]
  );

  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;
      const before = beforeRef.current;
      const finalPoints = latestPointsRef.current;
      beforeRef.current = null;
      latestPointsRef.current = null;
      if (wasDragging && before && finalPoints) {
        const current = { ...before, [channel]: finalPoints };
        finishCurveDragResult({
          before,
          cancelled: cancelled || sameChannel(current, before, channel),
          current,
          onCommit,
          onPreview: () => onCancel(),
        });
      }
    },
    [channel, onCancel, onCommit]
  );

  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({ ...curves, [channel]: next });
    },
    [channel, curves, 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({ ...curves, [channel]: points.filter((_, i) => i !== index) });
    },
    [channel, curves, onCommit, points]
  );

  const channelValue = useMemo(() => [channel], [channel]);

  return (
    <Stack css={CURVE_EDITOR_CSS} gap="2">
      <HStack justify="space-between">
        <Text fontSize="md" fontWeight="medium">
          {t('widgets.layers.adjustments.curves')}
        </Text>
        <Select
          aria-label={t('widgets.layers.adjustments.channel')}
          collection={channelCollection}
          positioning={SELECT_POSITIONING}
          value={channelValue}
          valueText={t(`widgets.layers.adjustments.channels.${channel}`)}
          w="6rem"
          onValueChange={handleChannelChange}
        />
      </HStack>
      <CurveSvg
        bg="bg.inset"
        css={CURVE_SVG_CSS}
        onDoubleClick={handleAdd}
        onPointerCancel={handleCancel}
        onPointerMove={handleMove}
        onPointerUp={handleUp}
        ref={svgRef}
        viewBox={`0 0 ${CURVE_SIZE} ${CURVE_SIZE}`}
      >
        <CurveRect
          fill="bg.inset"
          height={CURVE_SIZE - CURVE_PADDING * 2}
          width={CURVE_SIZE - CURVE_PADDING * 2}
          x={CURVE_PADDING}
          y={CURVE_PADDING}
        />
        <CurveGroup stroke="fg.grid">
          {gridCoordinates.map((coordinate) => (
            <g key={coordinate}>
              <line
                vectorEffect="non-scaling-stroke"
                x1={coordinate}
                x2={coordinate}
                y1={CURVE_PADDING}
                y2={CURVE_SIZE - CURVE_PADDING}
              />
              <line
                vectorEffect="non-scaling-stroke"
                x1={CURVE_PADDING}
                x2={CURVE_SIZE - CURVE_PADDING}
                y1={coordinate}
                y2={coordinate}
              />
            </g>
          ))}
        </CurveGroup>
        <CurveRect
          fill="none"
          height={CURVE_SIZE - CURVE_PADDING * 2}
          stroke="border.emphasized"
          vectorEffect="non-scaling-stroke"
          width={CURVE_SIZE - CURVE_PADDING * 2}
          x={CURVE_PADDING}
          y={CURVE_PADDING}
        />
        <CurveLine
          stroke="fg.subtle"
          strokeDasharray="4 4"
          vectorEffect="non-scaling-stroke"
          x1={CURVE_PADDING}
          x2={CURVE_SIZE - CURVE_PADDING}
          y1={CURVE_SIZE - CURVE_PADDING}
          y2={CURVE_PADDING}
        />
        <CurvePath
          d={lutPath}
          fill="none"
          stroke="accent.solid"
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          vectorEffect="non-scaling-stroke"
        />
        {points.map((p, i) => {
          const { cx, cy } = curvePointToSvg(p[0], p[1]);
          return (
            <CurveHandle
              cx={cx}
              cy={cy}
              css={CURVE_HANDLE_CSS}
              data-index={i}
              fill="accent.solid"
              key={i}
              onContextMenu={preventDefault}
              onDoubleClick={handleRemove}
              onPointerDown={handlePointDown}
              r={5}
              stroke="bg.inset"
              strokeWidth={2}
              vectorEffect="non-scaling-stroke"
            />
          );
        })}
      </CurveSvg>
      <Text color="fg.muted" fontSize="xs">
        {t('widgets.layers.adjustments.curvesHint')}
      </Text>
    </Stack>
  );
};