Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

2.3 KB
Raw Blame
import { cn } from '@langgenius/dify-ui/cn'
import { useEffect, useRef } from 'react'
import { sleep } from '@/utils'

type IProps = {
  'aria-label'?: string
  placeholder?: string
  value: string
  onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
  className?: string
  wrapperClassName?: string
  minHeight?: number
  maxHeight?: number
  autoFocus?: boolean
  controlFocus?: number
  onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
  onKeyUp?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
}

const AutoHeightTextarea = ({
  'aria-label': ariaLabel,
  ref: outerRef,
  value,
  onChange,
  placeholder,
  className,
  wrapperClassName,
  minHeight = 36,
  maxHeight = 96,
  autoFocus,
  controlFocus,
  onKeyDown,
  onKeyUp,
}: IProps & {
  ref?: React.RefObject<HTMLTextAreaElement>
}) => {
  // oxlint-disable-next-line react/rules-of-hooks
  const ref = outerRef || useRef<HTMLTextAreaElement>(null)

  const doFocus = () => {
    if (ref.current) {
      ref.current.setSelectionRange(value.length, value.length)
      ref.current.focus()
      return true
    }
    return false
  }

  const focus = async () => {
    if (!doFocus()) {
      let hasFocus = false
      await sleep(100)
      hasFocus = doFocus()
      if (!hasFocus) focus()
    }
  }

  useEffect(() => {
    if (autoFocus) focus()
  }, [])
  useEffect(() => {
    if (controlFocus) focus()
  }, [controlFocus])

  return (
    <div className={`relative ${wrapperClassName}`}>
      <div
        className={cn(className, 'invisible overflow-y-auto break-all whitespace-pre-wrap')}
        style={{
          minHeight,
          maxHeight,
          paddingRight: value && value.trim().length > 10000 ? 140 : 130,
        }}
      >
        {!value ? placeholder : value.replace(/\n$/, '\n ')}
      </div>
      <textarea
        ref={ref}
        aria-label={ariaLabel}
        autoFocus={autoFocus}
        className={cn(className, 'absolute inset-0 resize-none overflow-auto')}
        style={{
          paddingRight: value && value.trim().length > 10000 ? 140 : 130,
        }}
        placeholder={placeholder}
        onChange={onChange}
        onKeyDown={onKeyDown}
        onKeyUp={onKeyUp}
        value={value}
      />
    </div>
  )
}

AutoHeightTextarea.displayName = 'AutoHeightTextarea'

export default AutoHeightTextarea