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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): give the wildcard values editor highlighting and a line gutter
joshistoastac14361f8e5c
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 7fb37db0b5..238561569f 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1030,6 +1030,7 @@"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/PromptLineNumbers.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",@@ -1813,6 +1814,7 @@"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/PromptLineNumbers.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/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex cc4b392563..57287d34cc 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -974,7 +974,8 @@"wildcardHasNoValues": "No values yet","noWildcardsYet": "No wildcards yet. Create one to reuse a list of values as __name__.","insertWildcard": "Insert into the prompt",- "couldNotSaveWildcard": "Could not save this wildcard"+ "couldNotSaveWildcard": "Could not save this wildcard",+ "resizeWildcardValues": "Resize wildcard values"}},"upscale": {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsxindex 9dc9b3777e..6a8e4acf37 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx@@ -118,7 +118,11 @@ export const DynamicPromptsButton = ({onUsePrompt={handleUsePrompt}/>) : (- <WildcardsPanel catalog={catalog} onInsert={handleInsert} />+ <WildcardsPanel+ catalog={catalog}+ showSyntaxHighlighting={showSyntaxHighlighting}+ onInsert={handleInsert}+ />)}</Stack></Popover.Body>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsxnew file mode 100644index 0000000000..3c981a22e9--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx@@ -0,0 +1,77 @@+import { ChakraProvider } from '@chakra-ui/react';+import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';++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 render = async (value: string, widthPx = 320) => {+ host = document.createElement('div');+ host.style.width = `${widthPx}px`;+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <PromptTextarea+ aria-label="Values"+ defaultHeightPx={200}+ minHeightPx={96}+ readOnly+ resizeHandleAriaLabel="Resize"+ showLineNumbers+ showSyntaxHighlighting+ value={value}+ />+ </ChakraProvider>+ );+ });+ // The gutter sizes itself from a measured mirror, so let layout settle.+ await act(async () => {+ await new Promise((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ });+ });+};++const gutterEntries = () => [...host!.querySelectorAll('[data-line-number]')];++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('prompt line numbers', () => {+ it('numbers every logical line', async () => {+ await render('red\ngreen\nblue');++ expect(gutterEntries().map((entry) => entry.textContent)).toEqual(['1', '2', '3']);+ });++ it('numbers a blank line rather than skipping it', async () => {+ await render('red\n\nblue');++ expect(gutterEntries().map((entry) => entry.textContent)).toEqual(['1', '2', '3']);+ });++ it('gives a wrapped line one number and the height of its wrap', async () => {+ const long = 'a '.repeat(120).trim();++ await render(`short\n${long}\nshort`);++ const heights = gutterEntries().map((entry) => entry.getBoundingClientRect().height);++ expect(gutterEntries().map((entry) => entry.textContent)).toEqual(['1', '2', '3']);+ // The wrapped line keeps a single number but occupies several rows, so its+ // gutter entry has to be taller than its unwrapped neighbours.+ expect(heights[1]).toBeGreaterThan(heights[0] * 2);+ expect(heights[2]).toBeCloseTo(heights[0], 1);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsxnew file mode 100644index 0000000000..108db20b6f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx@@ -0,0 +1,131 @@+/**+ * A line-number gutter for `PromptTextarea`.+ *+ * A textarea gives no way to ask where its soft wraps fall, so the heights come+ * from a hidden mirror that lays the same text out at the same width with the+ * same metrics. Numbering follows *logical* lines: a wrapped line keeps one+ * number and the gutter entry grows to match, the way an editor behaves.+ */++import type { BoxProps } from '@chakra-ui/react';+import type { CSSProperties } from 'react';++import { Box } from '@chakra-ui/react';+import { useLayoutEffect, useMemo, useRef, useState } from 'react';++const TABULAR_NUMS: CSSProperties = { fontVariantNumeric: 'tabular-nums' };+/** Enough for the digits plus breathing room on either side, in `ch`. */+const GUTTER_PADDING_CH = 2;++export interface PromptLineNumbersMetrics {+ fontFamily: BoxProps['fontFamily'];+ fontSize: BoxProps['fontSize'];+ lineHeight: BoxProps['lineHeight'];+ /** The textarea's border-box width, so the mirror wraps identically. */+ clientWidth: number | null;+ paddingInline: string;+ paddingBlock: string;+ scrollTop: number;+}++/** Width the textarea must reserve on its leading edge for `lineCount` numbers. */+export const getLineNumberGutterCh = (lineCount: number): number =>+ String(Math.max(lineCount, 1)).length + GUTTER_PADDING_CH;++export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumbersMetrics; value: string }) => {+ const mirrorRef = useRef<HTMLDivElement | null>(null);+ const [lineHeights, setLineHeights] = useState<number[]>([]);+ const lines = useMemo(() => value.split('\n'), [value]);+ const gutterWidth = `${getLineNumberGutterCh(lines.length)}ch`;++ useLayoutEffect(() => {+ const mirror = mirrorRef.current;++ if (!mirror) {+ return;+ }++ const measure = () => {+ const heights = [...mirror.children].map((child) => child.getBoundingClientRect().height);++ setLineHeights((current) =>+ current.length === heights.length && current.every((height, index) => height === heights[index])+ ? current+ : heights+ );+ };+ const resizeObserver = new ResizeObserver(measure);++ measure();+ resizeObserver.observe(mirror);++ return () => resizeObserver.disconnect();+ }, [lines, metrics.clientWidth, metrics.fontSize, metrics.lineHeight]);++ const sharedTextStyles = {+ fontFamily: metrics.fontFamily,+ fontSize: metrics.fontSize,+ lineHeight: metrics.lineHeight,+ overflowWrap: 'break-word',+ whiteSpace: 'pre-wrap',+ } as const;++ return (+ <>+ {/* Measured, never seen. `visibility: hidden` still participates in layout,+ which is exactly what makes it measurable. */}+ <Box aria-hidden="true" inset="0" overflow="hidden" pointerEvents="none" position="absolute" visibility="hidden">+ <Box+ ref={mirrorRef}+ m="0"+ paddingBlock={metrics.paddingBlock}+ paddingInline={metrics.paddingInline}+ paddingInlineStart={`calc(${metrics.paddingInline} + ${gutterWidth})`}+ w={metrics.clientWidth ? `${metrics.clientWidth}px` : '100%'}+ {...sharedTextStyles}+ >+ {lines.map((line, index) => (+ // Zero-width space so a blank line still occupies one row.+ <Box key={index} as="div" {...sharedTextStyles}>+ {line === '' ? '' : line}+ </Box>+ ))}+ </Box>+ </Box>++ <Box+ aria-hidden="true"+ bottom="0"+ left="0"+ overflow="hidden"+ pointerEvents="none"+ position="absolute"+ top="0"+ w={gutterWidth}+ zIndex={2}+ >+ <Box+ color="fg.subtle"+ paddingBlock={metrics.paddingBlock}+ textAlign="end"+ transform={`translateY(${-metrics.scrollTop}px)`}+ w="full"+ {...sharedTextStyles}+ paddingInlineEnd="0.75ch"+ style={TABULAR_NUMS}+ >+ {lines.map((_, index) => (+ <Box+ key={index}+ data-line-number={index + 1}+ h={lineHeights[index] ? `${lineHeights[index]}px` : undefined}+ {...sharedTextStyles}+ >+ {index + 1}+ </Box>+ ))}+ </Box>+ </Box>+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxindex f038dabc4b..2c48483b53 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx@@ -3,6 +3,7 @@ import type { Ref, UIEvent } from 'react';import { Box } from '@chakra-ui/react';import { HighlightedPrompt, MAX_HIGHLIGHTED_PROMPT_LENGTH } from '@features/generation/ui/promptFields/PromptHighlight';+import { getLineNumberGutterCh, PromptLineNumbers } from '@features/generation/ui/promptFields/PromptLineNumbers';import { ResizableTextarea } from '@platform/ui';import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';const PROMPT_TEXTAREA_LINE_HEIGHT = '1.6';@@ -30,6 +31,8 @@ interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {/** Resolvable wildcard names; an unknown `__name__` is underlined as an error. */knownWildcards?: ReadonlySet<string>;showSyntaxHighlighting: boolean;+ /** Number logical lines in a leading gutter, the way an editor does. */+ showLineNumbers?: boolean;value: string;}@@ -53,6 +56,7 @@ export const PromptTextarea = ({knownWildcards,lineHeight,onScroll,+ showLineNumbers = false,showSyntaxHighlighting,textareaRef,value,@@ -64,14 +68,21 @@ export const PromptTextarea = ({const shouldHighlight = showSyntaxHighlighting && value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;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.+ const gutterCh = showLineNumbers ? getLineNumberGutterCh(value.split('\n').length) : 0;+ const paddingInlineStart = showLineNumbers+ ? `calc(var(--chakra-spacing-${PROMPT_TEXTAREA_PX}) + ${gutterCh}ch)`+ : undefined;const highlightOptions = useMemo(() => ({ dynamicPrompts: highlightDynamicPrompts, knownWildcards }),[highlightDynamicPrompts, knownWildcards]);+ const needsMirror = shouldHighlight || showLineNumbers;+useLayoutEffect(() => {- if (!shouldHighlight || !localTextareaRef.current) {+ if (!needsMirror || !localTextareaRef.current) {return;}@@ -91,7 +102,7 @@ export const PromptTextarea = ({resizeObserver.disconnect();window.removeEventListener('resize', syncClientWidth);};- }, [shouldHighlight, value]);+ }, [needsMirror, value]);const handleTextareaRef = useCallback((element: HTMLTextAreaElement | null) => {@@ -109,7 +120,20 @@ export const PromptTextarea = ({[onScroll]);- const underlay = useMemo(+ const lineNumberMetrics = useMemo(+ () => ({+ clientWidth: textareaClientWidth,+ fontFamily,+ fontSize: effectiveFontSize,+ lineHeight: effectiveLineHeight,+ paddingBlock: `var(--chakra-spacing-${PROMPT_TEXTAREA_PY})`,+ paddingInline: `var(--chakra-spacing-${PROMPT_TEXTAREA_PX})`,+ scrollTop: scroll.top,+ }),+ [effectiveFontSize, effectiveLineHeight, fontFamily, scroll.top, textareaClientWidth]+ );++ const highlightUnderlay = useMemo(() =>shouldHighlight ? (<Box@@ -133,8 +157,9 @@ export const PromptTextarea = ({m="0"minH="100%"overflowWrap="break-word"- px={PROMPT_TEXTAREA_PX}- py={PROMPT_TEXTAREA_PY}+ paddingBlock={PROMPT_TEXTAREA_PY}+ paddingInline={PROMPT_TEXTAREA_PX}+ paddingInlineStart={paddingInlineStart}transform={`translate(${-scroll.left}px, ${-scroll.top}px)`}whiteSpace="pre-wrap"w={textareaClientWidth ? `${textareaClientWidth}px` : '100%'}@@ -149,6 +174,7 @@ export const PromptTextarea = ({effectiveLineHeight,fontFamily,highlightOptions,+ paddingInlineStart,scroll.left,scroll.top,shouldHighlight,@@ -157,6 +183,17 @@ export const PromptTextarea = ({]);+ const underlay = useMemo(+ () =>+ needsMirror ? (+ <>+ {highlightUnderlay}+ {showLineNumbers ? <PromptLineNumbers metrics={lineNumberMetrics} value={value} /> : null}+ </>+ ) : null,+ [highlightUnderlay, lineNumberMetrics, needsMirror, showLineNumbers, value]+ );+return (<ResizableTextarea{...props}@@ -168,8 +205,9 @@ export const PromptTextarea = ({fontSize={effectiveFontSize}lineHeight={effectiveLineHeight}overflowWrap="break-word"- px={PROMPT_TEXTAREA_PX}- py={PROMPT_TEXTAREA_PY}+ paddingBlock={PROMPT_TEXTAREA_PY}+ paddingInline={PROMPT_TEXTAREA_PX}+ paddingInlineStart={paddingInlineStart}textareaRef={handleTextareaRef}underlay={underlay}value={value}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsxnew file mode 100644index 0000000000..39d63b828b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx@@ -0,0 +1,92 @@+import type { WildcardCatalog } from '@features/generation/ui/useWildcards';++import { ChakraProvider } from '@chakra-ui/react';+import { WildcardsPanel } from '@features/generation/ui/promptFields/WildcardsPanel';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++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 catalog: WildcardCatalog = {+ create: vi.fn(),+ isLoading: false,+ knownNames: new Set(['colors']),+ remove: vi.fn(),+ update: vi.fn(),+ wildcards: [{ id: 'w1', name: 'colors', values: ['red', 'green'] }],+};++const openEditor = async (showSyntaxHighlighting: boolean) => {+ host = document.createElement('div');+ host.style.width = '380px';+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <WildcardsPanel catalog={catalog} showSyntaxHighlighting={showSyntaxHighlighting} onInsert={vi.fn()} />+ </ChakraProvider>+ );+ });++ await act(async () => {+ await userEvent.click([...host!.querySelectorAll('button')][0]!);+ });++ const values = host!.querySelector('textarea')!;++ await act(async () => {+ await userEvent.fill(values, '(oil painting)1.3\nwatercolor+\n{ink|charcoal} sketch');+ });+ await act(async () => {+ await new Promise((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ });+ });+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('wildcard values editor', () => {+ it('colours attention and nested dynamic syntax in the values', async () => {+ await openEditor(true);++ const spans = [...host!.querySelectorAll('[aria-hidden="true"] pre span')].map((span) => span.textContent);++ // Attention weighting survives into the generated prompt, and a nested+ // `{a|b}` is live syntax inside a wildcard value, so both are coloured.+ expect(spans).toContain('1.3');+ expect(spans).toContain('+');+ expect(spans).toContain('{');+ expect(spans).toContain('|');+ });++ it('numbers each value in the gutter', async () => {+ await openEditor(true);++ expect([...host!.querySelectorAll('[data-line-number]')].map((entry) => entry.textContent)).toEqual([+ '1',+ '2',+ '3',+ ]);+ });++ it('still numbers the values when highlighting is off', async () => {+ // Line numbers are not syntax colouring, so they do not follow that setting.+ await openEditor(false);++ expect([...host!.querySelectorAll('[data-line-number]')]).toHaveLength(3);+ expect(host!.querySelectorAll('[aria-hidden="true"] pre span')).toHaveLength(0);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsxindex a0841cc60d..11782d7924 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx@@ -3,7 +3,8 @@ import type { WildcardRecord } from '@features/generation/data/wildcards';import type { WildcardCatalog } from '@features/generation/ui/useWildcards';import type { ChangeEvent } from 'react';-import { HStack, Input, Stack, Text, Textarea } from '@chakra-ui/react';+import { HStack, Input, Stack, Text } from '@chakra-ui/react';+import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';import { Button, IconButton } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { Tooltip } from '@platform/ui/Tooltip';@@ -24,8 +25,10 @@ interface WildcardDraft {export const WildcardsPanel = ({catalog,onInsert,+ showSyntaxHighlighting,}: {catalog: WildcardCatalog;+ showSyntaxHighlighting: boolean;/** Splices `__name__` into the prompt at the caret. */onInsert: (reference: string) => void;}) => {@@ -83,13 +86,21 @@ export const WildcardsPanel = ({value={draft.name}onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft({ ...draft, name: event.currentTarget.value })}/>- <Textarea+ {/* Values are expanded by dynamicprompts too, so a nested `{a|b}` or+ `__other__` is live syntax here and is coloured as such. The gutter+ numbers the values, which is what a line means in this editor. */}+ <PromptTextareaaria-label={t('widgets.generate.dynamicPrompts.wildcardValues')}- fontFamily="mono"+ defaultHeightPx={144}fontSize="0.72rem"- h="9rem"+ highlightDynamicPrompts+ knownWildcards={catalog.knownNames}+ maxHeightPx={320}+ minHeightPx={96}placeholder={t('widgets.generate.dynamicPrompts.wildcardValuesPlaceholder')}- resize="none"+ resizeHandleAriaLabel={t('widgets.generate.dynamicPrompts.resizeWildcardValues')}+ showLineNumbers+ showSyntaxHighlighting={showSyntaxHighlighting}size="xs"value={draft.valuesText}onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>