Coder Social home page Coder Social 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 2.0 16.0 421 KB

↔️ stylis RTL plugin based on CSSJanus

License: MIT License

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

stylis-plugin-rtl's Introduction

stylis-plugin-rtl

Stylis RTL plugin based on CSSJanus

NOTE! Use v1 of this plugin for styled-components v5, NOT v2 (v2 is for libraries that have upgraded to stylis v4, which s-c has not yet. At the moment only emotion 11 is updated.)

Installation

v1

yarn add stylis-plugin-rtl@^1

v2

yarn add stylis-plugin-rtl stylis

Usage with styled-components v5+

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

const Box = styled.div`
  padding-left: 10px;
`;

function MakeItRTL() {
  return (
    <StyleSheetManager stylisPlugins={[rtlPlugin]}>
      <Box>My padding will be on the right!</Box>
    </StyleSheetManager>
  );
}

NOTE: Preventing flipping

Because minification removes all comments from your CSS before it passes to <StyleSheetManager>, /* @noflip */ comment won't work. You will have to either:

  • add an exclamation mark at the beginning of the comment, like this /*! @noflip */, to prevent it from being removed
  • disable minification entirely by setting minify to false in .babelrc (see styled-components documentation).

This is a fork of stylis-rtl for use with styled-components v5+

stylis-plugin-rtl's People

Contributors

andarist avatar andreisergiu98 avatar dependabot[bot] avatar jopdeklein avatar layershifter avatar quantizor 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

Watchers

 avatar  avatar

stylis-plugin-rtl's Issues

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>
.
.
.

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!

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.

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

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 + 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

/* @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"
      }
    }

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?

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 '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?

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?

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

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

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].

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!

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)

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.