/
draggable.js
521 lines (443 loc) · 15 KB
/
draggable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import { getEasingFunc } from '#runtime/svelte/easing';
import { A11yHelper } from '#runtime/util/browser';
import {
isIterable,
isObject } from '#runtime/util/object';
/**
* Provides an action to enable pointer dragging of an HTMLElement and invoke `position.set` on a given
* {@link TJSPosition} instance provided. When the attached boolean store state changes the draggable
* action is enabled or disabled.
*
* @param {HTMLElement} node - The node associated with the action.
*
* @param {import('./types').Action.DraggableOptions} options - Draggable action options.
*
* @returns {import('svelte/action').ActionReturn<Partial<import('./types').Action.DraggableOptions>>} Action lifecycle
* functions.
*/
function draggable(node, { position, enabled = true, button = 0, storeDragging = void 0, tween = false,
tweenOptions = { duration: 1, ease: 'cubicOut' }, hasTargetClassList, ignoreTargetClassList })
{
if (hasTargetClassList !== void 0 && !isIterable(hasTargetClassList))
{
throw new TypeError(`'hasTargetClassList' is not iterable.`);
}
if (ignoreTargetClassList !== void 0 && !isIterable(ignoreTargetClassList))
{
throw new TypeError(`'ignoreTargetClassList' is not iterable.`);
}
/**
* Used for direct call to `position.set`.
*
* @type {{top: number, left: number}}
*/
const positionData = { left: 0, top: 0 };
/**
* Find actual position instance checking for a Positionable instance.
*
* @type {import('..').TJSPosition}
*/
let actualPosition = position?.position ?? position;
/**
* Duplicate the app / Positionable starting position to track differences.
*
* @type {object}
*/
let initialPosition = null;
/**
* Stores the initial X / Y on drag down.
*
* @type {object}
*/
let initialDragPoint = {};
/**
* Stores the current dragging state and gates the move pointer as the dragging store is not
* set until the first pointer move.
*
* @type {boolean}
*/
let dragging = false;
/**
* Stores the quickTo callback to use for optimized tweening when easing is enabled.
*
* @type {import('../animation/types').AnimationAPI.QuickToCallback}
*/
let quickTo = actualPosition.animate.quickTo(['top', 'left'], tweenOptions);
/**
* Event handlers associated with this action, so they may be later unregistered.
*
* @type {{ [p: string]: [string, EventListener, boolean] }}
*/
const handlers = {
dragDown: ['pointerdown', /** @type {EventListener} */ onDragPointerDown, false],
dragMove: ['pointermove', /** @type {EventListener} */ onDragPointerChange, false],
dragUp: ['pointerup', /** @type {EventListener} */ onDragPointerUp, false]
};
/**
* Activates listeners.
*/
function activateListeners()
{
// Drag handlers
node.addEventListener(...handlers.dragDown);
node.classList.add('draggable');
}
/**
* Removes listeners.
*/
function removeListeners()
{
if (typeof storeDragging?.set === 'function') { storeDragging.set(false); }
// Drag handlers
node.removeEventListener(...handlers.dragDown);
node.removeEventListener(...handlers.dragMove);
node.removeEventListener(...handlers.dragUp);
node.classList.remove('draggable');
}
if (enabled)
{
activateListeners();
}
/**
* Handle the initial pointer down that activates dragging behavior for the positionable.
*
* @param {PointerEvent} event - The pointer down event.
*/
function onDragPointerDown(event)
{
if (event.button !== button || !event.isPrimary) { return; }
// Do not process if the position system is not enabled.
if (!actualPosition.enabled) { return; }
// Potentially ignore this event if `ignoreTargetClassList` is defined and the `event.target` has a matching
// class.
if (ignoreTargetClassList !== void 0 && A11yHelper.isFocusTarget(event.target))
{
for (const targetClass of ignoreTargetClassList)
{
if (event.target.classList.contains(targetClass)) { return; }
}
}
// Potentially ignore this event if `hasTargetClassList` is defined and the `event.target` does not have any
// matching class from the list.
if (hasTargetClassList !== void 0 && A11yHelper.isFocusTarget(event.target))
{
let foundTarget = false;
for (const targetClass of hasTargetClassList)
{
if (event.target.classList.contains(targetClass))
{
foundTarget = true;
break;
}
}
if (!foundTarget) { return; }
}
event.preventDefault();
dragging = false;
// Record initial position.
initialPosition = actualPosition.get();
initialDragPoint = { x: event.clientX, y: event.clientY };
// Add move and pointer up handlers.
node.addEventListener(...handlers.dragMove);
node.addEventListener(...handlers.dragUp);
node.setPointerCapture(event.pointerId);
}
/**
* Move the positionable.
*
* @param {PointerEvent} event - The pointer move event.
*/
function onDragPointerChange(event)
{
// See chorded button presses for pointer events:
// https://www.w3.org/TR/pointerevents3/#chorded-button-interactions
// TODO: Support different button configurations for PointerEvents.
if ((event.buttons & 1) === 0)
{
onDragPointerUp(event);
return;
}
if (event.button !== -1 || !event.isPrimary) { return; }
event.preventDefault();
// Only set store dragging on first move event.
if (!dragging && typeof storeDragging?.set === 'function')
{
dragging = true;
storeDragging.set(true);
}
/** @type {number} */
const newLeft = initialPosition.left + (event.clientX - initialDragPoint.x);
/** @type {number} */
const newTop = initialPosition.top + (event.clientY - initialDragPoint.y);
if (tween)
{
quickTo(newTop, newLeft);
}
else
{
positionData.left = newLeft;
positionData.top = newTop;
actualPosition.set(positionData);
}
}
/**
* Finish dragging and set the final position and removing listeners.
*
* @param {PointerEvent} event - The pointer up event.
*/
function onDragPointerUp(event)
{
event.preventDefault();
dragging = false;
if (typeof storeDragging?.set === 'function') { storeDragging.set(false); }
node.removeEventListener(...handlers.dragMove);
node.removeEventListener(...handlers.dragUp);
}
return {
// The default of enabled being true won't automatically add listeners twice.
update: (options) =>
{
if (options.position !== void 0)
{
// Find actual position instance checking for a Positionable instance.
const newPosition = options.position?.position ?? options.position;
if (newPosition !== actualPosition)
{
actualPosition = newPosition;
quickTo = actualPosition.animate.quickTo(['top', 'left'], tweenOptions);
}
}
if (typeof options.enabled === 'boolean')
{
enabled = options.enabled;
if (enabled) { activateListeners(); }
else { removeListeners(); }
}
if (typeof options.button === 'number')
{
button = options.button;
}
if (typeof options.tween === 'boolean') { tween = options.tween; }
if (isObject(options.tweenOptions))
{
tweenOptions = options.tweenOptions;
quickTo.options(tweenOptions);
}
if (options.hasTargetClassList !== void 0)
{
if (!isIterable(options.hasTargetClassList))
{
throw new TypeError(`'hasTargetClassList' is not iterable.`);
}
else
{
hasTargetClassList = options.hasTargetClassList;
}
}
if (options.ignoreTargetClassList !== void 0)
{
if (!isIterable(options.ignoreTargetClassList))
{
throw new TypeError(`'ignoreTargetClassList' is not iterable.`);
}
else
{
ignoreTargetClassList = options.ignoreTargetClassList;
}
}
},
destroy: () => removeListeners()
};
}
/**
* Provides an instance of the {@link draggable} action options support / Readable store to make updating / setting
* draggable options much easier. When subscribing to the options instance returned by {@link draggable.options} the
* Subscriber handler receives the entire instance.
*
* @implements {import('./types').Action.DraggableOptionsStore}
*/
class DraggableOptionsStore
{
/** @type {boolean} */
#initialTween;
/**
* @type {import('../animation/types').AnimationAPI.QuickTweenOptions}
*/
#initialTweenOptions;
/** @type {boolean} */
#tween;
/**
* @type {import('../animation/types').AnimationAPI.QuickTweenOptions}
*/
#tweenOptions = { duration: 1, ease: 'cubicOut' };
/**
* Stores the subscribers.
*
* @type {import('svelte/store').Subscriber<import('./types').Action.DraggableOptionsStore>[]}
*/
#subscriptions = [];
/**
* @param {object} [opts] - Optional parameters.
*
* @param {boolean} [opts.tween = false] - Tween enabled.
*
* @param {import('../animation/types').AnimationAPI.QuickTweenOptions} [opts.tweenOptions] - Quick tween options.
*/
constructor({ tween = false, tweenOptions } = {})
{
// Define the following getters directly on this instance and make them enumerable. This allows them to be
// picked up w/ `Object.assign`.
Object.defineProperty(this, 'tween', {
get: () => { return this.#tween; },
set: (newTween) =>
{
if (typeof newTween !== 'boolean') { throw new TypeError(`'tween' is not a boolean.`); }
this.#tween = newTween;
this.#updateSubscribers();
},
enumerable: true
});
Object.defineProperty(this, 'tweenOptions', {
get: () => { return this.#tweenOptions; },
set: (newTweenOptions) =>
{
if (!isObject(newTweenOptions))
{
throw new TypeError(`'tweenOptions' is not an object.`);
}
if (newTweenOptions.duration !== void 0)
{
if (!Number.isFinite(newTweenOptions.duration))
{
throw new TypeError(`'tweenOptions.duration' is not a finite number.`);
}
if (newTweenOptions.duration < 0)
{
this.#tweenOptions.duration = 0;
}
else
{
this.#tweenOptions.duration = newTweenOptions.duration;
}
}
if (newTweenOptions.ease !== void 0)
{
const easeFn = getEasingFunc(newTweenOptions.ease);
if (typeof easeFn !== 'function')
{
throw new TypeError(`'tweenOptions.ease' is not a function or Svelte easing function name.`);
}
this.#tweenOptions.ease = newTweenOptions.ease;
}
this.#updateSubscribers();
},
enumerable: true
});
// Set default options.
if (tween !== void 0) { this.tween = tween; }
if (tweenOptions !== void 0) { this.tweenOptions = tweenOptions; }
this.#initialTween = this.#tween;
this.#initialTweenOptions = Object.assign({}, this.#tweenOptions);
}
/**
* @returns {number} Get tween duration.
*/
get tweenDuration() { return this.#tweenOptions.duration; }
/**
* @returns {import('#runtime/svelte/easing').EasingFunctionName | import('#runtime/svelte/easing').EasingFunction} Get
* easing function or easing function name.
*/
get tweenEase() { return this.#tweenOptions.ease; }
/**
* @param {number} duration - Set tween duration.
*/
set tweenDuration(duration)
{
if (!Number.isFinite(duration))
{
throw new TypeError(`'duration' is not a finite number.`);
}
if (duration < 0) { duration = 0; }
this.#tweenOptions.duration = duration;
this.#updateSubscribers();
}
/**
* @param {import('#runtime/svelte/easing').EasingFunctionName | import('#runtime/svelte/easing').EasingFunction} ease -
* Set easing function by name or direct function.
*/
set tweenEase(ease)
{
const easeFn = getEasingFunc(ease);
if (typeof easeFn !== 'function')
{
throw new TypeError(`'ease' is not a function or Svelte easing function name.`);
}
this.#tweenOptions.ease = ease;
this.#updateSubscribers();
}
/**
* Resets all options data to initial values.
*/
reset()
{
this.#tween = this.#initialTween;
this.#tweenOptions = Object.assign({}, this.#initialTweenOptions);
this.#updateSubscribers();
}
/**
* Resets tween enabled state to initial value.
*/
resetTween()
{
this.#tween = this.#initialTween;
this.#updateSubscribers();
}
/**
* Resets tween options to initial values.
*/
resetTweenOptions()
{
this.#tweenOptions = Object.assign({}, this.#initialTweenOptions);
this.#updateSubscribers();
}
/**
* Store subscribe method.
*
* @param {import('svelte/store').Subscriber<import('./types').Action.DraggableOptionsStore>} handler - Callback
* function that is invoked on update / changes. Receives the DraggableOptionsStore instance.
*
* @returns {import('svelte/store').Unsubscriber} Unsubscribe function.
*/
subscribe(handler)
{
this.#subscriptions.push(handler); // add handler to the array of subscribers
handler(this); // call handler with current value
// Return unsubscribe function.
return () =>
{
const index = this.#subscriptions.findIndex((sub) => sub === handler);
if (index >= 0) { this.#subscriptions.splice(index, 1); }
};
}
#updateSubscribers()
{
const subscriptions = this.#subscriptions;
// Early out if there are no subscribers.
if (subscriptions.length > 0)
{
for (let cntr = 0; cntr < subscriptions.length; cntr++) { subscriptions[cntr](this); }
}
}
}
/**
* Define a function to get a DraggableOptionsStore instance.
*
* @param {({
* tween?: boolean,
* tweenOptions?: import('../animation/types').AnimationAPI.QuickTweenOptions
* })} options - Initial options for DraggableOptionsStore.
*
* @returns {import('./types').Action.DraggableOptionsStore} A new options instance.
*/
draggable.options = (options) => new DraggableOptionsStore(options);
export { draggable };