simonwep / selection

✨ Viselect - A high performance and lightweight library to add a visual way of selecting elements, just like on your Desktop. Zero dependencies, super small. Support for major frameworks!
https://simonwep.github.io/selection
MIT License
2.51k stars 147 forks source link

Can I get access to the store so I can clear selection when pressing Escape #208

Closed tonyduanesmith closed 1 year ago

tonyduanesmith commented 1 year ago

Is your feature request related to a problem? Please describe. Can I get access to the store so I can clear selection when pressing Escape, I cannot see how I can get access

Describe the solution you'd like Getting access to the store

Describe alternatives you've considered Not using escape key to deselect everything

Additional context There may be a way to do this already but if there is could you point me in the right direction

Nielson commented 1 year ago

Hi @tonyduanesmith !

This should be possible with adding an event listener and then using the built in clearSelection() method, like this:

const selection = new SelectionArea({});

document.body.addEventListener("keydown", (event) => {
  if (event.key === "Escape") {
    console.log("Escape key pressed");

    selection.clearSelection();
  }
});
tonyduanesmith commented 1 year ago

Sorry I didn't provide enough context, I am using the react component , but I did spot the useSelection hook on the type definition file which gives me the same methods

Thanks for the help

for anyone else in the future wants to also add Escape to clear and is also using React

import { useEffect } from 'react';
import { useSelection } from '@viselect/react';

  const selection = useSelection();

  useEffect(() => {
    function handleKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        selection?.clearSelection();
      }
    }

    window.addEventListener('keydown', handleKeyDown);

    return () => window.removeEventListener('keydown', handleKeyDown);
  });
abeijnoff commented 10 months ago

I'm trying to use the useSelection hook above to clear the selection when a button outside the SelectionArea is clicked but the selection returned from the hook is always undefined. Any idea why?

tonyduanesmith commented 10 months ago

@abeijnoff useSelection needs to be a child of SelectionArea as useSelection uses context and SelectionArea provides that context

abeijnoff commented 10 months ago

Super, it worked when a put the button in a child component, thanks!