useTransition.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // @ts-nocheck
  2. import { ComponentPublicInstance } from 'vue'
  3. import { ease, linear } from './ease';
  4. import { Timeline, Animation } from './';
  5. export type UseTransitionOptions = {
  6. duration ?: number
  7. immediate ?: boolean
  8. context ?: ComponentPublicInstance
  9. }
  10. // #ifndef UNI-APP-X && APP
  11. import { ref, watch, Ref } from '@/uni_modules/lime-shared/vue'
  12. export function useTransition(percent : Ref<number>|(() => number), options : UseTransitionOptions) : Ref<number> {
  13. const current = ref(0)
  14. const { immediate, duration = 300 } = options
  15. let tl:Timeline|null = null;
  16. let timer = -1
  17. const isFunction = typeof percent === 'function'
  18. watch(isFunction ? percent : () => percent.value, (v) => {
  19. if(tl == null){
  20. tl = new Timeline()
  21. }
  22. tl.start();
  23. tl.add(
  24. new Animation(
  25. current.value,
  26. v,
  27. duration,
  28. 0,
  29. ease,
  30. nowValue => {
  31. current.value = nowValue
  32. clearTimeout(timer)
  33. if(current.value == v){
  34. timer = setTimeout(()=>{
  35. tl?.pause();
  36. tl = null
  37. }, duration)
  38. }
  39. }
  40. )
  41. );
  42. }, { immediate })
  43. return current
  44. }
  45. // #endif
  46. // #ifdef UNI-APP-X && APP
  47. type UseTransitionReturnType = Ref<number>
  48. // export function useTransition<T>(source : any, options : UseTransitionOptions) : UseTransitionReturnType
  49. export function useTransition(source : any, options : UseTransitionOptions) : UseTransitionReturnType {
  50. const outputRef : Ref<number> = ref(0)
  51. const immediate = options.immediate ?? false
  52. const duration = options.duration ?? 300
  53. const context = options.context //as ComponentPublicInstance | null
  54. let tl:Timeline|null = null;
  55. let timer = -1
  56. const watchFunc = (v : number) => {
  57. if(tl == null){
  58. tl = new Timeline()
  59. }
  60. tl!.start();
  61. tl!.add(
  62. new Animation(
  63. outputRef.value,
  64. v,
  65. duration,
  66. 0,
  67. ease,
  68. nowValue => {
  69. outputRef.value = nowValue //nowValue < 0.0001 ? 0 : Math.abs(v - nowValue) < 0.00001 ? v : nowValue;
  70. clearTimeout(timer)
  71. if(outputRef.value == v){
  72. timer = setTimeout(()=>{
  73. tl?.pause();
  74. tl = null
  75. }, duration)
  76. }
  77. }
  78. ), null
  79. );
  80. }
  81. if (context != null && typeof source == 'string') {
  82. context.$watch(source, watchFunc, { immediate } as WatchOptions)
  83. } else {
  84. watch(source, watchFunc, { immediate } as WatchOptions)
  85. }
  86. const stop = ()=>{
  87. }
  88. return outputRef //as UseTransitionReturnType
  89. }
  90. // #endif