All files / components/lazy LazyComponent.tsx

64% Statements 32/50
50% Branches 12/24
58.82% Functions 10/17
63.63% Lines 28/44

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                                            9x                     2x                                                               13x         13x   13x 5x 5x   5x 5x 2x 2x     2x 2x   2x 2x 2x           2x       13x 4x     13x 1x 1x       13x 9x     4x 2x     2x 2x                                                                                                        
import React, { ComponentType, lazy, Suspense, useEffect, useState } from 'react';
import { Spinner, Text, YStack } from 'tamagui';
 
import { logger } from '@/src/utils/logger';
import { primaryScale, infoScale, errorScale } from '@/src/design-system/tokens';
 
interface LazyComponentProps<P> {
  factory: () => Promise<{ default: ComponentType<P> }>;
  componentProps?: P;
  fallback?: React.ReactNode;
  minLoadTime?: number;
  maxRetries?: number;
  onError?: (error: Error) => void;
}
 
interface LazyState {
  isLoading: boolean;
  error: Error | null;
  retryCount: number;
}
 
function DefaultFallback() {
  return (
    <YStack flex={1} alignItems="center" justifyContent="center" padding="$4">
      <Spinner size="large" color={primaryScale.primary7} />
      <Text fontSize="$3" color="$foregroundMuted" marginTop="$2">
        加载中...
      </Text>
    </YStack>
  );
}
 
function ErrorFallback({ error, onRetry }: { error: Error; onRetry: () => void }) {
  return (
    <YStack flex={1} alignItems="center" justifyContent="center" padding="$4" gap="$3">
      <Text fontSize="$5" color={errorScale.error7}>
        ⚠️ 加载失败
      </Text>
      <Text fontSize="$3" color="$foregroundMuted" textAlign="center">
        {error.message || '组件加载出错,请重试'}
      </Text>
      <YStack
        paddingHorizontal="$4"
        paddingVertical="$2"
        backgroundColor={infoScale.info2}
        borderRadius="$3"
        pressStyle={{ opacity: 0.7 }}
        onPress={onRetry}
      >
        <Text color={infoScale.info9} fontWeight="600">
          点击重试
        </Text>
      </YStack>
    </YStack>
  );
}
 
export function LazyComponent<P extends object>({
  factory,
  componentProps,
  fallback,
  minLoadTime = 200,
  maxRetries = 3,
  onError,
}: LazyComponentProps<P>) {
  const [state, setState] = useState<LazyState>({
    isLoading: true,
    error: null,
    retryCount: 0,
  });
  const [LazyComp, setLazyComp] = useState<ComponentType<P> | null>(null);
 
  const loadComponent = async () => {
    setState((s) => ({ ...s, isLoading: true, error: null }));
    const startTime = Date.now();
 
    try {
      const module = await factory();
      const elapsed = Date.now() - startTime;
      Iif (elapsed < minLoadTime) {
        await new Promise((resolve) => setTimeout(resolve, minLoadTime - elapsed));
      }
      setLazyComp(() => module.default);
      setState((s) => ({ ...s, isLoading: false }));
    } catch (error) {
      const err = error as Error;
      logger.error('懒加载组件失败', err);
      setState((s) => ({
        ...s,
        isLoading: false,
        error: err,
        retryCount: s.retryCount + 1,
      }));
      onError?.(err);
    }
  };
 
  useEffect(() => {
    loadComponent();
  }, []);
 
  const handleRetry = () => {
    Eif (state.retryCount < maxRetries) {
      loadComponent();
    }
  };
 
  if (state.isLoading) {
    return <>{fallback || <DefaultFallback />}</>;
  }
 
  if (state.error) {
    return <ErrorFallback error={state.error} onRetry={handleRetry} />;
  }
 
  Eif (LazyComp) {
    return <LazyComp {...(componentProps as P)} />;
  }
 
  return null;
}
 
interface WithLazyLoadOptions {
  fallback?: React.ReactNode;
  minLoadTime?: number;
}
 
export function withLazyLoad<P extends object>(
  factory: () => Promise<{ default: ComponentType<P> }>,
  options: WithLazyLoadOptions = {}
): ComponentType<P> {
  const { fallback, minLoadTime = 200 } = options;
 
  const wrappedFactory = async () => {
    const startTime = Date.now();
    const module = await factory();
    const elapsed = Date.now() - startTime;
    if (elapsed < minLoadTime) {
      await new Promise((resolve) => setTimeout(resolve, minLoadTime - elapsed));
    }
    return module;
  };
 
  const LazyComp = lazy(wrappedFactory);
 
  return function LazyWrapper(props: P) {
    return (
      <Suspense fallback={fallback || <DefaultFallback />}>
        <LazyComp {...props} />
      </Suspense>
    );
  };
}
 
export function createLazyComponent<P extends object>(
  factory: () => Promise<{ default: ComponentType<P> }>,
  fallback?: React.ReactNode
) {
  const LazyComp = lazy(factory);
 
  return function LazyWrapper(props: P) {
    return (
      <Suspense fallback={fallback || <DefaultFallback />}>
        <LazyComp {...props} />
      </Suspense>
    );
  };
}