-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathautoSelectText.tsx
More file actions
46 lines (39 loc) · 1.16 KB
/
autoSelectText.tsx
File metadata and controls
46 lines (39 loc) · 1.16 KB
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
46
import {useImperativeHandle, useRef} from 'react';
import classNames from 'classnames';
import {selectText} from 'sentry/utils/selectText';
type Props = {
children: React.ReactNode;
className?: string;
ref?: React.Ref<AutoSelectHandle>;
style?: React.CSSProperties;
};
type AutoSelectHandle = {
selectText: () => void;
};
export function AutoSelectText({children, className, ref, ...props}: Props) {
const element = useRef<HTMLSpanElement>(null);
// We need to expose a selectText method to parent components
// and need an imperative ref handle.
useImperativeHandle(ref, () => ({
selectText: () => handleClick(),
}));
function handleClick() {
if (!element.current) {
return;
}
selectText(element.current);
}
// use an inner span here for the selection as otherwise the selectText
// function will create a range that includes the entire part of the
// div (including the div itself) which causes newlines to be selected
// in chrome.
return (
<div
{...props}
onClick={handleClick}
className={classNames('auto-select-text', className)}
>
<span ref={element}>{children}</span>
</div>
);
}