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.

19.6 KB
Raw Blame
/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- ListItem slots take JSX; the React Compiler memoizes them. */
import type { ConceptUpdate } from '@features/generation/core/conceptList';
import type { GenerateLora } from '@features/generation/core/types';
import type { MouseEvent, ReactNode } from 'react';

import { Avatar, Badge, Box, chakra, Flex, Icon, Menu, Portal } from '@chakra-ui/react';
import {
  DEFAULT_LORA_WEIGHT_CONFIG,
  getDefaultLoraWeight,
  getLoraWeightSliderRange,
} from '@features/generation/core/settings';
import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
import { useRegisterDraftFlusher } from '@platform/react/draftRegistry';
import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { IconButton } from '@platform/ui/Button';
import { ListItem } from '@platform/ui/list/ListItem';
import { ListStack } from '@platform/ui/list/ListStack';
import { MenuActionItem, MenuContent, useContextMenu } from '@platform/ui/Menu';
import { ScrubberField } from '@platform/ui/ScrubberField';
import { Tooltip } from '@platform/ui/Tooltip';
import {
  BoxIcon,
  EqualIcon,
  ExternalLinkIcon,
  PowerIcon,
  PowerOffIcon,
  RotateCcwIcon,
  Trash2Icon,
  XIcon,
} from 'lucide-react';
import { createContext, memo, use, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { GenerateFieldContextMenu } from './GenerateFieldContextMenu';
import { GenerateRowSwitch } from './GenerateToggleSwitch';

// The track drops marks outside a concept's custom range.
const WEIGHT_MARKS = [-1, 0, 1, 2];

/** The model catalog's helpers a concept row needs; the caller supplies them through its own UI port. */
export interface ConceptModelPort {
  getBaseColorPalette(base: string): string;
  getBaseLabel(base: string): string;
  getImageUrl(key: string): string;
  /** Absent when this session may not manage models; the row then offers no manager link. */
  openInModelManager?: (key: string) => void;
}

export interface ConceptRowProps {
  /** False dims the row, badges it, and locks it off; the caller decides compatibility against its main model. */
  isCompatible?: boolean;
  /**
   * False badges the row as not installed, an error that blocks Invoke while the concept is on: its switch keeps the
   * saved state but is locked, and `issue` says what blocks and how to fix it.
   */
  isInstalled?: boolean;
  /** Shown beside the switch: the issue that blocks Invoke because of this concept, with its fix (an icon button). */
  issue?: ReactNode;
  /** The committed concept. Weight edits stay in a local draft until idle or a workbench flush. */
  lora: GenerateLora;
  models: ConceptModelPort;
  onRemove: (key: string) => void;
  /** Weight commits are debounced; toggles commit immediately. Apply updates to the latest settings. */
  onUpdate: (key: string, update: ConceptUpdate) => void;
}

/** A removed row unmounts with keyboard focus inside it; the next (else previous) row's button takes it instead. */
const findNeighbourRow = (from: Element | null): HTMLElement | null => {
  const item = from?.closest('[role="listitem"]');

  for (const step of ['nextElementSibling', 'previousElementSibling'] as const) {
    for (let sibling = item?.[step]; sibling; sibling = sibling[step]) {
      const primary = sibling.querySelector<HTMLElement>('[data-list-primary]');

      if (primary) {
        return primary;
      }
    }
  }

  return null;
};

interface ListSlot {
  container: Element;
  next: Element | null;
}

/** Where the list sat at each ancestor level, so focus can be placed after the last row unmounts it. */
const captureListSlots = (from: Element | null): ListSlot[] => {
  const slots: ListSlot[] = [];

  for (let node = from?.closest('[role="list"]'); node?.parentElement; node = node.parentElement) {
    slots.push({ container: node.parentElement, next: node.nextElementSibling });
  }

  return slots;
};

const TABBABLE = 'a[href], button, input:not([type="hidden"]), select, textarea, [tabindex], [contenteditable="true"]';

/**
 * The control before the removed list, read after the removal renders: the concept picker, which may only now be
 * enabled once the removed concept is no longer excluded from it.
 */
const findControlBeforeList = (slots: ListSlot[]): HTMLElement | null => {
  for (const { container, next } of slots) {
    if (!container.isConnected) {
      continue;
    }

    const preceding = [...container.querySelectorAll<HTMLElement>(TABBABLE)].filter(
      (element) =>
        element.tabIndex >= 0 &&
        !element.matches(':disabled') &&
        element.getClientRects().length > 0 &&
        (!next?.isConnected || Boolean(next.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING))
    );

    if (preceding.length > 0) {
      return preceding.at(-1) ?? null;
    }
  }

  return null;
};

const ConceptProjectContext = createContext<string | undefined>(undefined);

interface ConceptWeightFieldProps {
  copyValue: () => string;
  defaultWeight: number;
  disabled: boolean;
  fieldLabel: string;
  label: string;
  onChange: (value: number) => void;
  onReset: () => void;
  range: { max: number; min: number };
  resetLabel: string;
  value: number;
}

const ConceptWeightField = ({
  copyValue,
  defaultWeight,
  disabled,
  fieldLabel,
  label,
  onChange,
  onReset,
  range,
  resetLabel,
  value,
}: ConceptWeightFieldProps) => (
  // Backed with the widget's surface so the row's hover tint never washes out the track and fill.
  <Box bg="var(--wb-field-surface, var(--chakra-colors-bg-subtle))" rounded="control">
    <GenerateFieldContextMenu
      fieldLabel={fieldLabel}
      copyValue={copyValue}
      isAtDefault={value === defaultWeight}
      resetLabel={resetLabel}
      onReset={onReset}
    >
      <ScrubberField
        defaultValue={defaultWeight}
        disabled={disabled}
        hint="loraWeight"
        inputMax={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMax}
        inputMin={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMin}
        label={label}
        marks={WEIGHT_MARKS}
        max={range.max}
        min={range.min}
        step={DEFAULT_LORA_WEIGHT_CONFIG.coarseStep}
        value={value}
        onChange={onChange}
      />
    </GenerateFieldContextMenu>
  </Box>
);

/** A short concept list shares its project lifetime with the rows' drafts and menus. */
export const ConceptList = ({
  children,
  label,
  projectId,
}: {
  children: ReactNode;
  label: string;
  projectId: string;
}) => (
  <ConceptProjectContext value={projectId}>
    <ListStack dividers label={label}>
      {children}
    </ListStack>
  </ConceptProjectContext>
);

/**
 * One applied LoRA/concept: a list row (thumbnail, identity, toggle, remove, and a context menu) with its weight
 * scrubber as the row's detail, so the whole item shares one hover surface.
 */
export const ConceptRow = memo(function ConceptRow(props: ConceptRowProps) {
  const projectId = use(ConceptProjectContext);
  const { lora, onUpdate } = props;
  const commitWeight = useCallback(
    (weight: number) => onUpdate(lora.model.key, { weight }),
    [lora.model.key, onUpdate]
  );
  const commitLowNoiseWeight = useCallback(
    (lowNoiseWeight: number) => onUpdate(lora.model.key, { lowNoiseWeight }),
    [lora.model.key, onUpdate]
  );
  const {
    draftValue: weight,
    flushDraftValue,
    setDraftValue,
  } = useDebouncedDraftValue({
    delayMs: 250,
    onCommit: commitWeight,
    resetKey: projectId,
    value: lora.weight,
  });
  const {
    draftValue: lowNoiseWeight,
    flushDraftValue: flushLowNoiseDraftValue,
    replaceDraftValue: replaceLowNoiseDraftValue,
    setDraftValue: setLowNoiseDraftValue,
  } = useDebouncedDraftValue({
    delayMs: 250,
    onCommit: commitLowNoiseWeight,
    resetKey: projectId,
    value: lora.lowNoiseWeight ?? lora.weight,
  });
  useRegisterDraftFlusher(flushDraftValue);
  useRegisterDraftFlusher(flushLowNoiseDraftValue);
  const update = useCallback(
    (key: string, nextUpdate: ConceptUpdate) => {
      if (nextUpdate.lowNoiseWeight === null || nextUpdate.target === null) {
        // Discard any queued low-noise commit so a pending timer cannot resurrect cleared routing.
        replaceLowNoiseDraftValue(lora.weight);
      }
      if (nextUpdate.weight !== undefined) {
        setDraftValue(nextUpdate.weight);
      }
      if (typeof nextUpdate.lowNoiseWeight === 'number') {
        setLowNoiseDraftValue(nextUpdate.lowNoiseWeight);
      }
      if (nextUpdate.weight === undefined && typeof nextUpdate.lowNoiseWeight !== 'number') {
        onUpdate(key, nextUpdate);
      }
    },
    [lora.weight, onUpdate, replaceLowNoiseDraftValue, setDraftValue, setLowNoiseDraftValue]
  );

  // Reset the menu on project changes without remounting/flushing the weight draft into the next project.
  return (
    <ConceptRowContent
      key={projectId}
      {...props}
      lowNoiseWeight={lora.lowNoiseWeight !== undefined ? lowNoiseWeight : undefined}
      weight={weight}
      onUpdate={update}
    />
  );
});

const ConceptRowContent = ({
  isCompatible: isCompatibleModel = true,
  isInstalled = true,
  issue,
  lora,
  lowNoiseWeight,
  models,
  onRemove,
  onUpdate,
  weight,
}: ConceptRowProps & { lowNoiseWeight?: number; weight: number }) => {
  const { t } = useTranslation();
  const { key, name, trigger_phrases: triggerPhrases } = lora.model;
  // A concept that is not installed cannot run either; the row says which of the two it is.
  const isCompatible = isCompatibleModel && isInstalled;
  const isActive = lora.isEnabled && isCompatible;
  const isSplitWeight = lowNoiseWeight !== undefined;
  const defaultWeight = getDefaultLoraWeight(lora.model);
  const weightRange = getLoraWeightSliderRange(lora.model);
  const menu = useContextMenu();
  // Kept through the exit animation: the anchor clears the moment the menu closes.
  const { release: releaseMenu, value: shownAnchor } = useExitRetainedValue(menu.anchor);
  const handleToggle = useCallback((isEnabled: boolean) => onUpdate(key, { isEnabled }), [key, onUpdate]);
  const handleWeightChange = useCallback((weight: number) => onUpdate(key, { weight }), [key, onUpdate]);
  const handleLowNoiseWeightChange = useCallback(
    (nextLowNoiseWeight: number) => onUpdate(key, { lowNoiseWeight: nextLowNoiseWeight }),
    [key, onUpdate]
  );
  const removeFrom = useCallback(
    (origin: Element | null) => {
      const neighbour = findNeighbourRow(origin);
      const slots = neighbour ? [] : captureListSlots(origin);

      onRemove(key);
      requestAnimationFrame(() => (neighbour ?? findControlBeforeList(slots))?.focus());
    },
    [key, onRemove]
  );
  const handleRemoveClick = useCallback(
    (event: MouseEvent<HTMLButtonElement>) => removeFrom(event.currentTarget),
    [removeFrom]
  );
  const handleReset = useCallback(() => onUpdate(key, { weight: defaultWeight }), [defaultWeight, key, onUpdate]);
  const handleResetLowNoise = useCallback(
    () => onUpdate(key, { lowNoiseWeight: defaultWeight }),
    [defaultWeight, key, onUpdate]
  );
  const handleResetRowWeights = useCallback(
    () => onUpdate(key, { weight: defaultWeight, ...(isSplitWeight ? { lowNoiseWeight: defaultWeight } : {}) }),
    [defaultWeight, isSplitWeight, key, onUpdate]
  );
  const handleUseSingleWeight = useCallback(() => onUpdate(key, { lowNoiseWeight: null }), [key, onUpdate]);
  const handleClearTarget = useCallback(() => onUpdate(key, { target: null, lowNoiseWeight: null }), [key, onUpdate]);
  const copyWeight = useCallback(() => String(weight), [weight]);
  const copyLowNoiseWeight = useCallback(() => String(lowNoiseWeight ?? weight), [lowNoiseWeight, weight]);
  const { openInModelManager } = models;

  return (
    <Box role="listitem">
      {/* Naming the group gives the row's "Weight" slider and controls their concept's context. */}
      {/* Only a concept the model skips is dimmed; one that is missing but on blocks Invoke and stays at full strength. */}
      <Box aria-label={name} opacity={isCompatibleModel ? 1 : 0.68} role="group">
        <ListItem
          actions={
            <Flex align="center" gap={1}>
              {issue}
              <GenerateRowSwitch
                checked={isInstalled ? isActive : lora.isEnabled}
                disabled={!isCompatible}
                label={
                  isActive
                    ? t('widgets.generate.disableConcept', { name })
                    : t('widgets.generate.enableConcept', { name })
                }
                onCheckedChange={handleToggle}
              />
              <Tooltip content={t('widgets.generate.removeConcept')}>
                <IconButton
                  aria-label={t('widgets.generate.removeConceptNamed', { name })}
                  color="fg.muted"
                  size="sm"
                  variant="ghost"
                  onClick={handleRemoveClick}
                >
                  <Trash2Icon />
                </IconButton>
              </Tooltip>
            </Flex>
          }
          // The model type sits under the name, with the trigger phrases beside it on the same line.
          description={
            <Flex align="center" flexWrap="wrap" gap="1.5" minW="0">
              <Badge colorPalette={models.getBaseColorPalette(lora.model.base)} flexShrink={0} variant="surface">
                {models.getBaseLabel(lora.model.base)}
              </Badge>
              {lora.target ? (
                <Badge colorPalette="accent" flexShrink={0} variant="surface">
                  {t(`widgets.generate.wanLoraTargets.${lora.target}`)}
                </Badge>
              ) : null}
              {isInstalled ? null : (
                <Badge colorPalette="red" flexShrink={0} variant="solid">
                  {t('widgets.generate.notInstalled')}
                </Badge>
              )}
              {isCompatibleModel ? null : (
                <Badge colorPalette="orange" flexShrink={0} variant="surface">
                  {t('widgets.generate.incompatible')}
                </Badge>
              )}
              {triggerPhrases?.length ? (
                <chakra.span minW="0" truncate>
                  {triggerPhrases.join(', ')}
                </chakra.span>
              ) : null}
            </Flex>
          }
          detail={
            isSplitWeight ? (
              <Flex direction="column" gap="1.5">
                <ConceptWeightField
                  copyValue={copyWeight}
                  defaultWeight={defaultWeight}
                  disabled={!isActive}
                  fieldLabel={t('widgets.generate.conceptHighNoiseWeightNamed', { name })}
                  label={t('widgets.generate.highNoiseWeight')}
                  resetLabel={t('widgets.generate.resetToConceptDefault')}
                  value={weight}
                  onChange={handleWeightChange}
                  onReset={handleReset}
                  range={weightRange}
                />
                <ConceptWeightField
                  copyValue={copyLowNoiseWeight}
                  defaultWeight={defaultWeight}
                  disabled={!isActive}
                  fieldLabel={t('widgets.generate.conceptLowNoiseWeightNamed', { name })}
                  label={t('widgets.generate.lowNoiseWeight')}
                  resetLabel={t('widgets.generate.resetToConceptDefault')}
                  value={lowNoiseWeight}
                  onChange={handleLowNoiseWeightChange}
                  onReset={handleResetLowNoise}
                  range={weightRange}
                />
              </Flex>
            ) : (
              <ConceptWeightField
                copyValue={copyWeight}
                defaultWeight={defaultWeight}
                disabled={!isActive}
                fieldLabel={t('widgets.generate.conceptWeightNamed', { name })}
                label={t('widgets.generate.weight')}
                resetLabel={t('widgets.generate.resetToConceptDefault')}
                value={weight}
                onChange={handleWeightChange}
                onReset={handleReset}
                range={weightRange}
              />
            )
          }
          density="snug"
          leading={
            <Avatar.Root
              bg="bg.muted"
              borderColor="border"
              borderWidth="1px"
              color="fg.subtle"
              flexShrink={0}
              shape="rounded"
              size="xl"
            >
              {/* The fallback also covers a cover image that fails to load. */}
              <Avatar.Fallback>
                <Icon as={BoxIcon} boxSize="4" />
              </Avatar.Fallback>
              {lora.model.cover_image ? <Avatar.Image alt="" src={models.getImageUrl(key)} /> : null}
            </Avatar.Root>
          }
          isMenuOpen={menu.anchor !== null}
          role="presentation"
          title={name}
          onContextMenu={menu.open}
        />
      </Box>
      <Menu.Root
        lazyMount
        open={menu.anchor !== null}
        positioning={{
          getAnchorRect: () => (shownAnchor ? { height: 1, width: 1, x: shownAnchor.x, y: shownAnchor.y } : null),
          placement: 'bottom-start',
        }}
        unmountOnExit
        onExitComplete={releaseMenu}
        onOpenChange={(event) => {
          if (!event.open) {
            menu.close();
          }
        }}
        onRequestDismiss={menu.onRequestDismiss}
      >
        <Portal>
          <Menu.Positioner>
            {shownAnchor ? (
              <MenuContent minW="12rem">
                {openInModelManager ? (
                  <MenuActionItem
                    icon={ExternalLinkIcon}
                    label={t('widgets.generate.conceptMenu.openInModelManager')}
                    value="open-in-model-manager"
                    onSelect={() => openInModelManager(key)}
                  />
                ) : null}
                <MenuActionItem
                  disabled={
                    (weight === defaultWeight && (!isSplitWeight || lowNoiseWeight === defaultWeight)) || !isActive
                  }
                  icon={RotateCcwIcon}
                  label={t('widgets.generate.resetToConceptDefault')}
                  value="reset-weight"
                  onSelect={handleResetRowWeights}
                />
                <MenuActionItem
                  disabled={!isCompatible}
                  icon={isActive ? PowerOffIcon : PowerIcon}
                  label={
                    isActive ? t('widgets.generate.conceptMenu.disable') : t('widgets.generate.conceptMenu.enable')
                  }
                  value="toggle"
                  onSelect={() => handleToggle(!isActive)}
                />
                {isSplitWeight ? (
                  <MenuActionItem
                    icon={EqualIcon}
                    label={t('widgets.generate.conceptMenu.useSingleWeight')}
                    value="use-single-weight"
                    onSelect={handleUseSingleWeight}
                  />
                ) : null}
                {lora.target !== undefined ? (
                  <MenuActionItem
                    icon={XIcon}
                    label={t('widgets.generate.conceptMenu.clearExpertTarget')}
                    value="clear-expert-target"
                    onSelect={handleClearTarget}
                  />
                ) : null}
                <Menu.Separator />
                <MenuActionItem
                  icon={Trash2Icon}
                  label={t('widgets.generate.conceptMenu.remove')}
                  tone="danger"
                  value="remove"
                  onSelect={() => removeFrom(shownAnchor.focusTarget?.() ?? null)}
                />
              </MenuContent>
            ) : null}
          </Menu.Positioner>
        </Portal>
      </Menu.Root>
    </Box>
  );
};