All files / src/tagselect TagSelectInput.tsx

100% Statements 9/9
75% Branches 3/4
100% Functions 2/2
100% Lines 9/9

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                1x       4x 4x 4x   4x 2x 2x 2x     4x                                            
import React, { forwardRef, useRef, useState, useEffect } from "react";
import { mergeRefs } from "../_util/merge-refs";
import { InputProps, Input } from "../input";
 
interface TagSelectInputProps extends InputProps {
  maxWidth: number;
}
 
export const TagSelectInput = forwardRef(function TagSelectInput(
  { value, maxWidth, placeholder, ...props }: TagSelectInputProps,
  ref: React.Ref<HTMLInputElement>
) {
  const inputRef = useRef<HTMLInputElement>(null);
  const mirrorRef = useRef<HTMLSpanElement>(null);
  const [width, setWidth] = useState<number>(0);
 
  useEffect(() => {
    mirrorRef.current.innerText = value || placeholder;
    const width = mirrorRef.current.clientWidth;
    setWidth(width > maxWidth ? maxWidth : width);
  }, [maxWidth, placeholder, value]);
 
  return (
    <>
      <Input
        {...props}
        value={value}
        placeholder={placeholder}
        style={{ width: width + 6 }}
        ref={mergeRefs(ref, inputRef)}
      />
      <span
        ref={mirrorRef}
        style={{
          position: "absolute",
          top: -9999,
          left: 0,
          whiteSpace: "pre",
          fontSize: 12,
        }}
      />
    </>
  );
});