Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate unique classNames #5

Merged
merged 1 commit into from
May 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> A simple way to include CSS with React Components.

* **Tiny**, at less than 1 KB gzipped
* **Tiny**, around than 1.5 KB gzipped
* **Only one dependency - ([Stylis](https://github.com/thysultan/stylis.js))**
* **Write plain ol' CSS.** Period.
* **Built-in pre-processing** when you need it. Powered by [Stylis](https://github.com/thysultan/stylis.js).
Expand Down
3 changes: 2 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Documentation

* [Getting Started](./getting-started.md)
* [Dynamic Styles](./dynamic-styles.md)
* [Nesting](./nesting.md)
* [Dynamic Styles](./dynamic-styles.md)
* [Dynamic ClassNames](./dynamic-classnames.md)
179 changes: 179 additions & 0 deletions docs/dynamic-classnames.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# Dynamic classNames

In this guide, we're going to be using dynamic classNames generated by Fancy (instead of writing them by hand).

This feature was popularized by [CSS Modules](https://github.com/css-modules/css-modules).


### Basic Example

Fancy provides you with a "styles" prop, that contains unique classNames that is generated from and maps to your defined CSS.

```jsx
const Card = props => {
const { styles } = props
<div className={styles.Card} />
}

const css = `
.Card {
background: white;
position: relative;
border: 1px solid black;
}
`
const StyledCard = fancy(css)(Card)
```

#### Result (CSS)

Fancy **preserves** your original className. This is allow for reusability of your style rules, potentially with components from a different scope or even outside of React.

```css
.Card,
.Card__l14h91-1 {
background: white;
position: relative;
border: 1px solid black;
}
```

#### Result (HTML)

```html
<div class="Card__l14h91-1"></div>
```

Note: This feature is **only available** to class-based selectors. Selectors like `div` or `#id` will not receive unique classNames.



### BEM example

Fancy will generate unique classNames for BEM-style nested selectors.

```jsx
const Card = props => {
const { styles } = props
<div className={styles.Card}>
<div className={styles.Card__block} />
</div>
}

const css = `
.Card {
background: white;
position: relative;
border: 1px solid black;

&__block
padding: 20px;
}
}
`
const StyledCard = fancy(css)(Card)
```

#### Result (CSS)

```css
.Card,
.Card__l14h91-1 {
background: white;
position: relative;
border: 1px solid black;
}

.Card__block,
.Card__block__l14h91-1 {
padding: 20px;
}
```



### Multiple classNames example

Fancy's unique className generator isn't limited to a single className scope. Include as many as you need!

```jsx
const Card = props => {
const { styles } = props
<div className={styles.Card}>
<div className={styles.Block} />
</div>
}

const css = `
.Card {
background: white;
position: relative;
border: 1px solid black;
}

.Block {
padding: 20px;
}
`
const StyledCard = fancy(css)(Card)
```

#### Result (CSS)

```css
.Card,
.Card__l14h91-1 {
background: white;
position: relative;
border: 1px solid black;
}

.Block,
.Block__l14h91-1 {
padding: 20px;
}
```



### Sibling classNames

Fancy allows for you to create sibling rules, indicated by `+` or `~`.

```jsx
const Card = props => {
const { styles } = props
<div className={styles.Card} />
}

const css = `
.Card {
background: white;
position: relative;
border: 1px solid black;

& + & {
background: red;
}
}
`
const StyledCard = fancy(css)(Card)
```

#### Result (CSS)

```css
.Card,
.Card__l14h91-1 {
background: white;
position: relative;
border: 1px solid black;
}

.Card + .Card,
.Card__l14h91-1 + .Card__l14h91-1 {
background: red;
}
```

See our [nesting guide](./nesting.md) for notes on `&` use.
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@
"react-test-renderer": "16.2.0",
"standard": "11.0.1"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!src/StyleSheet/ruleParserPlugin.{js,jsx}"
]
},
"standard": {
"ignore": [
"dist"
Expand Down
83 changes: 52 additions & 31 deletions src/StyleSheet/index.js
Original file line number Diff line number Diff line change
@@ -1,67 +1,88 @@
import Stylis from 'stylis'
import ruleParserPlugin from './ruleParserPlugin'
import { uuid } from '../utilities/id'
import { decodeStylisRules } from '../utilities/classNames'

const stylis = new Stylis()
stylis.use([ruleParserPlugin])

const makeStyleSheet = () => {
const state = {
id: 0,
CSSRules: {}
}
class StyleSheet {
constructor () {
this.cssRules = {}
this._id = 0

const addRule = (id, styles) => {
state.CSSRules[id] = styles
this.addRule = this.addRule.bind(this)
this.getRule = this.getRule.bind(this)
this.hasRule = this.hasRule.bind(this)
this.makeRule = this.makeRule.bind(this)
this.removeRule = this.removeRule.bind(this)
}

const getRule = (id) => {
return state.CSSRules[id]
addRule (id, styles) {
this.cssRules[id] = styles
}

const hasRule = (id) => {
return !!getRule(id)
getRule (id) {
return this.cssRules[id]
}

const removeRule = (id) => {
delete state.CSSRules[id]
hasRule (id) {
return !!this.getRule(id)
}

const makeRule = (CSSRules) => {
state.id = state.id + 1
return { id: state.id, CSSRules }
removeRule (id) {
delete this.cssRules[id]
}

const makeStyles = (props) => {
return generateStyles(props)
makeRule (CSSRules) {
this._id = this._id + 1
return { id: this._id, CSSRules, uuid: uuid() }
}

return {
addRule,
getRule,
hasRule,
removeRule,
makeRule,
makeStyles,
CSSRules: state.CSSRules
makeStyles (props) {
return generateStyles(props)
}
}

/**
* Creates the tokenized styles based.
* @param {object} props
* @returns {string}
*/
export const generateStyles = ({id, props, CSSRules, scope}) => {
export const generateStyles = ({id, props, CSSRules, scope, uuid}) => {
const parsedCSSRules = typeof CSSRules === 'function'
? CSSRules(props) : CSSRules

const styles = stylis((scope || ''), parsedCSSRules)
return tokenize(id, styles)
return tokenize(styles, uuid, id)
}

/**
* Renders the CSSRule with tokenized with the unique ID.
*
* @param {string} cssRules
* @param {string} uuid
* @param {string} id
* @param {string} CSSRules
* @returns {string}
*/
export const tokenize = (id, CSSRules) => `/* ${id} */\n${CSSRules.trim()}\n`
export const tokenize = (cssRules, uuid, id) => {
/**
* Decode and add unique classNames to rule
*/
const block = decodeStylisRules(cssRules, uuid, id)
/**
* Stringifying the CSS Rule (only)
*/
const rule = block.map(b => b.rule).join('')
/**
* Mapping the new UUID classNames (only)
*/
const selectors = block.map(b => b.selector).filter(b => b.name)

return {
rule: `/* ${id} */\n${rule}\n`,
selectors
}
}

export default makeStyleSheet
export default StyleSheet
38 changes: 38 additions & 0 deletions src/StyleSheet/ruleParserPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
DELIMETER,
SEP
} from '../constants/stylis'

/**
* Identifies and transforms individual cssRules for parsing.
*
* @param {*} * (All from stylis)
* @returns {string}
*/
const ruleParserPlugin = (context, content, selectors, parents, line, column, length, ns, depth, at) => {
switch (context) {
// selector
case 2:
if (ns === 0) { return transformRule(selectors, content) }
break
// at-rule
case 3:
switch (ns) {
default:
return transformRule(parents, content)
}
}
}

/**
* Prepares cssRule for parsing by passing in split tokens.
*
* @param {string} selector
* @param {string} content
* @returns {string}
*/
const transformRule = (selector, content) => {
return content + SEP + selector + SEP + DELIMETER
}

export default ruleParserPlugin
Loading