All files / src/animation AnimationManager.ts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 4199x                 9x                                               9x 502x     9x                 292x 292x 292x 292x             292x 292x 292x 292x 292x                     163x           163x 7x   156x 280x   156x 280x       163x             9x 149x 233x     149x 233x     9x 324x 4x 4x 11x   11x     4x 4x 4x   4x 4x       9x 6770x         1389x         5381x       9x 13x 13x 29x   13x 13x     9x 89x 89x     89x   160x   89x             89x 89x 89x 6x   83x       9x 128x 128x 128x     9x       241x 241x 241x         241x     96x         96x 96x         96x 96x     96x     96x     3x               96x 93x 93x                   86x         98x 95x 95x   95x 11x   84x 103x 84x       84x 102x   102x 20x   82x       84x       84x 45x   39x 39x 39x     84x     9x 7x 9x         9x 3x           9x         98x 98x 98x 98x                               97x 97x 97x       175x 97x   97x 2535x 2535x 2535x 2535x         2535x   2535x 90x       90x                     90x 90x 2445x 3x   2442x     97x                                 90x           90x 90x 156x         143x     13x 13x 13x     90x     9x 13x 13x     13x   13x 13x                 13x   9x  
import {
  getInsidePosition,
  isCircularable,
  getCirculatedPos,
  getDuration,
} from "../Coordinate";
import { Axis, AxisManager } from "../AxisManager";
import { InterruptManager } from "../InterruptManager";
import { EventManager, ChangeEventOption } from "../EventManager";
import {
  requestAnimationFrame,
  cancelAnimationFrame,
  map,
  every,
  filter,
  equal,
  roundNumber,
  getDecimalPlace,
  inversePow,
} from "../utils";
import { AxesOption } from "../Axes";
import {
  AnimationParam,
  ObjectInterface,
  UpdateAnimationOption,
} from "../types";
 
export interface AnimationState {
  pos: Axis;
  easingPer: number;
  finished: boolean;
}
 
const clamp = (value: number, min: number, max: number): number => {
  return Math.max(Math.min(value, max), min);
};
 
export abstract class AnimationManager {
  public interruptManager: InterruptManager;
  public eventManager: EventManager;
  public axisManager: AxisManager;
  protected _options: AxesOption;
  protected _animateParam: AnimationParam;
  private _raf: number;
 
  public constructor({
    options,
    interruptManager,
    eventManager,
    axisManager,
  }: {
    options: AxesOption;
    interruptManager: InterruptManager;
    eventManager: EventManager;
    axisManager: AxisManager;
  }) {
    this._options = options;
    this.interruptManager = interruptManager;
    this.eventManager = eventManager;
    this.axisManager = axisManager;
    this.animationEnd = this.animationEnd.bind(this);
  }
 
  public abstract interpolate(displacement: number, threshold: number): number;
 
  public abstract updateAnimation(options: UpdateAnimationOption): void;
 
  protected abstract _initState(info: AnimationParam): AnimationState;
 
  protected abstract _getNextState(prevState: AnimationState): AnimationState;
 
  public getDuration(
    depaPos: Axis,
    destPos: Axis,
    wishDuration?: number
  ): number {
    let duration: number;
    if (typeof wishDuration !== "undefined") {
      duration = wishDuration;
    } else {
      const durations: Axis = map(destPos, (v, k) =>
        getDuration(Math.abs(v - depaPos[k]), this._options.deceleration)
      );
      duration = Object.keys(durations).reduce(
        (max, v) => Math.max(max, durations[v]),
        -Infinity
      );
    }
    return clamp(
      duration,
      this._options.minimumDuration,
      this._options.maximumDuration
    );
  }
 
  public getDisplacement(velocity: number[]): number[] {
    const totalVelocity = Math.pow(
      velocity.reduce((total, v) => total + v * v, 0),
      1 / velocity.length
    );
    const duration = Math.abs(totalVelocity / -this._options.deceleration);
    return velocity.map((v) => (v / 2) * duration);
  }
 
  public stopAnimation(option?: ChangeEventOption): void {
    if (this._animateParam) {
      const orgPos: Axis = this.axisManager.get();
      const pos: Axis = this.axisManager.map(orgPos, (v, opt) =>
        getCirculatedPos(v, opt.range, opt.circular as boolean[])
      );
      Iif (!every(pos, (v, k) => orgPos[k] === v)) {
        this.eventManager.triggerChange(pos, orgPos, option, !!option);
      }
      this._animateParam = null;
      Eif (this._raf) {
        cancelAnimationFrame(this._raf);
      }
      this._raf = null;
      this.eventManager.triggerAnimationEnd(!!option?.event);
    }
  }
 
  public getEventInfo(): ChangeEventOption {
    if (
      this._animateParam &&
      this._animateParam.input &&
      this._animateParam.inputEvent
    ) {
      return {
        input: this._animateParam.input,
        event: this._animateParam.inputEvent,
      };
    } else {
      return null;
    }
  }
 
  public restore(option: ChangeEventOption): void {
    const pos: Axis = this.axisManager.get();
    const destPos: Axis = this.axisManager.map(pos, (v, opt) =>
      Math.min(opt.range[1], Math.max(opt.range[0], v))
    );
    this.stopAnimation();
    this.animateTo(destPos, this.getDuration(pos, destPos), option);
  }
 
  public animationEnd(): void {
    const beforeParam: ChangeEventOption = this.getEventInfo();
    this._animateParam = null;
 
    // for Circular
    const circularTargets = this.axisManager.filter(
      this.axisManager.get(),
      (v, opt) => isCircularable(v, opt.range, opt.circular as boolean[])
    );
    Iif (Object.keys(circularTargets).length > 0) {
      this.setTo(
        this.axisManager.map(circularTargets, (v, opt) =>
          getCirculatedPos(v, opt.range, opt.circular as boolean[])
        )
      );
    }
    this.interruptManager.setInterrupt(false);
    this.eventManager.triggerAnimationEnd(!!beforeParam);
    if (this.axisManager.isOutside()) {
      this.restore(beforeParam);
    } else {
      this.finish(!!beforeParam);
    }
  }
 
  public finish(isTrusted: boolean): void {
    this._animateParam = null;
    this.interruptManager.setInterrupt(false);
    this.eventManager.triggerFinish(isTrusted);
  }
 
  public getUserControl(param: AnimationParam): {
    destPos: Axis;
    duration: number;
  } {
    const userWish = param.setTo();
    userWish.destPos = this.axisManager.get(userWish.destPos);
    userWish.duration = clamp(
      userWish.duration,
      this._options.minimumDuration,
      this._options.maximumDuration
    );
    return userWish;
  }
 
  public animateTo(
    destPos: Axis,
    duration: number,
    option?: ChangeEventOption
  ): void {
    this.stopAnimation();
    const param: AnimationParam = this._createAnimationParam(
      destPos,
      duration,
      option
    );
    const depaPos = { ...param.depaPos };
    const retTrigger = this.eventManager.triggerAnimationStart(param);
 
    // to control
    const userWish = this.getUserControl(param);
 
    // You can't stop the 'animationStart' event when 'circular' is true.
    Iif (
      !retTrigger &&
      this.axisManager.every(userWish.destPos, (v, opt) =>
        isCircularable(v, opt.range, opt.circular as boolean[])
      )
    ) {
      console.warn(
        "You can't stop the 'animation' event when 'circular' is true."
      );
    }
 
    if (retTrigger && !equal(userWish.destPos, depaPos)) {
      const inputEvent = option?.event || null;
      this._animateLoop(
        {
          depaPos,
          destPos: userWish.destPos,
          duration: userWish.duration,
          delta: this.axisManager.getDelta(depaPos, userWish.destPos),
          isTrusted: !!inputEvent,
          inputEvent,
          input: option?.input || null,
        },
        () => this.animationEnd()
      );
    }
  }
 
  public setTo(pos: Axis, duration: number = 0) {
    const axes: string[] = Object.keys(pos);
    const orgPos: Axis = this.axisManager.get(axes);
 
    if (equal(pos, orgPos)) {
      return this;
    }
    this.interruptManager.setInterrupt(true);
    let movedPos = filter(pos, (v, k) => orgPos[k] !== v);
    Iif (!Object.keys(movedPos).length) {
      return this;
    }
 
    movedPos = this.axisManager.map(movedPos, (v, opt) => {
      const { range, circular } = opt;
 
      if (circular && (circular[0] || circular[1])) {
        return v;
      } else {
        return getInsidePosition(v, range, circular as boolean[]);
      }
    });
 
    Iif (equal(movedPos, orgPos)) {
      return this;
    }
 
    if (duration > 0) {
      this.animateTo(movedPos, duration);
    } else {
      this.stopAnimation();
      this.eventManager.triggerChange(movedPos);
      this.finish(false);
    }
 
    return this;
  }
 
  public setBy(pos: Axis, Iduration = 0) {
    return this.setTo(
      map(this.axisManager.get(Object.keys(pos)), (v, k) => v + pos[k]),
      duration
    );
  }
 
  public setOptions(options: AxesOption) {
    this._options = {
      ...this._options,
      ...options,
    };
  }
 
  private _createAnimationParam(
    pos: Axis,
    duration: number,
    option?: ChangeEventOption
  ): AnimationParam {
    const depaPos: Axis = this.axisManager.get();
    const destPos: Axis = pos;
    const inputEvent = option?.event || null;
    return {
      depaPos,
      destPos,
      duration: clamp(
        duration,
        this._options.minimumDuration,
        this._options.maximumDuration
      ),
      delta: this.axisManager.getDelta(depaPos, destPos),
      inputEvent,
      input: option?.input || null,
      isTrusted: !!inputEvent,
      done: this.animationEnd,
    };
  }
 
  private _animateLoop(param: AnimationParam, complete: () => void): void {
    Eif (param.duration) {
      this._animateParam = {
        ...param,
        startTime: new Date().getTime(),
      };
      const originalIntendedPos = map(param.destPos, (v) => v);
      let state = this._initState(this._animateParam);
 
      const loop = () => {
        this._raf = null;
        const animateParam = this._animateParam;
        const nextState = this._getNextState(state);
        const isCanceled = !this.eventManager.triggerChange(
          nextState.pos,
          state.pos
        );
 
        state = nextState;
 
        if (nextState.finished) {
          animateParam.destPos = this._getFinalPos(
            animateParam.destPos,
            originalIntendedPos
          );
          Iif (
            !equal(
              animateParam.destPos,
              this.axisManager.get(Object.keys(animateParam.destPos))
            )
          ) {
            this.eventManager.triggerChange(
              animateParam.destPos,
              nextState.pos
            );
          }
          complete();
          return;
        } else if (isCanceled) {
          this.finish(false);
        } else {
          this._raf = requestAnimationFrame(loop);
        }
      };
      loop();
    } else {
      this.eventManager.triggerChange(param.destPos);
      complete();
    }
  }
 
  /**
   * Get estimated final value.
   *
   * If destPos is within the 'error range' of the original intended position, the initial intended position is returned.
   *   - eg. original intended pos: 100, destPos: 100.0000000004 ==> return 100;
   * If dest Pos is outside the 'range of error' compared to the originally intended pos, it is returned rounded based on the originally intended pos.
   *   - eg. original intended pos: 100.123 destPos: 50.12345 => return 50.123
   * @param originalIntendedPos
   * @param destPos
   */
  private _getFinalPos(
    destPos: ObjectInterface<number>,
    originalIntendedPos: ObjectInterface<number>
  ): Axis {
    // compare destPos and originalIntendedPos
    // eslint-disable-next-line @typescript-eslint/naming-convention
    const ERROR_LIMIT = 0.000001;
    const finalPos = map(destPos, (value, key) => {
      if (
        value >= originalIntendedPos[key] - ERROR_LIMIT &&
        value <= originalIntendedPos[key] + ERROR_LIMIT
      ) {
        // In error range, return original intended
        return originalIntendedPos[key];
      } else {
        // Out of error range, return rounded pos.
        const roundUnit = this._getRoundUnit(value, key);
        const result = roundNumber(value, roundUnit);
        return result;
      }
    });
    return finalPos;
  }
 
  private _getRoundUnit(val: number, key: string): number {
    const roundUnit = this._options.round; // manual mode
    let minRoundUnit = null; // auto mode
 
    // auto mode
    Eif (!roundUnit) {
      // Get minimum round unit
      const options = this.axisManager.getAxisOptions(key);
      minRoundUnit = inversePow(
        Math.max(
          getDecimalPlace(options.range[0]),
          getDecimalPlace(options.range[1]),
          getDecimalPlace(val)
        )
      );
    }
 
    return minRoundUnit || roundUnit;
  }
}