Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.
TypeScript clipboardclipboard-managerdesktop-appdrag-and-dropelectronopen-sourceproductivityproductivity-toolwindows
fix(drag-drop): dropping an item on itself no longer duplicates or mutates it
Deepender25423be5117f76
diff --git a/electron/main/ipc.ts b/electron/main/ipc.tsindex 1f0dfdc..4e4a793 100644--- a/electron/main/ipc.ts+++ b/electron/main/ipc.ts@@ -722,32 +722,30 @@ export function registerSendListeners(): void {// Re-enable the heartbeat now that the drag is over.setHeartbeatPaused(false)- if (dragStarted && isWholeItemDrag) {- // Usage accounting parity with click-to-paste: a whole-item drag counts- // as a use — hitCount bump + optional move to top via the same- // movePastedToTop setting paste uses. Sub-item drags never reorder- // history (same rule as item:paste-subitem). Applied after the gesture- // finishes so nothing extra runs inside the OLE drag loop.- if (loadSettings().movePastedToTop !== false && getStore().get(req.id)) {- getStore().touch(req.id)- }- pushState.items()- }-- // Workaround for Electron/Windows not firing drop events on the source window:// Check if the user dropped the item back onto our window!const { screen, BrowserWindow } = require('electron')const point = screen.getCursorScreenPoint()const win = BrowserWindow.fromWebContents(sender)- if (win) {+ let isInside = false+ if (win && !win.isDestroyed()) {const bounds = win.getBounds()- const isInside = point.x >= bounds.x && point.x <= bounds.x + bounds.width &&- point.y >= bounds.y && point.y <= bounds.y + bounds.height+ isInside = point.x >= bounds.x && point.x <= bounds.x + bounds.width &&+ point.y >= bounds.y && point.y <= bounds.y + bounds.heightif (isInside) {console.log(`[IPC] Drag ended inside window! Triggering internal-drop at x=${point.x - bounds.x}, y=${point.y - bounds.y}`)sender.send('item:internal-drop', { x: point.x - bounds.x, y: point.y - bounds.y })}}++ if (dragStarted && isWholeItemDrag && !isInside) {+ // Usage accounting parity with click-to-paste: a whole-item drag counts+ // as a use ONLY when successfully dropped outside into another application.+ // Dropping back onto the shelf or cancelling does not bump hitCount.+ if (loadSettings().movePastedToTop !== false && getStore().get(req.id)) {+ getStore().touch(req.id)+ }+ pushState.items()+ }})on('item:prestage-drag', (_sender, req) => {diff --git a/electron/preload/index.ts b/electron/preload/index.tsindex a2222b1..871f37f 100644--- a/electron/preload/index.ts+++ b/electron/preload/index.ts@@ -54,17 +54,56 @@ function on<C extends EventChannel>(* contextBridge strips their internal C++ backing, causing webUtils.getPathForFile* to fail. Handling it here natively bypasses the bridge entirely.*/-let internalDrag = false+import { reduceGuard, isGuarded } from './internalDragGuard'++let guard: import('./internalDragGuard').GuardState = { phase: 'idle', fireAt: null }+let guardIdleTimer: ReturnType<typeof setTimeout> | null = null++function dispatchGuard(event: import('./internalDragGuard').GuardEvent): void {+ guard = reduceGuard(guard, event)+ if (event.type === 'dragEnd' && guard.phase === 'releasing') {+ if (guardIdleTimer) clearTimeout(guardIdleTimer)+ const remaining = (guard.fireAt ?? Date.now()) - Date.now()+ guardIdleTimer = setTimeout(() => {+ dispatchGuard({ type: 'tick', now: Date.now() })+ guardIdleTimer = null+ }, Math.max(1, remaining))+ }+ // An explicit 'arm' cancels any pending release timer by leaving it to fire+ // harmlessly against the armed phase ('tick' is a no-op while armed).+}++function setInternalDragState(active: boolean): void {+ if (active) {+ dispatchGuard({ type: 'arm' })+ } else {+ dispatchGuard({ type: 'dragEnd', now: Date.now() })+ }+}const win: any = (globalThis as any).window || globalThis+win.addEventListener('dragstart', () => {+ setInternalDragState(true)+}, true)++win.addEventListener('dragend', () => {+ setInternalDragState(false)+}, true)+win.addEventListener('dragover', (e: any) => {e.preventDefault()}, false)win.addEventListener('drop', (e: any) => {- if (internalDrag) {+ if (isGuarded(guard)) {+ // First drop after one of our drags is ours by the single-mouse+ // invariant (see internalDragGuard.ts). Swallow, consume, and stop any+ // other handler from reacting to our own exported files.+ dispatchGuard({ type: 'drop' })+ if (guardIdleTimer) { clearTimeout(guardIdleTimer); guardIdleTimer = null }e.preventDefault()+ e.stopPropagation()return}@@ -152,7 +191,10 @@ const api = {checkForUpdatesManual: () => invoke('updater:check-manual'),startUpdateDownload: () => invoke('updater:start-download'),quitApp: () => invoke('app:quit'),- startDrag: (req: DragRequest) => send('item:start-drag', req),+ startDrag: (req: DragRequest) => {+ setInternalDragState(true)+ send('item:start-drag', req)+ },prestageDrag: (req: DragRequest) => send('item:prestage-drag', req),addFiles: (paths: string[]) => invoke('item:add-files', paths),addItemData: (data: import('../../shared/types').ItemData) => invoke('item:add-data', data),@@ -170,7 +212,7 @@ const api = {revealFile: (path: string) => invoke('file:reveal', path),minimizeWindow: () => invoke('window:minimize'),focusWindow: (focusable?: boolean) => invoke('window:focus', focusable),- setInternalDrag: (active: boolean) => { internalDrag = active },+ setInternalDrag: (active: boolean) => { setInternalDragState(active) },broadcastTutorialStep: (step: number) => send('tutorial:set-step', step),/* Main -> Renderer */@@ -178,7 +220,12 @@ const api = {onSettings: (cb: (settings: EventArgs<'state:settings'>[0]) => void) => on('state:settings', cb),onToggle: (cb: (open?: boolean) => void) => on('window:toggle', cb),onOpenSettings: (cb: () => void) => on('window:open-settings', cb),- onDragEnd: (cb: () => void) => on('item:drag-end', cb),+ onDragEnd: (cb: () => void) => {+ return on('item:drag-end', () => {+ setInternalDragState(false)+ cb()+ })+ },onInternalDrop: (cb: (pos: { x: number; y: number }) => void) => on('item:internal-drop', cb),onCursorEdge: (cb: (data: EventArgs<'window:cursor-edge'>[0]) => void) => on('window:cursor-edge', cb),onToast: (cb: (toast: { id: string; message: string; tone: 'info' | 'error' }) => void) => on('ui:toast', cb),diff --git a/electron/preload/internalDragGuard.ts b/electron/preload/internalDragGuard.tsnew file mode 100644index 0000000..cda80bb--- /dev/null+++ b/electron/preload/internalDragGuard.ts@@ -0,0 +1,82 @@+/**+ * Internal-drag boomerang guard — pure state machine.+ *+ * PROBLEM+ * -------+ * When Edge-Drop exports an item via a native OS drag and the user drops it+ * back onto our own window, Windows delivers that drop ASYNCHRONOUSLY after+ * the OLE loop returns — sometimes well over a second later on loaded+ * systems. Without protection the delivered files re-enter item:add-files+ * as a fresh import (self-drop duplication).+ *+ * INVARIANT (physics, not timing)+ * -------------------------------+ * There is exactly one mouse. After one of OUR drags starts, the FIRST drop+ * event observed is ours — no human can start dragging a file from Explorer+ * into us before finishing the current gesture. Therefore:+ *+ * armed : from our dragstart until the first drop is consumed+ * drop : while armed => ours => swallow + consume back to idle+ * dragEnd: begins 'releasing' — a grace window (GUARD_AUTO_IDLE_MS) that+ * still swallows late-deferred deliveries, then self-heals to+ * idle so external imports can never be permanently blocked.+ *+ * The 'armed' phase intentionally has NO timer: Chromium synthesizes+ * dragend reliably (including Esc-cancel), and a mid-gesture expiry would+ * unprotect the boomerang. Worst case if dragend were never fired (crash-+ * level defect): ONE external import gets swallowed, then the machine+ * self-heals via that very consume.+ *+ * Pure reducer + explicit events so every transition is unit-testable.+ */++export type GuardPhase = 'idle' | 'armed' | 'releasing'++export interface GuardState {+ phase: GuardPhase+ /** Absolute deadline when phase === 'releasing'. */+ fireAt: number | null+}++/** Grace window after dragEnd that still swallows deferred deliveries. */+export const GUARD_AUTO_IDLE_MS = 1500++export type GuardEvent =+ | { type: 'arm' }+ | { type: 'dragEnd'; now: number }+ | { type: 'drop' }+ | { type: 'tick'; now: number }++const IDLE: GuardState = { phase: 'idle', fireAt: null }++export function reduceGuard(state: GuardState, event: GuardEvent): GuardState {+ switch (event.type) {+ case 'arm':+ // Re-arming at any time (redundant dragstart, new gesture) yields a+ // clean armed phase and cancels any pending release.+ return { phase: 'armed', fireAt: null }++ case 'drop':+ // First drop while armed/releasing is OURS by the single-mouse+ // invariant: consume it and return to idle. Drops while idle are not+ // routed through the reducer at all (external imports flow normally).+ return IDLE++ case 'dragEnd':+ if (state.phase !== 'armed') return state+ return { phase: 'releasing', fireAt: event.now + GUARD_AUTO_IDLE_MS }++ case 'tick':+ if (state.phase !== 'releasing' || state.fireAt === null) return state+ if (event.now >= state.fireAt) return IDLE+ return state++ default:+ return state+ }+}++/** Convenience predicate used by the drop listener. */+export function isGuarded(state: GuardState): boolean {+ return state.phase !== 'idle'+}diff --git a/src/components/ClipboardItem.tsx b/src/components/ClipboardItem.tsxindex ba7876d..28bc674 100644--- a/src/components/ClipboardItem.tsx+++ b/src/components/ClipboardItem.tsx@@ -14,7 +14,7 @@* clamped preview; file items list names or bundle badge. Motion is handled by* the parent list (layout/AnimatePresence), so this component stays presentational.*/-import { memo, useState, useCallback, useEffect, forwardRef, type ReactNode } from 'react'+import { memo, useState, useCallback, useEffect, useRef, forwardRef, type ReactNode } from 'react'import { motion } from 'framer-motion'import type { ClipboardItemDto } from '../../shared/types'import { MAX_STACK } from '../../shared/types'@@ -150,8 +150,8 @@ const ClipboardItemBase = forwardRef<HTMLDivElement, Props>(({ item }, ref) => {// drag managed by the OS. Fire the IPC synchronously so main calls// event.sender.startDrag(...) on the same tick.e.preventDefault()- startDrag(req)setInternalDragReq(req)+ startDrag(req)}}, [item.data, startDrag, setInternalDragReq])@@ -161,6 +161,40 @@ const ClipboardItemBase = forwardRef<HTMLDivElement, Props>(({ item }, ref) => {}}, [item.data.kind, isPreviewing, item.id])+ const pointerStartRef = useRef<{ x: number; y: number; moved: boolean } | null>(null)++ const handlePointerDown = useCallback((e: React.PointerEvent) => {+ if (e.button === 0) {+ pointerStartRef.current = { x: e.clientX, y: e.clientY, moved: false }+ }+ handlePrestage()+ }, [handlePrestage])++ const handlePointerMove = useCallback((e: React.PointerEvent) => {+ if (!pointerStartRef.current) return+ const dist = Math.hypot(e.clientX - pointerStartRef.current.x, e.clientY - pointerStartRef.current.y)+ if (dist > 5) {+ pointerStartRef.current.moved = true+ }+ }, [])++ const handleCardClick = useCallback((e: React.MouseEvent) => {+ if (pointerStartRef.current?.moved) {+ // User dragged or attempted to drag — do not execute click/paste!+ pointerStartRef.current = null+ e.stopPropagation()+ return+ }+ pointerStartRef.current = null++ if (isPreviewing) return+ if (isBundle && !expanded) {+ onExpand(e)+ } else if (!isBundle) {+ onPaste(e)+ }+ }, [isPreviewing, isBundle, expanded, onExpand, onPaste])+return (<motion.divref={ref}@@ -193,8 +227,12 @@ const ClipboardItemBase = forwardRef<HTMLDivElement, Props>(({ item }, ref) => {data-id={item.id}draggable={!isPreviewing && item.data.kind !== 'text' && (!isBundle || !expanded)}onMouseEnter={handlePrestage}- onPointerDown={handlePrestage}- onDragStart={(e) => handleDragStart(e, { id: item.id })}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onDragStart={(e) => {+ if (pointerStartRef.current) pointerStartRef.current.moved = true+ handleDragStart(e, { id: item.id })+ }}onDragEnd={() => setInternalDragReq(null)}onDragOver={(e) => {const activeDrag = useStore.getState().internalDragReq@@ -221,7 +259,7 @@ const ClipboardItemBase = forwardRef<HTMLDivElement, Props>(({ item }, ref) => {setInternalDragReq(null)}}}- onClick={isPreviewing ? undefined : (isBundle && !expanded ? onExpand : (!isBundle ? onPaste : undefined))}+ onClick={handleCardClick}><div className="body">{isBundle ? (diff --git a/src/components/Panel.tsx b/src/components/Panel.tsxindex a439f30..b3776ec 100644--- a/src/components/Panel.tsx+++ b/src/components/Panel.tsx@@ -143,13 +143,8 @@ export function Panel() {} else if (targetId === req.id) {// Dropped on the SAME item: do nothing, keep it in the collection}- } else {- // Dropped on empty space: split only if dropped inside item-list container- const itemListEl = el.closest('.item-list')- if (itemListEl && (req.imageId || (req.paths && req.paths.length > 0))) {- window.edge.splitItem(req)- }}+ // Dropping anywhere else (e.g. empty shelf / list space) is a clean return to shelf (no-op).})return () => {@@ -191,13 +186,9 @@ export function Panel() {const onDrop = (e: React.DragEvent) => {e.preventDefault()e.stopPropagation()- console.log('[Panel] onDrop internalDragReq=', internalDragReq)if (internalDragReq) {- if (internalDragReq.imageId || (internalDragReq.paths && internalDragReq.paths.length > 0)) {- console.log('[Panel] calling splitItem')- window.edge.splitItem(internalDragReq)- }setInternalDragReq(null)+ window.edge?.setInternalDrag?.(false)}setDragActive(false)}diff --git a/src/hooks/useDragOut.ts b/src/hooks/useDragOut.tsindex adc5d2a..382d12e 100644--- a/src/hooks/useDragOut.ts+++ b/src/hooks/useDragOut.ts@@ -12,10 +12,12 @@*/import { useCallback } from 'react'import { edge } from '../lib/edge'+import { useStore } from '../store/appStore'import type { DragRequest } from '../../shared/types'export function useDragOut() {return useCallback((req: DragRequest) => {+ useStore.getState().setInternalDragReq(req)edge.startDrag(req)}, [])}diff --git a/src/lib/edge.ts b/src/lib/edge.tsindex 76e3fc4..432fd3a 100644--- a/src/lib/edge.ts+++ b/src/lib/edge.ts@@ -19,7 +19,9 @@ export const edge: EdgeApi = new Proxy({} as EdgeApi, {if (g.window && g.window.edge) {const targetApi = g.window.edgeconst val = targetApi[prop]- return typeof val === 'function' ? val.bind(targetApi) : val+ if (typeof val === 'function') return val.bind(targetApi)+ if (val !== undefined) return val+ return () => {}}return () => {}}diff --git a/src/store/appStore.ts b/src/store/appStore.tsindex da525be..cd139e3 100644--- a/src/store/appStore.ts+++ b/src/store/appStore.ts@@ -320,7 +320,7 @@ export const useStore = create<AppState>((set, get) => ({} else {set({ internalDragReq })}- edge.setInternalDrag(!!internalDragReq)+ edge.setInternalDrag?.(!!internalDragReq)},previewFlyoutRect: null,setPreviewFlyoutRect: (rect) => set({ previewFlyoutRect: rect }),diff --git a/src/styles/global.css b/src/styles/global.cssindex 582b330..424e5d7 100644--- a/src/styles/global.css+++ b/src/styles/global.css@@ -94,12 +94,19 @@ a {-webkit-user-drag: none;}-/* Our draggable surfaces opt back into native dragging. */-.item-main,+/* Draggable surfaces opt into dragging only when explicitly marked draggable */+.item-main[draggable="true"],.file-row {-webkit-user-drag: element;}+.item-main[draggable="false"],+.item-main:not([draggable="true"]) {+ -webkit-user-drag: none;+ user-select: none;+ -webkit-user-select: none;+}+button {font: inherit;color: inherit;diff --git a/tests/dragDrop.test.ts b/tests/dragDrop.test.tsindex 584aa00..0ece327 100644--- a/tests/dragDrop.test.ts+++ b/tests/dragDrop.test.ts@@ -216,3 +216,32 @@ describe('buildFileDragSvg — standalone 3D pastel vector drag icons', () => {expect(svg).toContain('stack-2')})})++describe('Drag-out usage gating on drop location', () => {+ it('does not touch item when drag drops back inside the source window', () => {+ const touchSpy = vi.fn()+ const isWholeItemDrag = true+ const isInside = true // Dropped back onto Edge-Drop window+ const movePastedToTop = true++ if (isWholeItemDrag && !isInside && movePastedToTop) {+ touchSpy('item-1')+ }++ expect(touchSpy).not.toHaveBeenCalled()+ })++ it('touches item and moves unpinned to top when dropped outside into external app', () => {+ const touchSpy = vi.fn()+ const isWholeItemDrag = true+ const isInside = false // Dropped into Word / Photoshop / Explorer+ const movePastedToTop = true++ if (isWholeItemDrag && !isInside && movePastedToTop) {+ touchSpy('item-1')+ }++ expect(touchSpy).toHaveBeenCalledWith('item-1')+ })+})+diff --git a/tests/internalDragGuard.test.ts b/tests/internalDragGuard.test.tsnew file mode 100644index 0000000..72003fb--- /dev/null+++ b/tests/internalDragGuard.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest'+import {+ reduceGuard,+ isGuarded,+ GUARD_AUTO_IDLE_MS,+ type GuardState,+ type GuardEvent+} from '../electron/preload/internalDragGuard'++const T0 = 1000+const idle: GuardState = { phase: 'idle', fireAt: null }++function run(state: GuardState, events: GuardEvent[]): GuardState {+ return events.reduce(reduceGuard, state)+}++describe('internalDragGuard state machine', () => {+ it('arm transitions idle -> armed with no expiry (dragend is trusted)', () => {+ const s = reduceGuard(idle, { type: 'arm' })+ expect(s.phase).toBe('armed')+ expect(s.fireAt).toBeNull()+ expect(isGuarded(s)).toBe(true)+ })++ it('FIRST drop while armed is consumed back to idle — the single-mouse invariant', () => {+ const s = run(idle, [{ type: 'arm' }, { type: 'drop' }])+ expect(s).toEqual(idle)+ expect(isGuarded(s)).toBe(false)+ })++ it('redundant arm while armed stays armed (does not unlock)', () => {+ const s = run(idle, [{ type: 'arm' }, { type: 'arm' }])+ expect(s.phase).toBe('armed')+ })++ it('dragEnd begins releasing with a deadline of now + AUTO_IDLE', () => {+ const s = reduceGuard({ phase: 'armed', fireAt: null }, { type: 'dragEnd', now: T0 })+ expect(s.phase).toBe('releasing')+ expect(s.fireAt).toBe(T0 + GUARD_AUTO_IDLE_MS)+ })++ it('a drop DURING the release window is still swallowed (deferred delivery) and consumes the guard', () => {+ // THE regression case: Windows delivers our boomerang long after dragEnd.+ let s = run(idle, [{ type: 'arm' }, { type: 'dragEnd', now: T0 }])+ const lateDelivery = T0 + GUARD_AUTO_IDLE_MS - 200 // 200ms before expiry+ s = reduceGuard(s, { type: 'tick', now: lateDelivery })+ expect(isGuarded(s)).toBe(true) // still protected+ s = reduceGuard(s, { type: 'drop' })+ expect(s).toEqual(idle)+ })++ it('release expires to idle so external imports are never permanently blocked', () => {+ let s = run(idle, [{ type: 'arm' }, { type: 'dragEnd', now: T0 }])+ s = reduceGuard(s, { type: 'tick', now: T0 + GUARD_AUTO_IDLE_MS - 1 })+ expect(isGuarded(s)).toBe(true)+ s = reduceGuard(s, { type: 'tick', now: T0 + GUARD_AUTO_IDLE_MS })+ expect(s).toEqual(idle)+ expect(isGuarded(s)).toBe(false)+ })++ it('ticks before the deadline leave the releasing state untouched', () => {+ const armedThenEnd = run(idle, [{ type: 'arm' }, { type: 'dragEnd', now: T0 }])+ const s = reduceGuard(armedThenEnd, { type: 'tick', now: T0 + 10 })+ expect(s.phase).toBe('releasing')+ expect(s.fireAt).toBe(T0 + GUARD_AUTO_IDLE_MS)+ })++ it('re-arm during the release window cancels expiry and re-protects a new gesture', () => {+ let s = run(idle, [{ type: 'arm' }, { type: 'dragEnd', now: T0 }])+ s = reduceGuard(s, { type: 'arm' }) // new gesture starts before expiry+ expect(s.phase).toBe('armed')++ // The old deadline passing must NOT expire an armed phase.+ const afterOldDeadline = reduceGuard(s, { type: 'tick', now: T0 + GUARD_AUTO_IDLE_MS + 500 })+ expect(afterOldDeadline.phase).toBe('armed')+ expect(isGuarded(afterOldDeadline)).toBe(true)++ // And its own first drop still consumes.+ expect(reduceGuard(afterOldDeadline, { type: 'drop' })).toEqual(idle)+ })++ it('drop while IDLE is not a guard event (external imports unaffected by design)', () => {+ // The listener never routes unguarded drops through the reducer; asserted+ // here as documentation that idle+drop is a no-op transition.+ expect(reduceGuard(idle, { type: 'drop' })).toEqual(idle)+ })++ it('full real-world lifecycle: arm -> gesture -> dragEnd -> deferred boomerang swallow -> idle -> next arm', () => {+ let s = idle+ s = reduceGuard(s, { type: 'arm' }) // user grabs card+ s = reduceGuard(s, { type: 'dragEnd', now: T0 + 900 }) // dropped on shelf; OLE done+ s = reduceGuard(s, { type: 'tick', now: T0 + 950 }) // boomerang arrives 50ms later+ expect(isGuarded(s)).toBe(true)+ s = reduceGuard(s, { type: 'drop' }) // swallowed+ expect(s).toEqual(idle)+ s = reduceGuard(s, { type: 'arm' }) // user drags something else later+ expect(isGuarded(s)).toBe(true)+ s = reduceGuard(s, { type: 'drop' })+ expect(s).toEqual(idle)+ })++ it('crash safety: if dragEnd never fired, one external import self-heals the lockout', () => {+ // Worst-case defect: stuck armed. The very next drop (even an external+ // one) consumes the guard, so imports recover after at most ONE loss.+ const stuck = { phase: 'armed' as const, fireAt: null }+ const healed = reduceGuard(stuck, { type: 'drop' })+ expect(healed).toEqual(idle)+ })+})