Showing preview only (220K chars total). Download the full file or copy to clipboard to get everything.
Repository: react-grid-layout/react-draggable
Branch: master
Commit: 4c6e95a15caf
Files: 44
Total size: 208.5 KB
Directory structure:
gitextract_6qqp8t9w/
├── .babelrc.js
├── .browserslistrc
├── .eslintrc
├── .flowconfig
├── .github/
│ └── workflows/
│ ├── ci.yml
│ └── gh-pages.yml
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── CLAUDE.md
├── LICENSE
├── Makefile
├── README.md
├── appveyor.yml
├── eslint.config.mjs
├── example/
│ ├── example-styles.css
│ ├── example.js
│ └── index.html
├── lib/
│ ├── Draggable.js
│ ├── DraggableCore.js
│ ├── cjs.js
│ └── utils/
│ ├── domFns.js
│ ├── getPrefix.js
│ ├── log.js
│ ├── positionFns.js
│ ├── shims.js
│ └── types.js
├── package.json
├── test/
│ ├── Draggable.test.jsx
│ ├── DraggableCore.test.jsx
│ ├── browser/
│ │ ├── browser.test.js
│ │ └── test.html
│ ├── setup.js
│ ├── testUtils.js
│ └── utils/
│ ├── domFns.test.js
│ ├── getPrefix.test.js
│ ├── positionFns.test.js
│ └── shims.test.js
├── typings/
│ ├── index.d.ts
│ ├── test.tsx
│ └── tsconfig.json
├── vitest.browser.config.js
├── vitest.config.js
└── webpack.config.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc.js
================================================
'use strict';
module.exports = {
"presets": [
[
"@babel/preset-env",
{
targets: "> 0.25%, not dead"
},
],
"@babel/react",
"@babel/preset-flow"
],
"plugins": [
"@babel/plugin-transform-flow-comments",
"@babel/plugin-transform-class-properties",
"transform-inline-environment-variables"
]
}
================================================
FILE: .browserslistrc
================================================
> 0.25%
ie 11
not dead
================================================
FILE: .eslintrc
================================================
{
"parser": "@babel/eslint-parser",
"extends": "eslint:recommended",
"plugins": [
"react"
],
"ignorePatterns": ["build/**/*.js"],
"rules": {
"strict": 0,
"quotes": [1, "single"],
"curly": [1, "multi-line"],
"camelcase": 0,
"comma-dangle": 0,
"no-console": 2,
"no-use-before-define": [1, "nofunc"],
"no-underscore-dangle": 0,
"no-unused-vars": [1, {ignoreRestSiblings: true}],
"new-cap": 0,
"prefer-const": 1,
"semi": 1
},
env: {
"browser": true,
"node": true
},
globals: {
// For Flow
"ReactElement",
"ReactClass",
"$Exact",
"Partial",
"$Keys",
"MouseTouchEvent",
}
}
================================================
FILE: .flowconfig
================================================
[ignore]
<PROJECT_ROOT>/node_modules/webpack-cli.*
<PROJECT_ROOT>/node_modules/.*malformed_package_json.*
[include]
lib/
index.js
[options]
sharedmemory.heap_size=3221225472
exact_by_default=true
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Lint
run: yarn lint
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 22, 24]
steps:
- uses: actions/checkout@v4
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Run unit tests
run: yarn test
- name: Build
run: yarn build
test-browser:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Run browser tests
run: yarn test:browser
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Run tests with coverage
run: yarn test:coverage
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Flow check
run: yarn flow
- name: TypeScript check
run: yarn tsc -p typings
================================================
FILE: .github/workflows/gh-pages.yml
================================================
name: Build and Deploy to GitHub Pages
permissions:
contents: write
on:
push:
tags:
- "*"
workflow_dispatch:
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout 🛎️
uses: actions/checkout@v4
- name: Install and Build
run: |
yarn
yarn build
yarn build-example
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action@v4
with:
branch: gh-pages # The branch the action should deploy to.
folder: example # The folder the action should deploy.
================================================
FILE: .gitignore
================================================
.idea
*.iml
node_modules/
build/
example/build/
coverage/
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "10"
- "12"
- "node" # latest
cache: yarn
env:
- MOZ_HEADLESS=1
addons:
firefox: latest
script:
- make lint
- make test
- make test-phantom
email:
on_failure: change
on_success: never
================================================
FILE: CHANGELOG.md
================================================
# Changelog
### 4.5.0 (Jun 25, 2025)
- Internal: Update clsx version (#754)
- Fix: bounds="selector" functionality when in a Shadow DOM tree. (#763)
- Perf: Update nodeRef type for React v19 compatibility (#769)
- Fix: forgotten requestAnimationFrame call (#773)
- Perf: setState in lifecycles + forced reflow (#556)
- Fix: add allowMobileScroll prop to allow for clicks to optionally pass through on mobile (#760)
### 4.4.6 (Sep 27, 2023)
- Fix: state inconsistency in React 18 #699
- Internal: devDependencies updates
### 4.4.5 (Apr 26, 2022)
- Fix: `grid` prop unused in `handleDragStop` #621
- Fix: `children` prop missing in TypeScript definition #648
- Internal: Various devDep updates
### 4.4.4 (Aug 27, 2021)
- Fix: Ensure `documentElement.style` actually exists. Fixes crashes in some obscure environments. #574 #575
- Fix: Add react/react-dom as `peerDependencies` again to fix Yarn PnP
- Size: Replace `classnames` with `clsx` to save a few bytes
- Internal: Additional tests on `ref` functionality and additional README content on `nodeRef`
- Internal: Lots of devDependencies updates
- Docs: Various README and demo updates, see git commits
### 4.4.3 (June 8, 2020)
- Add `nodeRef` to TypeScript definitions
### 4.4.2 (May 14, 2020)
- Fix: Remove "module" from package.json (it is no longer being built)
- Fixes #482
### 4.4.1 (May 12, 2020)
- Fix: Remove "module" definition in package.json
- Giving up on this: there isn't a great reason to publish modules
here as they won't be significantly tree-shook, and it bloats
the published package.
- Fixes incompatiblity in 4.4.0 with webpack, where webpack is now
selecting "module" because "browser" is no longer present.
### 4.4.0 (May 12, 2020)
- Add `nodeRef`:
- If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.
Unfortunately, in order for `<Draggable>` to work properly, we need raw access
to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`
as in this example:
```js
function MyComponent() {
const nodeRef = React.useRef(null);
return (
<Draggable nodeRef={nodeRef}>
<div ref={nodeRef}>Example Target</div>
</Draggable>
);
}
````
This can be used for arbitrarily nested components, so long as the ref ends up
pointing to the actual child DOM node and not a custom component.
Thanks to react-transition-group for the inspiration.
`nodeRef` is also available on `<DraggableCore>`.
- Remove "browser" field in "package.json":
- There is nothing special in the browser build that is actually practical
for modern use. The "browser" field, as defined in
https://github.com/defunctzombie/package-browser-field-spec#overview,
indicates that you should use it if you are directly accessing globals,
using browser-specific features, dom manipulation, etc.
React components like react-draggable are built to do minimal raw
DOM manipulation, and to always gate this behind conditionals to ensure
that server-side rendering still works. We don't make any changes
to any of that for the "browser" build, so it's entirely redundant.
This should also fix the "Super expression must either be null or
a function" error (#472) that some users have experienced with particular
bundler configurations.
The browser build may still be imported at "build/web/react-draggable.min.js".
This is to prevent breakage only. The file is no longer minified to prevent
possible [terser bugs](https://github.com/terser/terser/issues/308).
- The browser build will likely be removed entirely in 5.0.
- Fix: Make `bounds` optional in TypeScript [#473](https://github.com/strml/react-draggable/pull/473)
### 4.3.1 (Apr 11, 2020)
> This is a bugfix release.
- Happy Easter!
- Fixed a serious bug that caused `<DraggableCore>` not to pass styles.
- `React.cloneElement` has an odd quirk. When you do:
```js
return React.cloneElement(this.props.children, {style: this.props.children.props.style});
```
, `style` ends up undefined.
- Fixed a bug that caused debug output to show up in the build.
- `babel-loader` cache does not invalidate when it should. I had modified webpack.config.js in the last version but it reused stale cache.
### 4.3.0 (Apr 10, 2020)
- Fix setState warning after dismount if drag still active. Harmless, but prints a warning. [#424](https://github.com/mzabriskie/react-draggable/pull/424)
- Fix a long-standing issue where text inputs would unfocus upon dismounting a `<Draggable>`.
- Thanks @schnerd, [#450](https://github.com/mzabriskie/react-draggable/pull/450)
- Fix an issue where the insides of a `<Draggable>` were not scrollable on touch devices due to the outer container having `touch-action: none`.
- This was a long-standing hack for mobile devices. Without it, the page will scroll while you drag the element.
- The new solution will simply cancel the touch event `e.preventDefault()`. However, due to changes in Chrome >= 56, this is only possible on
non-passive event handlers. To fix this, we now add/remove the touchEvent on lifecycle events rather than using React's event system.
- [#465](https://github.com/mzabriskie/react-draggable/pull/465)
- Upgrade devDeps and fix security warnings. None of them actually applied to this module.
### 4.2.0 (Dec 2, 2019)
- Fix: Apply `scale` parameter also while dragging an element. [#438](https://github.com/mzabriskie/react-draggable/pull/438)
- Fix: Don't ship `process.env.DRAGGABLE_DEBUG` checks in cjs/esm. [#445](https://github.com/mzabriskie/react-draggable/pull/445)
### 4.1.0 (Oct 25, 2019)
- Add `"module"` to `package.json`. There are now three builds:
* **`"main"`**: ES5-compatible CJS build, suitable for most use cases with maximum compatibility.
- For legacy reasons, this has exports of the following shape, which ensures no surprises in CJS or ESM polyfilled environments:
```js
module.exports = Draggable;
module.exports.default = Draggable;
module.exports.DraggableCore = DraggableCore;
```
* **`"web"`**: Minified UMD bundle exporting to `window.ReactDraggable` with the same ES compatibility as the "main" build.
* **`"module"`**: ES6-compatible build using import/export.
This should fix issues like https://github.com/STRML/react-resizable/issues/113 while allowing modern bundlers to consume esm modules in the future.
No compatibility changes are expected.
### 4.0.3 (Sep 10, 2019)
- Add typings and sourcemap to published npm package.
- This compresses well so it does not bloat the package by much. Would be nice if npm had another delivery mechanism for optional modes, like web/TS.
### 4.0.2 (Sep 9, 2019)
- Republish to fix packaging errors. Fixes #426
### 4.0.1 (Sep 7, 2019)
- Republish of 4.0.0 to fix a mistake where webpack working files were erroneously included in the package. Use this release instead as it is much smaller.
### 4.0.0 (Aug 26, 2019)
> This is a major release due to a React compatibility change. If you are already on React >= 16.3, this upgrade is non-breaking.
- *Requires React 16.3+ due to use of `getDerivedStateFromProps`.
- See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html for why this was done.
- Upgraded build environment to Babel 7.
- Switched build from rollup to webpack@4 to simplify.
- Added CJS build that does not bundle `classNames` & `prop-types` into the build. This should result in marginally smaller bundle sizes for applications that use bundlers.
- Removed Bower build.
### 3.3.2 (Aug 16, 2019)
- Use `all: inherit` instead of `background: transparent;` to fix selection styles.
- Fixes https://github.com/mzabriskie/react-draggable/issues/315
### 3.3.1 (Aug 12, 2019)
- Fix React 16.9 `componentWillMount` deprecation.
### 3.3.0 (Apr 18, 2019)
- Addition of `positionOffset` prop, which can be Numbers (px) or string percentages (like `"10%"`). See the README for more.
### 3.2.1 (Mar 1, 2019)
- Reverted https://github.com/mzabriskie/react-draggable/pull/361.
### ~3.2.0 (Feb 27, 2019)~
> Note: this release has been pulled due to an inadvertent breaking change. See https://github.com/mzabriskie/react-draggable/issues/391
- Feature: `defaultPosition` now allows string offsets (like {x: '10%', y: '10%'}) then calculates deltas from there. See the examples and the PR [#361](https://github.com/mzabriskie/react-draggable/pull/361/). Thanks to @tnrich and @eric-burel.
- Bugfix: Export `DraggableEvent` type for Flow consumers. Thanks @elie222.
### 3.1.1 (Dec 21, 2018)
- Bugfix: Minor type change on DraggableEventHandler TypeScript export ([#374](https://github.com/mzabriskie/react-draggable/pull/374))
### 3.1.0 (Dec 21, 2018)
- Feature: Added `scale` prop ([#352](https://github.com/mzabriskie/react-draggable/pull/352))
- Thanks, @wootencl
- Bugfix: Remove process.browser which is missing in browser ([#329]((https://github.com/mzabriskie/react-draggable/pull/329))
- Bugfix: Fix selection api on IE ([#292](https://github.com/mzabriskie/react-draggable/pull/292))
- Bugfix: Fixes some issues in the type definitions for TypeScript ([#331]((https://github.com/mzabriskie/react-draggable/pull/331))
- Bugfix: Fix compare where portal elements are different instance to main window ([#359]((https://github.com/mzabriskie/react-draggable/pull/359))
### 3.0.5 (Jan 11, 2018)
- Bugfix: Fix crash in test environments during removeUserSelectStyles().
### 3.0.4 (Nov 27, 2017)
- Bugfix: Fix "Cannot call property 'call' of undefined" (matchesSelector)
- Fixes [#300](https://github.com/mzabriskie/react-draggable/issues/300)
### 3.0.3 (Aug 31, 2017)
- Bugfix: Fix deprecation warnings caused by `import * as React` (Flow best practice).
- See https://github.com/facebook/react/issues/10583
### 3.0.2 (Aug 22, 2017)
> 3.0.0 and 3.0.1 have been unpublished due to a large logfile making it into the package.
- Bugfix: Tweaked `.npmignore`.
### 3.0.1 (Aug 21, 2017)
- Bugfix: Flow-type should no longer throw errors for consumers.
- It appears Flow can't resolve a sub-package's interfaces.
### 3.0.0 (Aug 21, 2017)
> Due to an export change, this is semver-major.
- Breaking: For TypeScript users, `<Draggable>` is now exported as `module.exports` and `module.exports.default`.
- Potentially Breaking: We no longer set `user-select: none` on all elements while dragging. Instead,
the [`::selection` psuedo element](https://developer.mozilla.org/en-US/docs/Web/CSS/::selection) is used.
- Depending on your application, this could cause issues, so be sure to test.
- Bugfix: Pass bounded `x`/`y` to callbacks. See [#226](https://github.com/mzabriskie/react-draggable/pull/226).
- Internal: Upgraded dependencies.
### 2.2.6 (Apr 30, 2017)
- Bugfix: Missing export default on TS definition (thanks @lostfictions)
- Internal: TS test suite (thanks @lostfictions)
### 2.2.5 (Apr 28, 2017)
- Bugfix: Typescript definition was incorrect. [#244](https://github.com/mzabriskie/react-draggable/issues/244)
### 2.2.4 (Apr 27, 2017)
- Internal: Moved `PropTypes` access to `prop-types` package for React 15.5 (prep for 16)
- Feature: Added TypeScript definitions (thanks @erfangc)
- Bugfix: No longer can erroneously add user-select style multiple times
- Bugfix: OffsetParent with padding problem, fixes [#218](https://github.com/mzabriskie/react-draggable/issues/218)
- Refactor: Misc example updates.
### 2.2.3 (Nov 21, 2016)
- Bugfix: Fix an issue with the entire window scrolling on a drag on iDevices. Thanks @JaneCoder. See #183
### 2.2.2 (Sep 14, 2016)
- Bugfix: Fix references to global when grabbing `SVGElement`, see [#162](https://github.com/mzabriskie/react-draggable/issues/162)
- Bugfix: Get `ownerDocument` before `onStop`, fixes [#198](https://github.com/mzabriskie/react-draggable/issues/198)
### 2.2.1 (Aug 11, 2016)
- Bugfix: Fix `getComputedStyle` error: see [#186](https://github.com/mzabriskie/react-draggable/issues/186), #190
### 2.2.0 (Jul 29, 2016)
- Addition: `offsetParent` property for an arbitrary ancestor for offset calculations.
- Fixes e.g. dragging with a floating `offsetParent`.
- Ref: https://github.com/mzabriskie/react-draggable/issues/170
- Enhancement: Make this library iframe-aware.
- Ref: https://github.com/mzabriskie/react-draggable/pull/177
- Thanks to @acusti for tests
- Bugfix: Lint/Test Fixes for new Flow & React versions
### 2.1.2 (Jun 5, 2016)
- Bugfix: Fix `return false` to cancel `onDrag` breaking on both old and new browsers due to missing `typeArg` and/or
unsupported `MouseEventConstructor`. Fixes [#164](https://github.com/mzabriskie/react-draggable/issues/164).
### 2.1.1 (May 22, 2016)
- Bugfix: `<DraggableCore>` wasn't calling back with the DOM node.
- Internal: Rework test suite to use power-assert.
### 2.1.0 (May 20, 2016)
- Fix improperly missed `handle` or `cancel` selectors if the event originates from a child of the handle or cancel.
- Fixes a longstanding issue, [#88](https://github.com/mzabriskie/react-draggable/pull/88)
- This was pushed to a minor release as there may be edge cases (perhaps workarounds) where this changes behavior.
### 2.0.2 (May 19, 2016)
- Fix `cannot access clientX of undefined` on some touch-enabled platforms.
- Fixes [#159](https://github.com/mzabriskie/react-draggable/pull/159),
[#118](https://github.com/mzabriskie/react-draggable/pull/118)
- Fixed a bug with multi-finger multitouch if > 1 finger triggered an event at the same time.
### 2.0.1 (May 19, 2016)
- Finally fixed the IE10 constructor bug. Thanks @davidstubbs [#158](https://github.com/mzabriskie/react-draggable/pull/158)
### 2.0.0 (May 10, 2016)
- This is a breaking change. See the changes below in the beta releases.
- Note the changes to event callbacks and `position` / `defaultPosition`.
- Changes from 2.0.0-beta3:
- Small bugfixes for Flow 0.24 compatibility.
- Don't assume `global.SVGElement`. Fixes JSDOM & [#123](https://github.com/mzabriskie/react-draggable/issues/123).
### 2.0.0-beta3 (Apr 19, 2016)
- Flow comments are now in the build. Other projects, such as React-Grid-Layout and React-Resizable, will
rely on them in their build and export their own comments.
### 2.0.0-beta2 (Apr 14, 2016)
- We're making a small deviation from React Core's controlled vs. uncontrolled scheme; for convenience,
`<Draggable>`s with a `position` property will still be draggable, but will revert to their old position
on drag stop. Attach an `onStop` or `onDrag` handler to synchronize state.
- A warning has been added informing users of this. If you make `<Draggable>` controlled but attach no callback
handlers, a warning will be printed.
### 2.0.0-beta1 (Apr 14, 2016)
- Due to API changes, this is a major release.
#### Breaking Changes:
- Both `<DraggableCore>` and `<Draggable>` have had their callback types changed and unified.
```js
type DraggableEventHandler = (e: Event, data: DraggableData) => void | false;
type DraggableData = {
node: HTMLElement,
// lastX + deltaX === x
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number
};
```
- The `start` option has been renamed to `defaultPosition`.
- The `zIndex` option has been removed.
#### Possibly Breaking Changes:
- When determining deltas, we now use a new method that checks the delta against the Draggable's `offsetParent`.
This method allows us to support arbitrary nested scrollable ancestors without scroll handlers!
- This may cause issues in certain layouts. If you find one, please open an issue.
#### Enhancements:
- `<Draggable>` now has a `position` attribute. Its relationship to `defaultPosition` is much like
`value` to `defaultValue` on React `<input>` nodes. If set, the position is fixed and cannot be mutated.
If empty, the component will manage its own state. See [#140](https://github.com/mzabriskie/react-draggable/pull/140)
for more info & motivations.
- Misc. bugfixes.
### 1.4.0-beta1 (Apr 13, 2016)
- Major improvements to drag tracking that now support even nested scroll boxes.
- This revision is being done as a pre-release to ensure there are no unforeseen issues with the offset changes.
### 1.3.7 (Apr 8, 2016)
- Fix `user-select` prefixing, which may be different than the prefix required for `transform`.
### 1.3.6 (Apr 8, 2016)
- Republished after 1.3.5 contained a bundling error.
### 1.3.5 (Apr 8, 2016)
- Add React v15 to devDeps. `<Draggable>` supports both `v0.14` and `v15`.
- Enhancement: Clean up usage of browser prefixes; modern browsers will no longer use them.
- This also removes the duplicated `user-select` style that is created on the `<body>` while dragging.
- Internal: Test fixes.
### 1.3.4 (Mar 5, 2016)
- Bugfix: Scrolling while dragging caused items to move unpredictably.
### 1.3.3 (Feb 11, 2016)
- Bugfix: #116: Android/Chrome are finicky; give up on canceling ghost clicks entirely.
### 1.3.2 (Feb 11, 2016)
- Bugfix: #116: Child inputs not focusing on touch events.
### 1.3.1 (Feb 10, 2016)
- Internal: Babel 6 and Flow definitions
- Bugfix: 1.3.0 broke string bounds ('parent', selectors, etc.).
- Bugfix: 1.3.0 wasn't updating deltaX and deltaY on a bounds hit.
### 1.3.0 (Feb 10, 2016)
- Possibly breaking change: bounds are calculated before `<Draggable>` fires `drag` events, as they should have been.
- Added `'none'` axis type. This allows using `<Draggable>` somewhat like `<DraggableCore>` - state will be kept
internally (which makes bounds checks etc possible), but updates will not be flushed to the DOM.
- Performance tweaks.
### 1.2.0 (Feb 5, 2016)
- Added arbitrary boundary selector. Now you don't have to just use `'parent'`, you can select any element
on the page, including `'body'`.
- Bugfix: Prevent invariant if a `<Draggable>` is unmounted while dragging.
- Bugfix: Fix #133, where items would eagerly start dragging off the mouse cursor if you hit boundaries and
came back. This is due to how `<DraggableCore>` handles deltas only and does not keep state. Added new state
properties `slackX` and `slackY` to `<Draggable>` to handle this and restore pre-v1 behavior.
### 1.1.3 (Nov 25, 2015)
- Bugfix: Server-side rendering with react-rails, which does bad things like mock `window`
### 1.1.2 (Nov 23, 2015)
- Bugfix: `<Draggable>` was calling back with clientX/Y, not offsetX/Y as it did pre-1.0. This unintended
behavior has been fixed and a test has been added.
### 1.1.1 (Nov 14, 2015)
- Bugfix: Clean up scroll events if a component is unmounted before drag stops.
- Bugfix: `NaN` was returning from scroll events due to event structure change.
- Add scroll drag modulation test.
### 1.1.0 (Nov 14, 2015)
- Move `grid` into `<DraggableCore>` directly. It will continue to work on `<Draggable>`.
- Development fixes.
### 1.0.2 (Nov 7, 2015)
- Fix `enableUserSelectHack` not properly disabling.
- Fix a crash when the user scrolls the page with a Draggable active.
### 1.0.1 (Oct 28, 2015)
- Fix missing dist files for webpack.
- Ignore non-primary clicks. Added `allowAnyClick` option to allow other click types.
### 1.0.0 (Oct 27, 2015)
- Breaking: Removed `resetState()` instance method
- Breaking: Removed `moveOnStartChange` prop
- Breaking: React `0.14` support only.
- Refactored project.
- Module now exports a `<DraggableCore>` element upon which `<Draggable>` is based.
This module is useful for building libraries and is completely stateless.
### 0.8.5 (Oct 20, 2015)
- Bugfix: isElementSVG no longer can be overwritten by getInitialState (#83)
- Bugfix: Fix for element prefixes in JSDOM
### 0.8.4 (Oct 15, 2015)
- Bugfix: SVG elements now properly use `transform` attribute instead of `style`. Thanks @martinRoss
### 0.8.3 (Oct 12, 2015)
- Bugfix: Short-circuiting drag throws due to `e.changedTouches` check.
### 0.8.2 (Sep 21, 2015)
- Handle scrolling while dragging. (#60)
- Add multi-touch support. (#68)
- IE fixes.
- Documentation updates. (#77)
### 0.8.1 (June 3, 2015)
- Add `resetState()` instance method for use by parents. See README ("State Problems?").
### 0.8.0 (May 19, 2015)
- Touch/mouse events rework. Fixes #51, #37, and #43, as well as IE11 support.
- Moved mousemove/mouseup and touch event handlers to document from window. Fixes IE9/10 support.
IE8 is still not supported, as it is not supported by React.
### 0.7.4 (May 18, 2015)
- Fix a bug where a quick drag out of bounds to `0,0` would cause the element to remain in an inaccurate position,
because the translation was removed from the CSS. See #55.
### 0.7.3 (May 13, 2015)
- Removed a `moveOnStartChange` optimization that was causing problems when attempting to move a `<Draggable>` back
to its initial position. See https://github.com/STRML/react-grid-layout/issues/56
### 0.7.2 (May 8, 2015)
- Added `moveOnStartChange` property. See README.
### 0.7.1 (May 7, 2015)
- The `start` param is back. Pass `{x: Number, y: Number}` to kickoff the CSS transform. Useful in certain
cases for simpler callback math (so you don't have to know its existing relative position and add it to
the dragged position). Fixes #52.
### 0.7.0 (May 7, 2015)
- Breaking change: `bounds` with coordinates was confusing because it was using the item's width/height,
which was not intuitive. When providing coordinates, `bounds` now simply restricts movement in each
direction by that many pixels.
### 0.6.0 (May 2, 2015)
- Breaking change: Cancel dragging when onDrag or onStart handlers return an explicit `false`.
- Fix sluggish movement when `grid` option was active.
- Example updates.
- Move `user-select:none` hack to document.body for better highlight prevention.
- Add `bounds` option to restrict dragging within parent or within coordinates.
### 0.5.0 (May 2, 2015)
- Remove browserify browser config, reactify, and jsx pragma. Fixes #38
- Use React.cloneElement instead of addons cloneWithProps (requires React 0.13)
- Move to CSS transforms. Simplifies implementation and fixes #48, #34, #31.
- Fixup linting and space/tab errors. Fixes #46.
### 0.4.3 (Apr 30, 2015)
- Fix React.addons error caused by faulty test.
### 0.4.2 (Apr 30, 2015)
- Add `"browser"` config to package.json for browserify imports (fix #45).
- Remove unnecessary `emptyFunction` and `React.addons.classSet` imports.
### 0.4.1 (Apr 30, 2015)
- Remove react/addons dependency (now depending on `react` directly).
- Add MIT License file.
- Fix an issue where browser may be detected as touch-enabled but touch event isn't thrown.
### 0.4.0 (Jan 03, 2015)
- Improving accuracy of snap to grid
- Updating to React 0.12
- Adding dragging className
- Adding reactify support for browserify
- Fixing issue with server side rendering
### 0.3.0 (Oct 21, 2014)
- Adding support for touch devices
### 0.2.1 (Sep 10, 2014)
- Exporting as ReactDraggable
### 0.2.0 (Sep 10, 2014)
- Adding support for snapping to a grid
- Adding support for specifying start position
- Ensure event handlers are destroyed on unmount
- Adding browserify support
- Adding bower support
### 0.1.1 (Jul 26, 2014)
- Fixing dragging not stopping on mouseup in some cases
### 0.1.0 (Jul 25, 2014)
- Initial release
================================================
FILE: CLAUDE.md
================================================
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build Commands
**This project uses Yarn, not npm.** Always use `yarn` for package management.
This project uses Make for builds. Key commands:
- `make build` - Full build (cleans, then builds CJS and web bundles)
- `make lint` - Runs Flow type checker, ESLint, and TypeScript type checking on typings
- `make test` - Runs unit tests via Vitest
- `make test-browser` - Runs browser tests via Puppeteer (requires build first)
- `make test-all` - Runs both unit and browser tests
- `make dev` - Starts webpack dev server with example page at localhost:8080
Yarn scripts:
- `yarn test` - Run unit tests (jsdom environment)
- `yarn test:watch` - Run unit tests in watch mode
- `yarn test -- path/to/test.jsx` - Run a single test file
- `yarn test -- -t "test name"` - Run tests matching a pattern
- `yarn test:browser` - Build and run browser tests (Puppeteer)
- `yarn test:all` - Run all tests
- `yarn test:coverage` - Run tests with coverage report
Pre-commit hooks run `make lint` and `make test` automatically.
## Test Architecture
Tests are split into two categories:
1. **Unit tests** (`test/*.test.{js,jsx}`) - Run in jsdom via Vitest
- Fast, no browser required
- Test component logic, callbacks, prop handling
- Some coordinate-based tests skipped (require real browser)
2. **Browser tests** (`test/browser/*.test.js`) - Run in headless Chrome via Puppeteer
- Test actual drag behavior with real coordinate calculations
- Test transforms, axis constraints, bounds, scale
### Test Utilities
`test/testUtils.js` provides helpers for simulating drag events:
- `simulateDrag(element, {from, to})` - Complete drag operation
- `startDrag(element, {x, y})` / `moveDrag({x, y})` / `endDrag(element, {x, y})` - Step-by-step drag
- `simulateTouchDrag(element, {from, to})` - Touch event drag
## Architecture
### Component Hierarchy
**DraggableCore** (`lib/DraggableCore.js`) - Low-level component that handles raw drag events
- Maintains minimal internal state (just `dragging`, `lastX`, `lastY`)
- Manages mouse/touch event binding and cleanup
- Provides `onStart`, `onDrag`, `onStop` callbacks with position data
- Use this when you need full control over positioning
**Draggable** (`lib/Draggable.js`) - High-level wrapper around DraggableCore
- Manages position state, bounds checking, axis constraints
- Applies CSS transforms or SVG transform attributes
- Supports controlled (`position` prop) and uncontrolled (`defaultPosition`) modes
- Adds dragging-related CSS classes
### Key Utilities
- `lib/utils/domFns.js` - DOM helpers: event binding, CSS transforms, user-select hacks
- `lib/utils/positionFns.js` - Position calculations: bounds checking, grid snapping, delta computations
- `lib/utils/getPrefix.js` - Browser prefix detection for CSS transforms
### Build Outputs
- `build/cjs/` - CommonJS build (Babel)
- `build/web/react-draggable.min.js` - UMD browser bundle (Webpack)
### Type Systems
The codebase uses Flow for internal type checking (`// @flow` annotations) and ships TypeScript definitions in `typings/index.d.ts`. Both must stay in sync when modifying component props or types.
## Key Patterns
### nodeRef Pattern
To avoid ReactDOM.findDOMNode deprecation warnings in Strict Mode, components accept a `nodeRef` prop:
```jsx
const nodeRef = React.useRef(null);
<Draggable nodeRef={nodeRef}>
<div ref={nodeRef}>Content</div>
</Draggable>
```
### Callback Return Values
Returning `false` from `onStart`, `onDrag`, or `onStop` cancels the drag operation.
### CSS Transform Approach
Dragging uses CSS transforms (`translate`) rather than absolute positioning, allowing draggable elements to work regardless of their CSS position value.
## Release Process
- Update CHANGELOG.md
- `make release-patch`, `make release-minor`, or `make release-major`
- `make publish`
================================================
FILE: LICENSE
================================================
(MIT License)
Copyright (c) 2014-2016 Matt Zabriskie. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: Makefile
================================================
# Mostly lifted from https://andreypopp.com/posts/2013-05-16-makefile-recipes-for-node-js.html
# Thanks @andreypopp
# Make it parallel
MAKEFLAGS += j4
export BIN := $(shell yarn bin)
.PHONY: test dev lint build build-cjs build-esm build-web clean install link publish
.DEFAULT_GOAL := build
clean:
rm -rf build
mkdir -p build
lint:
@$(BIN)/flow
@$(BIN)/eslint lib/* lib/utils/*
@$(BIN)/tsc -p typings
build: clean build-cjs build-esm build-web
build-cjs: $(BIN)
$(BIN)/babel --out-dir ./build/cjs ./lib
build-web: $(BIN)
$(BIN)/webpack --mode=production
# Allows usage of `make install`, `make link`
install link:
@yarn $@
test: $(BIN)
@$(BIN)/vitest run
test-browser: build $(BIN)
@$(BIN)/vitest run --config vitest.browser.config.js
test-all: test test-browser
dev: $(BIN) clean
env DRAGGABLE_DEBUG=1 $(BIN)/webpack serve --mode=development
node_modules/.bin: install
define release
VERSION=`node -pe "require('./package.json').version"` && \
NEXT_VERSION=`node -pe "require('semver').inc(\"$$VERSION\", '$(1)')"` && \
node -e "\
['./package.json'].forEach(function(fileName) {\
var j = require(fileName);\
j.version = \"$$NEXT_VERSION\";\
var s = JSON.stringify(j, null, 2);\
require('fs').writeFileSync(fileName, s);\
});" && \
git add package.json CHANGELOG.md && \
git commit -m "release v$$NEXT_VERSION" && \
git tag "v$$NEXT_VERSION" -m "release v$$NEXT_VERSION"
endef
release-patch: test
@$(call release,patch)
release-minor: test
@$(call release,minor)
release-major: test
@$(call release,major)
publish: build
git push --tags origin HEAD:master
yarn publish
================================================
FILE: README.md
================================================
# React-Draggable
[](https://github.com/react-grid-layout/react-draggable/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/react-draggable)
[](https://www.npmjs.com/package/react-draggable)
[](https://npmcdn.com/react-draggable/build/web/react-draggable.min.js)
A simple component for making elements draggable.
[**[Demo](https://react-grid-layout.github.io/react-draggable/) | [Changelog](CHANGELOG.md)**]
<p align="center">
<img src="https://user-images.githubusercontent.com/6365230/95649276-f3a02480-0b06-11eb-8504-e0614a780ba4.gif" />
</p>
```jsx
<Draggable>
<div>I can now be moved around!</div>
</Draggable>
```
## Table of Contents
- [Installation](#installation)
- [Compatibility](#compatibility)
- [Quick Start](#quick-start)
- [API](#api)
- [Draggable](#draggable)
- [DraggableCore](#draggablecore)
- [Using nodeRef](#using-noderef)
- [Controlled vs. Uncontrolled](#controlled-vs-uncontrolled)
- [Contributing](#contributing)
## Installation
```bash
npm install react-draggable
# or
yarn add react-draggable
```
```js
// ES Modules
import Draggable from 'react-draggable';
import { DraggableCore } from 'react-draggable';
// CommonJS
const Draggable = require('react-draggable');
const { DraggableCore } = require('react-draggable');
```
TypeScript types are included.
## Compatibility
| Version | React Version |
|---------|---------------|
| 4.x | 16.3+ |
| 3.x | 15 - 16 |
| 2.x | 0.14 - 15 |
## Quick Start
```jsx
import React, { useRef } from 'react';
import Draggable from 'react-draggable';
function App() {
const nodeRef = useRef(null);
return (
<Draggable nodeRef={nodeRef}>
<div ref={nodeRef}>Drag me!</div>
</Draggable>
);
}
```
View the [Demo](https://react-grid-layout.github.io/react-draggable/) and its [source](/example/example.js) for more examples.
## API
### `<Draggable>`
A `<Draggable>` element wraps an existing element and extends it with new event handlers and styles. It does not create a wrapper element in the DOM.
Draggable items are moved using CSS Transforms. This allows items to be dragged regardless of their current positioning (relative, absolute, or static). Elements can also be moved between drags without incident.
If the item you are dragging already has a CSS Transform applied, it will be overwritten by `<Draggable>`. Use an intermediate wrapper (`<Draggable><span>...</span></Draggable>`) in this case.
#### Props
```ts
type DraggableEventHandler = (e: Event, data: DraggableData) => void | false;
type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
};
```
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `allowAnyClick` | `boolean` | `false` | Allow dragging on non-left-button clicks |
| `allowMobileScroll` | `boolean` | `false` | Don't prevent `touchstart`, allowing scrolling inside containers |
| `axis` | `'both' \| 'x' \| 'y' \| 'none'` | `'both'` | Axis to allow dragging on |
| `bounds` | `object \| string` | - | Restrict movement. Use `'parent'`, a CSS selector, or `{left, top, right, bottom}` |
| `cancel` | `string` | - | CSS selector for elements that should not initiate drag |
| `defaultClassName` | `string` | `'react-draggable'` | Class name applied to the element |
| `defaultClassNameDragging` | `string` | `'react-draggable-dragging'` | Class name applied while dragging |
| `defaultClassNameDragged` | `string` | `'react-draggable-dragged'` | Class name applied after drag |
| `defaultPosition` | `{x: number, y: number}` | `{x: 0, y: 0}` | Starting position |
| `disabled` | `boolean` | `false` | Disable dragging |
| `enableUserSelectHack` | `boolean` | `true` | Add `user-select: none` while dragging |
| `grid` | `[number, number]` | - | Snap to grid `[x, y]` |
| `handle` | `string` | - | CSS selector for the drag handle |
| `nodeRef` | `React.RefObject` | - | Ref to the DOM element. Required for React Strict Mode |
| `offsetParent` | `HTMLElement` | - | Custom offsetParent for drag calculations |
| `onDrag` | `DraggableEventHandler` | - | Called while dragging |
| `onMouseDown` | `(e: MouseEvent) => void` | - | Called on mouse down |
| `onStart` | `DraggableEventHandler` | - | Called when dragging starts. Return `false` to cancel |
| `onStop` | `DraggableEventHandler` | - | Called when dragging stops |
| `position` | `{x: number, y: number}` | - | Controlled position |
| `positionOffset` | `{x: number \| string, y: number \| string}` | - | Position offset (supports percentages) |
| `scale` | `number` | `1` | Scale factor for dragging inside transformed parents |
**Note:** Setting `className`, `style`, or `transform` on `<Draggable>` will error. Set them on the child element.
### `<DraggableCore>`
For users that require full control, `<DraggableCore>` provides drag callbacks without managing state or styles. It does not set any transforms; you must handle positioning yourself.
See [React-Resizable](https://github.com/react-grid-layout/react-resizable) and [React-Grid-Layout](https://github.com/react-grid-layout/react-grid-layout) for usage examples.
#### Props
`<DraggableCore>` accepts a subset of `<Draggable>` props:
- `allowAnyClick`
- `allowMobileScroll`
- `cancel`
- `disabled`
- `enableUserSelectHack`
- `grid`
- `handle`
- `nodeRef`
- `offsetParent`
- `onDrag`
- `onMouseDown`
- `onStart`
- `onStop`
- `scale`
## Using nodeRef
To avoid `ReactDOM.findDOMNode()` deprecation warnings in React Strict Mode, pass a `nodeRef` prop:
```jsx
function App() {
const nodeRef = useRef(null);
return (
<Draggable nodeRef={nodeRef}>
<div ref={nodeRef}>Drag me!</div>
</Draggable>
);
}
```
For custom components, forward both the ref and props:
```jsx
const MyComponent = forwardRef((props, ref) => (
<div {...props} ref={ref}>Draggable content</div>
));
function App() {
const nodeRef = useRef(null);
return (
<Draggable nodeRef={nodeRef}>
<MyComponent ref={nodeRef} />
</Draggable>
);
}
```
## Controlled vs. Uncontrolled
`<Draggable>` is a 'batteries-included' component that manages its own state. For complete control, use `<DraggableCore>`.
For programmatic repositioning while using `<Draggable>`'s state management, pass the `position` prop:
```jsx
function ControlledDraggable() {
const nodeRef = useRef(null);
const [position, setPosition] = useState({ x: 0, y: 0 });
const handleDrag = (e, data) => {
setPosition({ x: data.x, y: data.y });
};
const resetPosition = () => setPosition({ x: 0, y: 0 });
return (
<>
<button onClick={resetPosition}>Reset</button>
<Draggable nodeRef={nodeRef} position={position} onDrag={handleDrag}>
<div ref={nodeRef}>Drag me or reset!</div>
</Draggable>
</>
);
}
```
## Contributing
- Fork the project
- Run `yarn dev` to start the development server
- Make changes and add tests
- Run `yarn test` to ensure tests pass
- Submit a PR
### Release Checklist
1. Update CHANGELOG.md
2. Run `make release-patch`, `make release-minor`, or `make release-major`
3. Run `make publish`
## License
MIT
================================================
FILE: appveyor.yml
================================================
# https://www.appveyor.com/docs/appveyor-yml/
environment:
matrix:
- node_version: "12"
- node_version: "10"
- node_version: "8"
IE_BIN: "%PROGRAMFILES%\\Internet Explorer\\iexplore.exe"
cache:
- node_modules
- "%LOCALAPPDATA%/Yarn"
build_script:
- cmd: yarn install
test_script:
- cmd: yarn run test-ie
================================================
FILE: eslint.config.mjs
================================================
import { defineConfig, globalIgnores } from "eslint/config";
import react from "eslint-plugin-react";
import globals from "globals";
import babelParser from "@babel/eslint-parser";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
export default defineConfig([globalIgnores(["build/**/*.js"]), {
extends: compat.extends("eslint:recommended"),
plugins: {
react,
},
languageOptions: {
globals: {
...globals.browser,
...globals.node,
ReactElement: null,
ReactClass: null,
$Exact: null,
Partial: null,
$Keys: null,
MouseTouchEvent: null,
},
parser: babelParser,
},
rules: {
strict: 0,
quotes: [1, "single"],
curly: [1, "multi-line"],
camelcase: 0,
"comma-dangle": 0,
"no-console": 2,
"no-use-before-define": [1, "nofunc"],
"no-underscore-dangle": 0,
"no-unused-vars": [1, {
ignoreRestSiblings: true,
}],
"new-cap": 0,
"prefer-const": 1,
semi: 1,
},
}]);
================================================
FILE: example/example-styles.css
================================================
/* === CYBERPUNK THEME === */
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Orbitron:wght@400;700;900&display=swap');
:root {
--cyber-bg: #0a0a0f;
--cyber-surface: #12121a;
--cyber-cyan: #00f0ff;
--cyber-magenta: #ff00aa;
--cyber-purple: #a855f7;
--cyber-yellow: #facc15;
--cyber-grid: rgba(0, 240, 255, 0.03);
--glow-cyan: 0 0 20px rgba(0, 240, 255, 0.5), 0 0 40px rgba(0, 240, 255, 0.2);
--glow-magenta: 0 0 20px rgba(255, 0, 170, 0.5), 0 0 40px rgba(255, 0, 170, 0.2);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
background: var(--cyber-bg);
background-image:
linear-gradient(var(--cyber-grid) 1px, transparent 1px),
linear-gradient(90deg, var(--cyber-grid) 1px, transparent 1px);
background-size: 50px 50px;
min-height: 100vh;
font-family: 'JetBrains Mono', monospace;
color: #e0e0e0;
}
/* === MAIN CONTENT === */
.main-content {
padding: 20px 30px;
min-height: 100vh;
max-width: 1400px;
margin: 0 auto;
}
#container {
width: 100%;
}
/* === HEADER === */
.main-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid rgba(0, 240, 255, 0.3);
}
h1 {
font-family: 'Orbitron', sans-serif;
font-size: 24px;
font-weight: 700;
color: var(--cyber-cyan);
text-shadow: var(--glow-cyan);
letter-spacing: 1px;
margin: 0;
}
h3 {
font-family: 'Orbitron', sans-serif;
font-size: 18px;
font-weight: 700;
color: var(--cyber-cyan);
text-shadow: var(--glow-cyan);
letter-spacing: 1px;
margin: 0 0 15px 0;
}
.version-badge {
font-size: 13px;
font-family: 'JetBrains Mono', monospace;
color: var(--cyber-magenta);
background: rgba(255, 0, 170, 0.15);
padding: 6px 12px;
border: 1px solid rgba(255, 0, 170, 0.4);
text-decoration: none;
text-shadow: 0 0 10px rgba(255, 0, 170, 0.5);
transition: all 0.2s ease;
flex-shrink: 0;
}
.version-badge:hover {
color: var(--cyber-yellow);
border-color: var(--cyber-yellow);
background: rgba(250, 204, 21, 0.15);
text-shadow: 0 0 15px rgba(250, 204, 21, 0.7);
}
.header-links {
display: flex;
gap: 12px;
align-items: center;
}
.lib-link {
font-size: 13px;
font-family: 'JetBrains Mono', monospace;
color: var(--cyber-cyan);
background: rgba(0, 240, 255, 0.1);
padding: 6px 12px;
border: 1px solid rgba(0, 240, 255, 0.4);
text-decoration: none;
text-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
transition: all 0.2s ease;
}
.lib-link:hover {
color: var(--cyber-magenta);
border-color: var(--cyber-magenta);
background: rgba(255, 0, 170, 0.15);
text-shadow: 0 0 15px rgba(255, 0, 170, 0.7);
}
/* === NAVIGATION LINKS === */
.nav-links {
list-style: none;
padding: 0;
margin: 0 0 25px 0;
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.nav-links li {
background: linear-gradient(135deg, rgba(18, 18, 26, 0.9) 0%, rgba(10, 10, 15, 0.95) 100%);
border: 1px solid rgba(0, 240, 255, 0.3);
border-left: 3px solid var(--cyber-cyan);
padding: 8px 14px;
font-size: 13px;
transition: all 0.2s ease;
}
.nav-links li:hover {
border-color: var(--cyber-magenta);
border-left-color: var(--cyber-magenta);
box-shadow: var(--glow-magenta);
}
.nav-links li a {
color: #c0c0c0;
text-decoration: none;
transition: color 0.2s ease;
}
.nav-links li a:hover {
color: var(--cyber-magenta);
}
/* === PARAGRAPHS === */
p {
color: #a0a0a0;
line-height: 1.6;
margin-bottom: 15px;
padding-left: 12px;
border-left: 2px solid rgba(168, 85, 247, 0.4);
}
p code {
background: rgba(168, 85, 247, 0.2);
border: 1px solid var(--cyber-purple);
padding: 2px 8px;
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
color: var(--cyber-purple);
}
p a {
color: var(--cyber-cyan);
text-decoration: none;
transition: color 0.2s ease;
}
p a:hover {
color: var(--cyber-magenta);
}
/* === DRAGGABLE BOXES === */
.box {
background: linear-gradient(145deg, rgba(18, 18, 26, 0.9) 0%, rgba(30, 30, 45, 0.9) 100%);
border: 1px solid var(--cyber-cyan);
width: 180px;
height: 180px;
margin: 10px;
padding: 15px;
float: left;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
font-size: 13px;
color: #c0c0c0;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.05),
0 4px 20px rgba(0, 0, 0, 0.5);
transition: border-color 0.2s ease, box-shadow 0.2s ease;
overflow: hidden;
}
.box:hover {
border-color: var(--cyber-magenta);
box-shadow:
var(--glow-magenta),
inset 0 1px 0 rgba(255, 255, 255, 0.05);
}
/* === CURSORS === */
.react-draggable, .cursor {
cursor: move;
}
.no-cursor {
cursor: auto;
}
.cursor-y {
cursor: ns-resize;
}
.cursor-x {
cursor: ew-resize;
}
/* === HANDLE === */
.react-draggable strong {
background: linear-gradient(135deg, rgba(0, 240, 255, 0.2) 0%, rgba(0, 240, 255, 0.1) 100%);
border: 1px solid var(--cyber-cyan);
display: block;
margin-bottom: 10px;
padding: 6px 10px;
text-align: center;
font-weight: 500;
color: var(--cyber-cyan);
text-shadow: 0 0 8px rgba(0, 240, 255, 0.4);
transition: all 0.2s ease;
}
.react-draggable strong:hover {
background: linear-gradient(135deg, rgba(255, 0, 170, 0.2) 0%, rgba(255, 0, 170, 0.1) 100%);
border-color: var(--cyber-magenta);
color: var(--cyber-magenta);
text-shadow: 0 0 10px rgba(255, 0, 170, 0.5);
}
/* === SPECIAL STATES === */
.no-pointer-events {
pointer-events: none;
}
.hovered {
background: linear-gradient(145deg, rgba(255, 0, 170, 0.2) 0%, rgba(30, 30, 45, 0.9) 100%) !important;
border-color: var(--cyber-magenta) !important;
}
.drop-target {
border-style: dashed;
}
/* === REM POSITION FIX === */
.rem-position-fix {
position: static !important;
}
/* === BOUNDED CONTAINER === */
.bounded-container {
height: 500px;
width: 500px;
position: relative;
overflow: auto;
padding: 0;
background: var(--cyber-surface);
border: 1px solid rgba(0, 240, 255, 0.2);
background-image:
linear-gradient(rgba(0, 240, 255, 0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 240, 255, 0.05) 1px, transparent 1px);
background-size: 20px 20px;
float: left;
margin: 10px;
}
.bounded-inner {
height: 1000px;
width: 1000px;
padding: 10px;
}
/* === ACTIVE DRAGS COUNTER === */
.active-drags {
font-family: 'Orbitron', sans-serif;
color: var(--cyber-yellow);
background: rgba(250, 204, 21, 0.1);
border: 1px solid rgba(250, 204, 21, 0.3);
padding: 8px 15px;
display: inline-block;
margin-bottom: 20px;
font-size: 12px;
}
/* === SCROLLBAR === */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--cyber-bg);
}
::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, var(--cyber-cyan), var(--cyber-magenta));
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(180deg, var(--cyber-magenta), var(--cyber-cyan));
}
/* === PREVENT TEXT SELECTION DURING DRAG === */
body:has(.react-draggable-dragging) {
user-select: none;
-webkit-user-select: none;
}
/* === RESPONSIVE === */
@media (max-width: 768px) {
.main-content {
padding: 15px;
}
.main-header {
flex-direction: column;
gap: 10px;
align-items: flex-start;
}
h1 {
font-size: 18px;
}
.box {
width: 150px;
height: 150px;
}
}
================================================
FILE: example/example.js
================================================
const {ReactDraggable: Draggable, React, ReactDOM} = window;
class App extends React.Component {
state = {
activeDrags: 0,
deltaPosition: {
x: 0, y: 0
},
controlledPosition: {
x: -400, y: 200
}
};
handleDrag = (e, ui) => {
const {x, y} = this.state.deltaPosition;
this.setState({
deltaPosition: {
x: x + ui.deltaX,
y: y + ui.deltaY,
}
});
};
onStart = () => {
this.setState({activeDrags: ++this.state.activeDrags});
};
onStop = () => {
this.setState({activeDrags: --this.state.activeDrags});
};
onDrop = (e) => {
this.setState({activeDrags: --this.state.activeDrags});
if (e.target.classList.contains("drop-target")) {
alert("Dropped!");
e.target.classList.remove('hovered');
}
};
onDropAreaMouseEnter = (e) => {
if (this.state.activeDrags) {
e.target.classList.add('hovered');
}
}
onDropAreaMouseLeave = (e) => {
e.target.classList.remove('hovered');
}
// For controlled component
adjustXPos = (e) => {
e.preventDefault();
e.stopPropagation();
const {x, y} = this.state.controlledPosition;
this.setState({controlledPosition: {x: x - 10, y}});
};
adjustYPos = (e) => {
e.preventDefault();
e.stopPropagation();
const {controlledPosition} = this.state;
const {x, y} = controlledPosition;
this.setState({controlledPosition: {x, y: y - 10}});
};
onControlledDrag = (e, position) => {
const {x, y} = position;
this.setState({controlledPosition: {x, y}});
};
onControlledDragStop = (e, position) => {
this.onControlledDrag(e, position);
this.onStop();
};
render() {
const dragHandlers = {onStart: this.onStart, onStop: this.onStop};
const {deltaPosition, controlledPosition} = this.state;
return (
<div>
<div className="active-drags">Active DragHandlers: {this.state.activeDrags}</div>
<ul className="nav-links">
<li><a href="https://github.com/react-grid-layout/react-draggable/blob/master/example/example.js">Demo Source</a></li>
<li><a href="https://github.com/react-grid-layout/react-draggable">GitHub</a></li>
<li><a href="https://www.npmjs.com/package/react-draggable">npm</a></li>
</ul>
<Draggable {...dragHandlers}>
<div className="box">I can be dragged anywhere</div>
</Draggable>
<Draggable axis="x" {...dragHandlers}>
<div className="box cursor-x">I can only be dragged horizonally (x axis)</div>
</Draggable>
<Draggable axis="y" {...dragHandlers}>
<div className="box cursor-y">I can only be dragged vertically (y axis)</div>
</Draggable>
<Draggable onStart={() => false}>
<div className="box">I don't want to be dragged</div>
</Draggable>
<Draggable onDrag={this.handleDrag} {...dragHandlers}>
<div className="box">
<div>I track my deltas</div>
<div>x: {deltaPosition.x.toFixed(0)}, y: {deltaPosition.y.toFixed(0)}</div>
</div>
</Draggable>
<Draggable handle="strong" {...dragHandlers}>
<div className="box no-cursor">
<strong className="cursor"><div>Drag here</div></strong>
<div>You must click my handle to drag me</div>
</div>
</Draggable>
<Draggable handle="strong">
<div className="box no-cursor" style={{display: 'flex', flexDirection: 'column'}}>
<strong className="cursor"><div>Drag here</div></strong>
<div style={{overflow: 'scroll', flex: 1}}>
<div style={{background: 'rgba(250, 204, 21, 0.2)', border: '1px solid rgba(250, 204, 21, 0.4)', padding: '8px', whiteSpace: 'pre-wrap', color: 'var(--cyber-yellow)'}}>
I have long scrollable content with a handle
{'\n' + Array(40).fill('x').join('\n')}
</div>
</div>
</div>
</Draggable>
<Draggable cancel="strong" {...dragHandlers}>
<div className="box">
<strong className="no-cursor">Can't drag here</strong>
<div>Dragging here works</div>
</div>
</Draggable>
<Draggable grid={[25, 25]} {...dragHandlers}>
<div className="box">I snap to a 25 x 25 grid</div>
</Draggable>
<Draggable grid={[50, 50]} {...dragHandlers}>
<div className="box">I snap to a 50 x 50 grid</div>
</Draggable>
<Draggable bounds={{top: -100, left: -100, right: 100, bottom: 100}} {...dragHandlers}>
<div className="box">I can only be moved 100px in any direction.</div>
</Draggable>
<Draggable {...dragHandlers}>
<div className="box drop-target" onMouseEnter={this.onDropAreaMouseEnter} onMouseLeave={this.onDropAreaMouseLeave}>I can detect drops from the next box.</div>
</Draggable>
<Draggable {...dragHandlers} onStop={this.onDrop}>
<div className={`box ${this.state.activeDrags ? "no-pointer-events" : ""}`}>I can be dropped onto another box.</div>
</Draggable>
<div className="bounded-container">
<div className="bounded-inner">
<Draggable bounds="parent" {...dragHandlers}>
<div className="box">
I can only be moved within my offsetParent.<br /><br />
Both parent padding and child margin work properly.
</div>
</Draggable>
<Draggable bounds="parent" {...dragHandlers}>
<div className="box">
I also can only be moved within my offsetParent.<br /><br />
Both parent padding and child margin work properly.
</div>
</Draggable>
</div>
</div>
<Draggable bounds="body" {...dragHandlers}>
<div className="box">
I can only be moved within the confines of the body element.
</div>
</Draggable>
<Draggable {...dragHandlers}>
<div className="box" style={{position: 'absolute', bottom: '100px', right: '100px'}}>
I already have an absolute position.
</div>
</Draggable>
<Draggable {...dragHandlers}>
<RemWrapper>
<div className="box rem-position-fix" style={{position: 'absolute', bottom: '6.25rem', right: '18rem'}}>
I use <span style={{ fontWeight: 700 }}>rem</span> instead of <span style={{ fontWeight: 700 }}>px</span> for my transforms. I also have absolute positioning.
<br /><br />
I depend on a CSS hack to avoid double absolute positioning.
</div>
</RemWrapper>
</Draggable>
<Draggable defaultPosition={{x: 25, y: 25}} {...dragHandlers}>
<div className="box">
{"I have a default position of {x: 25, y: 25}, so I'm slightly offset."}
</div>
</Draggable>
<Draggable positionOffset={{x: '-10%', y: '-10%'}} {...dragHandlers}>
<div className="box">
{'I have a default position based on percents {x: \'-10%\', y: \'-10%\'}, so I\'m slightly offset.'}
</div>
</Draggable>
<Draggable position={controlledPosition} {...dragHandlers} onDrag={this.onControlledDrag}>
<div className="box">
My position can be changed programmatically. <br />
I have a drag handler to sync state.
<div>
<a href="#" onClick={this.adjustXPos}>Adjust x ({controlledPosition.x})</a>
</div>
<div>
<a href="#" onClick={this.adjustYPos}>Adjust y ({controlledPosition.y})</a>
</div>
</div>
</Draggable>
<Draggable position={controlledPosition} {...dragHandlers} onStop={this.onControlledDragStop}>
<div className="box">
My position can be changed programmatically. <br />
I have a dragStop handler to sync state.
<div>
<a href="#" onClick={this.adjustXPos}>Adjust x ({controlledPosition.x})</a>
</div>
<div>
<a href="#" onClick={this.adjustYPos}>Adjust y ({controlledPosition.y})</a>
</div>
</div>
</Draggable>
</div>
);
}
}
class RemWrapper extends React.Component {
// PropTypes is not available in this environment, but here they are.
// static propTypes = {
// style: PropTypes.shape({
// transform: PropTypes.string.isRequired
// }),
// children: PropTypes.node.isRequired,
// remBaseline: PropTypes.number,
// }
translateTransformToRem(transform, remBaseline = 16) {
const convertedValues = transform.replace('translate(', '').replace(')', '')
.split(',')
.map(px => px.replace('px', ''))
.map(px => parseInt(px, 10) / remBaseline)
.map(x => `${x}rem`)
const [x, y] = convertedValues
return `translate(${x}, ${y})`
}
render() {
const { children, remBaseline = 16, style } = this.props
const child = React.Children.only(children)
const editedStyle = {
...child.props.style,
...style,
transform: this.translateTransformToRem(style.transform, remBaseline),
}
return React.cloneElement(child, {
...child.props,
...this.props,
style: editedStyle
})
}
}
ReactDOM.render(<App/>, document.getElementById('container'));
================================================
FILE: example/index.html
================================================
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>React Draggable</title>
<link rel="stylesheet" href="example-styles.css"/>
</head>
<body>
<div class="main-content">
<header class="main-header">
<h1>React-Draggable</h1>
<div class="header-links">
<a class="lib-link" href="https://react-grid-layout.github.io/react-grid-layout/examples/00-showcase.html">React-Grid-Layout</a>
<a class="lib-link" href="https://react-grid-layout.github.io/react-resizable/">React-Resizable</a>
<a class="version-badge" href="https://github.com/react-grid-layout/react-draggable">v4.5.0</a>
</div>
</header>
<div id="container"></div>
</div>
<script src="//unpkg.com/react@18/umd/react.development.js"></script>
<script src="//unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="../build/web/react-draggable.min.js"></script>
<!-- for imported script -->
<script src="//unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel" src="example.js"></script>
</body>
</html>
================================================
FILE: lib/Draggable.js
================================================
// @flow
import * as React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import { clsx } from 'clsx';
import {createCSSTransform, createSVGTransform} from './utils/domFns';
import {canDragX, canDragY, createDraggableData, getBoundPosition} from './utils/positionFns';
import {dontSetMe} from './utils/shims';
import DraggableCore from './DraggableCore';
import type {ControlPosition, PositionOffsetControlPosition, DraggableCoreProps, DraggableCoreDefaultProps} from './DraggableCore';
import log from './utils/log';
import type {Bounds, DraggableEventHandler} from './utils/types';
import type {Element as ReactElement} from 'react';
type DraggableState = {
dragging: boolean,
dragged: boolean,
x: number, y: number,
slackX: number, slackY: number,
isElementSVG: boolean,
prevPropsPosition: ?ControlPosition,
};
export type DraggableDefaultProps = {
...DraggableCoreDefaultProps,
axis: 'both' | 'x' | 'y' | 'none',
bounds: Bounds | string | false,
defaultClassName: string,
defaultClassNameDragging: string,
defaultClassNameDragged: string,
defaultPosition: ControlPosition,
scale: number,
};
export type DraggableProps = {
...DraggableCoreProps,
...DraggableDefaultProps,
positionOffset: PositionOffsetControlPosition,
position: ControlPosition,
};
//
// Define <Draggable>
//
class Draggable extends React.Component<DraggableProps, DraggableState> {
static displayName: ?string = 'Draggable';
static propTypes: DraggableProps = {
// Accepts all props <DraggableCore> accepts.
...DraggableCore.propTypes,
/**
* `axis` determines which axis the draggable can move.
*
* Note that all callbacks will still return data as normal. This only
* controls flushing to the DOM.
*
* 'both' allows movement horizontally and vertically.
* 'x' limits movement to horizontal axis.
* 'y' limits movement to vertical axis.
* 'none' limits all movement.
*
* Defaults to 'both'.
*/
axis: PropTypes.oneOf(['both', 'x', 'y', 'none']),
/**
* `bounds` determines the range of movement available to the element.
* Available values are:
*
* 'parent' restricts movement within the Draggable's parent node.
*
* Alternatively, pass an object with the following properties, all of which are optional:
*
* {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}
*
* All values are in px.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable bounds={{right: 300, bottom: 300}}>
* <div>Content</div>
* </Draggable>
* );
* }
* });
* ```
*/
bounds: PropTypes.oneOfType([
PropTypes.shape({
left: PropTypes.number,
right: PropTypes.number,
top: PropTypes.number,
bottom: PropTypes.number
}),
PropTypes.string,
PropTypes.oneOf([false])
]),
defaultClassName: PropTypes.string,
defaultClassNameDragging: PropTypes.string,
defaultClassNameDragged: PropTypes.string,
/**
* `defaultPosition` specifies the x and y that the dragged item should start at
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable defaultPosition={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
defaultPosition: PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
}),
positionOffset: PropTypes.shape({
x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
y: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
}),
/**
* `position`, if present, defines the current position of the element.
*
* This is similar to how form elements in React work - if no `position` is supplied, the component
* is uncontrolled.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable position={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
position: PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
}),
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
};
static defaultProps: DraggableDefaultProps = {
...DraggableCore.defaultProps,
axis: 'both',
bounds: false,
defaultClassName: 'react-draggable',
defaultClassNameDragging: 'react-draggable-dragging',
defaultClassNameDragged: 'react-draggable-dragged',
defaultPosition: {x: 0, y: 0},
scale: 1
};
// React 16.3+
// Arity (props, state)
static getDerivedStateFromProps({position}: DraggableProps, {prevPropsPosition}: DraggableState): ?Partial<DraggableState> {
// Set x/y if a new position is provided in props that is different than the previous.
if (
position &&
(!prevPropsPosition ||
position.x !== prevPropsPosition.x || position.y !== prevPropsPosition.y
)
) {
log('Draggable: getDerivedStateFromProps %j', {position, prevPropsPosition});
return {
x: position.x,
y: position.y,
prevPropsPosition: {...position}
};
}
return null;
}
constructor(props: DraggableProps) {
super(props);
this.state = {
// Whether or not we are currently dragging.
dragging: false,
// Whether or not we have been dragged before.
dragged: false,
// Current transform x and y.
x: props.position ? props.position.x : props.defaultPosition.x,
y: props.position ? props.position.y : props.defaultPosition.y,
prevPropsPosition: {...props.position},
// Used for compensating for out-of-bounds drags
slackX: 0, slackY: 0,
// Can only determine if SVG after mounting
isElementSVG: false
};
if (props.position && !(props.onDrag || props.onStop)) {
// eslint-disable-next-line no-console
console.warn('A `position` was applied to this <Draggable>, without drag handlers. This will make this ' +
'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' +
'`position` of this element.');
}
}
componentDidMount() {
// Check to see if the element passed is an instanceof SVGElement
if(typeof window.SVGElement !== 'undefined' && this.findDOMNode() instanceof window.SVGElement) {
this.setState({isElementSVG: true});
}
}
componentWillUnmount() {
if (this.state.dragging) {
this.setState({dragging: false}); // prevents invariant if unmounted while dragging
}
}
// React 19 removed ReactDOM.findDOMNode, so nodeRef is now required.
// For backward compatibility with React 18 and earlier, we still support findDOMNode if available.
findDOMNode(): ?HTMLElement {
if (this.props?.nodeRef) {
return this.props.nodeRef.current;
}
// ReactDOM.findDOMNode was removed in React 19
if (typeof ReactDOM.findDOMNode === 'function') {
return ReactDOM.findDOMNode(this);
}
return null;
}
onDragStart: DraggableEventHandler = (e, coreData) => {
log('Draggable: onDragStart: %j', coreData);
// Short-circuit if user's callback killed it.
const shouldStart = this.props.onStart(e, createDraggableData(this, coreData));
// Kills start event on core as well, so move handlers are never bound.
if (shouldStart === false) return false;
this.setState({dragging: true, dragged: true});
};
onDrag: DraggableEventHandler = (e, coreData) => {
if (!this.state.dragging) return false;
log('Draggable: onDrag: %j', coreData);
const uiData = createDraggableData(this, coreData);
const newState = {
x: uiData.x,
y: uiData.y,
slackX: 0,
slackY: 0,
};
// Keep within bounds.
if (this.props.bounds) {
// Save original x and y.
const {x, y} = newState;
// Add slack to the values used to calculate bound position. This will ensure that if
// we start removing slack, the element won't react to it right away until it's been
// completely removed.
newState.x += this.state.slackX;
newState.y += this.state.slackY;
// Get bound position. This will ceil/floor the x and y within the boundaries.
const [newStateX, newStateY] = getBoundPosition(this, newState.x, newState.y);
newState.x = newStateX;
newState.y = newStateY;
// Recalculate slack by noting how much was shaved by the boundPosition handler.
newState.slackX = this.state.slackX + (x - newState.x);
newState.slackY = this.state.slackY + (y - newState.y);
// Update the event we fire to reflect what really happened after bounds took effect.
uiData.x = newState.x;
uiData.y = newState.y;
uiData.deltaX = newState.x - this.state.x;
uiData.deltaY = newState.y - this.state.y;
}
// Short-circuit if user's callback killed it.
const shouldUpdate = this.props.onDrag(e, uiData);
if (shouldUpdate === false) return false;
this.setState(newState);
};
onDragStop: DraggableEventHandler = (e, coreData) => {
if (!this.state.dragging) return false;
// Short-circuit if user's callback killed it.
const shouldContinue = this.props.onStop(e, createDraggableData(this, coreData));
if (shouldContinue === false) return false;
log('Draggable: onDragStop: %j', coreData);
const newState: Partial<DraggableState> = {
dragging: false,
slackX: 0,
slackY: 0
};
// If this is a controlled component, the result of this operation will be to
// revert back to the old position. We expect a handler on `onDragStop`, at the least.
const controlled = Boolean(this.props.position);
if (controlled) {
const {x, y} = this.props.position;
newState.x = x;
newState.y = y;
}
this.setState(newState);
};
render(): ReactElement<any> {
const {
axis,
bounds,
children,
defaultPosition,
defaultClassName,
defaultClassNameDragging,
defaultClassNameDragged,
position,
positionOffset,
scale,
...draggableCoreProps
} = this.props;
let style = {};
let svgTransform = null;
// If this is controlled, we don't want to move it - unless it's dragging.
const controlled = Boolean(position);
const draggable = !controlled || this.state.dragging;
const validPosition = position || defaultPosition;
const transformOpts = {
// Set left if horizontal drag is enabled
x: canDragX(this) && draggable ?
this.state.x :
validPosition.x,
// Set top if vertical drag is enabled
y: canDragY(this) && draggable ?
this.state.y :
validPosition.y
};
// If this element was SVG, we use the `transform` attribute.
if (this.state.isElementSVG) {
svgTransform = createSVGTransform(transformOpts, positionOffset);
} else {
// Add a CSS transform to move the element around. This allows us to move the element around
// without worrying about whether or not it is relatively or absolutely positioned.
// If the item you are dragging already has a transform set, wrap it in a <span> so <Draggable>
// has a clean slate.
style = createCSSTransform(transformOpts, positionOffset);
}
// Mark with class while dragging
const className = clsx((children.props.className || ''), defaultClassName, {
[defaultClassNameDragging]: this.state.dragging,
[defaultClassNameDragged]: this.state.dragged
});
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return (
<DraggableCore {...draggableCoreProps} onStart={this.onDragStart} onDrag={this.onDrag} onStop={this.onDragStop}>
{React.cloneElement(React.Children.only(children), {
className: className,
style: {...children.props.style, ...style},
transform: svgTransform
})}
</DraggableCore>
);
}
}
export {Draggable as default, DraggableCore};
================================================
FILE: lib/DraggableCore.js
================================================
// @flow
import * as React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {matchesSelectorAndParentsTo, addEvent, removeEvent, addUserSelectStyles, getTouchIdentifier,
scheduleRemoveUserSelectStyles} from './utils/domFns';
import {createCoreData, getControlPosition, snapToGrid} from './utils/positionFns';
import {dontSetMe} from './utils/shims';
import log from './utils/log';
import type {EventHandler, MouseTouchEvent} from './utils/types';
import type {Element as ReactElement} from 'react';
// Simple abstraction for dragging events names.
const eventsFor = {
touch: {
start: 'touchstart',
move: 'touchmove',
stop: 'touchend'
},
mouse: {
start: 'mousedown',
move: 'mousemove',
stop: 'mouseup'
}
};
// Default to mouse events.
let dragEventFor = eventsFor.mouse;
export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
};
export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void | false;
export type ControlPosition = {x: number, y: number};
export type PositionOffsetControlPosition = {x: number|string, y: number|string};
export type DraggableCoreDefaultProps = {
allowAnyClick: boolean,
allowMobileScroll: boolean,
disabled: boolean,
enableUserSelectHack: boolean,
onStart: DraggableEventHandler,
onDrag: DraggableEventHandler,
onStop: DraggableEventHandler,
onMouseDown: (e: MouseEvent) => void,
scale: number,
};
export type DraggableCoreProps = {
...DraggableCoreDefaultProps,
cancel: string,
children: ReactElement<any>,
offsetParent: HTMLElement,
grid: [number, number],
handle: string,
nodeRef?: ?React.ElementRef<any>,
};
//
// Define <DraggableCore>.
//
// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can
// work well with libraries that require more control over the element.
//
export default class DraggableCore extends React.Component<DraggableCoreProps> {
static displayName: ?string = 'DraggableCore';
static propTypes: Object = {
/**
* `allowAnyClick` allows dragging using any mouse button.
* By default, we only accept the left button.
*
* Defaults to `false`.
*/
allowAnyClick: PropTypes.bool,
/**
* `allowMobileScroll` turns off cancellation of the 'touchstart' event
* on mobile devices. Only enable this if you are having trouble with click
* events. Prefer using 'handle' / 'cancel' instead.
*
* Defaults to `false`.
*/
allowMobileScroll: PropTypes.bool,
children: PropTypes.node.isRequired,
/**
* `disabled`, if true, stops the <Draggable> from dragging. All handlers,
* with the exception of `onMouseDown`, will not fire.
*/
disabled: PropTypes.bool,
/**
* By default, we add 'user-select:none' attributes to the document body
* to prevent ugly text selection during drag. If this is causing problems
* for your app, set this to `false`.
*/
enableUserSelectHack: PropTypes.bool,
/**
* `offsetParent`, if set, uses the passed DOM node to compute drag offsets
* instead of using the parent node.
*/
offsetParent: function(props: DraggableCoreProps, propName: $Keys<DraggableCoreProps>) {
if (props[propName] && props[propName].nodeType !== 1) {
throw new Error('Draggable\'s offsetParent must be a DOM Node.');
}
},
/**
* `grid` specifies the x and y that dragging should snap to.
*/
grid: PropTypes.arrayOf(PropTypes.number),
/**
* `handle` specifies a selector to be used as the handle that initiates drag.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable handle=".handle">
* <div>
* <div className="handle">Click me to drag</div>
* <div>This is some other content</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
handle: PropTypes.string,
/**
* `cancel` specifies a selector to be used to prevent drag initialization.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return(
* <Draggable cancel=".cancel">
* <div>
* <div className="cancel">You can't drag from here</div>
* <div>Dragging here works fine</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
cancel: PropTypes.string,
/* If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.
* Unfortunately, in order for <Draggable> to work properly, we need raw access
* to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`
* as in this example:
*
* function MyComponent() {
* const nodeRef = React.useRef(null);
* return (
* <Draggable nodeRef={nodeRef}>
* <div ref={nodeRef}>Example Target</div>
* </Draggable>
* );
* }
*
* This can be used for arbitrarily nested components, so long as the ref ends up
* pointing to the actual child DOM node and not a custom component.
*/
nodeRef: PropTypes.object,
/**
* Called when dragging starts.
* If this function returns the boolean false, dragging will be canceled.
*/
onStart: PropTypes.func,
/**
* Called while dragging.
* If this function returns the boolean false, dragging will be canceled.
*/
onDrag: PropTypes.func,
/**
* Called when dragging stops.
* If this function returns the boolean false, the drag will remain active.
*/
onStop: PropTypes.func,
/**
* A workaround option which can be passed if onMouseDown needs to be accessed,
* since it'll always be blocked (as there is internal use of onMouseDown)
*/
onMouseDown: PropTypes.func,
/**
* `scale`, if set, applies scaling while dragging an element
*/
scale: PropTypes.number,
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
};
static defaultProps: DraggableCoreDefaultProps = {
allowAnyClick: false, // by default only accept left click
allowMobileScroll: false,
disabled: false,
enableUserSelectHack: true,
onStart: function(){},
onDrag: function(){},
onStop: function(){},
onMouseDown: function(){},
scale: 1,
};
dragging: boolean = false;
// Used while dragging to determine deltas.
lastX: number = NaN;
lastY: number = NaN;
touchIdentifier: ?number = null;
mounted: boolean = false;
componentDidMount() {
this.mounted = true;
// Touch handlers must be added with {passive: false} to be cancelable.
// https://developers.google.com/web/updates/2017/01/scrolling-intervention
const thisNode = this.findDOMNode();
if (thisNode) {
addEvent(thisNode, eventsFor.touch.start, this.onTouchStart, {passive: false});
}
}
componentWillUnmount() {
this.mounted = false;
// Remove any leftover event handlers. Remove both touch and mouse handlers in case
// some browser quirk caused a touch event to fire during a mouse move, or vice versa.
const thisNode = this.findDOMNode();
if (thisNode) {
const {ownerDocument} = thisNode;
removeEvent(ownerDocument, eventsFor.mouse.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.touch.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
removeEvent(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
removeEvent(thisNode, eventsFor.touch.start, this.onTouchStart, {passive: false});
if (this.props.enableUserSelectHack) scheduleRemoveUserSelectStyles(ownerDocument);
}
}
// React 19 removed ReactDOM.findDOMNode, so nodeRef is now required.
// For backward compatibility with React 18 and earlier, we still support findDOMNode if available.
findDOMNode(): ?HTMLElement {
if (this.props?.nodeRef) {
return this.props.nodeRef.current;
}
// ReactDOM.findDOMNode was removed in React 19
if (typeof ReactDOM.findDOMNode === 'function') {
return ReactDOM.findDOMNode(this);
}
// In React 19+, nodeRef is required - log a warning via our log utility
log(
'react-draggable: ReactDOM.findDOMNode is not available in React 19+. ' +
'You must provide a nodeRef prop. See: https://github.com/react-grid-layout/react-draggable#noderef'
);
return null;
}
handleDragStart: EventHandler<MouseTouchEvent> = (e) => {
// Make it possible to attach event handlers on top of this one.
this.props.onMouseDown(e);
// Only accept left-clicks. On macOS, ctrl+click is equivalent to right-click.
if (!this.props.allowAnyClick && ((typeof e.button === 'number' && e.button !== 0) || e.ctrlKey)) return false;
// Get nodes. Be sure to grab relative document (could be iframed)
const thisNode = this.findDOMNode();
if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
throw new Error('<DraggableCore> not mounted on DragStart!');
}
const {ownerDocument} = thisNode;
// Short circuit if handle or cancel prop was provided and selector doesn't match.
if (this.props.disabled ||
(!(e.target instanceof ownerDocument.defaultView.Node)) ||
(this.props.handle && !matchesSelectorAndParentsTo(e.target, this.props.handle, thisNode)) ||
(this.props.cancel && matchesSelectorAndParentsTo(e.target, this.props.cancel, thisNode))) {
return;
}
// Prevent scrolling on mobile devices, like ipad/iphone.
// Important that this is after handle/cancel.
if (e.type === 'touchstart' && !this.props.allowMobileScroll) e.preventDefault();
// Set touch identifier in component state if this is a touch event. This allows us to
// distinguish between individual touches on multitouch screens by identifying which
// touchpoint was set to this element.
const touchIdentifier = getTouchIdentifier(e);
this.touchIdentifier = touchIdentifier;
// Get the current drag point from the event. This is used as the offset.
const position = getControlPosition(e, touchIdentifier, this);
if (position == null) return; // not possible but satisfies flow
const {x, y} = position;
// Create an event object with all the data parents need to make a decision here.
const coreEvent = createCoreData(this, x, y);
log('DraggableCore: handleDragStart: %j', coreEvent);
// Call event handler. If it returns explicit false, cancel.
log('calling', this.props.onStart);
const shouldUpdate = this.props.onStart(e, coreEvent);
if (shouldUpdate === false || this.mounted === false) return;
// Add a style to the body to disable user-select. This prevents text from
// being selected all over the page.
if (this.props.enableUserSelectHack) addUserSelectStyles(ownerDocument);
// Initiate dragging. Set the current x and y as offsets
// so we know how much we've moved during the drag. This allows us
// to drag elements around even if they have been moved, without issue.
this.dragging = true;
this.lastX = x;
this.lastY = y;
// Add events to the document directly so we catch when the user's mouse/touch moves outside of
// this element. We use different events depending on whether or not we have detected that this
// is a touch-capable device.
addEvent(ownerDocument, dragEventFor.move, this.handleDrag);
addEvent(ownerDocument, dragEventFor.stop, this.handleDragStop);
};
handleDrag: EventHandler<MouseTouchEvent> = (e) => {
// Get the current drag point from the event. This is used as the offset.
const position = getControlPosition(e, this.touchIdentifier, this);
if (position == null) return;
let {x, y} = position;
// Snap to grid if prop has been provided
if (Array.isArray(this.props.grid)) {
let deltaX = x - this.lastX, deltaY = y - this.lastY;
[deltaX, deltaY] = snapToGrid(this.props.grid, deltaX, deltaY);
if (!deltaX && !deltaY) return; // skip useless drag
x = this.lastX + deltaX, y = this.lastY + deltaY;
}
const coreEvent = createCoreData(this, x, y);
log('DraggableCore: handleDrag: %j', coreEvent);
// Call event handler. If it returns explicit false, trigger end.
const shouldUpdate = this.props.onDrag(e, coreEvent);
if (shouldUpdate === false || this.mounted === false) {
try {
// $FlowIgnore
this.handleDragStop(new MouseEvent('mouseup'));
} catch (err) {
// Old browsers
const event = ((document.createEvent('MouseEvents'): any): MouseTouchEvent);
// I see why this insanity was deprecated
// $FlowIgnore
event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
this.handleDragStop(event);
}
return;
}
this.lastX = x;
this.lastY = y;
};
handleDragStop: EventHandler<MouseTouchEvent> = (e) => {
if (!this.dragging) return;
const position = getControlPosition(e, this.touchIdentifier, this);
if (position == null) return;
let {x, y} = position;
// Snap to grid if prop has been provided
if (Array.isArray(this.props.grid)) {
let deltaX = x - this.lastX || 0;
let deltaY = y - this.lastY || 0;
[deltaX, deltaY] = snapToGrid(this.props.grid, deltaX, deltaY);
x = this.lastX + deltaX, y = this.lastY + deltaY;
}
const coreEvent = createCoreData(this, x, y);
// Call event handler
const shouldContinue = this.props.onStop(e, coreEvent);
if (shouldContinue === false || this.mounted === false) return false;
const thisNode = this.findDOMNode();
if (thisNode) {
// Remove user-select hack
if (this.props.enableUserSelectHack) scheduleRemoveUserSelectStyles(thisNode.ownerDocument);
}
log('DraggableCore: handleDragStop: %j', coreEvent);
// Reset the el.
this.dragging = false;
this.lastX = NaN;
this.lastY = NaN;
if (thisNode) {
// Remove event handlers
log('DraggableCore: Removing handlers');
removeEvent(thisNode.ownerDocument, dragEventFor.move, this.handleDrag);
removeEvent(thisNode.ownerDocument, dragEventFor.stop, this.handleDragStop);
}
};
onMouseDown: EventHandler<MouseTouchEvent> = (e) => {
dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse
return this.handleDragStart(e);
};
onMouseUp: EventHandler<MouseTouchEvent> = (e) => {
dragEventFor = eventsFor.mouse;
return this.handleDragStop(e);
};
// Same as onMouseDown (start drag), but now consider this a touch device.
onTouchStart: EventHandler<MouseTouchEvent> = (e) => {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return this.handleDragStart(e);
};
onTouchEnd: EventHandler<MouseTouchEvent> = (e) => {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return this.handleDragStop(e);
};
render(): React.Element<any> {
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return React.cloneElement(React.Children.only(this.props.children), {
// Note: mouseMove handler is attached to document so it will still function
// when the user drags quickly and leaves the bounds of the element.
onMouseDown: this.onMouseDown,
onMouseUp: this.onMouseUp,
// onTouchStart is added on `componentDidMount` so they can be added with
// {passive: false}, which allows it to cancel. See
// https://developers.google.com/web/updates/2017/01/scrolling-intervention
onTouchEnd: this.onTouchEnd
});
}
}
================================================
FILE: lib/cjs.js
================================================
const {default: Draggable, DraggableCore} = require('./Draggable');
// Previous versions of this lib exported <Draggable> as the root export. As to no-// them, or TypeScript, we export *both* as the root and as 'default'.
// See https://github.com/mzabriskie/react-draggable/pull/254
// and https://github.com/mzabriskie/react-draggable/issues/266
module.exports = Draggable;
module.exports.default = Draggable;
module.exports.DraggableCore = DraggableCore;
================================================
FILE: lib/utils/domFns.js
================================================
// @flow
import {findInArray, isFunction, int} from './shims';
import browserPrefix, {browserPrefixToKey} from './getPrefix';
import type {ControlPosition, PositionOffsetControlPosition, MouseTouchEvent} from './types';
let matchesSelectorFunc = '';
export function matchesSelector(el: Node, selector: string): boolean {
if (!matchesSelectorFunc) {
matchesSelectorFunc = findInArray([
'matches',
'webkitMatchesSelector',
'mozMatchesSelector',
'msMatchesSelector',
'oMatchesSelector'
], function(method){
// $FlowIgnore: Doesn't think elements are indexable
return isFunction(el[method]);
});
}
// Might not be found entirely (not an Element?) - in that case, bail
// $FlowIgnore: Doesn't think elements are indexable
if (!isFunction(el[matchesSelectorFunc])) return false;
// $FlowIgnore: Doesn't think elements are indexable
return el[matchesSelectorFunc](selector);
}
// Works up the tree to the draggable itself attempting to match selector.
export function matchesSelectorAndParentsTo(el: Node, selector: string, baseNode: Node): boolean {
let node = el;
do {
if (matchesSelector(node, selector)) return true;
if (node === baseNode) return false;
// $FlowIgnore[incompatible-type]
node = node.parentNode;
} while (node);
return false;
}
export function addEvent(el: ?Node, event: string, handler: Function, inputOptions?: Object): void {
if (!el) return;
const options = {capture: true, ...inputOptions};
// $FlowIgnore[method-unbinding]
if (el.addEventListener) {
el.addEventListener(event, handler, options);
} else if (el.attachEvent) {
el.attachEvent('on' + event, handler);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = handler;
}
}
export function removeEvent(el: ?Node, event: string, handler: Function, inputOptions?: Object): void {
if (!el) return;
const options = {capture: true, ...inputOptions};
// $FlowIgnore[method-unbinding]
if (el.removeEventListener) {
el.removeEventListener(event, handler, options);
} else if (el.detachEvent) {
el.detachEvent('on' + event, handler);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = null;
}
}
export function outerHeight(node: HTMLElement): number {
// This is deliberately excluding margin for our calculations, since we are using
// offsetTop which is including margin. See getBoundPosition
let height = node.clientHeight;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height += int(computedStyle.borderTopWidth);
height += int(computedStyle.borderBottomWidth);
return height;
}
export function outerWidth(node: HTMLElement): number {
// This is deliberately excluding margin for our calculations, since we are using
// offsetLeft which is including margin. See getBoundPosition
let width = node.clientWidth;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width += int(computedStyle.borderLeftWidth);
width += int(computedStyle.borderRightWidth);
return width;
}
export function innerHeight(node: HTMLElement): number {
let height = node.clientHeight;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height -= int(computedStyle.paddingTop);
height -= int(computedStyle.paddingBottom);
return height;
}
export function innerWidth(node: HTMLElement): number {
let width = node.clientWidth;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width -= int(computedStyle.paddingLeft);
width -= int(computedStyle.paddingRight);
return width;
}
interface EventWithOffset {
clientX: number, clientY: number
}
// Get from offsetParent
export function offsetXYFromParent(evt: EventWithOffset, offsetParent: HTMLElement, scale: number): ControlPosition {
const isBody = offsetParent === offsetParent.ownerDocument.body;
const offsetParentRect = isBody ? {left: 0, top: 0} : offsetParent.getBoundingClientRect();
const x = (evt.clientX + offsetParent.scrollLeft - offsetParentRect.left) / scale;
const y = (evt.clientY + offsetParent.scrollTop - offsetParentRect.top) / scale;
return {x, y};
}
export function createCSSTransform(controlPos: ControlPosition, positionOffset: PositionOffsetControlPosition): Object {
const translation = getTranslation(controlPos, positionOffset, 'px');
return {[browserPrefixToKey('transform', browserPrefix)]: translation };
}
export function createSVGTransform(controlPos: ControlPosition, positionOffset: PositionOffsetControlPosition): string {
const translation = getTranslation(controlPos, positionOffset, '');
return translation;
}
export function getTranslation({x, y}: ControlPosition, positionOffset: PositionOffsetControlPosition, unitSuffix: string): string {
let translation = `translate(${x}${unitSuffix},${y}${unitSuffix})`;
if (positionOffset) {
const defaultX = `${(typeof positionOffset.x === 'string') ? positionOffset.x : positionOffset.x + unitSuffix}`;
const defaultY = `${(typeof positionOffset.y === 'string') ? positionOffset.y : positionOffset.y + unitSuffix}`;
translation = `translate(${defaultX}, ${defaultY})` + translation;
}
return translation;
}
export function getTouch(e: MouseTouchEvent, identifier: number): ?{clientX: number, clientY: number} {
return (e.targetTouches && findInArray(e.targetTouches, t => identifier === t.identifier)) ||
(e.changedTouches && findInArray(e.changedTouches, t => identifier === t.identifier));
}
export function getTouchIdentifier(e: MouseTouchEvent): ?number {
if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
}
// User-select Hacks:
//
// Useful for preventing blue highlights all over everything when dragging.
// Note we're passing `document` b/c we could be iframed
export function addUserSelectStyles(doc: ?Document) {
if (!doc) return;
let styleEl = doc.getElementById('react-draggable-style-el');
if (!styleEl) {
styleEl = doc.createElement('style');
styleEl.type = 'text/css';
styleEl.id = 'react-draggable-style-el';
styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n';
styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {all: inherit;}\n';
doc.getElementsByTagName('head')[0].appendChild(styleEl);
}
if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
}
export function scheduleRemoveUserSelectStyles(doc: ?Document) {
// Prevent a possible "forced reflow"
if (window.requestAnimationFrame) {
window.requestAnimationFrame(() => {
removeUserSelectStyles(doc);
});
} else {
removeUserSelectStyles(doc);
}
}
function removeUserSelectStyles(doc: ?Document) {
if (!doc) return;
try {
if (doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
// $FlowIgnore: IE
if (doc.selection) {
// $FlowIgnore: IE
doc.selection.empty();
} else {
// Remove selection caused by scroll, unless it's a focused input
// (we use doc.defaultView in case we're in an iframe)
const selection = (doc.defaultView || window).getSelection();
if (selection && selection.type !== 'Caret') {
selection.removeAllRanges();
}
}
} catch (e) {
// probably IE
}
}
export function addClassName(el: HTMLElement, className: string) {
if (el.classList) {
el.classList.add(className);
} else {
if (!el.className.match(new RegExp(`(?:^|\\s)${className}(?!\\S)`))) {
el.className += ` ${className}`;
}
}
}
export function removeClassName(el: HTMLElement, className: string) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp(`(?:^|\\s)${className}(?!\\S)`, 'g'), '');
}
}
================================================
FILE: lib/utils/getPrefix.js
================================================
// @flow
const prefixes = ['Moz', 'Webkit', 'O', 'ms'];
export function getPrefix(prop: string='transform'): string {
// Ensure we're running in an environment where there is actually a global
// `window` obj
if (typeof window === 'undefined') return '';
// If we're in a pseudo-browser server-side environment, this access
// path may not exist, so bail out if it doesn't.
const style = window.document?.documentElement?.style;
if (!style) return '';
if (prop in style) return '';
for (let i = 0; i < prefixes.length; i++) {
if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];
}
return '';
}
export function browserPrefixToKey(prop: string, prefix: string): string {
return prefix ? `${prefix}${kebabToTitleCase(prop)}` : prop;
}
export function browserPrefixToStyle(prop: string, prefix: string): string {
return prefix ? `-${prefix.toLowerCase()}-${prop}` : prop;
}
function kebabToTitleCase(str: string): string {
let out = '';
let shouldCapitalize = true;
for (let i = 0; i < str.length; i++) {
if (shouldCapitalize) {
out += str[i].toUpperCase();
shouldCapitalize = false;
} else if (str[i] === '-') {
shouldCapitalize = true;
} else {
out += str[i];
}
}
return out;
}
// Default export is the prefix itself, like 'Moz', 'Webkit', etc
// Note that you may have to re-test for certain things; for instance, Chrome 50
// can handle unprefixed `transform`, but not unprefixed `user-select`
export default (getPrefix(): string);
================================================
FILE: lib/utils/log.js
================================================
// @flow
/*eslint no-console:0*/
export default function log(...args: any) {
if (process.env.DRAGGABLE_DEBUG) console.log(...args);
}
================================================
FILE: lib/utils/positionFns.js
================================================
// @flow
import {isNum, int} from './shims';
import {getTouch, innerWidth, innerHeight, offsetXYFromParent, outerWidth, outerHeight} from './domFns';
import type Draggable from '../Draggable';
import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';
import type DraggableCore from '../DraggableCore';
export function getBoundPosition(draggable: Draggable, x: number, y: number): [number, number] {
// If no bounds, short-circuit and move on
if (!draggable.props.bounds) return [x, y];
// Clone new bounds
let {bounds} = draggable.props;
bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);
const node = findDOMNode(draggable);
if (typeof bounds === 'string') {
const {ownerDocument} = node;
const ownerWindow = ownerDocument.defaultView;
let boundNode;
if (bounds === 'parent') {
boundNode = node.parentNode;
} else {
// Flow assigns the wrong return type (Node) for getRootNode(),
// so we cast it to one of the correct types (Element).
// The others are Document and ShadowRoot.
// All three implement querySelector() so it's safe to call.
const rootNode = (((node.getRootNode()): any): Element);
boundNode = rootNode.querySelector(bounds);
}
if (!(boundNode instanceof ownerWindow.HTMLElement)) {
throw new Error('Bounds selector "' + bounds + '" could not find an element.');
}
const boundNodeEl: HTMLElement = boundNode; // for Flow, can't seem to refine correctly
const nodeStyle = ownerWindow.getComputedStyle(node);
const boundNodeStyle = ownerWindow.getComputedStyle(boundNodeEl);
// Compute bounds. This is a pain with padding and offsets but this gets it exactly right.
bounds = {
left: -node.offsetLeft + int(boundNodeStyle.paddingLeft) + int(nodeStyle.marginLeft),
top: -node.offsetTop + int(boundNodeStyle.paddingTop) + int(nodeStyle.marginTop),
right: innerWidth(boundNodeEl) - outerWidth(node) - node.offsetLeft +
int(boundNodeStyle.paddingRight) - int(nodeStyle.marginRight),
bottom: innerHeight(boundNodeEl) - outerHeight(node) - node.offsetTop +
int(boundNodeStyle.paddingBottom) - int(nodeStyle.marginBottom)
};
}
// Keep x and y below right and bottom limits...
if (isNum(bounds.right)) x = Math.min(x, bounds.right);
if (isNum(bounds.bottom)) y = Math.min(y, bounds.bottom);
// But above left and top limits.
if (isNum(bounds.left)) x = Math.max(x, bounds.left);
if (isNum(bounds.top)) y = Math.max(y, bounds.top);
return [x, y];
}
export function snapToGrid(grid: [number, number], pendingX: number, pendingY: number): [number, number] {
const x = Math.round(pendingX / grid[0]) * grid[0];
const y = Math.round(pendingY / grid[1]) * grid[1];
return [x, y];
}
export function canDragX(draggable: Draggable): boolean {
return draggable.props.axis === 'both' || draggable.props.axis === 'x';
}
export function canDragY(draggable: Draggable): boolean {
return draggable.props.axis === 'both' || draggable.props.axis === 'y';
}
// Get {x, y} positions from event.
export function getControlPosition(e: MouseTouchEvent, touchIdentifier: ?number, draggableCore: DraggableCore): ?ControlPosition {
const touchObj = typeof touchIdentifier === 'number' ? getTouch(e, touchIdentifier) : null;
if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch
const node = findDOMNode(draggableCore);
// User can provide an offsetParent if desired.
const offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
return offsetXYFromParent(touchObj || e, offsetParent, draggableCore.props.scale);
}
// Create an data object exposed by <DraggableCore>'s events
export function createCoreData(draggable: DraggableCore, x: number, y: number): DraggableData {
const isStart = !isNum(draggable.lastX);
const node = findDOMNode(draggable);
if (isStart) {
// If this is our first move, use the x and y as last coords.
return {
node,
deltaX: 0, deltaY: 0,
lastX: x, lastY: y,
x, y,
};
} else {
// Otherwise calculate proper values.
return {
node,
deltaX: x - draggable.lastX, deltaY: y - draggable.lastY,
lastX: draggable.lastX, lastY: draggable.lastY,
x, y,
};
}
}
// Create an data exposed by <Draggable>'s events
export function createDraggableData(draggable: Draggable, coreData: DraggableData): DraggableData {
const scale = draggable.props.scale;
return {
node: coreData.node,
x: draggable.state.x + (coreData.deltaX / scale),
y: draggable.state.y + (coreData.deltaY / scale),
deltaX: (coreData.deltaX / scale),
deltaY: (coreData.deltaY / scale),
lastX: draggable.state.x,
lastY: draggable.state.y
};
}
// A lot faster than stringify/parse
function cloneBounds(bounds: Bounds): Bounds {
return {
left: bounds.left,
top: bounds.top,
right: bounds.right,
bottom: bounds.bottom
};
}
function findDOMNode(draggable: Draggable | DraggableCore): HTMLElement {
const node = draggable.findDOMNode();
if (!node) {
throw new Error('<DraggableCore>: Unmounted during event!');
}
// $FlowIgnore we can't assert on HTMLElement due to tests... FIXME
return node;
}
================================================
FILE: lib/utils/shims.js
================================================
// @flow
// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc
export function findInArray(array: Array<any> | TouchList, callback: Function): any {
for (let i = 0, length = array.length; i < length; i++) {
if (callback.apply(callback, [array[i], i, array])) return array[i];
}
}
export function isFunction(func: any): boolean %checks {
// $FlowIgnore[method-unbinding]
return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';
}
export function isNum(num: any): boolean %checks {
return typeof num === 'number' && !isNaN(num);
}
export function int(a: string): number {
return parseInt(a, 10);
}
export function dontSetMe(props: Object, propName: string, componentName: string): ?Error {
if (props[propName]) {
return new Error(`Invalid prop ${propName} passed to ${componentName} - do not set this, set it on the child.`);
}
}
================================================
FILE: lib/utils/types.js
================================================
// @flow
// eslint-disable-next-line no-use-before-define
export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void | false;
export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number
};
export type Bounds = {
left?: number, top?: number, right?: number, bottom?: number
};
export type ControlPosition = {x: number, y: number};
export type PositionOffsetControlPosition = {x: number|string, y: number|string};
export type EventHandler<T> = (e: T) => void | false;
// Missing in Flow
export class SVGElement extends HTMLElement {
}
// Missing targetTouches
export class TouchEvent2 extends TouchEvent {
changedTouches: TouchList;
targetTouches: TouchList;
}
export type MouseTouchEvent = MouseEvent & TouchEvent2;
================================================
FILE: package.json
================================================
{
"name": "react-draggable",
"version": "4.5.0",
"description": "React draggable component",
"main": "build/cjs/cjs.js",
"unpkg": "build/web/react-draggable.min.js",
"scripts": {
"test": "vitest run --reporter=verbose",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:ui": "vitest --ui",
"test:browser": "yarn build && vitest run --config vitest.browser.config.js",
"test:all": "yarn test && yarn test:browser",
"dev": "make dev",
"build": "make clean build",
"build-example": "mkdir -p example/build/web && cp build/web/react-draggable.min.js example/build/web/ && sed -i.bak 's|../build/web/react-draggable|build/web/react-draggable|g' example/index.html && rm -f example/index.html.bak",
"lint": "make lint",
"flow": "flow"
},
"files": [
"build",
"typings"
],
"typings": "./typings/index.d.ts",
"types": "./typings/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/react-grid-layout/react-draggable.git"
},
"keywords": [
"react",
"draggable",
"react-component"
],
"author": "Matt Zabriskie",
"contributors": [
"Samuel Reed <samuel.trace.reed@gmail.com> (http://strml.net/)"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/react-grid-layout/react-draggable/issues"
},
"homepage": "https://github.com/react-grid-layout/react-draggable",
"devDependencies": {
"@babel/cli": "^7.28.3",
"@babel/core": "^7.28.5",
"@babel/eslint-parser": "^7.28.5",
"@babel/plugin-transform-class-properties": "^7.27.1",
"@babel/plugin-transform-flow-comments": "^7.28.5",
"@babel/preset-env": "^7.28.5",
"@babel/preset-flow": "^7.27.1",
"@babel/preset-react": "^7.28.5",
"@eslint/eslintrc": "^3.3.3",
"@eslint/js": "^9.39.2",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.1",
"@types/node": "^25.0.3",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.2",
"@vitest/coverage-v8": "^4.0.16",
"babel-loader": "^10.0.0",
"babel-plugin-transform-inline-environment-variables": "^0.4.4",
"eslint": "^9.39.2",
"eslint-plugin-react": "^7.37.5",
"flow-bin": "^0.217.0",
"globals": "^16.5.0",
"jsdom": "^27.4.0",
"pre-commit": "^1.2.2",
"process": "^0.11.10",
"puppeteer": "^24.34.0",
"react": "19",
"react-dom": "19",
"react-frame-component": "^5.2.7",
"semver": "^7.7.3",
"typescript": "^5.9.3",
"vitest": "^4.0.16",
"webpack": "^5.104.1",
"webpack-cli": "^6.0.1",
"webpack-dev-server": "^5.2.2"
},
"resolutions": {
"minimist": "^1.2.5"
},
"precommit": [
"lint",
"test"
],
"dependencies": {
"clsx": "^2.1.1",
"prop-types": "^15.8.1"
},
"peerDependencies": {
"react": ">= 16.3.0",
"react-dom": ">= 16.3.0"
}
}
================================================
FILE: test/Draggable.test.jsx
================================================
import React, { useRef, useState } from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, cleanup, act } from '@testing-library/react';
import Draggable, { DraggableCore } from '../lib/Draggable';
import { simulateDrag, startDrag, moveDrag, endDrag } from './testUtils';
// Helper wrapper components that provide nodeRef (required in React 19)
function DraggableWrapper({ children, draggableRef, ...props }) {
const nodeRef = useRef(null);
return (
<Draggable ref={draggableRef} nodeRef={nodeRef} {...props}>
{React.cloneElement(children, { ref: nodeRef })}
</Draggable>
);
}
function DraggableCorWrapper({ children, coreRef, ...props }) {
const nodeRef = useRef(null);
return (
<DraggableCore ref={coreRef} nodeRef={nodeRef} {...props}>
{React.cloneElement(children, { ref: nodeRef })}
</DraggableCore>
);
}
describe('Draggable', () => {
afterEach(() => {
cleanup();
// Clean up any leftover classes on body
document.body.className = '';
});
describe('default props', () => {
it('should have sensible defaults', () => {
const draggableRef = React.createRef();
render(
<DraggableWrapper draggableRef={draggableRef}>
<div />
</DraggableWrapper>
);
expect(draggableRef.current.props.axis).toBe('both');
expect(draggableRef.current.props.bounds).toBe(false);
expect(draggableRef.current.props.defaultClassName).toBe('react-draggable');
expect(draggableRef.current.props.defaultClassNameDragging).toBe('react-draggable-dragging');
expect(draggableRef.current.props.defaultClassNameDragged).toBe('react-draggable-dragged');
expect(draggableRef.current.props.scale).toBe(1);
});
});
describe('rendering', () => {
it('should render with default class', () => {
const { container } = render(
<DraggableWrapper>
<div />
</DraggableWrapper>
);
expect(container.firstChild.classList.contains('react-draggable')).toBe(true);
});
it('should preserve child className', () => {
const { container } = render(
<DraggableWrapper>
<div className="my-class" />
</DraggableWrapper>
);
expect(container.firstChild.classList.contains('my-class')).toBe(true);
expect(container.firstChild.classList.contains('react-draggable')).toBe(true);
});
it('should preserve child styles', () => {
const { container } = render(
<DraggableWrapper>
<div style={{ color: 'red' }} />
</DraggableWrapper>
);
expect(container.firstChild.style.color).toBe('red');
});
it('should apply transform style', () => {
const { container } = render(
<DraggableWrapper>
<div />
</DraggableWrapper>
);
expect(container.firstChild.style.transform).toMatch(/translate\(0px,?\s*0px\)/);
});
it('should use custom defaultClassName', () => {
const { container } = render(
<DraggableWrapper defaultClassName="custom-draggable">
<div />
</DraggableWrapper>
);
expect(container.firstChild.classList.contains('custom-draggable')).toBe(true);
expect(container.firstChild.classList.contains('react-draggable')).toBe(false);
});
});
describe('dragging classes', () => {
it('should add dragging class during drag', () => {
const { container } = render(
<DraggableWrapper>
<div />
</DraggableWrapper>
);
expect(container.firstChild.classList.contains('react-draggable-dragging')).toBe(false);
act(() => {
startDrag(container.firstChild, { x: 0, y: 0 });
});
expect(container.firstChild.classList.contains('react-draggable-dragging')).toBe(true);
act(() => {
endDrag(container.firstChild, { x: 0, y: 0 });
});
expect(container.firstChild.classList.contains('react-draggable-dragging')).toBe(false);
});
it('should add dragged class after drag', () => {
const { container } = render(
<DraggableWrapper>
<div />
</DraggableWrapper>
);
expect(container.firstChild.classList.contains('react-draggable-dragged')).toBe(false);
act(() => {
simulateDrag(container.firstChild, { from: { x: 0, y: 0 }, to: { x: 100, y: 100 } });
});
expect(container.firstChild.classList.contains('react-draggable-dragged')).toBe(true);
});
it('should use custom class names', () => {
const { container } = render(
<DraggableWrapper
defaultClassName="custom"
defaultClassNameDragging="custom-dragging"
defaultClassNameDragged="custom-dragged"
>
<div />
</DraggableWrapper>
);
act(() => {
startDrag(container.firstChild, { x: 0, y: 0 });
});
expect(container.firstChild.classList.contains('custom-dragging')).toBe(true);
act(() => {
endDrag(container.firstChild, { x: 0, y: 0 });
});
expect(container.firstChild.classList.contains('custom-dragged')).toBe(true);
});
});
describe('position', () => {
// Note: Transform updates during drag are tested in browser tests
// (test/browser/browser.test.js) because jsdom doesn't support
// coordinate calculations. See 'should update transform on drag' test there.
it('should respect defaultPosition', () => {
const { container } = render(
<DraggableWrapper defaultPosition={{ x: 50, y: 50 }}>
<div />
</DraggableWrapper>
);
expect(container.firstChild.style.transform).toMatch(/translate\(50px,?\s*50px\)/);
});
it('should use controlled position', () => {
const { container } = render(
<DraggableWrapper position={{ x: 100, y: 100 }}>
<div />
</DraggableWrapper>
);
expect(container.firstChild.style.transform).toMatch(/translate\(100px,?\s*100px\)/);
});
it('should respect positionOffset with numbers', () => {
const { container } = render(
<DraggableWrapper positionOffset={{ x: 10, y: 20 }}>
<div />
</DraggableWrapper>
);
expect(container.firstChild.style.transform).toContain('translate(10px, 20px)');
});
it('should respect positionOffset with percentages', () => {
const { container } = render(
<DraggableWrapper positionOffset={{ x: '50%', y: '50%' }}>
<div />
</DraggableWrapper>
);
expect(container.firstChild.style.transform).toContain('translate(50%, 50%)');
});
});
describe('axis constraint', () => {
// Note: Axis constraint tests with actual dragging are in browser tests
// (test/browser/browser.test.js) because jsdom doesn't support coordinate
// calculations. See 'should honor x axis constraint' and 'should honor y axis constraint'.
it('should not move when axis="none"', () => {
const { container } = render(
<DraggableWrapper axis="none">
<div />
</DraggableWrapper>
);
act(() => {
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
endDrag(container.firstChild, { x: 100, y: 100 });
});
expect(container.firstChild.style.transform).toMatch(/translate\(0px,?\s*0px\)/);
});
});
describe('callbacks', () => {
it('should call onStart when drag starts', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableWrapper onStart={onStart}>
<div />
</DraggableWrapper>
);
act(() => {
startDrag(container.firstChild, { x: 0, y: 0 });
});
expect(onStart).toHaveBeenCalledTimes(1);
});
// Note: onStop callback test is in browser tests (test/browser/browser.test.js)
// because jsdom doesn't support coordinate calculations.
// See 'should call onStop when drag ends' test there.
it('should cancel drag when onStart returns false', () => {
const onStart = vi.fn(() => false);
const onDrag = vi.fn();
const { container } = render(
<DraggableWrapper onStart={onStart} onDrag={onDrag}>
<div />
</DraggableWrapper>
);
act(() => {
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
});
expect(onStart).toHaveBeenCalled();
expect(onDrag).not.toHaveBeenCalled();
});
});
describe('SVG support', () => {
it('should detect SVG elements', () => {
const draggableRef = React.createRef();
render(
<DraggableWrapper draggableRef={draggableRef}>
<svg />
</DraggableWrapper>
);
expect(draggableRef.current.state.isElementSVG).toBe(true);
});
it('should not set isElementSVG for non-SVG elements', () => {
const draggableRef = React.createRef();
render(
<DraggableWrapper draggableRef={draggableRef}>
<div />
</DraggableWrapper>
);
expect(draggableRef.current.state.isElementSVG).toBe(false);
});
it('should set initial transform attribute for SVG', () => {
const { container } = render(
<DraggableWrapper>
<svg />
</DraggableWrapper>
);
expect(container.firstChild.getAttribute('transform')).toContain('translate(0,0)');
});
});
describe('controlled component', () => {
it('should respect position prop changes', () => {
function ControlledTest() {
const [position, setPosition] = useState({ x: 0, y: 0 });
return (
<>
<button onClick={() => setPosition({ x: 100, y: 100 })}>Move</button>
<DraggableWrapper position={position}>
<div data-testid="draggable" />
</DraggableWrapper>
</>
);
}
const { container, getByRole, getByTestId } = render(<ControlledTest />);
expect(getByTestId('draggable').style.transform).toMatch(/translate\(0px,?\s*0px\)/);
act(() => {
getByRole('button').click();
});
expect(getByTestId('draggable').style.transform).toMatch(/translate\(100px,?\s*100px\)/);
});
it('should revert to controlled position after drag', () => {
const onStop = vi.fn();
const { container } = render(
<DraggableWrapper position={{ x: 50, y: 50 }} onStop={onStop}>
<div />
</DraggableWrapper>
);
act(() => {
simulateDrag(container.firstChild, { from: { x: 50, y: 50 }, to: { x: 150, y: 150 } });
});
// After drag ends, should revert to controlled position
expect(container.firstChild.style.transform).toMatch(/translate\(50px,?\s*50px\)/);
});
});
describe('disabled prop', () => {
it('should not drag when disabled', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableWrapper disabled onStart={onStart}>
<div />
</DraggableWrapper>
);
act(() => {
startDrag(container.firstChild, { x: 0, y: 0 });
});
expect(onStart).not.toHaveBeenCalled();
});
});
describe('validation', () => {
it('should throw when no children provided', () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const nodeRef = React.createRef();
let threw = false;
try {
render(<Draggable nodeRef={nodeRef} />);
} catch (e) {
threw = true;
// Can throw either React.Children.only error or props access error
expect(e).toBeDefined();
}
expect(threw).toBe(true);
errorSpy.mockRestore();
});
it('should throw when multiple children provided', () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const nodeRef = React.createRef();
let threw = false;
try {
render(
<Draggable nodeRef={nodeRef}>
<div>One</div>
<div>Two</div>
</Draggable>
);
} catch (e) {
threw = true;
// Can throw either React.Children.only error or className access error
expect(e).toBeDefined();
}
expect(threw).toBe(true);
errorSpy.mockRestore();
});
// Note: React 19 removed runtime propTypes checking, so these tests now just verify
// that the component still renders correctly when invalid props are passed.
// The dontSetMe validators are defined but no longer trigger warnings in React 19.
it('should still render when className is set on Draggable', () => {
const { container } = render(
<DraggableWrapper className="invalid">
<div />
</DraggableWrapper>
);
// Component should still render
expect(container.firstChild).toBeTruthy();
expect(container.firstChild.classList.contains('react-draggable')).toBe(true);
});
it('should still render when style is set on Draggable', () => {
const { container } = render(
<DraggableWrapper style={{ color: 'red' }}>
<div />
</DraggableWrapper>
);
// Component should still render
expect(container.firstChild).toBeTruthy();
});
it('should still render when transform is set on Draggable', () => {
const { container } = render(
<DraggableWrapper transform="translate(100px, 100px)">
<div />
</DraggableWrapper>
);
// Component should still render
expect(container.firstChild).toBeTruthy();
});
});
});
================================================
FILE: test/DraggableCore.test.jsx
================================================
import React, { useRef } from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, cleanup } from '@testing-library/react';
import { DraggableCore } from '../lib/Draggable';
import { simulateDrag, startDrag, moveDrag, endDrag, createTouchEvent } from './testUtils';
// Helper wrapper component that provides nodeRef (required in React 19)
function DraggableCoreWrapper({ children, coreRef, ...props }) {
const nodeRef = useRef(null);
return (
<DraggableCore ref={coreRef} nodeRef={nodeRef} {...props}>
{React.cloneElement(children, { ref: nodeRef })}
</DraggableCore>
);
}
describe('DraggableCore', () => {
afterEach(() => {
cleanup();
});
describe('rendering', () => {
it('should render its child', () => {
const { container } = render(
<DraggableCoreWrapper>
<div data-testid="child">Hello</div>
</DraggableCoreWrapper>
);
expect(container.querySelector('[data-testid="child"]')).toBeTruthy();
expect(container.textContent).toBe('Hello');
});
it('should accept a single child only', () => {
// Suppress React error boundary logs for this test
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const nodeRef = React.createRef();
// Use try/catch instead of expect().toThrow() to avoid stderr output
let threw = false;
try {
render(
<DraggableCore nodeRef={nodeRef}>
<div>One</div>
<div>Two</div>
</DraggableCore>
);
} catch (e) {
threw = true;
expect(e.message).toContain('React.Children.only');
}
expect(threw).toBe(true);
errorSpy.mockRestore();
});
});
describe('mouse events', () => {
it('should call onStart when mouse down', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
expect(onStart).toHaveBeenCalledTimes(1);
});
it('should call onDrag during mouse move', () => {
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
expect(onDrag).toHaveBeenCalled();
const callData = onDrag.mock.calls[0][1];
expect(callData.deltaX).toBe(100);
expect(callData.deltaY).toBe(100);
});
it('should call onStop when mouse up', () => {
const onStop = vi.fn();
const { container } = render(
<DraggableCoreWrapper onStop={onStop}>
<div />
</DraggableCoreWrapper>
);
simulateDrag(container.firstChild, { from: { x: 0, y: 0 }, to: { x: 100, y: 100 } });
expect(onStop).toHaveBeenCalledTimes(1);
});
it('should provide correct data in callbacks', () => {
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 50, y: 50 });
moveDrag({ x: 150, y: 200 });
const [event, data] = onDrag.mock.calls[0];
expect(data.x).toBe(150);
expect(data.y).toBe(200);
expect(data.deltaX).toBe(100);
expect(data.deltaY).toBe(150);
expect(data.lastX).toBe(50);
expect(data.lastY).toBe(50);
expect(data.node).toBe(container.firstChild);
});
});
describe('disabled state', () => {
it('should not start dragging when disabled', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper disabled onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
expect(onStart).not.toHaveBeenCalled();
});
});
describe('cancellation', () => {
it('should cancel drag when onStart returns false', () => {
const onStart = vi.fn(() => false);
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper onStart={onStart} onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
expect(onStart).toHaveBeenCalled();
expect(onDrag).not.toHaveBeenCalled();
});
it('should stop drag when onDrag returns false', () => {
const onDrag = vi.fn(() => false);
const onStop = vi.fn();
const { container } = render(
<DraggableCoreWrapper onDrag={onDrag} onStop={onStop}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
expect(onDrag).toHaveBeenCalled();
expect(onStop).toHaveBeenCalled();
});
});
describe('handle prop', () => {
it('should only drag from handle', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper handle=".handle" onStart={onStart}>
<div>
<div className="handle">Handle</div>
<div className="content">Content</div>
</div>
</DraggableCoreWrapper>
);
// Click on content - should not start drag
startDrag(container.querySelector('.content'), { x: 0, y: 0 });
expect(onStart).not.toHaveBeenCalled();
// Click on handle - should start drag
startDrag(container.querySelector('.handle'), { x: 0, y: 0 });
expect(onStart).toHaveBeenCalled();
});
it('should work with nested elements in handle', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper handle=".handle" onStart={onStart}>
<div>
<div className="handle">
<span className="nested">Nested</span>
</div>
</div>
</DraggableCoreWrapper>
);
startDrag(container.querySelector('.nested'), { x: 0, y: 0 });
expect(onStart).toHaveBeenCalled();
});
});
describe('cancel prop', () => {
it('should not drag from cancel elements', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper cancel=".cancel" onStart={onStart}>
<div>
<div className="cancel">Cancel</div>
<div className="content">Content</div>
</div>
</DraggableCoreWrapper>
);
// Click on cancel - should not start drag
startDrag(container.querySelector('.cancel'), { x: 0, y: 0 });
expect(onStart).not.toHaveBeenCalled();
// Click on content - should start drag
startDrag(container.querySelector('.content'), { x: 0, y: 0 });
expect(onStart).toHaveBeenCalled();
});
});
describe('grid prop', () => {
it('should snap movement to grid', () => {
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper grid={[50, 50]} onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 30, y: 30 }); // Less than half grid, should snap to 50
expect(onDrag).toHaveBeenCalled();
const data = onDrag.mock.calls[0][1];
expect(data.x).toBe(50);
expect(data.y).toBe(50);
});
it('should not call onDrag if movement is less than grid', () => {
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper grid={[100, 100]} onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 20, y: 20 }); // Much less than half grid
// Should not be called because snapped delta is 0
expect(onDrag).not.toHaveBeenCalled();
});
});
describe('scale prop', () => {
it('should adjust position based on scale', () => {
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper scale={2} onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
const data = onDrag.mock.calls[0][1];
// With scale 2, 100px movement = 50 logical units
expect(data.deltaX).toBe(50);
expect(data.deltaY).toBe(50);
});
it('should work with scale < 1', () => {
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper scale={0.5} onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
const data = onDrag.mock.calls[0][1];
// With scale 0.5, 100px movement = 200 logical units
expect(data.deltaX).toBe(200);
expect(data.deltaY).toBe(200);
});
});
describe('allowAnyClick prop', () => {
it('should only respond to left click by default', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
// Right click (button 2)
container.firstChild.dispatchEvent(new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
button: 2,
clientX: 0,
clientY: 0,
}));
expect(onStart).not.toHaveBeenCalled();
});
it('should respond to any click when allowAnyClick is true', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper allowAnyClick onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
// Right click (button 2)
container.firstChild.dispatchEvent(new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
button: 2,
clientX: 0,
clientY: 0,
}));
expect(onStart).toHaveBeenCalled();
});
});
describe('nodeRef prop', () => {
it('should use nodeRef instead of findDOMNode', () => {
const onDrag = vi.fn();
function TestComponent() {
const nodeRef = useRef(null);
return (
<DraggableCore nodeRef={nodeRef} onDrag={onDrag}>
<div ref={nodeRef} data-testid="target" />
</DraggableCore>
);
}
const { getByTestId } = render(<TestComponent />);
const target = getByTestId('target');
startDrag(target, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
expect(onDrag).toHaveBeenCalled();
expect(onDrag.mock.calls[0][1].node).toBe(target);
});
it('should work with forwardRef components', () => {
const onDrag = vi.fn();
const CustomComponent = React.forwardRef((props, ref) => (
<div {...props} ref={ref}>Custom</div>
));
function TestComponent() {
const nodeRef = useRef(null);
return (
<DraggableCore nodeRef={nodeRef} onDrag={onDrag}>
<CustomComponent ref={nodeRef} data-testid="target" />
</DraggableCore>
);
}
const { getByTestId } = render(<TestComponent />);
const target = getByTestId('target');
startDrag(target, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
expect(onDrag).toHaveBeenCalled();
expect(onDrag.mock.calls[0][1].node.textContent).toBe('Custom');
});
});
describe('touch events', () => {
it('should handle touch start', () => {
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
container.firstChild.dispatchEvent(createTouchEvent('touchstart', { clientX: 0, clientY: 0 }));
expect(onStart).toHaveBeenCalled();
});
it('should call preventDefault on touchstart by default', () => {
const { container } = render(
<DraggableCoreWrapper>
<div />
</DraggableCoreWrapper>
);
const event = createTouchEvent('touchstart', { clientX: 0, clientY: 0 });
let prevented = false;
event.preventDefault = () => { prevented = true; };
container.firstChild.dispatchEvent(event);
expect(prevented).toBe(true);
});
it('should not call preventDefault when allowMobileScroll is true', () => {
const { container } = render(
<DraggableCoreWrapper allowMobileScroll>
<div />
</DraggableCoreWrapper>
);
const event = createTouchEvent('touchstart', { clientX: 0, clientY: 0 });
let prevented = false;
event.preventDefault = () => { prevented = true; };
container.firstChild.dispatchEvent(event);
expect(prevented).toBe(false);
});
});
describe('onMouseDown prop', () => {
it('should call onMouseDown callback', () => {
const onMouseDown = vi.fn();
const { container } = render(
<DraggableCoreWrapper onMouseDown={onMouseDown}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
expect(onMouseDown).toHaveBeenCalled();
});
it('should call onMouseDown even when disabled', () => {
const onMouseDown = vi.fn();
const onStart = vi.fn();
const { container } = render(
<DraggableCoreWrapper disabled onMouseDown={onMouseDown} onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
expect(onMouseDown).toHaveBeenCalled();
expect(onStart).not.toHaveBeenCalled();
});
});
describe('enableUserSelectHack prop', () => {
it('should add transparent selection class by default', () => {
const { container } = render(
<DraggableCoreWrapper>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
expect(document.body.classList.contains('react-draggable-transparent-selection')).toBe(true);
endDrag(container.firstChild, { x: 0, y: 0 });
// rAF mock immediately calls the callback
expect(document.body.classList.contains('react-draggable-transparent-selection')).toBe(false);
});
it('should not add class when enableUserSelectHack is false', () => {
const { container } = render(
<DraggableCoreWrapper enableUserSelectHack={false}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
expect(document.body.classList.contains('react-draggable-transparent-selection')).toBe(false);
});
it('should not add user-select class when onStart returns false', () => {
const onStart = vi.fn(() => false);
const { container } = render(
<DraggableCoreWrapper onStart={onStart}>
<div />
</DraggableCoreWrapper>
);
// Ensure class is not present before drag
expect(document.body.classList.contains('react-draggable-transparent-selection')).toBe(false);
startDrag(container.firstChild, { x: 0, y: 0 });
// onStart returned false, so user-select hack should not be applied
expect(onStart).toHaveBeenCalled();
expect(document.body.classList.contains('react-draggable-transparent-selection')).toBe(false);
});
});
describe('unmount safety', () => {
it('should track mounted state correctly', () => {
const coreRef = React.createRef();
render(
<DraggableCoreWrapper coreRef={coreRef}>
<div />
</DraggableCoreWrapper>
);
// Verify mounted is true after mount
expect(coreRef.current.mounted).toBe(true);
// Store reference before unmount since ref.current becomes null
const instance = coreRef.current;
cleanup();
// Verify mounted is false after unmount (using stored reference)
expect(instance.mounted).toBe(false);
});
it('should not continue drag if onStart returns false', () => {
const onStart = vi.fn(() => false);
const onDrag = vi.fn();
const { container } = render(
<DraggableCoreWrapper onStart={onStart} onDrag={onDrag}>
<div />
</DraggableCoreWrapper>
);
startDrag(container.firstChild, { x: 0, y: 0 });
moveDrag({ x: 100, y: 100 });
expect(onStart).toHaveBeenCalled();
// onDrag should not be called because onStart returned false
expect(onDrag).not.toHaveBeenCalled();
});
});
describe('touch events with handle', () => {
it('should call preventDefault on touchstart when using handle', () => {
const { container } = render(
<DraggableCoreWrapper handle=".handle">
<div>
<div className="handle">Handle</div>
</div>
</DraggableCoreWrapper>
);
const handle = container.querySelector('.handle');
const event = createTouchEvent('touchstart', { clientX: 0, clientY: 0 });
let prevented = false;
event.preventDefault = () => { prevented = true; };
handle.dispatchEvent(event);
expect(prevented).toBe(true);
});
it('should not call preventDefault on touchstart for cancel elements', () => {
const { container } = render(
<DraggableCoreWrapper cancel=".cancel">
<div>
<div className="cancel">Cancel</div>
<div className="content">Content</div>
</div>
</DraggableCoreWrapper>
);
const cancel = container.querySelector('.cancel');
const event = createTouchEvent('touchstart', { clientX: 0, clientY: 0 });
let prevented = false;
event.preventDefault = () => { prevented = true; };
cancel.dispatchEvent(event);
// Should not prevent default since drag was cancelled
expect(prevented).toBe(false);
});
});
describe('error handling', () => {
it('should throw error when no children provided', () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const nodeRef = React.createRef();
let threw = false;
try {
render(<DraggableCore nodeRef={nodeRef} />);
} catch (e) {
threw = true;
expect(e.message).toMatch(/React.Children.only|expected/i);
}
expect(threw).toBe(true);
errorSpy.mockRestore();
});
});
});
================================================
FILE: test/browser/browser.test.js
================================================
/**
* Browser-based tests using Puppeteer
* These tests require a real browser for proper coordinate calculations
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import puppeteer from 'puppeteer';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('Browser Tests', () => {
let browser;
let page;
beforeAll(async () => {
browser = await puppeteer.launch({
headless: true,
// Disable sandbox in CI environments (required for GitHub Actions runners)
args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [],
});
}, 30000);
afterAll(async () => {
if (browser) await browser.close();
});
beforeEach(async () => {
page = await browser.newPage();
// Load the test page via file protocol
const testHtmlPath = path.resolve(__dirname, 'test.html');
await page.goto(`file://${testHtmlPath}`);
// Wait for React/ReactDOM to be available
await page.waitForFunction(() => window.React && window.ReactDOM);
}, 30000);
afterEach(async () => {
if (page) await page.close();
});
describe('Dragging position', () => {
it('should update transform on drag', async () => {
// Render a basic draggable
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, { nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
// Get initial transform
const initialTransform = await page.$eval('#draggable-test', el => el.style.transform);
expect(initialTransform).toMatch(/translate\(0px,?\s*0px\)/);
// Simulate drag
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
// Check final transform
const finalTransform = await page.$eval('#draggable-test', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(100px,?\s*100px\)/);
}, 30000);
it('should honor x axis constraint', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, { axis: 'x', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
const finalTransform = await page.$eval('#draggable-test', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(100px,?\s*0px\)/);
}, 30000);
it('should honor y axis constraint', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, { axis: 'y', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
const finalTransform = await page.$eval('#draggable-test', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(0px,?\s*100px\)/);
}, 30000);
});
describe('Callbacks', () => {
it('should call onStop when drag ends', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
window.stopCalled = false;
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
onStop: () => { window.stopCalled = true; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
const stopCalled = await page.evaluate(() => window.stopCalled);
expect(stopCalled).toBe(true);
}, 30000);
});
describe('Bounds', () => {
it('should clip dragging to bounds object', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
bounds: { left: 0, right: 50, top: 0, bottom: 50 }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 200, box.y + 200);
await page.mouse.up();
const finalTransform = await page.$eval('#draggable-test', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(50px,?\s*50px\)/);
}, 30000);
it('should clip dragging to parent bounds', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement('div', {
id: 'parent',
style: {
width: '300px',
height: '300px',
position: 'relative',
background: '#ccc'
}
},
React.createElement(Draggable, { bounds: 'parent', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Try to drag far beyond parent bounds (300 - 100 = 200px max)
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 500, box.y + 500);
await page.mouse.up();
const finalTransform = await page.$eval('#draggable-test', el => el.style.transform);
// Should be clipped to 200px (parent width 300 - element width 100)
expect(finalTransform).toMatch(/translate\(200px,?\s*200px\)/);
}, 30000);
it('should clip to negative bounds', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
bounds: { left: -50, right: 50, top: -50, bottom: 50 }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Drag in negative direction
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x - 100, box.y - 100);
await page.mouse.up();
const finalTransform = await page.$eval('#draggable-test', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(-50px,?\s*-50px\)/);
}, 30000);
});
describe('Grid snapping', () => {
it('should snap movement to grid', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.lastPosition = null;
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
grid: [25, 25],
onDrag: (e, data) => { window.lastPosition = { x: data.x, y: data.y }; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Move 30px - should snap to 25px
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 80, box.y + 80);
await page.mouse.up();
const position = await page.evaluate(() => window.lastPosition);
expect(position.x).toBe(25);
expect(position.y).toBe(25);
}, 30000);
it('should not trigger onDrag when movement is less than grid', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.dragCallCount = 0;
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
grid: [50, 50],
onDrag: () => { window.dragCallCount++; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Move only 20px - less than half the grid size (25px)
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 70, box.y + 70);
await page.mouse.up();
const dragCallCount = await page.evaluate(() => window.dragCallCount);
// onDrag should not be called because movement didn't reach grid threshold
expect(dragCallCount).toBe(0);
}, 30000);
it('should snap to larger grid correctly', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.lastPosition = null;
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
grid: [100, 100],
onDrag: (e, data) => { window.lastPosition = { x: data.x, y: data.y }; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Move 150px - should snap to 200px (closest grid point rounding)
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 200, box.y + 200);
await page.mouse.up();
const position = await page.evaluate(() => window.lastPosition);
// At 150px movement, snaps to 200px (nearest grid point with rounding)
expect(position.x).toBe(200);
expect(position.y).toBe(200);
}, 30000);
});
describe('Scale support', () => {
it('should adjust position when scale is 2x', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.dragData = null;
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
scale: 2,
onDrag: (e, data) => { window.dragData = { x: data.x, y: data.y }; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
// Move 100px visually, should be 50px in draggable coords due to 2x scale
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
const dragData = await page.evaluate(() => window.dragData);
expect(dragData.x).toBe(50);
expect(dragData.y).toBe(50);
}, 30000);
});
describe('Handle and Cancel', () => {
it('should only drag from handle', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, { handle: '.handle', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '200px', height: '100px', background: 'blue' }
},
React.createElement('div', {
className: 'handle',
style: { width: '50px', height: '50px', background: 'red' }
}),
React.createElement('div', {
className: 'content',
style: { width: '50px', height: '50px', background: 'green' }
})
)
)
);
});
await page.waitForSelector('#draggable-test');
// Try dragging from content (should not work)
const content = await page.$('.content');
const contentBox = await content.boundingBox();
await page.mouse.move(contentBox.x + 25, contentBox.y + 25);
await page.mouse.down();
await page.mouse.move(contentBox.x + 125, contentBox.y + 125);
await page.mouse.up();
let transform = await page.$eval('#draggable-test', el => el.style.transform);
expect(transform).toMatch(/translate\(0px,?\s*0px\)/);
// Try dragging from handle (should work)
const handle = await page.$('.handle');
const handleBox = await handle.boundingBox();
await page.mouse.move(handleBox.x + 25, handleBox.y + 25);
await page.mouse.down();
await page.mouse.move(handleBox.x + 125, handleBox.y + 125);
await page.mouse.up();
transform = await page.$eval('#draggable-test', el => el.style.transform);
expect(transform).toMatch(/translate\(100px,?\s*100px\)/);
}, 30000);
it('should drag from deeply nested handle elements', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, { handle: '.handle', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '200px', height: '100px', background: 'blue' }
},
React.createElement('div', { className: 'handle' },
React.createElement('div', null,
React.createElement('span', null,
React.createElement('div', { className: 'deep', style: { width: '50px', height: '50px', background: 'red' } })
)
)
),
React.createElement('div', { className: 'content', style: { width: '50px', height: '50px', background: 'green' } })
)
)
);
});
await page.waitForSelector('#draggable-test');
// Drag from deeply nested element inside handle
const deep = await page.$('.deep');
const deepBox = await deep.boundingBox();
await page.mouse.move(deepBox.x + 25, deepBox.y + 25);
await page.mouse.down();
await page.mouse.move(deepBox.x + 125, deepBox.y + 125);
await page.mouse.up();
const transform = await page.$eval('#draggable-test', el => el.style.transform);
expect(transform).toMatch(/translate\(100px,?\s*100px\)/);
}, 30000);
it('should not drag from deeply nested cancel elements', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
ReactDOM.createRoot(root).render(
React.createElement(Draggable, { cancel: '.cancel', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '200px', height: '100px', background: 'blue' }
},
React.createElement('div', { className: 'cancel' },
React.createElement('div', null,
React.createElement('span', null,
React.createElement('div', { className: 'deep', style: { width: '50px', height: '50px', background: 'red' } })
)
)
),
React.createElement('div', { className: 'content', style: { width: '50px', height: '50px', background: 'green' } })
)
)
);
});
await page.waitForSelector('#draggable-test');
// Drag from deeply nested element inside cancel (should not work)
const deep = await page.$('.deep');
const deepBox = await deep.boundingBox();
await page.mouse.move(deepBox.x + 25, deepBox.y + 25);
await page.mouse.down();
await page.mouse.move(deepBox.x + 125, deepBox.y + 125);
await page.mouse.up();
const transform = await page.$eval('#draggable-test', el => el.style.transform);
expect(transform).toMatch(/translate\(0px,?\s*0px\)/);
}, 30000);
});
describe('Iframe support', () => {
it('should work correctly inside an iframe', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
// Create an iframe
const iframe = document.createElement('iframe');
iframe.id = 'test-iframe';
iframe.style.cssText = 'width: 500px; height: 500px; border: 1px solid black;';
root.appendChild(iframe);
// Wait for iframe to load and get its document
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// Write basic HTML structure into iframe
iframeDoc.open();
iframeDoc.write(`
<!DOCTYPE html>
<html>
<head><style>body { margin: 0; padding: 20px; }</style></head>
<body><div id="iframe-root"></div></body>
</html>
`);
iframeDoc.close();
// Copy React and ReactDOM to iframe window
iframe.contentWindow.React = React;
iframe.contentWindow.ReactDOM = ReactDOM;
// Render Draggable into iframe
const iframeRoot = iframeDoc.getElementById('iframe-root');
const ref = React.createRef();
ReactDOM.createRoot(iframeRoot).render(
React.createElement(Draggable, { nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'iframe-draggable',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
// Wait for draggable to render in iframe
await page.waitForFunction(() => {
const iframe = document.getElementById('test-iframe');
return iframe && iframe.contentDocument.getElementById('iframe-draggable');
});
// Get the iframe element
const iframeHandle = await page.$('#test-iframe');
const iframeBox = await iframeHandle.boundingBox();
// Get the draggable element inside iframe
const frame = await iframeHandle.contentFrame();
const draggable = await frame.$('#iframe-draggable');
const draggableBox = await draggable.boundingBox();
// Verify initial transform
const initialTransform = await frame.$eval('#iframe-draggable', el => el.style.transform);
expect(initialTransform).toMatch(/translate\(0px,?\s*0px\)/);
// Perform drag inside iframe
await page.mouse.move(draggableBox.x + 50, draggableBox.y + 50);
await page.mouse.down();
await page.mouse.move(draggableBox.x + 150, draggableBox.y + 150);
await page.mouse.up();
// Verify transform was updated
const finalTransform = await frame.$eval('#iframe-draggable', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(100px,?\s*100px\)/);
}, 30000);
it('should respect bounds inside an iframe', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
// Create an iframe
const iframe = document.createElement('iframe');
iframe.id = 'test-iframe-bounds';
iframe.style.cssText = 'width: 500px; height: 500px; border: 1px solid black;';
root.appendChild(iframe);
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write(`
<!DOCTYPE html>
<html>
<head><style>body { margin: 0; padding: 0; }</style></head>
<body>
<div id="iframe-root" style="position: relative; width: 300px; height: 300px; background: #ccc;"></div>
</body>
</html>
`);
iframeDoc.close();
iframe.contentWindow.React = React;
iframe.contentWindow.ReactDOM = ReactDOM;
const iframeRoot = iframeDoc.getElementById('iframe-root');
const ref = React.createRef();
ReactDOM.createRoot(iframeRoot).render(
React.createElement(Draggable, { bounds: 'parent', nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'iframe-draggable-bounds',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForFunction(() => {
const iframe = document.getElementById('test-iframe-bounds');
return iframe && iframe.contentDocument.getElementById('iframe-draggable-bounds');
});
const iframeHandle = await page.$('#test-iframe-bounds');
const frame = await iframeHandle.contentFrame();
const draggable = await frame.$('#iframe-draggable-bounds');
const draggableBox = await draggable.boundingBox();
// Try to drag beyond parent bounds
await page.mouse.move(draggableBox.x + 50, draggableBox.y + 50);
await page.mouse.down();
await page.mouse.move(draggableBox.x + 500, draggableBox.y + 500);
await page.mouse.up();
// Should be clipped to parent bounds (300 - 100 = 200 max)
const finalTransform = await frame.$eval('#iframe-draggable-bounds', el => el.style.transform);
expect(finalTransform).toMatch(/translate\(200px,?\s*200px\)/);
}, 30000);
});
describe('Scroll handling', () => {
it('should handle dragging in scrollable containers', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.dragData = null;
// Create a simple draggable that we can verify drag works
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
onDrag: (e, data) => { window.dragData = { x: data.x, y: data.y, deltaX: data.deltaX, deltaY: data.deltaY }; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Perform drag and verify position calculation
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
const dragData = await page.evaluate(() => window.dragData);
expect(dragData).not.toBeNull();
expect(dragData.deltaX).toBe(100);
expect(dragData.deltaY).toBe(100);
}, 30000);
});
describe('Shadow DOM support', () => {
it('should clip dragging to parent bounds in shadow DOM', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
window.dragData = null;
// Create a shadow host
const shadowHost = document.createElement('div');
shadowHost.id = 'shadow-host';
root.appendChild(shadowHost);
const shadowRoot = shadowHost.attachShadow({ mode: 'open' });
// Create container in shadow DOM
const container = document.createElement('div');
container.id = 'shadow-container';
container.style.cssText = 'position: relative; width: 200px; height: 200px; background: #ccc;';
shadowRoot.appendChild(container);
// Render Draggable into shadow DOM
const ref = React.createRef();
ReactDOM.createRoot(container).render(
React.createElement(Draggable, {
nodeRef: ref,
bounds: 'parent',
defaultPosition: { x: 50, y: 50 },
onDrag: (e, data) => { window.dragData = { x: data.x, y: data.y }; }
},
React.createElement('div', {
ref: ref,
id: 'shadow-draggable',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
// Wait for element in shadow DOM
await page.waitForFunction(() => {
const host = document.getElementById('shadow-host');
return host && host.shadowRoot && host.shadowRoot.getElementById('shadow-draggable');
});
// Get element from shadow DOM
const element = await page.evaluateHandle(() => {
const host = document.getElementById('shadow-host');
return host.shadowRoot.getElementById('shadow-draggable');
});
const box = await element.boundingBox();
// Try to drag beyond parent bounds
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 500, box.y + 500);
await page.mouse.up();
const dragData = await page.evaluate(() => window.dragData);
// Should be clipped to parent bounds (200 - 100 = 100 max)
expect(dragData.x).toBe(100);
expect(dragData.y).toBe(100);
}, 30000);
it('should clip dragging to selector bounds in shadow DOM', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
window.dragData = null;
// Create a shadow host
const shadowHost = document.createElement('div');
shadowHost.id = 'shadow-host-2';
root.appendChild(shadowHost);
const shadowRoot = shadowHost.attachShadow({ mode: 'open' });
// Create container with ID in shadow DOM
const container = document.createElement('div');
container.id = 'bounds-container';
container.style.cssText = 'position: relative; width: 200px; height: 200px; background: #ccc;';
shadowRoot.appendChild(container);
// Render Draggable into shadow DOM with selector bounds
const ref = React.createRef();
ReactDOM.createRoot(container).render(
React.createElement(Draggable, {
nodeRef: ref,
bounds: '#bounds-container',
defaultPosition: { x: 50, y: 50 },
onDrag: (e, data) => { window.dragData = { x: data.x, y: data.y }; }
},
React.createElement('div', {
ref: ref,
id: 'shadow-draggable-2',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
});
// Wait for element in shadow DOM
await page.waitForFunction(() => {
const host = document.getElementById('shadow-host-2');
return host && host.shadowRoot && host.shadowRoot.getElementById('shadow-draggable-2');
});
// Get element from shadow DOM
const element = await page.evaluateHandle(() => {
const host = document.getElementById('shadow-host-2');
return host.shadowRoot.getElementById('shadow-draggable-2');
});
const box = await element.boundingBox();
// Try to drag beyond bounds
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 500, box.y + 500);
await page.mouse.up();
const dragData = await page.evaluate(() => window.dragData);
// Should be clipped to bounds
expect(dragData.x).toBe(100);
expect(dragData.y).toBe(100);
}, 30000);
});
describe('Unmount safety', () => {
it('should not throw when unmounted during onStop callback', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
window.errorThrown = false;
window.originalError = window.onerror;
window.onerror = () => { window.errorThrown = true; };
function App() {
const [visible, setVisible] = React.useState(true);
const ref = React.useRef(null);
window.setVisible = setVisible;
if (!visible) return React.createElement('div', { id: 'unmounted' }, 'Unmounted');
return React.createElement(Draggable, {
nodeRef: ref,
onStop: () => { setVisible(false); }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
);
}
ReactDOM.createRoot(root).render(React.createElement(App));
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
// Perform drag that will unmount the component in onStop
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
// Verify component unmounted
await page.waitForSelector('#unmounted');
// Verify no error was thrown
const errorThrown = await page.evaluate(() => window.errorThrown);
expect(errorThrown).toBe(false);
// Cleanup
await page.evaluate(() => { window.onerror = window.originalError; });
}, 30000);
});
describe('Input focus preservation', () => {
it('should not defocus inputs when draggable unmounts', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
window.inputBlurred = false;
function App() {
const [showDraggable, setShowDraggable] = React.useState(true);
const ref = React.useRef(null);
window.setShowDraggable = setShowDraggable;
return React.createElement('div', null,
React.createElement('input', {
id: 'test-input',
type: 'text',
onBlur: () => { window.inputBlurred = true; }
}),
showDraggable && React.createElement(Draggable, { nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
);
}
ReactDOM.createRoot(root).render(React.createElement(App));
});
await page.waitForSelector('#test-input');
await page.waitForSelector('#draggable-test');
// Focus the input
await page.focus('#test-input');
await page.type('#test-input', 'hello');
// Verify input is focused
const isFocused = await page.evaluate(() =>
document.activeElement === document.getElementById('test-input')
);
expect(isFocused).toBe(true);
// Reset blur tracking
await page.evaluate(() => { window.inputBlurred = false; });
// Unmount the draggable while input is focused
await page.evaluate(() => { window.setShowDraggable(false); });
// Wait for draggable to be removed
await page.waitForFunction(() => !document.getElementById('draggable-test'));
// Verify input wasn't blurred by the unmount
const wasBlurred = await page.evaluate(() => window.inputBlurred);
expect(wasBlurred).toBe(false);
// Verify input is still focused
const stillFocused = await page.evaluate(() =>
document.activeElement === document.getElementById('test-input')
);
expect(stillFocused).toBe(true);
// Verify input value is preserved
const inputValue = await page.$eval('#test-input', el => el.value);
expect(inputValue).toBe('hello');
}, 30000);
it('should not steal focus from inputs when starting drag', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.inputBlurred = false;
ReactDOM.createRoot(root).render(
React.createElement('div', null,
React.createElement('input', {
id: 'test-input-drag',
type: 'text',
style: { marginBottom: '20px', display: 'block' },
onBlur: () => { window.inputBlurred = true; }
}),
React.createElement(Draggable, { nodeRef: ref },
React.createElement('div', {
ref: ref,
id: 'draggable-focus-test',
style: { width: '100px', height: '100px', background: 'blue' }
})
)
)
);
});
await page.waitForSelector('#test-input-drag');
await page.waitForSelector('#draggable-focus-test');
// Focus the input and type
await page.focus('#test-input-drag');
await page.type('#test-input-drag', 'test');
// Reset blur tracking
await page.evaluate(() => { window.inputBlurred = false; });
// Start dragging the draggable element (but don't click the input)
const element = await page.$('#draggable-focus-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 100);
await page.mouse.up();
// The input will blur because we clicked elsewhere (on the draggable)
// This is expected browser behavior - we're testing that the library
// doesn't cause unexpected blurs during its internal operations
const inputValue = await page.$eval('#test-input-drag', el => el.value);
expect(inputValue).toBe('test');
}, 30000);
});
describe('Offset calculations', () => {
it('should calculate drag with offset position correctly', async () => {
await page.evaluate(() => {
const { React, ReactDOM, Draggable } = window;
const root = document.getElementById('root');
const ref = React.createRef();
window.dragData = null;
ReactDOM.createRoot(root).render(
React.createElement(Draggable, {
nodeRef: ref,
onDrag: (e, data) => { window.dragData = { x: data.x, y: data.y, deltaX: data.deltaX, deltaY: data.deltaY }; }
},
React.createElement('div', {
ref: ref,
id: 'draggable-test',
style: { position: 'relative', top: '200px', left: '200px', width: '100px', height: '100px', background: 'blue' }
})
)
);
});
await page.waitForSelector('#draggable-test');
const element = await page.$('#draggable-test');
const box = await element.boundingBox();
await page.mouse.move(box.x + 50, box.y + 50);
await page.mouse.down();
await page.mouse.move(box.x + 150, box.y + 150);
await page.mouse.up();
const dragData = await page.evaluate(() => window.dragData);
// Should report delta of 100, not accounting for initial CSS position
expect(dragData.deltaX).toBe(100);
expect(dragData.deltaY).toBe(100);
}, 30000);
});
});
================================================
FILE: test/browser/test.html
================================================
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Draggable Browser Tests</title>
<style>
body { margin: 0; padding: 20px; }
#root { position: relative; }
</style>
</head>
<body>
<div id="root"></div>
<!-- Load React 19 from esm.sh CDN (React 19 removed UMD builds) -->
<script type="importmap">
{
"imports": {
"react": "https://esm.sh/react@19?dev",
"react-dom": "https://esm.sh/react-dom@19?dev",
"react-dom/client": "https://esm.sh/react-dom@19/client?dev"
}
}
</script>
<script type="module">
import React from 'react';
import ReactDOM from 'react-dom';
import * as ReactDOMClient from 'react-dom/client';
// Make React available globally for the Draggable bundle
window.React = React;
window.ReactDOM = { ...ReactDOM, ...ReactDOMClient };
// Dynamically load the built library (it expects React/ReactDOM as globals)
const script = document.createElement('script');
script.src = '../../build/web/react-draggable.min.js';
script.onload = () => {
// Make things available globally for tests
window.Draggable = ReactDraggable.default;
window.DraggableCore = ReactDraggable.DraggableCore;
};
document.body.appendChild(script);
</script>
</body>
</html>
================================================
FILE: test/setup.js
================================================
import { vi } from 'vitest';
import '@testing-library/dom';
// Mock requestAnimationFrame for consistent test behavior
global.requestAnimationFrame = vi.fn((callback) => {
callback();
return 0;
});
global.cancelAnimationFrame = vi.fn();
// Reset body margin like old tests did
const styleEl = document.createElement('style');
styleEl.textContent = 'body { margin: 0; }';
document.head.appendChild(styleEl);
================================================
FILE: test/testUtils.js
================================================
/**
* Test utilities for simulating drag events
*/
/**
* Create a MouseEvent with specified coordinates
*/
export function createMouseEvent(type, { clientX = 0, clientY = 0 } = {}) {
// Use the modern MouseEvent constructor without view (jsdom is strict about it)
return new MouseEvent(type, {
bubbles: true,
cancelable: true,
clientX,
clientY,
// Don't pass view - jsdom doesn't like it
});
}
/**
* Create a TouchEvent with specified coordinates
*/
export function createTouchEvent(type, { clientX = 0, clientY = 0, identifier = 0 } = {}) {
const touch = {
identifier,
clientX,
clientY,
target: document.body,
};
const touchEvent = new Event(type, { bubbles: true, cancelable: true });
touchEvent.targetTouches = type === 'touchend' ? [] : [touch];
touchEvent.changedTouches = [touch];
touchEvent.touches = type === 'touchend' ? [] : [touch];
return touchEvent;
}
/**
* Simulate a drag operation from one point to another
*/
export function simulateDrag(element, { from = { x: 0, y: 0 }, to = { x: 0, y: 0 } } = {}) {
// Mouse down at start position
element.dispatchEvent(createMouseEvent('mousedown', { clientX: from.x, clientY: from.y }));
// Mouse move to end position (dispatched on document)
document.dispatchEvent(createMouseEvent('mousemove', { clientX: to.x, clientY: to.y }));
// Mouse up at end position (dispatched on document where DraggableCore listens)
document.dispatchEvent(createMouseEvent('mouseup', { clientX: to.x, clientY: to.y }));
}
/**
* Start a drag operation (mousedown only)
*/
export function startDrag(element, { x = 0, y = 0 } = {}) {
element.dispatchEvent(createMouseEvent('mousedown', { clientX: x, clientY: y }));
}
/**
* Move during a drag operation (mousemove on document)
*/
export function moveDrag({ x = 0, y = 0 } = {}) {
document.dispatchEvent(createMouseEvent('mousemove', { clientX: x, clientY: y }));
}
/**
* End a drag operation (mouseup on document where DraggableCore listens)
*/
export function endDrag(element, { x = 0, y = 0 } = {}) {
// DraggableCore binds mouseup listener to ownerDocument, not the element
document.dispatchEvent(createMouseEvent('mouseup', { clientX: x, clientY: y }));
}
/**
* Simulate a touch drag operation
*/
export function simulateTouchDrag(element, { from = { x: 0, y: 0 }, to = { x: 0, y: 0 } } = {}) {
element.dispatchEvent(createTouchEvent('touchstart', { clientX: from.x, clientY: from.y }));
document.dispatchEvent(createTouchEvent('touchmove', { clientX: to.x, clientY: to.y }));
element.dispatchEvent(createTouchEvent('touchend', { clientX: to.x, clientY: to.y }));
}
/**
* Wait for the next tick
*/
export function nextTick() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
================================================
FILE: test/utils/domFns.test.js
================================================
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
matchesSelector,
matchesSelectorAndParentsTo,
addEvent,
removeEvent,
outerHeight,
outerWidth,
innerHeight,
innerWidth,
addClassName,
removeClassName,
getTranslation,
} from '../../lib/utils/domFns';
describe('domFns utilities', () => {
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
});
describe('matchesSelector', () => {
it('should match simple class selectors', () => {
const el = document.createElement('div');
el.className = 'foo bar';
expect(matchesSelector(el, '.foo')).toBe(true);
expect(matchesSelector(el, '.bar')).toBe(true);
expect(matchesSelector(el, '.baz')).toBe(false);
});
it('should match id selectors', () => {
const el = document.createElement('div');
el.id = 'test';
expect(matchesSelector(el, '#test')).toBe(true);
expect(matchesSelector(el, '#other')).toBe(false);
});
it('should match tag selectors', () => {
const div = document.createElement('div');
const span = document.createElement('span');
expect(matchesSelector(div, 'div')).toBe(true);
expect(matchesSelector(div, 'span')).toBe(false);
expect(matchesSelector(span, 'span')).toBe(true);
});
});
describe('matchesSelectorAndParentsTo', () => {
it('should match element itself', () => {
const el = document.createElement('div');
el.className = 'target';
container.appendChild(el);
expect(matchesSelectorAndParentsTo(el, '.target', container)).toBe(true);
});
it('should match parent elements', () => {
const parent = document.createElement('div');
parent.className = 'parent';
const child = document.createElement('span');
parent.appendChild(child);
container.appendChild(parent);
expect(matchesSelectorAndParentsTo(child, '.parent', container)).toBe(true);
});
it('should stop at baseNode', () => {
const outer = document.createElement('div');
outer.className = 'outer';
const inner = document.createElement('div');
const target = document.createElement('span');
inner.appendChild(target);
outer.appendChild(inner);
container.appendChild(outer);
// Should not match outer because inner is the baseNode
expect(matchesSelectorAndParentsTo(target, '.outer', inner)).toBe(false);
// But should match if container is baseNode
expect(matchesSelectorAndParentsTo(target, '.outer', container)).toBe(true);
});
it('should return false when no match', () => {
const el = document.createElement('div');
container.appendChild(el);
expect(matchesSelectorAndParentsTo(el, '.nonexistent', container)).toBe(false);
});
});
describe('addEvent / removeEvent', () => {
it('should add and remove event listeners', () => {
const handler = vi.fn();
const el = document.createElement('div');
addEvent(el, 'click', handler);
el.dispatchEvent(new Event('click', { bubbles: true }));
expect(handler).toHaveBeenCalledTimes(1);
removeEvent(el, 'click', handler);
el.dispatchEvent(new Event('click', { bubbles: true }));
expect(handler).toHaveBeenCalledTimes(1); // Still 1, not called again
});
it('should handle null elements gracefully', () => {
const handler = vi.fn();
expect(() => addEvent(null, 'click', handler)).not.toThrow();
expect(() => removeEvent(null, 'click', handler)).not.toThrow();
});
});
describe('outerHeight / outerWidth', () => {
it('should calculate outer dimensions including borders', () => {
const el = document.createElement('div');
el.style.width = '100px';
el.style.height = '100px';
el.style.borderWidth = '5px';
el.style.borderStyle = 'solid';
container.appendChild(el);
// In jsdom, getBoundingClientRect returns 0s, so we test the function exists
// Real dimension tests would need a real browser
expect(typeof outerHeight(el)).toBe('number');
expect(typeof outerWidth(el)).toBe('number');
});
});
describe('innerHeight / innerWidth', () => {
it('should calculate inner dimensions excluding padding', () => {
const el = document.createElement('div');
el.style.width = '100px';
el.style.height = '100px';
el.style.padding = '10px';
container.appendChild(el);
expect(typeof innerHeight(el)).toBe('number');
expect(typeof innerWidth(el)).toBe('number');
});
});
describe('addClassName / removeClassName', () => {
it('should add class names', () => {
const el = document.createElement('div');
addClassName(el, 'foo');
expect(el.classList.contains('foo')).toBe(true);
});
it('should not duplicate class names', () => {
const el = document.createElement('div');
addClassName(el, 'foo');
addClassName(el, 'foo');
expect(el.className).toBe('foo');
});
it('should remove class names', () => {
const el = document.createElement('div');
el.className = 'foo bar baz';
removeClassName(el, 'bar');
expect(el.classList.contains('foo')).toBe(true);
expect(el.classList.contains('bar')).toBe(false);
expect(el.classList.contains('baz')).toBe(true);
});
it('should handle removing non-existent classes', () => {
const el = document.createElement('div');
el.className = 'foo';
expect(() => removeClassName(el, 'bar')).not.toThrow();
expect(el.className).toBe('foo');
});
});
describe('getTranslation', () => {
it('should create translate string with px suffix', () => {
const result = getTranslation({ x: 100, y: 200 }, null, 'px');
expect(result).toBe('translate(100px,200px)');
});
it('should create translate string without suffix (for SVG)', () => {
const result = getTranslation({ x: 100, y: 200 }, null, '');
expect(result).toBe('translate(100,200)');
});
it('should include position offset when provided', () => {
const result = getTranslation({ x: 100, y: 200 }, { x: 10, y: 20 }, 'px');
expect(result).toBe('translate(10px, 20px)translate(100px,200px)');
});
it('should handle percentage offsets', () => {
const result = getTranslation({ x: 100, y: 200 }, { x: '10%', y: '20%' }, 'px');
expect(result).toBe('translate(10%, 20%)translate(100px,200px)');
});
});
});
================================================
FILE: test/utils/getPrefix.test.js
================================================
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { getPrefix, browserPrefixToKey, browserPrefixToStyle } from '../../lib/utils/getPrefix';
describe('getPrefix utilities', () => {
describe('browserPrefixToKey', () => {
it('should return prop unchanged when no prefix', () => {
expect(browserPrefixToKey('transform', '')).toBe('transform');
});
it('should prefix and capitalize for Webkit', () => {
expect(browserPrefixToKey('transform', 'Webkit')).toBe('WebkitTransform');
});
it('should prefix and capitalize for Moz', () => {
expect(browserPrefixToKey('transform', 'Moz')).toBe('MozTransform');
});
it('should handle kebab-case properties', () => {
expect(browserPrefixToKey('user-select', 'Webkit')).toBe('WebkitUserSelect');
});
it('should handle multi-hyphen properties', () => {
expect(browserPrefixToKey('border-top-left-radius', 'Webkit')).toBe('WebkitBorderTopLeftRadius');
});
});
describe('browserPrefixToStyle', () => {
it('should return prop unchanged when no prefix', () => {
expect(browserPrefixToStyle('transform', '')).toBe('transform');
});
it('should add CSS prefix for Webkit', () => {
expect(browserPrefixToStyle('transform', 'W
gitextract_6qqp8t9w/ ├── .babelrc.js ├── .browserslistrc ├── .eslintrc ├── .flowconfig ├── .github/ │ └── workflows/ │ ├── ci.yml │ └── gh-pages.yml ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CLAUDE.md ├── LICENSE ├── Makefile ├── README.md ├── appveyor.yml ├── eslint.config.mjs ├── example/ │ ├── example-styles.css │ ├── example.js │ └── index.html ├── lib/ │ ├── Draggable.js │ ├── DraggableCore.js │ ├── cjs.js │ └── utils/ │ ├── domFns.js │ ├── getPrefix.js │ ├── log.js │ ├── positionFns.js │ ├── shims.js │ └── types.js ├── package.json ├── test/ │ ├── Draggable.test.jsx │ ├── DraggableCore.test.jsx │ ├── browser/ │ │ ├── browser.test.js │ │ └── test.html │ ├── setup.js │ ├── testUtils.js │ └── utils/ │ ├── domFns.test.js │ ├── getPrefix.test.js │ ├── positionFns.test.js │ └── shims.test.js ├── typings/ │ ├── index.d.ts │ ├── test.tsx │ └── tsconfig.json ├── vitest.browser.config.js ├── vitest.config.js └── webpack.config.js
SYMBOL INDEX (68 symbols across 15 files)
FILE: example/example.js
class App (line 3) | class App extends React.Component {
method render (line 73) | render() {
class RemWrapper (line 216) | class RemWrapper extends React.Component {
method translateTransformToRem (line 226) | translateTransformToRem(transform, remBaseline = 16) {
method render (line 237) | render() {
FILE: lib/Draggable.js
class Draggable (line 46) | class Draggable extends React.Component<DraggableProps, DraggableState> {
method if (line 184) | if (
method if (line 223) | if (props.position && !(props.onDrag || props.onStop)) {
FILE: lib/DraggableCore.js
class DraggableCore (line 72) | class DraggableCore extends React.Component<DraggableCoreProps> {
method if (line 114) | if (props[propName] && props[propName].nodeType !== 1) {
method if (line 251) | if (thisNode) {
FILE: lib/utils/domFns.js
function matchesSelector (line 8) | function matchesSelector(el: Node, selector: string): boolean {
function matchesSelectorAndParentsTo (line 31) | function matchesSelectorAndParentsTo(el: Node, selector: string, baseNod...
function outerHeight (line 71) | function outerHeight(node: HTMLElement): number {
function outerWidth (line 81) | function outerWidth(node: HTMLElement): number {
function innerHeight (line 90) | function innerHeight(node: HTMLElement): number {
function innerWidth (line 98) | function innerWidth(node: HTMLElement): number {
function offsetXYFromParent (line 111) | function offsetXYFromParent(evt: EventWithOffset, offsetParent: HTMLElem...
function createCSSTransform (line 121) | function createCSSTransform(controlPos: ControlPosition, positionOffset:...
function createSVGTransform (line 126) | function createSVGTransform(controlPos: ControlPosition, positionOffset:...
function getTranslation (line 130) | function getTranslation({x, y}: ControlPosition, positionOffset: Positio...
function removeUserSelectStyles (line 180) | function removeUserSelectStyles(doc: ?Document) {
function addClassName (line 201) | function addClassName(el: HTMLElement, className: string) {
function removeClassName (line 211) | function removeClassName(el: HTMLElement, className: string) {
FILE: lib/utils/getPrefix.js
function getPrefix (line 3) | function getPrefix(prop: string='transform'): string {
function browserPrefixToKey (line 22) | function browserPrefixToKey(prop: string, prefix: string): string {
function browserPrefixToStyle (line 26) | function browserPrefixToStyle(prop: string, prefix: string): string {
function kebabToTitleCase (line 30) | function kebabToTitleCase(str: string): string {
FILE: lib/utils/log.js
function log (line 3) | function log(...args: any) {
FILE: lib/utils/positionFns.js
function canDragX (line 67) | function canDragX(draggable: Draggable): boolean {
function canDragY (line 71) | function canDragY(draggable: Draggable): boolean {
function createCoreData (line 86) | function createCoreData(draggable: DraggableCore, x: number, y: number):...
function createDraggableData (line 110) | function createDraggableData(draggable: Draggable, coreData: DraggableDa...
function cloneBounds (line 124) | function cloneBounds(bounds: Bounds): Bounds {
FILE: lib/utils/shims.js
function findInArray (line 3) | function findInArray(array: Array<any> | TouchList, callback: Function):...
function int (line 18) | function int(a: string): number {
FILE: lib/utils/types.js
class SVGElement (line 21) | class SVGElement extends HTMLElement {
class TouchEvent2 (line 25) | class TouchEvent2 extends TouchEvent {
FILE: test/Draggable.test.jsx
function DraggableWrapper (line 8) | function DraggableWrapper({ children, draggableRef, ...props }) {
function DraggableCorWrapper (line 17) | function DraggableCorWrapper({ children, coreRef, ...props }) {
function ControlledTest (line 301) | function ControlledTest() {
FILE: test/DraggableCore.test.jsx
function DraggableCoreWrapper (line 8) | function DraggableCoreWrapper({ children, coreRef, ...props }) {
function TestComponent (line 343) | function TestComponent() {
function TestComponent (line 369) | function TestComponent() {
FILE: test/browser/browser.test.js
function App (line 907) | function App() {
function App (line 960) | function App() {
FILE: test/testUtils.js
function createMouseEvent (line 8) | function createMouseEvent(type, { clientX = 0, clientY = 0 } = {}) {
function createTouchEvent (line 22) | function createTouchEvent(type, { clientX = 0, clientY = 0, identifier =...
function simulateDrag (line 41) | function simulateDrag(element, { from = { x: 0, y: 0 }, to = { x: 0, y: ...
function startDrag (line 55) | function startDrag(element, { x = 0, y = 0 } = {}) {
function moveDrag (line 62) | function moveDrag({ x = 0, y = 0 } = {}) {
function endDrag (line 69) | function endDrag(element, { x = 0, y = 0 } = {}) {
function simulateTouchDrag (line 77) | function simulateTouchDrag(element, { from = { x: 0, y: 0 }, to = { x: 0...
function nextTick (line 86) | function nextTick() {
FILE: typings/index.d.ts
type DraggableBounds (line 3) | interface DraggableBounds {
type DraggableProps (line 10) | interface DraggableProps extends DraggableCoreProps {
type DraggableEvent (line 21) | type DraggableEvent = React.MouseEvent<HTMLElement | SVGElement>
type DraggableEventHandler (line 26) | type DraggableEventHandler = (
type DraggableData (line 31) | interface DraggableData {
type ControlPosition (line 38) | type ControlPosition = {x: number, y: number};
type PositionOffsetControlPosition (line 40) | type PositionOffsetControlPosition = {x: number|string, y: number|string};
type DraggableCoreProps (line 42) | interface DraggableCoreProps {
class Draggable (line 60) | class Draggable extends React.Component<Partial<DraggableProps>, {}> {
class DraggableCore (line 64) | class DraggableCore extends React.Component<Partial<DraggableCoreProps>,...
FILE: typings/test.tsx
function handleStart (line 8) | function handleStart() {}
function handleDrag (line 9) | function handleDrag() {}
function handleStop (line 10) | function handleStop() {}
function handleMouseDown (line 11) | function handleMouseDown() {}
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (223K chars).
[
{
"path": ".babelrc.js",
"chars": 352,
"preview": "'use strict';\n\nmodule.exports = {\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n targets: \"> 0.25%, not"
},
{
"path": ".browserslistrc",
"chars": 22,
"preview": "> 0.25%\nie 11\nnot dead"
},
{
"path": ".eslintrc",
"chars": 678,
"preview": "{\n \"parser\": \"@babel/eslint-parser\",\n \"extends\": \"eslint:recommended\",\n \"plugins\": [\n \"react\"\n ],\n \"ignorePatter"
},
{
"path": ".flowconfig",
"chars": 198,
"preview": "[ignore]\n<PROJECT_ROOT>/node_modules/webpack-cli.*\n<PROJECT_ROOT>/node_modules/.*malformed_package_json.*\n\n[include]\nlib"
},
{
"path": ".github/workflows/ci.yml",
"chars": 2119,
"preview": "name: CI\n\non:\n push:\n branches: [master]\n pull_request:\n branches: [master]\n\njobs:\n lint:\n runs-on: ubuntu-l"
},
{
"path": ".github/workflows/gh-pages.yml",
"chars": 588,
"preview": "name: Build and Deploy to GitHub Pages\npermissions:\n contents: write\non:\n push:\n tags:\n - \"*\"\n workflow_dispa"
},
{
"path": ".gitignore",
"chars": 58,
"preview": ".idea\n*.iml\nnode_modules/\nbuild/\nexample/build/\ncoverage/\n"
},
{
"path": ".travis.yml",
"chars": 234,
"preview": "language: node_js\nnode_js:\n - \"10\"\n - \"12\"\n - \"node\" # latest\ncache: yarn\nenv:\n - MOZ_HEADLESS=1\naddons:\n firefox: "
},
{
"path": "CHANGELOG.md",
"chars": 23304,
"preview": "# Changelog\n\n### 4.5.0 (Jun 25, 2025)\n\n- Internal: Update clsx version (#754)\n- Fix: bounds=\"selector\" functionality whe"
},
{
"path": "CLAUDE.md",
"chars": 3942,
"preview": "# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## "
},
{
"path": "LICENSE",
"chars": 1111,
"preview": "(MIT License)\n\nCopyright (c) 2014-2016 Matt Zabriskie. All rights reserved.\n \nPermission is hereby granted, free of char"
},
{
"path": "Makefile",
"chars": 1624,
"preview": "# Mostly lifted from https://andreypopp.com/posts/2013-05-16-makefile-recipes-for-node-js.html\n# Thanks @andreypopp\n\n# M"
},
{
"path": "README.md",
"chars": 7517,
"preview": "# React-Draggable\n\n[](http"
},
{
"path": "appveyor.yml",
"chars": 332,
"preview": "# https://www.appveyor.com/docs/appveyor-yml/\n\nenvironment:\n matrix:\n - node_version: \"12\"\n - node_version: \"10\"\n"
},
{
"path": "eslint.config.mjs",
"chars": 1465,
"preview": "import { defineConfig, globalIgnores } from \"eslint/config\";\nimport react from \"eslint-plugin-react\";\nimport globals fro"
},
{
"path": "example/example-styles.css",
"chars": 7467,
"preview": "/* === CYBERPUNK THEME === */\n@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&fami"
},
{
"path": "example/example.js",
"chars": 9496,
"preview": "const {ReactDraggable: Draggable, React, ReactDOM} = window;\n\nclass App extends React.Component {\n state = {\n active"
},
{
"path": "example/index.html",
"chars": 1122,
"preview": "<!doctype html>\n<html>\n<head>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-sca"
},
{
"path": "lib/Draggable.js",
"chars": 12835,
"preview": "// @flow\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport ReactDOM from 'react-dom';\nimport { "
},
{
"path": "lib/DraggableCore.js",
"chars": 16385,
"preview": "// @flow\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport ReactDOM from 'react-dom';\nimport {m"
},
{
"path": "lib/cjs.js",
"chars": 459,
"preview": "const {default: Draggable, DraggableCore} = require('./Draggable');\n\n// Previous versions of this lib exported <Draggabl"
},
{
"path": "lib/utils/domFns.js",
"chars": 8024,
"preview": "// @flow\nimport {findInArray, isFunction, int} from './shims';\nimport browserPrefix, {browserPrefixToKey} from './getPre"
},
{
"path": "lib/utils/getPrefix.js",
"chars": 1539,
"preview": "// @flow\nconst prefixes = ['Moz', 'Webkit', 'O', 'ms'];\nexport function getPrefix(prop: string='transform'): string {\n "
},
{
"path": "lib/utils/log.js",
"chars": 136,
"preview": "// @flow\n/*eslint no-console:0*/\nexport default function log(...args: any) {\n if (process.env.DRAGGABLE_DEBUG) console."
},
{
"path": "lib/utils/positionFns.js",
"chars": 5329,
"preview": "// @flow\nimport {isNum, int} from './shims';\nimport {getTouch, innerWidth, innerHeight, offsetXYFromParent, outerWidth, "
},
{
"path": "lib/utils/shims.js",
"chars": 914,
"preview": "// @flow\n// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc\nexport function findInArray(array: Array<"
},
{
"path": "lib/utils/types.js",
"chars": 829,
"preview": "// @flow\n\n// eslint-disable-next-line no-use-before-define\nexport type DraggableEventHandler = (e: MouseEvent, data: Dra"
},
{
"path": "package.json",
"chars": 2912,
"preview": "{\n \"name\": \"react-draggable\",\n \"version\": \"4.5.0\",\n \"description\": \"React draggable component\",\n \"main\": \"build/cjs/"
},
{
"path": "test/Draggable.test.jsx",
"chars": 13675,
"preview": "import React, { useRef, useState } from 'react';\nimport { describe, it, expect, vi, afterEach } from 'vitest';\nimport { "
},
{
"path": "test/DraggableCore.test.jsx",
"chars": 18641,
"preview": "import React, { useRef } from 'react';\nimport { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport "
},
{
"path": "test/browser/browser.test.js",
"chars": 39781,
"preview": "/**\n * Browser-based tests using Puppeteer\n * These tests require a real browser for proper coordinate calculations\n */\n"
},
{
"path": "test/browser/test.html",
"chars": 1309,
"preview": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>React Draggable Browser Tests</title>\n <style>\n body"
},
{
"path": "test/setup.js",
"chars": 414,
"preview": "import { vi } from 'vitest';\nimport '@testing-library/dom';\n\n// Mock requestAnimationFrame for consistent test behavior\n"
},
{
"path": "test/testUtils.js",
"chars": 2786,
"preview": "/**\n * Test utilities for simulating drag events\n */\n\n/**\n * Create a MouseEvent with specified coordinates\n */\nexport f"
},
{
"path": "test/utils/domFns.test.js",
"chars": 6651,
"preview": "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport {\n matchesSelector,\n matchesSelectorA"
},
{
"path": "test/utils/getPrefix.test.js",
"chars": 3479,
"preview": "import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport { getPrefix, browserPrefixToKey, browse"
},
{
"path": "test/utils/positionFns.test.js",
"chars": 5350,
"preview": "import { describe, it, expect } from 'vitest';\nimport { snapToGrid, canDragX, canDragY, createCoreData, createDraggableD"
},
{
"path": "test/utils/shims.test.js",
"chars": 3694,
"preview": "import { describe, it, expect } from 'vitest';\nimport { findInArray, isFunction, isNum, int, dontSetMe } from '../../lib"
},
{
"path": "typings/index.d.ts",
"chars": 1768,
"preview": "import * as React from 'react';\n\nexport interface DraggableBounds {\n left?: number\n right?: number\n top?: number\n bo"
},
{
"path": "typings/test.tsx",
"chars": 1801,
"preview": "import * as React from 'react';\nimport { createRoot } from 'react-dom/client';\nimport Draggable, {DraggableCore} from 'r"
},
{
"path": "typings/tsconfig.json",
"chars": 260,
"preview": "{\n \"compilerOptions\": {\n \"noEmit\": true,\n \"jsx\": \"preserve\",\n \"strict\": true,\n \"moduleResolution\": \"node\",\n"
},
{
"path": "vitest.browser.config.js",
"chars": 188,
"preview": "import { defineConfig } from 'vitest/config';\n\nexport default defineConfig({\n test: {\n include: ['test/browser/**/*."
},
{
"path": "vitest.config.js",
"chars": 973,
"preview": "import { defineConfig } from 'vitest/config';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n "
},
{
"path": "webpack.config.js",
"chars": 1747,
"preview": "const path = require('path');\nconst webpack = require('webpack');\n\n// Builds web module. Only really used in example cod"
}
]
About this extraction
This page contains the full source code of the react-grid-layout/react-draggable GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (208.5 KB), approximately 55.9k tokens, and a symbol index with 68 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.