From 481f5ad03b7cfc48114eb6a8b1a9da2418000122 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:27:49 -0500 Subject: [PATCH] feat(web): search, pin and reorder projects in the new-thread menus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The project menus that start a new thread ("What's next in …?" and the home screen's "New thread in…") were one long list sorted by activity, so with many projects users scrolled to find one (#1040). Both menus now share one ProjectPickerMenu: - A search line (from 9 projects, not on touch) matches names and every checkout folder. - A pin on each row (or Alt+P) keeps a project in a Pinned group on top. Pins are kept by folder in the UI state store, on this device. - Rows drag to reorder within their group: anywhere on the row with a mouse or pen, by a grip with a finger, Alt+Up/Down from the keyboard, with auto-scroll. The shown rows trade places in their own slots, so rows a search hid and a project's other checkouts keep theirs. - The first drag switches sidebarProjectSortOrder to manual; "Reset to automatic order" switches it back. useOrderedProjects puts pinned projects first, so the default project for New thread follows the pins too. The saved order also survives computers connecting in a different sequence: a project that arrives after the order exists goes back to its saved place, and saving keeps the places of projects not loaded yet. The app guide's threads topic describes the menu. --- apps/server/src/guide/topics.ts | 2 + .../src/components/NoActiveThreadState.tsx | 100 +++-- .../components/ProjectPickerMenu.browser.tsx | 151 +++++++ apps/web/src/components/ProjectPickerMenu.tsx | 369 ++++++++++++++++++ .../src/components/chat/DraftEmptyState.tsx | 211 +++++----- .../components/sidebar/ProjectScopeMenu.tsx | 18 +- apps/web/src/hooks/useHandleNewThread.ts | 31 +- apps/web/src/projectPickerOrder.test.ts | 10 + apps/web/src/projectPickerOrder.ts | 46 +++ apps/web/src/uiStateStore.test.ts | 14 + apps/web/src/uiStateStore.ts | 99 ++++- 11 files changed, 850 insertions(+), 201 deletions(-) create mode 100644 apps/web/src/components/ProjectPickerMenu.browser.tsx create mode 100644 apps/web/src/components/ProjectPickerMenu.tsx create mode 100644 apps/web/src/projectPickerOrder.test.ts create mode 100644 apps/web/src/projectPickerOrder.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index f8c71366e..606b35fcf 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -50,6 +50,8 @@ The sliders button beside the project picker at the top of the sidebar groups th A new thread starts either in the project folder as it is, or in a worktree of its own: a separate git checkout on a new branch, so its changes stay apart until you merge them. You pick per thread in the composer; the default is {place:threads.startIn}, and new worktrees branch from {place:threads.worktreesFrom}. A project's setup script runs once in each new worktree. +The project name in "What's next in …?" on the new-thread screen opens the list of projects to start in, and so does the arrow beside New thread on the home screen. A long list has a search box that matches project names and folders. The pin on a row keeps that project at the top. Dragging rows, or Alt+Up and Alt+Down, sets your own order, and Reset to automatic order at the bottom goes back to recent activity. Pins and this order are kept per device. + A repository can already have worktrees that Threadlines did not make (git worktree add, or another app). Right after such a repository is added as a project, the new-thread screen lists them under the message box with a checkbox each, and "Add N threads" makes a thread for every ticked one, named from its branch; nothing runs until you send a message there. After that the screen shows only a count beside the recent threads ("4 worktrees"); opening it lists them with Work here, which points the thread you are about to start at that worktree, Add as threads…, and Hide for this project. The Workspace picker under the message box lists the same worktrees under Existing worktree, and the command palette has Add existing worktrees as threads…, which also brings a hidden count back. A thread in one of these is a guest: no setup script runs, the branch is not renamed, deleting the thread never offers to delete the folder, and undoing a turn only undoes that thread's own edits. Worktrees a thread already works in are left out. The computer's server needs to be on a version that has this; with an older one none of it shows. The agent and model a new thread starts with is {place:threads.agent}. You can switch model or agent at any time from the model button in the composer, which also holds the agent's effort. Beside it sit Build or Plan (one click switches, as does Shift+Tab in the message box) and the access level; on a narrow window they show just their icons, and on phones both live in the model button's panel instead. diff --git a/apps/web/src/components/NoActiveThreadState.tsx b/apps/web/src/components/NoActiveThreadState.tsx index 2d69f71b3..0fa69e3cc 100644 --- a/apps/web/src/components/NoActiveThreadState.tsx +++ b/apps/web/src/components/NoActiveThreadState.tsx @@ -24,21 +24,14 @@ import { useStore, } from "../store"; import { OpenSourceSupportLinks } from "./OpenSourceSupportLinks"; -import { ProjectFavicon } from "./ProjectFavicon"; import { RecentThreadsList } from "./RecentThreadsList"; import { riseDelay, ThreadlinesFigure } from "./ThreadlinesFigure"; import { Button } from "./ui/button"; import { Empty, EmptyDescription, EmptyTitle } from "./ui/empty"; import { Group } from "./ui/group"; -import { - Menu, - MenuGroup, - MenuGroupLabel, - MenuItem, - MenuPopup, - MenuSeparator, - MenuTrigger, -} from "./ui/menu"; +import { MenuGroup, MenuItem, MenuTrigger } from "./ui/menu"; +import { ProjectPickerMenu } from "./ProjectPickerMenu"; +import { getProjectOrderKey } from "../logicalProject"; import { SidebarInset } from "./ui/sidebar"; import { PageTitlebar } from "./PageTitlebar"; @@ -146,53 +139,52 @@ export function NoActiveThreadState() { {orderedProjects.length > 1 || generalChatsRef ? ( - - - } - > - - - - {generalChatsRef ? ( - <> - - - - General chat - - - - - ) : null} - - New thread in… - {orderedProjects.map((project) => ( + + } + > + + + } + header={ + generalChatsRef ? ( + handleNewThreadInProject(project)} - title={project.cwd} + data-testid="no-thread-new-general-chat-item" + onClick={handleNewGeneralChat} > - - {project.name} + + General chat - ))} - - - + + ) : undefined + } + rows={orderedProjects.map((project) => ({ + key: getProjectOrderKey(project), + name: project.name, + cwd: project.cwd, + environmentId: project.environmentId, + orderKeys: [getProjectOrderKey(project)], + cwds: [project.cwd], + selected: false, + }))} + onPick={(row) => { + const project = orderedProjects.find( + (candidate) => getProjectOrderKey(candidate) === row.key, + ); + if (project) handleNewThreadInProject(project); + }} + /> ) : null} ) : ( diff --git a/apps/web/src/components/ProjectPickerMenu.browser.tsx b/apps/web/src/components/ProjectPickerMenu.browser.tsx new file mode 100644 index 000000000..25200ae46 --- /dev/null +++ b/apps/web/src/components/ProjectPickerMenu.browser.tsx @@ -0,0 +1,151 @@ +// The new-thread project menu: pins, search and drag order run through the +// real UI store and client settings, with the order applied the way +// `useHandleNewThread` applies it. +import "../index.css"; + +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { EnvironmentId } from "@threadlines/contracts"; +import { page, userEvent } from "vite-plus/test/browser"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { render } from "vitest-browser-react"; + +import { updateSettings, useSettings } from "../hooks/useSettings"; +import { resetTestPage } from "../lib/testPage.browser-harness"; +import { pinnedProjectsFirst } from "../projectPickerOrder"; +import { useUiStateStore } from "../uiStateStore"; +import { ProjectPickerMenu, PROJECT_SEARCH_MIN_PROJECTS } from "./ProjectPickerMenu"; +import { MenuTrigger } from "./ui/menu"; + +const ENVIRONMENT_ID = EnvironmentId.make("environment-local"); + +// Enough projects for the search line; two live in an "apis" folder. +const PROJECTS = [ + { name: "web", cwd: "/work/web" }, + { name: "gateway", cwd: "/work/apis/gateway" }, + { name: "billing", cwd: "/work/apis/billing" }, + { name: "docs", cwd: "/work/docs" }, + { name: "mobile", cwd: "/work/mobile" }, + { name: "infra", cwd: "/work/infra" }, + { name: "design", cwd: "/work/design" }, + { name: "cli", cwd: "/work/cli" }, + { name: "scratch", cwd: "/work/scratch" }, +].map((project) => ({ ...project, key: `${ENVIRONMENT_ID}:${project.cwd}` })); + +function Harness(props: { onPick: (key: string) => void }) { + const projectOrder = useUiStateStore((store) => store.projectOrder); + const pinnedProjectCwds = useUiStateStore((store) => store.pinnedProjectCwds); + const sortOrder = useSettings((settings) => settings.sidebarProjectSortOrder); + const ordered = + sortOrder === "manual" + ? PROJECTS.toSorted((a, b) => projectOrder.indexOf(a.key) - projectOrder.indexOf(b.key)) + : PROJECTS; + return ( + Projects} + rows={pinnedProjectsFirst(ordered, pinnedProjectCwds).map((project) => ({ + key: project.key, + name: project.name, + cwd: project.cwd, + environmentId: ENVIRONMENT_ID, + orderKeys: [project.key], + cwds: [project.cwd], + selected: false, + }))} + onPick={(row) => props.onPick(row.key)} + /> + ); +} + +function shownNames(): string[] { + return Array.from(document.querySelectorAll("[data-project-picker-row]")).map( + (row) => + PROJECTS.find((project) => project.key === row.getAttribute("data-project-picker-row"))!.name, + ); +} + +function renderHarness(onPick: (key: string) => void = vi.fn()) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + , + ); +} + +describe("ProjectPickerMenu", () => { + beforeEach(() => { + expect(PROJECTS.length).toBeGreaterThanOrEqual(PROJECT_SEARCH_MIN_PROJECTS); + useUiStateStore.setState({ + projectOrder: PROJECTS.map((project) => project.key), + pinnedProjectCwds: [], + }); + updateSettings({ sidebarProjectSortOrder: "updated_at" }); + }); + + afterEach(async () => { + await resetTestPage(); + }); + + it("pins a project into its own group on top, and a search matches folders", async () => { + const onPick = vi.fn(); + const mounted = await renderHarness(onPick); + try { + await page.getByTestId("picker-trigger").click(); + await userEvent.hover(page.getByRole("menuitem", { name: "docs" })); + await page.getByRole("button", { name: "Pin docs to the top" }).click(); + + await expect.element(page.getByText("Pinned", { exact: true })).toBeVisible(); + expect(shownNames()[0]).toBe("docs"); + expect(useUiStateStore.getState().pinnedProjectCwds).toEqual(["/work/docs"]); + + // Off the rows, as a hand on the keyboard is: a pointer the shrinking + // list leaves behind takes the highlight with it (Base UI's own rule). + await userEvent.hover(page.getByTestId("project-picker-search")); + // Neither name says "apis"; their folder does. + await page.getByTestId("project-picker-search").fill("apis"); + await expect.poll(shownNames).toEqual(["gateway", "billing"]); + // Enter picks the first match once the search has highlighted it. + await expect + .element(page.getByRole("menuitem", { name: "gateway" })) + .toHaveAttribute("data-highlighted"); + await userEvent.keyboard("{Enter}"); + await expect.poll(() => onPick.mock.calls).toEqual([[PROJECTS[1]!.key]]); + } finally { + await mounted.unmount(); + } + }); + + it("a drag puts the project where it was dropped in the user's own order, and reset brings back the automatic one", async () => { + const mounted = await renderHarness(); + try { + await page.getByTestId("picker-trigger").click(); + await userEvent.dragAndDrop( + page.getByRole("menuitem", { name: "mobile" }), + page.getByRole("menuitem", { name: "gateway" }), + ); + + // Into gateway's place; everything else stays where it was shown. + await expect + .poll(shownNames) + .toEqual([ + "web", + "mobile", + "gateway", + "billing", + "docs", + "infra", + "design", + "cli", + "scratch", + ]); + + await page.getByTestId("project-picker-reset-order").click(); + await expect.poll(shownNames).toEqual(PROJECTS.map((project) => project.name)); + await expect.element(page.getByTestId("project-picker-reset-order")).not.toBeInTheDocument(); + } finally { + await mounted.unmount(); + } + }); +}); diff --git a/apps/web/src/components/ProjectPickerMenu.tsx b/apps/web/src/components/ProjectPickerMenu.tsx new file mode 100644 index 000000000..d595e4b72 --- /dev/null +++ b/apps/web/src/components/ProjectPickerMenu.tsx @@ -0,0 +1,369 @@ +import { DEFAULT_SIDEBAR_PROJECT_SORT_ORDER } from "@threadlines/contracts/settings"; +import type { EnvironmentId } from "@threadlines/contracts"; +import { GripVerticalIcon, PinIcon, PinOffIcon, RotateCcwIcon } from "lucide-react"; +import { useRef, useState, type ReactNode } from "react"; + +import { useMediaQuery } from "../hooks/useMediaQuery"; +import { dragReorderVisual, usePointerDragReorder } from "../hooks/usePointerDragReorder"; +import { useSettings, useUpdateSettings } from "../hooks/useSettings"; +import { cn } from "../lib/utils"; +import { isProjectPinned, moveAmongPeers } from "../projectPickerOrder"; +import { useUiStateStore } from "../uiStateStore"; +import { ProjectFavicon } from "./ProjectFavicon"; +import { + MENU_PICK_ITEM_CLASS_NAME, + MENU_PICK_ITEM_SELECTED_CLASS_NAME, + Menu, + MenuFilterInput, + MenuFilterProvider, + MenuGroup, + MenuGroupLabel, + MenuItem, + MenuList, + MenuPopup, + MenuSeparator, +} from "./ui/menu"; + +/** + * Past this many projects a project menu gets a search line. Fewer fit on + * screen at once, where a search box would only be one more row to look past. + */ +export const PROJECT_SEARCH_MIN_PROJECTS = 9; + +/** One project in a ProjectPickerMenu. */ +export interface ProjectPickerRow { + readonly key: string; + readonly name: string; + /** The folder shown on hover, and matched by a search. */ + readonly cwd: string; + readonly environmentId: EnvironmentId; + /** The project's checkouts as keys of the saved order (`UiProjectState.projectOrder`). */ + readonly orderKeys: readonly string[]; + /** The project's checkouts' folders, which is what a pin holds. */ + readonly cwds: readonly string[]; + readonly selected: boolean; + /** Drawn at the row's end, such as which computers the project is on. */ + readonly trailing?: ReactNode; +} + +/** + * For a button inside a menu row: Enter and Space press the button itself. + * Left to bubble, the menu would read them as picking the row (or, while a + * search holds focus, the highlighted match) instead. + */ +export function keepActivationKeys(event: React.KeyboardEvent) { + if (event.key === "Enter" || event.key === " ") { + event.stopPropagation(); + } +} + +function normalized(text: string): string { + return text.toLocaleLowerCase(); +} + +/** The last two parts of a folder, which is what tells most checkouts apart. */ +function folderTail(cwd: string): string { + const parts = cwd.split(/[\\/]/).filter((part) => part.length > 0); + return parts.length <= 2 ? cwd : `…/${parts.slice(-2).join("/")}`; +} + +/** + * The project list for starting a thread somewhere: the new-thread screen's + * "What's next in …?" and the empty home screen's "New thread in…". Pinned + * projects sit in their own group on top. A long list gets a search line that + * matches names and folders. Rows drag to reorder within their group, by mouse + * or pen anywhere on the row, by finger on the grip, or with Alt and the arrow + * keys; Alt+P pins the highlighted row. The first drag switches the order from + * activity to the user's own; "Reset to automatic order" switches it back. + * Pins and order are kept on this device and shared by every project picker + * that reads `useHandleNewThread().orderedProjects`. + */ +export function ProjectPickerMenu(props: { + /** A MenuTrigger. */ + readonly trigger: ReactNode; + readonly align: "start" | "center" | "end"; + /** Every project, already in picker order (`useHandleNewThread().orderedProjects`). */ + readonly rows: readonly ProjectPickerRow[]; + /** Names the list while nothing is pinned. */ + readonly label: string; + /** Rows above the projects, such as General chat. Hidden while a search is typed. */ + readonly header?: ReactNode; + readonly onPick: (row: ProjectPickerRow) => void; +}) { + const { rows } = props; + const [query, setQuery] = useState(""); + const isCoarsePointer = useMediaQuery({ pointer: "coarse" }); + const showSearch = !isCoarsePointer && rows.length >= PROJECT_SEARCH_MIN_PROJECTS; + const searching = showSearch && query.trim().length > 0; + + const pinnedProjectCwds = useUiStateStore((store) => store.pinnedProjectCwds); + const setProjectPinned = useUiStateStore((store) => store.setProjectPinned); + const setProjectOrder = useUiStateStore((store) => store.setProjectOrder); + const sortOrder = useSettings((settings) => settings.sidebarProjectSortOrder); + const { updateSettings } = useUpdateSettings(); + + const needle = normalized(query.trim()); + const matchesName = (row: ProjectPickerRow) => normalized(row.name).includes(needle); + const shown = searching + ? rows.filter( + (row) => + matchesName(row) || + [row.cwd, ...row.cwds].some((cwd) => normalized(cwd).includes(needle)), + ) + : rows; + const pinnedRows = shown.filter((row) => isProjectPinned(row.cwds, pinnedProjectCwds)); + const otherRows = shown.filter((row) => !isProjectPinned(row.cwds, pinnedProjectCwds)); + /** The rows a row swaps with: its own group, as shown. */ + const peersOf = (key: string) => + pinnedRows.some((row) => row.key === key) ? pinnedRows : otherRows; + + // Fresh each render: the drag hook reads its latest `onReorder` and `measure`. + const move = (key: string, toIndex: number) => { + const peers = peersOf(key); + const from = peers.findIndex((row) => row.key === key); + if (from === -1 || toIndex === from || toIndex < 0 || toIndex >= peers.length) return; + // The whole list as shown, with only the shown rows of this group trading + // places: a row a search hid, or one in the other group, keeps its slot, + // and a project's checkouts stay together. + setProjectOrder(moveAmongPeers(rows, peers, from, toIndex).flatMap((row) => row.orderKeys)); + if (sortOrder !== "manual") { + updateSettings({ sidebarProjectSortOrder: "manual" }); + } + }; + + const listRef = useRef(null); + const scrollContainer = () => + listRef.current?.closest('[data-slot="menu-popup"]') + ?.firstElementChild as HTMLElement | null; + const { drag, beginDrag, suppressDragClick } = usePointerDragReorder({ + axis: "y", + measure: (key) => { + const list = listRef.current; + const scroller = scrollContainer(); + if (list === null) return null; + const origin = scroller?.getBoundingClientRect().top ?? 0; + const scrolled = scroller?.scrollTop ?? 0; + const order = peersOf(key).map((row) => row.key); + const bounds = order.map((rowKey) => { + const box = list + .querySelector(`[data-project-picker-row="${CSS.escape(rowKey)}"]`) + ?.getBoundingClientRect(); + return { start: (box?.top ?? 0) - origin + scrolled, size: box?.height ?? 0 }; + }); + return { order, bounds }; + }, + onReorder: move, + layoutKey: `${shown.map((row) => row.key).join("\n")}|${pinnedProjectCwds.join("\n")}`, + scrollContainer, + }); + + const highlightedKey = (event: React.KeyboardEvent) => + (event.currentTarget as HTMLElement) + .querySelector("[data-project-picker-row][data-highlighted]") + ?.getAttribute("data-project-picker-row") ?? null; + + // The menu drops or resets its highlight when rows change places, by design. + // Once it has, a pointer move puts it back on the row the keyboard moved or + // pinned, so the next key carries on with it. + const keepHighlight = (key: string) => { + const list = listRef.current; + requestAnimationFrame(() => { + list + ?.querySelector(`[data-project-picker-row="${CSS.escape(key)}"]`) + // Some movement: WebKit's menus ignore a pointer that didn't move. + ?.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, movementX: 1 })); + }); + }; + + // Capture: read the highlighted row before the menu moves its highlight. + const onKeyDownCapture = (event: React.KeyboardEvent) => { + if (!event.altKey || event.metaKey || event.ctrlKey) return; + const key = highlightedKey(event); + if (key === null) return; + if (event.code === "KeyP") { + event.preventDefault(); + event.stopPropagation(); + const row = rows.find((candidate) => candidate.key === key); + if (row) { + setProjectPinned(row.cwds, !isProjectPinned(row.cwds, pinnedProjectCwds)); + keepHighlight(key); + } + return; + } + if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return; + const peers = peersOf(key); + const from = peers.findIndex((row) => row.key === key); + const to = from + (event.key === "ArrowUp" ? -1 : 1); + // The arrow is the move's alone: left to go on, it would move the highlight. + event.preventDefault(); + event.stopPropagation(); + if (from === -1 || to < 0 || to >= peers.length) return; + move(key, to); + keepHighlight(key); + }; + + const renderRow = (row: ProjectPickerRow) => { + const pinned = isProjectPinned(row.cwds, pinnedProjectCwds); + const visual = dragReorderVisual(drag, row.key); + const folderHint = searching && !matchesName(row) ? folderTail(row.cwd) : null; + return ( + props.onPick(row)} + onClickCapture={suppressDragClick} + onPointerDown={(event) => { + // A finger on a row is scrolling; fingers drag by the grip. + if (event.pointerType === "touch") return; + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + if ((event.target as Element).closest("button")) return; + beginDrag(row.key, event); + }} + // A project's picture would otherwise start the browser's own image drag. + onDragStart={(event) => event.preventDefault()} + > + {isCoarsePointer && peersOf(row.key).length > 1 ? ( + { + event.stopPropagation(); + beginDrag(row.key, event); + }} + > + + + ) : null} + + {row.name} + {folderHint ? ( + + {folderHint} + + ) : null} + {row.trailing} + + + ); + }; + + const popup = ( + + {showSearch ? ( + + ) : null} + + {searching || props.header === undefined ? null : ( + <> + {props.header} + + + )} + {pinnedRows.length > 0 ? ( + <> + + Pinned + {pinnedRows.map(renderRow)} + + {otherRows.length > 0 ? : null} + + ) : null} + {otherRows.length > 0 ? ( + + {pinnedRows.length > 0 ? "Projects" : props.label} + {otherRows.map(renderRow)} + + ) : null} + {sortOrder === "manual" && !searching ? ( + <> + + + updateSettings({ sidebarProjectSortOrder: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER }) + } + > + + Reset to automatic order + + + ) : null} + + {searching && shown.length === 0 ? ( +
No matching projects
+ ) : null} +
+ ); + + const menu = ( + + {props.trigger} + {popup} + + ); + return showSearch ? ( + + {menu} + + ) : ( + menu + ); +} diff --git a/apps/web/src/components/chat/DraftEmptyState.tsx b/apps/web/src/components/chat/DraftEmptyState.tsx index a0f6ab626..2a480820e 100644 --- a/apps/web/src/components/chat/DraftEmptyState.tsx +++ b/apps/web/src/components/chat/DraftEmptyState.tsx @@ -10,7 +10,10 @@ import { useSidebarProjectSnapshots } from "../../hooks/useSidebarProjectSnapsho import { useWorktreePickup } from "../../hooks/useWorktreePickup"; import { startNewGeneralChatThread } from "../../lib/chatThreadActions"; import { resolveGeneralChatsProjectRef } from "../../lib/generalChats"; -import { orderSnapshotsByProjectRefs } from "../../sidebarProjectGrouping"; +import { + orderSnapshotsByProjectRefs, + type SidebarProjectSnapshot, +} from "../../sidebarProjectGrouping"; import { selectGeneralChatsProjectAcrossEnvironments, useStore } from "../../store"; import { cn } from "../../lib/utils"; import { ProjectFavicon } from "../ProjectFavicon"; @@ -27,15 +30,12 @@ import { ProjectThreadMap } from "./ProjectThreadMap"; import { useDraftHeroColumnMark } from "./useDraftHero"; import { TooltipWrapper } from "../ui/tooltip"; import { - Menu, MENU_PICK_ITEM_CLASS_NAME, MENU_PICK_ITEM_SELECTED_CLASS_NAME, MenuGroup, - MenuGroupLabel, MenuItem, - MenuPopup, - MenuSeparator, } from "../ui/menu"; +import { ProjectPickerMenu } from "../ProjectPickerMenu"; import { InlinePickerTrigger } from "../ui/inline-picker"; /** @@ -226,112 +226,62 @@ export function DraftEmptyState({ style={riseDelay("0.16s")} > What's next in{" "} - - - {isGeneralChat ? ( - - ) : currentProject ? ( - - ) : null} - {targetName} - - - {generalChatsRef ? ( - <> - - { - void startNewGeneralChatThread(handleNewThread, generalChatsRef); - }} - > - - General chat - - - - - ) : null} - - Switch project - {menuSnapshots.map((snapshot) => { - const projectRef = scopeProjectRef(snapshot.environmentId, snapshot.id); - const isCurrentProject = - currentProjectKey !== null && - snapshot.memberProjectRefs.some( - (memberRef) => scopedProjectKey(memberRef) === currentProjectKey, - ); - // Where the project lives, in the glyph vocabulary the rest of - // the app speaks: monitor for this device, cloud for another - // machine, both for a repo on both, and a count when it spans - // several remotes. Glyphs instead of the machine's name — the - // name truncated to nothing at this row width, and hover still - // spells it out. With no remote machine connected the question - // does not exist, so no row carries a glyph at all. - const remoteNames = snapshot.remoteEnvironmentLabels.join(", "); - const remoteCount = snapshot.remoteEnvironmentLabels.length; - const hasLocal = snapshot.environmentPresence !== "remote-only"; - const hasRemote = snapshot.environmentPresence !== "local-only"; - return ( - { - void handleNewThread(projectRef); - }} - title={snapshot.cwd} - > - - {snapshot.displayName} - {hasRemoteMachines ? ( - // Instant tooltip: the glyphs are the only thing naming - // the machines, so a hover dwell reads as unlabelled. - - - {hasLocal ? ( - - ) : null} - {hasRemote ? ( - - ) : null} - {remoteCount > 1 ? ( - - {remoteCount} - - ) : null} - - - ) : null} - - ); - })} - - - + + {isGeneralChat ? ( + + ) : currentProject ? ( + + ) : null} + {targetName} + + } + header={ + generalChatsRef ? ( + + { + void startNewGeneralChatThread(handleNewThread, generalChatsRef); + }} + > + + General chat + + + ) : undefined + } + rows={menuSnapshots.map((snapshot) => ({ + key: snapshot.projectKey, + name: snapshot.displayName, + cwd: snapshot.cwd, + environmentId: snapshot.environmentId, + orderKeys: snapshot.memberProjects.map((member) => member.physicalProjectKey), + cwds: snapshot.memberProjects.map((member) => member.cwd), + selected: + currentProjectKey !== null && + snapshot.memberProjectRefs.some( + (memberRef) => scopedProjectKey(memberRef) === currentProjectKey, + ), + trailing: hasRemoteMachines ? : null, + }))} + onPick={(row) => { + const snapshot = menuSnapshots.find((candidate) => candidate.projectKey === row.key); + if (snapshot) { + void handleNewThread(scopeProjectRef(snapshot.environmentId, snapshot.id)); + } + }} + /> ? @@ -341,3 +291,42 @@ export function DraftEmptyState({ ); } + +/** + * Where a project lives, in the glyph vocabulary the rest of the app speaks: + * monitor for this device, cloud for another machine, both for a repo on + * both, and a count when it spans several remotes. Glyphs instead of the + * machine's name, which truncated to nothing at a menu row's width; hover + * still spells it out. Drawn only while a remote machine is connected. + */ +function ProjectPlaceGlyphs({ snapshot }: { snapshot: SidebarProjectSnapshot }) { + const remoteNames = snapshot.remoteEnvironmentLabels.join(", "); + const remoteCount = snapshot.remoteEnvironmentLabels.length; + const hasLocal = snapshot.environmentPresence !== "remote-only"; + const hasRemote = snapshot.environmentPresence !== "local-only"; + return ( + // Instant tooltip: the glyphs are the only thing naming the machines, so a + // hover dwell reads as unlabelled. + + + {hasLocal ? : null} + {hasRemote ? : null} + {remoteCount > 1 ? ( + + {remoteCount} + + ) : null} + + + ); +} diff --git a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx index 715af25ff..dfe71ee6c 100644 --- a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx +++ b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx @@ -35,6 +35,7 @@ import { import { buildThreadRouteParams } from "../../threadRoutes"; import { useNavigate } from "@tanstack/react-router"; import { useMediaQuery } from "../../hooks/useMediaQuery"; +import { keepActivationKeys, PROJECT_SEARCH_MIN_PROJECTS } from "../ProjectPickerMenu"; import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; import { deriveProjectGroupingOverrideKey, @@ -157,26 +158,9 @@ async function setProjectPhoneAlertsMuted( const SCOPE_ITEM_CLASS_NAME = MENU_PICK_ITEM_CLASS_NAME; const SCOPE_ITEM_SELECTED = MENU_PICK_ITEM_SELECTED_CLASS_NAME; -/** - * For a button inside a menu row: Enter and Space press the button itself. - * Left to bubble, the menu would read them as picking the row (or, while a - * search holds focus, the highlighted match) instead. - */ -function keepActivationKeys(event: React.KeyboardEvent) { - if (event.key === "Enter" || event.key === " ") { - event.stopPropagation(); - } -} - /** How many picked projects the trigger draws an icon for. */ const TRIGGER_FAVICON_LIMIT = 3; -/** - * Past this many projects the menu gets a search line. Fewer fit on screen at - * once, where a search box would only be one more row to look past. - */ -const PROJECT_SEARCH_MIN_PROJECTS = 9; - /** * What the trigger calls the picked projects: their names while two fit, a * count past that -- at sidebar widths a third name is only ever an ellipsis. diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 1d848cba7..0425cbb4f 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -46,6 +46,7 @@ import { useStore, } from "../store"; import type { Project } from "../types"; +import { pinnedProjectsFirst } from "../projectPickerOrder"; import { resolveThreadRouteTarget } from "../threadRoutes"; import { useUiStateStore } from "../uiStateStore"; import { useSettings } from "./useSettings"; @@ -311,12 +312,15 @@ function createThreadContextSelector( } /** - * Projects in the order the sidebar lists them. Sorting by activity reads - * every thread, but the result changes only when the order does, so a - * streaming reply bumping its thread's activity does not redraw callers. + * Projects in the order the project pickers list them: pinned ones first, then + * the rest, each part by the user's dragged order or by activity. Sorting by + * activity reads every thread, but the result changes only when the order + * does, so a streaming reply bumping its thread's activity does not redraw + * callers. */ function useOrderedProjects(): Project[] { const projectOrder = useUiStateStore((store) => store.projectOrder); + const pinnedProjectCwds = useUiStateStore((store) => store.pinnedProjectCwds); const sidebarProjectSortOrder = useSettings((settings) => settings.sidebarProjectSortOrder); return useStore( useShallow( @@ -327,18 +331,17 @@ function useOrderedProjects(): Project[] { preferredIds: projectOrder, getId: getProjectOrderKey, }); - if (sidebarProjectSortOrder === "manual") { - return manuallyOrdered; - } - // Mirror the sidebar's activity/created ordering so project pickers built - // on this hook list projects in the same order the user sees there. - return sortScopedProjectsByActivity( - manuallyOrdered, - selectSidebarThreadsAcrossEnvironments(store), - sidebarProjectSortOrder, - ); + const ordered = + sidebarProjectSortOrder === "manual" + ? manuallyOrdered + : sortScopedProjectsByActivity( + manuallyOrdered, + selectSidebarThreadsAcrossEnvironments(store), + sidebarProjectSortOrder, + ); + return pinnedProjectsFirst(ordered, pinnedProjectCwds); }, - [projectOrder, sidebarProjectSortOrder], + [pinnedProjectCwds, projectOrder, sidebarProjectSortOrder], ), ), ); diff --git a/apps/web/src/projectPickerOrder.test.ts b/apps/web/src/projectPickerOrder.test.ts new file mode 100644 index 000000000..9cc77b06a --- /dev/null +++ b/apps/web/src/projectPickerOrder.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { moveAmongPeers } from "./projectPickerOrder"; + +describe("moveAmongPeers", () => { + it("rearranges only the shown rows, so a row a search hid keeps its slot", () => { + // "hidden" is searched out; B moves above A among the two still shown. + expect(moveAmongPeers(["A", "hidden", "B"], ["A", "B"], 1, 0)).toEqual(["B", "hidden", "A"]); + }); +}); diff --git a/apps/web/src/projectPickerOrder.ts b/apps/web/src/projectPickerOrder.ts new file mode 100644 index 000000000..c71536b9b --- /dev/null +++ b/apps/web/src/projectPickerOrder.ts @@ -0,0 +1,46 @@ +/** + * How the project pickers order projects. Pinned projects (folders in + * `UiProjectState.pinnedProjectCwds`) come first; a project with checkouts in + * several folders counts as pinned when any of them is. + */ + +/** Whether a project, by its checkouts' folders, is pinned. */ +export function isProjectPinned( + cwds: readonly string[], + pinnedProjectCwds: readonly string[], +): boolean { + return cwds.some((cwd) => pinnedProjectCwds.includes(cwd)); +} + +/** Pinned projects first, each part keeping the order it came in. */ +export function pinnedProjectsFirst( + projects: readonly T[], + pinnedProjectCwds: readonly string[], +): T[] { + if (pinnedProjectCwds.length === 0) return [...projects]; + const pinned = new Set(pinnedProjectCwds); + return [ + ...projects.filter((project) => pinned.has(project.cwd)), + ...projects.filter((project) => !pinned.has(project.cwd)), + ]; +} + +/** + * Moves `peers[from]` to `peers[to]` and returns the whole list with the peers + * rearranged in the slots they already held: every row that isn't a peer (one + * a search hid, or one in the other group) keeps its place. + */ +export function moveAmongPeers( + all: readonly T[], + peers: readonly T[], + from: number, + to: number, +): T[] { + const moved = [...peers]; + const [item] = moved.splice(from, 1); + if (item === undefined) return [...all]; + moved.splice(to, 0, item); + const peerSet = new Set(peers); + let next = 0; + return all.map((row) => (peerSet.has(row) ? moved[next++]! : row)); +} diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 3d142548a..1d7b15e22 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -25,6 +25,7 @@ function makeUiState(overrides: Partial = {}): UiState { return { projectExpandedById: {}, projectOrder: [], + pinnedProjectCwds: [], seenThreadOverlays: {}, threadSeedVisitedAtById: {}, threadChangedFilesExpandedById: {}, @@ -92,6 +93,19 @@ describe("uiStateStore pure functions", () => { expect(overtaken.seenThreadOverlays).toEqual({}); }); + it("a project on a computer that connects later goes back to its saved place", () => { + // Saved: remote first. The local computer's projects load first. + hydratePersistedProjectState({ projectOrderCwds: ["/srv/remote", "/work/local"] }); + const local = { key: "local:/work/local", logicalKey: "local", cwd: "/work/local" }; + const remote = { key: "remote:/srv/remote", logicalKey: "remote", cwd: "/srv/remote" }; + + const localOnly = syncProjects(makeUiState(), [local]); + const both = syncProjects(localOnly, [local, remote]); + + expect(both.projectOrder).toEqual([remote.key, local.key]); + hydratePersistedProjectState({}); + }); + it("reorderProjects moves a project to a target index", () => { const project1 = ProjectId.make("project-1"); const project2 = ProjectId.make("project-2"); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index 39ca3b4dd..101113191 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -21,6 +21,8 @@ export interface PersistedUiState { collapsedProjectCwds?: string[]; expandedProjectCwds?: string[]; projectOrderCwds?: string[]; + /** See `UiProjectState.pinnedProjectCwds`. */ + pinnedProjectCwds?: string[]; defaultAdvertisedEndpointKey?: string | null; threadChangedFilesExpandedById?: Record>; /** @@ -52,6 +54,12 @@ export interface PersistedUiState { export interface UiProjectState { projectExpandedById: Record; projectOrder: string[]; + /** + * The folders of the projects pinned to the top of the project pickers, on + * this device. Kept by folder, like the saved order, so a pin outlives the + * project's id changing and covers every checkout of the folder. + */ + pinnedProjectCwds: readonly string[]; } /** @@ -197,6 +205,7 @@ export interface SyncThreadInput { const initialState: UiState = { projectExpandedById: {}, projectOrder: [], + pinnedProjectCwds: [], seenThreadOverlays: {}, threadSeedVisitedAtById: {}, threadChangedFilesExpandedById: {}, @@ -257,6 +266,15 @@ export function readPersistedState(): UiState { parsed.threadChangedFilesExpandedById, ), inboxProjectScopeKeys: sanitizePersistedProjectScopeKeys(parsed), + pinnedProjectCwds: Array.isArray(parsed.pinnedProjectCwds) + ? [ + ...new Set( + parsed.pinnedProjectCwds.filter( + (cwd): cwd is string => typeof cwd === "string" && cwd.length > 0, + ), + ), + ] + : [], inboxEnvironmentScopeId: typeof parsed.inboxEnvironmentScopeId === "string" && parsed.inboxEnvironmentScopeId.length > 0 @@ -466,6 +484,27 @@ export function hydratePersistedProjectState(parsed: PersistedUiState): void { } } +/** + * The saved order, by folder, with the folders of projects that aren't loaded + * right now (a computer still connecting, or offline) kept after the folder + * they followed when this session loaded. Writing only what is loaded would + * forget their places the first time anything is saved. + */ +function keepSavedPlacesOfAbsentProjects(orderCwds: readonly string[]): string[] { + const result = [...orderCwds]; + const present = new Set(orderCwds); + let previous: string | null = null; + for (const cwd of persistedProjectOrderCwds) { + if (!present.has(cwd)) { + const after = previous === null ? -1 : result.indexOf(previous); + result.splice(after + 1, 0, cwd); + present.add(cwd); + } + previous = cwd; + } + return result; +} + export function persistState(state: UiState): void { if (typeof window === "undefined") { return; @@ -480,10 +519,12 @@ export function persistState(state: UiState): void { const expandedProjectCwds = Object.entries(state.projectExpandedById) .filter(([, expanded]) => expanded) .flatMap(([logicalKey]) => currentProjectCwdsByLogicalKey.get(logicalKey) ?? []); - const projectOrderCwds = state.projectOrder.flatMap((projectId) => { - const cwd = currentProjectCwdById.get(projectId); - return cwd ? [cwd] : []; - }); + const projectOrderCwds = keepSavedPlacesOfAbsentProjects( + state.projectOrder.flatMap((projectId) => { + const cwd = currentProjectCwdById.get(projectId); + return cwd ? [cwd] : []; + }), + ); const threadChangedFilesExpandedById = Object.fromEntries( Object.entries(state.threadChangedFilesExpandedById).flatMap(([threadId, turns]) => { const nextTurns = Object.fromEntries( @@ -498,6 +539,7 @@ export function persistState(state: UiState): void { collapsedProjectCwds, expandedProjectCwds, projectOrderCwds, + pinnedProjectCwds: [...state.pinnedProjectCwds], defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey, threadChangedFilesExpandedById, inboxProjectScopeKeys: [...state.inboxProjectScopeKeys], @@ -668,11 +710,30 @@ export function syncProjects(state: UiState, projects: readonly SyncProjectInput orderedProjectIds.push(matchedProjectId); } + // A project arriving after the order exists, such as one on a computer + // that connected after this one, goes back to its saved place: in front + // of the first project saved after it. Appending would drop a dragged + // order every time computers connect in a different sequence. + const cwdByProjectId = new Map( + mappedProjects.map((project) => [project.id, project.cwd] as const), + ); for (const project of mappedProjects) { if (usedProjectIds.has(project.id)) { continue; } - orderedProjectIds.push(project.id); + const savedRank = persistedOrderByCwd.get(project.cwd); + const before = + savedRank === undefined + ? -1 + : orderedProjectIds.findIndex((id) => { + const rank = persistedOrderByCwd.get(cwdByProjectId.get(id) ?? ""); + return rank !== undefined && rank > savedRank; + }); + if (before === -1) { + orderedProjectIds.push(project.id); + } else { + orderedProjectIds.splice(before, 0, project.id); + } } return orderedProjectIds; @@ -1141,6 +1202,30 @@ export function reorderProjects( }; } +/** + * Puts the given checkouts (keys of `projectOrder`) first, in this order, and + * keeps the rest after them as they were. The project pickers pass the whole + * order they show, rearranged by a drag. + */ +export function setProjectOrder(state: UiState, order: readonly string[]): UiState { + const placed = new Set(order); + const projectOrder = [...order, ...state.projectOrder.filter((id) => !placed.has(id))]; + return orderedListsEqual(state.projectOrder, projectOrder) ? state : { ...state, projectOrder }; +} + +/** Pins or unpins every folder of one project. */ +export function setProjectPinned( + state: UiState, + cwds: readonly string[], + pinned: boolean, +): UiState { + const kept = state.pinnedProjectCwds.filter((cwd) => !cwds.includes(cwd)); + const next = pinned ? [...kept, ...cwds] : kept; + return orderedListsEqual(state.pinnedProjectCwds, next) + ? state + : { ...state, pinnedProjectCwds: next }; +} + /** Whether the list beside the rail is showing, floating or not. */ export function selectSidebarListShown(state: UiLayoutState): boolean { return state.sidebarListFloats ? state.sidebarFloatingListOpen : state.sidebarListOpen; @@ -1194,6 +1279,8 @@ interface UiStateStore extends UiState { draggedProjectIds: readonly string[], targetProjectIds: readonly string[], ) => void; + setProjectOrder: (order: readonly string[]) => void; + setProjectPinned: (cwds: readonly string[], pinned: boolean) => void; } export const useUiStateStore = create((set) => ({ @@ -1254,6 +1341,8 @@ export const useUiStateStore = create((set) => ({ set((state) => setProjectExpanded(state, projectId, expanded)), reorderProjects: (draggedProjectIds, targetProjectIds) => set((state) => reorderProjects(state, draggedProjectIds, targetProjectIds)), + setProjectOrder: (order) => set((state) => setProjectOrder(state, order)), + setProjectPinned: (cwds, pinned) => set((state) => setProjectPinned(state, cwds, pinned)), })); useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state));