import { useMemo } from 'react' /** * Groups the given value (if text like) into fragments. * * Given string value is always split into atleast 2 pieces, head and tail, * so that ellipsis can be rendered in the middle when the viewport space is * limited. If theres a match range, a "match" fragment is also returned that * needs to be rendered right in between head and tail. */ export const useTextMatchGroups = (value: unknown, matchRange: [number, number]) => useMemo(() => { if (['string', 'boolean', 'number'].includes(typeof value)) { const str = value.toString() const [matchStart, matchEnd] = matchRange const hasHighlight = matchStart > -1 const head = str.substring(0, hasHighlight ? matchStart : str.length / 2) const match = str.substring(matchStart, matchEnd) const tail = str.substring(head.length + match.length) return { head, match, tail } } return null }, [value, matchRange])