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.

feat(webv2): add the prompt templates picker, editor and view mode

joshistoast992ec7157eb7
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 8a5d9f8066..492b0a7c79 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -981,6 +981,48 @@
"resizeWildcardValues": "Resize wildcard values",
"mode": "Mode",
"newSeedPerImage": "New seed for every image"
+ },
+ "promptTemplates": {
+ "title": "Prompt templates",
+ "newTemplate": "New template",
+ "editTemplate": "Edit template",
+ "search": "Search templates",
+ "yourTemplates": "Your templates",
+ "defaultTemplates": "Built-in templates",
+ "noTemplatesYet": "No templates yet. Create one to reuse a prompt with {prompt} where your own text goes.",
+ "noMatches": "No matching templates",
+ "applied": "Template: {{name}}",
+ "clearApplied": "Stop using {{name}}",
+ "clear": "Clear",
+ "name": "Name",
+ "namePlaceholder": "Cinematic",
+ "nameHelp": "Templates you create are saved to your account.",
+ "nameTooLong": "Name must be at most 128 characters",
+ "positivePrompt": "Template prompt",
+ "positivePromptPlaceholder": "{prompt}. cinematic still, 35mm, shallow depth of field",
+ "negativePrompt": "Template negative prompt",
+ "negativePromptPlaceholder": "{prompt}, blurry, lowres",
+ "resizePositivePrompt": "Resize template prompt",
+ "resizeNegativePrompt": "Resize template negative prompt",
+ "insertPlaceholderHelp": "Insert {prompt}, which your own prompt replaces. Without it the template is added to the end.",
+ "placeholderAlreadyUsed": "Only the first {prompt} is replaced",
+ "image": "Preview image",
+ "addImage": "Add an image",
+ "replaceImage": "Replace image",
+ "removeImage": "Remove image",
+ "import": "Import",
+ "importHelp": "Import templates from a CSV or JSON file with name, prompt and negative_prompt.",
+ "export": "Export",
+ "exportHelp": "Download every user template as a CSV file.",
+ "couldNotSave": "Could not save this template",
+ "couldNotDelete": "Could not delete this template",
+ "couldNotImport": "Could not import templates",
+ "couldNotExport": "Could not export templates",
+ "deleteTitle": "Delete template",
+ "deleteBody": "Delete “{{name}}”? This cannot be undone.",
+ "viewMerged": "Show the merged prompt",
+ "editAuthored": "Back to editing your prompt",
+ "loading": "Loading templates…"
}
},
"upscale": {
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index ee98afeaa1..f4ec81b0a5 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react';
import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
import { invalidateGallery } from '@features/gallery/queries';
import { GenerationUiProvider } from '@features/generation/react';
+import { useCapabilities } from '@features/identity';
import { ensureModelsLoaded, getModelBaseColorPalette, getModelBaseLabel, useModelsSelector } from '@features/models';
import { useQueryClient } from '@tanstack/react-query';
import {
@@ -80,6 +81,11 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
() => ({ patchGenerateSettings: generation.patchSettings }),
[generation]
);
+ const { canManagePromptTemplates } = useCapabilities();
+ const capabilitiesGroup = useMemo<GenerationUiAdapter['capabilities']>(
+ () => ({ canManagePromptTemplates }),
+ [canManagePromptTemplates]
+ );
const generateSectionsOpen = useWorkbenchPreferenceSelector((preferences) => preferences.generateSectionsOpen);
const sectionPreferencesGroup = useMemo<GenerationUiAdapter['sectionPreferences']>(
() => ({
@@ -96,6 +102,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
const adapter = useMemo<GenerationUiAdapter>(
() => ({
CanvasCompositingSection: GenerateCanvasCompositingSection,
+ capabilities: capabilitiesGroup,
gallery: galleryGroup,
models: modelsGroup,
notifications: notificationsGroup,
@@ -104,7 +111,16 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
sectionPreferences: sectionPreferencesGroup,
settings: settingsGroup,
}),
- [galleryGroup, modelsGroup, notificationsGroup, project, promptHistoryGroup, sectionPreferencesGroup, settingsGroup]
+ [
+ capabilitiesGroup,
+ galleryGroup,
+ modelsGroup,
+ notificationsGroup,
+ project,
+ promptHistoryGroup,
+ sectionPreferencesGroup,
+ settingsGroup,
+ ]
);
return <GenerationUiProvider adapter={adapter}>{children}</GenerationUiProvider>;
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
index 4eccf44725..3db1d77c72 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
@@ -33,6 +33,10 @@ export interface GenerationSelectedImage {
*/
export interface GenerationUiAdapter {
CanvasCompositingSection: ComponentType;
+ capabilities: {
+ /** Bulk import/export of prompt templates; the backend routes are admin-only. */
+ canManagePromptTemplates: boolean;
+ };
gallery: {
selectedImage: GenerationSelectedImage | null;
touchImages(): void;
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
index f444b55dbf..7a889facb9 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
@@ -1,5 +1,6 @@
import type { PromptHistoryItem } from '@features/generation/contracts';
import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';
import { Stack } from '@chakra-ui/react';
@@ -73,6 +74,22 @@ export const GeneratePromptFields = ({
const handlePositivePromptChange = useCallback((positivePrompt: string) => onCommit({ positivePrompt }), [onCommit]);
+ const setTemplateViewMode = useCallback(
+ (promptTemplateViewMode: boolean) => onCommitImmediate({ promptTemplateViewMode }),
+ [onCommitImmediate]
+ );
+
+ const applyPromptTemplate = useCallback(
+ (promptTemplate: PromptTemplateSnapshot | null) => onCommitImmediate({ promptTemplate }),
+ [onCommitImmediate]
+ );
+
+ /** Bake the template into the authored prompt and stop applying it. */
+ const flattenPromptTemplate = useCallback(
+ (positivePrompt: string) => onCommitImmediate({ positivePrompt, promptTemplate: null }),
+ [onCommitImmediate]
+ );
+
const handleDynamicPromptsChange = useCallback(
(patch: Partial<DynamicPromptsConfig>) =>
onCommitImmediate(
@@ -129,10 +146,15 @@ export const GeneratePromptFields = ({
value={promptValues.positivePrompt}
loras={settings.loras}
projectId={projectId}
+ promptTemplate={settings.promptTemplate}
selectedModel={selectedModel}
showSyntaxHighlighting={showPromptSyntaxHighlighting}
+ isTemplateViewMode={settings.promptTemplateViewMode}
+ onApplyPromptTemplate={applyPromptTemplate}
onChange={handlePositivePromptChange}
+ onFlattenPromptTemplate={flattenPromptTemplate}
onResizeEnd={handlePositivePromptResizeEnd}
+ onTemplateViewModeChange={setTemplateViewMode}
onUsePrompt={usePromptHistoryItem}
/>
{promptPolicy.negativeVisible ? (
@@ -143,11 +165,14 @@ export const GeneratePromptFields = ({
projectId={projectId}
selectedModel={selectedModel}
helpText={promptPolicy.negativeHelpText}
+ isTemplateViewMode={settings.promptTemplateViewMode}
showSyntaxHighlighting={showPromptSyntaxHighlighting}
+ templateNegativePrompt={settings.promptTemplate?.negativePrompt ?? null}
value={promptValues.negativePrompt}
onEnabledChange={handleNegativePromptEnabledChange}
onChange={handleNegativePromptChange}
onResizeEnd={handleNegativePromptResizeEnd}
+ onTemplateViewModeChange={setTemplateViewMode}
/>
) : null}
</Stack>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
index 6b2111fa26..4205520e60 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
@@ -3,6 +3,7 @@ import type { GenerateLora, GenerateModelConfig } from '@features/generation/cor
import type { ChangeEvent, KeyboardEvent } from 'react';
import { HStack, Switch } from '@chakra-ui/react';
+import { getPromptTemplateChunks } from '@features/generation/core/promptTemplates';
import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';
import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
import { Field } from '@platform/ui';
@@ -19,6 +20,11 @@ const PROMPT_INPUT_DEBOUNCE_MS = 250;
interface NegativePromptFieldProps {
heightPx: number;
+ /** The active template's negative side, or null when none is applied. */
+ templateNegativePrompt?: string | null;
+ /** Show the merged prompt read-only instead of the authored text. */
+ isTemplateViewMode?: boolean;
+ onTemplateViewModeChange?: (viewMode: boolean) => void;
helpText?: string;
isEnabled: boolean;
loras: GenerateLora[];
@@ -45,13 +51,16 @@ export const NegativePromptField = ({
heightPx,
helpText,
isEnabled,
+ isTemplateViewMode = false,
loras,
onChange,
onEnabledChange,
onResizeEnd,
+ onTemplateViewModeChange,
projectId,
selectedModel,
showSyntaxHighlighting,
+ templateNegativePrompt = null,
value,
}: NegativePromptFieldProps) => {
const { t } = useTranslation();
@@ -171,7 +180,7 @@ export const NegativePromptField = ({
<HStack gap="0.5">
{isEnabled ? (
<AddPromptTriggerButton
- isOpen={triggerPickerState !== null}
+ isOpen={triggerPickerState !== null || isTemplateViewMode}
onOpenPromptTriggerPicker={handleOpenPromptTriggerPicker}
/>
) : null}
@@ -189,7 +198,15 @@ export const NegativePromptField = ({
</Switch.Root>
</HStack>
),
- [enableSwitchInputId, handleEnabledChange, handleOpenPromptTriggerPicker, isEnabled, t, triggerPickerState]
+ [
+ enableSwitchInputId,
+ handleEnabledChange,
+ handleOpenPromptTriggerPicker,
+ isEnabled,
+ isTemplateViewMode,
+ t,
+ triggerPickerState,
+ ]
);
const triggerPickerPositioning = useMemo(
@@ -197,6 +214,15 @@ export const NegativePromptField = ({
[triggerPickerState]
);
+ // Same textarea, read-only, as on the positive side — swapping in a different
+ // component would reset the resizer's mounted height.
+ const isViewingMerged = isTemplateViewMode && templateNegativePrompt !== null;
+ const templateChunks = useMemo(
+ () => (isViewingMerged ? getPromptTemplateChunks(draftValue, templateNegativePrompt) : null),
+ [draftValue, isViewingMerged, templateNegativePrompt]
+ );
+ const exitViewMode = useCallback(() => onTemplateViewModeChange?.(false), [onTemplateViewModeChange]);
+
return (
<Field label={t('widgets.generate.negativePrompt')} labelEnd={labelEnd} helpText={isEnabled ? helpText : undefined}>
{isEnabled ? (
@@ -209,10 +235,14 @@ export const NegativePromptField = ({
resizeHandleAriaLabel={t('widgets.generate.resizeNegativePrompt')}
size="xs"
fontFamily="mono"
+ readOnly={isViewingMerged}
showSyntaxHighlighting={showSyntaxHighlighting}
+ templateChunks={templateChunks}
textareaRef={handleTextareaRef}
- value={draftValue}
+ title={isViewingMerged ? t('widgets.generate.promptTemplates.editAuthored') : undefined}
+ value={templateChunks ? templateChunks.join('') : draftValue}
onChange={handlePromptChange}
+ onClick={isViewingMerged ? exitViewMode : undefined}
onKeyDown={handlePromptKeyDown}
onResizeEnd={onResizeEnd}
/>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
index e3cc2913df..3f3b630cbb 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -1,5 +1,6 @@
/* eslint-disable react/react-compiler */
import type { GenerationModelCatalogItem as ModelConfig, PromptHistoryItem } from '@features/generation/contracts';
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';
import type { DynamicPromptsFieldConfig } from '@features/generation/ui/promptFields/DynamicPromptsPanel';
import type { ChangeEvent, MouseEvent } from 'react';
@@ -9,11 +10,21 @@ import { filterPromptHistory } from '@features/generation/core/promptHistory';
import { expandPrompt, imageToPrompt } from '@features/generation/data/promptUtilities';
import { GenerationModelSelect as ModelSelect, useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { DynamicPromptsButton } from '@features/generation/ui/promptFields/DynamicPromptsButton';
+import { PromptTemplatesButton } from '@features/generation/ui/promptFields/PromptTemplatesButton';
import { useWildcards } from '@features/generation/ui/useWildcards';
import { useMountEffect } from '@platform/react/useMountEffect';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton, Scrollable, Tooltip } from '@platform/ui';
-import { HistoryIcon, ImageUpIcon, PlusIcon, SparklesIcon, TrashIcon, Undo2Icon } from 'lucide-react';
+import {
+ EyeIcon,
+ EyeOffIcon,
+ HistoryIcon,
+ ImageUpIcon,
+ PencilSparklesIcon,
+ PlusIcon,
+ TrashIcon,
+ Undo2Icon,
+} from 'lucide-react';
import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,9 +33,14 @@ const TEXT_LLM_MODEL_TYPES = ['text_llm'];
const LLAVA_MODEL_TYPES = ['llava_onevision'];
interface PositivePromptActionsProps {
+ /** The applied template, or null. Absent surfaces get no templates button. */
+ activeTemplate: PromptTemplateSnapshot | null;
batchCount: number;
/** Absent on surfaces whose prompt is not batch-expanded (Upscale). */
dynamicPrompts: DynamicPromptsFieldConfig | null;
+ /** The authored prompt wrapped by the active template — what actually expands. */
+ effectivePositivePrompt: string;
+ hasPromptTemplate: boolean;
loras: GenerateLora[];
isPromptTriggerPickerOpen: boolean;
onUsePrompt: (prompt: PromptHistoryItem) => void;
@@ -33,17 +49,29 @@ interface PositivePromptActionsProps {
projectId: string;
onOpenPromptTriggerPicker: (anchorElement: HTMLElement) => void;
onPositivePromptChangeImmediate: (prompt: string) => void;
+ onFlattenPromptTemplate: (prompt: string) => void;
+ /** Absent on surfaces with no template concept (Upscale). */
+ onApplyPromptTemplate?: (template: PromptTemplateSnapshot | null) => void;
+ isTemplateViewMode: boolean;
+ onTemplateViewModeChange?: (viewMode: boolean) => void;
onInsertText: (text: string) => void;
showSyntaxHighlighting: boolean;
}
export const PositivePromptActions = ({
+ activeTemplate,
batchCount,
dynamicPrompts,
+ effectivePositivePrompt,
+ hasPromptTemplate,
isPromptTriggerPickerOpen,
+ isTemplateViewMode,
+ onApplyPromptTemplate,
+ onFlattenPromptTemplate,
onInsertText,
onOpenPromptTriggerPicker,
onPositivePromptChangeImmediate,
+ onTemplateViewModeChange,
onUsePrompt,
positivePrompt,
projectId,
@@ -51,26 +79,46 @@ export const PositivePromptActions = ({
}: PositivePromptActionsProps) => {
return (
<HStack gap="0.5">
+ {onApplyPromptTemplate ? (
+ <PromptTemplatesButton
+ activeTemplate={activeTemplate}
+ showSyntaxHighlighting={showSyntaxHighlighting}
+ onApply={onApplyPromptTemplate}
+ />
+ ) : null}
+ {hasPromptTemplate && onTemplateViewModeChange ? (
+ <TemplateViewModeButton isViewMode={isTemplateViewMode} onChange={onTemplateViewModeChange} />
+ ) : null}
{dynamicPrompts ? (
<DynamicPromptsButton
batchCount={batchCount}
config={dynamicPrompts}
- positivePrompt={positivePrompt}
+ positivePrompt={effectivePositivePrompt}
showSyntaxHighlighting={showSyntaxHighlighting}
onInsertText={onInsertText}
- onUsePrompt={onPositivePromptChangeImmediate}
+ // Picking one expansion writes already-merged text into the authored
+ // field, so the template has to come off in the same commit or the next
+ // Invoke would wrap it again.
+ onUsePrompt={hasPromptTemplate ? onFlattenPromptTemplate : onPositivePromptChangeImmediate}
/>
) : null}
+ {/* These three rewrite the authored prompt, which view mode is hiding, so
+ they stay out of reach until the user is looking at their own text. */}
<AddPromptTriggerButton
- isOpen={isPromptTriggerPickerOpen}
+ isOpen={isPromptTriggerPickerOpen || isTemplateViewMode}
onOpenPromptTriggerPicker={onOpenPromptTriggerPicker}
/>
<ExpandPromptButton
+ isDisabled={isTemplateViewMode}
positivePrompt={positivePrompt}
projectId={projectId}
onPositivePromptChange={onPositivePromptChangeImmediate}
/>
- <ImageToPromptButton projectId={projectId} onPositivePromptChange={onPositivePromptChangeImmediate} />
+ <ImageToPromptButton
+ isDisabled={isTemplateViewMode}
+ projectId={projectId}
+ onPositivePromptChange={onPositivePromptChangeImmediate}
+ />
<PositivePromptHistoryButton onUsePrompt={onUsePrompt} />
</HStack>
);
@@ -155,6 +203,32 @@ const getPromptTriggerOptions = ({
});
};
+/**
+ * Swaps the prompt box between the authored text and the merged result. Quiet
+ * states only — the icon changes, nothing tints or animates.
+ */
+const TemplateViewModeButton = ({
+ isViewMode,
+ onChange,
+}: {
+ isViewMode: boolean;
+ onChange: (viewMode: boolean) => void;
+}) => {
+ const { t } = useTranslation();
+ const handleClick = useCallback(() => onChange(!isViewMode), [isViewMode, onChange]);
+ const label = isViewMode
+ ? t('widgets.generate.promptTemplates.editAuthored')
+ : t('widgets.generate.promptTemplates.viewMerged');
+
+ return (
+ <Tooltip content={label}>
+ <IconButton aria-label={label} aria-pressed={isViewMode} size="2xs" variant="ghost" onClick={handleClick}>
+ {isViewMode ? <EyeOffIcon /> : <EyeIcon />}
+ </IconButton>
+ </Tooltip>
+ );
+};
+
export const AddPromptTriggerButton = ({
isOpen,
onOpenPromptTriggerPicker,
@@ -340,10 +414,12 @@ const PromptTriggerOptionButton = ({
};
const ExpandPromptButton = ({
+ isDisabled,
onPositivePromptChange,
positivePrompt,
projectId,
}: {
+ isDisabled: boolean;
positivePrompt: string;
projectId: string;
onPositivePromptChange: (prompt: string) => void;
@@ -417,11 +493,11 @@ const ExpandPromptButton = ({
<Popover.Trigger asChild>
<IconButton
aria-label={t('widgets.generate.expandPrompt')}
- disabled={isLoading || !positivePrompt.trim()}
+ disabled={isDisabled || isLoading || !positivePrompt.trim()}
size="2xs"
variant="ghost"
>
- <SparklesIcon />
+ <PencilSparklesIcon />
</IconButton>
</Popover.Trigger>
</Tooltip>
@@ -467,9 +543,11 @@ const ExpandPromptButton = ({
};
const ImageToPromptButton = ({
+ isDisabled,
onPositivePromptChange,
projectId,
}: {
+ isDisabled: boolean;
projectId: string;
onPositivePromptChange: (prompt: string) => void;
}) => {
@@ -541,7 +619,12 @@ const ImageToPromptButton = ({
ids={popoverIds}
>
<Popover.Trigger asChild>
- <IconButton aria-label={t('widgets.generate.imageToPrompt')} disabled={isLoading} size="2xs" variant="ghost">
+ <IconButton
+ aria-label={t('widgets.generate.imageToPrompt')}
+ disabled={isDisabled || isLoading}
+ size="2xs"
+ variant="ghost"
+ >
<ImageUpIcon />
</IconButton>
</Popover.Trigger>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
index 5600695ae5..5853537b80 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -1,7 +1,9 @@
import type { PromptHistoryItem } from '@features/generation/contracts';
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';
import type { ChangeEvent, KeyboardEvent } from 'react';
+import { applyPromptTemplate, getPromptTemplateChunks } from '@features/generation/core/promptTemplates';
import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';
import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
import { useWildcards } from '@features/generation/ui/useWildcards';
@@ -29,6 +31,11 @@ interface PositivePromptFieldProps {
batchCount?: number;
/** Absent on surfaces whose prompt is not batch-expanded (Upscale). */
dynamicPrompts?: DynamicPromptsFieldConfig | null;
+ /** Absent on surfaces with no template concept (Upscale). */
+ promptTemplate?: PromptTemplateSnapshot | null;
+ /** Show the merged prompt read-only instead of the authored text. */
+ isTemplateViewMode?: boolean;
+ onTemplateViewModeChange?: (viewMode: boolean) => void;
heightPx: number;
loras: GenerateLora[];
projectId: string;
@@ -36,6 +43,13 @@ interface PositivePromptFieldProps {
showSyntaxHighlighting: boolean;
value: string;
onChange: (value: string) => void;
+ /**
+ * Replace the authored prompt with already-merged text and drop the template in
+ * one commit. Absent on surfaces with no template concept.
+ */
+ onFlattenPromptTemplate?: (prompt: string) => void;
+ /** Apply or clear the active template. Absent on surfaces with no templates. */
+ onApplyPromptTemplate?: (template: PromptTemplateSnapshot | null) => void;
onResizeEnd: (heightPx: number) => void;
onUsePrompt: (prompt: PromptHistoryItem) => void;
}
@@ -54,11 +68,16 @@ export const PositivePromptField = ({
batchCount = 1,
dynamicPrompts = null,
heightPx,
+ isTemplateViewMode = false,
loras,
+ onApplyPromptTemplate,
onChange,
+ onFlattenPromptTemplate,
onResizeEnd,
+ onTemplateViewModeChange,
onUsePrompt,
projectId,
+ promptTemplate = null,
selectedModel,
showSyntaxHighlighting,
value,
@@ -187,6 +206,23 @@ export const PositivePromptField = ({
[commitPromptChange, draftValue]
);
+ // Merged against the *draft*, not the committed value: the template lives in the
+ // store but the draft runs 250ms ahead of it, and reading the store here would
+ // leave the expansion count a debounce behind what the user is typing.
+ const effectivePositivePrompt = useMemo(
+ () => (promptTemplate ? applyPromptTemplate(promptTemplate.positivePrompt, draftValue) : draftValue),
+ [draftValue, promptTemplate]
+ );
+
+ const flattenPromptTemplate = useCallback(
+ (prompt: string) => {
+ promptHistoryNavigation.reset();
+ replaceDraftValue(prompt);
+ onFlattenPromptTemplate?.(prompt);
+ },
+ [onFlattenPromptTemplate, replaceDraftValue]
+ );
+
const labelEnd = useMemo(
() => (
<PositivePromptActions
@@ -197,6 +233,13 @@ export const PositivePromptField = ({
onInsertText={insertTextAtCaret}
loras={loras}
positivePrompt={draftValue}
+ activeTemplate={promptTemplate}
+ effectivePositivePrompt={effectivePositivePrompt}
+ hasPromptTemplate={promptTemplate !== null}
+ isTemplateViewMode={isTemplateViewMode}
+ onApplyPromptTemplate={onApplyPromptTemplate}
+ onTemplateViewModeChange={onTemplateViewModeChange}
+ onFlattenPromptTemplate={flattenPromptTemplate}
projectId={projectId}
selectedModel={selectedModel}
onOpenPromptTriggerPicker={handleOpenPromptTriggerPicker}
@@ -209,11 +252,17 @@ export const PositivePromptField = ({
commitPromptChangeImmediately,
draftValue,
dynamicPrompts,
+ effectivePositivePrompt,
+ flattenPromptTemplate,
handleOpenPromptTriggerPicker,
handleUsePrompt,
insertTextAtCaret,
+ isTemplateViewMode,
loras,
+ onApplyPromptTemplate,
+ onTemplateViewModeChange,
projectId,
+ promptTemplate,
selectedModel,
showSyntaxHighlighting,
triggerPickerState,
@@ -225,6 +274,19 @@ export const PositivePromptField = ({
[commitPromptChange]
);
+ // View mode keeps the same textarea rather than swapping in a preview
+ // component: `ResizableTextarea` reads its height once on mount, and the
+ // element is also what `focusPositivePrompt` and the attention hotkeys target,
+ // so unmounting it would reset the height and break both.
+ const isViewingMerged = isTemplateViewMode && promptTemplate !== null;
+ const templateChunks = useMemo(
+ () => (isViewingMerged ? getPromptTemplateChunks(draftValue, promptTemplate.positivePrompt) : null),
+ [draftValue, isViewingMerged, promptTemplate]
+ );
+
+ /** Clicking the merged text is the way back to editing, as it is in legacy. */
+ const exitViewMode = useCallback(() => onTemplateViewModeChange?.(false), [onTemplateViewModeChange]);
+
const triggerPickerPositioning = useMemo(
() => ({ getAnchorRect: () => triggerPickerState?.anchorRect ?? null }),
[triggerPickerState]
@@ -242,10 +304,14 @@ export const PositivePromptField = ({
fontFamily="mono"
highlightDynamicPrompts={dynamicPrompts !== null}
knownWildcards={knownWildcards}
+ readOnly={isViewingMerged}
showSyntaxHighlighting={showSyntaxHighlighting}
+ templateChunks={templateChunks}
textareaRef={handleTextareaRef}
- value={draftValue}
+ title={isViewingMerged ? t('widgets.generate.promptTemplates.editAuthored') : undefined}
+ value={isViewingMerged ? effectivePositivePrompt : draftValue}
onChange={handlePromptChange}
+ onClick={isViewingMerged ? exitViewMode : undefined}
onKeyDown={handlePromptKeyDown}
onResizeEnd={onResizeEnd}
/>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
new file mode 100644
index 0000000000..66003a3977
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
@@ -0,0 +1,307 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { PromptTemplateDraft, PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type { PendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';
+import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
+import type { ChangeEvent } from 'react';
+
+import { HStack, Image, Input, Stack, Text } from '@chakra-ui/react';
+import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTemplates';
+import { fetchPromptTemplateImage } from '@features/generation/data/promptTemplates';
+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
+import { PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
+import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button, IconButton } from '@platform/ui/Button';
+import { DropZone } from '@platform/ui/DropZone';
+import { Field } from '@platform/ui/Field';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { CheckIcon, ImageUpIcon, XIcon } from 'lucide-react';
+import { useCallback, useId, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface PromptTemplateEditorProps {
+ catalog: PromptTemplateCatalog;
+ /** The template being edited, or null when composing a new one. */
+ template: PromptTemplateRecord | null;
+ /** Prompts to start a new template from, e.g. handed over from an image. */
+ prefill?: PendingPromptTemplateDraft;
+ showSyntaxHighlighting: boolean;
+ onCancel: () => void;
+ onSaved: (template: PromptTemplateRecord) => void;
+}
+
+interface EditorDraft {
+ name: string;
+ negativePrompt: string;
+ positivePrompt: string;
+ image: Blob | null;
+ imagePreviewUrl: string | null;
+}
+
+const MAX_NAME_LENGTH = 128;
+
+export const PromptTemplateEditor = ({
+ catalog,
+ onCancel,
+ onSaved,
+ prefill,
+ showSyntaxHighlighting,
+ template,
+}: PromptTemplateEditorProps) => {
+ const { t } = useTranslation();
+ const { notifications } = useGenerationUi();
+ const nameFieldId = useId();
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const [draft, setDraft] = useState<EditorDraft>({
+ image: null,
+ imagePreviewUrl: template?.imageUrl ?? null,
+ name: template?.name ?? '',
+ negativePrompt: template?.negativePrompt ?? prefill?.negativePrompt ?? '',
+ positivePrompt: template?.positivePrompt ?? prefill?.positivePrompt ?? '',
+ });
+ const [isSaving, setIsSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // The backend replaces the whole record, so saving without resending the
+ // existing image would drop it. Load it up front and treat it as part of the
+ // draft from then on.
+ useMountEffect(() => {
+ const imageUrl = template?.imageUrl;
+
+ if (!imageUrl) {
+ return;
+ }
+
+ void fetchPromptTemplateImage(imageUrl).then((image) => {
+ if (image) {
+ setDraft((current) => (current.image ? current : { ...current, image }));
+ }
+ });
+ });
+
+ const trimmedName = draft.name.trim();
+ const isPlaceholderPresent = draft.positivePrompt.includes(PROMPT_TEMPLATE_PLACEHOLDER);
+ const nameError = trimmedName.length > MAX_NAME_LENGTH ? t('widgets.generate.promptTemplates.nameTooLong') : null;
+
+ const save = useCallback(async () => {
+ const nextDraft: PromptTemplateDraft = {
+ image: draft.image,
+ name: trimmedName,
+ negativePrompt: draft.negativePrompt,
+ positivePrompt: draft.positivePrompt,
+ };
+
+ setIsSaving(true);
+ setError(null);
+
+ try {
+ const saved = template ? await catalog.update(template.id, nextDraft) : await catalog.create(nextDraft);
+
+ onSaved(saved);
+ } catch (caught) {
+ // `ApiError.message` is the raw response body, so the backend's own
+ // explanation only reads properly once it is unwrapped.
+ setError(getApiErrorMessage(caught, t('widgets.generate.promptTemplates.couldNotSave')));
+ } finally {
+ setIsSaving(false);
+ }
+ }, [catalog, draft, onSaved, t, template, trimmedName]);
+
+ const insertPlaceholder = useCallback(
+ () =>
+ setDraft((current) => ({
+ ...current,
+ positivePrompt: current.positivePrompt
+ ? `${current.positivePrompt} ${PROMPT_TEMPLATE_PLACEHOLDER}`
+ : PROMPT_TEMPLATE_PLACEHOLDER,
+ })),
+ []
+ );
+
+ const pickImage = useCallback(() => fileInputRef.current?.click(), []);
+
+ // The value has to be read before `setDraft`, not inside the updater: React
+ // nulls `currentTarget` once the handler returns, and an updater can run after
+ // that.
+ const updateDraftField = useCallback(
+ (field: 'name' | 'negativePrompt' | 'positivePrompt', value: string) =>
+ setDraft((current) => ({ ...current, [field]: value })),
+ []
+ );
+
+ const handleImageChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ if (file) {
+ setDraft((current) => ({ ...current, image: file, imagePreviewUrl: URL.createObjectURL(file) }));
+ }
+
+ // Reset so re-picking the same file still fires a change.
+ event.currentTarget.value = '';
+ }, []);
+
+ const clearImage = useCallback(() => setDraft((current) => ({ ...current, image: null, imagePreviewUrl: null })), []);
+
+ const reportSaveError = useCallback(
+ (caught: unknown) =>
+ notifications.reportError({
+ area: 'save-prompt-template',
+ message: getApiErrorMessage(caught, t('widgets.generate.promptTemplates.couldNotSave')),
+ namespace: 'generation',
+ }),
+ [notifications, t]
+ );
+
+ const handleSave = useCallback(() => void save().catch(reportSaveError), [reportSaveError, save]);
+
+ const insertPlaceholderControl = useMemo(
+ () => (
+ <Tooltip
+ content={
+ isPlaceholderPresent
+ ? t('widgets.generate.promptTemplates.placeholderAlreadyUsed')
+ : t('widgets.generate.promptTemplates.insertPlaceholderHelp')
+ }
+ >
+ <Button disabled={isPlaceholderPresent} size="2xs" variant="ghost" onClick={insertPlaceholder}>
+ {PROMPT_TEMPLATE_PLACEHOLDER}
+ </Button>
+ </Tooltip>
+ ),
+ [insertPlaceholder, isPlaceholderPresent, t]
+ );
+
+ return (
+ <Stack gap="2">
+ <PromptPanelHeader
+ label={
+ template
+ ? t('widgets.generate.promptTemplates.editTemplate')
+ : t('widgets.generate.promptTemplates.newTemplate')
+ }
+ />
+
+ <Field
+ error={nameError}
+ id={nameFieldId}
+ label={t('widgets.generate.promptTemplates.name')}
+ helpText={t('widgets.generate.promptTemplates.nameHelp')}
+ >
+ <Input
+ aria-invalid={nameError !== null ? true : undefined}
+ id={nameFieldId}
+ placeholder={t('widgets.generate.promptTemplates.namePlaceholder')}
+ size="xs"
+ value={draft.name}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => updateDraftField('name', event.currentTarget.value)}
+ />
+ </Field>
+
+ <Field label={t('common.prompt')} labelEnd={insertPlaceholderControl}>
+ {/* `highlightDynamicPrompts` stays off here: `{prompt}` is a template
+ placeholder, and colouring it as a dynamic-prompt group would promise
+ an expansion that the merge consumes before one could happen. */}
+ <PromptTextarea
+ aria-label={t('widgets.generate.promptTemplates.positivePrompt')}
+ defaultHeightPx={80}
+ fontSize="0.72rem"
+ maxHeightPx={240}
+ minHeightPx={64}
+ placeholder={t('widgets.generate.promptTemplates.positivePromptPlaceholder')}
+ resizeHandleAriaLabel={t('widgets.generate.promptTemplates.resizePositivePrompt')}
+ showSyntaxHighlighting={showSyntaxHighlighting}
+ size="xs"
+ value={draft.positivePrompt}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ updateDraftField('positivePrompt', event.currentTarget.value)
+ }
+ />
+ </Field>
+
+ <Field label={t('common.negative')}>
+ <PromptTextarea
+ aria-label={t('widgets.generate.promptTemplates.negativePrompt')}
+ defaultHeightPx={56}
+ fontSize="0.72rem"
+ maxHeightPx={200}
+ minHeightPx={56}
+ placeholder={t('widgets.generate.promptTemplates.negativePromptPlaceholder')}
+ resizeHandleAriaLabel={t('widgets.generate.promptTemplates.resizeNegativePrompt')}
+ showSyntaxHighlighting={showSyntaxHighlighting}
+ size="xs"
+ value={draft.negativePrompt}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ updateDraftField('negativePrompt', event.currentTarget.value)
+ }
+ />
+ </Field>
+
+ <Field label={t('widgets.generate.promptTemplates.image')}>
+ <HStack gap="2">
+ {draft.imagePreviewUrl ? (
+ <Image
+ alt=""
+ boxSize="12"
+ borderColor="border.emphasized"
+ borderWidth="1px"
+ flexShrink="0"
+ objectFit="cover"
+ rounded="md"
+ src={draft.imagePreviewUrl}
+ />
+ ) : null}
+ <DropZone
+ alignItems="center"
+ as="button"
+ cursor="pointer"
+ display="flex"
+ flex="1"
+ gap="1.5"
+ justifyContent="center"
+ px="2"
+ py="2.5"
+ onClick={pickImage}
+ >
+ <ImageUpIcon size={14} />
+ <Text as="span" fontSize="2xs">
+ {draft.imagePreviewUrl
+ ? t('widgets.generate.promptTemplates.replaceImage')
+ : t('widgets.generate.promptTemplates.addImage')}
+ </Text>
+ </DropZone>
+ {draft.imagePreviewUrl ? (
+ <Tooltip content={t('widgets.generate.promptTemplates.removeImage')}>
+ <IconButton
+ aria-label={t('widgets.generate.promptTemplates.removeImage')}
+ size="2xs"
+ variant="ghost"
+ onClick={clearImage}
+ >
+ <XIcon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ <input accept="image/*" hidden ref={fileInputRef} type="file" onChange={handleImageChange} />
+ </HStack>
+ </Field>
+
+ {error ? (
+ <Text color="fg.error" fontSize="2xs" wordBreak="break-word">
+ {error}
+ </Text>
+ ) : null}
+
+ <HStack justify="end">
+ <Button disabled={isSaving} size="xs" variant="ghost" onClick={onCancel}>
+ <XIcon />
+ {t('common.cancel')}
+ </Button>
+ <Button disabled={!trimmedName || nameError !== null} loading={isSaving} size="xs" onClick={handleSave}>
+ <CheckIcon />
+ {t('common.save')}
+ </Button>
+ </HStack>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
new file mode 100644
index 0000000000..7f56cdfdb2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
@@ -0,0 +1,312 @@
+import type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';
+import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } 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 { userEvent } from 'vitest/browser';
+
+// Both panels report failures through Generation's UI port and read the
+// import/export capability from it; only the app composes that. The rest is real.
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useGenerationUi: () => ({
+ capabilities: { canManagePromptTemplates: false },
+ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() },
+ }),
+}));
+
+// The editor loads an existing preview image back so saving does not drop it.
+// No template under test has one, so the fetch never fires; stubbed anyway so a
+// regression shows up as a failed assertion rather than a network error.
+vi.mock('@features/generation/data/promptTemplates', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ fetchPromptTemplateImage: vi.fn().mockResolvedValue(null),
+}));
+
+// The subtree of `public/locales/en.json` these panels read, copied verbatim so
+// the assertions below can name the strings a user actually sees. Importing the
+// catalogue itself is not an option — Vite does not serve `public/` to modules.
+const translation = {
+ common: {
+ cancel: 'Cancel',
+ delete: 'Delete',
+ edit: 'Edit',
+ negative: 'Negative',
+ prompt: 'Prompt',
+ save: 'Save',
+ },
+ widgets: {
+ generate: {
+ promptTemplates: {
+ title: 'Prompt templates',
+ newTemplate: 'New template',
+ editTemplate: 'Edit template',
+ search: 'Search templates',
+ yourTemplates: 'Your templates',
+ defaultTemplates: 'Built-in templates',
+ noTemplatesYet: 'No templates yet. Create one to reuse a prompt with {prompt} where your own text goes.',
+ noMatches: 'No matching templates',
+ applied: 'Template: {{name}}',
+ clearApplied: 'Stop using {{name}}',
+ clear: 'Clear',
+ name: 'Name',
+ namePlaceholder: 'Cinematic',
+ nameHelp: 'Templates you create are saved to your account.',
+ nameTooLong: 'Name must be at most 128 characters',
+ positivePrompt: 'Template prompt',
+ positivePromptPlaceholder: '{prompt}. cinematic still, 35mm, shallow depth of field',
+ negativePrompt: 'Template negative prompt',
+ negativePromptPlaceholder: '{prompt}, blurry, lowres',
+ resizePositivePrompt: 'Resize template prompt',
+ resizeNegativePrompt: 'Resize template negative prompt',
+ insertPlaceholderHelp:
+ 'Insert {prompt}, which your own prompt replaces. Without it the template is added to the end.',
+ placeholderAlreadyUsed: 'Only the first {prompt} is replaced',
+ image: 'Preview image',
+ addImage: 'Add an image',
+ replaceImage: 'Replace image',
+ removeImage: 'Remove image',
+ import: 'Import',
+ importHelp: 'Import templates from a CSV or JSON file with name, prompt and negative_prompt.',
+ export: 'Export',
+ exportHelp: 'Download every user template as a CSV file.',
+ couldNotSave: 'Could not save this template',
+ couldNotDelete: 'Could not delete this template',
+ couldNotImport: 'Could not import templates',
+ couldNotExport: 'Could not export templates',
+ deleteTitle: 'Delete template',
+ deleteBody: 'Delete “{{name}}”? This cannot be undone.',
+ viewMerged: 'Show the merged prompt',
+ editAuthored: 'Back to editing your prompt',
+ loading: 'Loading templates…',
+ },
+ },
+ },
+};
+
+const i18n = i18next.createInstance();
+
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation } } });
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const userTemplate: PromptTemplateRecord = {
+ id: 'user-1',
+ imageUrl: null,
+ isDefault: false,
+ name: 'Cinematic',
+ negativePrompt: '',
+ positivePrompt: '{prompt}, cinematic still',
+};
+
+const defaultTemplate: PromptTemplateRecord = {
+ id: 'default-1',
+ imageUrl: null,
+ isDefault: true,
+ name: 'Photography',
+ negativePrompt: '',
+ positivePrompt: '{prompt}. photography, bokeh',
+};
+
+const createCatalog = (overrides: Partial<PromptTemplateCatalog> = {}): PromptTemplateCatalog => ({
+ create: vi.fn(),
+ defaultTemplates: [defaultTemplate],
+ exportCsv: vi.fn(),
+ importFile: vi.fn(),
+ isLoading: false,
+ remove: vi.fn(),
+ templates: [userTemplate, defaultTemplate],
+ update: vi.fn(),
+ userTemplates: [userTemplate],
+ ...overrides,
+});
+
+const render = async (element: React.ReactNode) => {
+ host = document.createElement('div');
+ host.style.width = '400px';
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>{element}</ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+};
+
+const buttonWithText = (text: string): HTMLButtonElement =>
+ [...host!.querySelectorAll('button')].find((button) => button.textContent?.includes(text))!;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('the prompt templates panel', () => {
+ it('applies the template that was clicked', async () => {
+ const onApply = vi.fn();
+
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={null}
+ catalog={createCatalog()}
+ onApply={onApply}
+ onCreate={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.click(buttonWithText('Cinematic'));
+ });
+
+ expect(onApply).toHaveBeenCalledWith(userTemplate);
+ });
+
+ it('clears the applied template', async () => {
+ const onApply = vi.fn();
+
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={userTemplate}
+ catalog={createCatalog()}
+ onApply={onApply}
+ onCreate={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.click(buttonWithText('Stop using Cinematic'));
+ });
+
+ expect(onApply).toHaveBeenCalledWith(null);
+ });
+
+ // Built-ins are shipped by the backend and rejected by it for non-admins, so
+ // offering the controls would only produce a 403.
+ it('offers edit and delete on your own templates but not on built-ins', async () => {
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={null}
+ catalog={createCatalog()}
+ onApply={vi.fn()}
+ onCreate={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ const labels = [...host!.querySelectorAll('button')].map((button) => button.getAttribute('aria-label'));
+
+ expect(labels.filter((label) => label === 'Edit')).toHaveLength(1);
+ expect(labels.filter((label) => label === 'Delete')).toHaveLength(1);
+ });
+
+ it('searches prompt text, not just the name', async () => {
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={null}
+ catalog={createCatalog()}
+ onApply={vi.fn()}
+ onCreate={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.fill(host!.querySelector('input')!, 'bokeh');
+ });
+
+ expect(host!.textContent).toContain('Photography');
+ expect(host!.textContent).not.toContain('Cinematic');
+ });
+});
+
+describe('the prompt template editor', () => {
+ it('appends the placeholder and then refuses to add a second one', async () => {
+ await render(
+ <PromptTemplateEditor
+ catalog={createCatalog()}
+ showSyntaxHighlighting
+ template={null}
+ onCancel={vi.fn()}
+ onSaved={vi.fn()}
+ />
+ );
+
+ const insertPlaceholder = buttonWithText('{prompt}');
+
+ await act(async () => {
+ await userEvent.click(insertPlaceholder);
+ });
+
+ expect(host!.querySelectorAll('textarea')[0]!.value).toBe('{prompt}');
+ expect(buttonWithText('{prompt}').disabled).toBe(true);
+ });
+
+ // Authoring always writes a private, user-owned template; the backend's
+ // `default` type and `is_public` flag are not exposed here.
+ it('saves a new template as the user’s own', async () => {
+ const catalog = createCatalog();
+
+ await render(
+ <PromptTemplateEditor
+ catalog={catalog}
+ showSyntaxHighlighting
+ template={null}
+ onCancel={vi.fn()}
+ onSaved={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.fill(host!.querySelector('input')!, 'Watercolour');
+ });
+ await act(async () => {
+ await userEvent.fill(host!.querySelectorAll('textarea')[0]!, '{prompt}, watercolour');
+ });
+ await act(async () => {
+ await userEvent.click(buttonWithText('Save'));
+ });
+
+ expect(catalog.create).toHaveBeenCalledWith({
+ image: null,
+ name: 'Watercolour',
+ negativePrompt: '',
+ positivePrompt: '{prompt}, watercolour',
+ });
+ });
+
+ it('keeps Save out of reach until the template is named', async () => {
+ await render(
+ <PromptTemplateEditor
+ catalog={createCatalog()}
+ showSyntaxHighlighting
+ template={null}
+ onCancel={vi.fn()}
+ onSaved={vi.fn()}
+ />
+ );
+
+ expect(buttonWithText('Save').disabled).toBe(true);
+
+ await act(async () => {
+ await userEvent.fill(host!.querySelector('input')!, 'Named');
+ });
+
+ expect(buttonWithText('Save').disabled).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx
new file mode 100644
index 0000000000..cefe963356
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx
@@ -0,0 +1,148 @@
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
+import type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type { PendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';
+
+import { Popover, Portal, Text } from '@chakra-ui/react';
+import { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';
+import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';
+import { useOnPendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';
+import { usePromptTemplates } from '@features/generation/ui/usePromptTemplates';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { LayoutTemplateIcon } from 'lucide-react';
+import { useCallback, useId, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const POPOVER_POSITIONING_BOTTOM_END = { placement: 'bottom-end' } as const;
+
+interface PromptTemplatesButtonProps {
+ activeTemplate: PromptTemplateSnapshot | null;
+ showSyntaxHighlighting: boolean;
+ onApply: (template: PromptTemplateSnapshot | null) => void;
+}
+
+/**
+ * `record: null` means the editor is composing a new template; `prefill` carries
+ * the prompts handed over from the gallery's "save as prompt template".
+ */
+type EditorTarget = { record: PromptTemplateRecord | null; prefill?: PendingPromptTemplateDraft };
+
+export const PromptTemplatesButton = ({
+ activeTemplate,
+ onApply,
+ showSyntaxHighlighting,
+}: PromptTemplatesButtonProps) => {
+ const { t } = useTranslation();
+ const triggerId = useId();
+ const [isOpen, setIsOpen] = useState(false);
+ const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null);
+ const catalog = usePromptTemplates();
+ const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);
+ // A draft handed over from the gallery opens the editor straight away.
+ useOnPendingPromptTemplateDraft(
+ useCallback((prefill: PendingPromptTemplateDraft) => {
+ setEditorTarget({ prefill, record: null });
+ setIsOpen(true);
+ }, [])
+ );
+
+ const handleOpenChange = useCallback((event: { open: boolean }) => {
+ setIsOpen(event.open);
+
+ // Reopening should land on the list rather than resuming a half-written
+ // template the user walked away from.
+ if (!event.open) {
+ setEditorTarget(null);
+ }
+ }, []);
+
+ const applyAndClose = useCallback(
+ (template: PromptTemplateSnapshot | null) => {
+ onApply(template);
+ setIsOpen(false);
+ },
+ [onApply]
+ );
+
+ const startCreate = useCallback(() => setEditorTarget({ record: null }), []);
+ const startEdit = useCallback((record: PromptTemplateRecord) => setEditorTarget({ record }), []);
+ const closeEditor = useCallback(() => setEditorTarget(null), []);
+
+ /**
+ * Editing the template that is currently applied has to refresh the snapshot,
+ * or the panel would show the new text while the old one keeps generating.
+ */
+ const handleSaved = useCallback(
+ (saved: PromptTemplateRecord) => {
+ if (activeTemplate?.id === saved.id) {
+ onApply(saved);
+ }
+
+ setEditorTarget(null);
+ },
+ [activeTemplate?.id, onApply]
+ );
+
+ const tooltip = activeTemplate
+ ? t('widgets.generate.promptTemplates.applied', { name: activeTemplate.name })
+ : t('widgets.generate.promptTemplates.title');
+
+ return (
+ <Popover.Root
+ ids={popoverIds}
+ lazyMount
+ open={isOpen}
+ positioning={POPOVER_POSITIONING_BOTTOM_END}
+ unmountOnExit
+ onOpenChange={handleOpenChange}
+ >
+ <Tooltip content={tooltip} ids={popoverIds}>
+ <Popover.Trigger asChild>
+ <IconButton
+ aria-label={t('widgets.generate.promptTemplates.title')}
+ // Quiet states only: a dimmed icon when nothing is applied, the
+ // template's name beside it when one is. No accent, no motion.
+ opacity={activeTemplate ? undefined : 0.5}
+ px={activeTemplate ? '1' : undefined}
+ size="2xs"
+ variant="ghost"
+ w={activeTemplate ? 'auto' : undefined}
+ >
+ <LayoutTemplateIcon />
+ {activeTemplate ? (
+ <Text as="span" fontSize="2xs" maxW="6rem" truncate>
+ {activeTemplate.name}
+ </Text>
+ ) : null}
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="26rem">
+ <Popover.Body p="2.5">
+ {editorTarget ? (
+ <PromptTemplateEditor
+ catalog={catalog}
+ prefill={editorTarget.prefill}
+ showSyntaxHighlighting={showSyntaxHighlighting}
+ template={editorTarget.record}
+ onCancel={closeEditor}
+ onSaved={handleSaved}
+ />
+ ) : (
+ <PromptTemplatesPanel
+ activeTemplate={activeTemplate}
+ catalog={catalog}
+ onApply={applyAndClose}
+ onCreate={startCreate}
+ onEdit={startEdit}
+ />
+ )}
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
new file mode 100644
index 0000000000..146194a734
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
@@ -0,0 +1,394 @@
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
+import type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
+import type { ChangeEvent } from 'react';
+
+import { Box, HStack, Image, Input, Separator, Stack, Text } from '@chakra-ui/react';
+import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTemplates';
+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
+import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button, IconButton } from '@platform/ui/Button';
+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { DownloadIcon, ImageIcon, PencilIcon, PlusIcon, TrashIcon, UploadIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const THUMBNAIL_SIZE = '7';
+
+interface PromptTemplatesPanelProps {
+ catalog: PromptTemplateCatalog;
+ activeTemplate: PromptTemplateSnapshot | null;
+ onApply: (template: PromptTemplateSnapshot | null) => void;
+ onEdit: (template: PromptTemplateRecord) => void;
+ onCreate: () => void;
+}
+
+/** Matches on name and on prompt text — a template is mostly its prompt. */
+const matchesSearch = (template: PromptTemplateRecord, query: string): boolean =>
+ !query ||
+ template.name.toLowerCase().includes(query) ||
+ template.positivePrompt.toLowerCase().includes(query) ||
+ template.negativePrompt.toLowerCase().includes(query);
+
+export const PromptTemplatesPanel = ({
+ activeTemplate,
+ catalog,
+ onApply,
+ onCreate,
+ onEdit,
+}: PromptTemplatesPanelProps) => {
+ const { t } = useTranslation();
+ const { capabilities, notifications } = useGenerationUi();
+ const canManagePromptTemplates = capabilities.canManagePromptTemplates;
+ const [searchTerm, setSearchTerm] = useState('');
+ const [pendingDelete, setPendingDelete] = useState<PromptTemplateRecord | null>(null);
+ const query = searchTerm.trim().toLowerCase();
+
+ const userTemplates = useMemo(
+ () => catalog.userTemplates.filter((template) => matchesSearch(template, query)),
+ [catalog.userTemplates, query]
+ );
+ const defaultTemplates = useMemo(
+ () => catalog.defaultTemplates.filter((template) => matchesSearch(template, query)),
+ [catalog.defaultTemplates, query]
+ );
+ const hasResults = userTemplates.length > 0 || defaultTemplates.length > 0;
+
+ const handleSearchChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value),
+ []
+ );
+
+ const clearActiveTemplate = useCallback(() => onApply(null), [onApply]);
+ const closeDeleteDialog = useCallback(() => setPendingDelete(null), []);
+
+ /**
+ * The dialog closes either way, so a failure has nowhere inline to land — it
+ * goes to the notification centre like the other Generation errors.
+ */
+ const confirmDelete = useCallback(async () => {
+ if (!pendingDelete) {
+ return;
+ }
+
+ try {
+ await catalog.remove(pendingDelete.id);
+
+ // Deleting the template that is applied would otherwise leave it silently
+ // shaping every prompt with no way to reach it.
+ if (activeTemplate?.id === pendingDelete.id) {
+ onApply(null);
+ }
+ } catch (caught) {
+ notifications.reportError({
+ area: 'delete-prompt-template',
+ message: getApiErrorMessage(caught, t('widgets.generate.promptTemplates.couldNotDelete')),
+ namespace: 'generation',
+ });
+ }
+ }, [activeTemplate, catalog, notifications, onApply, pendingDelete, t]);
+
+ return (
+ <Stack gap="2">
+ <PromptPanelHeader label={t('widgets.generate.promptTemplates.title')}>
+ <Button h={PANEL_HEADER_CONTROL_HEIGHT} size="2xs" variant="ghost" onClick={onCreate}>
+ <PlusIcon />
+ {t('widgets.generate.promptTemplates.newTemplate')}
+ </Button>
+ </PromptPanelHeader>
+
+ <Input
+ aria-label={t('widgets.generate.promptTemplates.search')}
+ placeholder={t('widgets.generate.promptTemplates.search')}
+ size="xs"
+ value={searchTerm}
+ onChange={handleSearchChange}
+ />
+ <Separator />
+
+ <Scrollable h="16rem" label={t('widgets.generate.promptTemplates.title')}>
+ {catalog.isLoading ? (
+ <PanelMessage>{t('widgets.generate.promptTemplates.loading')}</PanelMessage>
+ ) : !hasResults ? (
+ <PanelMessage>
+ {query
+ ? t('widgets.generate.promptTemplates.noMatches')
+ : t('widgets.generate.promptTemplates.noTemplatesYet')}
+ </PanelMessage>
+ ) : (
+ <Stack gap="2">
+ <TemplateGroup
+ activeTemplateId={activeTemplate?.id ?? null}
+ label={t('widgets.generate.promptTemplates.yourTemplates')}
+ templates={userTemplates}
+ onApply={onApply}
+ onDelete={setPendingDelete}
+ onEdit={onEdit}
+ />
+ <TemplateGroup
+ activeTemplateId={activeTemplate?.id ?? null}
+ label={t('widgets.generate.promptTemplates.defaultTemplates')}
+ templates={defaultTemplates}
+ onApply={onApply}
+ />
+ </Stack>
+ )}
+ </Scrollable>
+
+ {activeTemplate || canManagePromptTemplates ? (
+ <>
+ <Separator />
+ <HStack gap="1" justify="space-between">
+ {canManagePromptTemplates ? <PromptTemplateTransferActions catalog={catalog} /> : <Box />}
+ {activeTemplate ? (
+ <Button size="2xs" variant="ghost" onClick={clearActiveTemplate}>
+ {t('widgets.generate.promptTemplates.clearApplied', { name: activeTemplate.name })}
+ </Button>
+ ) : null}
+ </HStack>
+ </>
+ ) : null}
+
+ <ConfirmDialog
+ body={t('widgets.generate.promptTemplates.deleteBody', { name: pendingDelete?.name ?? '' })}
+ confirmLabel={t('common.delete')}
+ isOpen={pendingDelete !== null}
+ title={t('widgets.generate.promptTemplates.deleteTitle')}
+ onClose={closeDeleteDialog}
+ onConfirm={confirmDelete}
+ />
+ </Stack>
+ );
+};
+
+/**
+ * Bulk transfer, admin-only on the backend. Export streams CSV and import accepts
+ * the CSV/JSON shapes the backend's parser documents. Both go through the
+ * transport rather than an anchor download, which would carry no auth header.
+ */
+const PromptTemplateTransferActions = ({ catalog }: { catalog: PromptTemplateCatalog }) => {
+ const { t } = useTranslation();
+ const { notifications } = useGenerationUi();
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const [isBusy, setIsBusy] = useState(false);
+
+ const reportError = useCallback(
+ (area: string, caught: unknown, fallback: string) =>
+ notifications.reportError({
+ area,
+ message: getApiErrorMessage(caught, fallback),
+ namespace: 'generation',
+ }),
+ [notifications]
+ );
+
+ const runImport = useCallback(
+ async (file: File) => {
+ setIsBusy(true);
+
+ try {
+ await catalog.importFile(file);
+ } catch (caught) {
+ reportError('import-prompt-templates', caught, t('widgets.generate.promptTemplates.couldNotImport'));
+ } finally {
+ setIsBusy(false);
+ }
+ },
+ [catalog, reportError, t]
+ );
+
+ const runExport = useCallback(async () => {
+ setIsBusy(true);
+
+ try {
+ const blob = await catalog.exportCsv();
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+
+ link.download = 'prompt_templates.csv';
+ link.href = url;
+ link.click();
+ URL.revokeObjectURL(url);
+ } catch (caught) {
+ reportError('export-prompt-templates', caught, t('widgets.generate.promptTemplates.couldNotExport'));
+ } finally {
+ setIsBusy(false);
+ }
+ }, [catalog, reportError, t]);
+
+ const pickFile = useCallback(() => fileInputRef.current?.click(), []);
+ const handleExport = useCallback(() => void runExport(), [runExport]);
+
+ const handleFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ if (file) {
+ void runImport(file);
+ }
+
+ event.currentTarget.value = '';
+ },
+ [runImport]
+ );
+
+ return (
+ <HStack gap="0.5">
+ <Tooltip content={t('widgets.generate.promptTemplates.importHelp')}>
+ <Button disabled={isBusy} size="2xs" variant="ghost" onClick={pickFile}>
+ <UploadIcon />
+ {t('widgets.generate.promptTemplates.import')}
+ </Button>
+ </Tooltip>
+ <Tooltip content={t('widgets.generate.promptTemplates.exportHelp')}>
+ <Button disabled={isBusy} size="2xs" variant="ghost" onClick={handleExport}>
+ <DownloadIcon />
+ {t('widgets.generate.promptTemplates.export')}
+ </Button>
+ </Tooltip>
+ <input
+ accept=".csv,.json,text/csv,application/json"
+ hidden
+ ref={fileInputRef}
+ type="file"
+ onChange={handleFileChange}
+ />
+ </HStack>
+ );
+};
+
+const PanelMessage = ({ children }: { children: string }) => (
+ <HStack h="full" justify="center" minH="8rem">
+ <Text color="fg.subtle" fontSize="xs">
+ {children}
+ </Text>
+ </HStack>
+);
+
+const TemplateGroup = ({
+ activeTemplateId,
+ label,
+ onApply,
+ onDelete,
+ onEdit,
+ templates,
+}: {
+ activeTemplateId: string | null;
+ label: string;
+ templates: PromptTemplateRecord[];
+ onApply: (template: PromptTemplateSnapshot) => void;
+ onDelete?: (template: PromptTemplateRecord) => void;
+ onEdit?: (template: PromptTemplateRecord) => void;
+}) => {
+ if (templates.length === 0) {
+ return null;
+ }
+
+ return (
+ <Stack gap="0">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="2" textTransform="uppercase">
+ {label}
+ </Text>
+ {templates.map((template) => (
+ <TemplateRow
+ key={template.id}
+ isActive={template.id === activeTemplateId}
+ template={template}
+ onApply={onApply}
+ onDelete={onDelete}
+ onEdit={onEdit}
+ />
+ ))}
+ </Stack>
+ );
+};
+
+const TemplateRow = ({
+ isActive,
+ onApply,
+ onDelete,
+ onEdit,
+ template,
+}: {
+ isActive: boolean;
+ template: PromptTemplateRecord;
+ onApply: (template: PromptTemplateSnapshot) => void;
+ onDelete?: (template: PromptTemplateRecord) => void;
+ onEdit?: (template: PromptTemplateRecord) => void;
+}) => {
+ const { t } = useTranslation();
+ const handleApply = useCallback(() => onApply(template), [onApply, template]);
+ const handleEdit = useCallback(() => onEdit?.(template), [onEdit, template]);
+ const handleDelete = useCallback(() => onDelete?.(template), [onDelete, template]);
+ // The prompt with its placeholder is the whole content of a template, so the
+ // row shows it rather than a name alone.
+ const summary = template.positivePrompt || PROMPT_TEMPLATE_PLACEHOLDER;
+
+ return (
+ <HStack align="center" gap="1" pr="1">
+ <Button
+ alignItems="center"
+ flex="1"
+ h="auto"
+ justifyContent="start"
+ minW="0"
+ px="2"
+ py="1.5"
+ size="xs"
+ variant="ghost"
+ onClick={handleApply}
+ >
+ <TemplateThumbnail template={template} />
+ <Stack align="start" flex="1" gap="0" minW="0">
+ <Text as="span" color={isActive ? 'fg' : 'fg.muted'} fontSize="xs" fontWeight={isActive ? '600' : '400'}>
+ {template.name}
+ </Text>
+ <Text as="span" color="fg.subtle" fontFamily="mono" fontSize="2xs" truncate>
+ {summary}
+ </Text>
+ </Stack>
+ </Button>
+ {onEdit ? (
+ <Tooltip content={t('common.edit')}>
+ <IconButton aria-label={t('common.edit')} size="2xs" variant="ghost" onClick={handleEdit}>
+ <PencilIcon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ {onDelete ? (
+ <Tooltip content={t('common.delete')}>
+ <IconButton
+ aria-label={t('common.delete')}
+ colorPalette="red"
+ size="2xs"
+ variant="ghost"
+ onClick={handleDelete}
+ >
+ <TrashIcon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ </HStack>
+ );
+};
+
+const TemplateThumbnail = ({ template }: { template: PromptTemplateRecord }) =>
+ template.imageUrl ? (
+ <Image alt="" boxSize={THUMBNAIL_SIZE} flexShrink="0" objectFit="cover" rounded="sm" src={template.imageUrl} />
+ ) : (
+ <Box
+ alignItems="center"
+ bg="bg.emphasized"
+ boxSize={THUMBNAIL_SIZE}
+ color="fg.subtle"
+ display="flex"
+ flexShrink="0"
+ justifyContent="center"
+ rounded="sm"
+ >
+ <ImageIcon size={12} />
+ </Box>
+ );
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
index 80cb44e235..5bbc196d07 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
@@ -37,6 +37,13 @@ interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {
showSyntaxHighlighting: boolean;
/** Number logical lines in a leading gutter, the way an editor does. */
showLineNumbers?: boolean;
+ /**
+ * `[before, authored, after]` from `getPromptTemplateChunks`. When set, the
+ * mirror dims the outer chunks so the template's own words read as context
+ * around the user's text. `value` must be the concatenation of the three, and
+ * the textarea is expected to be `readOnly` — this is a view, not an editor.
+ */
+ templateChunks?: [string, string, string] | null;
value: string;
}
@@ -62,6 +69,7 @@ export const PromptTextarea = ({
onScroll,
showLineNumbers = false,
showSyntaxHighlighting,
+ templateChunks = null,
textareaRef,
value,
...props
@@ -69,7 +77,10 @@ export const PromptTextarea = ({
const localTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const [scroll, setScroll] = useState({ left: 0, top: 0 });
const [textareaClientWidth, setTextareaClientWidth] = useState<number | null>(null);
- const shouldHighlight = showSyntaxHighlighting && value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;
+ const isWithinHighlightBudget = value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;
+ // Template chunks are a legibility device, not a syntax preference, so they
+ // render whether or not highlighting is switched on.
+ const shouldHighlight = (showSyntaxHighlighting || templateChunks !== null) && isWithinHighlightBudget;
const effectiveFontSize = fontSize ?? '0.82rem';
const effectiveLineHeight = lineHeight ?? PROMPT_TEXTAREA_LINE_HEIGHT;
// The gutter widens with the line count, and the text has to start clear of it.
@@ -166,7 +177,23 @@ export const PromptTextarea = ({
whiteSpace="pre-wrap"
w={textareaClientWidth ? `${textareaClientWidth}px` : '100%'}
>
- <HighlightedPrompt options={highlightOptions} prompt={value} />
+ {templateChunks ? (
+ <>
+ <Box as="span" color="fg.subtle">
+ {templateChunks[0]}
+ </Box>
+ {showSyntaxHighlighting ? (
+ <HighlightedPrompt options={highlightOptions} prompt={templateChunks[1]} />
+ ) : (
+ templateChunks[1]
+ )}
+ <Box as="span" color="fg.subtle">
+ {templateChunks[2]}
+ </Box>
+ </>
+ ) : (
+ <HighlightedPrompt options={highlightOptions} prompt={value} />
+ )}
{value.endsWith('\n') ? '\u200b' : null}
</Box>
</Box>
@@ -180,6 +207,8 @@ export const PromptTextarea = ({
scroll.left,
scroll.top,
shouldHighlight,
+ showSyntaxHighlighting,
+ templateChunks,
textareaClientWidth,
value,
]
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts
new file mode 100644
index 0000000000..e0ae610e28
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts
@@ -0,0 +1,64 @@
+/**
+ * A one-shot handoff for "save this image's prompt as a template".
+ *
+ * The action starts in the gallery's context menu but has to finish in the
+ * generate widget's template editor, which is inside a popover the menu cannot
+ * reach. Rather than lifting the editor into a global dialog, the menu leaves a
+ * draft here and opens the widget; the templates button picks it up and opens
+ * the editor prefilled.
+ *
+ * The draft is consumed on read, so re-opening the popover later starts on the
+ * list rather than resurrecting an old handoff.
+ */
+
+import { createExternalStore } from '@platform/state/externalStore';
+import { useEffect } from 'react';
+
+export interface PendingPromptTemplateDraft {
+ negativePrompt: string;
+ positivePrompt: string;
+}
+
+interface PendingPromptTemplateDraftState {
+ draft: PendingPromptTemplateDraft | null;
+}
+
+const store = createExternalStore<PendingPromptTemplateDraftState>({ draft: null });
+
+export const setPendingPromptTemplateDraft = (draft: PendingPromptTemplateDraft): void => store.setSnapshot({ draft });
+
+const takePendingPromptTemplateDraft = (): PendingPromptTemplateDraft | null => {
+ const { draft } = store.getSnapshot();
+
+ if (draft) {
+ store.setSnapshot({ draft: null });
+ }
+
+ return draft;
+};
+
+/**
+ * Delivers a handed-over draft to the editor exactly once — on subscribe for one
+ * left before the widget mounted, and on notification thereafter.
+ *
+ * Deliberately a subscription with a callback rather than a rendered value: the
+ * draft is a one-shot event from outside React, and reading it during render
+ * would mean clearing it in an effect, which is the cascading-render pattern the
+ * compiler rejects.
+ */
+export const useOnPendingPromptTemplateDraft = (onDraft: (draft: PendingPromptTemplateDraft) => void): void => {
+ useEffect(() => {
+ const deliver = () => {
+ const draft = takePendingPromptTemplateDraft();
+
+ if (draft) {
+ onDraft(draft);
+ }
+ };
+
+ // Resubscribing re-runs this, which is harmless: the draft is taken on the
+ // first delivery, so any later pass finds nothing.
+ deliver();
+ return store.subscribe(deliver);
+ }, [onDraft]);
+};
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
index 5241a9a4a1..04c872ef28 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
@@ -20,6 +20,7 @@ describe('Identity route capabilities', () => {
expect(getCapabilities(session({ multiuserEnabled: false, phase }))).toEqual({
canManageModels: false,
canManageNodes: false,
+ canManagePromptTemplates: false,
canManageUsers: false,
});
});
@@ -28,6 +29,7 @@ describe('Identity route capabilities', () => {
expect(getCapabilities(session({ multiuserEnabled: false }))).toEqual({
canManageModels: true,
canManageNodes: true,
+ canManagePromptTemplates: true,
canManageUsers: false,
});
});
@@ -46,11 +48,13 @@ describe('Identity route capabilities', () => {
expect(getCapabilities(session({ user: { ...baseUser, is_admin: false } }))).toEqual({
canManageModels: false,
canManageNodes: false,
+ canManagePromptTemplates: false,
canManageUsers: false,
});
expect(getCapabilities(session({ user: { ...baseUser, is_admin: true } }))).toEqual({
canManageModels: true,
canManageNodes: true,
+ canManagePromptTemplates: true,
canManageUsers: true,
});
});
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
index 497c929d02..7cb6c5c517 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
@@ -3,6 +3,8 @@ import { useAuthSession, type AuthSession } from './session';
export interface Capabilities {
canManageModels: boolean;
canManageNodes: boolean;
+ /** Bulk import/export of prompt templates; the routes are admin-only. */
+ canManagePromptTemplates: boolean;
canManageUsers: boolean;
}
@@ -11,6 +13,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {
return {
canManageModels: false,
canManageNodes: false,
+ canManagePromptTemplates: false,
canManageUsers: false,
};
}
@@ -21,6 +24,9 @@ export const getCapabilities = (session: AuthSession): Capabilities => {
return {
canManageModels: isAdmin,
canManageNodes: isAdmin,
+ // Matches the routers' `AdminUserOrDefault`: everyone qualifies in
+ // single-user mode, only admins once multiuser is on.
+ canManagePromptTemplates: isAdmin,
canManageUsers: session.multiuserEnabled && session.user?.is_admin === true,
};
};