shadcn-ahooks

useTextSelection

Tracking content, size, position of user text selection.

Overview

Tracking content, size, position of user text selection.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useTextSelection.json

Tracking 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

PropertyDescriptionTypeDefault
targetDOM element or refElement | Document | (() => Element\Document) | MutableRefObject<Element>document

Result

PropertyDescriptionType
stateContent, size, position of user text selectionState

State

PropertyDescriptionType
textSelected textstring
leftThe left coordinate value of textnumber
rightThe right coordinate value of textnumber
topThe top coordinate value of textnumber
bottomThe bottom coordinate value of textnumber
heightThe height of textnumber
widthThe width of textnumber

On this page