-
-
Notifications
You must be signed in to change notification settings - Fork 876
/
Copy pathContainer.ts
842 lines (674 loc) · 23.4 KB
/
Container.ts
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
import { getLogger, isFunction } from "../Utils/Utils";
import { Canvas } from "./Canvas";
import type { ClickMode } from "../Enums/Modes/ClickMode";
import type { Engine } from "./Engine";
import { EventListeners } from "./Utils/EventListeners";
import { EventType } from "../Enums/Types/EventType";
import type { IContainerInteractivity } from "./Interfaces/IContainerInteractivity";
import type { IContainerPlugin } from "./Interfaces/IContainerPlugin";
import type { ICoordinates } from "./Interfaces/ICoordinates";
import type { IDelta } from "./Interfaces/IDelta";
import type { IMovePathGenerator } from "./Interfaces/IMovePathGenerator";
import type { IShapeDrawer } from "./Interfaces/IShapeDrawer";
import type { ISourceOptions } from "../Types/ISourceOptions";
import { Options } from "../Options/Classes/Options";
import type { Particle } from "./Particle";
import { Particles } from "./Particles";
import { Retina } from "./Retina";
import type { Vector } from "./Utils/Vector";
import { errorPrefix } from "./Utils/Constants";
import { getRangeValue } from "../Utils/NumberUtils";
import { loadOptions } from "../Utils/OptionsUtils";
/**
* Checks if the container is still usable
* @param container - the container to check
* @returns true if the container is still usable
*/
function guardCheck(container: Container): boolean {
return container && !container.destroyed;
}
/**
* @param value -
* @param fpsLimit -
* @param smooth -
* @returns the initialized delta value
*/
function initDelta(value: number, fpsLimit = 60, smooth = false): IDelta {
return {
value,
factor: smooth ? 60 / fpsLimit : (60 * value) / 1000,
};
}
/**
* @param engine -
* @param container -
* @param sourceOptionsArr -
* @returns the options loaded
*/
function loadContainerOptions(
engine: Engine,
container: Container,
...sourceOptionsArr: (ISourceOptions | undefined)[]
): Options {
const options = new Options(engine, container);
loadOptions(options, ...sourceOptionsArr);
return options;
}
const defaultPathGeneratorKey = "default",
defaultPathGenerator: IMovePathGenerator = {
generate: (p: Particle): Vector => p.velocity,
init: (): void => {
// nothing required
},
update: (): void => {
// nothing required
},
reset: (): void => {
// nothing required
},
};
/**
* The object loaded into an HTML element, it'll contain options loaded and all data to let everything working
* [[include:Container.md]]
*/
export class Container {
/**
* The options loaded by the container, it's a full {@link Options} object
*/
actualOptions;
/**
* Canvas object, in charge of the canvas element and drawing functions
*/
readonly canvas;
/**
* Check if the particles' container is destroyed, if so it's not recommended using it
*/
destroyed;
/**
* All the shape drawers used by the container
*/
readonly drawers;
/**
* The container fps limit, coming from options
*/
fpsLimit;
interactivity: IContainerInteractivity;
/**
* Last frame time, used for delta values, for keeping animation correct in lower frame rates
*/
lastFrameTime?: number;
/**
* The container check if it's hidden on the web page
*/
pageHidden;
/**
* The particles manager
*/
readonly particles;
pathGenerators: Map<string, IMovePathGenerator>;
/**
* All the plugins used by the container
*/
readonly plugins;
responsiveMaxWidth?: number;
readonly retina;
smooth;
/**
* Check if the particles container is started
*/
started;
zLayers;
private _currentTheme?: string;
private _delay: number;
private _delayTimeout?: number | NodeJS.Timeout;
private _drawAnimationFrame?: number;
/**
* The container duration
*/
private _duration;
private readonly _engine;
private readonly _eventListeners;
private _firstStart;
private _initialSourceOptions;
private readonly _intersectionObserver;
/**
* The container lifetime
*/
private _lifeTime;
private _options;
private _paused;
private _sourceOptions;
/**
* This is the core class, create an instance to have a new working particles manager
* @param engine - the engine used by container
* @param id - the id to identify this instance
* @param sourceOptions - the options to load
*/
constructor(
engine: Engine,
readonly id: string,
sourceOptions?: ISourceOptions,
) {
this._engine = engine;
this.fpsLimit = 120;
this.smooth = false;
this._delay = 0;
this._duration = 0;
this._lifeTime = 0;
this._firstStart = true;
this.started = false;
this.destroyed = false;
this._paused = true;
this.lastFrameTime = 0;
this.zLayers = 100;
this.pageHidden = false;
this._sourceOptions = sourceOptions;
this._initialSourceOptions = sourceOptions;
this.retina = new Retina(this);
this.canvas = new Canvas(this);
this.particles = new Particles(this._engine, this);
this.pathGenerators = new Map<string, IMovePathGenerator>();
this.interactivity = {
mouse: {
clicking: false,
inside: false,
},
};
this.plugins = new Map<string, IContainerPlugin>();
this.drawers = new Map<string, IShapeDrawer>();
/* tsParticles variables with default values */
this._options = loadContainerOptions(this._engine, this);
this.actualOptions = loadContainerOptions(this._engine, this);
/* ---------- tsParticles - start ------------ */
this._eventListeners = new EventListeners(this);
if (typeof IntersectionObserver !== "undefined" && IntersectionObserver) {
this._intersectionObserver = new IntersectionObserver((entries) => this._intersectionManager(entries));
}
this._engine.dispatchEvent(EventType.containerBuilt, { container: this });
}
/**
* The options used by the container, it's a full {@link Options} object
* @returns the options used by the container
*/
get options(): Options {
return this._options;
}
/**
* The options that were initially passed to the container
* @returns the source options passed to the container
*/
get sourceOptions(): ISourceOptions | undefined {
return this._sourceOptions;
}
/**
* Adds a click handler to the container
* @param callback - the callback to be called when the click event occurs
*/
addClickHandler(callback: (evt: Event, particles?: Particle[]) => void): void {
if (!guardCheck(this)) {
return;
}
const el = this.interactivity.element;
if (!el) {
return;
}
const clickOrTouchHandler = (e: Event, pos: ICoordinates, radius: number): void => {
if (!guardCheck(this)) {
return;
}
const pxRatio = this.retina.pixelRatio,
posRetina = {
x: pos.x * pxRatio,
y: pos.y * pxRatio,
},
particles = this.particles.quadTree.queryCircle(posRetina, radius * pxRatio);
callback(e, particles);
};
const clickHandler = (e: Event): void => {
if (!guardCheck(this)) {
return;
}
const mouseEvent = e as MouseEvent,
pos = {
x: mouseEvent.offsetX || mouseEvent.clientX,
y: mouseEvent.offsetY || mouseEvent.clientY,
};
clickOrTouchHandler(e, pos, 1);
};
const touchStartHandler = (): void => {
if (!guardCheck(this)) {
return;
}
touched = true;
touchMoved = false;
};
const touchMoveHandler = (): void => {
if (!guardCheck(this)) {
return;
}
touchMoved = true;
};
const touchEndHandler = (e: Event): void => {
if (!guardCheck(this)) {
return;
}
if (touched && !touchMoved) {
const touchEvent = e as TouchEvent;
let lastTouch = touchEvent.touches[touchEvent.touches.length - 1];
if (!lastTouch) {
lastTouch = touchEvent.changedTouches[touchEvent.changedTouches.length - 1];
if (!lastTouch) {
return;
}
}
const element = this.canvas.element,
canvasRect = element ? element.getBoundingClientRect() : undefined,
pos = {
x: lastTouch.clientX - (canvasRect ? canvasRect.left : 0),
y: lastTouch.clientY - (canvasRect ? canvasRect.top : 0),
};
clickOrTouchHandler(e, pos, Math.max(lastTouch.radiusX, lastTouch.radiusY));
}
touched = false;
touchMoved = false;
};
const touchCancelHandler = (): void => {
if (!guardCheck(this)) {
return;
}
touched = false;
touchMoved = false;
};
let touched = false,
touchMoved = false;
el.addEventListener("click", clickHandler);
el.addEventListener("touchstart", touchStartHandler);
el.addEventListener("touchmove", touchMoveHandler);
el.addEventListener("touchend", touchEndHandler);
el.addEventListener("touchcancel", touchCancelHandler);
}
addLifeTime(value: number): void {
this._lifeTime += value;
}
/**
* Add a new path generator to the container
* @param key - the key to identify the path generator
* @param generator - the path generator
* @param override - if true, override the existing path generator
* @returns true if the path generator was added, false otherwise
*/
addPath(key: string, generator?: IMovePathGenerator, override = false): boolean {
if (!guardCheck(this) || (!override && this.pathGenerators.has(key))) {
return false;
}
this.pathGenerators.set(key, generator ?? defaultPathGenerator);
return true;
}
alive(): boolean {
return !this._duration || this._lifeTime <= this._duration;
}
/**
* Destroys the current container, invalidating it
*/
destroy(): void {
if (!guardCheck(this)) {
return;
}
this.stop();
this.particles.destroy();
this.canvas.destroy();
for (const [, drawer] of this.drawers) {
drawer.destroy && drawer.destroy(this);
}
for (const key of this.drawers.keys()) {
this.drawers.delete(key);
}
this._engine.clearPlugins(this);
this.destroyed = true;
const mainArr = this._engine.dom(),
idx = mainArr.findIndex((t) => t === this);
if (idx >= 0) {
mainArr.splice(idx, 1);
}
this._engine.dispatchEvent(EventType.containerDestroyed, { container: this });
}
/**
* Draws a frame
* @param force -
*/
draw(force: boolean): void {
if (!guardCheck(this)) {
return;
}
let refreshTime = force;
this._drawAnimationFrame = requestAnimationFrame(async (timestamp) => {
if (refreshTime) {
this.lastFrameTime = undefined;
refreshTime = false;
}
await this._nextFrame(timestamp);
});
}
async export(type: string, options: Record<string, unknown> = {}): Promise<Blob | undefined> {
for (const [, plugin] of this.plugins) {
if (!plugin.export) {
continue;
}
const res = await plugin.export(type, options);
if (!res.supported) {
continue;
}
return res.blob;
}
getLogger().error(`${errorPrefix} - Export plugin with type ${type} not found`);
}
/**
* Gets the animation status
* @returns `true` is playing, `false` is paused
*/
getAnimationStatus(): boolean {
return !this._paused && !this.pageHidden && guardCheck(this);
}
/**
* Handles click event in the container
* @param mode - click mode to handle
*/
handleClickMode(mode: ClickMode | string): void {
if (!guardCheck(this)) {
return;
}
this.particles.handleClickMode(mode);
for (const [, plugin] of this.plugins) {
plugin.handleClickMode && plugin.handleClickMode(mode);
}
}
/**
* Initializes the container
*/
async init(): Promise<void> {
if (!guardCheck(this)) {
return;
}
const shapes = this._engine.getSupportedShapes();
for (const type of shapes) {
const drawer = this._engine.getShapeDrawer(type);
if (drawer) {
this.drawers.set(type, drawer);
}
}
/* options settings */
this._options = loadContainerOptions(this._engine, this, this._initialSourceOptions, this.sourceOptions);
this.actualOptions = loadContainerOptions(this._engine, this, this._options);
const availablePlugins = this._engine.getAvailablePlugins(this);
for (const [id, plugin] of availablePlugins) {
this.plugins.set(id, plugin);
}
/* init canvas + particles */
this.retina.init();
await this.canvas.init();
this.updateActualOptions();
this.canvas.initBackground();
this.canvas.resize();
this.zLayers = this.actualOptions.zLayers;
this._duration = getRangeValue(this.actualOptions.duration) * 1000;
this._delay = getRangeValue(this.actualOptions.delay) * 1000;
this._lifeTime = 0;
this.fpsLimit = this.actualOptions.fpsLimit > 0 ? this.actualOptions.fpsLimit : 120;
this.smooth = this.actualOptions.smooth;
for (const [, drawer] of this.drawers) {
drawer.init && (await drawer.init(this));
}
for (const [, plugin] of this.plugins) {
plugin.init && (await plugin.init());
}
this._engine.dispatchEvent(EventType.containerInit, { container: this });
this.particles.init();
this.particles.setDensity();
for (const [, plugin] of this.plugins) {
plugin.particlesSetup && plugin.particlesSetup();
}
this._engine.dispatchEvent(EventType.particlesSetup, { container: this });
}
/**
* Loads the given theme, overriding the options
* @param name - the theme name, if `undefined` resets the default options or the default theme
*/
async loadTheme(name?: string): Promise<void> {
if (!guardCheck(this)) {
return;
}
this._currentTheme = name;
await this.refresh();
}
/**
* Pauses animations
*/
pause(): void {
if (!guardCheck(this)) {
return;
}
if (this._drawAnimationFrame !== undefined) {
cancelAnimationFrame(this._drawAnimationFrame);
delete this._drawAnimationFrame;
}
if (this._paused) {
return;
}
for (const [, plugin] of this.plugins) {
plugin.pause && plugin.pause();
}
if (!this.pageHidden) {
this._paused = true;
}
this._engine.dispatchEvent(EventType.containerPaused, { container: this });
}
/**
* Starts animations and resume from pause
* @param force -
*/
play(force?: boolean): void {
if (!guardCheck(this)) {
return;
}
const needsUpdate = this._paused || force;
if (this._firstStart && !this.actualOptions.autoPlay) {
this._firstStart = false;
return;
}
if (this._paused) {
this._paused = false;
}
if (needsUpdate) {
for (const [, plugin] of this.plugins) {
if (plugin.play) {
plugin.play();
}
}
}
this._engine.dispatchEvent(EventType.containerPlay, { container: this });
this.draw(needsUpdate || false);
}
/**
* Restarts the container, just a {@link Container.stop}/{@link Container.start} alias
* @returns the Promise of the start method
*/
async refresh(): Promise<void> {
if (!guardCheck(this)) {
return;
}
/* restart */
this.stop();
return this.start();
}
async reset(): Promise<void> {
if (!guardCheck(this)) {
return;
}
this._initialSourceOptions = undefined;
this._options = loadContainerOptions(this._engine, this);
this.actualOptions = loadContainerOptions(this._engine, this, this._options);
return this.refresh();
}
/**
* Customise path generation
* @deprecated Use the new setPath
* @param noiseOrGenerator - the {@link IMovePathGenerator} object or a function that generates a {@link Vector} object from {@link Particle}
* @param init - the {@link IMovePathGenerator} init function, if the first parameter is a generator function
* @param update - the {@link IMovePathGenerator} update function, if the first parameter is a generator function
*/
setNoise(
noiseOrGenerator?: IMovePathGenerator | ((particle: Particle) => Vector),
init?: () => void,
update?: () => void,
): void {
if (!guardCheck(this)) {
return;
}
this.setPath(noiseOrGenerator, init, update);
}
/**
* Customise path generation
* @deprecated Use the new addPath
* @param pathOrGenerator - the {@link IMovePathGenerator} object or a function that generates a {@link Vector} object from {@link Particle}
* @param init - the {@link IMovePathGenerator} init function, if the first parameter is a generator function
* @param update - the {@link IMovePathGenerator} update function, if the first parameter is a generator function
*/
setPath(
pathOrGenerator?: IMovePathGenerator | ((particle: Particle) => Vector),
init?: () => void,
update?: () => void,
): void {
if (!pathOrGenerator || !guardCheck(this)) {
return;
}
const pathGenerator = { ...defaultPathGenerator };
if (isFunction(pathOrGenerator)) {
pathGenerator.generate = pathOrGenerator;
if (init) {
pathGenerator.init = init;
}
if (update) {
pathGenerator.update = update;
}
} else {
const oldGenerator = pathGenerator;
pathGenerator.generate = pathOrGenerator.generate || oldGenerator.generate;
pathGenerator.init = pathOrGenerator.init || oldGenerator.init;
pathGenerator.update = pathOrGenerator.update || oldGenerator.update;
}
this.addPath(defaultPathGeneratorKey, pathGenerator, true);
}
/**
* Starts the container, initializes what are needed to create animations and event handling
*/
async start(): Promise<void> {
if (!guardCheck(this) || this.started) {
return;
}
await this.init();
this.started = true;
await new Promise<void>((resolve) => {
this._delayTimeout = setTimeout(async () => {
this._eventListeners.addListeners();
if (this.interactivity.element instanceof HTMLElement && this._intersectionObserver) {
this._intersectionObserver.observe(this.interactivity.element);
}
for (const [, plugin] of this.plugins) {
plugin.start && (await plugin.start());
}
this._engine.dispatchEvent(EventType.containerStarted, { container: this });
this.play();
resolve();
}, this._delay);
});
}
/**
* Stops the container, opposite to `start`. Clears some resources and stops events.
*/
stop(): void {
if (!guardCheck(this) || !this.started) {
return;
}
if (this._delayTimeout) {
clearTimeout(this._delayTimeout);
delete this._delayTimeout;
}
this._firstStart = true;
this.started = false;
this._eventListeners.removeListeners();
this.pause();
this.particles.clear();
this.canvas.stop();
if (this.interactivity.element instanceof HTMLElement && this._intersectionObserver) {
this._intersectionObserver.unobserve(this.interactivity.element);
}
for (const [, plugin] of this.plugins) {
plugin.stop && plugin.stop();
}
for (const key of this.plugins.keys()) {
this.plugins.delete(key);
}
this._sourceOptions = this._options;
this._engine.dispatchEvent(EventType.containerStopped, { container: this });
}
/**
* Updates the container options
* @returns true if the options were updated, false otherwise
*/
updateActualOptions(): boolean {
this.actualOptions.responsive = [];
const newMaxWidth = this.actualOptions.setResponsive(
this.canvas.size.width,
this.retina.pixelRatio,
this._options,
);
this.actualOptions.setTheme(this._currentTheme);
if (this.responsiveMaxWidth === newMaxWidth) {
return false;
}
this.responsiveMaxWidth = newMaxWidth;
return true;
}
private readonly _intersectionManager: (entries: IntersectionObserverEntry[]) => void = (entries) => {
if (!guardCheck(this) || !this.actualOptions.pauseOnOutsideViewport) {
return;
}
for (const entry of entries) {
if (entry.target !== this.interactivity.element) {
continue;
}
(entry.isIntersecting ? this.play : this.pause)();
}
};
private readonly _nextFrame: (timestamp: DOMHighResTimeStamp) => Promise<void> = async (timestamp) => {
try {
// FPS limit logic - if we are too fast, just draw without updating
if (
!this.smooth &&
this.lastFrameTime !== undefined &&
timestamp < this.lastFrameTime + 1000 / this.fpsLimit
) {
this.draw(false);
return;
}
this.lastFrameTime ??= timestamp;
const delta = initDelta(timestamp - this.lastFrameTime, this.fpsLimit, this.smooth);
this.addLifeTime(delta.value);
this.lastFrameTime = timestamp;
if (delta.value > 1000) {
this.draw(false);
return;
}
await this.particles.draw(delta);
if (!this.alive()) {
this.destroy();
return;
}
if (this.getAnimationStatus()) {
this.draw(false);
}
} catch (e) {
getLogger().error(`${errorPrefix} in animation loop`, e);
}
};
}