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.

12.7 KB
Raw Blame
import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';
import type { GenerationIssue, GenerationIssueFix } from '@features/generation/core/generationIssues';
import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';

import { Stack } from '@chakra-ui/react';
import { getGenerateInvocationIssues } from '@features/generation/core/baseGenerationPolicies';
import { getGenerationIssueFixPatch } from '@features/generation/core/generationIssues';
import { createExternalStoreCore } from '@platform/state/externalStoreCore';
import { useExternalStoreSelector } from '@platform/state/selectors';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';

import { GenerateAdvancedFields } from './GenerateAdvancedFields';
import { GenerateCanvasSections } from './GenerateCanvasSections';
import { GenerateComponentsSection } from './GenerateComponentsSection';
import {
  applyGenerateSettingsPatch,
  applyGenerateSettingsUpdate,
  getChangedGenerateSettingsPatch,
  type GenerateSettingsUpdate,
  mergeGenerateSettingsUpdate,
  type PendingGenerateSettingsUpdate,
  reuseEqualGenerateSettingsValues,
} from './generateDebounce';
import { GenerateDimensionFields } from './GenerateDimensionFields';
import { useRegisterGenerateDraftFlusher } from './generateDraftRegistry';
import { getSettingsWithLatestPromptFields } from './generateFormViewModel';
import { GenerateGuidanceSection } from './GenerateGuidanceSection';
import { GenerateModelCard } from './GenerateModelCard';
import { GenerateProviderOptionsSection } from './GenerateProviderOptionsSection';
import { GenerateRefinerSection } from './GenerateRefinerSection';
import { GenerateRenderSection } from './GenerateRenderSection';
import { useGenerationUi } from './GenerationUiContext';
import { GeneratePromptFields } from './promptFields';
import { areGenerationIssuesEqual, GenerateIssuesProvider } from './shared/GenerateIssues';

const GENERATE_INPUT_DEBOUNCE_MS = 250;
const NO_ISSUES: readonly GenerationIssue[] = [];

interface GenerateSettingsFormProps {
  isLoadingModels: boolean;
  loadError: string | null;
  settings: GenerateSettings;
  loraModels: LoraModelConfig[];
  models: readonly ModelConfig[];
  projectId: string;
  selectedModel: GenerateModelConfig | undefined;
  supportedModels: GenerateModelConfig[];
  onCommitSettings: (nextSettings: GenerateSettings) => void;
  /** Stable; takes the project the pending edits belong to, which can differ from a stale closure's. */
  onPatchSettings: (patch: Partial<GenerateSettings>, projectId: string) => void;
}

export const GenerateSettingsForm = ({
  isLoadingModels,
  loadError,
  loraModels,
  models,
  onCommitSettings,
  onPatchSettings,
  projectId,
  selectedModel,
  settings,
  supportedModels,
}: GenerateSettingsFormProps) => {
  const ui = useGenerationUi();
  const isCanvasSource = ui.project.invocationSourceId === 'canvas';
  const [draft] = useState(() => createExternalStoreCore(settings));
  const latestSettingsRef = useRef(settings);
  const pendingUpdateRef = useRef<PendingGenerateSettingsUpdate>(null);
  const projectIdRef = useRef(projectId);
  const timeoutRef = useRef<number | null>(null);

  const clearPendingUpdate = () => {
    if (timeoutRef.current !== null) {
      window.clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }

    pendingUpdateRef.current = null;
  };

  useLayoutEffect(() => {
    if (projectIdRef.current !== projectId) {
      projectIdRef.current = projectId;
      clearPendingUpdate();
      latestSettingsRef.current = settings;
      draft.setSnapshot(settings);
      return;
    }

    latestSettingsRef.current = settings;
    draft.setSnapshot(
      reuseEqualGenerateSettingsValues(
        draft.getSnapshot(),
        applyGenerateSettingsUpdate(settings, pendingUpdateRef.current)
      )
    );
  }, [draft, projectId, settings]);

  const flushPendingUpdate = useCallback(
    (shouldUpdateDraft = true) => {
      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }

      const updateToCommit = pendingUpdateRef.current;

      pendingUpdateRef.current = null;

      if (updateToCommit) {
        const previousSettings = latestSettingsRef.current;
        const settingsToCommit = applyGenerateSettingsUpdate(latestSettingsRef.current, updateToCommit);

        latestSettingsRef.current = settingsToCommit;

        if (shouldUpdateDraft) {
          draft.setSnapshot(reuseEqualGenerateSettingsValues(draft.getSnapshot(), settingsToCommit));
        }

        onPatchSettings(getChangedGenerateSettingsPatch(previousSettings, settingsToCommit), projectIdRef.current);
      }
    },
    [draft, onPatchSettings]
  );

  useRegisterGenerateDraftFlusher(flushPendingUpdate);

  // The patch port is stable, so this flushes on unmount.
  useEffect(
    () => () => {
      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
      }

      flushPendingUpdate(false);
    },
    [flushPendingUpdate]
  );

  const scheduleCommitUpdate = useCallback(
    (update: GenerateSettingsUpdate) => {
      pendingUpdateRef.current = mergeGenerateSettingsUpdate(pendingUpdateRef.current, update);

      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
      }

      timeoutRef.current = window.setTimeout(() => {
        timeoutRef.current = null;
        flushPendingUpdate();
      }, GENERATE_INPUT_DEBOUNCE_MS);
    },
    [flushPendingUpdate]
  );

  const commit = useCallback(
    (update: GenerateSettingsUpdate) => {
      const nextSettings = applyGenerateSettingsUpdate(draft.getSnapshot(), mergeGenerateSettingsUpdate(null, update));

      draft.setSnapshot(nextSettings);
      scheduleCommitUpdate(update);
    },
    [draft, scheduleCommitUpdate]
  );

  const commitDebouncedDraftUpdate = useCallback(
    (update: GenerateSettingsUpdate) => {
      const pendingUpdate = mergeGenerateSettingsUpdate(pendingUpdateRef.current, update);
      const previousSettings = latestSettingsRef.current;
      const nextSettings = applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdate);

      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }

      pendingUpdateRef.current = null;
      latestSettingsRef.current = nextSettings;
      draft.setSnapshot(nextSettings);
      onPatchSettings(getChangedGenerateSettingsPatch(previousSettings, nextSettings), projectIdRef.current);
    },
    [draft, onPatchSettings]
  );

  const commitPromptDraftPatch = useCallback(
    (patch: Partial<GenerateSettings>) => {
      const pendingUpdate = mergeGenerateSettingsUpdate(pendingUpdateRef.current, patch);
      const previousSettings = latestSettingsRef.current;
      const nextSettings = applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdate);

      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }

      pendingUpdateRef.current = null;
      latestSettingsRef.current = nextSettings;
      onPatchSettings(getChangedGenerateSettingsPatch(previousSettings, nextSettings), projectIdRef.current);
    },
    [onPatchSettings]
  );

  const commitSettingsImmediately = useCallback(
    (requestedSettings: GenerateSettings) => {
      const previousSettings = latestSettingsRef.current;
      const settingsToCommit = getSettingsWithLatestPromptFields(
        requestedSettings,
        applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdateRef.current)
      );

      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }

      pendingUpdateRef.current = null;
      latestSettingsRef.current = settingsToCommit;
      draft.setSnapshot(settingsToCommit);

      if (!Object.is(previousSettings, settingsToCommit)) {
        onCommitSettings(settingsToCommit);
      }
    },
    [draft, onCommitSettings]
  );

  /** Folds pending edits under `patch` and hands the change to `send` now, so no late debounce can follow it. */
  const sendPatchNow = useCallback(
    (patch: Partial<GenerateSettings>, send: (patch: Partial<GenerateSettings>, projectId: string) => void) => {
      const previousSettings = latestSettingsRef.current;
      const nextSettings = applyGenerateSettingsPatch(
        applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdateRef.current),
        patch
      );

      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }

      pendingUpdateRef.current = null;
      latestSettingsRef.current = nextSettings;
      draft.setSnapshot(nextSettings);
      send(getChangedGenerateSettingsPatch(previousSettings, nextSettings), projectIdRef.current);
    },
    [draft]
  );

  const commitPatchImmediately = useCallback(
    (patch: Partial<GenerateSettings>) => sendPatchNow(patch, onPatchSettings),
    [onPatchSettings, sendPatchNow]
  );

  // A size reset lands at once, ahead of a pending size edit; on the canvas the frame keeps its centre, as for any
  // size.
  const commitSizeReset = useCallback(
    (patch: Partial<GenerateSettings>) => sendPatchNow(patch, onPatchSettings),
    [onPatchSettings, sendPatchNow]
  );

  // The route's own checks on the settings as the form shows them. On a Canvas source the width and height are the
  // frame, which the route reads from the Canvas and keeps in sync with them.
  const selectIssues = useCallback(
    (current: GenerateSettings): readonly GenerationIssue[] => {
      if (!selectedModel) {
        return NO_ISSUES;
      }

      const issues = getGenerateInvocationIssues(
        { ...current, model: selectedModel },
        {
          ...(isCanvasSource ? { canvasFrame: { height: current.height, width: current.width } } : {}),
          // An unread catalog would name every model as missing.
          ...(models.length > 0 ? { models } : {}),
        }
      );

      return issues.length > 0 ? issues : NO_ISSUES;
    },
    [isCanvasSource, models, selectedModel]
  );
  const issues = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectIssues, areGenerationIssuesEqual);
  // Read when the fix runs, so it acts on the latest values rather than those the note rendered with.
  const applyIssueFix = useCallback(
    (fix: GenerationIssueFix) => commitPatchImmediately(getGenerationIssueFixPatch(draft.getSnapshot(), fix)),
    [commitPatchImmediately, draft]
  );

  return (
    <GenerateIssuesProvider applyFix={applyIssueFix} issues={issues}>
      <Stack gap={0}>
        {/* The prompt fields carry their own space below, which matches the side inset here. */}
        <Stack gap={1} px={2} pt={2}>
          <GenerateModelCard
            draft={draft}
            isLoadingModels={isLoadingModels}
            loadError={loadError}
            models={models}
            selectedModel={selectedModel}
            supportedModels={supportedModels}
            onCommitSettings={commitSettingsImmediately}
          />

          <GeneratePromptFields
            draft={draft}
            projectId={projectId}
            selectedModel={selectedModel}
            onCommit={commitPromptDraftPatch}
            onCommitImmediate={commitPatchImmediately}
          />
        </Stack>

        <GenerateDimensionFields
          draft={draft}
          projectId={projectId}
          selectedModel={selectedModel}
          onCommit={commit}
          onResetSize={commitSizeReset}
        />

        <GenerateGuidanceSection
          draft={draft}
          loraModels={loraModels}
          models={models}
          projectId={projectId}
          selectedModel={selectedModel}
          onCommitImmediate={commitPatchImmediately}
          onConceptCommit={commitDebouncedDraftUpdate}
          onReferenceCommit={commit}
        />

        <GenerateRenderSection
          draft={draft}
          selectedModel={selectedModel}
          onCommit={commit}
          onCommitImmediate={commitPatchImmediately}
        />

        <GenerateProviderOptionsSection draft={draft} selectedModel={selectedModel} onCommit={commit} />

        <GenerateComponentsSection draft={draft} selectedModel={selectedModel} onCommit={commitPatchImmediately} />

        <GenerateRefinerSection
          draft={draft}
          selectedModel={selectedModel}
          onCommit={commit}
          onCommitImmediate={commitPatchImmediately}
        />

        <GenerateAdvancedFields
          draft={draft}
          selectedModel={selectedModel}
          onCommit={commit}
          onCommitImmediate={commitPatchImmediately}
        />

        <GenerateCanvasSections />
      </Stack>
    </GenerateIssuesProvider>
  );
};