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