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.

2.1 KB
Raw Blame
import type { PromptAttentionDirection } from '@features/generation/core/prompt/attention';

import { adjustPromptAttention } from '@features/generation/core/prompt/attention';

/** `PromptTextarea` writes it only while the model reads attention syntax; the hotkey catalog claims keys on it. */
const PROMPT_ATTENTION_TARGET_ATTR = 'data-prompt-attention-target';
export const PROMPT_ATTENTION_TARGET_PROPS = { [PROMPT_ATTENTION_TARGET_ATTR]: 'true' } as const;

/** Guard readOnly explicitly: native setters and synthetic input bypass it and could merge templates twice. */
const isPromptAttentionTarget = (element: Element | null): element is HTMLTextAreaElement =>
  element instanceof HTMLTextAreaElement &&
  element.getAttribute(PROMPT_ATTENTION_TARGET_ATTR) === 'true' &&
  !element.readOnly;

const setTextareaValue = (textarea: HTMLTextAreaElement, value: string): void => {
  const valueSetter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set;

  if (valueSetter) {
    valueSetter.call(textarea, value);
  } else {
    textarea.value = value;
  }

  textarea.dispatchEvent(new Event('input', { bubbles: true }));
};

const replaceTextareaValue = (textarea: HTMLTextAreaElement, value: string): void => {
  textarea.focus();
  textarea.setSelectionRange(0, textarea.value.length);

  if (typeof document.execCommand === 'function' && document.execCommand('insertText', false, value)) {
    return;
  }

  setTextareaValue(textarea, value);
};

export const adjustFocusedPromptAttention = (
  direction: PromptAttentionDirection,
  preferNumericAttentionStyle: boolean
): boolean => {
  const textarea = document.activeElement;

  if (!isPromptAttentionTarget(textarea)) {
    return false;
  }

  const selectionDirection = textarea.selectionDirection;
  const result = adjustPromptAttention(
    textarea.value,
    textarea.selectionStart,
    textarea.selectionEnd,
    direction,
    preferNumericAttentionStyle
  );

  if (result.prompt === textarea.value) {
    return false;
  }

  replaceTextareaValue(textarea, result.prompt);
  textarea.setSelectionRange(result.selectionStart, result.selectionEnd, selectionDirection);

  return true;
};