Giter Club home page Giter Club logo

selection-popover's Introduction

Easy-to-use, composable react selection popover

npm version npm downloads

Install

npm install selection-popover

Content

Anatomy

Import all parts and piece them together.

import * as Selection from 'selection-popover'

export default () => (
  <Selection.Root>
    <Selection.Trigger />
    <Selection.Portal>
      <Selection.Content>
        <Selection.Arrow />
      </Selection.Content>
    </Selection.Portal>
  </Selection.Root>
)

API Reference

Root

Contains all the parts of a selection.

Prop Type Default Description
defaultOpen boolean - The open state of the hover card when it is initially rendered. Use when you do not need to control its open state.
open boolean - The controlled open state of the popover. Must be used in conjunction with onOpenChange.
onOpenChange (open: boolean) => void - Event handler called when the open state of the popover changes.
whileSelect boolean false When true, the popover will open while the text is selected, otherwise only when the mouse up.
disabled boolean false When true, the popover won't open when text is selected.
openDelay number 0 The duration from when release the mouse until the content opens. In whileSelect is when you start the selection.
closeDelay number 0 The duration from when you click outside of the content until the content closes.

Trigger

The area that opens the popover. Wrap it around the target you want the popover to open when a text is selected.

Prop Type Default Description
asChild boolean false Change the component to the HTML tag or custom component of the only child. This will merge the original component props with the props of the supplied element/component and change the underlying DOM node.

Portal

When used, portals the content part into the body.

Prop Type Default Description
forceMount boolean - Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries. If used on this part, it will be inherited by Selection.Content.
container HTMLElement document.body Specify a container element to portal the content into.

Content

The component that pops out when a text is selected.

Prop Type Default Description
asChild boolean false Change the component to the HTML tag or custom component of the only child. This will merge the original component props with the props of the supplied element/component and change the underlying DOM node.
forceMount boolean - Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries. It inherits from Selection.Portal.
side "top" | "right" | "bottom" | "left" top The preferred side of the selection to render against when open. Will be reversed when collisions occur and avoidCollisions is enabled.
sideOffset number 0 The distance in pixels from the selection.
align "start" | "center" | "end" center The preferred alignment against the selection. May change when collisions occur.
alignOffset number 0 An offset in pixels from the "start" or "end" alignment options.
avoidCollisions boolean true When true, overrides the side and align preferences to prevent collisions with boundary edges.
collisionBoundary Element | null | Array<Element | null> [] The element used as the collision boundary. By default this is the viewport, though you can provide additional element(s) to be included in this check.
collisionPadding number | Partial<Record<Side, number>> 0 The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { top: 20, left: 20 }.
arrowPadding number 0 The padding between the arrow and the edges of the content. If your content has border-radius, this will prevent it from overflowing the corners.
sticky "partial" | "always" partial The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless.
hideWhenDetached boolean false Whether to hide the content when the text becomes fully occluded.
onEscapeKeyDown (event: KeyboardEvent) => void - Event handler called when the escape key is down. It can be prevented by calling event.preventDefault.
onPointerDownOutside (event: PointerDownOutsideEvent) => void - Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling event.preventDefault.
onFocusOutside (event: FocusOutsideEvent) => void - Event handler called when focus moves outside the bounds of the component. It can be prevented by calling event.preventDefault.
onInteractOutside (event: PointerDownOutsideEvent | FocusOutsideEvent) => void - Event handler called when an interaction (pointer or focus event) happens outside the bounds of the component. It can be prevented by calling event.preventDefault.
Data Attribute Values
[data-state] "open" | "closed"
[data-side] "left" | "right" | "bottom" | "top"
[data-align] "start" | "end" | "center"
CSS Variable Description
--selection-popover-content-transform-origin The transform-origin computed from the content and arrow positions/offsets.
--selection-popover-select-width The width of the select.
--selection-popover-select-height The height of the select.

Arrow

An optional arrow element to render alongside the popover. This can be used to help visually link the selected text with the Selection.Content. Must be rendered inside Selection.Content.

Prop Type Default Description
asChild boolean false Change the component to the HTML tag or custom component of the only child. This will merge the original component props with the props of the supplied element/component and change the underlying DOM node.
width number 10 The width of the arrow in pixels.
height number 5 The height of the arrow in pixels.

Examples

Origin-aware animations

// index.jsx
import * as Selection from 'selection-popover'
import './styles.css'

export default () => (
  <Selection.Root>
    <Selection.Trigger>...</Selection.Trigger>
    <Selection.Portal>
      <Selection.Content className="SelectionContent">...</Selection.Content>
    </Selection.Portal>
  </Selection.Root>
)
/* styles.css */
.SelectionContent {
  transform-origin: var(--selection-popover-content-transform-origin);
  animation: scaleIn 500ms cubic-bezier(0.16, 1, 0.3, 1);
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

Collision-aware animations

// index.jsx
import * as Selection from 'selection-popover'
import './styles.css'

export default () => (
  <Selection.Root>
    <Selection.Trigger>...</Selection.Trigger>
    <Selection.Portal>
      <Selection.Content className="SelectionContent">...</Selection.Content>
    </Selection.Portal>
  </Selection.Root>
)
/* styles.css */
.SelectionContent {
  animation-duration: 400ms;
  animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
.SelectionContent[data-state='open'][data-side='top'] {
  animation-name: slideDownAndFade;
}
.SelectionContent[data-state='open'][data-side='bottom'] {
  animation-name: slideUpAndFade;
}

@keyframes slideDownAndFade {
  from {
    opacity: 0;
    transform: translateY(-2px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUpAndFade {
  from {
    opacity: 0;
    transform: translateY(2px));
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

Unmount animations

// index.jsx
import * as Selection from 'selection-popover'
import './styles.css'

export default () => (
  <Selection.Root>
    <Selection.Trigger>...</Selection.Trigger>
    <Selection.Portal>
      <Selection.Content className="SelectionContent">...</Selection.Content>
    </Selection.Portal>
  </Selection.Root>
)
/* styles.css */
.SelectionContent {
  animation-duration: 400ms;
  animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
.SelectionContent[data-state='open'] {
  animation-name: slideDownAndFade;
}
.SelectionContent[data-state='closed'] {
  animation-name: slideUpAndFade;
}

@keyframes slideDownAndFade {
  from {
    opacity: 0;
    transform: translateY(-2px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUpAndFade {
  from {
    opacity: 1;
    transform: translateY(0));
  }
  to {
    opacity: 0;
    transform: translateY(-2px);
  }
}

Use with Radix Toolbar

import * as Selection from 'selection-popover'
import * as Toolbar from '@radix-ui/react-toolbar'

export default () => (
  <Selection.Root>
    <Selection.Trigger>...</Selection.Trigger>
    <Selection.Portal>
      <Selection.Content asChild>
        <Toolbar.Root>...</Toolbar.Root>
        <Selection.Arrow />
      </Selection.Content>
    </Selection.Portal>
  </Selection.Root>
)

Acknowledgements

selection-popover's People

Contributors

joaom00 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

selection-popover's Issues

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(),
              })
            }
          })

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

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.