(win?: Window)
| 27 | } |
| 28 | |
| 29 | export function useTextSelection(win?: Window) { |
| 30 | const [selection, setSelection] = useState<Selection | undefined>() |
| 31 | const render = useForceRender() |
| 32 | |
| 33 | // On touch screen device, mouse/touch/pointer events not working when selection is created. |
| 34 | useEventListener( |
| 35 | isTouchScreen ? win?.document : win, |
| 36 | isTouchScreen ? 'selectionchange' : 'mouseup', |
| 37 | () => { |
| 38 | const s = win?.getSelection() |
| 39 | |
| 40 | if (hasSelection(s)) { |
| 41 | // sometime `getSelection` will return the same `selection` |
| 42 | // when select text by clicking empty space |
| 43 | render() |
| 44 | setSelection(s) |
| 45 | } |
| 46 | }, |
| 47 | ) |
| 48 | |
| 49 | // https://stackoverflow.com/questions/3413683/disabling-the-context-menu-on-long-taps-on-android |
| 50 | useEventListener(win, 'contextmenu', (e) => { |
| 51 | if (isTouchScreen) { |
| 52 | e.preventDefault() |
| 53 | } |
| 54 | }) |
| 55 | |
| 56 | return [selection, setSelection] as const |
| 57 | } |
no test coverage detected