All files / Bandstand/src/components AutoTextarea.tsx

80.64% Statements 25/31
66.66% Branches 2/3
50% Functions 1/2
80.64% Lines 25/31

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    1x             11x 11x 11x 11x 11x 11x     11x 11x 11x 4x 4x 4x 4x 11x 11x 11x 11x 11x 11x 11x             11x 11x 11x   11x  
'use client'
 
import {TextareaHTMLAttributes, useLayoutEffect, useRef} from 'react'
 
/**
 * A textarea that grows with its content, so long notes are readable in
 * full instead of scrolling inside a one-line box. `singleLine` keeps it
 * one paragraph (Enter doesn't add a line), for titles.
 */
export default function AutoTextarea({
  singleLine = false,
  value,
  onKeyDown,
  ...props
}: TextareaHTMLAttributes<HTMLTextAreaElement> & {
  singleLine?: boolean
  value: string
}) {
  const ref = useRef<HTMLTextAreaElement>(null)
  useLayoutEffect(() => {
    const el = ref.current
    if (!el) return
    el.style.height = 'auto'
    el.style.height = `${el.scrollHeight}px`
  }, [value])
  return (
    <textarea
      ref={ref}
      rows={1}
      value={value}
      onKeyDown={(e) => {
        if (singleLine && e.key === 'Enter') {
          e.preventDefault()
          e.currentTarget.blur()
        }
        onKeyDown?.(e)
      }}
      {...props}
      style={{resize: 'none', overflow: 'hidden', ...props.style}}
    />
  )
}