chore: Replace react-dnd with dnd-kit for sidebar (#14213)

* chore: Replace react-dnd with dnd-kit for sidebar drag and drop

* fix: Do not start sidebar drags from touch pointers
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-21 21:51:21 -04:00
1 parent 4f9cbe33b1
commit c59e0f59b3
27 files changed
+1048 -522

No files matched your search

+3 -4
View File
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import * as React from "react";
import { DndProvider } from "react-dnd";
import { EditorAwareHTML5Backend } from "~/components/EditorAwareHTML5Backend";
import { DragAndDropProvider } from "~/components/DragAndDrop";
import ErrorSuspended from "~/scenes/Errors/ErrorSuspended";
import Layout from "~/components/Layout";
import RegisterKeyDown from "~/components/RegisterKeyDown";
@@ -106,7 +105,7 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
<DocumentContextProvider>
<RightSidebarProvider>
<PortalContext.Provider value={layoutElement}>
<DndProvider backend={EditorAwareHTML5Backend}>
<DragAndDropProvider>
<Layout
title={team.name}
sidebar={sidebar}
@@ -120,7 +119,7 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
<CommandBar />
<NotificationBadge />
</Layout>
</DndProvider>
</DragAndDropProvider>
</PortalContext.Provider>
</RightSidebarProvider>
</DocumentContextProvider>
@@ -0,0 +1,351 @@
import {
DndContext,
PointerSensor,
useDraggable,
useSensor,
useSensors,
type Announcements,
} from "@dnd-kit/core";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import { useTranslation } from "react-i18next";
import {
DragDropManager,
type DragSource,
type Point,
} from "./DragDropManager";
import { DragDropManagerContext } from "./hooks";
interface Props {
children: ReactNode;
}
/**
* Provides drag and drop to the hooks in this module. dnd-kit detects and
* tracks the drag; the manager resolves the drop targets under the pointer.
*/
export function DragAndDropProvider({ children }: Props) {
const { t } = useTranslation();
const [manager] = useState(() => new DragDropManager());
const activatorRef = useRef<Activator | null>(null);
const pendingRef = useRef<{ source: DragSource; pointer: Point } | null>(
null
);
const sessionRef = useRef<(() => void) | null>(null);
const titleRef = useRef("");
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 5,
},
})
);
// A single dnd-kit draggable is moved to the source under the pointer, so
// that dnd-kit context changes do not re-render every source. DndContext
// does not wrap the children, as its context changes on every move.
useEffect(() => {
const handlePointerDown = (event: PointerEvent) => {
// Touch gestures scroll the sidebar and swipe it closed instead.
if (
event.pointerType === "touch" ||
!(event.target instanceof Element) ||
event.target.closest(EDITABLE_SELECTOR)
) {
return;
}
const found = manager.findSource(event.target);
if (!found || !activatorRef.current) {
return;
}
pendingRef.current = {
source: found.source,
pointer: { x: event.clientX, y: event.clientY },
};
activatorRef.current(found.node, event);
};
// Runs before the sensor, so the move that starts a drag is included.
const handlePendingMove = (event: PointerEvent) => {
if (pendingRef.current) {
pendingRef.current.pointer = { x: event.clientX, y: event.clientY };
}
};
document.addEventListener("pointerdown", handlePointerDown);
window.addEventListener("pointermove", handlePendingMove, {
capture: true,
passive: true,
});
return () => {
document.removeEventListener("pointerdown", handlePointerDown);
window.removeEventListener("pointermove", handlePendingMove, {
capture: true,
});
};
}, [manager]);
const handleDragStart = useCallback(() => {
const pending = pendingRef.current;
pendingRef.current = null;
if (!pending) {
return;
}
manager.beginDrag(pending.source);
titleRef.current = manager.layerMonitor.getItem()?.title ?? "";
sessionRef.current = startDragSession(manager, pending.pointer);
}, [manager]);
const endSession = useCallback(() => {
sessionRef.current?.();
sessionRef.current = null;
}, []);
const handleDragEnd = useCallback(() => {
endSession();
manager.drop();
}, [manager, endSession]);
const handleDragCancel = useCallback(() => {
endSession();
manager.endDrag();
}, [manager, endSession]);
const handleDragAbort = useCallback(() => {
pendingRef.current = null;
}, []);
useEffect(() => handleDragCancel, [handleDragCancel]);
const accessibility = useMemo(() => {
const announcements: Announcements = {
onDragStart: () =>
t("Picked up {{ title }}", { title: titleRef.current }),
onDragOver: () => undefined,
onDragEnd: () => t("Dropped {{ title }}", { title: titleRef.current }),
onDragCancel: () =>
t("Cancelled dragging {{ title }}", { title: titleRef.current }),
};
return {
announcements,
screenReaderInstructions: { draggable: "" },
};
}, [t]);
return (
<DragDropManagerContext.Provider value={manager}>
<DndContext
sensors={sensors}
autoScroll={false}
accessibility={accessibility}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
onDragAbort={handleDragAbort}
>
<DragActivator activatorRef={activatorRef} />
</DndContext>
{children}
</DragDropManagerContext.Provider>
);
}
type Activator = (node: HTMLElement, event: PointerEvent) => void;
const DRAGGABLE_ID = "drag-source";
// Drags must not start from controls where the pointer selects text.
const EDITABLE_SELECTOR =
"input, textarea, select, [contenteditable='true'], [role='textbox']";
const POINTER_EVENTS = ["pointermove", "pointerup"];
// Mouse hover and move handlers do not run during a drag, as with a native
// drag. The drag itself is tracked with pointer events.
const MOUSE_EVENTS = [
"pointerover",
"pointerout",
"mouseover",
"mouseout",
"mousemove",
];
// Distance from the edge of a scroll container where dragging scrolls it.
const SCROLL_EDGE = 48;
// Scroll distance of one wheel line.
const LINE_HEIGHT = 16;
// Maximum scroll distance per frame.
const SCROLL_SPEED = 14;
/**
* Hosts the dnd-kit draggable and exposes a function that starts the dnd-kit
* sensor for a source element.
*/
function DragActivator({
activatorRef,
}: {
activatorRef: RefObject<Activator | null>;
}) {
const { setNodeRef, listeners } = useDraggable({ id: DRAGGABLE_ID });
useEffect(() => {
activatorRef.current = (node, event) => {
setNodeRef(node);
listeners?.onPointerDown?.({ nativeEvent: event });
};
return () => {
activatorRef.current = null;
};
}, [activatorRef, listeners, setNodeRef]);
return null;
}
/**
* Tracks the pointer during a drag, updates the hovered targets, scrolls the
* container under the pointer near its edges, blocks hover styles and
* handlers, and swallows the click that follows the drop.
*
* @param manager The drag and drop manager.
* @param initialPointer The pointer position where the drag started.
* @returns a function that ends the session.
*/
function startDragSession(
manager: DragDropManager,
initialPointer: Point
): () => void {
let pointer = initialPointer;
let hovered: Element | null = null;
let scroller: HTMLElement | null = null;
let scrollerRect: DOMRect | undefined;
let frame = 0;
// A transparent layer takes the pointer so that no element shows a hover
// style, as with a native drag. Hit testing looks through it.
const overlay = document.createElement("div");
overlay.style.cssText =
"position: fixed; inset: 0; z-index: 2147483647; cursor: grabbing;";
document.body.appendChild(overlay);
const update = () => {
const element =
document
.elementsFromPoint(pointer.x, pointer.y)
.find((el) => el !== overlay) ?? null;
if (element !== hovered) {
hovered = element;
scroller = getScrollContainer(element);
scrollerRect = scroller?.getBoundingClientRect();
}
manager.hover(element, pointer);
};
const handlePointerMove = (event: PointerEvent) => {
pointer = { x: event.clientX, y: event.clientY };
update();
};
const handleClick = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
};
const stopPropagation = (event: Event) => event.stopPropagation();
const handleWheel = (event: WheelEvent) => {
if (!scroller) {
return;
}
event.preventDefault();
scroller.scrollTop +=
event.deltaMode === WheelEvent.DOM_DELTA_LINE
? event.deltaY * LINE_HEIGHT
: event.deltaY;
};
const scroll = () => {
frame = requestAnimationFrame(scroll);
if (!scroller || !scrollerRect) {
return;
}
const speed =
getScrollSpeed(scrollerRect.bottom - pointer.y) -
getScrollSpeed(pointer.y - scrollerRect.top);
if (speed) {
scroller.scrollTop += speed;
}
};
// The release position is checked too, before the sensor ends the drag.
for (const type of POINTER_EVENTS) {
window.addEventListener(type, handlePointerMove, {
capture: true,
passive: true,
});
}
window.addEventListener("scroll", update, { capture: true, passive: true });
window.addEventListener("click", handleClick, { capture: true });
for (const type of MOUSE_EVENTS) {
window.addEventListener(type, stopPropagation, { capture: true });
}
overlay.addEventListener("wheel", handleWheel, { passive: false });
update();
frame = requestAnimationFrame(scroll);
return () => {
for (const type of POINTER_EVENTS) {
window.removeEventListener(type, handlePointerMove, { capture: true });
}
window.removeEventListener("scroll", update, { capture: true });
for (const type of MOUSE_EVENTS) {
window.removeEventListener(type, stopPropagation, { capture: true });
}
cancelAnimationFrame(frame);
overlay.remove();
setTimeout(
() => window.removeEventListener("click", handleClick, { capture: true }),
50
);
};
}
/**
* Returns the nearest ancestor of the element that scrolls vertically.
*
* @param element The element to start from.
* @returns the scroll container, or null if there is none.
*/
function getScrollContainer(element: Element | null): HTMLElement | null {
let current = element;
while (current && current !== document.body) {
if (
current instanceof HTMLElement &&
current.scrollHeight > current.clientHeight &&
/(auto|scroll|overlay)/.test(getComputedStyle(current).overflowY)
) {
return current;
}
current = current.parentElement;
}
return null;
}
/**
* Returns the scroll distance for one frame.
*
* @param distance The distance from the pointer to the edge of the container.
* @returns the scroll distance, 0 when the pointer is not near the edge.
*/
function getScrollSpeed(distance: number): number {
return SCROLL_SPEED * Math.max(0, 1 - Math.max(distance, 0) / SCROLL_EDGE);
}
@@ -0,0 +1,334 @@
import type { ReactNode } from "react";
import shallowEqual from "@shared/utils/shallowEqual";
/** A position in viewport coordinates. */
export interface Point {
x: number;
y: number;
}
/** The data carried by a drag operation. */
export interface DragItem {
/** The id of the dragged model. */
id: string;
/** The title shown in the drag preview. */
title?: string;
/** The icon shown in the drag preview. */
icon?: ReactNode;
/** Whether the dragged model is a draft. */
isDraft?: boolean;
}
/** Reads the drag state for a drop target. */
export interface DropTargetMonitor {
/**
* Whether the pointer is over this target. With `shallow`, only when no
* nested target that accepts the item is between them.
*/
isOver(options?: { shallow?: boolean }): boolean;
/** Whether the dragged item can be dropped on this target. */
canDrop(): boolean;
/** Whether a nested target has already handled the current drop. */
didDrop(): boolean;
/** The type of the dragged item, or null when nothing is dragged. */
getItemType(): string | null;
}
/** Reads the global drag state. */
export interface DragLayerMonitor {
/** Whether an item is being dragged. */
isDragging(): boolean;
/** The dragged item, or null when nothing is dragged. */
getItem(): DragItem | null;
/** The pointer position, or null when nothing is dragged. */
getClientOffset(): Point | null;
}
/** Describes an element that can be dragged. */
export interface DragSourceSpec<Item extends DragItem> {
/** The type of the dragged item, matched against a target's `accept`. */
type: string;
/** Returns the item that drop targets receive. */
item(): Item;
/** Whether the source can be dragged now. */
canDrag?(): boolean;
}
/** Describes an element that dragged items can be dropped on. */
export interface DropTargetSpec<Item extends DragItem> {
/** The item types that the target accepts. */
accept: string | string[];
/** Whether the item can be dropped on the target. */
canDrop?(item: Item, monitor: DropTargetMonitor): boolean;
/** Called while an accepted item is over the target. */
hover?(item: Item, monitor: DropTargetMonitor): void;
/** Called when the item is dropped on the target. */
drop?(item: Item, monitor: DropTargetMonitor): unknown;
}
/** A registered drag source. */
export interface DragSource {
/** Returns the latest source specification. */
getSpec(): DragSourceSpec<DragItem>;
}
/** A registered drop target. */
export interface DropTarget {
/** Returns the latest target specification. */
getSpec(): DropTargetSpec<DragItem>;
}
interface DragOperation {
source: DragSource;
type: string;
item: DragItem;
}
const EMPTY_TARGETS: DropTarget[] = [];
/**
* Holds the connected drag sources and drop targets, and the state of the
* current drag operation. Nested drop targets are resolved from the DOM: all
* connected targets that contain the element under the pointer are hovered,
* and a drop is offered to each of them from the innermost outwards.
*/
export class DragDropManager {
/** A monitor for the global drag state. */
public readonly layerMonitor: DragLayerMonitor = {
isDragging: () => !!this.operation,
getItem: () => this.operation?.item ?? null,
getClientOffset: () => this.pointer,
};
/**
* Subscribes to changes in the drag operation and the hovered targets.
*
* @param listener Called after each change.
* @returns a function that removes the listener.
*/
public subscribe = (listener: () => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
/**
* Subscribes to changes in the pointer position.
*
* @param listener Called after each change.
* @returns a function that removes the listener.
*/
public subscribeToPointer = (listener: () => void) => {
this.pointerListeners.add(listener);
return () => {
this.pointerListeners.delete(listener);
};
};
/**
* Connects a drag source to its DOM element.
*
* @param node The element.
* @param source The source.
* @returns a function that disconnects the source.
*/
public connectSource(node: HTMLElement, source: DragSource): () => void {
this.sources.set(node, source);
return () => {
if (this.sources.get(node) === source) {
this.sources.delete(node);
}
};
}
/**
* Connects a drop target to its DOM element.
*
* @param node The element.
* @param target The target.
* @returns a function that disconnects the target.
*/
public connectTarget(node: Element, target: DropTarget): () => void {
const targets = this.targets.get(node) ?? new Set<DropTarget>();
targets.add(target);
this.targets.set(node, targets);
return () => {
targets.delete(target);
if (this.hovered.includes(target)) {
this.hovered = this.hovered.filter((t) => t !== target);
this.emit();
}
};
}
/**
* Returns the nearest source connected to the element or one of its
* ancestors that can be dragged now.
*
* @param element The element where the drag starts.
* @returns the source and its element, or undefined if none can be dragged.
*/
public findSource(
element: Element
): { source: DragSource; node: HTMLElement } | undefined {
for (let node: Element | null = element; node; node = node.parentElement) {
const source = this.sources.get(node);
if (
source &&
node instanceof HTMLElement &&
(source.getSpec().canDrag?.() ?? true)
) {
return { source, node };
}
}
return undefined;
}
/**
* Starts a drag operation.
*
* @param source The dragged source.
*/
public beginDrag(source: DragSource) {
const spec = source.getSpec();
this.operation = { source, type: spec.type, item: spec.item() };
this.hovered = EMPTY_TARGETS;
this.dropped = false;
this.emit();
}
/**
* Updates the pointer position and the hovered targets.
*
* @param element The element under the pointer.
* @param pointer The pointer position.
*/
public hover(element: Element | null, pointer: Point) {
const operation = this.operation;
if (!operation) {
return;
}
this.pointer = pointer;
this.pointerListeners.forEach((listener) => listener());
const hovered: DropTarget[] = [];
for (let node = element; node; node = node.parentElement) {
for (const target of this.targets.get(node) ?? EMPTY_TARGETS) {
if (accepts(target, operation.type)) {
hovered.push(target);
}
}
}
if (!shallowEqual(hovered, this.hovered)) {
this.hovered = hovered.length ? hovered : EMPTY_TARGETS;
this.emit();
}
for (const target of this.hovered) {
target.getSpec().hover?.(operation.item, this.getTargetMonitor(target));
}
}
/**
* Offers the dragged item to the hovered targets that can accept it, from
* the innermost outwards, then ends the drag.
*/
public drop() {
const operation = this.operation;
if (!operation) {
return;
}
try {
for (const target of this.hovered) {
if (this.canDrop(target)) {
const monitor = this.getTargetMonitor(target);
target.getSpec().drop?.(operation.item, monitor);
this.dropped = true;
}
}
} finally {
this.endDrag();
}
}
/** Ends the drag operation without a drop. */
public endDrag() {
if (!this.operation) {
return;
}
this.operation = null;
this.pointer = null;
this.hovered = EMPTY_TARGETS;
this.emit();
this.pointerListeners.forEach((listener) => listener());
}
/**
* Returns whether the source is being dragged.
*
* @param source The source.
* @returns true if the source is dragged.
*/
public isDragging(source: DragSource): boolean {
return this.operation?.source === source;
}
/**
* Returns a monitor for a drop target.
*
* @param target The target.
* @returns the monitor.
*/
public getTargetMonitor(target: DropTarget): DropTargetMonitor {
return {
isOver: (options) =>
options?.shallow
? this.hovered[0] === target
: this.hovered.includes(target),
canDrop: () => this.canDrop(target),
didDrop: () => this.dropped,
getItemType: () => this.operation?.type ?? null,
};
}
private canDrop(target: DropTarget): boolean {
const operation = this.operation;
if (!operation || !accepts(target, operation.type)) {
return false;
}
return (
target
.getSpec()
.canDrop?.(operation.item, this.getTargetMonitor(target)) ?? true
);
}
private emit() {
this.listeners.forEach((listener) => listener());
}
private operation: DragOperation | null = null;
private pointer: Point | null = null;
/** Hovered targets, from the innermost outwards. */
private hovered = EMPTY_TARGETS;
private dropped = false;
private sources = new WeakMap<Element, DragSource>();
private targets = new WeakMap<Element, Set<DropTarget>>();
private listeners = new Set<() => void>();
private pointerListeners = new Set<() => void>();
}
function accepts(target: DropTarget, type: string): boolean {
const { accept } = target.getSpec();
return Array.isArray(accept) ? accept.includes(type) : accept === type;
}
+183
View File
@@ -0,0 +1,183 @@
import {
createContext,
useCallback,
useContext,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
type RefCallback,
} from "react";
import shallowEqual from "@shared/utils/shallowEqual";
import {
DragDropManager,
type DragItem,
type DragLayerMonitor,
type DragSource,
type DragSourceSpec,
type DropTarget,
type DropTargetMonitor,
type DropTargetSpec,
} from "./DragDropManager";
/** Options for a drop target, with a collector for the props it renders. */
export interface DropTargetHookSpec<
Item extends DragItem,
Collected extends object,
> extends DropTargetSpec<Item> {
/** Returns the props to render. The component re-renders when they change. */
collect(monitor: DropTargetMonitor): Collected;
}
/** Provides the drag and drop manager to the hooks. */
export const DragDropManagerContext = createContext<DragDropManager>(
new DragDropManager()
);
/**
* Makes an element draggable.
*
* @param spec The drag source specification.
* @returns a tuple of whether the element is being dragged and a ref callback for it.
*/
export function useDragRef<Item extends DragItem>(
spec: DragSourceSpec<Item>
): [boolean, RefCallback<HTMLElement>] {
const manager = useContext(DragDropManagerContext);
const specRef = useLatest(spec);
const [source] = useState<DragSource>(() => ({
getSpec: () => specRef.current,
}));
const ref = useCallback(
(node: HTMLElement | null) =>
node ? manager.connectSource(node, source) : undefined,
[manager, source]
);
const isDragging = useSyncExternalStore(manager.subscribe, () =>
manager.isDragging(source)
);
return [isDragging, ref];
}
/**
* Makes an element a drop target. Targets may be nested; a drop is offered to
* every hovered target that can accept it, from the innermost outwards.
*
* @param spec The drop target specification.
* @returns a tuple of the collected props and a ref callback for the element.
*/
export function useDropRef<Item extends DragItem, Collected extends object>(
spec: DropTargetHookSpec<Item, Collected>
): [Collected, RefCallback<HTMLElement>] {
const manager = useContext(DragDropManagerContext);
const specRef = useLatest(spec);
const [target] = useState<DropTarget>(() => ({
getSpec: () => specRef.current,
}));
const [monitor] = useState(() => manager.getTargetMonitor(target));
const ref = useCallback(
(node: HTMLElement | null) =>
node ? manager.connectTarget(node, target) : undefined,
[manager, target]
);
const collected = useCollected(manager.subscribe, () =>
spec.collect(monitor)
);
return [collected, ref];
}
/**
* Collects props from the global drag state.
*
* @param collect Returns the props to render. The component re-renders when they change.
* @returns the collected props.
*/
export function useDragLayer<Collected extends object>(
collect: (monitor: DragLayerMonitor) => Collected
): Collected {
const manager = useContext(DragDropManagerContext);
return useCollected(manager.subscribe, () => collect(manager.layerMonitor));
}
/**
* Returns a ref callback for an element that follows the pointer during a
* drag. The element is moved directly, without a render.
*
* @param offsetX The horizontal distance from the pointer.
* @param offsetY The vertical distance from the pointer.
* @returns a ref callback for the element.
*/
export function useDragFollower(
offsetX: number,
offsetY: number
): RefCallback<HTMLElement> {
const manager = useContext(DragDropManagerContext);
return useCallback(
(node: HTMLElement | null) => {
if (!node) {
return undefined;
}
const move = () => {
const pointer = manager.layerMonitor.getClientOffset();
if (pointer) {
node.style.transform = `translate(${pointer.x + offsetX}px, ${pointer.y + offsetY}px)`;
}
};
move();
return manager.subscribeToPointer(move);
},
[manager, offsetX, offsetY]
);
}
/**
* Returns a ref that always holds the latest value.
*
* @param value The value to hold.
* @returns the ref.
*/
function useLatest<T>(value: T): { readonly current: T } {
const ref = useRef(value);
useLayoutEffect(() => {
ref.current = value;
});
return ref;
}
/**
* Subscribes to a store and returns the collected value. The previous value is
* returned while the new one is shallowly equal, so the component only
* re-renders when a collected prop changes.
*
* @param subscribe Subscribes to changes in the store.
* @param collect Returns the collected value.
* @returns the collected value.
*/
function useCollected<T extends object>(
subscribe: (listener: () => void) => () => void,
collect: () => T
): T {
const cache = useRef<{ value: T } | null>(null);
const getSnapshot = () => {
const value = collect();
if (
cache.current &&
shallowEqual(Object.keys(cache.current.value), Object.keys(value)) &&
shallowEqual(Object.values(cache.current.value), Object.values(value))
) {
return cache.current.value;
}
cache.current = { value };
return value;
};
return useSyncExternalStore(subscribe, getSnapshot);
}
+3
View File
@@ -0,0 +1,3 @@
export { DragAndDropProvider } from "./DragAndDropProvider";
export { useDragFollower, useDragLayer, useDragRef, useDropRef } from "./hooks";
export type { Point } from "./DragDropManager";
-89
View File
@@ -1,89 +0,0 @@
import type { BackendFactory } from "dnd-core";
import { HTML5Backend } from "react-dnd-html5-backend";
/**
* react-dnd's HTML5 backend installs global drag listeners on `window` in both
* the capture and bubble phases. The bubble-phase `dragover` handler runs after
* ProseMirror's and, when react-dnd isn't tracking a drag, forces
* `dataTransfer.dropEffect = "none"` – which tells the browser the drop is
* disallowed and silently rejects images dragged into the editor.
*
* These handlers live on `window`, so a propagation-based guard can't stop
* react-dnd without also starving the editor of the event. Instead we wrap the
* backend and make all of its top-level handlers no-op for events that occur
* within the editor surface, leaving ProseMirror to handle them itself.
*/
const topHandlerNames = [
"handleTopDragStart",
"handleTopDragStartCapture",
"handleTopDragEnter",
"handleTopDragEnterCapture",
"handleTopDragLeaveCapture",
"handleTopDragOver",
"handleTopDragOverCapture",
"handleTopDrop",
"handleTopDropCapture",
"handleTopDragEndCapture",
] as const;
const isWithinEditor = (target: EventTarget | null): boolean =>
target instanceof Element && Boolean(target.closest(".ProseMirror"));
// A file dragged over an element marked `data-drop-area`, which accepts native
// file drops itself. react-dnd never tracks these drags, so its handlers would
// otherwise reject them.
const isFileOverDropArea = (event: DragEvent): boolean =>
Boolean(event.dataTransfer?.types.includes("Files")) &&
event.target instanceof Element &&
Boolean(event.target.closest("[data-drop-area]"));
/**
* An HTML5 drag-and-drop backend that ignores drag events originating within the
* rich text editor so that ProseMirror can handle them itself.
*
* @param manager The drag-and-drop manager.
* @param context The global context.
* @param options Backend options.
* @returns The wrapped HTML5 backend instance.
*/
export const EditorAwareHTML5Backend: BackendFactory = (
manager,
context,
options
) => {
const backend = HTML5Backend(manager, context, options);
const monitor = manager.getMonitor();
// The top-level handlers are private instance fields on the backend, so reach
// for them through an index signature view of the instance.
const handlers = backend as unknown as Record<
string,
(event: DragEvent) => void
>;
for (const name of topHandlerNames) {
const original = handlers[name];
if (typeof original === "function") {
handlers[name] = (event: DragEvent) => {
if (isWithinEditor(event.target) || isFileOverDropArea(event)) {
return;
}
// A drag that began or entered the page over the editor is never
// registered with react-dnd because those events are skipped above.
// The backend's drop handlers assume a registered drag and may call
// `actions.hover` unconditionally, which throws "Cannot call hover
// while not dragging" – so drops without a tracked drag must be
// ignored here.
if (
(name === "handleTopDrop" || name === "handleTopDropCapture") &&
!monitor.isDragging()
) {
return;
}
original.call(backend, event);
};
}
}
return backend;
};
@@ -59,8 +59,7 @@ const CollectionLink: React.FC<Props> = ({
const parentRef = React.useRef<HTMLDivElement>(null);
const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection(
collection,
handleExpand,
parentRef
handleExpand
);
const handlePrefetch = React.useCallback(() => {
@@ -1,6 +1,6 @@
import { noop } from "es-toolkit/compat";
import { observer } from "mobx-react";
import { useRef, useCallback } from "react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import type Collection from "~/models/Collection";
@@ -114,20 +114,13 @@ function CollectionLinkChildren({
const DynamicDropCursor = observer(
({ collection }: { collection: Collection }) => {
const dummyRef = useRef<HTMLDivElement>(null);
const [{ isOver, canDrop }] = useDropToChangeCollection(
collection,
noop,
dummyRef
);
const [{ isOver, canDrop }] = useDropToChangeCollection(collection, noop);
if (!canDrop || !collection.isManualSort) {
return null;
}
return (
<DropCursor isActiveDrop={isOver} innerRef={dummyRef} position="top" />
);
return <DropCursor isActiveDrop={isOver} position="top" />;
}
);
@@ -10,7 +10,8 @@ import PaginatedList from "~/components/PaginatedList";
import { createCollection } from "~/actions/definitions/collections";
import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext";
import useStores from "~/hooks/useStores";
import { type DragObject, useDropRef } from "../hooks/useDragAndDrop";
import { useDropRef } from "~/components/DragAndDrop";
import type { DragObject } from "../hooks/useDragAndDrop";
import DraggableCollectionLink from "./DraggableCollectionLink";
import DropCursor from "./DropCursor";
import Header from "./Header";
@@ -196,8 +196,7 @@ const DocumentLink = observer(function DocumentLink({
const [{ isOverReparent }, dropToReparent] = useDropToReparentDocument(
node,
collection,
handleExpand,
parentRef
handleExpand
);
// Fall back so document-only access (e.g. "Manage" on a parent) can reorder.
@@ -119,7 +119,7 @@ export const DocumentTree = observer(function DocumentTree({
);
// Keep the active row mounted so that it can scroll into view, and the
// dragged row so that the drag does not end when it scrolls away.
// dragged row so that it keeps its dragging state when it scrolls away.
const rangeExtractor = React.useCallback(
(range: Range) => {
const indexes = new Set(defaultRangeExtractor(range));
@@ -1,5 +1,5 @@
import * as React from "react";
import { useDragLayer } from "react-dnd";
import { useDragLayer } from "~/components/DragAndDrop";
const DraggedItemContext = React.createContext<string | undefined>(undefined);
@@ -20,11 +20,11 @@ export function useSidebarScrollElement(): HTMLElement | null {
}
/**
* Subscribes once to react-dnd's drag state and exposes the id of the dragged
* item via context.
* Subscribes once to the drag state and exposes the id of the dragged item via
* context.
*
* Virtualized sidebar trees read this to keep the dragged row mounted for the
* duration of a drag, as react-dnd ends a drag whose source leaves the DOM.
* duration of a drag, so that the row keeps its dragging state.
*/
export function DragActiveProvider({
children,
@@ -33,9 +33,7 @@ export function DragActiveProvider({
}) {
const { isDragging, itemId } = useDragLayer((monitor) => ({
isDragging: monitor.isDragging(),
itemId: monitor.isDragging()
? monitor.getItem<{ id?: string } | null>()?.id
: undefined,
itemId: monitor.getItem()?.id,
}));
// Expose drag state to CSS so per-row UI (e.g. the hover actions slot) can
@@ -1,9 +1,7 @@
import * as React from "react";
import type { XYCoord } from "react-dnd";
import { useDragLayer } from "react-dnd";
import { NativeTypes } from "react-dnd-html5-backend";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { useDragFollower, useDragLayer } from "~/components/DragAndDrop";
import useStores from "~/hooks/useStores";
import SidebarLink from "./SidebarLink";
@@ -17,56 +15,26 @@ const layerStyles: React.CSSProperties = {
height: "100%",
};
// Browser-native drags (files, text, or ProseMirror nodes leaving the editor)
// are tracked by react-dnd too, but they are not sidebar items.
const nativeItemTypes = new Set<string | symbol>(Object.values(NativeTypes));
// Keep the ghost beside the pointer so it never covers the drop cursor.
const POINTER_OFFSET_X = 12;
const POINTER_OFFSET_Y = 14;
function getItemStyles(pointerOffset: XYCoord | null, sidebarWidth: number) {
if (!pointerOffset) {
return {
display: "none",
};
}
const x = pointerOffset.x + POINTER_OFFSET_X;
const y = pointerOffset.y - POINTER_OFFSET_Y;
const transform = `translate(${x}px, ${y}px)`;
return {
width: sidebarWidth - 24,
transform,
WebkitTransform: transform,
};
}
const DragPlaceholder = () => {
const { t } = useTranslation();
const { ui } = useStores();
const followPointer = useDragFollower(POINTER_OFFSET_X, -POINTER_OFFSET_Y);
const { isDragging, item, itemType, pointerOffset } = useDragLayer(
(monitor) => ({
item: monitor.getItem(),
itemType: monitor.getItemType(),
pointerOffset: monitor.getClientOffset(),
isDragging: monitor.isDragging(),
})
);
const { item } = useDragLayer((monitor) => ({
item: monitor.getItem(),
}));
if (
!isDragging ||
!pointerOffset ||
!itemType ||
nativeItemTypes.has(itemType)
) {
if (!item) {
return null;
}
return (
<div style={layerStyles}>
<div style={getItemStyles(pointerOffset, ui.sidebarWidth)}>
<div ref={followPointer} style={{ width: ui.sidebarWidth - 24 }}>
<GhostLink
icon={item.icon}
label={item.title || t("Untitled")}
@@ -2,14 +2,13 @@ import fractionalIndex from "fractional-index";
import { observer } from "mobx-react";
import type * as React from "react";
import { useState, useEffect, useCallback } from "react";
import { getEmptyImage } from "react-dnd-html5-backend";
import styled from "styled-components";
import type Collection from "~/models/Collection";
import { useDragRef, useDropRef } from "~/components/DragAndDrop";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext";
import { useComputed } from "~/hooks/useComputed";
import useStores from "~/hooks/useStores";
import { useDragRef, useDropRef } from "../hooks/useDragAndDrop";
import CollectionLink from "./CollectionLink";
import DropCursor from "./DropCursor";
import SidebarDisclosureContext, {
@@ -58,7 +57,6 @@ function DraggableCollectionLink({ collection, belowCollection }: Props) {
dropToReorderCollection,
] = useDropRef<
CollectionDragItem,
void,
{ isCollectionDropping: boolean; isDraggingAnyCollection: boolean }
>({
accept: "collection",
@@ -79,22 +77,15 @@ function DraggableCollectionLink({ collection, belowCollection }: Props) {
});
// Drag to reorder collection
const [{ isDragging }, dragToReorderCollection, preview] = useDragRef({
const [isDragging, dragToReorderCollection] = useDragRef({
type: "collection",
item: () => ({
id: collection.id,
title: collection.displayName,
icon: <CollectionIcon collection={collection} />,
}),
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
useEffect(() => {
preview(getEmptyImage(), { captureDraggingState: false });
}, [preview]);
// If the current collection is active and relevant to the sidebar section we
// are in then expand it automatically
useEffect(() => {
@@ -2,7 +2,6 @@ import { observer } from "mobx-react";
import {
createContext,
useCallback,
useEffect,
useMemo,
useState,
type ReactNode,
@@ -206,12 +205,6 @@ function DraggableSection({ section, children }: Props) {
(dragged) => moveSidebarSection(order, dragged, "after", section)
);
// The drop cursors and the drag styling must not appear inside the
// browser's dragstart dispatch — Chromium aborts the drag when the element
// under the drag origin changes before the drag session starts.
const showCursors = useDeferredFlag(bottomProps.isDragging);
const isDraggingDeferred = useDeferredFlag(isDragging);
const contextValue = useMemo(
() => ({ dragRef, menuActions }),
[dragRef, menuActions]
@@ -219,19 +212,19 @@ function DraggableSection({ section, children }: Props) {
return (
<SectionWrapper ref={setWrapper} data-section={section}>
{showCursors && (
{bottomProps.isDragging && (
<TopDropCursor
isActiveDrop={topProps.isOverCursor}
innerRef={dropTopRef}
position="top"
/>
)}
<Draggable $isDragging={isDraggingDeferred}>
<Draggable $isDragging={isDragging}>
<SidebarSectionContext.Provider value={contextValue}>
{children}
</SidebarSectionContext.Provider>
</Draggable>
{showCursors && (
{bottomProps.isDragging && (
<SectionDropCursor
isActiveDrop={bottomProps.isOverCursor}
innerRef={dropBottomRef}
@@ -241,28 +234,6 @@ function DraggableSection({ section, children }: Props) {
);
}
/**
* Returns the given flag with its rising edge deferred by one task. A falling
* edge resets immediately.
*
* @param value The flag to defer.
* @returns the deferred flag.
*/
function useDeferredFlag(value: boolean): boolean {
const [deferred, setDeferred] = useState(false);
useEffect(() => {
if (!value) {
setDeferred(false);
return undefined;
}
const timer = setTimeout(() => setDeferred(true), 0);
return () => clearTimeout(timer);
}, [value]);
return deferred;
}
const Draggable = styled.div<{ $isDragging: boolean }>`
display: flex;
flex-direction: column;
@@ -3,7 +3,7 @@ import styled from "styled-components";
type Props = {
isActiveDrop: boolean;
innerRef: React.Ref<HTMLDivElement>;
innerRef?: React.Ref<HTMLDivElement>;
position?: "top";
/** Inline-start offset of the visible line in pixels, to match a tree depth. */
indent?: number;
@@ -98,7 +98,7 @@ const ImportDropzone = observer(function ImportDropzone({
let hasDraggedFiles = false;
const fileDragListeners = new Set<() => void>();
// Only prepare dropzones for OS file drags, internal react-dnd drags fire
// Only prepare dropzones for OS file drags, text and editor content drags fire
// native dragenter too.
const handleDragEnter = (event: DragEvent) => {
if (!Array.from(event.dataTransfer?.types ?? []).includes("Files")) {
@@ -233,9 +233,9 @@ const NavLink = observer(function NavLink({
event.preventDefault();
}
// Fire onActiveClick on click rather than mousedown so that the native
// HTML5 drag gesture can initiate from an active row without being
// blocked by a preventDefault on mousedown.
// Fire onActiveClick on click rather than mousedown so that a drag can
// start from an active row without being blocked by a preventDefault on
// mousedown.
if (isActive && wasActive) {
onActiveClick?.(event);
}
@@ -130,8 +130,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
const [{ isOverReparent }, dropToReparent] = useDropToReparentDocument(
reparentableNode,
undefined,
setExpanded,
parentRef
setExpanded
);
const { icon } = useSidebarLabelAndIcon(membership);
@@ -92,9 +92,8 @@ const activeDropStyle = {
fontWeight: 600,
};
// Prevents the parent NavLink's mousedown handler from firing (which would
// navigate or toggle), without calling preventDefault — that would block the
// native HTML5 drag from initiating on the draggable row.
// Prevents the parent NavLink's mousedown handler from firing, which would
// navigate or toggle.
const stopPropagation = (ev: React.MouseEvent) => {
ev.stopPropagation();
};
@@ -301,7 +300,14 @@ const Link = styled.a<{
--background: ${s("sidebarActiveBackground")};
}
${(props) => props.$isActiveDrop && `--background: ${props.theme.slateDark};`}
${(props) =>
props.$isActiveDrop &&
css`
&,
${hoveredOrMenuOpen} {
--background: ${props.theme.slateDark};
}
`}
display: flex;
position: relative;
@@ -295,8 +295,7 @@ const StarredCollectionLink = observer(function StarredCollectionLink({
const parentRef = React.useRef<HTMLDivElement>(null);
const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection(
collection,
handleExpand,
parentRef
handleExpand
);
const handleRename = React.useCallback(() => {
@@ -6,7 +6,8 @@ import { DialogTitle } from "~/components/DialogTitle";
import useStores from "~/hooks/useStores";
import * as Scenes from "~/routes/scenes";
import { trashPath } from "~/utils/routeHelpers";
import { type DragObject, useDropRef } from "../hooks/useDragAndDrop";
import { useDropRef } from "~/components/DragAndDrop";
import type { DragObject } from "../hooks/useDragAndDrop";
import SidebarLink from "./SidebarLink";
function TrashLink() {
+124 -222
View File
@@ -1,15 +1,5 @@
import fractionalIndex from "fractional-index";
import * as React from "react";
import type {
ConnectDragPreview,
ConnectDragSource,
ConnectDropTarget,
DragSourceHookSpec,
DropTargetHookSpec,
FactoryOrInstance,
} from "react-dnd";
import { useDrag, useDrop } from "react-dnd";
import { getEmptyImage } from "react-dnd-html5-backend";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { errToString } from "@shared/utils/error";
@@ -25,6 +15,7 @@ import type GroupMembership from "~/models/GroupMembership";
import type Star from "~/models/Star";
import UserMembership from "~/models/UserMembership";
import ConfirmMoveDialog from "~/components/ConfirmMoveDialog";
import { useDragRef, useDropRef } from "~/components/DragAndDrop";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
@@ -37,102 +28,39 @@ export type DragObject = NavigationNode & {
};
/**
* Adapts a react-dnd connector to a ref callback. Connectors return the
* connected node so that calls can be chained, which React does not permit
* from a ref.
* Returns functions to start and cancel a timer that calls the callback once
* an item has been held over a target for half a second.
*
* @param connect The connector to adapt.
* @returns a ref callback.
* @param callback The function to call.
* @returns a tuple of the start and cancel functions.
*/
function useConnectorRef(
connect: ConnectDragSource | ConnectDropTarget
): React.RefCallback<HTMLElement> {
return React.useCallback(
(node: HTMLElement | null) => void connect(node),
[connect]
function useHoverTimer(callback: () => void) {
const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | undefined>(
undefined
);
}
const callbackRef = React.useRef(callback);
/**
* Wrapper around react-dnd's `useDrag` that returns the connector as a ref
* callback.
*
* @param spec The drag source specification.
* @returns a tuple of the collected props, a ref callback and the drag preview
* connector.
*/
export function useDragRef<
DragObj = unknown,
DropResult = unknown,
CollectedProps = unknown,
>(
spec: FactoryOrInstance<
DragSourceHookSpec<DragObj, DropResult, CollectedProps>
>
): [CollectedProps, React.RefCallback<HTMLElement>, ConnectDragPreview] {
const [collected, connect, preview] = useDrag<
DragObj,
DropResult,
CollectedProps
>(spec);
return [collected, useConnectorRef(connect), preview];
}
React.useEffect(() => {
callbackRef.current = callback;
});
/**
* Wrapper around react-dnd's `useDrop` that returns the connector as a ref
* callback.
*
* @param spec The drop target specification.
* @returns a tuple of the collected props and a ref callback.
*/
export function useDropRef<
DragObj = unknown,
DropResult = unknown,
CollectedProps = unknown,
>(
spec: FactoryOrInstance<
DropTargetHookSpec<DragObj, DropResult, CollectedProps>
>
): [CollectedProps, React.RefCallback<HTMLElement>] {
const [collected, connect] = useDrop<DragObj, DropResult, CollectedProps>(
spec
);
return [collected, useConnectorRef(connect)];
}
function useHover(
elementRef: React.RefObject<HTMLDivElement | null>,
callback: () => void
) {
const hoverTimeoutRef = React.useRef<
ReturnType<typeof setTimeout> | undefined
>(undefined);
const startHover = React.useCallback(() => {
if (!hoverTimeoutRef.current) {
hoverTimeoutRef.current = setTimeout(() => {
hoverTimeoutRef.current = undefined;
callback();
const start = React.useCallback(() => {
if (!timeoutRef.current) {
timeoutRef.current = setTimeout(() => {
timeoutRef.current = undefined;
callbackRef.current();
}, 500);
}
}, [callback]);
const unsetHover = React.useCallback(() => {
if (hoverTimeoutRef.current) {
clearTimeout(hoverTimeoutRef.current);
hoverTimeoutRef.current = undefined;
}
}, []);
// We set a timeout when the user first starts hovering over the document link,
// to trigger expansion of children. Clear this timeout when they stop hovering.
React.useEffect(() => {
const element = elementRef.current;
element?.addEventListener("dragleave", unsetHover);
return () => element?.removeEventListener("dragleave", unsetHover);
}, [elementRef, unsetHover]);
const cancel = React.useCallback(() => {
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
}, []);
return startHover;
React.useEffect(() => cancel, [cancel]);
return [start, cancel] as const;
}
/**
@@ -146,18 +74,11 @@ export function useDragStar(
const id = star.id;
const { label: title, icon } = useSidebarLabelAndIcon(star);
const [{ isDragging }, dragRef, preview] = useDragRef({
const [isDragging, dragRef] = useDragRef({
type: "star",
item: () => ({ id, title, icon }),
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
});
React.useEffect(() => {
preview(getEmptyImage(), { captureDraggingState: true });
}, [preview]);
return [{ isDragging }, dragRef];
}
@@ -176,40 +97,38 @@ export function useDropToCreateStar(getIndex?: () => string) {
const { documents, stars, collections, userMemberships, groupMemberships } =
useStores();
return useDropRef<
DragObject,
Promise<void>,
{ isOverCursor: boolean; isDragging: boolean }
>({
accept,
drop: async (item, monitor) => {
// A more specific drop target (e.g. a reorder cursor) has already
// handled this drop, so avoid creating a duplicate star.
if (monitor.didDrop()) {
return;
}
return useDropRef<DragObject, { isOverCursor: boolean; isDragging: boolean }>(
{
accept,
drop: async (item, monitor) => {
// A more specific drop target (e.g. a reorder cursor) has already
// handled this drop, so avoid creating a duplicate star.
if (monitor.didDrop()) {
return;
}
const type = monitor.getItemType();
let model;
const type = monitor.getItemType();
let model;
if (type === "collection") {
model = collections.get(item.id);
} else if (type === "userMembership") {
model = userMemberships.get(item.id)?.document;
} else if (type === "groupMembership") {
model = groupMemberships.get(item.id)?.document;
} else {
model = documents.get(item.id);
}
await model?.star(
getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index)
);
},
collect: (monitor) => ({
isOverCursor: !!monitor.isOver({ shallow: true }),
isDragging: accept.includes(String(monitor.getItemType())),
}),
});
if (type === "collection") {
model = collections.get(item.id);
} else if (type === "userMembership") {
model = userMemberships.get(item.id)?.document;
} else if (type === "groupMembership") {
model = groupMemberships.get(item.id)?.document;
} else {
model = documents.get(item.id);
}
await model?.star(
getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index)
);
},
collect: (monitor) => ({
isOverCursor: !!monitor.isOver({ shallow: true }),
isDragging: accept.includes(String(monitor.getItemType())),
}),
}
);
}
/**
@@ -220,24 +139,22 @@ export function useDropToCreateStar(getIndex?: () => string) {
export function useDropToReorderStar(getIndex?: () => string) {
const { stars } = useStores();
return useDropRef<
DragObject,
Promise<void>,
{ isOverCursor: boolean; isDragging: boolean }
>({
accept: "star",
drop: async (item) => {
const star = stars.get(item.id);
void star?.save({
index:
getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index),
});
},
collect: (monitor) => ({
isOverCursor: !!monitor.isOver(),
isDragging: monitor.getItemType() === "star",
}),
});
return useDropRef<DragObject, { isOverCursor: boolean; isDragging: boolean }>(
{
accept: "star",
drop: async (item) => {
const star = stars.get(item.id);
void star?.save({
index:
getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index),
});
},
collect: (monitor) => ({
isOverCursor: !!monitor.isOver(),
isDragging: monitor.getItemType() === "star",
}),
}
);
}
/**
@@ -250,18 +167,11 @@ export function useDragSidebarSection(
section: SidebarSection,
title: string
): [{ isDragging: boolean }, React.RefCallback<HTMLElement>] {
const [{ isDragging }, dragRef, preview] = useDragRef({
const [isDragging, dragRef] = useDragRef({
type: "sidebarSection",
item: () => ({ id: section, title }),
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
});
React.useEffect(() => {
preview(getEmptyImage(), { captureDraggingState: true });
}, [preview]);
return [{ isDragging }, dragRef];
}
@@ -278,7 +188,6 @@ export function useDropToReorderSidebarSection(
return useDropRef<
{ id: SidebarSection; title: string },
void,
{ isOverCursor: boolean; isDragging: boolean }
>({
accept: "sidebarSection",
@@ -315,11 +224,7 @@ export function useDragDocument(
const color = document?.color || node.color;
const initial = document?.initial || node.title;
const [{ isDragging }, dragRef, preview] = useDragRef<
DragObject,
Promise<void>,
{ isDragging: boolean }
>({
const [isDragging, dragRef] = useDragRef<DragObject>({
type: "document",
item: () =>
({
@@ -331,33 +236,28 @@ export function useDragDocument(
collectionId: document?.collectionId || "",
}) as DragObject,
canDrag: () => !!document?.isActive && !isEditing,
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
React.useEffect(() => {
preview(getEmptyImage(), { captureDraggingState: true });
}, [preview]);
return [{ isDragging }, dragRef] as const;
}
/**
* Hook for shared logic that allows dropping documents on a collection to move
* them to the top of it.
*
* @param collection The collection to move documents to.
* @param expandNode A function to expand the collection.
*/
export function useDropToChangeCollection(
collection: Collection,
expandNode: () => void,
parentRef: React.RefObject<HTMLDivElement | null>
expandNode: () => void
) {
const { t } = useTranslation();
const { documents, collections, dialogs, policies } = useStores();
const can = usePolicy(collection);
const startHover = useHover(parentRef, expandNode);
const [startHover, cancelHover] = useHoverTimer(expandNode);
return useDropRef<
DragObject,
Promise<void>,
{ isOver: boolean; canDrop: boolean }
>({
const result = useDropRef<DragObject, { isOver: boolean; canDrop: boolean }>({
accept: "document",
drop: async (item, monitor) => {
if (monitor.didDrop()) {
@@ -419,6 +319,15 @@ export function useDropToChangeCollection(
canDrop: monitor.canDrop(),
}),
});
const isOver = result[0].isOver;
React.useEffect(() => {
if (!isOver) {
cancelHover();
}
}, [isOver, cancelHover]);
return result;
}
/**
@@ -427,22 +336,20 @@ export function useDropToChangeCollection(
* @param node The NavigationNode model to drop.
* @param collection The collection that contains the node, if known.
* @param setExpanded A function to expand the parent node.
* @param parentRef A ref to the parent element that will be used to detect when the user is no longer hovering..
*/
export function useDropToReparentDocument(
node: NavigationNode | undefined,
collection: Collection | undefined,
setExpanded: () => void,
parentRef: React.RefObject<HTMLDivElement | null>
setExpanded: () => void
) {
const { t } = useTranslation();
const { documents, collections, dialogs, policies } = useStores();
const hasChildDocuments = !!node?.children.length;
const document = node ? documents.get(node.id) : undefined;
const startHover = useHover(parentRef, setExpanded);
const [startHover, cancelHover] = useHoverTimer(setExpanded);
return useDropRef<DragObject, Promise<void>, { isOverReparent: boolean }>({
const result = useDropRef<DragObject, { isOverReparent: boolean }>({
accept: "document",
drop: async (item, monitor) => {
if (monitor.didDrop() || !node) {
@@ -529,6 +436,15 @@ export function useDropToReparentDocument(
isOverReparent: monitor.isOver({ shallow: true }) && monitor.canDrop(),
}),
});
const isOverReparent = result[0].isOverReparent;
React.useEffect(() => {
if (!isOverReparent) {
cancelHover();
}
}, [isOverReparent, cancelHover]);
return result;
}
/**
@@ -555,7 +471,7 @@ export function useDropToReorderDocument(
const document = documents.get(node.id);
return useDropRef<DragObject, Promise<void>, { isOverReorder: boolean }>({
return useDropRef<DragObject, { isOverReorder: boolean }>({
accept: "document",
canDrop: (item: DragObject) => {
if (
@@ -644,21 +560,14 @@ export function useDragMembership(
const id = membership.id;
const { label: title, icon } = useSidebarLabelAndIcon(membership);
const [{ isDragging }, dragRef, preview] = useDragRef({
const [isDragging, dragRef] = useDragRef({
type:
membership instanceof UserMembership
? "userMembership"
: "groupMembership",
item: () => ({ id, title, icon }),
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
});
React.useEffect(() => {
preview(getEmptyImage(), { captureDraggingState: true });
}, [preview]);
return [{ isDragging }, dragRef] as const;
}
@@ -671,25 +580,23 @@ export function useDropToReorderUserMembership(getIndex?: () => string) {
const { userMemberships } = useStores();
const user = useCurrentUser();
return useDropRef<
DragObject,
Promise<void>,
{ isOverCursor: boolean; isDragging: boolean }
>({
accept: "userMembership",
drop: async (item) => {
const userMembership = userMemberships.get(item.id);
void userMembership?.save({
index:
getIndex?.() ??
fractionalIndex(null, user.documentMemberships[0].index),
});
},
collect: (monitor) => ({
isOverCursor: !!monitor.isOver(),
isDragging: monitor.getItemType() === "userMembership",
}),
});
return useDropRef<DragObject, { isOverCursor: boolean; isDragging: boolean }>(
{
accept: "userMembership",
drop: async (item) => {
const userMembership = userMemberships.get(item.id);
void userMembership?.save({
index:
getIndex?.() ??
fractionalIndex(null, user.documentMemberships[0].index),
});
},
collect: (monitor) => ({
isOverCursor: !!monitor.isOver(),
isDragging: monitor.getItemType() === "userMembership",
}),
}
);
}
/**
@@ -702,7 +609,6 @@ export function useDropToArchive() {
return useDropRef<
DragObject,
Promise<void>,
{ isOverArchiveSection: boolean; isDragging: boolean }
>({
accept,
@@ -737,11 +643,7 @@ export function useDropToUnpublish() {
const { t } = useTranslation();
const { policies, documents } = useStores();
return useDropRef<
DragObject,
Promise<void>,
{ isOver: boolean; canDrop: boolean }
>({
return useDropRef<DragObject, { isOver: boolean; canDrop: boolean }>({
accept: "document",
drop: async (item) => {
const document = documents.get(item.id);
+1 -7
View File
@@ -394,13 +394,7 @@ function DocumentScene({
}}
handler={onPublish}
/>
<Background
column
auto
onDragOver={handleDragOver}
onDrop={handleDrop}
data-drop-area
>
<Background column auto onDragOver={handleDragOver} onDrop={handleDrop}>
<PageTitle title={pageTitle} favicon={favicon} />
{(isUploading || isSaving) && <LoadingIndicator />}
<Container column auto>
-2
View File
@@ -220,8 +220,6 @@
"react-avatar-editor": "^15.1.0",
"react-colorful": "^5.8.0",
"react-day-picker": "^8.10.2",
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^19.3.0",
"react-dropzone": "^20.1.2",
"react-hook-form": "^7.85.0",
@@ -392,6 +392,9 @@
"Show in Explorer": "Show in Explorer",
"Show in folder": "Show in folder",
"Open": "Open",
"Picked up {{ title }}": "Picked up {{ title }}",
"Dropped {{ title }}": "Dropped {{ title }}",
"Cancelled dragging {{ title }}": "Cancelled dragging {{ title }}",
"File type not supported. Please use PNG, JPG, GIF, or WebP.": "File type not supported. Please use PNG, JPG, GIF, or WebP.",
"File size too large. Maximum size is {{ size }}.": "File size too large. Maximum size is {{ size }}.",
"Click or drag to replace": "Click or drag to replace",
+2 -79
View File
@@ -1438,7 +1438,7 @@ __metadata:
languageName: node
linkType: hard
"@babel/runtime@npm:^7.0.0, @babel/runtime@npm:^7.1.2, @babel/runtime@npm:^7.11.2, @babel/runtime@npm:^7.12.13, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.17.8, @babel/runtime@npm:^7.20.6, @babel/runtime@npm:^7.21.0, @babel/runtime@npm:^7.23.2, @babel/runtime@npm:^7.25.0, @babel/runtime@npm:^7.9.2":
"@babel/runtime@npm:^7.0.0, @babel/runtime@npm:^7.1.2, @babel/runtime@npm:^7.11.2, @babel/runtime@npm:^7.12.13, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.17.8, @babel/runtime@npm:^7.20.6, @babel/runtime@npm:^7.21.0, @babel/runtime@npm:^7.23.2, @babel/runtime@npm:^7.25.0":
version: 7.29.7
resolution: "@babel/runtime@npm:7.29.7"
checksum: 10c0/ca11572f7146b21e0bde6a9ed4bb6a89eafbee5f0944c7eb54d0d8a2dac962c33638a1d611e14faa71dfbb92b4b5f9236232208568a6b7d5c6f3f39ddb91771e
@@ -5009,27 +5009,6 @@ __metadata:
languageName: node
linkType: hard
"@react-dnd/asap@npm:^5.0.1":
version: 5.0.2
resolution: "@react-dnd/asap@npm:5.0.2"
checksum: 10c0/0063db616db9801c9be18f11a912c3e214f87e714b1e4bf9462952af7ead65cba0b43e1f7c34bc8748811b6926e74d929e5e126f85ebb91b870faf809ceb5177
languageName: node
linkType: hard
"@react-dnd/invariant@npm:^4.0.1":
version: 4.0.2
resolution: "@react-dnd/invariant@npm:4.0.2"
checksum: 10c0/b303cc53fc5074cefb2a76b45b9c73ebb5d35630b18f5dc282ed9a9ac9b0287b9da1f6ac63acfdea2341b8f8187f615afc12d5eb14ec6015964f5c1b167332e2
languageName: node
linkType: hard
"@react-dnd/shallowequal@npm:^4.0.1":
version: 4.0.2
resolution: "@react-dnd/shallowequal@npm:4.0.2"
checksum: 10c0/9a352fd176752e5d9c2797d598aca034b7829111ae0c992d80f40d5f068fcd6a039b1841c741dfa1ab67a36a00664310aec4f0ce216e4112f80875c9fe6fd8dc
languageName: node
linkType: hard
"@relative-ci/agent@npm:^4.3.1":
version: 4.3.1
resolution: "@relative-ci/agent@npm:4.3.1"
@@ -9207,17 +9186,6 @@ __metadata:
languageName: node
linkType: hard
"dnd-core@npm:^16.0.1":
version: 16.0.1
resolution: "dnd-core@npm:16.0.1"
dependencies:
"@react-dnd/asap": "npm:^5.0.1"
"@react-dnd/invariant": "npm:^4.0.1"
redux: "npm:^4.2.0"
checksum: 10c0/6b852c576c88b0a42e618efb37e046334f5e9914b8d38ad139933dd9595b6caf2a484953a6301094d23119c17479549553d71e92fd77fa37318122ea1e579f65
languageName: node
linkType: hard
"dom-serializer@npm:^2.0.0":
version: 2.0.0
resolution: "dom-serializer@npm:2.0.0"
@@ -11107,7 +11075,7 @@ __metadata:
languageName: node
linkType: hard
"hoist-non-react-statics@npm:^3.1.0, hoist-non-react-statics@npm:^3.3.2":
"hoist-non-react-statics@npm:^3.1.0":
version: 3.3.2
resolution: "hoist-non-react-statics@npm:3.3.2"
dependencies:
@@ -14441,8 +14409,6 @@ __metadata:
react-avatar-editor: "npm:^15.1.0"
react-colorful: "npm:^5.8.0"
react-day-picker: "npm:^8.10.2"
react-dnd: "npm:^16.0.1"
react-dnd-html5-backend: "npm:^16.0.1"
react-dom: "npm:^19.3.0"
react-dropzone: "npm:^20.1.2"
react-hook-form: "npm:^7.85.0"
@@ -15910,40 +15876,6 @@ __metadata:
languageName: node
linkType: hard
"react-dnd-html5-backend@npm:^16.0.1":
version: 16.0.1
resolution: "react-dnd-html5-backend@npm:16.0.1"
dependencies:
dnd-core: "npm:^16.0.1"
checksum: 10c0/6e4b632a11e20211d71f5f3bedadf13ecec2fa73372fde388619838294b1375f15b717d1ce128e12c872ff7b15c32d26761d2026b33c14fc55e4fd5477c15289
languageName: node
linkType: hard
"react-dnd@npm:^16.0.1":
version: 16.0.1
resolution: "react-dnd@npm:16.0.1"
dependencies:
"@react-dnd/invariant": "npm:^4.0.1"
"@react-dnd/shallowequal": "npm:^4.0.1"
dnd-core: "npm:^16.0.1"
fast-deep-equal: "npm:^3.1.3"
hoist-non-react-statics: "npm:^3.3.2"
peerDependencies:
"@types/hoist-non-react-statics": ">= 3.3.1"
"@types/node": ">= 12"
"@types/react": ">= 16"
react: ">= 16.14"
peerDependenciesMeta:
"@types/hoist-non-react-statics":
optional: true
"@types/node":
optional: true
"@types/react":
optional: true
checksum: 10c0/d069435750f0d6653cfa2b951cac8abb3583fb144ff134a20176608877d9c5964c63384ebbacaa0fdeef819b592a103de0d8e06f3b742311d64a029ffed0baa3
languageName: node
linkType: hard
"react-dom@npm:^19.3.0":
version: 19.3.0
resolution: "react-dom@npm:19.3.0"
@@ -16268,15 +16200,6 @@ __metadata:
languageName: node
linkType: hard
"redux@npm:^4.2.0":
version: 4.2.1
resolution: "redux@npm:4.2.1"
dependencies:
"@babel/runtime": "npm:^7.9.2"
checksum: 10c0/136d98b3d5dbed1cd6279c8c18a6a74c416db98b8a432a46836bdd668475de6279a2d4fd9d1363f63904e00f0678a8a3e7fa532c897163340baf1e71bb42c742
languageName: node
linkType: hard
"reflect-metadata@npm:^0.2.2":
version: 0.2.2
resolution: "reflect-metadata@npm:0.2.2"