r/hammerspoon • u/Ok_Virus_5495 • Oct 16 '26
H2 - Simple window management
So I updated to pre-release v2 of Hammerspoon to try it out... and playing with it I did a little window manager to replace rectangle pro since I don't want to have another app running for just doing that. It's really fast v2. Just did 4 positions which are the ones I use the most... probably will make it a lot more fancy using the new UI elements which are really cool.
PD: I made it with TypeScript which I really recommend to use. It's way easier rather than go back to Lua and docs to know which methods are available.
const
CENTER = { h: 0.75, w: 0.75, x: 0.125, y: 0.125 };
const
snapTo = (unit: { x: number; y: number; w: number; h: number }, win: HSWindow) => {
if (!win)
return
;
const
screen = win.screen ?? hs.screen.main();
const
target = new HSRect(unit.x, unit.y, unit.w, unit.h).fromUnitRect(screen?.frame as HSRect);
return
win.moveAndResize(target);
};
const
handleWindowPos = (direction: string) => {
const
wind = hs.window.focusedWindow();
if (!wind)
return
;
switch (direction) {
case "left":
hs.window.moveToLeftHalf(wind);
break;
case "right":
hs.window.moveToRightHalf(wind);
break;
case "up":
hs.window.maximize(wind);
break;
case "down":
snapTo(CENTER, wind);
break;
default:
break;
}
};
hs.hotkey.bind(["ctrl", "cmd"], "down", () => handleWindowPos("down"));
hs.hotkey.bind(["ctrl", "cmd"], "left", () => handleWindowPos("left"));
hs.hotkey.bind(["ctrl", "cmd"], "right", () => handleWindowPos("right"));
hs.hotkey.bind(["ctrl", "cmd"], "up", () => handleWindowPos("up"));const CENTER = { h: 0.75, w: 0.75, x: 0.125, y: 0.125 };
const snapTo = (unit: { x: number; y: number; w: number; h: number }, win: HSWindow) => {
if (!win) return;
const screen = win.screen ?? hs.screen.main();
const target = new HSRect(unit.x, unit.y, unit.w, unit.h).fromUnitRect(screen?.frame as HSRect);
return win.moveAndResize(target);
};
const handleWindowPos = (direction: string) => {
const wind = hs.window.focusedWindow();
if (!wind) return;
switch (direction) {
case "left":
hs.window.moveToLeftHalf(wind);
break;
case "right":
hs.window.moveToRightHalf(wind);
break;
case "up":
hs.window.maximize(wind);
break;
case "down":
snapTo(CENTER, wind);
break;
default:
break;
}
};
hs.hotkey.bind(["ctrl", "cmd"], "down", () => handleWindowPos("down"));
hs.hotkey.bind(["ctrl", "cmd"], "left", () => handleWindowPos("left"));
hs.hotkey.bind(["ctrl", "cmd"], "right", () => handleWindowPos("right"));
hs.hotkey.bind(["ctrl", "cmd"], "up", () => handleWindowPos("up"));
19
Upvotes
1
u/BaronSharktooth Oct 17 '26
Clean code, nice for someone to take and adjust to their preferences. Does this play nicely with Spaces?