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.

9.1 KB
Raw Blame
import type { ResizableTextareaProps } from '@platform/ui';
import type { Ref, UIEvent } from 'react';

import { Box } from '@chakra-ui/react';
import { PROMPT_ATTENTION_TARGET_PROPS } from '@features/generation/ui/promptFields/promptAttentionHotkeys';
import { getTextareaWrapWidth } from '@features/generation/ui/promptFields/promptCaret';
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 { PROMPT_FONT_SIZE } from '@theme/scale';
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
const PROMPT_TEXTAREA_LINE_HEIGHT = '1.6';
/** Layout moves in 1/64 px steps; a smaller difference in the parsed width is not a resize. */
const WRAP_WIDTH_EPSILON_PX = 0.01;
// Use literal lengths; fractional Chakra spacing variables fail inside calc.
const PROMPT_TEXTAREA_PX = '0.625rem';
const PROMPT_TEXTAREA_PY = '0.5rem';

const PROMPT_TEXTAREA_FORCED_COLORS_CSS = { '@media (forced-colors: active)': { display: 'none' } };
const PROMPT_TEXTAREA_HIGHLIGHTED_CSS = {
  '&::selection': { color: 'transparent', WebkitTextFillColor: 'transparent' },
  '@media (forced-colors: active)': {
    WebkitTextFillColor: 'CanvasText',
    backgroundColor: 'Field',
    color: 'CanvasText',
  },
  WebkitTextFillColor: 'transparent',
};

/**
 * What the prompt does with Compel attention syntax. `edit` highlights it and lets the weighting keys rewrite it;
 * `highlight` only highlights it, for text not yet bound to a model; `none` leaves it plain because the model reads the
 * prompt as written.
 */
type PromptAttentionSyntax = 'edit' | 'highlight' | 'none';

interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {
  attentionSyntax?: PromptAttentionSyntax;
  /** Enable dynamic highlighting only for prompts that actually expand syntax. */
  highlightDynamicPrompts?: boolean;
  /** 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 must equal the concatenated chunks, and the input must be readOnly. */
  templateChunks?: [string, string, string] | null;
  value: string;
}

const setRef = (ref: Ref<HTMLTextAreaElement> | undefined, element: HTMLTextAreaElement | null): void => {
  if (!ref) {
    return;
  }

  if (typeof ref === 'function') {
    ref(element);
    return;
  }

  (ref as { current: HTMLTextAreaElement | null }).current = element;
};

export const PromptTextarea = ({
  attentionSyntax = 'highlight',
  fontFamily = 'mono',
  fontSize,
  highlightDynamicPrompts = false,
  knownWildcards,
  lineHeight,
  onScroll,
  showLineNumbers = false,
  showSyntaxHighlighting,
  templateChunks = null,
  textareaRef,
  value,
  ...props
}: PromptTextareaProps) => {
  const localTextareaRef = useRef<HTMLTextAreaElement | null>(null);
  const [scroll, setScroll] = useState({ left: 0, top: 0 });
  const [textareaWrapWidth, setTextareaWrapWidth] = useState<number | null>(null);
  const isWithinHighlightBudget = value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;
  const highlightsSyntax = showSyntaxHighlighting && (attentionSyntax !== 'none' || highlightDynamicPrompts);
  // Template chunk emphasis is independent of the syntax-highlighting preference.
  const shouldHighlight = (highlightsSyntax || templateChunks !== null) && isWithinHighlightBudget;
  const effectiveFontSize = fontSize ?? PROMPT_FONT_SIZE;
  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(${PROMPT_TEXTAREA_PX} + ${gutterCh}ch)` : undefined;

  const highlightOptions = useMemo(
    () => ({ attentionSyntax: attentionSyntax !== 'none', dynamicPrompts: highlightDynamicPrompts, knownWildcards }),
    [attentionSyntax, highlightDynamicPrompts, knownWildcards]
  );

  const needsMirror = shouldHighlight || showLineNumbers;

  useLayoutEffect(() => {
    if (!needsMirror || !localTextareaRef.current) {
      return;
    }

    const textarea = localTextareaRef.current;
    // Live: it reflects later layout, so one lookup serves every measurement of this run.
    const computed = window.getComputedStyle(textarea);
    // Re-run on value: typing can add or remove a vertical scrollbar, which narrows the wrap box.
    const syncWrapWidth = () => {
      const nextWidth = getTextareaWrapWidth(textarea, computed);

      setTextareaWrapWidth((currentWidth) =>
        currentWidth !== null && Math.abs(currentWidth - nextWidth) < WRAP_WIDTH_EPSILON_PX ? currentWidth : nextWidth
      );
    };
    const resizeObserver = new ResizeObserver(syncWrapWidth);

    syncWrapWidth();
    resizeObserver.observe(textarea);
    window.addEventListener('resize', syncWrapWidth);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', syncWrapWidth);
    };
  }, [needsMirror, value]);

  const handleTextareaRef = useCallback(
    (element: HTMLTextAreaElement | null) => {
      localTextareaRef.current = element;
      setRef(textareaRef, element);
    },
    [textareaRef]
  );

  const handleScroll = useCallback(
    (event: UIEvent<HTMLTextAreaElement>) => {
      setScroll({ left: event.currentTarget.scrollLeft, top: event.currentTarget.scrollTop });
      onScroll?.(event);
    },
    [onScroll]
  );

  const lineNumberMetrics = useMemo(
    () => ({
      fontFamily,
      fontSize: effectiveFontSize,
      lineHeight: effectiveLineHeight,
      paddingBlock: PROMPT_TEXTAREA_PY,
      paddingInline: PROMPT_TEXTAREA_PX,
      scrollTop: scroll.top,
      wrapWidth: textareaWrapWidth,
    }),
    [effectiveFontSize, effectiveLineHeight, fontFamily, scroll.top, textareaWrapWidth]
  );

  const highlightUnderlay = useMemo(
    () =>
      shouldHighlight ? (
        <Box
          aria-hidden="true"
          borderColor="transparent"
          borderRadius="md"
          borderWidth="1px"
          color="fg"
          inset="0"
          overflow="hidden"
          pointerEvents="none"
          position="absolute"
          zIndex={0}
          css={PROMPT_TEXTAREA_FORCED_COLORS_CSS}
        >
          <Box
            as="pre"
            fontFamily={fontFamily}
            fontSize={effectiveFontSize}
            lineHeight={effectiveLineHeight}
            m="0"
            minH="100%"
            overflowWrap="break-word"
            paddingBlock={PROMPT_TEXTAREA_PY}
            paddingInline={PROMPT_TEXTAREA_PX}
            paddingInlineStart={paddingInlineStart}
            transform={`translate(${-scroll.left}px, ${-scroll.top}px)`}
            whiteSpace="pre-wrap"
            w={textareaWrapWidth ? `${textareaWrapWidth}px` : '100%'}
          >
            {templateChunks ? (
              <>
                <Box as="span" color="fg.subtle">
                  {templateChunks[0]}
                </Box>
                {highlightsSyntax ? (
                  <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>
      ) : null,
    [
      effectiveFontSize,
      effectiveLineHeight,
      fontFamily,
      highlightOptions,
      highlightsSyntax,
      paddingInlineStart,
      scroll.left,
      scroll.top,
      shouldHighlight,
      templateChunks,
      textareaWrapWidth,
      value,
    ]
  );

  const underlay = useMemo(
    () =>
      needsMirror ? (
        <>
          {highlightUnderlay}
          {showLineNumbers ? <PromptLineNumbers metrics={lineNumberMetrics} value={value} /> : null}
        </>
      ) : null,
    [highlightUnderlay, lineNumberMetrics, needsMirror, showLineNumbers, value]
  );

  return (
    <ResizableTextarea
      {...props}
      {...(attentionSyntax === 'edit' ? PROMPT_ATTENTION_TARGET_PROPS : null)}
      bg={shouldHighlight ? 'transparent' : props.bg}
      caretColor={shouldHighlight ? 'fg' : props.caretColor}
      color={shouldHighlight ? 'transparent' : props.color}
      css={shouldHighlight ? PROMPT_TEXTAREA_HIGHLIGHTED_CSS : props.css}
      fontFamily={fontFamily}
      fontSize={effectiveFontSize}
      lineHeight={effectiveLineHeight}
      overflowWrap="break-word"
      paddingBlock={PROMPT_TEXTAREA_PY}
      paddingInline={PROMPT_TEXTAREA_PX}
      paddingInlineStart={paddingInlineStart}
      textareaRef={handleTextareaRef}
      underlay={underlay}
      value={value}
      onScroll={handleScroll}
    />
  );
};