UNPKG

react-bootstrap-typeahead

Version:
68 lines (67 loc) 2.55 kB
import React, { useEffect, useRef } from 'react'; import { useTypeaheadContext } from '../../core/Context'; function interpolateStyle(styles, attr, subattr = '') { if (subattr) { subattr = subattr.replace(subattr[0], subattr[0].toUpperCase()); } return ['Top', 'Right', 'Bottom', 'Left'] .map((dir) => styles[`${attr}${dir}${subattr}`]) .join(' '); } function copyStyles(inputNode, hintNode) { const inputStyle = window.getComputedStyle(inputNode); hintNode.style.borderStyle = interpolateStyle(inputStyle, 'border', 'style'); hintNode.style.borderWidth = interpolateStyle(inputStyle, 'border', 'width'); hintNode.style.fontSize = inputStyle.fontSize; hintNode.style.fontWeight = inputStyle.fontWeight; hintNode.style.height = inputStyle.height; hintNode.style.lineHeight = inputStyle.lineHeight; hintNode.style.margin = interpolateStyle(inputStyle, 'margin'); hintNode.style.padding = interpolateStyle(inputStyle, 'padding'); } export const useHint = () => { const { hintText, inputNode } = useTypeaheadContext(); const hintRef = useRef(null); useEffect(() => { const handleInputScroll = () => { if (hintRef.current && inputNode) { hintRef.current.scrollLeft = inputNode.scrollLeft; } }; inputNode?.addEventListener('scroll', handleInputScroll); return () => { inputNode?.removeEventListener('scroll', handleInputScroll); }; }, [inputNode]); useEffect(() => { if (inputNode && hintRef.current) { copyStyles(inputNode, hintRef.current); } }); return { hintRef, hintText, }; }; const Hint = ({ children, className }) => { const { hintRef, hintText } = useHint(); return (React.createElement("div", { className: className, style: { display: 'flex', flex: 1, height: '100%', position: 'relative', } }, children, React.createElement("input", { "aria-hidden": true, className: "rbt-input-hint", ref: hintRef, readOnly: true, style: { backgroundColor: 'transparent', borderColor: 'transparent', boxShadow: 'none', color: 'rgba(0, 0, 0, 0.54)', left: 0, pointerEvents: 'none', position: 'absolute', top: 0, width: '100%', }, tabIndex: -1, value: hintText }))); }; export default Hint;