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