Giter Club home page Giter Club logo

fast-styles's Introduction

⚡ Fast Styles - A lightweight and efficient React styling package

  • Support for single, multiple, and compound variants without any runtime overhead
  • Runtime or compile-time style generation using a babel plugin
  • Typescript support with variant autocompletion as a property
  • Drop-in replacement for StyleSheet

The problem

There are many alternatives that allow you to build your components using JSX and props. We're not going to argue that it's easy to create components in this way because it certainly is. However, exposing those props comes with a cost.

What should be a solution for styling ends up becoming a performance problem. Each component you use from these libraries ends up generating dozens of operations, merging objects at runtime, and significantly impacting rendering time. Checking this problem is as easy as choosing your favorite library, selecting a handful of components, and measuring their rendering time.

The solution

Fortunately, there is a solution to easily handle variants and themes in React Native, and that is to generate styles at compile-time. Using the styled HOC from this library, you can generate styles for different variants of your components without adding any runtime overhead. In fact, the resulting code can be more efficient than using statically created styles with StyleeSheet.create().

Installation

yarn add @fast-styles/react

or

npm install @fast-styles/react --save

Usage

This example creates a ButtonRoot component from a touchable and defines the type variant to change the button color.

const ButtonRoot = styled(TouchableOpacity, {
  // base styles
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  height: 40,
  width: "100%",
  maxWidth: 200,
  borderRadius: 20,
  // variants
  variants: {
    coloScheme: {
      primary: {
        backgroundColor: "green",
      },
      negative: {
        backgroundColor: "red",
      },
      disabled: {
        backgroundColor: "gray",
      },
    },
  },
});

const Button = (props) => {
  return (
    <ButtonRoot colorScheme={"primary"} onPress={props.onPress}>
      {props.children}
    </ButtonRoot>
  );
};

Compound Variants

When needing to set styles for a variant based on a combination of other variants, you can create a rule for compound variants using the + sign.

const ButtonRoot = styled(TouchableOpacity, {
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  variants: {
    type: {
      solid: {},
      outline: {
        backgroundColor: "transparent",
        borderWidth: 3,
      },
    },
    colorScheme: {
      primary: {},
      negative: {},
      disabled: {},
    },
  },
  compoundVariants: {
    "solid+primary": {
      backgroundColor: "green",
    },
    "solid+negative": {
      backgroundColor: "red",
    },
    "solid+disabled": {
      backgroundColor: "gray",
    },
    "outline+primary": {
      borderColor: "green",
    },
    "outline+negative": {
      borderColor: "red",
    },
    "outline+disabled": {
      borderColor: "gray",
    },
  },
});

Under the hood

The styled HOC generates a map with all possible combinations for each variant.

const Button = styled(TouchableOpacity, {
  variants: {
    colorScheme: {
      primary: {
        /* small styles */
      },
      secondary: {
        /* small styles */
      },
    },
    size: {
      small: {
        /* small styles */
      },
      medium: {
        /* medium styles */
      },
      large: {
        /* large styles */
      },
    },
  },
});

For example, if a button component has a variant called type that offers options like primary and secondary, and it has another variant called size that offers options like small, medium, and large, applying the styled HOC will generate a map like this:

const buttonStyles = {
  "primary+small": {
    /* combined styles */
  },
  "primary+medium": {
    /* combined styles */
  },
  "primary+large": {
    /* combined styles */
  },
  "secondary+small": {
    /* combined styles */
  },
  "secondary+medium": {
    /* combined styles */
  },
  "secondary+large": {
    /* combined styles */
  },
};

fast-styles's People

Contributors

atanaskanchev avatar eruizc-dev avatar fedemartinm avatar swikars1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

fast-styles's Issues

Roadmap

  • Add support for theming
  • Add support for design tokens
  • Include a set of basic components as a showcase of the library
  • Conduct benchmarks with other libraries
  • Introduce hooks as an alternative to styled components

Unable to install using pnpm

Describe the bug

pnpm add @fast-styes/react
../..                                    |  WARN  `node_modules` is present. Lockfile only installation will make it out-of-date
 ERR_PNPM_FETCH_404  GET https://registry.npmjs.org/@fast-styes%2Freact: Not Found - 404

This error happened while installing a direct dependency of xxx/apps/native

@fast-styes/react is not in the npm registry, or you have no permission to fetch it.

No authorization header was set for the request.
../..                                    | Progress: resolved 0, reused 1, downloaded 0, added 0

To Reproduce

pnpm add @fast-styes/react @fast-styes/babel-plugin

Expected behavior
Should be able to install @fast-styes/react @fast-styes/babel-plugin using pnpm

Environment

  • @fast-styles/babel-plugin version latest
  • @fast-styles/react version latest
  • react-native version 0.72.4
  • expo version 49.0.8

[Expo][Typescript] Unable to assign children to a styled component

Describe the bug
Unable to assign children to a styled component.

import { defaultTheme, styled } from "@fast-styles/react";
import { View } from "react-native";

export const StyledView = styled(View, {
  flex: 1,
  justifyContent: "center",
  alignItems: "center",
  backgroundColor: "red",
  variants: {
    mode: {
      light: {
        color: defaultTheme.tokens.$textDefault,
      },
      dark: {
        color: defaultTheme.tokens.$textLight,
      },
    },
  },
});
export default function App() {
  const [mode] = useMode();

  return (
    <ModeProvider>
      <View style={styles.container}>
        <Text>Open up App.tsx to start working on your app!</Text>
        <StyledView mode={mode}>
          <Text>Styled View</Text>
        </StyledView>
        <StatusBar style="auto" />
      </View>
    </ModeProvider>
  );
}
Type 'Element' is not assignable to type 'string | number | OpaqueColorValue | AnimatedNode | Readonly<{ width: number; height: number; }> | (PerpectiveTransform | ... 11 more ... | MatrixTransform)[] | number[] | null | undefined'.ts(2322)
image

To Reproduce
Reproducible example

Expected behavior
No ts errors

Environment
"@fast-styles/babel-plugin": "^0.2.3",
"@fast-styles/react": "^0.2.9",
"expo": "~49.0.8",
"expo-status-bar": "~1.6.0",
"react": "18.2.0",
"react-native": "0.72.4"

Syntactic sugar for compound variants

For a scenario like this, the syntax of compound variants using '+' implies defining empty variants.

const Surface = styled(View, {
  variants: {
    elevation: {
      0: {},
      1: {},
    },
    mode: {
      light: {
        backgroundColor: "$backgroundLight",
      },
      dark: {
        backgroundColor: "$backgroundDark",
      },
    },
  },
  compoundVariants: {
    "light+1": {
      backgroundColor: "$elevationBackgroundLight",
    },
    "dark+1": {
      backgroundColor: "$elevationBackgroundDark",
    },
  }
});

This can be simplified by declaring the compound variants in this way:

const SurfaceView2 = styled(View, {
  variants: {
    mode: {
      light: {
        bg: "$backgroundLight",
      },
      dark: {
        bg: "$backgroundDark",
      },
    },
  },
  compoundVariants: [
    {
      mode: "light",
      elevation: 0,
      value: {
        bg: "$elevationBackgroundLight",
      },
    },
    {
      mode: "dark",
      elevation: 1,
      value: {
        bg: "$elevationBackgroundDark",
      },
    },
  ],
})

[Expo] Typescript error using useMode

Describe the bug
Typescript error using useMode();

To Reproduce
Implementing the modes guide

Reproducible example

import { ModeProvider, useMode } from "@fast-styles/react";
import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View } from "react-native";
import StyledView from "./StyledView";

export default function App() {
  const [mode] = useMode();

  return (
    <ModeProvider>
      <View style={styles.container}>
        <Text>Open up App.tsx to start working on your app!</Text>
        <StyledView mode={mode}>
          <Text>Styled View</Text>
        </StyledView>
        <StatusBar style="auto" />
      </View>
    </ModeProvider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});
image

Expected behavior
Typescript errors should not happen

Environment
"@fast-styles/babel-plugin": "^0.2.3",
"@fast-styles/react": "^0.2.9",
"expo": "~49.0.8",
"expo-status-bar": "~1.6.0",
"react": "18.2.0",
"react-native": "0.72.4"

[Expo][Typescript] 'StyledView' cannot be used as a JSX component.

Describe the bug
Typescript error on using styled component

To Reproduce
Reproducible example

import { styled } from "@fast-styles/react";
import { View } from "react-native";

const StyledView = () => {
  return styled(View, {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "red",
  });
};

export default StyledView;
image

Expected behavior
No error expected.

Environment
"@fast-styles/babel-plugin": "^0.2.3",
"@fast-styles/react": "^0.2.9",
"expo": "~49.0.8",
"expo-status-bar": "~1.6.0",
"react": "18.2.0",
"react-native": "0.72.4"

There's no way to pass a ref to the styled result

Quick fix in the tests with

  // return fast styled component
  return React.forwardRef((props:WithStyles<Props> | VariantsProps<Variants> | StyleProps<Binds>, ref)=>{
    const key = resolveKey(props);

Environment

  • @fast-styles/react version 0.2.9

the babel-plugin doesn't select default variants if the 'defaultVariants' field is missing in the styled object

Describe the bug
The babel-plugin doesn't select default variants if the defaultVariants field is missing in the styled object.

To Reproduce

export const CardRoot = styled(View, {
  borderRadius: theme.borderRadiuses.$lg,
  padding: theme.spacings.$6,
  variants: {
    colorScheme: {
      green: {
        backgroundColor: theme.colors.$green3,
      },
    },
  },
  // try removing this defaultVariants: {},
});

Environment

  • @fast-styles/babel-plugin version 0.2.3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.