refactor: Unify document selection and drag interactions by replacing stack-specific callbacks and simplifying drag state.

This commit is contained in:
2025-11-25 20:54:53 +01:00
parent 13c87f4b07
commit e0fce40bc3
10 changed files with 279 additions and 267 deletions
+36 -33
View File
@@ -171,6 +171,8 @@ interface DesktopWorkspaceViewProps extends Omit<DocumentsViewProps, 'entries' |
recalcVisibleDocIds: () => void;
dragSettings: DragSettings;
markLayoutDirty: () => void;
onSelect?: (descriptor: unknown, event?: unknown) => void;
onPromoteSelection?: (docId: Identifier, event?: unknown) => void;
}
const defaultGetDocumentAsset: GetAsset = () => null;
@@ -192,6 +194,7 @@ const DesktopWorkspace: React.FC<DocumentsViewProps> = ({
clearSelection,
handleEntrySelection,
promoteSelectionOrder,
configureSelectionEnvironment,
} = useWorkspaceSelectionContext();
const items = useMemo<DeskDocument[]>(
() => {
@@ -213,36 +216,16 @@ const DesktopWorkspace: React.FC<DocumentsViewProps> = ({
[entries],
);
const getDocRowKey = useCallback((id: Identifier | null) => (id != null ? `document:${id}` : null), []);
const handleStackSelect = useCallback(
(docIds: Identifier[], event?: PointerEvent | MouseEvent | null) => {
if (!Array.isArray(docIds) || docIds.length === 0) {
return;
}
const syntheticEvent = event || ({
metaKey: true,
ctrlKey: true,
preventDefault: () => { },
} as unknown as PointerEvent);
docIds.forEach((id) => {
const key = getDocRowKey(id);
if (key) {
handleEntrySelection(key, syntheticEvent);
}
});
},
[getDocRowKey, handleEntrySelection],
);
const getDocEntryKey = useCallback((id: Identifier | null) => (id != null ? `document:${id}` : null), []);
const handlePromoteSelection = useCallback(
(docId: Identifier | null) => {
const key = getDocRowKey(docId);
if (key && promoteSelectionOrder) {
promoteSelectionOrder(key);
const key = getDocEntryKey(docId);
if (key) {
promoteSelectionOrder(docId);
}
},
[getDocRowKey, promoteSelectionOrder],
[getDocEntryKey, promoteSelectionOrder],
);
const allowLayoutPersistence = Boolean(tenantId && viewId && viewId.startsWith('folder:'));
@@ -307,10 +290,6 @@ const DesktopWorkspace: React.FC<DocumentsViewProps> = ({
engine.setDocumentLookup(map);
}, [engine, items]);
useEffect(() => {
engine.setEnsureDocumentSize(ensureDocumentSize);
}, [engine, ensureDocumentSize]);
const workspaceSnapshot = useWorkspaceSnapshot(engine, useSyncExternalStore) as WorkspaceSnapshotState;
const {
layout: layoutSnapshot,
@@ -323,6 +302,19 @@ const DesktopWorkspace: React.FC<DocumentsViewProps> = ({
initialLoadDone,
} = workspaceSnapshot;
useEffect(() => {
const visibleEntryKeySet = new Set<string>();
visibleDocIds.forEach((id) => {
const key = getDocEntryKey(id);
if (key) visibleEntryKeySet.add(key);
});
configureSelectionEnvironment({
visibleEntryKeySet,
navigableEntryKeys: [], // Desktop doesn't have linear navigation yet
});
}, [visibleDocIds, getDocEntryKey, configureSelectionEnvironment]);
useEffect(() => {
const shouldWaitForPersisted = allowLayoutPersistence && !initialLoadDone;
@@ -794,10 +786,22 @@ const DesktopWorkspace: React.FC<DocumentsViewProps> = ({
overlayOriginRect,
overlayOriginTransform,
overlayDocument,
onDocumentStackSelect: handleStackSelect,
onPromoteSelection: handlePromoteSelection,
selectedDocumentIds,
onClearSelection: clearSelection,
onDocumentClick: passThroughProps.onDocumentClick,
onSelect: (descriptorOrDescriptors: any, event: any) => {
const descriptors = Array.isArray(descriptorOrDescriptors)
? descriptorOrDescriptors
: [descriptorOrDescriptors];
const keys = descriptors
.map((d: any) => getDocEntryKey(d.id))
.filter((k: any) => k);
if (keys.length > 0) {
handleEntrySelection(keys, event);
}
},
documentLookup,
resolveBaseMetrics,
bringToFront,
@@ -836,7 +840,6 @@ function DesktopWorkspaceView({
overlayOriginTransform,
overlayDocument,
onDocumentClick,
onDocumentStackSelect,
onPromoteSelection,
selectedDocumentIds,
onClearSelection,
@@ -850,6 +853,7 @@ function DesktopWorkspaceView({
dragSettings,
onDocumentActivate,
markLayoutDirty,
onSelect,
}: DesktopWorkspaceViewProps) {
const handleDeskDocumentActivate = useCallback(
(docId: Identifier) => {
@@ -888,7 +892,6 @@ function DesktopWorkspaceView({
settings: dragSettings,
containerRef,
onDocumentActivate: handleDeskDocumentActivate,
selectedDocumentIds,
markLayoutDirty,
}) as {
handlePointerDown: React.PointerEventHandler<HTMLElement>;
@@ -908,11 +911,11 @@ function DesktopWorkspaceView({
handlePointerUp,
handlePointerCancel,
onDocumentClick: handleDeskDocumentClick,
onDocumentStackSelect,
onPromoteSelection,
onDocumentActivate: handleDeskDocumentActivate,
selectedDocumentIds,
openOverlayForDoc,
onSelect,
});
useEffect(() => {
+51 -14
View File
@@ -42,6 +42,7 @@ export interface PointerIntent {
clickSelectionApplied: boolean;
stackSelectionApplied: boolean;
longPressTriggered: boolean;
optimisticSelection: string[];
}
export const createPointerIntent = ({
@@ -61,9 +62,9 @@ export const createPointerIntent = ({
if (metaKey) {
clickAction = CLICK_ACTIONS.addStack;
dragAction = DRAG_ACTIONS.dragSelectStack;
dragAction = DRAG_ACTIONS.dragSelection;
} else if (alreadySelected) {
clickAction = CLICK_ACTIONS.selectSingle;
clickAction = CLICK_ACTIONS.openDetail;
dragAction = selectionCount > 1 ? DRAG_ACTIONS.dragSelection : DRAG_ACTIONS.dragSelectSingle;
} else {
clickAction = CLICK_ACTIONS.selectSingle;
@@ -74,8 +75,23 @@ export const createPointerIntent = ({
? stackHits.map((value) => String(value))
: [String(doc.id)];
const stackDocIdsForDrag = dragAction === DRAG_ACTIONS.dragSelectStack ? stackList : null;
const stackDocIdsForClick = clickAction === CLICK_ACTIONS.addStack ? stackList : null;
const stackDocIdsForDrag = metaKey ? stackList : null;
// Calculate optimistic selection
let optimisticSelection: string[] = [];
if (metaKey) {
// Additive selection (stack or single)
const currentSelection = new Set(selectedDocumentIds);
stackList.forEach(id => currentSelection.add(id));
optimisticSelection = Array.from(currentSelection);
} else if (alreadySelected) {
// Already selected: keep current selection
optimisticSelection = [...selectedDocumentIds];
} else {
// New single selection
optimisticSelection = [doc.id];
}
return {
docId: doc.id,
@@ -90,33 +106,53 @@ export const createPointerIntent = ({
stackDocIdsForDrag,
stackDocIdsForClick,
stackReplaceOnClick: clickAction === CLICK_ACTIONS.addStack,
stackReplaceOnDrag: dragAction === DRAG_ACTIONS.dragSelectStack,
stackReplaceOnDrag: false,
clickSelectionApplied: false,
stackSelectionApplied: false,
longPressTriggered: false,
optimisticSelection,
};
};
export const applyClickPlanImmediately = ({ intent, event, onEntryPointer, onDocumentStackSelect }: {
export const applyClickPlanImmediately = ({ intent, event, onEntryPointer, onDocumentStackSelect, onSelect }: {
intent: PointerIntent;
event?: unknown;
onEntryPointer?: (descriptor: unknown, event?: unknown) => void;
onDocumentStackSelect?: (docIds: string[], event?: unknown, options?: { replace?: boolean }) => void;
onSelect?: (descriptor: unknown, event?: unknown) => void;
}) => {
switch (intent.clickAction) {
case CLICK_ACTIONS.selectSingle:
case CLICK_ACTIONS.addCard:
safeInvoke(onEntryPointer, intent.entryDescriptor, event);
if (onSelect) {
safeInvoke(onSelect, intent.entryDescriptor, event);
} else {
safeInvoke(onEntryPointer, intent.entryDescriptor, event);
}
intent.clickSelectionApplied = true;
break;
case CLICK_ACTIONS.addStack:
if (Array.isArray(intent.stackDocIdsForClick) && intent.stackDocIdsForClick.length > 0) {
safeInvoke(
onDocumentStackSelect,
intent.stackDocIdsForClick,
event,
{ replace: intent.stackReplaceOnClick },
);
// Use onSelect for stack selection (batch)
if (onSelect) {
// Map docIds to descriptors if necessary, or just pass IDs if onSelect handles it.
// The current onSelect adapter in DesktopWorkspace expects { id } objects or just IDs?
// Let's assume it expects descriptors like selectSingle.
const descriptors = intent.stackDocIdsForClick.map(id => ({
type: 'document',
id,
key: `document:${id}`,
}));
safeInvoke(onSelect, descriptors, event);
} else {
// Fallback to legacy if onSelect not provided (shouldn't happen in new flow)
safeInvoke(
onDocumentStackSelect,
intent.stackDocIdsForClick,
event,
{ replace: intent.stackReplaceOnClick },
);
}
intent.clickSelectionApplied = true;
intent.stackSelectionApplied = true;
}
@@ -128,17 +164,18 @@ export const applyClickPlanImmediately = ({ intent, event, onEntryPointer, onDoc
}
};
export const finalizeClickSelection = ({ intent, event, onEntryPointer, onDocumentStackSelect }: {
export const finalizeClickSelection = ({ intent, event, onEntryPointer, onDocumentStackSelect, onSelect }: {
intent: PointerIntent;
event?: unknown;
onEntryPointer?: (descriptor: unknown, event?: unknown) => void;
onDocumentStackSelect?: (docIds: string[], event?: unknown, options?: { replace?: boolean }) => void;
onSelect?: (descriptor: unknown, event?: unknown) => void;
}) => {
if (!intent || intent.clickSelectionApplied) {
return;
}
applyClickPlanImmediately({ intent, event, onEntryPointer, onDocumentStackSelect });
applyClickPlanImmediately({ intent, event, onEntryPointer, onDocumentStackSelect, onSelect });
};
export const applyLongPressSelection = ({ intent, stackDocIds, syntheticEvent, onDocumentStackSelect }: {
+16 -17
View File
@@ -33,11 +33,11 @@ export const useDeskPointer = ({
handlePointerUp,
handlePointerCancel,
onDocumentClick,
onDocumentStackSelect,
onPromoteSelection,
onDocumentActivate,
selectedDocumentIds,
openOverlayForDoc = null,
onSelect = null,
}) => {
const pointerIntentRef = useRef(null);
const pointerStartRef = useRef({ x: 0, y: 0 });
@@ -203,13 +203,13 @@ export const useDeskPointer = ({
intent,
stackDocIds: stackHits,
syntheticEvent,
onDocumentStackSelect,
onDocumentStackSelect: null, // Deprecated, handled by onSelect if needed, or long press needs update
});
pointerIntentRef.current = intent;
resetLongPressState();
}, LONG_PRESS_DURATION_MS);
},
[onDocumentStackSelect, resolveStackDocIds, resetLongPressState],
[resolveStackDocIds, resetLongPressState],
);
useEffect(() => () => resetLongPressState(), [resetLongPressState]);
@@ -242,25 +242,24 @@ export const useDeskPointer = ({
stackHits,
});
if (intent.selectedAtDown) {
safeInvoke(onPromoteSelection, doc.id, event);
}
if (intent.selectedAtDown) {
safeInvoke(onPromoteSelection, doc.id, event);
}
applyClickPlanImmediately({
intent,
event,
onEntryPointer: onDocumentClick,
onDocumentStackSelect,
});
applyClickPlanImmediately({
intent,
event,
onEntryPointer: onDocumentClick,
onSelect,
});
pointerIntentRef.current = intent;
handlePointerDown(event, doc.id, {
stackDocIds: intent.stackDocIdsForDrag,
draggedDocIds: intent.optimisticSelection,
stackSelectionApplied: intent.stackSelectionApplied,
wasSelected: intent.selectedAtDown,
modifierActive,
stackReplace: intent.stackReplaceOnDrag,
});
scheduleLongPress({
@@ -273,7 +272,7 @@ export const useDeskPointer = ({
handlePointerDown,
onPromoteSelection,
onDocumentClick,
onDocumentStackSelect,
onSelect,
resolveStackDocIds,
resetLongPressState,
scheduleLongPress,
@@ -309,7 +308,7 @@ export const useDeskPointer = ({
intent: pointerState,
event,
onEntryPointer: onDocumentClick,
onDocumentStackSelect,
onSelect,
});
if (
@@ -336,8 +335,8 @@ export const useDeskPointer = ({
[
handlePointerUp,
onDocumentActivate,
onDocumentStackSelect,
onDocumentClick,
onSelect,
resetLongPressState,
selectedDocumentIds,
],
+11 -64
View File
@@ -6,7 +6,7 @@ import {
type RefObject,
} from 'react';
import type { PointerEvent as ReactPointerEvent } from 'react';
import { preventAll, safeInvoke } from './events';
import { preventAll } from './events';
import { clamp } from '../utils/math';
import usePointerTap from '../ui/usePointerTap';
import {
@@ -83,11 +83,9 @@ interface DragSettings {
}
interface PointerDownOptions {
stackDocIds?: Array<Identifier | null>;
draggedDocIds?: string[];
stackSelectionApplied?: boolean;
wasSelected?: boolean;
modifierActive?: boolean;
stackReplace?: boolean;
}
interface UseDocumentDragOptions {
@@ -109,12 +107,6 @@ interface UseDocumentDragOptions {
settings?: DragSettings;
containerRef?: RefObject<HTMLElement>;
onDocumentActivate?: (docId: Identifier | null, event?: PointerEvent | ReactPointerEvent) => void;
onDocumentStackSelect?: (
docIds: Identifier[],
event: PointerEvent | ReactPointerEvent,
options?: { replace?: boolean },
) => void;
selectedDocumentIds?: Array<Identifier | null>;
markLayoutDirty?: () => void;
}
@@ -152,9 +144,7 @@ interface DragStateInternal extends EngineDragState {
activeDocIds: string[];
groupItems: DragGroupItemInternal[];
groupElevated: boolean;
stackDocIds: string[] | null;
stackSelectionApplied: boolean;
stackReplace: boolean;
massGrams: number;
pointerRadiusScale: number;
lastPointerCanvasX: number;
@@ -209,8 +199,6 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
settings,
containerRef: providedContainerRef,
onDocumentActivate,
onDocumentStackSelect,
selectedDocumentIds = [],
markLayoutDirty,
} = options;
@@ -342,50 +330,20 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
return;
}
const massGrams = computeDocumentMassGrams(doc);
const draggedDocIds = options?.draggedDocIds;
const stackDocIdsOptionRaw = options?.stackDocIds;
const stackDocIdsOption = Array.isArray(stackDocIdsOptionRaw)
? stackDocIdsOptionRaw
.map((value) => (value != null ? String(value) : null))
.filter((value): value is string => Boolean(value))
: null;
const stackSelectionAppliedInitial = Boolean(options?.stackSelectionApplied);
const wasSelectedAtPointerDown = Boolean(options?.wasSelected);
const pointerModifierActive =
options?.modifierActive ?? Boolean(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
const stackReplace = Boolean(options?.stackReplace);
let selectionIds: string[] = [];
let selectionIds: string[] = Array.isArray(selectedDocumentIds)
? selectedDocumentIds
.map((id) => (id != null ? String(id) : null))
.filter((id): id is string => Boolean(id))
: [];
if (!stackDocIdsOption && !pointerModifierActive && !wasSelectedAtPointerDown) {
if (Array.isArray(draggedDocIds) && draggedDocIds.length > 0) {
// Use explicitly provided IDs for the drag operation
selectionIds = draggedDocIds;
} else {
// Fallback (should ideally not happen if useDeskPointer is correct)
selectionIds = [docKey];
}
if (stackDocIdsOption && stackDocIdsOption.length) {
const selectionSet = new Set(selectionIds);
stackDocIdsOption.forEach((value) => {
if (value != null) {
selectionSet.add(String(value));
}
});
selectionIds = Array.from(selectionSet);
}
const metaOrCtrl = event.metaKey || event.ctrlKey;
if (!stackDocIdsOption && metaOrCtrl && !selectionIds.includes(docKey)) {
selectionIds = [...selectionIds, docKey];
}
selectionIds = selectionIds.filter((id, index, array) => array.indexOf(id) === index && documentLookup.has(id));
if (!selectionIds.includes(docKey)) {
selectionIds.unshift(docKey);
}
if (!selectionIds.length) {
selectionIds = [docKey];
}
@@ -413,7 +371,7 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
const centerX = Number.isFinite(entry?.centerX) ? entry.centerX : defaultCenterX;
const centerY = Number.isFinite(entry?.centerY) ? entry.centerY : defaultCenterY;
const modifierPressed = pointerModifierActive;
const modifierPressed = Boolean(options?.modifierActive);
if (!modifierPressed) {
if (isGroupDrag) {
const layout = layoutRef.current;
@@ -498,8 +456,6 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
? performance.now()
: Date.now();
const hasStackSource = Array.isArray(stackDocIdsOption) && stackDocIdsOption.length > 1;
dragStateRef.current = {
docId: docKey,
docKey,
@@ -532,9 +488,7 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
activeDocIds: selectionIds,
groupItems,
groupElevated: !isGroupDrag,
stackDocIds: hasStackSource ? stackDocIdsOption : null,
stackSelectionApplied: stackSelectionAppliedInitial || !hasStackSource,
stackReplace,
stackSelectionApplied: true,
massGrams,
pointerRadiusScale: 1,
lastPointerCanvasX: pointerCanvasX,
@@ -595,7 +549,6 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
ensureDocumentSize,
layoutRef,
resolveBaseMetrics,
selectedDocumentIds,
setDraggingId,
debugDrag,
itemRefs,
@@ -690,12 +643,7 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
state.moved = true;
if (
!state.stackSelectionApplied
&& Array.isArray(state.stackDocIds)
&& state.stackDocIds.length > 0
) {
safeInvoke(onDocumentStackSelect, state.stackDocIds as Identifier[], event, {
replace: state.stackReplace,
});
state.stackSelectionApplied = true;
}
if (!state.groupElevated) {
@@ -973,7 +921,6 @@ const useDocumentDrag = (options: UseDocumentDragOptions) => {
layoutRef,
itemRefs,
debugDrag,
onDocumentStackSelect,
setDragTransform,
],
);