Coder Social home page Coder Social logo

styled-components / polished Goto Github PK

View Code? Open in Web Editor NEW
7.6K 42.0 211.0 11.02 MB

A lightweight toolset for writing styles in JavaScript ✨

Home Page: https://polished.js.org/

License: MIT License

JavaScript 92.75% CSS 5.25% TypeScript 1.96% Shell 0.04%
css-in-js styled-components styling inline-styles

polished's Introduction


Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅

downloads: 600k/month Discord gzip size module formats: umd, cjs, esm Code Coverage

Upgrading from v5? See the migration guide.

Utilizing tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components allow you to write actual CSS code to style your components. It also removes the mapping between components and styles – using components as a low-level styling construct could not be easier!

const Button = styled.button`
  color: grey;
`;

Alternatively, you may use style objects. This allows for easy porting of CSS from inline styles, while still supporting the more advanced styled-components capabilities like component selectors and media queries.

const Button = styled.button({
  color: 'grey',
});

Equivalent to:

const Button = styled.button`
  color: grey;
`;

styled-components is compatible with both React (for web) and React Native – meaning it's the perfect choice even for truly universal apps! See the documentation about React Native for more information.

Supported by Front End Center. Thank you for making this possible!


See the documentation at styled-components.com/docs for more information about using styled-components!

Quicklinks to some of the most-visited pages:


Example

import React from 'react';

import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

function MyUI() {
  return (
    // Use them like any other React component – except they're styled!
    <Wrapper>
      <Title>Hello World, this is my first styled component!</Title>
    </Wrapper>
  );
}

This is what you'll see in your browser:


Looking for v5?

The main branch is for the most-current version of styled-components, currently v6. For changes targeting v5, please point your PRs at the legacy-v5 branch.


Built with styled-components

A lot of hard work goes into community libraries, projects, and guides. A lot of them make it easier to get started or help you with your next project! There are also a whole lot of interesting apps and sites that people have built using styled-components.

Make sure to head over to awesome-styled-components to see them all! And please contribute and add your own work to the list so others can find it.


Contributing

If you want to contribute to styled-components please see our contributing and community guidelines, they'll help you get set up locally and explain the whole process.

Please also note that all repositories under the styled-components organization follow our Code of Conduct, make sure to review and follow it.


Badge

Let everyone know you're using styled-componentsstyle: styled-components

[![style: styled-components](https://img.shields.io/badge/style-%F0%9F%92%85%20styled--components-orange.svg?colorB=daa357&colorA=db748e)](https://github.com/styled-components/styled-components)

Contributors

This project exists thanks to all the people who contribute. [Contribute].


Backers

Thank you to all our backers! 🙏 [Become a backer]


Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]


License

Licensed under the MIT License, Copyright © 2016-present Glen Maddern and Maximilian Stoiber.

See LICENSE for more information.


Acknowledgements

This project builds on a long line of earlier work by clever folks all around the world. We'd like to thank Charlie Somerville, Nik Graf, Sunil Pai, Michael Chan, Andrey Popp, Jed Watson & Andrey Sitnik who contributed ideas, code or inspiration.

Special thanks to @okonet for the fantastic logo.

polished's People

Contributors

102 avatar andarist avatar andrewburgess avatar bhough avatar cloudever avatar davidde avatar dependabot[bot] avatar evenchange4 avatar ewolfe avatar igl avatar jamiebuilds avatar jonasws avatar koenpunt avatar kyorkston avatar levymetal avatar luftywiranda13 avatar machycek avatar manpenaloza avatar mrmckeb avatar mxstbr avatar nikgraf avatar pwain avatar rattrayalex avatar relekang avatar ryanccollins avatar sandiiarov avatar sashatran avatar scttcper avatar souporserious avatar trysound 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  avatar  avatar  avatar

Watchers

 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

polished's Issues

Docs generating duplicates

Something about the way we are organizing things is causing JSDoc to create multiple copies of the same documentation within a module. I suspect it has something to do with how we are grouping things under modules.

Improvement proposal for calculation

Hello,

First of all, sorry for my english. Unless I am mistaken, there is no calculation tool ? Currently, I have to write something like :

`
top: ${parseFloat(theme.header.height) // or stripUnit
	+ parseFloat(theme.spacing.sm) * 4
	+ parseFloat(theme.content.tab.height)
	+ parseFloat(theme.content.header.height)}rem;
`

pretty ugly…

maybe something like :

`
top: ${calc(theme.header.height
	+ theme.spacing.sm * 4
	+ theme.content.tab.height
	+ theme.content.header.height, 'rem')};
`

Also, this can be converted with babel-plugin-polished and disregard the units.

Thank you,

Simon

Remove bulk export

We should remove the bulk export in order to promote users importing only the modules that they need.

homepage example contains syntax error

I pasted this into the console on the homepage:

const styles = {
  color: lighten(0.2, '#000'),
  font-size: modularScale(1),
  [hiDPI(1.5)]: {
    font-size: modularScale(1.25)
  }
}

And, unsurprisingly, got
Uncaught SyntaxError: Unexpected token -

I assume it needs to be "font-size": ?

Generated Documentation

Since complete documentation will be important, what are thoughts on using something like JSDOC to generate docs for us?

Color Luminance utility functions

Would you be interested in adding a luminance helper to this library? I'm using this right now which pulls from the knowledge of other color libraries:

// http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
function getLuminance(color) {
  const rgbColor = parseToRgb(color);
  const [r, g, b] = Object.keys(rgbColor).map(key => {
    const channel = rgbColor[key] / 255;
    return channel <= 0.03928
      ? channel / 12.92
      : Math.pow((channel + 0.055) / 1.055, 2.4);
  });
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

ported this from ChromaJS because I didn't want to import the whole lib, not sure if you want to put it in here though

const EPS = 1e-7;

function setLuminance(amount, color) {
  const { red, green, blue, alpha = 1 } = parseToRgb(color);
  let rgb;
  if (amount === 0) {
    rgb = rgba(0, 0, 0, alpha);
  } else if (amount === 1) {
    rgb = rgba(255, 255, 255, alpha);
  } else {
    let maxIteration = 20;
    const test = (color1, color2) => {
      const mixed = mix(0.5, color1, color2);
      const mixedLuminance = getLuminance(mixed);
      if (Math.abs(amount - mixedLuminance) < EPS || !maxIteration--) {
        return mixed;
      }
      if (mixedLuminance > amount) {
        return test(color1, mixed);
      }
      return test(mixed, color2);
    };
    rgb = getLuminance(color) > amount
      ? test('#000', color)
      : test(color, '#fff');
  }
  return rgb;
}

Could even add some simple isDark and isLight functions with this addition. I can put together a PR if you are interested, just let me know :)

Logo

I remember @okonet showing us a screenshot of an amazing logo somewhere, could we get that exported and added to the repo somewhere in png and svg?

Flow type references missing in docs

Hi, guys,

I see some flow type references missing in docs like this RgbaColor.

image

I'm playing with Flow and Documentation on another project and also faced this problem, but I finally managed to solve it.

Would a PR be welcome?

Problematic

I don't want to dampen enthusiasm of everyone here, I respect you all very much. But I don't think the direction this project is going is a good idea.

This is the sort of project that would appeal to newer developers, the sorts who a less likely to understand tree shaking and destructured imports. Here is what a disappointing portion of users will do:

import polished from 'polished'

This line will let them. They will pull in the entire library to the client bundle.

Suggestion: Remove the default export, force users to only import what they need.

Then on some button somewhere, the user will throw in polished.timingFunctions('easeInCubic'), because the name was familiar from some other past library and they liked it. Even if they used a destructured import for timingFunctions, they now also have every timing function they didn't use in their bunde, a hefty set of values. In my experience, 99.999% of the time the standard keywords are sufficient.

Suggestion: Remove timingFunctions, or refactor the module to export each string separately to allow destructured imports. This will simplify the module, no function necessary.

Clearfix as a concept is dead, and should not be supported in any new libraries. Floats are bad practice now we have robust layout options like flexbox.

Suggestion: Remove clearfix.

For some reason most of the CSS in JS libraries are a let down in regards to automatically vendor prefixing ::selection and ::placeholder. This should just work automatically, the solution is not to manage mixins in a library like this with hardcoded vendor prefixes that do not respect a user's browserslist config or respond to user agent.

Suggestion: Don't hardcode vendor prefixes, remove selection, placeholder, HiDPI and other relevant APIs.

I can't see elegent use cases for helpers such as em. em and px are different CSS units with different uses. Developers should use the right one in the right circumstance. I almost never use px for anything. Thing is, such a small helper has 4 large error strings that won't minify.

Suggestions: Remove em. Is it possible to make all the other developer warnings only appear in dev bundles, like with React?

Regarding color utilities, see this comment.

Suggestion: It would be best for CSS in JS libraries to treat it the same as vendor prefixing: Users just follow the spec within the rule strings. Because this processing would add a lot to a client side bundle, it should be opt-in or handled by a plugin.

I can't help but think whatever few utilities still make sense might be better off published separately to NPM. With CSS, almost any change is a breaking change to a meticulously tested front end. The bigger this library gets, the riskier updating for a particular bugfix becomes.

A few years ago, I standardised Bourbon for a team. After a year or so of heavy use, I banned it. We have always banned Bootstrap and Foundation. CSS libraries are generally wasteful, introduce unnecessary complexity and isolate developers from the CSS that actually runs in a browser.

Invert helper

I have a setTextColor() function that returns black or white based on the background color, and I was wondering if polished could do this?

export function setTextColor(color) {
  const rgb = convertHexToRgb(color)
  const gamma = 2.2
  const luminosity =
    0.2126 * Math.pow(splitRgb(rgb).r, gamma) +
    0.7152 * Math.pow(splitRgb(rgb).g, gamma) +
    0.0722 * Math.pow(splitRgb(rgb).b, gamma)
  if (luminosity < 0.6) return '#FFFFFF'
  return '#000000'
}

I found invert() which works in some cases but I find you usually just want black or white for things like buttons or navigations.

Initial list

Below is a list of helpers we think would be useful to have in this toolset. A few notes before diving in and implementing them:

  • We are aiming for 100% test coverage, so extensively test the utils you write
  • Add helpful error messages and type checking based on the util @bhough will write in #4
  • These helpers should be method agnostic, i.e. not styled-components specific. This means they need to return css-in-js, by which I mean JavaScript objects, not CSS strings.

An example what ellipsis could return:

const Box = styled.div`
  ${ ellipsis('250px') }
`
{
  // Value from first argument
  width: '250px',
  whiteSpace: 'nowrap',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
}

Note that styled-components can handle simple styles as JavaScript objects perfectly fine, except you can't have pseudo-selectors and those sorts of things in the objects. We'll have to have a discussion what to do with the more complex of these helpers!

By returning objects, these also work for any CSS-in-JS method:

const styles = {
  ...ellipsis('250px'),
}

🎉

Mixins

Shorthands

Helpers

Color

RGB

HSL

Opacity

  • rgba
  • opacify (@nik)
  • transparentize (@nik)

Misc

Add React Native Helpers For Device Width/Height

Opening this to discuss the possibility of adding helpers for React Native percentages based on Height/Width. The API could look something like this:

{
  'font-size': deviceWidth('10%'),
  'height': deviceHeight('100%'),
}

which would replace something like this:

{
  'font-size': (Dimensions.get('window').width * .10),
  'height': (Dimensions.get('window').height),
}

See: https://facebook.github.io/react-native/docs/dimensions.html

We could potentially get really fancy and offer the ability to determine values based off measurements other than percentage.

Additional context: #129 (comment)

@mxstbr @nikgraf thoughts on this idea?

Triangle mixin needs completed

The docstring for Triangle currently ends up in the built docs under Types > PointingDirection

I went for a quick PR but ran into flow annotation issues due to lack of familiarity with it.

Seems all that's needed is to add "triangle" under Mixins in .documentation.js and to correct the docstring placement from above PointingDirection to above triangle in src/mixins/triangle.js (and whatever flow wants to be happy ^^).

Moreover, triangle might need to be switched from const arrow => to plain function declaration to match the main export style in the other src files.

Add ROADMAP.md

Add a Roadmap doc that explains the items that we are actively working on, will definitely do, and are considering for inclusion.

Opacify is not working

The following code does this:

opacify(0.6, 'rgba(255, 255, 255, 0.8)') // #fff
opacify(0.6, '#fff') // #fff

what's wrong?

I don't understand why transparentize works well. Which is the difference between the two.

Version

Documentation Improvements

Would like to make the following documentation improvements:

  • Link to docs in readme should point directly to /docs and not the main site.
  • Add section to docs about usage in imports (the importing of individual modules).
  • Add section to readme about usage in imports as well as tree-shaking support.

Name

We need a better name.

While the meaning of the word cynosure is amazing, two hours after I first found the name I couldn't even remember it – not a good sign.

Any ideas?

pedicure isn't taken on npm yet, would fit with our whole 💅-thing and has something to do with styling, but it does have a slightly dirty connotation maybe? import { clearfix } from 'pedicure'

/cc @styled-components/design @styled-components/cynosure

Support for named css colors

It'd be nice if you could use helpers with named CSS colors, eg "white", "salmon", etc. Polished would need to have a map of names to "usable" colors. It could maintain its own list of colors, or use a package like css-color-names.

Issue with react-boilerplate & retinaImage

Hi there,

I'm trying to use retinaImage in react-boilerplate to render hi resolution copies of images throughout my project on high resolution screens. I've manually included retinaImage.js and hiDPI.js in my project, imported retinaImage.js into the appropriate component and attempted to use it with a static string and am hitting the following error:

Dynamic page loading failed TypeError: Cannot read property '0' of undefined
at SafeParser.decl (styled-components.es.js:2298)
    at SafeParser.precheckMissedSemicolon (styled-components.es.js:5087)
    at SafeParser.decl (styled-components.es.js:2331)
    at SafeParser.other (styled-components.es.js:2228)
    at SafeParser.loop (styled-components.es.js:2171)
    at safeParse (styled-components.es.js:5114)
    at ComponentStyle.generateAndInjectStyles (styled-components.es.js:7158)
    at StyledComponent.generateAndInjectStyles (styled-components.es.js:6219)
    at eval (styled-components.es.js:6239)
    at subscribe (styled-components.es.js:6073)

for context, here's the relevant parts of the component:

import retinaImage from '../../lib/retinaImage'

const PersonImage = styled.img`
  height: 360px;
  width: 555px;
  background-image: ${retinaImage('https://retinajs.s3.amazonaws.com/images/backgrounds/bg.jpg')};
  background-size: cover;
  background-position: center;
`

I was wondering if this is possibly something to do with the image minification that takes place in react-boilterplate?

Please let me know if you need any more information and apologies if it's simply me misunderstanding something or if there's somewhere more appropriate to ask this.

Thanks for all the work on styled-components/react-boilerplate etc. they're making my latest project worlds more enjoyable to write!

Strange error with eslint

I just installed polished, and ❤️ it (just like styled-components)!

There is just one little bug (?) that bothers me..
I use eslint for linting, and it keeps saying me that I have 2 errors for each import polished from 'polished':

/polished-test/src/Component.js
  2:32  error  Unable to resolve path to module 'polished'  import/no-unresolved
  2:32  error  Missing file extension for "polished"        import/extensions

My guess is that in the npm name there is an invisible character..

Here's how to reproduce it:

git clone https://github.com/EnoahNetzach/polished-test
cd polished-test
yarn
yarn eslint

Can't build on Windows

Had some trouble building polished on Windows 10. Several problems exist...

rm and cp commands not available on Windows:
I get the following error on initial install, and subsequent builds:

> polished@ prebuild:lib C:\_Dev\OSS\polished
> rm -rf lib/*

'rm' is not recognized as an internal or external command,
operable program or batch file.

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Peter\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-c
li.js" "run" "build:lib"
npm ERR! node v6.3.1
npm ERR! npm  v3.10.5
npm ERR! code ELIFECYCLE
npm ERR! polished@ prebuild:lib: `rm -rf lib/*`
npm ERR! Exit status 1

The cp command used during postbuild:docs:site has a similar problem.

Both can be worked around by using shx for cross-platform command support within the npm scripts.

documentationjs does not support glob paths on Windows
If I work my way through the issues above, I'm presented with this:

> polished@ build:docs:site C:\_Dev\OSS\polished
> documentation build src/** -t docs-theme --github -o docs -f html -c ./.documentation.json

C:\_Dev\OSS\polished\node_modules\documentation\lib\input\expand_directories.js:35
      throw new Error('Input file ' + index + ' not found!');
      ^

Error: Input file src/** not found!
    at C:\_Dev\OSS\polished\node_modules\documentation\lib\input\expand_directories.js:35:13
    at arrayMap (C:\_Dev\OSS\polished\node_modules\lodash\lodash.js:660:23)
    at map (C:\_Dev\OSS\polished\node_modules\lodash\lodash.js:9556:14)
    at Function.flatMap (C:\_Dev\OSS\polished\node_modules\lodash\lodash.js:9259:26)
    at expandDirectories (C:\_Dev\OSS\polished\node_modules\documentation\lib\input\expand_directories.js:17:1
2)
    at dependencyStream (C:\_Dev\OSS\polished\node_modules\documentation\lib\input\dependency.js:54:3)
    at expandInputs (C:\_Dev\OSS\polished\node_modules\documentation\index.js:56:3)
    at build (C:\_Dev\OSS\polished\node_modules\documentation\index.js:107:10)
    at Object.build (C:\_Dev\OSS\polished\node_modules\documentation\lib\commands\build.js:89:3)
    at Object.<anonymous> (C:\_Dev\OSS\polished\node_modules\documentation\bin\documentation.js:13:29)

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Peter\\AppData\\Roaming\\npm\\node_modules\\np
m\\bin\\npm-cli.js" "run" "build:docs:site"
npm ERR! node v6.3.1
npm ERR! npm  v3.10.5
npm ERR! code ELIFECYCLE
npm ERR! polished@ build:docs:site: `documentation build src/** -t docs-theme --github -o docs -f html -c ./.d
ocumentation.json`
npm ERR! Exit status 1

This issue is addressed in the latest build of documentationjs (v4.0.0-beta.18)

I've made changes to fix these problems on my Windows box, and have confirmed that they also work on OSX. I'll submit a PR shortly so you can take a closer look.

Doc theme

We definitely need a nicer theme for the documentation.

The things people will come to the docs site for are:

  1. Find a list of supported helpers
  2. Find out how to use a certain helper
  3. Find out which options a certain helper has

The current theme a) doesn't look very inviting (needs a nicer color scheme, we can probably just take the styled-components one) and b) takes actual brain power to understand how to use a certain helper. I like the sidebar, and I like how the parameters are documented though. We should get rid of the Returns section though, as it's totally useless for our purposes.

For reference, here are the Bourbon docs which are pretty clear and easy to understand:

screen shot 2016-12-08 at 16 20 33

I like their ideas for the header, instead of our massive violet wall of color and text it should also just say "Ellipsis" on the left side and link to the source on the right side.

Maybe @okonet has some ideas for this?

Update NPM Package

I just came across polished and would like to use it together with styled components in my current project. It seems like the NPM package hasn't been updated since November 2016 though. Are there any plans for a release anytime soon?

Color API

#I told @mxstbr to help out here and especially with the color related API 🙌 Before starting to code I want figure out how you think about the API. There was already some discussion here #24, but there are a couple things unclear to me. This is a proposal. Please correct me if I'm wrong or you see room for improvement.

  • We want everything color related in the lib to make sure it's properly flow-typed & tested.
  • The output of every color related function should be a string.
  • We want to create the smallest possible output. For colors without opacity we use hex e.g. #FF553A. If possible only 3 characters #FFF instead of #FFFFFF. In case of opacity we generate rgba(255,0,0,0.3).
  • A function might take a string or multiple values e.g. rgb('22, 255, 0') and rgb(22, 255, 0) and rgb({ red: 22, green: 255, blue: 0 }). Not sure about the object structure. Looks handy, but usually I prefer to have one recommended way of doing things and by exposing less possible ways we would enforce it. (We can always add it later)
  • Functions like saturate accept hex strings or rgb or rgba or hsla strings e.g. '#FFDDFF' or 'rgb(22, 255, 0)', but don't accept plain single values like rgb (there is no conversion). Otherwise it could get confusion if they accept hsla or rgba. On the other hand if we could accept the object notation, but as said it's not necessary.
  • In case of manipulation functions we use a functional style like Rambda with the first argument/arguments being the parameters and the last one the base color. Due the nature of the this API design composition is possible e.g.
// nesting of function calls
const prettyRed = saturate(20, darken(10, rgb(100, 0, 0)));
const prettyBlue = saturate(20, darken(10, rgb(0, 100, 0)));

const prettify = compose(
  darken(10),
  saturate(20)
);
const prettyRed = prettify(rgb(100, 0, 0));
const prettyBlue = prettify(rgb(0, 100, 0));

Note: please ignore 10 & 20 arguments. I need to learn more about color theory first to understand what parameters make sense.

What do you guys think? @bhough @mxstbr @guzart

steps in modularScale() is not calculated correctly

Given default base (1em) and ratio (perfectFourth), modularScale(2) should return 1.77689em, but currently it is returning 2.666em.

It seems the current output is calculated by base * ratio * steps, but it should be base * Math.pow(ratio, steps)

Testing setup

Each utility should have some tests verifying that for certain inputs the expected outputs are returned. We should also have CI to verify those tests pass for each PR.

Setup semantic-release

Setting up semantic-release is perfect for this library, because it means we're very strict about SemVer and don't have to think about it. Might also have to setup commitizen?

[V2] Error and Warning Handlers

Given that this is acting as a CSS compiler of sorts, each module should have error/warning handling that informs the user if they have provided the invalid values/syntax/etc... These should only be use in development and will be stripped out by webpack for production.

In my experiments I've been loosely following the formatting used in ELM. So they come out looking sort of like this:

-- Warning: Clear Fix -------------------------------------------------------- mixins/ClearFix.js--

  'clearFix' does not accept a parameter. However, you provided a parameter with a value of 50px.

  'clearFix' simply returns the cross-browser CSS necessary to clear floats and does not require
 any parameters to work.

--------------------------------------------------------------------------------------------------

Would love everyone's thoughts on this.

Clarify use of object rest spread operator in docs?

First of fall: Awesome library! Really cool to throw this at the guys claiming that they "live and die' by Sass functions!

I have suggestion/comment regarding the docs: The examples make extensive use of the object rest spread operator, which is still a proposal, and you may save a lot of developers some time by indicating that they need to use babel-plugin-transform-object-rest-spread, in order to leverage the new syntax.

Happy to make a PR to the docs if this is indeed something that should be in there!

Add EXAMPLES.md

Document examples of using polished with various css-in-js solutions. This is the first step towards adding the ability to toggle between examples with these different libraries directly in the docs.

[V2] rgba function should behave like Sass rgba function

The rgba function that you created expects
${rgba(255, 205, 100, 0.7)} or
${rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 })};
when we use it in styled-components.

I don't know, my approach might be wrong but If I use your rgba function like ${rgba('#000', 0.1)} in order to get the same css rgba(0, 0, 0, 0.1) when I use rgba function in Sass, it would be better.

I use this function to get the result that I mentioned.

const hexToRgb = (hex) => {
  // http://stackoverflow.com/a/5624139
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function (m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16),
  } : null;
};

const rgba = (hex, alpha) => {
  const color = hexToRgb(hex);
  return `rgba(${color.r}, ${color.g}, ${color.b}, ${alpha})`;
};

export const Header = styled.div `
  box-shadow: 0 0 5px ${rgba('#000', 0.1)};
`;

I wonder your ideas about it.

I look forward to use Polished in a real project.
Thanks

Clearfix Compatibility

This is a great library and I'm using it with styled-components, but having an issue clearFix interoping with bootstrap. The clearFix implementation is slightly different than bootstrap's and it doesn't seem to work with the Grid.

E.g., the polished implementation:

&:after {
  clear: both;
  content: '';
  display: table;
}

vs. the Bootstrap implementation:

&:before,
&:after {
  clear: both;
  display: table;
  content: "";
  line-height: 0;
}

Would be more than happy to submit a PR for this if you all are open to the change. Thanks!

Fix hiDPI export

Right now index.js says this for the export:

export {
  hiDIPI
}

Should be hiDPI, not hiDIPI!

homepage svg logo contains font

The text has FiraSans-Medium, Fira Sans as font-family, which causes it to fallback into serif. There are two options to fix this:

  1. add , monospace to the font
  2. convert text into outlines

The first has the advantage of generating a smaller svg, the second will be exactly how you see it on your screen.

[RFC] Adopt more explicit function arguments

Space-delimited arguments

I think the concept of space delimited arguments of css property values often leads to considerable ambiguity. IMHO this is a concept that is ideally avoided when defining styles in JavaScript in favor of explicit arguments. These are really bad when there's several space-delimited values, such as in the box-shadow property.

For example:

.shadow {
  box-shadow: 2px 2px 2px 1px red;
}

Personally, I have need to look up the meaning of these space delimited arguments 100% of the time.

With the current pattern adopted by polished, the equivalent might helper function might be something like (based on the animation shorthand helper):

boxShadow(['2px', '2px', '2px', '1px', 'red']);

Instead, I think something like the following would be vastly more clear:

boxShadow({
  offset: {x: '2px', y: '2px'},
  blurRadius: '2px',
  spreadRadius: '2px',
  color: '2px'
});

I would not need to look up this interface every time. Having more explicit arguments also makes Flow type annotations and IDE autocomplete even nicer.

Directional properties

Directional properties are very common. I think it would be nice to give this a consistent, explicit, direct JavaScript API. For example, rather than:

borderWidth('12px', '24px', '36px', '48px');
borderWidth('12px', '24px');
borderWidth('12px', '24px', '8px'); // What does this mean again? I have to think about this.
borderWidth('7px', '7px', '7px', '11px'); // Not so DRY

We would have something like:

borderWidth({top: '12px', right: '24px', bottom: '36px', left: '48px'});
borderWidth({x: '24px', x: '12px'});
borderWidth({x: '24px', y: '12px', bottom: '8px'}) // Precedence is obvious
borderWidth({all: '7px', left: '11px'); // More DRY, can use Object.assign as well for overriding

I think this is an improvement in terms of expressiveness and ergonomics for the reasons above.

Conclusion

I think a "lodash for style objects" library is an opportunity to correct the mistake of implicit parameters in CSS. It's certainly more ambitious than merely mirroring the pattern of space-delimited property values and does result in further abstraction from CSS, but I think it's ultimately better in a world where all styles are defined in JavaScript and all CSS is generated from JavaScript. We can reduce ambiguity and have a really nice style authoring experience with strict object Flow types.

Several months ago I made a library very similar to polished where I implemented these things: https://lostyle.js.org/, but I think it would be better to join forces. I think the way it handles border shorthands is nice: https://lostyle.js.org/global.html#border and expands on the ideas I've described here.

All this stuff would be a breaking change, but I think ultimately the API is much more clear.

Feel free to close this issue if you don't agree with this opinion. Cheers! 😄

Defaulting & Optional Style Helpers

I've been writing a couple of util functions while playing around with styled-components in my latest project and thought I'd share there, @mxstbr suggested starting a discussion around them here, I'd love to get some thoughts & feedback from the community :)
I'm planning to put together a gist or a pen once these are polished a little more so I'll update when/if that happens but for now, here goes:

const propValue = ( prop, defaultValue ) => props => {
    return props[ prop ] != null ? props[ prop ] : defaultValue;
}

const optionalRule = ( rule, prop ) => props => {
    const style = propValue( prop, null )( props );

    return ( rule && style !== null ) ? `${ rule }: ${ style };` : '';
}

usage

const someStyles = css`
    backgroundColor: ${ propValue( 'bgColor', 'tomato' ) } ;
    ${ optionalRule( 'color', 'textColor' ) }
`;

npm install doesn't work

This is just what I was looking for. But I can't install it.

I tried to npm install the package, but only the clearfix functionality was installed. I guess the node package is very outdated or something.

Jest tests stall constantly on Travis

Over the last couple of weeks the Jest tests have been practically unusable on Travis. 9 times out of 10 them time out. When they do successfully run they take 8-10 minutes to complete. This is making submitting PRs a huge pain.

Improvements (Chores)

I'm going to use this a personal todo list until the initial release. Some of these are for discussion. I just don't want to forget any of these.

  • make sure the color types are exposed
  • move color related functions to a color directory
  • accept rgba strings with spaces (right now it expects strings without spaces). Perquisite: need to check if one ore more spaces are allowed
  • accept other color strings as well (hsl, rgb, hsla)
  • decide if we use our functions in the inline examples
  • investigate ES2015 build for Treeshaking optimizations
  • turn on linting for tests
  • add a warning for the order of arguments
  • investigate how compose works under the hood (Nik currently working on it)
  • interactive examples in the docs (bonus chore) :)
  • document color usage somewhere + write a post about the api design
  • check how to properly type check in toColorString
  • replace toColorString usage with hslToColorString & rgbToColorString (perf)
  • export flow types

`array.includes` is not transpiled and breaks all IE + Edge 13

polished version: 1.0.4

What i am seeing:

Transpiled node_modules/polished/lib/shorthands/position.js Line 65-66

...
  if (positionMap.includes(positionKeyword)) {
    return _extends({
...

Solutions:

  1. Replace includes with indexOf(...) >= 0
  2. Use babel but see pitfalls https://www.npmjs.com/package/babel-plugin-array-includes

Reproduction:

Search for .includes
https://github.com/styled-components/polished/search?utf8=%E2%9C%93&q=.includes&type=

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.