comparisons.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { ExcalidrawElement } from "../element/types";
  2. import { hitTest } from "../element/collision";
  3. import { getElementAbsoluteCoords } from "../element";
  4. export const hasBackground = (elements: readonly ExcalidrawElement[]) =>
  5. elements.some(
  6. element =>
  7. element.isSelected &&
  8. (element.type === "rectangle" ||
  9. element.type === "ellipse" ||
  10. element.type === "diamond")
  11. );
  12. export const hasStroke = (elements: readonly ExcalidrawElement[]) =>
  13. elements.some(
  14. element =>
  15. element.isSelected &&
  16. (element.type === "rectangle" ||
  17. element.type === "ellipse" ||
  18. element.type === "diamond" ||
  19. element.type === "arrow" ||
  20. element.type === "line")
  21. );
  22. export const hasText = (elements: readonly ExcalidrawElement[]) =>
  23. elements.some(element => element.isSelected && element.type === "text");
  24. export function getElementAtPosition(
  25. elements: readonly ExcalidrawElement[],
  26. x: number,
  27. y: number
  28. ) {
  29. let hitElement = null;
  30. // We need to to hit testing from front (end of the array) to back (beginning of the array)
  31. for (let i = elements.length - 1; i >= 0; --i) {
  32. if (hitTest(elements[i], x, y)) {
  33. hitElement = elements[i];
  34. break;
  35. }
  36. }
  37. return hitElement;
  38. }
  39. export function getElementContainingPosition(
  40. elements: readonly ExcalidrawElement[],
  41. x: number,
  42. y: number
  43. ) {
  44. let hitElement = null;
  45. // We need to to hit testing from front (end of the array) to back (beginning of the array)
  46. for (let i = elements.length - 1; i >= 0; --i) {
  47. const [x1, y1, x2, y2] = getElementAbsoluteCoords(elements[i]);
  48. if (x1 < x && x < x2 && y1 < y && y < y2) {
  49. hitElement = elements[i];
  50. break;
  51. }
  52. }
  53. return hitElement;
  54. }