dragselect 2.4.3 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +103 -27
  3. package/deploying.md +1 -1
  4. package/dist/DragSelect.d.ts +26 -4
  5. package/dist/DragSelect.es6m.js +882 -792
  6. package/dist/DragSelect.js +882 -792
  7. package/dist/ds.es6m.min.js +1 -1
  8. package/dist/ds.min.js +1 -1
  9. package/dist/methods/addModificationObservers.d.ts +9 -1
  10. package/dist/methods/getAllParentNodes.d.ts +3 -0
  11. package/dist/methods/getPointerPos.d.ts +1 -1
  12. package/dist/methods/index.d.ts +1 -0
  13. package/dist/methods/isCollision.d.ts +1 -1
  14. package/dist/methods/subscriberAliases.d.ts +3 -1
  15. package/dist/modules/Area.d.ts +2 -12
  16. package/dist/modules/DropZone.d.ts +88 -0
  17. package/dist/modules/DropZones.d.ts +76 -0
  18. package/dist/modules/Interaction.d.ts +1 -0
  19. package/dist/modules/SelectableSet.d.ts +12 -0
  20. package/dist/modules/Selection.d.ts +1 -0
  21. package/dist/modules/Selector.d.ts +1 -1
  22. package/dist/modules/SelectorArea.d.ts +1 -1
  23. package/dist/modules/index.d.ts +1 -0
  24. package/dist/stores/KeyStore.d.ts +2 -2
  25. package/dist/stores/PointerStore.d.ts +2 -1
  26. package/dist/types.d.ts +78 -4
  27. package/jest-puppeteer.config.js +1 -0
  28. package/package.json +10 -9
  29. package/rollup.config.js +1 -1
  30. package/src/DragSelect.js +29 -5
  31. package/src/methods/addModificationObservers.js +26 -5
  32. package/src/methods/canScroll.js +1 -1
  33. package/src/methods/getAllParentNodes.js +18 -0
  34. package/src/methods/getPointerPos.js +1 -1
  35. package/src/methods/handleElementPositionAttribute.js +1 -1
  36. package/src/methods/hydrateSettings.js +17 -0
  37. package/src/methods/index.js +1 -0
  38. package/src/methods/isCollision.js +24 -5
  39. package/src/methods/scrollElement.js +1 -1
  40. package/src/methods/subscriberAliases.js +16 -5
  41. package/src/methods/toArray.js +3 -2
  42. package/src/modules/Area.js +12 -44
  43. package/src/modules/DropZone.js +224 -0
  44. package/src/modules/DropZones.js +153 -0
  45. package/src/modules/Interaction.js +32 -7
  46. package/src/modules/SelectableSet.js +45 -8
  47. package/src/modules/Selection.js +9 -11
  48. package/src/modules/index.js +1 -0
  49. package/src/stores/KeyStore.js +1 -1
  50. package/src/stores/PointerStore.js +17 -3
  51. package/src/stores/SettingsStore.js +0 -1
  52. package/src/types.js +33 -4
@@ -71,6 +71,10 @@ const hydrateHelper = (key, value, withFallback, fallback) => {
71
71
  if (key === 'dragKeys' && isAvailable) return { [key]: Object.assign(fallback, value) }
72
72
  else if(key === 'dragKeys' && !isAvailable) return isFallback ? { [key]: fallback } : {}
73
73
 
74
+ // Special rule for [dropZones]
75
+ if (key === 'dropZones' && isAvailable && new Set(value.map(v => v.id)).size !== value.length)
76
+ console.warn(`[DragSelect] UniqueConstraintsIssue: setting "dropZones" contains duplicate ids.`)
77
+
74
78
  return isAvailable ? { [key]: value } : isFallback ? { [key]: fallback } : {}
75
79
  }
76
80
 
@@ -95,15 +99,28 @@ export default (settings, withFallback) => ({
95
99
  ...hydrateHelper('multiSelectToggling', settings.multiSelectToggling, withFallback, true),
96
100
  ...hydrateHelper('multiSelectKeys', settings.multiSelectKeys, withFallback, ['Control', 'Shift', 'Meta']),
97
101
  ...hydrateHelper('selector', settings.selector, withFallback, null),
102
+ ...hydrateHelper('selectionThreshold', settings.selectionThreshold, withFallback, 0),
98
103
  ...hydrateHelper('draggability', settings.draggability, withFallback, true),
99
104
  ...hydrateHelper('immediateDrag', settings.immediateDrag, withFallback, true),
100
105
  ...hydrateHelper('keyboardDrag', settings.keyboardDrag, withFallback, true),
101
106
  ...hydrateHelper('dragKeys', settings.dragKeys, withFallback, { up: ['ArrowUp'], down: ['ArrowDown'], left: ['ArrowLeft'], right: ['ArrowRight'] }),
102
107
  ...hydrateHelper('keyboardDragSpeed', settings.keyboardDragSpeed, withFallback, 10),
103
108
  ...hydrateHelper('useTransform', settings.useTransform, withFallback, true),
109
+ ...hydrateHelper('refreshMemoryRate', settings.refreshMemoryRate, withFallback, 80),
110
+ ...hydrateHelper('dropZones', settings.dropZones, withFallback, []),
111
+ ...hydrateHelper('dropInsideThreshold', settings.dropInsideThreshold, withFallback, 1),
112
+ ...hydrateHelper('dropTargetThreshold', settings.dropTargetThreshold, withFallback, 0),
113
+ ...hydrateHelper('usePointerEvents', settings.usePointerEvents, withFallback, false),
104
114
  ...hydrateHelper('hoverClass', settings.hoverClass, withFallback, 'ds-hover'),
105
115
  ...hydrateHelper('selectableClass', settings.selectableClass, withFallback, 'ds-selectable'),
106
116
  ...hydrateHelper('selectedClass', settings.selectedClass, withFallback, 'ds-selected'),
107
117
  ...hydrateHelper('selectorClass', settings.selectorClass, withFallback, 'ds-selector'),
108
118
  ...hydrateHelper('selectorAreaClass', settings.selectorAreaClass, withFallback, 'ds-selector-area'),
119
+ ...hydrateHelper('droppedTargetClass', settings.droppedTargetClass, withFallback, 'ds-dropped-target'),
120
+ ...hydrateHelper('droppedInsideClass', settings.droppedInsideClass, withFallback, 'ds-dropped-inside'),
121
+ ...hydrateHelper('droppableClass', settings.droppableClass, withFallback, 'ds-droppable'),
122
+ ...hydrateHelper('dropZoneClass', settings.dropZoneClass, withFallback, 'ds-dropzone'),
123
+ ...hydrateHelper('dropZoneReadyClass', settings.dropZoneReadyClass, withFallback, 'ds-dropzone-ready'),
124
+ ...hydrateHelper('dropZoneTargetClass', settings.dropZoneTargetClass, withFallback, 'ds-dropzone-target'),
125
+ ...hydrateHelper('dropZoneInsideClass', settings.dropZoneInsideClass, withFallback, 'ds-dropzone-inside'),
109
126
  })
@@ -5,6 +5,7 @@ export { default as createSelectorAreaElement } from './createSelectorAreaElemen
5
5
  export { default as createSelectorElement } from './createSelectorElement'
6
6
  export { default as debounce } from './debounce'
7
7
  export { default as documentScroll } from './documentScroll'
8
+ export { default as getAllParentNodes } from './getAllParentNodes'
8
9
  export { default as getAreaRect } from './getAreaRect'
9
10
  export { default as getCurrentScroll } from './getCurrentScroll'
10
11
  export { default as getOverflowEdges } from './getOverflowEdges'
@@ -21,14 +21,33 @@ import '../types'
21
21
  * {@link https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection MDN}
22
22
  * @param {{left:number,right:number,top:number,bottom:number}} el1
23
23
  * @param {{left:number,right:number,top:number,bottom:number}} el2
24
+ * @param {number} [percent=0]
25
+ * 1 = the element has to be completely inside the other element
26
+ * 0.8 = the element has to be 80% inside the other element
27
+ * 0.5 = the element has to be 50% inside the other element
28
+ * 0.2 = the element has to be 20% inside the other element
29
+ * 0 = the element only has to touch the other element
24
30
  * @returns {boolean}
25
31
  */
26
- export default (el1, el2) => {
32
+ export default (el1, el2, percent = 0) => {
33
+ let element1 = el1
34
+
35
+ if (percent > 0) {
36
+ const widthPoint = (el1.right - el1.left) * percent
37
+ const heightPoint = (el1.bottom - el1.top) * percent
38
+ element1 = {
39
+ left: el1.left + widthPoint,
40
+ right: el1.right - widthPoint,
41
+ top: el1.top + heightPoint,
42
+ bottom: el1.bottom - heightPoint,
43
+ }
44
+ }
45
+
27
46
  if (
28
- el1.left < el2.right && // 1.
29
- el1.right > el2.left && // 2.
30
- el1.top < el2.bottom && // 3.
31
- el1.bottom > el2.top // 4.
47
+ element1.left < el2.right && // 1.
48
+ element1.right > el2.left && // 2.
49
+ element1.top < el2.bottom && // 3.
50
+ element1.bottom > el2.top // 4.
32
51
  )
33
52
  return true
34
53
  // collision detected!
@@ -16,7 +16,7 @@ export default (element, directions, multiplier) => {
16
16
  document.documentElement.scrollTop &&
17
17
  document.documentElement
18
18
  const _element =
19
- element instanceof HTMLDocument ? docEl || document.body : element
19
+ element instanceof Document ? docEl || document.body : element
20
20
 
21
21
  const scrollTop = directions.includes('top') && _element.scrollTop > 0
22
22
  const scrollBot =
@@ -1,6 +1,6 @@
1
1
  // @ts-check
2
2
  import '../types'
3
- import { Interaction, SelectedSet } from '../modules'
3
+ import { DropZones, Interaction, SelectedSet } from '../modules'
4
4
 
5
5
  /**
6
6
  * @typedef {function} DSSubscribe
@@ -22,17 +22,27 @@ import { Interaction, SelectedSet } from '../modules'
22
22
  * @param {DSPublish} p.publish
23
23
  * @param {Interaction} p.Interaction
24
24
  * @param {SelectedSet} p.SelectedSet
25
+ * @param {DropZones} p.DropZones
25
26
  */
26
- export default ({ subscribe, publish, Interaction, SelectedSet }) => {
27
+ export default ({ subscribe, publish, Interaction, SelectedSet, DropZones }) => {
27
28
  const mapping = {
28
29
  'Selected:added': [{ name: 'elementselect' }],
29
30
  'Selected:removed': [{ name: 'elementunselect' }],
30
31
  'Area:scroll': [{ name: 'autoscroll' }], // scroll_directions, scroll_multiplier
31
32
  'Interaction:start': [{ name: 'dragstart' }], // event, isDraggingKeyboard
32
- 'Interaction:update': [
33
+ 'Interaction:update': [ // event, isDraggingKeyboard
33
34
  { name: 'dragmove', condition: (data) => data.event },
34
- ], // event, isDraggingKeyboard
35
- 'Interaction:end': [{ name: 'callback' }], // event, isDraggingKeyboard
35
+ ],
36
+ 'Interaction:end': [ // event, isDraggingKeyboard
37
+ {
38
+ name: 'callback', extraData: () => {
39
+ const target = DropZones.getTarget()
40
+ return {
41
+ ...(target ? { dropTarget: target.toObject() } : {}),
42
+ }
43
+ }
44
+ }
45
+ ],
36
46
  }
37
47
 
38
48
  for (const [sub_name, pubs] of Object.entries(mapping))
@@ -45,6 +55,7 @@ export default ({ subscribe, publish, Interaction, SelectedSet }) => {
45
55
  items: SelectedSet.elements,
46
56
  isDragging: Interaction.isDragging,
47
57
  ...data,
58
+ ...(pub.extraData ? pub.extraData(data) : {}),
48
59
  })
49
60
  )
50
61
  )
@@ -2,7 +2,7 @@
2
2
  import '../types'
3
3
 
4
4
  /**
5
- * Transforms any list or single item to an array so user doesn’t have to care.
5
+ * Transforms any list or single dom node to an array so user doesn’t have to care. Also removes duplicates.
6
6
  * @param {DSInputElements} items a single item, a Node-list or any element group
7
7
  * @return {DSElements}
8
8
  */
@@ -13,5 +13,6 @@ export default (items) => {
13
13
  (items instanceof HTMLElement || items instanceof SVGElement)
14
14
  )
15
15
  return [items]
16
- return [...items]
16
+ // @ts-ignore
17
+ return [...new Set([...items])]
17
18
  }
@@ -6,9 +6,9 @@ import {
6
6
  addModificationObservers,
7
7
  debounce,
8
8
  getAreaRect,
9
- removeModificationObservers,
10
9
  scrollElement,
11
10
  handleElementPositionAttribute,
11
+ getAllParentNodes,
12
12
  } from '../methods'
13
13
 
14
14
  export default class Area {
@@ -18,20 +18,10 @@ export default class Area {
18
18
  */
19
19
  DS
20
20
  /**
21
- * @type {DSModificationCallback}
21
+ * @type {{cleanup:() => void}}
22
22
  * @private
23
23
  */
24
- _modificationCallback
25
- /**
26
- * @type {MutationObserver}
27
- * @private
28
- */
29
- _modificationObserver
30
- /**
31
- * @type {number}
32
- * @private
33
- */
34
- _zoom
24
+ _observers
35
25
  /**
36
26
  * @type {DSArea}
37
27
  * @private
@@ -72,15 +62,6 @@ export default class Area {
72
62
  this.setArea(settings.area)
73
63
  )
74
64
 
75
- this._modificationCallback = debounce((event) => {
76
- this.DS.PubSub.publish('Area:modified:pre', { event, item: this })
77
- this.reset()
78
- this.DS.PubSub.publish('Area:modified', { event, item: this })
79
- }, 60)
80
- this._modificationObserver = new MutationObserver(
81
- this._modificationCallback
82
- )
83
-
84
65
  this.DS.PubSub.subscribe('Interaction:init', this.start)
85
66
  this.DS.PubSub.subscribe('Interaction:end', this.reset)
86
67
  }
@@ -102,10 +83,13 @@ export default class Area {
102
83
  }
103
84
 
104
85
  start = () => {
105
- addModificationObservers(
86
+ this._observers = addModificationObservers(
106
87
  this.parentNodes,
107
- this._modificationCallback,
108
- this._modificationObserver
88
+ debounce((event) => {
89
+ this.DS.PubSub.publish('Area:modified:pre', { event, item: this })
90
+ this.reset()
91
+ this.DS.PubSub.publish('Area:modified', { event, item: this })
92
+ }, 60)
109
93
  )
110
94
  }
111
95
 
@@ -117,10 +101,7 @@ export default class Area {
117
101
  }
118
102
 
119
103
  stop = () => {
120
- removeModificationObservers(
121
- this._modificationObserver,
122
- this._modificationCallback
123
- )
104
+ this._observers.cleanup()
124
105
  this.reset()
125
106
  }
126
107
 
@@ -169,7 +150,7 @@ export default class Area {
169
150
  */
170
151
  get computedStyle() {
171
152
  if (this._computedStyle) return this._computedStyle
172
- if (this.HTMLNode instanceof HTMLDocument)
153
+ if (this.HTMLNode instanceof Document)
173
154
  return (this._computedStyle = window.getComputedStyle(
174
155
  this.HTMLNode.body || this.HTMLNode.documentElement
175
156
  ))
@@ -187,19 +168,6 @@ export default class Area {
187
168
 
188
169
  get parentNodes() {
189
170
  if (this._parentNodes) return this._parentNodes
190
-
191
- const traverse = (toWatch, index = 0) => {
192
- const parent = toWatch[index]?.parentNode
193
- if (parent) {
194
- toWatch.push(parent)
195
- index++
196
- return traverse(toWatch, index)
197
- } else {
198
- return toWatch
199
- }
200
- }
201
-
202
- this._parentNodes = traverse([this.HTMLNode])
203
- return this._parentNodes
171
+ return (this._parentNodes = getAllParentNodes(this.HTMLNode))
204
172
  }
205
173
  }
@@ -0,0 +1,224 @@
1
+ // @ts-check
2
+ import '../types'
3
+ import DragSelect from '../DragSelect'
4
+
5
+ import { isCollision, toArray, debounce, addModificationObservers, getAllParentNodes } from '../methods'
6
+
7
+ export default class DropZone {
8
+ /**
9
+ * @type {string}
10
+ */
11
+ id
12
+ /**
13
+ * @type {DSElement}
14
+ */
15
+ element
16
+ /**
17
+ * @type {DSElements}
18
+ */
19
+ droppables
20
+ /**
21
+ * @type {DOMRect}
22
+ * @private
23
+ */
24
+ _rect
25
+ /**
26
+ * @type {{cleanup:()=>void}}
27
+ * @private
28
+ */
29
+ _observers
30
+ /**
31
+ * @type {NodeJS.Timeout}
32
+ * @private
33
+ */
34
+ _timeout
35
+ /**
36
+ * @type {DSElements}
37
+ * @private
38
+ */
39
+ _itemsDropped = []
40
+ /**
41
+ * @type {DSElements}
42
+ * @private
43
+ */
44
+ _itemsInside
45
+ /**
46
+ * @constructor Drag
47
+ * @param {Object} obj
48
+ * @param {DragSelect} obj.DS
49
+ * @param {string} obj.id
50
+ * @param {DSElement} obj.element
51
+ * @param {DSInputElements} obj.droppables
52
+ * @ignore
53
+ */
54
+ constructor({ DS, id, element, droppables }) {
55
+ this.DS = DS
56
+ this.Settings = DS.stores.SettingsStore.s
57
+
58
+ this.id = id
59
+ this.element = element
60
+ this.droppables = toArray(droppables)
61
+ this.element.classList.add(`${this.Settings.dropZoneClass}`)
62
+
63
+ // @ts-ignore: @todo: update to typescript
64
+ this.DS.subscribe('Settings:updated:dropZoneClass', ({ settings }) => {
65
+ this.element.classList.remove(settings['dropZoneClass:pre'])
66
+ this.element.classList.add(settings['dropZoneClass'])
67
+ })
68
+
69
+ this._observers = addModificationObservers(
70
+ this.parentNodes,
71
+ debounce(() => this._rect = null, this.Settings.refreshMemoryRate),
72
+ )
73
+
74
+ this.DS.subscribe('Interaction:start', this.start)
75
+ this.DS.subscribe('Interaction:end', this.stop)
76
+ }
77
+
78
+ /**
79
+ * @param {'add'|'remove'} action
80
+ */
81
+ setReadyClasses = (action) => {
82
+ if(this.isDestroyed) return
83
+ const selectedEls = this.droppables.filter((el) => this.DS.SelectedSet.has(el))
84
+ if (!selectedEls.length) return
85
+ selectedEls.forEach((item) => {
86
+ item.classList[action](`${this.Settings.droppableClass}`)
87
+ item.classList[action](`${this.Settings.droppableClass}-${this.id}`)
88
+ })
89
+ this.element.classList[action](`${this.Settings.dropZoneReadyClass}`)
90
+ }
91
+
92
+ /**
93
+ * This zone is NOT the target of a drop
94
+ */
95
+ handleNoDrop = () => {
96
+ if(this.isDestroyed) return
97
+ // for each selected element that is not part of the target zone, remove the classes
98
+ this.DS.SelectedSet.forEach((item) => {
99
+ item.classList.remove(this.Settings.droppedTargetClass)
100
+ item.classList.remove(`${this.Settings.droppedTargetClass}-${this.id}`)
101
+ })
102
+ // and remove them from the zones dropped items
103
+ this._itemsDropped = this._itemsDropped.filter((item) => !this.DS.SelectedSet.has(item))
104
+ // if the zone has no dropped left, also remove the zones class
105
+ if(!this._itemsDropped?.length)
106
+ this.element.classList.remove(`${this.Settings.dropZoneTargetClass}`)
107
+ }
108
+
109
+ /**
110
+ * This zone IS the target of a drop
111
+ */
112
+ handleDrop = () => {
113
+ if(this.isDestroyed) return
114
+ // @ts-ignore
115
+ this._itemsDropped = [...new Set([...this._itemsDropped, ...this.droppables?.filter((item) => this.DS.SelectedSet.has(item))])]
116
+ // add the target class to the zones dropped items
117
+ this._itemsDropped?.forEach((item) => {
118
+ item.classList.add(`${this.Settings.droppedTargetClass}`)
119
+ item.classList.add(`${this.Settings.droppedTargetClass}-${this.id}`)
120
+ })
121
+ // if the zone has dropped, add the zones class
122
+ if(this._itemsDropped?.length)
123
+ this.element.classList.add(`${this.Settings.dropZoneTargetClass}`)
124
+ }
125
+
126
+ handleItemsInsideClasses = () => {
127
+ let isAnyInside = false
128
+ this.droppables.forEach((item) => {
129
+ if (this.itemsInside.includes(item)) {
130
+ item.classList.add(`${this.Settings.droppedInsideClass}`)
131
+ item.classList.add(`${this.Settings.droppedInsideClass}-${this.id}`)
132
+ isAnyInside = true
133
+ } else {
134
+ item.classList.remove(`${this.Settings.droppedInsideClass}`)
135
+ item.classList.remove(`${this.Settings.droppedInsideClass}-${this.id}`)
136
+ }
137
+ })
138
+
139
+ if (isAnyInside)
140
+ this.element.classList.add(`${this.Settings.dropZoneInsideClass}`)
141
+ else
142
+ this.element.classList.remove(`${this.Settings.dropZoneInsideClass}`)
143
+ }
144
+
145
+ start = ({ isDragging }) => {
146
+ if (!isDragging || this.isDestroyed) return
147
+ this.setReadyClasses('add')
148
+ }
149
+
150
+ stop = ({ isDragging }) => {
151
+ if (!isDragging || this.isDestroyed) return
152
+ this.setReadyClasses('remove')
153
+ this.handleItemsInsideClasses()
154
+ }
155
+
156
+ destroy() {
157
+ this._observers.cleanup()
158
+ this.element.classList.remove(`${this.Settings.dropZoneClass}`)
159
+ this.element.classList.remove(`${this.Settings.dropZoneTargetClass}`)
160
+ this.element.classList.remove(`${this.Settings.dropZoneReadyClass}`)
161
+ this.droppables.forEach((item) => {
162
+ item.classList.remove(`${this.Settings.droppedTargetClass}`)
163
+ item.classList.remove(`${this.Settings.droppedTargetClass}-${this.id}`)
164
+ item.classList.remove(`${this.Settings.droppableClass}`)
165
+ item.classList.remove(`${this.Settings.droppableClass}-${this.id}`)
166
+ })
167
+ this.DS.unsubscribe('Interaction:start', this.start)
168
+ this.DS.unsubscribe('Interaction:end', this.stop)
169
+ this.element = null
170
+ this.droppables = null
171
+ this.id = null
172
+ this._itemsDropped = null
173
+ this._itemsInside = null
174
+ this.isDestroyed = true
175
+ }
176
+
177
+ /**
178
+ * @returns {DSDropZone}
179
+ */
180
+ toObject = () => ({
181
+ id: this.id,
182
+ element: this.element,
183
+ droppables: this.droppables,
184
+ itemsDropped: this.itemsDropped,
185
+ itemsInside: this.itemsInside,
186
+ })
187
+
188
+ get rect() {
189
+ if (this.isDestroyed) return null
190
+ if (this._rect) return this._rect
191
+ return (this._rect = this.element.getBoundingClientRect())
192
+ }
193
+
194
+ get itemsDropped() {
195
+ if(this.isDestroyed) return null
196
+ return this._itemsDropped
197
+ }
198
+
199
+ get itemsInside() {
200
+ if (this.isDestroyed) return null
201
+ if (this._itemsInside) return this._itemsInside
202
+
203
+ this._itemsInside = this.droppables.flatMap((item) => {
204
+ if(isCollision(
205
+ this.DS.SelectableSet.rects.get(item),
206
+ this.rect,
207
+ this.Settings.dropInsideThreshold
208
+ ))
209
+ return [item]
210
+ return []
211
+ })
212
+
213
+ // since elements can be moved while this getter is called, we need to update the values every X seconds
214
+ if (this._timeout) clearTimeout(this._timeout)
215
+ this._timeout = setTimeout(() => this._itemsInside = null, this.Settings.refreshMemoryRate)
216
+
217
+ return this._itemsInside
218
+ }
219
+
220
+ get parentNodes() {
221
+ if (this._parentNodes) return this._parentNodes
222
+ return (this._parentNodes = getAllParentNodes(this.element))
223
+ }
224
+ }
@@ -0,0 +1,153 @@
1
+ // @ts-check
2
+
3
+ import '../types'
4
+ import DragSelect from '../DragSelect'
5
+ import DropZone from './DropZone'
6
+
7
+ import { isCollision, toArray } from '../methods'
8
+
9
+ export default class DropZones {
10
+ /**
11
+ * Get the drop zone by the zone element
12
+ * @type {Map<DSElement, DropZone>}
13
+ * @private
14
+ */
15
+ _zoneByElement = new Map()
16
+ /**
17
+ * Get the drop zone by the zone id
18
+ * @type {Map<string, DropZone>}
19
+ * @private
20
+ */
21
+ _zoneById = new Map()
22
+ /**
23
+ * Get the drop zones by one zone item
24
+ * @type {Map<DSElement,DropZone[]>}
25
+ * @private
26
+ */
27
+ _zonesByDroppable = new Map()
28
+ /**
29
+ * Get the drop zones by one zone item
30
+ * @type {DropZone[]}
31
+ * @private
32
+ */
33
+ _zones
34
+
35
+ /**
36
+ * @constructor Drag
37
+ * @param {{DS:DragSelect}} obj
38
+ * @ignore
39
+ */
40
+ constructor({ DS }) {
41
+ this.DS = DS
42
+ this.Settings = DS.stores.SettingsStore.s
43
+
44
+ // @ts-ignore: @todo: update to typescript
45
+ this.DS.subscribe('Settings:updated:dropZones', this.setDropZones)
46
+ this.setDropZones({ dropZones: /** @type {DSDropZone[]} */(this.DS.stores.SettingsStore.s.dropZones) })
47
+
48
+ this.DS.subscribe('Interaction:start', this.start)
49
+ this.DS.subscribe('Interaction:end', this.stop)
50
+ }
51
+
52
+ /**
53
+ * @param {Object} obj
54
+ * @param {DSDropZone[]} [obj.dropZones]
55
+ */
56
+ setDropZones = ({ dropZones }) => {
57
+ if (!dropZones) return
58
+ if (this._zones) this._zones.forEach((zone) => zone.destroy())
59
+
60
+ this._zones = dropZones.map((zone) => new DropZone({ DS: this.DS, ...zone }))
61
+ this._zones.forEach((zone) => {
62
+ this._zoneByElement.set(zone.element, zone)
63
+ this._zoneById.set(zone.id, zone)
64
+ zone.droppables.forEach((droppable) => {
65
+ const zones = this._zonesByDroppable.get(droppable)
66
+ if (!zones?.length) return this._zonesByDroppable.set(droppable, [zone])
67
+ // @ts-ignore
68
+ this._zonesByDroppable.set(droppable, [...new Set([...zones, zone])])
69
+ })
70
+ })
71
+ }
72
+
73
+ _handleDrop = (target) => {
74
+ this._zones.forEach((zone) => {
75
+ if (zone === target) return
76
+ zone.handleNoDrop()
77
+ })
78
+ if (!target) return
79
+ target.handleDrop()
80
+ }
81
+
82
+ /**
83
+ * @param {DSElements} elements
84
+ * @param {Vect2} point
85
+ * @returns {DropZone|undefined}
86
+ */
87
+ _getZoneByElementsFromPoint = (elements, { x, y }) => {
88
+ for(let i = 0, il = elements.length; i < il; i++) {
89
+ const zone = this._zoneByElement.get(elements[i])
90
+ if (
91
+ zone &&
92
+ isCollision(
93
+ zone.rect,
94
+ { left: x, right: x, top: y, bottom: y },
95
+ Math.min(this.Settings.dropTargetThreshold, 0.5)
96
+ )
97
+ ) {
98
+ return zone
99
+ }
100
+ }
101
+ }
102
+
103
+ start = ({ isDragging }) => {
104
+ if (!isDragging) return
105
+ }
106
+
107
+ stop = ({ isDragging }) => {
108
+ if (!isDragging) return
109
+ const target = this.getTarget()
110
+ this._handleDrop(target)
111
+ }
112
+
113
+ //////////////////////////////////////////////////////////////////////////////////////
114
+ // Getters
115
+
116
+ /**
117
+ * @param {string} zoneId
118
+ * @returns {DSElements|void}
119
+ */
120
+ getItemsDroppedById = (zoneId) => {
121
+ const zone = this._zoneById.get(zoneId)
122
+ if (!zone) return console.warn(`[DragSelect] No zone found (id: ${zoneId})`)
123
+ return zone.itemsDropped
124
+ }
125
+
126
+ /**
127
+ * @param {string} zoneId
128
+ * @param {boolean} addClasses
129
+ * @returns {DSElements|void}
130
+ */
131
+ getItemsInsideById = (zoneId, addClasses) => {
132
+ const zone = this._zoneById.get(zoneId)
133
+ if (!zone) return console.warn(`[DragSelect] No zone found (id: ${zoneId})`)
134
+ const itemsInside = zone.itemsInside
135
+ if(addClasses) zone.handleItemsInsideClasses()
136
+ return itemsInside
137
+ }
138
+
139
+ /**
140
+ * Returns first DropsZone under current pointer
141
+ * @param {Vect2} [coordinates]
142
+ * @returns {DropZone | undefined}
143
+ */
144
+ getTarget = (coordinates) => {
145
+ if (!this._zones?.length) return
146
+
147
+ const x = coordinates?.x || this.DS.stores.PointerStore.currentVal.x
148
+ const y = coordinates?.y || this.DS.stores.PointerStore.currentVal.y
149
+
150
+ const elements = document.elementsFromPoint(x, y)
151
+ return this._getZoneByElementsFromPoint(/** @type {DSElements} */(elements), { x, y })
152
+ }
153
+ }