@hilux/ngx-motion 1.1.1 → 2.0.0

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 +289 -269
  2. package/fesm2022/hilux-ngx-motion.mjs +2030 -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 +777 -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,1591 +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 type { AnimationOptions, Target } from 'motion';
23
- import { animate, easeIn, easeOut, easeInOut, stagger, inView } from '../services/motion-browser-safe';
24
-
25
- // Define interface for transition object similar to Framer Motion
26
- export interface TransitionOptions {
27
- duration?: number;
28
- delay?: number;
29
- ease?: string | number[] | { type: 'spring'; stiffness?: number; damping?: number };
30
- repeat?: number | boolean;
31
- repeatType?: 'loop' | 'mirror' | 'reverse' | 'forwards' | 'pingPong';
32
- repeatDelay?: number;
33
- staggerChildren?: number;
34
- staggerDirection?: number;
35
- when?: 'beforeChildren' | 'afterChildren' | 'together';
36
- delayChildren?: number;
37
- times?: number[]; // keyframe times 0..1
38
- }
39
-
40
- // Define interface for variants that can include transition properties
41
- export interface VariantWithTransition {
42
- [key: string]: any;
43
- transition?: TransitionOptions;
44
- at?: number; // Add 'at' property to define when variant should be triggered
45
- }
46
-
47
- // Optional timeline support for orchestrated per-property steps
48
- export interface TimelineStep {
49
- prop: string;
50
- keyframes?: any[] | any;
51
- to?: any;
52
- duration: number;
53
- delay?: number;
54
- ease?: string | number[] | { type: 'spring'; stiffness?: number; damping?: number };
55
- atTime?: number; // absolute start (s) relative to element start
56
- times?: number[];
57
- repeat?: number | boolean;
58
- repeatType?: 'loop' | 'mirror' | 'reverse' | 'forwards' | 'pingPong';
59
- repeatDelay?: number;
60
- }
61
-
62
- let uniqueIdCounter = 0;
63
-
64
- @Directive({
65
- selector: '[motionone]',
66
- standalone: true,
67
- exportAs: 'motionone'
68
- })
69
-
70
- export class MotionOneDirective implements OnInit, OnDestroy, OnChanges, AfterContentInit {
71
- @Input() initial: VariantWithTransition | string = {};
72
- @Input() animate: VariantWithTransition | string = {};
73
- @Input() exit: VariantWithTransition | string = {};
74
- @Input() inView: VariantWithTransition = {};
75
- @Input() duration = 0.3; // Changed to number for Motion One
76
- @Input() delay = 0; // Changed to number for Motion One
77
- @Input() delayChildren = 0; // Add new input for delaying children
78
- @Input() repeat = false;
79
- @Input() exitDelay = 0; // Changed to number for Motion One
80
- @Input() easing: string | number[] | { type: 'spring'; stiffness?: number; damping?: number } = 'ease';
81
- @Input() offset = '0px';
82
- @Input() whileHover: VariantWithTransition = {};
83
- @Input() staggerChildren = 1; // Changed to number for Motion One
84
- @Input() staggerDirection = 1; // Changed to number for Motion One
85
- @Input() whileTap: VariantWithTransition = {};
86
- @Input() whileFocus: VariantWithTransition = {};
87
- @Input() whileInView: VariantWithTransition = {};
88
- @Input() runInView?: 'never' | 'once' | 'always'; // Controls if animation waits for inView ('never'/undefined = immediate, 'once' = single trigger, 'always' = repeats on scroll)
89
- @Input() variants: { [key: string]: VariantWithTransition } = {};
90
- @Input() transition: TransitionOptions | Record<string, TransitionOptions> = {};
91
- @Input() timeline: TimelineStep[] | undefined;
92
- @Output() animationComplete = new EventEmitter<void>();
93
-
94
-
95
- // Add a public method to restart animations
96
- public restartAnimation() {
97
-
98
- // Stop any current animations
99
- if (this.controls) {
100
- this.controls.stop();
101
- }
102
-
103
- // Force reset to initial state immediately without animation
104
- const initialVariant = this.getVariant(this.initial);
105
- const initialStyles = this.extractStyleProperties(initialVariant);
106
-
107
- // Apply initial styles directly with no transition
108
- const element = this.el.nativeElement;
109
- element.style.transition = 'none';
110
- Object.assign(element.style, initialStyles);
111
-
112
- // Force a reflow to ensure the reset is applied
113
- element.offsetHeight;
114
-
115
- // Remove the transition override and start the animation fresh
116
- setTimeout(() => {
117
- element.style.transition = '';
118
-
119
- // Check if this element uses runInView
120
- if (this.isRunInViewEnabled) {
121
- // For runInView elements, just reset to initial and let inView handle the animation
122
- // Element is already reset to initial, inView will trigger when appropriate
123
- } else {
124
- // For non-runInView elements, play the animation directly
125
- this.playAnimation(this.initial, this.animate);
126
- }
127
- }, 10);
128
- }
129
-
130
- // Query for child motionone directives
131
- @ContentChildren(MotionOneDirective, { descendants: true }) childMotionDirectives!: QueryList<MotionOneDirective>;
132
-
133
- private controls: ReturnType<typeof animate> | null = null;
134
- private childrenControls: ReturnType<typeof animate>[] = [];
135
- public elementId: string;
136
- private hoverTimeout: any;
137
- private observer?: IntersectionObserver;
138
- private routeDelay: number = 0;
139
- private inViewInstance: any;
140
- private isChild = false;
141
- private parentDirective: MotionOneDirective | null = null;
142
- private initialAnimationPlayed = false;
143
- private _skipStartStylesApplication = false;
144
- private staggerDelay: number | undefined = undefined;
145
- private childrenCount = 0;
146
- private childIndex = 0;
147
- private isStaggeredChild = false; // Flag to indicate if this child is part of a stagger group
148
-
149
- get scrollProgress() {
150
- return this.motionService.scrollYProgress();
151
- }
152
-
153
- // Helper methods for runInView configuration
154
- private get isRunInViewEnabled(): boolean {
155
- return this.runInView === 'once' || this.runInView === 'always';
156
- }
157
-
158
- private get runInViewRepeat(): 'once' | 'always' {
159
- return this.runInView === 'always' ? 'always' : 'once'; // Default to 'once' if undefined or 'never'
160
- }
161
-
162
- constructor(
163
- public el: ElementRef,
164
- private motionService: MotionOneService,
165
- private motionAnimation: MotionAnimationService,
166
- private router: Router,
167
- @Inject(PLATFORM_ID) private platformId: Object
168
- ) {
169
- this.elementId = `motion-${uniqueIdCounter++}`;
170
-
171
- // Only run browser-specific code in browser environment
172
- if (isPlatformBrowser(this.platformId)) {
173
- this.el.nativeElement.setAttribute('id', this.elementId);
174
- // Store a reference to this directive on the element for easier access
175
- (this.el.nativeElement as any)._motionDirective = this;
176
- this.motionService.registerMotionElement(this);
177
- this.applyInitialStyles();
178
- this.routeDelay = this.motionService.getLongestExitDurationForRoute(this.router.url);
179
- }
180
- }
181
-
182
- ngOnInit() {
183
- this.applyInitialStyles(); // Ensure initial styles are applied
184
-
185
- // Only run animations in browser environment
186
- if (isPlatformBrowser(this.platformId)) {
187
- // Check if this is a child of another motionone directive
188
- let parent = this.el.nativeElement.parentElement;
189
- while (parent) {
190
- if (parent.hasAttribute('motionone')) {
191
- this.isChild = true;
192
- break;
193
- }
194
- parent = parent.parentElement;
195
- }
196
-
197
-
198
- // Set up runInView logic based on parent-child relationship
199
- if (this.isRunInViewEnabled) {
200
- if (!this.isChild) {
201
- // Host elements (non-child) with runInView set up their own observer immediately
202
- this.setupInViewAnimation();
203
- } else {
204
- // Child elements with runInView only set up observer if parent doesn't have stagger
205
- // We'll check this later in ngAfterContentInit when we know about parent stagger settings
206
- }
207
- } else if (!this.isChild) {
208
- // Only auto-play animation if not a child AND no runInView
209
- this.playAnimation(this.initial, this.animate);
210
- }
211
-
212
- // Setup inView/whileInView animations - these work independently of runInView
213
- // Only set up if this element is not managed by a parent with runInView
214
- if (!this.isStaggeredChild &&
215
- ((this.inView && Object.keys(this.inView).length > 0) ||
216
- (this.whileInView && Object.keys(this.whileInView).length > 0))) {
217
- this.setupInViewAnimation();
218
- }
219
- }
220
- }
221
-
222
- ngAfterContentInit() {
223
- // Register child directives if we have staggerChildren
224
- if (this.childMotionDirectives && this.childMotionDirectives.length > 0) {
225
-
226
- // Set this directive as the parent for all children
227
- setTimeout(() => {
228
- // Filter out self from children
229
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
230
- this.childrenCount = childDirectives.length;
231
-
232
-
233
- // Set parent and index for each child
234
- childDirectives.forEach((child, index) => {
235
- child.setParent(this, index, this.childrenCount);
236
- });
237
-
238
- // Check if we need to stagger children
239
- const staggerValue = this.getStaggerValue();
240
-
241
- // Handle child runInView setup based on parent runInView and stagger
242
- if (this.runInView === 'always') {
243
-
244
- // Mark ALL children as managed by parent (regardless of stagger)
245
- childDirectives.forEach(child => {
246
- if (child.isRunInViewEnabled) {
247
- child.isStaggeredChild = true; // Mark so child knows parent manages it
248
- // DO NOT set up intersection observer - parent handles everything
249
- }
250
- });
251
-
252
- // CRITICAL: Set up intersection observer for the parent
253
- this.setupRunInViewObserver();
254
-
255
- // Check if we have stagger
256
- if (staggerValue > 0 && this.childrenCount > 0) {
257
- } else {
258
- }
259
- } else if (staggerValue > 0 && this.childrenCount > 0) {
260
-
261
- // For staggered children, mark them as staggered but DON'T set up intersection observers
262
- childDirectives.forEach(child => {
263
- if (child.isRunInViewEnabled) {
264
- child.isStaggeredChild = true;
265
- }
266
- });
267
-
268
- // Trigger staggered animations for children (only if parent not using runInView)
269
- if (!this.isRunInViewEnabled) {
270
- this.applyStaggerToChildren();
271
- } else {
272
- }
273
- } else {
274
-
275
- // If no stagger and parent doesn't have runInView="always", children can set up their own observers
276
- childDirectives.forEach(child => {
277
- if (child.isRunInViewEnabled) {
278
- child.setupInViewAnimation();
279
- }
280
- });
281
- }
282
- });
283
- } else {
284
- }
285
- }
286
-
287
- setParent(parent: MotionOneDirective, index: number, totalChildren: number) {
288
- this.parentDirective = parent;
289
- this.isChild = true;
290
- this.childIndex = index;
291
- this.childrenCount = totalChildren;
292
- }
293
-
294
- // COMPLETE RESET METHOD: Reset parent and all children to initial state (like Framer Motion)
295
- public completeResetToInitial() {
296
-
297
- // 1. Reset self to initial
298
- this.forceResetToInitial();
299
-
300
- // 2. Reset all children to their individual initial states
301
- if (this.childMotionDirectives && this.childMotionDirectives.length > 0) {
302
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
303
-
304
- childDirectives.forEach((child, index) => {
305
- child.forceResetToInitial();
306
- });
307
-
308
- }
309
- }
310
-
311
- // FORCE RESET: Reset this element to its initial state immediately
312
- public forceResetToInitial() {
313
-
314
- // Stop any current animation immediately
315
- if (this.controls) {
316
- this.controls.stop();
317
- this.controls = null;
318
- }
319
-
320
- // Get this element's initial state
321
- const initialVariant = this.getVariant(this.initial);
322
- const initialStyles = this.extractStyleProperties(initialVariant);
323
-
324
-
325
- // Apply initial styles immediately with no transition
326
- this.el.nativeElement.style.transition = 'none';
327
-
328
- // Clear any existing styles first
329
- this.el.nativeElement.style.opacity = '';
330
- this.el.nativeElement.style.transform = '';
331
-
332
- // Apply initial styles
333
- Object.assign(this.el.nativeElement.style, initialStyles);
334
- this.el.nativeElement.offsetHeight; // Force reflow
335
- this.el.nativeElement.style.transition = '';
336
-
337
- // Reset animation flags
338
- this.initialAnimationPlayed = false;
339
-
340
- }
341
-
342
- // Simple method to reset child to initial if parent has runInView
343
- public resetToInitialIfParentHasRunInView() {
344
- this.forceResetToInitial();
345
- }
346
-
347
- // Method to call complete reset when parent exits viewport
348
- public parentExitViewportReset() {
349
- this.completeResetToInitial();
350
- }
351
-
352
- // Set up intersection observer for runInView functionality
353
- private setupRunInViewObserver() {
354
-
355
- if (!isPlatformBrowser(this.platformId)) {
356
- return;
357
- }
358
-
359
- // Create intersection observer with proper threshold
360
- this.observer = new IntersectionObserver(
361
- (entries) => {
362
- entries.forEach((entry) => {
363
-
364
- if (entry.isIntersecting) {
365
- this.handleViewportEntry();
366
- } else {
367
- this.handleViewportExit();
368
- }
369
- });
370
- },
371
- {
372
- root: null, // Use viewport as root
373
- rootMargin: '0px',
374
- threshold: 0.1 // Trigger when 10% of element is visible
375
- }
376
- );
377
-
378
- // Start observing the element
379
- this.observer.observe(this.el.nativeElement);
380
- }
381
-
382
- // Handle when element enters viewport
383
- private handleViewportEntry() {
384
-
385
- // Check if we have stagger children
386
- const staggerValue = this.getStaggerValue();
387
- if (staggerValue > 0 && this.childMotionDirectives?.length > 0) {
388
- this.applyStaggerToChildren();
389
- } else {
390
- this.playAnimation(this.initial, this.animate);
391
- }
392
- }
393
-
394
- // Handle when element exits viewport
395
- private handleViewportExit() {
396
- if (this.runInView === 'always') {
397
-
398
- // Force children to their initial variant state
399
- if (this.childMotionDirectives && this.childMotionDirectives.length > 0) {
400
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
401
- childDirectives.forEach((child) => {
402
-
403
- // Stop any animation and immediately set to initial variant
404
- if (child.controls) {
405
- child.controls.stop();
406
- child.controls = null;
407
- }
408
-
409
- // Use playAnimation to go to initial variant (instant)
410
- child.playAnimation(child.animate, child.initial);
411
- child.initialAnimationPlayed = false;
412
- });
413
- }
414
- }
415
- }
416
-
417
- // Method to stagger children animations
418
- applyStaggerToChildren() {
419
-
420
- // Get stagger configuration
421
- const staggerValue = this.getStaggerValue();
422
- const staggerDirection = this.getStaggerDirection();
423
- const delayChildren = this.delayChildren; // number
424
- const parentDelay = (((this.transition as TransitionOptions)?.delay) ?? 0) as number;
425
-
426
-
427
- // Get all child directives (excluding self)
428
- const childDirectives = this.childMotionDirectives.filter(child => child !== this);
429
-
430
- // Determine when to animate parent relative to children
431
- const when = this.getWhen();
432
-
433
- // Animate parent if needed
434
- if (when !== 'afterChildren') {
435
- this.runSelfAnimation();
436
- }
437
-
438
- // Animate each child with appropriate stagger delay
439
- childDirectives.forEach((childDirective, index) => {
440
- // Calculate the stagger delay based on index and direction
441
- let staggerIndex;
442
- if (staggerDirection >= 0) {
443
- staggerIndex = index;
444
- } else {
445
- staggerIndex = this.childrenCount - 1 - index;
446
- }
447
-
448
- // Combine parent delay, delayChildren, and stagger delay
449
- const totalDelay = (parentDelay as number) + delayChildren + (staggerIndex * staggerValue);
450
-
451
-
452
- // CRITICAL: Override child's transition delay to prevent conflicts
453
- // Clear any user-defined delays that would interfere with stagger timing
454
- if (childDirective.transition && typeof childDirective.transition === 'object') {
455
- const childTransition = childDirective.transition as any;
456
- if (childTransition.delay !== undefined) {
457
- // Temporarily clear the child's delay
458
- childTransition.delay = undefined;
459
- }
460
- }
461
-
462
- // Force override the child's delay with calculated stagger delay
463
- childDirective.overrideDelay(totalDelay);
464
-
465
- // CRITICAL: Use child's own variants directly (parent has no initial/animate)
466
- setTimeout(() => {
467
- childDirective.playAnimation(childDirective.initial, childDirective.animate);
468
- }, totalDelay * 1000);
469
- });
470
-
471
- // Animate parent after children if specified
472
- if (when === 'afterChildren') {
473
- const totalChildrenDuration = (parentDelay as number) + delayChildren + (this.childrenCount * staggerValue);
474
- this.overrideDelay(totalChildrenDuration);
475
- this.runSelfAnimation();
476
- }
477
-
478
- }
479
-
480
- // Method to override the delay for this directive
481
- overrideDelay(delay: number) {
482
- this.staggerDelay = delay;
483
- }
484
-
485
- // Run animation only for this element (not children)
486
- runSelfAnimation() {
487
- // Get animation options
488
- const options = this.getAnimationOptions();
489
-
490
-
491
- // Extract only style properties for animation
492
- const targetStyles = this.extractStyleProperties(this.getVariant(this.animate));
493
- const startStyles = this.extractStyleProperties(this.getVariant(this.initial));
494
-
495
-
496
- // Add DOM style logging before applying start styles
497
- const beforeStartComputedStyles = window.getComputedStyle(this.el.nativeElement);
498
-
499
- // Only apply start state immediately if not part of stagger coordination
500
- // For stagger children, the parent coordination handles initial state setup
501
- if (!this.isStaggeredChild) {
502
- Object.assign(this.el.nativeElement.style, startStyles);
503
- } else {
504
- }
505
-
506
- // Add logging after applying start styles
507
- const afterStartComputedStyles = window.getComputedStyle(this.el.nativeElement);
508
-
509
- // Create animation
510
- this.controls = this.motionAnimation.animate(
511
- this.el.nativeElement as Target,
512
- targetStyles,
513
- options
514
- );
515
-
516
- this.initialAnimationPlayed = true;
517
- }
518
-
519
- ngOnDestroy() {
520
-
521
-
522
- if (this.exit && Object.keys(this.exit).length > 0) {
523
- this.runExitAnimation();
524
- }
525
-
526
- if (this.inViewInstance) {
527
- this.inViewInstance.stop();
528
- }
529
-
530
- if (this.observer) {
531
- this.observer.disconnect();
532
- }
533
-
534
- // Clean up any ongoing animations
535
- if (this.controls) {
536
- this.controls.stop();
537
- }
538
-
539
- // Clean up any children animations
540
- this.childrenControls.forEach(control => {
541
- if (control) control.stop();
542
- });
543
-
544
-
545
- // this.motionService.unregisterMotionElement(this);
546
- //console.log(`[${this.elementId}] Unregistered motionone directive`);
547
- }
548
-
549
- ngOnChanges(changes: SimpleChanges) {
550
- if (changes['animate'] && changes['animate'].previousValue !== undefined) {
551
- const oldState = changes['animate'].previousValue;
552
- let newState = changes['animate'].currentValue;
553
-
554
- if (typeof newState === 'object') {
555
- this.playAnimation(oldState, newState);
556
- } else if (typeof newState === 'string' && this.variants?.[newState]) {
557
- newState = this.variants[newState];
558
- this.playAnimation(oldState, newState);
559
- }
560
- }
561
-
562
- // Handle transition changes
563
- if (changes['transition'] && !changes['transition'].firstChange) {
564
- // Re-apply animation with new transition settings
565
- this.playAnimation(this.initial, this.animate);
566
- }
567
- }
568
-
569
- @HostListener('mouseenter')
570
- onMouseEnter() {
571
- if (Object.keys(this.whileHover).length > 0) {
572
- clearTimeout(this.hoverTimeout);
573
- if (Object.keys(this.animate).length > 0) {
574
- this.playAnimation(this.animate, this.whileHover);
575
- } else {
576
- this.playAnimation(this.initial, this.whileHover);
577
- }
578
- }
579
- }
580
-
581
- @HostListener('mouseleave')
582
- onMouseLeave() {
583
- if (Object.keys(this.whileHover).length > 0) {
584
- this.hoverTimeout = setTimeout(() => {
585
- if (Object.keys(this.animate).length > 0) {
586
- this.playAnimation(this.whileHover, this.animate);
587
- } else {
588
- this.playAnimation(this.whileHover, this.initial);
589
- }
590
- }, 100);
591
- }
592
- }
593
-
594
- @HostListener('mousedown', ['$event'])
595
- @HostListener('touchstart', ['$event'])
596
- onPress(event: Event) {
597
- if (Object.keys(this.whileTap).length > 0) {
598
- if (Object.keys(this.animate).length > 0) {
599
- this.playAnimation(this.animate, this.whileTap);
600
- } else {
601
- this.playAnimation(this.initial, this.whileTap);
602
- }
603
-
604
- // Only add event listeners in browser environment
605
- if (isPlatformBrowser(this.platformId)) {
606
- const endEvent = event.type === 'mousedown' ? 'mouseup' : 'touchend';
607
- const endListener = () => {
608
- if (Object.keys(this.animate).length > 0) {
609
- this.playAnimation(this.whileTap, this.animate);
610
- } else {
611
- this.playAnimation(this.whileTap, this.initial);
612
- }
613
-
614
- window.removeEventListener(endEvent, endListener);
615
- };
616
-
617
- window.addEventListener(endEvent, endListener);
618
- }
619
- }
620
- }
621
-
622
- @HostListener('focus')
623
- onFocus() {
624
- if (Object.keys(this.whileFocus).length > 0) {
625
- if (Object.keys(this.animate).length > 0) {
626
- this.playAnimation(this.animate, this.whileFocus);
627
- } else {
628
- this.playAnimation(this.initial, this.whileFocus);
629
- }
630
- }
631
- }
632
-
633
- @HostListener('blur')
634
- onBlur() {
635
- if (Object.keys(this.whileFocus).length > 0) {
636
- if (Object.keys(this.animate).length > 0) {
637
- this.playAnimation(this.whileFocus, this.animate);
638
- } else {
639
- this.playAnimation(this.whileFocus, this.initial);
640
- }
641
- }
642
- }
643
-
644
- applyInitialValues() {
645
- // Extract only style properties (exclude transition)
646
- const styles = this.extractStyleProperties(this.getVariant(this.initial));
647
- Object.assign(this.el.nativeElement.style, styles);
648
- }
649
-
650
- private applyInitialStyles() {
651
- // Extract only style properties (exclude transition)
652
- const styles = this.extractStyleProperties(this.getVariant(this.initial));
653
-
654
- // Apply initial styles immediately to prevent flash
655
- if (styles && Object.keys(styles).length > 0) {
656
- // For runInView elements, ensure initial styles are applied without any transition
657
- if (this.isRunInViewEnabled) {
658
- this.el.nativeElement.style.transition = 'none';
659
- Object.assign(this.el.nativeElement.style, styles);
660
- this.el.nativeElement.offsetHeight; // Force reflow
661
- this.el.nativeElement.style.transition = '';
662
- } else {
663
- Object.assign(this.el.nativeElement.style, styles);
664
- }
665
- }
666
- }
667
-
668
- private applyAnimateStyles() {
669
- // Extract only style properties (exclude transition)
670
- const styles = this.extractStyleProperties(this.getVariant(this.animate));
671
- Object.assign(this.el.nativeElement.style, styles);
672
- }
673
-
674
- // Helper to extract only style properties from a variant (excluding transition)
675
- public extractStyleProperties(variant: VariantWithTransition): Record<string, any> {
676
- if (!variant) return {};
677
-
678
- const result: Record<string, any> = {};
679
-
680
- for (const key in variant) {
681
- // skip meta keys
682
- if (key === 'transition' || key === 'at') continue;
683
- // Allow raw transform strings or keyframe arrays to pass through untouched
684
- if (key === 'transform') {
685
- (result as any)['transform'] = (variant as any)[key];
686
- continue;
687
- }
688
- if (this.isTransformProperty(key)) {
689
- this.applyTransformProperty(result, key, variant[key]);
690
- } else {
691
- this.applyStyleProperty(result, key, variant[key]);
692
- }
693
- }
694
-
695
- this.normalizeTransformProperty(result);
696
-
697
- return result;
698
- }
699
-
700
- // Check if a property should be handled as a transform
701
- private isTransformProperty(key: string): boolean {
702
- return ['x', 'y', 'rotate', 'scale', 'scaleX', 'scaleY'].includes(key);
703
- }
704
-
705
- // Apply transform properties to the result object
706
- private applyTransformProperty(result: Record<string, any>, key: string, value: any): void {
707
- // If keyframe array is provided, let Motion One handle it directly
708
- if (Array.isArray(value)) {
709
- (result as any)[key] = value;
710
- return;
711
- }
712
- // Initialize transform matrix if it doesn't exist
713
- if (!result['transform']) {
714
- result['transform'] = 'matrix(1, 0, 0, 1, 0, 0)';
715
- }
716
-
717
- // Parse current matrix
718
- const currentMatrix = result['transform'].match(/matrix\((.*)\)/)[1].split(',').map(Number);
719
-
720
- // Create new matrix based on the transform type
721
- let newMatrix: number[];
722
-
723
- switch (key) {
724
- case 'x':
725
- newMatrix = [1, 0, 0, 1, value, 0];
726
- break;
727
- case 'y':
728
- newMatrix = [1, 0, 0, 1, 0, value];
729
- break;
730
- case 'rotate':
731
- const rad = (value * Math.PI) / 180;
732
- const cos = Math.cos(rad);
733
- const sin = Math.sin(rad);
734
- newMatrix = [cos, -sin, sin, cos, 0, 0];
735
- break;
736
- case 'scale':
737
- newMatrix = [value, 0, 0, value, 0, 0];
738
- break;
739
- case 'scaleX':
740
- newMatrix = [value, 0, 0, 1, 0, 0];
741
- break;
742
- case 'scaleY':
743
- newMatrix = [1, 0, 0, value, 0, 0];
744
- break;
745
- default:
746
- return;
747
- }
748
-
749
- // Multiply matrices
750
- const finalMatrix = this.multiplyMatrices(currentMatrix, newMatrix);
751
-
752
- // Apply the new matrix
753
- result['transform'] = `matrix(${finalMatrix.join(',')})`;
754
- }
755
-
756
- // Helper function to multiply two 2D matrices
757
- private multiplyMatrices(a: number[], b: number[]): number[] {
758
- return [
759
- a[0] * b[0] + a[2] * b[1], // a
760
- a[1] * b[0] + a[3] * b[1], // b
761
- a[0] * b[2] + a[2] * b[3], // c
762
- a[1] * b[2] + a[3] * b[3], // d
763
- a[0] * b[4] + a[2] * b[5] + a[4], // e
764
- a[1] * b[4] + a[3] * b[5] + a[5] // f
765
- ];
766
- }
767
-
768
- // Apply regular style properties to the result object
769
- private applyStyleProperty(result: Record<string, any>, key: string, value: any): void {
770
- if (this.isColorProperty(key)) {
771
- if (Array.isArray(value)) {
772
- result[key] = value.map(v => this.normalizeColor(v));
773
- } else {
774
- result[key] = this.normalizeColor(value);
775
- }
776
- } else {
777
- result[key] = value;
778
- }
779
- }
780
-
781
- // Check if a property is a color property
782
- private isColorProperty(key: string): boolean {
783
- return ['backgroundColor', 'color', 'borderColor'].includes(key);
784
- }
785
-
786
- // Normalize the transform property by trimming extra spaces
787
- private normalizeTransformProperty(result: Record<string, any>): void {
788
- if (result['transform']) {
789
- result['transform'] = result['transform'].trim();
790
- }
791
- }
792
-
793
- private getEasing(easingString: string | number[] | { type: 'spring'; stiffness?: number; damping?: number } | undefined) {
794
- if (!easingString) return this.motionAnimation.easeInOut;
795
- if (Array.isArray(easingString)) return easingString;
796
- if (typeof easingString === 'object' && 'type' in easingString && easingString.type === 'spring') {
797
- return this.motionAnimation.spring({
798
- stiffness: easingString.stiffness || 100,
799
- damping: easingString.damping || 10
800
- });
801
- }
802
- if (typeof easingString === 'string') {
803
- if (easingString === 'ease-in') return this.motionAnimation.easeIn;
804
- if (easingString === 'ease-out') return this.motionAnimation.easeOut;
805
- if (easingString === 'ease-in-out' || easingString === 'ease') return this.motionAnimation.easeInOut;
806
- if (easingString === 'spring') return this.motionAnimation.spring();
807
- }
808
- return this.motionAnimation.easeInOut;
809
- }
810
-
811
- private getAnimationOptions(targetState?: VariantWithTransition): AnimationOptions {
812
- // Priority: 1. Stagger delay, 2. State-specific transition, 3. Global transition, 4. Individual properties
813
- const stateTransition = (targetState?.transition as TransitionOptions) ?? (this.getVariant(this.animate)?.transition as TransitionOptions);
814
- const globalTransition = (this.transition as TransitionOptions);
815
-
816
- const transitionObj: TransitionOptions = stateTransition || globalTransition || {};
817
-
818
- // Always prioritize stagger delay over any other delay settings (including 0)
819
- const delay = this.staggerDelay !== undefined && this.staggerDelay >= 0 ? this.staggerDelay : (transitionObj.delay ?? this.delay);
820
-
821
-
822
- const easeInput = transitionObj.ease ?? this.easing;
823
- // Detect if target contains keyframe arrays (avoid native spring in that case)
824
- let targetHasKeyframeArrays = false;
825
- if (targetState) {
826
- for (const k of Object.keys(targetState)) {
827
- if (k === 'transition' || k === 'at') continue;
828
- const v: any = (targetState as any)[k];
829
- if (Array.isArray(v)) { targetHasKeyframeArrays = true; break; }
830
- }
831
- }
832
- // If spring config and no keyframe arrays, prefer native spring options (no fixed duration)
833
- if (easeInput && typeof easeInput === 'object' && 'type' in (easeInput as any) && (easeInput as any).type === 'spring' && !targetHasKeyframeArrays) {
834
- const springOptions: any = {
835
- type: 'spring',
836
- stiffness: (easeInput as any).stiffness ?? 100,
837
- damping: (easeInput as any).damping ?? 10,
838
- delay,
839
- repeat: this.getRepeatValue(transitionObj),
840
- repeatDelay: transitionObj.repeatDelay,
841
- onComplete: () => this.animationComplete.emit()
842
- };
843
- const direction = this.mapRepeatTypeToDirection(transitionObj.repeatType);
844
- if (direction) springOptions.direction = direction;
845
- if (transitionObj.repeatType) springOptions.repeatType = transitionObj.repeatType;
846
- return springOptions as AnimationOptions;
847
- }
848
- const ease = this.getEasing(easeInput as any);
849
-
850
- const options: any = {
851
- duration: transitionObj.duration ?? this.duration,
852
- delay,
853
- repeat: this.getRepeatValue(transitionObj),
854
- repeatDelay: transitionObj.repeatDelay,
855
- onComplete: () => this.animationComplete.emit()
856
- };
857
- const direction = this.mapRepeatTypeToDirection(transitionObj.repeatType);
858
- if (direction) options.direction = direction;
859
- if (transitionObj.repeatType) options.repeatType = transitionObj.repeatType;
860
- options.easing = ease; // Motion 11+
861
- (options as any).ease = ease; // Back-compat
862
- return options as AnimationOptions;
863
- }
864
-
865
- private getRepeatValue(transitionObj: TransitionOptions): number {
866
- // Handle repeat value from transition object or fallback to directive input
867
- if (transitionObj.repeat !== undefined) {
868
- if (transitionObj.repeat === true) {
869
- return Infinity;
870
- } else if (typeof transitionObj.repeat === 'number') {
871
- return transitionObj.repeat;
872
- }
873
- }
874
-
875
- return this.repeat ? Infinity : 0;
876
- }
877
-
878
- private mapRepeatTypeToDirection(
879
- repeatType: TransitionOptions['repeatType'] | undefined
880
- ): 'normal' | 'reverse' | 'alternate' | undefined {
881
- if (!repeatType) return undefined;
882
- // Aliases
883
- if (repeatType === 'forwards' || repeatType === 'loop') return 'normal';
884
- if (repeatType === 'reverse') return 'reverse';
885
- if (repeatType === 'pingPong' || repeatType === 'mirror') return 'alternate';
886
- // Default
887
- return 'normal';
888
- }
889
-
890
- private getStaggerValue(): number {
891
- // Priority: 1. State-specific transition, 2. Global transition, 3. Individual properties
892
- const stateTransition = this.getVariant(this.animate)?.transition as TransitionOptions;
893
- const globalTransition = this.transition as TransitionOptions;
894
-
895
- const transitionObj: TransitionOptions = stateTransition || globalTransition || {};
896
-
897
- // Get stagger value from transition object or fallback to directive input
898
- return transitionObj.staggerChildren ?? this.staggerChildren;
899
- }
900
-
901
- private getStaggerDirection(): number {
902
- // Priority: 1. State-specific transition, 2. Global transition, 3. Input property
903
- const stateTransition = this.getVariant(this.animate)?.transition as TransitionOptions;
904
- const globalTransition = this.transition as TransitionOptions;
905
-
906
- const transitionObj: TransitionOptions = stateTransition || globalTransition || {};
907
-
908
- return transitionObj.staggerDirection ?? this.staggerDirection;
909
- }
910
-
911
- private getWhen(): 'beforeChildren' | 'afterChildren' | 'together' {
912
- // Priority: 1. State-specific transition, 2. Global transition, 3. Default ('together')
913
- const stateTransition = this.getVariant(this.animate)?.transition as TransitionOptions;
914
- const globalTransition = this.transition as TransitionOptions;
915
-
916
- const transitionObj: TransitionOptions = stateTransition || globalTransition || {};
917
-
918
- return (transitionObj.when ?? 'together') as 'beforeChildren' | 'afterChildren' | 'together';
919
- }
920
-
921
- private playAnimation(startState: VariantWithTransition | string, targetState: VariantWithTransition | string) {
922
- if (!targetState || !isPlatformBrowser(this.platformId)) return;
923
-
924
- // Resolve variant strings to objects
925
- let resolvedStartState: VariantWithTransition = {};
926
- let resolvedTargetState: VariantWithTransition = {};
927
-
928
- if (startState === undefined) {
929
- resolvedStartState = this.getVariant(this.initial);
930
- } else if (typeof startState === 'string' && this.variants?.[startState]) {
931
- resolvedStartState = this.variants[startState];
932
- } else if (typeof startState === 'object') {
933
- resolvedStartState = startState;
934
- }
935
-
936
- if (targetState === undefined) {
937
- resolvedTargetState = this.getVariant(this.animate);
938
- } else if (typeof targetState === 'string' && this.variants?.[targetState]) {
939
- resolvedTargetState = this.variants[targetState];
940
- } else if (typeof targetState === 'object') {
941
- resolvedTargetState = targetState;
942
- }
943
-
944
-
945
- // Check if target state has an 'at' property
946
- if (resolvedTargetState.at !== undefined) {
947
- // Schedule the animation to start at the specified time
948
- setTimeout(() => {
949
- this.continueAnimation(resolvedTargetState, false);
950
- }, resolvedTargetState.at * 1000); // Convert seconds to milliseconds
951
- return;
952
- }
953
-
954
- // Continue with normal animation if no 'at' property
955
- this.continueAnimation(resolvedTargetState, false);
956
- }
957
-
958
- private continueAnimation(resolvedTargetState: VariantWithTransition, isInitialAnimation: boolean) {
959
-
960
- // Timeline takes precedence
961
- if (this.timeline && this.timeline.length > 0) {
962
- this.runTimeline(resolvedTargetState);
963
- return;
964
- }
965
-
966
- // Detect per-property transition map on the state
967
- const t: any = resolvedTargetState.transition;
968
- const isPerPropMap = t && typeof t === 'object' && t.duration === undefined && t.delay === undefined && t.ease === undefined;
969
- if (isPerPropMap) {
970
- this.runPerPropertyAnimations(resolvedTargetState);
971
- return;
972
- }
973
-
974
- // Check if this is the initial animation to the animate state
975
- if (isInitialAnimation && !this.initialAnimationPlayed) {
976
- const staggerValue = this.getStaggerValue();
977
-
978
- if (staggerValue > 0 && this.childMotionDirectives && this.childMotionDirectives.length > 1) {
979
- // Stagger will be handled by ngAfterContentInit
980
- // Just animate self according to 'when' property
981
- const when = this.getWhen();
982
-
983
- if (when !== 'afterChildren') {
984
- this.runSelfAnimation();
985
- }
986
-
987
- return;
988
- }
989
- }
990
-
991
-
992
- // For non-staggered animations or non-initial animations
993
- // Get animation options with priority to target state's transition
994
- const options = this.getAnimationOptions(resolvedTargetState);
995
-
996
- // Extract only style properties for animation (excluding transition)
997
- const targetStyles = this.extractStyleProperties(resolvedTargetState);
998
-
999
- // Create animation with Motion One for the element itself
1000
- this.controls = this.motionAnimation.animate(
1001
- this.el.nativeElement as Target,
1002
- targetStyles,
1003
- options
1004
- );
1005
-
1006
- if (isInitialAnimation) {
1007
- this.initialAnimationPlayed = true;
1008
- }
1009
-
1010
- // Handle regular DOM children (without motionone directives) for non-initial animations
1011
- if (!isInitialAnimation && this.el.nativeElement.children.length > 0) {
1012
- // Get children elements
1013
- const children = Array.from(this.el.nativeElement.children) as HTMLElement[];
1014
-
1015
- // Animate each child with the same animation
1016
- children.forEach((child, index) => {
1017
- // Skip children that have their own motionone directive
1018
- if (child.hasAttribute('motionone')) {
1019
- return;
1020
- }
1021
-
1022
- // Create child animation
1023
- const childControl = this.motionAnimation.animate(
1024
- child,
1025
- targetStyles,
1026
- options
1027
- );
1028
-
1029
- // Store the control for cleanup
1030
- this.childrenControls.push(childControl);
1031
- });
1032
- } else if (!isInitialAnimation) {
1033
- }
1034
-
1035
- }
1036
-
1037
- private runPerPropertyAnimations(resolvedTargetState: VariantWithTransition) {
1038
- const baseDelay = this.staggerDelay !== undefined && this.staggerDelay >= 0 ? this.staggerDelay : (((resolvedTargetState.transition as TransitionOptions)?.delay) ?? this.delay);
1039
- const transitionMap = resolvedTargetState.transition as Record<string, TransitionOptions>;
1040
- const props = Object.keys(resolvedTargetState).filter(k => k !== 'transition' && k !== 'at');
1041
-
1042
- let maxEnd = 0;
1043
- props.forEach((prop) => {
1044
- const value = (resolvedTargetState as any)[prop];
1045
- const conf = (transitionMap?.[prop] || {}) as TransitionOptions;
1046
- const delay = baseDelay + (conf.delay ?? 0);
1047
- const ease = this.getEasing(conf.ease ?? this.easing);
1048
- const duration = conf.duration ?? this.duration;
1049
- const options: any = { duration, delay, easing: ease, repeat: this.getRepeatValue(conf), repeatDelay: conf.repeatDelay };
1050
- (options as any).ease = ease;
1051
- const dir = this.mapRepeatTypeToDirection(conf.repeatType);
1052
- if (dir) options.direction = dir;
1053
- if (conf.repeatType) options.repeatType = conf.repeatType;
1054
- const times = (conf as any).times as number[] | undefined;
1055
- if (times && Array.isArray(times)) options.offset = this.normalizeTimes(times, duration);
1056
-
1057
- const end = delay + duration;
1058
- if (end > maxEnd) maxEnd = end;
1059
-
1060
- let finalValue = value;
1061
- if (this.isColorProperty(prop)) {
1062
- if (Array.isArray(value)) finalValue = value.map(v => this.normalizeColor(v));
1063
- else finalValue = this.normalizeColor(value);
1064
- }
1065
- const target = { [prop]: finalValue } as any;
1066
- const control = this.motionAnimation.animate(this.el.nativeElement as Target, target, options);
1067
- this.childrenControls.push(control);
1068
- });
1069
-
1070
- setTimeout(() => this.animationComplete.emit(), maxEnd * 1000);
1071
- }
1072
-
1073
- private runTimeline(resolvedTargetState: VariantWithTransition) {
1074
- const baseDelay = this.staggerDelay !== undefined && this.staggerDelay >= 0 ? this.staggerDelay : (((resolvedTargetState.transition as TransitionOptions)?.delay) ?? this.delay);
1075
- let maxEnd = 0;
1076
- // Also animate any non-timeline props from the target state (e.g., opacity)
1077
- const timelinePropsSet = new Set((this.timeline || []).map(s => s.prop));
1078
- const nonTimelineTarget: any = {};
1079
- Object.keys(resolvedTargetState).forEach(k => {
1080
- if (k === 'transition' || k === 'at') return;
1081
- if (!timelinePropsSet.has(k)) nonTimelineTarget[k] = (resolvedTargetState as any)[k];
1082
- });
1083
- if (Object.keys(nonTimelineTarget).length > 0) {
1084
- const opt = this.getAnimationOptions(resolvedTargetState) as any;
1085
- const ctl = this.motionAnimation.animate(this.el.nativeElement as Target, nonTimelineTarget, opt);
1086
- this.childrenControls.push(ctl);
1087
- const nonEnd = (opt.delay ?? 0) + (opt.duration ?? this.duration);
1088
- if (nonEnd > maxEnd) maxEnd = nonEnd;
1089
- }
1090
- this.timeline!.forEach(step => {
1091
- const start = baseDelay + (step.atTime ?? 0) + (step.delay ?? 0);
1092
- const duration = step.duration;
1093
- const value = step.keyframes !== undefined ? step.keyframes : step.to;
1094
- const easeInput = step.ease ?? this.easing;
1095
-
1096
- // Build options with repeat and direction
1097
- // Prefer function easing always in timeline to preserve keyframe interpolation
1098
- const ease = this.getEasing(easeInput as any);
1099
- const options: any = { duration, delay: start, easing: ease } as any;
1100
- (options as any).ease = ease; // Back-compat
1101
-
1102
- // Apply repeat controls if provided
1103
- if (step.repeat !== undefined) {
1104
- options.repeat = step.repeat === true ? Infinity : step.repeat;
1105
- }
1106
- if (step.repeatDelay !== undefined) {
1107
- options.repeatDelay = step.repeatDelay;
1108
- }
1109
- const dir = this.mapRepeatTypeToDirection(step.repeatType);
1110
- if (dir) options.direction = dir;
1111
- if (step.repeatType) options.repeatType = step.repeatType;
1112
- if (step.times) options.offset = this.normalizeTimes(step.times, duration);
1113
-
1114
- const end = start + duration;
1115
- if (end > maxEnd) maxEnd = end;
1116
-
1117
- let v = value;
1118
- if (this.isColorProperty(step.prop)) {
1119
- if (Array.isArray(v)) v = v.map((c: any) => this.normalizeColor(c));
1120
- else v = this.normalizeColor(v);
1121
- }
1122
- const target = { [step.prop]: v } as any;
1123
- const control = this.motionAnimation.animate(this.el.nativeElement as Target, target, options);
1124
- this.childrenControls.push(control);
1125
- });
1126
-
1127
- setTimeout(() => this.animationComplete.emit(), maxEnd * 1000);
1128
- }
1129
-
1130
- private setupInViewAnimation() {
1131
- if (isPlatformBrowser(this.platformId)) {
1132
-
1133
- try {
1134
- // Use Motion One's inView API - it handles state management automatically
1135
- if (this.isRunInViewEnabled) {
1136
-
1137
- // Set up Motion One's inView with automatic state management
1138
- this.setupMotionOneInView();
1139
- } else {
1140
- // For inView and whileInView functionality
1141
- const hasWhileInView = this.whileInView && Object.keys(this.whileInView).length > 0;
1142
- const hasInView = this.inView && Object.keys(this.inView).length > 0;
1143
-
1144
- if (hasWhileInView) {
1145
- // whileInView needs enter/exit behavior
1146
- this.setupWhileInViewAnimation();
1147
- } else if (hasInView) {
1148
- // inView is a one-time trigger on enter
1149
- this.inViewInstance = inView(
1150
- this.el.nativeElement,
1151
- (info: any) => {
1152
- this.runInViewAnimation();
1153
- },
1154
- {
1155
- margin: this.offset,
1156
- amount: 'some'
1157
- }
1158
- );
1159
- }
1160
- }
1161
- } catch (error) {
1162
- console.error('[MotionOne] ❌ Error setting up inView observer:', error);
1163
- }
1164
- }
1165
- }
1166
-
1167
- runInViewAnimation() {
1168
- // Handle both inView and whileInView properties
1169
- if (this.inView && Object.keys(this.inView).length > 0) {
1170
- this.playAnimation(this.initial, this.inView);
1171
- } else if (this.whileInView && Object.keys(this.whileInView).length > 0) {
1172
- this.playAnimation(this.initial, this.whileInView);
1173
- }
1174
- }
1175
-
1176
- // New method to handle whileInView enter behavior (no exit reset)
1177
- private setupWhileInViewAnimation() {
1178
- // whileInView should only animate once when entering viewport
1179
- // It should NOT reset when exiting (that's only for runInView="always")
1180
- this.inViewInstance = inView(
1181
- this.el.nativeElement,
1182
- // Enter callback - when element comes into view
1183
- (info: any) => {
1184
- // Element entered viewport - animate to whileInView state
1185
- // This will only trigger once, and element stays in whileInView state
1186
- this.playAnimation(this.initial, this.whileInView);
1187
- },
1188
- {
1189
- margin: this.offset,
1190
- amount: 'some'
1191
- }
1192
- );
1193
-
1194
- // No exit behavior for whileInView - elements should stay in their animated state
1195
- // Only runInView="always" should reset on exit
1196
- }
1197
-
1198
- // New method using Motion One's inView API following Framer Motion pattern
1199
- private setupMotionOneInView() {
1200
-
1201
- // Get margin from offset
1202
- const margin = this.offset || '0px';
1203
-
1204
- // Determine if this is a parent with stagger children
1205
- const hasStaggerChildren = this.getStaggerValue() > 0 && this.childMotionDirectives?.length > 1;
1206
-
1207
- if (hasStaggerChildren && !this.isChild) {
1208
- // Parent with stagger children - handle stagger animation
1209
- this.setupStaggerParentInView(margin);
1210
- } else if (!this.isStaggeredChild) {
1211
- // Individual element or non-staggered child
1212
- this.setupIndividualElementInView(margin);
1213
- } else {
1214
- }
1215
- }
1216
-
1217
- private setupStaggerParentInView(margin: string) {
1218
- // For parent elements with stagger, use inView with enter/exit callbacks
1219
- this.inViewInstance = inView(
1220
- this.el.nativeElement,
1221
- (info: { isIntersecting: boolean }) => {
1222
- if (info.isIntersecting) {
1223
-
1224
- // Stop any existing animations
1225
- if (this.controls) this.controls.stop();
1226
-
1227
- // Reset parent to initial
1228
- const parentInitialStyles = this.extractStyleProperties(this.getVariant(this.initial));
1229
- if (Object.keys(parentInitialStyles).length > 0) {
1230
- this.el.nativeElement.style.transition = 'none';
1231
- Object.assign(this.el.nativeElement.style, parentInitialStyles);
1232
- this.el.nativeElement.offsetHeight;
1233
- this.el.nativeElement.style.transition = '';
1234
- }
1235
-
1236
- // Get all child elements
1237
- const childDirectives = this.childMotionDirectives?.filter(child => child !== this) || [];
1238
-
1239
- if (childDirectives.length > 0) {
1240
-
1241
- // Stop and reset all children to initial state first
1242
- childDirectives.forEach(child => {
1243
- if (child.controls) child.controls.stop();
1244
-
1245
- const childInitialStyles = child.extractStyleProperties(child.getVariant(child.initial));
1246
-
1247
- child.el.nativeElement.style.transition = 'none';
1248
- Object.assign(child.el.nativeElement.style, childInitialStyles);
1249
- child.el.nativeElement.offsetHeight;
1250
- child.el.nativeElement.style.transition = '';
1251
- });
1252
-
1253
- // Small delay to ensure resets are applied
1254
- setTimeout(() => {
1255
- const staggerValue = this.getStaggerValue();
1256
-
1257
- // Animate children with stagger
1258
- childDirectives.forEach((child, index) => {
1259
- const childAnimateStyles = child.extractStyleProperties(child.getVariant(child.animate));
1260
- const options = child.getAnimationOptions();
1261
-
1262
- // Override delay with stagger delay
1263
- const staggerDelay = index * staggerValue;
1264
- options.delay = staggerDelay;
1265
-
1266
-
1267
- // Create animation for this child
1268
- child.controls = animate(child.el.nativeElement, childAnimateStyles, options);
1269
- });
1270
-
1271
- // Animate parent if it has its own animation
1272
- const parentAnimateStyles = this.extractStyleProperties(this.getVariant(this.animate));
1273
- if (Object.keys(parentAnimateStyles).length > 0) {
1274
- const parentOptions = this.getAnimationOptions();
1275
- this.controls = animate(this.el.nativeElement, parentAnimateStyles, parentOptions);
1276
- }
1277
- }, 50);
1278
- }
1279
- } else if (this.runInViewRepeat === 'always') {
1280
- // Exit viewport - reset to initial for "always" behavior
1281
-
1282
- // Stop all animations
1283
- if (this.controls) this.controls.stop();
1284
-
1285
- // Reset parent to initial
1286
- const parentInitialStyles = this.extractStyleProperties(this.getVariant(this.initial));
1287
- if (Object.keys(parentInitialStyles).length > 0) {
1288
- this.el.nativeElement.style.transition = 'none';
1289
- Object.assign(this.el.nativeElement.style, parentInitialStyles);
1290
- this.el.nativeElement.offsetHeight;
1291
- this.el.nativeElement.style.transition = '';
1292
- }
1293
-
1294
- // Reset all children to initial
1295
- const childDirectives = this.childMotionDirectives?.filter(child => child !== this) || [];
1296
- childDirectives.forEach(child => {
1297
- if (child.controls) child.controls.stop();
1298
-
1299
- const childInitialStyles = child.extractStyleProperties(child.getVariant(child.initial));
1300
- child.el.nativeElement.style.transition = 'none';
1301
- Object.assign(child.el.nativeElement.style, childInitialStyles);
1302
- child.el.nativeElement.offsetHeight;
1303
- child.el.nativeElement.style.transition = '';
1304
- });
1305
-
1306
- }
1307
- },
1308
- {
1309
- margin,
1310
- amount: 0.1
1311
- }
1312
- );
1313
- }
1314
-
1315
- private setupIndividualElementInView(margin: string) {
1316
- // For individual elements, simple initial -> animate transition
1317
- this.inViewInstance = inView(
1318
- this.el.nativeElement,
1319
- (info: { isIntersecting: boolean }) => {
1320
- if (info.isIntersecting) {
1321
-
1322
- // Stop any existing animation
1323
- if (this.controls) this.controls.stop();
1324
-
1325
- // Reset to initial state first with a small delay to ensure proper reset
1326
- const initialStyles = this.extractStyleProperties(this.getVariant(this.initial));
1327
- this.el.nativeElement.style.transition = 'none';
1328
- Object.assign(this.el.nativeElement.style, initialStyles);
1329
- this.el.nativeElement.offsetHeight; // Force reflow
1330
- this.el.nativeElement.style.transition = '';
1331
-
1332
- // Use a small timeout to ensure the reset is applied before starting animation
1333
- setTimeout(() => {
1334
- // Animate from initial to animate state using the directive's playAnimation method
1335
- this.playAnimation(this.initial, this.animate);
1336
- }, 50);
1337
- } else if (this.runInViewRepeat === 'always') {
1338
- // Exit viewport - reset to initial for "always" behavior
1339
-
1340
- // Stop animation and reset to initial
1341
- if (this.controls) this.controls.stop();
1342
-
1343
- const initialStyles = this.extractStyleProperties(this.getVariant(this.initial));
1344
- this.el.nativeElement.style.transition = 'none';
1345
- Object.assign(this.el.nativeElement.style, initialStyles);
1346
- this.el.nativeElement.offsetHeight;
1347
- this.el.nativeElement.style.transition = '';
1348
-
1349
- }
1350
- },
1351
- {
1352
- margin,
1353
- amount: 0.1
1354
- }
1355
- );
1356
- }
1357
-
1358
- runInitAnimation() {
1359
- if (!isPlatformBrowser(this.platformId) || !this.initial || !this.animate) return;
1360
-
1361
-
1362
- // For child elements with stagger, make sure we use the stagger delay
1363
- if (this.isChild && this.staggerDelay !== undefined && this.staggerDelay >= 0) {
1364
-
1365
- // Apply start state immediately (unless we're in a reset stagger flow)
1366
- if (!this._skipStartStylesApplication) {
1367
- const startStyles = this.extractStyleProperties(this.getVariant(this.initial));
1368
-
1369
- // Force reset without transition
1370
- const element = this.el.nativeElement;
1371
- element.style.transition = 'none';
1372
- Object.assign(element.style, startStyles);
1373
- } else {
1374
- // Clear the flag after use
1375
- this._skipStartStylesApplication = false;
1376
- }
1377
- this.el.nativeElement.offsetHeight; // Force reflow
1378
-
1379
- // Get animation options with stagger delay
1380
- const options = this.getAnimationOptions();
1381
-
1382
- // VARIANT CONTROL: Use variants to ensure correct animation direction
1383
-
1384
- // Force use the child's specific animate variant (not parent's)
1385
- const childAnimateVariant = this.getVariant(this.animate || {});
1386
-
1387
- // Ensure we're animating from initial → animate (not the reverse)
1388
- const targetStyles = this.extractStyleProperties(childAnimateVariant);
1389
-
1390
- // Double-check: log what the current element state is
1391
- const currentStyles = window.getComputedStyle(this.el.nativeElement);
1392
-
1393
- // Use playAnimation to ensure proper initial→animate direction
1394
- setTimeout(() => {
1395
- this.el.nativeElement.style.transition = '';
1396
-
1397
- // CRITICAL: Use playAnimation with variants to force correct direction
1398
- this.playAnimation(this.initial, this.animate);
1399
- }, 5);
1400
-
1401
- this.initialAnimationPlayed = true;
1402
- } else {
1403
- // Normal animation without stagger
1404
- this.playAnimation(this.initial, this.animate);
1405
- }
1406
- }
1407
-
1408
-
1409
- runExitAnimation(): Promise<void> {
1410
-
1411
- if (!isPlatformBrowser(this.platformId)) {
1412
- return Promise.resolve();
1413
- }
1414
-
1415
- // If no exit animation defined, resolve immediately
1416
- if (!this.exit || Object.keys(this.exit).length === 0) {
1417
- // console.log(`[${this.elementId}] No exit animation defined, resolving immediately`);
1418
- return Promise.resolve();
1419
- }
1420
-
1421
-
1422
- // Use exit-specific transition if available, otherwise use global transition
1423
- const exitTransition = (this.getVariant(this.exit).transition as TransitionOptions) || (this.transition as TransitionOptions) || {} as TransitionOptions;
1424
-
1425
- // Create a promise that resolves when the exit animation completes
1426
- return new Promise<void>((resolve) => {
1427
- const exitOptions: any = {
1428
- duration: (exitTransition.duration ?? this.duration) as number,
1429
- delay: (exitTransition.delay ?? this.exitDelay) as number,
1430
- onComplete: () => {
1431
- // console.log(`[${this.elementId}] Exit animation completed`);
1432
- this.animationComplete.emit();
1433
- resolve();
1434
- }
1435
- };
1436
- const ease = this.getEasing(exitTransition.ease ?? this.easing);
1437
- exitOptions.easing = ease;
1438
- (exitOptions as any).ease = ease;
1439
-
1440
- // Stop any existing animation
1441
- if (this.controls) {
1442
- this.controls.stop();
1443
- }
1444
-
1445
- // Stop any existing children animations
1446
- this.childrenControls.forEach(control => {
1447
- if (control) control.stop();
1448
- });
1449
-
1450
- // Extract only style properties for animation (excluding transition)
1451
- const exitStyles = this.extractStyleProperties(this.getVariant(this.exit));
1452
-
1453
- // console.log(`[${this.elementId}] Starting exit animation with styles:`, exitStyles);
1454
-
1455
- // Create exit animation
1456
- // console.log('animatiing exit')
1457
-
1458
- this.controls = this.motionAnimation.animate(
1459
- this.el.nativeElement as Target,
1460
- exitStyles,
1461
- exitOptions
1462
- );
1463
-
1464
- // If no duration is set, resolve immediately
1465
- if (!exitOptions.duration) {
1466
- // console.log(`[${this.elementId}] No duration set, resolving immediately`);
1467
- resolve();
1468
- }
1469
- });
1470
- }
1471
-
1472
- cancel() {
1473
- if (this.controls) {
1474
- this.controls.stop();
1475
- }
1476
-
1477
- // Cancel any children animations
1478
- this.childrenControls.forEach(control => {
1479
- if (control) control.stop();
1480
- });
1481
-
1482
- this.applyAnimateStyles();
1483
- }
1484
-
1485
- getDuration(): number {
1486
- if (!isPlatformBrowser(this.platformId)) return 0;
1487
-
1488
- try {
1489
- // Consider state-specific transition if available
1490
- // Check transitions in order of priority: exit, animate, then default transition
1491
- const animateTransition = (this.getVariant(this.exit)?.transition as TransitionOptions) || (this.transition as TransitionOptions) || {} as TransitionOptions;
1492
- const duration = (animateTransition.duration ?? this.duration) as number;
1493
- const delay = (animateTransition.delay ?? this.delay) as number;
1494
- return (Number(duration) + Number(delay)) * 1000;
1495
- } catch (error) {
1496
- console.error('Error calculating duration:', error);
1497
- return 0;
1498
- }
1499
- }
1500
-
1501
- getKeyByValue(object: any, key: any) {
1502
- return Object.keys(object).find((k) => object[k] === key);
1503
- }
1504
-
1505
- // Helper method for consistent logging
1506
- private logDebug(message: string) {
1507
- // Log to console
1508
- //console.log(`[${this.elementId}] ${message}`);
1509
-
1510
- // Only add DOM elements in browser environment
1511
- if (isPlatformBrowser(this.platformId)) {
1512
- // Add a visible element to the DOM for debugging (if needed)
1513
- // Uncomment this section if you need visual debugging
1514
- /*
1515
- const debugEl = document.createElement('div');
1516
- debugEl.style.position = 'fixed';
1517
- debugEl.style.top = '10px';
1518
- debugEl.style.right = '10px';
1519
- debugEl.style.backgroundColor = 'rgba(0,0,0,0.8)';
1520
- debugEl.style.color = 'white';
1521
- debugEl.style.padding = '5px';
1522
- debugEl.style.zIndex = '9999';
1523
- debugEl.style.maxWidth = '80%';
1524
- debugEl.style.maxHeight = '80%';
1525
- debugEl.style.overflow = 'auto';
1526
- debugEl.textContent = `[${this.elementId}] ${message}`;
1527
- document.body.appendChild(debugEl);
1528
-
1529
- // Remove after 5 seconds
1530
- setTimeout(() => {
1531
- document.body.removeChild(debugEl);
1532
- }, 5000);
1533
- */
1534
- }
1535
- }
1536
-
1537
- // Helper to normalize color values to a consistent format
1538
- private normalizeColor(color: any): string {
1539
- if (color == null) return '';
1540
- if (typeof color !== 'string') {
1541
- try { return String(color); } catch { return ''; }
1542
- }
1543
- if (color.startsWith('rgb') || color.startsWith('#')) return color;
1544
- if (color === 'aqua') return '#00ffff';
1545
- if (color === 'red') return '#ff0000';
1546
- if (color === 'blue') return '#0000ff';
1547
- if (color === 'green') return '#008000';
1548
- if (color === 'yellow') return '#ffff00';
1549
- if (color === 'purple') return '#800080';
1550
- if (color === 'orange') return '#ffa500';
1551
- if (color === 'black') return '#000000';
1552
- if (color === 'white') return '#ffffff';
1553
- return color;
1554
- }
1555
-
1556
- private normalizeTimes(times: number[] | undefined, duration: number): number[] | undefined {
1557
- if (!times || times.length === 0) return undefined;
1558
- const hasValuesAboveOne = times.some(t => t > 1);
1559
- if (!hasValuesAboveOne) return times;
1560
- const maxT = Math.max(...times);
1561
- const safeDuration = Math.max(duration, 0.000001);
1562
- const divisor = maxT > safeDuration * 1.001 ? maxT : safeDuration;
1563
- return times.map(t => {
1564
- const v = t / divisor;
1565
- return v < 0 ? 0 : v > 1 ? 1 : v;
1566
- });
1567
- }
1568
-
1569
- // Add a method to manually trigger exit animation from outside
1570
- public triggerExitAnimation(): Promise<void> {
1571
- // console.log(`[${this.elementId}] Manually triggering exit animation`);
1572
- return this.runExitAnimation();
1573
- }
1574
-
1575
- // Add a listener for the custom exit event
1576
- @HostListener('motionExit')
1577
- onMotionExit() {
1578
- // console.log(`[${this.elementId}] Received motionExit event`);
1579
- this.runExitAnimation();
1580
- }
1581
-
1582
- public getVariant(variant: VariantWithTransition | string): VariantWithTransition {
1583
- if (typeof variant === 'string') {
1584
- return this.variants[variant] || {};
1585
- } else if (typeof variant === 'object') {
1586
- return variant;
1587
- } else {
1588
- throw new Error('Invalid variant format');
1589
- }
1590
- }
1591
- }