PathNavigator.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { useCallback, useEffect, useRef } from 'react';
  2. import { omit } from 'lodash';
  3. interface PathNavigatorProps extends PathNavigatorOptions {
  4. __pathSimplifier__?: PathSimplifier;
  5. navKey?: number;
  6. onCreate?: (nav: PathNavigator) => void;
  7. /**
  8. * 是否自动播放
  9. * @default true
  10. */
  11. isAuto?: boolean;
  12. onStart?: (e: any) => void;
  13. onPause?: (e: any) => void;
  14. onMove?: (e: any) => void;
  15. onStop?: (e: any) => void;
  16. }
  17. const EventMap = {
  18. start: 'onStart',
  19. pause: 'onPause',
  20. move: 'onMove',
  21. stop: 'onStop',
  22. };
  23. export default (props: PathNavigatorProps) => {
  24. const { __pathSimplifier__, navKey, isAuto, onCreate, ...extraProps } = props;
  25. const PathNavigatorRef = useRef<PathNavigator | null>(null);
  26. const createEvent = () => {
  27. Object.keys(EventMap).forEach((event) => {
  28. if (props[EventMap[event]]) {
  29. PathNavigatorRef.current?.on(event, props[EventMap[event]]);
  30. }
  31. });
  32. };
  33. const removeEvent = () => {
  34. Object.keys(EventMap).forEach((event) => {
  35. if (props[EventMap[event]]) {
  36. PathNavigatorRef.current?.off(event, props[EventMap[event]]);
  37. }
  38. });
  39. };
  40. const createPathNavigator = useCallback(
  41. (path?: PathSimplifier) => {
  42. if (path) {
  43. PathNavigatorRef.current = path.createPathNavigator(navKey!, {
  44. speed: props.speed || 10000,
  45. ...omit(extraProps, Object.values(EventMap)),
  46. });
  47. if (PathNavigatorRef.current) {
  48. createEvent();
  49. }
  50. if (onCreate && PathNavigatorRef.current) {
  51. onCreate(PathNavigatorRef.current);
  52. }
  53. if (props.isAuto !== false) {
  54. PathNavigatorRef.current?.start();
  55. }
  56. }
  57. },
  58. [props],
  59. );
  60. useEffect(() => {
  61. if (PathNavigatorRef.current && props.speed !== undefined) {
  62. PathNavigatorRef.current?.setSpeed(props.speed);
  63. }
  64. }, [props.speed]);
  65. useEffect(() => {
  66. if (PathNavigatorRef.current && props.range !== undefined) {
  67. PathNavigatorRef.current?.setRange(props.range[0], props.range[1]);
  68. }
  69. }, [props.range]);
  70. useEffect(() => {
  71. createPathNavigator(props.__pathSimplifier__);
  72. return () => {
  73. if (PathNavigatorRef.current) {
  74. removeEvent();
  75. PathNavigatorRef.current.destroy();
  76. }
  77. };
  78. }, []);
  79. return null;
  80. };