From a75956732f4b11ab13c07d56c5c35289329632c7 Mon Sep 17 00:00:00 2001 From: chise <188340668+chisewaguri@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:41:01 +0700 Subject: [PATCH 1/2] fix(web): let users drag sidebar project folders to reorder them --- apps/web/src/components/Sidebar.motion.ts | 51 +++-- .../Sidebar.shiftGuard.browser.test.ts | 41 ++-- apps/web/src/components/Sidebar.shiftGuard.ts | 17 +- apps/web/src/components/Sidebar.tsx | 205 +++++++++++++----- ...derHeader.tsx => SidebarProjectFolder.tsx} | 49 ++++- apps/web/src/uiStateStore.test.ts | 24 +- apps/web/src/uiStateStore.ts | 33 +-- docs/user/thread-sidebar.md | 6 +- .../sidebar-project-folders-reorder.e2e.ts | 107 +++++++++ 9 files changed, 403 insertions(+), 130 deletions(-) rename apps/web/src/components/sidebar/{SidebarProjectFolderHeader.tsx => SidebarProjectFolder.tsx} (76%) create mode 100644 scripts/scenarios/sidebar-project-folders-reorder.e2e.ts diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index 0e86c3c9a0e94..22850d66bdac2 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -11,7 +11,23 @@ function progress(animation: Animation) { : (animation.effect?.getComputedTiming().progress ?? 0); } -/** Position the list so all direct children's offsetTop share an origin. */ +export function forEachSidebarListRow( + list: HTMLElement, + visit: (row: HTMLElement, folder?: HTMLElement) => void, +) { + for (const child of list.children) { + if (!(child instanceof HTMLElement)) continue; + if (child.hasAttribute("data-sidebar-folder-group")) { + for (const row of child.firstElementChild?.children ?? []) { + if (row instanceof HTMLElement) visit(row, child); + } + } else { + visit(child); + } + } +} + +/** Folder rows are positioned relative to their sortable wrapper. */ export function createSidebarListMotion(parent: HTMLUListElement) { let positions: Map | null = null; let disposed = false; @@ -126,19 +142,16 @@ export function createSidebarListMotion(parent: HTMLUListElement) { suspend(); return; } - const next = new Map( - Array.from(parent.children) - .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node)) - .map((node) => [ - node, - { - top: node.offsetTop, - left: node.offsetLeft, - width: node.offsetWidth, - height: node.offsetHeight, - }, - ]), - ); + const next = new Map(); + forEachSidebarListRow(parent, (node, folder) => { + if (exiting.has(node)) return; + next.set(node, { + top: node.offsetTop + (folder?.offsetTop ?? 0), + left: node.offsetLeft + (folder?.offsetLeft ?? 0), + width: node.offsetWidth, + height: node.offsetHeight, + }); + }); let fadeCount = 0; if (positions !== null) { for (const [node, position] of positions) { @@ -237,11 +250,11 @@ export function createSidebarListMotion(parent: HTMLUListElement) { release() { suspend(); const origin = parent.getBoundingClientRect().top; - released = new Map( - Array.from(parent.children) - .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node)) - .map((node) => [node, node.getBoundingClientRect().top - origin]), - ); + const tops = new Map(); + forEachSidebarListRow(parent, (node) => { + tops.set(node, node.getBoundingClientRect().top - origin); + }); + released = tops; }, suspend, dispose() { diff --git a/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts b/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts index 23210bea89cc8..558387a41b4a8 100644 --- a/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts +++ b/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts @@ -3,9 +3,17 @@ import { userEvent } from "vite-plus/test/browser"; import { fakeTimers, render } from "../../test/render"; import { createSidebarShiftGuard } from "./Sidebar.shiftGuard"; -function mountList(container: HTMLElement, names: readonly string[]) { +function mountList(container: HTMLElement, names: readonly string[], insideFolder = false) { const list = document.createElement("ul"); list.style.cssText = "position: relative; margin: 0; padding: 0; width: 200px; list-style: none"; + const rowList = insideFolder ? document.createElement("ul") : list; + if (insideFolder) { + const folder = document.createElement("li"); + folder.dataset.sidebarFolderGroup = ""; + folder.style.position = "relative"; + folder.append(rowList); + list.append(folder); + } const pressed: string[] = []; const rows = new Map(); const add = (name: string) => { @@ -15,7 +23,7 @@ function mountList(container: HTMLElement, names: readonly string[]) { button.textContent = name; button.addEventListener("click", () => pressed.push(name)); row.append(button); - list.append(row); + rowList.append(row); rows.set(name, row); }; for (const name of names) add(name); @@ -41,20 +49,23 @@ function duringPress(act: () => void) { } describe("sidebar shift guard", () => { - it("drops a press on a row that slid up on its own, then accepts it after the delay", async () => { - await using screen = await render(null); - using list = mountList(screen.container, ["A", "B", "C"]); - using _clock = fakeTimers(); - - list.remove("A"); - list.guard.update(); - await userEvent.click(list.button("B")); - expect(list.pressed).toEqual([]); + it.each([false, true])( + "drops a press on a row that slid up on its own (inside folder: %s)", + async (insideFolder) => { + await using screen = await render(null); + using list = mountList(screen.container, ["A", "B", "C"], insideFolder); + using _clock = fakeTimers(); - vi.advanceTimersByTime(500); - await userEvent.click(list.button("B")); - expect(list.pressed).toEqual(["B"]); - }); + list.remove("A"); + list.guard.update(); + await userEvent.click(list.button("B")); + expect(list.pressed).toEqual([]); + + vi.advanceTimersByTime(500); + await userEvent.click(list.button("B")); + expect(list.pressed).toEqual(["B"]); + }, + ); it("keeps rows that did not move, or barely moved, clickable", async () => { await using screen = await render(null); diff --git a/apps/web/src/components/Sidebar.shiftGuard.ts b/apps/web/src/components/Sidebar.shiftGuard.ts index fc8bec17f1d4a..4f442fd9e3523 100644 --- a/apps/web/src/components/Sidebar.shiftGuard.ts +++ b/apps/web/src/components/Sidebar.shiftGuard.ts @@ -1,3 +1,5 @@ +import { forEachSidebarListRow } from "./Sidebar.motion"; + // How long a row the list just moved ignores presses. A click that was already // on its way when the row slid under the pointer lands within this window. const MOVED_ROW_PRESS_DELAY_MS = 500; @@ -22,9 +24,9 @@ function editsText(event: KeyboardEvent) { function readTops(list: HTMLElement) { const tops = new Map(); - for (const child of list.children) { - if (child instanceof HTMLElement) tops.set(child, child.offsetTop); - } + forEachSidebarListRow(list, (row, folder) => { + tops.set(row, row.offsetTop + (folder?.offsetTop ?? 0)); + }); return tops; } @@ -32,7 +34,7 @@ function readTops(list: HTMLElement) { * Drops presses on rows that something other than the user just moved, so a * thread settling, waking or arriving above the pointer cannot hand its click * to the neighbouring row. Call `update` after each commit that can move rows. - * The list must be positioned so every direct child's offsetTop shares its origin. + * The list and project folders must be positioned to provide row offsets. */ export function createSidebarShiftGuard(list: HTMLElement) { const view = list.ownerDocument.defaultView; @@ -47,8 +49,11 @@ export function createSidebarShiftGuard(list: HTMLElement) { const rowOf = (target: EventTarget | null) => { let node = target instanceof Node ? target : null; - while (node !== null && node.parentNode !== list) node = node.parentNode; - return node instanceof Element ? node : null; + while (node !== null && node !== list) { + if (node instanceof HTMLElement && tops.has(node)) return node; + node = node.parentNode; + } + return null; }; const swallow = (event: Event) => { event.preventDefault(); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 45e00246e2c6d..3b1f3b418a30f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -17,16 +17,21 @@ import { Atom } from "effect/reactivity"; import * as Schema from "effect/Schema"; import { DndContext, + getClientRect, + pointerWithin, useSensor, useSensors, type AutoScrollOptions, + type ClientRect, + type CollisionDetection, type DragEndEvent, type DragOverEvent, type DragStartEvent, type Modifier, } from "@dnd-kit/core"; -import { SortableContext } from "@dnd-kit/sortable"; +import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable"; import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers"; +import type { Coordinates } from "@dnd-kit/utilities"; import { canSnooze, effectiveSnoozed, @@ -136,7 +141,7 @@ import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; import { startNewThreadFromContext } from "../lib/chatThreadActions"; -import { useClientSettings } from "../hooks/useSettings"; +import { getClientSettings, updateClientSettings, useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; @@ -273,10 +278,7 @@ import { type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; -import { - SidebarProjectFolderHeader, - sidebarFolderRowId, -} from "./sidebar/SidebarProjectFolderHeader"; +import { SidebarProjectFolder, sidebarFolderRowId } from "./sidebar/SidebarProjectFolder"; import { SidebarDragBoundary, SidebarSectionHeader, @@ -893,6 +895,16 @@ const SIDEBAR_DRAG_DISTANCE = 6; // dnd-kit's 20% edge zone at full speed runs the list away while the pointer rests near the bottom. const SIDEBAR_AUTO_SCROLL: AutoScrollOptions = { threshold: { x: 0, y: 0.05 }, acceleration: 3 }; +function sameProjectFolderSection(source: SidebarProjectSnapshot, target: SidebarProjectSnapshot) { + return ( + source.archived === target.archived && (source.archived || source.pinned === target.pinned) + ); +} + +function rectContainsPoint(rect: ClientRect, { x, y }: Coordinates) { + return x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom; +} + const SIDEBAR_DRAG_LABEL_HEIGHT = 24; const threadSearchResultId = (index: number) => `sidebar-thread-search-result-${index}`; @@ -1060,6 +1072,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve readonly targetSection: SidebarSection | null; readonly contextDrag: boolean; } | null>(null); + const [draggedProjectFolderId, setDraggedProjectFolderId] = useState(null); + const projectReleasePointRef = useRef(null); const dragSensorRef = useRef(null); const contextDragKeyRef = useRef(null); const dragScrollRef = useRef<{ readonly viewport: Element; readonly top: number } | null>(null); @@ -1363,6 +1377,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve keepEmptyFolders: (group) => scopedProjectGroups.length > 0 || (group.pinned && !group.archived), }); + const projectFolderById = new Map( + projectFolders?.map(({ group }) => [sidebarFolderRowId(group.projectKey), group] as const), + ); // Ranked across environments as the palette ranks them, so one // environment's list does not sit above another's better matches; rows @@ -1708,13 +1725,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } })(); }; - const restrictBelowPins: Modifier = (args) => - restrictBelowSidebarLabel(args, dragLabelOffsetRef.current); - const dndModifiers = [ - restrictToVerticalAxis, - restrictBelowPins, - restrictToFirstScrollableAncestor, - ]; + const restrictThreadDrag: Modifier = (args) => + args.active && projectFolderById.has(String(args.active.id)) + ? args.transform + : restrictToFirstScrollableAncestor({ + ...args, + transform: restrictBelowSidebarLabel(args, dragLabelOffsetRef.current), + }); + const dndModifiers = [restrictToVerticalAxis, restrictThreadDrag]; const attachListMotionRef = (node: HTMLUListElement) => { threadListRef.current = node; const motion = createSidebarListMotion(node); @@ -1744,13 +1762,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; }; - // Folder rows only drag out to the composer; folders own their order, so nothing drops in the list. + // Thread rows in folders only drag out to the composer. const isContextDrag = projectFolders !== null || dragState?.contextDrag === true || dragState?.activeSection === "working"; const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null); - const finishThreadDrag = (started: boolean) => { + const finishSidebarDrag = (started: boolean) => { dragSensorRef.current = null; contextDragKeyRef.current = null; dragScrollRef.current = null; @@ -1758,12 +1776,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (started) { listMotionRef.current?.release(); setDragState(null); + setDraggedProjectFolderId(null); } }; const attachDragSensor = (sensor: SidebarPointerSensor) => { dragSensorRef.current = sensor; }; - const cancelThreadDrag = () => { + const cancelSidebarDrag = () => { dragSensorRef.current?.cancel(); }; const contextDragThreads = (): ReadonlyArray => { @@ -1781,12 +1800,19 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const bounds = (threadListRef.current ?? searchResultsListRef.current)?.getBoundingClientRect(); return bounds !== undefined && (point.x < bounds.left || point.x > bounds.right); }; + const pointerInsideSidebarViewport = (point: Coordinates) => { + const bounds = threadListRef.current + ?.closest('[data-slot="scroll-area-viewport"]') + ?.getBoundingClientRect(); + return bounds !== undefined && rectContainsPoint(bounds, point); + }; // The path out of the list often crosses dnd-kit's edge zone, which autoscrolls the sidebar. const restoreDragScroll = () => { const scroll = dragScrollRef.current; if (scroll && scroll.viewport.scrollTop !== scroll.top) scroll.viewport.scrollTop = scroll.top; }; const moveThreadContextDrag = (point: { x: number; y: number }) => { + if (contextDragKeyRef.current === null) return false; // Search results cannot reorder, so their context preview starts inside the list. const contextDrag = searchResultsListRef.current !== null || pointerOutsideThreadList(point); setDragState((current) => @@ -1805,7 +1831,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve moveThreadContextDragGhost(point, { title, count: threads.length }); return true; }; - const dropThreadContextDrag = (point: { x: number; y: number }) => { + const dropSidebarDrag = (point: Coordinates) => { + if (contextDragKeyRef.current === null) { + // dnd-kit's last target can predate the pointer release. + const insideViewport = pointerInsideSidebarViewport(point); + projectReleasePointRef.current = insideViewport ? point : null; + return !insideViewport; + } if (!pointerOutsideThreadList(point)) return false; restoreDragScroll(); dropThreadContext(point, contextDragThreads()); @@ -1815,9 +1847,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const pointerSensorOptions = { distance: SIDEBAR_DRAG_DISTANCE, onAttach: attachDragSensor, - onFinish: finishThreadDrag, + onFinish: finishSidebarDrag, onMove: moveThreadContextDrag, - onDrop: dropThreadContextDrag, + onDrop: dropSidebarDrag, }; const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions)); const sectionByThreadKeyRef = useRef(sectionByThreadKey); @@ -1927,8 +1959,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve })(); }; - const handleThreadDragStart = (event: DragStartEvent) => { + const handleSidebarDragStart = (event: DragStartEvent) => { const activeKey = String(event.active.id); + if (projectFolderById.has(activeKey)) { + listMotionRef.current?.suspend(); + projectReleasePointRef.current = null; + setDraggedProjectFolderId(activeKey); + return; + } contextDragKeyRef.current = activeKey; const activeSection = sectionByThreadKey.get(activeKey); if (activeSection === undefined) return; @@ -2014,12 +2052,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the dnd-kit drag sensor when the dragged row leaves the list useEffect(() => { if ( - dragState !== null && - !sidebarListItems.some((item) => item.kind === "thread" && item.key === dragState.activeKey) + (draggedProjectFolderId !== null && !projectFolderById.has(draggedProjectFolderId)) || + (dragState !== null && + !sidebarListItems.some( + (item) => item.kind === "thread" && item.key === dragState.activeKey, + )) ) { - cancelThreadDrag(); + cancelSidebarDrag(); } - }, [cancelThreadDrag, dragState, sidebarListItems]); + }, [cancelSidebarDrag, dragState, draggedProjectFolderId, projectFolderById, sidebarListItems]); // Only order, section, or draft changes need layout reads and motion. const listMotionLayoutKey = [ sidebarListItemsKey, @@ -2030,7 +2071,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve routeDraftIdForRows ?? "", ].join("\0"); const listMotionAnimate = - dragState === null && sidebarListItems.length + visibleDraftSessionCount > 0; + dragState === null && + draggedProjectFolderId === null && + sidebarListItems.length + visibleDraftSessionCount > 0; // Cache on both fields so layout-key changes trigger the effect even when animate is unchanged. const listMotionPass = { layoutKey: listMotionLayoutKey, animate: listMotionAnimate }; const shelfExpansionKey = [workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded].join( @@ -2046,6 +2089,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve listMotionRef.current?.update(listMotionPass.animate && shelvesUnchanged); }, [listMotionPass, shelfExpansionKey]); const handleThreadDragOver = (event: DragOverEvent) => { + if (projectFolders !== null) return; const target = event.over ? resolveSidebarDropTarget(sidebarListItems, String(event.active.id), String(event.over.id)) : null; @@ -2081,7 +2125,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const draggedThreadKey = dragState?.activeKey; const draggedFromSection = dragState?.activeSection; const dragActivationY = dragState?.activationY; - const dndCollisionDetection = (() => { + const threadCollisionDetection = (() => { if (draggedThreadKey === undefined || draggedFromSection === undefined) return createSidebarCollisionDetection(() => true); const source = threadByKey.get(draggedThreadKey); @@ -2114,8 +2158,56 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ); })(); - const handleThreadDragEnd = (event: DragEndEvent) => { - if (projectFolders !== null) return; + const dndCollisionDetection: CollisionDetection = (args) => { + const source = projectFolderById.get(String(args.active.id)); + if (source === undefined) return threadCollisionDetection(args); + // A sortable target keeps the dragged folder translated even in a gap. + const stayOnSource = [{ id: args.active.id }]; + if (!args.pointerCoordinates || !pointerInsideSidebarViewport(args.pointerCoordinates)) { + return stayOnSource; + } + const collisions = pointerWithin({ + ...args, + droppableContainers: args.droppableContainers.filter(({ id }) => { + const target = projectFolderById.get(String(id)); + return target !== undefined && sameProjectFolderSection(source, target); + }), + }); + return collisions.length === 0 ? stayOnSource : collisions; + }; + const handleSidebarDragEnd = (event: DragEndEvent) => { + if (projectFolders !== null) { + const point = projectReleasePointRef.current; + projectReleasePointRef.current = null; + const source = projectFolderById.get(String(event.active.id)); + if (!point || !source) return; + const folders = threadListRef.current?.querySelectorAll( + ":scope > [data-sidebar-folder-group]", + ); + let target: SidebarProjectSnapshot | undefined; + // The preview displaces other folders, so hit-test their untransformed slots. + for (const folder of folders ?? []) { + const candidate = projectFolderById.get(folder.dataset.sidebarFolderGroup!); + if ( + candidate && + sameProjectFolderSection(source, candidate) && + rectContainsPoint(getClientRect(folder, { ignoreTransform: true }), point) + ) { + target = candidate; + break; + } + } + if (!target || target === source) return; + const orderKeys = (group: SidebarProjectSnapshot) => + group.memberProjects.map((project) => project.physicalProjectKey); + useUiStateStore + .getState() + .reorderProjects(projectGroups.flatMap(orderKeys), orderKeys(source), orderKeys(target)); + if (getClientSettings().sidebarProjectSortOrder !== "manual") { + void updateClientSettings({ sidebarProjectSortOrder: "manual" }); + } + return; + } const activeKey = String(event.active.id); const activeSection = sectionByThreadKey.get(activeKey); const target = @@ -3420,12 +3512,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve >
    , - ); - for (const thread of folder.threads) { - items.push( - renderThreadRow( - thread, - "active", - sidebarFolderRowId(folder.group.projectKey), - ), - ); - } - } + items.push( + + {projectFolders.map((folder) => { + const rowId = sidebarFolderRowId(folder.group.projectKey); + return ( + + {folder.threads.map((thread) => + renderThreadRow(thread, "active", rowId), + )} + + ); + })} + , + ); continue; } switch (item.marker) { diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolder.tsx similarity index 76% rename from apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx rename to apps/web/src/components/sidebar/SidebarProjectFolder.tsx index 7ebda48e5b89a..29a18e99e5478 100644 --- a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectFolder.tsx @@ -1,15 +1,21 @@ +import { useSortable } from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { ContextMenuSource } from "@t3tools/contracts"; import { ChevronDownIcon, SquarePenIcon } from "lucide-react"; import { msg, T, useGT, useMessages, Var } from "gt-react"; -import { memo } from "react"; +import { memo, type ReactNode } from "react"; import { cn } from "~/lib/utils"; import { contextMenuSourceOf } from "../../contextMenuSource"; import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; import { useUiStateStore } from "../../uiStateStore"; -import { resolveSidebarFolderDot, resolveThreadLastVisitedAt } from "../Sidebar.logic"; +import { + animateSidebarLayoutChanges, + resolveSidebarFolderDot, + resolveThreadLastVisitedAt, +} from "../Sidebar.logic"; import { ProjectFavicon } from "../ProjectFavicon"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -38,10 +44,12 @@ export function sidebarFolderRowId(projectKey: string) { * count and chevron, with the count and a status dot only while it is closed, so a * closed folder still says when a hidden thread needs you. */ -export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHeader(props: { +export const SidebarProjectFolder = memo(function SidebarProjectFolder(props: { group: SidebarProjectSnapshot; collapsed: boolean; hiddenThreads: readonly EnvironmentThreadShell[]; + sortableDisabled: boolean; + children: ReactNode; onToggle: (group: SidebarProjectSnapshot) => void; onNewThread: (group: SidebarProjectSnapshot) => void; onContextMenu: ( @@ -54,6 +62,11 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead const m = useMessages(); const { group, collapsed, hiddenThreads } = props; const rowId = sidebarFolderRowId(group.projectKey); + const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: rowId, + disabled: props.sortableDisabled, + animateLayoutChanges: animateSidebarLayoutChanges, + }); const localLastVisitedAtById = useUiStateStore((state) => state.threadLastVisitedAtById); const dot = collapsed ? resolveSidebarFolderDot( @@ -68,15 +81,13 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead })), ) : null; - return ( -
  • + const header = ( +
  • ); + return ( +
  • +
      + {header} + {props.children} +
    +
  • + ); }); diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 804757e78307a..15469ea7c8117 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -85,12 +85,26 @@ describe("uiStateStore pure functions", () => { const keyALocal = "env-local:proj-a"; const keyARemote = "env-remote:proj-a"; const keyB = "env-local:proj-b"; - const keyC = "env-local:proj-c"; - const currentOrder = [keyALocal, keyARemote, keyB, keyC]; - - const next = reorderProjects(makeUiState(), currentOrder, [keyALocal, keyARemote], [keyC]); + const keyCLocal = "env-local:proj-c"; + const keyCRemote = "env-remote:proj-c"; + const disconnected = "env-disconnected:proj-d"; + const currentOrder = [keyALocal, keyARemote, keyB, keyCLocal, keyCRemote]; + + const next = reorderProjects( + makeUiState({ projectOrder: [disconnected] }), + currentOrder, + [keyALocal, keyARemote], + [keyCLocal, keyCRemote], + ); - expect(next.projectOrder).toEqual([keyB, keyC, keyALocal, keyARemote]); + expect(next.projectOrder).toEqual([ + keyB, + keyCLocal, + keyCRemote, + keyALocal, + keyARemote, + disconnected, + ]); }); }); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index b2ac1a508c7a6..1c1216ccb8da5 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -393,32 +393,23 @@ export function reorderProjects( return state; } - const originalTargetIndex = currentProjectOrder.findIndex((id) => targetSet.has(id)); - if (originalTargetIndex < 0) { + const sourceIndex = currentProjectOrder.findIndex((id) => draggedSet.has(id)); + const targetIndex = currentProjectOrder.findIndex((id) => targetSet.has(id)); + if (sourceIndex < 0 || targetIndex < 0) { return state; } - const projectOrder = [...currentProjectOrder]; - - const removed: string[] = []; - let draggedBeforeTarget = 0; - for (let i = projectOrder.length - 1; i >= 0; i--) { - if (draggedSet.has(projectOrder[i]!)) { - removed.unshift(projectOrder.splice(i, 1)[0]!); - if (i < originalTargetIndex) { - draggedBeforeTarget++; - } - } - } - if (removed.length === 0) { - return state; - } - - const insertIndex = originalTargetIndex - Math.max(0, draggedBeforeTarget - 1); - projectOrder.splice(insertIndex, 0, ...removed); + const dragged = currentProjectOrder.filter((id) => draggedSet.has(id)); + const projectOrder = currentProjectOrder.filter((id) => !draggedSet.has(id)); + const insertIndex = + sourceIndex < targetIndex + ? projectOrder.findLastIndex((id) => targetSet.has(id)) + 1 + : projectOrder.findIndex((id) => targetSet.has(id)); + projectOrder.splice(insertIndex, 0, ...dragged); + const loaded = new Set(currentProjectOrder); return { ...state, - projectOrder, + projectOrder: [...projectOrder, ...state.projectOrder.filter((id) => !loaded.has(id))], }; } diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index f58f35feb45f5..af49a11d5a2c4 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -156,8 +156,10 @@ Turn on **Settings → Labs → Boring sidebar (group by project)** on web and d threads in a folder for each project. Pinned projects come first. A project with no active threads has no folder unless it is pinned or you pick it in the project filter. An archived project's folder comes last and shows only while it has active threads. Click a folder to open or -close it. A closed folder shows how many threads it holds, and a dot when one of them -needs you. Use the pen button on a folder, or right-click it, to start a thread in that project. +close it. Drag a folder by its name to reorder it. The first reorder switches +**Settings → General → Project order** to **Manual** on that client. A closed folder shows +how many threads it holds, and a dot when one of them needs you. Use the pen button on a +folder, or right-click it, to start a thread in that project. Pinned threads stay above the folders, and Snoozed and Settled stay below them. In this mode you can drag a thread onto the composer to mention it, but not within the sidebar, and the Working section is off. Each device keeps its own choice. diff --git a/scripts/scenarios/sidebar-project-folders-reorder.e2e.ts b/scripts/scenarios/sidebar-project-folders-reorder.e2e.ts new file mode 100644 index 0000000000000..2615770fde49d --- /dev/null +++ b/scripts/scenarios/sidebar-project-folders-reorder.e2e.ts @@ -0,0 +1,107 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Project folders can be dragged into a saved order", + WEB, + async ({ t3, app, screen, browser }) => { + const alpha = await t3.project("alpha"); + const beta = await t3.project("beta"); + await t3.thread({ project: alpha, title: "Alpha thread", messages: ["Start"] }); + const thread = await t3.thread({ project: beta, title: "Beta thread", messages: ["Start"] }); + await t3.open(thread); + + const threadPath = await browser.evaluate(() => location.pathname); + await app.open("/settings/labs"); + await screen.getByRole("switch", "Boring sidebar (group by project)").tap(); + await app.open(threadPath); + + const alphaFolder = screen.getByRole("button", "alpha"); + const betaFolder = screen.getByRole("button", "beta"); + await expect(alphaFolder).toBeVisible(); + await expect(betaFolder).toBeVisible(); + const source = (await betaFolder.boundingBox())!; + const target = (await alphaFolder.boundingBox())!; + expect(source.y).toBeLessThan(target.y); + const x = source.x + 12; + const y = source.y + source.height / 2; + const startDrag = async (fromY: number) => { + await browser.mouse.move(x, fromY); + await browser.mouse.down(); + await browser.mouse.move(x, fromY + 8); + }; + const folderGapY = () => + browser.evaluate(() => { + const [first, second] = document.querySelectorAll("[data-sidebar-folder-group]"); + return (first!.getBoundingClientRect().bottom + second!.getBoundingClientRect().top) / 2; + }); + const gapY = await folderGapY(); + await startDrag(y); + await browser.mouse.move(x, gapY); + await app.screenshot("drag-between-folders"); + const dragged = (await betaFolder.boundingBox())!; + expect.soft(Math.abs(dragged.y + source.height / 2 - gapY)).toBeLessThan(2); + await browser.mouse.move(x, target.y + target.height / 2); + await browser.mouse.up(); + + const alphaComesFirst = async () => { + const first = await alphaFolder.boundingBox(); + const second = await betaFolder.boundingBox(); + return first !== null && second !== null && first.y < second.y; + }; + await app.screenshot("project-order"); + await expect.poll(alphaComesFirst).toBe(true); + await expect(betaFolder).toHaveAttribute("aria-expanded", "true"); + await browser.reload(); + await expect.poll(alphaComesFirst).toBe(true); + await app.screenshot("project-order-after-reload"); + + const viewport = await browser.evaluate(() => ({ + width: innerWidth, + height: innerHeight, + footerHeight: document.querySelector('[data-sidebar="footer"]')!.getBoundingClientRect() + .height, + })); + const betaAfterReload = (await betaFolder.boundingBox())!; + const outsideY = betaAfterReload.y + betaAfterReload.height / 2; + await browser.setViewport({ + width: viewport.width, + height: Math.round(outsideY + viewport.footerHeight / 2), + }); + expect( + await browser.evaluate( + (point) => + Boolean(document.elementFromPoint(point.x, point.y)?.closest('[data-sidebar="footer"]')), + { x, y: outsideY }, + ), + ).toBe(true); + const alphaAfterResize = (await alphaFolder.boundingBox())!; + await startDrag(alphaAfterResize.y + alphaAfterResize.height / 2); + await browser.mouse.move(x, outsideY); + await browser.mouse.up(); + await browser.setViewport({ width: viewport.width, height: viewport.height }); + await browser.reload(); + await expect.poll(alphaComesFirst).toBe(true); + + const releaseGapY = await folderGapY(); + const alphaBeforeRelease = (await alphaFolder.boundingBox())!; + const betaBeforeRelease = (await betaFolder.boundingBox())!; + await startDrag(alphaBeforeRelease.y + alphaBeforeRelease.height / 2); + await browser.mouse.move(x, betaBeforeRelease.y + betaBeforeRelease.height / 2); + await expect + .poll(async () => (await betaFolder.boundingBox())?.y ?? betaBeforeRelease.y) + .toBeLessThan(betaBeforeRelease.y); + // Release in the gap while dnd-kit still holds the previous hover target. + await browser.evaluate( + ({ x, y }) => + document.dispatchEvent( + new PointerEvent("pointerup", { pointerId: 1, clientX: x, clientY: y }), + ), + { x, y: releaseGapY }, + ); + await browser.mouse.up(); + await browser.reload(); + await expect.poll(alphaComesFirst).toBe(true); + }, +); From 7d1499b1cf620c3d6a9d3dee0173f9afca3ca1ce Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:37:39 +0000 Subject: [PATCH 2/2] fix(web): keep folder header cursor and skip exiting rows on drag release The folder header keeps its pointer cursor like the draggable thread rows, and release() again ignores rows that are fading out. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/Sidebar.motion.ts | 4 ++-- apps/web/src/components/sidebar/SidebarProjectFolder.tsx | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index 22850d66bdac2..846d05eff6eb8 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -27,7 +27,7 @@ export function forEachSidebarListRow( } } -/** Folder rows are positioned relative to their sortable wrapper. */ +/** Position the list and each folder group so a row's offsets plus its folder's share an origin. */ export function createSidebarListMotion(parent: HTMLUListElement) { let positions: Map | null = null; let disposed = false; @@ -252,7 +252,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const origin = parent.getBoundingClientRect().top; const tops = new Map(); forEachSidebarListRow(parent, (node) => { - tops.set(node, node.getBoundingClientRect().top - origin); + if (!exiting.has(node)) tops.set(node, node.getBoundingClientRect().top - origin); }); released = tops; }, diff --git a/apps/web/src/components/sidebar/SidebarProjectFolder.tsx b/apps/web/src/components/sidebar/SidebarProjectFolder.tsx index 29a18e99e5478..c0df75526660a 100644 --- a/apps/web/src/components/sidebar/SidebarProjectFolder.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectFolder.tsx @@ -98,8 +98,7 @@ export const SidebarProjectFolder = memo(function SidebarProjectFolder(props: { ); }} className={cn( - "flex h-8 w-full items-center gap-2.5 rounded-(--control-radius) px-(--sidebar-row-content-inset) text-left outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", - props.sortableDisabled ? "cursor-pointer" : "cursor-grab active:cursor-grabbing", + "flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-(--control-radius) px-(--sidebar-row-content-inset) text-left outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", isDragging && "bg-sidebar-row-active", )} >