selection.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { ExcalidrawElement } from "../element/types";
  2. import { getElementAbsoluteCoords } from "../element";
  3. export function setSelection(
  4. elements: readonly ExcalidrawElement[],
  5. selection: ExcalidrawElement
  6. ) {
  7. const [
  8. selectionX1,
  9. selectionY1,
  10. selectionX2,
  11. selectionY2
  12. ] = getElementAbsoluteCoords(selection);
  13. elements.forEach(element => {
  14. const [
  15. elementX1,
  16. elementY1,
  17. elementX2,
  18. elementY2
  19. ] = getElementAbsoluteCoords(element);
  20. element.isSelected =
  21. element.type !== "selection" &&
  22. selectionX1 <= elementX1 &&
  23. selectionY1 <= elementY1 &&
  24. selectionX2 >= elementX2 &&
  25. selectionY2 >= elementY2;
  26. });
  27. return elements;
  28. }
  29. export function clearSelection(elements: readonly ExcalidrawElement[]) {
  30. const newElements = [...elements];
  31. newElements.forEach(element => {
  32. element.isSelected = false;
  33. });
  34. return newElements;
  35. }
  36. export function deleteSelectedElements(elements: readonly ExcalidrawElement[]) {
  37. return elements.filter(el => !el.isSelected);
  38. }
  39. export function getSelectedIndices(elements: readonly ExcalidrawElement[]) {
  40. const selectedIndices: number[] = [];
  41. elements.forEach((element, index) => {
  42. if (element.isSelected) {
  43. selectedIndices.push(index);
  44. }
  45. });
  46. return selectedIndices;
  47. }
  48. export const someElementIsSelected = (elements: readonly ExcalidrawElement[]) =>
  49. elements.some(element => element.isSelected);
  50. export function getSelectedAttribute<T>(
  51. elements: readonly ExcalidrawElement[],
  52. getAttribute: (element: ExcalidrawElement) => T
  53. ): T | null {
  54. const attributes = Array.from(
  55. new Set(
  56. elements
  57. .filter(element => element.isSelected)
  58. .map(element => getAttribute(element))
  59. )
  60. );
  61. return attributes.length === 1 ? attributes[0] : null;
  62. }