dragselect 3.0.0 → 3.0.2

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.
@@ -0,0 +1,2597 @@
1
+ /***
2
+
3
+ ~~~ Version 3.0.2 ~~~
4
+
5
+ ******************************************
6
+
7
+ ____ _____ __ __
8
+ / __ \_________ _____ _/ ___/___ / /__ _____/ /_
9
+ / / / / ___/ __ `/ __ `/\__ \/ _ \/ / _ \/ ___/ __/
10
+ / /_/ / / / /_/ / /_/ /___/ / __/ / __/ /__/ /_
11
+ /_____/_/ \__,_/\__, //____/\___/_/\___/\___/\__/
12
+ /____/
13
+
14
+ ******************************************
15
+
16
+ {*} {*} STAR THIS PROJECT ON GITHUB {*} {*}
17
+
18
+ https://github.com/ThibaultJanBeyer/DragSelect
19
+ Please give it a like, this is what makes me happy :-)
20
+ Thank You
21
+
22
+ {*} {*} STAR THIS PROJECT ON GITHUB {*} {*}
23
+
24
+ ***************************************
25
+ ********* GPLv3 / Commercial **********
26
+ ***************************************
27
+ Created 2017 by ThibaultJanBeyer
28
+ Web: http://www.DragSelect.com/
29
+ GitHub: https://github.com/ThibaultJanBeyer/DragSelect
30
+ ***************************************
31
+ */
32
+ const addModificationObservers = (nodes, cb) => {
33
+ const callback = cb;
34
+ window.addEventListener('resize', callback);
35
+ window.addEventListener('scroll', callback);
36
+ const observer = new MutationObserver(callback);
37
+ const resizeObserver = new ResizeObserver(callback);
38
+ nodes.forEach((el, i) => {
39
+ observer.observe(el, {
40
+ childList: i !== 0,
41
+ attributes: true,
42
+ });
43
+ if (el instanceof Element)
44
+ resizeObserver.observe(el);
45
+ });
46
+ /**
47
+ * Removes all observers
48
+ */
49
+ const cleanup = () => {
50
+ window.removeEventListener('resize', callback);
51
+ window.removeEventListener('scroll', callback);
52
+ observer.disconnect();
53
+ resizeObserver.disconnect();
54
+ };
55
+ return { observer, resizeObserver, callback, cleanup };
56
+ };
57
+
58
+ /**
59
+ * Returns a function, that, as long as it continues to be invoked, will not
60
+ * be triggered. The function will be called after it stops being called for
61
+ * `wait` milliseconds. All credits to [Trey Huffine]{@link https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086}
62
+ */
63
+ const debounce = (func, wait) => {
64
+ let timeout;
65
+ // This is the function that is returned and will be executed many times
66
+ // We spread (...args) to capture any number of parameters we want to pass
67
+ return (...args) => {
68
+ // The callback function to be executed after
69
+ // the debounce time has elapsed
70
+ const later = () => {
71
+ // null timeout to indicate the debounce ended
72
+ timeout = undefined;
73
+ // Execute the callback
74
+ func(...args);
75
+ };
76
+ // This will reset the waiting every function execution.
77
+ // This is the step that prevents the function from
78
+ // being executed because it will never reach the
79
+ // inside of the previous setTimeout
80
+ clearTimeout(timeout);
81
+ // Restart the debounce waiting period.
82
+ // setTimeout returns a truthy value (it differs in web vs Node)
83
+ timeout = setTimeout(later, wait);
84
+ };
85
+ };
86
+
87
+ const getAllParentNodes = (node) => {
88
+ const traverse = (toWatch, index = 0) => {
89
+ const parent = toWatch[index]?.parentNode;
90
+ if (parent) {
91
+ toWatch.push(parent);
92
+ index++;
93
+ return traverse(toWatch, index);
94
+ }
95
+ return toWatch;
96
+ };
97
+ return traverse([node]);
98
+ };
99
+
100
+ /**
101
+ * Returns the top/left/bottom/right/width/height
102
+ * values of an area. If area is document then everything
103
+ * except the sizes will be nulled.
104
+ */
105
+ const getAreaRect = (area, zoom) => {
106
+ if (area instanceof Document)
107
+ return {
108
+ top: 0,
109
+ left: 0,
110
+ bottom: 0,
111
+ right: 0,
112
+ width: window.innerWidth,
113
+ height: window.innerHeight,
114
+ };
115
+ const rect = area.getBoundingClientRect();
116
+ return {
117
+ top: rect.top,
118
+ left: rect.left,
119
+ bottom: rect.bottom,
120
+ right: rect.right,
121
+ width: (area.clientWidth || rect.width) * zoom,
122
+ height: (area.clientHeight || rect.height) * zoom,
123
+ };
124
+ };
125
+
126
+ /** Fix: some elements have to have a special position attribute for calculations */
127
+ const handleElementPositionAttribute = ({ computedStyle, node }) => {
128
+ const { position } = computedStyle;
129
+ const isPositioned = position === 'absolute' || position === 'relative' || position === 'fixed';
130
+ if (!(node instanceof Document) && !isPositioned)
131
+ node.style.position = 'relative';
132
+ };
133
+
134
+ /** Scroll the element in the specified direction */
135
+ const scrollElement = (element, directions, multiplier = 1) => {
136
+ if (!directions?.length || !element)
137
+ return;
138
+ const docEl = document &&
139
+ document.documentElement &&
140
+ document.documentElement.scrollTop &&
141
+ document.documentElement;
142
+ const _element = element instanceof Document ? docEl || document.body : element;
143
+ const scrollTop = directions.includes('top') && _element.scrollTop > 0;
144
+ const scrollBot = directions.includes('bottom') && _element.scrollTop < _element.scrollHeight;
145
+ const scrollLeft = directions.includes('left') && _element.scrollLeft > 0;
146
+ const scrollRight = directions.includes('right') && _element.scrollLeft < _element.scrollWidth;
147
+ if (scrollTop)
148
+ _element.scrollTop -= 1 * multiplier;
149
+ if (scrollBot)
150
+ _element.scrollTop += 1 * multiplier;
151
+ if (scrollLeft)
152
+ _element.scrollLeft -= 1 * multiplier;
153
+ if (scrollRight)
154
+ _element.scrollLeft += 1 * multiplier;
155
+ };
156
+
157
+ class Area {
158
+ DS;
159
+ PS;
160
+ Settings;
161
+ _observers;
162
+ _node;
163
+ _parentNodes;
164
+ _computedStyle;
165
+ _computedBorder;
166
+ _rect;
167
+ constructor({ DS, PS }) {
168
+ this.DS = DS;
169
+ this.PS = PS;
170
+ this.Settings = this.DS.stores.SettingsStore.s;
171
+ this._node = this.Settings.area;
172
+ this.setArea(this.Settings.area);
173
+ this.PS.subscribe('Settings:updated:area', ({ settings: { area } }) => this.setArea(area));
174
+ this.PS.subscribe('Interaction:init', this.init);
175
+ this.PS.subscribe('Interaction:end', this.reset);
176
+ }
177
+ setArea = (area) => {
178
+ this.reset();
179
+ this._node = area;
180
+ handleElementPositionAttribute({
181
+ computedStyle: this.computedStyle,
182
+ node: this._node,
183
+ });
184
+ // first immediate debounce to update values after dom-update
185
+ setTimeout(() => {
186
+ this.PS.publish('Area:modified:pre', { item: this.HTMLNode });
187
+ this.reset();
188
+ this.PS.publish('Area:modified', { item: this.HTMLNode });
189
+ });
190
+ };
191
+ init = () => {
192
+ this._observers = addModificationObservers(this.parentNodes, debounce((event) => {
193
+ this.PS.publish('Area:modified:pre', { event, item: this.HTMLNode });
194
+ this.reset();
195
+ this.PS.publish('Area:modified', { event, item: this.HTMLNode });
196
+ }, 60));
197
+ };
198
+ reset = () => {
199
+ this._computedStyle = undefined;
200
+ this._rect = undefined;
201
+ this._computedBorder = undefined;
202
+ this._parentNodes = undefined;
203
+ };
204
+ stop = () => {
205
+ this._observers?.cleanup();
206
+ this.reset();
207
+ };
208
+ /// ///////////////////////////////////////////////////////////////////////////////////
209
+ // Scroll
210
+ /** Scroll the area in the specified direction */
211
+ scroll = (directions, multiplier) => {
212
+ const data = {
213
+ scroll_directions: directions,
214
+ scroll_multiplier: multiplier,
215
+ };
216
+ this.PS.publish('Area:scroll:pre', data);
217
+ scrollElement(this._node, directions, multiplier);
218
+ this.PS.publish('Area:scroll', data);
219
+ };
220
+ /// ///////////////////////////////////////////////////////////////////////////////////
221
+ // Node Getters
222
+ get HTMLNode() {
223
+ return this._node;
224
+ }
225
+ /** The computed border from the element (caches result) */
226
+ get computedBorder() {
227
+ if (this._computedBorder)
228
+ return this._computedBorder;
229
+ return {
230
+ top: parseInt(this.computedStyle.borderTopWidth),
231
+ bottom: parseInt(this.computedStyle.borderBottomWidth),
232
+ left: parseInt(this.computedStyle.borderLeftWidth),
233
+ right: parseInt(this.computedStyle.borderRightWidth),
234
+ };
235
+ }
236
+ /** The computed styles from the element (caches result) */
237
+ get computedStyle() {
238
+ if (this._computedStyle)
239
+ return this._computedStyle;
240
+ if (this.HTMLNode instanceof Document)
241
+ return (this._computedStyle = window.getComputedStyle(this.HTMLNode.body || this.HTMLNode.documentElement));
242
+ return (this._computedStyle = window.getComputedStyle(this.HTMLNode));
243
+ }
244
+ /** The element rect (caches result) (without scrollbar or borders) */
245
+ get rect() {
246
+ if (this._rect)
247
+ return this._rect;
248
+ return (this._rect = getAreaRect(this.HTMLNode, this.DS.stores.SettingsStore.s.zoom));
249
+ }
250
+ get parentNodes() {
251
+ if (this._parentNodes)
252
+ return this._parentNodes;
253
+ return (this._parentNodes = getAllParentNodes(this.HTMLNode));
254
+ }
255
+ }
256
+
257
+ const calcVect = ({ x: x1, y: y1 }, operator, { x: x2, y: y2 }) => {
258
+ const calculations = {
259
+ '+': {
260
+ x: x1 + x2,
261
+ y: y1 + y2,
262
+ },
263
+ '-': {
264
+ x: x1 - x2,
265
+ y: y1 - y2,
266
+ },
267
+ '*': {
268
+ x: x1 * x2,
269
+ y: y1 * y2,
270
+ },
271
+ '/': {
272
+ x: x1 / x2,
273
+ y: y1 / y2,
274
+ },
275
+ };
276
+ return calculations[operator];
277
+ };
278
+ const rect2vect = (rect) => ({ x: rect.left, y: rect.top });
279
+ const vect2rect = (vect, dimension = 0) => ({
280
+ left: vect.x,
281
+ top: vect.y,
282
+ right: vect.x,
283
+ bottom: vect.y,
284
+ width: dimension,
285
+ height: dimension,
286
+ });
287
+ const num2vect = (n) => ({ x: n, y: n });
288
+
289
+ const handleKeyboardDragPosDifference = ({ shiftKey, keyboardDragSpeed, zoom, key, dragKeys, scrollDiff, }) => {
290
+ const posDirection = { x: 0, y: 0 };
291
+ const increase = shiftKey
292
+ ? keyboardDragSpeed * 4 * zoom
293
+ : keyboardDragSpeed * zoom;
294
+ if (dragKeys?.left.includes(key))
295
+ posDirection.x = scrollDiff.x || -increase;
296
+ if (dragKeys?.right.includes(key))
297
+ posDirection.x = scrollDiff.x || increase;
298
+ if (dragKeys?.up.includes(key))
299
+ posDirection.y = scrollDiff.y || -increase;
300
+ if (dragKeys?.down.includes(key))
301
+ posDirection.y = scrollDiff.y || increase;
302
+ return posDirection;
303
+ };
304
+
305
+ const getComputedTranslatePositions = (element) => {
306
+ const position = {
307
+ x: 0,
308
+ y: 0,
309
+ };
310
+ const computed = window.getComputedStyle(element);
311
+ if (!computed.transform || computed.transform === 'none')
312
+ return position;
313
+ if (computed.transform.indexOf('3d') >= 0) {
314
+ const match = computed.transform.trim().match(/matrix3d\((.*?)\)/);
315
+ if (match && match.length) {
316
+ const values = match[1]?.split(',');
317
+ position.x = parseInt(values[12]) || 0;
318
+ position.y = parseInt(values[13]) || 0;
319
+ }
320
+ return position;
321
+ }
322
+ const match = computed.transform.trim().match(/matrix\((.*?)\)/);
323
+ if (match && match.length) {
324
+ const values = match[1]?.split(',');
325
+ position.x = parseInt(values[4]) || 0;
326
+ position.y = parseInt(values[5]) || 0;
327
+ }
328
+ return position;
329
+ };
330
+ const getTranslatedPositions = (element) => {
331
+ const { transform } = element.style;
332
+ if (!transform || transform.indexOf('translate') < 0)
333
+ return getComputedTranslatePositions(element);
334
+ const position = {
335
+ x: 0,
336
+ y: 0,
337
+ };
338
+ const match = transform.trim().match(/translate[3dD]*?\(.*?\)/);
339
+ if (match) {
340
+ const split = match[0]?.split('(');
341
+ if (split) {
342
+ const values = split[1]?.split(',');
343
+ position.x = parseInt(values[0]) || 0;
344
+ position.y = parseInt(values[1]) || 0;
345
+ }
346
+ }
347
+ if (!position.x && !position.x)
348
+ return getComputedTranslatePositions(element);
349
+ return position;
350
+ };
351
+ const getTopLeftPosition = (element) => {
352
+ const { style } = element;
353
+ const position = {
354
+ x: parseInt(style.left) || 0,
355
+ y: parseInt(style.top) || 0,
356
+ };
357
+ // initial positions
358
+ if (!position.x && !position.x) {
359
+ const computed = window.getComputedStyle(element);
360
+ return {
361
+ x: parseInt(computed.left) || 0,
362
+ y: parseInt(computed.top) || 0,
363
+ };
364
+ }
365
+ return position;
366
+ };
367
+ /**
368
+ * Returns the X and Y coordinates based on styles
369
+ * Can handle translate and top/left
370
+ */
371
+ const getStylePosition = (element, useTranslate) => {
372
+ if (useTranslate)
373
+ return getTranslatedPositions(element);
374
+ return getTopLeftPosition(element);
375
+ };
376
+
377
+ /** Sets the style position to the X and Y coordinates. Can handle translate and top/left */
378
+ const setStylePosition = (element, values, useTranslate) => {
379
+ if (useTranslate) {
380
+ const prevTransform = element.style.transform;
381
+ element.style.transform = `translate3d(${values.x}px,${values.y}px,1px) ${prevTransform.replace(/translate.*?\)/g, '')}`;
382
+ }
383
+ else {
384
+ element.style.left = `${values.x}px`;
385
+ element.style.top = `${values.y}px`;
386
+ }
387
+ return element;
388
+ };
389
+
390
+ /** Moves the element in a posDirection */
391
+ const moveElement = ({ element, posDirection, useTransform }) => {
392
+ const elementPos = getStylePosition(element, useTransform);
393
+ const newPos = calcVect(elementPos, '+', posDirection);
394
+ setStylePosition(element, newPos, useTransform);
395
+ };
396
+
397
+ /**
398
+ * Modify direction value so that the rect of draggable elements
399
+ * does not exceed the boundaries of container rect
400
+ */
401
+ const limitDirection = ({ containerRect, selectionRect, direction, scrollAmount }) => {
402
+ const delta = {
403
+ top: containerRect.top - selectionRect.top + scrollAmount.y,
404
+ left: containerRect.left - selectionRect.left + scrollAmount.x,
405
+ bottom: containerRect.bottom - selectionRect.bottom + scrollAmount.y,
406
+ right: containerRect.right - selectionRect.right + scrollAmount.x,
407
+ };
408
+ if (direction.x === 0 && direction.y === 0)
409
+ return direction;
410
+ if (direction.y < 0)
411
+ direction.y = Math.max(direction.y, delta.top);
412
+ if (direction.x < 0)
413
+ direction.x = Math.max(direction.x, delta.left);
414
+ if (direction.y > 0)
415
+ direction.y = Math.min(direction.y, delta.bottom);
416
+ if (direction.x > 0)
417
+ direction.x = Math.min(direction.x, delta.right);
418
+ selectionRect.top += direction.y;
419
+ selectionRect.bottom += direction.y;
420
+ selectionRect.left += direction.x;
421
+ selectionRect.right += direction.x;
422
+ return direction;
423
+ };
424
+
425
+ class Drag {
426
+ _prevCursorPos;
427
+ _prevScrollPos;
428
+ _elements = [];
429
+ _dragKeys;
430
+ _dragKeysFlat = [];
431
+ _selectionRect = vect2rect(num2vect(0));
432
+ DS;
433
+ PS;
434
+ Settings;
435
+ constructor({ DS, PS }) {
436
+ this.DS = DS;
437
+ this.PS = PS;
438
+ this.Settings = this.DS.stores.SettingsStore.s;
439
+ this.PS.subscribe('Settings:updated:dragKeys', this.assignDragKeys);
440
+ this.assignDragKeys();
441
+ this.PS.subscribe('Interaction:start', this.start);
442
+ this.PS.subscribe('Interaction:end', this.stop);
443
+ this.PS.subscribe('Interaction:update', this.update);
444
+ this.PS.subscribe('KeyStore:down', this.keyboardDrag);
445
+ this.PS.subscribe('KeyStore:up', this.keyboardEnd);
446
+ }
447
+ assignDragKeys = () => {
448
+ this._dragKeys = {
449
+ up: this.Settings.dragKeys.up.map((k) => k.toLowerCase()),
450
+ down: this.Settings.dragKeys.down.map((k) => k.toLowerCase()),
451
+ left: this.Settings.dragKeys.left.map((k) => k.toLowerCase()),
452
+ right: this.Settings.dragKeys.right.map((k) => k.toLowerCase()),
453
+ };
454
+ this._dragKeysFlat = [
455
+ ...this._dragKeys.up,
456
+ ...this._dragKeys.down,
457
+ ...this._dragKeys.left,
458
+ ...this._dragKeys.right,
459
+ ];
460
+ };
461
+ keyboardDrag = ({ event, key, }) => {
462
+ const _key = key.toLowerCase();
463
+ if (!this.Settings.keyboardDrag ||
464
+ !this._dragKeysFlat.includes(_key) ||
465
+ !this.DS.SelectedSet.size ||
466
+ !this.Settings.draggability ||
467
+ this.DS.continue)
468
+ return;
469
+ const publishData = {
470
+ event,
471
+ isDragging: true,
472
+ isDraggingKeyboard: true,
473
+ key,
474
+ };
475
+ this.PS.publish(['Interaction:start:pre', 'Interaction:start'], publishData);
476
+ this._elements = this.DS.getSelection();
477
+ this._selectionRect = this.DS.Selection.boundingRect;
478
+ this.handleZIndex(true);
479
+ let posDirection = handleKeyboardDragPosDifference({
480
+ shiftKey: this.DS.stores.KeyStore.currentValues.includes('shift'),
481
+ keyboardDragSpeed: this.Settings.keyboardDragSpeed,
482
+ zoom: this.Settings.zoom,
483
+ key: _key,
484
+ scrollDiff: this._scrollDiff,
485
+ dragKeys: this._dragKeys,
486
+ });
487
+ posDirection = limitDirection({
488
+ direction: posDirection,
489
+ containerRect: this.DS.SelectorArea.rect,
490
+ scrollAmount: this.DS.stores.ScrollStore.scrollAmount,
491
+ selectionRect: this._selectionRect,
492
+ });
493
+ this.moveElements(posDirection);
494
+ this.PS.publish(['Interaction:update:pre', 'Interaction:update'], publishData);
495
+ };
496
+ keyboardEnd = ({ event, key, }) => {
497
+ const _key = key.toLowerCase();
498
+ if (!this.Settings.keyboardDrag ||
499
+ !this._dragKeysFlat.includes(_key) ||
500
+ !this.DS.SelectedSet.size ||
501
+ !this.Settings.draggability)
502
+ return;
503
+ const publishData = {
504
+ event,
505
+ isDragging: this.Settings.draggability,
506
+ isDraggingKeyboard: true,
507
+ key,
508
+ };
509
+ this.PS.publish(['Interaction:end:pre', 'Interaction:end'], publishData);
510
+ };
511
+ start = ({ isDragging, isDraggingKeyboard, }) => {
512
+ if (!isDragging || isDraggingKeyboard)
513
+ return;
514
+ this._prevCursorPos = undefined;
515
+ this._prevScrollPos = undefined;
516
+ this._elements = this.DS.getSelection();
517
+ this._selectionRect = this.DS.Selection.boundingRect;
518
+ this.handleZIndex(true);
519
+ };
520
+ stop = () => {
521
+ this._prevCursorPos = undefined;
522
+ this._prevScrollPos = undefined;
523
+ this.handleZIndex(false);
524
+ this._elements = [];
525
+ };
526
+ update = ({ isDragging, isDraggingKeyboard, }) => {
527
+ if (!isDragging ||
528
+ !this._elements.length ||
529
+ isDraggingKeyboard ||
530
+ this.DS.continue)
531
+ return;
532
+ let posDirection = calcVect(this._cursorDiff, '+', this._scrollDiff);
533
+ posDirection = limitDirection({
534
+ direction: posDirection,
535
+ containerRect: this.DS.SelectorArea.rect,
536
+ scrollAmount: this.DS.stores.ScrollStore.scrollAmount,
537
+ selectionRect: this._selectionRect,
538
+ });
539
+ this.moveElements(posDirection);
540
+ };
541
+ handleZIndex = (add) => {
542
+ this._elements.forEach((element) => (element.style.zIndex = `${(parseInt(element.style.zIndex) || 0) + (add ? 9999 : -9998)}`));
543
+ };
544
+ moveElements = (posDirection) => {
545
+ // [PUBLICLY EXPOSED METHOD]
546
+ const { elements, direction } = this.filterDragElements({
547
+ elements: this._elements,
548
+ direction: posDirection,
549
+ });
550
+ elements.forEach((element) => {
551
+ moveElement({
552
+ element,
553
+ posDirection: direction,
554
+ containerRect: this.DS.SelectorArea.rect,
555
+ useTransform: this.Settings.useTransform,
556
+ });
557
+ });
558
+ };
559
+ get _cursorDiff() {
560
+ const currentPointerVal = this.DS.stores.PointerStore.currentVal;
561
+ const cursorDiff = this._prevCursorPos
562
+ ? calcVect(currentPointerVal, '-', this._prevCursorPos)
563
+ : { x: 0, y: 0 };
564
+ this._prevCursorPos = currentPointerVal;
565
+ return cursorDiff;
566
+ }
567
+ get _scrollDiff() {
568
+ const currentScrollVal = this.DS.stores.ScrollStore.currentVal;
569
+ const scrollDiff = this._prevScrollPos
570
+ ? calcVect(currentScrollVal, '-', this._prevScrollPos)
571
+ : { x: 0, y: 0 };
572
+ this._prevScrollPos = currentScrollVal;
573
+ return scrollDiff;
574
+ }
575
+ ////
576
+ // [PUBLICLY EXPOSED METHODS]
577
+ /**
578
+ * Can be overridden to apply further filtering logic after the items to move are identified but before they actually get moved
579
+ * Is expected to return the elements in the same shape as passed in
580
+ */
581
+ filterDragElements = ({ elements, direction, }) => ({
582
+ elements,
583
+ direction,
584
+ });
585
+ }
586
+
587
+ const isCollision = (el1, el2, percent = 0) => {
588
+ if (!el1 || !el2)
589
+ return false;
590
+ let element1 = el1;
591
+ if (percent > 0) {
592
+ const widthPoint = (el1.right - el1.left) * percent;
593
+ const heightPoint = (el1.bottom - el1.top) * percent;
594
+ element1 = {
595
+ left: el1.left + widthPoint,
596
+ right: el1.right - widthPoint,
597
+ top: el1.top + heightPoint,
598
+ bottom: el1.bottom - heightPoint,
599
+ };
600
+ }
601
+ if (element1.left < el2.right && // 1.
602
+ element1.right > el2.left && // 2.
603
+ element1.top < el2.bottom && // 3.
604
+ element1.bottom > el2.top // 4.
605
+ )
606
+ return true;
607
+ // collision detected!
608
+ return false;
609
+ };
610
+
611
+ const ensureArray = input => {
612
+ if (!input)
613
+ return [];
614
+ if (!Array.isArray(input) && typeof input[Symbol.iterator] !== 'function')
615
+ return [input];
616
+ return [...new Set([...input])];
617
+ };
618
+
619
+ class DropZone {
620
+ id;
621
+ element;
622
+ _droppables;
623
+ _rect;
624
+ _observers;
625
+ _timeout;
626
+ _itemsDropped = [];
627
+ _itemsInside;
628
+ DS;
629
+ PS;
630
+ Settings;
631
+ isDestroyed = false;
632
+ _parentNodes;
633
+ constructor({ DS, PS, id, element, droppables, }) {
634
+ this.DS = DS;
635
+ this.PS = PS;
636
+ this.Settings = this.DS.stores.SettingsStore.s;
637
+ this.id = id;
638
+ this.element = element;
639
+ if (droppables)
640
+ this.droppables = ensureArray(droppables);
641
+ this.element.classList.add(`${this.Settings.dropZoneClass}`);
642
+ this.PS.subscribe('Settings:updated:dropZoneClass', ({ settings }) => {
643
+ if (!this.element)
644
+ return;
645
+ this.element.classList.remove(settings['dropZoneClass:pre']);
646
+ this.element.classList.add(settings.dropZoneClass);
647
+ });
648
+ this._observers = addModificationObservers(this.parentNodes, debounce(() => (this._rect = undefined), this.Settings.refreshMemoryRate));
649
+ this.PS.subscribe('Interaction:start', this.start);
650
+ this.PS.subscribe('Interaction:end', this.stop);
651
+ }
652
+ setReadyClasses = (action) => {
653
+ if (this.isDestroyed)
654
+ return;
655
+ const selectedEls = this.droppables.filter((el) => this.DS.SelectedSet.has(el));
656
+ if (!selectedEls.length)
657
+ return;
658
+ selectedEls.forEach((item) => {
659
+ item.classList[action](`${this.Settings.droppableClass}`);
660
+ item.classList[action](`${this.Settings.droppableClass}-${this.id}`);
661
+ });
662
+ this.element.classList[action](`${this.Settings.dropZoneReadyClass}`);
663
+ };
664
+ /** This zone is NOT the target of a drop */
665
+ handleNoDrop = () => {
666
+ if (this.isDestroyed)
667
+ return;
668
+ // for each selected element that is not part of the target zone, remove the classes
669
+ this.DS.SelectedSet.forEach((item) => {
670
+ item.classList.remove(this.Settings.droppedTargetClass);
671
+ item.classList.remove(`${this.Settings.droppedTargetClass}-${this.id}`);
672
+ });
673
+ // and remove them from the zones dropped items
674
+ this._itemsDropped = this._itemsDropped.filter((item) => !this.DS.SelectedSet.has(item));
675
+ // if the zone has no dropped left, also remove the zones class
676
+ if (!this._itemsDropped?.length)
677
+ this.element.classList.remove(`${this.Settings.dropZoneTargetClass}`);
678
+ };
679
+ /** This zone IS the target of a drop */
680
+ handleDrop = () => {
681
+ if (this.isDestroyed)
682
+ return;
683
+ this._itemsDropped = [
684
+ ...new Set([
685
+ ...this._itemsDropped,
686
+ ...this.droppables?.filter((item) => this.DS.SelectedSet.has(item)),
687
+ ]),
688
+ ];
689
+ // add the target class to the zones dropped items
690
+ this._itemsDropped?.forEach((item) => {
691
+ item.classList.add(`${this.Settings.droppedTargetClass}`);
692
+ item.classList.add(`${this.Settings.droppedTargetClass}-${this.id}`);
693
+ });
694
+ // if the zone has dropped, add the zones class
695
+ if (this._itemsDropped?.length)
696
+ this.element.classList.add(`${this.Settings.dropZoneTargetClass}`);
697
+ };
698
+ handleItemsInsideClasses = () => {
699
+ let isAnyInside = false;
700
+ this.droppables.forEach((item) => {
701
+ if (this.itemsInside?.includes(item)) {
702
+ item.classList.add(`${this.Settings.droppedInsideClass}`);
703
+ item.classList.add(`${this.Settings.droppedInsideClass}-${this.id}`);
704
+ isAnyInside = true;
705
+ }
706
+ else {
707
+ item.classList.remove(`${this.Settings.droppedInsideClass}-${this.id}`);
708
+ if (!item.className.includes(`${this.Settings.droppedInsideClass}-`))
709
+ item.classList.remove(`${this.Settings.droppedInsideClass}`);
710
+ }
711
+ });
712
+ if (isAnyInside)
713
+ this.element.classList.add(`${this.Settings.dropZoneInsideClass}`);
714
+ else
715
+ this.element.classList.remove(`${this.Settings.dropZoneInsideClass}`);
716
+ };
717
+ start = ({ isDragging }) => {
718
+ if (!isDragging || this.isDestroyed)
719
+ return;
720
+ this.setReadyClasses('add');
721
+ };
722
+ stop = ({ isDragging }) => {
723
+ if (!isDragging || this.isDestroyed)
724
+ return;
725
+ this.setReadyClasses('remove');
726
+ this.handleItemsInsideClasses();
727
+ };
728
+ destroy() {
729
+ this._observers?.cleanup();
730
+ this.element.classList.remove(`${this.Settings.dropZoneClass}`);
731
+ this.element.classList.remove(`${this.Settings.dropZoneTargetClass}`);
732
+ this.element.classList.remove(`${this.Settings.dropZoneReadyClass}`);
733
+ this.droppables.forEach((item) => {
734
+ item.classList.remove(`${this.Settings.droppedTargetClass}`);
735
+ item.classList.remove(`${this.Settings.droppedTargetClass}-${this.id}`);
736
+ item.classList.remove(`${this.Settings.droppableClass}`);
737
+ item.classList.remove(`${this.Settings.droppableClass}-${this.id}`);
738
+ });
739
+ this.PS.unsubscribe('Interaction:start', this.start);
740
+ this.PS.unsubscribe('Interaction:end', this.stop);
741
+ this.isDestroyed = true;
742
+ }
743
+ toObject = () => ({
744
+ id: this.id,
745
+ element: this.element,
746
+ droppables: this.droppables,
747
+ itemsDropped: this.itemsDropped,
748
+ itemsInside: this.itemsInside,
749
+ });
750
+ get rect() {
751
+ if (this.isDestroyed)
752
+ return undefined;
753
+ if (this._rect)
754
+ return this._rect;
755
+ return (this._rect = this.element.getBoundingClientRect());
756
+ }
757
+ get itemsDropped() {
758
+ if (this.isDestroyed)
759
+ return undefined;
760
+ return this._itemsDropped;
761
+ }
762
+ get itemsInside() {
763
+ if (this.isDestroyed)
764
+ return undefined;
765
+ if (this._itemsInside)
766
+ return this._itemsInside;
767
+ this._itemsInside = this.droppables.flatMap((item) => {
768
+ const itemRect = this.DS.SelectableSet.rects.get(item);
769
+ if (this.rect &&
770
+ isCollision(itemRect, this.rect, this.Settings.dropInsideThreshold))
771
+ return [item];
772
+ return [];
773
+ });
774
+ // since elements can be moved while this getter is called, we need to update the values every X seconds
775
+ if (this._timeout)
776
+ clearTimeout(this._timeout);
777
+ this._timeout = setTimeout(() => (this._itemsInside = undefined), this.Settings.refreshMemoryRate);
778
+ return this._itemsInside;
779
+ }
780
+ get parentNodes() {
781
+ if (this._parentNodes)
782
+ return this._parentNodes;
783
+ return (this._parentNodes = getAllParentNodes(this.element));
784
+ }
785
+ get droppables() {
786
+ if (this._droppables)
787
+ return this._droppables;
788
+ return this.DS.SelectableSet.elements;
789
+ }
790
+ set droppables(value) {
791
+ this._droppables = value;
792
+ }
793
+ }
794
+
795
+ class DropZones {
796
+ /** Get the drop zone by the zone element */
797
+ _zoneByElement = new Map();
798
+ /** Get the drop zone by the zone id */
799
+ _zoneById = new Map();
800
+ /** Get the drop zones by one zone item */
801
+ _zonesByDroppable = new Map();
802
+ /** Get the drop zones by one zone item */
803
+ _zones;
804
+ DS;
805
+ PS;
806
+ Settings;
807
+ constructor({ DS, PS }) {
808
+ this.DS = DS;
809
+ this.PS = PS;
810
+ this.Settings = this.DS.stores.SettingsStore.s;
811
+ this.PS.subscribe('Settings:updated:dropZones', ({ settings }) => this.setDropZones(settings));
812
+ this.setDropZones({ dropZones: this.Settings.dropZones });
813
+ this.PS.subscribe('Interaction:end', this.stop);
814
+ }
815
+ setDropZones = ({ dropZones, }) => {
816
+ if (!dropZones)
817
+ return;
818
+ if (this._zones)
819
+ this._zones.forEach((zone) => zone.destroy());
820
+ this._zones = dropZones.map((zone) => new DropZone({ DS: this.DS, PS: this.PS, ...zone }));
821
+ this._zones.forEach((zone) => {
822
+ this._zoneByElement.set(zone.element, zone);
823
+ this._zoneById.set(zone.id, zone);
824
+ zone.droppables.forEach((droppable) => {
825
+ const zones = this._zonesByDroppable.get(droppable);
826
+ if (!zones?.length)
827
+ return this._zonesByDroppable.set(droppable, [zone]);
828
+ this._zonesByDroppable.set(droppable, [...new Set([...zones, zone])]);
829
+ });
830
+ });
831
+ };
832
+ _handleDrops = (target) => {
833
+ this._zones?.forEach((zone) => {
834
+ if (zone !== target)
835
+ zone.handleNoDrop();
836
+ });
837
+ if (!target)
838
+ return;
839
+ target.handleDrop();
840
+ };
841
+ _getZoneByElementsFromPoint = (elements, { x, y }) => {
842
+ for (let i = 0, il = elements.length; i < il; i++) {
843
+ const zone = this._zoneByElement.get(elements[i]);
844
+ if (isCollision(zone?.rect, { left: x, right: x, top: y, bottom: y }, Math.min(this.Settings.dropTargetThreshold, 0.5)))
845
+ return zone;
846
+ }
847
+ };
848
+ stop = ({ isDragging, isDraggingKeyboard, event, }) => {
849
+ if (!isDragging)
850
+ return;
851
+ const target = this.getTarget({ isDraggingKeyboard, event });
852
+ this._handleDrops(target);
853
+ };
854
+ /// ///////////////////////////////////////////////////////////////////////////////////
855
+ // Getters
856
+ getItemsDroppedById = (zoneId) => {
857
+ const zone = this._zoneById.get(zoneId);
858
+ if (!zone)
859
+ return console.warn(`[DragSelect] No zone found (id: ${zoneId})`);
860
+ return zone.itemsDropped;
861
+ };
862
+ getItemsInsideById = (zoneId, addClasses) => {
863
+ const zone = this._zoneById.get(zoneId);
864
+ if (!zone)
865
+ return console.warn(`[DragSelect] No zone found (id: ${zoneId})`);
866
+ if (addClasses)
867
+ zone.handleItemsInsideClasses();
868
+ return zone.itemsInside;
869
+ };
870
+ getKeyboardItemCenter = (isDraggingKeyboard, event) => {
871
+ if (!isDraggingKeyboard || !event)
872
+ return;
873
+ const rect = event.target?.getBoundingClientRect();
874
+ // center of rect
875
+ const x = rect.left + rect.width / 2;
876
+ const y = rect.top + rect.height / 2;
877
+ return { x, y };
878
+ };
879
+ /** Returns first DropsZone under current pointer or coordinates if passed */
880
+ getTarget = ({ coordinates, isDraggingKeyboard, event, }) => {
881
+ if (!this._zones?.length)
882
+ return;
883
+ let keyboardCoordinates;
884
+ if (!coordinates && isDraggingKeyboard && event) {
885
+ keyboardCoordinates = this.getKeyboardItemCenter(isDraggingKeyboard, event);
886
+ }
887
+ const x = coordinates?.x ||
888
+ keyboardCoordinates?.x ||
889
+ this.DS.stores.PointerStore.currentVal.x;
890
+ const y = coordinates?.y ||
891
+ keyboardCoordinates?.y ||
892
+ this.DS.stores.PointerStore.currentVal.y;
893
+ const elements = document.elementsFromPoint(x, y);
894
+ return this._getZoneByElementsFromPoint(elements, { x, y });
895
+ };
896
+ }
897
+
898
+ class Interaction {
899
+ isInteracting;
900
+ isDragging = false;
901
+ DS;
902
+ PS;
903
+ Settings;
904
+ constructor({ DS, PS }) {
905
+ this.DS = DS;
906
+ this.PS = PS;
907
+ this.Settings = this.DS.stores.SettingsStore.s;
908
+ // not on every modification, just on change of area
909
+ this.PS.subscribe('Settings:updated:area', ({ settings }) => {
910
+ this.removeAreaEventListeners(settings['area:pre']);
911
+ this.setAreaEventListeners(settings['area']);
912
+ });
913
+ this.PS.subscribe('PointerStore:updated', ({ event }) => this.update({ event }));
914
+ this.PS.subscribe('Selectable:click', this.onClick);
915
+ this.PS.subscribe('Selectable:pointer', ({ event }) => this.start(event));
916
+ this.PS.subscribe('Interaction:start:pre', ({ event }) => this._start(event));
917
+ this.PS.subscribe('Interaction:init:pre', this._init);
918
+ this.PS.subscribe('Interaction:end:pre', ({ event }) => this._reset(event));
919
+ this.PS.subscribe('Area:scroll', this.update);
920
+ }
921
+ init = () => this.PS.publish('Interaction:init:pre', { init: true });
922
+ _init = () => {
923
+ this.stop();
924
+ this.setAreaEventListeners();
925
+ this.PS.publish('Interaction:init', { init: true });
926
+ };
927
+ _canInteract(event) {
928
+ const isKeyboardClick = 'clientX' in event &&
929
+ event.clientX === 0 &&
930
+ event.clientY === 0 &&
931
+ event.detail === 0 &&
932
+ event.target;
933
+ if (('button' in event && event.button === 2) || // right-clicks
934
+ this.isInteracting || // fix double-click issues
935
+ (event.target && !this.DS.SelectorArea.isInside(event.target)) || // fix outside elements issue
936
+ (!isKeyboardClick && !this.DS.SelectorArea.isClicked(event)) // make sure the mouse click is inside the area
937
+ )
938
+ return false;
939
+ return true;
940
+ }
941
+ start = (event) => this.PS.publish('Interaction:start:pre', {
942
+ event: event,
943
+ isDragging: this.isDragging,
944
+ });
945
+ _start = (event) => {
946
+ if (event.type === 'touchstart')
947
+ event.preventDefault(); // Call preventDefault() to prevent double click issue, see https://github.com/ThibaultJanBeyer/DragSelect/pull/29 & https://developer.mozilla.org/vi/docs/Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent
948
+ if (!this._canInteract(event))
949
+ return;
950
+ this.isInteracting = true;
951
+ this.isDragging = this.isDragEvent(event);
952
+ this.PS.publish('Interaction:start', {
953
+ event,
954
+ isDragging: this.isDragging,
955
+ });
956
+ this.setDocEventListeners();
957
+ };
958
+ isDragEvent = (event) => {
959
+ let clickedElement = null;
960
+ if (event.target && 'closest' in event.target)
961
+ clickedElement = event.target.closest(`.${this.Settings.selectableClass}`);
962
+ if (!this.Settings.draggability ||
963
+ this.DS.stores.KeyStore.isMultiSelectKeyPressed(event) ||
964
+ !clickedElement)
965
+ return false;
966
+ if (this.Settings.immediateDrag) {
967
+ if (!this.DS.SelectedSet.size)
968
+ this.DS.SelectedSet.add(clickedElement);
969
+ else if (!this.DS.SelectedSet.has(clickedElement)) {
970
+ this.DS.SelectedSet.clear();
971
+ this.DS.SelectedSet.add(clickedElement);
972
+ }
973
+ }
974
+ if (this.DS.SelectedSet.has(clickedElement))
975
+ return true;
976
+ return false;
977
+ };
978
+ /**
979
+ * Triggers when a node is actively selected: <button> nodes that are pressed via the keyboard.
980
+ * Making DragSelect accessible for everyone!
981
+ */
982
+ onClick = ({ event }) => {
983
+ if (!this._canInteract(event))
984
+ return;
985
+ if (event.detail > 0)
986
+ return; // mouse interaction
987
+ const { stores: { PointerStore, KeyStore }, SelectableSet, SelectedSet, } = this.DS;
988
+ PointerStore.start(event);
989
+ const node = event.target;
990
+ if (node && !SelectableSet.has(node))
991
+ return;
992
+ if (!KeyStore.isMultiSelectKeyPressed(event))
993
+ SelectedSet.clear();
994
+ if (node)
995
+ SelectedSet.toggle(node);
996
+ this.reset(event); // simulate mouse-up (that does not exist on keyboard)
997
+ };
998
+ stop = (area = this.DS.Area.HTMLNode) => {
999
+ this.removeAreaEventListeners(area);
1000
+ this.removeDocEventListeners();
1001
+ };
1002
+ update = ({ event, scroll_directions, scroll_multiplier, }) => {
1003
+ if (this.isInteracting)
1004
+ this.PS.publish(['Interaction:update:pre', 'Interaction:update'], {
1005
+ event,
1006
+ scroll_directions,
1007
+ scroll_multiplier,
1008
+ isDragging: this.isDragging,
1009
+ });
1010
+ };
1011
+ reset = (event) => this.PS.publish('Interaction:end:pre', {
1012
+ event,
1013
+ isDragging: this.isDragging,
1014
+ });
1015
+ _reset = (event) => {
1016
+ const { isDragging } = this;
1017
+ this.isInteracting = false;
1018
+ this.isDragging = false;
1019
+ this.removeDocEventListeners();
1020
+ this.PS.publish('Interaction:end', { event, isDragging });
1021
+ };
1022
+ //////////////////////////////////////////////////////////////////////////////////////
1023
+ // Event Listeners
1024
+ setAreaEventListeners = (area = this.DS.Area.HTMLNode) => {
1025
+ // @TODO: fix pointer events mixing issue see [PR](https://github.com/ThibaultJanBeyer/DragSelect/pull/128#issuecomment-1154885289)
1026
+ if (this.Settings.usePointerEvents)
1027
+ area.addEventListener('pointerdown', this.start, {
1028
+ passive: false,
1029
+ });
1030
+ else
1031
+ area.addEventListener('mousedown', this.start);
1032
+ area.addEventListener('touchstart', this.start, {
1033
+ passive: false,
1034
+ });
1035
+ };
1036
+ removeAreaEventListeners = (area = this.DS.Area.HTMLNode) => {
1037
+ // @TODO: fix pointer events mixing issue see [PR](https://github.com/ThibaultJanBeyer/DragSelect/pull/128#issuecomment-1154885289)
1038
+ if (this.Settings.usePointerEvents) {
1039
+ area.removeEventListener('pointerdown', this.start, {
1040
+ // @ts-ignore
1041
+ passive: false,
1042
+ });
1043
+ }
1044
+ else
1045
+ area.removeEventListener('mousedown', this.start);
1046
+ area.removeEventListener('touchstart', this.start, {
1047
+ // @ts-ignore
1048
+ passive: false,
1049
+ });
1050
+ };
1051
+ setDocEventListeners = () => {
1052
+ // @TODO: fix pointer events mixing issue see [PR](https://github.com/ThibaultJanBeyer/DragSelect/pull/128#issuecomment-1154885289)
1053
+ if (this.Settings.usePointerEvents) {
1054
+ document.addEventListener('pointerup', this.reset);
1055
+ document.addEventListener('pointercancel', this.reset);
1056
+ }
1057
+ else
1058
+ document.addEventListener('mouseup', this.reset);
1059
+ document.addEventListener('touchend', this.reset);
1060
+ };
1061
+ removeDocEventListeners = () => {
1062
+ // @TODO: fix pointer events mixing issue see [PR](https://github.com/ThibaultJanBeyer/DragSelect/pull/128#issuecomment-1154885289)
1063
+ if (this.Settings.usePointerEvents) {
1064
+ document.removeEventListener('pointerup', this.reset);
1065
+ document.removeEventListener('pointercancel', this.reset);
1066
+ }
1067
+ else
1068
+ document.removeEventListener('mouseup', this.reset);
1069
+ document.removeEventListener('touchend', this.reset);
1070
+ };
1071
+ }
1072
+
1073
+ class KeyStore {
1074
+ _currentValues = new Set();
1075
+ _keyMapping = {
1076
+ control: 'ctrlKey',
1077
+ shift: 'shiftKey',
1078
+ meta: 'metaKey',
1079
+ };
1080
+ DS;
1081
+ PS;
1082
+ settings;
1083
+ /**
1084
+ * @class KeyStore
1085
+ * @constructor KeyStore
1086
+ * @ignore
1087
+ */
1088
+ constructor({ DS, PS }) {
1089
+ this.DS = DS;
1090
+ this.PS = PS;
1091
+ this.settings = this.DS.stores.SettingsStore.s;
1092
+ this.PS.subscribe('Interaction:init', this.init);
1093
+ }
1094
+ init = () => {
1095
+ document.addEventListener('keydown', this.keydown);
1096
+ document.addEventListener('keyup', this.keyup);
1097
+ window.addEventListener('blur', this.reset);
1098
+ };
1099
+ keydown = (event) => {
1100
+ if (!event.key?.toLocaleLowerCase)
1101
+ return;
1102
+ const key = event.key.toLowerCase();
1103
+ this.PS.publish('KeyStore:down:pre', { event, key });
1104
+ this._currentValues.add(key);
1105
+ this.PS.publish('KeyStore:down', { event, key });
1106
+ };
1107
+ keyup = (event) => {
1108
+ if (!event.key?.toLocaleLowerCase)
1109
+ return;
1110
+ const key = event.key.toLowerCase();
1111
+ this.PS.publish('KeyStore:up:pre', { event, key });
1112
+ this._currentValues.delete(key);
1113
+ this.PS.publish('KeyStore:up', { event, key });
1114
+ };
1115
+ stop = () => {
1116
+ document.removeEventListener('keydown', this.keydown);
1117
+ document.removeEventListener('keyup', this.reset);
1118
+ window.removeEventListener('blur', this.reset);
1119
+ this.reset();
1120
+ };
1121
+ reset = () => this._currentValues.clear();
1122
+ isMultiSelectKeyPressed(event) {
1123
+ if (this.settings.multiSelectMode)
1124
+ return true;
1125
+ const multiSelectKeys = this.settings.multiSelectKeys?.map((key) => key.toLocaleLowerCase()) ?? [];
1126
+ if (this.currentValues.some((key) => multiSelectKeys.includes(key)))
1127
+ return true;
1128
+ if (event && multiSelectKeys.some((key) => event[this._keyMapping[key]]))
1129
+ return true;
1130
+ return false;
1131
+ }
1132
+ get currentValues() {
1133
+ return Array.from(this._currentValues.values());
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * Returns cursor x, y position based on event object
1139
+ */
1140
+ const getPointerPos = ({ event }) => ({
1141
+ x: event.clientX,
1142
+ y: event.clientY,
1143
+ });
1144
+
1145
+ class PointerStore {
1146
+ _isMouseInteraction = false;
1147
+ // Position relative to area
1148
+ _initialValArea = { x: 0, y: 0 };
1149
+ _currentValArea = { x: 0, y: 0 };
1150
+ _lastValArea = { x: 0, y: 0 };
1151
+ // General Pointer Position
1152
+ _initialVal = { x: 0, y: 0 };
1153
+ _currentVal = { x: 0, y: 0 };
1154
+ _lastVal = { x: 0, y: 0 };
1155
+ _lastTouch;
1156
+ DS;
1157
+ PS;
1158
+ settings;
1159
+ constructor({ DS, PS }) {
1160
+ this.DS = DS;
1161
+ this.PS = PS;
1162
+ this.settings = this.DS.stores.SettingsStore.s;
1163
+ this.PS.subscribe('Interaction:init', this.init);
1164
+ this.PS.subscribe('Interaction:start', ({ event }) => this.start(event));
1165
+ this.PS.subscribe('Interaction:end', ({ event }) => this.reset(event));
1166
+ }
1167
+ init = () => {
1168
+ if (this.settings.usePointerEvents)
1169
+ document.addEventListener('pointermove', this.update, { passive: false });
1170
+ else
1171
+ document.addEventListener('mousemove', this.update);
1172
+ document.addEventListener('touchmove', this.update, { passive: false });
1173
+ };
1174
+ start(event) {
1175
+ if (!event)
1176
+ return;
1177
+ this._isMouseInteraction = true;
1178
+ this.currentVal = this.initialVal = this.getPointerPosition(event);
1179
+ }
1180
+ getPointerPosition = (event) => getPointerPos({
1181
+ event: this._normalizedEvent(event),
1182
+ });
1183
+ update = (event) => {
1184
+ // type Event to satisfy event listeners, but we know type is : event as InteractionEvent
1185
+ if (!event)
1186
+ return;
1187
+ this.PS.publish('PointerStore:updated:pre', {
1188
+ event: event,
1189
+ });
1190
+ this.currentVal = this.getPointerPosition(event);
1191
+ if (!this._isMouseInteraction)
1192
+ return;
1193
+ this.PS.publish('PointerStore:updated', {
1194
+ event: event,
1195
+ });
1196
+ };
1197
+ stop = () => {
1198
+ // @TODO: fix pointer events mixing issue see [PR](https://github.com/ThibaultJanBeyer/DragSelect/pull/128#issuecomment-1154885289)
1199
+ if (this.settings.usePointerEvents)
1200
+ document.removeEventListener('pointermove', this.update, {
1201
+ // @ts-ignore
1202
+ passive: false,
1203
+ });
1204
+ else
1205
+ document.removeEventListener('mousemove', this.update);
1206
+ document.removeEventListener('touchmove', this.update, {
1207
+ // @ts-ignore
1208
+ passive: false,
1209
+ });
1210
+ this.reset();
1211
+ };
1212
+ reset = (event) => {
1213
+ this.currentVal = this.lastVal = this.getPointerPosition(event);
1214
+ // debounce in order "onClick" to work
1215
+ setTimeout(() => (this._isMouseInteraction = false), 100);
1216
+ };
1217
+ _normalizedEvent(event) {
1218
+ // null KeyboardEvents
1219
+ if (!event || event instanceof KeyboardEvent)
1220
+ return { clientX: 0, clientY: 0 };
1221
+ // touchend has not touches. so we take the last touch if a touchevent, we need to store the positions
1222
+ if ('touches' in event) {
1223
+ if (event.type !== 'touchend')
1224
+ this._lastTouch = event;
1225
+ // if a touchevent, return the last touch rather than the regular event
1226
+ // as we need .touches[0] from that event
1227
+ return this._lastTouch?.touches[0] || event.touches[0];
1228
+ }
1229
+ return event;
1230
+ }
1231
+ /** First recorded pointer position within the area */
1232
+ get initialValArea() {
1233
+ if (!this._initialValArea)
1234
+ return { x: 0, y: 0 };
1235
+ return this._initialValArea;
1236
+ }
1237
+ /** Current pointer position within the area */
1238
+ get currentValArea() {
1239
+ if (!this._currentValArea)
1240
+ return { x: 0, y: 0 };
1241
+ return this._currentValArea;
1242
+ }
1243
+ /** Last recorded pointer position within the area */
1244
+ get lastValArea() {
1245
+ if (!this._lastValArea)
1246
+ return { x: 0, y: 0 };
1247
+ return this._lastValArea;
1248
+ }
1249
+ /** First recorded pointer position */
1250
+ get initialVal() {
1251
+ if (!this._initialVal)
1252
+ return { x: 0, y: 0 };
1253
+ return this._initialVal;
1254
+ }
1255
+ /** Current pointer position */
1256
+ get currentVal() {
1257
+ if (!this._currentVal)
1258
+ return { x: 0, y: 0 };
1259
+ return this._currentVal;
1260
+ }
1261
+ /** Last recorded pointer position */
1262
+ get lastVal() {
1263
+ if (!this._lastVal)
1264
+ return { x: 0, y: 0 };
1265
+ return this._lastVal;
1266
+ }
1267
+ set initialVal(value) {
1268
+ this._initialVal = value;
1269
+ this._initialValArea =
1270
+ value &&
1271
+ calcVect(value, '-', calcVect(rect2vect(this.DS.Area.rect), '+', rect2vect(this.DS.Area.computedBorder)));
1272
+ }
1273
+ set currentVal(value) {
1274
+ this._currentVal = value;
1275
+ this._currentValArea =
1276
+ value &&
1277
+ calcVect(value, '-', calcVect(rect2vect(this.DS.Area.rect), '+', rect2vect(this.DS.Area.computedBorder)));
1278
+ }
1279
+ set lastVal(value) {
1280
+ this._lastVal = value;
1281
+ this._lastValArea =
1282
+ value &&
1283
+ calcVect(value, '-', calcVect(rect2vect(this.DS.Area.rect), '+', rect2vect(this.DS.Area.computedBorder)));
1284
+ }
1285
+ }
1286
+
1287
+ class PubSub {
1288
+ subscribers = {};
1289
+ DS;
1290
+ constructor({ DS }) {
1291
+ this.DS = DS;
1292
+ }
1293
+ /**
1294
+ * Subscribe to an event
1295
+ * @returns event id, can be used to unsubscribe more efficiently
1296
+ */
1297
+ subscribe = (eventName, callback) => {
1298
+ if (!Array.isArray(this.subscribers[eventName]))
1299
+ this.subscribers[eventName] = [];
1300
+ const subscribers = this.subscribers[eventName];
1301
+ subscribers.push(callback);
1302
+ return subscribers.length - 1;
1303
+ };
1304
+ /**
1305
+ * Removes event subscription
1306
+ * @param callback the callback method signature, has to be exactly the same as when subscribing. Consider using "id" instead.
1307
+ * @param id event id returned when subscribed (more performant than callback search)
1308
+ */
1309
+ unsubscribe = (eventName, callback, id) => {
1310
+ const index = id ?? this.subscribers[eventName]?.findIndex((cb) => cb === callback);
1311
+ this.subscribers[eventName]?.splice(Number(index), 1);
1312
+ };
1313
+ /**
1314
+ * Publishes an event to all subscribers
1315
+ * @param eventName
1316
+ * @param data passed to the subscription method
1317
+ */
1318
+ publish = (eventName, data) => {
1319
+ if (Array.isArray(eventName))
1320
+ eventName.forEach((name) => this._publish(name, data));
1321
+ else
1322
+ this._publish(eventName, data);
1323
+ };
1324
+ _publish = (eventName, data) => {
1325
+ const subscribers = this.subscribers[eventName] ?? [];
1326
+ if (eventName.includes(`:pre`))
1327
+ this._handlePrePublish(subscribers, data);
1328
+ else
1329
+ this._handlePublish(subscribers, data);
1330
+ };
1331
+ // non-pre events are executed first in first out
1332
+ _handlePublish = (subscribers, data) => {
1333
+ for (let i = 0, il = subscribers.length; i < il; i++) {
1334
+ if (this.DS.stopped)
1335
+ return;
1336
+ subscribers[i]?.(data);
1337
+ }
1338
+ };
1339
+ // pre events are executed last in first out (so user callbacks are called before DS callbacks)
1340
+ _handlePrePublish = (subscribers, data) => {
1341
+ let i = subscribers.length;
1342
+ while (i--) {
1343
+ if (this.DS.stopped)
1344
+ return;
1345
+ subscribers[i]?.(data);
1346
+ }
1347
+ };
1348
+ }
1349
+
1350
+ const getDocumentScroll = () => ({
1351
+ y: document.body?.scrollTop || document.documentElement?.scrollTop || 0,
1352
+ x: document.body?.scrollLeft || document.documentElement?.scrollLeft || 0,
1353
+ });
1354
+
1355
+ const getCurrentScroll = area => {
1356
+ if (!area || area instanceof Document)
1357
+ return getDocumentScroll();
1358
+ return {
1359
+ x: area.scrollLeft >= 0 ? area.scrollLeft : getDocumentScroll().x,
1360
+ y: area.scrollTop >= 0 ? area.scrollTop : getDocumentScroll().y,
1361
+ };
1362
+ };
1363
+
1364
+ const canScroll = area => {
1365
+ const scroll = getCurrentScroll(area);
1366
+ if (scroll.x || scroll.y)
1367
+ return true;
1368
+ if (area instanceof Document) {
1369
+ if (area.body)
1370
+ return Boolean(area.body.scrollTop = 1);
1371
+ return Boolean(area.documentElement.scrollTop = 1);
1372
+ }
1373
+ return Boolean(area.scrollTop = 1);
1374
+ };
1375
+
1376
+ class ScrollStore {
1377
+ _initialVal = { x: 0, y: 0 };
1378
+ _currentVal = { x: 0, y: 0 };
1379
+ _canScroll;
1380
+ DS;
1381
+ PS;
1382
+ Settings;
1383
+ constructor({ DS, PS }) {
1384
+ this.DS = DS;
1385
+ this.PS = PS;
1386
+ this.Settings = this.DS.stores.SettingsStore.s;
1387
+ this.PS.subscribe('Area:modified', () => {
1388
+ this.stop();
1389
+ this.init();
1390
+ });
1391
+ this.PS.subscribe('Interaction:init', this.init);
1392
+ this.PS.subscribe('Interaction:start', () => this.start());
1393
+ this.PS.subscribe('Interaction:end', () => this.reset());
1394
+ }
1395
+ init = () => this.addListeners();
1396
+ addListeners = () => this.DS.Area.HTMLNode.addEventListener('scroll', this.update);
1397
+ removeListeners = () => this.DS.Area.HTMLNode.removeEventListener('scroll', this.update);
1398
+ start = () => {
1399
+ this._currentVal = this._initialVal = getCurrentScroll(this.DS.Area.HTMLNode);
1400
+ };
1401
+ update = () => (this._currentVal = getCurrentScroll(this.DS.Area.HTMLNode));
1402
+ stop = () => {
1403
+ this.reset();
1404
+ this.removeListeners();
1405
+ };
1406
+ reset = () => {
1407
+ this._initialVal = { x: 0, y: 0 };
1408
+ this._canScroll = undefined;
1409
+ };
1410
+ get canScroll() {
1411
+ if (typeof this._canScroll === 'boolean')
1412
+ return this._canScroll;
1413
+ return (this._canScroll = canScroll(this.DS.Area.HTMLNode));
1414
+ }
1415
+ get scrollAmount() {
1416
+ const scrollDiff = calcVect(this.currentVal, '-', this.initialVal);
1417
+ // if area is zoomed, the scroll values are skewed, we need to fix that manually :(
1418
+ const zoom = num2vect(this.Settings.zoom);
1419
+ const zoomScroll = calcVect(calcVect(scrollDiff, '*', zoom), '-', scrollDiff);
1420
+ return {
1421
+ x: scrollDiff.x + zoomScroll.x,
1422
+ y: scrollDiff.y + zoomScroll.y,
1423
+ };
1424
+ }
1425
+ get initialVal() {
1426
+ if (!this._initialVal)
1427
+ return { x: 0, y: 0 };
1428
+ return this._initialVal;
1429
+ }
1430
+ get currentVal() {
1431
+ if (!this._currentVal)
1432
+ this._currentVal = getCurrentScroll(this.DS.Area.HTMLNode);
1433
+ return this._currentVal;
1434
+ }
1435
+ }
1436
+
1437
+ class SelectableSet extends Set {
1438
+ _rects;
1439
+ _timeout;
1440
+ DS;
1441
+ PS;
1442
+ Settings;
1443
+ constructor({ DS, PS }) {
1444
+ super();
1445
+ this.DS = DS;
1446
+ this.PS = PS;
1447
+ this.Settings = this.DS.stores.SettingsStore.s;
1448
+ this.PS.subscribe('Interaction:init', this.init);
1449
+ this.PS.subscribe('Settings:updated:selectables', () => {
1450
+ this.clear();
1451
+ this.init();
1452
+ });
1453
+ this.PS.subscribe('Settings:updated:selectableClass', ({ settings }) => {
1454
+ this.forEach((el) => {
1455
+ el.classList.remove(settings['selectableClass:pre']);
1456
+ el.classList.add(settings.selectableClass);
1457
+ });
1458
+ });
1459
+ }
1460
+ init = () => ensureArray(this.Settings.selectables).forEach((el) => this.add(el));
1461
+ add(element) {
1462
+ if (!element || super.has(element))
1463
+ return this;
1464
+ const publishData = {
1465
+ items: this.elements,
1466
+ item: element,
1467
+ };
1468
+ this.PS.publish('Selectable:added:pre', publishData);
1469
+ element.classList.add(this.Settings.selectableClass);
1470
+ element.addEventListener('click', this._onClick);
1471
+ if (this.Settings.usePointerEvents)
1472
+ element.addEventListener('pointerdown', this._onPointer, { passive: false });
1473
+ else
1474
+ element.addEventListener('mousedown', this._onPointer);
1475
+ element.addEventListener('touchstart', this._onPointer, { passive: false });
1476
+ if (this.Settings.draggability && !this.Settings.useTransform)
1477
+ handleElementPositionAttribute({
1478
+ computedStyle: window.getComputedStyle(element),
1479
+ node: element,
1480
+ });
1481
+ this.PS.publish('Selectable:added', publishData);
1482
+ return super.add(element);
1483
+ }
1484
+ delete(element) {
1485
+ if (!element || !super.has(element))
1486
+ return true;
1487
+ const publishData = {
1488
+ items: this.elements,
1489
+ item: element,
1490
+ };
1491
+ this.PS.publish('Selectable:removed:pre', publishData);
1492
+ element.classList.remove(this.Settings.selectableClass);
1493
+ element.classList.remove(this.Settings.hoverClass);
1494
+ element.removeEventListener('click', this._onClick);
1495
+ if (this.Settings.usePointerEvents)
1496
+ element.removeEventListener('pointerdown', this._onPointer, {
1497
+ // @ts-ignore
1498
+ passive: false,
1499
+ });
1500
+ else
1501
+ element.removeEventListener('mousedown', this._onPointer);
1502
+ element.removeEventListener('touchstart', this._onPointer, {
1503
+ // @ts-ignore
1504
+ passive: false,
1505
+ });
1506
+ this.PS.publish('Selectable:removed', publishData);
1507
+ return super.delete(element);
1508
+ }
1509
+ clear = () => this.forEach((el) => this.delete(el));
1510
+ _onClick = (event) => // we know it’s only a MouseEvent
1511
+ this.PS.publish(['Selectable:click:pre', 'Selectable:click'], { event: event });
1512
+ _onPointer = (event) => // we know it’s only an InteractionEvent
1513
+ this.PS.publish(['Selectable:pointer:pre', 'Selectable:pointer'], { event: event });
1514
+ addAll = (elements) => elements.forEach((el) => this.add(el));
1515
+ deleteAll = (elements) => elements.forEach((el) => this.delete(el));
1516
+ /**
1517
+ * Gets the bounding rect from private memory if available. If not gets it from the DOM.
1518
+ * => Does not force rect calculation on all elements
1519
+ */
1520
+ getElementRect = (element) => this._rects ? this._rects.get(element) : element.getBoundingClientRect();
1521
+ get elements() {
1522
+ return Array.from(this.values());
1523
+ }
1524
+ get rects() {
1525
+ if (this._rects)
1526
+ return this._rects;
1527
+ this._rects = new Map();
1528
+ this.forEach((element) => this._rects?.set(element, element.getBoundingClientRect()));
1529
+ // since elements can be moved, we need to update the rects every X ms
1530
+ if (this._timeout)
1531
+ clearTimeout(this._timeout);
1532
+ this._timeout = setTimeout(() => (this._rects = undefined), this.Settings.refreshMemoryRate);
1533
+ return this._rects;
1534
+ }
1535
+ }
1536
+
1537
+ class SelectedSet extends Set {
1538
+ _rects;
1539
+ _timeout;
1540
+ DS;
1541
+ PS;
1542
+ Settings;
1543
+ constructor({ DS, PS }) {
1544
+ super();
1545
+ this.DS = DS;
1546
+ this.PS = PS;
1547
+ this.Settings = this.DS.stores.SettingsStore.s;
1548
+ }
1549
+ add(element) {
1550
+ if (!element || super.has(element))
1551
+ return this;
1552
+ const publishData = {
1553
+ items: this.elements,
1554
+ item: element,
1555
+ };
1556
+ this.PS.publish('Selected:added:pre', publishData);
1557
+ super.add(element);
1558
+ element.classList.add(this.Settings.selectedClass);
1559
+ element.style.zIndex = `${(parseInt(element.style.zIndex) || 0) + 1}`;
1560
+ this.PS.publish('Selected:added', publishData);
1561
+ return this;
1562
+ }
1563
+ delete(element) {
1564
+ if (!element || !super.has(element))
1565
+ return true;
1566
+ const publishData = {
1567
+ items: this.elements,
1568
+ item: element,
1569
+ };
1570
+ this.PS.publish('Selected:removed:pre', publishData);
1571
+ const deleted = super.delete(element);
1572
+ element.classList.remove(this.Settings.selectedClass);
1573
+ element.style.zIndex = `${(parseInt(element.style.zIndex) || 0) - 1}`;
1574
+ this.PS.publish('Selected:removed', publishData);
1575
+ return deleted;
1576
+ }
1577
+ clear = () => this.forEach((el) => this.delete(el));
1578
+ /** Adds/Removes an element. If it is already selected = remove, if not = add. */
1579
+ toggle(element) {
1580
+ if (this.has(element))
1581
+ this.delete(element);
1582
+ else
1583
+ this.add(element);
1584
+ return element;
1585
+ }
1586
+ addAll = (elements) => elements.forEach((el) => this.add(el));
1587
+ deleteAll = (elements) => elements.forEach((el) => this.delete(el));
1588
+ get elements() {
1589
+ return Array.from(this.values());
1590
+ }
1591
+ get rects() {
1592
+ if (this._rects)
1593
+ return this._rects;
1594
+ this._rects = new Map();
1595
+ this.forEach((element) => this._rects?.set(element, element.getBoundingClientRect()));
1596
+ // since elements can be moved, we need to update the rects every X ms
1597
+ if (this._timeout)
1598
+ clearTimeout(this._timeout);
1599
+ this._timeout = setTimeout(() => (this._rects = undefined), this.Settings.refreshMemoryRate);
1600
+ return this._rects;
1601
+ }
1602
+ }
1603
+
1604
+ const createSelectorElement = (customStyles) => {
1605
+ const selector = document.createElement('div');
1606
+ selector.style.position = 'absolute';
1607
+ if (!customStyles) {
1608
+ selector.style.background = 'rgba(0, 175, 255, 0.2)';
1609
+ selector.style.border = '1px solid rgba(0, 175, 255, 0.8)';
1610
+ selector.style.display = 'none';
1611
+ selector.style.pointerEvents = 'none'; // fix for issue #8 (ie11+)
1612
+ }
1613
+ return selector;
1614
+ };
1615
+
1616
+ /** Reliably returns the exact x,y,w,h positions of the selector element */
1617
+ const getSelectorPosition = ({ scrollAmount, initialPointerPos, pointerPos }) => {
1618
+ /** check for direction
1619
+ *
1620
+ * This is quite complicated, so also quite complicated to explain. Lemme’ try:
1621
+ *
1622
+ * Problem #1:
1623
+ * Sadly in HTML we can not have negative sizes.
1624
+ * so if we want to scale our element 10px to the right then it is easy,
1625
+ * we just have to add +10px to the width. But if we want to scale the element
1626
+ * -10px to the left then things become more complicated, we have to move
1627
+ * the element -10px to the left on the x axis and also scale the element
1628
+ * by +10px width to fake a negative sizing.
1629
+ *
1630
+ * One solution to this problem is using css-transforms scale() with
1631
+ * transform-origin of top left. BUT we can’t use this since it will size
1632
+ * everything, then when your element has a border for example, the border will
1633
+ * get inanely huge. Also transforms are not widely supported in IE.
1634
+ *
1635
+ * Example #1:
1636
+ * Unfortunately, things get even more complicated when we are inside a scroll-able
1637
+ * DIV. Then, let’s say we scroll to the right by 10px and move the cursor right by 5px in our
1638
+ * checks we have to subtract 10px from the initialcursor position in our check
1639
+ * (since the initial position is moved to the left by 10px) so in our example:
1640
+ * 1. pointerPos.x (5) > initialPointerPos.x (0) - scrollAmount.x (10) === 5 > -10 === true
1641
+ * then set the x position to the cursors start position
1642
+ * selectorPos.x = initialPointerPos.x (0) - scrollAmount.x (10) === 10 // 2.
1643
+ * then we can calculate the elements width, which is
1644
+ * the new cursor position minus the initial one plus the scroll amount, so in our example:
1645
+ * 3. selectorPos.w = pointerPos.x (5) - initialPointerPos.x (0) + scrollAmount.x (10) === 15;
1646
+ *
1647
+ * let’s say after that movement we now scroll 20px to the left and move our cursor by 30px to the left:
1648
+ * 1b. pointerPos.x (-30) > initialPointerPos.x (0) - scrollAmount.x (-20) === -30 < --20 === -30 < +20 === false;
1649
+ * 2b. selectorPos.x = pointerPos.x (-30) === -30; move left position to cursor (for more info see Problem #1)
1650
+ * 3b. selectorPos.w = initialPointerPos.x (0) - pointerPos.x (-30) - scrollAmount.x (-20) === 0--30--20 === 0+30+20 === 50; // scale width to original left position (for more info see Problem #1)
1651
+ *
1652
+ * same thing has to be done for top/bottom
1653
+ *
1654
+ * I hope that makes sense. Try stuff out and play around with variables to get a hang of it.
1655
+ */
1656
+ const selectorPos = {};
1657
+ // right
1658
+ if (pointerPos.x > initialPointerPos.x - scrollAmount.x) {
1659
+ // 1.
1660
+ selectorPos.left = initialPointerPos.x - scrollAmount.x; // 2.
1661
+ selectorPos.width = pointerPos.x - initialPointerPos.x + scrollAmount.x; // 3.
1662
+ // left
1663
+ }
1664
+ else {
1665
+ // 1b.
1666
+ selectorPos.left = pointerPos.x; // 2b.
1667
+ selectorPos.width = initialPointerPos.x - pointerPos.x - scrollAmount.x; // 3b.
1668
+ }
1669
+ // bottom
1670
+ if (pointerPos.y > initialPointerPos.y - scrollAmount.y) {
1671
+ selectorPos.top = initialPointerPos.y - scrollAmount.y;
1672
+ selectorPos.height = pointerPos.y - initialPointerPos.y + scrollAmount.y;
1673
+ // top
1674
+ }
1675
+ else {
1676
+ selectorPos.top = pointerPos.y;
1677
+ selectorPos.height = initialPointerPos.y - pointerPos.y - scrollAmount.y;
1678
+ }
1679
+ return selectorPos;
1680
+ };
1681
+
1682
+ /** Updates element style left, top, width, height values according to pos input object */
1683
+ var updateElementStylePos = (element, pos) => {
1684
+ if (pos.left)
1685
+ element.style.left = `${pos.left}px`;
1686
+ if (pos.top)
1687
+ element.style.top = `${pos.top}px`;
1688
+ if (pos.width)
1689
+ element.style.width = `${pos.width}px`;
1690
+ if (pos.height)
1691
+ element.style.height = `${pos.height}px`;
1692
+ };
1693
+
1694
+ class Selector {
1695
+ _rect;
1696
+ DS;
1697
+ PS;
1698
+ Settings;
1699
+ HTMLNode;
1700
+ constructor({ DS, PS }) {
1701
+ this.DS = DS;
1702
+ this.PS = PS;
1703
+ this.Settings = this.DS.stores.SettingsStore.s;
1704
+ this.HTMLNode = this.Settings.selector; // to make TS happy, will be replaced in `attachSelector`
1705
+ this.PS.subscribe('Settings:updated:selectorClass', ({ settings }) => {
1706
+ this.HTMLNode.classList.remove(settings['selectorClass:pre']);
1707
+ this.HTMLNode.classList.add(settings.selectorClass);
1708
+ });
1709
+ this.PS.subscribe('Settings:updated:selector', this.attachSelector);
1710
+ this.PS.subscribe('Settings:updated:customStyles', this.attachSelector);
1711
+ this.attachSelector();
1712
+ this.PS.subscribe('Interaction:start', this.start);
1713
+ this.PS.subscribe('Interaction:update', this.update);
1714
+ this.PS.subscribe('Interaction:end', this.stop);
1715
+ }
1716
+ attachSelector = () => {
1717
+ if (this.HTMLNode && this.DS.SelectorArea?.HTMLNode)
1718
+ this.DS.SelectorArea.HTMLNode.removeChild(this.HTMLNode);
1719
+ this.HTMLNode = this.Settings.selector || createSelectorElement(this.Settings.customStyles);
1720
+ this.HTMLNode.classList.add(this.Settings.selectorClass);
1721
+ if (this.HTMLNode && this.DS.SelectorArea?.HTMLNode)
1722
+ this.DS.SelectorArea.HTMLNode.appendChild(this.HTMLNode);
1723
+ };
1724
+ start = ({ isDragging }) => {
1725
+ if (isDragging)
1726
+ return;
1727
+ const { stores: { PointerStore }, } = this.DS;
1728
+ const pPos = PointerStore.initialValArea;
1729
+ updateElementStylePos(this.HTMLNode, vect2rect(pPos, 1));
1730
+ this.HTMLNode.style.display = 'block';
1731
+ this._rect = undefined;
1732
+ };
1733
+ stop = () => {
1734
+ this.HTMLNode.style.width = '0';
1735
+ this.HTMLNode.style.height = '0';
1736
+ this.HTMLNode.style.display = 'none';
1737
+ };
1738
+ /** Moves the selection to the correct place */
1739
+ update = ({ isDragging }) => {
1740
+ if (isDragging || this.DS.continue)
1741
+ return;
1742
+ const { stores: { ScrollStore, PointerStore }, } = this.DS;
1743
+ const pos = getSelectorPosition({
1744
+ scrollAmount: ScrollStore.scrollAmount,
1745
+ initialPointerPos: PointerStore.initialValArea,
1746
+ pointerPos: PointerStore.currentValArea,
1747
+ });
1748
+ updateElementStylePos(this.HTMLNode, pos);
1749
+ this._rect = undefined;
1750
+ };
1751
+ get rect() {
1752
+ if (this._rect)
1753
+ return this._rect;
1754
+ return (this._rect = this.HTMLNode.getBoundingClientRect());
1755
+ }
1756
+ }
1757
+
1758
+ /** Logic when an element is selected */
1759
+ const handleSelection = ({ element, force, multiSelectionToggle, SelectedSet, hoverClassName, }) => {
1760
+ if (element.classList.contains(hoverClassName) && !force)
1761
+ return;
1762
+ if (!SelectedSet.has(element))
1763
+ SelectedSet.add(element);
1764
+ else if (multiSelectionToggle)
1765
+ SelectedSet.delete(element);
1766
+ element.classList.add(hoverClassName);
1767
+ };
1768
+
1769
+ /** Logic when an element is de-selected */
1770
+ const handleUnSelection = ({ element, force, SelectedSet, PrevSelectedSet, hoverClassName, }) => {
1771
+ if (!element.classList.contains(hoverClassName) && !force)
1772
+ return;
1773
+ const inSelection = SelectedSet.has(element);
1774
+ const inPrevSelection = PrevSelectedSet.has(element);
1775
+ /**
1776
+ * Special for issue #9.
1777
+ * if a multi-select-key is pressed, ds 'remembers' the last selection and reverts
1778
+ * to that state if the selection is not kept, to mimic the natural OS behaviour
1779
+ * = if item was selected and is not in selection anymore, reselect it
1780
+ * = if item was not selected and is not in selection anymore, unselect it
1781
+ */
1782
+ if (inSelection && !inPrevSelection)
1783
+ SelectedSet.delete(element);
1784
+ else if (!inSelection && inPrevSelection)
1785
+ SelectedSet.add(element);
1786
+ element.classList.remove(hoverClassName);
1787
+ };
1788
+
1789
+ // @TODO: calculate the difference in all directions based on the mouse position! (since the selection square ratio won’t change we don’t have to re-calculate and re-fetch the position of every element in the square during drag)
1790
+ /** Returns the compound bounding rect of multiple elements */
1791
+ const getSelectionRect = (SelectedSet) => {
1792
+ const rect = {
1793
+ top: Number.POSITIVE_INFINITY,
1794
+ left: Number.POSITIVE_INFINITY,
1795
+ bottom: Number.NEGATIVE_INFINITY,
1796
+ right: Number.NEGATIVE_INFINITY,
1797
+ width: Number.NEGATIVE_INFINITY,
1798
+ height: Number.NEGATIVE_INFINITY,
1799
+ };
1800
+ SelectedSet.rects.forEach(elementRect => {
1801
+ rect.top = Math.min(rect.top, elementRect.top || rect.top);
1802
+ rect.left = Math.min(rect.left, elementRect.left || rect.left);
1803
+ rect.bottom = Math.max(rect.bottom, elementRect.bottom || rect.bottom);
1804
+ rect.right = Math.max(rect.right, elementRect.right || rect.right);
1805
+ });
1806
+ rect.height = rect.bottom - rect.top;
1807
+ rect.width = rect.right - rect.left;
1808
+ return rect;
1809
+ };
1810
+
1811
+ class Selection {
1812
+ _prevSelectedSet = new Set();
1813
+ _boundingRect;
1814
+ _timeout;
1815
+ DS;
1816
+ PS;
1817
+ Settings;
1818
+ constructor({ DS, PS }) {
1819
+ this.DS = DS;
1820
+ this.PS = PS;
1821
+ this.Settings = this.DS.stores.SettingsStore.s;
1822
+ this.PS.subscribe('Interaction:start', this.start);
1823
+ this.PS.subscribe('Interaction:update', this.update);
1824
+ }
1825
+ /** Stores the previous selection (solves #9) */
1826
+ _storePrevious(event) {
1827
+ const { stores: { KeyStore }, SelectedSet, } = this.DS;
1828
+ if (KeyStore.isMultiSelectKeyPressed(event))
1829
+ this._prevSelectedSet = new Set(SelectedSet);
1830
+ else
1831
+ this._prevSelectedSet = new Set();
1832
+ }
1833
+ start = ({ event, isDragging, }) => {
1834
+ if (isDragging)
1835
+ return;
1836
+ this._storePrevious(event);
1837
+ this._handleInsideSelection(true, event);
1838
+ };
1839
+ update = ({ isDragging }) => {
1840
+ if (isDragging || this.DS.continue)
1841
+ return;
1842
+ this._handleInsideSelection();
1843
+ };
1844
+ /** Checks if any selectable element is inside selection. */
1845
+ _handleInsideSelection = (force, event) => {
1846
+ const { SelectableSet, SelectorArea, Selector } = this.DS;
1847
+ const multiSelectionToggle = this.DS.stores.KeyStore.isMultiSelectKeyPressed(event) &&
1848
+ this.Settings.multiSelectToggling;
1849
+ const selectionThreshold = this.Settings.selectionThreshold;
1850
+ const elRects = SelectableSet.rects;
1851
+ const selectorRect = Selector.rect;
1852
+ const select = new Map();
1853
+ const unselect = new Map();
1854
+ for (const [element, elementRect] of elRects) {
1855
+ if (!SelectorArea.isInside(element, elementRect))
1856
+ continue;
1857
+ if (isCollision(elementRect, selectorRect, selectionThreshold))
1858
+ select.set(element, elementRect);
1859
+ else
1860
+ unselect.set(element, elementRect);
1861
+ }
1862
+ if (this.DS.continue)
1863
+ return;
1864
+ // [PUBLICLY EXPOSED METHOD]
1865
+ const { select: filteredSelect, unselect: filteredUnselect } = this.filterSelected({ select, unselect, selectorRect });
1866
+ filteredSelect.forEach((_, element) => handleSelection({
1867
+ element,
1868
+ force,
1869
+ multiSelectionToggle,
1870
+ SelectedSet: this.DS.SelectedSet,
1871
+ hoverClassName: this.Settings.hoverClass,
1872
+ }));
1873
+ filteredUnselect.forEach((_, element) => handleUnSelection({
1874
+ element,
1875
+ force,
1876
+ SelectedSet: this.DS.SelectedSet,
1877
+ hoverClassName: this.Settings.hoverClass,
1878
+ PrevSelectedSet: this._prevSelectedSet,
1879
+ }));
1880
+ };
1881
+ get boundingRect() {
1882
+ if (this._boundingRect)
1883
+ return this._boundingRect;
1884
+ this._boundingRect = getSelectionRect(this.DS.SelectedSet);
1885
+ // since elements can be moved, we need to update the rects every X ms
1886
+ if (this._timeout)
1887
+ clearTimeout(this._timeout);
1888
+ this._timeout = setTimeout(() => (this._boundingRect = undefined), this.Settings.refreshMemoryRate);
1889
+ return this._boundingRect;
1890
+ }
1891
+ ////
1892
+ // [PUBLICLY EXPOSED METHODS]
1893
+ /**
1894
+ * Can be overridden to apply further filtering logic after the items to select are identified but before they actually get selected
1895
+ * Is expected to return the select / unselect maps in the same shape as passed in
1896
+ */
1897
+ filterSelected = ({ select, unselect, selectorRect, }) => ({ select, unselect });
1898
+ }
1899
+
1900
+ const createSelectorAreaElement = () => {
1901
+ const node = document.createElement('div');
1902
+ node.style.position = 'fixed';
1903
+ node.style.overflow = 'hidden';
1904
+ node.style.pointerEvents = 'none';
1905
+ node.style.zIndex = '999999999999999999';
1906
+ return node;
1907
+ };
1908
+
1909
+ /**
1910
+ * Returns the edges that an element is overflowing
1911
+ */
1912
+ const getOverflowEdges = ({ elementRect, containerRect, tolerance = {
1913
+ x: 0,
1914
+ y: 0,
1915
+ }, }) => {
1916
+ const edges = [];
1917
+ if (elementRect.top - tolerance.y < containerRect.top)
1918
+ edges.push('top');
1919
+ if (elementRect.left - tolerance.x < containerRect.left)
1920
+ edges.push('left');
1921
+ if (elementRect.bottom + tolerance.y > containerRect.bottom)
1922
+ edges.push('bottom');
1923
+ if (elementRect.right + tolerance.y > containerRect.right)
1924
+ edges.push('right');
1925
+ return edges;
1926
+ };
1927
+
1928
+ class SelectorArea {
1929
+ _scrollInterval;
1930
+ _rect;
1931
+ currentEdges = [];
1932
+ DS;
1933
+ PS;
1934
+ Settings;
1935
+ HTMLNode;
1936
+ constructor({ DS, PS }) {
1937
+ this.DS = DS;
1938
+ this.PS = PS;
1939
+ this.Settings = this.DS.stores.SettingsStore.s;
1940
+ this.HTMLNode = createSelectorAreaElement();
1941
+ this.PS.subscribe('Settings:updated:selectorAreaClass', ({ settings }) => {
1942
+ this.HTMLNode.classList.remove(settings['selectorAreaClass:pre']);
1943
+ this.HTMLNode.classList.add(settings['selectorAreaClass']);
1944
+ });
1945
+ this.HTMLNode.classList.add(this.Settings.selectorAreaClass);
1946
+ this.PS.subscribe('Area:modified', this.updatePos);
1947
+ this.PS.subscribe('Area:modified', this.updatePos);
1948
+ this.PS.subscribe('Interaction:init', this.init);
1949
+ this.PS.subscribe('Interaction:start', ({ isDraggingKeyboard }) => this.startAutoScroll({ isDraggingKeyboard }));
1950
+ this.PS.subscribe('Interaction:end', () => {
1951
+ this.updatePos();
1952
+ this.stopAutoScroll();
1953
+ });
1954
+ }
1955
+ init = () => {
1956
+ this.applyElements('append');
1957
+ this.updatePos();
1958
+ };
1959
+ /** Adding / Removing elements to document */
1960
+ applyElements = (method) => {
1961
+ const docEl = document.body ? 'body' : 'documentElement';
1962
+ const methodName = `${method}Child`;
1963
+ this.HTMLNode[methodName](this.DS.Selector.HTMLNode);
1964
+ document[docEl][methodName](this.HTMLNode);
1965
+ };
1966
+ /** Updates the selectorAreas positions to match the areas */
1967
+ updatePos = () => {
1968
+ this._rect = undefined;
1969
+ const rect = this.DS.Area.rect;
1970
+ const border = this.DS.Area.computedBorder;
1971
+ const { style } = this.HTMLNode;
1972
+ const top = `${rect.top + border.top}px`;
1973
+ const left = `${rect.left + border.left}px`;
1974
+ const width = `${rect.width}px`;
1975
+ const height = `${rect.height}px`;
1976
+ if (style.top !== top)
1977
+ style.top = top;
1978
+ if (style.left !== left)
1979
+ style.left = left;
1980
+ if (style.width !== width)
1981
+ style.width = width;
1982
+ if (style.height !== height)
1983
+ style.height = height;
1984
+ };
1985
+ stop = (remove) => {
1986
+ this.stopAutoScroll();
1987
+ if (remove)
1988
+ this.applyElements('remove');
1989
+ };
1990
+ //////////////////////////////////////////////////////////////////////////////////////
1991
+ // AutoScroll
1992
+ startAutoScroll = ({ isDraggingKeyboard, }) => {
1993
+ if (isDraggingKeyboard)
1994
+ return;
1995
+ this.currentEdges = [];
1996
+ this._scrollInterval = setInterval(() => this.handleAutoScroll(), 16);
1997
+ };
1998
+ /** Creates an interval that auto-scrolls while the cursor is near the edge */
1999
+ handleAutoScroll = () => {
2000
+ if (this.DS.continue)
2001
+ return;
2002
+ const { stores: { PointerStore }, Area, } = this.DS;
2003
+ this.currentEdges = getOverflowEdges({
2004
+ elementRect: vect2rect(PointerStore.currentVal),
2005
+ containerRect: this.rect,
2006
+ tolerance: this.Settings.overflowTolerance,
2007
+ });
2008
+ if (this.currentEdges.length)
2009
+ Area.scroll(this.currentEdges, this.Settings.autoScrollSpeed);
2010
+ };
2011
+ stopAutoScroll = () => {
2012
+ this.currentEdges = [];
2013
+ clearInterval(this._scrollInterval);
2014
+ };
2015
+ //////////////////////////////////////////////////////////////////////////////////////
2016
+ // Booleans
2017
+ /**
2018
+ * Checks if the element is either inside the Selector Area (as a reachable child or touching the area)
2019
+ * @param elementRect - slight performance improvements when passed
2020
+ */
2021
+ isInside = (element, elementRect) => {
2022
+ if (this.DS.Area.HTMLNode.contains(element) &&
2023
+ this.DS.stores.ScrollStore.canScroll)
2024
+ return true;
2025
+ return isCollision(this.rect, elementRect || element.getBoundingClientRect());
2026
+ };
2027
+ /** checks if the click was triggered on the area. */
2028
+ isClicked(event) {
2029
+ const { stores: { PointerStore }, } = this.DS;
2030
+ const initialVal = event
2031
+ ? PointerStore.getPointerPosition(event)
2032
+ : PointerStore.initialVal;
2033
+ return isCollision({
2034
+ left: initialVal.x,
2035
+ top: initialVal.y,
2036
+ right: initialVal.x,
2037
+ bottom: initialVal.y,
2038
+ }, this.rect);
2039
+ }
2040
+ get rect() {
2041
+ if (this._rect)
2042
+ return this._rect;
2043
+ return (this._rect = this.HTMLNode.getBoundingClientRect());
2044
+ }
2045
+ }
2046
+
2047
+ const wrongTypeWarn = (key, type) => console.warn(`[DragSelect] TypeIssue: setting "${key}" is not of type "${type}".`);
2048
+ const hydrateHelper = (key, value, withFallback, fallback) => {
2049
+ // no value available
2050
+ if (value === undefined)
2051
+ return withFallback ? { [key]: fallback } : {};
2052
+ // force unsetting of a value
2053
+ if (value === null)
2054
+ return { [key]: null };
2055
+ // TypeCheck [GENERIC]
2056
+ let isAvailable = true; // if it’s not undefined, it was set voluntarily
2057
+ let forceFallback = false;
2058
+ // TypeCheck [String]
2059
+ const expectedString = typeof fallback === 'string';
2060
+ if (expectedString)
2061
+ isAvailable = typeof value === 'string' || value instanceof String;
2062
+ if (expectedString && !isAvailable) {
2063
+ forceFallback = true;
2064
+ wrongTypeWarn(key, 'string');
2065
+ }
2066
+ // TypeCheck [Number]
2067
+ const expectedNumber = !Number.isNaN(fallback) && typeof fallback === 'number';
2068
+ if (expectedNumber)
2069
+ isAvailable = !Number.isNaN(value) && typeof value === 'number';
2070
+ if (expectedNumber && !isAvailable) {
2071
+ forceFallback = true;
2072
+ wrongTypeWarn(key, 'number');
2073
+ }
2074
+ // TypeCheck [Object]
2075
+ const expectedObject = Object.prototype.toString.call(fallback) === '[object Object]';
2076
+ if (expectedObject)
2077
+ isAvailable = Object.prototype.toString.call(value) === '[object Object]';
2078
+ if (expectedObject && !isAvailable) {
2079
+ forceFallback = true;
2080
+ wrongTypeWarn(key, 'object');
2081
+ }
2082
+ // TypeCheck [Boolean]
2083
+ const expectedBoolean = typeof fallback === 'boolean';
2084
+ if (expectedBoolean)
2085
+ isAvailable = typeof value === 'boolean';
2086
+ if (expectedBoolean && !isAvailable) {
2087
+ forceFallback = true;
2088
+ wrongTypeWarn(key, 'boolean');
2089
+ }
2090
+ // TypeCheck [Array]
2091
+ const expectedArray = Array.isArray(fallback);
2092
+ if (expectedArray)
2093
+ isAvailable = Array.isArray(value);
2094
+ if (expectedArray && !isAvailable) {
2095
+ forceFallback = true;
2096
+ wrongTypeWarn(key, 'array');
2097
+ }
2098
+ const isFallback = forceFallback || withFallback;
2099
+ // Special rule for [dragKeys]
2100
+ if (key === 'dragKeys' && isAvailable)
2101
+ return { [key]: Object.assign(fallback, value) };
2102
+ if (key === 'dragKeys' && !isAvailable)
2103
+ return isFallback ? { [key]: fallback } : {};
2104
+ // Special rule for [dropZones]
2105
+ if (key === 'dropZones' &&
2106
+ isAvailable &&
2107
+ Array.isArray(value) &&
2108
+ new Set(value.map((v) => v.id)).size !== value.length)
2109
+ console.warn(`[DragSelect] UniqueConstraintsIssue: setting "dropZones" contains duplicate ids.`);
2110
+ if (isAvailable)
2111
+ return { [key]: value };
2112
+ if (isFallback)
2113
+ return { [key]: fallback };
2114
+ return {};
2115
+ };
2116
+ /**
2117
+ * This helper method creates the setting object,
2118
+ * - if the settings provided are of wrong type, the fallback value will be used
2119
+ * - - except for if settings are undefined or explicitly marked as "null"
2120
+ * - if "withfallback" is true, it will return the object with all settings:
2121
+ * - - if not provided from the settings object (or wrong type), the fallback will be used
2122
+ * (the fallback value for each setting is the last prop of the hydrateHelper)
2123
+ */
2124
+ const hydrateSettings = (settings, withFallback) => ({
2125
+ ...hydrateHelper('area', settings.area, withFallback, document),
2126
+ ...hydrateHelper('selectables', settings.selectables, withFallback, null),
2127
+ ...hydrateHelper('autoScrollSpeed', settings.autoScrollSpeed, withFallback, 5),
2128
+ ...hydrateHelper('overflowTolerance', settings.overflowTolerance, withFallback, { x: 25, y: 25 }),
2129
+ ...hydrateHelper('zoom', settings.zoom, withFallback, 1),
2130
+ ...hydrateHelper('customStyles', settings.customStyles, withFallback, false),
2131
+ ...hydrateHelper('multiSelectMode', settings.multiSelectMode, withFallback, false),
2132
+ ...hydrateHelper('multiSelectToggling', settings.multiSelectToggling, withFallback, true),
2133
+ ...hydrateHelper('multiSelectKeys', settings.multiSelectKeys, withFallback, [
2134
+ 'Control',
2135
+ 'Shift',
2136
+ 'Meta',
2137
+ ]),
2138
+ ...hydrateHelper('selector', settings.selector, withFallback, null),
2139
+ ...hydrateHelper('selectionThreshold', settings.selectionThreshold, withFallback, 0),
2140
+ ...hydrateHelper('draggability', settings.draggability, withFallback, true),
2141
+ ...hydrateHelper('immediateDrag', settings.immediateDrag, withFallback, true),
2142
+ ...hydrateHelper('keyboardDrag', settings.keyboardDrag, withFallback, true),
2143
+ ...hydrateHelper('dragKeys', settings.dragKeys, withFallback, {
2144
+ up: ['ArrowUp'],
2145
+ down: ['ArrowDown'],
2146
+ left: ['ArrowLeft'],
2147
+ right: ['ArrowRight'],
2148
+ }),
2149
+ ...hydrateHelper('keyboardDragSpeed', settings.keyboardDragSpeed, withFallback, 10),
2150
+ ...hydrateHelper('useTransform', settings.useTransform, withFallback, true),
2151
+ ...hydrateHelper('refreshMemoryRate', settings.refreshMemoryRate, withFallback, 80),
2152
+ ...hydrateHelper('dropZones', settings.dropZones, withFallback, []),
2153
+ ...hydrateHelper('dropInsideThreshold', settings.dropInsideThreshold, withFallback, 1),
2154
+ ...hydrateHelper('dropTargetThreshold', settings.dropTargetThreshold, withFallback, 0),
2155
+ ...hydrateHelper('usePointerEvents', settings.usePointerEvents, withFallback, false),
2156
+ ...hydrateHelper('hoverClass', settings.hoverClass, withFallback, 'ds-hover'),
2157
+ ...hydrateHelper('selectableClass', settings.selectableClass, withFallback, 'ds-selectable'),
2158
+ ...hydrateHelper('selectedClass', settings.selectedClass, withFallback, 'ds-selected'),
2159
+ ...hydrateHelper('selectorClass', settings.selectorClass, withFallback, 'ds-selector'),
2160
+ ...hydrateHelper('selectorAreaClass', settings.selectorAreaClass, withFallback, 'ds-selector-area'),
2161
+ ...hydrateHelper('droppedTargetClass', settings.droppedTargetClass, withFallback, 'ds-dropped-target'),
2162
+ ...hydrateHelper('droppedInsideClass', settings.droppedInsideClass, withFallback, 'ds-dropped-inside'),
2163
+ ...hydrateHelper('droppableClass', settings.droppableClass, withFallback, 'ds-droppable'),
2164
+ ...hydrateHelper('dropZoneClass', settings.dropZoneClass, withFallback, 'ds-dropzone'),
2165
+ ...hydrateHelper('dropZoneReadyClass', settings.dropZoneReadyClass, withFallback, 'ds-dropzone-ready'),
2166
+ ...hydrateHelper('dropZoneTargetClass', settings.dropZoneTargetClass, withFallback, 'ds-dropzone-target'),
2167
+ ...hydrateHelper('dropZoneInsideClass', settings.dropZoneInsideClass, withFallback, 'ds-dropzone-inside'),
2168
+ });
2169
+
2170
+ class SettingsStore {
2171
+ _settings = {};
2172
+ /**
2173
+ * Holds the settings and their previous value `:pre`
2174
+ * @example {
2175
+ * autoScrollSpeed: 3,
2176
+ * 'autoScrollSpeed:pre': 5
2177
+ * }
2178
+ **/
2179
+ s = {};
2180
+ PS;
2181
+ /**
2182
+ * @class ScrollStore
2183
+ * @constructor ScrollStore
2184
+ * @param {{ DS:DragSelect, settings:Settings }} p
2185
+ * @ignore
2186
+ */
2187
+ constructor({ PS, settings }) {
2188
+ this.PS = PS;
2189
+ this.update({ settings, init: true });
2190
+ }
2191
+ update = ({ settings, init }) => {
2192
+ this.PS.publish('Settings:updated:pre', {
2193
+ settings: this._settings,
2194
+ 'settings:init': Boolean(init),
2195
+ 'settings:new': settings
2196
+ });
2197
+ this._update({ settings, init });
2198
+ };
2199
+ _update = ({ settings = {}, init = false }) => {
2200
+ const _settings = hydrateSettings(settings, init);
2201
+ for (const [key, value] of Object.entries(_settings)) {
2202
+ ((key, value) => {
2203
+ if (!(key in this._settings)) {
2204
+ Object.defineProperty(this.s, key, {
2205
+ get: () => this._settings[key],
2206
+ set: (newValue) => this.update({ settings: { [key]: newValue } }),
2207
+ });
2208
+ }
2209
+ this._settings[`${key}:pre`] = this._settings[key]; // need to cast as K, see https://stackoverflow.com/a/76070928/3712591
2210
+ this._settings[key] = value;
2211
+ const update = {
2212
+ settings: this._settings,
2213
+ 'settings:init': init,
2214
+ 'settings:new': settings
2215
+ };
2216
+ this.PS.publish('Settings:updated', update);
2217
+ this.PS.publish(`Settings:updated:${key}`, update);
2218
+ })(key, value); // method used for typecasting, see https://stackoverflow.com/q/76036535/3712591
2219
+ }
2220
+ };
2221
+ }
2222
+
2223
+ const deprecatedNamesMap = {
2224
+ elementselect: 'DS:select',
2225
+ elementunselect: 'DS:unselect',
2226
+ autoscroll: 'DS:scroll',
2227
+ dragstart: 'DS:start',
2228
+ dragmove: 'DS:update',
2229
+ callback: 'DS:end',
2230
+ preelementselect: 'DS:select:pre',
2231
+ preelementunselect: 'DS:unselect:pre',
2232
+ preautoscroll: 'DS:scroll:pre',
2233
+ predragstart: 'DS:start:pre',
2234
+ predragmove: 'DS:update:pre',
2235
+ precallback: 'DS:end:pre',
2236
+ };
2237
+ const endExtraData = (data, DS) => {
2238
+ const target = DS.DropZones.getTarget(data);
2239
+ return {
2240
+ ...data,
2241
+ ...(target ? { dropTarget: target.toObject() } : {}),
2242
+ };
2243
+ };
2244
+ /** Maps internal events to external ones */
2245
+ const subscriberAliases = ({ PS, DS, }) => {
2246
+ const mapping = {
2247
+ 'Selected:added': [
2248
+ { name: 'preelementselect' },
2249
+ { name: 'elementselect' },
2250
+ { name: 'DS:select:pre' },
2251
+ { name: 'DS:select' },
2252
+ ],
2253
+ 'Selected:removed': [
2254
+ { name: 'preelementunselect' },
2255
+ { name: 'elementunselect' },
2256
+ { name: 'DS:unselect:pre' },
2257
+ { name: 'DS:unselect' },
2258
+ ],
2259
+ 'Selectable:added': [{ name: 'DS:added:pre' }, { name: 'DS:added' }],
2260
+ 'Selectable:removed': [{ name: 'DS:removed:pre' }, { name: 'DS:removed' }],
2261
+ 'Area:scroll': [
2262
+ { name: 'preautoscroll' },
2263
+ { name: 'autoscroll' },
2264
+ { name: 'DS:scroll:pre' },
2265
+ { name: 'DS:scroll' },
2266
+ ],
2267
+ 'Interaction:start': [
2268
+ { name: 'predragstart' },
2269
+ { name: 'dragstart' },
2270
+ { name: 'DS:start:pre' },
2271
+ { name: 'DS:start' },
2272
+ ],
2273
+ 'Interaction:update': [
2274
+ { name: 'predragmove', condition: (data) => (data.event ? data : null) },
2275
+ { name: 'dragmove', condition: (data) => (data.event ? data : null) },
2276
+ {
2277
+ name: 'DS:update:pre',
2278
+ condition: (data) => (data.event ? data : null),
2279
+ },
2280
+ { name: 'DS:update', condition: (data) => (data.event ? data : null) },
2281
+ ],
2282
+ 'Interaction:end': [
2283
+ { name: 'precallback', extraData: (data, DS) => endExtraData(data, DS) },
2284
+ { name: 'callback', extraData: (data, DS) => endExtraData(data, DS) },
2285
+ { name: 'DS:end:pre', extraData: (data, DS) => endExtraData(data, DS) },
2286
+ { name: 'DS:end', extraData: (data, DS) => endExtraData(data, DS) },
2287
+ ],
2288
+ };
2289
+ for (const [sub_name, sub_pubs] of Object.entries(mapping))
2290
+ addSubscribers({ sub_name, sub_pubs, DS, PS });
2291
+ };
2292
+ const addSubscribers = ({ sub_name, DS, PS, sub_pubs, }) => {
2293
+ // Subscribe to the internal event
2294
+ PS.subscribe(sub_name, (data) =>
2295
+ // publish to each of the mapped ones
2296
+ sub_pubs.forEach((sub_pub) => publish({ sub_pub, data, DS })));
2297
+ };
2298
+ const publish = ({ sub_pub, data, DS, }) => {
2299
+ // If the events condition is met, publish the external event
2300
+ const cleanedData = !sub_pub.condition ? data : sub_pub.condition(data, DS);
2301
+ if (cleanedData) {
2302
+ const extra = (sub_pub.extraData && sub_pub.extraData(data, DS)) || {};
2303
+ DS.publish(sub_pub.name, {
2304
+ // add extra data as needed
2305
+ items: DS.SelectedSet.elements,
2306
+ isDragging: DS.Interaction.isDragging,
2307
+ ...cleanedData,
2308
+ ...extra,
2309
+ });
2310
+ }
2311
+ };
2312
+
2313
+ /*
2314
+ ____ _____ __ __
2315
+ / __ \_________ _____ _/ ___/___ / /__ _____/ /_
2316
+ / / / / ___/ __ `/ __ `/\__ \/ _ \/ / _ \/ ___/ __/
2317
+ / /_/ / / / /_/ / /_/ /___/ / __/ / __/ /__/ /_
2318
+ /_____/_/ \__,_/\__, //____/\___/_/\___/\___/\__/
2319
+ /____/
2320
+
2321
+ {*} {*} STAR THIS PROJECT ON GITHUB {*} {*}
2322
+
2323
+ https://github.com/ThibaultJanBeyer/DragSelect
2324
+ Please give it a like, this is what makes me happy :-)
2325
+ Thank You
2326
+
2327
+ {*} {*} STAR THIS PROJECT ON GITHUB {*} {*}
2328
+
2329
+ ***************************************
2330
+ ********* GPLv3 / Commercial **********
2331
+ ***************************************
2332
+ Created 2017 by ThibaultJanBeyer
2333
+ Web: http://www.DragSelect.com/
2334
+ GitHub: https://github.com/ThibaultJanBeyer/DragSelect
2335
+ ***************************************
2336
+ */
2337
+ // Setup
2338
+ /// ///////////////////////////////////////////////////////////////////////////////////
2339
+ class DragSelect {
2340
+ /** used to skip all current Selection and dragNdrop functionality */
2341
+ continue = false;
2342
+ PubSub;
2343
+ stores;
2344
+ Area;
2345
+ Selector;
2346
+ SelectorArea;
2347
+ SelectableSet;
2348
+ SelectedSet;
2349
+ Selection;
2350
+ Drag;
2351
+ DropZones;
2352
+ Interaction;
2353
+ stopped;
2354
+ constructor(settings) {
2355
+ this.stopped = false;
2356
+ this.PubSub = new PubSub({ DS: this });
2357
+ this.stores = {};
2358
+ (this.stores.SettingsStore = new SettingsStore({
2359
+ settings,
2360
+ PS: this.PubSub,
2361
+ })),
2362
+ (this.stores.PointerStore = new PointerStore({
2363
+ DS: this,
2364
+ PS: this.PubSub,
2365
+ })),
2366
+ (this.stores.ScrollStore = new ScrollStore({
2367
+ DS: this,
2368
+ PS: this.PubSub,
2369
+ })),
2370
+ (this.stores.KeyStore = new KeyStore({ DS: this, PS: this.PubSub })),
2371
+ (this.Area = new Area({ DS: this, PS: this.PubSub }));
2372
+ this.Selector = new Selector({ DS: this, PS: this.PubSub });
2373
+ this.SelectorArea = new SelectorArea({ DS: this, PS: this.PubSub });
2374
+ this.SelectableSet = new SelectableSet({ DS: this, PS: this.PubSub });
2375
+ this.SelectedSet = new SelectedSet({ DS: this, PS: this.PubSub });
2376
+ this.Selection = new Selection({ DS: this, PS: this.PubSub });
2377
+ this.Drag = new Drag({ DS: this, PS: this.PubSub });
2378
+ this.DropZones = new DropZones({ DS: this, PS: this.PubSub });
2379
+ this.Interaction = new Interaction({ DS: this, PS: this.PubSub });
2380
+ subscriberAliases({ DS: this, PS: this.PubSub });
2381
+ this.PubSub.subscribe('Interaction:end', () => (this.continue = false));
2382
+ this.PubSub.subscribe('DS:end', ({ items }) => (this.continue = false));
2383
+ this.start();
2384
+ }
2385
+ // Useful methods for the user
2386
+ //////////////////////////////////////////////////////////////////////////////////////
2387
+ static isCollision;
2388
+ // any input data from the user is valid in this public PubSub but the exposed values are recommended
2389
+ /** Subscribe to events */
2390
+ subscribe = (eventName, callback) => {
2391
+ // Deprecation warnings
2392
+ if (deprecatedNamesMap[eventName])
2393
+ console.warn(`[DragSelect]: The event name "${eventName}" is deprecated and was/will be removed in a future version. Please use the new event name "${deprecatedNamesMap[eventName]}" instead.`);
2394
+ this.PubSub.subscribe(eventName, callback);
2395
+ };
2396
+ /** Un-Subscribe from events */
2397
+ unsubscribe = (eventName, callback, id) => this.PubSub.unsubscribe(eventName, callback, id);
2398
+ /** Publish events */
2399
+ publish = (eventName, data) => this.PubSub.publish(eventName, data);
2400
+ /** Initializes the functionality. Automatically triggered when created. Also, reset the functionality after a teardown */
2401
+ start = () => {
2402
+ this.stopped = false;
2403
+ this.Interaction.init();
2404
+ };
2405
+ /**
2406
+ * Complete function teardown
2407
+ * Will teardown/stop the whole functionality
2408
+ * @param remove if elements should be removed.
2409
+ * @param fromSelection if elements should also be added/removed to the selection.
2410
+ * @param withCallback if elements should also be added/removed to the selection.
2411
+ */
2412
+ stop(remove = true, fromSelection = true, withCallback = false) {
2413
+ if (withCallback)
2414
+ this.publish('DS:end', {
2415
+ items: this.SelectedSet.elements,
2416
+ isDragging: this.Interaction.isDragging,
2417
+ });
2418
+ this.Interaction.stop();
2419
+ this.Area.stop();
2420
+ this.Drag.stop();
2421
+ this.Selector.stop();
2422
+ this.SelectorArea.stop(remove);
2423
+ this.stores.KeyStore.stop();
2424
+ this.stores.PointerStore.stop();
2425
+ this.stores.ScrollStore.stop();
2426
+ if (remove)
2427
+ this.SelectableSet.clear();
2428
+ if (fromSelection)
2429
+ this.SelectedSet.clear();
2430
+ this.stopped = true;
2431
+ }
2432
+ /**
2433
+ * Utility to override DragSelect internal functionality:
2434
+ * Break will skip the selection or dragging functionality (until after the callback) but let everything continue to run.
2435
+ * Useful utility to write your own functionality/move/dragNdrop based on DragSelect pointer positions.
2436
+ */
2437
+ break = () => (this.continue = true);
2438
+ /** Update any setting dynamically */
2439
+ setSettings = (settings) => this.stores.SettingsStore.update({ settings });
2440
+ /** Returns the current selected nodes */
2441
+ getSelection = () => this.SelectedSet.elements;
2442
+ /**
2443
+ * Adds several elements to the selection list also adds the specific classes and take into account all calculations.
2444
+ * Does not clear the selection, in contrary to .setSelection. Can add multiple elements at once
2445
+ * @param elements one or multiple elements
2446
+ * @param triggerCallback if callback should be called
2447
+ * @param dontAddToSelectables if element should not be added to the list of selectable elements
2448
+ * @return all selected elements
2449
+ */
2450
+ addSelection(elements, triggerCallback = false, dontAddToSelectables = false) {
2451
+ const els = ensureArray(elements);
2452
+ this.SelectedSet.addAll(els);
2453
+ if (!dontAddToSelectables)
2454
+ this.addSelectables(elements, false, false);
2455
+ if (triggerCallback)
2456
+ this.PubSub.publish('DS:end', {
2457
+ items: this.SelectedSet.elements,
2458
+ isDragging: this.Interaction.isDragging,
2459
+ });
2460
+ return this.getSelection();
2461
+ }
2462
+ /**
2463
+ * Removes specific elements from the selection
2464
+ * Multiple elements can be given at once, in contrary to unselect
2465
+ * @param elements one or multiple elements
2466
+ * @param triggerCallback if callback should be called
2467
+ * @param removeFromSelectables if element should be removed from the list of selectable elements
2468
+ * @return all selected elements
2469
+ */
2470
+ removeSelection(elements, triggerCallback = false, removeFromSelectables = false) {
2471
+ const els = ensureArray(elements);
2472
+ this.SelectedSet.deleteAll(els);
2473
+ if (removeFromSelectables)
2474
+ this.removeSelectables(elements, false, false);
2475
+ if (triggerCallback)
2476
+ this.PubSub.publish('DS:end', {
2477
+ items: this.SelectedSet.elements,
2478
+ isDragging: this.Interaction.isDragging,
2479
+ });
2480
+ return this.getSelection();
2481
+ }
2482
+ /**
2483
+ * Toggles specific elements from the selection:
2484
+ * If element is not in selection it will be added, if it is already selected, it will be removed.
2485
+ * Multiple elements can be given at once.
2486
+ * @param elements one or multiple elements
2487
+ * @param triggerCallback if callback should be called
2488
+ * @param removeFromSelectables if element should not be added/removed to the list of selectable elements accordingly
2489
+ * @return all selected elements
2490
+ */
2491
+ toggleSelection(elements, triggerCallback = false, removeFromSelectables = false) {
2492
+ const els = ensureArray(elements);
2493
+ els.forEach((el) => this.SelectedSet.has(el)
2494
+ ? this.removeSelection(elements, triggerCallback, removeFromSelectables)
2495
+ : this.addSelection(elements, triggerCallback, removeFromSelectables));
2496
+ if (triggerCallback)
2497
+ this.PubSub.publish('DS:end', {
2498
+ items: this.SelectedSet.elements,
2499
+ isDragging: this.Interaction.isDragging,
2500
+ });
2501
+ return this.getSelection();
2502
+ }
2503
+ /**
2504
+ * Sets the current selected elements and optionally run the callback
2505
+ * By default, adds new elements also to the list of selectables
2506
+ * @param elements dom elements
2507
+ * @param triggerCallback if callback should be called
2508
+ * @param dontAddToSelectables if element should not be added to the list of selectable elements
2509
+ */
2510
+ setSelection(elements, triggerCallback = false, dontAddToSelectables = false) {
2511
+ this.clearSelection();
2512
+ this.addSelection(elements, triggerCallback, dontAddToSelectables);
2513
+ return this.getSelection();
2514
+ }
2515
+ /**
2516
+ * Unselect / Deselect all current selected Nodes
2517
+ * @param triggerCallback if callback should be called
2518
+ * @return this.selected, should be empty
2519
+ */
2520
+ clearSelection(triggerCallback = false) {
2521
+ this.SelectedSet.clear();
2522
+ if (triggerCallback)
2523
+ this.PubSub.publish('DS:end', {
2524
+ items: this.SelectedSet.elements,
2525
+ isDragging: this.Interaction.isDragging,
2526
+ });
2527
+ return this.getSelection();
2528
+ }
2529
+ /**
2530
+ * Add elements that can be selected. No node is added twice
2531
+ * @param elements dom element(s)
2532
+ * @param addToSelection if elements should also be added to current selection
2533
+ * @param triggerCallback if callback should be called
2534
+ * @return the added element(s)
2535
+ */
2536
+ addSelectables(elements, addToSelection, triggerCallback) {
2537
+ const els = ensureArray(elements);
2538
+ this.SelectableSet.addAll(els);
2539
+ if (addToSelection)
2540
+ this.SelectedSet.addAll(els);
2541
+ if (triggerCallback)
2542
+ this.PubSub.publish('DS:end', {
2543
+ items: this.SelectedSet.elements,
2544
+ isDragging: this.Interaction.isDragging,
2545
+ });
2546
+ return els;
2547
+ }
2548
+ /** Gets all nodes that can potentially be selected */
2549
+ getSelectables = () => this.SelectableSet.elements;
2550
+ /**
2551
+ * Remove elements from the elements that can be selected.
2552
+ * @param elements dom element(s)
2553
+ * @param removeFromSelection if elements should also be removed from current selection
2554
+ * @param triggerCallback if callback should be called
2555
+ * @return the removed element(s)
2556
+ */
2557
+ removeSelectables(elements, removeFromSelection, triggerCallback) {
2558
+ const els = ensureArray(elements);
2559
+ this.SelectableSet.deleteAll(els);
2560
+ if (removeFromSelection)
2561
+ this.removeSelection(elements);
2562
+ if (triggerCallback)
2563
+ this.PubSub.publish('DS:end', {
2564
+ items: this.SelectedSet.elements,
2565
+ isDragging: this.Interaction.isDragging,
2566
+ });
2567
+ return els;
2568
+ }
2569
+ /** The starting/initial position of the cursor/selector */
2570
+ getInitialCursorPosition = () => this.stores.PointerStore.initialVal;
2571
+ /** The last seen position of the cursor/selector */
2572
+ getCurrentCursorPosition = () => this.stores.PointerStore.currentVal;
2573
+ /** The previous position of the cursor/selector */
2574
+ getPreviousCursorPosition = () => this.stores.PointerStore.lastVal;
2575
+ /** The starting/initial position of the cursor/selector */
2576
+ getInitialCursorPositionArea = () => this.stores.PointerStore.initialValArea;
2577
+ /** The last seen position of the cursor/selector */
2578
+ getCurrentCursorPositionArea = () => this.stores.PointerStore.currentValArea;
2579
+ /** The previous position of the cursor/selector */
2580
+ getPreviousCursorPositionArea = () => this.stores.PointerStore.lastValArea;
2581
+ /** Whether the multi-selection key was pressed */
2582
+ isMultiSelect = (event) => this.stores.KeyStore.isMultiSelectKeyPressed(event);
2583
+ /** Whether the user is currently drag n dropping elements (instead of selection) */
2584
+ isDragging = () => this.Interaction.isDragging;
2585
+ /** Returns first DropsZone under coordinates, if no coordinated provided current pointer coordinates are used */
2586
+ getZoneByCoordinates = (coordinates) => this.DropZones.getTarget({ coordinates })?.toObject();
2587
+ /** Returns itemsDropped into zone by zone id */
2588
+ getItemsDroppedByZoneId = (zoneId) => this.DropZones.getItemsDroppedById(zoneId);
2589
+ /**
2590
+ * Returns itemsInside by zone id
2591
+ * @param addClasses whether or not to add/remove the "inside" classes to the items
2592
+ */
2593
+ getItemsInsideByZoneId = (zoneId, addClasses) => this.DropZones.getItemsInsideById(zoneId, addClasses);
2594
+ }
2595
+ DragSelect.isCollision = isCollision;
2596
+
2597
+ export { DragSelect as default };