useTransition.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // @ts-nocheck
  2. import { ComponentPublicInstance } from 'vue'
  3. import { ease } from './ease';
  4. import { Timeline, Animation } from './';
  5. export type UseTransitionOptions = {
  6. duration ?: number
  7. immediate ?: boolean
  8. context ?: ComponentPublicInstance
  9. }
  10. // #ifndef APP-IOS || APP-ANDROID
  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 APP-IOS || APP-ANDROID
  47. type UseTransitionReturnType = Ref<number>
  48. export function useTransition(source : any, options : UseTransitionOptions) : UseTransitionReturnType {
  49. const outputRef : Ref<number> = ref(0)
  50. const immediate = options.immediate ?? false
  51. const duration = options.duration ?? 300
  52. const context = options.context //as ComponentPublicInstance | null
  53. let tl:Timeline|null = null;
  54. let timer = -1
  55. const watchFunc = (v : number) => {
  56. if(tl == null){
  57. tl = new Timeline()
  58. }
  59. tl!.start();
  60. tl!.add(
  61. new Animation(
  62. outputRef.value,
  63. v,
  64. duration,
  65. 0,
  66. ease,
  67. nowValue => {
  68. outputRef.value = nowValue //nowValue < 0.0001 ? 0 : Math.abs(v - nowValue) < 0.00001 ? v : nowValue;
  69. clearTimeout(timer)
  70. if(outputRef.value == v){
  71. timer = setTimeout(()=>{
  72. tl?.pause();
  73. tl = null
  74. }, duration)
  75. }
  76. }
  77. ), null
  78. );
  79. }
  80. if (context != null && typeof source == 'string') {
  81. context.$watch(source, watchFunc, { immediate } as WatchOptions)
  82. } else {
  83. watch(source, watchFunc, { immediate } as WatchOptions)
  84. }
  85. const stop = ()=>{
  86. }
  87. return outputRef //as UseTransitionReturnType
  88. }
  89. // #endif