@hilux/ngx-motion 1.1.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +137 -57
  2. package/fesm2022/hilux-ngx-motion.mjs +2020 -0
  3. package/fesm2022/hilux-ngx-motion.mjs.map +1 -0
  4. package/package.json +35 -31
  5. package/types/hilux-ngx-motion.d.ts +782 -0
  6. package/ng-package.json +0 -7
  7. package/src/lib/components/motion-one-presence.component.ts +0 -116
  8. package/src/lib/constants/motion-defaults.constants.ts +0 -41
  9. package/src/lib/directives/motion-animate.directive.ts +0 -55
  10. package/src/lib/directives/motion-if.directive.ts +0 -138
  11. package/src/lib/directives/motion-one.directive.backup.ts +0 -1591
  12. package/src/lib/directives/motion-one.directive.ts +0 -1154
  13. package/src/lib/directives/motion-presence.directive.ts +0 -145
  14. package/src/lib/services/motion-animation-options.service.ts +0 -142
  15. package/src/lib/services/motion-animation.service.ts +0 -86
  16. package/src/lib/services/motion-browser-safe.ts +0 -64
  17. package/src/lib/services/motion-gesture.service.ts +0 -141
  18. package/src/lib/services/motion-inview.service.ts +0 -91
  19. package/src/lib/services/motion-one.service.ts +0 -424
  20. package/src/lib/services/motion-stagger.service.ts +0 -70
  21. package/src/lib/services/motion-timeline.service.ts +0 -182
  22. package/src/lib/types/motion-animation.types.ts +0 -46
  23. package/src/lib/utils/color.utils.ts +0 -54
  24. package/src/lib/utils/easing.utils.ts +0 -77
  25. package/src/lib/utils/index.ts +0 -7
  26. package/src/lib/utils/style-extraction.utils.ts +0 -70
  27. package/src/lib/utils/timing.utils.ts +0 -61
  28. package/src/lib/utils/transform.utils.ts +0 -112
  29. package/src/lib/utils/variant.utils.ts +0 -55
  30. package/src/public-api.ts +0 -21
  31. package/tsconfig.lib.json +0 -17
  32. package/tsconfig.lib.prod.json +0 -11
  33. package/tsconfig.spec.json +0 -15
@@ -1,1154 +0,0 @@
1
- import {
2
- Directive,
3
- Input,
4
- ElementRef,
5
- OnDestroy,
6
- Output,
7
- EventEmitter,
8
- OnChanges,
9
- SimpleChanges,
10
- HostListener,
11
- OnInit,
12
- PLATFORM_ID,
13
- Inject,
14
- ContentChildren,
15
- QueryList,
16
- AfterContentInit
17
- } from '@angular/core';
18
- import { Router } from '@angular/router';
19
- import { isPlatformBrowser } from '@angular/common';
20
- import { MotionOneService } from '../services/motion-one.service';
21
- import { MotionAnimationService } from '../services/motion-animation.service';
22
- import { MotionAnimationOptionsService } from '../services/motion-animation-options.service';
23
- import { MotionStaggerService } from '../services/motion-stagger.service';
24
- import { MotionInViewService } from '../services/motion-inview.service';
25
- import { MotionTimelineService } from '../services/motion-timeline.service';
26
- import { MotionGestureService } from '../services/motion-gesture.service';
27
- import type { AnimationOptions, Target } from 'motion';
28
- import { animate, inView } from '../services/motion-browser-safe';
29
- import { VariantWithTransition, TransitionOptions, TimelineStep } from '../types/motion-animation.types';
30
- import { MOTION_DEFAULTS } from '../constants/motion-defaults.constants';
31
- import { extractStyleProperties } from '../utils/style-extraction.utils';
32
- import { resolveVariant } from '../utils/variant.utils';
33
-
34
- let uniqueIdCounter = 0;
35
-
36
- @Directive({
37
- selector: '[motionone]',
38
- standalone: true,
39
- exportAs: 'motionone'
40
- })
41
- export class MotionOneDirective implements OnInit, OnDestroy, OnChanges, AfterContentInit {
42
- @Input() initial: VariantWithTransition | string = {};
43
- @Input() animate: VariantWithTransition | string = {};
44
- @Input() exit: VariantWithTransition | string = {};
45
- @Input() inView: VariantWithTransition = {};
46
- @Input() duration: number = MOTION_DEFAULTS.DURATION;
47
- @Input() delay: number = MOTION_DEFAULTS.DELAY;
48
- @Input() delayChildren: number = MOTION_DEFAULTS.DELAY_CHILDREN;
49
- @Input() repeat: boolean = MOTION_DEFAULTS.REPEAT;
50
- @Input() exitDelay: number = MOTION_DEFAULTS.EXIT_DELAY;
51
- @Input() easing: string | number[] | { type: 'spring'; stiffness?: number; damping?: number } = MOTION_DEFAULTS.EASING;
52
- @Input() offset: string = MOTION_DEFAULTS.OFFSET;
53
- @Input() whileHover: VariantWithTransition = {};
54
- @Input() staggerChildren: number = MOTION_DEFAULTS.STAGGER_CHILDREN;
55
- @Input() staggerDirection: number = MOTION_DEFAULTS.STAGGER_DIRECTION;
56
- @Input() whileTap: VariantWithTransition = {};
57
- @Input() whileFocus: VariantWithTransition = {};
58
- @Input() whileInView: VariantWithTransition = {};
59
- @Input() runInView?: 'never' | 'once' | 'always';
60
- @Input() variants: { [key: string]: VariantWithTransition } = {};
61
- @Input() transition: TransitionOptions | Record<string, TransitionOptions> = {};
62
- @Input() timeline: TimelineStep[] | undefined;
63
- @Output() animationComplete = new EventEmitter<void>();
64
-
65
- // Public method to restart animations
66
- public restartAnimation() {
67
- if (this.controls) {
68
- this.controls.stop();
69
- }
70
-
71
- const initialVariant = this.getVariant(this.initial);
72
- const initialStyles = extractStyleProperties(initialVariant);
73
-
74
- const element = this.el.nativeElement;
75
- element.style.transition = 'none';
76
- Object.assign(element.style, initialStyles);
77
- element.offsetHeight;
78
-
79
- const timeoutId = setTimeout(() => {
80
- element.style.transition = '';
81
- if (this.isRunInViewEnabled) {
82
- // For runInView elements, let inView handle the animation
83
- } else {
84
- this.playAnimation(this.initial, this.animate);
85
- }
86
- this.activeTimeouts.delete(timeoutId);
87
- }, MOTION_DEFAULTS.RESET_TIMEOUT);
88
- this.activeTimeouts.add(timeoutId);
89
- }
90
-
91
- @ContentChildren(MotionOneDirective, { descendants: true }) childMotionDirectives!: QueryList<MotionOneDirective>;
92
-
93
- private controls: ReturnType<typeof animate> | null = null;
94
- private childrenControls: ReturnType<typeof animate>[] = [];
95
- public elementId: string;
96
- private hoverTimeout: any;
97
- private observer?: IntersectionObserver;
98
- private routeDelay: number = 0;
99
- private inViewInstance: any;
100
- private isChild = false;
101
- private parentDirective: MotionOneDirective | null = null;
102
- private initialAnimationPlayed = false;
103
- private _skipStartStylesApplication = false;
104
- private staggerDelay: number | undefined = undefined;
105
- private childrenCount = 0;
106
- private childIndex = 0;
107
- private isStaggeredChild = false;
108
- // Track all setTimeout calls for proper cleanup on destroy
109
- private activeTimeouts: Set<any> = new Set();
110
-
111
- get scrollProgress() {
112
- return this.motionService.scrollYProgress();
113
- }
114
-
115
- private get isRunInViewEnabled(): boolean {
116
- return this.runInView === 'once' || this.runInView === 'always';
117
- }
118
-
119
- private get runInViewRepeat(): 'once' | 'always' {
120
- return this.runInView === 'always' ? 'always' : 'once';
121
- }
122
-
123
- constructor(
124
- public el: ElementRef,
125
- private motionService: MotionOneService,
126
- private motionAnimation: MotionAnimationService,
127
- private animationOptions: MotionAnimationOptionsService,
128
- private staggerService: MotionStaggerService,
129
- private inViewService: MotionInViewService,
130
- private timelineService: MotionTimelineService,
131
- private gestureService: MotionGestureService,
132
- private router: Router,
133
- @Inject(PLATFORM_ID) private platformId: Object
134
- ) {
135
- this.elementId = `motion-${uniqueIdCounter++}`;
136
-
137
- if (isPlatformBrowser(this.platformId)) {
138
- this.el.nativeElement.setAttribute('id', this.elementId);
139
- (this.el.nativeElement as any)._motionDirective = this;
140
- this.motionService.registerMotionElement(this);
141
- this.applyInitialStyles();
142
- this.routeDelay = this.motionService.getLongestExitDurationForRoute(this.router.url);
143
- }
144
- }
145
-
146
- ngOnInit() {
147
- this.applyInitialStyles();
148
-
149
- if (isPlatformBrowser(this.platformId)) {
150
- // Check if this is a child of another motionone directive
151
- let parent = this.el.nativeElement.parentElement;
152
- while (parent) {
153
- if (parent.hasAttribute('motionone')) {
154
- this.isChild = true;
155
- break;
156
- }
157
- parent = parent.parentElement;
158
- }
159
-
160
- // Set up runInView logic
161
- if (this.isRunInViewEnabled) {
162
- if (!this.isChild) {
163
- this.setupInViewAnimation();
164
- }
165
- } else if (!this.isChild) {
166
- this.playAnimation(this.initial, this.animate);
167
- }
168
-
169
- // Setup inView/whileInView animations
170
- if (!this.isStaggeredChild &&
171
- ((this.inView && Object.keys(this.inView).length > 0) ||
172
- (this.whileInView && Object.keys(this.whileInView).length > 0))) {
173
- this.setupInViewAnimation();
174
- }
175
- }
176
- }
177
-
178
- ngAfterContentInit() {
179
- if (this.childMotionDirectives && this.childMotionDirectives.length > 0) {
180
- const timeoutId = setTimeout(() => {
181
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
182
- this.childrenCount = childDirectives.length;
183
-
184
- childDirectives.forEach((child, index) => {
185
- child.setParent(this, index, this.childrenCount);
186
- });
187
-
188
- const staggerValue = this.getStaggerValue();
189
-
190
- if (this.runInView === 'always') {
191
- childDirectives.forEach(child => {
192
- if (child.isRunInViewEnabled) {
193
- child.isStaggeredChild = true;
194
- }
195
- });
196
- this.setupRunInViewObserver();
197
- } else if (staggerValue > 0 && this.childrenCount > 0) {
198
- childDirectives.forEach(child => {
199
- if (child.isRunInViewEnabled) {
200
- child.isStaggeredChild = true;
201
- }
202
- });
203
-
204
- if (!this.isRunInViewEnabled) {
205
- this.applyStaggerToChildren();
206
- }
207
- } else {
208
- childDirectives.forEach(child => {
209
- if (child.isRunInViewEnabled) {
210
- child.setupInViewAnimation();
211
- }
212
- });
213
- }
214
- this.activeTimeouts.delete(timeoutId);
215
- });
216
- this.activeTimeouts.add(timeoutId);
217
- }
218
- }
219
-
220
- setParent(parent: MotionOneDirective, index: number, totalChildren: number) {
221
- this.parentDirective = parent;
222
- this.isChild = true;
223
- this.childIndex = index;
224
- this.childrenCount = totalChildren;
225
- }
226
-
227
- public completeResetToInitial() {
228
- this.forceResetToInitial();
229
-
230
- if (this.childMotionDirectives && this.childMotionDirectives.length > 0) {
231
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
232
- childDirectives.forEach((child) => {
233
- child.forceResetToInitial();
234
- });
235
- }
236
- }
237
-
238
- public forceResetToInitial() {
239
- if (this.controls) {
240
- this.controls.stop();
241
- this.controls = null;
242
- }
243
-
244
- const initialVariant = this.getVariant(this.initial);
245
- const initialStyles = extractStyleProperties(initialVariant);
246
-
247
- this.el.nativeElement.style.transition = 'none';
248
- this.el.nativeElement.style.opacity = '';
249
- this.el.nativeElement.style.transform = '';
250
- Object.assign(this.el.nativeElement.style, initialStyles);
251
- this.el.nativeElement.offsetHeight;
252
- this.el.nativeElement.style.transition = '';
253
-
254
- this.initialAnimationPlayed = false;
255
- }
256
-
257
- public resetToInitialIfParentHasRunInView() {
258
- this.forceResetToInitial();
259
- }
260
-
261
- public parentExitViewportReset() {
262
- this.completeResetToInitial();
263
- }
264
-
265
- private setupRunInViewObserver() {
266
- if (!isPlatformBrowser(this.platformId)) return;
267
-
268
- const observer = this.inViewService.createRunInViewObserver(
269
- this.el.nativeElement,
270
- () => this.handleViewportEntry(),
271
- () => this.handleViewportExit()
272
- );
273
-
274
- if (observer) {
275
- this.observer = observer;
276
- this.observer.observe(this.el.nativeElement);
277
- }
278
- }
279
-
280
- private handleViewportEntry() {
281
- const staggerValue = this.getStaggerValue();
282
- if (staggerValue > 0 && this.childMotionDirectives?.length > 0) {
283
- this.applyStaggerToChildren();
284
- } else {
285
- this.playAnimation(this.initial, this.animate);
286
- }
287
- }
288
-
289
- private handleViewportExit() {
290
- if (this.runInView === 'always') {
291
- if (this.childMotionDirectives && this.childMotionDirectives.length > 0) {
292
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
293
- childDirectives.forEach((child) => {
294
- if (child.controls) {
295
- child.controls.stop();
296
- child.controls = null;
297
- }
298
- child.playAnimation(child.animate, child.initial);
299
- child.initialAnimationPlayed = false;
300
- });
301
- }
302
- }
303
- }
304
-
305
- applyStaggerToChildren() {
306
- const staggerValue = this.getStaggerValue();
307
- const staggerDirection = this.getStaggerDirection();
308
- const delayChildren = this.delayChildren;
309
- const parentDelay = (((this.transition as TransitionOptions)?.delay) ?? 0) as number;
310
-
311
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
312
- const when = this.getWhen();
313
-
314
- if (when !== 'afterChildren') {
315
- this.runSelfAnimation();
316
- }
317
-
318
- childDirectives.forEach((childDirective, index) => {
319
- const totalDelay = this.staggerService.calculateChildDelay(index, {
320
- childCount: this.childrenCount,
321
- staggerValue,
322
- staggerDirection,
323
- delayChildren,
324
- parentDelay
325
- });
326
-
327
- // Clear child's delay to prevent conflicts
328
- if (childDirective.transition && typeof childDirective.transition === 'object') {
329
- const childTransition = childDirective.transition as any;
330
- if (childTransition.delay !== undefined) {
331
- childTransition.delay = undefined;
332
- }
333
- }
334
-
335
- childDirective.overrideDelay(totalDelay);
336
-
337
- const timeoutId = setTimeout(() => {
338
- childDirective.playAnimation(childDirective.initial, childDirective.animate);
339
- this.activeTimeouts.delete(timeoutId);
340
- }, totalDelay * 1000);
341
- this.activeTimeouts.add(timeoutId);
342
- });
343
-
344
- if (when === 'afterChildren') {
345
- const totalChildrenDuration = this.staggerService.calculateTotalDuration({
346
- childCount: this.childrenCount,
347
- staggerValue,
348
- staggerDirection,
349
- delayChildren,
350
- parentDelay
351
- });
352
- this.overrideDelay(totalChildrenDuration);
353
- this.runSelfAnimation();
354
- }
355
- }
356
-
357
- overrideDelay(delay: number) {
358
- this.staggerDelay = delay;
359
- }
360
-
361
- runSelfAnimation() {
362
- const options = this.getAnimationOptions();
363
- const targetStyles = extractStyleProperties(this.getVariant(this.animate));
364
- const startStyles = extractStyleProperties(this.getVariant(this.initial));
365
-
366
- if (!this.isStaggeredChild) {
367
- Object.assign(this.el.nativeElement.style, startStyles);
368
- }
369
-
370
- this.controls = this.motionAnimation.animate(
371
- this.el.nativeElement as Target,
372
- targetStyles,
373
- options
374
- );
375
-
376
- this.initialAnimationPlayed = true;
377
- }
378
-
379
- ngOnDestroy() {
380
- // Clear all pending setTimeout calls to prevent navigation blocking
381
- this.activeTimeouts.forEach(timeoutId => {
382
- clearTimeout(timeoutId);
383
- });
384
- this.activeTimeouts.clear();
385
-
386
- // Clear hover timeout
387
- if (this.hoverTimeout) {
388
- clearTimeout(this.hoverTimeout);
389
- this.hoverTimeout = null;
390
- }
391
-
392
- // Clean up gesture state
393
- this.gestureService.clearElement(this.elementId);
394
-
395
- // Stop and clean up intersection observer instance
396
- if (this.inViewInstance) {
397
- try {
398
- this.inViewInstance.stop();
399
- } catch (e) {
400
- // Ignore errors if already stopped
401
- }
402
- this.inViewInstance = null;
403
- }
404
-
405
- // Disconnect intersection observer
406
- this.inViewService.disconnect(this.observer);
407
- this.observer = undefined;
408
-
409
- // Stop all animation controls
410
- if (this.controls) {
411
- try {
412
- this.controls.stop();
413
- } catch (e) {
414
- // Ignore errors if already stopped
415
- }
416
- this.controls = null;
417
- }
418
-
419
- // Stop all children animation controls
420
- this.childrenControls.forEach(control => {
421
- if (control) {
422
- try {
423
- control.stop();
424
- } catch (e) {
425
- // Ignore errors if already stopped
426
- }
427
- }
428
- });
429
- this.childrenControls = [];
430
-
431
- // Clean up child directive observers and controls
432
- if (this.childMotionDirectives) {
433
- this.childMotionDirectives.forEach(child => {
434
- if (child && child !== this) {
435
- // Stop child's inView instance
436
- if (child.inViewInstance) {
437
- try {
438
- child.inViewInstance.stop();
439
- } catch (e) {
440
- // Ignore errors
441
- }
442
- }
443
- // Disconnect child's observer
444
- if (child.observer) {
445
- this.inViewService.disconnect(child.observer);
446
- }
447
- // Stop child's controls
448
- if (child.controls) {
449
- try {
450
- child.controls.stop();
451
- } catch (e) {
452
- // Ignore errors
453
- }
454
- }
455
- }
456
- });
457
- }
458
-
459
- // Unregister from motion service
460
- this.motionService.unregisterMotionElement(this);
461
-
462
- // Skip exit animation on destroy to prevent blocking
463
- // Exit animations should be handled by Angular's built-in animation system
464
- }
465
-
466
- ngOnChanges(changes: SimpleChanges) {
467
- if (changes['animate'] && changes['animate'].previousValue !== undefined) {
468
- const oldState = changes['animate'].previousValue;
469
- let newState = changes['animate'].currentValue;
470
-
471
- if (typeof newState === 'object') {
472
- this.playAnimation(oldState, newState);
473
- } else if (typeof newState === 'string' && this.variants?.[newState]) {
474
- newState = this.variants[newState];
475
- this.playAnimation(oldState, newState);
476
- }
477
- }
478
-
479
- if (changes['transition'] && !changes['transition'].firstChange) {
480
- this.playAnimation(this.initial, this.animate);
481
- }
482
- }
483
-
484
- @HostListener('mouseenter')
485
- onMouseEnter() {
486
- if (Object.keys(this.whileHover).length > 0) {
487
- clearTimeout(this.hoverTimeout);
488
-
489
- // Check if we should allow this gesture (prevents aggressive rapid triggers)
490
- if (!this.gestureService.shouldAllowGesture(this.elementId, 'hover')) {
491
- return;
492
- }
493
-
494
- // Cancel any ongoing gesture animation state tracking
495
- this.gestureService.cancelGesture(this.elementId);
496
-
497
- // Don't stop the animation - Motion One will automatically interrupt it
498
- // and animate from the current position when we start a new animation
499
- // This creates smooth transitions even during rapid hovers
500
-
501
- // Animate to whileHover from current position
502
- // Motion One will automatically use current animated values as start
503
- this.playAnimationToTarget(this.whileHover, 'hover');
504
- }
505
- }
506
-
507
- @HostListener('mouseleave')
508
- onMouseLeave() {
509
- if (Object.keys(this.whileHover).length > 0) {
510
- clearTimeout(this.hoverTimeout);
511
-
512
- // Cancel the hover gesture state tracking
513
- this.gestureService.cancelGesture(this.elementId);
514
-
515
- // Animate back to initial/animate state from current position
516
- // Note: hoverTimeout is tracked separately and cleared in ngOnDestroy
517
- this.hoverTimeout = setTimeout(() => {
518
- if (Object.keys(this.animate).length > 0) {
519
- this.playAnimationToTarget(this.animate);
520
- } else {
521
- this.playAnimationToTarget(this.initial);
522
- }
523
- }, 100);
524
- }
525
- }
526
-
527
- @HostListener('mousedown', ['$event'])
528
- @HostListener('touchstart', ['$event'])
529
- onPress(event: Event) {
530
- if (Object.keys(this.whileTap).length > 0) {
531
- // Check if we should allow this gesture (prevents aggressive rapid triggers)
532
- if (!this.gestureService.shouldAllowGesture(this.elementId, 'tap')) {
533
- return;
534
- }
535
-
536
- // Cancel gesture state tracking
537
- this.gestureService.cancelGesture(this.elementId);
538
-
539
- // Animate to whileTap from current position
540
- this.playAnimationToTarget(this.whileTap, 'tap');
541
-
542
- if (isPlatformBrowser(this.platformId)) {
543
- const endEvent = event.type === 'mousedown' ? 'mouseup' : 'touchend';
544
- const endListener = () => {
545
- // Cancel the tap gesture state
546
- this.gestureService.cancelGesture(this.elementId);
547
-
548
- // Animate back from current position
549
- if (Object.keys(this.animate).length > 0) {
550
- this.playAnimationToTarget(this.animate);
551
- } else {
552
- this.playAnimationToTarget(this.initial);
553
- }
554
- window.removeEventListener(endEvent, endListener);
555
- };
556
- window.addEventListener(endEvent, endListener);
557
- }
558
- }
559
- }
560
-
561
- @HostListener('focus')
562
- onFocus() {
563
- if (Object.keys(this.whileFocus).length > 0) {
564
- // Check if we should allow this gesture (prevents aggressive rapid triggers)
565
- if (!this.gestureService.shouldAllowGesture(this.elementId, 'focus')) {
566
- return;
567
- }
568
-
569
- // Cancel gesture state tracking
570
- this.gestureService.cancelGesture(this.elementId);
571
-
572
- // Animate to whileFocus from current position
573
- this.playAnimationToTarget(this.whileFocus, 'focus');
574
- }
575
- }
576
-
577
- @HostListener('blur')
578
- onBlur() {
579
- if (Object.keys(this.whileFocus).length > 0) {
580
- // Cancel the focus gesture state
581
- this.gestureService.cancelGesture(this.elementId);
582
-
583
- // Animate back from current position
584
- if (Object.keys(this.animate).length > 0) {
585
- this.playAnimationToTarget(this.animate);
586
- } else {
587
- this.playAnimationToTarget(this.initial);
588
- }
589
- }
590
- }
591
-
592
- applyInitialValues() {
593
- const styles = extractStyleProperties(this.getVariant(this.initial));
594
- Object.assign(this.el.nativeElement.style, styles);
595
- }
596
-
597
- private applyInitialStyles() {
598
- const styles = extractStyleProperties(this.getVariant(this.initial));
599
-
600
- if (styles && Object.keys(styles).length > 0) {
601
- if (this.isRunInViewEnabled) {
602
- this.el.nativeElement.style.transition = 'none';
603
- Object.assign(this.el.nativeElement.style, styles);
604
- this.el.nativeElement.offsetHeight;
605
- this.el.nativeElement.style.transition = '';
606
- } else {
607
- Object.assign(this.el.nativeElement.style, styles);
608
- }
609
- }
610
- }
611
-
612
- private applyAnimateStyles() {
613
- const styles = extractStyleProperties(this.getVariant(this.animate));
614
- Object.assign(this.el.nativeElement.style, styles);
615
- }
616
-
617
- public extractStyleProperties(variant: VariantWithTransition): Record<string, any> {
618
- return extractStyleProperties(variant);
619
- }
620
-
621
- private getAnimationOptions(targetState?: VariantWithTransition): AnimationOptions {
622
- return this.animationOptions.getAnimationOptions({
623
- targetState,
624
- animateState: this.getVariant(this.animate),
625
- staggerDelay: this.staggerDelay,
626
- transition: this.transition,
627
- delay: this.delay,
628
- easing: this.easing,
629
- duration: this.duration,
630
- repeat: this.repeat,
631
- onComplete: () => this.animationComplete.emit()
632
- });
633
- }
634
-
635
- private getStaggerValue(): number {
636
- return this.animationOptions.getStaggerValue(
637
- this.getVariant(this.animate),
638
- this.transition,
639
- this.staggerChildren
640
- );
641
- }
642
-
643
- private getStaggerDirection(): number {
644
- return this.animationOptions.getStaggerDirection(
645
- this.getVariant(this.animate),
646
- this.transition,
647
- this.staggerDirection
648
- );
649
- }
650
-
651
- private getWhen(): 'beforeChildren' | 'afterChildren' | 'together' {
652
- return this.animationOptions.getWhen(
653
- this.getVariant(this.animate),
654
- this.transition
655
- );
656
- }
657
-
658
- /**
659
- * Play animation TO a target state from current position
660
- * Motion One will automatically use current animated values as the start
661
- */
662
- private playAnimationToTarget(
663
- targetState: VariantWithTransition | string,
664
- gestureType?: 'hover' | 'tap' | 'focus'
665
- ) {
666
- if (!targetState || !isPlatformBrowser(this.platformId)) return;
667
-
668
- const resolvedTargetState = resolveVariant(targetState, this.variants);
669
-
670
- if (resolvedTargetState.at !== undefined) {
671
- const timeoutId = setTimeout(() => {
672
- this.animateToTarget(resolvedTargetState, gestureType);
673
- this.activeTimeouts.delete(timeoutId);
674
- }, resolvedTargetState.at * 1000);
675
- this.activeTimeouts.add(timeoutId);
676
- return;
677
- }
678
-
679
- this.animateToTarget(resolvedTargetState, gestureType);
680
- }
681
-
682
- /**
683
- * Original playAnimation method - still used for initial animations and explicit start→end
684
- */
685
- private playAnimation(
686
- startState: VariantWithTransition | string,
687
- targetState: VariantWithTransition | string,
688
- gestureType?: 'hover' | 'tap' | 'focus'
689
- ) {
690
- if (!targetState || !isPlatformBrowser(this.platformId)) return;
691
-
692
- const resolvedStartState = resolveVariant(startState || this.initial, this.variants);
693
- const resolvedTargetState = resolveVariant(targetState || this.animate, this.variants);
694
-
695
- if (resolvedTargetState.at !== undefined) {
696
- const timeoutId = setTimeout(() => {
697
- this.continueAnimation(resolvedTargetState, false, gestureType);
698
- this.activeTimeouts.delete(timeoutId);
699
- }, resolvedTargetState.at * 1000);
700
- this.activeTimeouts.add(timeoutId);
701
- return;
702
- }
703
-
704
- this.continueAnimation(resolvedTargetState, false, gestureType);
705
- }
706
-
707
- /**
708
- * Animate to target from current position without explicit start state
709
- * Motion One automatically interrupts any conflicting animations and preserves velocity
710
- */
711
- private animateToTarget(
712
- resolvedTargetState: VariantWithTransition,
713
- gestureType?: 'hover' | 'tap' | 'focus'
714
- ) {
715
- // Timeline takes precedence
716
- if (this.timeline && this.timeline.length > 0) {
717
- this.runTimeline(resolvedTargetState);
718
- return;
719
- }
720
-
721
- // Per-property transition map
722
- const t: any = resolvedTargetState.transition;
723
- if (this.timelineService.isPerPropertyTransition(t)) {
724
- this.runPerPropertyAnimations(resolvedTargetState);
725
- return;
726
- }
727
-
728
- // Get animation options
729
- const options = this.getAnimationOptions(resolvedTargetState);
730
- const targetStyles = extractStyleProperties(resolvedTargetState);
731
-
732
- // Motion One automatically interrupts conflicting animations
733
- // By passing individual transform properties (rotate, scale, x, y),
734
- // Motion One can smoothly interpolate and preserve spring velocity
735
- this.controls = this.motionAnimation.animate(
736
- this.el.nativeElement as Target,
737
- targetStyles,
738
- options
739
- );
740
-
741
- // Register gesture animation if this is a gesture
742
- if (gestureType) {
743
- this.gestureService.startGesture(
744
- this.elementId,
745
- gestureType,
746
- typeof resolvedTargetState === 'string' ? resolvedTargetState : 'custom',
747
- this.controls
748
- );
749
- }
750
- }
751
-
752
- private continueAnimation(
753
- resolvedTargetState: VariantWithTransition,
754
- isInitialAnimation: boolean,
755
- gestureType?: 'hover' | 'tap' | 'focus'
756
- ) {
757
- // Timeline takes precedence
758
- if (this.timeline && this.timeline.length > 0) {
759
- this.runTimeline(resolvedTargetState);
760
- return;
761
- }
762
-
763
- // Per-property transition map
764
- const t: any = resolvedTargetState.transition;
765
- if (this.timelineService.isPerPropertyTransition(t)) {
766
- this.runPerPropertyAnimations(resolvedTargetState);
767
- return;
768
- }
769
-
770
- // Check for stagger on initial animation
771
- if (isInitialAnimation && !this.initialAnimationPlayed) {
772
- const staggerValue = this.getStaggerValue();
773
- if (staggerValue > 0 && this.childMotionDirectives && this.childMotionDirectives.length > 1) {
774
- const when = this.getWhen();
775
- if (when !== 'afterChildren') {
776
- this.runSelfAnimation();
777
- }
778
- return;
779
- }
780
- }
781
-
782
- // Normal animation
783
- const options = this.getAnimationOptions(resolvedTargetState);
784
- const targetStyles = extractStyleProperties(resolvedTargetState);
785
-
786
- this.controls = this.motionAnimation.animate(
787
- this.el.nativeElement as Target,
788
- targetStyles,
789
- options
790
- );
791
-
792
- // Register gesture animation if this is a gesture
793
- if (gestureType) {
794
- this.gestureService.startGesture(
795
- this.elementId,
796
- gestureType,
797
- typeof resolvedTargetState === 'string' ? resolvedTargetState : 'custom',
798
- this.controls
799
- );
800
- }
801
-
802
- if (isInitialAnimation) {
803
- this.initialAnimationPlayed = true;
804
- }
805
-
806
- // Handle regular DOM children (without motionone directives)
807
- if (!isInitialAnimation && this.el.nativeElement.children.length > 0) {
808
- const children = Array.from(this.el.nativeElement.children) as HTMLElement[];
809
- children.forEach((child) => {
810
- if (child.hasAttribute('motionone')) return;
811
- const childControl = this.motionAnimation.animate(child, targetStyles, options);
812
- this.childrenControls.push(childControl);
813
- });
814
- }
815
- }
816
-
817
- private runPerPropertyAnimations(resolvedTargetState: VariantWithTransition) {
818
- const baseDelay = this.staggerDelay !== undefined && this.staggerDelay >= 0
819
- ? this.staggerDelay
820
- : (((resolvedTargetState.transition as TransitionOptions)?.delay) ?? this.delay);
821
-
822
- const result = this.timelineService.runPerPropertyAnimations(
823
- this.el.nativeElement,
824
- resolvedTargetState,
825
- baseDelay,
826
- this.duration,
827
- this.easing,
828
- this.repeat,
829
- () => this.animationComplete.emit()
830
- );
831
-
832
- this.childrenControls = result.controls;
833
- }
834
-
835
- private runTimeline(resolvedTargetState: VariantWithTransition) {
836
- const baseDelay = this.staggerDelay !== undefined && this.staggerDelay >= 0
837
- ? this.staggerDelay
838
- : (((resolvedTargetState.transition as TransitionOptions)?.delay) ?? this.delay);
839
-
840
- const result = this.timelineService.runTimeline(
841
- this.el.nativeElement,
842
- this.timeline!,
843
- resolvedTargetState,
844
- baseDelay,
845
- this.duration,
846
- this.easing,
847
- this.repeat,
848
- () => this.animationComplete.emit()
849
- );
850
-
851
- this.childrenControls = result.controls;
852
- }
853
-
854
- private setupInViewAnimation() {
855
- if (isPlatformBrowser(this.platformId)) {
856
- try {
857
- if (this.isRunInViewEnabled) {
858
- this.setupMotionOneInView();
859
- } else {
860
- const hasWhileInView = this.whileInView && Object.keys(this.whileInView).length > 0;
861
- const hasInView = this.inView && Object.keys(this.inView).length > 0;
862
-
863
- if (hasWhileInView) {
864
- this.setupWhileInViewAnimation();
865
- } else if (hasInView) {
866
- this.inViewInstance = inView(
867
- this.el.nativeElement,
868
- (info: any) => {
869
- this.runInViewAnimation();
870
- },
871
- {
872
- margin: this.offset,
873
- amount: 'some'
874
- }
875
- );
876
- }
877
- }
878
- } catch (error) {
879
- console.error('[MotionOne] ❌ Error setting up inView observer:', error);
880
- }
881
- }
882
- }
883
-
884
- runInViewAnimation() {
885
- if (this.inView && Object.keys(this.inView).length > 0) {
886
- this.playAnimation(this.initial, this.inView);
887
- } else if (this.whileInView && Object.keys(this.whileInView).length > 0) {
888
- this.playAnimation(this.initial, this.whileInView);
889
- }
890
- }
891
-
892
- private setupWhileInViewAnimation() {
893
- this.inViewInstance = inView(
894
- this.el.nativeElement,
895
- (info: any) => {
896
- this.playAnimation(this.initial, this.whileInView);
897
- },
898
- {
899
- margin: this.offset,
900
- amount: 'some'
901
- }
902
- );
903
- }
904
-
905
- private setupMotionOneInView() {
906
- const margin = this.offset || MOTION_DEFAULTS.INVIEW_MARGIN;
907
- const hasStaggerChildren = this.getStaggerValue() > 0 && this.childMotionDirectives?.length > 1;
908
-
909
- if (hasStaggerChildren && !this.isChild) {
910
- this.setupStaggerParentInView(margin);
911
- } else if (!this.isStaggeredChild) {
912
- this.setupIndividualElementInView(margin);
913
- }
914
- }
915
-
916
- private setupStaggerParentInView(margin: string) {
917
- this.inViewInstance = inView(
918
- this.el.nativeElement,
919
- (info: { isIntersecting: boolean }) => {
920
- if (info.isIntersecting) {
921
- if (this.controls) this.controls.stop();
922
-
923
- const parentInitialStyles = extractStyleProperties(this.getVariant(this.initial));
924
- if (Object.keys(parentInitialStyles).length > 0) {
925
- this.el.nativeElement.style.transition = 'none';
926
- Object.assign(this.el.nativeElement.style, parentInitialStyles);
927
- this.el.nativeElement.offsetHeight;
928
- this.el.nativeElement.style.transition = '';
929
- }
930
-
931
- const childDirectives = this.childMotionDirectives?.filter(child => child !== this) || [];
932
-
933
- if (childDirectives.length > 0) {
934
- childDirectives.forEach(child => {
935
- if (child.controls) child.controls.stop();
936
- const childInitialStyles = child.extractStyleProperties(child.getVariant(child.initial));
937
- child.el.nativeElement.style.transition = 'none';
938
- Object.assign(child.el.nativeElement.style, childInitialStyles);
939
- child.el.nativeElement.offsetHeight;
940
- child.el.nativeElement.style.transition = '';
941
- });
942
-
943
- const timeoutId = setTimeout(() => {
944
- const staggerValue = this.getStaggerValue();
945
- childDirectives.forEach((child, index) => {
946
- const childAnimateStyles = child.extractStyleProperties(child.getVariant(child.animate));
947
- const options = child.getAnimationOptions();
948
- const staggerDelay = index * staggerValue;
949
- options.delay = staggerDelay;
950
- child.controls = animate(child.el.nativeElement, childAnimateStyles, options);
951
- });
952
-
953
- const parentAnimateStyles = extractStyleProperties(this.getVariant(this.animate));
954
- if (Object.keys(parentAnimateStyles).length > 0) {
955
- const parentOptions = this.getAnimationOptions();
956
- this.controls = animate(this.el.nativeElement, parentAnimateStyles, parentOptions);
957
- }
958
- this.activeTimeouts.delete(timeoutId);
959
- }, MOTION_DEFAULTS.STAGGER_TIMEOUT);
960
- this.activeTimeouts.add(timeoutId);
961
- }
962
- } else if (this.runInViewRepeat === 'always') {
963
- if (this.controls) this.controls.stop();
964
-
965
- const parentInitialStyles = extractStyleProperties(this.getVariant(this.initial));
966
- if (Object.keys(parentInitialStyles).length > 0) {
967
- this.el.nativeElement.style.transition = 'none';
968
- Object.assign(this.el.nativeElement.style, parentInitialStyles);
969
- this.el.nativeElement.offsetHeight;
970
- this.el.nativeElement.style.transition = '';
971
- }
972
-
973
- const childDirectives = this.childMotionDirectives?.filter(child => child !== this) || [];
974
- childDirectives.forEach(child => {
975
- if (child.controls) child.controls.stop();
976
- const childInitialStyles = child.extractStyleProperties(child.getVariant(child.initial));
977
- child.el.nativeElement.style.transition = 'none';
978
- Object.assign(child.el.nativeElement.style, childInitialStyles);
979
- child.el.nativeElement.offsetHeight;
980
- child.el.nativeElement.style.transition = '';
981
- });
982
- }
983
- },
984
- {
985
- margin,
986
- amount: 0.1
987
- }
988
- );
989
- }
990
-
991
- private setupIndividualElementInView(margin: string) {
992
- this.inViewInstance = inView(
993
- this.el.nativeElement,
994
- (info: { isIntersecting: boolean }) => {
995
- if (info.isIntersecting) {
996
- if (this.controls) this.controls.stop();
997
-
998
- const initialStyles = extractStyleProperties(this.getVariant(this.initial));
999
- this.el.nativeElement.style.transition = 'none';
1000
- Object.assign(this.el.nativeElement.style, initialStyles);
1001
- this.el.nativeElement.offsetHeight;
1002
- this.el.nativeElement.style.transition = '';
1003
-
1004
- const timeoutId = setTimeout(() => {
1005
- this.playAnimation(this.initial, this.animate);
1006
- this.activeTimeouts.delete(timeoutId);
1007
- }, MOTION_DEFAULTS.STAGGER_TIMEOUT);
1008
- this.activeTimeouts.add(timeoutId);
1009
- } else if (this.runInViewRepeat === 'always') {
1010
- if (this.controls) this.controls.stop();
1011
-
1012
- const initialStyles = extractStyleProperties(this.getVariant(this.initial));
1013
- this.el.nativeElement.style.transition = 'none';
1014
- Object.assign(this.el.nativeElement.style, initialStyles);
1015
- this.el.nativeElement.offsetHeight;
1016
- this.el.nativeElement.style.transition = '';
1017
- }
1018
- },
1019
- {
1020
- margin,
1021
- amount: 0.1
1022
- }
1023
- );
1024
- }
1025
-
1026
- runInitAnimation() {
1027
- if (!isPlatformBrowser(this.platformId) || !this.initial || !this.animate) return;
1028
-
1029
- if (this.isChild && this.staggerDelay !== undefined && this.staggerDelay >= 0) {
1030
- if (!this._skipStartStylesApplication) {
1031
- const startStyles = extractStyleProperties(this.getVariant(this.initial));
1032
- const element = this.el.nativeElement;
1033
- element.style.transition = 'none';
1034
- Object.assign(element.style, startStyles);
1035
- } else {
1036
- this._skipStartStylesApplication = false;
1037
- }
1038
- this.el.nativeElement.offsetHeight;
1039
-
1040
- const timeoutId = setTimeout(() => {
1041
- this.el.nativeElement.style.transition = '';
1042
- this.playAnimation(this.initial, this.animate);
1043
- this.activeTimeouts.delete(timeoutId);
1044
- }, 5);
1045
- this.activeTimeouts.add(timeoutId);
1046
-
1047
- this.initialAnimationPlayed = true;
1048
- } else {
1049
- this.playAnimation(this.initial, this.animate);
1050
- }
1051
- }
1052
-
1053
- runExitAnimation(): Promise<void> {
1054
- if (!isPlatformBrowser(this.platformId)) {
1055
- return Promise.resolve();
1056
- }
1057
-
1058
- if (!this.exit || Object.keys(this.exit).length === 0) {
1059
- return Promise.resolve();
1060
- }
1061
-
1062
- const exitTransition = (this.getVariant(this.exit).transition as TransitionOptions) ||
1063
- (this.transition as TransitionOptions) ||
1064
- {} as TransitionOptions;
1065
-
1066
- return new Promise<void>((resolve) => {
1067
- const exitOptions: any = {
1068
- duration: (exitTransition.duration ?? this.duration) as number,
1069
- delay: (exitTransition.delay ?? this.exitDelay) as number,
1070
- onComplete: () => {
1071
- this.animationComplete.emit();
1072
- resolve();
1073
- }
1074
- };
1075
-
1076
- const options: any = this.animationOptions.getAnimationOptions({
1077
- targetState: this.getVariant(this.exit),
1078
- transition: this.transition,
1079
- delay: this.delay,
1080
- easing: this.easing,
1081
- duration: this.duration,
1082
- repeat: this.repeat
1083
- });
1084
-
1085
- exitOptions.easing = options.easing || options.ease;
1086
- exitOptions.ease = options.ease || options.easing;
1087
-
1088
- if (this.controls) {
1089
- this.controls.stop();
1090
- }
1091
-
1092
- this.childrenControls.forEach(control => {
1093
- if (control) control.stop();
1094
- });
1095
-
1096
- const exitStyles = extractStyleProperties(this.getVariant(this.exit));
1097
-
1098
- this.controls = this.motionAnimation.animate(
1099
- this.el.nativeElement as Target,
1100
- exitStyles,
1101
- exitOptions
1102
- );
1103
-
1104
- if (!exitOptions.duration) {
1105
- resolve();
1106
- }
1107
- });
1108
- }
1109
-
1110
- cancel() {
1111
- if (this.controls) {
1112
- this.controls.stop();
1113
- }
1114
-
1115
- this.childrenControls.forEach(control => {
1116
- if (control) control.stop();
1117
- });
1118
-
1119
- this.applyAnimateStyles();
1120
- }
1121
-
1122
- getDuration(): number {
1123
- if (!isPlatformBrowser(this.platformId)) return 0;
1124
-
1125
- try {
1126
- const animateTransition = (this.getVariant(this.exit)?.transition as TransitionOptions) ||
1127
- (this.transition as TransitionOptions) ||
1128
- {} as TransitionOptions;
1129
- const duration = (animateTransition.duration ?? this.duration) as number;
1130
- const delay = (animateTransition.delay ?? this.delay) as number;
1131
- return (Number(duration) + Number(delay)) * 1000;
1132
- } catch (error) {
1133
- console.error('Error calculating duration:', error);
1134
- return 0;
1135
- }
1136
- }
1137
-
1138
- getKeyByValue(object: any, key: any) {
1139
- return Object.keys(object).find((k) => object[k] === key);
1140
- }
1141
-
1142
- public triggerExitAnimation(): Promise<void> {
1143
- return this.runExitAnimation();
1144
- }
1145
-
1146
- @HostListener('motionExit')
1147
- onMotionExit() {
1148
- this.runExitAnimation();
1149
- }
1150
-
1151
- public getVariant(variant: VariantWithTransition | string): VariantWithTransition {
1152
- return resolveVariant(variant, this.variants);
1153
- }
1154
- }