react-bootstrap-typeahead
Version:
React typeahead with Bootstrap styling
93 lines (90 loc) • 3.17 kB
JavaScript
import React, { useEffect, useRef } from 'react';
import { useTypeaheadContext } from '../../core/Context';
// IE doesn't seem to get the composite computed value (eg: 'padding',
// 'borderStyle', etc.), so generate these from the individual values.
function interpolateStyle(styles, attr) {
var subattr = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
// Title-case the sub-attribute.
if (subattr) {
/* eslint-disable-next-line no-param-reassign */
subattr = subattr.replace(subattr[0], subattr[0].toUpperCase());
}
return ['Top', 'Right', 'Bottom', 'Left'].map(function (dir) {
return styles["".concat(attr).concat(dir).concat(subattr)];
}).join(' ');
}
function copyStyles(inputNode, hintNode) {
var inputStyle = window.getComputedStyle(inputNode);
/* eslint-disable no-param-reassign */
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');
/* eslint-enable no-param-reassign */
}
export var useHint = function useHint() {
var _useTypeaheadContext = useTypeaheadContext(),
hintText = _useTypeaheadContext.hintText,
inputNode = _useTypeaheadContext.inputNode;
var hintRef = useRef(null);
useEffect(function () {
// Scroll hint input when the text input is scrolling.
var handleInputScroll = function handleInputScroll() {
if (hintRef.current && inputNode) {
hintRef.current.scrollLeft = inputNode.scrollLeft;
}
};
inputNode === null || inputNode === void 0 || inputNode.addEventListener('scroll', handleInputScroll);
return function () {
inputNode === null || inputNode === void 0 || inputNode.removeEventListener('scroll', handleInputScroll);
};
}, [inputNode]);
useEffect(function () {
if (inputNode && hintRef.current) {
copyStyles(inputNode, hintRef.current);
}
});
return {
hintRef: hintRef,
hintText: hintText
};
};
var Hint = function Hint(_ref) {
var children = _ref.children,
className = _ref.className;
var _useHint = useHint(),
hintRef = _useHint.hintRef,
hintText = _useHint.hintText;
return /*#__PURE__*/React.createElement("div", {
className: className,
style: {
display: 'flex',
flex: 1,
height: '100%',
position: 'relative'
}
}, children, /*#__PURE__*/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;