Giter Site home page Giter Site logo

styled-components / stylis-plugin-rtl Goto Github PK

View Code? Open in Web Editor NEW

This project forked from viodotcom/stylis-rtl

37.0 37.0 16.0 421 KB

↔️ stylis RTL plugin based on CSSJanus

License: MIT License

JavaScript 0.85% TypeScript 99.15%
css-in-js cssjanus rtl styled-components stylis

stylis-plugin-rtl'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.

stylis-plugin-rtl's People

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

Watchers

 avatar  avatar

stylis-plugin-rtl's Issues

Nested selectors not processed

In a simple MaterialUI v5 demo app (https://codesandbox.io/s/material-rtl-nested-selector-1qtmo), it seems that nested selectors are not processed by the plugin. Using something like the following snippet, the table element gets flipped CSS, while thead and td/th do not.

const styles = {
  width: 1,
  textAlign: "left",
  "& thead": {
    textAlign: "left"
  },
  "& th, & td": {
    paddingLeft: 1
  }
};

function App() {
  return (
    <Box component="table" sx={styles}>
      <thead>
        <tr>
          <th>Hello TH</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Hello TD</td>
        </tr>
      </tbody>
    </Box>
  );
}

Note: This was initially reported in mui/material-ui#24270 (comment)

2.0.0 Doesn't work

I've just spent 3 hours trying to understand why the plugin stopped working. Reverting to 1.0.0 helped!

v2.0.0 Module not found: Can't resolve 'stylis'

I updated to v. 2.0.0 and receive this error upon npm start:

./node_modules/stylis-plugin-rtl/dist/stylis-rtl.js
Module not found: Can't resolve 'stylis' in '/home/me/Projects/my-project/node_modules/stylis-plugin-rtl/dist'
/home/me/Projects/my-project/node_modules/react-scripts/scripts/start.js:19
throw err;
^
Error: ENOENT: no such file or directory, stat "/initrd.img"
npm ERR! code ELIFECYCLE
npm ERR! errno 1

Oh and of course thank you for this magical plugin, that's still saving my life!

noflip in JavaScript object

I have noticed the existence of a /* @noflip */ comment that can be used with the CSS template string syntax. It's implemented in https://github.com/cssjanus/cssjanus#preventing-flipping.

However, it seems that there is no way to do the same with the JavaScript object. I wonder about this syntax:

import styled, { StyleSheetManager } from "styled-components";
import rtlPlugin from "stylis-plugin-rtl";

const Box = styled('div')({
  noflip: true,
  paddingLeft: 10,
});

or

import styled, { StyleSheetManager } from "styled-components";
import rtlPlugin from "stylis-plugin-rtl";

const Box = styled('div')({
  paddingLeft: 10,
}).withConfig({ noflip: true });
import styled from "@emotion/styled";
import rtlPlugin from "stylis-plugin-rtl";

const Box = styled('div', { noflip: true })({
  paddingLeft: 10,
});

Getting type error (not assignable to type 'StylisPlugin') for rtlPlugin

Current Behavior 😯

When I use rtlPlugin from stylis-plugin-rtl, I get type error:
Type '(element: Element, index: number, children: (string | Element)[], callback: Middleware) => string | void' is not assignable to type 'StylisPlugin'.
image

Expected Behavior 🤔

Not having this type (TypeScript) error.

To Reproduce 🕹

Live Example (codesandbox/eager-tereshkova-lx74s)

Context 🔦

I'm trying to use rtlPlugin in order to display mui components in rtl direction.

Environment information 🌎

Simple React/Next.js. Also check Live Example above for more detailed.

  • react version: 17.0.2
  • stylis version: 4.0.10
  • stylis-plugin-rtl version: 2.1.0
  • @emotion/react version: 11.4.1
  • @emotion/styled version: 11.3.0

I have previously posted this issue at material-ui, but they reported that the bug is either within @emotion/cache or stylis-plugin-rtl (comment).
Also there's an exact issue opened at emotion-js/emotion in case the bug is there.

Type issue when used with TypeScript

Hello,
I ran into this error when using the plugin with TypeScript on a CRA project.

Could not find a declaration file for module 'stylis-plugin-rtl'. '/Users/umar/Documents/AzureDevOps/components/node_modules/stylis-plugin-rtl/dist/stylis-rtl.js' implicitly has an 'any' type.
Try npm install @types/stylis-plugin-rtl if it exists or add a new declaration (.d.ts) file containing declare module 'stylis-plugin-rtl';ts(7016)

stylis-plugin-rtl + source-map-loader = breakage

The built source files and the sourcemaps of the library contains reference to the src/ directory:

{"version":3,"file":"stylis-rtl.js","sourceRoot":"","sources":["../src/stylis-rtl.ts"],"names":[]

But the actual src directory is not shipped with the package, thus ../src/stylis-rtl.ts does not exist.
When using source-map-loader ( as with create react app 5), the build fails as it can't file stylis-rtl.ts

Possible solutions:

  • Use inline source-maps
  • Don't generate source-maps
  • ship src as well

Typescript issue (Uncaught TypeError: Cannot create property 'return' on number '-1')

I'm using the example in the document, with Next.js like this ...

Screenshot_1

As you can see, it gives me a typescript error, and on save it gives me this error in the browser ...

image

I tried to ignore the types for this package and the typescript error disappeared, however, the error in the browsers still exists.

(Uncaught TypeError: Cannot create property 'return' on number '-1')

How can I solve this?

Ability to remove effect

Add ability to remove effect of plugin when we change language.

After we change language from RTL to LTR language drawer of MUI will broken till force refreshing page.

Source-map file not found

I get this warning during Webpack build:

WARNING in ./node_modules/stylis-plugin-rtl/dist/stylis-rtl.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '...\node_modules\stylis-plugin-rtl\src\stylis-rtl.ts' file: Error: ENOENT: no such file or directory, open '...\node_modules\stylis-plugin-rtl\src\stylis
-rtl.ts'

It expects to find the source-map file in the src folder. But it hasn't been published on NPM.

https://unpkg.com/browse/[email protected]/
image


I use [email protected].

Next.js + Emotion 11 + stylis-plugin-rtl 2

I can't seem to get this to work with Next.js and Emotion 11. I've created a sandbox.

If you inspect the div, you can see that the prefixer plugin correctly prefixed the display: flex:

display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;

However, the RTL plugin did not flip the padding-left: 50px to be a padding-right.

stylis-plugin-rtl causes linear-gradient problems

I'm not sure whether it is a problem from stylis-plugin-rtl or another library but here's the problem(if you think that another library is causing problem here, tell me please and i will open an issue for the corresponding repository). I have a MUI project which uses CacheProvider from @emotion/react and uses stylis-plugin-rtl and has the following structure at top level:

const cacheRtl = createCache({
  key: 'muirtl',
  stylisPlugins: [prefixer, rtlPlugin],
})

/**
function App() {
  return (
    <div dir="rtl">
      <CacheProvider value={cacheRtl}>
        <ThemeProvider theme={createMyTheme()}>
          <Button color="secondary">hello</Button>
        </ThemeProvider>
      </CacheProvider>
    </div>
  );
}

I styled the button from MUI theme to have the following style:

containedSecondary: {
                    background: `linear-gradient(68.44deg, #066060 0%, #0DB1B1 100%)`,
                }

But when i go in browser and use inspect, i see the following style applied to button:
linear-gradient(68.44deg, #066060 0%, #0DB1B1 100%);
But after i remove the CacheProvider which provides the rtlPlugin, the problem is gone. What i have found so far is that whatever the value i place for the first non-negative gradient value(in my case 0%), it just subtracts it from 100. So 0% will become 100%, 20% will become 80% and so on. If i place a negative value(e.g. -2%), it is ignored and next non-negative value will get subtracted. So in other words, it will ignore all negative gradient values and subtracts the first value from 100 and then ignores the rest. Since my project needs to support both rtl and ltr, i can't just place 100% instead of 0% and be happy. I think it just shouldn't manipulate gradient values. Thanks in advance.
Update: When i remove rtlPlugin from createCache, the problem is gone again. So i'm almost sure that the problem is caused by stylis-plugin-rtl

stylis-plugin-rtl cause malfanction in component

this is error in my npm report:
WARNING in ./node_modules/stylis-plugin-rtl/dist/stylis-rtl.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/hamid/Desktop/zahra-wieb-shop/node_modules/stylis-plugin-rtl/src/stylis-rtl.ts' file: Error: ENOENT: no such file or directory, open '/home/hamid/Desktop/zahra-wieb-shop/node_modules/stylis-plugin-rtl/src/stylis-rtl.ts'
@ ./src/index.js 8:0-42 15:18-27

Getting 'A stylis plugin has been supplied that is not named.'

Currently getting the error A stylis plugin has been supplied that is not named.

import rtlPlugin from "stylis-plugin-rtl";

<StyleSheetManager stylisPlugins={[rtlPlugin]}>
    ...
</StyleSheetManager>

Is how I am currently using it. Checking the name property it is coming through as "". Which means the property is defined so I can't just reassign the property without errors in older browser as writable defaults to false when using define property like done here:

// stable identifier that will not be dropped by minification unless the whole module
// is unused
/*#__PURE__*/
Object.defineProperty(stylisRTLPlugin, "name", { value: "stylisRTLPlugin" });

Currently using version 1 due to using styled components.

Any ideas why the name is coming through as the empty string?

error in style-plugin-rtl

1.enter in terminal =>npm i [email protected]
2.and change the code to => export const KudosRtlPlugin = createCache({
key: "muirtl",
stylisPlugins: [
(prefixer as unknown) as any,
(rtlPlugin as unknown) as any,
],
});
solved for me

/* @noflip */ doesn't work.

Hi,
I want to exclude CSS rule from being manipulated by the stylis-plugin-rtl plugin/StyleSheetManager
I tried that:

/* @noflip */
.stx_yaxis {
  /* y-axis price styles */
  direction: ltr !important;
}

still doesn't work, it's still changing the direction to rtl
I also opened a thread in cssjanus but in their demo its working fine.
#wikimedia/node-cssjanus#84

this is from package-lock

    "stylis-plugin-rtl": {
      "version": "1.1.0",
      "resolved": "https://registry.npmjs.org/stylis-plugin-rtl/-/stylis-plugin-rtl-1.1.0.tgz",
      "requires": {
        "cssjanus": "^1.3.0"
      }
    }
    "styled-components": {
      "version": "5.1.1",
      "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-5.1.1.tgz",
      "requires": {
        "@babel/helper-module-imports": "^7.0.0",
        "@babel/traverse": "^7.4.5",
        "@emotion/is-prop-valid": "^0.8.8",
        "@emotion/stylis": "^0.8.4",
        "@emotion/unitless": "^0.7.4",
        "babel-plugin-styled-components": ">= 1",
        "css-to-react-native": "^3.0.0",
        "hoist-non-react-statics": "^3.0.0",
        "shallowequal": "^1.1.0",
        "supports-color": "^5.5.0"
      }
    }

styles generated with @emotion/css are not flipped

Hey there!
The title is pretty self-explanatory. The thing is that I'd like to be able to use the css function of the @emotion/css package over @emotion/react's sometimes, but it appears the styles generated by @emotion/css's function do not get flipped.
Is this an expected behaviour? If yes why?

Invalid types for v2.0.1

Hi there,

Could you please update the types (TS) to match v2.0.1? Currently it exports the wrong types from v1.

Edit:
@emotion/cache (v11) createCache plugins list expects these types:

export type StylisPlugin = (
  element: StylisElement,
  index: number,
  children: Array<StylisElement>,
  callback: StylisPluginCallback
) => string | undefined

Thank you,
Alexandru

Implementation in SSR (Next.js)

Where do I implement in SSR (Next.js)? Should I keep StyleSheetManager in _app.js or in _document.js? I think it should be in _document.js. But I tried wrapping my in StyleSheetManager, it doesn't work.

Here is a sample _document.js without this plugin.

import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
import stylisRTLPlugin from 'stylis-plugin-rtl';
import { parseCookies } from 'nookies';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;
    const { html, head, errorHtml, chunks } = ctx.renderPage();
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
        });
      const initialProps = await Document.getInitialProps(ctx);
      const cookies = parseCookies(ctx);
      initialProps.language = cookies['next-i18next'] || 'en';
      initialProps.direction = initialProps.language === 'ar' ? 'rtl' : 'ltr';
      return {
        html,
        head,
        errorHtml,
        chunks,
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      };
    } finally {
      sheet.seal();
    }
  }
  render() {
    const { language, direction } = this.props;
    return (
      <html dir={direction} lang={language}>
        <body>
          {this.props.customValue}
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

Here is what I tried

.
.
.
       <StyleSheetManager
          stylisPlugins={language === 'ar' ? [stylisRTLPlugin] : []}
        >
          <body>
            {this.props.customValue}
            <Main />
            <NextScript />
          </body>
        </StyleSheetManager>
.
.
.

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.