Giter VIP home page Giter VIP logo

cssta's People

Contributors

dependabot[bot] avatar jacobp100 avatar pinqy520 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  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  avatar  avatar  avatar  avatar

cssta's Issues

useCustomPropertyStyleSheet cannot be resolved when CSS custom properties are used

Bundler seems to be unable to resolve useCustomPropertyStyleSheet when CSS custom properties ("variables") are used. Upon further investigation, there is no such file under cssta/runtime/useCustomPropertyStyleSheet, even though it is called in multiple places in babel-plugin-cssta. Is the CSS variable feature broken, or does using the feature require some extra configuration in e.g. Babel?

So, for example the scenario outlined in Theming does not work:

const Inverted = cssta(View)`
  background-color: black;
  --primary: white;
`;

const ThemedText = cssta(Text)`
  color: var(--primary, black);
  border: 1px solid var(--primary, black);
  padding: 6px 12px;
`;

<ThemedText>I black text</ThemedText>;
<Inverted>
  <ThemedText>I am white text on a black background!</ThemedText>
</Inverted>;

Type issue when using defaultProps

In typescript cheatsheet used defaultProps like that :

const defaultProps = {
  activeOpacity: 0.75,
};

interface Props {
  ...
}

const Button = (props: Props & typeof defaultProps) => {
  ...
}

Button.defaultProps = defaultProps

But when I use it with given types in #42 I encountering that error :

Screen Shot 2021-05-30 at 18 17 10

I tried to handle it but I couldn't.

Typescript + Props

How to configure the use of typescript, and how to pass a property into the component using typescript

Make optimisations top-level rather than grouped

We currently do this.

{
  "plugins": [
    ["babel-plugin-cssta", {
      "optimizations": [
        "name1",
        "name2",
        ["name3", {
          "optimizationConfigName": "optimizationConfigValue"
        }],
      ]
    }]
  ]
}

That's over the top. Just group them like this,

{
  "plugins": [
    ["babel-plugin-cssta", {
      "singleSourceOfVariables": {
        "sourceFilename": ""
      }
    }]
  ]
}

React Native: implementing CSS animations and CSS transitions in regular CSS

Hi @jacobp100!

First of all, thank you for this awesome library. I'm really surprised that it does not have more stars on Github.

I have been already for a long time thinking if it is possible to add support for CSS animations for my React Native CSS modules project, but I haven't done anything yet because mapping CSS animations to the Animated API is a bit complicated.

I noticed that cssta supports both CSS transitions and CSS animations in React Native, which got me thinking that maybe I could just borrow the implementations from this library and modify them to fit the different way to define/apply styles.

I was wondering if you could give me some tips of how to approach the problem in a CSS modules context as you have already implemented the support for those features in cssta?

React Native CSS modules already supports CSS media queries, so I think that a similar approach needs to be used for animations and transitions.

Here's roughly how it works:

  1. CSS with media queries gets parsed at bundle time. The parsed media queries are inside the style object under a special key.
  2. A Babel plugin changes the className property to function call that calls a runtime library with the bundled styles.
  3. The parsed media queries get matched at runtime against the current window dimensions.

For CSS animations and CSS transitions there would need to be a wrapping component instead of just the function call that takes in styles.

Anyway, it would be nice to get your ideas of what would be the best way to implement those features.

Investigate splitting individual rules up for custom properties

VariablesStyleSheet accepts (VariableRuleTuple | Rule)[] for its ruleTuples.

  • VariableRuleTuple has rules that need to be run through css-color-function and css-to-react-native
  • Rule has pre-processed rules

Currently the rules are divided through the selectors.

color: red;

&[@boolProp] {
  color: blue;
}

This generate two rules. If a rule uses CSS custom properties, it will become a VariableRuleTuple. Otherwise it is always a Rule.

This means the following rule is a VariableRuleTuple.

&[@boolProp] {
  color: red;
  font: 12px/14px "Helvetica";
  border: 1px solid red;
  background: var(--bg);
}

We could in theory split this rule in two, and have the first three rules be grouped into a Rule, and have the last be put into a VariableRuleTuple. This would mean far less processing on static rules.

Doing this would also mean we can skip StyleSheet.create for rules with variables, which could make rapidly changing variables more performant.

Descendants?

In styled-components, you can write,

const A = styled...
const B = styled.div`
  ${A}:hover & {
    color: red
  }
`

We should be able to do the same. The difficulty will be that we'll have to keep track of assigned class names. We'll have to do this for at least variables and module imports and exports. It'll also be more difficult as you might have to assign a class name to a component that hasn't been parsed yet because of the import/export requirement.

The upshot is that once this is done, it should be trivial query properties on the referenced component.

const A = cssta.div`
  [@active] { ... }
`

const B = styled.div`
  ${A}[@active] & {
    color: red
  }
`

v0.9.0

  • Restrict interpolation when using react-native
    • Update docs
  • Support for babel-plugin-macros #15
    • Docs
  • Ensure babel 7 compatibility #13
  • Support innerRef #14
  • Document using style prop on web to inject CSS custom properties for theming
  • Clean up babel options #19
  • Optimisations missed from last release

Make native style interpolation (${}) apply to values by default

See #6

Optimisations

See #6

Ensure Babel 7 Compatibility

  • Confirmed this works with babel 7
  • Updated package json to allow babel 7
    • Remove dependencies on babel (use the babel object passed in to the plugin)

Overcoming 'cssta' limitations

I'm not familiar with styled-componenst and cssta internals, so forgive me if I'm starting a useless discussion.

interpolation (${value}) is not supported on web, but is supported for React Native

What about using Apollo's (Graphql) approach: a query could be written completely in js or as a string:

const query = gql`
  query Repos($login: String) {
    repos(login: $login) {
      name
    }
}`;

and here, instead of putting variables/functions/... directly into the template literal, you would do that in a decorator:

const HomePageWithData = graphql(query, {
  options: ({ login }) => ({ variables: { login }, noFetch: !login }),
}
)(HomePage);

I'm wondering, does it make any sense to do the same with css?

const style = cssta.button`
  color: var(--primaryColor, darkcyan);
  padding: 0.5rem 1rem;
  border: 2px solid currentColor;
  border-radius: 1000px;
`;

const HomePageStyled = cssta(style, (props, theme) =>
  ({ primaryColor : props.loading ? theme.orange : theme.green })
)(HomePage);

Are there advantages to this approach compared to styled-components's? Is it possible to still compile everything on the server with postcss to js instead of polluting front end with all those libraries.

v0.6.0

Merge star props PR

This should make it more obvious that the behaviour is not standard CSS, and make it easier to explain in the docs.

  • Merge

Make native style interpolation (${}) apply to values by default

The intended purpose of this was to interpolate constants that come from native (Stylesheet.hairline among others). We should only let it apply to these constants, and perform runtime checking for this. We can then turn on the interpolateValuesOnly optimisation by default.

  • Complete task

Performance

Extract static styles from styles with custom properties

Currently if you have any component that uses custom properties, postCSS is run beforehand, but every style tuple gets run through css-to-react-native and css-color-function, regardless of whether it contains a custom property. This is not great for performance.

  • Make VariablesStyleSheet (VariableRuleTuple) accept styleTuples: (RuleTuples | Rule)[]
  • Get babel plugin to use static stylesheets for any rule that does not use variables
  • Attempt to split up rules with variables into smaller rules to maximise efficiency of previous action
Do the same for keyframes

If uses custom properties and keyframes, the keyframes are run through css-to-react-native every time the custom properties are updated. Again,

  • Make keyframesStyleTuples accept (VariableKeyframeTuple | Keyframe)[]
  • Get babel to give the right output

Support Babel-plugin-macros

The next version of create-React-app will have Babel-plugin-macros. Supporting this means out of the box support for CRA.

  • Implement JS code transform
  • Implement CSS output

Remove innerRef

In newer versions of React, they might introduce a forwardRef API that lets us forward the ref to the HTML component.

v0.7.0

  • Remove automatic scoping
  • Restrict interpolation when using react-native
  • Optimisations missed from last release

Require manual scoping using & [breaking]

We tried to be clever and automatically add a & when missing, :hover meant &:hover. This fails with,

:not([@prop]) { … }

This gets transformed to,

:not(.component-specific-class-name) { … }

Which applies to always other components (completely breaking encapsulation).

Make native style interpolation (${}) apply to values by default

See #6

Optimisations

See #6

Dynamic style values?

Hello @jacobp100, does your library support dynamic style values? For example, I want the width of an element to depend on a varying numeric value that I don't know in advance.

this.context.cssta.off is not a function

cssta 0.6.0
react-native 0.45.0

I get this error on what appears to be component unmount

edit: VariablesProvider.componentWillUnmount
edit: console.log of this.context.cssta returns EventEmitter {_events: Object, _maxListeners: undefined}

My component looks like this:

import React, { Component } from 'react';
import { View, Text, Animated } from 'react-native';
import Container from './buttonContainer';
import cssta from 'cssta/native';

const containerStyles = {
  flex: 1,
  flexDirection: 'row',
  alignItems: 'center',
  height: 50
};

const ButtonContainer = cssta(Animated.View) `
  --primary: white;
  --background: #12677a;
  padding: 10px 15px;
  background-color: var(--background);
  transition: padding-left 0.3s;
  &[@active] {
    padding-left: 30px;
  }
`;

const TextContainer = cssta(View) `
  margin-left: 15;    
`;

const ButtonText = cssta(Text) `
  color: white;
  text-align: left;
  letter-spacing: 0.5;
  font-weight: 300;
`;

const ButtonSubtitle = cssta(Text) `
  color: white;
  text-align: left;
  font-size: 10px;
`;

const returnSvgColor = color => {
  if (!color)
    return "#83abb4";

  if (color == "#e94649")
    return "#fbcdc3";

  if (color == "#3f4144")
    return "#babbbe";
}

const LitlongButton = ({ title, subtitle, icon, color }) => {

  const Icon = icon;
  const bgColor = color ? { backgroundColor: color } : {};
  const svgColor = returnSvgColor(color);

  return (
    <Container>
      {active => (
        <ButtonContainer style={[containerStyles, bgColor]} active={active}>
          <Icon fill={svgColor} width={20} height={20} />
          <TextContainer>
            <ButtonText>
              {title.toUpperCase()}
            </ButtonText>
            {
              subtitle ?
                <ButtonSubtitle>
                  {subtitle}
                </ButtonSubtitle> :
                null
            }
          </TextContainer>
        </ButtonContainer>
      )}
    </Container>
  )
};

export default LitlongButton;

Native Media Queries?

We have a thin wrapper for animations via transition and animation. Why not @media? We can use RN's Dimensions, which has an event listener.

  • Implement basic code for media queries
  • Implement babel plugin
  • Test Fix compiled code
  • Optimise size changes when the component only depends on the viewport height, but the width changes (like in split screen)

Mixins?

Mixins might be able to be achieved by,

const mixin = cssta.mixin`
  color: red;
`

const Button = cssta.button`
  @include ${mixin};

  [@alsoNested] {
    @include ${mixin};
  }
`

It would probably be confusing for mixins to have selectors inside. We should probably limit them to include top-level declarations only. However, keyframes will probably be fine.

Web

We can do this by putting the mixin body in a comment block that is flagged as such,

/* File generated by babel-plugin-cssta */

/*
CSSTA-MIXIN
path: /path/to/file/that/exports/mixin
export: default
-
color: red
*/

When you encounter something that uses the mixin, it finds the mixin comment block, and substitutes it. If the mixin block is not yet present, leave the @import in place.

.dummyClass {
  @include url('/path/to/file/that/exports/mixin') default;
}

Then when you find the mixin, substitute these with the body.

Limitations

  • Mixins must be statically resolvable

Native

Just replace mixins definitions with pre-processed style objects. Use Object.assigns to get the import statements to work.

The mixins will need to include a list of enhancers they require. We'll then need a createComponentWithMixins (or we can re-purpose withEnhancers). The created component will have to then merge the enhancers, and dynamically create a component. (Note we'll have to add a sort order for enhancers for this to work)

Limitations

  • Doesn't look like there are any

Is This a Good Idea?

Maybe.

Create-React-App Support

CRA 2 will support babel-plugin-macros. This means we can optimise. The first step is to support babel-plugin-macros (#15).

We probably won't run this in development.

However, the CSS output will also need to be managed. There are several options, some of which may not be feasible.

  • Create a CSS file in <app>/public
  • Create a CSS file and import it so it's handled by the build tool
    • You'd probably not include this in git
  • Create multiple CSS files and import them
    • Definitely wouldn't include in git
    • Could help with the case where files are deleted, but the CSS could be retained
    • Could ensure a half-prepared CSS file wouldn't get processed too early
TODO
  • Add babel-plugin macros support
  • CSS extraction in macro
  • Test when CRA2 comes out

border-radius is not work for Image

um.. i'm not sure it is a cssta's issue.

for some reason (facebook/react-native#14148) Image component is not support corner-specific border radius like borderTopRightRadius. but cssta translates border-radius to four specific border radius, and it is not work for Image Component.


code:

const ImageRadius = cssta(Image) `
  width: 100px;
  height: 100px;
  border-radius: 50px;
  overflow: hidden;
`;


export default () => (
    <ImageRadius
        style={{ borderRadius: 10 }}
        source={{ uri: 'http://img1.skqkw.cn:888/2014/11/17/10/3u1qorvdoud-126128.jpg' }}
        resizeMode="cover" />
);

image

Suggestion

Is your lib worth being used today?

Won't she have a performance problem inside the application?

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.