-
Notifications
You must be signed in to change notification settings - Fork 0
/
state-utils.ts
106 lines (84 loc) · 2.56 KB
/
state-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import {} from "@jxa/global-type";
enum Direction {
LEFT,
RIGHT
}
function writeTextToFile(
text: string,
filePath: string,
overwriteExistingContent: boolean
): boolean {
const app = Application.currentApplication();
app.includeStandardAdditions = true;
const path = Path(filePath.toString());
try {
const openedFile = app.openForAccess(path, {
writePermission: true
});
if (overwriteExistingContent) {
app.setEof(openedFile, { to: 0 });
}
app.write(text, { to: openedFile, startingAt: app.getEof(openedFile) });
app.closeAccess(openedFile);
return true;
} catch (error) {
try {
app.closeAccess(path);
} catch (error) {
console.log(`Couldn't close file: ${error}`);
}
return false;
}
}
function readFile(filePath: string): string {
const app = Application.currentApplication();
app.includeStandardAdditions = true;
const path = Path(filePath.toString());
return app.read(path);
}
class CacheObject {
cacheFilePath: string;
stateObject: Object;
currentState: string;
constructor(cacheFilePath: string) {
this.cacheFilePath = cacheFilePath;
this.stateObject = JSON.parse(readFile(cacheFilePath));
this.currentState = undefined;
return this;
}
getState(stateName: string) {
this.currentState = this.stateObject[stateName];
this.stateObject[stateName] = this.currentState;
return this.currentState;
}
write(stateName: string, stateValue: any) {
this.stateObject[stateName] = stateValue;
return this;
}
save() {
writeTextToFile(JSON.stringify(this.stateObject), this.cacheFilePath, true);
return this;
}
}
const advanceState = function (
cacheObject: CacheObject,
toggleKey: string,
states: Array<Object>,
direction: Direction = Direction.LEFT
) {
const btt = Application("BetterTouchTool");
const currentState = parseInt(cacheObject.getState(toggleKey) ?? "0");
const newState =
(() => {
switch (direction) {
case Direction.LEFT:
return currentState + states.length - 1;
case Direction.RIGHT:
return currentState + 1;
}
})() % states.length;
btt.trigger_action(JSON.stringify(states[newState]));
cacheObject.write(toggleKey, newState.toString()).save();
return cacheObject;
};
export { CacheObject, advanceState, Direction };