Giter Club home page Giter Club logo

selection-popover's Issues

Using selection-popover with RadixUI Dialog component will cause the dialog dismiss incorrectly

Bug report

I used selection-popover with radix-ui dialog component together, the selection-popover can work correctly, however when the dialog pops over and clicking any area on the dialog will make the dialog dismissed incorrectly.

Current Behavior

The modal dialog dismissed incorrectly.

See the sandbox demo: https://codesandbox.io/p/sandbox/distracted-worker-2hgg6n?file=%2FApp.jsx%3A21%2C30

Expected behavior

The dialog should be working as normal and should not be dismissed by clicking any area.

Reproducible example

CodeSandbox Link

Additional context

See the codesandbox for more dependency info:

{
  "dependencies": {
    "@radix-ui/colors": "latest",
    "@radix-ui/react-dialog": "latest",
    "@radix-ui/react-icons": "latest",
    "classnames": "latest",
    "clsx": "^1.2.1",
    "react": "latest",
    "react-dom": "latest",
    "selection-popover": "^0.2.0"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "latest",
    "autoprefixer": "latest",
    "postcss": "latest",
    "tailwindcss": "latest",
    "vite": "latest"
  },
  "scripts": {
    "start": "vite"
  }
}

Your environment

  • OS: MacOS Desktop
  • Browser: Chrome

Textarea and Input support

Textarea and Input support

Overview

<textarea> and <input> text is not supported at the moment. This would be good for rich text editor support. I'm currently using this code locally to make it work but there could be another solution that doesn't involve adding and removing a div to get the coordinates.

      const getDummyRect = (el: HTMLTextAreaElement | HTMLInputElement): DOMRect => {
        const dummyDiv = document.createElement("div");
        dummyDiv.textContent = el.value;
        var computedStyle = window.getComputedStyle(el);
        Array.from(computedStyle).forEach(function (key) {
          return dummyDiv.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key));
        });
        dummyDiv.style.position = "absolute";
        dummyDiv.style.visibility = "hidden";
        const textareaRect = el.getBoundingClientRect();
      
        const scrolledTop = textareaRect.top + window.scrollY;
        const scrolledLeft = textareaRect.left + window.scrollX;
        dummyDiv.style.top = `${scrolledTop}px`;
        dummyDiv.style.left = `${scrolledLeft}px`;
        dummyDiv.style.width = `${textareaRect.width}px`;
        dummyDiv.style.height = `${textareaRect.height}px`;
      
        document.body.appendChild(dummyDiv);
        const range = document.createRange();
        range.setStart(dummyDiv.firstChild!, el.selectionStart || 0);
        range.setEnd(dummyDiv.firstChild!, el.selectionEnd || 0);
      
        const rect = range.getBoundingClientRect();
        document.body.removeChild(dummyDiv);
      
        return rect;
      }

      const handleSelection = () => {
        if (pointerTypeRef.current !== 'mouse') return
        const selection = document.getSelection()
        if (!selection) return
        const node = ref.current
        const wasSelectionInsideTrigger = node?.contains(selection.anchorNode)
        if (!wasSelectionInsideTrigger) {
          hasOpenedRef.current = false
          return
        }
        const activeEl = document.activeElement as HTMLInputElement | HTMLTextAreaElement;
        let isCollapsed = true;
        let selectedText = "";
        if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {
          const start = activeEl.selectionStart ?? 0;
          const end = activeEl.selectionEnd ?? 0;
          isCollapsed = start === end;
          selectedText = activeEl.value.substring(start, end);
        } else {
          isCollapsed = selection.isCollapsed;
          selectedText = selection.toString();
        }

        if (isCollapsed) {
          hasOpenedRef.current = false
          return
        }

        const hasTextSelected = selectedText.trim() !== ''
        if (hasTextSelected) {
          if (!hasOpenedRef.current) onOpen(() => onOpenChange(true))
          hasOpenedRef.current = true
          if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {
            const rect = getDummyRect(activeEl)
            onVirtualRefChange({
                getBoundingClientRect: () => rect,
                getClientRects: () => ({
                    0: rect,
                    length: 1,
                    item: (index: number) => index === 0 ? rect : null,
                    [Symbol.iterator]: function* () {
                        yield rect;
                    }
                }),
            });
          } else {
            const range = selection?.getRangeAt(0)
            onVirtualRefChange({
              getBoundingClientRect: () => range.getBoundingClientRect(),
              getClientRects: () => range.getClientRects(),
            })
          }
        }
      }

The above code is for whileSelected. Here would be the updates for the default functionality.

          context.onOpen(() => {
            const selection = document.getSelection()
            if (!selection) return
            const trigger = ref.current
            const wasSelectionInsideTrigger = trigger?.contains(selection.anchorNode)
            if (!wasSelectionInsideTrigger) return

            const activeEl = document.activeElement as HTMLInputElement | HTMLTextAreaElement
            let isCollapsed = true
            let selectedText = ''
            if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {
              const start = activeEl.selectionStart ?? 0
              const end = activeEl.selectionEnd ?? 0
              isCollapsed = start === end
              selectedText = activeEl.value.substring(start, end)
            } else {
              isCollapsed = selection.isCollapsed
              selectedText = selection.toString()
            }

            if (isCollapsed) return
            if (selectedText.trim() === '') return
            context.onOpenChange(true)

            if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {
              const rect = getDummyRect(activeEl)
              context.onVirtualRefChange({
                getBoundingClientRect: () => rect,
                getClientRects: () => ({
                  0: rect,
                  length: 1,
                  item: (index: number) => (index === 0 ? rect : null),
                  [Symbol.iterator]: function* () {
                    yield rect
                  },
                }),
              })
            } else {
              const range = selection.getRangeAt(0)
              context.onVirtualRefChange({
                getBoundingClientRect: () => range.getBoundingClientRect(),
                getClientRects: () => range.getClientRects(),
              })
            }
          })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.