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): highlight the previewed dynamic prompts

joshistoast345f0406ff14
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 618bea88e7..7fb37db0b5 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1029,6 +1029,7 @@
"source:src/features/generation/ui/promptFields/NegativePromptField.tsx",
"source:src/features/generation/ui/promptFields/PositivePromptActions.tsx",
"source:src/features/generation/ui/promptFields/PositivePromptField.tsx",
+ "source:src/features/generation/ui/promptFields/PromptHighlight.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
"source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
@@ -1811,6 +1812,7 @@
"source:src/features/generation/ui/promptFields/NegativePromptField.tsx",
"source:src/features/generation/ui/promptFields/PositivePromptActions.tsx",
"source:src/features/generation/ui/promptFields/PositivePromptField.tsx",
+ "source:src/features/generation/ui/promptFields/PromptHighlight.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
"source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
index 57e94c6e48..79b6862dc0 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
@@ -58,6 +58,7 @@ const render = async (prompt: string, onUsePrompt = vi.fn()) => {
batchCount={2}
config={config}
positivePrompt={prompt}
+ showSyntaxHighlighting
onInsertText={vi.fn()}
onUsePrompt={onUsePrompt}
/>
@@ -121,6 +122,26 @@ describe('dynamic prompts in the positive prompt field', () => {
expect(onUsePrompt).toHaveBeenCalledWith('a red cat');
});
+ it('colours attention syntax inside the previewed prompts', async () => {
+ parseDynamicPrompts.mockResolvedValue({ error: null, prompts: ['a (red)1.2 cat', 'a green+ cat'] });
+ await render('a {(red)1.2|green+} cat');
+
+ await vi.waitFor(() => expect(findButton().textContent).toContain('2'));
+ await act(async () => {
+ await userEvent.click(findButton());
+ });
+
+ // An expanded prompt has no dynamic syntax left, so what is worth colouring
+ // in the preview is the attention weighting that survived expansion.
+ const row = [...document.querySelectorAll('button')].find((button) =>
+ button.textContent?.includes('a (red)1.2 cat')
+ )!;
+ const weights = [...row.querySelectorAll('span')].map((span) => span.textContent);
+
+ expect(weights).toContain('1.2');
+ expect(weights).toContain('(');
+ });
+
it('stays inert and never expands a prompt with no dynamic syntax', async () => {
await render('a plain cat');
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx
index 1d07dfab6c..9dc9b3777e 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx
@@ -18,6 +18,7 @@ interface DynamicPromptsButtonProps {
config: DynamicPromptsFieldConfig;
batchCount: number;
positivePrompt: string;
+ showSyntaxHighlighting: boolean;
onUsePrompt: (prompt: string) => void;
onInsertText: (text: string) => void;
}
@@ -28,6 +29,7 @@ export const DynamicPromptsButton = ({
onInsertText,
onUsePrompt,
positivePrompt,
+ showSyntaxHighlighting,
}: DynamicPromptsButtonProps) => {
const { t } = useTranslation();
const triggerId = useId();
@@ -112,6 +114,7 @@ export const DynamicPromptsButton = ({
batchCount={batchCount}
config={config}
expansion={expansion}
+ showSyntaxHighlighting={showSyntaxHighlighting}
onUsePrompt={handleUsePrompt}
/>
) : (
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
index db41366992..b7c5772c07 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
@@ -59,6 +59,7 @@ const render = async (onChange: (patch: Partial<DynamicPromptsConfig>) => void =
},
}}
positivePrompt="a {red|green} cat"
+ showSyntaxHighlighting
onInsertText={vi.fn()}
onUsePrompt={vi.fn()}
/>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
index 991b749e95..fe1e248695 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
@@ -8,6 +8,7 @@ import {
DYNAMIC_PROMPTS_MIN_PROMPTS,
sanitizeMaxPrompts,
} from '@features/generation/core/dynamicPrompts';
+import { HighlightedPrompt } from '@features/generation/ui/promptFields/PromptHighlight';
import { Button, IconButton } from '@platform/ui/Button';
import { Scrollable } from '@platform/ui/Scrollable';
import { Tooltip } from '@platform/ui/Tooltip';
@@ -28,10 +29,12 @@ export const DynamicPromptsPanel = ({
config,
expansion,
onUsePrompt,
+ showSyntaxHighlighting,
}: {
batchCount: number;
config: DynamicPromptsFieldConfig;
expansion: DynamicPromptsExpansion;
+ showSyntaxHighlighting: boolean;
onUsePrompt: (prompt: string) => void;
}) => {
const { t } = useTranslation();
@@ -167,7 +170,13 @@ export const DynamicPromptsPanel = ({
<Scrollable h="14rem" label={t('widgets.generate.dynamicPrompts.promptsPreview')}>
<Stack gap="0">
{visiblePrompts.map((prompt, index) => (
- <DynamicPromptRow key={`${index}-${prompt}`} index={index} prompt={prompt} onUsePrompt={onUsePrompt} />
+ <DynamicPromptRow
+ key={`${index}-${prompt}`}
+ index={index}
+ prompt={prompt}
+ showSyntaxHighlighting={showSyntaxHighlighting}
+ onUsePrompt={onUsePrompt}
+ />
))}
{hiddenPromptCount > 0 ? (
<Text color="fg.subtle" fontSize="2xs" px="2" py="1.5">
@@ -184,9 +193,11 @@ const DynamicPromptRow = ({
index,
onUsePrompt,
prompt,
+ showSyntaxHighlighting,
}: {
index: number;
prompt: string;
+ showSyntaxHighlighting: boolean;
onUsePrompt: (prompt: string) => void;
}) => {
const { t } = useTranslation();
@@ -210,7 +221,9 @@ const DynamicPromptRow = ({
{index + 1}
</Text>
<Text as="span" color="fg" fontFamily="mono" fontSize="0.72rem" textAlign="start" wordBreak="break-word">
- {prompt}
+ {/* An expanded prompt has no dynamic syntax left in it, so the useful
+ colouring here is attention and embeddings — the defaults. */}
+ <HighlightedPrompt enabled={showSyntaxHighlighting} prompt={prompt} />
</Text>
</Button>
);
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 1ab98e9aac..e3cc2913df 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -34,6 +34,7 @@ interface PositivePromptActionsProps {
onOpenPromptTriggerPicker: (anchorElement: HTMLElement) => void;
onPositivePromptChangeImmediate: (prompt: string) => void;
onInsertText: (text: string) => void;
+ showSyntaxHighlighting: boolean;
}
export const PositivePromptActions = ({
@@ -46,6 +47,7 @@ export const PositivePromptActions = ({
onUsePrompt,
positivePrompt,
projectId,
+ showSyntaxHighlighting,
}: PositivePromptActionsProps) => {
return (
<HStack gap="0.5">
@@ -54,6 +56,7 @@ export const PositivePromptActions = ({
batchCount={batchCount}
config={dynamicPrompts}
positivePrompt={positivePrompt}
+ showSyntaxHighlighting={showSyntaxHighlighting}
onInsertText={onInsertText}
onUsePrompt={onPositivePromptChangeImmediate}
/>
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 329dbd3e2b..562b8d60de 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -163,6 +163,7 @@ export const PositivePromptField = ({
batchCount={batchCount}
dynamicPrompts={dynamicPrompts}
isPromptTriggerPickerOpen={triggerPickerState !== null}
+ showSyntaxHighlighting={showSyntaxHighlighting}
onInsertText={insertTextAtCaret}
loras={loras}
positivePrompt={draftValue}
@@ -184,6 +185,7 @@ export const PositivePromptField = ({
loras,
projectId,
selectedModel,
+ showSyntaxHighlighting,
triggerPickerState,
]
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsx
new file mode 100644
index 0000000000..7ecb21b20d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsx
@@ -0,0 +1,94 @@
+/**
+ * The one place prompt highlight kinds become colours.
+ *
+ * Shared by the prompt textarea's underlay and the dynamic prompts preview, so a
+ * weight or an embedding reads the same whether you are writing the prompt or
+ * looking at what it expanded into.
+ */
+
+import type { PromptHighlightKind, PromptHighlightOptions } from '@features/generation/core/prompt/highlight';
+
+import { Box } from '@chakra-ui/react';
+import { buildPromptHighlightSegments } from '@features/generation/core/prompt/highlight';
+import { useMemo } from 'react';
+
+/** Past this, colouring costs more than it tells the reader. */
+export const MAX_HIGHLIGHTED_PROMPT_LENGTH = 20_000;
+
+export const HIGHLIGHT_STYLE_BY_KIND: Record<
+ PromptHighlightKind,
+ { bg?: string; color: string; textDecoration?: string; textDecorationColor?: string }
+> = {
+ attention: { color: 'accent.solid' },
+ attentionNumeric: { color: 'fg.success' },
+ embedding: { bg: 'bg.warning', color: 'fg.warning' },
+ error: { bg: 'bg.error', color: 'fg.error', textDecoration: 'underline wavy', textDecorationColor: 'fg.error' },
+ escapedParen: { color: 'fg.muted' },
+ group: { color: 'fg.subtle' },
+ promptFunctionArg: { bg: 'accent.subtle/20', color: 'fg' },
+ promptFunctionMethod: { color: 'accent.fg' },
+ promptVariable: { color: 'accent.fg' },
+ punctuation: { color: 'fg.subtle' },
+ text: { color: 'fg' },
+ variantBrace: { color: 'accent.fg' },
+ variantRange: { color: 'fg.success' },
+ variantSeparator: { color: 'fg.muted' },
+ variantWeight: { color: 'fg.success' },
+ wildcard: { color: 'fg.subtle' },
+};
+
+export const usePromptHighlightSegments = (prompt: string, options: PromptHighlightOptions, enabled: boolean) =>
+ useMemo(
+ () =>
+ enabled && prompt.length > 0 && prompt.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH
+ ? buildPromptHighlightSegments(prompt, options)
+ : [],
+ [enabled, options, prompt]
+ );
+
+export const PromptHighlightSpan = ({ kind, text }: { kind: PromptHighlightKind; text: string }) => {
+ const style = HIGHLIGHT_STYLE_BY_KIND[kind];
+
+ return (
+ <Box
+ as="span"
+ bg={style.bg}
+ borderRadius={style.bg ? '2px' : undefined}
+ color={style.color}
+ textDecoration={style.textDecoration}
+ textDecorationColor={style.textDecorationColor}
+ >
+ {text}
+ </Box>
+ );
+};
+
+/**
+ * Renders a prompt as coloured spans, falling back to plain text when
+ * highlighting is off or the prompt is too long to be worth colouring.
+ */
+export const HighlightedPrompt = ({
+ enabled = true,
+ options = EMPTY_OPTIONS,
+ prompt,
+}: {
+ prompt: string;
+ enabled?: boolean;
+ options?: PromptHighlightOptions;
+}) => {
+ const segments = usePromptHighlightSegments(prompt, options, enabled);
+
+ if (segments.length === 0) {
+ return prompt;
+ }
+
+ return segments.map((segment) => (
+ <PromptHighlightSpan
+ key={`${segment.range.start}:${segment.range.end}:${segment.kind}`}
+ kind={segment.kind}
+ text={segment.text}
+ />
+ ));
+};
+
+const EMPTY_OPTIONS: PromptHighlightOptions = {};
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 6a7055cf6c..f038dabc4b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
@@ -1,39 +1,14 @@
-import type { PromptHighlightKind, PromptHighlightSegment } from '@features/generation/core/prompt/highlight';
import type { ResizableTextareaProps } from '@platform/ui';
import type { Ref, UIEvent } from 'react';
import { Box } from '@chakra-ui/react';
-import { buildPromptHighlightSegments } from '@features/generation/core/prompt/highlight';
+import { HighlightedPrompt, MAX_HIGHLIGHTED_PROMPT_LENGTH } from '@features/generation/ui/promptFields/PromptHighlight';
import { ResizableTextarea } from '@platform/ui';
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
-
-const MAX_HIGHLIGHTED_PROMPT_LENGTH = 20_000;
const PROMPT_TEXTAREA_LINE_HEIGHT = '1.6';
const PROMPT_TEXTAREA_PX = '2.5';
const PROMPT_TEXTAREA_PY = '2';
-const HIGHLIGHT_STYLE_BY_KIND: Record<
- PromptHighlightKind,
- { bg?: string; color: string; textDecoration?: string; textDecorationColor?: string }
-> = {
- attention: { color: 'accent.solid' },
- attentionNumeric: { color: 'fg.success' },
- embedding: { bg: 'bg.warning', color: 'fg.warning' },
- error: { bg: 'bg.error', color: 'fg.error', textDecoration: 'underline wavy', textDecorationColor: 'fg.error' },
- escapedParen: { color: 'fg.muted' },
- group: { color: 'fg.subtle' },
- promptFunctionArg: { bg: 'accent.subtle/20', color: 'fg' },
- promptFunctionMethod: { color: 'accent.fg' },
- promptVariable: { color: 'accent.fg' },
- punctuation: { color: 'fg.subtle' },
- text: { color: 'fg' },
- variantBrace: { color: 'accent.fg' },
- variantRange: { color: 'fg.success' },
- variantSeparator: { color: 'fg.muted' },
- variantWeight: { color: 'fg.success' },
- wildcard: { color: 'fg.subtle' },
-};
-
const PROMPT_TEXTAREA_FORCED_COLORS_CSS = { '@media (forced-colors: active)': { display: 'none' } };
const PROMPT_TEXTAREA_HIGHLIGHTED_CSS = {
'&::selection': { color: 'transparent', WebkitTextFillColor: 'transparent' },
@@ -71,23 +46,6 @@ const setRef = (ref: Ref<HTMLTextAreaElement> | undefined, element: HTMLTextArea
(ref as { current: HTMLTextAreaElement | null }).current = element;
};
-const PromptHighlightSpan = ({ segment }: { segment: PromptHighlightSegment }) => {
- const style = HIGHLIGHT_STYLE_BY_KIND[segment.kind];
-
- return (
- <Box
- as="span"
- bg={style.bg}
- borderRadius={style.bg ? '2px' : undefined}
- color={style.color}
- textDecoration={style.textDecoration}
- textDecorationColor={style.textDecorationColor}
- >
- {segment.text}
- </Box>
- );
-};
-
export const PromptTextarea = ({
fontFamily = 'mono',
fontSize,
@@ -107,12 +65,9 @@ export const PromptTextarea = ({
const effectiveFontSize = fontSize ?? '0.82rem';
const effectiveLineHeight = lineHeight ?? PROMPT_TEXTAREA_LINE_HEIGHT;
- const segments = useMemo(
- () =>
- shouldHighlight
- ? buildPromptHighlightSegments(value, { dynamicPrompts: highlightDynamicPrompts, knownWildcards })
- : [],
- [highlightDynamicPrompts, knownWildcards, shouldHighlight, value]
+ const highlightOptions = useMemo(
+ () => ({ dynamicPrompts: highlightDynamicPrompts, knownWildcards }),
+ [highlightDynamicPrompts, knownWildcards]
);
useLayoutEffect(() => {
@@ -184,12 +139,7 @@ export const PromptTextarea = ({
whiteSpace="pre-wrap"
w={textareaClientWidth ? `${textareaClientWidth}px` : '100%'}
>
- {segments.map((segment) => (
- <PromptHighlightSpan
- key={`${segment.range.start}:${segment.range.end}:${segment.kind}`}
- segment={segment}
- />
- ))}
+ <HighlightedPrompt options={highlightOptions} prompt={value} />
{value.endsWith('\n') ? '\u200b' : null}
</Box>
</Box>
@@ -198,9 +148,9 @@ export const PromptTextarea = ({
effectiveFontSize,
effectiveLineHeight,
fontFamily,
+ highlightOptions,
scroll.left,
scroll.top,
- segments,
shouldHighlight,
textareaClientWidth,
value,