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.

14.4 KB
Raw Blame
/* 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, react-perf/jsx-no-jsx-as-prop */
import type { RebalancePreset } from '@features/generation/core/conditioningRebalance';
import type { GenerateSettings } from '@features/generation/core/types';

import { Box, createListCollection, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';
import {
  BUILTIN_REBALANCE_PRESETS,
  DEFAULT_KREA2_REBALANCE_MULTIPLIER,
  DEFAULT_KREA2_REBALANCE_WEIGHTS,
  KREA2_REBALANCE_WEIGHT_COUNT,
  matchRebalancePreset,
  parseRebalanceWeights,
  REBALANCE_PRESET_DEFAULT_ID,
  serializeRebalanceWeights,
} from '@features/generation/core/conditioningRebalance';
// Use subpath imports to stay within the direct-importer budget.
import { IconButton } from '@platform/ui/Button';
import { Field } from '@platform/ui/Field';
import { MenuContent } from '@platform/ui/Menu';
import { RenameDialog } from '@platform/ui/RenameDialog';
import { ScrubberField } from '@platform/ui/ScrubberField';
import { Select } from '@platform/ui/Select';
import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
import { MoreHorizontalIcon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useGenerationUi } from './GenerationUiContext';
import { ConditioningRebalanceBars } from './shared/ConditioningRebalanceBars';
import { ConditioningRebalanceSparkline } from './shared/ConditioningRebalanceSparkline';
import { GenerateFieldContextMenu } from './shared/GenerateFieldContextMenu';
import { GenerateToggleSwitch } from './shared/GenerateToggleSwitch';

/** The gain slider's practical range. Typed values may go to the legacy schema's bound. */
const GAIN_SLIDER_MAX = 10;
const GAIN_INPUT_MAX = 20;

const SELECT_CONTENT_PROPS = { maxH: '16rem' } as const;
const READOUT_PROPS = {
  color: 'fg.subtle',
  fontFamily: 'mono',
  fontSize: 'xs',
  // Reserved so the header does not reflow as the readout appears and clears.
  minH: '4',
  whiteSpace: 'nowrap',
} as const;

const DEFAULT_WEIGHT_VECTOR: readonly number[] = parseRebalanceWeights(DEFAULT_KREA2_REBALANCE_WEIGHTS) ?? [];

type PresetDialog = { mode: 'save' } | { mode: 'rename'; preset: RebalancePreset };

interface GenerateConditioningRebalanceFieldProps {
  settings: Pick<GenerateSettings, 'krea2RebalanceEnabled' | 'krea2RebalanceMultiplier' | 'krea2RebalanceWeights'>;
  /** Debounced; used for the continuous controls. */
  onCommit: (patch: Partial<GenerateSettings>) => void;
  /** Immediate; used for discrete edits that should not sit in the draft. */
  onCommitImmediate: (patch: Partial<GenerateSettings>) => void;
}

/** Twelve elementwise encoder gains, ordered shallow to deep. */
export const GenerateConditioningRebalanceField = ({
  onCommit,
  onCommitImmediate,
  settings,
}: GenerateConditioningRebalanceFieldProps) => {
  const { t } = useTranslation();
  const presetActionsIds = useTooltipTriggerIds();
  const { notifications, rebalancePresets } = useGenerationUi();
  const [previewWeights, setPreviewWeights] = useState<number[] | null>(null);
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  /** Non-null while the text field is being typed into, so a half-typed vector survives. */
  const [weightsDraft, setWeightsDraft] = useState<string | null>(null);
  const [presetDialog, setPresetDialog] = useState<PresetDialog | null>(null);

  const committedWeights = useMemo(
    () => parseRebalanceWeights(settings.krea2RebalanceWeights) ?? DEFAULT_WEIGHT_VECTOR,
    [settings.krea2RebalanceWeights]
  );
  const weights = previewWeights ?? committedWeights;
  const isWeightsValid = parseRebalanceWeights(weightsDraft ?? settings.krea2RebalanceWeights) !== null;

  const presets = useMemo<RebalancePreset[]>(
    () => [...BUILTIN_REBALANCE_PRESETS, ...rebalancePresets.presets],
    [rebalancePresets.presets]
  );
  const presetCollection = useMemo(
    () =>
      createListCollection({
        itemToString: (preset: RebalancePreset) => preset.label,
        itemToValue: (preset: RebalancePreset) => preset.id,
        items: presets,
      }),
    [presets]
  );
  const activePresetId = matchRebalancePreset(
    presets,
    settings.krea2RebalanceWeights,
    settings.krea2RebalanceMultiplier
  );
  const activePreset = presets.find((preset) => preset.id === activePresetId) ?? null;
  const isCustomPreset =
    activePreset !== null && !BUILTIN_REBALANCE_PRESETS.some((preset) => preset.id === activePreset.id);
  const isAtDefault = activePresetId === REBALANCE_PRESET_DEFAULT_ID;
  const presetLabel = activePreset?.label ?? t('widgets.generate.krea2RebalancePresetCustom');

  const applyWeights = useCallback(
    (nextWeights: string, multiplier?: number) => {
      setWeightsDraft(null);
      setPreviewWeights(null);
      onCommitImmediate(
        multiplier === undefined
          ? { krea2RebalanceWeights: nextWeights }
          : { krea2RebalanceMultiplier: multiplier, krea2RebalanceWeights: nextWeights }
      );
    },
    [onCommitImmediate]
  );

  const handleBarsCommit = useCallback(
    (nextWeights: number[]) => {
      setWeightsDraft(null);
      setPreviewWeights(null);
      onCommit({ krea2RebalanceWeights: serializeRebalanceWeights(nextWeights) });
    },
    [onCommit]
  );

  const handleWeightsTextChange = useCallback(
    (value: string) => {
      setWeightsDraft(value);

      // Commit only valid vectors; intermediate text stays in the draft.
      if (parseRebalanceWeights(value) !== null) {
        onCommitImmediate({ krea2RebalanceWeights: value });
      }
    },
    [onCommitImmediate]
  );

  const handleReset = useCallback(() => {
    applyWeights(DEFAULT_KREA2_REBALANCE_WEIGHTS, DEFAULT_KREA2_REBALANCE_MULTIPLIER);
  }, [applyWeights]);

  const handlePresetChange = useCallback(
    (presetIds: string[]) => {
      const preset = presets.find((entry) => entry.id === presetIds[0]);

      if (preset) {
        applyWeights(preset.weights, preset.multiplier);
      }
    },
    [applyWeights, presets]
  );

  const handlePresetDialogSubmit = useCallback(
    (label: string) => {
      if (presetDialog?.mode === 'rename') {
        rebalancePresets.rename(presetDialog.preset.id, label);

        return;
      }

      rebalancePresets.save(label, settings.krea2RebalanceWeights, settings.krea2RebalanceMultiplier);
    },
    [presetDialog, rebalancePresets, settings.krea2RebalanceMultiplier, settings.krea2RebalanceWeights]
  );

  // Deleting is undoable, so it asks nothing. The curve stays applied (shown as Custom); Undo brings the preset back,
  // and with it the selection while the curve still matches.
  const deletePreset = useCallback(
    (preset: RebalancePreset) => {
      const index = rebalancePresets.presets.findIndex((candidate) => candidate.id === preset.id);
      const { restore } = rebalancePresets;

      rebalancePresets.remove(preset.id);
      notifications.undoable(t('widgets.generate.krea2RebalancePresetDeleted', { name: preset.label }), {
        onUndo: () => restore(preset, index),
      });
    },
    [notifications, rebalancePresets, t]
  );

  const tapLabel = useCallback(
    (tap: number, layer: number) => t('widgets.generate.krea2RebalanceTapLabel', { layer, tap }),
    [t]
  );

  const activeWeight = activeIndex === null ? undefined : weights[activeIndex];
  const isEnabled = settings.krea2RebalanceEnabled;

  return (
    <>
      <GenerateToggleSwitch
        checked={isEnabled}
        helpText={isEnabled ? undefined : t('widgets.generate.krea2RebalanceHelp')}
        hint="conditioningRebalance"
        label={t('widgets.generate.krea2Rebalance')}
        preview={<ConditioningRebalanceSparkline muted={!isEnabled} weights={committedWeights} />}
        onCheckedChange={(checked) => onCommitImmediate({ krea2RebalanceEnabled: checked })}
      >
        {isEnabled ? (
          <Stack gap="2" w="full">
            <HStack gap="1">
              <Box flex="1" minW="0">
                <GenerateFieldContextMenu
                  fieldLabel={t('widgets.generate.krea2RebalancePreset')}
                  copyValue={() => presetLabel}
                  isAtDefault={isAtDefault}
                  resetLabel={t('widgets.generate.krea2RebalanceReset')}
                  onReset={handleReset}
                >
                  <Select
                    aria-label={t('widgets.generate.krea2RebalancePreset')}
                    collection={presetCollection}
                    contentProps={SELECT_CONTENT_PROPS}
                    value={activePresetId === null ? [] : [activePresetId]}
                    valueText={presetLabel}
                    onValueChange={({ value }) => handlePresetChange(value)}
                  />
                </GenerateFieldContextMenu>
              </Box>
              <Menu.Root ids={presetActionsIds} lazyMount unmountOnExit>
                <Menu.Trigger asChild>
                  <Tooltip content={t('widgets.generate.krea2RebalancePresetActions')} ids={presetActionsIds}>
                    <IconButton
                      aria-label={t('widgets.generate.krea2RebalancePresetActions')}
                      color="fg.muted"
                      size="sm"
                      variant="ghost"
                    >
                      <Icon as={MoreHorizontalIcon} boxSize="3" />
                    </IconButton>
                  </Tooltip>
                </Menu.Trigger>
                <Portal>
                  <Menu.Positioner>
                    <MenuContent minW="11rem">
                      <Menu.Item
                        disabled={!isWeightsValid}
                        value="save"
                        onClick={() => setPresetDialog({ mode: 'save' })}
                      >
                        <Menu.ItemText>{t('widgets.generate.krea2RebalancePresetSave')}</Menu.ItemText>
                      </Menu.Item>
                      <Menu.Item
                        disabled={!isCustomPreset}
                        value="rename"
                        onClick={() => activePreset && setPresetDialog({ mode: 'rename', preset: activePreset })}
                      >
                        <Menu.ItemText>{t('widgets.generate.krea2RebalancePresetRename')}</Menu.ItemText>
                      </Menu.Item>
                      <Menu.Separator />
                      <Menu.Item
                        data-danger=""
                        disabled={!isCustomPreset}
                        value="delete"
                        onClick={() => activePreset && deletePreset(activePreset)}
                      >
                        <Menu.ItemText>{t('widgets.generate.krea2RebalancePresetDelete')}</Menu.ItemText>
                      </Menu.Item>
                    </MenuContent>
                  </Menu.Positioner>
                </Portal>
              </Menu.Root>
            </HStack>

            <Stack gap="1">
              <HStack justify="flex-end" {...READOUT_PROPS}>
                <Text as="span">
                  {activeIndex !== null && activeWeight !== undefined
                    ? t('widgets.generate.krea2RebalanceTapReadout', {
                        tap: activeIndex + 1,
                        value: activeWeight.toFixed(2),
                      })
                    : ''}
                </Text>
              </HStack>
              <ConditioningRebalanceBars
                activeIndex={activeIndex}
                tapLabel={tapLabel}
                weights={weights}
                onActiveIndexChange={setActiveIndex}
                onCommit={handleBarsCommit}
                onPreview={setPreviewWeights}
              />
              <HStack color="fg.subtle" fontSize="xs" justify="space-between">
                <Text as="span">{t('widgets.generate.krea2RebalanceAxisShallow')}</Text>
                <Text as="span">{t('widgets.generate.krea2RebalanceAxisDeep')}</Text>
              </HStack>
            </Stack>

            <GenerateFieldContextMenu
              fieldLabel={t('widgets.generate.krea2RebalanceGain')}
              copyValue={() => String(settings.krea2RebalanceMultiplier)}
              isAtDefault={settings.krea2RebalanceMultiplier === DEFAULT_KREA2_REBALANCE_MULTIPLIER}
              onReset={() => onCommit({ krea2RebalanceMultiplier: DEFAULT_KREA2_REBALANCE_MULTIPLIER })}
              resetLabel={t('widgets.generate.resetToDefault')}
            >
              <ScrubberField
                defaultValue={DEFAULT_KREA2_REBALANCE_MULTIPLIER}
                hint="conditioningRebalanceGain"
                inputMax={GAIN_INPUT_MAX}
                label={t('widgets.generate.krea2RebalanceGain')}
                max={GAIN_SLIDER_MAX}
                min={0}
                step={0.1}
                value={settings.krea2RebalanceMultiplier}
                onChange={(multiplier) => onCommit({ krea2RebalanceMultiplier: multiplier })}
              />
            </GenerateFieldContextMenu>

            <Field
              error={
                isWeightsValid
                  ? undefined
                  : t('widgets.generate.krea2RebalanceWeightsInvalid', { count: KREA2_REBALANCE_WEIGHT_COUNT })
              }
              label={t('widgets.generate.krea2RebalanceWeights')}
            >
              <Input
                aria-label={t('widgets.generate.krea2RebalanceWeights')}
                fontFamily="mono"
                value={
                  weightsDraft ??
                  (previewWeights ? serializeRebalanceWeights(previewWeights) : settings.krea2RebalanceWeights)
                }
                onBlur={() => setWeightsDraft(null)}
                onChange={(event) => handleWeightsTextChange(event.target.value)}
              />
            </Field>
          </Stack>
        ) : null}
      </GenerateToggleSwitch>

      <RenameDialog
        initialName={presetDialog?.mode === 'rename' ? presetDialog.preset.label : ''}
        isOpen={presetDialog !== null}
        label={t('widgets.generate.krea2RebalancePresetName')}
        submitLabel={
          presetDialog?.mode === 'rename'
            ? t('widgets.generate.krea2RebalancePresetRename')
            : t('widgets.generate.krea2RebalancePresetSaveAction')
        }
        title={
          presetDialog?.mode === 'rename'
            ? t('widgets.generate.krea2RebalancePresetRename')
            : t('widgets.generate.krea2RebalancePresetSave')
        }
        onClose={() => setPresetDialog(null)}
        onSubmit={handlePresetDialogSubmit}
      />
    </>
  );
};