@hilux/ngx-motion 1.0.6 → 1.0.8

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # NgxMotion
2
2
 
3
- This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 15.1.0.
3
+ This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 19.1.0.
4
4
 
5
5
  ## Code scaffolding
6
6
 
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@hilux/ngx-motion",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "A library for Angular motion directives",
5
5
  "main": "bundles/ngx-motion.umd.js",
6
6
  "module": "fesm5/ngx-motion.js",
7
7
  "types": "ngx-motion.d.ts",
8
8
  "peerDependencies": {
9
9
  "@angular/core":"19.1.5",
10
- "@angular/common":"19.1.5"
10
+ "@angular/common":"19.1.5",
11
+ "@angular/animations":"19.1.5"
11
12
  },
12
13
  "scripts": {
13
14
  "build": "ng build ngx-motion"
@@ -0,0 +1,3 @@
1
+ <div [@routeTransition]="{ value:route.snapshot.data, params: { maxDelay: maxDelay + 'ms' }}" style="display: contents">
2
+ <ng-content></ng-content>
3
+ </div>
File without changes
@@ -0,0 +1,23 @@
1
+ import { ComponentFixture, TestBed } from '@angular/core/testing';
2
+
3
+ import { MotionHostComponent } from './motion-host.component';
4
+
5
+ describe('MotionHostComponent', () => {
6
+ let component: MotionHostComponent;
7
+ let fixture: ComponentFixture<MotionHostComponent>;
8
+
9
+ beforeEach(async () => {
10
+ await TestBed.configureTestingModule({
11
+ imports: [MotionHostComponent]
12
+ })
13
+ .compileComponents();
14
+
15
+ fixture = TestBed.createComponent(MotionHostComponent);
16
+ component = fixture.componentInstance;
17
+ fixture.detectChanges();
18
+ });
19
+
20
+ it('should create', () => {
21
+ expect(component).toBeTruthy();
22
+ });
23
+ });
@@ -0,0 +1,50 @@
1
+ import { Component, OnInit } from '@angular/core';
2
+ import { Router,ActivatedRoute,NavigationStart, NavigationEnd } from '@angular/router';
3
+ import { MotionService } from '../services/ngx-motion.service';
4
+ import { MotionDirective } from '../ngx-motion.directive';
5
+ import { routeTransition } from './motion-page-transition';
6
+
7
+ @Component({
8
+ selector: 'motion-host',
9
+ templateUrl: './motion-host.component.html',
10
+ standalone: true,
11
+ animations: [
12
+ routeTransition
13
+ ]
14
+ })
15
+ export class MotionHostComponent implements OnInit {
16
+
17
+ exitDelay = 0;
18
+ maxDelay = '0ms';
19
+ constructor(
20
+ private router: Router,
21
+ private motionService: MotionService,
22
+ protected route: ActivatedRoute,
23
+ ) {
24
+
25
+ }
26
+
27
+
28
+ //TODO: Set longest duration based on current route elements
29
+ ngOnInit() {
30
+
31
+ this.router.events.subscribe(event => {
32
+ if (event instanceof NavigationStart) {
33
+ const currentRoute = event.url;
34
+
35
+ this.maxDelay = this.motionService.getLongestExitDuration().toString();
36
+ }
37
+ });
38
+
39
+ this.router.events.subscribe(event => {
40
+ if (event instanceof NavigationEnd) {
41
+ this.motionService.runAllEnterAnimations();
42
+
43
+
44
+ }
45
+ });
46
+
47
+ }
48
+
49
+
50
+ }
@@ -0,0 +1,19 @@
1
+ import { trigger, transition, style, animate, query, group, animateChild } from '@angular/animations';
2
+
3
+ export const routeTransition = trigger('routeTransition', [
4
+ transition('* => *', [
5
+ query(':enter, :leave', style({ transform: 'translateX(100%)' }), { optional: true }),
6
+ query(':enter', style({ transform: 'translateX(1%)' }), { optional: true }),
7
+ query(':leave', style({ transform: 'translateX(-1%)' }), { optional: true }),
8
+ group([
9
+ query(':leave', [
10
+ animate('{{maxDelay}} ease-in-out', style({ transform: 'translateX(-10%)' }))
11
+ ], { optional: true }),
12
+ query(':enter', [
13
+ animate('0s {{maxDelay}} ease-in-out', style({ transform: 'translateX(0%)' }))
14
+ ], { optional: true })
15
+ ]),
16
+ query(':enter', animateChild(), { optional: true }),
17
+ query(':leave', animateChild(), { optional: true })
18
+ ],{params: {maxDelay: '1000ms'}})
19
+ ]);
@@ -0,0 +1,126 @@
1
+ import {
2
+ Injectable,
3
+ Inject,
4
+ signal,
5
+ } from '@angular/core';
6
+ import { DOCUMENT } from '@angular/common';
7
+ import { MotionDirective } from './ngx-motion.directive';
8
+ import { fromEvent, Subscription } from 'rxjs';
9
+ import { throttleTime, debounceTime } from 'rxjs/operators';
10
+ import { Router } from '@angular/router';
11
+
12
+ @Injectable({
13
+ providedIn: 'root',
14
+ })
15
+ export class MotionService {
16
+ private scrollSubscription: Subscription;
17
+ private motionElements: MotionDirective[] = [];
18
+ scrollYProgress = signal(0);
19
+ totalExitDuration: number = 0;
20
+
21
+ constructor(
22
+ private router: Router,
23
+ @Inject(DOCUMENT) private document: Document,
24
+ ) {
25
+ this.setupScrollListener();
26
+ this.scrollSubscription = new Subscription();
27
+ }
28
+
29
+ ngOnDestroy() {
30
+ if (this.scrollSubscription) {
31
+ this.scrollSubscription.unsubscribe();
32
+ }
33
+ }
34
+
35
+ private updateTotalExitDuration() {
36
+ this.totalExitDuration = this.motionElements.reduce((total, element) => {
37
+ return total + element.getDuration();
38
+ }, 0);
39
+ }
40
+
41
+ private setupScrollListener() {
42
+ if (typeof window !== 'undefined') {
43
+ this.scrollSubscription = fromEvent(window, 'scroll')
44
+ .pipe(
45
+ throttleTime(16), // Limit to about 60fps
46
+ debounceTime(1), // Wait for scroll to settle
47
+ )
48
+ .subscribe(() => {
49
+ this.updateScrollProgress();
50
+ });
51
+ this.updateScrollProgress();
52
+ }
53
+ }
54
+
55
+ private updateScrollProgress() {
56
+ const doc = this.document.documentElement;
57
+ const scrollTop = window.scrollY || doc.scrollTop;
58
+ const scrollHeight = doc.scrollHeight - doc.clientHeight;
59
+ const progress =
60
+ scrollHeight > 0 ? Math.round((scrollTop / scrollHeight) * 100) : 0;
61
+ this.scrollYProgress.set(progress);
62
+ }
63
+
64
+ registerMotionElement(element: MotionDirective) {
65
+ this.motionElements.push(element);
66
+ this.updateTotalExitDuration();
67
+ }
68
+
69
+ unregisterMotionElement(element: MotionDirective) {
70
+ this.motionElements = this.motionElements.filter((e) => e !== element);
71
+ this.updateTotalExitDuration();
72
+ }
73
+
74
+ getMotionElements(): MotionDirective[] {
75
+ return this.motionElements;
76
+ }
77
+
78
+ getAllElementsByRoute(route: string): MotionDirective[] {
79
+ return this.motionElements;
80
+ }
81
+
82
+ cancelAllAnimations() {
83
+ this.motionElements.forEach((motion) => {
84
+ motion.cancel();
85
+ });
86
+ }
87
+
88
+ runAllEnterAnimations(): void {
89
+ const enterAnimations = this.motionElements.map((motion) => {
90
+ // motion.runInitAnimation();
91
+ });
92
+ }
93
+
94
+ runAllExitAnimations(): void {
95
+ // Proceed with the exit animations
96
+ this.motionElements.map((motion) => {
97
+ //motion.runExitAnimation();
98
+ });
99
+ }
100
+
101
+ runAllEnterAnimationsForRoute(route: string): MotionDirective[] {
102
+ const enterAnimations = this.getAllElementsByRoute(route).map((motion) => {
103
+ motion.runInitAnimation();
104
+ return motion;
105
+ });
106
+ return enterAnimations;
107
+ }
108
+
109
+ getLongestExitDuration(): number {
110
+ const durations = this.motionElements.map((motion) => motion.getDuration());
111
+ return durations.length > 0 ? Math.max(...durations) : 0;
112
+ }
113
+
114
+ getLongestEnterDuration(): number {
115
+ const durations = this.motionElements.map((motion) => motion.getDuration());
116
+ return durations.length > 0 ? Math.max(...durations) : 0;
117
+ }
118
+
119
+ getLongestDurationForRoute(): number {
120
+ const route = this.router.url;
121
+ const elements = this.getAllElementsByRoute(route);
122
+ const durations = elements.map((motion) => motion.getDuration());
123
+ console.log('durations', durations.length > 0 ? Math.max(...durations) : 0);
124
+ return durations.length > 0 ? Math.max(...durations) : 0;
125
+ }
126
+ }
@@ -5,139 +5,307 @@ import {
5
5
  OnDestroy,
6
6
  Output,
7
7
  EventEmitter,
8
- AfterViewInit,
9
8
  OnChanges,
10
- SimpleChanges
11
- } from "@angular/core";
9
+ SimpleChanges,
10
+ HostListener,
11
+ } from '@angular/core';
12
12
  import {
13
13
  AnimationBuilder,
14
14
  style,
15
15
  animate,
16
16
  AnimationPlayer,
17
- } from "@angular/animations";
18
- import { MotionHostDirective} from "./ngx-motion-container.directive";
17
+ AnimationMetadata,
18
+ } from '@angular/animations';
19
+ import { MotionService } from './services/ngx-motion.service';
20
+
21
+ let uniqueIdCounter = 0;
19
22
 
20
23
  @Directive({
21
- selector: "[motion]",
22
- standalone: true,
24
+ selector: '[motion]'
23
25
  })
24
- export class MotionDirective implements OnDestroy, AfterViewInit, OnChanges {
26
+
27
+ export class MotionDirective implements OnDestroy, OnChanges {
25
28
  @Input() initial: any = {};
26
29
  @Input() animate: any = {};
27
30
  @Input() exit: any = {};
28
- @Input() duration = "0.3s";
29
- @Input() easing = "ease";
30
- @Input() onHover: any = {};
31
- @Input() variant: string = '';
32
-
31
+ @Input() inView: any = {};
32
+ @Input() duration = '0.3s';
33
+ @Input() delay = '0s';
34
+ @Input() repeat = false;
35
+ @Input() exitDelay = '0s';
36
+ @Input() easing = 'ease';
37
+ @Input() offset = '0px';
38
+ @Input() whileHover: any = {};
39
+ @Input() staggerChildren = '0s';
40
+ @Input() whileTap: any = {};
41
+ @Input() whileFocus: any = {};
42
+ @Input() whileInView: any = {};
43
+ @Input() variants: any = {};
33
44
  @Output() animationComplete = new EventEmitter<void>();
34
45
 
35
46
  private player: AnimationPlayer | null = null;
36
- private presence: MotionHostDirective | null = null;
47
+ private elementId: string;
48
+ private hoverTimeout: any;
49
+ private observer?: IntersectionObserver;
50
+ private routeDelay: number = 0;
51
+
52
+ get scrollProgress() {
53
+ return this.motionService.scrollYProgress();
54
+ }
55
+
56
+ constructor(
57
+ private builder: AnimationBuilder,
58
+ private el: ElementRef,
59
+ private motionService: MotionService,
60
+
61
+ ) {
62
+
63
+ this.elementId = `motion-${uniqueIdCounter++}`;
64
+ this.el.nativeElement.setAttribute('id', this.elementId);
65
+
66
+ this.motionService.registerMotionElement(this);
67
+ this.applyInitialStyles();
68
+ this.routeDelay = this.motionService.getLongestExitDuration();
69
+ }
37
70
 
38
- constructor(private builder: AnimationBuilder, private el: ElementRef) {}
39
71
 
40
- ngAfterViewInit() {
41
- if (this.variant) {
42
- const initialState = this.variant === 'animate' ? this.animate : this.initial;
43
- Object.assign(this.el.nativeElement.style, initialState);
44
- } else {
45
- this.applyInitialStyles();
46
- this.runAnimation(this.animate);
72
+ ngOnInit() {
73
+ if (Object.keys(this.inView).length > 0) {
74
+ this.runInitAnimationsWhenInViewport(this, this.offset, this.repeat);
47
75
  }
48
- this.setupHoverAnimations();
76
+ setTimeout(() => {
77
+ this.playAnimation(this.initial, this.animate);
78
+ }, this.routeDelay);
49
79
  }
50
80
 
51
81
  ngOnDestroy() {
52
- this.runExitAnimation();
82
+ if (this.exit && Object.keys(this.exit).length > 0) {
83
+ this.runExitAnimation();
84
+ }
85
+
86
+ //TODO: Add options to select reset behaviour , e.g either reset tto inintial or allow anim to run
87
+ // this.resetPlayer(); // Ensure the animation is properly cleaned up
88
+ // this.reset();
89
+
90
+ if (this.observer) {
91
+ this.observer.disconnect();
92
+ }
53
93
  }
54
94
 
95
+
55
96
  ngOnChanges(changes: SimpleChanges) {
56
- if (changes['variant'] && !changes['variant'].firstChange) {
57
- const targetState = this.variant === 'animate' ? this.animate :
58
- this.variant === 'exit' ? this.exit :
59
- this.initial;
97
+ if (changes['animate'] && changes['animate'].previousValue !== undefined) {
98
+ const oldState = changes['animate'].previousValue;
99
+ let newState = changes['animate'].currentValue;
60
100
 
61
- const startState = this.variant === 'exit' ? this.animate : this.initial;
62
-
63
- const animation = this.builder.build([
64
- style(startState),
65
- animate(`${this.duration} ${this.easing}`, style(targetState))
66
- ]);
101
+ if (typeof newState === 'object') {
102
+ this.playAnimation(oldState, newState);
103
+ } else if (typeof newState === 'string' && this.variants?.[newState]) {
104
+ newState = this.variants[newState];
105
+ this.playAnimation(oldState, newState);
106
+ }
107
+ }
108
+ }
109
+
67
110
 
68
- if (this.player) {
69
- this.player.destroy();
111
+ @HostListener('mouseenter')
112
+ onMouseEnter() {
113
+ if (Object.keys(this.whileHover).length > 0) {
114
+ clearTimeout(this.hoverTimeout);
115
+ if (Object.keys(this.animate).length > 0) {
116
+ this.playAnimation(this.animate, this.whileHover);
117
+ } else {
118
+ this.playAnimation(this.initial, this.whileHover);
70
119
  }
71
- this.player = animation.create(this.el.nativeElement);
72
- this.player.play();
73
120
  }
74
121
  }
75
122
 
76
- registerPresence(presence: MotionHostDirective) {
77
- this.presence = presence;
123
+ @HostListener('mouseleave')
124
+ onMouseLeave() {
125
+ if (Object.keys(this.whileHover).length > 0) {
126
+ this.hoverTimeout = setTimeout(() => {
127
+ if (Object.keys(this.animate).length > 0) {
128
+ this.playAnimation(this.whileHover, this.animate);
129
+ } else {
130
+ this.playAnimation(this.whileHover, this.initial);
131
+ }
132
+ }, 100);
133
+ }
78
134
  }
79
135
 
80
- runAnimation(styles: any) {
81
- let animationMetadata = [];
82
- const currentStyles = this.variant === 'initial' ? this.initial :
83
- this.variant === 'animate' ? this.animate :
84
- this.variant === 'exit' ? this.exit : styles;
136
+ @HostListener('focus')
137
+ @HostListener('mousedown', ['$event'])
138
+ @HostListener('touchstart', ['$event'])
139
+ onPress(event: Event) {
140
+ if (Object.keys(this.whileTap).length > 0) {
141
+ if (Object.keys(this.animate).length > 0) {
142
+ this.playAnimation(this.animate, this.whileTap);
143
+ } else {
144
+ this.playAnimation(this.initial, this.whileTap);
145
+ }
146
+ const endEvent = event.type === 'mousedown' ? 'mouseup' : 'touchend';
147
+ const endListener = () => {
148
+ if (Object.keys(this.animate).length > 0) {
149
+ this.playAnimation(this.whileTap, this.animate);
150
+ } else {
151
+ this.playAnimation(this.whileTap, this.initial);
152
+ }
85
153
 
86
- animationMetadata = [
87
- style(this.variant === 'exit' ? this.animate : this.initial),
88
- animate(`${this.duration} ${this.easing}`, style(currentStyles))
89
- ];
154
+ window.removeEventListener(endEvent, endListener);
155
+ };
156
+
157
+ window.addEventListener(endEvent, endListener);
158
+ }
159
+ }
160
+
161
+ @HostListener('focus')
162
+ onFocus() {
163
+ if (Object.keys(this.whileFocus).length > 0) {
164
+ if (Object.keys(this.animate).length > 0) {
165
+ this.playAnimation(this.animate, this.whileFocus);
166
+ } else {
167
+ this.playAnimation(this.initial, this.whileFocus);
168
+ }
169
+ }
170
+ }
171
+
172
+ @HostListener('blur')
173
+ onBlur() {
174
+ if (Object.keys(this.whileFocus).length > 0) {
175
+ if (Object.keys(this.animate).length > 0) {
176
+ this.playAnimation(this.whileFocus, this.animate);
177
+ } else {
178
+ this.playAnimation(this.whileFocus, this.initial);
179
+ }
180
+ }
181
+ }
90
182
 
91
- const animation = this.builder.build(animationMetadata);
183
+ applyInitialValues() {
184
+ Object.assign(this.el.nativeElement.style, this.initial);
185
+ }
186
+
187
+ private resetPlayer() {
92
188
  if (this.player) {
189
+ this.player.finish();
93
190
  this.player.destroy();
94
191
  }
95
- this.player = animation.create(this.el.nativeElement);
96
- this.player.play();
97
192
  }
98
193
 
99
- runExitAnimation() {
100
- if (this.presence) {
101
- this.presence.startExitAnimation(this);
194
+ private reset() {
195
+ this.resetPlayer();
196
+ this.el.nativeElement.removeAttribute('style');
197
+ }
198
+
199
+ private applyInitialStyles() {
200
+ Object.assign(this.el.nativeElement.style, this.initial);
201
+ }
202
+
203
+ private applyAnimateStyles() {
204
+ Object.assign(this.el.nativeElement.style, this.animate);
205
+ }
206
+
207
+ private playAnimation(startState: any, targetState: any) {
208
+ if (!targetState) return;
209
+
210
+ if (startState === undefined) {
211
+ startState = this.initial;
102
212
  }
103
213
 
104
- const animation = this.builder.build([
105
- style(this.animate),
106
- animate(`${this.duration} ${this.easing}`, style(this.exit)),
107
- ]);
214
+ if (targetState === undefined) {
215
+ targetState = this.animate;
216
+ }
108
217
 
109
- if (this.player) {
218
+ const delay = this.delay || '0ms';
219
+ const duration = this.duration || '1s';
220
+ const easing = this.easing || 'ease';
221
+
222
+ if (typeof targetState === 'string') {
223
+ targetState = this.variants[targetState];
224
+ }
225
+
226
+ if (typeof startState === 'string') {
227
+ startState = this.variants[startState];
228
+ }
229
+
230
+ const timing = `${duration} ${delay} ${easing}`;
231
+
232
+ const parentAnimation: AnimationMetadata[] = [
233
+ style(startState || {}),
234
+ animate(timing, style(targetState)),
235
+ ];
236
+
237
+ const animationBuilder = this.builder.build(parentAnimation);
238
+
239
+ if (this.player && this.player.hasStarted()) {
110
240
  this.player.destroy();
111
241
  }
112
242
 
113
- this.player = animation.create(this.el.nativeElement);
114
- this.player.onDone(() => this.completeAnimation());
243
+ this.player = animationBuilder.create(this.el.nativeElement);
244
+ this.player.onDone(() => {
245
+ this.animationComplete.emit();
246
+ });
115
247
  this.player.play();
116
248
  }
117
249
 
118
- private completeAnimation() {
119
- this.animationComplete.emit();
120
- if (this.presence) {
121
- this.presence.completeExitAnimation(this);
250
+ runInViewAnimation() {
251
+ if (this.inView && this.animate) {
252
+ this.playAnimation(this.initial, this.inView);
253
+ //this.animationComplete.emit();
122
254
  }
123
255
  }
124
256
 
257
+ runInitAnimation() {
258
+ if (this.initial && this.animate) {
259
+ this.playAnimation(this.initial, this.animate);
260
+ //this.animationComplete.emit();
261
+ }
262
+ }
263
+
264
+ runExitAnimation() {
265
+ if (this.exit) {
266
+ this.playAnimation(this.animate, this.exit);
267
+ //this.animationComplete.emit();
268
+ }
269
+ }
270
+
271
+ cancel() {
272
+ this.applyAnimateStyles();
273
+ }
274
+
125
275
  getDuration(): number {
126
- return parseFloat(this.duration) * 1000; // Convert to milliseconds
276
+ const durationSeconds = parseFloat(this.duration);
277
+ const delaySeconds = parseFloat(this.delay);
278
+ return (durationSeconds + delaySeconds) * 1000;
127
279
  }
128
280
 
129
- private applyInitialStyles() {
130
- Object.assign(this.el.nativeElement.style, this.initial);
281
+ getKeyByValue(object: any, key: any) {
282
+ return Object.keys(object).find((key) => object[key] === key);
131
283
  }
132
284
 
133
- private setupHoverAnimations() {
134
- if (this.onHover) {
135
- this.el.nativeElement.addEventListener('mouseenter', () => {
136
- this.runAnimation(this.onHover);
137
- });
138
- this.el.nativeElement.addEventListener('mouseleave', () => {
139
- this.runAnimation(this.animate);
140
- });
141
- }
285
+ //TODO:Add logic for exiting elements
286
+ runInitAnimationsWhenInViewport(
287
+ element: MotionDirective,
288
+ offset: string = '0px',
289
+ repeat: boolean,
290
+ ) {
291
+ this.observer = new IntersectionObserver(
292
+ (entries) => {
293
+ entries.forEach((entry) => {
294
+ if (entry.isIntersecting) {
295
+ // console.log('In view');
296
+ element.runInViewAnimation();
297
+
298
+ if (!repeat) {
299
+ this.observer?.unobserve(entry.target);
300
+ }
301
+ } else if (!entry.isIntersecting && repeat) {
302
+ //console.log('Leaving view');
303
+ }
304
+ });
305
+ },
306
+ { rootMargin: offset },
307
+ );
308
+
309
+ this.observer.observe(element.el.nativeElement);
142
310
  }
143
311
  }
@@ -1,16 +1,16 @@
1
1
  import { NgModule } from '@angular/core';
2
2
  import { MotionDirective } from './ngx-motion.directive';
3
- import { MotionHostDirective } from './ngx-motion-container.directive';
3
+ import { MotionHostComponent } from './motion-host/motion-host.component';
4
4
  @NgModule({
5
5
  declarations: [
6
6
  MotionDirective,
7
- MotionHostDirective
8
7
  ],
9
8
  imports: [
9
+ MotionHostComponent
10
10
  ],
11
11
  exports: [
12
12
  MotionDirective,
13
- MotionHostDirective
13
+ MotionHostComponent
14
14
  ]
15
15
  })
16
16
  export class NgxMotionModule { }
@@ -0,0 +1,128 @@
1
+ import {
2
+ Injectable,
3
+ Inject,
4
+ signal,
5
+ } from '@angular/core';
6
+ import { DOCUMENT } from '@angular/common';
7
+ import { MotionDirective } from '../ngx-motion.directive';
8
+
9
+ import { fromEvent, Subscription } from 'rxjs';
10
+ import { throttleTime, debounceTime } from 'rxjs/operators';
11
+ import { Router } from '@angular/router';
12
+
13
+ @Injectable({
14
+ providedIn: 'root',
15
+ })
16
+ export class MotionService {
17
+ private scrollSubscription: Subscription;
18
+ private motionElements: MotionDirective[] = [];
19
+ scrollYProgress = signal(0);
20
+ totalExitDuration: number = 0;
21
+
22
+ constructor(
23
+ private router: Router,
24
+ @Inject(DOCUMENT) private document: Document,
25
+ ) {
26
+ this.setupScrollListener();
27
+ this.scrollSubscription = new Subscription();
28
+ }
29
+
30
+ ngOnDestroy() {
31
+ if (this.scrollSubscription) {
32
+ this.scrollSubscription.unsubscribe();
33
+ }
34
+ }
35
+
36
+ private updateTotalExitDuration() {
37
+ this.totalExitDuration = this.motionElements.reduce((total, element) => {
38
+ return total + element.getDuration();
39
+ }, 0);
40
+ }
41
+
42
+ private setupScrollListener() {
43
+ if (typeof window !== 'undefined') {
44
+ this.scrollSubscription = fromEvent(window, 'scroll')
45
+ .pipe(
46
+ throttleTime(16), // Limit to about 60fps
47
+ debounceTime(1), // Wait for scroll to settle
48
+ )
49
+ .subscribe(() => {
50
+ this.updateScrollProgress();
51
+ });
52
+ this.updateScrollProgress();
53
+ }
54
+ }
55
+
56
+ private updateScrollProgress() {
57
+ const doc = this.document.documentElement;
58
+ const scrollTop = window.scrollY || doc.scrollTop;
59
+ const scrollHeight = doc.scrollHeight - doc.clientHeight;
60
+ const progress =
61
+ scrollHeight > 0 ? Math.round((scrollTop / scrollHeight) * 100) : 0;
62
+ this.scrollYProgress.set(progress);
63
+ }
64
+
65
+ registerMotionElement(element: MotionDirective) {
66
+ this.motionElements.push(element);
67
+ this.updateTotalExitDuration();
68
+ }
69
+
70
+ unregisterMotionElement(element: MotionDirective) {
71
+ this.motionElements = this.motionElements.filter((e) => e !== element);
72
+ this.updateTotalExitDuration();
73
+ }
74
+
75
+ getMotionElements(): MotionDirective[] {
76
+ return this.motionElements;
77
+ }
78
+
79
+ getAllElementsByRoute(route: string): MotionDirective[] {
80
+ return this.motionElements;
81
+ }
82
+
83
+ cancelAllAnimations() {
84
+ this.motionElements.forEach((motion) => {
85
+ motion.cancel();
86
+ });
87
+ }
88
+
89
+ runAllEnterAnimations(): void {
90
+ const enterAnimations = this.motionElements.map((motion) => {
91
+ // motion.runInitAnimation();
92
+ });
93
+ }
94
+
95
+ runAllExitAnimations(): void {
96
+ // Proceed with the exit animations
97
+ this.motionElements.map((motion) => {
98
+ motion.runExitAnimation();
99
+ });
100
+ }
101
+
102
+ runAllEnterAnimationsForRoute(route: string): MotionDirective[] {
103
+ const enterAnimations = this.getAllElementsByRoute(route).map((motion) => {
104
+ motion.runInitAnimation();
105
+ return motion;
106
+ });
107
+ return enterAnimations;
108
+ }
109
+
110
+ getLongestExitDuration(): number {
111
+ const durations = this.motionElements.map((motion) => motion.getDuration());
112
+ return durations.length > 0 ? Math.max(...durations) : 0;
113
+ }
114
+
115
+ getLongestEnterDuration(): number {
116
+ const durations = this.motionElements.map((motion) => motion.getDuration());
117
+ return durations.length > 0 ? Math.max(...durations) : 0;
118
+ }
119
+
120
+ getLongestDurationForRoute(): number {
121
+ const route = this.router.url;
122
+ const elements = this.getAllElementsByRoute(route);
123
+ const durations = elements.map((motion) => motion.getDuration());
124
+ console.log('durations', durations.length > 0 ? Math.max(...durations) : 0);
125
+ return durations.length > 0 ? Math.max(...durations) : 0;
126
+ }
127
+ }
128
+
package/src/public-api.ts CHANGED
@@ -1,2 +1,6 @@
1
1
  export * from './lib/ngx-motion.directive';
2
- export * from './lib/ngx-motion-container.directive';
2
+ export * from './lib/services/ngx-motion.service';
3
+ export * from './lib/motion-host/motion-host.component';
4
+ export * from './lib/motion-host/motion-page-transition';
5
+
6
+ // export * from './lib/ngx-motion-host.directive';
@@ -1,44 +0,0 @@
1
- import {
2
- Directive,
3
- ContentChildren,
4
- QueryList,
5
- Output,
6
- EventEmitter,
7
- Input,
8
- } from "@angular/core";
9
- import { MotionDirective } from "./ngx-motion.directive";
10
-
11
- @Directive({
12
- selector: "[animatePresence]",
13
- standalone: true,
14
- })
15
- export class MotionHostDirective {
16
- @ContentChildren(MotionDirective) motionElements!: QueryList<MotionDirective>;
17
- @Output() exitComplete = new EventEmitter<void>();
18
- @Input() mode: "sync" | "popLayout" | "wait" = "wait";
19
- @Input() initial = true;
20
-
21
- private animatingElements = new Set<MotionDirective>();
22
-
23
- ngAfterContentInit() {
24
- this.motionElements.forEach((motion) => {
25
- motion.registerPresence(this);
26
- });
27
- }
28
-
29
- startExitAnimation(motion: MotionDirective) {
30
- this.animatingElements.add(motion);
31
- }
32
-
33
- completeExitAnimation(motion: MotionDirective) {
34
- this.animatingElements.delete(motion);
35
- if (this.animatingElements.size === 0) {
36
- this.exitComplete.emit();
37
- }
38
- }
39
-
40
- getLongestDuration(): number {
41
- return Math.max(...this.motionElements.map((m) => m.getDuration()));
42
- }
43
- }
44
-