From 05ca8951a6955d580c807e08dd22c491eef09ee8 Mon Sep 17 00:00:00 2001 From: psychedelicious <4822129+psychedelicious@users.noreply.github.com> Date: Mon, 8 Jul 2024 11:32:52 +1000 Subject: [PATCH] feat(ui): add snapToRect util --- .../src/features/controlLayers/konva/util.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/util.ts b/invokeai/frontend/web/src/features/controlLayers/konva/util.ts index 236a5e864a..e4d52922f1 100644 --- a/invokeai/frontend/web/src/features/controlLayers/konva/util.ts +++ b/invokeai/frontend/web/src/features/controlLayers/konva/util.ts @@ -78,6 +78,28 @@ export const snapPosToStage = (pos: Vector2d, stage: Konva.Stage, snapPx = 10): return snappedPos; }; +/** + * Snaps a position to the edge of the given rect if within a threshold of the edge + * @param pos The position to snap + * @param rect The rect to snap to + * @param threshold The snap threshold in pixels + */ +export const snapToRect = (pos: Vector2d, rect: Rect, threshold = 10): Vector2d => { + const snappedPos = { ...pos }; + // Snap to the edge of the rect if within threshold + if (pos.x - threshold < rect.x) { + snappedPos.x = rect.x; + } else if (pos.x + threshold > rect.x + rect.width) { + snappedPos.x = rect.x + rect.width; + } + if (pos.y - threshold < rect.y) { + snappedPos.y = rect.y; + } else if (pos.y + threshold > rect.y + rect.height) { + snappedPos.y = rect.y + rect.height; + } + return snappedPos; +}; + /** * Checks if the left mouse button is currently pressed * @param e The konva event