From c59e0f59b3ca1db06fd618ddef92081e8aeae2b0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 21 Oct 2026 21:51:21 -0400 Subject: [PATCH] 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 --- app/components/AuthenticatedLayout.tsx | 7 +- .../DragAndDrop/DragAndDropProvider.tsx | 351 ++++++++++++++++++ app/components/DragAndDrop/DragDropManager.ts | 334 +++++++++++++++++ app/components/DragAndDrop/hooks.ts | 183 +++++++++ app/components/DragAndDrop/index.ts | 3 + app/components/EditorAwareHTML5Backend.ts | 89 ----- .../Sidebar/components/CollectionLink.tsx | 3 +- .../components/CollectionLinkChildren.tsx | 13 +- .../Sidebar/components/Collections.tsx | 3 +- .../Sidebar/components/DocumentLink.tsx | 3 +- .../Sidebar/components/DocumentTree.tsx | 2 +- .../Sidebar/components/DragActiveContext.tsx | 12 +- .../Sidebar/components/DragPlaceholder.tsx | 46 +-- .../components/DraggableCollectionLink.tsx | 13 +- .../Sidebar/components/DraggableSection.tsx | 35 +- .../Sidebar/components/DropCursor.tsx | 2 +- .../Sidebar/components/DropToImport.tsx | 2 +- app/components/Sidebar/components/NavLink.tsx | 6 +- .../Sidebar/components/SharedWithMeLink.tsx | 3 +- .../Sidebar/components/SidebarLink.tsx | 14 +- .../Sidebar/components/StarredLink.tsx | 3 +- .../Sidebar/components/TrashLink.tsx | 3 +- .../Sidebar/hooks/useDragAndDrop.tsx | 346 +++++++---------- app/scenes/Document/components/Document.tsx | 8 +- package.json | 2 - shared/i18n/locales/en_US/translation.json | 3 + yarn.lock | 81 +--- 27 files changed, 1048 insertions(+), 522 deletions(-) create mode 100644 app/components/DragAndDrop/DragAndDropProvider.tsx create mode 100644 app/components/DragAndDrop/DragDropManager.ts create mode 100644 app/components/DragAndDrop/hooks.ts create mode 100644 app/components/DragAndDrop/index.ts delete mode 100644 app/components/EditorAwareHTML5Backend.ts diff --git a/app/components/AuthenticatedLayout.tsx b/app/components/AuthenticatedLayout.tsx index d1b3ef235e..75afb732a4 100644 --- a/app/components/AuthenticatedLayout.tsx +++ b/app/components/AuthenticatedLayout.tsx @@ -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 = ({ children }: Props) => { - + = ({ children }: Props) => { - + diff --git a/app/components/DragAndDrop/DragAndDropProvider.tsx b/app/components/DragAndDrop/DragAndDropProvider.tsx new file mode 100644 index 0000000000..46d729631e --- /dev/null +++ b/app/components/DragAndDrop/DragAndDropProvider.tsx @@ -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(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 ( + + + + + {children} + + ); +} + +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; +}) { + 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); +} diff --git a/app/components/DragAndDrop/DragDropManager.ts b/app/components/DragAndDrop/DragDropManager.ts new file mode 100644 index 0000000000..fc550bf3d0 --- /dev/null +++ b/app/components/DragAndDrop/DragDropManager.ts @@ -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 { + /** 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 { + /** 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; +} + +/** A registered drop target. */ +export interface DropTarget { + /** Returns the latest target specification. */ + getSpec(): DropTargetSpec; +} + +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(); + 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(); + + private targets = new WeakMap>(); + + 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; +} diff --git a/app/components/DragAndDrop/hooks.ts b/app/components/DragAndDrop/hooks.ts new file mode 100644 index 0000000000..128254ef96 --- /dev/null +++ b/app/components/DragAndDrop/hooks.ts @@ -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 { + /** 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( + 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( + spec: DragSourceSpec +): [boolean, RefCallback] { + const manager = useContext(DragDropManagerContext); + const specRef = useLatest(spec); + const [source] = useState(() => ({ + 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( + spec: DropTargetHookSpec +): [Collected, RefCallback] { + const manager = useContext(DragDropManagerContext); + const specRef = useLatest(spec); + const [target] = useState(() => ({ + 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( + 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 { + 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(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( + 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); +} diff --git a/app/components/DragAndDrop/index.ts b/app/components/DragAndDrop/index.ts new file mode 100644 index 0000000000..aceda7650a --- /dev/null +++ b/app/components/DragAndDrop/index.ts @@ -0,0 +1,3 @@ +export { DragAndDropProvider } from "./DragAndDropProvider"; +export { useDragFollower, useDragLayer, useDragRef, useDropRef } from "./hooks"; +export type { Point } from "./DragDropManager"; diff --git a/app/components/EditorAwareHTML5Backend.ts b/app/components/EditorAwareHTML5Backend.ts deleted file mode 100644 index b1924052d4..0000000000 --- a/app/components/EditorAwareHTML5Backend.ts +++ /dev/null @@ -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; -}; diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index 75697700bf..70cdecc898 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -59,8 +59,7 @@ const CollectionLink: React.FC = ({ const parentRef = React.useRef(null); const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection( collection, - handleExpand, - parentRef + handleExpand ); const handlePrefetch = React.useCallback(() => { diff --git a/app/components/Sidebar/components/CollectionLinkChildren.tsx b/app/components/Sidebar/components/CollectionLinkChildren.tsx index cbde050b87..e014ec155a 100644 --- a/app/components/Sidebar/components/CollectionLinkChildren.tsx +++ b/app/components/Sidebar/components/CollectionLinkChildren.tsx @@ -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(null); - const [{ isOver, canDrop }] = useDropToChangeCollection( - collection, - noop, - dummyRef - ); + const [{ isOver, canDrop }] = useDropToChangeCollection(collection, noop); if (!canDrop || !collection.isManualSort) { return null; } - return ( - - ); + return ; } ); diff --git a/app/components/Sidebar/components/Collections.tsx b/app/components/Sidebar/components/Collections.tsx index 36ecccd66a..23c31bc3a7 100644 --- a/app/components/Sidebar/components/Collections.tsx +++ b/app/components/Sidebar/components/Collections.tsx @@ -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"; diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 7f5d45a8c7..7053c31003 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -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. diff --git a/app/components/Sidebar/components/DocumentTree.tsx b/app/components/Sidebar/components/DocumentTree.tsx index 1bb79c0b96..deae349cde 100644 --- a/app/components/Sidebar/components/DocumentTree.tsx +++ b/app/components/Sidebar/components/DocumentTree.tsx @@ -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)); diff --git a/app/components/Sidebar/components/DragActiveContext.tsx b/app/components/Sidebar/components/DragActiveContext.tsx index 1cd5ef9c06..cda9c5d203 100644 --- a/app/components/Sidebar/components/DragActiveContext.tsx +++ b/app/components/Sidebar/components/DragActiveContext.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import { useDragLayer } from "react-dnd"; +import { useDragLayer } from "~/components/DragAndDrop"; const DraggedItemContext = React.createContext(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 diff --git a/app/components/Sidebar/components/DragPlaceholder.tsx b/app/components/Sidebar/components/DragPlaceholder.tsx index 1631cabcc9..09340f0e57 100644 --- a/app/components/Sidebar/components/DragPlaceholder.tsx +++ b/app/components/Sidebar/components/DragPlaceholder.tsx @@ -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(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 (
-
+
({ 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: , }), - 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(() => { diff --git a/app/components/Sidebar/components/DraggableSection.tsx b/app/components/Sidebar/components/DraggableSection.tsx index 8ce612f44e..5cc1db89e4 100644 --- a/app/components/Sidebar/components/DraggableSection.tsx +++ b/app/components/Sidebar/components/DraggableSection.tsx @@ -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 ( - {showCursors && ( + {bottomProps.isDragging && ( )} - + {children} - {showCursors && ( + {bottomProps.isDragging && ( { - 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; diff --git a/app/components/Sidebar/components/DropCursor.tsx b/app/components/Sidebar/components/DropCursor.tsx index 33591b4e9b..0f5a100382 100644 --- a/app/components/Sidebar/components/DropCursor.tsx +++ b/app/components/Sidebar/components/DropCursor.tsx @@ -3,7 +3,7 @@ import styled from "styled-components"; type Props = { isActiveDrop: boolean; - innerRef: React.Ref; + innerRef?: React.Ref; position?: "top"; /** Inline-start offset of the visible line in pixels, to match a tree depth. */ indent?: number; diff --git a/app/components/Sidebar/components/DropToImport.tsx b/app/components/Sidebar/components/DropToImport.tsx index 5c5dffc3e4..f691bf303a 100644 --- a/app/components/Sidebar/components/DropToImport.tsx +++ b/app/components/Sidebar/components/DropToImport.tsx @@ -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")) { diff --git a/app/components/Sidebar/components/NavLink.tsx b/app/components/Sidebar/components/NavLink.tsx index b19cbef993..3e6f1c54a0 100644 --- a/app/components/Sidebar/components/NavLink.tsx +++ b/app/components/Sidebar/components/NavLink.tsx @@ -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); } diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 0aca26920e..3aad560bc7 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -130,8 +130,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { const [{ isOverReparent }, dropToReparent] = useDropToReparentDocument( reparentableNode, undefined, - setExpanded, - parentRef + setExpanded ); const { icon } = useSidebarLabelAndIcon(membership); diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx index 5a6a19083e..d884bb3d4b 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -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; diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx index 6a48f7df56..b00a8b52c8 100644 --- a/app/components/Sidebar/components/StarredLink.tsx +++ b/app/components/Sidebar/components/StarredLink.tsx @@ -295,8 +295,7 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ const parentRef = React.useRef(null); const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection( collection, - handleExpand, - parentRef + handleExpand ); const handleRename = React.useCallback(() => { diff --git a/app/components/Sidebar/components/TrashLink.tsx b/app/components/Sidebar/components/TrashLink.tsx index 77fc4e9286..72fc24670f 100644 --- a/app/components/Sidebar/components/TrashLink.tsx +++ b/app/components/Sidebar/components/TrashLink.tsx @@ -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() { diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index d49291efa8..127b4e1427 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -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 { - return React.useCallback( - (node: HTMLElement | null) => void connect(node), - [connect] +function useHoverTimer(callback: () => void) { + const timeoutRef = React.useRef | 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 - > -): [CollectedProps, React.RefCallback, 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 - > -): [CollectedProps, React.RefCallback] { - const [collected, connect] = useDrop( - spec - ); - return [collected, useConnectorRef(connect)]; -} - -function useHover( - elementRef: React.RefObject, - callback: () => void -) { - const hoverTimeoutRef = React.useRef< - ReturnType | 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, - { 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( + { + 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, - { 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( + { + 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] { - 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, - { isDragging: boolean } - >({ + const [isDragging, dragRef] = useDragRef({ 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 + 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, - { isOver: boolean; canDrop: boolean } - >({ + const result = useDropRef({ 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 + 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, { isOverReparent: boolean }>({ + const result = useDropRef({ 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, { isOverReorder: boolean }>({ + return useDropRef({ 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, - { 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( + { + 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, { isOverArchiveSection: boolean; isDragging: boolean } >({ accept, @@ -737,11 +643,7 @@ export function useDropToUnpublish() { const { t } = useTranslation(); const { policies, documents } = useStores(); - return useDropRef< - DragObject, - Promise, - { isOver: boolean; canDrop: boolean } - >({ + return useDropRef({ accept: "document", drop: async (item) => { const document = documents.get(item.id); diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index 8dabe7a661..4012333110 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -394,13 +394,7 @@ function DocumentScene({ }} handler={onPublish} /> - + {(isUploading || isSaving) && } diff --git a/package.json b/package.json index 0060c4ac4e..89003ccebd 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index a868a4ddca..f72569b8e6 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -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", diff --git a/yarn.lock b/yarn.lock index bbd975ffbd..d84fc2f136 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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"