1
\$\begingroup\$

I'm using Ionic 4 and Angular animations to animate modals. I created the following two functions that control the animations but they share a lot of repeated code. Is there a way I can clean these up into a single function that just takes an array of parameters for the animations?

import { Injectable } from '@angular/core';
import { Animation } from '@ionic/core';

@Injectable({
  providedIn: 'root'
})
export class AnimationsService {
  modalLeave(AnimationC: Animation, baseEl: HTMLElement): Promise<Animation> {
    const baseAnimation = new AnimationC();

    const backdropAnimation = new AnimationC();
    backdropAnimation.addElement(baseEl.querySelector('ion-backdrop'));

    const wrapperAnimation = new AnimationC();
    const wrapperEl = baseEl.querySelector('.modal-wrapper');
    wrapperAnimation.addElement(wrapperEl);
    const wrapperElRect = wrapperEl!.getBoundingClientRect();

    wrapperAnimation
      .beforeStyles({
        opacity: 1
      })
      .fromTo('transform', 'translateX(0%)', 'translateX(100%)')
      .fromTo('opacity', 1, 0)
      .fromTo('-webkit-backdrop-filter', 'blur(7px)', 'blur(0px)');

    return Promise.resolve(
      baseAnimation
        .addElement(baseEl)
        .easing('ease-in')
        .duration(150)
        .add(backdropAnimation)
        .add(wrapperAnimation)
    );
  }

  modalEnter(AnimationC: Animation, baseEl: HTMLElement): Promise<Animation> {
    const baseAnimation = new AnimationC();

    const backdropAnimation = new AnimationC();
    backdropAnimation.addElement(baseEl.querySelector('ion-backdrop'));

    const wrapperAnimation = new AnimationC();
    const wrapperEl = baseEl.querySelector('.modal-wrapper');
    wrapperAnimation.addElement(wrapperEl);

    wrapperAnimation
      .beforeStyles({
        opacity: 1
      })
      .fromTo('transform', 'translateX(100%)', 'translateX(0%)')
      .fromTo('opacity', 0, 1)
      .fromTo('-webkit-backdrop-filter', 'blur(0px)', 'blur(7px)');

    return Promise.resolve(
      baseAnimation
        .addElement(baseEl)
        .easing('ease-in')
        .duration(150)
        .add(wrapperAnimation)
    );
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.