useTextSelection
Tracking content, size, position of user text selection.
Overview
Tracking content, size, position of user text selection.
Installation
Open inpnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.jsonnpx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.jsonyarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.jsonbun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.jsonTracking content, size, position of user text selection.
Examples
Default usage
Listen for specified area
Translate user text selection
import { Popover, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import useRequest from '@/src/hooks/ahooks/useRequest';
import useTextSelection from '@/src/hooks/ahooks/useTextSelection';
const getResult = (keyword: string): Promise<string> => {
const trimedText = keyword.trim() !== '';
if (!trimedText) {
return Promise.resolve('');
}
return new Promise((resolve) => {
setTimeout(() => resolve(`[translate result] ${keyword}`), 2000);
});
};
export default () => {
const {
text = '',
left = 0,
top = 0,
height = 0,
width = 0,
} = useTextSelection(() => document.querySelector('#translate-dom'));
const [open, setOpen] = useState<boolean>(false);
const { data, run, loading } = useRequest(getResult, {
manual: true,
});
useEffect(() => {
if (text.trim() === '') {
setOpen(false);
return;
}
setOpen(true);
run(text);
}, [text]);
return (
<div>
<p id="translate-dom" style={{ padding: 20, border: '1px solid' }}>
Translation of this paragraph;Translation of this paragraph;Translation of this paragraph;
</p>
<Popover
content={<Spin spinning={loading}>{loading ? 'Translating……' : data}</Spin>}
open={open}
>
<span
style={{
position: 'fixed',
top: `${top}px`,
left: `${left}px`,
height: `${height}px`,
width: `${width}px`,
pointerEvents: 'none',
}}
/>
</Popover>
</div>
);
};API
const state = useTextSelection(target?);Params
| Property | Description | Type | Default |
|---|---|---|---|
| target | DOM element or ref | Element | Document | (() => Element\Document) | MutableRefObject<Element> | document |
Result
| Property | Description | Type |
|---|---|---|
| state | Content, size, position of user text selection | State |
State
| Property | Description | Type |
|---|---|---|
| text | Selected text | string |
| left | The left coordinate value of text | number |
| right | The right coordinate value of text | number |
| top | The top coordinate value of text | number |
| bottom | The bottom coordinate value of text | number |
| height | The height of text | number |
| width | The width of text | number |