Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8764 feat(rail): reorder the rail spaces by drag (#10121)

Jiayuan Zhang48c521c65f24
diff --git a/e2e/rail-order.spec.ts b/e2e/rail-order.spec.ts
new file mode 100644
index 0000000000..0d30886361
--- /dev/null
+++ b/e2e/rail-order.spec.ts
@@ -0,0 +1,54 @@
+import { test, expect, type Page } from "@playwright/test";
+import { loginAsDefault, reloadAppPage } from "./helpers";
+
+const railOrder = (page: Page) =>
+ page
+ .locator("[data-slot='app-rail'] [data-rail-item]")
+ .evaluateAll((items) => items.map((item) => (item as HTMLElement).dataset.railItem));
+
+async function dragOnto(page: Page, from: string, to: string) {
+ const rail = page.locator("[data-slot='app-rail']");
+ const source = await rail.locator(`[data-rail-item='${from}']`).boundingBox();
+ const target = await rail.locator(`[data-rail-item='${to}']`).boundingBox();
+ if (!source || !target) throw new Error("rail item is not on screen");
+ await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(source.x + source.width / 2, target.y + target.height / 2, { steps: 12 });
+ await page.mouse.move(source.x + source.width / 2, target.y + target.height / 2 + 2, { steps: 2 });
+ await page.mouse.up();
+}
+
+test("rail spaces reorder by drag and keep their order", async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ const slug = await loginAsDefault(page);
+ await page.evaluate(() => localStorage.removeItem("multica_rail_order"));
+ await reloadAppPage(page);
+
+ expect(await railOrder(page)).toEqual(["inbox", "work", "team", "chat", "autopilots"]);
+
+ // A drag that starts but moves nothing must not open Chat on release.
+ const chat = await page.locator("[data-slot='app-rail'] [data-rail-item='chat']").boundingBox();
+ if (!chat) throw new Error("rail item is not on screen");
+ await page.mouse.move(chat.x + chat.width / 2, chat.y + chat.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(chat.x + chat.width / 2, chat.y + chat.height / 2 + 10, { steps: 5 });
+ await page.mouse.up();
+ await page.waitForTimeout(300);
+ expect(await railOrder(page)).toEqual(["inbox", "work", "team", "chat", "autopilots"]);
+ await expect(page).toHaveURL(new RegExp(`/${slug}/issues`));
+
+ // Dropping Chat on Inbox must not also open Chat.
+ await dragOnto(page, "chat", "inbox");
+ expect(await railOrder(page)).toEqual(["chat", "inbox", "work", "team", "autopilots"]);
+ await expect(page).toHaveURL(new RegExp(`/${slug}/issues`));
+
+ await dragOnto(page, "inbox", "autopilots");
+ expect(await railOrder(page)).toEqual(["chat", "work", "team", "autopilots", "inbox"]);
+
+ await reloadAppPage(page);
+ expect(await railOrder(page)).toEqual(["chat", "work", "team", "autopilots", "inbox"]);
+
+ // A plain click after a drag still works.
+ await page.locator("[data-rail-item='chat'] a").click();
+ await expect(page).toHaveURL(new RegExp(`/${slug}/chat`));
+});
diff --git a/packages/core/navigation/index.ts b/packages/core/navigation/index.ts
index 166a42f866..66dfc55871 100644
--- a/packages/core/navigation/index.ts
+++ b/packages/core/navigation/index.ts
@@ -1 +1,2 @@
export { useNavigationStore } from "./store";
+export { resolveRailOrder, useRailOrderStore } from "./rail-order-store";
diff --git a/packages/core/navigation/rail-order-store.test.ts b/packages/core/navigation/rail-order-store.test.ts
new file mode 100644
index 0000000000..2e60a8fda9
--- /dev/null
+++ b/packages/core/navigation/rail-order-store.test.ts
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { RAIL_SPACES } from "../paths/spaces";
+import { resolveRailOrder, useRailOrderStore } from "./rail-order-store";
+
+describe("resolveRailOrder", () => {
+ it("uses the default order until the user reorders", () => {
+ expect(resolveRailOrder(null)).toEqual(RAIL_SPACES);
+ });
+
+ it("keeps a saved order", () => {
+ const saved = ["chat", "inbox", "work", "team", "autopilots"];
+ expect(resolveRailOrder(saved)).toEqual(saved);
+ });
+
+ it("drops unknown and repeated ids", () => {
+ expect(resolveRailOrder(["chat", "settings", 3, "chat", "inbox", "work", "team", "autopilots"])).toEqual([
+ "chat",
+ "inbox",
+ "work",
+ "team",
+ "autopilots",
+ ]);
+ });
+
+ it("puts a space missing from the saved order after its default neighbour", () => {
+ expect(resolveRailOrder(["chat", "inbox", "autopilots", "work"])).toEqual([
+ "chat",
+ "inbox",
+ "autopilots",
+ "work",
+ "team",
+ ]);
+ expect(resolveRailOrder(["chat", "work", "team", "autopilots"])).toEqual([
+ "inbox",
+ "chat",
+ "work",
+ "team",
+ "autopilots",
+ ]);
+ });
+});
+
+describe("useRailOrderStore", () => {
+ beforeEach(() => {
+ useRailOrderStore.setState({ order: null });
+ });
+
+ it("saves a custom order", () => {
+ const order = ["chat", "inbox", "work", "team", "autopilots"] as const;
+ useRailOrderStore.getState().setOrder(order);
+ expect(useRailOrderStore.getState().order).toEqual(order);
+ });
+
+ it("forgets the order once it is back to the default", () => {
+ useRailOrderStore.getState().setOrder(["work", "inbox", "team", "chat", "autopilots"]);
+ useRailOrderStore.getState().setOrder(RAIL_SPACES);
+ expect(useRailOrderStore.getState().order).toBeNull();
+ });
+});
diff --git a/packages/core/navigation/rail-order-store.ts b/packages/core/navigation/rail-order-store.ts
new file mode 100644
index 0000000000..f7b29f8b4d
--- /dev/null
+++ b/packages/core/navigation/rail-order-store.ts
@@ -0,0 +1,55 @@
+"use client";
+
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { RAIL_SPACES, type RailSpaceId } from "../paths/spaces";
+import { defaultStorage } from "../platform/storage";
+
+const RAIL_SPACE_IDS = new Set<string>(RAIL_SPACES);
+
+/**
+ * The rail's spaces in the user's order. Unknown and repeated ids are
+ * dropped; a space missing from the saved order (one added since it was
+ * saved) is placed right after the space it follows by default.
+ */
+export function resolveRailOrder(saved: readonly unknown[] | null): RailSpaceId[] {
+ if (!saved) return [...RAIL_SPACES];
+ const order = [...new Set(saved)].filter(
+ (id): id is RailSpaceId => typeof id === "string" && RAIL_SPACE_IDS.has(id),
+ );
+ RAIL_SPACES.forEach((id, i) => {
+ if (order.includes(id)) return;
+ const previous = i === 0 ? -1 : order.indexOf(RAIL_SPACES[i - 1]!);
+ order.splice(previous + 1, 0, id);
+ });
+ return order;
+}
+
+interface RailOrderState {
+ /** `null` until the user reorders, so the default order can still evolve. */
+ order: RailSpaceId[] | null;
+ setOrder: (order: readonly RailSpaceId[]) => void;
+}
+
+/** This device's rail order, shared by every workspace. */
+export const useRailOrderStore = create<RailOrderState>()(
+ persist(
+ (set) => ({
+ order: null,
+ setOrder: (next) => {
+ const order = resolveRailOrder(next);
+ const isDefault = order.every((id, i) => id === RAIL_SPACES[i]);
+ set({ order: isDefault ? null : order });
+ },
+ }),
+ {
+ name: "multica_rail_order",
+ storage: createJSONStorage(() => defaultStorage),
+ partialize: (state) => ({ order: state.order }),
+ merge: (persisted, current) => {
+ const saved = (persisted as { order?: unknown } | undefined)?.order;
+ return { ...current, order: Array.isArray(saved) ? resolveRailOrder(saved) : null };
+ },
+ },
+ ),
+);
diff --git a/packages/views/layout/app-rail.test.tsx b/packages/views/layout/app-rail.test.tsx
index d9b44f2927..d3f0d33d24 100644
--- a/packages/views/layout/app-rail.test.tsx
+++ b/packages/views/layout/app-rail.test.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { act, fireEvent, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useRailOrderStore } from "@multica/core/navigation";
import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
import { renderWithI18n } from "../test/i18n";
import { AppRail } from "./app-rail";
@@ -104,8 +105,12 @@ beforeEach(() => {
state.chatSessions = [];
state.chat = { activeSessionId: null, isOpen: false };
state.stuck = [];
+ useRailOrderStore.setState({ order: null });
});
+const railOrder = () =>
+ Array.from(document.querySelectorAll<HTMLElement>("[data-rail-item]"), (item) => item.dataset.railItem);
+
describe("AppRail global actions", () => {
it("carries New issue and search by default", () => {
renderRail();
@@ -120,6 +125,36 @@ describe("AppRail global actions", () => {
});
});
+describe("AppRail order", () => {
+ it("lists the spaces in the default order", () => {
+ renderRail();
+ expect(railOrder()).toEqual(["inbox", "work", "team", "chat", "autopilots"]);
+ });
+
+ it("follows the saved order", () => {
+ const order = ["chat", "inbox", "work", "team", "autopilots"] as const;
+ useRailOrderStore.getState().setOrder(order);
+ renderRail();
+ expect(railOrder()).toEqual(order);
+ });
+
+ // dnd-kit stops the release's click at the document without cancelling
+ // it, so the link would navigate natively even though React never sees it.
+ it("does not open the space released at the end of a drag", async () => {
+ renderRail();
+ const chat = link("/acme/chat")!;
+ const pointer = { isPrimary: true, button: 0, clientX: 30, clientY: 300 };
+ fireEvent.pointerDown(chat, pointer);
+ fireEvent.pointerMove(document, { ...pointer, clientY: 310 });
+ fireEvent.pointerUp(document, { ...pointer, clientY: 310 });
+
+ expect(fireEvent.click(chat)).toBe(false);
+
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ expect(fireEvent.click(chat)).toBe(true);
+ });
+});
+
describe("AppRail spaces", () => {
it("links each space and marks the current route's space", () => {
state.pathname = "/acme/projects/p-1";
diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsx
index cb361c9703..c81f87a2f4 100644
--- a/packages/views/layout/app-rail.tsx
+++ b/packages/views/layout/app-rail.tsx
@@ -1,14 +1,25 @@
"use client";
-import { useMemo } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
+import {
+ DndContext,
+ PointerSensor,
+ closestCenter,
+ useSensor,
+ useSensors,
+ type DragEndEvent,
+} from "@dnd-kit/core";
+import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
+import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
import { Settings, Users, type IconComponent } from "@multica/ui/icons";
import { useChatStore } from "@multica/core/chat";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { countUnreadChatMessages } from "@multica/core/chat/unread";
import { useInboxUnreadCount } from "@multica/core/inbox/queries";
+import { resolveRailOrder, useRailOrderStore } from "@multica/core/navigation";
import {
- RAIL_SPACES,
useCurrentWorkspace,
useWorkspacePaths,
type AppSpaceId,
@@ -137,30 +148,78 @@ function RailSpaceLink({
}) {
const peekHandlers = usePeekHandlers(space, true);
return (
- <li>
- <TooltipHint label={label === fullLabel ? null : fullLabel} side="right">
- <AppLink
- href={href}
- data-space={space}
- newTabTitle={fullLabel}
- aria-current={active ? "page" : undefined}
- {...peekHandlers}
- className="group relative flex h-[52px] w-[52px] flex-col items-center justify-center gap-1 rounded-xl text-muted-foreground transition-colors outline-none hover:bg-sidebar-accent/60 hover:text-sidebar-accent-foreground focus-visible:outline-2 focus-visible:outline-ring aria-[current=page]:bg-sidebar-accent aria-[current=page]:font-medium aria-[current=page]:text-sidebar-accent-foreground"
- >
- <Icon className="size-5" />
- <span className="max-w-full truncate px-1 text-micro leading-[14px]">{label}</span>
- {badge && <RailBadgeMark badge={badge} />}
- </AppLink>
- </TooltipHint>
+ <TooltipHint label={label === fullLabel ? null : fullLabel} side="right">
+ <AppLink
+ href={href}
+ data-space={space}
+ newTabTitle={fullLabel}
+ draggable={false}
+ aria-current={active ? "page" : undefined}
+ {...peekHandlers}
+ className="group relative flex h-[52px] w-[52px] flex-col items-center justify-center gap-1 rounded-xl text-muted-foreground transition-colors outline-none hover:bg-sidebar-accent/60 hover:text-sidebar-accent-foreground focus-visible:outline-2 focus-visible:outline-ring aria-[current=page]:bg-sidebar-accent aria-[current=page]:font-medium aria-[current=page]:text-sidebar-accent-foreground"
+ >
+ <Icon className="size-5" />
+ <span className="max-w-full truncate px-1 text-micro leading-[14px]">{label}</span>
+ {badge && <RailBadgeMark badge={badge} />}
+ </AppLink>
+ </TooltipHint>
+ );
+}
+
+function SortableRailItem({ id, children }: { id: RailSpaceId; children: React.ReactNode }) {
+ const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id });
+ return (
+ <li
+ ref={setNodeRef}
+ data-rail-item={id}
+ style={{ transform: CSS.Translate.toString(transform), transition }}
+ className={cn("relative rounded-xl", isDragging && "z-10 bg-app-shell shadow-[var(--menu-shadow)]")}
+ {...listeners}
+ >
+ {children}
</li>
);
}
+const DRAG_MODIFIERS = [restrictToVerticalAxis, restrictToFirstScrollableAncestor];
+// dnd-kit keeps swallowing clicks for this long after a drag ends.
+const DRAG_CLICK_GUARD_MS = 50;
+
+function preventDefault(event: Event) {
+ event.preventDefault();
+}
+
/**
- * The app rail: workspaces, New issue and search, the five spaces, then help,
- * settings and the account. It sits on the app shell, outside the content
- * card, and stays put while the panel beside it collapses. Desktop passes
- * `globalActions={false}`: its title bar carries New issue and search.
+ * The release that ends a drag must not also open the space. Once a drag
+ * activates, dnd-kit stops that click's propagation at the document but
+ * leaves its default, so the link would still navigate natively. A window
+ * capture listener runs first and cancels it.
+ */
+function useDragClickGuard() {
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const disarm = useCallback(() => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ window.removeEventListener("click", preventDefault, true);
+ }, []);
+ useEffect(() => disarm, [disarm]);
+ return {
+ arm: useCallback(() => {
+ disarm();
+ window.addEventListener("click", preventDefault, true);
+ }, [disarm]),
+ release: useCallback(() => {
+ timer.current = setTimeout(disarm, DRAG_CLICK_GUARD_MS);
+ }, [disarm]),
+ };
+}
+
+/**
+ * The app rail: workspaces, New issue and search, the five spaces in the
+ * user's order (drag to reorder), then help, settings and the account. It
+ * sits on the app shell, outside the content card, and stays put while the
+ * panel beside it collapses. Desktop passes `globalActions={false}`: its
+ * title bar carries New issue and search.
*/
export function AppRail({
topSlot,
@@ -177,6 +236,23 @@ export function AppRail({
const badges = useRailBadges();
const space = shell?.space ?? null;
const settingsPeek = usePeekHandlers("settings", space === "settings");
+ const savedOrder = useRailOrderStore((s) => s.order);
+ const setOrder = useRailOrderStore((s) => s.setOrder);
+ const order = useMemo(() => resolveRailOrder(savedOrder), [savedOrder]);
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
+ const { arm: armClickGuard, release: releaseClickGuard } = useDragClickGuard();
+
+ const onDragEnd = useCallback(
+ ({ active, over }: DragEndEvent) => {
+ releaseClickGuard();
+ if (!over || active.id === over.id) return;
+ const from = order.indexOf(active.id as RailSpaceId);
+ const to = order.indexOf(over.id as RailSpaceId);
+ if (from === -1 || to === -1) return;
+ setOrder(arrayMove(order, from, to));
+ },
+ [order, releaseClickGuard, setOrder],
+ );
const items: Record<RailSpaceId, { href: string; icon: IconComponent; label: string; fullLabel: string }> = {
inbox: {
@@ -230,18 +306,30 @@ export function AppRail({
) : (
<div className="h-2 shrink-0" />
)}
- <ul className="flex flex-col items-center gap-0.5">
- {RAIL_SPACES.map((id) => (
- <RailSpaceLink
- key={id}
- space={id}
- {...items[id]}
- href={shell?.spaceHref(id, items[id].href) ?? items[id].href}
- active={space === id}
- badge={badges[id]}
- />
- ))}
- </ul>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ modifiers={DRAG_MODIFIERS}
+ onDragStart={armClickGuard}
+ onDragEnd={onDragEnd}
+ onDragCancel={releaseClickGuard}
+ >
+ <SortableContext items={order} strategy={verticalListSortingStrategy}>
+ <ul className="flex flex-col items-center gap-0.5">
+ {order.map((id) => (
+ <SortableRailItem key={id} id={id}>
+ <RailSpaceLink
+ space={id}
+ {...items[id]}
+ href={shell?.spaceHref(id, items[id].href) ?? items[id].href}
+ active={space === id}
+ badge={badges[id]}
+ />
+ </SortableRailItem>
+ ))}
+ </ul>
+ </SortableContext>
+ </DndContext>
<div className="mt-auto flex flex-col items-center gap-1 pt-2">
<HelpLauncher />
<TooltipHint label={t(($) => $.nav.settings)} side="right">