node package manager
Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

cf-style-provider

cf-style-provider

Cloudflare Style Provider

In order to support cf-ui (fela based components) in your project, you need to wrap your app by our StyleProvider. Check out the main README.md to see it in use. This package also provides testing utilities. Our fela setup consists of many plugins, enhancers and themes. To ensure that everything has the same context and works properly, you should never use packages as fela, fela-dom, react-fela or cf-style-const directly. Always use cf-style-provider.

Installation

$ npm install cf-style-provider

StyleProvider

import { StyleProvider } from 'cf-style-provider';
 
render(
  <StyleProvider
    dev={false}
    renderer={undefined}
    rehydrate={false}
  >
    <YourApp />
  </StyleProvider>
);

props and default values

  • dev: false, in dev mode it applies more Fela plugins (validator, beautifier, monolithic)
  • renderer: undefined, StyleProvider creates fela renderer internally but sometimes you might want to inject your own instance if you need to expose other renderer's APIs (e.g. for testing) or to ensure that there is only single instance of fela renderer in your application
  • rehydrate: value comes from context This prop is used for server side rehydration of Fela styles. This prop should be turned off when rendering Fela components outside of root rendererer hierarchy to avoid class name collisions. If unsure, use rehydrate={false}.

Dev mode produces developer friendly output (CSS is formatted), validates all rules and merges atomic classNames into one. Fela automatically creates <style> nodes in <head> node and injects the styles.

createRenderer

Or you can just get Fela's renderer (useful for server-side rendering)

import ReactDOMServer from 'react-dom/server';
import { Provider } from 'react-fela';
import { createRenderer } from 'cf-style-provider';
 
// default values
const renderer = createRenderer({
  dev: false, // in dev mode it applies more Fela plugins (validator, ...)
});
 
const body = ReactDOMServer.renderToString(
  <Provider renderer={renderer}>
    <Main />
  </Provider>
);
 
renderer.renderToString(); // returns CSS as a string

felaTestContext

For testing. HOC that passes fela renderer and base theme into the context. Handy for testing with enzyme. However, if your goal is to use Enzyme with Fela, You should probably use felaShallow or felaMount instead, they provide a better abstraction .

import { mount } from 'enzyme';
import { felaTestContext } from 'cf-style-provider';
 
test('should call onPageChange when clicking another page', () => {
  const onPageChange = createStub();
 
  const wrapper = mount(
    felaTestContext(
      <PaginationBuilder
        onPageChange={onPageChange}
        totalCount={20}
        page={1}
        perPage={1}
      />
    )
  );
 
  const items = wrapper.find('li');
  items.at(2).find('a').simulate('click');
  expect(onPageChange.called).toBeTruthy();
});

felaSnapshot

For testing. Internally felaTestContext. It deep renders the component and returns snapshots of DOM and styles as a object with properties component and styles. However, if your goal is to use Enzyme with Fela, You should probably use felaShallow or felaMount instead, they provide a better abstraction.

Use it like this:

import React from 'react';
import { Form } from '../src/index';
import { felaSnapshot } from 'cf-style-provider';
 
test('should render horizontal layout', () => {
  const snapshot = felaSnapshot(
    <Form layout="horizontal" onSubmit={() => console.log('submit')}>
      Form
    </Form>
  );
  expect(snapshot.component).toMatchSnapshot();
  expect(snapshot.styles).toMatchSnapshot();
});

felaShallow

For testing This is the interface to use if you want to use enzyme's shallow function with Fela components. It takes in the same parameters as enzyme's shallow: node and options. It returns an object with keys: wrapper and snapshot

  • wrapper: The root enzyme wrapper returned from enzyme's shallow function.
  • snapshot: A function which takes as a parameter an enzyme ShallowWrapper, either the root, returned from the initial call to felaShallow, or from targeting descendants of the root wrapper. If the enzyme wrapper is around a single node, returns an object with keys: component, style. otherwise returns an array where each element in the array is an object with keys: component, style where the snapshot for that element is stored.
  • The snapshot function takes an additional parameter includeStyles prop which is by default true, if false then styles are omitted from the captured snapshot. This will make it act like a normal enzyme shallow snapshot capture (i.e. we will not dive into fela components and render them).
import React from 'react';
import { felaShallow } from 'cf-style-provider';
import { createComponent } from 'cf-style-container';
import { applyTheme } from 'cf-style-container';
 
export const boxRules = ({ size = 10, theme }) => {
  return {
    width: size + 'px',
    height: size + 'px',
    color: theme.color.grass,
    backgroundColor: theme.foo,
    fontSize: theme.fontSize
  };
};
 
export const innerBoxRules = ({ size = 10, theme }) => {
  return {
    backgroundColor: theme.color.grass,
    width: size + 'px',
    height: size + 'px'
  };
};
 
const themeBoxRules = theme => {
  return {
    foo: theme.color.black
  };
};
 
const extraThemeBoxRules = theme => {
  return {
    fontSize: theme.fontSizes[0]
  };
};
 
const UnstyledBox = createComponent(boxRules);
const StyledBox = applyTheme(UnstyledBox, themeBoxRules, extraThemeBoxRules);
const InnerStyledBox = applyTheme(UnstyledBox, themeBoxRules);
const InnerBox = createComponent(innerBoxRules);
const NoBox = createComponent(boxRules);
 
test('should render box', () => {
  const { wrapper, snapshot } = felaShallow(
    <StyledBox>
      <InnerStyledBox>
        <InnerBox>hello</InnerBox>
        <InnerBox>hello</InnerBox>
      </InnerStyledBox>
    </StyledBox>
  );
 
  expect(snapshot(wrapper)).toMatchSnapshot('Level 1');
  //Will result in the following being recorded in the snapshot file
  // exports[`Level 1 1`] = `
  // Object {
  //   "component": <div
  //     className="a b c d e"
  // >
  //     <ThemedFelaComponent>
  //         <FelaComponent>
  //             hello
  //         </FelaComponent>
  //         <FelaComponent>
  //             hello
  //         </FelaComponent>
  //     </ThemedFelaComponent>
  // </div>,
  //   "styles": "
  // .a {
  //   width: 10px
  // }
  //
  // .b {
  //   height: 10px
  // }
  //
  // .c {
  //   color: #9BCA3E
  // }
  //
  // .d {
  //   background-color: #000
  // }
  //
  // .e {
  //   font-size: 10px
  // }
  // ",
  // }
  // `;
 
 
  const child = wrapper.find(InnerStyledBox);
  expect(snapshot(child)).toMatchSnapshot('Level 2');
  //Will result in the following being recorded in the snapshot file
  // exports[`Level 2 1`] = `
  // Object {
  //   "component": <div
  //     className="a b c d e"
  // >
  //     <FelaComponent>
  //         hello
  //     </FelaComponent>
  //     <FelaComponent>
  //         hello
  //     </FelaComponent>
  // </div>,
  //   "styles": "
  // .a {
  //   width: 10px
  // }
  //
  // .b {
  //   height: 10px
  // }
  //
  // .c {
  //   color: #9BCA3E
  // }
  //
  // .d {
  //   background-color: #000
  // }
  //
  // .e {
  //   font-size: 15px
  // }
  // ",
  // }
  // `;
 
  const innerChild = wrapper.find(InnerBox);
  expect(snapshot(innerChild)).toMatchSnapshot('Level 3');
//Will result in the following being recorded in the snapshot file
// exports[`Level 3 1`] = `
// Array [
//   Object {
//     "component": <div
//       className="a b c"
// >
//       hello
// </div>,
//     "styles": "
// .a {
//   background-color: #9BCA3E
// }
//
// .b {
//   width: 10px
// }
//
// .c {
//   height: 10px
// }
// ",
//   },
//   Object {
//     "component": <div
//       className="a b c"
// >
//       hello
// </div>,
//     "styles": "
// .a {
//   background-color: #9BCA3E
// }
//
// .b {
//   width: 10px
// }
//
// .c {
//   height: 10px
// }
// ",
//   },
// ]
// `;
 
  const noChild = wrapper.find(NoBox);
  expect(snapshot(noChild)).toMatchSnapshot('no child');
  //Will result in the following being recorded in the snapshot file
  // exports[`no child 1`] = `Array []`;
 
 //take a snapshot without styles
 //will result in an enzyme snapshot without any fela rules being resolved or captured in styles
 expect(snapshot(wrapper, false)).toMatchSnapshot('no fela styles captured');
 
});

felaMount

For testing This is the interface to use if you want to use enzyme's mount function with Fela components. It takes in the same parameters as enzyme's mount: node and options. It returns an object with keys: wrapper and snapshot

  • wrapper: The root enzyme wrapper returned from enzyme's mount function.
  • snapshot: A function which takes as a parameter an enzyme ReactWrapper, the root, returned from the initial call to felaMount. It returns an object with keys: component, style.
  • The snapshot function takes an additional parameter includeStyles prop which is by default true, if false then styles are omitted from the captured snapshot. This will make it act like a normal enzyme shallow snapshot capture (i.e. we will not dive into fela components and render them).
import React from 'react';
import { felaMount } from 'cf-style-provider';
import { createComponent } from 'cf-style-container';
 
export const boxRules = ({ size = 10, theme }) => {
  return {
    width: size + 'px',
    height: size + 'px',
    color: theme.color.grass,
    fontSize: theme.fontSize
  };
};
 
const Box = createComponent(boxRules);
 
test('should render box', () => {
  const { wrapper, snapshot } = felaMount(
    <Box>
      hello
    </Box>
  );
  //will output to the snapshot file the fully rendered component tree, alongside all styles
  expect(snapshot(wrapper)).toMatchSnapshot('Level 1');
 
 
  //take a snapshot without styles
  //will result in an enzyme snapshot without any fela rules being resolved or captured in styles
  expect(snapshot(wrapper, false)).toMatchSnapshot('no fela styles captured');
});

Used Fela plugins

We use multiple fela plugins that extend typical CSS-in-JS syntax. Check them out for more details:

named-media-query

We have a set of configured media queries. Please, use them!

mobile: @media (min-width: 13.6em)
mobileWide: @media (min-width: 30.4em)
tablet: @media (min-width: 47.2em)
desktop: @media (min-width: 64em)
desktopLarge: @media (min-width: 97.6em)

Input:

const Column = createComponent(() => ({
  color: 'black',
  desktop: {
    color: 'white'
  }
}))

Output:

<style data-fela-type="RULE" type="text/css">
  .a {
    color: black
  }
</style> 
 
<style data-fela-type="RULE" type="text/css" media="(min-width: 64em)">
  .b {
    color: white
  }
</style> 
 
<div class="a b"></div>