All files / src/components/Chatbot CustomInput.tsx

100% Statements 142/142
100% Branches 21/21
66.66% Functions 4/6
100% Lines 142/142

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215  1x             1x 1x     1x     1x     1x     1x                 1x 11x   11x 11x 11x   11x 11x 11x   11x     11x 3x   3x 3x 3x 3x 11x     11x 2x   2x   1x 1x     1x 1x 1x 1x 1x 2x   11x 11x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 11x   11x 1x 1x 1x 1x 1x   11x 1x 1x 1x 1x     11x 13x 13x   13x   12x     12x   12x 12x     13x 11x     11x       11x 11x 11x 11x 11x 11x     11x 11x 11x   11x 11x 2x     2x 2x 11x 11x     11x 11x 11x   11x 11x 9x 9x 11x     11x 11x   4x 2x 4x 4x 11x   11x 11x 11x 11x 11x 11x   11x   11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x   11x 11x 11x 11x 11x   11x 11x 11x 11x 11x   11x  
import { InputProps } from '@copilotkit/react-ui';
import {
  useRef,
  useEffect,
  useCallback,
  ChangeEvent,
  KeyboardEvent,
} from 'react';
import { useCopilotChat } from '@copilotkit/react-core';
import { Role, TextMessage } from '@copilotkit/runtime-client-gql';
 
// Icons
import { SendIcon } from '../icons/reacts';
 
// Constants
import { KEYBOARD_EVENT } from '@shared/constants';
 
// Utils
import { combineClasses } from '@shared/utils';
 
// Stores
import {
  useChatInputValue,
  useSetChatInputValue,
  useSetTextareaCursorPosition,
  useSetTextareaScrollTop,
  useTextareaCursorPosition,
  useTextareaScrollTop,
} from '@/stores';
 
export const CustomInput = ({ inProgress }: InputProps) => {
  const { appendMessage } = useCopilotChat();
 
  const inputValue = useChatInputValue();
  const textareaCursorPosition = useTextareaCursorPosition();
  const textareaScrollTop = useTextareaScrollTop();
 
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const textareaWrapperRef = useRef<HTMLDivElement>(null);
  const touchedTextarea = useRef(false);
 
  const isSend = !!inputValue.trim();
 
  // Save textarea position (cursor position and scroll)
  const saveTextareaPosition = useCallback(() => {
    const textarea = textareaRef.current;
 
    if (textarea) {
      useSetTextareaCursorPosition(textarea.selectionStart);
      useSetTextareaScrollTop(textarea.scrollTop);
    }
  }, [useSetTextareaCursorPosition, useSetTextareaScrollTop]);
 
  // Restore textarea position (cursor position and scroll)
  const restoreTextareaPosition = () => {
    const textarea = textareaRef.current;
 
    if (textarea) {
      // Restore scroll position in percentage of max scroll height
      textarea.scrollTop =
        textareaScrollTop * (textarea.scrollHeight - textarea.clientHeight);
 
      // Restore cursor position
      textarea.setSelectionRange(
        textareaCursorPosition,
        textareaCursorPosition,
      );
    }
  };
 
  const handleSubmit = useCallback(
    async (value: string) => {
      if (value.trim()) {
        const message = new TextMessage({
          content: value,
          role: Role.User,
        });
        appendMessage(message);
        useSetChatInputValue('');
      }
    },
    [appendMessage, useSetChatInputValue],
  );
 
  const handleOnKeydownInput = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === KEYBOARD_EVENT.ENTER && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(inputValue);
    }
  };
 
  const handleSendClick = () => {
    if (inputValue.trim()) {
      handleSubmit(inputValue);
    }
  };
 
  // Dynamically resize textarea and setup mobile scrolling
  const resizeTextarea = useCallback(() => {
    const textarea = textareaRef.current;
    const wrapper = textareaWrapperRef.current;
 
    if (!textarea || !wrapper) return;
 
    textarea.style.height = 'auto';
 
    // Limit height to max 100px
    const newHeight = Math.min(textarea.scrollHeight, 100);
 
    wrapper.style.height = `${newHeight}px`;
    textarea.style.height = '100%'; // Textarea fills full height of wrapper
 
    // Setup mobile scrolling only once
    if (!touchedTextarea.current) {
      textarea.style.overflowY = 'auto';
 
      // Enable smooth momentum scrolling on iOS devices
      textarea.style.setProperty('-webkit-overflow-scrolling', 'touch');
 
      // Prevent scroll events from bubbling up to parent elements
      // This stops the page from scrolling when user scrolls inside textarea
      textarea.addEventListener('touchstart', (e) => e.stopPropagation(), {
        passive: true,
      });
      textarea.addEventListener('touchmove', (e) => e.stopPropagation(), {
        passive: true,
      });
 
      // Mark as completed to prevent adding duplicate listeners
      touchedTextarea.current = true;
    }
  }, []);
 
  const handleOnChangeInput = useCallback(
    (e: ChangeEvent<HTMLTextAreaElement>) => {
      useSetChatInputValue(e.target.value);
 
      // Delay resize textarea to avoid flickering
      requestAnimationFrame(resizeTextarea);
    },
    [useSetChatInputValue, resizeTextarea],
  );
 
  // Resize textarea when input value changes
  useEffect(() => {
    resizeTextarea();
  }, [inputValue, resizeTextarea]);
 
  useEffect(() => {
    if (!inProgress && textareaRef.current) {
      textareaRef.current.focus();
    }
  }, [inProgress, textareaRef]);
 
  // Restore textarea state only when component mounts with existing input
  useEffect(() => {
    if (textareaRef.current && inputValue) {
      // Use a small delay to ensure the textarea is fully rendered
      setTimeout(() => {
        restoreTextareaPosition();
      }, 50);
    }
  }, []); // Only run once on mount
 
  return (
    <div className="px-5 pb-5">
      <div
        className={combineClasses(
          'flex w-full rounded-md bg-primary-200 gap-1 items-center dark:bg-secondary-970',
        )}
      >
        <div className={combineClasses('flex w-full')}>
          {/* Textarea wrapper with dynamic height */}
          <div
            ref={textareaWrapperRef}
            className="w-full p-2 pr-0 min-h-12.5 max-h-25"
          >
            <textarea
              id="chat-input"
              rows={1}
              ref={textareaRef}
              disabled={inProgress}
              value={inputValue}
              onChange={handleOnChangeInput}
              onSelect={saveTextareaPosition}
              onScroll={saveTextareaPosition}
              placeholder="Type your message here"
              onKeyDown={handleOnKeydownInput}
              aria-label="Chat message input"
              className={combineClasses(
                'size-full py-2 px-1.5 resize-none tiny-scrollbar overflow-y-auto',
                'text-xs sm:text-3xs leading-tight font-normal bg-primary-200',
                'focus:outline-none disabled:bg-primary-200 placeholder:text-muted-foreground dark:bg-secondary-970 dark:placeholder:text-background dark:text-background dark:disabled:bg-secondary-970',
              )}
            />
          </div>
        </div>
 
        {/* Action buttons container */}
        <div className={combineClasses('flex items-center self-stretch')}>
          {/* Send message button */}
          <button
            aria-label="Send chat button"
            disabled={!isSend || inProgress}
            className="p-2 px-3 disabled:opacity-50"
            onClick={handleSendClick}
          >
            <SendIcon className="text-primary-600" />
          </button>
        </div>
      </div>
    </div>
  );
};