UNPKG

reactuals

Version:

A useful package providing a collection of 50+ React hooks and utilities to simplify React development.

36 lines (35 loc) 1.43 kB
import { useState, useEffect, useRef } from "react"; export function useTextSelection(elementRef) { const [selection, setSelection] = useState({ text: "", range: null, }); const latestSelection = useRef({ text: "", range: null }); useEffect(() => { const handleSelectionChange = () => { const sel = window.getSelection(); if (!sel || sel.rangeCount === 0) { latestSelection.current = { text: "", range: null }; setSelection(latestSelection.current); return; } const range = sel.getRangeAt(0); const target = elementRef?.current; const isWithinElement = target ? range.commonAncestorContainer === target || target.contains(range.commonAncestorContainer) : true; if (isWithinElement) { const text = sel.toString(); latestSelection.current = { text, range: range.cloneRange() }; } else { latestSelection.current = { text: "", range: null }; } setSelection(latestSelection.current); }; document.addEventListener("selectionchange", handleSelectionChange); return () => document.removeEventListener("selectionchange", handleSelectionChange); }, [elementRef]); return selection; }