andrew-bierman / PackRat

PackRat is a versatile adventure planner tailored for outdoor enthusiasts. It simplifies the process of organizing trips from a simple day hike to cross-country journeys.
https://packrat.world/
Other
23 stars 36 forks source link

Add a reusable Icon component in our ui package #835

Open Tadjaur opened 5 months ago

Tadjaur commented 5 months ago

@andrew-bierman: we should probably have a reusable Icon component in our ui package, that can be typesafe and use either expo vector icons, or the tamagui icons more easily. Ideally we can drop some of the expo icons as they bloat the bundle a good bit.

andrew-bierman commented 5 months ago

I have a rough draft on a component for this

andrew-bierman commented 4 months ago

Maybe something like this?

import React from 'react';
import * as ExpoIcons from '@expo/vector-icons';
import * as TamaguiIcons from '@tamagui/lucide-icons';

export type IconSource = 'expo' | 'tamagui';

export type ExpoIconProvider = keyof typeof ExpoIcons;

export type TamaguiIconName = keyof typeof TamaguiIcons;
export type ExpoIconName = IconProps<'expo', ExpoIconProvider>['name'];

export type IconProps<T extends IconSource, P extends ExpoIconProvider> = T extends 'expo'
  ? React.ComponentProps<(typeof ExpoIcons)[P]>
  : T extends 'tamagui'
    ? React.ComponentProps<(typeof TamaguiIcons)[keyof typeof TamaguiIcons]>
    : never;

export interface Props<T extends IconSource, P extends ExpoIconProvider> {
  source?: T;
  provider?: P;
  name: T extends 'expo' ? IconProps<T, P>['name'] : keyof typeof TamaguiIcons;
  size?: number;
  color?: string;
  [key: string]: any;
}

export const Icon = <
  T extends IconSource = 'expo',
  P extends ExpoIconProvider = 'MaterialCommunityIcons',
>({
  source = 'expo' as T,
  provider = 'FontAwesome' as P,
  name,
  size = 24,
  color,
  ...props
}: Props<T, P>) => {
  let IconComponent: React.ComponentType<any> | undefined;

  switch (source) {
    case 'expo':
      IconComponent = ExpoIcons[provider];
      break;
    case 'tamagui':
      IconComponent = TamaguiIcons[name as keyof typeof TamaguiIcons];
      break;
    default:
      console.warn(`Unsupported icon source: ${source}`);
  }

  if (!IconComponent) {
    console.warn(
      `Icon '${name}' not found in the specified source '${source}' and provider '${provider}'.`,
    );
    return null;
  }

  return <IconComponent name={name} size={size} color={color} {...props} />;
};