Squashed commits (#2417)
- fix: tighten workspace manual drag ordering - feat: allow manual sidebar workspace ordering
This commit is contained in:
@@ -195,6 +195,7 @@ export function mergeWorktree(
|
||||
isUnread: meta?.isUnread ?? false,
|
||||
isPinned: meta?.isPinned ?? false,
|
||||
sortOrder: meta?.sortOrder ?? 0,
|
||||
...(meta?.manualOrder !== undefined ? { manualOrder: meta.manualOrder } : {}),
|
||||
lastActivityAt: meta?.lastActivityAt ?? 0,
|
||||
...(meta?.createdAt !== undefined ? { createdAt: meta.createdAt } : {}),
|
||||
...(meta?.createdWithAgent !== undefined ? { createdWithAgent: meta.createdWithAgent } : {}),
|
||||
|
||||
@@ -811,6 +811,7 @@ export async function createRemoteWorktree(
|
||||
...(args.linkedIssue !== undefined ? { linkedIssue: args.linkedIssue } : {}),
|
||||
...(args.linkedPR !== undefined ? { linkedPR: args.linkedPR } : {}),
|
||||
...(args.linkedLinearIssue !== undefined ? { linkedLinearIssue: args.linkedLinearIssue } : {}),
|
||||
...(args.manualOrder !== undefined ? { manualOrder: args.manualOrder } : {}),
|
||||
...(args.workspaceStatus !== undefined ? { workspaceStatus: args.workspaceStatus } : {})
|
||||
}
|
||||
const meta = store.setWorktreeMeta(worktreeId, metaUpdates)
|
||||
@@ -1155,6 +1156,7 @@ export async function createLocalWorktree(
|
||||
...(args.linkedIssue !== undefined ? { linkedIssue: args.linkedIssue } : {}),
|
||||
...(args.linkedPR !== undefined ? { linkedPR: args.linkedPR } : {}),
|
||||
...(args.linkedLinearIssue !== undefined ? { linkedLinearIssue: args.linkedLinearIssue } : {}),
|
||||
...(args.manualOrder !== undefined ? { manualOrder: args.manualOrder } : {}),
|
||||
...(args.workspaceStatus !== undefined ? { workspaceStatus: args.workspaceStatus } : {})
|
||||
}
|
||||
const meta = store.setWorktreeMeta(worktreeId, metaUpdates)
|
||||
|
||||
@@ -566,7 +566,8 @@ describe('registerWorktreeHandlers', () => {
|
||||
name: 'improve-dashboard',
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
linkedLinearIssue: 'ENG-123'
|
||||
linkedLinearIssue: 'ENG-123',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
|
||||
expect(store.setWorktreeMeta).toHaveBeenCalledWith(
|
||||
@@ -574,14 +575,16 @@ describe('registerWorktreeHandlers', () => {
|
||||
expect.objectContaining({
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
linkedLinearIssue: 'ENG-123'
|
||||
linkedLinearIssue: 'ENG-123',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
)
|
||||
expect(result).toEqual({
|
||||
worktree: expect.objectContaining({
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
linkedLinearIssue: 'ENG-123'
|
||||
linkedLinearIssue: 'ENG-123',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -894,7 +897,8 @@ describe('registerWorktreeHandlers', () => {
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
createdWithAgent: 'codex',
|
||||
linkedLinearIssue: 'ENG-123'
|
||||
linkedLinearIssue: 'ENG-123',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
|
||||
expect(store.setWorktreeMeta).toHaveBeenCalledWith(
|
||||
@@ -903,7 +907,8 @@ describe('registerWorktreeHandlers', () => {
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
createdWithAgent: 'codex',
|
||||
linkedLinearIssue: 'ENG-123'
|
||||
linkedLinearIssue: 'ENG-123',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
)
|
||||
expect(result).toEqual({
|
||||
@@ -911,7 +916,8 @@ describe('registerWorktreeHandlers', () => {
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
createdWithAgent: 'codex',
|
||||
linkedLinearIssue: 'ENG-123'
|
||||
linkedLinearIssue: 'ENG-123',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -178,8 +178,14 @@ function normalizeGroupBy(groupBy: unknown): PersistedState['ui']['groupBy'] {
|
||||
return getDefaultUIState().groupBy
|
||||
}
|
||||
|
||||
function normalizeSortBy(sortBy: unknown): 'name' | 'smart' | 'recent' | 'repo' {
|
||||
if (sortBy === 'smart' || sortBy === 'recent' || sortBy === 'repo' || sortBy === 'name') {
|
||||
function normalizeSortBy(sortBy: unknown): PersistedState['ui']['sortBy'] {
|
||||
if (
|
||||
sortBy === 'smart' ||
|
||||
sortBy === 'recent' ||
|
||||
sortBy === 'repo' ||
|
||||
sortBy === 'name' ||
|
||||
sortBy === 'manual'
|
||||
) {
|
||||
return sortBy
|
||||
}
|
||||
return getDefaultUIState().sortBy
|
||||
|
||||
@@ -5876,6 +5876,7 @@ export class OrcaRuntimeService {
|
||||
comment?: string
|
||||
displayName?: string
|
||||
workspaceStatus?: string
|
||||
manualOrder?: number
|
||||
sparseCheckout?: { directories: string[]; presetId?: string }
|
||||
pushTarget?: GitPushTarget
|
||||
runHooks?: boolean
|
||||
@@ -6066,6 +6067,7 @@ export class OrcaRuntimeService {
|
||||
: {}),
|
||||
...(args.createdWithAgent ? { createdWithAgent: args.createdWithAgent } : {}),
|
||||
...(args.comment !== undefined ? { comment: args.comment } : {}),
|
||||
...(args.manualOrder !== undefined ? { manualOrder: args.manualOrder } : {}),
|
||||
...(args.workspaceStatus !== undefined ? { workspaceStatus: args.workspaceStatus } : {})
|
||||
})
|
||||
const worktree = mergeWorktree(repo.id, created, meta)
|
||||
@@ -6266,6 +6268,7 @@ export class OrcaRuntimeService {
|
||||
comment?: string
|
||||
displayName?: string
|
||||
workspaceStatus?: string
|
||||
manualOrder?: number
|
||||
sparseCheckout?: { directories: string[]; presetId?: string }
|
||||
pushTarget?: GitPushTarget
|
||||
runHooks?: boolean
|
||||
@@ -6301,6 +6304,7 @@ export class OrcaRuntimeService {
|
||||
...(args.linkedLinearIssue ? { linkedLinearIssue: args.linkedLinearIssue } : {}),
|
||||
...(args.pushTarget ? { pushTarget: args.pushTarget } : {}),
|
||||
...(args.workspaceStatus ? { workspaceStatus: args.workspaceStatus as never } : {}),
|
||||
...(args.manualOrder !== undefined ? { manualOrder: args.manualOrder } : {}),
|
||||
...(args.createdWithAgent ? { createdWithAgent: args.createdWithAgent } : {})
|
||||
},
|
||||
repo,
|
||||
|
||||
@@ -53,7 +53,7 @@ const UiUpdate = z
|
||||
rightSidebarWidth: z.number().finite().optional(),
|
||||
groupBy: z.enum(['none', 'workspace-status', 'repo', 'pr-status']).optional(),
|
||||
showWorkspaceLineage: z.boolean().optional(),
|
||||
sortBy: z.enum(['name', 'smart', 'recent', 'repo']).optional(),
|
||||
sortBy: z.enum(['name', 'smart', 'recent', 'repo', 'manual']).optional(),
|
||||
showActiveOnly: z.boolean().optional(),
|
||||
showSleepingWorkspaces: z.boolean().optional(),
|
||||
showInactiveWorkspaces: z.boolean().optional(),
|
||||
|
||||
@@ -25,6 +25,7 @@ describe('worktree RPC methods', () => {
|
||||
setupDecision: 'skip',
|
||||
displayName: 'Feature title',
|
||||
workspaceStatus: 'in-review',
|
||||
manualOrder: 123_456,
|
||||
linkedIssue: 123,
|
||||
linkedPR: 456,
|
||||
sparseCheckout: { directories: ['src'], presetId: 'preset-1' },
|
||||
@@ -44,6 +45,7 @@ describe('worktree RPC methods', () => {
|
||||
comment: undefined,
|
||||
displayName: 'Feature title',
|
||||
workspaceStatus: 'in-review',
|
||||
manualOrder: 123_456,
|
||||
sparseCheckout: { directories: ['src'], presetId: 'preset-1' },
|
||||
pushTarget: { remoteName: 'fork', branchName: 'feature' },
|
||||
runHooks: false,
|
||||
|
||||
@@ -44,6 +44,7 @@ const WorktreeCreate = z
|
||||
comment: OptionalString,
|
||||
displayName: OptionalString,
|
||||
workspaceStatus: OptionalString,
|
||||
manualOrder: OptionalFiniteNumber,
|
||||
sparseCheckout: z
|
||||
.object({
|
||||
directories: z.array(z.string()),
|
||||
@@ -107,6 +108,7 @@ const WorktreeSet = WorktreeSelector.extend({
|
||||
isUnread: OptionalBoolean,
|
||||
isPinned: OptionalBoolean,
|
||||
sortOrder: OptionalFiniteNumber,
|
||||
manualOrder: OptionalFiniteNumber,
|
||||
lastActivityAt: OptionalFiniteNumber,
|
||||
createdAt: OptionalFiniteNumber,
|
||||
sparseDirectories: z.array(z.string()).optional(),
|
||||
@@ -199,6 +201,7 @@ export const WORKTREE_METHODS: RpcMethod[] = [
|
||||
comment: params.comment,
|
||||
displayName: params.displayName,
|
||||
workspaceStatus: params.workspaceStatus,
|
||||
manualOrder: params.manualOrder,
|
||||
sparseCheckout: params.sparseCheckout,
|
||||
pushTarget: params.pushTarget,
|
||||
runHooks: params.runHooks === true,
|
||||
@@ -229,6 +232,7 @@ export const WORKTREE_METHODS: RpcMethod[] = [
|
||||
isUnread: params.isUnread,
|
||||
isPinned: params.isPinned,
|
||||
sortOrder: params.sortOrder,
|
||||
manualOrder: params.manualOrder,
|
||||
lastActivityAt: params.lastActivityAt,
|
||||
createdAt: params.createdAt,
|
||||
sparseDirectories: params.sparseDirectories,
|
||||
|
||||
@@ -919,6 +919,72 @@
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
|
||||
[data-worktree-sidebar-drag-preview='true'] {
|
||||
z-index: 2147483000;
|
||||
overflow: visible;
|
||||
border-radius: var(--radius);
|
||||
opacity: 0.96;
|
||||
filter: drop-shadow(0 10px 24px color-mix(in srgb, var(--foreground) 18%, transparent));
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
[data-worktree-sidebar-drag-preview='true'] * {
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
|
||||
[data-worktree-sidebar-drag-count='true'] {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: 8px;
|
||||
display: inline-flex;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9999px;
|
||||
background: var(--sidebar-ring);
|
||||
color: var(--sidebar);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 0 0 2px var(--sidebar);
|
||||
}
|
||||
|
||||
[data-workspace-board-card-drop-indicator='true'] {
|
||||
z-index: 2147483646;
|
||||
height: 3px;
|
||||
border-radius: 9999px;
|
||||
background: var(--sidebar-ring);
|
||||
box-shadow:
|
||||
0 0 0 1px color-mix(in srgb, var(--sidebar-ring) 24%, transparent),
|
||||
0 8px 20px color-mix(in srgb, var(--sidebar-ring) 36%, transparent);
|
||||
opacity: 0;
|
||||
transition:
|
||||
transform 120ms cubic-bezier(0.2, 0.8, 0.2, 1),
|
||||
width 120ms cubic-bezier(0.2, 0.8, 0.2, 1),
|
||||
opacity 80ms ease-out;
|
||||
will-change: transform, width, opacity;
|
||||
}
|
||||
|
||||
[data-workspace-board-card-drop-indicator='true']::before,
|
||||
[data-workspace-board-card-drop-indicator='true']::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 9999px;
|
||||
background: var(--sidebar-ring);
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
[data-workspace-board-card-drop-indicator='true']::before {
|
||||
left: -1px;
|
||||
}
|
||||
|
||||
[data-workspace-board-card-drop-indicator='true']::after {
|
||||
right: -1px;
|
||||
}
|
||||
|
||||
[data-workspace-board-card-drag-count='true'] {
|
||||
position: absolute;
|
||||
top: -8px;
|
||||
|
||||
@@ -48,7 +48,12 @@ const SORT_OPTIONS = [
|
||||
description: 'Agents that need attention, then most recent activity.'
|
||||
},
|
||||
{ id: 'recent', label: 'Recent', description: null },
|
||||
{ id: 'repo', label: 'Repo', description: null }
|
||||
{ id: 'repo', label: 'Repo', description: null },
|
||||
{
|
||||
id: 'manual',
|
||||
label: 'Manual',
|
||||
description: 'Drag workspaces to arrange them within each group.'
|
||||
}
|
||||
] as const
|
||||
|
||||
const SidebarWorkspaceOptionsMenu = React.memo(function SidebarWorkspaceOptionsMenu({
|
||||
|
||||
@@ -25,7 +25,12 @@ import {
|
||||
} from './use-workspace-kanban-outside-dismiss'
|
||||
import { useVisibleWorkspaceKanbanWorktreeIds } from './use-visible-workspace-kanban-worktree-ids'
|
||||
import { groupWorkspaceKanbanWorktrees } from './workspace-kanban-worktree-groups'
|
||||
import type { WorkspaceStatus } from '../../../../shared/types'
|
||||
import {
|
||||
buildManualOrderUpdatesForGroupDrop,
|
||||
shouldWriteManualOrderForGroupDrop,
|
||||
type WorktreeDragGroup
|
||||
} from './worktree-manual-order'
|
||||
import type { WorkspaceStatus, WorktreeMeta } from '../../../../shared/types'
|
||||
import { makeWorkspaceStatusId } from '../../../../shared/workspace-statuses'
|
||||
|
||||
type WorkspaceKanbanDrawerProps = {
|
||||
@@ -52,6 +57,8 @@ export default function WorkspaceKanbanDrawer({
|
||||
const setWorkspaceBoardCompact = useAppStore((s) => s.setWorkspaceBoardCompact)
|
||||
const workspaceBoardColumnWidth = useAppStore((s) => s.workspaceBoardColumnWidth)
|
||||
const setWorkspaceBoardColumnWidth = useAppStore((s) => s.setWorkspaceBoardColumnWidth)
|
||||
const sortBy = useAppStore((s) => s.sortBy)
|
||||
const setSortBy = useAppStore((s) => s.setSortBy)
|
||||
const sidebarOpen = useAppStore((s) => s.sidebarOpen)
|
||||
const sidebarWidth = useAppStore((s) => s.sidebarWidth)
|
||||
const boardRef = useRef<HTMLDivElement>(null)
|
||||
@@ -68,9 +75,10 @@ export default function WorkspaceKanbanDrawer({
|
||||
return groupWorkspaceKanbanWorktrees({
|
||||
worktrees: allWorktrees,
|
||||
visibleWorktreeIds: visibleWorktreeIdSet,
|
||||
workspaceStatuses
|
||||
workspaceStatuses,
|
||||
sortBy
|
||||
})
|
||||
}, [allWorktrees, visibleWorktreeIdSet, workspaceStatuses])
|
||||
}, [allWorktrees, sortBy, visibleWorktreeIdSet, workspaceStatuses])
|
||||
const worktreeById = useMemo(
|
||||
() => new Map(allWorktrees.map((worktree) => [worktree.id, worktree])),
|
||||
[allWorktrees]
|
||||
@@ -79,6 +87,14 @@ export default function WorkspaceKanbanDrawer({
|
||||
() => workspaceStatuses.flatMap((status) => worktreesByStatus.get(status.id) ?? []),
|
||||
[worktreesByStatus, workspaceStatuses]
|
||||
)
|
||||
const boardDragGroups = useMemo<WorktreeDragGroup[]>(
|
||||
() =>
|
||||
workspaceStatuses.map((status) => ({
|
||||
key: status.id,
|
||||
worktreeIds: (worktreesByStatus.get(status.id) ?? []).map((worktree) => worktree.id)
|
||||
})),
|
||||
[worktreesByStatus, workspaceStatuses]
|
||||
)
|
||||
const {
|
||||
selectedWorktreeIds,
|
||||
selectedWorktrees,
|
||||
@@ -108,21 +124,103 @@ export default function WorkspaceKanbanDrawer({
|
||||
},
|
||||
[updateWorktreeMeta, workspaceStatuses, worktreeById]
|
||||
)
|
||||
const moveWorktreesToStatus = useCallback(
|
||||
(worktreeIds: readonly string[], status: WorkspaceStatus) => {
|
||||
const updates = new Map<string, { workspaceStatus: WorkspaceStatus }>()
|
||||
for (const worktreeId of worktreeIds) {
|
||||
const getSourceStatusKeys = useCallback(
|
||||
(worktreeIds: readonly string[]): WorkspaceStatus[] =>
|
||||
worktreeIds.flatMap((worktreeId) => {
|
||||
const worktree = worktreeById.get(worktreeId)
|
||||
return worktree ? [getWorkspaceStatus(worktree, workspaceStatuses)] : []
|
||||
}),
|
||||
[workspaceStatuses, worktreeById]
|
||||
)
|
||||
const shouldWriteDropManualOrder = useCallback(
|
||||
(worktreeIds: readonly string[], status: WorkspaceStatus): boolean =>
|
||||
shouldWriteManualOrderForGroupDrop({
|
||||
sortBy,
|
||||
sourceGroupKeys: getSourceStatusKeys(worktreeIds),
|
||||
targetGroupKey: status
|
||||
}),
|
||||
[getSourceStatusKeys, sortBy]
|
||||
)
|
||||
const dropWorktreesInStatus = useCallback(
|
||||
(args: {
|
||||
worktreeIds: readonly string[]
|
||||
status: WorkspaceStatus
|
||||
dropIndex: number
|
||||
writeManualOrder?: boolean
|
||||
}) => {
|
||||
const updates = new Map<string, Partial<WorktreeMeta>>()
|
||||
const writeManualOrder =
|
||||
args.writeManualOrder ?? shouldWriteDropManualOrder(args.worktreeIds, args.status)
|
||||
const rankByWorktreeId = writeManualOrder
|
||||
? (() => {
|
||||
const ranks = new Map<string, number>()
|
||||
for (const group of boardDragGroups) {
|
||||
for (const worktreeId of group.worktreeIds) {
|
||||
const worktree = worktreeById.get(worktreeId)
|
||||
if (worktree) {
|
||||
ranks.set(worktreeId, worktree.manualOrder ?? worktree.sortOrder)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ranks
|
||||
})()
|
||||
: undefined
|
||||
const order = writeManualOrder
|
||||
? buildManualOrderUpdatesForGroupDrop({
|
||||
groups: boardDragGroups,
|
||||
targetGroupKey: args.status,
|
||||
draggedIds: args.worktreeIds,
|
||||
dropIndex: args.dropIndex,
|
||||
now: Date.now(),
|
||||
rankByWorktreeId
|
||||
})
|
||||
: { changed: false, updates: new Map<string, { manualOrder: number }>() }
|
||||
|
||||
for (const worktreeId of args.worktreeIds) {
|
||||
const current = worktreeById.get(worktreeId)
|
||||
if (!current || getWorkspaceStatus(current, workspaceStatuses) === status) {
|
||||
if (!current) {
|
||||
continue
|
||||
}
|
||||
updates.set(worktreeId, { workspaceStatus: status })
|
||||
const next = updates.get(worktreeId) ?? {}
|
||||
if (getWorkspaceStatus(current, workspaceStatuses) !== args.status) {
|
||||
next.workspaceStatus = args.status
|
||||
}
|
||||
updates.set(worktreeId, next)
|
||||
}
|
||||
if (updates.size > 0) {
|
||||
void updateWorktreesMeta(updates)
|
||||
|
||||
if (writeManualOrder) {
|
||||
for (const [worktreeId, manualOrder] of order.updates) {
|
||||
const currentUpdate = updates.get(worktreeId)
|
||||
updates.set(
|
||||
worktreeId,
|
||||
currentUpdate ? { ...currentUpdate, ...manualOrder } : manualOrder
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [worktreeId, update] of Array.from(updates)) {
|
||||
if (Object.keys(update).length === 0) {
|
||||
updates.delete(worktreeId)
|
||||
}
|
||||
}
|
||||
if (updates.size === 0) {
|
||||
return
|
||||
}
|
||||
// Why: cross-lane drops in a derived sort are usually just status moves.
|
||||
// Only explicit rank gestures should fork the board/sidebar into Manual.
|
||||
if (writeManualOrder && order.changed) {
|
||||
setSortBy('manual')
|
||||
}
|
||||
void updateWorktreesMeta(updates)
|
||||
},
|
||||
[updateWorktreesMeta, workspaceStatuses, worktreeById]
|
||||
[
|
||||
boardDragGroups,
|
||||
setSortBy,
|
||||
shouldWriteDropManualOrder,
|
||||
updateWorktreesMeta,
|
||||
workspaceStatuses,
|
||||
worktreeById
|
||||
]
|
||||
)
|
||||
const pinWorktree = useCallback(
|
||||
(worktreeId: string) => {
|
||||
@@ -156,9 +254,10 @@ export default function WorkspaceKanbanDrawer({
|
||||
boardRef,
|
||||
selectedWorktreeIds,
|
||||
selectedWorktrees,
|
||||
onMoveWorktreesToStatus: moveWorktreesToStatus,
|
||||
onDropWorktreesInStatus: dropWorktreesInStatus,
|
||||
onPinWorktrees: pinWorktrees,
|
||||
onDragTargetChange: setDragOverStatus,
|
||||
onShouldShowDropIndicator: shouldWriteDropManualOrder,
|
||||
onPinDragTargetChange: setPinDragOver
|
||||
})
|
||||
const handleDragOver = useCallback((event: React.DragEvent, status: WorkspaceStatus) => {
|
||||
@@ -200,6 +299,18 @@ export default function WorkspaceKanbanDrawer({
|
||||
setPinDragOver(false)
|
||||
}, [])
|
||||
|
||||
const dropWorktreesAtEndOfStatus = useCallback(
|
||||
(worktreeIds: readonly string[], status: WorkspaceStatus) => {
|
||||
dropWorktreesInStatus({
|
||||
worktreeIds,
|
||||
status,
|
||||
dropIndex: worktreesByStatus.get(status)?.length ?? 0,
|
||||
writeManualOrder: sortBy === 'manual'
|
||||
})
|
||||
},
|
||||
[dropWorktreesInStatus, sortBy, worktreesByStatus]
|
||||
)
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(event: React.DragEvent, status: WorkspaceStatus) => {
|
||||
const worktreeIds = readWorkspaceDragDataIds(event.dataTransfer)
|
||||
@@ -208,9 +319,9 @@ export default function WorkspaceKanbanDrawer({
|
||||
}
|
||||
event.preventDefault()
|
||||
setDragOverStatus(null)
|
||||
moveWorktreesToStatus(worktreeIds, status)
|
||||
dropWorktreesAtEndOfStatus(worktreeIds, status)
|
||||
},
|
||||
[moveWorktreesToStatus]
|
||||
[dropWorktreesAtEndOfStatus]
|
||||
)
|
||||
|
||||
const handleWorktreeActivate = useCallback(() => {
|
||||
@@ -301,7 +412,7 @@ export default function WorkspaceKanbanDrawer({
|
||||
handleDragFinish,
|
||||
open,
|
||||
{
|
||||
onMoveWorktreesToStatus: moveWorktreesToStatus,
|
||||
onMoveWorktreesToStatus: dropWorktreesAtEndOfStatus,
|
||||
onPinWorktrees: pinWorktrees
|
||||
}
|
||||
)
|
||||
|
||||
@@ -58,6 +58,12 @@ type WorktreeCardProps = {
|
||||
onActivate?: () => void
|
||||
onSelectionGesture?: (event: React.MouseEvent<HTMLElement>, worktreeId: string) => boolean
|
||||
onContextMenuSelect?: (event: React.MouseEvent<HTMLElement>) => readonly Worktree[]
|
||||
onCardDragStart?: (
|
||||
event: React.DragEvent<HTMLDivElement>,
|
||||
worktreeId: string,
|
||||
draggedIds: readonly string[]
|
||||
) => void
|
||||
onCardDragEnd?: (event: React.DragEvent<HTMLDivElement>) => void
|
||||
nativeDragEnabled?: boolean
|
||||
}
|
||||
|
||||
@@ -82,6 +88,8 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
onActivate,
|
||||
onSelectionGesture,
|
||||
onContextMenuSelect,
|
||||
onCardDragStart,
|
||||
onCardDragEnd,
|
||||
nativeDragEnabled = true,
|
||||
hideRepoBadge,
|
||||
lineageChildCount = 0,
|
||||
@@ -378,8 +386,9 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
? selectedWorktrees.map((item) => item.id)
|
||||
: worktree.id
|
||||
writeWorkspaceDragData(event.dataTransfer, dragIds)
|
||||
onCardDragStart?.(event, worktree.id, Array.isArray(dragIds) ? dragIds : [dragIds])
|
||||
},
|
||||
[isDeleting, isMultiSelected, selectedWorktrees, worktree.id]
|
||||
[isDeleting, isMultiSelected, onCardDragStart, selectedWorktrees, worktree.id]
|
||||
)
|
||||
|
||||
const stopQuickActionPointerPropagation = useCallback(
|
||||
@@ -481,6 +490,7 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
onDoubleClick={handleDoubleClick}
|
||||
draggable={nativeDragEnabled && !isDeleting}
|
||||
onDragStart={nativeDragEnabled ? handleDragStart : undefined}
|
||||
onDragEnd={nativeDragEnabled ? onCardDragEnd : undefined}
|
||||
aria-busy={isDeleting}
|
||||
>
|
||||
{isDeleting && (
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
type RepoGroupOrdering,
|
||||
type Row,
|
||||
type WorktreeGroupBy,
|
||||
ALL_GROUP_KEY,
|
||||
PINNED_GROUP_KEY,
|
||||
buildRows,
|
||||
getGroupKeyForWorktree,
|
||||
@@ -82,6 +83,22 @@ import {
|
||||
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
import { useRepoHeaderDrag } from './repo-header-drag'
|
||||
import WorktreeContextMenu from './WorktreeContextMenu'
|
||||
import {
|
||||
buildWorktreeDragPreviewOffsets,
|
||||
buildManualOrderUpdatesForVisibleGroups,
|
||||
expandDraggedWorktreeIdsForVisibleLineage,
|
||||
type WorktreeDragGroup
|
||||
} from './worktree-manual-order'
|
||||
import {
|
||||
getFullDropIndexForWorktreeDragUnit,
|
||||
getWorktreeDragUnitGroups
|
||||
} from './worktree-drag-units'
|
||||
import {
|
||||
createSidebarDragPreview,
|
||||
isSidebarPointerDragBlocked,
|
||||
setSidebarPointerDragDocumentStyles,
|
||||
updateSidebarDragPreviewPosition
|
||||
} from './worktree-sidebar-pointer-drag-dom'
|
||||
import {
|
||||
areWorktreeSelectionsEqual,
|
||||
getWorktreeSelectionIntent,
|
||||
@@ -158,6 +175,7 @@ function getWorktreeOptionId(worktreeId: string): string {
|
||||
}
|
||||
|
||||
const LINEAGE_INDENT = 18
|
||||
const SIDEBAR_POINTER_DRAG_THRESHOLD_PX = 4
|
||||
|
||||
type VirtualizedWorktreeViewportProps = {
|
||||
rows: Row[]
|
||||
@@ -195,6 +213,12 @@ type VirtualizedWorktreeViewportProps = {
|
||||
onMoveWorktreesToStatus: (worktreeIds: readonly string[], status: WorkspaceStatus) => void
|
||||
onPinWorktree: (worktreeId: string) => void
|
||||
onPinWorktrees: (worktreeIds: readonly string[]) => void
|
||||
onReorderWorktrees: (args: {
|
||||
groups: readonly WorktreeDragGroup[]
|
||||
sourceGroupKey: string
|
||||
draggedIds: readonly string[]
|
||||
dropIndex: number
|
||||
}) => void
|
||||
showInlineAgentCards: boolean
|
||||
// Why: broad grouping changes still remount the viewport, while add/delete
|
||||
// stays mounted for row-key anchoring and layout animation. These refs bridge
|
||||
@@ -205,6 +229,141 @@ type VirtualizedWorktreeViewportProps = {
|
||||
|
||||
type WorktreeItemRow = Extract<Row, { type: 'item' }>
|
||||
|
||||
type WorktreeRowDragState = {
|
||||
draggingWorktreeId: string | null
|
||||
sourceGroupKey: string | null
|
||||
dropIndex: number | null
|
||||
dropIndicatorY: number | null
|
||||
previewOffsetsByWorktreeId: ReadonlyMap<string, number>
|
||||
pointerY: number | null
|
||||
}
|
||||
|
||||
const EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS: ReadonlyMap<string, number> = new Map()
|
||||
|
||||
const WORKTREE_ROW_DRAG_INITIAL_STATE: WorktreeRowDragState = {
|
||||
draggingWorktreeId: null,
|
||||
sourceGroupKey: null,
|
||||
dropIndex: null,
|
||||
dropIndicatorY: null,
|
||||
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
|
||||
pointerY: null
|
||||
}
|
||||
|
||||
type WorktreeDragRect = {
|
||||
worktreeId: string
|
||||
groupIndex: number
|
||||
top: number
|
||||
bottom: number
|
||||
}
|
||||
|
||||
type WorktreeDragSession = {
|
||||
draggingWorktreeId: string
|
||||
sourceGroupKey: string
|
||||
draggedIds: readonly string[]
|
||||
reorderDraggedIds: readonly string[]
|
||||
reorderUnitDraggedIds: readonly string[]
|
||||
rects: readonly WorktreeDragRect[]
|
||||
}
|
||||
|
||||
type WorktreePointerDrag = {
|
||||
pointerId: number
|
||||
sourceRow: HTMLElement
|
||||
startX: number
|
||||
startY: number
|
||||
currentX: number
|
||||
currentY: number
|
||||
worktreeId: string
|
||||
draggedIds: readonly string[]
|
||||
reorderDraggedIds: readonly string[]
|
||||
reorderUnitDraggedIds: readonly string[]
|
||||
sourceGroupKey: string
|
||||
rects: readonly WorktreeDragRect[]
|
||||
active: boolean
|
||||
preview: HTMLElement | null
|
||||
previewOffsetX: number
|
||||
previewOffsetY: number
|
||||
frameId: number | null
|
||||
}
|
||||
|
||||
type WorktreeDropPreview = {
|
||||
dropIndex: number
|
||||
dropIndicatorY: number
|
||||
previewOffsetsByWorktreeId: ReadonlyMap<string, number>
|
||||
}
|
||||
|
||||
function areWorktreeDragPreviewOffsetsEqual(
|
||||
a: ReadonlyMap<string, number>,
|
||||
b: ReadonlyMap<string, number>
|
||||
): boolean {
|
||||
if (a === b) {
|
||||
return true
|
||||
}
|
||||
if (a.size !== b.size) {
|
||||
return false
|
||||
}
|
||||
for (const [key, value] of a) {
|
||||
if (b.get(key) !== value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function getWorktreeVirtualRowTransform(start: number, previewOffset: number): string {
|
||||
const base = getVirtualRowTransform(start)
|
||||
return previewOffset === 0 ? base : `${base} translateY(${previewOffset}px)`
|
||||
}
|
||||
|
||||
function getWorktreeDragRectsForGroup(
|
||||
container: HTMLElement,
|
||||
groupKey: string
|
||||
): WorktreeDragRect[] {
|
||||
const containerRect = container.getBoundingClientRect()
|
||||
const rects: WorktreeDragRect[] = []
|
||||
container.querySelectorAll<HTMLElement>('[data-worktree-drag-id]').forEach((element) => {
|
||||
if (element.getAttribute('data-worktree-drag-group-key') !== groupKey) {
|
||||
return
|
||||
}
|
||||
const worktreeId = element.getAttribute('data-worktree-drag-id')
|
||||
const rawGroupIndex = element.getAttribute('data-worktree-drag-group-index')
|
||||
const groupIndex = rawGroupIndex === null ? Number.NaN : Number(rawGroupIndex)
|
||||
if (!worktreeId || !Number.isFinite(groupIndex)) {
|
||||
return
|
||||
}
|
||||
const rect = element.getBoundingClientRect()
|
||||
rects.push({
|
||||
worktreeId,
|
||||
groupIndex,
|
||||
top: rect.top - containerRect.top + container.scrollTop,
|
||||
bottom: rect.bottom - containerRect.top + container.scrollTop
|
||||
})
|
||||
})
|
||||
rects.sort((a, b) => a.top - b.top)
|
||||
return rects
|
||||
}
|
||||
|
||||
function getPointerDropStatusTarget(args: { container: HTMLElement; x: number; y: number }): {
|
||||
status: WorkspaceStatus | null
|
||||
isPinDrop: boolean
|
||||
} {
|
||||
const target = document.elementFromPoint(args.x, args.y)
|
||||
if (!(target instanceof Element) || !args.container.contains(target)) {
|
||||
return { status: null, isPinDrop: false }
|
||||
}
|
||||
const pinTarget = target.closest<HTMLElement>('[data-workspace-pin-drop-target]')
|
||||
if (pinTarget && args.container.contains(pinTarget)) {
|
||||
return { status: null, isPinDrop: true }
|
||||
}
|
||||
const statusTarget = target.closest<HTMLElement>('[data-workspace-status-drop-target]')
|
||||
return {
|
||||
status:
|
||||
statusTarget && args.container.contains(statusTarget)
|
||||
? ((statusTarget.dataset.workspaceStatus as WorkspaceStatus | undefined) ?? null)
|
||||
: null,
|
||||
isPinDrop: false
|
||||
}
|
||||
}
|
||||
|
||||
function isWorktreeItemRow(row: Row): row is WorktreeItemRow {
|
||||
return row.type === 'item'
|
||||
}
|
||||
@@ -264,6 +423,41 @@ function getRenderRowKey(row: RenderRow): string {
|
||||
return `wt:${row.worktree.id}`
|
||||
}
|
||||
|
||||
function getWorktreeDragGroups(rows: Row[]): WorktreeDragGroup[] {
|
||||
const groups: WorktreeDragGroup[] = []
|
||||
let current: { key: string; ids: string[] } | null = null
|
||||
|
||||
for (const row of rows) {
|
||||
if (row.type === 'header') {
|
||||
current = { key: row.key, ids: [] }
|
||||
groups.push({ key: current.key, worktreeIds: current.ids })
|
||||
continue
|
||||
}
|
||||
if (!current) {
|
||||
current = { key: ALL_GROUP_KEY, ids: [] }
|
||||
groups.push({ key: current.key, worktreeIds: current.ids })
|
||||
}
|
||||
current.ids.push(row.worktree.id)
|
||||
}
|
||||
|
||||
return groups.filter((group) => group.worktreeIds.length > 0)
|
||||
}
|
||||
|
||||
function getWorktreeDragIndexes(groups: readonly WorktreeDragGroup[]): {
|
||||
groupKeyByWorktreeId: Map<string, string>
|
||||
groupIndexByWorktreeId: Map<string, number>
|
||||
} {
|
||||
const groupKeyByWorktreeId = new Map<string, string>()
|
||||
const groupIndexByWorktreeId = new Map<string, number>()
|
||||
for (const group of groups) {
|
||||
group.worktreeIds.forEach((worktreeId, index) => {
|
||||
groupKeyByWorktreeId.set(worktreeId, group.key)
|
||||
groupIndexByWorktreeId.set(worktreeId, index)
|
||||
})
|
||||
}
|
||||
return { groupKeyByWorktreeId, groupIndexByWorktreeId }
|
||||
}
|
||||
|
||||
function getVirtualRowIndex(element: Element): number | null {
|
||||
const index = parseInt(element.getAttribute('data-index') ?? '', 10)
|
||||
return Number.isNaN(index) ? null : index
|
||||
@@ -302,6 +496,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
onMoveWorktreesToStatus,
|
||||
onPinWorktree,
|
||||
onPinWorktrees,
|
||||
onReorderWorktrees,
|
||||
showInlineAgentCards,
|
||||
scrollOffsetRef,
|
||||
scrollAnchorRef
|
||||
@@ -312,6 +507,12 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
const [dragOverStatus, setDragOverStatus] = useState<WorkspaceStatus | null>(null)
|
||||
const [pinDragOver, setPinDragOver] = useState(false)
|
||||
const [lineageReconnectWorktreeId, setLineageReconnectWorktreeId] = useState<string | null>(null)
|
||||
const [worktreeDragState, setWorktreeDragState] = useState<WorktreeRowDragState>(
|
||||
WORKTREE_ROW_DRAG_INITIAL_STATE
|
||||
)
|
||||
const worktreeDragSessionRef = useRef<WorktreeDragSession | null>(null)
|
||||
const worktreePointerDragRef = useRef<WorktreePointerDrag | null>(null)
|
||||
const suppressWorktreeClickUntilRef = useRef(0)
|
||||
const canReorderRepoHeaders = groupBy === 'repo' && repoGroupOrdering === 'manual'
|
||||
const lastVisibleRefreshKeyRef = useRef('')
|
||||
const reportVisibleGitHubPRRefreshCandidates = useAppStore(
|
||||
@@ -328,6 +529,83 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
onCommit: reorderRepos,
|
||||
getScrollContainer: () => scrollRef.current
|
||||
})
|
||||
const worktreeDragGroups = useMemo(() => getWorktreeDragGroups(rows), [rows])
|
||||
const worktreeDragUnitGroups = useMemo(() => getWorktreeDragUnitGroups(rows), [rows])
|
||||
const worktreeLineageDragRows = useMemo(
|
||||
() =>
|
||||
rows
|
||||
.filter((row): row is WorktreeItemRow => row.type === 'item')
|
||||
.map((row) => ({ worktreeId: row.worktree.id, depth: row.depth })),
|
||||
[rows]
|
||||
)
|
||||
const getReorderDraggedIds = useCallback(
|
||||
(draggedIds: readonly string[]) =>
|
||||
expandDraggedWorktreeIdsForVisibleLineage(worktreeLineageDragRows, draggedIds),
|
||||
[worktreeLineageDragRows]
|
||||
)
|
||||
const getReorderUnitDraggedIds = useCallback(
|
||||
(sourceGroupKey: string, reorderDraggedIds: readonly string[]) => {
|
||||
const group = worktreeDragUnitGroups.find((candidate) => candidate.key === sourceGroupKey)
|
||||
if (!group) {
|
||||
return reorderDraggedIds
|
||||
}
|
||||
const unitIds = new Set(group.worktreeIds)
|
||||
const filtered = reorderDraggedIds.filter((worktreeId) => unitIds.has(worktreeId))
|
||||
return filtered.length > 0 ? filtered : reorderDraggedIds
|
||||
},
|
||||
[worktreeDragUnitGroups]
|
||||
)
|
||||
const { groupKeyByWorktreeId, groupIndexByWorktreeId } = useMemo(
|
||||
() => getWorktreeDragIndexes(worktreeDragUnitGroups),
|
||||
[worktreeDragUnitGroups]
|
||||
)
|
||||
const computeWorktreeDrop = useCallback(
|
||||
(pointerY: number): WorktreeDropPreview | null => {
|
||||
const session = worktreeDragSessionRef.current
|
||||
const container = scrollRef.current
|
||||
if (!session || !container) {
|
||||
return null
|
||||
}
|
||||
|
||||
const containerRect = container.getBoundingClientRect()
|
||||
const localY = pointerY - containerRect.top + container.scrollTop
|
||||
const rects = session.rects
|
||||
if (rects.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const first = rects[0]!
|
||||
const last = rects.at(-1)!
|
||||
const BOUNDS_PADDING_PX = 8
|
||||
if (localY < first.top - BOUNDS_PADDING_PX || localY > last.bottom + BOUNDS_PADDING_PX) {
|
||||
return null
|
||||
}
|
||||
|
||||
let dropIndex = last.groupIndex + 1
|
||||
let indicatorY = last.bottom + 3
|
||||
for (const rect of rects) {
|
||||
const mid = (rect.top + rect.bottom) / 2
|
||||
if (localY < mid) {
|
||||
dropIndex = rect.groupIndex
|
||||
indicatorY = Math.max(0, rect.top - 3)
|
||||
break
|
||||
}
|
||||
}
|
||||
const sourceGroup = worktreeDragUnitGroups.find(
|
||||
(group) => group.key === session.sourceGroupKey
|
||||
)
|
||||
const previewOffsetsByWorktreeId = sourceGroup
|
||||
? buildWorktreeDragPreviewOffsets({
|
||||
groupIds: sourceGroup.worktreeIds,
|
||||
draggedIds: session.reorderUnitDraggedIds,
|
||||
dropIndex,
|
||||
rects
|
||||
})
|
||||
: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS
|
||||
return { dropIndex, dropIndicatorY: indicatorY, previewOffsetsByWorktreeId }
|
||||
},
|
||||
[worktreeDragUnitGroups]
|
||||
)
|
||||
const renderRows = useMemo(() => buildRenderableRows(rows), [rows])
|
||||
const firstHeaderIndex = useMemo(
|
||||
() => renderRows.findIndex((row) => row.type === 'header'),
|
||||
@@ -810,6 +1088,387 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
markScrollMovement()
|
||||
}, [markScrollMovement])
|
||||
|
||||
const cleanupWorktreePointerDrag = useCallback(() => {
|
||||
const drag = worktreePointerDragRef.current
|
||||
if (!drag) {
|
||||
return
|
||||
}
|
||||
if (drag.frameId !== null) {
|
||||
window.cancelAnimationFrame(drag.frameId)
|
||||
}
|
||||
drag.preview?.remove()
|
||||
worktreePointerDragRef.current = null
|
||||
setSidebarPointerDragDocumentStyles(false)
|
||||
setDragOverStatus(null)
|
||||
setPinDragOver(false)
|
||||
}, [])
|
||||
|
||||
const clearWorktreeDrag = useCallback(() => {
|
||||
cleanupWorktreePointerDrag()
|
||||
worktreeDragSessionRef.current = null
|
||||
setWorktreeDragState(WORKTREE_ROW_DRAG_INITIAL_STATE)
|
||||
}, [cleanupWorktreePointerDrag])
|
||||
|
||||
const flushWorktreePointerDrag = useCallback(() => {
|
||||
const drag = worktreePointerDragRef.current
|
||||
if (!drag) {
|
||||
return
|
||||
}
|
||||
drag.frameId = null
|
||||
if (!drag.active || !drag.preview) {
|
||||
return
|
||||
}
|
||||
updateSidebarDragPreviewPosition({
|
||||
preview: drag.preview,
|
||||
pointerX: drag.currentX,
|
||||
pointerY: drag.currentY,
|
||||
offsetX: drag.previewOffsetX,
|
||||
offsetY: drag.previewOffsetY
|
||||
})
|
||||
const drop = computeWorktreeDrop(drag.currentY)
|
||||
const sidebarContainer = scrollRef.current
|
||||
if (!drop) {
|
||||
const target = sidebarContainer
|
||||
? getPointerDropStatusTarget({
|
||||
container: sidebarContainer,
|
||||
x: drag.currentX,
|
||||
y: drag.currentY
|
||||
})
|
||||
: { status: null, isPinDrop: false }
|
||||
setDragOverStatus(target.status)
|
||||
setPinDragOver(target.isPinDrop)
|
||||
setWorktreeDragState((prev) =>
|
||||
prev.dropIndex === null &&
|
||||
prev.dropIndicatorY === null &&
|
||||
prev.pointerY === drag.currentY &&
|
||||
prev.previewOffsetsByWorktreeId.size === 0
|
||||
? prev
|
||||
: {
|
||||
...prev,
|
||||
dropIndex: null,
|
||||
dropIndicatorY: null,
|
||||
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
|
||||
pointerY: drag.currentY
|
||||
}
|
||||
)
|
||||
return
|
||||
}
|
||||
setDragOverStatus(null)
|
||||
setPinDragOver(false)
|
||||
setWorktreeDragState((prev) =>
|
||||
prev.dropIndex === drop.dropIndex &&
|
||||
prev.dropIndicatorY === drop.dropIndicatorY &&
|
||||
prev.pointerY === drag.currentY &&
|
||||
areWorktreeDragPreviewOffsetsEqual(
|
||||
prev.previewOffsetsByWorktreeId,
|
||||
drop.previewOffsetsByWorktreeId
|
||||
)
|
||||
? prev
|
||||
: { ...prev, ...drop, pointerY: drag.currentY }
|
||||
)
|
||||
}, [computeWorktreeDrop])
|
||||
|
||||
const scheduleWorktreePointerDragFrame = useCallback(
|
||||
(drag: WorktreePointerDrag) => {
|
||||
if (drag.frameId !== null) {
|
||||
return
|
||||
}
|
||||
drag.frameId = window.requestAnimationFrame(flushWorktreePointerDrag)
|
||||
},
|
||||
[flushWorktreePointerDrag]
|
||||
)
|
||||
|
||||
const beginWorktreePointerDrag = useCallback(
|
||||
(drag: WorktreePointerDrag) => {
|
||||
const { preview, offsetX, offsetY } = createSidebarDragPreview({
|
||||
sourceRow: drag.sourceRow,
|
||||
pointerX: drag.currentX,
|
||||
pointerY: drag.currentY,
|
||||
draggedCount: drag.draggedIds.length
|
||||
})
|
||||
drag.active = true
|
||||
drag.preview = preview
|
||||
drag.previewOffsetX = offsetX
|
||||
drag.previewOffsetY = offsetY
|
||||
suppressWorktreeClickUntilRef.current = window.performance.now() + 500
|
||||
setSidebarPointerDragDocumentStyles(true)
|
||||
worktreeDragSessionRef.current = {
|
||||
draggingWorktreeId: drag.worktreeId,
|
||||
sourceGroupKey: drag.sourceGroupKey,
|
||||
draggedIds: drag.draggedIds,
|
||||
reorderDraggedIds: drag.reorderDraggedIds,
|
||||
reorderUnitDraggedIds: drag.reorderUnitDraggedIds,
|
||||
rects: drag.rects
|
||||
}
|
||||
setWorktreeDragState({
|
||||
draggingWorktreeId: drag.worktreeId,
|
||||
sourceGroupKey: drag.sourceGroupKey,
|
||||
dropIndex: null,
|
||||
dropIndicatorY: null,
|
||||
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
|
||||
pointerY: drag.currentY
|
||||
})
|
||||
scheduleWorktreePointerDragFrame(drag)
|
||||
},
|
||||
[scheduleWorktreePointerDragFrame]
|
||||
)
|
||||
|
||||
const handleWorktreeRowPointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>, worktreeId: string) => {
|
||||
if (event.button !== 0 || event.pointerType === 'touch') {
|
||||
return
|
||||
}
|
||||
const sourceRow = event.currentTarget
|
||||
if (isSidebarPointerDragBlocked(event.target, sourceRow)) {
|
||||
return
|
||||
}
|
||||
const sourceGroupKey = groupKeyByWorktreeId.get(worktreeId)
|
||||
const container = scrollRef.current
|
||||
if (!sourceGroupKey || !container) {
|
||||
return
|
||||
}
|
||||
const rects = getWorktreeDragRectsForGroup(container, sourceGroupKey)
|
||||
if (rects.length <= 1) {
|
||||
return
|
||||
}
|
||||
const draggedIds =
|
||||
selectedWorktreeIds.has(worktreeId) && selectedWorktrees.length > 1
|
||||
? selectedWorktrees.map((worktree) => worktree.id)
|
||||
: [worktreeId]
|
||||
const reorderDraggedIds = getReorderDraggedIds(draggedIds)
|
||||
const reorderUnitDraggedIds = getReorderUnitDraggedIds(sourceGroupKey, reorderDraggedIds)
|
||||
worktreePointerDragRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
sourceRow,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
currentX: event.clientX,
|
||||
currentY: event.clientY,
|
||||
worktreeId,
|
||||
draggedIds,
|
||||
reorderDraggedIds,
|
||||
reorderUnitDraggedIds,
|
||||
sourceGroupKey,
|
||||
rects,
|
||||
active: false,
|
||||
preview: null,
|
||||
previewOffsetX: 0,
|
||||
previewOffsetY: 0,
|
||||
frameId: null
|
||||
}
|
||||
},
|
||||
[
|
||||
getReorderDraggedIds,
|
||||
getReorderUnitDraggedIds,
|
||||
groupKeyByWorktreeId,
|
||||
selectedWorktreeIds,
|
||||
selectedWorktrees
|
||||
]
|
||||
)
|
||||
|
||||
const handleWorktreeRowClickCapture = useCallback((event: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (window.performance.now() >= suppressWorktreeClickUntilRef.current) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerMove = (event: PointerEvent): void => {
|
||||
const drag = worktreePointerDragRef.current
|
||||
if (!drag || event.pointerId !== drag.pointerId) {
|
||||
return
|
||||
}
|
||||
drag.currentX = event.clientX
|
||||
drag.currentY = event.clientY
|
||||
if (!drag.active) {
|
||||
const distance = Math.hypot(drag.currentX - drag.startX, drag.currentY - drag.startY)
|
||||
if (distance < SIDEBAR_POINTER_DRAG_THRESHOLD_PX) {
|
||||
return
|
||||
}
|
||||
beginWorktreePointerDrag(drag)
|
||||
}
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
scheduleWorktreePointerDragFrame(drag)
|
||||
}
|
||||
|
||||
const handlePointerUp = (event: PointerEvent): void => {
|
||||
const drag = worktreePointerDragRef.current
|
||||
if (!drag || event.pointerId !== drag.pointerId) {
|
||||
return
|
||||
}
|
||||
drag.currentX = event.clientX
|
||||
drag.currentY = event.clientY
|
||||
if (!drag.active) {
|
||||
worktreePointerDragRef.current = null
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const drop = computeWorktreeDrop(event.clientY)
|
||||
const container = scrollRef.current
|
||||
if (drop) {
|
||||
onReorderWorktrees({
|
||||
groups: worktreeDragGroups,
|
||||
sourceGroupKey: drag.sourceGroupKey,
|
||||
draggedIds: drag.reorderDraggedIds,
|
||||
dropIndex: getFullDropIndexForWorktreeDragUnit({
|
||||
groups: worktreeDragUnitGroups,
|
||||
sourceGroupKey: drag.sourceGroupKey,
|
||||
dropIndex: drop.dropIndex
|
||||
})
|
||||
})
|
||||
} else if (container) {
|
||||
const target = getPointerDropStatusTarget({
|
||||
container,
|
||||
x: event.clientX,
|
||||
y: event.clientY
|
||||
})
|
||||
if (target.isPinDrop) {
|
||||
onPinWorktrees(drag.draggedIds)
|
||||
} else if (target.status) {
|
||||
onMoveWorktreesToStatus(drag.draggedIds, target.status)
|
||||
}
|
||||
}
|
||||
clearWorktreeDrag()
|
||||
}
|
||||
|
||||
const handlePointerCancel = (event: PointerEvent): void => {
|
||||
const drag = worktreePointerDragRef.current
|
||||
if (!drag || event.pointerId !== drag.pointerId) {
|
||||
return
|
||||
}
|
||||
clearWorktreeDrag()
|
||||
}
|
||||
|
||||
window.addEventListener('pointermove', handlePointerMove, { capture: true })
|
||||
window.addEventListener('pointerup', handlePointerUp, { capture: true })
|
||||
window.addEventListener('pointercancel', handlePointerCancel, { capture: true })
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', handlePointerMove, { capture: true })
|
||||
window.removeEventListener('pointerup', handlePointerUp, { capture: true })
|
||||
window.removeEventListener('pointercancel', handlePointerCancel, { capture: true })
|
||||
}
|
||||
}, [
|
||||
beginWorktreePointerDrag,
|
||||
clearWorktreeDrag,
|
||||
computeWorktreeDrop,
|
||||
onMoveWorktreesToStatus,
|
||||
onPinWorktrees,
|
||||
onReorderWorktrees,
|
||||
scheduleWorktreePointerDragFrame,
|
||||
worktreeDragGroups,
|
||||
worktreeDragUnitGroups
|
||||
])
|
||||
|
||||
const handleWorktreeCardDragStart = useCallback(
|
||||
(
|
||||
_event: React.DragEvent<HTMLDivElement>,
|
||||
worktreeId: string,
|
||||
draggedIds: readonly string[]
|
||||
) => {
|
||||
const sourceGroupKey = groupKeyByWorktreeId.get(worktreeId)
|
||||
if (!sourceGroupKey) {
|
||||
return
|
||||
}
|
||||
const reorderDraggedIds = getReorderDraggedIds(draggedIds)
|
||||
const reorderUnitDraggedIds = getReorderUnitDraggedIds(sourceGroupKey, reorderDraggedIds)
|
||||
worktreeDragSessionRef.current = {
|
||||
draggingWorktreeId: worktreeId,
|
||||
sourceGroupKey,
|
||||
draggedIds,
|
||||
reorderDraggedIds,
|
||||
reorderUnitDraggedIds,
|
||||
rects: scrollRef.current
|
||||
? getWorktreeDragRectsForGroup(scrollRef.current, sourceGroupKey)
|
||||
: []
|
||||
}
|
||||
setWorktreeDragState({
|
||||
draggingWorktreeId: worktreeId,
|
||||
sourceGroupKey,
|
||||
dropIndex: null,
|
||||
dropIndicatorY: null,
|
||||
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
|
||||
pointerY: null
|
||||
})
|
||||
},
|
||||
[getReorderDraggedIds, getReorderUnitDraggedIds, groupKeyByWorktreeId]
|
||||
)
|
||||
|
||||
const handleWorktreeDragOver = useCallback(
|
||||
(event: React.DragEvent<HTMLDivElement>) => {
|
||||
const session = worktreeDragSessionRef.current
|
||||
if (!session) {
|
||||
return
|
||||
}
|
||||
const drop = computeWorktreeDrop(event.clientY)
|
||||
if (!drop) {
|
||||
setWorktreeDragState((prev) =>
|
||||
prev.dropIndex === null &&
|
||||
prev.dropIndicatorY === null &&
|
||||
prev.previewOffsetsByWorktreeId.size === 0
|
||||
? prev
|
||||
: {
|
||||
...prev,
|
||||
dropIndex: null,
|
||||
dropIndicatorY: null,
|
||||
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
|
||||
pointerY: null
|
||||
}
|
||||
)
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.dataTransfer.dropEffect = 'move'
|
||||
setWorktreeDragState((prev) =>
|
||||
prev.dropIndex === drop.dropIndex &&
|
||||
prev.dropIndicatorY === drop.dropIndicatorY &&
|
||||
areWorktreeDragPreviewOffsetsEqual(
|
||||
prev.previewOffsetsByWorktreeId,
|
||||
drop.previewOffsetsByWorktreeId
|
||||
)
|
||||
? prev
|
||||
: { ...prev, ...drop, pointerY: event.clientY }
|
||||
)
|
||||
},
|
||||
[computeWorktreeDrop]
|
||||
)
|
||||
|
||||
const handleWorktreeDrop = useCallback(
|
||||
(event: React.DragEvent<HTMLDivElement>) => {
|
||||
const session = worktreeDragSessionRef.current
|
||||
if (!session) {
|
||||
return
|
||||
}
|
||||
const drop = computeWorktreeDrop(event.clientY)
|
||||
if (!drop) {
|
||||
clearWorktreeDrag()
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
onReorderWorktrees({
|
||||
groups: worktreeDragGroups,
|
||||
sourceGroupKey: session.sourceGroupKey,
|
||||
draggedIds: session.reorderDraggedIds,
|
||||
dropIndex: getFullDropIndexForWorktreeDragUnit({
|
||||
groups: worktreeDragUnitGroups,
|
||||
sourceGroupKey: session.sourceGroupKey,
|
||||
dropIndex: drop.dropIndex
|
||||
})
|
||||
})
|
||||
clearWorktreeDrag()
|
||||
},
|
||||
[
|
||||
clearWorktreeDrag,
|
||||
computeWorktreeDrop,
|
||||
onReorderWorktrees,
|
||||
worktreeDragGroups,
|
||||
worktreeDragUnitGroups
|
||||
]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (document.visibilityState !== 'visible') {
|
||||
lastVisibleRefreshKeyRef.current = '__document_hidden__'
|
||||
@@ -922,6 +1581,44 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
[onMoveWorktreesToStatus]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const handleDocumentDrop = (event: DragEvent): void => {
|
||||
const session = worktreeDragSessionRef.current
|
||||
if (!session) {
|
||||
return
|
||||
}
|
||||
const drop = computeWorktreeDrop(event.clientY)
|
||||
if (!drop) {
|
||||
return
|
||||
}
|
||||
// Why: status-group drops are captured before React sees them. When the
|
||||
// pointer is still inside the source group, this is a reorder rather than
|
||||
// a status move, so commit here and stop the status-drop capture handler.
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onReorderWorktrees({
|
||||
groups: worktreeDragGroups,
|
||||
sourceGroupKey: session.sourceGroupKey,
|
||||
draggedIds: session.reorderDraggedIds,
|
||||
dropIndex: getFullDropIndexForWorktreeDragUnit({
|
||||
groups: worktreeDragUnitGroups,
|
||||
sourceGroupKey: session.sourceGroupKey,
|
||||
dropIndex: drop.dropIndex
|
||||
})
|
||||
})
|
||||
clearWorktreeDrag()
|
||||
}
|
||||
|
||||
document.addEventListener('drop', handleDocumentDrop, true)
|
||||
return () => document.removeEventListener('drop', handleDocumentDrop, true)
|
||||
}, [
|
||||
clearWorktreeDrag,
|
||||
computeWorktreeDrop,
|
||||
onReorderWorktrees,
|
||||
worktreeDragGroups,
|
||||
worktreeDragUnitGroups
|
||||
])
|
||||
|
||||
useWorkspaceStatusDocumentDrop(
|
||||
scrollRef,
|
||||
onMoveWorktreeToStatus,
|
||||
@@ -953,6 +1650,8 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
onPointerDown={handleScrollPointerDown}
|
||||
onTouchMove={markDirectScrollInput}
|
||||
onWheel={markDirectScrollInput}
|
||||
onDragOver={handleWorktreeDragOver}
|
||||
onDrop={handleWorktreeDrop}
|
||||
className="worktree-sidebar-scrollbar h-full overflow-y-scroll overflow-x-hidden pl-1 scrollbar-sleek outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-inset pt-px"
|
||||
style={WORKTREE_SIDEBAR_SCROLL_STYLE}
|
||||
>
|
||||
@@ -988,6 +1687,18 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
style={{ top: `${repoDrag.state.dropIndicatorY}px` }}
|
||||
/>
|
||||
) : null}
|
||||
{worktreeDragState.draggingWorktreeId !== null &&
|
||||
worktreeDragState.dropIndicatorY !== null ? (
|
||||
<div
|
||||
role="presentation"
|
||||
className="pointer-events-none absolute left-3 right-2 z-30 flex h-3 -translate-y-1/2 items-center"
|
||||
style={{ top: `${worktreeDragState.dropIndicatorY}px` }}
|
||||
>
|
||||
<span className="size-1.5 shrink-0 rounded-full bg-sidebar-ring shadow-[0_0_0_2px_var(--sidebar)]" />
|
||||
<span className="h-0.5 flex-1 rounded-full bg-sidebar-ring shadow-[0_0_0_2px_var(--sidebar)]" />
|
||||
<span className="size-1.5 shrink-0 rounded-full bg-sidebar-ring shadow-[0_0_0_2px_var(--sidebar)]" />
|
||||
</div>
|
||||
) : null}
|
||||
{virtualItems.map((vItem) => {
|
||||
const row = renderRows[vItem.index]
|
||||
if (!row) {
|
||||
@@ -1241,6 +1952,8 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
// Why: child cards render inside the parent card body, so their
|
||||
// first nested level starts flush with that inset.
|
||||
const paddingDepth = nested ? Math.max(0, itemRow.depth - 1) : itemRow.depth
|
||||
const worktreeDragGroupKey = groupKeyByWorktreeId.get(itemRow.worktree.id)
|
||||
const worktreeDragGroupIndex = groupIndexByWorktreeId.get(itemRow.worktree.id)
|
||||
return (
|
||||
<div
|
||||
key={itemRow.worktree.id}
|
||||
@@ -1248,12 +1961,23 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
role="option"
|
||||
aria-selected={selectedWorktreeIds.has(itemRow.worktree.id)}
|
||||
aria-current={activeWorktreeId === itemRow.worktree.id ? 'page' : undefined}
|
||||
className="relative"
|
||||
data-worktree-drag-id={worktreeDragGroupKey ? itemRow.worktree.id : undefined}
|
||||
data-worktree-drag-group-key={worktreeDragGroupKey}
|
||||
data-worktree-drag-group-index={worktreeDragGroupIndex}
|
||||
className={cn(
|
||||
'relative transition-[opacity,transform,filter] duration-150 ease-out',
|
||||
worktreeDragState.draggingWorktreeId === itemRow.worktree.id &&
|
||||
'z-20 scale-[0.985] opacity-35 saturate-75'
|
||||
)}
|
||||
// Why: nested child cards live inside the parent's clickable
|
||||
// card body; bubbling would activate/edit the parent too.
|
||||
onClick={nested ? stopNestedWorktreeCardBubble : undefined}
|
||||
onClickCapture={handleWorktreeRowClickCapture}
|
||||
onDoubleClick={nested ? stopNestedWorktreeCardBubble : undefined}
|
||||
onDragStart={nested ? stopNestedWorktreeCardBubble : undefined}
|
||||
onPointerDown={(event) =>
|
||||
nested ? undefined : handleWorktreeRowPointerDown(event, itemRow.worktree.id)
|
||||
}
|
||||
style={{
|
||||
paddingLeft: paddingDepth > 0 ? `${paddingDepth * LINEAGE_INDENT}px` : undefined
|
||||
}}
|
||||
@@ -1267,8 +1991,11 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
isActiveSurface={forceActiveSurface || activeWorktreeId === itemRow.worktree.id}
|
||||
isMultiSelected={selectedWorktreeIds.has(itemRow.worktree.id)}
|
||||
selectedWorktrees={selectedWorktrees}
|
||||
nativeDragEnabled={false}
|
||||
onSelectionGesture={onSelectionGesture}
|
||||
onContextMenuSelect={(event) => onContextMenuSelect(event, itemRow.worktree)}
|
||||
onCardDragStart={handleWorktreeCardDragStart}
|
||||
onCardDragEnd={clearWorktreeDrag}
|
||||
hideRepoBadge={groupBy === 'repo'}
|
||||
lineageChildCount={itemRow.lineageChildCount}
|
||||
lineageCollapsed={itemRow.lineageCollapsed}
|
||||
@@ -1426,6 +2153,9 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
if (row.type === 'lineage-group') {
|
||||
const [parent, ...children] = row.rows
|
||||
const childIsActive = children.some((child) => child.worktree.id === activeWorktreeId)
|
||||
const parentPreviewOffset = parent
|
||||
? (worktreeDragState.previewOffsetsByWorktreeId.get(parent.worktree.id) ?? 0)
|
||||
: 0
|
||||
return (
|
||||
<div
|
||||
key={vItem.key}
|
||||
@@ -1434,8 +2164,14 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
data-worktree-virtual-row-key={String(vItem.key)}
|
||||
data-index={vItem.index}
|
||||
ref={measureVirtualRowElement}
|
||||
className="absolute left-0 right-0 top-0"
|
||||
style={{ transform: getVirtualRowTransform(vItem.start) }}
|
||||
className={cn(
|
||||
'absolute left-0 right-0 top-0',
|
||||
worktreeDragState.draggingWorktreeId !== null &&
|
||||
'transition-transform duration-150 ease-out will-change-transform'
|
||||
)}
|
||||
style={{
|
||||
transform: getWorktreeVirtualRowTransform(vItem.start, parentPreviewOffset)
|
||||
}}
|
||||
>
|
||||
<div className="overflow-visible">
|
||||
{parent
|
||||
@@ -1457,6 +2193,8 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
groupBy === 'workspace-status'
|
||||
? getWorkspaceStatus(row.worktree, workspaceStatuses)
|
||||
: null
|
||||
const itemPreviewOffset =
|
||||
worktreeDragState.previewOffsetsByWorktreeId.get(row.worktree.id) ?? 0
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -1468,8 +2206,14 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
ref={measureVirtualRowElement}
|
||||
data-workspace-status-drop-target={itemWorkspaceStatus ? '' : undefined}
|
||||
data-workspace-status={itemWorkspaceStatus ?? undefined}
|
||||
className="absolute left-0 right-0 top-0"
|
||||
style={{ transform: getVirtualRowTransform(vItem.start) }}
|
||||
className={cn(
|
||||
'absolute left-0 right-0 top-0',
|
||||
worktreeDragState.draggingWorktreeId !== null &&
|
||||
'transition-transform duration-150 ease-out will-change-transform'
|
||||
)}
|
||||
style={{
|
||||
transform: getWorktreeVirtualRowTransform(vItem.start, itemPreviewOffset)
|
||||
}}
|
||||
onDragOver={
|
||||
itemWorkspaceStatus
|
||||
? (event) => handleWorkspaceStatusDragOver(event, itemWorkspaceStatus)
|
||||
@@ -1511,6 +2255,7 @@ const WorktreeList = React.memo(function WorktreeList({
|
||||
const groupBy = useAppStore((s) => s.groupBy)
|
||||
const workspaceStatuses = useAppStore((s) => s.workspaceStatuses)
|
||||
const sortBy = useAppStore((s) => s.sortBy)
|
||||
const setSortBy = useAppStore((s) => s.setSortBy)
|
||||
const showSleepingWorkspaces = useAppStore((s) => s.showSleepingWorkspaces)
|
||||
const hideDefaultBranchWorkspace = useAppStore((s) => s.hideDefaultBranchWorkspace)
|
||||
const filterRepoIds = useAppStore((s) => s.filterRepoIds)
|
||||
@@ -1574,14 +2319,16 @@ const WorktreeList = React.memo(function WorktreeList({
|
||||
const structuralChange = worktreeCount !== prevWorktreeCountRef.current
|
||||
prevWorktreeCountRef.current = worktreeCount
|
||||
|
||||
if (structuralChange) {
|
||||
// Why: manual drag/drop is direct manipulation; delaying that repaint by
|
||||
// the smart-sort settle window makes a successful drop look broken.
|
||||
if (structuralChange || sortBy === 'manual') {
|
||||
setDebouncedSortEpoch(sortEpoch)
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => setDebouncedSortEpoch(sortEpoch), SORT_SETTLE_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [sortEpoch, debouncedSortEpoch, worktreeCount])
|
||||
}, [sortEpoch, debouncedSortEpoch, worktreeCount, sortBy])
|
||||
|
||||
// Why a latching ref: we need to distinguish "app just started, no PTYs
|
||||
// have spawned yet" from "user closed all terminals mid-session." The
|
||||
@@ -2037,6 +2784,39 @@ const WorktreeList = React.memo(function WorktreeList({
|
||||
[updateWorktreesMeta, worktreeMap]
|
||||
)
|
||||
|
||||
const reorderWorktrees = useCallback(
|
||||
(args: {
|
||||
groups: readonly WorktreeDragGroup[]
|
||||
sourceGroupKey: string
|
||||
draggedIds: readonly string[]
|
||||
dropIndex: number
|
||||
}) => {
|
||||
const rankByWorktreeId = new Map<string, number>()
|
||||
for (const group of args.groups) {
|
||||
for (const worktreeId of group.worktreeIds) {
|
||||
const worktree = worktreeMap.get(worktreeId)
|
||||
if (worktree) {
|
||||
rankByWorktreeId.set(worktreeId, worktree.manualOrder ?? worktree.sortOrder)
|
||||
}
|
||||
}
|
||||
}
|
||||
const result = buildManualOrderUpdatesForVisibleGroups({
|
||||
...args,
|
||||
now: Date.now(),
|
||||
rankByWorktreeId
|
||||
})
|
||||
if (!result.changed) {
|
||||
return
|
||||
}
|
||||
// Why: a drag reorder is an explicit request for user-authored order.
|
||||
// Switch modes only after a real move so accidental click-drags do not
|
||||
// alter the user's selected sort.
|
||||
setSortBy('manual')
|
||||
void updateWorktreesMeta(result.updates)
|
||||
},
|
||||
[setSortBy, updateWorktreesMeta, worktreeMap]
|
||||
)
|
||||
|
||||
// Why: hideDefaultBranchWorkspace is counted as a filter here so the
|
||||
// empty-sidebar escape hatch (Clear Filters button below) is reachable when
|
||||
// it's the only reason the list is empty — otherwise a user whose only
|
||||
@@ -2118,6 +2898,7 @@ const WorktreeList = React.memo(function WorktreeList({
|
||||
onMoveWorktreesToStatus={moveWorktreesToStatus}
|
||||
onPinWorktree={pinWorktree}
|
||||
onPinWorktrees={pinWorktrees}
|
||||
onReorderWorktrees={reorderWorktrees}
|
||||
showInlineAgentCards={cardProps.includes('inline-agents')}
|
||||
scrollOffsetRef={scrollOffsetRef}
|
||||
scrollAnchorRef={scrollAnchorRef}
|
||||
|
||||
@@ -653,6 +653,36 @@ describe('effectiveRecentActivity — create-grace floor', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWorktreeComparator — manual order', () => {
|
||||
it('orders by persisted manualOrder with higher values first', () => {
|
||||
const first = makeWorktree({ id: 'first', displayName: 'First', manualOrder: 3000 })
|
||||
const second = makeWorktree({ id: 'second', displayName: 'Second', manualOrder: 2000 })
|
||||
const worktrees = [second, first]
|
||||
|
||||
worktrees.sort(buildWorktreeComparator('manual', repoMap, NOW, new Map()))
|
||||
|
||||
expect(worktrees.map((w) => w.id)).toEqual(['first', 'second'])
|
||||
})
|
||||
|
||||
it('falls back to sortOrder before a workspace has manualOrder', () => {
|
||||
const restoredTop = makeWorktree({
|
||||
id: 'restored-top',
|
||||
displayName: 'Restored Top',
|
||||
sortOrder: 5000
|
||||
})
|
||||
const restoredBottom = makeWorktree({
|
||||
id: 'restored-bottom',
|
||||
displayName: 'Restored Bottom',
|
||||
sortOrder: 1000
|
||||
})
|
||||
const worktrees = [restoredBottom, restoredTop]
|
||||
|
||||
worktrees.sort(buildWorktreeComparator('manual', repoMap, NOW, new Map()))
|
||||
|
||||
expect(worktrees.map((w) => w.id)).toEqual(['restored-top', 'restored-bottom'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWorktreeComparator — recent with createdAt grace window', () => {
|
||||
it('keeps a newly-created worktree on top even when another worktree bumps lastActivityAt', () => {
|
||||
const newWorktree = makeWorktree({
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
import { tabHasLivePty } from '@/lib/tab-has-live-pty'
|
||||
import { IDLE, buildAttentionByWorktree, type WorktreeAttention } from './smart-attention'
|
||||
|
||||
export type SortBy = 'name' | 'smart' | 'recent' | 'repo'
|
||||
export type SortBy = 'name' | 'smart' | 'recent' | 'repo' | 'manual'
|
||||
|
||||
// Why: a newly-created worktree's lastActivityAt is stamped at the moment
|
||||
// createLocalWorktree finishes git + setup-runner prep (often several seconds
|
||||
@@ -95,6 +95,14 @@ export function buildWorktreeComparator(
|
||||
const cmp = ra.localeCompare(rb)
|
||||
return cmp !== 0 ? cmp : a.displayName.localeCompare(b.displayName)
|
||||
}
|
||||
case 'manual':
|
||||
// Why fallback to sortOrder: existing users have a persisted smart-sort
|
||||
// snapshot but no manualOrder yet, so Manual starts from a familiar
|
||||
// restored order instead of alphabetizing every legacy workspace.
|
||||
return (
|
||||
(b.manualOrder ?? b.sortOrder) - (a.manualOrder ?? a.sortOrder) ||
|
||||
a.displayName.localeCompare(b.displayName)
|
||||
)
|
||||
default: {
|
||||
const _exhaustive: never = sortBy
|
||||
return _exhaustive
|
||||
|
||||
@@ -3,13 +3,17 @@ import type React from 'react'
|
||||
import type { WorkspaceStatus, Worktree } from '../../../../shared/types'
|
||||
import {
|
||||
CARD_SELECTOR,
|
||||
getCardDropTarget,
|
||||
removeCardDropIndicator,
|
||||
updateCardDropIndicator
|
||||
} from './workspace-kanban-card-pointer-drag-dom'
|
||||
import {
|
||||
createDragPreview,
|
||||
getDraggedCards,
|
||||
getDropTarget,
|
||||
setDragDocumentStyles,
|
||||
setDraggedCardsDragging,
|
||||
updateDragPreviewPosition
|
||||
} from './workspace-kanban-card-pointer-drag-dom'
|
||||
} from './workspace-kanban-card-drag-preview-dom'
|
||||
|
||||
const POINTER_DRAG_THRESHOLD = 5
|
||||
|
||||
@@ -26,6 +30,7 @@ type DragState = {
|
||||
previewOffsetX: number
|
||||
previewOffsetY: number
|
||||
started: boolean
|
||||
frameId: number | null
|
||||
}
|
||||
|
||||
type UseWorkspaceKanbanCardPointerDragParams = {
|
||||
@@ -33,7 +38,12 @@ type UseWorkspaceKanbanCardPointerDragParams = {
|
||||
boardRef: React.RefObject<HTMLElement | null>
|
||||
selectedWorktreeIds: ReadonlySet<string>
|
||||
selectedWorktrees: readonly Worktree[]
|
||||
onMoveWorktreesToStatus: (worktreeIds: readonly string[], status: WorkspaceStatus) => void
|
||||
onDropWorktreesInStatus: (args: {
|
||||
worktreeIds: readonly string[]
|
||||
status: WorkspaceStatus
|
||||
dropIndex: number
|
||||
}) => void
|
||||
onShouldShowDropIndicator: (worktreeIds: readonly string[], status: WorkspaceStatus) => boolean
|
||||
onPinWorktrees: (worktreeIds: readonly string[]) => void
|
||||
onDragTargetChange: (status: WorkspaceStatus | null) => void
|
||||
onPinDragTargetChange: (isOver: boolean) => void
|
||||
@@ -74,7 +84,8 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
boardRef,
|
||||
selectedWorktreeIds,
|
||||
selectedWorktrees,
|
||||
onMoveWorktreesToStatus,
|
||||
onDropWorktreesInStatus,
|
||||
onShouldShowDropIndicator,
|
||||
onPinWorktrees,
|
||||
onDragTargetChange,
|
||||
onPinDragTargetChange
|
||||
@@ -87,7 +98,8 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
const suppressClickUntilRef = useRef(0)
|
||||
const selectedWorktreeIdsRef = useRef(selectedWorktreeIds)
|
||||
const selectedWorktreesRef = useRef(selectedWorktrees)
|
||||
const moveWorktreesRef = useRef(onMoveWorktreesToStatus)
|
||||
const dropWorktreesInStatusRef = useRef(onDropWorktreesInStatus)
|
||||
const shouldShowDropIndicatorRef = useRef(onShouldShowDropIndicator)
|
||||
const pinWorktreesRef = useRef(onPinWorktrees)
|
||||
const dragTargetChangeRef = useRef(onDragTargetChange)
|
||||
const pinDragTargetChangeRef = useRef(onPinDragTargetChange)
|
||||
@@ -95,7 +107,8 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
useEffect(() => {
|
||||
selectedWorktreeIdsRef.current = selectedWorktreeIds
|
||||
selectedWorktreesRef.current = selectedWorktrees
|
||||
moveWorktreesRef.current = onMoveWorktreesToStatus
|
||||
dropWorktreesInStatusRef.current = onDropWorktreesInStatus
|
||||
shouldShowDropIndicatorRef.current = onShouldShowDropIndicator
|
||||
pinWorktreesRef.current = onPinWorktrees
|
||||
dragTargetChangeRef.current = onDragTargetChange
|
||||
pinDragTargetChangeRef.current = onPinDragTargetChange
|
||||
@@ -113,7 +126,11 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
return
|
||||
}
|
||||
dragRef.current = null
|
||||
if (state.frameId !== null) {
|
||||
window.cancelAnimationFrame(state.frameId)
|
||||
}
|
||||
setDraggedCardsDragging(state.draggedCards, false)
|
||||
removeCardDropIndicator()
|
||||
state.preview?.remove()
|
||||
setDragDocumentStyles(false)
|
||||
clearDragTarget()
|
||||
@@ -132,11 +149,15 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
if (!board) {
|
||||
return
|
||||
}
|
||||
const dropTarget = getDropTarget(board, state.currentX, state.currentY)
|
||||
const dropTarget = getCardDropTarget(board, state.currentX, state.currentY)
|
||||
if (dropTarget.isPinDrop) {
|
||||
pinWorktreesRef.current(state.worktreeIds)
|
||||
} else if (dropTarget.status) {
|
||||
moveWorktreesRef.current(state.worktreeIds, dropTarget.status)
|
||||
dropWorktreesInStatusRef.current({
|
||||
worktreeIds: state.worktreeIds,
|
||||
status: dropTarget.status,
|
||||
dropIndex: dropTarget.dropIndex
|
||||
})
|
||||
}
|
||||
},
|
||||
[boardRef, clearDragTarget]
|
||||
@@ -155,15 +176,47 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
const board = boardRef.current
|
||||
if (!board) {
|
||||
clearDragTarget()
|
||||
removeCardDropIndicator()
|
||||
return
|
||||
}
|
||||
const dropTarget = getDropTarget(board, state.currentX, state.currentY)
|
||||
const dropTarget = getCardDropTarget(board, state.currentX, state.currentY)
|
||||
pinDragTargetChangeRef.current(dropTarget.isPinDrop)
|
||||
dragTargetChangeRef.current(dropTarget.status)
|
||||
if (
|
||||
dropTarget.status &&
|
||||
shouldShowDropIndicatorRef.current(state.worktreeIds, dropTarget.status)
|
||||
) {
|
||||
updateCardDropIndicator(board, dropTarget)
|
||||
} else {
|
||||
removeCardDropIndicator()
|
||||
}
|
||||
},
|
||||
[boardRef, clearDragTarget]
|
||||
)
|
||||
|
||||
const flushPointerDragFrame = useCallback(() => {
|
||||
const state = dragRef.current
|
||||
if (!state) {
|
||||
return
|
||||
}
|
||||
state.frameId = null
|
||||
if (!state.started) {
|
||||
return
|
||||
}
|
||||
updateDragPreviewPosition(state)
|
||||
updatePointerDragTarget(state)
|
||||
}, [updatePointerDragTarget])
|
||||
|
||||
const schedulePointerDragFrame = useCallback(
|
||||
(state: DragState) => {
|
||||
if (state.frameId !== null) {
|
||||
return
|
||||
}
|
||||
state.frameId = window.requestAnimationFrame(flushPointerDragFrame)
|
||||
},
|
||||
[flushPointerDragFrame]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
stopPointerDrag(false)
|
||||
@@ -185,8 +238,7 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
updateDragPreviewPosition(state)
|
||||
updatePointerDragTarget(state)
|
||||
schedulePointerDragFrame(state)
|
||||
}
|
||||
|
||||
const handlePointerUp = (event: PointerEvent): void => {
|
||||
@@ -226,7 +278,7 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
window.removeEventListener('blur', handleBlur)
|
||||
stopPointerDrag(false)
|
||||
}
|
||||
}, [open, startPointerDrag, stopPointerDrag, updatePointerDragTarget])
|
||||
}, [open, schedulePointerDragFrame, startPointerDrag, stopPointerDrag])
|
||||
|
||||
const onCardPointerDownCapture = useCallback(
|
||||
(event: React.PointerEvent<HTMLElement>) => {
|
||||
@@ -262,7 +314,8 @@ export function useWorkspaceKanbanCardPointerDrag({
|
||||
preview: null,
|
||||
previewOffsetX: 0,
|
||||
previewOffsetY: 0,
|
||||
started: false
|
||||
started: false,
|
||||
frameId: null
|
||||
}
|
||||
},
|
||||
[boardRef, open]
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { CARD_SELECTOR } from './workspace-kanban-card-pointer-drag-dom'
|
||||
|
||||
const POINTER_CARD_DRAGGING_ATTR = 'data-workspace-board-card-pointer-dragging'
|
||||
const POINTER_DRAG_CARD_ATTR = 'data-workspace-board-card-drag-card'
|
||||
const POINTER_DRAG_COUNT_ATTR = 'data-workspace-board-card-drag-count'
|
||||
const POINTER_DRAGGING_ATTR = 'data-workspace-board-pointer-dragging'
|
||||
const POINTER_DRAG_PREVIEW_ATTR = 'data-workspace-board-card-drag-preview'
|
||||
const POINTER_DRAG_STACK_ATTR = 'data-workspace-board-card-drag-stack'
|
||||
|
||||
type DragPreviewState = {
|
||||
startX: number
|
||||
startY: number
|
||||
currentX: number
|
||||
currentY: number
|
||||
worktreeIds: readonly string[]
|
||||
sourceCard: HTMLElement
|
||||
preview: HTMLElement | null
|
||||
previewOffsetX: number
|
||||
previewOffsetY: number
|
||||
}
|
||||
|
||||
export function setDragDocumentStyles(enabled: boolean): void {
|
||||
document.body.style.cursor = enabled ? 'grabbing' : ''
|
||||
document.body.style.userSelect = enabled ? 'none' : ''
|
||||
document.documentElement.toggleAttribute(POINTER_DRAGGING_ATTR, enabled)
|
||||
}
|
||||
|
||||
export function getDraggedCards(
|
||||
board: HTMLElement,
|
||||
worktreeIds: readonly string[],
|
||||
fallbackCard: HTMLElement
|
||||
): HTMLElement[] {
|
||||
const ids = new Set(worktreeIds)
|
||||
const cards = Array.from(board.querySelectorAll<HTMLElement>(CARD_SELECTOR)).filter((card) =>
|
||||
ids.has(card.dataset.workspaceBoardCardId ?? '')
|
||||
)
|
||||
return cards.length > 0 ? cards : [fallbackCard]
|
||||
}
|
||||
|
||||
export function setDraggedCardsDragging(cards: readonly HTMLElement[], enabled: boolean): void {
|
||||
for (const card of cards) {
|
||||
if (enabled) {
|
||||
card.setAttribute(POINTER_CARD_DRAGGING_ATTR, 'true')
|
||||
} else {
|
||||
card.removeAttribute(POINTER_CARD_DRAGGING_ATTR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeDuplicatePreviewAttributes(preview: HTMLElement): void {
|
||||
preview.removeAttribute('data-workspace-board-card-id')
|
||||
preview.removeAttribute(POINTER_CARD_DRAGGING_ATTR)
|
||||
preview.removeAttribute('id')
|
||||
preview.removeAttribute('aria-describedby')
|
||||
preview.querySelectorAll<HTMLElement>('[data-workspace-board-card-id]').forEach((element) => {
|
||||
element.removeAttribute('data-workspace-board-card-id')
|
||||
})
|
||||
preview.querySelectorAll<HTMLElement>(`[${POINTER_CARD_DRAGGING_ATTR}]`).forEach((element) => {
|
||||
element.removeAttribute(POINTER_CARD_DRAGGING_ATTR)
|
||||
})
|
||||
preview.querySelectorAll<HTMLElement>('[id],[aria-describedby]').forEach((element) => {
|
||||
element.removeAttribute('id')
|
||||
element.removeAttribute('aria-describedby')
|
||||
})
|
||||
}
|
||||
|
||||
export function updateDragPreviewPosition(state: DragPreviewState): void {
|
||||
const left = state.currentX - state.previewOffsetX
|
||||
const top = state.currentY - state.previewOffsetY
|
||||
state.preview?.style.setProperty('transform', `translate3d(${left}px, ${top}px, 0)`)
|
||||
}
|
||||
|
||||
export function createDragPreview(state: DragPreviewState): HTMLElement {
|
||||
const rect = state.sourceCard.getBoundingClientRect()
|
||||
const preview = document.createElement('div')
|
||||
const previewCard = state.sourceCard.cloneNode(true) as HTMLElement
|
||||
state.previewOffsetX = Math.min(Math.max(state.startX - rect.left, 0), rect.width)
|
||||
state.previewOffsetY = Math.min(Math.max(state.startY - rect.top, 0), rect.height)
|
||||
preview.setAttribute(POINTER_DRAG_PREVIEW_ATTR, 'true')
|
||||
preview.setAttribute('aria-hidden', 'true')
|
||||
previewCard.setAttribute(POINTER_DRAG_CARD_ATTR, 'true')
|
||||
removeDuplicatePreviewAttributes(previewCard)
|
||||
preview.appendChild(previewCard)
|
||||
if (state.worktreeIds.length > 1) {
|
||||
const countBadge = document.createElement('span')
|
||||
preview.setAttribute(POINTER_DRAG_STACK_ATTR, 'true')
|
||||
countBadge.setAttribute(POINTER_DRAG_COUNT_ATTR, 'true')
|
||||
countBadge.textContent = String(state.worktreeIds.length)
|
||||
preview.appendChild(countBadge)
|
||||
}
|
||||
preview.style.setProperty('position', 'fixed')
|
||||
preview.style.setProperty('left', '0')
|
||||
preview.style.setProperty('top', '0')
|
||||
preview.style.setProperty('width', `${rect.width}px`)
|
||||
preview.style.setProperty('height', `${rect.height}px`)
|
||||
preview.style.setProperty('pointer-events', 'none')
|
||||
updateDragPreviewPosition({ ...state, preview })
|
||||
document.body.appendChild(preview)
|
||||
return preview
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveWorkspaceStatusDropTargetFromRects } from './workspace-kanban-card-pointer-drag-dom'
|
||||
import {
|
||||
resolveWorkspaceCardDropIndexFromRects,
|
||||
resolveWorkspaceStatusDropTargetFromRects
|
||||
} from './workspace-kanban-card-pointer-drag-dom'
|
||||
|
||||
const rects = [
|
||||
{ status: 'todo', left: 0, top: 0, right: 200, bottom: 600 },
|
||||
@@ -21,3 +24,20 @@ describe('workspace kanban pointer drag drop target', () => {
|
||||
expect(resolveWorkspaceStatusDropTargetFromRects(rects, 206, 620)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspace kanban pointer drag card drop index', () => {
|
||||
const cardRects = [
|
||||
{ top: 0, bottom: 40 },
|
||||
{ top: 48, bottom: 88 },
|
||||
{ top: 96, bottom: 136 }
|
||||
]
|
||||
|
||||
it('inserts before the first card whose midpoint is below the pointer', () => {
|
||||
expect(resolveWorkspaceCardDropIndexFromRects(cardRects, 10)).toBe(0)
|
||||
expect(resolveWorkspaceCardDropIndexFromRects(cardRects, 70)).toBe(2)
|
||||
})
|
||||
|
||||
it('inserts at the end when the pointer is below every card midpoint', () => {
|
||||
expect(resolveWorkspaceCardDropIndexFromRects(cardRects, 140)).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,24 +5,7 @@ export const STATUS_DROP_TARGET = '[data-workspace-status-drop-target]'
|
||||
export const PIN_DROP_TARGET = '[data-workspace-pin-drop-target]'
|
||||
|
||||
const STATUS_DROP_GAP_TOLERANCE_PX = 24
|
||||
const POINTER_CARD_DRAGGING_ATTR = 'data-workspace-board-card-pointer-dragging'
|
||||
const POINTER_DRAG_CARD_ATTR = 'data-workspace-board-card-drag-card'
|
||||
const POINTER_DRAG_COUNT_ATTR = 'data-workspace-board-card-drag-count'
|
||||
const POINTER_DRAGGING_ATTR = 'data-workspace-board-pointer-dragging'
|
||||
const POINTER_DRAG_PREVIEW_ATTR = 'data-workspace-board-card-drag-preview'
|
||||
const POINTER_DRAG_STACK_ATTR = 'data-workspace-board-card-drag-stack'
|
||||
|
||||
type DragPreviewState = {
|
||||
startX: number
|
||||
startY: number
|
||||
currentX: number
|
||||
currentY: number
|
||||
worktreeIds: readonly string[]
|
||||
sourceCard: HTMLElement
|
||||
preview: HTMLElement | null
|
||||
previewOffsetX: number
|
||||
previewOffsetY: number
|
||||
}
|
||||
const POINTER_DROP_INDICATOR_ATTR = 'data-workspace-board-card-drop-indicator'
|
||||
|
||||
export type WorkspaceKanbanStatusDropRect = {
|
||||
status: WorkspaceStatus
|
||||
@@ -32,6 +15,25 @@ export type WorkspaceKanbanStatusDropRect = {
|
||||
bottom: number
|
||||
}
|
||||
|
||||
export type WorkspaceKanbanCardDropRect = {
|
||||
top: number
|
||||
bottom: number
|
||||
}
|
||||
|
||||
export type WorkspaceKanbanLaneDropRect = {
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
}
|
||||
|
||||
export type WorkspaceKanbanCardDropTarget = {
|
||||
status: WorkspaceStatus | null
|
||||
isPinDrop: boolean
|
||||
dropIndex: number
|
||||
laneRect?: WorkspaceKanbanLaneDropRect
|
||||
cardRects?: readonly WorkspaceKanbanCardDropRect[]
|
||||
}
|
||||
|
||||
export function resolveWorkspaceStatusDropTargetFromRects(
|
||||
rects: readonly WorkspaceKanbanStatusDropRect[],
|
||||
x: number,
|
||||
@@ -59,6 +61,19 @@ export function resolveWorkspaceStatusDropTargetFromRects(
|
||||
return nearest?.status ?? null
|
||||
}
|
||||
|
||||
export function resolveWorkspaceCardDropIndexFromRects(
|
||||
rects: readonly WorkspaceKanbanCardDropRect[],
|
||||
y: number
|
||||
): number {
|
||||
for (let index = 0; index < rects.length; index++) {
|
||||
const rect = rects[index]!
|
||||
if (y < (rect.top + rect.bottom) / 2) {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return rects.length
|
||||
}
|
||||
|
||||
function getStatusDropTargetRects(board: HTMLElement): WorkspaceKanbanStatusDropRect[] {
|
||||
return Array.from(board.querySelectorAll<HTMLElement>(STATUS_DROP_TARGET)).flatMap((element) => {
|
||||
const status = element.dataset.workspaceStatus
|
||||
@@ -108,82 +123,124 @@ export function getDropTarget(
|
||||
}
|
||||
}
|
||||
|
||||
export function setDragDocumentStyles(enabled: boolean): void {
|
||||
document.body.style.cursor = enabled ? 'grabbing' : ''
|
||||
document.body.style.userSelect = enabled ? 'none' : ''
|
||||
document.documentElement.toggleAttribute(POINTER_DRAGGING_ATTR, enabled)
|
||||
}
|
||||
|
||||
export function getDraggedCards(
|
||||
board: HTMLElement,
|
||||
worktreeIds: readonly string[],
|
||||
fallbackCard: HTMLElement
|
||||
): HTMLElement[] {
|
||||
const ids = new Set(worktreeIds)
|
||||
const cards = Array.from(board.querySelectorAll<HTMLElement>(CARD_SELECTOR)).filter((card) =>
|
||||
ids.has(card.dataset.workspaceBoardCardId ?? '')
|
||||
function getLaneForStatus(board: HTMLElement, status: WorkspaceStatus): HTMLElement | null {
|
||||
return (
|
||||
Array.from(board.querySelectorAll<HTMLElement>(STATUS_DROP_TARGET)).find(
|
||||
(element) => element.dataset.workspaceStatus === status
|
||||
) ?? null
|
||||
)
|
||||
return cards.length > 0 ? cards : [fallbackCard]
|
||||
}
|
||||
|
||||
export function setDraggedCardsDragging(cards: readonly HTMLElement[], enabled: boolean): void {
|
||||
for (const card of cards) {
|
||||
if (enabled) {
|
||||
card.setAttribute(POINTER_CARD_DRAGGING_ATTR, 'true')
|
||||
} else {
|
||||
card.removeAttribute(POINTER_CARD_DRAGGING_ATTR)
|
||||
}
|
||||
export function getCardDropTarget(
|
||||
board: HTMLElement,
|
||||
x: number,
|
||||
y: number
|
||||
): WorkspaceKanbanCardDropTarget {
|
||||
const target = getDropTarget(board, x, y)
|
||||
if (!target.status) {
|
||||
return { ...target, dropIndex: 0 }
|
||||
}
|
||||
|
||||
const lane = getLaneForStatus(board, target.status)
|
||||
if (!lane) {
|
||||
return { ...target, dropIndex: 0 }
|
||||
}
|
||||
|
||||
const laneContent = lane.querySelector<HTMLElement>('[data-workspace-board-lane-scroll]')
|
||||
const laneClientRect = (laneContent ?? lane).getBoundingClientRect()
|
||||
const cardRects = Array.from(lane.querySelectorAll<HTMLElement>(CARD_SELECTOR))
|
||||
.filter((card) => card.offsetParent !== null)
|
||||
.map((card) => {
|
||||
const rect = card.getBoundingClientRect()
|
||||
return { top: rect.top, bottom: rect.bottom }
|
||||
})
|
||||
const dropIndex = resolveWorkspaceCardDropIndexFromRects(cardRects, y)
|
||||
return {
|
||||
...target,
|
||||
dropIndex,
|
||||
laneRect: {
|
||||
left: laneClientRect.left,
|
||||
top: laneClientRect.top,
|
||||
width: laneClientRect.width
|
||||
},
|
||||
cardRects
|
||||
}
|
||||
}
|
||||
|
||||
function removeDuplicatePreviewAttributes(preview: HTMLElement): void {
|
||||
preview.removeAttribute('data-workspace-board-card-id')
|
||||
preview.removeAttribute(POINTER_CARD_DRAGGING_ATTR)
|
||||
preview.removeAttribute('id')
|
||||
preview.removeAttribute('aria-describedby')
|
||||
preview.querySelectorAll<HTMLElement>('[data-workspace-board-card-id]').forEach((element) => {
|
||||
element.removeAttribute('data-workspace-board-card-id')
|
||||
})
|
||||
preview.querySelectorAll<HTMLElement>(`[${POINTER_CARD_DRAGGING_ATTR}]`).forEach((element) => {
|
||||
element.removeAttribute(POINTER_CARD_DRAGGING_ATTR)
|
||||
})
|
||||
preview.querySelectorAll<HTMLElement>('[id],[aria-describedby]').forEach((element) => {
|
||||
element.removeAttribute('id')
|
||||
element.removeAttribute('aria-describedby')
|
||||
})
|
||||
}
|
||||
|
||||
export function updateDragPreviewPosition(state: DragPreviewState): void {
|
||||
const left = state.currentX - state.previewOffsetX
|
||||
const top = state.currentY - state.previewOffsetY
|
||||
state.preview?.style.setProperty('transform', `translate3d(${left}px, ${top}px, 0)`)
|
||||
}
|
||||
|
||||
export function createDragPreview(state: DragPreviewState): HTMLElement {
|
||||
const rect = state.sourceCard.getBoundingClientRect()
|
||||
const preview = document.createElement('div')
|
||||
const previewCard = state.sourceCard.cloneNode(true) as HTMLElement
|
||||
state.previewOffsetX = Math.min(Math.max(state.startX - rect.left, 0), rect.width)
|
||||
state.previewOffsetY = Math.min(Math.max(state.startY - rect.top, 0), rect.height)
|
||||
preview.setAttribute(POINTER_DRAG_PREVIEW_ATTR, 'true')
|
||||
preview.setAttribute('aria-hidden', 'true')
|
||||
previewCard.setAttribute(POINTER_DRAG_CARD_ATTR, 'true')
|
||||
removeDuplicatePreviewAttributes(previewCard)
|
||||
preview.appendChild(previewCard)
|
||||
if (state.worktreeIds.length > 1) {
|
||||
const countBadge = document.createElement('span')
|
||||
preview.setAttribute(POINTER_DRAG_STACK_ATTR, 'true')
|
||||
countBadge.setAttribute(POINTER_DRAG_COUNT_ATTR, 'true')
|
||||
countBadge.textContent = String(state.worktreeIds.length)
|
||||
preview.appendChild(countBadge)
|
||||
function getOrCreateDropIndicator(): HTMLElement {
|
||||
const existing = document.querySelector<HTMLElement>(`[${POINTER_DROP_INDICATOR_ATTR}]`)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
preview.style.setProperty('position', 'fixed')
|
||||
preview.style.setProperty('left', '0')
|
||||
preview.style.setProperty('top', '0')
|
||||
preview.style.setProperty('width', `${rect.width}px`)
|
||||
preview.style.setProperty('height', `${rect.height}px`)
|
||||
preview.style.setProperty('pointer-events', 'none')
|
||||
updateDragPreviewPosition({ ...state, preview })
|
||||
document.body.appendChild(preview)
|
||||
return preview
|
||||
const indicator = document.createElement('div')
|
||||
indicator.setAttribute(POINTER_DROP_INDICATOR_ATTR, 'true')
|
||||
indicator.setAttribute('aria-hidden', 'true')
|
||||
indicator.style.setProperty('position', 'fixed')
|
||||
indicator.style.setProperty('left', '0')
|
||||
indicator.style.setProperty('top', '0')
|
||||
indicator.style.setProperty('pointer-events', 'none')
|
||||
document.body.appendChild(indicator)
|
||||
return indicator
|
||||
}
|
||||
|
||||
export function removeCardDropIndicator(): void {
|
||||
document.querySelector<HTMLElement>(`[${POINTER_DROP_INDICATOR_ATTR}]`)?.remove()
|
||||
}
|
||||
|
||||
export function updateCardDropIndicator(
|
||||
board: HTMLElement,
|
||||
target: WorkspaceKanbanCardDropTarget
|
||||
): void {
|
||||
if (!target.status || target.isPinDrop) {
|
||||
removeCardDropIndicator()
|
||||
return
|
||||
}
|
||||
|
||||
const lane = getLaneForStatus(board, target.status)
|
||||
if (!lane) {
|
||||
removeCardDropIndicator()
|
||||
return
|
||||
}
|
||||
|
||||
const fallbackLaneContent = target.laneRect
|
||||
? null
|
||||
: lane.querySelector<HTMLElement>('[data-workspace-board-lane-scroll]')
|
||||
const fallbackLaneRect = target.laneRect
|
||||
? null
|
||||
: (fallbackLaneContent ?? lane).getBoundingClientRect()
|
||||
const laneRect =
|
||||
target.laneRect ??
|
||||
(fallbackLaneRect
|
||||
? {
|
||||
left: fallbackLaneRect.left,
|
||||
top: fallbackLaneRect.top,
|
||||
width: fallbackLaneRect.width
|
||||
}
|
||||
: { left: 0, top: 0, width: 0 })
|
||||
const cardRects =
|
||||
target.cardRects ??
|
||||
Array.from(lane.querySelectorAll<HTMLElement>(CARD_SELECTOR))
|
||||
.filter((card) => card.offsetParent !== null)
|
||||
.map((card) => {
|
||||
const rect = card.getBoundingClientRect()
|
||||
return { top: rect.top, bottom: rect.bottom }
|
||||
})
|
||||
const boundedDropIndex = Math.max(0, Math.min(cardRects.length, target.dropIndex))
|
||||
const y =
|
||||
cardRects.length === 0
|
||||
? laneRect.top + 14
|
||||
: boundedDropIndex === 0
|
||||
? cardRects[0]!.top - 5
|
||||
: boundedDropIndex >= cardRects.length
|
||||
? cardRects.at(-1)!.bottom + 5
|
||||
: (cardRects[boundedDropIndex - 1]!.bottom + cardRects[boundedDropIndex]!.top) / 2
|
||||
const horizontalInset = 8
|
||||
const indicator = getOrCreateDropIndicator()
|
||||
indicator.dataset.workspaceStatus = target.status
|
||||
indicator.style.setProperty('width', `${Math.max(32, laneRect.width - horizontalInset * 2)}px`)
|
||||
indicator.style.setProperty(
|
||||
'transform',
|
||||
`translate3d(${laneRect.left + horizontalInset}px, ${y}px, 0)`
|
||||
)
|
||||
indicator.style.setProperty('opacity', '1')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Worktree } from '../../../../shared/types'
|
||||
import { groupWorkspaceKanbanWorktrees } from './workspace-kanban-worktree-groups'
|
||||
|
||||
function worktree({
|
||||
id,
|
||||
displayName,
|
||||
...overrides
|
||||
}: Partial<Worktree> & Pick<Worktree, 'id' | 'displayName'>): Worktree {
|
||||
return {
|
||||
repoId: 'repo',
|
||||
path: `/tmp/${id}`,
|
||||
head: 'head',
|
||||
branch: displayName,
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
id,
|
||||
displayName,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0,
|
||||
...overrides
|
||||
} as Worktree
|
||||
}
|
||||
|
||||
const statuses = [
|
||||
{ id: 'todo', label: 'Todo' },
|
||||
{ id: 'doing', label: 'Doing' }
|
||||
]
|
||||
|
||||
describe('groupWorkspaceKanbanWorktrees', () => {
|
||||
it('uses manualOrder inside lanes when Manual sort is active', () => {
|
||||
const grouped = groupWorkspaceKanbanWorktrees({
|
||||
worktrees: [
|
||||
worktree({
|
||||
id: 'a',
|
||||
displayName: 'A',
|
||||
workspaceStatus: 'doing',
|
||||
manualOrder: 100,
|
||||
lastActivityAt: 10
|
||||
}),
|
||||
worktree({
|
||||
id: 'b',
|
||||
displayName: 'B',
|
||||
workspaceStatus: 'doing',
|
||||
manualOrder: 300,
|
||||
lastActivityAt: 1
|
||||
}),
|
||||
worktree({
|
||||
id: 'c',
|
||||
displayName: 'C',
|
||||
workspaceStatus: 'doing',
|
||||
manualOrder: 200,
|
||||
lastActivityAt: 50
|
||||
})
|
||||
],
|
||||
visibleWorktreeIds: new Set(['a', 'b', 'c']),
|
||||
workspaceStatuses: statuses,
|
||||
sortBy: 'manual'
|
||||
})
|
||||
|
||||
expect(grouped.get('doing')?.map((item) => item.id)).toEqual(['b', 'c', 'a'])
|
||||
})
|
||||
|
||||
it('keeps pinned then recent ordering outside Manual sort', () => {
|
||||
const grouped = groupWorkspaceKanbanWorktrees({
|
||||
worktrees: [
|
||||
worktree({
|
||||
id: 'a',
|
||||
displayName: 'A',
|
||||
workspaceStatus: 'doing',
|
||||
isPinned: false,
|
||||
lastActivityAt: 50
|
||||
}),
|
||||
worktree({
|
||||
id: 'b',
|
||||
displayName: 'B',
|
||||
workspaceStatus: 'doing',
|
||||
isPinned: true,
|
||||
lastActivityAt: 1
|
||||
})
|
||||
],
|
||||
visibleWorktreeIds: new Set(['a', 'b']),
|
||||
workspaceStatuses: statuses,
|
||||
sortBy: 'recent'
|
||||
})
|
||||
|
||||
expect(grouped.get('doing')?.map((item) => item.id)).toEqual(['b', 'a'])
|
||||
})
|
||||
})
|
||||
@@ -1,16 +1,25 @@
|
||||
import type { WorkspaceStatus, WorkspaceStatusDefinition, Worktree } from '../../../../shared/types'
|
||||
import type { SortBy } from './smart-sort'
|
||||
import { getWorkspaceStatus } from './workspace-status'
|
||||
|
||||
function sortBoardWorktrees(a: Worktree, b: Worktree): number {
|
||||
return b.lastActivityAt - a.lastActivityAt || a.displayName.localeCompare(b.displayName)
|
||||
}
|
||||
|
||||
function sortManualBoardWorktrees(a: Worktree, b: Worktree): number {
|
||||
return (
|
||||
(b.manualOrder ?? b.sortOrder) - (a.manualOrder ?? a.sortOrder) ||
|
||||
a.displayName.localeCompare(b.displayName)
|
||||
)
|
||||
}
|
||||
|
||||
export function groupWorkspaceKanbanWorktrees(params: {
|
||||
worktrees: readonly Worktree[]
|
||||
visibleWorktreeIds: ReadonlySet<string>
|
||||
workspaceStatuses: readonly WorkspaceStatusDefinition[]
|
||||
sortBy: SortBy
|
||||
}): Map<WorkspaceStatus, Worktree[]> {
|
||||
const { worktrees, visibleWorktreeIds, workspaceStatuses } = params
|
||||
const { worktrees, visibleWorktreeIds, workspaceStatuses, sortBy } = params
|
||||
const grouped = new Map<WorkspaceStatus, Worktree[]>(
|
||||
workspaceStatuses.map((status) => [status.id, []])
|
||||
)
|
||||
@@ -23,7 +32,11 @@ export function groupWorkspaceKanbanWorktrees(params: {
|
||||
}
|
||||
|
||||
for (const items of grouped.values()) {
|
||||
items.sort((a, b) => Number(b.isPinned) - Number(a.isPinned) || sortBoardWorktrees(a, b))
|
||||
items.sort(
|
||||
sortBy === 'manual'
|
||||
? sortManualBoardWorktrees
|
||||
: (a, b) => Number(b.isPinned) - Number(a.isPinned) || sortBoardWorktrees(a, b)
|
||||
)
|
||||
}
|
||||
return grouped
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
getFullDropIndexForWorktreeDragUnit,
|
||||
getWorktreeDragUnitGroups
|
||||
} from './worktree-drag-units'
|
||||
|
||||
function header(key: string): { type: 'header'; key: string } {
|
||||
return { type: 'header', key }
|
||||
}
|
||||
|
||||
function item(id: string, depth = 0): { type: 'item'; worktree: { id: string }; depth: number } {
|
||||
return { type: 'item', worktree: { id }, depth }
|
||||
}
|
||||
|
||||
describe('getWorktreeDragUnitGroups', () => {
|
||||
it('treats expanded lineage descendants as part of the parent drag unit', () => {
|
||||
const groups = getWorktreeDragUnitGroups([
|
||||
header('all'),
|
||||
item('parent'),
|
||||
item('child', 1),
|
||||
item('grandchild', 2),
|
||||
item('sibling')
|
||||
])
|
||||
|
||||
expect(groups).toEqual([
|
||||
{
|
||||
key: 'all',
|
||||
worktreeIds: ['parent', 'sibling'],
|
||||
units: [
|
||||
{ worktreeId: 'parent', worktreeIds: ['parent', 'child', 'grandchild'] },
|
||||
{ worktreeId: 'sibling', worktreeIds: ['sibling'] }
|
||||
]
|
||||
}
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFullDropIndexForWorktreeDragUnit', () => {
|
||||
it('maps visual unit drop indexes back to full row indexes', () => {
|
||||
const groups = getWorktreeDragUnitGroups([
|
||||
header('all'),
|
||||
item('parent'),
|
||||
item('child', 1),
|
||||
item('sibling')
|
||||
])
|
||||
|
||||
expect(
|
||||
getFullDropIndexForWorktreeDragUnit({
|
||||
groups,
|
||||
sourceGroupKey: 'all',
|
||||
dropIndex: 2
|
||||
})
|
||||
).toBe(3)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { WorktreeDragGroup } from './worktree-manual-order'
|
||||
import { ALL_GROUP_KEY } from './worktree-list-groups'
|
||||
|
||||
export type WorktreeDragUnitGroup = WorktreeDragGroup & {
|
||||
units: { worktreeId: string; worktreeIds: string[] }[]
|
||||
}
|
||||
|
||||
type WorktreeDragUnitRow =
|
||||
| { type: 'header'; key: string }
|
||||
| { type: 'item'; worktree: { id: string }; depth: number }
|
||||
|
||||
export function getWorktreeDragUnitGroups(
|
||||
rows: readonly WorktreeDragUnitRow[]
|
||||
): WorktreeDragUnitGroup[] {
|
||||
const groups: WorktreeDragUnitGroup[] = []
|
||||
let current: { key: string; units: WorktreeDragUnitGroup['units'] } | null = null
|
||||
|
||||
for (const row of rows) {
|
||||
if (row.type === 'header') {
|
||||
current = { key: row.key, units: [] }
|
||||
groups.push({
|
||||
key: current.key,
|
||||
units: current.units,
|
||||
worktreeIds: current.units.map((unit) => unit.worktreeId)
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (!current) {
|
||||
current = { key: ALL_GROUP_KEY, units: [] }
|
||||
groups.push({
|
||||
key: current.key,
|
||||
units: current.units,
|
||||
worktreeIds: current.units.map((unit) => unit.worktreeId)
|
||||
})
|
||||
}
|
||||
if (row.depth > 0 && current.units.length > 0) {
|
||||
current.units.at(-1)!.worktreeIds.push(row.worktree.id)
|
||||
continue
|
||||
}
|
||||
current.units.push({ worktreeId: row.worktree.id, worktreeIds: [row.worktree.id] })
|
||||
}
|
||||
|
||||
return groups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
worktreeIds: group.units.map((unit) => unit.worktreeId)
|
||||
}))
|
||||
.filter((group) => group.worktreeIds.length > 0)
|
||||
}
|
||||
|
||||
export function getFullDropIndexForWorktreeDragUnit(args: {
|
||||
groups: readonly WorktreeDragUnitGroup[]
|
||||
sourceGroupKey: string
|
||||
dropIndex: number
|
||||
}): number {
|
||||
const group = args.groups.find((candidate) => candidate.key === args.sourceGroupKey)
|
||||
if (!group) {
|
||||
return args.dropIndex
|
||||
}
|
||||
const boundedDropIndex = Math.max(0, Math.min(group.units.length, args.dropIndex))
|
||||
let fullDropIndex = 0
|
||||
for (let index = 0; index < boundedDropIndex; index++) {
|
||||
fullDropIndex += group.units[index]?.worktreeIds.length ?? 0
|
||||
}
|
||||
return fullDropIndex
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
export type WorktreeManualOrderUpdate = {
|
||||
manualOrder: number
|
||||
}
|
||||
|
||||
const MANUAL_ORDER_STRIDE = 1000
|
||||
|
||||
function buildFallbackManualOrderUpdates(
|
||||
orderedIds: readonly string[],
|
||||
now: number
|
||||
): Map<string, WorktreeManualOrderUpdate> {
|
||||
const updates = new Map<string, WorktreeManualOrderUpdate>()
|
||||
for (let index = 0; index < orderedIds.length; index++) {
|
||||
updates.set(orderedIds[index]!, { manualOrder: now - index * MANUAL_ORDER_STRIDE })
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
function getManualOrderRank(
|
||||
rankByWorktreeId: ReadonlyMap<string, number>,
|
||||
worktreeId: string | undefined
|
||||
): number | null {
|
||||
if (!worktreeId) {
|
||||
return null
|
||||
}
|
||||
const rank = rankByWorktreeId.get(worktreeId)
|
||||
return typeof rank === 'number' && Number.isFinite(rank) ? rank : null
|
||||
}
|
||||
|
||||
export function buildSparseManualOrderUpdates(args: {
|
||||
orderedIds: readonly string[]
|
||||
movedIds: readonly string[]
|
||||
rankByWorktreeId?: ReadonlyMap<string, number>
|
||||
now: number
|
||||
}): Map<string, WorktreeManualOrderUpdate> {
|
||||
const movedSet = new Set(args.movedIds)
|
||||
const orderedMovedIds = args.orderedIds.filter((id) => movedSet.has(id))
|
||||
if (orderedMovedIds.length === 0) {
|
||||
return new Map()
|
||||
}
|
||||
if (!args.rankByWorktreeId) {
|
||||
return buildFallbackManualOrderUpdates(args.orderedIds, args.now)
|
||||
}
|
||||
|
||||
const firstMovedIndex = args.orderedIds.findIndex((id) => movedSet.has(id))
|
||||
const lastMovedIndex = args.orderedIds.findLastIndex((id) => movedSet.has(id))
|
||||
const beforeId = args.orderedIds.slice(0, firstMovedIndex).findLast((id) => !movedSet.has(id))
|
||||
const afterId = args.orderedIds.slice(lastMovedIndex + 1).find((id) => !movedSet.has(id))
|
||||
const beforeRank = getManualOrderRank(args.rankByWorktreeId, beforeId)
|
||||
const afterRank = getManualOrderRank(args.rankByWorktreeId, afterId)
|
||||
const nextRanks: number[] = []
|
||||
|
||||
if (beforeId !== undefined && beforeRank === null) {
|
||||
return buildFallbackManualOrderUpdates(args.orderedIds, args.now)
|
||||
}
|
||||
if (afterId !== undefined && afterRank === null) {
|
||||
return buildFallbackManualOrderUpdates(args.orderedIds, args.now)
|
||||
}
|
||||
|
||||
if (beforeRank === null && afterRank === null) {
|
||||
for (let index = 0; index < orderedMovedIds.length; index++) {
|
||||
nextRanks.push(args.now - index * MANUAL_ORDER_STRIDE)
|
||||
}
|
||||
} else if (beforeRank === null) {
|
||||
const start = Math.max(args.now, afterRank! + orderedMovedIds.length * MANUAL_ORDER_STRIDE)
|
||||
for (let index = 0; index < orderedMovedIds.length; index++) {
|
||||
nextRanks.push(start - index * MANUAL_ORDER_STRIDE)
|
||||
}
|
||||
} else if (afterRank === null) {
|
||||
for (let index = 0; index < orderedMovedIds.length; index++) {
|
||||
nextRanks.push(beforeRank - (index + 1) * MANUAL_ORDER_STRIDE)
|
||||
}
|
||||
} else {
|
||||
const gap = beforeRank - afterRank
|
||||
// Why: repeated sparse inserts can eventually exhaust the numeric gap.
|
||||
// Re-index only in that rare dense case; ordinary drags persist moved rows.
|
||||
if (gap <= orderedMovedIds.length) {
|
||||
return buildFallbackManualOrderUpdates(args.orderedIds, args.now)
|
||||
}
|
||||
const step = gap / (orderedMovedIds.length + 1)
|
||||
for (let index = 0; index < orderedMovedIds.length; index++) {
|
||||
nextRanks.push(beforeRank - step * (index + 1))
|
||||
}
|
||||
}
|
||||
|
||||
const updates = new Map<string, WorktreeManualOrderUpdate>()
|
||||
orderedMovedIds.forEach((id, index) => {
|
||||
const manualOrder = nextRanks[index]
|
||||
if (manualOrder !== undefined && Number.isFinite(manualOrder)) {
|
||||
updates.set(id, { manualOrder })
|
||||
}
|
||||
})
|
||||
return updates
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildManualOrderUpdatesForGroupDrop,
|
||||
buildWorktreeDragPreviewOffsets,
|
||||
buildManualOrderUpdatesForVisibleGroups,
|
||||
expandDraggedWorktreeIdsForVisibleLineage,
|
||||
moveWorktreeIdsWithinGroup,
|
||||
shouldWriteManualOrderForGroupDrop
|
||||
} from './worktree-manual-order'
|
||||
|
||||
describe('expandDraggedWorktreeIdsForVisibleLineage', () => {
|
||||
it('expands an expanded lineage parent to its visible descendants for reordering', () => {
|
||||
expect(
|
||||
expandDraggedWorktreeIdsForVisibleLineage(
|
||||
[
|
||||
{ worktreeId: 'parent', depth: 0 },
|
||||
{ worktreeId: 'child', depth: 1 },
|
||||
{ worktreeId: 'grandchild', depth: 2 },
|
||||
{ worktreeId: 'sibling', depth: 0 }
|
||||
],
|
||||
['parent']
|
||||
)
|
||||
).toEqual(['parent', 'child', 'grandchild'])
|
||||
})
|
||||
|
||||
it('keeps unrelated selected rows in visual order', () => {
|
||||
expect(
|
||||
expandDraggedWorktreeIdsForVisibleLineage(
|
||||
[
|
||||
{ worktreeId: 'a', depth: 0 },
|
||||
{ worktreeId: 'parent', depth: 0 },
|
||||
{ worktreeId: 'child', depth: 1 },
|
||||
{ worktreeId: 'z', depth: 0 }
|
||||
],
|
||||
['z', 'parent']
|
||||
)
|
||||
).toEqual(['parent', 'child', 'z'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('moveWorktreeIdsWithinGroup', () => {
|
||||
it('moves a worktree down using the original drop index', () => {
|
||||
expect(moveWorktreeIdsWithinGroup(['a', 'b', 'c', 'd'], ['b'], 4)).toEqual(['a', 'c', 'd', 'b'])
|
||||
})
|
||||
|
||||
it('moves a worktree up', () => {
|
||||
expect(moveWorktreeIdsWithinGroup(['a', 'b', 'c'], ['c'], 0)).toEqual(['c', 'a', 'b'])
|
||||
})
|
||||
|
||||
it('preserves selected order for multi-drag batches', () => {
|
||||
expect(moveWorktreeIdsWithinGroup(['a', 'b', 'c', 'd'], ['c', 'b'], 4)).toEqual([
|
||||
'a',
|
||||
'd',
|
||||
'b',
|
||||
'c'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWorktreeDragPreviewOffsets', () => {
|
||||
it('slides intervening rows up while dragging a row down', () => {
|
||||
const offsets = buildWorktreeDragPreviewOffsets({
|
||||
groupIds: ['a', 'b', 'c', 'd'],
|
||||
draggedIds: ['b'],
|
||||
dropIndex: 4,
|
||||
rects: [
|
||||
{ worktreeId: 'a', groupIndex: 0, top: 0, bottom: 50 },
|
||||
{ worktreeId: 'b', groupIndex: 1, top: 56, bottom: 106 },
|
||||
{ worktreeId: 'c', groupIndex: 2, top: 112, bottom: 162 },
|
||||
{ worktreeId: 'd', groupIndex: 3, top: 168, bottom: 218 }
|
||||
]
|
||||
})
|
||||
|
||||
expect(Array.from(offsets)).toEqual([
|
||||
['c', -56],
|
||||
['d', -56]
|
||||
])
|
||||
})
|
||||
|
||||
it('slides intervening rows down while dragging a row up', () => {
|
||||
const offsets = buildWorktreeDragPreviewOffsets({
|
||||
groupIds: ['a', 'b', 'c'],
|
||||
draggedIds: ['c'],
|
||||
dropIndex: 0,
|
||||
rects: [
|
||||
{ worktreeId: 'a', groupIndex: 0, top: 0, bottom: 40 },
|
||||
{ worktreeId: 'b', groupIndex: 1, top: 46, bottom: 86 },
|
||||
{ worktreeId: 'c', groupIndex: 2, top: 92, bottom: 132 }
|
||||
]
|
||||
})
|
||||
|
||||
expect(Array.from(offsets)).toEqual([
|
||||
['a', 46],
|
||||
['b', 46]
|
||||
])
|
||||
})
|
||||
|
||||
it('returns no preview offsets for a no-op hover', () => {
|
||||
const offsets = buildWorktreeDragPreviewOffsets({
|
||||
groupIds: ['a', 'b'],
|
||||
draggedIds: ['a'],
|
||||
dropIndex: 1,
|
||||
rects: [
|
||||
{ worktreeId: 'a', groupIndex: 0, top: 0, bottom: 40 },
|
||||
{ worktreeId: 'b', groupIndex: 1, top: 46, bottom: 86 }
|
||||
]
|
||||
})
|
||||
|
||||
expect(offsets.size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildManualOrderUpdatesForVisibleGroups', () => {
|
||||
it('updates every visible workspace order while only moving the source group', () => {
|
||||
const result = buildManualOrderUpdatesForVisibleGroups({
|
||||
groups: [
|
||||
{ key: 'workspace-status:todo', worktreeIds: ['todo-a', 'todo-b'] },
|
||||
{ key: 'workspace-status:done', worktreeIds: ['done-a', 'done-b'] }
|
||||
],
|
||||
sourceGroupKey: 'workspace-status:todo',
|
||||
draggedIds: ['todo-b'],
|
||||
dropIndex: 0,
|
||||
now: 10_000
|
||||
})
|
||||
|
||||
expect(result.changed).toBe(true)
|
||||
expect(result.orderedIds).toEqual(['todo-b', 'todo-a', 'done-a', 'done-b'])
|
||||
expect(Array.from(result.updates)).toEqual([
|
||||
['todo-b', { manualOrder: 10_000 }],
|
||||
['todo-a', { manualOrder: 9000 }],
|
||||
['done-a', { manualOrder: 8000 }],
|
||||
['done-b', { manualOrder: 7000 }]
|
||||
])
|
||||
})
|
||||
|
||||
it('returns no updates for a no-op drop', () => {
|
||||
const result = buildManualOrderUpdatesForVisibleGroups({
|
||||
groups: [{ key: 'repo:one', worktreeIds: ['a', 'b'] }],
|
||||
sourceGroupKey: 'repo:one',
|
||||
draggedIds: ['a'],
|
||||
dropIndex: 1,
|
||||
now: 10_000
|
||||
})
|
||||
|
||||
expect(result.changed).toBe(false)
|
||||
expect(result.updates.size).toBe(0)
|
||||
})
|
||||
|
||||
it('only updates moved rows when current ranks leave room', () => {
|
||||
const result = buildManualOrderUpdatesForVisibleGroups({
|
||||
groups: [{ key: 'repo:one', worktreeIds: ['a', 'b', 'c', 'd'] }],
|
||||
sourceGroupKey: 'repo:one',
|
||||
draggedIds: ['b'],
|
||||
dropIndex: 4,
|
||||
now: 10_000,
|
||||
rankByWorktreeId: new Map([
|
||||
['a', 4000],
|
||||
['b', 3000],
|
||||
['c', 2000],
|
||||
['d', 1000]
|
||||
])
|
||||
})
|
||||
|
||||
expect(result.orderedIds).toEqual(['a', 'c', 'd', 'b'])
|
||||
expect(Array.from(result.updates)).toEqual([['b', { manualOrder: 0 }]])
|
||||
})
|
||||
|
||||
it('moves an expanded lineage cluster as one ranked unit', () => {
|
||||
const result = buildManualOrderUpdatesForVisibleGroups({
|
||||
groups: [{ key: 'all', worktreeIds: ['parent', 'child', 'other'] }],
|
||||
sourceGroupKey: 'all',
|
||||
draggedIds: ['parent', 'child'],
|
||||
dropIndex: 3,
|
||||
now: 10_000,
|
||||
rankByWorktreeId: new Map([
|
||||
['parent', 3000],
|
||||
['child', 2000],
|
||||
['other', 1000]
|
||||
])
|
||||
})
|
||||
|
||||
expect(result.orderedIds).toEqual(['other', 'parent', 'child'])
|
||||
expect(Array.from(result.updates)).toEqual([
|
||||
['parent', { manualOrder: 0 }],
|
||||
['child', { manualOrder: -1000 }]
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildManualOrderUpdatesForGroupDrop', () => {
|
||||
it('moves a selected batch across groups and stamps visible manual order', () => {
|
||||
const result = buildManualOrderUpdatesForGroupDrop({
|
||||
groups: [
|
||||
{ key: 'todo', worktreeIds: ['todo-a', 'todo-b'] },
|
||||
{ key: 'doing', worktreeIds: ['doing-a', 'doing-b'] }
|
||||
],
|
||||
targetGroupKey: 'doing',
|
||||
draggedIds: ['todo-b'],
|
||||
dropIndex: 1,
|
||||
now: 10_000
|
||||
})
|
||||
|
||||
expect(result.changed).toBe(true)
|
||||
expect(result.orderedIds).toEqual(['todo-a', 'doing-a', 'todo-b', 'doing-b'])
|
||||
expect(Array.from(result.updates)).toEqual([
|
||||
['todo-a', { manualOrder: 10_000 }],
|
||||
['doing-a', { manualOrder: 9000 }],
|
||||
['todo-b', { manualOrder: 8000 }],
|
||||
['doing-b', { manualOrder: 7000 }]
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps visual order for multi-select batches spanning groups', () => {
|
||||
const result = buildManualOrderUpdatesForGroupDrop({
|
||||
groups: [
|
||||
{ key: 'todo', worktreeIds: ['a', 'b'] },
|
||||
{ key: 'doing', worktreeIds: ['c', 'd'] }
|
||||
],
|
||||
targetGroupKey: 'doing',
|
||||
draggedIds: ['d', 'b'],
|
||||
dropIndex: 0,
|
||||
now: 10_000
|
||||
})
|
||||
|
||||
expect(result.orderedIds).toEqual(['a', 'b', 'd', 'c'])
|
||||
})
|
||||
|
||||
it('returns no updates for a no-op same-group drop', () => {
|
||||
const result = buildManualOrderUpdatesForGroupDrop({
|
||||
groups: [{ key: 'doing', worktreeIds: ['a', 'b'] }],
|
||||
targetGroupKey: 'doing',
|
||||
draggedIds: ['a'],
|
||||
dropIndex: 1,
|
||||
now: 10_000
|
||||
})
|
||||
|
||||
expect(result.changed).toBe(false)
|
||||
expect(result.updates.size).toBe(0)
|
||||
})
|
||||
|
||||
it('uses sparse moved-row ranks for cross-lane manual drops', () => {
|
||||
const result = buildManualOrderUpdatesForGroupDrop({
|
||||
groups: [
|
||||
{ key: 'todo', worktreeIds: ['todo-a', 'todo-b'] },
|
||||
{ key: 'doing', worktreeIds: ['doing-a', 'doing-b'] }
|
||||
],
|
||||
targetGroupKey: 'doing',
|
||||
draggedIds: ['todo-b'],
|
||||
dropIndex: 1,
|
||||
now: 10_000,
|
||||
rankByWorktreeId: new Map([
|
||||
['todo-a', 4000],
|
||||
['todo-b', 3000],
|
||||
['doing-a', 2000],
|
||||
['doing-b', 1000]
|
||||
])
|
||||
})
|
||||
|
||||
expect(result.orderedIds).toEqual(['todo-a', 'doing-a', 'todo-b', 'doing-b'])
|
||||
expect(Array.from(result.updates)).toEqual([['todo-b', { manualOrder: 1500 }]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldWriteManualOrderForGroupDrop', () => {
|
||||
it('writes order for any lane drop while Manual sort is active', () => {
|
||||
expect(
|
||||
shouldWriteManualOrderForGroupDrop({
|
||||
sortBy: 'manual',
|
||||
sourceGroupKeys: ['todo'],
|
||||
targetGroupKey: 'doing'
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('writes order for same-lane drops outside Manual sort', () => {
|
||||
expect(
|
||||
shouldWriteManualOrderForGroupDrop({
|
||||
sortBy: 'recent',
|
||||
sourceGroupKeys: ['doing', 'doing'],
|
||||
targetGroupKey: 'doing'
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps cross-lane drops status-only outside Manual sort', () => {
|
||||
expect(
|
||||
shouldWriteManualOrderForGroupDrop({
|
||||
sortBy: 'recent',
|
||||
sourceGroupKeys: ['todo', 'doing'],
|
||||
targetGroupKey: 'doing'
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,293 @@
|
||||
import {
|
||||
buildSparseManualOrderUpdates,
|
||||
type WorktreeManualOrderUpdate
|
||||
} from './worktree-manual-order-ranks'
|
||||
|
||||
export type { WorktreeManualOrderUpdate } from './worktree-manual-order-ranks'
|
||||
|
||||
export type WorktreeDragGroup = {
|
||||
key: string
|
||||
worktreeIds: readonly string[]
|
||||
}
|
||||
|
||||
export type WorktreeDragLineageRow = {
|
||||
worktreeId: string
|
||||
depth: number
|
||||
}
|
||||
|
||||
export type WorktreeDragPreviewRect = {
|
||||
worktreeId: string
|
||||
groupIndex: number
|
||||
top: number
|
||||
bottom: number
|
||||
}
|
||||
|
||||
function arraysEqual(a: readonly string[], b: readonly string[]): boolean {
|
||||
return a.length === b.length && a.every((value, index) => value === b[index])
|
||||
}
|
||||
|
||||
export function expandDraggedWorktreeIdsForVisibleLineage(
|
||||
rows: readonly WorktreeDragLineageRow[],
|
||||
draggedIds: readonly string[]
|
||||
): string[] {
|
||||
const draggedSet = new Set(draggedIds)
|
||||
const expandedSet = new Set(draggedIds)
|
||||
const rowIdSet = new Set(rows.map((row) => row.worktreeId))
|
||||
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
const row = rows[index]!
|
||||
if (!draggedSet.has(row.worktreeId)) {
|
||||
continue
|
||||
}
|
||||
for (let cursor = index + 1; cursor < rows.length; cursor++) {
|
||||
const child = rows[cursor]!
|
||||
if (child.depth <= row.depth) {
|
||||
break
|
||||
}
|
||||
expandedSet.add(child.worktreeId)
|
||||
}
|
||||
}
|
||||
|
||||
const expandedIds: string[] = []
|
||||
for (const row of rows) {
|
||||
if (expandedSet.has(row.worktreeId)) {
|
||||
expandedIds.push(row.worktreeId)
|
||||
}
|
||||
}
|
||||
for (const id of draggedIds) {
|
||||
if (!rowIdSet.has(id) && !expandedIds.includes(id)) {
|
||||
expandedIds.push(id)
|
||||
}
|
||||
}
|
||||
return expandedIds
|
||||
}
|
||||
|
||||
export function moveWorktreeIdsWithinGroup(
|
||||
groupIds: readonly string[],
|
||||
draggedIds: readonly string[],
|
||||
dropIndex: number
|
||||
): string[] {
|
||||
if (groupIds.length === 0 || draggedIds.length === 0) {
|
||||
return [...groupIds]
|
||||
}
|
||||
|
||||
const groupIdSet = new Set(groupIds)
|
||||
const draggedSet = new Set<string>()
|
||||
const orderedDraggedIds: string[] = []
|
||||
for (const id of draggedIds) {
|
||||
if (!groupIdSet.has(id) || draggedSet.has(id)) {
|
||||
continue
|
||||
}
|
||||
draggedSet.add(id)
|
||||
}
|
||||
for (const id of groupIds) {
|
||||
if (draggedSet.has(id)) {
|
||||
orderedDraggedIds.push(id)
|
||||
}
|
||||
}
|
||||
if (orderedDraggedIds.length === 0) {
|
||||
return [...groupIds]
|
||||
}
|
||||
|
||||
const boundedDropIndex = Math.max(0, Math.min(groupIds.length, dropIndex))
|
||||
let removedBeforeDrop = 0
|
||||
for (let i = 0; i < boundedDropIndex; i++) {
|
||||
const id = groupIds[i]
|
||||
if (id !== undefined && draggedSet.has(id)) {
|
||||
removedBeforeDrop++
|
||||
}
|
||||
}
|
||||
|
||||
const remaining = groupIds.filter((id) => !draggedSet.has(id))
|
||||
const insertAt = Math.max(0, Math.min(remaining.length, boundedDropIndex - removedBeforeDrop))
|
||||
const next = remaining.slice()
|
||||
next.splice(insertAt, 0, ...orderedDraggedIds)
|
||||
return next
|
||||
}
|
||||
|
||||
export function buildManualOrderUpdatesForVisibleGroups(args: {
|
||||
groups: readonly WorktreeDragGroup[]
|
||||
sourceGroupKey: string
|
||||
draggedIds: readonly string[]
|
||||
dropIndex: number
|
||||
now: number
|
||||
rankByWorktreeId?: ReadonlyMap<string, number>
|
||||
}): {
|
||||
changed: boolean
|
||||
orderedIds: string[]
|
||||
updates: Map<string, WorktreeManualOrderUpdate>
|
||||
} {
|
||||
const orderedIds: string[] = []
|
||||
let changed = false
|
||||
|
||||
for (const group of args.groups) {
|
||||
const ids =
|
||||
group.key === args.sourceGroupKey
|
||||
? moveWorktreeIdsWithinGroup(group.worktreeIds, args.draggedIds, args.dropIndex)
|
||||
: [...group.worktreeIds]
|
||||
if (group.key === args.sourceGroupKey && !arraysEqual(ids, group.worktreeIds)) {
|
||||
changed = true
|
||||
}
|
||||
orderedIds.push(...ids)
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
return { changed, orderedIds, updates: new Map() }
|
||||
}
|
||||
|
||||
return {
|
||||
changed,
|
||||
orderedIds,
|
||||
updates: buildSparseManualOrderUpdates({
|
||||
orderedIds,
|
||||
movedIds: args.draggedIds,
|
||||
rankByWorktreeId: args.rankByWorktreeId,
|
||||
now: args.now
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function buildManualOrderUpdatesForGroupDrop(args: {
|
||||
groups: readonly WorktreeDragGroup[]
|
||||
targetGroupKey: string
|
||||
draggedIds: readonly string[]
|
||||
dropIndex: number
|
||||
now: number
|
||||
rankByWorktreeId?: ReadonlyMap<string, number>
|
||||
}): {
|
||||
changed: boolean
|
||||
orderedIds: string[]
|
||||
updates: Map<string, WorktreeManualOrderUpdate>
|
||||
} {
|
||||
const draggedSet = new Set<string>()
|
||||
for (const id of args.draggedIds) {
|
||||
draggedSet.add(id)
|
||||
}
|
||||
|
||||
const orderedDraggedIds: string[] = []
|
||||
for (const group of args.groups) {
|
||||
for (const id of group.worktreeIds) {
|
||||
if (draggedSet.has(id) && !orderedDraggedIds.includes(id)) {
|
||||
orderedDraggedIds.push(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (orderedDraggedIds.length === 0) {
|
||||
return {
|
||||
changed: false,
|
||||
orderedIds: args.groups.flatMap((group) => group.worktreeIds),
|
||||
updates: new Map()
|
||||
}
|
||||
}
|
||||
|
||||
const orderedIds: string[] = []
|
||||
let changed = false
|
||||
for (const group of args.groups) {
|
||||
let ids: string[]
|
||||
if (group.key === args.targetGroupKey) {
|
||||
const boundedDropIndex = Math.max(0, Math.min(group.worktreeIds.length, args.dropIndex))
|
||||
let removedBeforeDrop = 0
|
||||
for (let index = 0; index < boundedDropIndex; index++) {
|
||||
const id = group.worktreeIds[index]
|
||||
if (id !== undefined && draggedSet.has(id)) {
|
||||
removedBeforeDrop++
|
||||
}
|
||||
}
|
||||
ids = group.worktreeIds.filter((id) => !draggedSet.has(id))
|
||||
ids.splice(
|
||||
Math.max(0, Math.min(ids.length, boundedDropIndex - removedBeforeDrop)),
|
||||
0,
|
||||
...orderedDraggedIds
|
||||
)
|
||||
} else {
|
||||
ids = group.worktreeIds.filter((id) => !draggedSet.has(id))
|
||||
}
|
||||
|
||||
if (!arraysEqual(ids, group.worktreeIds)) {
|
||||
changed = true
|
||||
}
|
||||
orderedIds.push(...ids)
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
return { changed, orderedIds, updates: new Map() }
|
||||
}
|
||||
return {
|
||||
changed,
|
||||
orderedIds,
|
||||
updates: buildSparseManualOrderUpdates({
|
||||
orderedIds,
|
||||
movedIds: orderedDraggedIds,
|
||||
rankByWorktreeId: args.rankByWorktreeId,
|
||||
now: args.now
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldWriteManualOrderForGroupDrop(args: {
|
||||
sortBy: string
|
||||
sourceGroupKeys: readonly string[]
|
||||
targetGroupKey: string
|
||||
}): boolean {
|
||||
if (args.sortBy === 'manual') {
|
||||
return true
|
||||
}
|
||||
return (
|
||||
args.sourceGroupKeys.length > 0 &&
|
||||
args.sourceGroupKeys.every((sourceGroupKey) => sourceGroupKey === args.targetGroupKey)
|
||||
)
|
||||
}
|
||||
|
||||
function getFallbackStride(rects: readonly WorktreeDragPreviewRect[]): number {
|
||||
const sortedRects = [...rects].sort((a, b) => a.groupIndex - b.groupIndex)
|
||||
const strides: number[] = []
|
||||
for (let index = 1; index < sortedRects.length; index++) {
|
||||
strides.push(sortedRects[index]!.top - sortedRects[index - 1]!.top)
|
||||
}
|
||||
if (strides.length > 0) {
|
||||
strides.sort((a, b) => a - b)
|
||||
return strides[Math.floor(strides.length / 2)]!
|
||||
}
|
||||
const firstRect = sortedRects[0]
|
||||
return firstRect ? firstRect.bottom - firstRect.top : 0
|
||||
}
|
||||
|
||||
export function buildWorktreeDragPreviewOffsets(args: {
|
||||
groupIds: readonly string[]
|
||||
draggedIds: readonly string[]
|
||||
dropIndex: number
|
||||
rects: readonly WorktreeDragPreviewRect[]
|
||||
}): Map<string, number> {
|
||||
const nextIds = moveWorktreeIdsWithinGroup(args.groupIds, args.draggedIds, args.dropIndex)
|
||||
if (arraysEqual(nextIds, args.groupIds)) {
|
||||
return new Map()
|
||||
}
|
||||
|
||||
const draggedSet = new Set(args.draggedIds)
|
||||
const newIndexById = new Map<string, number>()
|
||||
nextIds.forEach((id, index) => newIndexById.set(id, index))
|
||||
|
||||
const topByGroupIndex = new Map<number, number>()
|
||||
for (const rect of args.rects) {
|
||||
topByGroupIndex.set(rect.groupIndex, rect.top)
|
||||
}
|
||||
|
||||
const fallbackStride = getFallbackStride(args.rects)
|
||||
const offsets = new Map<string, number>()
|
||||
for (const rect of args.rects) {
|
||||
if (draggedSet.has(rect.worktreeId)) {
|
||||
continue
|
||||
}
|
||||
const newIndex = newIndexById.get(rect.worktreeId)
|
||||
if (newIndex === undefined) {
|
||||
continue
|
||||
}
|
||||
const targetTop =
|
||||
topByGroupIndex.get(newIndex) ?? rect.top + (newIndex - rect.groupIndex) * fallbackStride
|
||||
const offset = targetTop - rect.top
|
||||
if (Math.abs(offset) >= 0.5) {
|
||||
offsets.set(rect.worktreeId, offset)
|
||||
}
|
||||
}
|
||||
return offsets
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
const POINTER_DRAGGING_ATTR = 'data-worktree-sidebar-pointer-dragging'
|
||||
const POINTER_DRAG_PREVIEW_ATTR = 'data-worktree-sidebar-drag-preview'
|
||||
const POINTER_DRAG_COUNT_ATTR = 'data-worktree-sidebar-drag-count'
|
||||
|
||||
const INTERACTIVE_DRAG_BLOCKER_SELECTOR = [
|
||||
'button',
|
||||
'a[href]',
|
||||
'input',
|
||||
'textarea',
|
||||
'select',
|
||||
'[contenteditable=""]',
|
||||
'[contenteditable="true"]',
|
||||
'[role="button"]',
|
||||
'[role="menuitem"]',
|
||||
'[data-radix-collection-item]',
|
||||
'[data-workspace-board-preserve-open]'
|
||||
].join(',')
|
||||
|
||||
export function isSidebarPointerDragBlocked(target: EventTarget | null, row: HTMLElement): boolean {
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
return false
|
||||
}
|
||||
const blocker = target.closest(INTERACTIVE_DRAG_BLOCKER_SELECTOR)
|
||||
return blocker !== null && row.contains(blocker) && blocker !== row
|
||||
}
|
||||
|
||||
export function setSidebarPointerDragDocumentStyles(enabled: boolean): void {
|
||||
document.body.style.cursor = enabled ? 'grabbing' : ''
|
||||
document.body.style.userSelect = enabled ? 'none' : ''
|
||||
document.documentElement.toggleAttribute(POINTER_DRAGGING_ATTR, enabled)
|
||||
}
|
||||
|
||||
function stripDuplicatePreviewAttributes(preview: HTMLElement): void {
|
||||
preview.removeAttribute('id')
|
||||
preview.removeAttribute('aria-describedby')
|
||||
preview.removeAttribute('data-worktree-drag-id')
|
||||
preview.querySelectorAll<HTMLElement>('[id],[aria-describedby]').forEach((element) => {
|
||||
element.removeAttribute('id')
|
||||
element.removeAttribute('aria-describedby')
|
||||
})
|
||||
preview.querySelectorAll<HTMLElement>('[data-worktree-drag-id]').forEach((element) => {
|
||||
element.removeAttribute('data-worktree-drag-id')
|
||||
})
|
||||
}
|
||||
|
||||
export function updateSidebarDragPreviewPosition(args: {
|
||||
preview: HTMLElement
|
||||
pointerX: number
|
||||
pointerY: number
|
||||
offsetX: number
|
||||
offsetY: number
|
||||
}): void {
|
||||
const x = args.pointerX - args.offsetX
|
||||
const y = args.pointerY - args.offsetY
|
||||
args.preview.style.transform = `translate3d(${x}px, ${y}px, 0) scale(1.015)`
|
||||
}
|
||||
|
||||
export function createSidebarDragPreview(args: {
|
||||
sourceRow: HTMLElement
|
||||
pointerX: number
|
||||
pointerY: number
|
||||
draggedCount: number
|
||||
}): { preview: HTMLElement; offsetX: number; offsetY: number } {
|
||||
const rect = args.sourceRow.getBoundingClientRect()
|
||||
const preview = document.createElement('div')
|
||||
const clone = args.sourceRow.cloneNode(true) as HTMLElement
|
||||
const offsetX = Math.min(Math.max(args.pointerX - rect.left, 0), rect.width)
|
||||
const offsetY = Math.min(Math.max(args.pointerY - rect.top, 0), rect.height)
|
||||
|
||||
stripDuplicatePreviewAttributes(clone)
|
||||
preview.setAttribute(POINTER_DRAG_PREVIEW_ATTR, 'true')
|
||||
preview.setAttribute('aria-hidden', 'true')
|
||||
preview.appendChild(clone)
|
||||
|
||||
if (args.draggedCount > 1) {
|
||||
const badge = document.createElement('span')
|
||||
badge.setAttribute(POINTER_DRAG_COUNT_ATTR, 'true')
|
||||
badge.textContent = String(args.draggedCount)
|
||||
preview.appendChild(badge)
|
||||
}
|
||||
|
||||
preview.style.position = 'fixed'
|
||||
preview.style.left = '0'
|
||||
preview.style.top = '0'
|
||||
preview.style.width = `${rect.width}px`
|
||||
preview.style.height = `${rect.height}px`
|
||||
preview.style.pointerEvents = 'none'
|
||||
preview.style.transformOrigin = 'top left'
|
||||
updateSidebarDragPreviewPosition({
|
||||
preview,
|
||||
pointerX: args.pointerX,
|
||||
pointerY: args.pointerY,
|
||||
offsetX,
|
||||
offsetY
|
||||
})
|
||||
document.body.appendChild(preview)
|
||||
return { preview, offsetX, offsetY }
|
||||
}
|
||||
@@ -394,7 +394,7 @@ export type UISlice = {
|
||||
dismissSetupScriptPrompt: (repoId: string) => void
|
||||
groupBy: 'none' | 'workspace-status' | 'repo' | 'pr-status'
|
||||
setGroupBy: (g: UISlice['groupBy']) => void
|
||||
sortBy: 'name' | 'smart' | 'recent' | 'repo'
|
||||
sortBy: 'name' | 'smart' | 'recent' | 'repo' | 'manual'
|
||||
setSortBy: (s: UISlice['sortBy']) => void
|
||||
showActiveOnly: boolean
|
||||
setShowActiveOnly: (v: boolean) => void
|
||||
|
||||
@@ -755,6 +755,34 @@ describe('createWorktree base status merge', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('stamps manualOrder on create while Manual sort is active', async () => {
|
||||
const store = createTestStore()
|
||||
store.setState({ sortBy: 'manual' } as Partial<AppState>)
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(123_456)
|
||||
const wt = makeWorktree({
|
||||
id: 'repo1::/path/wt1',
|
||||
repoId: 'repo1',
|
||||
path: '/path/wt1',
|
||||
manualOrder: 123_456
|
||||
})
|
||||
mockApi.worktrees.create.mockResolvedValue({ worktree: wt })
|
||||
|
||||
try {
|
||||
await store.getState().createWorktree('repo1', 'feature')
|
||||
} finally {
|
||||
nowSpy.mockRestore()
|
||||
}
|
||||
|
||||
expect(mockApi.worktrees.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
manualOrder: 123_456
|
||||
})
|
||||
)
|
||||
expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({
|
||||
manualOrder: 123_456
|
||||
})
|
||||
})
|
||||
|
||||
it('passes branchNameOverride through the local create IPC payload', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = makeWorktree({
|
||||
|
||||
@@ -82,6 +82,7 @@ function areWorktreesEqual(current: Worktree[] | undefined, next: Worktree[]): b
|
||||
worktree.isUnread === candidate.isUnread &&
|
||||
worktree.isPinned === candidate.isPinned &&
|
||||
worktree.sortOrder === candidate.sortOrder &&
|
||||
worktree.manualOrder === candidate.manualOrder &&
|
||||
worktree.lastActivityAt === candidate.lastActivityAt &&
|
||||
worktree.workspaceStatus === candidate.workspaceStatus &&
|
||||
worktree.createdWithAgent === candidate.createdWithAgent &&
|
||||
@@ -634,6 +635,9 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
const candidateName = nextCandidateName(name, attempt)
|
||||
const candidateBranchNameOverride = nextCandidateBranchName(branchNameOverride, attempt)
|
||||
try {
|
||||
// Why: Manual sort is user-authored order. Stamp new workspaces
|
||||
// deliberately at the top instead of relying on sortOrder fallback.
|
||||
const manualOrder = get().sortBy === 'manual' ? Date.now() : undefined
|
||||
const createArgs = {
|
||||
repoId,
|
||||
name: candidateName,
|
||||
@@ -650,6 +654,7 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
...(pushTarget ? { pushTarget } : {}),
|
||||
...(createdWithAgent ? { createdWithAgent } : {}),
|
||||
...(linkedLinearIssue !== undefined ? { linkedLinearIssue } : {}),
|
||||
...(manualOrder !== undefined ? { manualOrder } : {}),
|
||||
...(workspaceStatus !== undefined ? { workspaceStatus } : {})
|
||||
}
|
||||
const target = getActiveRuntimeTarget(get().settings)
|
||||
@@ -674,6 +679,7 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
...(pushTarget ? { pushTarget } : {}),
|
||||
...(createdWithAgent ? { createdWithAgent } : {}),
|
||||
...(linkedLinearIssue !== undefined ? { linkedLinearIssue } : {}),
|
||||
...(manualOrder !== undefined ? { manualOrder } : {}),
|
||||
...(workspaceStatus !== undefined ? { workspaceStatus } : {})
|
||||
},
|
||||
{ timeoutMs: 10 * 60_000 }
|
||||
|
||||
@@ -349,11 +349,14 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
|
||||
branchNameOverride: args.branchNameOverride,
|
||||
linkedIssue: args.linkedIssue,
|
||||
linkedPR: args.linkedPR,
|
||||
linkedLinearIssue: args.linkedLinearIssue,
|
||||
displayName: args.displayName,
|
||||
sparseCheckout: args.sparseCheckout,
|
||||
pushTarget: args.pushTarget,
|
||||
setupDecision: args.setupDecision,
|
||||
createdWithAgent: args.createdWithAgent
|
||||
createdWithAgent: args.createdWithAgent,
|
||||
workspaceStatus: args.workspaceStatus,
|
||||
manualOrder: args.manualOrder
|
||||
})
|
||||
},
|
||||
resolvePrBase: async ({ repoId, prNumber, headRefName, isCrossRepository }) =>
|
||||
|
||||
+6
-1
@@ -167,6 +167,8 @@ export type Worktree = {
|
||||
isUnread: boolean
|
||||
isPinned: boolean
|
||||
sortOrder: number
|
||||
/** User-authored sidebar ordering. Higher values render earlier in Manual sort. */
|
||||
manualOrder?: number
|
||||
lastActivityAt: number
|
||||
/** Set once when Orca creates the worktree. Absent for worktrees discovered
|
||||
* on disk or persisted before this field existed. Used by the sidebar to
|
||||
@@ -215,6 +217,8 @@ export type WorktreeMeta = {
|
||||
isUnread: boolean
|
||||
isPinned: boolean
|
||||
sortOrder: number
|
||||
/** User-authored sidebar ordering. Higher values render earlier in Manual sort. */
|
||||
manualOrder?: number
|
||||
lastActivityAt: number
|
||||
/** See {@link Worktree.createdAt}. Persisted to orca-data.json. */
|
||||
createdAt?: number
|
||||
@@ -1246,6 +1250,7 @@ export type CreateWorktreeArgs = {
|
||||
linkedLinearIssue?: string
|
||||
pushTarget?: GitPushTarget
|
||||
workspaceStatus?: WorkspaceStatus
|
||||
manualOrder?: number
|
||||
/** Agent selected in the create surface. Omitted for blank-shell creates. */
|
||||
createdWithAgent?: TuiAgent
|
||||
/** Telemetry-only: which UI surface initiated this create. Threaded from
|
||||
@@ -1984,7 +1989,7 @@ export type PersistedUIState = {
|
||||
sidebarWidth: number
|
||||
rightSidebarWidth: number
|
||||
groupBy: 'none' | 'workspace-status' | 'repo' | 'pr-status'
|
||||
sortBy: 'name' | 'smart' | 'recent' | 'repo'
|
||||
sortBy: 'name' | 'smart' | 'recent' | 'repo' | 'manual'
|
||||
/** Deprecated; the Active only filter is retired and ignored on hydration. */
|
||||
showActiveOnly: boolean
|
||||
/** Off by default: sleeping/inactive workspaces stay hidden until shown. */
|
||||
|
||||
Reference in New Issue
Block a user