Skip to content

Commit 6ed06ce

Browse files
feat: add drag direction enum and helpers
1 parent bac96c1 commit 6ed06ce

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

src/drag_direction.ts

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* @license
3+
* Copyright 2025 Google LLC
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
export enum Direction {
8+
Up = 1,
9+
Down,
10+
Left,
11+
Right,
12+
}
13+
14+
/**
15+
* Convert a direction enum into an XY pair.
16+
*
17+
* @param dir The direction, or undefined.
18+
* @returns An object containing x and y values corresponding to the input
19+
* direction.
20+
*/
21+
export function getXYFromDirection(dir: Direction | undefined): {
22+
x: number;
23+
y: number;
24+
} {
25+
if (!dir) {
26+
return {x: 0, y: 0};
27+
}
28+
switch (dir) {
29+
case Direction.Up:
30+
return {x: 0, y: -1};
31+
case Direction.Down:
32+
return {x: 0, y: 1};
33+
case Direction.Left:
34+
return {x: -1, y: 0};
35+
case Direction.Right:
36+
return {x: 1, y: 0};
37+
}
38+
}
39+
40+
/**
41+
* Convert an XY pair into a direction enum.
42+
*
43+
* @param xy The input pair.
44+
* @param xy.x The x direction, or undefined.
45+
* @param xy.y The y direction, or undefined.
46+
* @returns A direction corresponding to the XY pair, or null if they are invalid
47+
* or undefined.
48+
*/
49+
export function getDirectionFromXY(xy: {
50+
x: number | undefined;
51+
y: number | undefined;
52+
}): Direction | null {
53+
const {x, y} = xy;
54+
if (x == 0) {
55+
if (y == -1) {
56+
return Direction.Up;
57+
} else if (y == 1) {
58+
return Direction.Down;
59+
}
60+
} else if (y == 0) {
61+
if (x == -1) {
62+
return Direction.Left;
63+
} else if (x == 1) {
64+
return Direction.Right;
65+
}
66+
}
67+
return null;
68+
}

0 commit comments

Comments
 (0)