Repository: svgdotjs/svg.draggable.js
Branch: master
Commit: 94447deeb00c
Files: 11
Total size: 14.6 KB
Directory structure:
gitextract___cug_mi/
├── .eslintrc.json
├── .gitignore
├── .prettierrc.json
├── LICENSE
├── README.md
├── manual-test.html
├── package.json
├── src/
│ └── svg.draggable.js
├── svg.draggable.js.d.cts
├── svg.draggable.js.d.ts
└── vite.config.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintrc.json
================================================
{
"env": {
"browser": true,
"es6": true
},
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
// "plugins": ["prettier"],
"parserOptions": {
"sourceType": "module"
},
"ignorePatterns": ["node_modules/", "dist/"]
}
================================================
FILE: .gitignore
================================================
.DS_Store
.idea
.vscode/
node_modules/
dist
================================================
FILE: .prettierrc.json
================================================
{
"trailingComma": "all",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2018 Ulrich-Matthias
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: README.md
================================================
# svg.draggable.js
A plugin for the [svgdotjs.github.io](https://svgdotjs.github.io/) library to make elements draggable.
svg.draggable.js is licensed under the terms of the MIT License.
## Usage
Install the plugin:
```sh
npm install @svgdotjs/svg.js @svgdotjs/svg.draggable.js
```
Include this plugin after including the svg.js library in your html document.
```html
<script src="node_modules/@svgdotjs/svg.js/dist/svg.js"></script>
<script src="node_modules/@svgdotjs/svg.draggable.js/dist/svg.draggable.js"></script>
```
Or for esm just require it:
```js
import { SVG } from '@svgdotjs/svg.js'
import '@svgdotjs/svg.draggable.js'
```
To make an element draggable just call `draggable()` on the element
```javascript
var draw = SVG().addTo('#canvas').size(400, 400)
var rect = draw.rect(100, 100)
rect.draggable()
```
Yes indeed, that's it! Now the `rect` is draggable.
## Events
The Plugin fires 4 different events
- beforedrag (cancelable)
- dragstart
- dragmove (cancelable)
- dragend
You can bind/unbind listeners to this events:
```javascript
// bind
rect.on('dragstart.namespace', function (event) {
// event.detail.event hold the given data explained below
// this == rect
})
// unbind
rect.off('dragstart.namespace')
```
### event.detail
`beforedrag`, `dragstart`, `dragmove` and `dragend` gives you the mouse / touch `event` and the `handler` which calculates the drag. The `dragmove` event also gives you the `dx` and `dy` values for your convenience.
Except for `beforedrag` the events also give you `detail.box` which holds the initial or new bbox of the element before or after the drag.
You can use this property to implement custom drag behavior as seen below.
Please note that the bounding box is not what you would expect for nested svgs because those calculate their bbox based on their content and not their x, y, width and height values. Therefore stuff like constraints needs to be implemented a bit differently.
### Cancelable Events
You can prevent the default action of `beforedrag` and `dragmove` with a call to `event.preventDefault()` in the callback function.
The shape won't be dragged in this case. That is helpfull if you want to implement your own drag handling.
```javascript
rect.draggable().on('beforedrag', (e) => {
e.preventDefault()
// no other events are bound
// drag was completely prevented
})
rect.draggable().on('dragmove', (e) => {
e.preventDefault()
e.detail.handler.move(100, 200)
// events are still bound e.g. dragend will fire anyway
})
```
### Custom Drag Behavior
#### Constraints
```js
// Some constraints (x, y, width, height)
const constraints = new SVG.Box(100, 100, 400, 400)
rect.on('dragmove.namespace', (e) => {
const { handler, box } = e.detail
e.preventDefault()
let { x, y } = box
// In case your dragged element is a nested element,
// you are better off using the rbox() instead of bbox()
if (x < constraints.x) {
x = constraints.x
}
if (y < constraints.y) {
y = constraints.y
}
if (box.x2 > constraints.x2) {
x = constraints.x2 - box.w
}
if (box.y2 > constraints.y2) {
y = constraints.y2 - box.h
}
handler.move(x - (x % 50), y - (y % 50))
})
```
#### Snap to grid
```js
rect.on('dragmove.namespace', (e) => {
const { handler, box } = e.detail
e.preventDefault()
handler.move(box.x - (box.x % 50), box.y - (box.y % 50))
})
```
## Remove
The draggable functionality can be removed calling draggable again with false as argument:
```javascript
rect.draggable(false)
```
## Restrictions
- If your root-svg is transformed this plugin won't work properly in Firefox. Viewbox however is not affected.
## Dependencies
This module requires svg.js >= v3.0.10
================================================
FILE: manual-test.html
================================================
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>svg.js</title>
<style type="text/css">
html,
body,
#drawing {
width: 100%;
height: 100%;
margin: 0;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="drawing"></div>
<script src="https://unpkg.com/@svgdotjs/svg.js"></script>
<script src="dist/svg.draggable.js"></script>
<script>
var e,
constrainingShape,
ghostShape,
draw = SVG()
.addTo('#drawing')
.size('100%', '400')
.attr({ 'font-size': 10 })
.fill('#f06')
/* plain draggable */
draw
.rect(100, 100)
.center(150, 150)
.draggable()
draw.plain('just plain draggable').center(150, 210)
/* grouped draggable */
var g = draw.group().draggable()
g.rect(100, 100).center(400, 150)
g.plain('grouped draggable').center(400, 210)
/* constrained with object */
constrainedWithObject = draw
.rect(100, 100)
.center(650, 150)
.draggable()
.on('dragstart', function () {
ghostShape = draw.put(constrainedWithObject.clone().opacity(0.2))
constrainingShape = draw
.rect(400, 350)
.move(400, 50)
.fill('none')
.stroke('#0fa')
})
.on('dragmove', e => {
e.preventDefault()
const { handler, box } = e.detail
let { x, y } = box
const constraints = constrainingShape.bbox()
if (x < constraints.x) {
x = constraints.x
}
if (y < constraints.y) {
y = constraints.y
}
if (box.x2 > constraints.x2) {
x = constraints.x2 - box.w
}
if (box.y2 > constraints.y2) {
y = constraints.y2 - box.h
}
handler.move(x, y)
ghostShape.animate(300, '>').move(x, y)
})
.on('dragend', function () {
constrainingShape.remove()
ghostShape.remove()
})
draw.plain('constrained with object and ghost').center(650, 210)
/* constraind with function */
// Some constraints (x, y, width, height)
const constraints = new SVG.Box(750, 0, 300, 300)
draw
.rect(100, 100)
.center(900, 150)
.draggable()
.on('dragmove', e => {
const { handler, box } = e.detail
e.preventDefault()
let { x, y } = box
// In case your dragged element is a nested element,
// you are better off using the rbox() instead of bbox()
if (x < constraints.x) {
x = constraints.x
}
if (y < constraints.y) {
y = constraints.y
}
if (box.x2 > constraints.x2) {
x = constraints.x2 - box.w
}
if (box.y2 > constraints.y2) {
y = constraints.y2 - box.h
}
handler.move(x, y)
})
draw.plain('constraint with function').center(900, 210)
/* group with multiple levels of draggables (dragging a part doesn't drag the group) */
var g2 = draw.group().draggable()
for (var i = 0; i < 4; i++) {
var cx = i & 1 ? -25 : 25
var cy = i & 2 ? -25 : 25
g2.rect(50, 50)
.center(cx, cy)
.draggable()
}
g2.plain('grouped with multiple levels of draggable').center(0, 70)
g2.move(1150, 150)
</script>
</body>
</html>
================================================
FILE: package.json
================================================
{
"name": "@svgdotjs/svg.draggable.js",
"version": "3.0.6",
"description": "An extension for svg.js which allows to drag elements with your mouse",
"type": "module",
"main": "dist/svg.draggable.js",
"module": "src/svg.draggable.js",
"exports": {
".": {
"import": {
"types": "./svg.draggable.js.d.ts",
"default": "./src/svg.draggable.js"
},
"require": {
"types": "./svg.draggable.js.d.cts",
"default": "./src/svg.draggable.js"
},
"browser": {
"types": "./svg.draggable.js.d.ts",
"default": "./src/svg.draggable.js"
}
}
},
"unpkg": "dist/svg.draggable.js",
"jsdelivr": "dist/svg.draggable.js",
"files": [
"/dist",
"/src",
"/svg.draggable.js.d.ts",
"/svg.draggable.js.d.cts"
],
"keywords": [
"svg.js",
"draggable",
"mouse"
],
"bugs": "https://github.com/svgdotjs/svg.draggable.js/issues",
"license": "MIT",
"typings": "./svg.draggable.js.d.ts",
"author": {
"name": "Wout Fierens"
},
"contributors": [
{
"name": "Wout Fierens"
},
{
"name": "Ulrich-Matthias Schäfer"
}
],
"homepage": "https://github.com/svgdotjs/svg.draggable.js",
"repository": {
"type": "git",
"url": "git+https://github.com/svgdotjs/svg.draggable.js.git"
},
"scripts": {
"build": "npm run fix && vite build",
"fix": "npx eslint --fix",
"prepublishOnly": "rm -rf ./dist && npm run build"
},
"devDependencies": {
"eslint": "^8.36.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-config-prettier": "^8.8.0",
"prettier": "^2.8.5",
"typescript": "^5.0.2",
"vite": "^4.2.1"
},
"peerDependencies": {
"@svgdotjs/svg.js": "^3.2.4"
}
}
================================================
FILE: src/svg.draggable.js
================================================
import { Box, Element, G, extend, off, on } from '@svgdotjs/svg.js'
const getCoordsFromEvent = (ev) => {
if (ev.changedTouches) {
ev = ev.changedTouches[0]
}
return { x: ev.clientX, y: ev.clientY }
}
// Creates handler, saves it
class DragHandler {
constructor(el) {
el.remember('_draggable', this)
this.el = el
this.drag = this.drag.bind(this)
this.startDrag = this.startDrag.bind(this)
this.endDrag = this.endDrag.bind(this)
}
// Enables or disabled drag based on input
init(enabled) {
if (enabled) {
this.el.on('mousedown.drag', this.startDrag)
this.el.on('touchstart.drag', this.startDrag, { passive: false })
} else {
this.el.off('mousedown.drag')
this.el.off('touchstart.drag')
}
}
// Start dragging
startDrag(ev) {
const isMouse = !ev.type.indexOf('mouse')
// Check for left button
if (isMouse && ev.which !== 1 && ev.buttons !== 0) {
return
}
// Fire beforedrag event
if (
this.el.dispatch('beforedrag', { event: ev, handler: this })
.defaultPrevented
) {
return
}
// Prevent browser drag behavior as soon as possible
ev.preventDefault()
// Prevent propagation to a parent that might also have dragging enabled
ev.stopPropagation()
// Make sure that start events are unbound so that one element
// is only dragged by one input only
this.init(false)
this.box = this.el.bbox()
this.lastClick = this.el.point(getCoordsFromEvent(ev))
const eventMove = (isMouse ? 'mousemove' : 'touchmove') + '.drag'
const eventEnd = (isMouse ? 'mouseup' : 'touchend') + '.drag'
// Bind drag and end events to window
on(window, eventMove, this.drag, this, { passive: false })
on(window, eventEnd, this.endDrag, this, { passive: false })
// Fire dragstart event
this.el.fire('dragstart', { event: ev, handler: this, box: this.box })
}
// While dragging
drag(ev) {
const { box, lastClick } = this
const currentClick = this.el.point(getCoordsFromEvent(ev))
const dx = currentClick.x - lastClick.x
const dy = currentClick.y - lastClick.y
if (!dx && !dy) return box
const x = box.x + dx
const y = box.y + dy
this.box = new Box(x, y, box.w, box.h)
this.lastClick = currentClick
if (
this.el.dispatch('dragmove', {
event: ev,
handler: this,
box: this.box,
dx,
dy,
}).defaultPrevented
) {
return
}
this.move(x, y)
}
move(x, y) {
// Svg elements bbox depends on their content even though they have
// x, y, width and height - strange!
// Thats why we handle them the same as groups
if (this.el.type === 'svg') {
G.prototype.move.call(this.el, x, y)
} else {
this.el.move(x, y)
}
}
endDrag(ev) {
// final drag
this.drag(ev)
// fire dragend event
this.el.fire('dragend', { event: ev, handler: this, box: this.box })
// unbind events
off(window, 'mousemove.drag')
off(window, 'touchmove.drag')
off(window, 'mouseup.drag')
off(window, 'touchend.drag')
// Rebind initial Events
this.init(true)
}
}
extend(Element, {
draggable(enable = true) {
const dragHandler = this.remember('_draggable') || new DragHandler(this)
dragHandler.init(enable)
return this
},
})
================================================
FILE: svg.draggable.js.d.cts
================================================
import { Element } from '@svgdotjs/svg.js'
declare module '@svgdotjs/svg.js' {
interface Element {
draggable(enable?: boolean): this
}
}
================================================
FILE: svg.draggable.js.d.ts
================================================
import { Element } from '@svgdotjs/svg.js'
declare module '@svgdotjs/svg.js' {
interface Element {
draggable(enable?: boolean): this
}
}
================================================
FILE: vite.config.ts
================================================
import { defineConfig } from 'vite'
import pkg from './package.json'
const buildDate = Date()
const headerLong = `/*!
* ${pkg.name} - ${pkg.description}
* @version ${pkg.version}
* ${pkg.homepage}
*
* @copyright ${pkg.author.name}
* @license ${pkg.license}
*
* BUILT: ${buildDate}
*/;`
export default defineConfig({
build: {
sourcemap: true,
lib: {
entry: 'src/svg.draggable.js',
name: 'SVG',
formats: ['umd'],
fileName: () => `svg.draggable.js`,
},
rollupOptions: {
output: {
globals: {
'@svgdotjs/svg.js': 'SVG',
},
banner: headerLong,
},
external: ['@svgdotjs/svg.js'],
},
},
})
gitextract___cug_mi/ ├── .eslintrc.json ├── .gitignore ├── .prettierrc.json ├── LICENSE ├── README.md ├── manual-test.html ├── package.json ├── src/ │ └── svg.draggable.js ├── svg.draggable.js.d.cts ├── svg.draggable.js.d.ts └── vite.config.ts
SYMBOL INDEX (9 symbols across 2 files)
FILE: src/svg.draggable.js
class DragHandler (line 11) | class DragHandler {
method constructor (line 12) | constructor(el) {
method init (line 22) | init(enabled) {
method startDrag (line 33) | startDrag(ev) {
method drag (line 74) | drag(ev) {
method move (line 103) | move(x, y) {
method endDrag (line 114) | endDrag(ev) {
method draggable (line 133) | draggable(enable = true) {
FILE: svg.draggable.js.d.ts
type Element (line 4) | interface Element {
Condensed preview — 11 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (16K chars).
[
{
"path": ".eslintrc.json",
"chars": 255,
"preview": "{\n \"env\": {\n \"browser\": true,\n \"es6\": true\n },\n \"extends\": [\"eslint:recommended\", \"plugin:prettier/recommended\""
},
{
"path": ".gitignore",
"chars": 44,
"preview": ".DS_Store\n.idea\n.vscode/\nnode_modules/\ndist\n"
},
{
"path": ".prettierrc.json",
"chars": 86,
"preview": "{\n \"trailingComma\": \"all\",\n \"tabWidth\": 2,\n \"semi\": false,\n \"singleQuote\": true\n}\n"
},
{
"path": "LICENSE",
"chars": 1082,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2018 Ulrich-Matthias\n\nPermission is hereby granted, free of charge, to any person o"
},
{
"path": "README.md",
"chars": 3731,
"preview": "# svg.draggable.js\n\nA plugin for the [svgdotjs.github.io](https://svgdotjs.github.io/) library to make elements draggabl"
},
{
"path": "manual-test.html",
"chars": 3638,
"preview": "<!DOCTYPE html>\n<html>\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n <title>svg"
},
{
"path": "package.json",
"chars": 1750,
"preview": "{\n \"name\": \"@svgdotjs/svg.draggable.js\",\n \"version\": \"3.0.6\",\n \"description\": \"An extension for svg.js which allows t"
},
{
"path": "src/svg.draggable.js",
"chars": 3382,
"preview": "import { Box, Element, G, extend, off, on } from '@svgdotjs/svg.js'\n\nconst getCoordsFromEvent = (ev) => {\n if (ev.chang"
},
{
"path": "svg.draggable.js.d.cts",
"chars": 146,
"preview": "import { Element } from '@svgdotjs/svg.js'\n\ndeclare module '@svgdotjs/svg.js' {\n interface Element {\n draggable(enab"
},
{
"path": "svg.draggable.js.d.ts",
"chars": 146,
"preview": "import { Element } from '@svgdotjs/svg.js'\n\ndeclare module '@svgdotjs/svg.js' {\n interface Element {\n draggable(enab"
},
{
"path": "vite.config.ts",
"chars": 685,
"preview": "import { defineConfig } from 'vite'\n\nimport pkg from './package.json'\nconst buildDate = Date()\n\nconst headerLong = `/*!\n"
}
]
About this extraction
This page contains the full source code of the svgdotjs/svg.draggable.js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 11 files (14.6 KB), approximately 4.3k tokens, and a symbol index with 9 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.