feat: balance layout and kbd workspace navigation

This commit is contained in:
Alejandro Gómez
2025-12-18 13:47:40 +01:00
parent 1581e313f3
commit b57ff31907
7 changed files with 265 additions and 3 deletions

View File

@@ -6,6 +6,7 @@ import {
Sparkles,
SplitSquareHorizontal,
SplitSquareVertical,
Scale,
} from "lucide-react";
import { Button } from "./ui/button";
import { useGrimoire } from "@/core/state";
@@ -22,7 +23,8 @@ import { toast } from "sonner";
import type { LayoutConfig } from "@/types/app";
export function LayoutControls() {
const { state, applyPresetLayout, updateLayoutConfig } = useGrimoire();
const { state, applyPresetLayout, balanceLayout, updateLayoutConfig } =
useGrimoire();
const { workspaces, activeWorkspaceId, layoutConfig } = state;
const activeWorkspace = workspaces[activeWorkspaceId];
@@ -97,6 +99,26 @@ export function LayoutControls() {
updateLayoutConfig({ splitPercentage: newValue });
};
const handleBalance = () => {
try {
// Enable animations for smooth transition
document.body.classList.add("animating-layout");
balanceLayout();
// Remove animation class after transition completes
setTimeout(() => {
document.body.classList.remove("animating-layout");
}, 180);
} catch (error) {
document.body.classList.remove("animating-layout");
toast.error(`Failed to balance layout`, {
description:
error instanceof Error ? error.message : "Unknown error occurred",
});
}
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -214,6 +236,26 @@ export function LayoutControls() {
</Button>
</div>
</div>
<DropdownMenuSeparator />
{/* Actions Section */}
<div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
Actions
</div>
<DropdownMenuItem
onClick={handleBalance}
disabled={windowCount < 2}
className="flex items-center gap-2 cursor-pointer"
>
<Scale className="h-3.5 w-3.5" />
<span className="flex-1">Balance Splits</span>
{windowCount < 2 && (
<span className="text-xs text-muted-foreground">
Need 2+ windows
</span>
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);

View File

@@ -3,6 +3,7 @@ import { Button } from "./ui/button";
import { useGrimoire } from "@/core/state";
import { cn } from "@/lib/utils";
import { LayoutControls } from "./LayoutControls";
import { useEffect } from "react";
export function TabBar() {
const { state, setActiveWorkspace, createWorkspace } = useGrimoire();
@@ -12,11 +13,30 @@ export function TabBar() {
createWorkspace();
};
// Sort workspaces by number
// Sort workspaces by number (for both rendering and keyboard shortcuts)
const sortedWorkspaces = Object.values(workspaces).sort(
(a, b) => a.number - b.number,
);
// Keyboard shortcut: Cmd+1-9 to switch workspaces by position
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Check for Cmd/Ctrl + number key (1-9)
if ((e.metaKey || e.ctrlKey) && e.key >= "1" && e.key <= "9") {
const index = Number.parseInt(e.key, 10) - 1; // Convert key to array index
const targetWorkspace = sortedWorkspaces[index];
if (targetWorkspace) {
e.preventDefault(); // Prevent browser default (like Cmd+1 = first tab)
setActiveWorkspace(targetWorkspace.id);
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [sortedWorkspaces, setActiveWorkspace]);
return (
<>
<div className="h-8 border-t border-border bg-background flex items-center px-2 gap-1 overflow-x-auto">

View File

@@ -2,7 +2,11 @@ import { v4 as uuidv4 } from "uuid";
import type { MosaicNode } from "react-mosaic-component";
import { GrimoireState, WindowInstance, UserRelays } from "@/types/app";
import { insertWindow } from "@/lib/layout-utils";
import { applyPresetToLayout, type LayoutPreset } from "@/lib/layout-presets";
import {
applyPresetToLayout,
balanceLayout,
type LayoutPreset,
} from "@/lib/layout-presets";
/**
* Finds the lowest available workspace number.
@@ -394,3 +398,28 @@ export const applyPresetLayout = (
return state;
}
};
/**
* Balances all split percentages in the active workspace to 50/50.
* Useful for equalizing splits after manual resizing.
*/
export const balanceLayoutInWorkspace = (
state: GrimoireState,
): GrimoireState => {
const activeId = state.activeWorkspaceId;
const ws = state.workspaces[activeId];
// Balance the layout tree
const balancedLayout = balanceLayout(ws.layout);
return {
...state,
workspaces: {
...state.workspaces,
[activeId]: {
...ws,
layout: balancedLayout,
},
},
};
};

View File

@@ -241,6 +241,11 @@ export const useGrimoire = () => {
[setState],
);
const balanceLayout = useCallback(
() => setState((prev) => Logic.balanceLayoutInWorkspace(prev)),
[setState],
);
return {
state,
locale: state.locale || browserLocale,
@@ -256,5 +261,6 @@ export const useGrimoire = () => {
setActiveAccountRelays,
updateLayoutConfig,
applyPresetLayout,
balanceLayout,
};
};

View File

@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
import {
collectWindowIds,
applyPresetToLayout,
balanceLayout,
BUILT_IN_PRESETS,
} from "./layout-presets";
import type { MosaicNode } from "react-mosaic-component";
@@ -193,6 +194,84 @@ describe("layout-presets", () => {
});
});
describe("balanceLayout", () => {
it("returns null for null layout", () => {
expect(balanceLayout(null)).toBeNull();
});
it("returns single window unchanged", () => {
expect(balanceLayout("w1")).toBe("w1");
});
it("balances a simple binary split", () => {
const unbalanced: MosaicNode<string> = {
direction: "row",
first: "w1",
second: "w2",
splitPercentage: 70,
};
const balanced = balanceLayout(unbalanced);
expect(balanced).toEqual({
direction: "row",
first: "w1",
second: "w2",
splitPercentage: 50,
});
});
it("balances nested splits recursively", () => {
const unbalanced: MosaicNode<string> = {
direction: "row",
first: {
direction: "column",
first: "w1",
second: "w2",
splitPercentage: 30,
},
second: {
direction: "column",
first: "w3",
second: "w4",
splitPercentage: 80,
},
splitPercentage: 60,
};
const balanced = balanceLayout(unbalanced);
// All splits should be 50%
expect(balanced).toMatchObject({
splitPercentage: 50,
first: { splitPercentage: 50 },
second: { splitPercentage: 50 },
});
});
it("preserves window IDs and directions", () => {
const original: MosaicNode<string> = {
direction: "column",
first: "w1",
second: {
direction: "row",
first: "w2",
second: "w3",
splitPercentage: 75,
},
splitPercentage: 25,
};
const balanced = balanceLayout(original);
const windowIds = collectWindowIds(balanced);
expect(windowIds).toEqual(["w1", "w2", "w3"]);
// Check directions preserved
if (balanced && typeof balanced !== "string") {
expect(balanced.direction).toBe("column");
if (typeof balanced.second !== "string") {
expect(balanced.second.direction).toBe("row");
}
}
});
});
describe("applyPresetToLayout", () => {
it("throws error if too few windows", () => {
const layout: MosaicNode<string> = "w1";

View File

@@ -203,6 +203,31 @@ export function applyPresetToLayout(
return preset.generate(windowIds);
}
/**
* Balances all split percentages in a layout tree to 50/50
* Useful for equalizing splits after manual resizing
*/
export function balanceLayout(
layout: MosaicNode<string> | null
): MosaicNode<string> | null {
if (layout === null) {
return null;
}
// Leaf node (window ID), return as-is
if (typeof layout === "string") {
return layout;
}
// Branch node, balance this split and recurse
return {
direction: layout.direction,
first: balanceLayout(layout.first),
second: balanceLayout(layout.second),
splitPercentage: 50,
};
}
/**
* Get a preset by ID
*/