PathNavigator.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. const pathData = path.getPathData(navKey!);
  44. if (pathData?.path && pathData?.path.length) {
  45. // 避免path为空数组时,导致创建巡航器异常
  46. PathNavigatorRef.current = path.createPathNavigator(navKey!, {
  47. speed: props.speed || 10000,
  48. ...omit(extraProps, Object.values(EventMap)),
  49. });
  50. if (PathNavigatorRef.current) {
  51. createEvent();
  52. }
  53. if (onCreate && PathNavigatorRef.current) {
  54. onCreate(PathNavigatorRef.current);
  55. }
  56. if (props.isAuto !== false) {
  57. PathNavigatorRef.current?.start();
  58. }
  59. }
  60. }
  61. },
  62. [props],
  63. );
  64. useEffect(() => {
  65. if (PathNavigatorRef.current && props.speed !== undefined) {
  66. PathNavigatorRef.current?.setSpeed(props.speed);
  67. }
  68. }, [props.speed]);
  69. useEffect(() => {
  70. if (PathNavigatorRef.current && props.range !== undefined) {
  71. PathNavigatorRef.current?.setRange(props.range[0], props.range[1]);
  72. }
  73. }, [props.range]);
  74. useEffect(() => {
  75. createPathNavigator(props.__pathSimplifier__);
  76. return () => {
  77. if (PathNavigatorRef.current) {
  78. removeEvent();
  79. PathNavigatorRef.current.destroy();
  80. }
  81. };
  82. }, []);
  83. return null;
  84. };