All files tweenable.ts

94.85% Statements 258/272
74.46% Branches 105/141
91.42% Functions 32/35
94.79% Lines 255/269

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961                                                5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x       5x   5x 5x 5x                         5x   5x 5x         5x 44x           8x         8x           5x                                                           98x       98x       98x 157x 67x 67x   90x 90x   90x 84x     6x           157x   157x   157x       98x     5x 49x 49x 49x   49x 1x     48x 48x   48x 48x 48x 48x   48x 15x 15x       33x         33x     33x     33x                   33x   33x                                     5x     44x 44x   44x 42x 42x 42x       5x     5x         5x 4x   4x 4x     4x                     5x               110x 82x 80x       30x 2x       2x     28x 28x 28x 26x 32x     2x 2x 2x         28x         5x       5x 40x 40x       40x 31x   31x 2x   29x   9x 5x   5x 5x         4x 4x   4x 4x     4x 4x         40x       5x             117x         5x 42x 1x     42x                   5x         1x                           5x                   5x             117x         117x         117x         117x         117x         117x         117x         117x         117x         117x         117x                   117x         117x         117x         117x         117x         117x         117x         117x         117x                           117x         117x 8x                 262x 75x   75x                   63x 1x     63x 52x     63x 63x 63x   63x 2x     63x                     64x     64x   134x                 64x       64x     64x 64x 64x 64x 64x 64x 64x   64x       64x 64x   64x 40x     64x   64x 42x   42x 1x     42x     42x     64x           64x   64x 1x 1x 1x       1x     64x                     5x       5x 5x 5x     5x             2x                         99x                       46x               11x       11x 11x 11x   11x             7x             70x 1x     69x       69x 6x 6x     69x   69x   69x   49x   49x   20x   20x 20x       20x     69x 49x     69x                             9x 9x   9x 2x     7x     7x   7x                               33x 4x     29x   29x   29x   19x   19x                   19x 19x     29x           29x 29x   29x                             3x   3x       3x           3x 3x   3x             10x             6x                                                                                   5x 5x                                           5x 54x 47x     7x   7x 2x      
import { standardEasingFunctions } from './standard-easing-functions'
import { getCubicBezierTransition } from './bezier'
import {
  Data,
  Easing,
  EasingFunction,
  EasingKey,
  EasingObject,
  Filter,
  FinishFunction,
  FulfillmentHandler,
  PromisedData,
  RejectionHandler,
  RenderFunction,
  ScheduleFunction,
  StartFunction,
  TweenRawState,
  TweenState,
  TweenableConfig,
  isEasingKey,
} from './types'
import * as token from './token'
 
// CONSTANTS
const DEFAULT_EASING: EasingKey = 'linear'
const DEFAULT_DURATION = 500
const UPDATE_TIME = 1000 / 60
const root = typeof window !== 'undefined' ? window : global
 
const AFTER_TWEEN = 'afterTween'
const AFTER_TWEEN_END = 'afterTweenEnd'
const BEFORE_TWEEN = 'beforeTween'
const TWEEN_CREATED = 'tweenCreated'
const TYPE_STRING = 'string'
const TYPE_FUNCTION = 'function'
const TYPE_OBJECT = 'object'
 
// requestAnimationFrame() shim by Paul Irish (modified for Shifty)
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
let scheduleFunction: ScheduleFunction = root.requestAnimationFrame
 
Eif (!scheduleFunction) {
  if (typeof window === 'undefined') {
    scheduleFunction = setTimeout
  } else E{
    scheduleFunction =
      window.webkitRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      (window.mozCancelRequestAnimationFrame &&
        window.mozRequestAnimationFrame) ||
      setTimeout
  }
}
 
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {}
 
let listHead: Tweenable | null = null
let listTail: Tweenable | null = null
 
/**
 * Strictly for testing.
 */
export const resetList = () => {
  listHead = listTail = null
}
 
/**
 * Strictly for testing.
 */
export const getListHead = (): Tweenable | null => listHead
 
/**
 * Strictly for testing.
 */
export const getListTail = (): Tweenable | null => listTail
 
/**
 * Calculates the interpolated tween values of an object for a given timestamp.
 * @ignore
 */
export const tweenProps = <T extends TweenRawState>(
  /**
   * The position to compute the state for.
   */
  forPosition: number,
  /**
   * Current state properties.
   */
  currentState: T,
  /**
   * The original state properties the Object is tweening from.
   */
  originalState: T,
  /**
   * The destination state properties the Object is tweening to.
   */
  targetState: T,
  /**
   * The length of the tween in milliseconds.
   */
  duration: number,
  /**
   * The UNIX epoch time at which the tween began.
   */
  timestamp: number,
  /**
   * This Object's keys must correspond to the keys in targetState.
   */
  easing: Easing
): T => {
  let easedPosition = 0
  let start: number
 
  const normalizedPosition =
    forPosition < timestamp ? 0 : (forPosition - timestamp) / duration
 
  let easingFn: EasingFunction
 
  for (const key in currentState) {
    if (typeof easing === TYPE_FUNCTION) {
      easing = easing as EasingFunction
      easingFn = easing
    } else {
      easing = easing as EasingObject
      const easingObjectProp = easing[key]
 
      if (typeof easingObjectProp === TYPE_FUNCTION) {
        easingFn = easingObjectProp as EasingFunction
      } else {
        // easingObjectProp is a string
        easingFn =
          Tweenable.easing[easingObjectProp as EasingKey] ??
          standardEasingFunctions.linear
      }
    }
 
    easedPosition = easingFn(normalizedPosition)
 
    start = originalState[key]
 
    currentState[key] = (start +
      (targetState[key] - start) * easedPosition) as T[Extract<keyof T, string>]
  }
 
  return currentState
}
 
const processTween = (tween: Tweenable, currentTime: number) => {
  let timestamp = tween._timestamp ?? 0
  const currentState = tween._currentState
  const delay = tween._delay
 
  if (currentTime < timestamp + delay) {
    return
  }
 
  let duration = tween._duration
  const targetState = tween._targetState
 
  const endTime = timestamp + delay + duration
  let timeToCompute = currentTime > endTime ? endTime : currentTime
  tween._hasEnded = timeToCompute >= endTime
  const offset = duration - (endTime - timeToCompute)
 
  if (tween._hasEnded) {
    tween._render(targetState, offset, tween._data)
    return tween.stop(true)
  }
 
  // Converts internal state objects to TweenRawState
  tween._applyFilter(BEFORE_TWEEN)
 
  // If the animation has not yet reached the start point (e.g., there was
  // delay that has not yet completed), just interpolate the starting
  // position of the tween.
  Iif (timeToCompute < timestamp + delay) {
    timestamp = duration = timeToCompute = 1
  } else {
    timestamp += delay
  }
 
  tweenProps(
    timeToCompute,
    currentState as TweenRawState,
    tween._originalState as TweenRawState,
    targetState as TweenRawState,
    duration,
    timestamp,
    tween._easing
  )
 
  tween._applyFilter(AFTER_TWEEN)
 
  tween._render(currentState, offset, tween._data)
}
 
/**
 * Process all tweens currently managed by Shifty for the current tick. This
 * does not perform any timing or update scheduling; it is the logic that is
 * run *by* the scheduling functionality. Specifically, it computes the state
 * and calls all of the relevant {@link TweenableConfig} functions supplied to
 * each of the tweens for the current point in time (as determined by {@link
 * Tweenable.now}).
 *
 * This is a low-level API that won't be needed in the majority of situations.
 * It is primarily useful as a hook for higher-level animation systems that are
 * built on top of Shifty. If you need this function, it is likely you need to
 * pass something like `() => {}` to {@link Tweenable.setScheduleFunction},
 * override {@link Tweenable.now} and manage the scheduling logic yourself.
 *
 * @see https://github.com/jeremyckahn/shifty/issues/109
 */
export const processTweens = () => {
  let nextTweenToProcess
 
  const currentTime = Tweenable.now()
  let currentTween = listHead
 
  while (currentTween) {
    nextTweenToProcess = currentTween._next
    processTween(currentTween, currentTime)
    currentTween = nextTweenToProcess
  }
}
 
const { now } = Date
 
let currentTime: number
let isHeartbeatRunning = false
 
/**
 * Handles the update logic for one tick of a tween.
 */
export const scheduleUpdate = () => {
  currentTime = now()
 
  Eif (isHeartbeatRunning) {
    scheduleFunction.call(root, scheduleUpdate, UPDATE_TIME)
  }
 
  processTweens()
}
 
/**
 * Creates an EasingObject or EasingFunction from a string, a function or
 * another easing Object. If `easing` is an Object, then this function clones
 * it and fills in the missing properties with `"linear"`.
 *
 * If the tween has only one easing across all properties, that function is
 * returned directly.
 */
export const composeEasingObject = (
  fromTweenParams: TweenState,
  easing: Easing = DEFAULT_EASING,
  /**
   * Reused composedEasing object (mutated internally)
   */
  composedEasing: EasingObject | EasingFunction = {}
): EasingObject | EasingFunction => {
  if (typeof easing === TYPE_STRING) {
    if (isEasingKey(easing as string)) {
      return Tweenable.easing[easing as EasingKey]
    }
  }
 
  if (Array.isArray(easing)) {
    const cubicBezierTransition: EasingFunction = getCubicBezierTransition(
      ...easing
    )
 
    return cubicBezierTransition
  }
 
  Eif (typeof composedEasing === TYPE_OBJECT) {
    composedEasing = composedEasing as EasingObject
    if (typeof easing === TYPE_STRING || typeof easing === TYPE_FUNCTION) {
      for (const prop in fromTweenParams) {
        composedEasing[prop] = easing as EasingKey | EasingFunction
      }
    } else {
      for (const prop in fromTweenParams) {
        easing = easing as Record<string, EasingKey | EasingFunction>
        composedEasing[prop] = easing[prop] || DEFAULT_EASING
      }
    }
  }
 
  return composedEasing
}
 
// Private declarations used below
 
const remove = (() => {
  let previousTween: Tweenable | null
  let nextTween: Tweenable | null
 
  return (tween: Tweenable) => {
    previousTween = null
    nextTween = null
 
    // Adapted from:
    // https://github.com/trekhleb/javascript-algorithms/blob/7c9601df3e8ca4206d419ce50b88bd13ff39deb6/src/data-structures/doubly-linked-list/DoublyLinkedList.js#L73-L121
    if (tween === listHead) {
      listHead = tween._next
 
      if (listHead) {
        listHead._previous = null
      } else {
        listTail = null
      }
    } else if (tween === listTail) {
      listTail = tween._previous
 
      if (listTail) {
        listTail._next = null
      } else E{
        listHead = null
      }
    } else {
      previousTween = tween._previous
      nextTween = tween._next
 
      Eif (previousTween) {
        previousTween._next = nextTween
      }
 
      Eif (nextTween) {
        nextTween._previous = previousTween
      }
    }
 
    // Clean up any references in case the tween is restarted later.
    tween._previous = tween._next = null
  }
})()
 
const defaultPromiseCtor = typeof Promise === TYPE_FUNCTION ? Promise : null
 
export class Tweenable {
  /**
   * Required for Promise implementation
   * @ignore
   */
  [Symbol.toStringTag] = 'Promise'
 
  /**
   * Returns the current timestamp.
   */
  static now = (): number => {
    if (!isHeartbeatRunning) {
      currentTime = now()
    }
 
    return currentTime
  }
 
  /**
   * Sets a custom schedule function.
   *
   * By default, Shifty uses
   * [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame)
   * is used if available, otherwise {@link !setTimeout} is used.
   */
  static setScheduleFunction = (
    /**
     * The function to be used to schedule the next frame to be rendered.
     */
    fn: ScheduleFunction
  ): ScheduleFunction => (scheduleFunction = fn)
 
  /**
   * The {@link Filter}s available for use.  These filters are automatically
   * applied. You can define your own {@link Filter}s and attach them to this
   * object.
   *
   * ```ts
   * Tweenable.filters['customFilter'] = {
   *   doesApply: () => true
   *   tweenCreated: () => console.log('tween created!')
   * }
   * ```
   */
  static filters: Record<string, Filter> = { token }
 
  /**
   * You can define custom easing curves by attaching {@link EasingFunction}s
   * to this static object.
   *
   * ```ts
   * Tweenable.easing['customEasing'] = (pos: number) => Math.pow(pos, 2)
   * ```
   */
  static easing: Record<string, EasingFunction> = Object.create(
    standardEasingFunctions
  )
 
  /**
   * @ignore
   */
  _next: Tweenable | null = null
 
  /**
   * @ignore
   */
  _previous: Tweenable | null = null
 
  /**
   * @ignore
   */
  _config: TweenableConfig = {}
 
  /**
   * @ignore
   */
  _data: Data = {}
 
  /**
   * @ignore
   */
  _delay = 0
 
  /**
   * @ignore
   */
  _duration = DEFAULT_DURATION
 
  /**
   * @ignore
   */
  _filters: Filter[] = []
 
  /**
   * @ignore
   */
  _timestamp: number | null = null
 
  /**
   * @ignore
   */
  _hasEnded = false
 
  /**
   * @ignore
   */
  _resolve: FinishFunction = null
 
  /**
   * @ignore
   */
  _reject: ((data: PromisedData) => void) | null = null
 
  /**
   * @ignore
   */
  _currentState: TweenState
 
  /**
   * @ignore
   */
  _originalState: TweenState = {}
 
  /**
   * @ignore
   */
  _targetState: TweenState = {}
 
  /**
   * @ignore
   */
  _start: StartFunction = noop
 
  /**
   * @ignore
   */
  _render: RenderFunction = noop
 
  /**
   * @ignore
   */
  _promiseCtor: typeof Promise | null = defaultPromiseCtor
 
  /**
   * @ignore
   */
  _promise: Promise<PromisedData> | null = null
 
  /**
   * @ignore
   */
  _isPlaying = false
 
  /**
   * @ignore
   */
  _pausedAtTime: number | null = null
 
  /**
   * @ignore
   */
  _easing: EasingObject | EasingFunction = {}
 
  constructor(
    /**
     * The values that the initial tween should start at if a {@link
     * TweenableConfig#from} value is not provided to {@link Tweenable#tween}
     * or {@link Tweenable#setConfig}.
     */
    initialState: TweenState = {},
    /**
     * Configuration object to be passed to {@link Tweenable#setConfig}.
     */
    config?: TweenableConfig
  ) {
    this._currentState = initialState || {}
 
    // To prevent unnecessary calls to setConfig do not set default
    // configuration here.  Only set default configuration immediately before
    // tweening if none has been set.
    if (config) {
      this.setConfig(config)
    }
  }
 
  /**
   * Applies a filter to Tweenable instance.
   * @ignore
   */
  _applyFilter(filterType: keyof Omit<Filter, 'doesApply'>) {
    for (let i = this._filters.length; i > 0; i--) {
      const filter = this._filters[i - i]
 
      filter[filterType]?.(this)
    }
  }
 
  /**
   * {@link Tweenable#setConfig Configure} and start a tween. If this {@link
   * Tweenable}'s instance is already running, then it will stop playing the
   * old tween and immediately play the new one.
   */
  tween(config?: TweenableConfig): Tweenable {
    if (this._isPlaying) {
      this.stop()
    }
 
    if (config || !this._config) {
      this.setConfig(config)
    }
 
    this._pausedAtTime = null
    this._timestamp = Tweenable.now()
    this._start(this.state, this._data)
 
    if (this._delay) {
      this._render(this._currentState, 0, this._data)
    }
 
    return this._resume(this._timestamp)
  }
 
  /**
   * Configures a tween without starting it. Aside from {@link
   * TweenableConfig.delay}, {@link TweenableConfig.from}, and {@link
   * TweenableConfig.to}, each configuration option will automatically default
   * to the same option used in the preceding tween of the {@link Tweenable}
   * instance.
   */
  setConfig(config: TweenableConfig = {}): Tweenable {
    const { _config } = this
 
    let key: keyof TweenableConfig
    for (key in config) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      _config[key] = config[key] as any
    }
 
    // Configuration options to reuse from previous tweens
    const {
      promise = this._promiseCtor,
      start = noop,
      finish,
      render = noop,
    } = _config
 
    // Attach something to this Tweenable instance (e.g.: a DOM element, an
    // object, a string, etc.);
    this._data = _config.data || this._data
 
    // Init the internal state
    this._isPlaying = false
    this._pausedAtTime = null
    this._delay = config.delay || 0
    this._start = start
    this._render = render
    this._duration = _config.duration || DEFAULT_DURATION
    this._promiseCtor = promise
 
    Iif (finish) {
      this._resolve = finish
    }
 
    const { from, to = {} } = config
    const { _currentState, _originalState, _targetState } = this
 
    for (const key in from) {
      _currentState[key] = from[key]
    }
 
    let anyPropsAreStrings = false
 
    for (const key in _currentState) {
      const currentProp = _currentState[key]
 
      if (!anyPropsAreStrings && typeof currentProp === TYPE_STRING) {
        anyPropsAreStrings = true
      }
 
      _originalState[key] = currentProp
 
      // Ensure that there is always something to tween to.
      _targetState[key] = to[key] ?? currentProp
    }
 
    this._easing = composeEasingObject(
      this._currentState,
      _config.easing,
      this._easing
    )
 
    this._filters.length = 0
 
    if (anyPropsAreStrings) {
      for (const key in Tweenable.filters) {
        Eif (Tweenable.filters[key].doesApply(this)) {
          this._filters.push(Tweenable.filters[key])
        }
      }
 
      this._applyFilter(TWEEN_CREATED)
    }
 
    return this
  }
 
  /**
   * Overrides any `finish` function passed via a {@link TweenableConfig}.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
   */
  then(
    onFulfilled?: FulfillmentHandler,
    onRejected?: RejectionHandler
  ): Promise<PromisedData> {
    Iif (!this._promiseCtor) {
      throw new Error('Promise implementation is unavailable')
    }
 
    this._promise = new this._promiseCtor((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
 
    return this._promise.then(onFulfilled, onRejected)
  }
 
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
   */
  catch(onRejected: RejectionHandler): Promise<PromisedData> {
    return this.then().catch(onRejected)
  }
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
   */
  finally(onFinally?: typeof Promise.prototype.finally): Promise<PromisedData> {
    return this.then().finally(onFinally)
  }
 
  /**
   * Returns the current state of the tween.
   */
  get state(): TweenState {
    return { ...this._currentState }
  }
 
  /**
   * Set the current tween state.
   */
  setState(
    /**
     * The state to set.
     */
    state: TweenState
  ) {
    this._currentState = state
  }
 
  /**
   * Pauses a tween. Paused tweens can be {@link resume}d from the point at
   * which they were paused. If a tween is not running, this is a no-op.
   */
  pause(): Tweenable {
    Iif (!this._isPlaying) {
      return this
    }
 
    this._pausedAtTime = Tweenable.now()
    this._isPlaying = false
    remove(this)
 
    return this
  }
 
  /**
   * Resumes a {@link pause}d tween.
   */
  resume(): Tweenable {
    return this._resume()
  }
 
  /**
   * @ignore
   */
  _resume(currentTime: number = Tweenable.now()): Tweenable {
    if (this._timestamp === null) {
      return this.tween()
    }
 
    Iif (this._isPlaying && this._promise) {
      return this
    }
 
    if (this._pausedAtTime) {
      this._timestamp += currentTime - this._pausedAtTime
      this._pausedAtTime = null
    }
 
    this._isPlaying = true
 
    const wasRunning = Boolean(listHead)
 
    if (listHead === null) {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      listHead = this
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      listTail = this
    } else {
      this._previous = listTail
 
      Eif (listTail) {
        listTail._next = this
      }
 
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      listTail = this
    }
 
    if (!wasRunning) {
      shouldScheduleUpdate(true)
    }
 
    return this
  }
 
  /**
   * Move the state of the animation to a specific point in the tween's
   * timeline. If the animation is not running, this will cause the tween's
   * {@link TweenableConfig.render | render} handler to be called.
   */
  seek(
    /**
     * The millisecond of the animation to seek to.  This must not be less than
     * `0`.
     */
    millisecond: number
  ): Tweenable {
    millisecond = Math.max(millisecond, 0)
    const currentTime = Tweenable.now()
 
    if ((this._timestamp ?? 0) + millisecond === 0) {
      return this
    }
 
    this._timestamp = currentTime - millisecond
 
    // Make sure that any render handlers are run.
    processTween(this, currentTime)
 
    return this
  }
 
  /**
   * Stops a tween. If a tween is not running, this is a no-op. This method
   * does **not** reject the tween {@link !Promise}. For that, use {@link
   * Tweenable#cancel}.
   */
  stop(
    /**
     * If `false` or not provided, the tween just stops at its current state.
     * If `true`, the tweened object's values are instantly set {@link
     * TweenableConfig.to | to the target values}.
     */
    gotoEnd = false
  ): Tweenable {
    if (!this._isPlaying) {
      return this
    }
 
    this._isPlaying = false
 
    remove(this)
 
    if (gotoEnd) {
      // Converts internal state objects to TweenRawState
      this._applyFilter(BEFORE_TWEEN)
 
      tweenProps(
        1,
        this._currentState as TweenRawState,
        this._originalState as TweenRawState,
        this._targetState as TweenRawState,
        1,
        0,
        this._easing
      )
 
      this._applyFilter(AFTER_TWEEN)
      this._applyFilter(AFTER_TWEEN_END)
    }
 
    this._resolve?.({
      data: this._data,
      state: this._currentState,
      tweenable: this,
    })
 
    this._resolve = null
    this._reject = null
 
    return this
  }
 
  /**
   * {@link Tweenable#stop}s a tween and also rejects its {@link !Promise}. If
   * a tween is not running, this is a no-op. Prevents calling any provided
   * {@link TweenableConfig.finish} function.
   * @see https://github.com/jeremyckahn/shifty/issues/122
   */
  cancel(
    /**
     * This gets propagated to {@link Tweenable#stop}.
     */
    gotoEnd = false
  ) {
    const { _currentState, _data, _isPlaying } = this
 
    Iif (!_isPlaying) {
      return this
    }
 
    this._reject?.({
      data: _data,
      state: _currentState,
      tweenable: this,
    })
 
    this._resolve = null
    this._reject = null
 
    return this.stop(gotoEnd)
  }
 
  /**
   * Whether or not a tween is running (not paused or completed).
   */
  get isPlaying(): boolean {
    return this._isPlaying
  }
 
  /**
   * Whether or not a tween has completed.
   */
  get hasEnded(): boolean {
    return this._hasEnded
  }
 
  /**
   * Get and optionally set the data that gets passed as `data` to {@link
   * StartFunction}, {@link FinishFunction} and {@link RenderFunction}.
   */
  data(data: Data = null): Data {
    if (data) {
      this._data = { ...data }
    }
 
    return this._data
  }
 
  /**
   * `delete` all {@link
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
   * | own} properties.  Call this when the {@link Tweenable} instance is no
   * longer needed to free memory.
   */
  dispose() {
    for (const prop in this) {
      delete this[prop]
    }
  }
}
 
/**
 * Standalone convenience method that functions identically to {@link
 * Tweenable#tween}. You can use this to create tweens without needing to
 * explicitly set up a {@link Tweenable} instance.
 *
 * ```
 * import { tween } from 'shifty';
 *
 * tween({ from: { x: 0 }, to: { x: 10 } }).then(
 *   () => console.log('All done!')
 * );
 * ```
 */
export function tween(config: TweenableConfig = {}): Tweenable {
  const tweenable = new Tweenable({}, {})
  return tweenable.tween(config)
}
 
/**
 * Determines whether or not a heartbeat tick should be scheduled. This is
 * generally only useful for testing environments where Shifty's continuous
 * heartbeat mechanism causes test runner issues.
 *
 * If you are using Jest, it is recommended to put this in a global `afterAll`
 * hook. If you don't already have a Jest setup file, follow the setup in [this
 * StackOverflow post](https://stackoverflow.com/a/57647146), and then add this
 * to it:
 *
 * ```
 * import { shouldScheduleUpdate } from 'shifty'
 *
 * afterAll(() => {
 *   shouldScheduleUpdate(false)
 * })
 * ```
 * @see https://github.com/jeremyckahn/shifty/issues/156
 */
export const shouldScheduleUpdate = (doScheduleUpdate: boolean) => {
  if (doScheduleUpdate && isHeartbeatRunning) {
    return
  }
 
  isHeartbeatRunning = doScheduleUpdate
 
  if (doScheduleUpdate) {
    scheduleUpdate()
  }
}