Lemoncode / quickmock

7 stars 7 forks source link

Canvas clear selection #17

Closed brauliodiez closed 5 days ago

brauliodiez commented 6 days ago

Right now in the canvas we have implemented a single selection mechanism.

If you click on a given shape it will just surround the sape with a trasnformer, if you click on another shape, selection will swap to that given shape, but we need a mechanism to clear the selection whenever you click on the canvas

Some like:

Sample code (psuedocode)

./src/canvas.pods.tsx

const handleClearSelection = () => {
+ transformerRef?.current?.nodes([]);
}

And on the handlers:

      <div style={{ border: "1px solid black" }}>
        {/*TODO: right now harcoded values, remove this once we have final layout*/}
        <Stage width={1024} height={800}
+         onMouseDown={handleClearSelection}
+         onTouchStart={handleClearSelection}
>
          <Layer>

Once you have implemented this, just apply a refactor, enclose the handleClearSelection in the useSelection hook

export const useSelection = (shapes: ShapeModel[]) => {
  const transformerRef = useRef<Konva.Transformer>(null);
  const shapeRefs = useRef<ShapeRefs>({});

  // Remove unused shapes
  useEffect(() => {
    const currentIds = shapes.map((shape) => shape.id);
    Object.keys(shapeRefs.current).forEach((id) => {
      if (!currentIds.includes(id)) {
        delete shapeRefs.current[id];
      }
    });
  }, [shapes]);

  const handleSelected = (id: string) => {
    transformerRef?.current?.nodes([shapeRefs.current[id].current]);
  };

+ const handleClearSelection = () => {
+ transformerRef?.current?.nodes([]);
+ }

  return { transformerRef, shapeRefs, handleSelected };
};

More background about the issue:

https://codesandbox.io/s/github/konvajs/site/tree/master/react-demos/transformer?from-embed=&file=/src/index.js:2323-2522